From f0e24dd7cb26a908f4c9346e962d16b3dc1b8db2 Mon Sep 17 00:00:00 2001 From: Kenneth Lausdahl Date: Thu, 2 Nov 2023 09:26:07 +0100 Subject: [PATCH] updated fmi3 with new types in the builder --- .../maestro/fmi/Fmi2ModelDescription.java | 2 +- .../fmi/fmi2/Fmi2ModelDescriptionUnit.kt | 1 - .../org/intocps/maestro/fmi/fmi2/Fmi2Unit.kt | 2 +- .../maestro/fmi/fmi3/Fmi3ModelDescription.kt | 8 +- .../maestro/fmi/fmi3/Fmi3ModelStructure.kt | 2 +- .../maestro/fmi/fmi3/Fmi3TypeDefinitions.kt | 2 +- .../org/intocps/maestro/fmi/fmi3/Fmi3Unit.kt | 2 +- .../intocps/maestro/fmi/fmi3/Fmi3Variables.kt | 90 +++-- .../framework/fmi2/api/FmiBuilder.java | 310 +++++++++--------- .../maestro/framework/core/IRelation.java | 4 +- .../maestro/framework/core/IVariable.java | 8 +- .../framework/core/RelationVariable.java | 62 +++- .../fmi2/Fmi2SimulationEnvironment.java | 231 +++++++++---- .../maestro/framework/fmi2/InstanceInfo.java | 2 +- .../framework/fmi2/RelationVariable.java | 285 +++++++++++++++- .../framework/fmi2/RelationVariable3.java | 108 +++--- .../framework/fmi2/api/mabl/BuilderUtil.java | 12 +- .../fmi2/api/mabl/FromMaBLToMaBLAPI.java | 21 +- .../api/mabl/ModelDescriptionContext.java | 3 +- .../api/mabl/ModelDescriptionContext3.java | 5 +- .../framework/fmi2/api/mabl/PortFmi2Api.java | 12 +- .../framework/fmi2/api/mabl/PortFmi3Api.java | 75 ++++- .../scoping/DynamicActiveBuilderScope.java | 2 +- .../fmi2/api/mabl/scoping/IMablScope.java | 2 +- .../fmi2/api/mabl/scoping/ScopeFmi2Api.java | 3 +- .../values/PortValueExpresssionMapImpl.java | 5 +- .../api/mabl/values/PortValueMapImpl.java | 5 +- .../variables/ComponentVariableFmi2Api.java | 38 ++- .../variables/InstanceVariableFmi3Api.java | 179 +++++----- .../mabl/variables/PortVariableMapImpl.java | 4 +- .../variables/VariableCreatorFmi3Api.java | 7 +- .../framework/fmi2/api/mabl/SetPortsTest.java | 3 +- .../webapi/maestro2/Maestro2Broker.java | 44 +-- .../maestro/MablSpecificationGenerator.java | 28 +- .../template/MaBLTemplateGenerator.java | 18 +- .../org/intocps/maestro/BuilderFmi3Test.java | 22 +- .../test/resources/cli-test/config-fmi3.json | 2 +- .../fmi3/basic/basic1/fmi3_basic.mabl | 2 +- .../fmi3/reference/bounchingball/fmi3_bb.mabl | 2 +- .../maestro/plugin/DataExchangeHandler.java | 58 ++-- .../maestro/plugin/DataWriterHandler.java | 25 +- .../maestro/plugin/DerivativesHandler.java | 52 ++- .../plugin/initializer/PhasePredicates.java | 9 +- .../plugin/initializer/PhasePredicates3.java | 23 ++ .../initializer/RelationsPredicates.java | 4 +- .../plugin/initializer/TopologicalPlugin.java | 20 +- .../spec/StatementGeneratorContainer.java | 64 ++-- .../src/main/kotlin/Initializer.kt | 244 ++++++++------ .../maestro/plugin/JacobianStepBuilder.java | 6 +- .../verificationsuite/graph/GraphDrawer.java | 5 +- .../InitializationPrologQuery.java | 4 +- .../prologverifier/PrologGenerator.java | 33 +- .../src/test/java/GraphPlotterTest.java | 24 +- .../src/test/java/PrologVerifierTest.java | 4 +- pom.xml | 2 +- .../org/intocps/maestro/typechecker/FMI3.mabl | 24 +- 56 files changed, 1420 insertions(+), 794 deletions(-) create mode 100644 plugins/initializer/src/main/java/org/intocps/maestro/plugin/initializer/PhasePredicates3.java diff --git a/fmi/src/main/java/org/intocps/maestro/fmi/Fmi2ModelDescription.java b/fmi/src/main/java/org/intocps/maestro/fmi/Fmi2ModelDescription.java index 1f6a0e21e..c353e69dd 100644 --- a/fmi/src/main/java/org/intocps/maestro/fmi/Fmi2ModelDescription.java +++ b/fmi/src/main/java/org/intocps/maestro/fmi/Fmi2ModelDescription.java @@ -38,7 +38,7 @@ import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.intocps.maestro.fmi.fmi2.Fmi2ModelDescriptionUnit; -import org.intocps.maestro.fmi.org.intocps.maestro.fmi.fmi2.Fmi2Unit; +import org.intocps.maestro.fmi.fmi2.Fmi2Unit; import org.intocps.maestro.fmi.xml.NodeIterator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/fmi/src/main/kotlin/org/intocps/maestro/fmi/fmi2/Fmi2ModelDescriptionUnit.kt b/fmi/src/main/kotlin/org/intocps/maestro/fmi/fmi2/Fmi2ModelDescriptionUnit.kt index 3ccc1cca1..1c48529b7 100644 --- a/fmi/src/main/kotlin/org/intocps/maestro/fmi/fmi2/Fmi2ModelDescriptionUnit.kt +++ b/fmi/src/main/kotlin/org/intocps/maestro/fmi/fmi2/Fmi2ModelDescriptionUnit.kt @@ -2,7 +2,6 @@ package org.intocps.maestro.fmi.fmi2 import org.intocps.fmi.jnifmuapi.fmi2.schemas.Fmi2Schema import org.intocps.maestro.fmi.ModelDescription -import org.intocps.maestro.fmi.org.intocps.maestro.fmi.fmi2.Fmi2Unit import org.intocps.maestro.fmi.xml.NodeIterator import org.xml.sax.SAXException import java.io.IOException diff --git a/fmi/src/main/kotlin/org/intocps/maestro/fmi/fmi2/Fmi2Unit.kt b/fmi/src/main/kotlin/org/intocps/maestro/fmi/fmi2/Fmi2Unit.kt index 179a69a87..4b0c1a446 100644 --- a/fmi/src/main/kotlin/org/intocps/maestro/fmi/fmi2/Fmi2Unit.kt +++ b/fmi/src/main/kotlin/org/intocps/maestro/fmi/fmi2/Fmi2Unit.kt @@ -1,4 +1,4 @@ -package org.intocps.maestro.fmi.org.intocps.maestro.fmi.fmi2 +package org.intocps.maestro.fmi.fmi2 import org.intocps.maestro.fmi.ModelDescription diff --git a/fmi/src/main/kotlin/org/intocps/maestro/fmi/fmi3/Fmi3ModelDescription.kt b/fmi/src/main/kotlin/org/intocps/maestro/fmi/fmi3/Fmi3ModelDescription.kt index 72fe09eac..a2b5cc837 100644 --- a/fmi/src/main/kotlin/org/intocps/maestro/fmi/fmi3/Fmi3ModelDescription.kt +++ b/fmi/src/main/kotlin/org/intocps/maestro/fmi/fmi3/Fmi3ModelDescription.kt @@ -1,4 +1,4 @@ -package org.intocps.maestro.fmi.org.intocps.maestro.fmi.fmi3 +package org.intocps.maestro.fmi.fmi3 import org.apache.commons.io.IOUtils import org.intocps.fmi.jnifmuapi.fmi3.schemas.Fmi3Schema @@ -491,6 +491,9 @@ class Fmi3ModelDescription : ModelDescription { node.attributes.getNamedItem("previous")?.nodeValue?.toUInt(), node.attributes.getNamedItem("clocks")?.nodeValue?.split(" ")?.map { value -> value.toUInt() }, Fmi3TypeEnum.StringType, + (node.attributes.getNamedItem("initial")?.nodeValue ?: "").let { + if (it.isEmpty()) null else valueOf(it) + }, node.attributes.let { att -> val startValues: MutableList = mutableListOf() for (i in 0 until att.length) { @@ -571,6 +574,9 @@ class Fmi3ModelDescription : ModelDescription { node.attributes.getNamedItem("quantity")?.nodeValue ?: typeDefinition?.quantity, node.attributes.getNamedItem("min")?.nodeValue?.toLong(), node.attributes.getNamedItem("max")?.nodeValue?.toLong(), + (node.attributes.getNamedItem("initial")?.nodeValue ?: "").let { + if (it.isEmpty()) null else valueOf(it) + }, node.attributes.getNamedItem("start")?.nodeValue?.split(" ")?.map { value -> value.toLong() }, getDimensionsFromVariableNode(node) ) diff --git a/fmi/src/main/kotlin/org/intocps/maestro/fmi/fmi3/Fmi3ModelStructure.kt b/fmi/src/main/kotlin/org/intocps/maestro/fmi/fmi3/Fmi3ModelStructure.kt index 7a2cabbaf..431bcd3d7 100644 --- a/fmi/src/main/kotlin/org/intocps/maestro/fmi/fmi3/Fmi3ModelStructure.kt +++ b/fmi/src/main/kotlin/org/intocps/maestro/fmi/fmi3/Fmi3ModelStructure.kt @@ -1,4 +1,4 @@ -package org.intocps.maestro.fmi.org.intocps.maestro.fmi.fmi3 +package org.intocps.maestro.fmi.fmi3 data class Fmi3ModelStructureElement(val elementType: Fmi3ModelStructureElementEnum, val valueReference: UInt, val dependencies: List?, val dependenciesKind: List?) diff --git a/fmi/src/main/kotlin/org/intocps/maestro/fmi/fmi3/Fmi3TypeDefinitions.kt b/fmi/src/main/kotlin/org/intocps/maestro/fmi/fmi3/Fmi3TypeDefinitions.kt index 1f33a9ffa..122f4d5fa 100644 --- a/fmi/src/main/kotlin/org/intocps/maestro/fmi/fmi3/Fmi3TypeDefinitions.kt +++ b/fmi/src/main/kotlin/org/intocps/maestro/fmi/fmi3/Fmi3TypeDefinitions.kt @@ -1,4 +1,4 @@ -package org.intocps.maestro.fmi.org.intocps.maestro.fmi.fmi3 +package org.intocps.maestro.fmi.fmi3 data class FloatTypeDefinition( override val name: String, diff --git a/fmi/src/main/kotlin/org/intocps/maestro/fmi/fmi3/Fmi3Unit.kt b/fmi/src/main/kotlin/org/intocps/maestro/fmi/fmi3/Fmi3Unit.kt index 84a7cf83c..e5a8b5b0d 100644 --- a/fmi/src/main/kotlin/org/intocps/maestro/fmi/fmi3/Fmi3Unit.kt +++ b/fmi/src/main/kotlin/org/intocps/maestro/fmi/fmi3/Fmi3Unit.kt @@ -1,4 +1,4 @@ -package org.intocps.maestro.fmi.org.intocps.maestro.fmi.fmi3 +package org.intocps.maestro.fmi.fmi3 import org.intocps.maestro.fmi.ModelDescription diff --git a/fmi/src/main/kotlin/org/intocps/maestro/fmi/fmi3/Fmi3Variables.kt b/fmi/src/main/kotlin/org/intocps/maestro/fmi/fmi3/Fmi3Variables.kt index f0b774653..5a91d5910 100644 --- a/fmi/src/main/kotlin/org/intocps/maestro/fmi/fmi3/Fmi3Variables.kt +++ b/fmi/src/main/kotlin/org/intocps/maestro/fmi/fmi3/Fmi3Variables.kt @@ -1,6 +1,5 @@ -package org.intocps.maestro.fmi.org.intocps.maestro.fmi.fmi3 +package org.intocps.maestro.fmi.fmi3 -import org.intocps.maestro.fmi.Fmi2ModelDescription import org.intocps.maestro.fmi.ModelDescription abstract class Fmi3Variable protected constructor( @@ -13,9 +12,20 @@ abstract class Fmi3Variable protected constructor( val intermediateUpdate: Boolean? = false, val previous: UInt? = null, val clocks: List? = null, - val typeIdentifier: Fmi3TypeEnum // This is for easier type identification and is not part of the official spec + val typeIdentifier: Fmi3TypeEnum, // This is for easier type identification and is not part of the official spec + val initial: ModelDescription.Initial? = null //this is not present for all but added for convenience ) { - fun getValueReferenceAsLong():Long { return valueReference.toLong() } + fun getValueReferenceAsLong(): Long { + return valueReference.toLong() + } + + override fun toString(): String { + return "$name: ${typeIdentifier.name}" + } + + abstract fun isScalar(): Boolean; + + } data class Dimension(val valueReference: UInt?, val start: List?) @@ -32,7 +42,7 @@ class FloatVariable( clocks: List? = null, typeIdentifier: Fmi3TypeEnum, val declaredType: String? = null, - val initial: ModelDescription.Initial? = null, + initial: ModelDescription.Initial? = null, val quantity: String? = null, val unit: String? = null, val displayUnit: String? = null, @@ -44,7 +54,7 @@ class FloatVariable( val start: Collection? = null, val derivative: UInt? = null, val reinit: Boolean? = false, - val dimensions: List? = null + val dimensions: List? = null ) : Fmi3Variable( name, valueReference, @@ -55,8 +65,13 @@ class FloatVariable( intermediateUpdate, previous, clocks, - typeIdentifier -) + typeIdentifier, + initial +) { + override fun isScalar(): Boolean { + return dimensions.isNullOrEmpty() + } +} class Int64Variable( name: String, @@ -70,7 +85,7 @@ class Int64Variable( clocks: List? = null, typeIdentifier: Fmi3TypeEnum, val declaredType: String? = null, - val initial: ModelDescription.Initial? = null, + initial: ModelDescription.Initial? = null, val quantity: String? = null, val min: Long? = null, val max: Long? = null, @@ -86,8 +101,11 @@ class Int64Variable( intermediateUpdate, previous, clocks, - typeIdentifier -) + typeIdentifier, + initial +){ override fun isScalar(): Boolean { + return dimensions.isNullOrEmpty() +}} class IntVariable( name: String, @@ -101,7 +119,7 @@ class IntVariable( clocks: List? = null, typeIdentifier: Fmi3TypeEnum, val declaredType: String? = null, - val initial: ModelDescription.Initial? = null, + initial: ModelDescription.Initial? = null, val quantity: String? = null, val min: Int? = null, val max: Int? = null, @@ -117,8 +135,11 @@ class IntVariable( intermediateUpdate, previous, clocks, - typeIdentifier -) + typeIdentifier, + initial +){ override fun isScalar(): Boolean { + return dimensions.isNullOrEmpty() +}} class BooleanVariable( name: String, @@ -132,7 +153,7 @@ class BooleanVariable( clocks: List? = null, typeIdentifier: Fmi3TypeEnum, val declaredType: String? = null, - val initial: ModelDescription.Initial? = null, + initial: ModelDescription.Initial? = null, val start: List? = null, val dimensions: List? = null ) : Fmi3Variable( @@ -145,8 +166,11 @@ class BooleanVariable( intermediateUpdate, previous, clocks, - typeIdentifier -) + typeIdentifier, + initial +){ override fun isScalar(): Boolean { + return dimensions.isNullOrEmpty() +}} class StringVariable( name: String, @@ -159,6 +183,7 @@ class StringVariable( previous: UInt? = null, clocks: List? = null, typeIdentifier: Fmi3TypeEnum, + initial: ModelDescription.Initial? = null, val start: List? = null, val dimensions: List? = null ) : Fmi3Variable( @@ -171,8 +196,11 @@ class StringVariable( intermediateUpdate, previous, clocks, - typeIdentifier -) + typeIdentifier, + initial +){ override fun isScalar(): Boolean { + return dimensions.isNullOrEmpty() +}} class BinaryVariable( name: String, @@ -186,7 +214,7 @@ class BinaryVariable( clocks: List? = null, typeIdentifier: Fmi3TypeEnum, val declaredType: String? = null, - val initial: ModelDescription.Initial? = null, + initial: ModelDescription.Initial? = null, val mimeType: String? = null, val maxSize: UInt? = null, val start: List? = null, @@ -201,8 +229,11 @@ class BinaryVariable( intermediateUpdate, previous, clocks, - typeIdentifier -) + typeIdentifier, + initial +){ override fun isScalar(): Boolean { + return dimensions.isNullOrEmpty() +}} class EnumerationVariable( name: String, @@ -219,6 +250,7 @@ class EnumerationVariable( val quantity: String? = null, val min: Long? = null, val max: Long? = null, + initial: ModelDescription.Initial? = null, val start: List? = null, val dimensions: List? = null ) : Fmi3Variable( @@ -231,8 +263,11 @@ class EnumerationVariable( intermediateUpdate, previous, clocks, - typeIdentifier -) + typeIdentifier, + initial +){ override fun isScalar(): Boolean { + return dimensions.isNullOrEmpty() +}} class ClockVariable( name: String, @@ -266,8 +301,11 @@ class ClockVariable( intermediateUpdate, previous, clocks, - typeIdentifier -) + typeIdentifier, + null +){ override fun isScalar(): Boolean { + return dimensions.isNullOrEmpty() +}} enum class Fmi3Causality { StructuralParameter, diff --git a/frameworks/builder/src/main/java/org/intocps/maestro/framework/fmi2/api/FmiBuilder.java b/frameworks/builder/src/main/java/org/intocps/maestro/framework/fmi2/api/FmiBuilder.java index 239a660cf..09378386e 100644 --- a/frameworks/builder/src/main/java/org/intocps/maestro/framework/fmi2/api/FmiBuilder.java +++ b/frameworks/builder/src/main/java/org/intocps/maestro/framework/fmi2/api/FmiBuilder.java @@ -10,7 +10,7 @@ import java.util.Map; @SuppressWarnings("unused") -public interface FmiBuilder { +public interface FmiBuilder { B build() throws Exception; SETTINGS getSettings(); @@ -31,18 +31,18 @@ public interface FmiBuilder { PStm buildRaw() throws Exception; - RuntimeModule loadRuntimeModule(String name, Object... args); + RuntimeModule loadRuntimeModule(String name, Object... args); - RuntimeModule loadRuntimeModule(TryScope scope, String name, Object... args); + RuntimeModule loadRuntimeModule(TryScope scope, String name, Object... args); /** * Gets the default scope * * @return */ - Scope getRootScope(); + Scope getRootScope(); - DynamicActiveScope getDynamicScope(); + DynamicActiveScope getDynamicScope(); /** * Gets a tag to the last value obtained for the given port @@ -52,18 +52,18 @@ public interface FmiBuilder { */ Variable getCurrentLinkedValue(Port port); - DoubleVariable getDoubleVariableFrom(E exp); + DoubleVariable getDoubleVariableFrom(E exp); - IntVariable getIntVariableFrom(E exp); + IntVariable getIntVariableFrom(E exp); - StringVariable getStringVariableFrom(E exp); + StringVariable getStringVariableFrom(E exp); - BoolVariable getBooleanVariableFrom(E exp); + BoolVariable getBooleanVariableFrom(E exp); Variable getFmuVariableFrom(E exp); - interface RuntimeModule extends FmiBuilder.Variable> { + interface RuntimeModule extends FmiBuilder.Variable> { void initialize(List declaredFuncs); void initialize(RuntimeFunction... declaredFuncs); @@ -71,11 +71,11 @@ interface RuntimeModule extends FmiBuilder.Variable> { //not sure how to allow a mix of double, int and var except for object void callVoid(RuntimeFunction functionId, Object... args); - void callVoid(Scope scope, RuntimeFunction functionId, Object... args); + void callVoid(Scope scope, RuntimeFunction functionId, Object... args); - Variable call(Scope scope, RuntimeFunction functionId, Object... args); + Variable call(Scope scope, RuntimeFunction functionId, Object... args); - Variable call(RuntimeFunction functionId, Object... args); + Variable call(RuntimeFunction functionId, Object... args); // void destroy(); // @@ -116,7 +116,7 @@ interface RuntimeFunction { boolean usingVargs(); - static public class FunctionType { + class FunctionType { final Type nativeType; final String namedType; @@ -160,23 +160,23 @@ static public enum Type { /** * Scoping element which defines a scope like a block, if, while etc. * - * @param the type the scoping element encloses + * @param the type the scoping element encloses */ - interface ScopeElement { + interface ScopeElement { /** * The parent element of this element or null if root * * @return the parent */ - ScopeElement parent(); + ScopeElement parent(); /** * The declaration node that defined the underlying scope * * @return the scope */ - T getDeclaration(); + AST getDeclaration(); /** * Find a prent element of a specific type @@ -185,36 +185,36 @@ interface ScopeElement { * @param

the type of class * @return the parent of the specified type or null */ -

> P findParent(Class

clz); +

> P findParent(Class

clz); } /** * Scoping functions */ - interface Scoping extends ScopeElement { - WhileScope enterWhile(Predicate predicate); + interface Scoping extends ScopeElement { + WhileScope enterWhile(Predicate predicate); - IfScope enterIf(Predicate predicate); + IfScope enterIf(Predicate predicate); - TryScope enterTry(); + TryScope enterTry(); - Scoping parallel(); + Scoping parallel(); - Scoping enterScope(); + Scoping enterScope(); - Scope leave(); + Scope leave(); - void add(T... commands); + void add(AST... commands); - void addAll(Collection commands); + void addAll(Collection commands); - void addBefore(T item, T... commands); + void addBefore(AST item, AST... commands); - void addAfter(T item, T... commands); + void addAfter(AST item, AST... commands); - Scoping activate(); + Scoping activate(); } @@ -222,9 +222,9 @@ interface Scoping extends ScopeElement { /** * Basic scope. Allows a value to be stored or override a tag */ - interface Scope extends Scoping { + interface Scope extends Scoping { @Override - Scope activate(); + Scope activate(); /** * Store a given value @@ -232,13 +232,13 @@ interface Scope extends Scoping { * @param value * @return */ - DoubleVariable store(double value); + DoubleVariable store(double value); - StringVariable store(String value); + StringVariable store(String value); - BoolVariable store(boolean value); + BoolVariable store(boolean value); - IntVariable store(int value); + IntVariable store(int value); /** * Store a given value with a prefix name @@ -246,15 +246,15 @@ interface Scope extends Scoping { * @param value * @return */ - DoubleVariable store(String name, double value); + DoubleVariable store(String name, double value); - StringVariable store(String name, String value); + StringVariable store(String name, String value); - BoolVariable store(String name, boolean value); + BoolVariable store(String name, boolean value); - IntVariable store(String name, int value); + IntVariable store(String name, int value); - ArrayVariable store(String name, CV value[]); + ArrayVariable store(String name, CV value[]); /** * Store the given value and get a tag for it. Copy @@ -263,11 +263,11 @@ interface Scope extends Scoping { * @return */ @Deprecated - Variable store(Value tag); + Variable store(Value tag); - Fmu2Variable createFMU(String name, String loaderName, String... args) throws Exception; + Fmu2Variable createFMU(String name, String loaderName, String... args) throws Exception; - Fmu3Variable createFMU3(String name, String loaderName, String... args) throws Exception; + Fmu3Variable createFMU3(String name, String loaderName, String... args) throws Exception; void markTransferPoint(String... names); @@ -278,61 +278,61 @@ interface Scope extends Scoping { /** * Dynamic scope which always reflects the current active scope of the builder */ - interface DynamicActiveScope extends Scope { + interface DynamicActiveScope extends Scope { } /** * If scope, default scope is then */ - interface IfScope extends ScopeElement { + interface IfScope extends ScopeElement { /** * Switch to then scope * * @return */ - Scope enterThen(); + Scope enterThen(); /** * Switch to else scope * * @return */ - Scope enterElse(); + Scope enterElse(); - Scope leave(); + Scope leave(); } /** * Try finally scope, default scope is body */ - interface TryScope extends ScopeElement { + interface TryScope extends ScopeElement { /** * Switch to body scope * * @return */ - Scope enter(); + Scope enter(); /** * Switch to finally scope * * @return */ - Scope enterFinally(); + Scope enterFinally(); - Scope leave(); + Scope leave(); - Scope getBody(); + Scope getBody(); - Scope getFinallyBody(); + Scope getFinallyBody(); } /** * While */ - interface WhileScope extends Scope, ScopeElement { + interface WhileScope extends Scope, ScopeElement { } @@ -356,7 +356,7 @@ interface Numeric extends Value, Type { } - interface Port { + interface Port { /** * Gets the fully qualified port name including its source reference. Often on the form source.name @@ -365,12 +365,20 @@ interface Port { */ String getQualifiedName(); + + /** + * Get the owner of this port. This is the object that should be used to get/set its values + * + * @return the instance owning the port + */ + FmiSimulationInstance getOwner(); + /** * Gets the underlying objects from which the port is created * * @return */ - T getSourceObject(); + PORT_SCALAR_TYPE getSourceObject(); /** * Get the port name @@ -391,7 +399,7 @@ interface Port { * * @param receiver */ - void linkTo(Port... receiver) throws PortLinkException; + void linkTo(Port< PORT_SCALAR_TYPE,AST>... receiver) throws PortLinkException; /** * Break the source link @@ -439,7 +447,7 @@ interface NamedValue extends Value { } - interface IntVariable extends Variable, ProvidesTypedReferenceExp, NumericTypedReferenceExp { + interface IntVariable extends Variable, ProvidesTypedReferenceExp, NumericTypedReferenceExp { void decrement(); void increment(); @@ -456,12 +464,12 @@ interface ProvidesTypedReferenceExp { interface NumericTypedReferenceExp extends ProvidesTypedReferenceExp { } - interface DoubleVariable extends Variable, ProvidesTypedReferenceExp, NumericTypedReferenceExp { + interface DoubleVariable extends Variable, ProvidesTypedReferenceExp, NumericTypedReferenceExp { void set(Double value); } - interface BoolVariable extends Variable, ProvidesTypedReferenceExp { + interface BoolVariable extends Variable, ProvidesTypedReferenceExp { Predicate toPredicate(); } @@ -470,10 +478,10 @@ interface StringVariable extends Variable, Provides } - interface NamedVariable extends Variable { + interface NamedVariable extends Variable { } - interface StateVariable extends Variable { + interface StateVariable extends Variable { /** * Sets this state on the owning component in the active scope */ @@ -482,7 +490,7 @@ interface StateVariable extends Variable { /** * Sets this state on the owning component in the given scope */ - void set(Scope scope) throws IllegalStateException; + void set(Scope scope) throws IllegalStateException; /** * Destroys the state in the active scope. After this no other operation on the state is allowed @@ -492,17 +500,17 @@ interface StateVariable extends Variable { /** * Destroys the state in the active scope. After this no other operation on the state is allowed */ - void destroy(Scope scope) throws IllegalStateException; + void destroy(Scope scope) throws IllegalStateException; } /** * Handle for an fmu for the creation of component */ - interface Fmu2Variable extends Variable> { - Fmi2ComponentVariable instantiate(String name, String environmentname); + interface Fmu2Variable extends Variable> { + Fmi2ComponentVariable instantiate(String name, String environmentname); - Fmi2ComponentVariable instantiate(String name); + Fmi2ComponentVariable instantiate(String name); // /** // * Performs null check and frees the instance @@ -520,12 +528,13 @@ interface Fmu2Variable extends Variable> { // throw new RuntimeException("Argument is not an FMU instance - it is not an instance of ComponentVariableFmi2API"); // } // } - Fmi2ComponentVariable instantiate(String namePrefix, TryScope enclosingTryScope, Scope scope, String environmentName); + Fmi2ComponentVariable instantiate(String namePrefix, TryScope enclosingTryScope, Scope scope, + String environmentName); - Fmi2ComponentVariable instantiate(String namePrefix, FmiBuilder.TryScope enclosingTryScope, FmiBuilder.Scope scope, - String environmentName, boolean loggingOn); + Fmi2ComponentVariable instantiate(String namePrefix, FmiBuilder.TryScope enclosingTryScope, + FmiBuilder.Scope scope, String environmentName, boolean loggingOn); - Fmi2ComponentVariable instantiate(String name, TryScope enclosingTryScope, Scope scope); + Fmi2ComponentVariable instantiate(String name, TryScope enclosingTryScope, Scope scope); //void freeInstance(Fmi2ComponentVariable comp); @@ -539,7 +548,7 @@ Fmi2ComponentVariable instantiate(String namePrefix, FmiBuilder.TryScope< /** * Handle for an fmu for the creation of component */ - interface Fmu3Variable extends Variable> { + interface Fmu3Variable extends Variable> { } @@ -547,18 +556,18 @@ interface Fmu3Variable extends Variable> { /** * Generic type for all simulation instances * - * @param + * @param */ - interface SimulationInstance extends Variable> { + interface SimulationInstance extends Variable> { } /** * Type that represents common FMI functions accross versions for now 2 and 3 * - * @param the construction type. Often a kind of AST statement - * @param the port internal reference type. Often a kind of scalar variable from FMI + * @param the construction type. Often a kind of AST statement + * @param the port internal reference type. Often a kind of scalar variable from FMI */ - interface FmiSimulationInstance extends SimulationInstance { + interface FmiSimulationInstance extends SimulationInstance { void setDebugLogging(List categories, boolean enableLogging); @@ -570,19 +579,20 @@ interface FmiSimulationInstance extends SimulationInstance { * @param noSetFMUStatePriorToCurrentPoint a pair representing (full step completed, current time after step) * @return */ - Map.Entry, DoubleVariable> step(Scope scope, DoubleVariable currentCommunicationPoint, - DoubleVariable communicationStepSize, BoolVariable noSetFMUStatePriorToCurrentPoint); + Map.Entry, DoubleVariable> step(Scope scope, DoubleVariable currentCommunicationPoint, + DoubleVariable communicationStepSize, BoolVariable noSetFMUStatePriorToCurrentPoint); - Map.Entry, DoubleVariable> step(Scope scope, DoubleVariable currentCommunicationPoint, - DoubleVariable communicationStepSize); + Map.Entry, DoubleVariable> step(Scope scope, DoubleVariable currentCommunicationPoint, + DoubleVariable communicationStepSize); - Map.Entry, DoubleVariable> step(DoubleVariable currentCommunicationPoint, DoubleVariable communicationStepSize, - BoolVariable noSetFMUStatePriorToCurrentPoint); + Map.Entry, DoubleVariable> step(DoubleVariable currentCommunicationPoint, + DoubleVariable communicationStepSize, BoolVariable noSetFMUStatePriorToCurrentPoint); - Map.Entry, DoubleVariable> step(DoubleVariable currentCommunicationPoint, DoubleVariable communicationStepSize); + Map.Entry, DoubleVariable> step(DoubleVariable currentCommunicationPoint, + DoubleVariable communicationStepSize); - List> getPorts(); + List> getPorts(); /** * Get ports by name @@ -590,7 +600,7 @@ Map.Entry, DoubleVariable> step(DoubleVariable currentComm * @param names * @return */ - List> getPorts(String... names); + List> getPorts(String... names); /** * Get ports by ref val @@ -598,7 +608,7 @@ Map.Entry, DoubleVariable> step(DoubleVariable currentComm * @param valueReferences * @return */ - List> getPorts(int... valueReferences); + List> getPorts(int... valueReferences); /** * Get port by name @@ -606,7 +616,7 @@ Map.Entry, DoubleVariable> step(DoubleVariable currentComm * @param name * @return */ - Port getPort(String name); + Port getPort(String name); /** * Get port by ref val @@ -614,7 +624,7 @@ Map.Entry, DoubleVariable> step(DoubleVariable currentComm * @param valueReference * @return */ - Port getPort(int valueReference); + Port getPort(int valueReference); /** * Get port values aka fmiGet @@ -622,16 +632,16 @@ Map.Entry, DoubleVariable> step(DoubleVariable currentComm * @param ports * @return */ - Map, ? extends Variable> get(Port... ports); + Map, ? extends Variable> get(Port... ports); - Map, ? extends Variable> get(Scope scope, Port... ports); + Map, ? extends Variable> get(Scope scope, Port... ports); /** * Get all (linked) port values * * @return */ - Map, ? extends Variable> get(); + Map, ? extends Variable> get(); /** * get filter by value reference @@ -639,7 +649,7 @@ Map.Entry, DoubleVariable> step(DoubleVariable currentComm * @param valueReferences * @return */ - Map, ? extends Variable> get(int... valueReferences); + Map, ? extends Variable> get(int... valueReferences); /** * Get filter by names @@ -647,17 +657,17 @@ Map.Entry, DoubleVariable> step(DoubleVariable currentComm * @param names * @return */ - Map, ? extends Variable> get(String... names); + Map, ? extends Variable> get(String... names); - Map, ? extends Variable> getAndShare(String... names); + Map, ? extends Variable> getAndShare(String... names); - Map, ? extends Variable> getAndShare(Port... ports); + Map, ? extends Variable> getAndShare(Port... ports); - Map, ? extends Variable> getAndShare(); + Map, ? extends Variable> getAndShare(); - Variable getShared(String name); + Variable getShared(String name); - Variable getShared(Port port); + Variable getShared(Port port); /** * Get the value of a single port @@ -665,38 +675,38 @@ Map.Entry, DoubleVariable> step(DoubleVariable currentComm * @param name * @return */ - Variable getSingle(String name); + Variable getSingle(String name); - Variable getSingle(Port port); + Variable getSingle(Port port); - void set(Scope scope, PortValueMap value); + void set(Scope scope, PortValueMap value); - void set(Scope scope, PortVariableMap value); + void set(Scope scope, PortVariableMap< V, PORT_SCALAR_TYPE, AST> value); /** * Set port values (if ports is not from this fmu then the links are used to remap) * * @param value */ - void set(PortValueMap value); + void set(PortValueMap value); - void set(Port port, Value value); + void set(Port port, Value value); - void set(Port port, Variable value); + void set(Port port, Variable value); - void set(Scope scope, Port port, Variable value); + void set(Scope scope, Port port, Variable value); - void set(PortVariableMap value); + void set(PortVariableMap< V, PORT_SCALAR_TYPE, AST> value); /** * Set this fmu port by name and link */ - void setLinked(Scope scope, Port... filterPorts); + void setLinked(Scope scope, Port... filterPorts); void setLinked(); - void setLinked(Port... filterPorts); + void setLinked(Port... filterPorts); void setLinked(String... filterNames); @@ -722,7 +732,7 @@ Map.Entry, DoubleVariable> step(DoubleVariable currentComm * * @param values */ - void share(Map, ? extends Variable> values); + void share(Map, ? extends Variable> values); /** * Makes the value publicly available to all linked connections. On next set these ports will be resolved to the values given for @@ -730,64 +740,66 @@ Map.Entry, DoubleVariable> step(DoubleVariable currentComm * * @param value */ - void share(Port port, Variable value); + void share(Port port, Variable value); /** * Get the current state * * @return */ - StateVariable getState() throws XPathExpressionException; + StateVariable getState() throws XPathExpressionException; /** * Get the current state * * @return */ - StateVariable getState(Scope scope) throws XPathExpressionException; + StateVariable getState(Scope scope) throws XPathExpressionException; - interface PortVariableMap extends Map, Variable> { + interface PortVariableMap< V, PORT_SCALAR_TYPE, AST> extends Map, Variable> { } - interface PortValueMap extends Map, Value> { + interface PortValueMap extends Map, Value> { } - interface PortExpressionValueMap extends Map, ExpressionValue> { + interface PortExpressionValueMap extends Map, ExpressionValue> { } } /** * Simulation instance for FMI3 * - * @param building block - * @param fmi3 scalar variable type + * @param building block + * @param fmi3 scalar variable type */ - interface Fmi3InstanceVariable extends FmiSimulationInstance { + interface Fmi3InstanceVariable extends FmiSimulationInstance { - void setupExperiment(DoubleVariable startTime, DoubleVariable endTime, BoolVariable endTimeDefined, Double tolerance); + void setupExperiment(DoubleVariable startTime, DoubleVariable endTime, BoolVariable endTimeDefined, Double tolerance); void setupExperiment(double startTime, Double endTime, Double tolerance); void enterInitializationMode(boolean toleranceDefined, double tolerance, double startTime, boolean stopTimeDefined, double stopTime); - void enterInitializationMode(Scope scope,FmiBuilder.BoolVariable toleranceDefined, FmiBuilder.DoubleVariable tolerance, FmiBuilder.DoubleVariable startTime, - FmiBuilder.BoolVariable stopTimeDefined, FmiBuilder.DoubleVariable stopTime); - void enterInitializationMode(FmiBuilder.BoolVariable toleranceDefined, FmiBuilder.DoubleVariable tolerance, FmiBuilder.DoubleVariable startTime, - FmiBuilder.BoolVariable stopTimeDefined, FmiBuilder.DoubleVariable stopTime); + void enterInitializationMode(Scope scope, FmiBuilder.BoolVariable toleranceDefined, FmiBuilder.DoubleVariable tolerance, + FmiBuilder.DoubleVariable startTime, FmiBuilder.BoolVariable stopTimeDefined, FmiBuilder.DoubleVariable stopTime); + + void enterInitializationMode(FmiBuilder.BoolVariable toleranceDefined, FmiBuilder.DoubleVariable tolerance, + FmiBuilder.DoubleVariable startTime, FmiBuilder.BoolVariable stopTimeDefined, FmiBuilder.DoubleVariable stopTime); + void exitInitializationMode(); - void setupExperiment(Scope scope, DoubleVariable startTime, DoubleVariable endTime, BoolVariable endTimeDefined, + void setupExperiment(Scope scope, DoubleVariable startTime, DoubleVariable endTime, BoolVariable endTimeDefined, Double tolerance); - void setupExperiment(Scope scope, double startTime, Double endTime, Double tolerance); + void setupExperiment(Scope scope, double startTime, Double endTime, Double tolerance); - void enterInitializationMode(Scope scope,boolean toleranceDefined, double tolerance, double startTime, boolean stopTimeDefined, + void enterInitializationMode(Scope scope, boolean toleranceDefined, double tolerance, double startTime, boolean stopTimeDefined, double stopTime); - void exitInitializationMode(Scope scope); + void exitInitializationMode(Scope scope); - void terminate(Scope scope); + void terminate(Scope scope); void terminate(); @@ -799,14 +811,14 @@ void enterInitializationMode(Scope scope,boolean toleranceDefined, double tol *

* Note that all methods that do not take a scope uses the builders dynamic scope and adds the underlying instructions int he active scope. * - * @param building block - * @param fmi2 scalar variable type + * @param building block + * @param fmi2 scalar variable type */ - interface Fmi2ComponentVariable extends FmiSimulationInstance { + interface Fmi2ComponentVariable extends FmiSimulationInstance { void setDebugLogging(List categories, boolean enableLogging); - void setupExperiment(DoubleVariable startTime, DoubleVariable endTime, BoolVariable endTimeDefined, Double tolerance); + void setupExperiment(DoubleVariable startTime, DoubleVariable endTime, BoolVariable endTimeDefined, Double tolerance); void setupExperiment(double startTime, Double endTime, Double tolerance); @@ -814,39 +826,39 @@ interface Fmi2ComponentVariable extends FmiSimulationInstance { void exitInitializationMode(); - void setupExperiment(Scope scope, DoubleVariable startTime, DoubleVariable endTime, BoolVariable endTimeDefined, + void setupExperiment(Scope scope, DoubleVariable startTime, DoubleVariable endTime, BoolVariable endTimeDefined, Double tolerance); - void setupExperiment(Scope scope, double startTime, Double endTime, Double tolerance); + void setupExperiment(Scope scope, double startTime, Double endTime, Double tolerance); - void enterInitializationMode(Scope scope); + void enterInitializationMode(Scope scope); - void exitInitializationMode(Scope scope); + void exitInitializationMode(Scope scope); - void terminate(Scope scope); + void terminate(Scope scope); void terminate(); } - interface Variable { + interface Variable { String getName(); void setValue(V value); - void setValue(Variable variable); + void setValue(Variable variable); - void setValue(Scope scope, Variable variable); + void setValue(Scope scope, Variable variable); - void setValue(Scope scope, V value); + void setValue(Scope scope, V value); - Scope getDeclaredScope(); + Scope getDeclaredScope(); } - interface ArrayVariable extends Variable> { + interface ArrayVariable extends Variable> { int size(); - List> items(); + List> items(); void setValue(IntExpressionValue index, ExpressionValue value); } diff --git a/frameworks/core/src/main/java/org/intocps/maestro/framework/core/IRelation.java b/frameworks/core/src/main/java/org/intocps/maestro/framework/core/IRelation.java index ee7407125..1e69de09b 100644 --- a/frameworks/core/src/main/java/org/intocps/maestro/framework/core/IRelation.java +++ b/frameworks/core/src/main/java/org/intocps/maestro/framework/core/IRelation.java @@ -7,11 +7,11 @@ public interface IRelation { InternalOrExternal getOrigin(); - IVariable getSource(); + RelationVariable getSource(); Direction getDirection(); - Map getTargets(); + Map getTargets(); public enum InternalOrExternal { Internal, diff --git a/frameworks/core/src/main/java/org/intocps/maestro/framework/core/IVariable.java b/frameworks/core/src/main/java/org/intocps/maestro/framework/core/IVariable.java index e1e2bfb7e..3d4ddbf84 100644 --- a/frameworks/core/src/main/java/org/intocps/maestro/framework/core/IVariable.java +++ b/frameworks/core/src/main/java/org/intocps/maestro/framework/core/IVariable.java @@ -1,6 +1,6 @@ package org.intocps.maestro.framework.core; -public interface IVariable { - - RelationVariable getScalarVariable(); -} +//public interface IVariable { +// +// RelationVariable getScalarVariable(); +//} diff --git a/frameworks/core/src/main/java/org/intocps/maestro/framework/core/RelationVariable.java b/frameworks/core/src/main/java/org/intocps/maestro/framework/core/RelationVariable.java index a1755c759..f57482474 100644 --- a/frameworks/core/src/main/java/org/intocps/maestro/framework/core/RelationVariable.java +++ b/frameworks/core/src/main/java/org/intocps/maestro/framework/core/RelationVariable.java @@ -1,12 +1,72 @@ package org.intocps.maestro.framework.core; import org.intocps.maestro.ast.LexIdentifier; +import org.intocps.maestro.ast.node.PExp; +import org.intocps.maestro.ast.node.PType; import org.intocps.maestro.fmi.Fmi2ModelDescription; public interface RelationVariable { + /** + * Get the instance reference aka the lex name for the instance + * + * @return the lex identifier + */ LexIdentifier getInstance(); + /** + * Get the scalar variable name as in the model description this name will not be changed due to slashes + * + * @return the name + */ String getName(); - T getScalarVariable(Class clz); + /** + * Get the underlying scalar variable object as is or null is not matching the requested type + * + * @param clz the underlying type to filter by + * @param the filter type + * @return the underlying scalar variable object of the requested type + */ + T getScalarVariable(Class clz); + + /** + * Checks if any of the scalar variable enums apply for i.e. causality, Variability etc. + * + * @param scalarAttributeType object to check + * @return true if present + */ + boolean has(Object scalarAttributeType); + + + Type getType(); + +// Type getType(Class clz); + + /** + * The value reference of the scalar variable + * + * @return the value reference + */ + long getValueReference(); + + interface Type { + +// TP as(Class clz); + + /** + * Check if the scala variable holds the requested type enum + * + * @param type type enum to check for + * @return true if of the specified type + */ + boolean hasType(TypeEnum type); + + T get(); + + PType getLexType(); + + PExp getLexDefaultValue(); + + boolean isAssignableFrom(T other, boolean autoConvert); + } } diff --git a/frameworks/fmi2/src/main/java/org/intocps/maestro/framework/fmi2/Fmi2SimulationEnvironment.java b/frameworks/fmi2/src/main/java/org/intocps/maestro/framework/fmi2/Fmi2SimulationEnvironment.java index 968987edb..650cf633c 100644 --- a/frameworks/fmi2/src/main/java/org/intocps/maestro/framework/fmi2/Fmi2SimulationEnvironment.java +++ b/frameworks/fmi2/src/main/java/org/intocps/maestro/framework/fmi2/Fmi2SimulationEnvironment.java @@ -11,7 +11,8 @@ import org.intocps.maestro.core.messages.IErrorReporter; import org.intocps.maestro.fmi.Fmi2ModelDescription; import org.intocps.maestro.fmi.ModelDescription; -import org.intocps.maestro.fmi.org.intocps.maestro.fmi.fmi3.Fmi3ModelDescription; +import org.intocps.maestro.fmi.fmi3.Fmi3Causality; +import org.intocps.maestro.fmi.fmi3.Fmi3ModelDescription; import org.intocps.maestro.framework.core.*; import org.intocps.maestro.parser.template.MablSwapConditionParserUtil; import org.slf4j.Logger; @@ -35,6 +36,7 @@ import java.util.stream.Collectors; import java.util.stream.Stream; +@SuppressWarnings("rawtypes") public class Fmi2SimulationEnvironment implements ISimulationEnvironment, ISimulationEnvironmentTransfer { final static Logger logger = LoggerFactory.getLogger(Fmi2SimulationEnvironment.class); private final Map instanceLexToInstanceName = new HashMap<>(); @@ -43,8 +45,8 @@ public class Fmi2SimulationEnvironment implements ISimulationEnvironment, ISimul Map instanceNameToInstanceComponentInfo = new HashMap<>(); HashMap fmuKeyToModelDescription = new HashMap<>(); Map fmuToUri = null; - Map variables = new HashMap<>(); - Map> globalVariablesToLogForInstance = new HashMap<>(); + Map variables = new HashMap<>(); + Map> globalVariablesToLogForInstance = new HashMap<>(); Map instanceToModelTransfer = new HashMap<>(); Map instanceToModelSwap = new HashMap<>(); private String faultInjectionConfigurationPath; @@ -95,7 +97,7 @@ private static Map> t = variablesToLogMap.entrySet().stream().collect( Collectors.toMap(entry -> extractInstance.apply(entry.getKey()), entry -> globalVariablesToLogForInstance.get(extractInstance.apply(entry.getKey())).stream() - .filter(x -> entry.getValue().contains(x.scalarVariable.name)).collect(Collectors.toList()))); + .filter(x -> entry.getValue().contains(x.getName())).collect(Collectors.toList()))); return t; } @@ -103,9 +105,8 @@ private static Map getConnectedOutputs() { return getInstances().stream().flatMap(instance -> this.getRelations(new LexIdentifier(instance.getKey(), null)).stream() - .filter(relation -> (relation.getOrigin() == Relation.InternalOrExternal.External) && - (relation.getDirection() == Relation.Direction.OutputToInput)).map(x -> x.getSource().scalarVariable)) - .collect(Collectors.toList()); + .filter(relation -> (relation.getOrigin() == Relation.InternalOrExternal.External) && + (relation.getDirection() == Relation.Direction.OutputToInput)).map(x -> x.getSource())).collect(Collectors.toList()); } @@ -150,8 +151,8 @@ public FrameworkUnitInfo getInstanceByLexName(String lexName) { * @return */ @Override - public List getVariablesToLog(String instanceName) { - List vars = this.globalVariablesToLogForInstance.get(instanceName); + public List getVariablesToLog(String instanceName) { + List vars = this.globalVariablesToLogForInstance.get(instanceName); if (vars == null) { return new ArrayList<>(); } else { @@ -222,7 +223,7 @@ private void initialize(Fmi2SimulationEnvironmentConfiguration msg, ModelDescrip HashMap fmuKeyToModelDescription = buildFmuKeyToFmuMD(fmuToURI, resolver); this.fmuKeyToModelDescription = fmuKeyToModelDescription; - if (msg.faultInjectConfigurationPath != null && msg.faultInjectConfigurationPath.length() > 0) { + if (msg.faultInjectConfigurationPath != null && !msg.faultInjectConfigurationPath.isEmpty()) { if ((new File(msg.faultInjectConfigurationPath).exists())) { this.faultInjectionConfigurationPath = msg.faultInjectConfigurationPath; } else { @@ -264,7 +265,7 @@ private Map> buildRelations(Fmi2SimulationEnvironme // Add the instance to the globalVariablesToLogForInstance map. - List globalVariablesToLogForGivenInstance; + List globalVariablesToLogForGivenInstance; if (this.globalVariablesToLogForInstance.containsKey(instance.instanceName)) { globalVariablesToLogForGivenInstance = this.globalVariablesToLogForInstance.get(instance.instanceName); } else { @@ -278,7 +279,8 @@ private Map> buildRelations(Fmi2SimulationEnvironme buildFmi2Relation((Fmi2ModelDescription) md, instance, instanceLexIdentifier, idToRelations, connections, globalVariablesToLogForGivenInstance); } else if (md instanceof Fmi3ModelDescription) { - + buildFmi3Relation((Fmi3ModelDescription) md, instance, instanceLexIdentifier, idToRelations, connections, + globalVariablesToLogForGivenInstance); } } @@ -296,22 +298,26 @@ private Map> buildRelations(Fmi2SimulationEnvironme } - List variablesToLogForInstance = new ArrayList<>(); + List variablesToLogForInstance = new ArrayList<>(); String logVariablesKey = instance.key + "." + instance.instanceName; if (globalLogVariablesMaps.containsKey(logVariablesKey)) { for (String s : globalLogVariablesMaps.get(logVariablesKey)) { ModelDescription md = this.fmuKeyToModelDescription.get(instance.key); - org.intocps.maestro.framework.core.RelationVariable rvar = null; + RelationVariable rvar = null; if (md instanceof Fmi2ModelDescription) { - rvar = new RelationVariable( - ((Fmi2ModelDescription) md).getScalarVariables().stream().filter(x -> x.name.equals(s)).findFirst().get(), - instanceLexIdentifier); + Fmi2ModelDescription.ScalarVariable sv = + ((Fmi2ModelDescription) md).getScalarVariables().stream().filter(x -> x.name.equals(s)).findFirst().get(); + rvar = new RelationVariable<>(sv, sv.getName(), instanceLexIdentifier, sv.getValueReference(), + new RelationVariable.RelationFmi2Type(sv.getType())); } else if (md instanceof Fmi3ModelDescription) { - rvar = new RelationVariable3( + Fmi3ModelDescription.Fmi3ScalarVariable sv = ((Fmi3ModelDescription) md).getScalarVariables().stream().filter(x -> x.getVariable().getName().equals(s)).findFirst() - .get(), instanceLexIdentifier); + .get(); + rvar = new RelationVariable<>(sv, sv.getVariable().getName(), instanceLexIdentifier, + sv.getVariable().getValueReferenceAsLong(), + new RelationVariable.RelationFmi3Type(sv.getVariable().getTypeIdentifier())); } @@ -320,9 +326,8 @@ private Map> buildRelations(Fmi2SimulationEnvironme } if (this.globalVariablesToLogForInstance.containsKey(instance.instanceName)) { - List existingRVs = - this.globalVariablesToLogForInstance.get(instance.instanceName); - for (org.intocps.maestro.framework.core.RelationVariable rv : variablesToLogForInstance) { + List existingRVs = this.globalVariablesToLogForInstance.get(instance.instanceName); + for (RelationVariable rv : variablesToLogForInstance) { if (!existingRVs.contains(rv)) { existingRVs.add(rv); } @@ -338,25 +343,31 @@ private Map> buildRelations(Fmi2SimulationEnvironme private void buildFmi2Relation(Fmi2ModelDescription md2, ModelConnection.ModelInstance instance, LexIdentifier instanceLexIdentifier, Map> idToRelations, List connections, - List globalVariablesToLogForGivenInstance) throws XPathExpressionException, InvocationTargetException, IllegalAccessException, EnvironmentException { + List globalVariablesToLogForGivenInstance) throws XPathExpressionException, InvocationTargetException, IllegalAccessException, EnvironmentException { + + List instanceOutputScalarVariablesPorts = md2.getScalarVariables().stream().filter(x -> x.causality == Fmi2ModelDescription.Causality.Output).collect(Collectors.toList()); Set instanceRelations = idToRelations.computeIfAbsent(instanceLexIdentifier, key -> new HashSet<>()); for (Fmi2ModelDescription.ScalarVariable outputScalarVariable : instanceOutputScalarVariablesPorts) { - Variable outputVariable = getOrCreateVariable(outputScalarVariable, instanceLexIdentifier); + RelationVariable outputVariable = getOrCreateVariable( + new org.intocps.maestro.framework.fmi2.RelationVariable<>(outputScalarVariable, outputScalarVariable.getName(), + instanceLexIdentifier), instanceLexIdentifier); // dependantInputs are the inputs on which the current output depends on internally - Map dependantInputs = new HashMap<>(); + Map dependantInputs = new HashMap<>(); for (Fmi2ModelDescription.ScalarVariable inputScalarVariable : outputScalarVariable.outputDependencies.keySet()) { if (inputScalarVariable.causality == Fmi2ModelDescription.Causality.Input) { - Variable inputVariable = getOrCreateVariable(inputScalarVariable, instanceLexIdentifier); + RelationVariable inputVariable = getOrCreateVariable( + new org.intocps.maestro.framework.fmi2.RelationVariable<>(outputScalarVariable, outputScalarVariable.getName(), + instanceLexIdentifier), instanceLexIdentifier); dependantInputs.put(instanceLexIdentifier, inputVariable); } // TODO: Add relation from each input to the given output? } - if (dependantInputs.size() != 0) { + if (!dependantInputs.isEmpty()) { Relation r = new Relation(); r.source = outputVariable; r.targets = dependantInputs; @@ -369,11 +380,11 @@ private void buildFmi2Relation(Fmi2ModelDescription md2, ModelConnection.ModelIn List externalInputTargets = connections.stream().filter(conn -> conn.from.instance.equals(instance) && conn.from.variable.equals(outputScalarVariable.name)) .map(conn -> conn.to).collect(Collectors.toList()); - if (externalInputTargets.size() != 0) { + if (!externalInputTargets.isEmpty()) { // Log the current output as there is an input depending on it. - globalVariablesToLogForGivenInstance.add(outputVariable.scalarVariable); + globalVariablesToLogForGivenInstance.add(outputVariable); // externalInputs are all the external Inputs that depends on the current output - Map externalInputs = new HashMap<>(); + Map externalInputs = new HashMap<>(); for (ModelConnection.Variable modelConnToVar : externalInputTargets) { FrameworkUnitInfo frameworkUnitInfo = instanceNameToInstanceComponentInfo.get(modelConnToVar.instance.instanceName); @@ -385,7 +396,97 @@ private void buildFmi2Relation(Fmi2ModelDescription md2, ModelConnection.ModelIn .filter(sv -> sv.name.equals(modelConnToVar.variable)).findFirst(); if (toScalarVariable.isPresent()) { LexIdentifier inputInstanceLexIdentifier = new LexIdentifier(modelConnToVar.instance.instanceName, null); - Variable inputVariable = getOrCreateVariable(toScalarVariable.get(), inputInstanceLexIdentifier); + RelationVariable inputVariable = getOrCreateVariable( + new org.intocps.maestro.framework.fmi2.RelationVariable<>(toScalarVariable.get(), + toScalarVariable.get().getName(), inputInstanceLexIdentifier), inputInstanceLexIdentifier); + externalInputs.put(inputInstanceLexIdentifier, inputVariable); + + //Add relation from the input to the given output + Set inputInstanceRelations = idToRelations.computeIfAbsent(inputInstanceLexIdentifier, key -> new HashSet<>()); + Relation r = new Relation(); + r.source = inputVariable; + r.targets = new HashMap<>() {{ + put(instanceLexIdentifier, outputVariable); + }}; + r.origin = Relation.InternalOrExternal.External; + r.direction = Relation.Direction.InputToOutput; + inputInstanceRelations.add(r); + } else { + throw new EnvironmentException( + "Failed to find the scalar variable " + modelConnToVar.variable + " at " + modelConnToVar.instance + + " when building the dependencies tree"); + } + } else { + logger.warn("Framework unit is not a component: {}", frameworkUnitInfo.getClass().getName()); + } + } + + Relation r = new Relation(); + r.source = outputVariable; + r.targets = externalInputs; + r.direction = Relation.Direction.OutputToInput; + r.origin = Relation.InternalOrExternal.External; + instanceRelations.add(r); + } + } + } + + private void buildFmi3Relation(Fmi3ModelDescription md2, ModelConnection.ModelInstance instance, LexIdentifier instanceLexIdentifier, + Map> idToRelations, List connections, + List globalVariablesToLogForGivenInstance) throws EnvironmentException { + List instanceOutputScalarVariablesPorts = + md2.getScalarVariables().stream().filter(x -> x.getVariable().getCausality() == Fmi3Causality.Output).collect(Collectors.toList()); + + Set instanceRelations = idToRelations.computeIfAbsent(instanceLexIdentifier, key -> new HashSet<>()); + + for (Fmi3ModelDescription.Fmi3ScalarVariable outputScalarVariable : instanceOutputScalarVariablesPorts) { + RelationVariable outputVariable = getOrCreateVariable( + new org.intocps.maestro.framework.fmi2.RelationVariable<>(outputScalarVariable, outputScalarVariable.getVariable().getName(), + instanceLexIdentifier), instanceLexIdentifier); + + // dependantInputs are the inputs on which the current output depends on internally + Map dependantInputs = new HashMap<>(); + for (Fmi3ModelDescription.Fmi3ScalarVariable inputScalarVariable : outputScalarVariable.getOutputDependencies().keySet()) { + if (inputScalarVariable.getVariable().getCausality() == Fmi3Causality.Input) { + RelationVariable inputVariable = getOrCreateVariable( + new org.intocps.maestro.framework.fmi2.RelationVariable<>(inputScalarVariable, + inputScalarVariable.getVariable().getName(), instanceLexIdentifier), instanceLexIdentifier); + dependantInputs.put(instanceLexIdentifier, inputVariable); + } + // TODO: Add relation from each input to the given output? + } + if (!dependantInputs.isEmpty()) { + Relation r = new Relation(); + r.source = outputVariable; + r.targets = dependantInputs; + r.direction = Relation.Direction.OutputToInput; + r.origin = Relation.InternalOrExternal.Internal; + instanceRelations.add(r); + } + + // externalInputTargets are the inputs that depend on the current output based on the provided connections. + List externalInputTargets = connections.stream() + .filter(conn -> conn.from.instance.equals(instance) && conn.from.variable.equals(outputScalarVariable.getVariable().getName())) + .map(conn -> conn.to).collect(Collectors.toList()); + if (!externalInputTargets.isEmpty()) { + // Log the current output as there is an input depending on it. + globalVariablesToLogForGivenInstance.add(outputVariable); + // externalInputs are all the external Inputs that depends on the current output + Map externalInputs = new HashMap<>(); + for (ModelConnection.Variable modelConnToVar : externalInputTargets) { + FrameworkUnitInfo frameworkUnitInfo = instanceNameToInstanceComponentInfo.get(modelConnToVar.instance.instanceName); + + if (frameworkUnitInfo instanceof InstanceInfo) { + + + Optional toScalarVariable = + ((InstanceInfo) frameworkUnitInfo).getModelDescription().getScalarVariables().stream() + .filter(sv -> sv.getVariable().getName().equals(modelConnToVar.variable)).findFirst(); + if (toScalarVariable.isPresent()) { + LexIdentifier inputInstanceLexIdentifier = new LexIdentifier(modelConnToVar.instance.instanceName, null); + RelationVariable inputVariable = getOrCreateVariable( + new org.intocps.maestro.framework.fmi2.RelationVariable<>(toScalarVariable.get(), + toScalarVariable.get().getVariable().getName(), inputInstanceLexIdentifier), inputInstanceLexIdentifier); externalInputs.put(inputInstanceLexIdentifier, inputVariable); //Add relation from the input to the given output @@ -433,13 +534,14 @@ private HashMap buildFmuKeyToFmuMD(Map fm return fmuKeyToFmuWithMD; } - Variable getOrCreateVariable(Fmi2ModelDescription.ScalarVariable inputScalarVariable, LexIdentifier instanceLexIdentifier) { - if (variables.containsKey(inputScalarVariable.name + instanceLexIdentifier)) { - return variables.get(inputScalarVariable.name + instanceLexIdentifier); + + RelationVariable getOrCreateVariable(RelationVariable relationVariable, LexIdentifier instanceLexIdentifier) { + if (variables.containsKey(relationVariable.getName() + instanceLexIdentifier)) { + return variables.get(relationVariable.getName() + instanceLexIdentifier); } else { - Variable variable = new Variable(new org.intocps.maestro.framework.fmi2.RelationVariable(inputScalarVariable, instanceLexIdentifier)); - variables.put(inputScalarVariable.name + instanceLexIdentifier, variable); - return variable; + // RelationVariable variable = new RelationVariable(relationVariable, relationVariable.getName(), instanceLexIdentifier); + variables.put(relationVariable.getName() + instanceLexIdentifier, relationVariable); + return relationVariable; } } @@ -523,10 +625,10 @@ public interface ModelDescriptionResolver extends BiFunction targets; + Map targets; @Override public InternalOrExternal getOrigin() { @@ -534,7 +636,7 @@ public InternalOrExternal getOrigin() { } @Override - public Variable getSource() { + public RelationVariable getSource() { return source; } @@ -544,7 +646,7 @@ public Direction getDirection() { } @Override - public Map getTargets() { + public Map getTargets() { return targets; } @@ -557,12 +659,12 @@ public String toString() { public static class RelationBuilder { - private final Variable source; - private final Map targets; + private final RelationVariable source; + private final Map targets; private InternalOrExternal origin = InternalOrExternal.External; private Direction direction = Direction.OutputToInput; - public RelationBuilder(Variable source, Map targets) { + public RelationBuilder(RelationVariable source, Map targets) { this.source = source; this.targets = targets; } @@ -588,27 +690,28 @@ public Relation build() { } } - public static class Variable implements IVariable { - public final org.intocps.maestro.framework.fmi2.RelationVariable scalarVariable; - - public Variable(org.intocps.maestro.framework.fmi2.RelationVariable scalarVariable) { - this.scalarVariable = scalarVariable; - } + // public static class Variable implements IVariable { + // public final org.intocps.maestro.framework.core.RelationVariable scalarVariable; + // + // public Variable(org.intocps.maestro.framework.core.RelationVariable scalarVariable) { + // this.scalarVariable = scalarVariable; + // } + // + // @Override + // public org.intocps.maestro.framework.core.RelationVariable getScalarVariable() { + // return scalarVariable; + // } + // + // T getFrameworkInfo(Framework framework) { + // return (T) scalarVariable; + // } + // + // @Override + // public String toString() { + // return scalarVariable.toString(); + // } + // } - @Override - public org.intocps.maestro.framework.fmi2.RelationVariable getScalarVariable() { - return scalarVariable; - } - - T getFrameworkInfo(Framework framework) { - return (T) scalarVariable; - } - - @Override - public String toString() { - return scalarVariable.toString(); - } - } public static class FileModelDescriptionResolver implements ModelDescriptionResolver { static XPath xPath = XPathFactory.newInstance().newXPath(); diff --git a/frameworks/fmi2/src/main/java/org/intocps/maestro/framework/fmi2/InstanceInfo.java b/frameworks/fmi2/src/main/java/org/intocps/maestro/framework/fmi2/InstanceInfo.java index e2527c4b9..57cbfcb9b 100644 --- a/frameworks/fmi2/src/main/java/org/intocps/maestro/framework/fmi2/InstanceInfo.java +++ b/frameworks/fmi2/src/main/java/org/intocps/maestro/framework/fmi2/InstanceInfo.java @@ -1,6 +1,6 @@ package org.intocps.maestro.framework.fmi2; -import org.intocps.maestro.fmi.org.intocps.maestro.fmi.fmi3.Fmi3ModelDescription; +import org.intocps.maestro.fmi.fmi3.Fmi3ModelDescription; import org.intocps.maestro.framework.core.FaultInject; import org.intocps.maestro.framework.core.FrameworkUnitInfo; diff --git a/frameworks/fmi2/src/main/java/org/intocps/maestro/framework/fmi2/RelationVariable.java b/frameworks/fmi2/src/main/java/org/intocps/maestro/framework/fmi2/RelationVariable.java index d5724ca14..ce9f208ff 100644 --- a/frameworks/fmi2/src/main/java/org/intocps/maestro/framework/fmi2/RelationVariable.java +++ b/frameworks/fmi2/src/main/java/org/intocps/maestro/framework/fmi2/RelationVariable.java @@ -1,20 +1,46 @@ package org.intocps.maestro.framework.fmi2; import org.intocps.maestro.ast.LexIdentifier; +import org.intocps.maestro.ast.node.PExp; +import org.intocps.maestro.ast.node.PType; import org.intocps.maestro.fmi.Fmi2ModelDescription; +import org.intocps.maestro.fmi.fmi3.Fmi3Causality; +import org.intocps.maestro.fmi.fmi3.Fmi3ModelDescription; +import org.intocps.maestro.fmi.fmi3.Fmi3TypeEnum; +import java.util.Optional; -public class RelationVariable implements org.intocps.maestro.framework.core.RelationVariable { - public final Fmi2ModelDescription.ScalarVariable scalarVariable; +import static org.intocps.maestro.ast.MableAstFactory.*; + + +public class RelationVariable implements org.intocps.maestro.framework.core.RelationVariable { + private final SCALAR_TYPE scalarVariable; + final String name; // instance is necessary because: // If you look up the relations for FMU Component A, // and there is a dependency from FMU Component B Input as Source to FMU Component A as Target. // Then it is only possible to figure out that Source actually belongs to FMU Component B if instance is part of Source. public final LexIdentifier instance; + private final long valueReference; + private final Object type; - public RelationVariable(Fmi2ModelDescription.ScalarVariable scalarVariable, LexIdentifier instance) { + public RelationVariable(SCALAR_TYPE scalarVariable, String name, LexIdentifier instance, long valueReference, Type type) { this.scalarVariable = scalarVariable; + this.name = name; this.instance = instance; + this.valueReference = valueReference; + this.type = type; + } + + public RelationVariable(Fmi2ModelDescription.ScalarVariable scalarVariable, String name, LexIdentifier instance) { + this((SCALAR_TYPE) scalarVariable, name, instance, scalarVariable.getValueReference(), new RelationFmi2Type(scalarVariable.getType())); + + } + + public RelationVariable(Fmi3ModelDescription.Fmi3ScalarVariable scalarVariable, String name, LexIdentifier instance) { + this((SCALAR_TYPE) scalarVariable, name, instance, scalarVariable.getVariable().getValueReferenceAsLong(), + new RelationFmi3Type(scalarVariable.getVariable().getTypeIdentifier())); + } @Override @@ -24,7 +50,7 @@ public LexIdentifier getInstance() { @Override public String getName() { - return scalarVariable.getName(); + return name; } @Override @@ -35,8 +61,72 @@ public T getScalarVariable(Class clz) { return null; } - public Fmi2ModelDescription.ScalarVariable getScalarVariable() { - return getScalarVariable(this.scalarVariable.getClass()); + @Override + public boolean has(Object scalarAttributeType) { + if (scalarAttributeType instanceof Fmi2ModelDescription.Causality) { + return has((Fmi2ModelDescription.Causality) scalarAttributeType); + } else if (scalarAttributeType instanceof Fmi3Causality) { + return has((Fmi3Causality) scalarAttributeType); + } + return false; + } + + @Override + public Type getType() { + return (Type) type; + } + + public RelationFmi2Type getType2() { + if (this.type instanceof RelationFmi2Type) { + return (RelationFmi2Type) this.type; + } else if (this.type instanceof RelationFmi3Type) { + //todo convert if possible + } + return null; + } + + public RelationFmi3Type getType3() { + if (this.type instanceof RelationFmi2Type) { + //todo convert if possible + } else if (this.type instanceof RelationFmi3Type) { + return (RelationFmi3Type) this.type; + } + return null; + } + + // @Override + // public Type getType(Class clz) { + // + // if (type != null && clz.isAssignableFrom(type.get().getClass())) { + // return (Type) type; + // } + // return null; + // } + + @Override + public long getValueReference() { + return valueReference; + } + + public boolean has(Fmi2ModelDescription.Causality scalarAttributeType) { + return getFmi2ScalarVariable().map(s -> s.causality == scalarAttributeType).orElse(false); + } + + public boolean has(Fmi3Causality scalarAttributeType) { + return getFmi3ScalarVariable().map(s -> s.getVariable().getCausality() == scalarAttributeType).orElse(false); + } + + + public Optional getFmi2ScalarVariable() { + return Optional.of(getScalarVariable(Fmi2ModelDescription.ScalarVariable.class)); + } + + public Optional getFmi3ScalarVariable() { + return Optional.of(getScalarVariable(Fmi3ModelDescription.Fmi3ScalarVariable.class)); + } + + public SCALAR_TYPE getScalarVariable() { + return scalarVariable; } @Override @@ -56,4 +146,187 @@ public boolean equals(Object o) { RelationVariable rv = (RelationVariable) o; return rv.toString().equals(this.toString()); } + + public static class RelationFmi2Type implements org.intocps.maestro.framework.core.RelationVariable.Type { + + final Fmi2ModelDescription.Type type; + + public RelationFmi2Type(Fmi2ModelDescription.Type type) { + this.type = type; + } + + // @Override + // public T as(Class clz) { + // + // if (clz.isAssignableFrom(type.getClass())) { + // return (T) clz.cast(type); + // } + // + // return null; + // } + + @Override + public boolean hasType(Fmi2ModelDescription.Types type) { + return this.type.type == type; + } + + @Override + public Fmi2ModelDescription.Type get() { + return this.type; + } + + @Override + public PType getLexType() { + switch (this.type.type) { + case Boolean: + return newABoleanPrimitiveType(); + case Real: + return newARealNumericPrimitiveType(); + case Integer: + return newAIntNumericPrimitiveType(); + case String: + return newAStringPrimitiveType(); + default: + throw new UnsupportedOperationException("Converting fmi type: " + type + " to mabl type is not supported."); + } + } + + @Override + public PExp getLexDefaultValue() { + + + switch (this.type.type) { + + case Boolean: + return newABoolLiteralExp(false); + case Real: + return newARealLiteralExp(0.0); + case Integer: + case Enumeration: + return newAIntLiteralExp(0); + case String: + return newAStringLiteralExp(""); + + + } + throw new RuntimeException("Unknown type"); + } + + @Override + public boolean isAssignableFrom(Fmi2ModelDescription.Type other, boolean autoConvert) { + return this.type.isAssignableFrom(other, autoConvert); + } + } + + public static class RelationFmi3Type implements org.intocps.maestro.framework.core.RelationVariable.Type { + + final Fmi3TypeEnum type; + + public RelationFmi3Type(Fmi3TypeEnum type) { + this.type = type; + } + + // @Override + // public T as(Class clz) { + // + // if (clz.isAssignableFrom(type.getClass())) { + // return (T) clz.cast(type); + // } + // + // return null; + // } + + @Override + public boolean hasType(Fmi3TypeEnum type) { + return this.type == type; + } + + @Override + public Fmi3TypeEnum get() { + return this.type; + } + + @Override + public PType getLexType() { + switch (this.type) { + case Float32Type: + break; + case Float64Type: + break; + case Int8Type: + break; + case UInt8Type: + break; + case Int16Type: + break; + case UInt16Type: + break; + case Int32Type: + return newAIntNumericPrimitiveType(); + case UInt32Type: + break; + case Int64Type: + break; + case UInt64Type: + return newARealNumericPrimitiveType(); + case BooleanType: + return newABoleanPrimitiveType(); + case StringType: + return newAStringPrimitiveType(); + case BinaryType: + break; + case EnumerationType: + break; + case ClockType: + break; + default: + throw new UnsupportedOperationException("Converting fmi type: " + type + " to mabl type is not supported."); + } + return null; + } + + @Override + public PExp getLexDefaultValue() { + + switch (this.type) { + + case Float32Type: + break; + case Float64Type: + break; + case Int8Type: + break; + case UInt8Type: + break; + case Int16Type: + break; + case UInt16Type: + break; + case Int32Type: + return newAIntLiteralExp(0); + case UInt32Type: + break; + case Int64Type: + break; + case UInt64Type: + break; + case BooleanType: + return newABoolLiteralExp(false); + case StringType: + return newAStringLiteralExp(""); + case BinaryType: + break; + case EnumerationType: + break; + case ClockType: + break; + } + throw new RuntimeException("Unknown type"); + } + + @Override + public boolean isAssignableFrom(Fmi3TypeEnum other, boolean autoConvert) { + return this.type.equals(other); + } + } } diff --git a/frameworks/fmi2/src/main/java/org/intocps/maestro/framework/fmi2/RelationVariable3.java b/frameworks/fmi2/src/main/java/org/intocps/maestro/framework/fmi2/RelationVariable3.java index 680cfd003..dfddbb95f 100644 --- a/frameworks/fmi2/src/main/java/org/intocps/maestro/framework/fmi2/RelationVariable3.java +++ b/frameworks/fmi2/src/main/java/org/intocps/maestro/framework/fmi2/RelationVariable3.java @@ -1,54 +1,54 @@ -package org.intocps.maestro.framework.fmi2; - -import org.intocps.maestro.ast.LexIdentifier; -import org.intocps.maestro.fmi.org.intocps.maestro.fmi.fmi3.Fmi3ModelDescription; - -public class RelationVariable3 implements org.intocps.maestro.framework.core.RelationVariable { - public final Fmi3ModelDescription.Fmi3ScalarVariable scalarVariable; - public final LexIdentifier instance; - - public RelationVariable3(Fmi3ModelDescription.Fmi3ScalarVariable scalarVariable, LexIdentifier instance) { - this.scalarVariable = scalarVariable; - this.instance = instance; - } - - @Override - public LexIdentifier getInstance() { - return this.instance; - } - - @Override - public String getName() { - return scalarVariable.getVariable().getName(); - } - - @Override - public T getScalarVariable(Class clz) { - if (clz.isAssignableFrom(scalarVariable.getClass())) { - return clz.cast(scalarVariable); - } - return null; - } - - public Fmi3ModelDescription.Fmi3ScalarVariable getScalarVariable() { - return getScalarVariable(this.scalarVariable.getClass()); - } - - @Override - public String toString() { - return instance + "." + scalarVariable; - } - - @Override - public boolean equals(Object o) { - if (o == this) { - return true; - } - if (!(o instanceof RelationVariable)) { - return false; - } - - RelationVariable rv = (RelationVariable) o; - return rv.toString().equals(this.toString()); - } -} \ No newline at end of file +//package org.intocps.maestro.framework.fmi2; +// +//import org.intocps.maestro.ast.LexIdentifier; +//import org.intocps.maestro.fmi.fmi3.Fmi3ModelDescription; +// +//public class RelationVariable3 implements org.intocps.maestro.framework.core.RelationVariable { +// public final Fmi3ModelDescription.Fmi3ScalarVariable scalarVariable; +// public final LexIdentifier instance; +// +// public RelationVariable3(Fmi3ModelDescription.Fmi3ScalarVariable scalarVariable, LexIdentifier instance) { +// this.scalarVariable = scalarVariable; +// this.instance = instance; +// } +// +// @Override +// public LexIdentifier getInstance() { +// return this.instance; +// } +// +// @Override +// public String getName() { +// return scalarVariable.getVariable().getName(); +// } +// +// @Override +// public T getScalarVariable(Class clz) { +// if (clz.isAssignableFrom(scalarVariable.getClass())) { +// return clz.cast(scalarVariable); +// } +// return null; +// } +// +// public Fmi3ModelDescription.Fmi3ScalarVariable getScalarVariable() { +// return getScalarVariable(this.scalarVariable.getClass()); +// } +// +// @Override +// public String toString() { +// return instance + "." + scalarVariable; +// } +// +// @Override +// public boolean equals(Object o) { +// if (o == this) { +// return true; +// } +// if (!(o instanceof RelationVariable)) { +// return false; +// } +// +// RelationVariable rv = (RelationVariable) o; +// return rv.toString().equals(this.toString()); +// } +//} \ No newline at end of file diff --git a/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/BuilderUtil.java b/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/BuilderUtil.java index 40a3da138..3dc14248d 100644 --- a/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/BuilderUtil.java +++ b/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/BuilderUtil.java @@ -1,9 +1,6 @@ package org.intocps.maestro.framework.fmi2.api.mabl; -import org.intocps.maestro.ast.node.PExp; -import org.intocps.maestro.ast.node.PStateDesignator; -import org.intocps.maestro.ast.node.PStm; -import org.intocps.maestro.ast.node.PType; +import org.intocps.maestro.ast.node.*; import org.intocps.maestro.framework.fmi2.api.FmiBuilder; import org.intocps.maestro.framework.fmi2.api.mabl.variables.ComponentVariableFmi2Api; import org.intocps.maestro.framework.fmi2.api.mabl.variables.FmuVariableFmi2Api; @@ -32,7 +29,12 @@ public static List createTypeConvertingAssignment(PStateDesignator designa // String varName = builder.getNameGenerator().getName(); // statements.add(newVariable(varName, targetType)); - if (typeComparator.compatible(newBoleanType(), valueType) && (typeComparator.compatible(newRealType(), targetType)) || + if (typeComparator.compatible(newRealType(), valueType) && typeComparator.compatible(new AFloatNumericPrimitiveType(), targetType)) { + // real to float + + statements.add(newAAssignmentStm(designator, value)); + + } else if (typeComparator.compatible(newBoleanType(), valueType) && (typeComparator.compatible(newRealType(), targetType)) || typeComparator.compatible(newRealType(), targetType) || typeComparator.compatible(newRealType(), targetType)) { //bool to number PExp trueToken = newAIntLiteralExp(1); diff --git a/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/FromMaBLToMaBLAPI.java b/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/FromMaBLToMaBLAPI.java index 7031446d5..1c26f5040 100644 --- a/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/FromMaBLToMaBLAPI.java +++ b/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/FromMaBLToMaBLAPI.java @@ -3,10 +3,13 @@ import org.intocps.maestro.ast.AVariableDeclaration; import org.intocps.maestro.ast.LexIdentifier; import org.intocps.maestro.ast.node.*; -import org.intocps.maestro.framework.core.*; +import org.intocps.maestro.framework.core.FrameworkUnitInfo; +import org.intocps.maestro.framework.core.IRelation; +import org.intocps.maestro.framework.core.ISimulationEnvironment; import org.intocps.maestro.framework.fmi2.ComponentInfo; import org.intocps.maestro.framework.fmi2.Fmi2SimulationEnvironment; import org.intocps.maestro.framework.fmi2.InstanceInfo; +import org.intocps.maestro.framework.fmi2.RelationVariable; import org.intocps.maestro.framework.fmi2.api.FmiBuilder; import org.intocps.maestro.framework.fmi2.api.mabl.variables.ComponentVariableFmi2Api; import org.intocps.maestro.framework.fmi2.api.mabl.variables.FmuVariableFmi2Api; @@ -136,8 +139,8 @@ public static void createBindings(Map instance for (IRelation relation : relations.stream().filter(x -> x.getDirection() == Fmi2SimulationEnvironment.Relation.Direction.OutputToInput && x.getOrigin() == Fmi2SimulationEnvironment.Relation.InternalOrExternal.External).collect(Collectors.toList())) { - for (IVariable targetVar : relation.getTargets().values()) { - String targetName = targetVar.getScalarVariable().getInstance().getText(); + for (var targetVar : relation.getTargets().values()) { + String targetName = targetVar.getInstance().getText(); if (instances.containsKey(targetName) || instances.values().stream().anyMatch(x -> x.getEnvironmentName().equalsIgnoreCase(targetName))) { ComponentVariableFmi2Api instance = instances.get(targetName); @@ -149,9 +152,9 @@ public static void createBindings(Map instance } } - PortFmi2Api targetPort = instance.getPort(targetVar.getScalarVariable().getName()); + PortFmi2Api targetPort = instance.getPort(targetVar.getName()); - String sourcePortName = relation.getSource().getScalarVariable().getName(); + String sourcePortName = relation.getSource().getName(); if (targetPort != null) { entry.getValue().getPort(sourcePortName).linkTo(targetPort); } else { @@ -177,8 +180,8 @@ public static void createBindings3(Map instance for (IRelation relation : relations.stream().filter(x -> x.getDirection() == Fmi2SimulationEnvironment.Relation.Direction.OutputToInput && x.getOrigin() == Fmi2SimulationEnvironment.Relation.InternalOrExternal.External).collect(Collectors.toList())) { - for (IVariable targetVar : relation.getTargets().values()) { - String targetName = targetVar.getScalarVariable().getInstance().getText(); + for (var targetVar : relation.getTargets().values()) { + String targetName = targetVar.getInstance().getText(); if (instances.containsKey(targetName) || instances.values().stream().anyMatch(x -> x.getEnvironmentName().equalsIgnoreCase(targetName))) { InstanceVariableFmi3Api instance = instances.get(targetName); @@ -190,9 +193,9 @@ public static void createBindings3(Map instance } } - PortFmi3Api targetPort = instance.getPort(targetVar.getScalarVariable().getName()); + PortFmi3Api targetPort = instance.getPort(targetVar.getName()); - String sourcePortName = relation.getSource().getScalarVariable().getName(); + String sourcePortName = relation.getSource().getName(); if (targetPort != null) { entry.getValue().getPort(sourcePortName).linkTo(targetPort); } else { diff --git a/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/ModelDescriptionContext.java b/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/ModelDescriptionContext.java index b926d197f..408506ef1 100644 --- a/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/ModelDescriptionContext.java +++ b/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/ModelDescriptionContext.java @@ -1,7 +1,6 @@ package org.intocps.maestro.framework.fmi2.api.mabl; import org.intocps.maestro.fmi.Fmi2ModelDescription; -import org.intocps.maestro.fmi.org.intocps.maestro.fmi.fmi3.Fmi3ModelDescription; import javax.xml.xpath.XPathExpressionException; import java.lang.reflect.InvocationTargetException; @@ -13,6 +12,7 @@ public class ModelDescriptionContext { private final Fmi2ModelDescription modelDescription; public Map nameToSv = new HashMap<>(); public Map valRefToSv = new HashMap<>(); + public ModelDescriptionContext( Fmi2ModelDescription modelDescription) throws IllegalAccessException, XPathExpressionException, InvocationTargetException { this.modelDescription = modelDescription; @@ -21,6 +21,7 @@ public ModelDescriptionContext( this.valRefToSv.put(sv.valueReference, sv); }); } + public Fmi2ModelDescription getModelDescription() { return modelDescription; } diff --git a/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/ModelDescriptionContext3.java b/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/ModelDescriptionContext3.java index 3c9e75125..2c3142672 100644 --- a/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/ModelDescriptionContext3.java +++ b/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/ModelDescriptionContext3.java @@ -1,7 +1,6 @@ package org.intocps.maestro.framework.fmi2.api.mabl; -import kotlin.UInt; -import org.intocps.maestro.fmi.org.intocps.maestro.fmi.fmi3.Fmi3ModelDescription; +import org.intocps.maestro.fmi.fmi3.Fmi3ModelDescription; import javax.xml.xpath.XPathExpressionException; import java.lang.reflect.InvocationTargetException; @@ -13,6 +12,7 @@ public class ModelDescriptionContext3 { private final Fmi3ModelDescription modelDescription; public Map nameToSv = new HashMap<>(); public Map valRefToSv = new HashMap<>(); + public ModelDescriptionContext3( Fmi3ModelDescription modelDescription) throws IllegalAccessException, XPathExpressionException, InvocationTargetException { this.modelDescription = modelDescription; @@ -21,6 +21,7 @@ public ModelDescriptionContext3( this.valRefToSv.put((long) sv.getVariable().getValueReferenceAsLong(), sv); }); } + public Fmi3ModelDescription getModelDescription() { return modelDescription; } diff --git a/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/PortFmi2Api.java b/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/PortFmi2Api.java index 0d8390752..6445411c2 100644 --- a/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/PortFmi2Api.java +++ b/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/PortFmi2Api.java @@ -1,5 +1,6 @@ package org.intocps.maestro.framework.fmi2.api.mabl; +import org.intocps.maestro.ast.node.PStm; import org.intocps.maestro.ast.node.PType; import org.intocps.maestro.fmi.Fmi2ModelDescription; import org.intocps.maestro.framework.fmi2.api.FmiBuilder; @@ -11,7 +12,7 @@ import static org.intocps.maestro.ast.MableAstFactory.*; -public class PortFmi2Api implements FmiBuilder.Port { +public class PortFmi2Api implements FmiBuilder.Port { public final ComponentVariableFmi2Api aMablFmi2ComponentAPI; public final Fmi2ModelDescription.ScalarVariable scalarVariable; @@ -61,6 +62,11 @@ public String getQualifiedName() { this.getName(); } + @Override + public FmiBuilder.FmiSimulationInstance getOwner() { + return this.aMablFmi2ComponentAPI; + } + @Override public Fmi2ModelDescription.ScalarVariable getSourceObject() { return this.scalarVariable; @@ -78,7 +84,7 @@ public Long getPortReferenceValue() { @Override - public void linkTo(FmiBuilder.Port... receivers) throws PortLinkException { + public void linkTo(FmiBuilder.Port... receivers) throws PortLinkException { if (receivers == null || receivers.length == 0) { return; @@ -88,7 +94,7 @@ public void linkTo(FmiBuilder.Port... recei throw new PortLinkException("Can only link output ports. This port is: " + this.scalarVariable.causality, this); } - for (FmiBuilder.Port receiver : receivers) { + for (FmiBuilder.Port receiver : receivers) { PortFmi2Api receiverPort = (PortFmi2Api) receiver; if (receiverPort.scalarVariable.causality != Fmi2ModelDescription.Causality.Input) { diff --git a/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/PortFmi3Api.java b/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/PortFmi3Api.java index 303838f7b..94f8e32d2 100644 --- a/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/PortFmi3Api.java +++ b/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/PortFmi3Api.java @@ -1,8 +1,8 @@ package org.intocps.maestro.framework.fmi2.api.mabl; -import org.intocps.maestro.ast.node.PType; -import org.intocps.maestro.fmi.org.intocps.maestro.fmi.fmi3.Fmi3Causality; -import org.intocps.maestro.fmi.org.intocps.maestro.fmi.fmi3.Fmi3ModelDescription; +import org.intocps.maestro.ast.node.*; +import org.intocps.maestro.fmi.fmi3.Fmi3Causality; +import org.intocps.maestro.fmi.fmi3.Fmi3ModelDescription; import org.intocps.maestro.framework.fmi2.api.FmiBuilder; import org.intocps.maestro.framework.fmi2.api.mabl.variables.InstanceVariableFmi3Api; import org.intocps.maestro.framework.fmi2.api.mabl.variables.VariableFmi2Api; @@ -10,7 +10,9 @@ import java.util.ArrayList; import java.util.List; -public class PortFmi3Api implements FmiBuilder.Port { +import static org.intocps.maestro.ast.MableAstFactory.*; + +public class PortFmi3Api implements FmiBuilder.Port { public final InstanceVariableFmi3Api aMablFmi3InstanceAPI; public final Fmi3ModelDescription.Fmi3ScalarVariable scalarVariable; @@ -42,15 +44,55 @@ public void setSharedAsVariable(VariableFmi2Api sharedAsVariable) { public PType getType() { switch (scalarVariable.getVariable().getTypeIdentifier()) { - // case Boolean: - // return newBoleanType(); - // case Real: - // return newRealType(); - // case Integer: - // return newIntType(); - // case String: - // return newStringType(); - // case Enumeration: + + + // case Boolean: + // return newBoleanType(); + // case Real: + // return newRealType(); + // case Integer: + // return newIntType(); + // case String: + // return newStringType(); + // case Enumeration: + /*#primitive + = {boolean} + | {string} + | #numeric + ; + +#numeric + = {real} + | {int} + | {uInt} + | {float} + | {short} + | {byte} + | {long}*/ + case Float64Type: + return new ARealNumericPrimitiveType(); + case Float32Type: + case ClockType: + return new AFloatNumericPrimitiveType(); + case Int8Type: + return new AShortNumericPrimitiveType(); + case UInt8Type: + case Int16Type: + case UInt16Type: + case Int32Type: + return newIntType(); + case UInt32Type: + case Int64Type: + case UInt64Type: + new ALongNumericPrimitiveType(); + case BooleanType: + return newBoleanType(); + case StringType: + return newStringType(); + case BinaryType: + return null; + case EnumerationType: + new ALongNumericPrimitiveType(); default: return null; } @@ -61,6 +103,11 @@ public String getQualifiedName() { return this.aMablFmi3InstanceAPI.getOwner().getFmuIdentifier() + "." + this.aMablFmi3InstanceAPI.getEnvironmentName() + "." + this.getName(); } + @Override + public FmiBuilder.FmiSimulationInstance getOwner() { + return this.aMablFmi3InstanceAPI; + } + @Override public Fmi3ModelDescription.Fmi3ScalarVariable getSourceObject() { return this.scalarVariable; @@ -78,7 +125,7 @@ public Long getPortReferenceValue() { @Override - public void linkTo(FmiBuilder.Port... receivers) throws PortLinkException { + public void linkTo(FmiBuilder.Port... receivers) throws PortLinkException { if (receivers == null || receivers.length == 0) { return; diff --git a/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/scoping/DynamicActiveBuilderScope.java b/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/scoping/DynamicActiveBuilderScope.java index 98b9b52e0..ebcd344fe 100644 --- a/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/scoping/DynamicActiveBuilderScope.java +++ b/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/scoping/DynamicActiveBuilderScope.java @@ -2,7 +2,7 @@ import org.intocps.maestro.ast.node.PStm; import org.intocps.maestro.fmi.Fmi2ModelDescription; -import org.intocps.maestro.fmi.org.intocps.maestro.fmi.fmi3.Fmi3ModelDescription; +import org.intocps.maestro.fmi.fmi3.Fmi3ModelDescription; import org.intocps.maestro.framework.fmi2.api.FmiBuilder; import org.intocps.maestro.framework.fmi2.api.mabl.variables.*; diff --git a/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/scoping/IMablScope.java b/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/scoping/IMablScope.java index 93c2b9069..29b0186af 100644 --- a/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/scoping/IMablScope.java +++ b/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/scoping/IMablScope.java @@ -2,7 +2,7 @@ import org.intocps.maestro.ast.node.PStm; import org.intocps.maestro.fmi.Fmi2ModelDescription; -import org.intocps.maestro.fmi.org.intocps.maestro.fmi.fmi3.Fmi3ModelDescription; +import org.intocps.maestro.fmi.fmi3.Fmi3ModelDescription; import org.intocps.maestro.framework.fmi2.api.FmiBuilder; import org.intocps.maestro.framework.fmi2.api.mabl.variables.*; diff --git a/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/scoping/ScopeFmi2Api.java b/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/scoping/ScopeFmi2Api.java index ac2608d99..294fb1680 100644 --- a/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/scoping/ScopeFmi2Api.java +++ b/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/scoping/ScopeFmi2Api.java @@ -5,7 +5,8 @@ import org.intocps.maestro.ast.MableAstFactory; import org.intocps.maestro.ast.node.*; import org.intocps.maestro.fmi.Fmi2ModelDescription; -import org.intocps.maestro.fmi.org.intocps.maestro.fmi.fmi3.Fmi3ModelDescription; + +import org.intocps.maestro.fmi.fmi3.Fmi3ModelDescription; import org.intocps.maestro.framework.fmi2.api.FmiBuilder; import org.intocps.maestro.framework.fmi2.api.mabl.MablApiBuilder; import org.intocps.maestro.framework.fmi2.api.mabl.PredicateFmi2Api; diff --git a/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/values/PortValueExpresssionMapImpl.java b/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/values/PortValueExpresssionMapImpl.java index 52c02e5c5..889089e02 100644 --- a/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/values/PortValueExpresssionMapImpl.java +++ b/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/values/PortValueExpresssionMapImpl.java @@ -1,11 +1,12 @@ package org.intocps.maestro.framework.fmi2.api.mabl.values; +import org.intocps.maestro.ast.node.PStm; import org.intocps.maestro.framework.fmi2.api.FmiBuilder; import java.util.HashMap; import java.util.Map; -public class PortValueExpresssionMapImpl extends HashMap, FmiBuilder.ExpressionValue> implements FmiBuilder.Fmi2ComponentVariable.PortExpressionValueMap { +public class PortValueExpresssionMapImpl extends HashMap, FmiBuilder.ExpressionValue> implements FmiBuilder.Fmi2ComponentVariable.PortExpressionValueMap { public PortValueExpresssionMapImpl(int initialCapacity, float loadFactor) { super(initialCapacity, loadFactor); } @@ -17,7 +18,7 @@ public PortValueExpresssionMapImpl(int initialCapacity) { public PortValueExpresssionMapImpl() { } - public PortValueExpresssionMapImpl(Map, ? extends FmiBuilder.ExpressionValue> m) { + public PortValueExpresssionMapImpl(Map, ? extends FmiBuilder.ExpressionValue> m) { super(m); } } diff --git a/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/values/PortValueMapImpl.java b/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/values/PortValueMapImpl.java index 0a6171ac6..58342628f 100644 --- a/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/values/PortValueMapImpl.java +++ b/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/values/PortValueMapImpl.java @@ -1,11 +1,12 @@ package org.intocps.maestro.framework.fmi2.api.mabl.values; +import org.intocps.maestro.ast.node.PStm; import org.intocps.maestro.framework.fmi2.api.FmiBuilder; import java.util.HashMap; import java.util.Map; -public class PortValueMapImpl extends HashMap, FmiBuilder.Value> implements FmiBuilder.Fmi2ComponentVariable.PortValueMap { +public class PortValueMapImpl extends HashMap, FmiBuilder.Value> implements FmiBuilder.Fmi2ComponentVariable.PortValueMap { public PortValueMapImpl(int initialCapacity, float loadFactor) { super(initialCapacity, loadFactor); } @@ -17,7 +18,7 @@ public PortValueMapImpl(int initialCapacity) { public PortValueMapImpl() { } - public PortValueMapImpl(Map, ? extends FmiBuilder.Value> m) { + public PortValueMapImpl(Map, ? extends FmiBuilder.Value> m) { super(m); } } diff --git a/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/variables/ComponentVariableFmi2Api.java b/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/variables/ComponentVariableFmi2Api.java index cf6c395c1..339ffa2b6 100644 --- a/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/variables/ComponentVariableFmi2Api.java +++ b/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/variables/ComponentVariableFmi2Api.java @@ -98,13 +98,13 @@ public List getVariablesToLog() { return this.getPorts(this.variabesToLog.toArray(new String[0])); } - public void setVariablesToLog(List variablesToLog) { + public void setVariablesToLog(List variablesToLog) { this.variabesToLog = variablesToLog.stream().map(RelationVariable::getName).collect(Collectors.toList()); } @Override - public void share(FmiBuilder.Port port, FmiBuilder.Variable value) { - Map, FmiBuilder.Variable> map = new HashMap<>(); + public void share(FmiBuilder.Port port, FmiBuilder.Variable value) { + Map, FmiBuilder.Variable> map = new HashMap<>(); map.put(port, value); share(map); } @@ -474,12 +474,13 @@ public Map> getTentative(IMablScope scope, S } @Override - public Map> get(FmiBuilder.Port... ports) { + public Map> get(FmiBuilder.Port... ports) { return get(builder.getDynamicScope().getActiveScope(), ports); } @Override - public Map> get(FmiBuilder.Scope scope, FmiBuilder.Port... ports) { + public Map> get(FmiBuilder.Scope scope, + FmiBuilder.Port... ports) { List selectedPorts; if (ports == null || ports.length == 0) { @@ -664,15 +665,15 @@ public Map> getAndShare(String... names) { } @Override - public Map, ? extends FmiBuilder.Variable> getAndShare( - FmiBuilder.Port... ports) { + public Map, ? extends FmiBuilder.Variable> getAndShare( + FmiBuilder.Port... ports) { Map> values = get(ports); share(values); return values; } @Override - public Map, ? extends FmiBuilder.Variable> getAndShare() { + public Map, ? extends FmiBuilder.Variable> getAndShare() { Map> values = get(); share(values); return values; @@ -689,7 +690,7 @@ public VariableFmi2Api getShared(FmiBuilder.Port port) { } @Override - public VariableFmi2Api getSingle(FmiBuilder.Port port) { + public VariableFmi2Api getSingle(FmiBuilder.Port port) { return (VariableFmi2Api) this.get(port).entrySet().iterator().next().getValue(); } @@ -751,7 +752,7 @@ public void set(PortExpressionValueMap value) { this.set(builder.getDynamicScope().getActiveScope(), value); } - public void set(FmiBuilder.Scope scope, PortExpressionValueMap value) { + public void set(FmiBuilder.Scope scope, PortExpressionValueMap value) { if (value == null || value.isEmpty()) { return; } @@ -765,7 +766,7 @@ public void set(FmiBuilder.Scope scope, PortExpressionValueMap void set(FmiBuilder.Scope scope, PortValueMap value) { + public void set(FmiBuilder.Scope scope, PortValueMap value) { if (value == null || value.isEmpty()) { @@ -797,7 +798,7 @@ public void set(FmiBuilder.Scope scope, PortValueMap void set(FmiBuilder.Scope scope, PortVariableMap value) { + public void set(FmiBuilder.Scope scope, PortVariableMap value) { List selectedPorts; if (value == null || value.isEmpty()) { @@ -962,17 +963,18 @@ public void setDerivatives(ArrayVariableFmi2Api derValInBuf, ArrayVariableFmi2Ap } @Override - public void set(PortValueMap value) { + public void set(PortValueMap value) { set(builder.getDynamicScope(), value); } @Override - public void set(FmiBuilder.Port port, FmiBuilder.Variable value) { + public void set(FmiBuilder.Port port, FmiBuilder.Variable value) { this.set(new PortVariableMapImpl(Map.of(port, value))); } @Override - public void set(FmiBuilder.Scope scope, FmiBuilder.Port port, FmiBuilder.Variable value) { + public void set(FmiBuilder.Scope scope, FmiBuilder.Port port, + FmiBuilder.Variable value) { this.set(scope, new PortVariableMapImpl(Map.of(port, value))); } @@ -986,12 +988,12 @@ public void set(FmiBuilder.Port port, FmiBuilder.Value value) { @Override - public void set(PortVariableMap value) { + public void set(PortVariableMap value) { set(builder.getDynamicScope(), value); } @Override - public void setLinked(FmiBuilder.Scope scope, FmiBuilder.Port... filterPorts) { + public void setLinked(FmiBuilder.Scope scope, FmiBuilder.Port... filterPorts) { List selectedPorts = ports.stream().filter(isLinked).collect(Collectors.toList()); if (filterPorts != null && filterPorts.length != 0) { @@ -1081,7 +1083,7 @@ public void terminate(FmiBuilder.Scope scope) { } @Override - public void share(Map, ? extends FmiBuilder.Variable> values) { + public void share(Map, ? extends FmiBuilder.Variable> values) { // Group by the string value of the port type as grouping by the port type itself doesnt utilise equals values.entrySet().stream().collect(Collectors.groupingBy(map -> ((PortFmi2Api) map.getKey()).getType().toString())).entrySet().stream() .forEach(map -> { diff --git a/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/variables/InstanceVariableFmi3Api.java b/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/variables/InstanceVariableFmi3Api.java index f040c2b06..11a46967a 100644 --- a/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/variables/InstanceVariableFmi3Api.java +++ b/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/variables/InstanceVariableFmi3Api.java @@ -6,9 +6,9 @@ import org.intocps.maestro.ast.analysis.AnalysisException; import org.intocps.maestro.ast.analysis.DepthFirstAnalysisAdaptor; import org.intocps.maestro.ast.node.*; -import org.intocps.maestro.fmi.org.intocps.maestro.fmi.fmi3.Fmi3Causality; -import org.intocps.maestro.fmi.org.intocps.maestro.fmi.fmi3.Fmi3ModelDescription; -import org.intocps.maestro.fmi.org.intocps.maestro.fmi.fmi3.Fmi3TypeEnum; +import org.intocps.maestro.fmi.fmi3.Fmi3Causality; +import org.intocps.maestro.fmi.fmi3.Fmi3ModelDescription; +import org.intocps.maestro.fmi.fmi3.Fmi3TypeEnum; import org.intocps.maestro.framework.fmi2.RelationVariable; import org.intocps.maestro.framework.fmi2.api.FmiBuilder; import org.intocps.maestro.framework.fmi2.api.mabl.*; @@ -94,12 +94,12 @@ public List getVariablesToLog() { } public void setVariablesToLog(List variablesToLog) { - this.variabesToLog = variablesToLog.stream().map(x -> x.scalarVariable.getName()).collect(Collectors.toList()); + this.variabesToLog = variablesToLog.stream().map(x -> x.getName()).collect(Collectors.toList()); } @Override - public void share(FmiBuilder.Port port, FmiBuilder.Variable value) { - Map, FmiBuilder.Variable> map = new HashMap<>(); + public void share(FmiBuilder.Port port, FmiBuilder.Variable value) { + Map, FmiBuilder.Variable> map = new HashMap<>(); map.put(port, value); share(map); } @@ -487,14 +487,14 @@ public Map> getTentative(IMablScope scope, S } @Override - public Map> get(FmiBuilder.Port... ports) { + public Map> get(FmiBuilder.Port... ports) { return get(builder.getDynamicScope().getActiveScope(), ports); } @SuppressWarnings("unchecked") @Override public Map> get(FmiBuilder.Scope scope, - FmiBuilder.Port... ports) { + FmiBuilder.Port... ports) { List selectedPorts; if (ports == null || ports.length == 0) { @@ -700,15 +700,15 @@ public Map> getAndShare(String... names) { } @Override - public Map, ? extends FmiBuilder.Variable> getAndShare( - FmiBuilder.Port... ports) { + public Map, ? extends FmiBuilder.Variable> getAndShare( + FmiBuilder.Port... ports) { Map> values = get(ports); share(values); return values; } @Override - public Map, ? extends FmiBuilder.Variable> getAndShare() { + public Map, ? extends FmiBuilder.Variable> getAndShare() { Map> values = get(); share(values); return values; @@ -728,7 +728,7 @@ public VariableFmi2Api getShared(FmiBuilder.Port port) { @SuppressWarnings("unchecked") @Override - public VariableFmi2Api getSingle(FmiBuilder.Port port) { + public VariableFmi2Api getSingle(FmiBuilder.Port port) { return (VariableFmi2Api) this.get(port).entrySet().iterator().next().getValue(); } @@ -748,7 +748,7 @@ private String createFunctionName(FmiFunctionType f, Fmi3TypeEnum type) { default: throw new RuntimeException("Attempting to call non type-dependant function with type: " + type); } - functionName += type.name(); + functionName += type.name().substring(0, type.name().length() - "Type".length()); return functionName; } @@ -764,7 +764,7 @@ public void set(FmiBuilder.Port p, FmiBuilder.ExpressionValue v) { } @SuppressWarnings("unchecked") - public void set(FmiBuilder.Scope scope, FmiBuilder.Port p, FmiBuilder.ExpressionValue v) { + public void set(FmiBuilder.Scope scope, FmiBuilder.Port p, FmiBuilder.ExpressionValue v) { this.set(scope, new PortValueMapImpl(Map.of(p, v))); } @@ -772,7 +772,7 @@ public void set(PortExpressionValueMap value) { this.set(builder.getDynamicScope().getActiveScope(), value); } - public void set(FmiBuilder.Scope scope, PortExpressionValueMap value) { + public void set(FmiBuilder.Scope scope, PortExpressionValueMap value) { if (value == null || value.isEmpty()) { return; } @@ -786,7 +786,7 @@ public void set(FmiBuilder.Scope scope, PortExpressionValueMap void set(FmiBuilder.Scope scope, PortValueMap value) { + public void set(FmiBuilder.Scope scope, PortValueMap value) { if (value == null || value.isEmpty()) { @@ -819,7 +819,7 @@ public void set(FmiBuilder.Scope scope, PortValueMap void set(FmiBuilder.Scope scope, PortVariableMap value) { + public void set(FmiBuilder.Scope scope, PortVariableMap value) { List selectedPorts; if (value == null || value.isEmpty()) { @@ -869,7 +869,7 @@ public void set(FmiBuilder.Scope scope, List selectedPorts, F AAssigmentStm stm = newAAssignmentStm(((IMablScope) scope).getFmiStatusVariable().getDesignator().clone(), call(this.getReferenceExp().clone(), createFunctionName(FmiFunctionType.SET, value.get(0)), vrefBuf.getReferenceExp().clone(), - newAUIntLiteralExp((long) value.size()), valBuf.getReferenceExp().clone())); + newAIntLiteralExp(value.size()), valBuf.getReferenceExp().clone(), newAIntLiteralExp(value.size()))); scope.add(stm); handleError(scope, createFunctionName(FmiFunctionType.SET, sortedPorts.get(0))); @@ -978,39 +978,39 @@ public void setDerivatives(ArrayVariableFmi2Api derValInBuf, ArrayVariableFmi2Ap } @Override - public void set(PortValueMap value) { + public void set(PortValueMap value) { set(builder.getDynamicScope(), value); } @SuppressWarnings("unchecked") @Override - public void set(FmiBuilder.Port port, FmiBuilder.Variable value) { + public void set(FmiBuilder.Port port, FmiBuilder.Variable value) { this.set(new PortVariableMapImpl(Map.of(port, value))); } @SuppressWarnings("unchecked") @Override - public void set(FmiBuilder.Scope scope, FmiBuilder.Port port, + public void set(FmiBuilder.Scope scope, FmiBuilder.Port port, FmiBuilder.Variable value) { this.set(scope, new PortVariableMapImpl(Map.of(port, value))); } @SuppressWarnings("unchecked") @Override - public void set(FmiBuilder.Port port, FmiBuilder.Value value) { + public void set(FmiBuilder.Port port, FmiBuilder.Value value) { PortValueMap map = new PortValueMapImpl(); map.put(port, value); set(map); } @Override - public void set(PortVariableMap value) { + public void set(PortVariableMap value) { set(builder.getDynamicScope(), value); } @SuppressWarnings("unchecked") @Override - public void setLinked(FmiBuilder.Scope scope, FmiBuilder.Port... filterPorts) { + public void setLinked(FmiBuilder.Scope scope, FmiBuilder.Port... filterPorts) { List selectedPorts = ports.stream().filter(isLinked).collect(Collectors.toList()); if (filterPorts != null && filterPorts.length != 0) { @@ -1051,7 +1051,7 @@ public void setLinked(FmiBuilder.Scope scope, FmiBuilder.Port[]) null); + this.setLinked(dynamicScope, (FmiBuilder.Port[]) null); } @SuppressWarnings("unchecked") @@ -1115,75 +1115,72 @@ public void freeInstance(FmiBuilder.Scope scope) { // TODO: implement this from the other share function below. This for now to build. - @Override - public void share(Map, ? extends FmiBuilder.Variable> values) { - ; - } - // @Override - // public void share(Map> values) { - // // Group by the string value of the port type as grouping by the port type itself doesnt utilise equals - // values.entrySet().stream().collect(Collectors.groupingBy(map -> ((PortFmi3Api) map.getKey()).getType().toString())).entrySet().stream() - // .forEach(map -> { - // PType type = ((PortFmi3Api) map.getValue().get(0).getKey()).getType(); - // - // Map data = - // map.getValue().stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); - // - // data.keySet().stream().map(PortFmi3Api.class::cast).sorted(Comparator.comparing(PortFmi3Api::getPortReferenceValue)) - // .forEach(port -> { - // //this is the sorted set of assignments, these can be replaced by a memcopy later - // ArrayVariableFmi2Api buffer = getSharedBuffer(type); - // if (port.getSharedAsVariable() == null) { - // ArrayVariableFmi2Api newBuf = growBuffer(buffer, 1); - // this.setSharedBuffer(newBuf, type); - // - // VariableFmi2Api newShared = newBuf.items().get(newBuf.items().size() - 1); - // port.setSharedAsVariable(newShared); - // } - // - // PStateDesignator designator = port.getSharedAsVariable().getDesignator(); - // builder.getDynamicScope().addAll(BuilderUtil.createTypeConvertingAssignment(builder, dynamicScope, designator.clone(), - // ((VariableFmi2Api) data.get(port)).getReferenceExp().clone(), port.getType(), - // ((VariableFmi2Api) ((VariableFmi2Api) data.get(port))).type)); - // - // - // if (type.equals(new ARealNumericPrimitiveType()) && derivativePortsToShare != null) { - // // Find match a derivativePortsToShare where both port reference and derivative port reference matches. - // derivativePortsToShare.keySet().stream().filter(derivativePort -> { - // try { - // return modelDescriptionContext.getModelDescription().getDerivativesMap().entrySet().stream().anyMatch( - // e -> e.getKey().getValueReference().equals(port.getPortReferenceValue()) && - // e.getValue().getValueReference().equals(derivativePort.getPortReferenceValue())); - // } catch (XPathExpressionException | InvocationTargetException | IllegalAccessException e) { - // throw new RuntimeException( - // "Attempting to obtain shared values from a port that is linked but has no value shared. Share a value " + - // "first. " + port); - // } - // }).findFirst().ifPresent((derivativePort) -> { - // // If the derivative port is not yet shared then get shared derivative buffer, grow it by one and set the port as shared - // // with the new array. - // if (derivativePort.getSharedAsVariable() == null) { - // ArrayVariableFmi2Api sharedDerBuf = growSharedDerBuf(1); - // - // ArrayVariableFmi2Api newSharedArray = - // (ArrayVariableFmi2Api) sharedDerBuf.items().get(sharedDerBuf.items().size() - 1); - // derivativePort.setSharedAsVariable(newSharedArray); - // } - // - // // DerivativePorts.get(derivativePort).size should equal derivativePort.getSharedAsVariable().items().size() as they are - // // both determined by the max derivative order. - // List derivatives = ((ArrayVariableFmi2Api) derivativePort.getSharedAsVariable()).items(); - // for (int i = 0; i < derivatives.size(); i++) { - // PExp val = derivativePortsToShare.get(derivativePort).get(i).getReferenceExp().clone(); - // builder.getDynamicScope().add(newAAssignmentStm(derivatives.get(i).getDesignator().clone(), val)); - // } - // }); - // } - // }); - // }); + // public void share( + // Map, ? extends FmiBuilder.Variable> values) { + // ; // } + @Override + public void share( + Map, ? extends FmiBuilder.Variable> values) { + // Group by the string value of the port type as grouping by the port type itself doesnt utilise equals + values.entrySet().stream().collect(Collectors.groupingBy(map -> ((PortFmi3Api) map.getKey()).getType().toString())).entrySet().stream() + .forEach(map -> { + PType type = ((PortFmi3Api) map.getValue().get(0).getKey()).getType(); + + Map, FmiBuilder.Variable> data = + map.getValue().stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + + data.keySet().stream().map(PortFmi3Api.class::cast).sorted(Comparator.comparing(PortFmi3Api::getPortReferenceValue)) + .forEach(port -> { + //this is the sorted set of assignments, these can be replaced by a memcopy later + ArrayVariableFmi2Api buffer = getSharedBuffer(type); + if (port.getSharedAsVariable() == null) { + ArrayVariableFmi2Api newBuf = growBuffer(buffer, 1); + this.setSharedBuffer(newBuf, type); + + VariableFmi2Api newShared = newBuf.items().get(newBuf.items().size() - 1); + port.setSharedAsVariable(newShared); + } + + PStateDesignator designator = port.getSharedAsVariable().getDesignator(); + builder.getDynamicScope().addAll(BuilderUtil.createTypeConvertingAssignment(builder, dynamicScope, designator.clone(), + ((VariableFmi2Api) data.get(port)).getReferenceExp().clone(), port.getType(), + ((VariableFmi2Api) ((VariableFmi2Api) data.get(port))).type)); + + + if (type.equals(new ARealNumericPrimitiveType()) && derivativePortsToShare != null) { + // Find match a derivativePortsToShare where both port reference and derivative port reference matches. + derivativePortsToShare.keySet().stream().filter(derivativePort -> { + return modelDescriptionContext.getModelDescription().getDerivatives().stream() + .map(v -> v.getVariable().getValueReferenceAsLong()).anyMatch( + vref -> vref.equals(port.getPortReferenceValue()) && + vref.equals(derivativePort.getPortReferenceValue())); + }).findFirst().ifPresent((derivativePort) -> { + // If the derivative port is not yet shared then get shared derivative buffer, grow it by one and set the port as shared + // with the new array. + if (derivativePort.getSharedAsVariable() == null) { + ArrayVariableFmi2Api sharedDerBuf = growSharedDerBuf(1); + + ArrayVariableFmi2Api newSharedArray = + (ArrayVariableFmi2Api) sharedDerBuf.items().get(sharedDerBuf.items().size() - 1); + derivativePort.setSharedAsVariable(newSharedArray); + } + + // DerivativePorts.get(derivativePort).size should equal derivativePort.getSharedAsVariable().items().size() as they are + // both determined by the max derivative order. + List derivatives = ((ArrayVariableFmi2Api) derivativePort.getSharedAsVariable()).items(); + for (int i = 0; i < derivatives.size(); i++) { + PExp val = derivativePortsToShare.get(derivativePort).get(i).getReferenceExp().clone(); + builder.getDynamicScope().add(newAAssignmentStm(derivatives.get(i).getDesignator().clone(), val)); + } + }); + } + }); + }); + } + /** * @param increaseByCount the length of which the outer array should grow * @return a two dimensional non-jagged array for derivatives. diff --git a/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/variables/PortVariableMapImpl.java b/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/variables/PortVariableMapImpl.java index dec8237c8..942d01c9b 100644 --- a/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/variables/PortVariableMapImpl.java +++ b/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/variables/PortVariableMapImpl.java @@ -6,7 +6,7 @@ import java.util.HashMap; import java.util.Map; -public class PortVariableMapImpl extends HashMap, FmiBuilder.Variable> implements FmiBuilder.FmiSimulationInstance.PortVariableMap { +public class PortVariableMapImpl extends HashMap, FmiBuilder.Variable> implements FmiBuilder.FmiSimulationInstance.PortVariableMap { public PortVariableMapImpl(int initialCapacity, float loadFactor) { super(initialCapacity, loadFactor); } @@ -18,7 +18,7 @@ public PortVariableMapImpl(int initialCapacity) { public PortVariableMapImpl() { } - public PortVariableMapImpl(Map, ? extends FmiBuilder.Variable> m) { + public PortVariableMapImpl(Map, ? extends FmiBuilder.Variable> m) { super(m); } } diff --git a/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/variables/VariableCreatorFmi3Api.java b/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/variables/VariableCreatorFmi3Api.java index 154b44e1c..a3efc7179 100644 --- a/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/variables/VariableCreatorFmi3Api.java +++ b/frameworks/fmi2api/src/main/java/org/intocps/maestro/framework/fmi2/api/mabl/variables/VariableCreatorFmi3Api.java @@ -7,9 +7,12 @@ import org.intocps.maestro.ast.node.PStm; import org.intocps.maestro.ast.node.PType; import org.intocps.maestro.fmi.Fmi2ModelDescription; -import org.intocps.maestro.fmi.org.intocps.maestro.fmi.fmi3.Fmi3ModelDescription; +import org.intocps.maestro.fmi.fmi3.Fmi3ModelDescription; import org.intocps.maestro.framework.fmi2.FmuFactory; -import org.intocps.maestro.framework.fmi2.api.mabl.*; +import org.intocps.maestro.framework.fmi2.api.mabl.MablApiBuilder; +import org.intocps.maestro.framework.fmi2.api.mabl.ModelDescriptionContext3; +import org.intocps.maestro.framework.fmi2.api.mabl.PredicateFmi2Api; +import org.intocps.maestro.framework.fmi2.api.mabl.TagNameGenerator; import org.intocps.maestro.framework.fmi2.api.mabl.scoping.DynamicActiveBuilderScope; import org.intocps.maestro.framework.fmi2.api.mabl.scoping.IMablScope; import org.intocps.maestro.framework.fmi2.api.mabl.scoping.ScopeFmi2Api; diff --git a/frameworks/fmi2api/src/test/java/org/intocps/maestro/framework/fmi2/api/mabl/SetPortsTest.java b/frameworks/fmi2api/src/test/java/org/intocps/maestro/framework/fmi2/api/mabl/SetPortsTest.java index 2651f7f30..b82ef8aee 100644 --- a/frameworks/fmi2api/src/test/java/org/intocps/maestro/framework/fmi2/api/mabl/SetPortsTest.java +++ b/frameworks/fmi2api/src/test/java/org/intocps/maestro/framework/fmi2/api/mabl/SetPortsTest.java @@ -1,5 +1,6 @@ package org.intocps.maestro.framework.fmi2.api.mabl; +import org.intocps.maestro.ast.node.PStm; import org.intocps.maestro.fmi.Fmi2ModelDescription; import org.intocps.maestro.framework.fmi2.api.FmiBuilder; import org.intocps.maestro.framework.fmi2.api.mabl.scoping.DynamicActiveBuilderScope; @@ -37,7 +38,7 @@ public void undeclaredPortsTest() throws Exception { controllerInstance.get(controllerInstance.getPorts().stream().map(PortFmi2Api::getName).toArray(String[]::new)); controllerInstance.share(controllerPortMap); - FmiBuilder.Fmi2ComponentVariable.PortValueMap portsToSet = + FmiBuilder.Fmi2ComponentVariable.PortValueMap portsToSet = new PortValueMapImpl(controllerPortMap); // ASSERT diff --git a/maestro-webapi/src/main/java/org/intocps/maestro/webapi/maestro2/Maestro2Broker.java b/maestro-webapi/src/main/java/org/intocps/maestro/webapi/maestro2/Maestro2Broker.java index 9c111ae6e..55ef8500a 100644 --- a/maestro-webapi/src/main/java/org/intocps/maestro/webapi/maestro2/Maestro2Broker.java +++ b/maestro-webapi/src/main/java/org/intocps/maestro/webapi/maestro2/Maestro2Broker.java @@ -55,8 +55,9 @@ public class Maestro2Broker { final File workingDirectory; final ErrorReporter reporter; private final Supplier isStopRequsted; - private final Function>, List> flattenFmuIds = map -> map.entrySet().stream() - .flatMap(entry -> entry.getValue().stream().map(v -> entry.getKey() + "." + v)).collect(Collectors.toList()); + private final Function>, List> flattenFmuIds = + map -> map.entrySet().stream().flatMap(entry -> entry.getValue().stream().map(v -> entry.getKey() + "." + v)) + .collect(Collectors.toList()); private Map.Entry> typeCheckResult; public Maestro2Broker(File workingDirectory, ErrorReporter reporter, Supplier isStopRequsted) { @@ -74,18 +75,20 @@ public Maestro2Broker(File workingDirectory, ErrorReporter reporter, Supplier void buildAndRunMasterModel(Map> livestreamVariables, WebSocketSession socket, T multiModel, SigverSimulateRequestBody body, File csvOutputFile) throws Exception { MasterModel masterModel = ScenarioLoader.load(new ByteArrayInputStream(body.getMasterModel().getBytes())); - Fmi2SimulationEnvironmentConfiguration simulationConfiguration = new Fmi2SimulationEnvironmentConfiguration( - MasterModelMapper.Companion.masterModelConnectionsToMultiModelConnections(masterModel), multiModel.getFmus()); + Fmi2SimulationEnvironmentConfiguration simulationConfiguration = + new Fmi2SimulationEnvironmentConfiguration(MasterModelMapper.Companion.masterModelConnectionsToMultiModelConnections(masterModel), + multiModel.getFmus()); simulationConfiguration.logVariables = multiModel.getLogVariables(); if (simulationConfiguration.logVariables == null) { simulationConfiguration.variablesToLog = new HashMap<>(); } Fmi2SimulationEnvironment simulationEnvironment = Fmi2SimulationEnvironment.of(simulationConfiguration, reporter); - ScenarioConfiguration configuration = new ScenarioConfiguration(simulationEnvironment, masterModel, multiModel.getParameters(), - multiModel.getGlobal_relative_tolerance(), multiModel.getGlobal_absolute_tolerance(), multiModel.getConvergenceAttempts(), - body.getStartTime(), body.getEndTime(), multiModel.getAlgorithm().getStepSize(), Pair.of(Framework.FMI2, simulationConfiguration), - multiModel.isLoggingOn(), multiModel.getLogLevels()); + ScenarioConfiguration configuration = + new ScenarioConfiguration(simulationEnvironment, masterModel, multiModel.getParameters(), multiModel.getGlobal_relative_tolerance(), + multiModel.getGlobal_absolute_tolerance(), multiModel.getConvergenceAttempts(), body.getStartTime(), body.getEndTime(), + multiModel.getAlgorithm().getStepSize(), Pair.of(Framework.FMI2, simulationConfiguration), multiModel.isLoggingOn(), + multiModel.getLogLevels()); String runtimeJsonConfigString = generateSpecification(configuration, null); @@ -101,7 +104,7 @@ public void buildAndRunMasterModel(Map portsToLog = Stream.concat(simulationEnvironment.getConnectedOutputs().stream().map(x -> { ComponentInfo i = simulationEnvironment.getUnitInfo(new LexIdentifier(x.instance.getText(), null), Framework.FMI2); - return String.format("%s.%s.%s", i.fmuIdentifier, x.instance.getText(), x.scalarVariable.getName()); + return String.format("%s.%s.%s", i.fmuIdentifier, x.instance.getText(), x.getName()); }), multiModel.getLogVariables() == null ? Stream.of() : multiModel.getLogVariables().entrySet().stream() .flatMap(entry -> entry.getValue().stream().map(v -> entry.getKey() + "." + v))).collect(Collectors.toList()); @@ -117,8 +120,8 @@ public void buildAndRun(InitializationData initializeRequest, SimulateRequestBod //Initially resolve any FMUs to the local folder in case they are uploaded ImportCmd.resolveFmuPaths(Collections.singletonList(workingDirectory), initializeRequest.getFmus()); - Fmi2SimulationEnvironmentConfiguration simulationConfiguration = new Fmi2SimulationEnvironmentConfiguration( - initializeRequest.getConnections(), initializeRequest.getFmus()); + Fmi2SimulationEnvironmentConfiguration simulationConfiguration = + new Fmi2SimulationEnvironmentConfiguration(initializeRequest.getConnections(), initializeRequest.getFmus()); simulationConfiguration.logVariables = initializeRequest.getLogVariables(); if (simulationConfiguration.logVariables == null) { @@ -162,10 +165,11 @@ public void buildAndRun(InitializationData initializeRequest, SimulateRequestBod config.startTime = body.getStartTime(); config.endTime = body.getEndTime(); - MaBLTemplateConfiguration.MaBLTemplateConfigurationBuilder builder = MaBLTemplateConfiguration.MaBLTemplateConfigurationBuilder.getBuilder() - .setFrameworkConfig(Framework.FMI2, simulationConfiguration).useInitializer(true, new ObjectMapper().writeValueAsString(initialize)) - .setFramework(Framework.FMI2).setLogLevels(removedFMUKeyFromLogLevels).setVisible(initializeRequest.isVisible()) - .setLoggingOn(initializeRequest.isLoggingOn()).setStepAlgorithmConfig(config); + MaBLTemplateConfiguration.MaBLTemplateConfigurationBuilder builder = + MaBLTemplateConfiguration.MaBLTemplateConfigurationBuilder.getBuilder().setFrameworkConfig(Framework.FMI2, simulationConfiguration) + .useInitializer(true, new ObjectMapper().writeValueAsString(initialize)).setFramework(Framework.FMI2) + .setLogLevels(removedFMUKeyFromLogLevels).setVisible(initializeRequest.isVisible()) + .setLoggingOn(initializeRequest.isLoggingOn()).setStepAlgorithmConfig(config); MaBLTemplateConfiguration configuration = builder.build(); @@ -187,8 +191,8 @@ public void buildAndRun(InitializationData initializeRequest, SimulateRequestBod if (filesNotResolved.size() > 0) { errMsg = "Cannot resolve path to spec files: " + nonMablFiles.stream().map(File::getName).reduce("", (prev, cur) -> prev + " " + cur); } else if (nonMablFiles.size() > 0) { - errMsg = "Cannot load spec files: " + nonMablFiles.stream().map(File::getName) - .reduce("", (prev, cur) -> prev + " " + cur) + ". Only mabl files should be " + "included as " + "external specs."; + errMsg = "Cannot load spec files: " + nonMablFiles.stream().map(File::getName).reduce("", (prev, cur) -> prev + " " + cur) + + ". Only mabl files should be " + "included as " + "external specs."; } if (!errMsg.equals("")) { @@ -198,8 +202,8 @@ public void buildAndRun(InitializationData initializeRequest, SimulateRequestBod mabl.parse(initializeRequest.getExternalSpecs()); } // If fault injection is configured then the faultinject.mabl file should be included as an external spec. - if (initializeRequest.faultInjectConfigurationPath != null && !initializeRequest.faultInjectConfigurationPath.equals( - "") && !didLocateFaultInjectionFile.get()) { + if (initializeRequest.faultInjectConfigurationPath != null && !initializeRequest.faultInjectConfigurationPath.equals("") && + !didLocateFaultInjectionFile.get()) { throw new Exception("Remember to include FaultInject.mabl as an external spec"); } String runtimeJsonConfigString = generateSpecification(configuration, parameters); @@ -215,7 +219,7 @@ public void buildAndRun(InitializationData initializeRequest, SimulateRequestBod List connectedOutputs = simulationEnvironment.getConnectedOutputs().stream().map(x -> { ComponentInfo i = simulationEnvironment.getUnitInfo(new LexIdentifier(x.instance.getText(), null), Framework.FMI2); - return String.format("%s.%s.%s", i.fmuIdentifier, x.instance.getText(), x.scalarVariable.getName()); + return String.format("%s.%s.%s", i.fmuIdentifier, x.instance.getText(), x.getName()); }).collect(Collectors.toList()); diff --git a/maestro/src/main/java/org/intocps/maestro/MablSpecificationGenerator.java b/maestro/src/main/java/org/intocps/maestro/MablSpecificationGenerator.java index 84970e79b..91562d818 100644 --- a/maestro/src/main/java/org/intocps/maestro/MablSpecificationGenerator.java +++ b/maestro/src/main/java/org/intocps/maestro/MablSpecificationGenerator.java @@ -66,7 +66,7 @@ public static Collection loadExpansionPlugins(Framework //load recursive plugin dependencies List pluginsToUnfoldWithDependencies = Stream.concat(pluginsToUnfold.stream(), - pluginsToUnfold.stream().map(p -> collectPluginDependencies(plugins, p, new Vector<>()).stream()).flatMap(Function.identity())) + pluginsToUnfold.stream().map(p -> collectPluginDependencies(plugins, p, new Vector<>()).stream()).flatMap(Function.identity())) .distinct().collect(Collectors.toList()); @@ -95,7 +95,7 @@ static Collection collectPluginDependencies(Collection< } return Stream.concat(requiredPlugins.stream(), - requiredPlugins.stream().map(p -> collectPluginDependencies(plugins, p, checked).stream()).flatMap(Function.identity())) + requiredPlugins.stream().map(p -> collectPluginDependencies(plugins, p, checked).stream()).flatMap(Function.identity())) .collect(Collectors.toList()); } @@ -203,8 +203,7 @@ private ARootDocument expandExternals(List importedDocumentList, .collect(Collectors.toList())); }); - for (Map.Entry>> callReplacement : replaceWith - .entrySet()) { + for (Map.Entry>> callReplacement : replaceWith.entrySet()) { ACallExp call = callReplacement.getKey(); AFunctionDeclaration replacement = callReplacement.getValue().get().getValue(); IMaestroExpansionPlugin replacementPlugin = @@ -255,8 +254,8 @@ private void replaceCall(ACallExp callToBeReplaced, AFunctionDeclaration replace BuilderHelper builderHelper = new BuilderHelper(callToBeReplaced, typesMap, simulationEnvironment); builderHelper.getBuilder().resetDirty(); - IMaestroExpansionPlugin.RuntimeConfigAddition runtimeConfigProduced = replacementPlugin - .expandWithRuntimeAddition(replacement, builderHelper.getBuilder(), builderHelper.getArgumentVariables(), config, + IMaestroExpansionPlugin.RuntimeConfigAddition runtimeConfigProduced = + replacementPlugin.expandWithRuntimeAddition(replacement, builderHelper.getBuilder(), builderHelper.getArgumentVariables(), config, simulationEnvironment, reporter); if (builderHelper.getBuilder().isDirty()) { @@ -273,19 +272,19 @@ private void replaceCall(ACallExp callToBeReplaced, AFunctionDeclaration replace //2: see fallback to the raw interface { if (unfoled == null) { - unfoled = replacementPlugin - .expandWithRuntimeAddition(replacement, callToBeReplaced.getArgs(), config, simulationEnvironment, reporter); + unfoled = replacementPlugin.expandWithRuntimeAddition(replacement, callToBeReplaced.getArgs(), config, simulationEnvironment, + reporter); } } } catch (ExpandException e) { - logger.error("Internal error in plug-in '{}' at {}. Message: {}", replacementPlugin.getName(), - callToBeReplaced.getMethodName().toString(), e.getMessage()); + logger.error(String.format("Internal error in plug-in '%s' at %s. Message: %s", replacementPlugin.getName(), + callToBeReplaced.getMethodName().toString(), e.getMessage()), e); reporter.report(999, String.format("Internal error in plug-in '%s' at %s. Message: %s", replacementPlugin.getName(), callToBeReplaced.getMethodName().toString(), e.getMessage()), callToBeReplaced.getMethodName().getSymbol()); } catch (Exception e) { - logger.error("Internal error while processing builder for in plug-in '{}' at {}. Message: {}", replacementPlugin.getName(), - callToBeReplaced.getMethodName().toString(), e.getMessage()); + logger.error(String.format("Internal error while processing builder for in plug-in '%s' at %s. Message: %s", replacementPlugin.getName(), + callToBeReplaced.getMethodName().toString(), e.getMessage()), e); reporter.report(998, String.format("Internal error in plug-in '%s' at %s. Message: %s", replacementPlugin.getName(), callToBeReplaced.getMethodName().toString(), e.getMessage()), callToBeReplaced.getMethodName().getSymbol()); } @@ -452,8 +451,9 @@ private void handleInstanceMappingStatements(ASimulationSpecificationCompilation if (simulationModule.getBody() instanceof SBlockStm) { Optional> instanceMappings = NodeCollector.collect(simulationModule.getBody(), AInstanceMappingStm.class); if (instanceMappings.isPresent()) { - instanceMappings.get().forEach(x -> ((Fmi2SimulationEnvironment) this.simulationEnvironment) - .setLexNameToInstanceNameMapping(x.getIdentifier().getText(), x.getName())); + instanceMappings.get().forEach( + x -> ((Fmi2SimulationEnvironment) this.simulationEnvironment).setLexNameToInstanceNameMapping(x.getIdentifier().getText(), + x.getName())); } } } diff --git a/maestro/src/main/java/org/intocps/maestro/template/MaBLTemplateGenerator.java b/maestro/src/main/java/org/intocps/maestro/template/MaBLTemplateGenerator.java index 842dca19f..1f08c2eb6 100644 --- a/maestro/src/main/java/org/intocps/maestro/template/MaBLTemplateGenerator.java +++ b/maestro/src/main/java/org/intocps/maestro/template/MaBLTemplateGenerator.java @@ -11,13 +11,10 @@ import org.intocps.maestro.core.dto.IAlgorithmConfig; import org.intocps.maestro.fmi.Fmi2ModelDescription; import org.intocps.maestro.fmi.ModelDescription; -import org.intocps.maestro.fmi.org.intocps.maestro.fmi.fmi3.Fmi3ModelDescription; +import org.intocps.maestro.fmi.fmi3.Fmi3ModelDescription; import org.intocps.maestro.framework.core.FrameworkUnitInfo; import org.intocps.maestro.framework.core.IRelation; -import org.intocps.maestro.framework.fmi2.ComponentInfo; -import org.intocps.maestro.framework.fmi2.FaultInjectWithLexName; -import org.intocps.maestro.framework.fmi2.Fmi2SimulationEnvironment; -import org.intocps.maestro.framework.fmi2.InstanceInfo; +import org.intocps.maestro.framework.fmi2.*; import org.intocps.maestro.plugin.IMaestroPlugin; import org.intocps.maestro.plugin.JacobianStepConfig; import org.slf4j.Logger; @@ -520,15 +517,12 @@ private static void checkConnectionUnits(Fmi2SimulationEnvironment unitRelationS for (Map.Entry instance : unitRelationShip.getInstances()) { for (Fmi2SimulationEnvironment.Relation relation : unitRelationShip.getRelations(instance.getKey())) { if (relation.getOrigin() == IRelation.InternalOrExternal.External && relation.getDirection() == IRelation.Direction.OutputToInput) { - for (Map.Entry target : relation.getTargets().entrySet()) { + for (Map.Entry target : relation.getTargets().entrySet()) { - if (!target.getValue().getScalarVariable().getScalarVariable().getType() - .isAssignableFrom(relation.getSource().getScalarVariable().getScalarVariable().getType(), false)) { + if (!target.getValue().getType().isAssignableFrom(relation.getSource().getType().get(), false)) { sbUnitError.append(String.format("Invalid unit for connection: %s.%s [%s] -> %s.%s [%s]", instance.getKey(), - relation.getSource().getScalarVariable().getScalarVariable().name, - relation.getSource().getScalarVariable().getScalarVariable().getType().unit.getName(), target.getKey().getText(), - target.getValue().getScalarVariable().getScalarVariable().name, - target.getValue().getScalarVariable().getScalarVariable().getType().unit.getName())); + relation.getSource().getName(), relation.getSource().getType2().get().unit.getName(), target.getKey().getText(), + target.getValue().getName(), target.getValue().getType2().get().unit.getName())); } } } diff --git a/maestro/src/test/java/org/intocps/maestro/BuilderFmi3Test.java b/maestro/src/test/java/org/intocps/maestro/BuilderFmi3Test.java index 5df7cc699..95561bc32 100644 --- a/maestro/src/test/java/org/intocps/maestro/BuilderFmi3Test.java +++ b/maestro/src/test/java/org/intocps/maestro/BuilderFmi3Test.java @@ -10,7 +10,7 @@ import org.intocps.maestro.core.messages.ErrorReporter; import org.intocps.maestro.core.messages.IErrorReporter; import org.intocps.maestro.fmi.Fmi2ModelDescription; -import org.intocps.maestro.fmi.org.intocps.maestro.fmi.fmi3.Fmi3ModelDescription; +import org.intocps.maestro.fmi.fmi3.Fmi3ModelDescription; import org.intocps.maestro.fmi3.Fmi3ModuleReferenceFmusTest; import org.intocps.maestro.framework.fmi2.Fmi2SimulationEnvironment; import org.intocps.maestro.framework.fmi2.Fmi2SimulationEnvironmentConfiguration; @@ -31,7 +31,6 @@ import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; -import java.lang.reflect.Array; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.Collections; @@ -79,7 +78,7 @@ public void wt() throws Exception { URI ballUri = new File("target/Fmi3ModuleReferenceFmusTest/cache/BouncingBall.fmu").getAbsoluteFile().toURI(); Fmu3 ball = new Fmu3(new File(ballUri)); - ArrayVariableFmi2Api requiredIntermediateVariables = builder.getDynamicScope().store("requiredIntermediateVariables", new Long[] {1L}); + ArrayVariableFmi2Api requiredIntermediateVariables = builder.getDynamicScope().store("requiredIntermediateVariables", new Long[]{1L}); Fmi3ModelDescription md3Ball = new Fmi3ModelDescription(ball.getModelDescription()); @@ -89,25 +88,20 @@ public void wt() throws Exception { boolean loggingOn = true; boolean eventModeUsed = true; boolean earlyReturnAllowed = true; - InstanceVariableFmi3Api ballInstance = ballFmu.instantiate("ballInstance", visible, loggingOn, eventModeUsed, earlyReturnAllowed, - requiredIntermediateVariables); + InstanceVariableFmi3Api ballInstance = + ballFmu.instantiate("ballInstance", visible, loggingOn, eventModeUsed, earlyReturnAllowed, requiredIntermediateVariables); - ballInstance.enterInitializationMode(false, 0.0, 0.0, true,10.0); + ballInstance.enterInitializationMode(false, 0.0, 0.0, true, 10.0); ballInstance.exitInitializationMode(); -// ArrayVariableFmi2Api svs = builder.getDynamicScope().store("svs", new Long[] {5L, 6L}); -// ArrayVariableFmi2Api values_r = builder.getDynamicScope().store("values_r", new Double[] {-9.81, 0.7}); + // ArrayVariableFmi2Api svs = builder.getDynamicScope().store("svs", new Long[] {5L, 6L}); + // ArrayVariableFmi2Api values_r = builder.getDynamicScope().store("values_r", new Double[] {-9.81, 0.7}); ballInstance.terminate(); -// ballInstance.freeInstance(); - - - - - + // ballInstance.freeInstance(); // Create the two FMUs diff --git a/maestro/src/test/resources/cli-test/config-fmi3.json b/maestro/src/test/resources/cli-test/config-fmi3.json index 594755e72..f3891dc6b 100644 --- a/maestro/src/test/resources/cli-test/config-fmi3.json +++ b/maestro/src/test/resources/cli-test/config-fmi3.json @@ -4,7 +4,7 @@ "{x2}": "src/test/resources/singlewatertank-20sim.fmu" }, "connections": { - "{x1}.controller.valve": [ + "{x1}.controller.h": [ "{x2}.tank.valvecontrol" ], "{x2}.tank.level": [ diff --git a/maestro/src/test/resources/fmi3/basic/basic1/fmi3_basic.mabl b/maestro/src/test/resources/fmi3/basic/basic1/fmi3_basic.mabl index cd1738d60..0a074f590 100644 --- a/maestro/src/test/resources/fmi3/basic/basic1/fmi3_basic.mabl +++ b/maestro/src/test/resources/fmi3/basic/basic1/fmi3_basic.mabl @@ -27,7 +27,7 @@ import FMI3; float f1 = 1; byte b1 = 2; byte valu8[3]={100,0,0}; - instance.setUInt8(sv,valu8); + instance.setUInt8(sv,3,valu8,3); x1.freeInstance(instance); diff --git a/maestro/src/test/resources/fmi3/reference/bounchingball/fmi3_bb.mabl b/maestro/src/test/resources/fmi3/reference/bounchingball/fmi3_bb.mabl index 466015039..5a0701018 100644 --- a/maestro/src/test/resources/fmi3/reference/bounchingball/fmi3_bb.mabl +++ b/maestro/src/test/resources/fmi3/reference/bounchingball/fmi3_bb.mabl @@ -34,7 +34,7 @@ import Logger; uint svs[2]={sv_par_g, sv_par_e}; float values_r[2]={-9.81,0.7}; - res=instance.setFloat32(svs,values_r); + res=instance.setFloat32(svs,2,values_r,2); logger.log(3,"setFloat32 status %d",res); res=instance.enterInitializationMode(false, 0.0, 0.0, true,10.0); diff --git a/plugins/fixedstep/src/main/java/org/intocps/maestro/plugin/DataExchangeHandler.java b/plugins/fixedstep/src/main/java/org/intocps/maestro/plugin/DataExchangeHandler.java index 73141d9c7..b5fd7dac0 100644 --- a/plugins/fixedstep/src/main/java/org/intocps/maestro/plugin/DataExchangeHandler.java +++ b/plugins/fixedstep/src/main/java/org/intocps/maestro/plugin/DataExchangeHandler.java @@ -33,11 +33,11 @@ public DataExchangeHandler(Set relations, Fm // outputs contains both outputs based on relations and outputs based on additional variables to log //FIXME fmi3 is excluded - outputs = outputRelations.stream().map(r -> r.getSource().scalarVariable.instance).distinct().collect(Collectors.toMap(Function.identity(), - s -> outputRelations.stream().filter(r -> r.getSource().scalarVariable.instance.equals(s)).flatMap(r -> { - List outputs_ = - env.getVariablesToLog(s.getText()).stream().map(x -> x.getScalarVariable(Fmi2ModelDescription.ScalarVariable.class)) - .filter(Objects::nonNull).collect(Collectors.toList()); + outputs = outputRelations.stream().map(r -> r.getSource().getInstance()).distinct().collect( + Collectors.toMap(Function.identity(), s -> outputRelations.stream().filter(r -> r.getSource().getInstance().equals(s)).flatMap(r -> { + List outputs_ = env.getVariablesToLog(s.getText()).stream() + .map(x -> (Fmi2ModelDescription.ScalarVariable) x.getScalarVariable(Fmi2ModelDescription.ScalarVariable.class)) + .filter(Objects::nonNull).collect(Collectors.toList()); //outputs_.add(r.getSource().scalarVariable.getScalarVariable()); return outputs_.stream(); }).distinct().collect(Collectors.groupingBy(sv -> sv.getType().type)))); @@ -47,9 +47,10 @@ public DataExchangeHandler(Set relations, Fm inputRelations = relations.stream().filter(r -> r.getDirection() == Fmi2SimulationEnvironment.Relation.Direction.InputToOutput) .collect(Collectors.toSet()); - inputs = inputRelations.stream().map(r -> r.getSource().scalarVariable.instance).distinct().collect(Collectors.toMap(Function.identity(), - s -> inputRelations.stream().filter(r -> r.getSource().scalarVariable.instance.equals(s)) - .map(r -> r.getSource().scalarVariable.getScalarVariable()).collect(Collectors.groupingBy(sv -> sv.getType().type)))); + inputs = inputRelations.stream().map(r -> r.getSource().getInstance()).distinct().collect(Collectors.toMap(Function.identity(), + s -> inputRelations.stream().filter(r -> r.getSource().getInstance().equals(s)) + .map(r -> (Fmi2ModelDescription.ScalarVariable) r.getSource().getScalarVariable(Fmi2ModelDescription.ScalarVariable.class)) + .collect(Collectors.groupingBy(sv -> sv.getType().type)))); } @@ -189,32 +190,35 @@ public List setAll() { public List exchangeData() { Consumer> exchangeData = (list) -> inputRelations.forEach(r -> { - int toIndex = - inputs.get(r.getSource().scalarVariable.instance).get(r.getSource().scalarVariable.getScalarVariable().getType().type).stream() - .map(Fmi2ModelDescription.ScalarVariable::getName).collect(Collectors.toList()) - .indexOf(r.getSource().scalarVariable.scalarVariable.getName()); - AArrayStateDesignator to = newAArayStateDesignator(newAIdentifierStateDesignator( - getBufferName(r.getSource().scalarVariable.instance, r.getSource().scalarVariable.getScalarVariable().getType().type, - UsageType.In)), newAIntLiteralExp(toIndex)); + Fmi2ModelDescription.Types sourceType = r.getSource().getType2().get().type; + + int toIndex = inputs.get(r.getSource().getInstance()).get(sourceType).stream().map(Fmi2ModelDescription.ScalarVariable::getName) + .collect(Collectors.toList()).indexOf(r.getSource().getName()); + + AArrayStateDesignator to = + newAArayStateDesignator(newAIdentifierStateDesignator(getBufferName(r.getSource().getInstance(), sourceType, UsageType.In)), + newAIntLiteralExp(toIndex)); //the relation should be a one to one relation so just take the first one - RelationVariable fromVar = r.getTargets().values().iterator().next().scalarVariable; - PExp from = newAArrayIndexExp(newAIdentifierExp(getBufferName(fromVar.instance, fromVar.getScalarVariable().type.type, UsageType.Out)), - Collections.singletonList(newAIntLiteralExp(outputs.get(fromVar.instance).get(fromVar.getScalarVariable().getType().type).stream() - .map(Fmi2ModelDescription.ScalarVariable::getName).collect(Collectors.toList()) - .indexOf(fromVar.scalarVariable.getName())))); + RelationVariable fromVar = r.getTargets().values().iterator().next(); + + Fmi2ModelDescription.Types fromVarType = fromVar.getType2().get().type; + + PExp from = newAArrayIndexExp(newAIdentifierExp(getBufferName(fromVar.instance, fromVar.getType2().get().type, UsageType.Out)), + Collections.singletonList(newAIntLiteralExp(outputs.get(fromVar.instance).get(fromVar.getType2().get().type).stream() + .map(Fmi2ModelDescription.ScalarVariable::getName).collect(Collectors.toList()).indexOf(fromVar.getName())))); - if (r.getSource().scalarVariable.getScalarVariable().getType().type != fromVar.getScalarVariable().getType().type) { + if (sourceType != fromVar.getType2().get().type) { //ok the types are not matching, lets use a converter - AArrayIndexExp toAsExp = newAArrayIndexExp(newAIdentifierExp( - getBufferName(r.getSource().scalarVariable.instance, r.getSource().scalarVariable.getScalarVariable().getType().type, - UsageType.In)), Arrays.asList(newAIntLiteralExp(toIndex))); + AArrayIndexExp toAsExp = newAArrayIndexExp( + newAIdentifierExp(getBufferName(r.getSource().getInstance(), r.getSource().getType2().get().type, UsageType.In)), + Arrays.asList(newAIntLiteralExp(toIndex))); - list.add(newExpressionStm(newACallExp(newExpandToken(), newAIdentifierExp("TypeConverter"), newAIdentifier( - "convert" + fromVar.getScalarVariable().getType().type + "2" + - r.getSource().scalarVariable.getScalarVariable().getType().type), Arrays.asList(from, toAsExp)))); + list.add(newExpressionStm(newACallExp(newExpandToken(), newAIdentifierExp("TypeConverter"), + newAIdentifier("convert" + fromVar.getType2().get().type + "2" + r.getSource().getType2().get().type), + Arrays.asList(from, toAsExp)))); } else { diff --git a/plugins/fixedstep/src/main/java/org/intocps/maestro/plugin/DataWriterHandler.java b/plugins/fixedstep/src/main/java/org/intocps/maestro/plugin/DataWriterHandler.java index 796c7bebd..9986ab4ec 100644 --- a/plugins/fixedstep/src/main/java/org/intocps/maestro/plugin/DataWriterHandler.java +++ b/plugins/fixedstep/src/main/java/org/intocps/maestro/plugin/DataWriterHandler.java @@ -4,6 +4,8 @@ import org.intocps.maestro.ast.MableAstFactory; import org.intocps.maestro.ast.node.PExp; import org.intocps.maestro.ast.node.PStm; +import org.intocps.maestro.ast.node.PType; +import org.intocps.maestro.ast.node.SPrimitiveType; import org.intocps.maestro.core.Framework; import org.intocps.maestro.fmi.Fmi2ModelDescription; import org.intocps.maestro.framework.core.FrameworkUnitInfo; @@ -34,11 +36,11 @@ public List allocate(Set inputRelation List statements = new Vector<>(); List variableNames = new Vector<>(); - Function getLogName = k -> k.getInstance().getText() + "." + k.getName(); + Function getLogName = k -> k.getInstance().getText() + "." + k.getName(); csvFields = inputRelations.stream().map(r -> r.getTargets().values().stream().findFirst()).filter(Optional::isPresent).map(Optional::get) .flatMap(h -> { - List outputs_ = env.getVariablesToLog(h.scalarVariable.instance.getText()); + List outputs_ = env.getVariablesToLog(h.getInstance().getText()); //outputs_.add(h.scalarVariable); return outputs_.stream(); //return h.scalarVariable; @@ -46,17 +48,14 @@ public List allocate(Set inputRelation //the relation should be a one to one relation so just take the first one - org.intocps.maestro.framework.core.RelationVariable fromVar = r; - - if (fromVar instanceof RelationVariable) { - Fmi2ModelDescription.Types fromType = ((RelationVariable) fromVar).getScalarVariable().type.type; - PExp from = arrayGet(getBufferName(fromVar.getInstance(), fromType, DataExchangeHandler.UsageType.Out), - outputs.get(fromVar.getInstance()).get(fromType).stream().map(Fmi2ModelDescription.ScalarVariable::getName) - .collect(Collectors.toList()).indexOf(fromVar.getName())); - return from; - } else { - throw new RuntimeException("Not a fmi 2 variable"); - } + RelationVariable fromVar = r; + + + PType fromType = fromVar.getType().getLexType(); + PExp from = arrayGet(getBufferName(fromVar.getInstance(), (SPrimitiveType) fromType, DataExchangeHandler.UsageType.Out), + outputs.get(fromVar.getInstance()).get(fromVar.getType2().get().type).stream() + .map(Fmi2ModelDescription.ScalarVariable::getName).collect(Collectors.toList()).indexOf(fromVar.getName())); + return from; }, (oldValue, newValue) -> oldValue, LinkedHashMap::new)); diff --git a/plugins/fixedstep/src/main/java/org/intocps/maestro/plugin/DerivativesHandler.java b/plugins/fixedstep/src/main/java/org/intocps/maestro/plugin/DerivativesHandler.java index 6b2a8daf3..020e99dee 100644 --- a/plugins/fixedstep/src/main/java/org/intocps/maestro/plugin/DerivativesHandler.java +++ b/plugins/fixedstep/src/main/java/org/intocps/maestro/plugin/DerivativesHandler.java @@ -30,9 +30,9 @@ class DerivativesHandler { final static Logger logger = LoggerFactory.getLogger(DerivativesHandler.class); - final BiPredicate canInterpolateInputsFilter = (env, v) -> { + final BiPredicate canInterpolateInputsFilter = (env, v) -> { try { - return ((ComponentInfo) env.getUnitInfo(v.scalarVariable.instance, Framework.FMI2)).modelDescription.getCanInterpolateInputs(); + return ((ComponentInfo) env.getUnitInfo(v.getInstance(), Framework.FMI2)).modelDescription.getCanInterpolateInputs(); } catch (XPathExpressionException e) { return false; } @@ -50,7 +50,7 @@ class DerivativesHandler { Map derivativesGetInfo = new HashMap<>(); private boolean allocated = false; private boolean requireArrayUtilUnload = false; - private Map>, LinkedHashMap>> + private Map>, LinkedHashMap>> resolvedInputData; public List allocateMemory(List componentNames, Set inputRelations, @@ -58,20 +58,19 @@ public List allocateMemory(List componentNames, Set> tmp = - inputRelations.stream().filter(r -> canInterpolateInputsFilter.test(env, r.getSource())) - .map(Fmi2SimulationEnvironment.Relation::getTargets).collect(Collectors.toSet()); + Set> tmp = inputRelations.stream().filter(r -> canInterpolateInputsFilter.test(env, r.getSource())) + .map(Fmi2SimulationEnvironment.Relation::getTargets).collect(Collectors.toSet()); - Map> vars = new HashMap<>(); - for (Map map : tmp) { - for (Map.Entry entry : map.entrySet()) { + Map> vars = new HashMap<>(); + for (Map map : tmp) { + for (Map.Entry entry : map.entrySet()) { vars.computeIfAbsent(entry.getKey(), key -> new Vector<>()).add(entry.getValue()); } } - for (Map.Entry> entry : vars.entrySet()) { - entry.getValue().sort(Comparator.comparing(v -> v.getScalarVariable().getScalarVariable().valueReference)); + for (Map.Entry> entry : vars.entrySet()) { + entry.getValue().sort(Comparator.comparing(v -> v.getValueReference())); } @@ -92,7 +91,7 @@ public List allocateMemory(List componentNames, Set allocateMemory(List componentNames, Set IntStream.range(1, order + 1) - .mapToObj(o -> newAIntLiteralExp((int) v.getScalarVariable().getScalarVariable().valueReference))) + statements.add(newVariable(varSelectName, newUIntType(), f.getValue().stream() + .flatMap(v -> IntStream.range(1, order + 1).mapToObj(o -> newAIntLiteralExp((int) v.getValueReference()))) .collect(Collectors.toList()))); varDerInfo.valueSelectArrayId = varSelectName; derivativesGetInfo.put(id, varDerInfo); @@ -130,20 +129,18 @@ public List allocateMemory(List componentNames, Set allocateForInput(Set inputRelations, Fmi2SimulationEnvironment env) { resolvedInputData = inputRelations.stream().filter(r -> canInterpolateInputsFilter.test(env, r.getSource())) - .collect(Collectors.groupingBy(s -> s.getSource().getScalarVariable().instance)).entrySet().stream().collect(Collectors - .toMap(Function.identity(), mapped -> mapped.getValue().stream() - .sorted(Comparator.comparing(map -> map.getSource().getScalarVariable().getScalarVariable().valueReference)) + .collect(Collectors.groupingBy(s -> s.getSource().getInstance())).entrySet().stream().collect(Collectors.toMap(Function.identity(), + mapped -> mapped.getValue().stream().sorted(Comparator.comparing(map -> map.getSource().getValueReference())) .collect(Collectors.toMap(Fmi2SimulationEnvironment.Relation::getSource, map -> { //the relation should be a one to one relation so just take the first one - Fmi2SimulationEnvironment.Variable next = map.getTargets().values().iterator().next(); - RelationVariable fromVar = next.scalarVariable; + RelationVariable next = map.getTargets().values().iterator().next(); + RelationVariable fromVar = next; GetDerivativesInfo fromVarDerivativeInfo = derivativesGetInfo.get(fromVar.instance); if (fromVarDerivativeInfo != null) { - logger.trace("Derivative mapping {}.{} to {}.{}", fromVar.instance, fromVar.scalarVariable.name, - map.getSource().getScalarVariable().instance, - map.getSource().getScalarVariable().scalarVariable.name); + logger.trace("Derivative mapping {}.{} to {}.{}", fromVar.instance, fromVar.getName(), + map.getSource().getInstance(), map.getSource().getName()); } return Map.entry(next, fromVarDerivativeInfo); @@ -161,12 +158,11 @@ private List allocateForInput(Set inpu List allocationStatements = Stream.concat(Stream.of(newVariable("der_input_buffer", newARealNumericPrimitiveType(), size)), resolvedInputData.entrySet().stream().flatMap(map -> { - LinkedHashMap> resolved = - map.getValue(); + LinkedHashMap> resolved = map.getValue(); List inputSelectIndices = resolved.entrySet().stream().flatMap( - m -> IntStream.range(1, m.getValue().getValue().varMaxOrder + 1) - .mapToObj(i -> Long.valueOf(m.getKey().getScalarVariable().scalarVariable.valueReference).intValue())) + m -> IntStream.range(1, m.getValue().getValue().varMaxOrder + 1) + .mapToObj(i -> Long.valueOf(m.getKey().getValueReference()).intValue())) .collect(Collectors.toList()); List inputOrders = resolved.entrySet().stream().flatMap(m -> IntStream.range(1, m.getValue().getValue().varMaxOrder + 1).mapToObj(i -> i)) @@ -175,7 +171,7 @@ private List allocateForInput(Set inpu LexIdentifier name = map.getKey().getKey(); return Stream.of(newVariable("der_input_select_" + name.getText(), newAIntNumericPrimitiveType(), - inputSelectIndices.stream().map(MableAstFactory::newAIntLiteralExp).collect(Collectors.toList())), + inputSelectIndices.stream().map(MableAstFactory::newAIntLiteralExp).collect(Collectors.toList())), newVariable("der_input_order" + "_" + name.getText(), newAIntNumericPrimitiveType(), inputOrders.stream().map(MableAstFactory::newAIntLiteralExp).collect(Collectors.toList()))); @@ -282,7 +278,7 @@ class GetDerivativesInfo { String orderArrayId; String valueSelectArrayId; PExp valueDestIdentifier; - Map varStartIndex = new HashMap<>(); + Map varStartIndex = new HashMap<>(); Integer varMaxOrder; } } diff --git a/plugins/initializer/src/main/java/org/intocps/maestro/plugin/initializer/PhasePredicates.java b/plugins/initializer/src/main/java/org/intocps/maestro/plugin/initializer/PhasePredicates.java index f7e60d47f..3dc77e1ed 100644 --- a/plugins/initializer/src/main/java/org/intocps/maestro/plugin/initializer/PhasePredicates.java +++ b/plugins/initializer/src/main/java/org/intocps/maestro/plugin/initializer/PhasePredicates.java @@ -1,6 +1,7 @@ package org.intocps.maestro.plugin.initializer; import org.intocps.maestro.fmi.Fmi2ModelDescription; +import org.intocps.maestro.fmi.fmi3.Fmi3ModelDescription; import static org.intocps.maestro.fmi.Fmi2ModelDescription.*; @@ -13,16 +14,12 @@ public static Predicate iniPhase() { (o.causality == Causality.Parameter && o.variability == Variability.Tunable); } - public static Predicate iniePhase() { - return o -> o.initial == Initial.Exact && o.variability != Variability.Constant; - } public static Predicate inPhase() { return o -> (o.causality == Causality.Input && o.initial == Initial.Calculated || o.causality == Causality.Parameter && o.variability == Variability.Tunable); } - public static Predicate initPhase() { - return o -> o.causality == Causality.Output; - } + + } \ No newline at end of file diff --git a/plugins/initializer/src/main/java/org/intocps/maestro/plugin/initializer/PhasePredicates3.java b/plugins/initializer/src/main/java/org/intocps/maestro/plugin/initializer/PhasePredicates3.java new file mode 100644 index 000000000..25ecea2e5 --- /dev/null +++ b/plugins/initializer/src/main/java/org/intocps/maestro/plugin/initializer/PhasePredicates3.java @@ -0,0 +1,23 @@ +package org.intocps.maestro.plugin.initializer; + + +import org.intocps.maestro.fmi.ModelDescription; +import org.intocps.maestro.fmi.fmi3.Fmi3Causality; +import org.intocps.maestro.fmi.fmi3.Fmi3Variable; + +import java.util.function.Predicate; + +public class PhasePredicates3 { + + public static Predicate iniPhase() { + return o -> ((o.getInitial() == ModelDescription.Initial.Exact || o.getInitial() == ModelDescription.Initial.Approx) && + o.getVariability() != ModelDescription.Variability.Constant) || + (o.getCausality() == Fmi3Causality.Parameter && o.getVariability() == ModelDescription.Variability.Tunable); + } + + + public static Predicate inPhase() { + return o -> (o.getCausality() == Fmi3Causality.Input && o.getInitial() == ModelDescription.Initial.Calculated || + o.getCausality() == Fmi3Causality.Parameter && o.getVariability() == ModelDescription.Variability.Tunable); + } +} diff --git a/plugins/initializer/src/main/java/org/intocps/maestro/plugin/initializer/RelationsPredicates.java b/plugins/initializer/src/main/java/org/intocps/maestro/plugin/initializer/RelationsPredicates.java index 4568ba9c1..4fa44aae5 100644 --- a/plugins/initializer/src/main/java/org/intocps/maestro/plugin/initializer/RelationsPredicates.java +++ b/plugins/initializer/src/main/java/org/intocps/maestro/plugin/initializer/RelationsPredicates.java @@ -19,11 +19,11 @@ public static Predicate inputToOutput() { } public static Predicate inputSource() { - return o -> (o.getSource().scalarVariable.getScalarVariable().causality == Fmi2ModelDescription.Causality.Input); + return o -> (o.getSource().has( Fmi2ModelDescription.Causality.Input)); } public static Predicate outputSource() { - return o -> (o.getSource().scalarVariable.getScalarVariable().causality == Fmi2ModelDescription.Causality.Output); + return o -> (o.getSource().has( Fmi2ModelDescription.Causality.Output)); } } \ No newline at end of file diff --git a/plugins/initializer/src/main/java/org/intocps/maestro/plugin/initializer/TopologicalPlugin.java b/plugins/initializer/src/main/java/org/intocps/maestro/plugin/initializer/TopologicalPlugin.java index 6e6f430dd..966246505 100644 --- a/plugins/initializer/src/main/java/org/intocps/maestro/plugin/initializer/TopologicalPlugin.java +++ b/plugins/initializer/src/main/java/org/intocps/maestro/plugin/initializer/TopologicalPlugin.java @@ -15,7 +15,7 @@ public class TopologicalPlugin { //This method find the right instantiation order using the topological sort plugin. The plugin is in scala so some mapping between java and // scala is needed - public List findInstantiationOrder(Set relations, + public List findInstantiationOrder(Set relations, Set filterTargets) throws ExpandException { TarjanGraph graphSolver = getTarjanGraph(relations, filterTargets); @@ -25,27 +25,27 @@ public List findInstantiationOrder(Set) JavaConverters + return (List) JavaConverters .seqAsJavaListConverter(((AcyclicDependencyResult) topologicalOrderToInstantiate).totalOrder()).asJava(); } - public List> findInstantiationOrderStrongComponents(Set relations, + public List> findInstantiationOrderStrongComponents(Set relations, Set filterTargets) { TarjanGraph graphSolver = getTarjanGraph(relations, filterTargets); var topologicalOrderToInstantiate = graphSolver.topologicalSCC(); - Map javaMap = - (Map) JavaConverters.mapAsJavaMapConverter(topologicalOrderToInstantiate).asJava(); + Map javaMap = + (Map) JavaConverters.mapAsJavaMapConverter(topologicalOrderToInstantiate).asJava(); return groupSCC(javaMap); } - private List> groupSCC(Map javaMap) { - List> sccs = new Vector<>(); + private List> groupSCC(Map javaMap) { + List> sccs = new Vector<>(); var list = javaMap.entrySet().stream().collect(Collectors.groupingBy(o -> o.getValue())); javaMap.values().stream().sorted().forEach(scc -> { - HashSet variablesSet = new HashSet<>(); + HashSet variablesSet = new HashSet<>(); list.get(scc).forEach(v -> variablesSet.add(v.getKey())); sccs.add(variablesSet); }); @@ -62,9 +62,9 @@ private TarjanGraph getTarjanGraph(Set relat .outputSource().and(o -> externalRelations.stream().anyMatch(i -> o.getSource() == i.getSource())))) .collect(Collectors.toList()); - var edges = new Vector>(); + var edges = new Vector>(); externalRelations.forEach(o -> o.getTargets().values().forEach(e -> { - if (filterTargets != null && filterTargets.contains(e.getScalarVariable().getInstance())) { return; } + if (filterTargets != null && filterTargets.contains(e.getInstance())) { return; } edges.add(new Edge11(o.getSource(), e, o.getOrigin())); })); internalRelations.forEach(o -> o.getTargets().values().forEach(e -> { diff --git a/plugins/initializer/src/main/java/org/intocps/maestro/plugin/initializer/spec/StatementGeneratorContainer.java b/plugins/initializer/src/main/java/org/intocps/maestro/plugin/initializer/spec/StatementGeneratorContainer.java index 13965e9f2..f2ed43fe6 100644 --- a/plugins/initializer/src/main/java/org/intocps/maestro/plugin/initializer/spec/StatementGeneratorContainer.java +++ b/plugins/initializer/src/main/java/org/intocps/maestro/plugin/initializer/spec/StatementGeneratorContainer.java @@ -39,8 +39,8 @@ public class StatementGeneratorContainer { private final Map intArrays = new HashMap<>(); private final Map stringArrays = new HashMap<>(); - private final Map convergenceRefArray = new HashMap<>(); - private final Map loopValueArray = new HashMap<>(); + private final Map convergenceRefArray = new HashMap<>(); + private final Map loopValueArray = new HashMap<>(); private final EnumMap typesStringMap = new EnumMap<>(Fmi2ModelDescription.Types.class) { { @@ -154,8 +154,8 @@ public PStm exitInitializationMode(String instanceName) { (LexIdentifier) createLexIdentifier.apply("exitInitializationMode").clone(), null)); } - public List createFixedPointIteration(List loopVariables, int iterationMax, int sccNumber, - Fmi2SimulationEnvironment env) throws ExpandException { + public List createFixedPointIteration(List loopVariables, int iterationMax, + int sccNumber, Fmi2SimulationEnvironment env) throws ExpandException { LexIdentifier end = newAIdentifier(String.format("end%d", sccNumber)); LexIdentifier start = newAIdentifier(String.format("start%d", sccNumber)); List statements = new Vector<>(); @@ -164,13 +164,13 @@ public List createFixedPointIteration(List o.scalarVariable.getScalarVariable().causality == Fmi2ModelDescription.Causality.Output && - o.scalarVariable.scalarVariable.getType().type == Fmi2ModelDescription.Types.Real).collect(Collectors.toList()); + var outputs = loopVariables.stream() + .filter(o -> o.has(Fmi2ModelDescription.Causality.Output) && o.getType().hasType(Fmi2ModelDescription.Types.Real)) + .collect(Collectors.toList()); - for (Fmi2SimulationEnvironment.Variable output : outputs) { - var lexIdentifier = createLexIdentifier.apply( - "Ref" + output.scalarVariable.instance.getText() + output.scalarVariable.scalarVariable.getName() + "ValueRef" + - output.scalarVariable.scalarVariable.getValueReference()); + for (org.intocps.maestro.framework.fmi2.RelationVariable output : outputs) { + var lexIdentifier = + createLexIdentifier.apply("Ref" + output.getInstance().getText() + output.getName() + "ValueRef" + output.getValueReference()); statements.add(createReferenceArray(output, lexIdentifier)); //Create map to test references against convergenceRefArray.put(output, lexIdentifier); @@ -204,28 +204,29 @@ public List createFixedPointIteration(List performLoopActions(List loopVariables, Fmi2SimulationEnvironment env) { + private List performLoopActions(List loopVariables, Fmi2SimulationEnvironment env) { List LoopStatements = new Vector<>(); loopVariables.stream().forEach(variable -> { - long[] scalarValueIndices = new long[]{variable.scalarVariable.scalarVariable.valueReference}; + long[] scalarValueIndices = new long[]{variable.getValueReference()}; //All members of the same set has the same causality, type and comes from the same instance - if (variable.scalarVariable.scalarVariable.causality == Fmi2ModelDescription.Causality.Output) { - var lexId = createLexIdentifier.apply(variable.scalarVariable.instance + variable.scalarVariable.getScalarVariable().name); - LoopStatements.add(newALocalVariableStm( - newAVariableDeclaration(lexId, newAArrayType(fmiTypeToMablType(variable.scalarVariable.scalarVariable.getType().type)), 1, - null))); + if (variable.has(Fmi2ModelDescription.Causality.Output)) { + var lexId = createLexIdentifier.apply(variable.getInstance().getText() + variable.getName()); + LoopStatements.add(newALocalVariableStm(newAVariableDeclaration(lexId, newAArrayType(variable.getType().getLexType()), 1, null))); loopValueArray.put(variable, lexId); try { - LoopStatements.addAll(getValueStm(variable.scalarVariable.instance.getText(), lexId, scalarValueIndices, - variable.scalarVariable.scalarVariable.getType().type)); + LoopStatements.addAll(getValueStm(variable.getInstance().getText(), lexId, scalarValueIndices, + ((Fmi2ModelDescription.Type) variable.getType().get()).type)); } catch (ExpandException e) { e.printStackTrace(); } } else { try { - LoopStatements.addAll(setValueOnPortStm(variable.scalarVariable.instance, variable.scalarVariable.scalarVariable.getType().type, - Collections.singletonList(variable.scalarVariable.scalarVariable), scalarValueIndices, env)); + LoopStatements.addAll(setValueOnPortStm(variable.getInstance(), + ((Fmi2ModelDescription.Type)variable.getType().get()).type, + Collections.singletonList( + (Fmi2ModelDescription.ScalarVariable) variable.getScalarVariable(Fmi2ModelDescription.ScalarVariable.class)), + scalarValueIndices, env)); } catch (ExpandException e) { e.printStackTrace(); } @@ -257,17 +258,15 @@ public List setValueOnPortStm(LexIdentifier comp, Fmi2ModelDescription.Typ } } - private PStm createReferenceArray(Fmi2SimulationEnvironment.Variable variable, LexIdentifier lexID) throws ExpandException { + private PStm createReferenceArray(org.intocps.maestro.framework.fmi2.RelationVariable variable, LexIdentifier lexID) throws ExpandException { List args = new ArrayList<>(); - args.add(getDefaultArrayValue(variable.scalarVariable.scalarVariable.getType().type)); + args.add(variable.getType().getLexDefaultValue()); PInitializer initializer = MableAstFactory.newAArrayInitializer(args); - return newALocalVariableStm( - newAVariableDeclaration(lexID, newAArrayType(fmiTypeToMablType(variable.scalarVariable.scalarVariable.getType().type)), 1, - initializer)); + return newALocalVariableStm(newAVariableDeclaration(lexID, newAArrayType(variable.getType().getLexType()), 1, initializer)); } - private List updateReferenceArray(List outputPorts) { + private List updateReferenceArray(List outputPorts) { List updateStmts = new Vector<>(); outputPorts.forEach(o -> { var referenceValue = convergenceRefArray.get(o); @@ -279,7 +278,7 @@ private List updateReferenceArray(List } //This method should check if all output of the Fixed Point iteration have stabilized/converged - private List checkLoopConvergence(List outputPorts, LexIdentifier doesConverge) { + private List checkLoopConvergence(List outputPorts, LexIdentifier doesConverge) { LexIdentifier index = newAIdentifier("index"); List result = new Vector<>(); result.add(newALocalVariableStm(newAVariableDeclaration(index, newAIntNumericPrimitiveType(), newAExpInitializer(newAIntLiteralExp(0))))); @@ -497,7 +496,8 @@ public List setRealsStm(String instanceName, long[] longs, double[] double LexIdentifier valueArray = findArrayOfSize(realArrays, longs.length); // The array does not exist. Create it and initialize it. if (valueArray == null) { - var value = createArray(doubles.length, valueLocator, realArrayVariableName.apply(longs.length), Fmi2ModelDescription.Types.Real, realArrays); + var value = + createArray(doubles.length, valueLocator, realArrayVariableName.apply(longs.length), Fmi2ModelDescription.Types.Real, realArrays); valueArray = value.getLeft(); statements.addAll(value.getRight()); } else { @@ -548,7 +548,8 @@ public List setIntegersStm(String instanceName, long[] longs, int[] ints) LexIdentifier valueArray = findArrayOfSize(intArrays, longs.length); // The array does not exist. Create it and initialize it. if (valueArray == null) { - var value = createArray(ints.length, valueLocator, intArrayVariableName.apply(longs.length), Fmi2ModelDescription.Types.Integer, intArrays); + var value = + createArray(ints.length, valueLocator, intArrayVariableName.apply(longs.length), Fmi2ModelDescription.Types.Integer, intArrays); valueArray = value.getLeft(); statements.addAll(value.getRight()); } else { @@ -656,7 +657,8 @@ private Object getNewValue(Fmi2ModelDescription.ScalarVariable sv, ModelConnecti return newVal; } - public List getValueStm(String instanceName, LexIdentifier valueArray, long[] longs, Fmi2ModelDescription.Types type) throws ExpandException { + public List getValueStm(String instanceName, LexIdentifier valueArray, long[] longs, + Fmi2ModelDescription.Types type) throws ExpandException { if (!instancesLookupDependencies) { instancesLookupDependencies = true; } diff --git a/plugins/initializer/src/main/kotlin/Initializer.kt b/plugins/initializer/src/main/kotlin/Initializer.kt index 6aceca8ee..0d0146faa 100644 --- a/plugins/initializer/src/main/kotlin/Initializer.kt +++ b/plugins/initializer/src/main/kotlin/Initializer.kt @@ -9,6 +9,7 @@ import org.intocps.maestro.ast.node.* import org.intocps.maestro.core.Framework import org.intocps.maestro.core.messages.IErrorReporter import org.intocps.maestro.fmi.Fmi2ModelDescription +import org.intocps.maestro.fmi.fmi3.* import org.intocps.maestro.framework.core.IRelation import org.intocps.maestro.framework.core.ISimulationEnvironment import org.intocps.maestro.framework.core.RelationVariable @@ -17,6 +18,7 @@ import org.intocps.maestro.framework.fmi2.InvalidVariableStringException import org.intocps.maestro.framework.fmi2.ModelConnection import org.intocps.maestro.framework.fmi2.api.FmiBuilder import org.intocps.maestro.framework.fmi2.api.FmiBuilder.ArrayVariable +import org.intocps.maestro.framework.fmi2.api.FmiBuilder.SimulationInstance import org.intocps.maestro.framework.fmi2.api.mabl.* import org.intocps.maestro.framework.fmi2.api.mabl.scoping.DynamicActiveBuilderScope import org.intocps.maestro.framework.fmi2.api.mabl.scoping.ScopeFmi2Api @@ -97,7 +99,7 @@ class Initializer : BasicMaestroExpansionPlugin { ), MableAstFactory.newAVoidType() ) - private val portsAlreadySet = HashMap>() + private val portsAlreadySet = HashMap, Set>() private val topologicalPlugin: TopologicalPlugin private val initializationPrologQuery: InitializationPrologQuery var config: InitializationConfig? = null @@ -359,11 +361,7 @@ class Initializer : BasicMaestroExpansionPlugin { math ) -// val algorithm = builder.buildRaw() as SBlockStm -// algorithm.apply(ToParExp()) -// -// -// algorithm.body + } catch (e: Exception) { throw ExpandException("Internal error: ", e) } @@ -422,11 +420,12 @@ class Initializer : BasicMaestroExpansionPlugin { //Set variables for all components in IniPhase setComponentsVariables(fmuInstances, PhasePredicates.iniPhase(), builder) + setInstanceVariables(fmu3Instances, PhasePredicates3.iniPhase(), builder) //Enter initialization Mode logger.debug("Enter initialization Mode") fmuInstances.values.forEach(Consumer { fmu: ComponentVariableFmi2Api -> fmu.enterInitializationMode() }) - //FIXME: missing parameters + val fmi3ToloranceDefined = dynamicScope.store("absoluteTolerance", this.config!!.absoluteTolerance) fmu3Instances.values.forEach(Consumer { fmu: InstanceVariableFmi3Api -> fmu.enterInitializationMode( @@ -438,6 +437,8 @@ class Initializer : BasicMaestroExpansionPlugin { ) }) + + //TODO not sure what this is - stabilization maybe val instructions = instantiationOrder.map { i -> createInitInstructions( i.toList(), dynamicScope, fmuInstances, booleanLogic, math @@ -459,9 +460,11 @@ class Initializer : BasicMaestroExpansionPlugin { stabilisationScope.activate() stabilisationScope.leave(); } + //TODO end setRemainingInputs(fmuInstances, builder) + setRemainingInputs3(fmu3Instances, builder) //Exit initialization Mode fmuInstances.values.forEach(Consumer { obj: ComponentVariableFmi2Api -> obj.exitInitializationMode() }) @@ -527,76 +530,7 @@ class Initializer : BasicMaestroExpansionPlugin { booleanLogic, math ); -// -// // Create bindings -// FromMaBLToMaBLAPI.createBindings(fmuInstances, env) -// -// this.config = config as InitializationConfig -// -// this.modelParameters = config.modelParameters -// this.envParameters = config.envParameters -// -// // Convergence related variables -// absoluteTolerance = dynamicScope.store("absoluteTolerance", this.config!!.absoluteTolerance) -// relativeTolerance = dynamicScope.store("relativeTolerance", this.config!!.relativeTolerance) -// maxConvergeAttempts = dynamicScope.store("maxConvergeAttempts", this.config!!.maxIterations) -// -// logger.debug("Setup experiment for all components") -// fmuInstances.values.forEach { i -> -// i.setupExperiment( -// externalStartTime, -// externalEndTime, -// this.config!!.relativeTolerance -// ) -// }; -// val connections = createConnections(env, fmuInstances) -// -// //Find the right order to instantiate dependentPorts and make sure where doesn't exist any cycles in the connections -// val instantiationOrder = topologicalPlugin.findInstantiationOrderStrongComponents(connections) -// -// //Verification against prolog should only be done if it turned on and there is no loops -// if (this.config!!.verifyAgainstProlog && instantiationOrder.all { i -> i.size == 1 }) -// initializationPrologQuery.initializationOrderIsValid(instantiationOrder.flatten(), connections) -// -// -// //Set variables for all components in IniPhase -// setComponentsVariables(fmuInstances, PhasePredicates.iniPhase(), builder) -// -// //Enter initialization Mode -// logger.debug("Enter initialization Mode") -// fmuInstances.values.forEach(Consumer { fmu: ComponentVariableFmi2Api -> fmu.enterInitializationMode() }) -// -// val instructions = instantiationOrder.map { i -> -// createInitInstructions( -// i.toList(), -// dynamicScope, -// fmuInstances, -// booleanLogic, -// math -// ) -// } -// var stabilisationScope: ScopeFmi2Api? = null -// var stabilisationLoop: IntVariableFmi2Api? = null -// if (this.config!!.stabilisation) { -// stabilisationLoop = dynamicScope.store("stabilisation_loop", this.config!!.maxIterations) -// stabilisationScope = dynamicScope.enterWhile( -// stabilisationLoop!!.toMath().greaterThan(IntExpressionValue.of(0)) -// ) -// } -// -// instructions.forEach { i -> i.perform() } -// -// if (stabilisationScope != null) { -// stabilisationLoop!!.decrement(); -// stabilisationScope.activate() -// stabilisationScope.leave(); -// } -// -// -// setRemainingInputs(fmuInstances, builder) -// -// //Exit initialization Mode -// fmuInstances.values.forEach(Consumer { obj: ComponentVariableFmi2Api -> obj.exitInitializationMode() }) + val algorithm = builder.buildRaw() as SBlockStm algorithm.apply(ToParExp()) @@ -615,7 +549,7 @@ class Initializer : BasicMaestroExpansionPlugin { try { val scalarVariables = comp.modelDescription.scalarVariables val inputsScalars = scalarVariables.filter { x -> - PhasePredicates.inPhase().test(x) && !portSet(comp, x) + PhasePredicates.inPhase().test(x) && !isPortSet(comp, x) } val ports = @@ -631,10 +565,36 @@ class Initializer : BasicMaestroExpansionPlugin { } } - private fun portSet(comp: ComponentVariableFmi2Api, x: Fmi2ModelDescription.ScalarVariable?): Boolean { + private fun setRemainingInputs3( + fmuInstances: Map, builder: MablApiBuilder + ) { + for (comp in fmuInstances.values) { + try { + val scalarVariables = comp.modelDescription.getScalarVariables() + val inputsScalars = scalarVariables.filter { x -> + PhasePredicates3.inPhase().test(x.variable) && !isPortSet(comp, x.variable) + } + + val ports = + comp.getPorts( + *inputsScalars.stream() + .mapToInt { sv -> Math.toIntExact(sv.variable.getValueReferenceAsLong()) } + .toArray()) + + for (port in ports) { + setParameterOnPort(port, comp, builder) + } + } catch (e: Exception) { + throw ExpandException("Initializer failed to read scalarvariables", e) + } + } + } + + private fun isPortSet(comp: SimulationInstance, x: Any?): Boolean { return if (portsAlreadySet.containsKey(comp)) portsAlreadySet.getValue(comp).contains(x) else false } + private fun setParameterOnPort( port: PortFmi2Api, comp: ComponentVariableFmi2Api, builder: MablApiBuilder ) { @@ -691,7 +651,69 @@ class Initializer : BasicMaestroExpansionPlugin { addToPortsAlreadySet(comp, port.scalarVariable) } - private fun addToPortsAlreadySet(comp: ComponentVariableFmi2Api, port: Fmi2ModelDescription.ScalarVariable) { + private fun setParameterOnPort( + port: PortFmi3Api, comp: InstanceVariableFmi3Api, builder: MablApiBuilder + ) { + val fmuName = comp.name +// var value = findUseDefault(fmuName, port.scalarVariable, modelParameters) + + val useEnvForPort = this.envParameters?.contains(port.multiModelScalarVariableName) + if (useEnvForPort == null || !useEnvForPort) { + + var staticValue = findParameterOrDefault(fmuName, port.scalarVariable, modelParameters) + when (port.scalarVariable.variable.typeIdentifier!!) { + Fmi3TypeEnum.BooleanType -> comp.set(port, BooleanExpressionValue.of(staticValue as Boolean)) + Fmi3TypeEnum.Float64Type -> { + + if (port.scalarVariable.variable.isScalar()) { + staticValue = (staticValue as List).get(0) + + + if (staticValue is Int) { + staticValue = staticValue.toDouble() + } + val b: Double = staticValue as Double + comp.set(port, DoubleExpressionValue.of(b)) + } + } + + Fmi3TypeEnum.Int32Type -> comp.set(port, IntExpressionValue.of(staticValue as Int)) + Fmi3TypeEnum.StringType -> comp.set(port, StringExpressionValue.of(staticValue as String)) + Fmi3TypeEnum.EnumerationType -> throw ExpandException("Enumeration not supported") + else -> throw ExpandException("Not known type") + } + } else { + when (port.scalarVariable.variable.typeIdentifier!!) { + Fmi3TypeEnum.BooleanType -> { + val v = builder.executionEnvironment.getBool(port.multiModelScalarVariableName) + comp.set(port, v) + } + + Fmi3TypeEnum.Float64Type -> { + val v = builder.executionEnvironment.getReal(port.multiModelScalarVariableName) + comp.set(port, v) + } + + Fmi3TypeEnum.Int32Type -> { + val v = builder.executionEnvironment.getInt(port.multiModelScalarVariableName) + comp.set(port, v) + } + + Fmi3TypeEnum.StringType -> { + val v = builder.executionEnvironment.getString(port.multiModelScalarVariableName) + comp.set(port, v) + } + + Fmi3TypeEnum.EnumerationType -> throw ExpandException("Enumeration not supported") + else -> throw ExpandException("Not known type") + } + } + + + addToPortsAlreadySet(comp, port.scalarVariable) + } + + private fun addToPortsAlreadySet(comp: FmiBuilder.SimulationInstance, port: Any?) { if (portsAlreadySet.containsKey(comp)) { portsAlreadySet.replace(comp, portsAlreadySet.getValue(comp).plus(port)) } else { @@ -700,7 +722,7 @@ class Initializer : BasicMaestroExpansionPlugin { } private fun createInitInstructions( - ports: List, + ports: List>, dynamicScope: DynamicActiveBuilderScope, fmuInstances: Map, booleanLogic: BooleanBuilderFmi2Api, @@ -712,8 +734,8 @@ class Initializer : BasicMaestroExpansionPlugin { } else { val actions = ports.map { c -> fmuCoSimInstruction(fmuInstances, c) } val outputPorts = - ports.filter { p -> p.scalarVariable.scalarVariable.causality == Fmi2ModelDescription.Causality.Output } - .map { i -> i.scalarVariable } + ports.filter { p -> p.has(Fmi2ModelDescription.Causality.Output) } + .map { i -> i } LoopSimInstruction( dynamicScope, maxConvergeAttempts!!, @@ -728,22 +750,22 @@ class Initializer : BasicMaestroExpansionPlugin { } private fun fmuCoSimInstruction( - fmuInstances: Map, p: Fmi2SimulationEnvironment.Variable + fmuInstances: Map, p: org.intocps.maestro.framework.fmi2.RelationVariable ): FMUCoSimInstruction { - val fmu = fmuInstances.values.find { x -> x.environmentName.equals(p.scalarVariable.instance.text) } + val instance = fmuInstances.values.find { x -> x.environmentName.equals(p.getInstance().text) } // val fmu = fmuInstances.getValue(p.scalarVariable.instance.text) - if (fmu != null) { - val port = fmu.getPort(p.scalarVariable.scalarVariable.name) - return when (p.scalarVariable.scalarVariable.causality) { - Fmi2ModelDescription.Causality.Output -> GetInstruction(fmu, port, false) - Fmi2ModelDescription.Causality.Input -> { - addToPortsAlreadySet(fmu, port.scalarVariable) - SetInstruction(fmu, port) + if (instance != null) { + val port = instance.getPort(p.name) + return when { + p.has(Fmi2ModelDescription.Causality.Output) -> GetInstruction(instance, port, false) + p.has(Fmi2ModelDescription.Causality.Input) -> { + addToPortsAlreadySet(instance, port.scalarVariable) + SetInstruction(instance, port) } else -> throw ExpandException("Internal error") } - } else throw ExpandException("Failed to retrieve FMUInstance by name: " + p.scalarVariable.instance.text) + } else throw ExpandException("Failed to retrieve FMUInstance by name: " + p.name) } @@ -811,6 +833,19 @@ class Initializer : BasicMaestroExpansionPlugin { } } + private fun setInstanceVariables( + fmuInstances: Map, + predicate: Predicate, + builder: MablApiBuilder + ) { + fmuInstances.entries.forEach { (fmuName, comp) -> + for (sv in comp.modelDescription.getModelVariables().filter { i -> predicate.test(i) }) { + val port = comp.getPort(sv.name) + setParameterOnPort(port, comp, builder) + } + } + } + @Throws(ExpandException::class) private fun verifyArguments( @@ -941,6 +976,29 @@ class Initializer : BasicMaestroExpansionPlugin { return if (parameterValue != null) parameterValue.value else sv.type.start } + private fun findParameterOrDefault( + compName: String, sv: Fmi3ModelDescription.Fmi3ScalarVariable, modelParameters: List? + ): Any? { + val parameterValue = + modelParameters?.firstOrNull { x: ModelParameter -> x.variable.instance.instanceName == compName && x.variable.variable == sv.variable.name } + return if (parameterValue != null) parameterValue.value else getStartValue(sv.variable) + } + + private fun getStartValue(variable: Fmi3Variable): Any? { + return when (variable) { + is FloatVariable -> variable.start + is Int64Variable -> variable.start + is IntVariable -> variable.start + is BooleanVariable -> variable.start + is StringVariable -> variable.start + is BinaryVariable -> variable.start + is EnumerationVariable -> variable.start + is ClockVariable -> null + else -> null + + } + } + // /** // * This functions either returns null if the parameter has a value or it returns the model description start value // */ diff --git a/plugins/jacobianstepbuilder/src/main/java/org/intocps/maestro/plugin/JacobianStepBuilder.java b/plugins/jacobianstepbuilder/src/main/java/org/intocps/maestro/plugin/JacobianStepBuilder.java index f010b1a4b..10be060b4 100644 --- a/plugins/jacobianstepbuilder/src/main/java/org/intocps/maestro/plugin/JacobianStepBuilder.java +++ b/plugins/jacobianstepbuilder/src/main/java/org/intocps/maestro/plugin/JacobianStepBuilder.java @@ -672,8 +672,8 @@ private PortFmi2Api getSwapSourcePort(PortFmi2Api port, Set r.getTargets().values().stream().anyMatch(v -> v.toString().equals(port.getMultiModelScalarVariableNameWithoutFmu()))) .findFirst(); if (relation.isPresent()) { - String source = relation.get().getSource().scalarVariable.instance.getText(); - sourcePort = fmuInstances.get(source).getPort(relation.get().getSource().scalarVariable.scalarVariable.getName()); + String source = relation.get().getSource().getInstance().getText(); + sourcePort = fmuInstances.get(source).getPort(relation.get().getSource().getName()); } return sourcePort; } @@ -685,7 +685,7 @@ private ModelSwapInfo getSwapSourceInfo(PortFmi2Api port, Set r.getTargets().values().stream().anyMatch(v -> v.toString().equals(port.getMultiModelScalarVariableNameWithoutFmu()))) .findFirst(); if (relation.isPresent()) { - String source = relation.get().getSource().scalarVariable.instance.getText(); + String source = relation.get().getSource().getInstance().getText(); Optional> infoEntry = env.getModelSwaps().stream().filter(e -> e.getValue().swapInstance.equals(source)).findFirst(); if (infoEntry.isPresent()) { diff --git a/plugins/verificationsuite/src/main/java/org/intocps/maestro/plugin/verificationsuite/graph/GraphDrawer.java b/plugins/verificationsuite/src/main/java/org/intocps/maestro/plugin/verificationsuite/graph/GraphDrawer.java index 73b51ba37..8827fee85 100644 --- a/plugins/verificationsuite/src/main/java/org/intocps/maestro/plugin/verificationsuite/graph/GraphDrawer.java +++ b/plugins/verificationsuite/src/main/java/org/intocps/maestro/plugin/verificationsuite/graph/GraphDrawer.java @@ -6,6 +6,7 @@ import guru.nidi.graphviz.engine.Graphviz; import guru.nidi.graphviz.model.MutableGraph; import org.intocps.maestro.framework.fmi2.Fmi2SimulationEnvironment; +import org.intocps.maestro.framework.fmi2.RelationVariable; import java.io.File; import java.io.IOException; @@ -16,8 +17,8 @@ import static guru.nidi.graphviz.model.Factory.mutNode; public class GraphDrawer { - private String getInstanceName(Fmi2SimulationEnvironment.Variable o) { - return o.scalarVariable.instance.getText() + "." + o.scalarVariable.scalarVariable.getName(); + private String getInstanceName(RelationVariable o) { + return o.getInstance().getText() + "." + o.getName(); } public void plotGraph(Set relations, String name) throws IOException { diff --git a/plugins/verificationsuite/src/main/java/org/intocps/maestro/plugin/verificationsuite/prologverifier/InitializationPrologQuery.java b/plugins/verificationsuite/src/main/java/org/intocps/maestro/plugin/verificationsuite/prologverifier/InitializationPrologQuery.java index 6618742c4..bfd83c0a4 100644 --- a/plugins/verificationsuite/src/main/java/org/intocps/maestro/plugin/verificationsuite/prologverifier/InitializationPrologQuery.java +++ b/plugins/verificationsuite/src/main/java/org/intocps/maestro/plugin/verificationsuite/prologverifier/InitializationPrologQuery.java @@ -2,6 +2,7 @@ import com.ugos.jiprolog.engine.*; import org.intocps.maestro.framework.fmi2.Fmi2SimulationEnvironment; +import org.intocps.maestro.framework.fmi2.RelationVariable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -23,8 +24,7 @@ public InitializationPrologQuery() { this.prologGenerator = new PrologGenerator(); } - public boolean initializationOrderIsValid(List instantiationOrder, - Set relations) { + public boolean initializationOrderIsValid(List instantiationOrder, Set relations) { // New instance of prolog engine JIPEngine jip = new JIPEngine(); JIPTerm queryTerm = null; diff --git a/plugins/verificationsuite/src/main/java/org/intocps/maestro/plugin/verificationsuite/prologverifier/PrologGenerator.java b/plugins/verificationsuite/src/main/java/org/intocps/maestro/plugin/verificationsuite/prologverifier/PrologGenerator.java index f59a2f6df..b49599561 100644 --- a/plugins/verificationsuite/src/main/java/org/intocps/maestro/plugin/verificationsuite/prologverifier/PrologGenerator.java +++ b/plugins/verificationsuite/src/main/java/org/intocps/maestro/plugin/verificationsuite/prologverifier/PrologGenerator.java @@ -3,6 +3,7 @@ import org.intocps.maestro.ast.LexIdentifier; import org.intocps.maestro.fmi.Fmi2ModelDescription; import org.intocps.maestro.framework.fmi2.Fmi2SimulationEnvironment; +import org.intocps.maestro.framework.fmi2.RelationVariable; import org.intocps.maestro.plugin.ExpandException; import java.util.Collection; @@ -11,12 +12,11 @@ import java.util.stream.Collectors; public class PrologGenerator { - public String createInitOperationOrder(List instantiationOrder) { + public String createInitOperationOrder(List instantiationOrder) { StringBuilder initOrder = new StringBuilder(); instantiationOrder.forEach(o -> { try { - initOrder.append(String.format("%s(%s, %s),", getMethod(o), o.scalarVariable.getInstance().getText().toLowerCase(), - o.scalarVariable.getScalarVariable().getName().toLowerCase())); + initOrder.append(String.format("%s(%s, %s),", getMethod(o), o.getInstance().getText().toLowerCase(), o.getName().toLowerCase())); } catch (ExpandException e) { e.printStackTrace(); } @@ -27,7 +27,7 @@ public String createInitOperationOrder(List public String createFMUs(Set relations) { StringBuilder fmuString = new StringBuilder(); - var fmuList = relations.stream().map(o -> o.getSource().scalarVariable.getInstance()).collect(Collectors.toSet()); + var fmuList = relations.stream().map(o -> o.getSource().getInstance()).collect(Collectors.toSet()); fmuList.forEach(fmu -> { fmuString.append(String.format("fmu(%s, %s, %s),", fmu.getText().toLowerCase(), getInPorts(relations, fmu), getOutPorts(relations, fmu))); }); @@ -39,10 +39,8 @@ public String createConnections(List relatio StringBuilder connections = new StringBuilder(); relations.forEach(relation -> { relation.getTargets().values().forEach(target -> { - connections.append(String.format("connect(%s,%s, %s, %s),", relation.getSource().scalarVariable.getInstance().getText().toLowerCase(), - relation.getSource().scalarVariable.getScalarVariable().getName().toLowerCase(), - target.scalarVariable.getInstance().getText().toLowerCase(), - target.scalarVariable.getScalarVariable().getName().toLowerCase())); + connections.append(String.format("connect(%s,%s, %s, %s),", relation.getSource().getInstance().getText().toLowerCase(), + relation.getSource().getName().toLowerCase(), target.getInstance().getText().toLowerCase(), target.getName().toLowerCase())); }); }); return fixListFormat(connections).toString(); @@ -60,11 +58,10 @@ private StringBuilder fixListFormat(StringBuilder stringBuilder) { private String getInPorts(Set relations, LexIdentifier fmu) { StringBuilder inPorts = new StringBuilder(); var inputPorts = relations.stream().map(p -> p.getTargets().values()).collect(Collectors.toList()).stream().flatMap(Collection::stream) - .collect(Collectors.toSet()).stream().filter(o -> o.scalarVariable.getInstance().getText().equals(fmu.getText())) - .collect(Collectors.toSet()); + .collect(Collectors.toSet()).stream().filter(o -> o.getInstance().getText().equals(fmu.getText())).collect(Collectors.toSet()); inputPorts.forEach(port -> { - inPorts.append(String.format("port(%s, delayed),", port.scalarVariable.getScalarVariable().getName().toLowerCase())); + inPorts.append(String.format("port(%s, delayed),", port.getName().toLowerCase())); }); return fixListFormat(inPorts).toString(); @@ -76,33 +73,33 @@ private String getOutPorts(Set relations, Le .collect(Collectors.toSet()); var internalRelations = relations.stream().filter(o -> o.getOrigin() == Fmi2SimulationEnvironment.Relation.InternalOrExternal.Internal) .collect(Collectors.toSet()); - var outputPorts = externalRelations.stream().filter(p -> p.getSource().scalarVariable.getInstance() == fmu).collect(Collectors.toSet()); + var outputPorts = externalRelations.stream().filter(p -> p.getSource().getInstance() == fmu).collect(Collectors.toSet()); outputPorts.forEach(port -> { - outPorts.append(String.format("port(%s, %s),", port.getSource().scalarVariable.getScalarVariable().getName().toLowerCase(), + outPorts.append(String.format("port(%s, %s),", port.getSource().getName().toLowerCase(), getInternalDependencies(port.getSource(), internalRelations))); }); return fixListFormat(outPorts).toString(); } - private String getInternalDependencies(Fmi2SimulationEnvironment.Variable source, Set internalRelations) { + private String getInternalDependencies(RelationVariable source, Set internalRelations) { var sources = internalRelations.stream().filter(rel -> rel.getSource() == source).map(o -> o.getTargets().values()).collect(Collectors.toSet()) .stream().flatMap(Collection::stream).collect(Collectors.toSet()); StringBuilder internalConnections = new StringBuilder(); sources.forEach(s -> { - internalConnections.append(String.format("%s,", s.scalarVariable.getScalarVariable().getName().toLowerCase())); + internalConnections.append(String.format("%s,", s.getName().toLowerCase())); }); return fixListFormat(internalConnections).toString(); } - private String getMethod(Fmi2SimulationEnvironment.Variable variable) throws ExpandException { - if (variable.scalarVariable.getScalarVariable().causality == Fmi2ModelDescription.Causality.Output) { + private String getMethod(RelationVariable variable) throws ExpandException { + if (variable.has(Fmi2ModelDescription.Causality.Output)) { return "getOut"; - } else if (variable.scalarVariable.getScalarVariable().causality == Fmi2ModelDescription.Causality.Input) { + } else if (variable.has(Fmi2ModelDescription.Causality.Input)) { return "setIn"; } else { throw new ExpandException("Unknown causality of port"); diff --git a/plugins/verificationsuite/src/test/java/GraphPlotterTest.java b/plugins/verificationsuite/src/test/java/GraphPlotterTest.java index dce2278d6..e2faedcf3 100644 --- a/plugins/verificationsuite/src/test/java/GraphPlotterTest.java +++ b/plugins/verificationsuite/src/test/java/GraphPlotterTest.java @@ -51,17 +51,17 @@ public void plotGraphWithSimpleLoop() throws Exception { var variable3 = createVariable("CE", "Level", unitRelationship); var variable4 = createVariable("Tank", "Level", unitRelationship); - HashMap target1 = new HashMap<>(); - target1.put(new LexIdentifier(variable1.scalarVariable.instance.getText(), null), variable1); - HashMap target2 = new HashMap<>(); - target2.put(new LexIdentifier(variable2.scalarVariable.instance.getText(), null), variable2); - HashMap target3 = new HashMap<>(); - target3.put(new LexIdentifier(variable3.scalarVariable.instance.getText(), null), variable3); - HashMap target4 = new HashMap<>(); - target4.put(new LexIdentifier(variable4.scalarVariable.instance.getText(), null), variable4); + HashMap target1 = new HashMap<>(); + target1.put(new LexIdentifier(variable1.getInstance().getText(), null), variable1); + HashMap target2 = new HashMap<>(); + target2.put(new LexIdentifier(variable2.getInstance().getText(), null), variable2); + HashMap target3 = new HashMap<>(); + target3.put(new LexIdentifier(variable3.getInstance().getText(), null), variable3); + HashMap target4 = new HashMap<>(); + target4.put(new LexIdentifier(variable4.getInstance().getText(), null), variable4); relations.add(new Fmi2SimulationEnvironment.Relation.RelationBuilder(variable1, target2).build()); - relations.add(new Fmi2SimulationEnvironment.Relation.RelationBuilder(variable3, target2) - .setInternalOrExternal(Fmi2SimulationEnvironment.Relation.InternalOrExternal.Internal).build()); + relations.add(new Fmi2SimulationEnvironment.Relation.RelationBuilder(variable3, target2).setInternalOrExternal( + Fmi2SimulationEnvironment.Relation.InternalOrExternal.Internal).build()); relations.add(new Fmi2SimulationEnvironment.Relation.RelationBuilder(variable3, target1).build()); relations.add(new Fmi2SimulationEnvironment.Relation.RelationBuilder(variable3, target4).build()); @@ -69,10 +69,10 @@ public void plotGraphWithSimpleLoop() throws Exception { } - private Fmi2SimulationEnvironment.Variable createVariable(String fmuName, String variableName, Fmi2SimulationEnvironment unitRelationship) { + private RelationVariable createVariable(String fmuName, String variableName, Fmi2SimulationEnvironment unitRelationship) { var scalarVar = new Fmi2ModelDescription.ScalarVariable(); scalarVar.name = variableName; - return new Fmi2SimulationEnvironment.Variable(new RelationVariable(scalarVar, new LexIdentifier(fmuName, null))); + return new RelationVariable(scalarVar, scalarVar.getName(), new LexIdentifier(fmuName, null)); } } diff --git a/plugins/verificationsuite/src/test/java/PrologVerifierTest.java b/plugins/verificationsuite/src/test/java/PrologVerifierTest.java index 76dcd16c5..1ffcf02ba 100644 --- a/plugins/verificationsuite/src/test/java/PrologVerifierTest.java +++ b/plugins/verificationsuite/src/test/java/PrologVerifierTest.java @@ -71,10 +71,10 @@ public void VerifyInitializationOrderProlog() throws Exception { } */ - private Fmi2SimulationEnvironment.Variable createVariable(String fmuName, String variableName, Fmi2SimulationEnvironment unitRelationship) { + private RelationVariable createVariable(String fmuName, String variableName, Fmi2SimulationEnvironment unitRelationship) { var scalarVar = new Fmi2ModelDescription.ScalarVariable(); scalarVar.name = variableName; - return new Fmi2SimulationEnvironment.Variable(new RelationVariable(scalarVar, new LexIdentifier(fmuName, null))); + return new RelationVariable(scalarVar, scalarVar.getName(), new LexIdentifier(fmuName, null)); } } diff --git a/pom.xml b/pom.xml index 1e8896238..a2683db33 100644 --- a/pom.xml +++ b/pom.xml @@ -24,7 +24,7 @@ 11 11 2.17.1 - 1.3.6-SNAPSHOT + 1.4.0-SNAPSHOT 1.0.10 1.9.0 2.13.11 diff --git a/typechecker/src/main/resources/org/intocps/maestro/typechecker/FMI3.mabl b/typechecker/src/main/resources/org/intocps/maestro/typechecker/FMI3.mabl index 657f40d04..2c5d9bf8e 100644 --- a/typechecker/src/main/resources/org/intocps/maestro/typechecker/FMI3.mabl +++ b/typechecker/src/main/resources/org/intocps/maestro/typechecker/FMI3.mabl @@ -84,29 +84,29 @@ module FMI3Instance import FMU3State;{ /* end::getters[] */ /* tag::setters[] */ - int setFloat32(uint valueReferences[], float values[]); + int setFloat32(uint valueReferences[],int nvr, float values[],int nv); - int setFloat64(uint valueReferences[], real values[]); + int setFloat64(uint valueReferences[],int nvr, real values[],int nv); - int setInt8(uint valueReferences[], byte values[]); + int setInt8(uint valueReferences[],int nvr, byte values[],int nv); - int setUInt8(uint valueReferences[], byte values[]); + int setUInt8(uint valueReferences[],int nvr, byte values[],int nv); - int setInt16(uint valueReferences[], short values[]); + int setInt16(uint valueReferences[],int nvr, short values[],int nv); - int setUInt16(uint valueReferences[], short values[]); + int setUInt16(uint valueReferences[],int nvr, short values[],int nv); - int setInt32(uint valueReferences[], int values[]); + int setInt32(uint valueReferences[],int nvr, int values[],int nv); - int setUInt32(uint valueReferences[], int values[]); + int setUInt32(uint valueReferences[],int nvr, int values[],int nv); - int setInt64(uint valueReferences[], long values[]); + int setInt64(uint valueReferences[],int nvr, long values[],int nv); - int setUInt64(uint valueReferences[], long values[]); + int setUInt64(uint valueReferences[],int nvr, long values[],int nv); - int setBoolean(uint valueReferences[], bool values[]); + int setBoolean(uint valueReferences[],int nvr, bool values[],int nv); - int setString(uint valueReferences[], string values[]); + int setString(uint valueReferences[],int nvr, string values[],int nv); int setBinary(uint valueReferences[], long sizes[], byte array_name[][]); /* end::setters[] */