From 56d186b60d7904ed253b34995e6ff4543a16e09d Mon Sep 17 00:00:00 2001 From: Lennart Ochel Date: Wed, 6 May 2015 11:13:04 +0200 Subject: [PATCH] Separation of back end transformations... ... for simulation and initialization * Move initialization before post-optimization phase * Revert some CodegenC.tpl changes * Remove workaround for "symEuler" * Moved 'encapsulateWhenConditions' to pre-optimization phase * Cleanup known variables after 'remove simple equations' * Activate more modules for initialization - activate modules "simplifyComplexFunction" and "simplifyLoops" - Fixed module "simplifyLoops" for initialization * Moved each post-opt module to a new line * Moved module "simplifyLoops" from simulation to initialization * Don't add known vars to simulation system in post-optimization * Updated debug dumps * Fixed "Known Variables" again * Initialize relations properly * New opt module "removeInitializationStuff" - This module does simplifications by removing initialization information like homotopy(..) and initial() from simulation DAE. * Fixed Stubs files --- Compiler/BackEnd/BackendDAE.mo | 2 - Compiler/BackEnd/BackendDAEOptimize.mo | 14 +--- Compiler/BackEnd/BackendDAEUtil.mo | 68 +++++++-------- Compiler/BackEnd/BackendEquation.mo | 1 + Compiler/BackEnd/BackendVariable.mo | 16 ++++ Compiler/BackEnd/Initialization.mo | 82 +++++++++++++++++-- Compiler/BackEnd/OpenTURNS.mo | 10 ++- Compiler/BackEnd/RemoveSimpleEquations.mo | 79 ++++++++++++++++-- Compiler/Main/Main.mo | 17 +++- Compiler/SimCode/HpcOmSimCodeMain.mo | 13 +-- Compiler/SimCode/SimCodeMain.mo | 65 +++++++++++---- Compiler/SimCode/SimCodeUtil.mo | 25 ++---- Compiler/Stubs/BackendDAEUtil.mo | 5 ++ Compiler/Stubs/SimCodeMain.mo | 7 +- Compiler/Util/Flags.mo | 10 ++- .../solver/initialization/initialization.c | 7 +- .../c/simulation/solver/model_help.h | 6 +- 17 files changed, 310 insertions(+), 117 deletions(-) diff --git a/Compiler/BackEnd/BackendDAE.mo b/Compiler/BackEnd/BackendDAE.mo index 9689730752..68963e7825 100644 --- a/Compiler/BackEnd/BackendDAE.mo +++ b/Compiler/BackEnd/BackendDAE.mo @@ -33,8 +33,6 @@ encapsulated package BackendDAE " file: BackendDAE.mo package: BackendDAE description: BackendDAE contains the data-types used by the back end. - - RCS: $Id$ " public import Absyn; diff --git a/Compiler/BackEnd/BackendDAEOptimize.mo b/Compiler/BackEnd/BackendDAEOptimize.mo index 308bfc0efd..79606d96ef 100644 --- a/Compiler/BackEnd/BackendDAEOptimize.mo +++ b/Compiler/BackEnd/BackendDAEOptimize.mo @@ -4340,7 +4340,8 @@ algorithm functionTree := shared.functionTree; simDAE := match shared - case BackendDAE.SHARED(backendDAEType = BackendDAE.SIMULATION()) then true; + case BackendDAE.SHARED(backendDAEType=BackendDAE.SIMULATION()) then true; + case BackendDAE.SHARED(backendDAEType=BackendDAE.INITIALSYSTEM()) then true; else false; end match; @@ -4818,17 +4819,6 @@ public function symEuler algorithm outDAE := if Flags.getConfigBool(Flags.SYM_EULER) then symEulerWork(inDAE, true) else inDAE; end symEuler; -public function symEulerInit -" -fix the difference quotient for initial equations[0/0] -ToDo: remove me -" - input BackendDAE.BackendDAE inDAE; - output BackendDAE.BackendDAE outDAE; -algorithm - outDAE := if Flags.getConfigBool(Flags.SYM_EULER) then symEulerWork(BackendDAEUtil.copyBackendDAE(inDAE), false) else inDAE; - -end symEulerInit; protected function symEulerWork input BackendDAE.BackendDAE inDAE; diff --git a/Compiler/BackEnd/BackendDAEUtil.mo b/Compiler/BackEnd/BackendDAEUtil.mo index 146ba86154..1d10d7f506 100644 --- a/Compiler/BackEnd/BackendDAEUtil.mo +++ b/Compiler/BackEnd/BackendDAEUtil.mo @@ -34,8 +34,6 @@ encapsulated package BackendDAEUtil package: BackendDAEUtil description: BackendDAEUtil comprised functions for BackendDAE data types. - RCS: $Id$ - This module is a lowered form of a DAE including equations and simple equations in two separate lists. The variables are split into known variables @@ -62,8 +60,8 @@ protected import BackendDump; protected import BackendEquation; protected import BackendDAEEXT; protected import BackendInline; -protected import BackendVariable; protected import BackendVarTransform; +protected import BackendVariable; protected import BinaryTree; protected import Causalize; protected import Ceval; @@ -93,10 +91,12 @@ protected import HpcOmEqSystems; protected import HpcOmTaskGraph; protected import HpcOmSimCodeMain; protected import IndexReduction; +protected import Initialization; protected import Inline; protected import InlineArrayEquations; protected import List; protected import Matching; +protected import MetaModelica.Dangerous.listReverseInPlace; protected import OnRelaxation; protected import RemoveSimpleEquations; protected import ResolveLoops; @@ -112,7 +112,6 @@ protected import Types; protected import UnitCheck; protected import Values; protected import XMLDump; -protected import MetaModelica.Dangerous.listReverseInPlace; protected type Var = BackendDAE.Var; @@ -6494,6 +6493,11 @@ public function getSolvedSystem "Run the equation system pipeline." input Option strdaeHandler = NONE(); input Option> strPostOptModules = NONE(); output BackendDAE.BackendDAE outSODE; + output BackendDAE.BackendDAE outInitDAE; + output Boolean outUseHomotopy "true if homotopy(...) is used during initialization"; + output list outRemovedInitialEquationLst; + output list outPrimaryParameters "already sorted"; + output list outAllPrimaryParameters "already sorted"; protected BackendDAE.BackendDAE optdae, sode, sode1, optsode; list> preOptModules; @@ -6533,6 +6537,9 @@ algorithm sode := BackendDAEOptimize.evaluateOutputsOnly(sode); end if; + // generate system for initialization + (outInitDAE, outUseHomotopy, outRemovedInitialEquationLst, outPrimaryParameters, outAllPrimaryParameters) := Initialization.solveInitialSystem(sode); + // post-optimization phase optsode := postOptimizeDAE(sode, postOptModules, matchingAlgorithm, daeHandler); @@ -7192,7 +7199,8 @@ algorithm (CommonSubExpression.commonSubExpressionReplacement, "comSubExp", false), (CommonSubExpression.CSE_EachCall, "CSE_EachCall", false), (BackendDump.dumpDAE, "dumpDAE", false), - (XMLDump.dumpDAEXML, "dumpDAEXML", false) + (XMLDump.dumpDAEXML, "dumpDAEXML", false), + (FindZeroCrossings.encapsulateWhenConditions, "encapsulateWhenConditions", true) }; strPreOptModules := getPreOptModulesString(); strPreOptModules := Util.getOptionOrDefault(ostrPreOptModules,strPreOptModules); @@ -7210,10 +7218,10 @@ public function getPostOptModules input Option> ostrpostOptModules; output list> postOptModules; protected - list> allpostOptModules; + list> allpostOptModules; list strpostOptModules; algorithm - allpostOptModules := {(FindZeroCrossings.encapsulateWhenConditions, "encapsulateWhenConditions", true), + allpostOptModules := {(Initialization.removeInitializationStuff, "removeInitializationStuff", true), (BackendInline.lateInlineFunction, "lateInlineFunction", false), (RemoveSimpleEquations.removeSimpleEquations, "removeSimpleEquations", false), (BackendDAEOptimize.removeEqualFunctionCalls, "removeEqualFunctionCalls", false), @@ -7228,7 +7236,6 @@ algorithm (BackendDAEOptimize.removeUnusedParameter, "removeUnusedParameter", false), (BackendDAEOptimize.removeUnusedVariables, "removeUnusedVariables", false), (BackendDAEOptimize.symEuler, "symEuler", false), - (BackendDAEOptimize.symEulerInit, "symEulerInit", false), (SymbolicJacobian.constantLinearSystem, "constantLinearSystem", false), (OnRelaxation.relaxSystem, "relaxSystem", false), (BackendDAEOptimize.countOperations, "countOperations", false), @@ -7654,34 +7661,33 @@ protected function getConditionList1 "author: lochel" output list outConditionVarList; output Boolean outInitialCall; algorithm - (outConditionVarList, outInitialCall) := matchcontinue (inConditionList, inConditionVarList, inInitialCall) + (outConditionVarList, outInitialCall) := match inConditionList local list conditionList; list conditionVarList; Boolean initialCall; DAE.ComponentRef componentRef; DAE.Exp exp; - String msg; - case ({}, _, _) - then (inConditionVarList, inInitialCall); + case {} + then (inConditionVarList, inInitialCall); - case (DAE.CALL(path = Absyn.IDENT(name = "initial"))::conditionList, _, _) - equation - (conditionVarList, initialCall) = getConditionList1(conditionList, inConditionVarList, true); - then (conditionVarList, initialCall); + case DAE.BCONST(false)::conditionList equation + (conditionVarList, initialCall) = getConditionList1(conditionList, inConditionVarList, inInitialCall); + then (conditionVarList, initialCall); - case (DAE.CREF(componentRef=componentRef)::conditionList, _, _) - equation - (conditionVarList, initialCall) = getConditionList1(conditionList, componentRef::inConditionVarList, inInitialCall); - then (conditionVarList, initialCall); + case DAE.CALL(path=Absyn.IDENT(name="initial"))::conditionList equation + (conditionVarList, initialCall) = getConditionList1(conditionList, inConditionVarList, true); + then (conditionVarList, initialCall); - case (exp::_, _ ,_) - equation - msg = "./Compiler/BackEnd/BackendDAEUtil.mo: function getConditionList1 failed for " + ExpressionDump.printExpStr(exp) + "\n"; - Error.addMessage(Error.INTERNAL_ERROR, {msg}); - then fail(); - end matchcontinue; + case DAE.CREF(componentRef=componentRef)::conditionList equation + (conditionVarList, initialCall) = getConditionList1(conditionList, componentRef::inConditionVarList, inInitialCall); + then (conditionVarList, initialCall); + + case exp::_ equation + Error.addInternalError("function getConditionList1 failed for " + ExpressionDump.printExpStr(exp), sourceInfo()); + then fail(); + end match; end getConditionList1; public function isArrayComp"outputs true if the strongComponent is an arrayEquation" @@ -8093,15 +8099,9 @@ end setSharedEventInfo; public function setSharedKnVars input BackendDAE.Shared inShared; input BackendDAE.Variables knownVars; - output BackendDAE.Shared outShared; + output BackendDAE.Shared outShared = inShared; algorithm - outShared := match inShared - local - BackendDAE.Shared shared; - case shared as BackendDAE.SHARED() - algorithm shared.knownVars := knownVars; - then shared; - end match; + outShared.knownVars := knownVars; end setSharedKnVars; public function setSharedAliasVars diff --git a/Compiler/BackEnd/BackendEquation.mo b/Compiler/BackEnd/BackendEquation.mo index 38fea5bb85..fe639e0ee6 100644 --- a/Compiler/BackEnd/BackendEquation.mo +++ b/Compiler/BackEnd/BackendEquation.mo @@ -2479,6 +2479,7 @@ algorithm b := listEmpty(inputsKnVars); end if; + b := false "hack"; if b then if noPara then oExp := ExpressionSimplify.simplify(iExp); diff --git a/Compiler/BackEnd/BackendVariable.mo b/Compiler/BackEnd/BackendVariable.mo index 34f262a1cf..4b5a56b80d 100644 --- a/Compiler/BackEnd/BackendVariable.mo +++ b/Compiler/BackEnd/BackendVariable.mo @@ -2449,6 +2449,22 @@ algorithm end try; end existsVar; +public function existsAnyVar +"author: PA + Return true if a variable exists in the vector" + input list inComponentRefs; + input BackendDAE.Variables inVariables; + input Boolean skipDiscrete = false; + output Boolean outExists = false; +algorithm + for cref in inComponentRefs loop + if existsVar(cref, inVariables, skipDiscrete) and not isState(cref, inVariables) then + outExists := true; + break; + end if; + end for; +end existsAnyVar; + public function makeVar input DAE.ComponentRef cr; output BackendDAE.Var v = BackendDAE.VAR(cr, BackendDAE.VARIABLE(), DAE.BIDIR(), DAE.NON_PARALLEL(), DAE.T_REAL_DEFAULT, NONE(), NONE(), {}, DAE.emptyElementSource, NONE(), NONE(), NONE(), DAE.NON_CONNECTOR(), DAE.NOT_INNER_OUTER(), false); diff --git a/Compiler/BackEnd/Initialization.mo b/Compiler/BackEnd/Initialization.mo index 490fe7aff5..732fe76fc8 100644 --- a/Compiler/BackEnd/Initialization.mo +++ b/Compiler/BackEnd/Initialization.mo @@ -34,8 +34,7 @@ encapsulated package Initialization package: Initialization description: Initialization.mo contains everything needed to set up the BackendDAE for the initial system. - - RCS: $Id$" +" public import Absyn; public import BackendDAE; @@ -99,15 +98,20 @@ protected tuple matchingAlgorithm; algorithm try - // TODO: remove this once the initialization is moved before post-optimization - dae := BackendDAEOptimize.symEulerInit(inDAE); + //if Flags.isSet(Flags.DUMP_INITIAL_SYSTEM) then + // BackendDump.dumpBackendDAE(inDAE, "inDAE for initialization"); + //end if; // inline all when equations, if active with body else with lhs=pre(lhs) - dae := inlineWhenForInitialization(dae); - // fcall2(Flags.DUMP_INITIAL_SYSTEM, BackendDump.dumpBackendDAE, dae, "inlineWhenForInitialization"); + dae := inlineWhenForInitialization(inDAE); + //if Flags.isSet(Flags.DUMP_INITIAL_SYSTEM) then + // BackendDump.dumpBackendDAE(dae, "inlineWhenForInitialization"); + //end if; (initVars, outPrimaryParameters, outAllPrimaryParameters) := selectInitializationVariablesDAE(dae); - // fcall2(Flags.DUMP_INITIAL_SYSTEM, BackendDump.dumpVariables, initVars, "selected initialization variables"); + //if Flags.isSet(Flags.DUMP_INITIAL_SYSTEM) then + // BackendDump.dumpVariables(initVars, "selected initialization variables"); + //end if; hs := collectPreVariables(dae); // collect vars and eqns for initial system @@ -120,7 +124,9 @@ algorithm ((vars, fixvars, eqns, _)) := BackendVariable.traverseBackendDAEVars(dae.shared.knownVars, collectInitialVars, (vars, fixvars, eqns, hs)); ((eqns, reeqns)) := BackendEquation.traverseEquationArray(dae.shared.initialEqs, collectInitialEqns, (eqns, reeqns)); - // fcall2(Flags.DUMP_INITIAL_SYSTEM, BackendDump.dumpEquationArray, eqns, "initial equations"); + //if Flags.isSet(Flags.DUMP_INITIAL_SYSTEM) then + // BackendDump.dumpEquationArray(eqns, "initial equations"); + //end if; ((vars, fixvars, eqns, reeqns, _)) := List.fold(dae.eqs, collectInitialVarsEqnsSystem, ((vars, fixvars, eqns, reeqns, hs))); @@ -172,7 +178,19 @@ algorithm initdae := BackendDAEUtil.mapEqSystem(initdae, solveInitialSystemEqSystem); // transform and optimize DAE - pastOptModules := BackendDAEUtil.getPostOptModules(SOME({"constantLinearSystem", "tearingSystem", "calculateStrongComponentJacobians", "solveSimpleEquations"})); + pastOptModules := BackendDAEUtil.getPostOptModules(SOME({ + "constantLinearSystem", + "simplifyComplexFunction", + //"reduceDynamicOptimization", // before tearing + "tearingSystem", + "simplifyLoops", + "recursiveTearing", + "calculateStrongComponentJacobians", + "solveSimpleEquations" + //"inputDerivativesUsed", + //"extendDynamicOptimization" + })); + matchingAlgorithm := BackendDAEUtil.getMatchingAlgorithm(NONE()); daeHandler := BackendDAEUtil.getIndexReductionMethod(NONE()); @@ -2310,5 +2328,51 @@ algorithm end match; end collectInitialBindings; + +// ============================================================================= +// section for post-optimization module "removeInitializationStuff" +// +// ============================================================================= + +public function removeInitializationStuff + input BackendDAE.BackendDAE inDAE; + output BackendDAE.BackendDAE outDAE = inDAE; +algorithm + for eqs in outDAE.eqs loop + _ := BackendDAEUtil.traverseBackendDAEExpsEqnsWithUpdate(eqs.orderedEqs, removeInitializationStuff1, false); + end for; +end removeInitializationStuff; + +protected function removeInitializationStuff1 + input DAE.Exp inExp; + input Boolean inUseHomotopy; + output DAE.Exp outExp; + output Boolean outUseHomotopy; +algorithm + (outExp, outUseHomotopy) := Expression.traverseExpBottomUp(inExp, removeInitializationStuff2, inUseHomotopy); +end removeInitializationStuff1; + +protected function removeInitializationStuff2 + input DAE.Exp inExp; + input Boolean inUseHomotopy; + output DAE.Exp outExp; + output Boolean outUseHomotopy; +algorithm + (outExp, outUseHomotopy) := match (inExp, inUseHomotopy) + local + DAE.Exp e1, e2, e3, actual, simplified; + + // replace initial() with false + case (DAE.CALL(path=Absyn.IDENT(name="initial")), _) + then (DAE.BCONST(false), inUseHomotopy); + + // replace homotopy(actual, simplified) with actual + case (DAE.CALL(path=Absyn.IDENT(name="homotopy"), expLst=actual::simplified::_), _) + then (actual, true); + + else (inExp, inUseHomotopy); + end match; +end removeInitializationStuff2; + annotation(__OpenModelica_Interface="backend"); end Initialization; diff --git a/Compiler/BackEnd/OpenTURNS.mo b/Compiler/BackEnd/OpenTURNS.mo index 7fe51074e0..e2ec5a3c44 100644 --- a/Compiler/BackEnd/OpenTURNS.mo +++ b/Compiler/BackEnd/OpenTURNS.mo @@ -88,6 +88,11 @@ public function generateOpenTURNSInterface "generates the dll and the python scr list libs; BackendDAE.BackendDAE dae,strippedDae; SimCode.SimulationSettings simSettings; + BackendDAE.BackendDAE initDAE; + Boolean useHomotopy "true if homotopy(...) is used during initialization"; + list removedInitialEquationLst; + list primaryParameters "already sorted"; + list allPrimaryParameters "already sorted"; algorithm cname_str := Absyn.pathString(inPath); cname_last_str := Absyn.pathLastIdent(inPath); @@ -108,12 +113,13 @@ algorithm // Strip correlation vector from dae to be able to compile (bug in OpenModelica with vectors of records ) strippedDae := stripCorrelationFromDae(inDaelow); - strippedDae := BackendDAEUtil.getSolvedSystem(strippedDae,""); + (strippedDae, initDAE, useHomotopy, removedInitialEquationLst, primaryParameters, allPrimaryParameters) := BackendDAEUtil.getSolvedSystem(strippedDae,""); //print("strippedDae :"); //BackendDump.dump(strippedDae); _ := System.realtimeTock(ClockIndexes.RT_CLOCK_BACKEND); // Is this necessary? - (libs, fileDir, _, _) := SimCodeMain.generateModelCode(strippedDae, inProgram, inPath, cname_str, SOME(simSettings), Absyn.FUNCTIONARGS({}, {})); + + (libs, fileDir, _, _) := SimCodeMain.generateModelCode(strippedDae, initDAE, useHomotopy, removedInitialEquationLst, primaryParameters, allPrimaryParameters,inProgram, inPath, cname_str, SOME(simSettings), Absyn.FUNCTIONARGS({}, {})); //print("..compiling, fileNamePrefix = "+fileNamePrefix+"\n"); CevalScript.compileModel(fileNamePrefix , libs); diff --git a/Compiler/BackEnd/RemoveSimpleEquations.mo b/Compiler/BackEnd/RemoveSimpleEquations.mo index 6f4bfea2cd..e813b3aae2 100644 --- a/Compiler/BackEnd/RemoveSimpleEquations.mo +++ b/Compiler/BackEnd/RemoveSimpleEquations.mo @@ -43,9 +43,7 @@ encapsulated package RemoveSimpleEquations " the function may needs a lots of time. causal: to remove with a linear scaling with respect to the number of equations in an causal system all - simple equations - - RCS: $Id: RemoveSimpleEquations.mo 14235 2012-12-05 04:34:35Z wbraun $" + simple equations" public import Absyn; public import BackendDAE; @@ -164,7 +162,7 @@ algorithm end match; outDAE := fixAliasVars(outDAE) "workaround for #3323"; - outDAE := fixAliasVarsCausal(inDAE, outDAE); + outDAE := fixAliasAndKnownVarsCausal(inDAE, outDAE); else // This case performs "remove simple equations" on an acausal system. outDAE := match(Flags.getConfigString(Flags.REMOVE_SIMPLE_EQUATIONS)) @@ -208,7 +206,7 @@ algorithm outDAE := BackendDAEUtil.setKnownVars(outDAE, BackendVariable.listVar(knownVarList)); end fixAliasVars; -protected function fixAliasVarsCausal "author: lochel +protected function fixAliasAndKnownVarsCausal "author: lochel TODO: Remove this once removeSimpleEquations is implemented properly. This module moves back all newly introduced alias variables to the correct partition." @@ -216,14 +214,18 @@ protected function fixAliasVarsCausal "author: lochel input BackendDAE.BackendDAE inDAE2 "transformed dae"; output BackendDAE.BackendDAE outDAE = inDAE2; protected - BackendDAE.Variables aliasVars1; - BackendDAE.Variables aliasVars2; + BackendDAE.Variables aliasVars1, knownVars1; + BackendDAE.Variables aliasVars2, knownVars2; list aliasVarList = {}; + list knownVarList = {}; DAE.ComponentRef cref; algorithm aliasVars1 := BackendDAEUtil.getAliasVars(inDAE1); aliasVars2 := BackendDAEUtil.getAliasVars(inDAE2); + knownVars1 := BackendDAEUtil.getKnownVars(inDAE1); + knownVars2 := BackendDAEUtil.getKnownVars(inDAE2); + for var in BackendVariable.varList(aliasVars2) loop cref := BackendVariable.varCref(var); if not BackendVariable.existsVar(cref, aliasVars1, false) then @@ -233,9 +235,21 @@ algorithm aliasVarList := var::aliasVarList; end if; end for; - outDAE := BackendDAEUtil.setAliasVars(outDAE, BackendVariable.listVar(aliasVarList)); -end fixAliasVarsCausal; + + //BackendDump.dumpVarList(knownVarList, "knownVarList in"); + for var in BackendVariable.varList(knownVars2) loop + cref := BackendVariable.varCref(var); + if not BackendVariable.existsVar(cref, knownVars1, false) and (not BackendVariable.isInput(var)) then + // put var back to the correct partition + outDAE := fixKnownVarsCausal2(var, outDAE); + else + knownVarList := var::knownVarList; + end if; + end for; + //BackendDump.dumpVarList(knownVarList, "knownVarList out"); + outDAE := BackendDAEUtil.setKnownVars(outDAE, BackendVariable.listVar(knownVarList)); +end fixAliasAndKnownVarsCausal; protected function fixAliasVarsCausal2 input BackendDAE.Var inVar; @@ -289,6 +303,53 @@ algorithm end try; end fixAliasVarsCausal2; +protected function fixKnownVarsCausal2 + input BackendDAE.Var inVar; + input BackendDAE.BackendDAE inDAE; + output BackendDAE.BackendDAE outDAE; +protected + DAE.Exp binding; + list rightCrefs; + BackendDAE.EqSystems eqs1 = {}; + Boolean done=false; + + BackendDAE.Var var; + BackendDAE.Equation eqn; + + BackendDAE.Variables orderedVars "ordered Variables, only states and alg. vars"; + BackendDAE.EquationArray orderedEqs "ordered Equations"; +algorithm + try + binding := BackendVariable.varBindExp(inVar); + rightCrefs := Expression.getAllCrefs(binding); + var := BackendVariable.setBindExp(inVar, NONE()); + eqn := BackendDAE.EQUATION(BackendVariable.varExp(var), binding, DAE.emptyElementSource, BackendDAE.EQ_ATTR_DEFAULT_BINDING); + for eq in inDAE.eqs loop + BackendDAE.EQSYSTEM(orderedVars=orderedVars, orderedEqs=orderedEqs) := eq; + if BackendVariable.existsAnyVar(rightCrefs, orderedVars, false) then + orderedVars := BackendVariable.addVar(var, orderedVars); + orderedEqs := BackendEquation.addEquation(eqn, orderedEqs); + eqs1 := BackendDAEUtil.setEqSystEqs(BackendDAEUtil.setEqSystVars(eq, orderedVars), orderedEqs)::eqs1; + false := done; + done := true; + else + eqs1 := eq::eqs1; + end if; + end for; + + // if no partition was selected, create a new one + if not done then + eqs1 := BackendDAEUtil.createEqSystem( BackendVariable.listVar({var}), BackendEquation.listEquation({eqn}), + {}, BackendDAE.UNSPECIFIED_PARTITION() )::eqs1; + end if; + outDAE := BackendDAE.DAE(listReverse(eqs1), inDAE.shared); + else + BackendDump.dumpVarList({inVar}, "fixKnownVarsCausal2 failed for ..."); + Error.addCompilerError("fixKnownVarsCausal2 failed"); + fail(); + end try; +end fixKnownVarsCausal2; + // ============================================================================= // section for fastAcausal // diff --git a/Compiler/Main/Main.mo b/Compiler/Main/Main.mo index 5ba0583c01..4419db81a7 100644 --- a/Compiler/Main/Main.mo +++ b/Compiler/Main/Main.mo @@ -593,18 +593,28 @@ protected function optimizeDae protected BackendDAE.ExtraInfo info; BackendDAE.BackendDAE dlow; + BackendDAE.BackendDAE initDAE; + Boolean useHomotopy "true if homotopy(...) is used during initialization"; + list removedInitialEquationLst; + list primaryParameters "already sorted"; + list allPrimaryParameters "already sorted"; algorithm if Config.simulationCg() then info := BackendDAE.EXTRA_INFO(DAEUtil.daeDescription(dae), Absyn.pathString(inClassName)); dlow := BackendDAECreate.lower(dae, inCache, inEnv, info); - dlow := BackendDAEUtil.getSolvedSystem(dlow, ""); - simcodegen(dlow, inClassName, ap); + (dlow, initDAE, useHomotopy, removedInitialEquationLst, primaryParameters, allPrimaryParameters) := BackendDAEUtil.getSolvedSystem(dlow, ""); + simcodegen(dlow, initDAE, useHomotopy, removedInitialEquationLst, primaryParameters, allPrimaryParameters, inClassName, ap); end if; end optimizeDae; protected function simcodegen " Genereates simulation code using the SimCode module" input BackendDAE.BackendDAE inBackendDAE; + input BackendDAE.BackendDAE inInitDAE; + input Boolean inUseHomotopy "true if homotopy(...) is used during initialization"; + input list inRemovedInitialEquationLst; + input list inPrimaryParameters "already sorted"; + input list inAllPrimaryParameters "already sorted"; input Absyn.Path inClassName; input Absyn.Program inProgram; protected @@ -624,7 +634,8 @@ algorithm SimCodeMain.createSimulationSettings(0.0, 1.0, 500, 1e-6, "dassl", "", "mat", ".*", ""); System.realtimeTock(ClockIndexes.RT_CLOCK_BACKEND); // Is this necessary? - SimCodeMain.generateModelCode(inBackendDAE, inProgram, inClassName, cname, SOME(sim_settings), Absyn.FUNCTIONARGS({}, {})); + SimCodeMain.generateModelCode(inBackendDAE, inInitDAE, inUseHomotopy, inRemovedInitialEquationLst, inPrimaryParameters, inAllPrimaryParameters, inProgram, inClassName, cname, SOME(sim_settings), Absyn.FUNCTIONARGS({}, {})); + SimCodeFunctionUtil.execStat("Codegen Done"); end if; end simcodegen; diff --git a/Compiler/SimCode/HpcOmSimCodeMain.mo b/Compiler/SimCode/HpcOmSimCodeMain.mo index fdfab66ac9..4141113980 100644 --- a/Compiler/SimCode/HpcOmSimCodeMain.mo +++ b/Compiler/SimCode/HpcOmSimCodeMain.mo @@ -67,6 +67,11 @@ protected import Util; public function createSimCode "function createSimCode entry point to create SimCode from BackendDAE." input BackendDAE.BackendDAE inBackendDAE; + input BackendDAE.BackendDAE inInitDAE; + input Boolean inUseHomotopy "true if homotopy(...) is used during initialization"; + input list inRemovedInitialEquationLst; + input list inPrimaryParameters "already sorted"; + input list inAllPrimaryParameters "already sorted"; input Absyn.Path inClassName; input String filenamePrefix; input String inString11; @@ -87,7 +92,7 @@ algorithm Integer lastEqMappingIdx, maxDelayedExpIndex, uniqueEqIndex, numberofEqns, numberOfInitialEquations, numberOfInitialAlgorithms, numStateSets; Integer numberofLinearSys, numberofNonLinearSys, numberofMixedSys; BackendDAE.BackendDAE dlow, dlow2; - Option initDAE; + BackendDAE.BackendDAE initDAE; BackendDAE.IncidenceMatrix incidenceMatrix; DAE.FunctionTree functionTree; BackendDAE.SymbolicJacobians symJacs; @@ -182,15 +187,13 @@ algorithm case (BackendDAE.DAE(eqs=eqs), _, _, _, _,_, _, _, _, _, _, _, _) equation //Initial System //-------------- - //(initDAE, _, _) = Initialization.solveInitialSystem(inBackendDAE); - //removedInitialEquations = {}; - //createAndExportInitialSystemTaskGraph(initDAE, filenamePrefix); + //createAndExportInitialSystemTaskGraph(inInitDAE, filenamePrefix); //Setup //----- System.realtimeTick(ClockIndexes.RT_CLOCK_EXECSTAT_HPCOM_MODULES); (simCode,(lastEqMappingIdx,equationSccMapping)) = - SimCodeUtil.createSimCode( inBackendDAE, inClassName, filenamePrefix, inString11, functions, + SimCodeUtil.createSimCode( inBackendDAE, inInitDAE, inUseHomotopy, inRemovedInitialEquationLst, inPrimaryParameters, inAllPrimaryParameters, inClassName, filenamePrefix, inString11, functions, externalFunctionIncludes, includeDirs, libs,libPaths, simSettingsOpt, recordDecls, literals, args ); simVarMapping = SimCodeUtil.getSimVarMappingOfBackendMapping(simCode.backendMapping); diff --git a/Compiler/SimCode/SimCodeMain.mo b/Compiler/SimCode/SimCodeMain.mo index ee1ce01847..fc3176ce23 100644 --- a/Compiler/SimCode/SimCodeMain.mo +++ b/Compiler/SimCode/SimCodeMain.mo @@ -115,6 +115,11 @@ protected function generateModelCodeFMU " Generates code for a model by creating a SimCode structure and calling the template-based code generator on it." input BackendDAE.BackendDAE inBackendDAE; + input BackendDAE.BackendDAE inInitDAE; + input Boolean inUseHomotopy "true if homotopy(...) is used during initialization"; + input list inRemovedInitialEquationLst; + input list inPrimaryParameters "already sorted"; + input list inAllPrimaryParameters "already sorted"; input Absyn.Program p; input Absyn.Path className; input String FMUVersion; @@ -141,8 +146,8 @@ algorithm fileDir := CevalScriptBackend.getFileDir(a_cref, p); (libs,libPaths,includes, includeDirs, recordDecls, functions, literals) := SimCodeUtil.createFunctions(p, inBackendDAE); - simCode := createSimCode(inBackendDAE, - className, filenamePrefix, fileDir, functions, includes, includeDirs, libs, libPaths, simSettingsOpt, recordDecls, literals,Absyn.FUNCTIONARGS({},{})); + simCode := createSimCode(inBackendDAE, inInitDAE, inUseHomotopy, inRemovedInitialEquationLst, inPrimaryParameters, inAllPrimaryParameters, + className, filenamePrefix, fileDir, functions, includes, includeDirs, libs, libPaths, simSettingsOpt, recordDecls, literals, Absyn.FUNCTIONARGS({},{})); timeSimCode := System.realtimeTock(ClockIndexes.RT_CLOCK_SIMCODE); SimCodeFunctionUtil.execStat("SimCode"); @@ -156,6 +161,11 @@ protected function generateModelCodeXML " Generates code for a model by creating a SimCode structure and calling the template-based code generator on it." input BackendDAE.BackendDAE inBackendDAE; + input BackendDAE.BackendDAE inInitDAE; + input Boolean inUseHomotopy "true if homotopy(...) is used during initialization"; + input list inRemovedInitialEquationLst; + input list inPrimaryParameters "already sorted"; + input list inAllPrimaryParameters "already sorted"; input Absyn.Program p; input Absyn.Path className; input String filenamePrefix; @@ -180,7 +190,7 @@ algorithm fileDir := CevalScriptBackend.getFileDir(a_cref, p); (libs, libPaths, includes, includeDirs, recordDecls, functions, literals) := SimCodeUtil.createFunctions(p, inBackendDAE); - (simCode,_) := SimCodeUtil.createSimCode(inBackendDAE, + (simCode,_) := SimCodeUtil.createSimCode(inBackendDAE, inInitDAE, inUseHomotopy, inRemovedInitialEquationLst, inPrimaryParameters, inAllPrimaryParameters, className, filenamePrefix, fileDir, functions, includes, includeDirs, libs,libPaths, simSettingsOpt, recordDecls, literals,Absyn.FUNCTIONARGS({},{})); timeSimCode := System.realtimeTock(ClockIndexes.RT_CLOCK_SIMCODE); SimCodeFunctionUtil.execStat("SimCode"); @@ -230,6 +240,11 @@ algorithm Boolean symbolicJacActivated; Boolean fmi20; Boolean flagValue; + BackendDAE.BackendDAE initDAE; + Boolean useHomotopy "true if homotopy(...) is used during initialization"; + list removedInitialEquationLst; + list primaryParameters "already sorted"; + list allPrimaryParameters "already sorted"; case (cache,graph,_,st as GlobalScript.SYMBOLTABLE(ast=p),FMUVersion,FMUType,filenameprefix,_, _) equation @@ -251,11 +266,11 @@ algorithm dae = DAEUtil.transformationsBeforeBackend(cache,graph,dae); description = DAEUtil.daeDescription(dae); dlow = BackendDAECreate.lower(dae, cache, graph, BackendDAE.EXTRA_INFO(description,filenameprefix)); - dlow_1 = BackendDAEUtil.getSolvedSystem(dlow,inFileNamePrefix); + (dlow_1, initDAE, useHomotopy, removedInitialEquationLst, primaryParameters, allPrimaryParameters) = BackendDAEUtil.getSolvedSystem(dlow, inFileNamePrefix); timeBackend = System.realtimeTock(ClockIndexes.RT_CLOCK_BACKEND); (libs,file_dir,timeSimCode,timeTemplates) = - generateModelCodeFMU(dlow_1, p, className, FMUVersion, FMUType, filenameprefix, inSimSettingsOpt); + generateModelCodeFMU(dlow_1, initDAE, useHomotopy, removedInitialEquationLst, primaryParameters, allPrimaryParameters, p, className, FMUVersion, FMUType, filenameprefix, inSimSettingsOpt); //reset config flag Flags.setConfigBool(Flags.GENERATE_SYMBOLIC_LINEARIZATION, symbolicJacActivated); @@ -315,6 +330,12 @@ algorithm FCore.Cache cache; DAE.FunctionTree funcs; Real timeSimCode, timeTemplates, timeBackend, timeFrontend; + BackendDAE.BackendDAE initDAE; + Boolean useHomotopy "true if homotopy(...) is used during initialization"; + list removedInitialEquationLst; + list primaryParameters "already sorted"; + list allPrimaryParameters "already sorted"; + case (cache,graph,_,st as GlobalScript.SYMBOLTABLE(ast=p),filenameprefix,_, _) equation /* calculate stuff that we need to create SimCode data structure */ @@ -327,11 +348,11 @@ algorithm dae = DAEUtil.transformationsBeforeBackend(cache,graph,dae); description = DAEUtil.daeDescription(dae); dlow = BackendDAECreate.lower(dae, cache, graph, BackendDAE.EXTRA_INFO(description,filenameprefix)); - dlow_1 = BackendDAEUtil.getSolvedSystem(dlow,inFileNamePrefix); + (dlow_1, initDAE, useHomotopy, removedInitialEquationLst, primaryParameters, allPrimaryParameters) = BackendDAEUtil.getSolvedSystem(dlow,inFileNamePrefix); timeBackend = System.realtimeTock(ClockIndexes.RT_CLOCK_BACKEND); (libs,file_dir,timeSimCode,timeTemplates) = - generateModelCodeXML(dlow_1, p, className, filenameprefix, inSimSettingsOpt); + generateModelCodeXML(dlow_1, initDAE, useHomotopy, removedInitialEquationLst, primaryParameters, allPrimaryParameters, p, className, filenameprefix, inSimSettingsOpt); resultValues = {("timeTemplates",Values.REAL(timeTemplates)), ("timeSimCode", Values.REAL(timeSimCode)), @@ -358,6 +379,11 @@ public function generateModelCode " Generates code for a model by creating a SimCode structure and calling the template-based code generator on it." input BackendDAE.BackendDAE inBackendDAE; + input BackendDAE.BackendDAE inInitDAE; + input Boolean inUseHomotopy "true if homotopy(...) is used during initialization"; + input list inRemovedInitialEquationLst; + input list inPrimaryParameters "already sorted"; + input list inAllPrimaryParameters "already sorted"; input Absyn.Program p; input Absyn.Path className; input String filenamePrefix; @@ -381,8 +407,9 @@ algorithm System.realtimeTick(ClockIndexes.RT_CLOCK_SIMCODE); a_cref := Absyn.pathToCref(className); fileDir := CevalScriptBackend.getFileDir(a_cref, p); - (libs, libPaths,includes, includeDirs, recordDecls, functions, literals) := SimCodeUtil.createFunctions(p, inBackendDAE); - simCode := createSimCode(inBackendDAE, className, filenamePrefix, fileDir, functions, includes, includeDirs, libs,libPaths, simSettingsOpt, recordDecls, literals, args); + + (libs, libPaths, includes, includeDirs, recordDecls, functions, literals) := SimCodeUtil.createFunctions(p, inBackendDAE); + simCode := createSimCode(inBackendDAE, inInitDAE, inUseHomotopy, inRemovedInitialEquationLst, inPrimaryParameters, inAllPrimaryParameters, className, filenamePrefix, fileDir, functions, includes, includeDirs, libs,libPaths, simSettingsOpt, recordDecls, literals, args); timeSimCode := System.realtimeTock(ClockIndexes.RT_CLOCK_SIMCODE); SimCodeFunctionUtil.execStat("SimCode"); @@ -395,6 +422,11 @@ end generateModelCode; protected function createSimCode " SimCode generator switch - if the NUMPROC-Flag is set, the simcode will be extended with parallel informations." input BackendDAE.BackendDAE inBackendDAE; + input BackendDAE.BackendDAE inInitDAE; + input Boolean inUseHomotopy "true if homotopy(...) is used during initialization"; + input list inRemovedInitialEquationLst; + input list inPrimaryParameters "already sorted"; + input list inAllPrimaryParameters "already sorted"; input Absyn.Path inClassName; input String filenamePrefix; input String inString11; @@ -425,7 +457,7 @@ algorithm numProc = Flags.getConfigInt(Flags.NUM_PROC); true = numProc == 0; print("hpcom computes the ideal number of processors. If you want to set the number manually, use the flag +n=_ \n"); - then HpcOmSimCodeMain.createSimCode(inBackendDAE, inClassName, filenamePrefix, inString11, functions, externalFunctionIncludes, includeDirs, libs,libPaths, simSettingsOpt, recordDecls, literals, args); + then HpcOmSimCodeMain.createSimCode(inBackendDAE, inInitDAE, inUseHomotopy, inRemovedInitialEquationLst, inPrimaryParameters, inAllPrimaryParameters, inClassName, filenamePrefix, inString11, functions, externalFunctionIncludes, includeDirs, libs,libPaths, simSettingsOpt, recordDecls, literals, args); case(_, _, _, _, _, _, _, _, _,_, _, _, _) equation true = Flags.isSet(Flags.HPCOM); @@ -437,10 +469,10 @@ algorithm numProc = Flags.getConfigInt(Flags.NUM_PROC); true = (numProc > 0); - then HpcOmSimCodeMain.createSimCode(inBackendDAE, inClassName, filenamePrefix, inString11, functions, externalFunctionIncludes, includeDirs, libs, libPaths,simSettingsOpt, recordDecls, literals, args); + then HpcOmSimCodeMain.createSimCode(inBackendDAE, inInitDAE, inUseHomotopy, inRemovedInitialEquationLst, inPrimaryParameters, inAllPrimaryParameters, inClassName, filenamePrefix, inString11, functions, externalFunctionIncludes, includeDirs, libs, libPaths,simSettingsOpt, recordDecls, literals, args); else equation - (tmpSimCode, _) = SimCodeUtil.createSimCode(inBackendDAE, inClassName, filenamePrefix, inString11, functions, externalFunctionIncludes, includeDirs, libs,libPaths, simSettingsOpt, recordDecls, literals, args); + (tmpSimCode, _) = SimCodeUtil.createSimCode(inBackendDAE, inInitDAE, inUseHomotopy, inRemovedInitialEquationLst, inPrimaryParameters, inAllPrimaryParameters, inClassName, filenamePrefix, inString11, functions, externalFunctionIncludes, includeDirs, libs,libPaths, simSettingsOpt, recordDecls, literals, args); then tmpSimCode; end matchcontinue; end createSimCode; @@ -626,6 +658,11 @@ algorithm //DAE.Exp fileprefix; FCore.Cache cache; Real timeSimCode, timeTemplates, timeBackend, timeFrontend; + BackendDAE.BackendDAE initDAE; + Boolean useHomotopy "true if homotopy(...) is used during initialization"; + list removedInitialEquationLst; + list primaryParameters "already sorted"; + list allPrimaryParameters "already sorted"; case (cache, graph, _, (st as GlobalScript.SYMBOLTABLE(ast=p)), filenameprefix, _, _, _) equation // calculate stuff that we need to create SimCode data structure @@ -642,11 +679,11 @@ algorithm description = DAEUtil.daeDescription(dae); dlow = BackendDAECreate.lower(dae, cache, graph, BackendDAE.EXTRA_INFO(description,filenameprefix)); //BackendDump.printBackendDAE(dlow); - dlow_1 = BackendDAEUtil.getSolvedSystem(dlow,inFileNamePrefix); + (dlow_1, initDAE, useHomotopy, removedInitialEquationLst, primaryParameters, allPrimaryParameters) = BackendDAEUtil.getSolvedSystem(dlow,inFileNamePrefix); timeBackend = System.realtimeTock(ClockIndexes.RT_CLOCK_BACKEND); (libs, file_dir, timeSimCode, timeTemplates) = - generateModelCode(dlow_1, p, className, filenameprefix, inSimSettingsOpt, args); + generateModelCode(dlow_1, initDAE, useHomotopy, removedInitialEquationLst, primaryParameters, allPrimaryParameters, p, className, filenameprefix, inSimSettingsOpt, args); resultValues = {("timeTemplates", Values.REAL(timeTemplates)), ("timeSimCode", Values.REAL(timeSimCode)), diff --git a/Compiler/SimCode/SimCodeUtil.mo b/Compiler/SimCode/SimCodeUtil.mo index af453eb877..76fd270015 100644 --- a/Compiler/SimCode/SimCodeUtil.mo +++ b/Compiler/SimCode/SimCodeUtil.mo @@ -86,12 +86,10 @@ import Expression; import ExpressionDump; import ExpressionSimplify; import ExpressionSolve; -import FindZeroCrossings; import Flags; import Graph; import HashSet; import HpcOmSimCode; -import Initialization; import Inline; import List; import Matching; @@ -150,6 +148,11 @@ end simulationFindLiterals; public function createSimCode "entry point to create SimCode from BackendDAE." input BackendDAE.BackendDAE inBackendDAE; + input BackendDAE.BackendDAE inInitDAE; + input Boolean inUseHomotopy "true if homotopy(...) is used during initialization"; + input list inRemovedInitialEquationLst; + input list inPrimaryParameters "already sorted"; + input list inAllPrimaryParameters "already sorted"; input Absyn.Path inClassName; input String filenamePrefix; input String inFileDir; @@ -173,7 +176,6 @@ protected BackendDAE.SymbolicJacobians symJacs; BackendDAE.Variables knownVars; Boolean ifcpp; - Boolean useHomotopy "true if homotopy(...) is used during initialization"; HashTableCrIListArray.HashTable varToArrayIndexMapping "maps each array-variable to a array of positions"; HashTableCrILst.HashTable varToIndexMapping "maps each variable to an array position"; Integer maxDelayedExpIndex, uniqueEqIndex, numberofEqns, numStateSets, numberOfJacobians, sccOffset; @@ -221,6 +223,7 @@ protected algorithm try dlow := inBackendDAE; + initDAE := inInitDAE; System.tmpTickReset(0); uniqueEqIndex := 1; @@ -236,16 +239,6 @@ algorithm VisualXML.visualizationInfoXML(dlow, filenamePrefix); end if; - // fcall(Flags.FAILTRACE, print, "is that Cpp? : " + Dump.printBoolStr(ifcpp) + "\n"); - else - Error.addInternalError("function createSimCode failed [Transformation from optimised DAE to simulation code structure failed]", sourceInfo()); - fail(); - end try; - - // generate initDAE before replacing pre(alias)! - (initDAE, useHomotopy, removedInitialEquationLst, primaryParameters, allPrimaryParameters) := Initialization.solveInitialSystem(dlow); - - try if Flags.isSet(Flags.ITERATION_VARS) then BackendDAEOptimize.listAllIterationVariables(dlow); end if; @@ -254,7 +247,7 @@ algorithm dlow := BackendDAEOptimize.simplifyTimeIndepFuncCalls(dlow); // initialization stuff - (initialEquations, removedInitialEquations, uniqueEqIndex, tempvars) := createInitialEquations(initDAE, removedInitialEquationLst, uniqueEqIndex, {}); + (initialEquations, removedInitialEquations, uniqueEqIndex, tempvars) := createInitialEquations(initDAE, inRemovedInitialEquationLst, uniqueEqIndex, {}); // addInitialStmtsToAlgorithms dlow := BackendDAEOptimize.addInitialStmtsToAlgorithms(dlow); @@ -297,7 +290,7 @@ algorithm ((uniqueEqIndex, minValueEquations)) := BackendDAEUtil.foldEqSystem(dlow, createMinValueEquations, (uniqueEqIndex, {})); ((uniqueEqIndex, maxValueEquations)) := BackendDAEUtil.foldEqSystem(dlow, createMaxValueEquations, (uniqueEqIndex, {})); ((uniqueEqIndex, parameterEquations)) := BackendDAEUtil.foldEqSystem(dlow, createVarNominalAssertFromVars, (uniqueEqIndex, {})); - (uniqueEqIndex, parameterEquations) := createParameterEquations(uniqueEqIndex, parameterEquations, primaryParameters, allPrimaryParameters); + (uniqueEqIndex, parameterEquations) := createParameterEquations(uniqueEqIndex, parameterEquations, inPrimaryParameters, inAllPrimaryParameters); //((uniqueEqIndex, paramAssertSimEqs)) := BackendEquation.traverseEquationArray(BackendEquation.listEquation(paramAsserts), traversedlowEqToSimEqSystem, (uniqueEqIndex, {})); //parameterEquations := listAppend(parameterEquations, paramAssertSimEqs); @@ -420,7 +413,7 @@ algorithm odeEquations, algebraicEquations, clockedPartitions, - useHomotopy, + inUseHomotopy, initialEquations, removedInitialEquations, startValueEquations, diff --git a/Compiler/Stubs/BackendDAEUtil.mo b/Compiler/Stubs/BackendDAEUtil.mo index 80388db77b..8be4d4390e 100644 --- a/Compiler/Stubs/BackendDAEUtil.mo +++ b/Compiler/Stubs/BackendDAEUtil.mo @@ -10,6 +10,11 @@ function getSolvedSystem input Option strdaeHandler = NONE(); input Option> strPostOptModules = NONE(); output A outSODE; + output A outInitDAE; + output Boolean outUseHomotopy; + output list outRemovedInitialEquationLst; + output list outPrimaryParameters; + output list outAllPrimaryParameters; algorithm assert(false, getInstanceName()); end getSolvedSystem; diff --git a/Compiler/Stubs/SimCodeMain.mo b/Compiler/Stubs/SimCodeMain.mo index 0ee53a53c8..d42ce0aa33 100644 --- a/Compiler/Stubs/SimCodeMain.mo +++ b/Compiler/Stubs/SimCodeMain.mo @@ -19,8 +19,13 @@ algorithm assert(false, getInstanceName()); end createSimulationSettings; -function generateModelCode +function generateModelCode input T inBackendDAE; + input T inInitDAE; + input Boolean inUseHomotopy; + input list inRemovedInitialEquationLst; + input B inPrimaryParameters; + input B inAllPrimaryParameters; input A p; input C className; input String filenamePrefix; diff --git a/Compiler/Util/Flags.mo b/Compiler/Util/Flags.mo index 38b0c25367..0a3963961d 100644 --- a/Compiler/Util/Flags.mo +++ b/Compiler/Util/Flags.mo @@ -683,7 +683,8 @@ constant ConfigFlag PRE_OPT_MODULES = CONFIG_FLAG(12, "preOptModules", // "addInitialStmtsToAlgorithms", "resolveLoops", "evalFunc", - "sortEqnsVars" + "sortEqnsVars", + "encapsulateWhenConditions" }), SOME(STRING_DESC_OPTION({ ("CSE_EachCall", Util.gettext("Common Function Call Elimination")), @@ -716,7 +717,8 @@ constant ConfigFlag PRE_OPT_MODULES = CONFIG_FLAG(12, "preOptModules", ("evalFunc", Util.gettext("evaluates functions partially")), ("comSubExp", Util.gettext("replaces common sub expressions")), ("dumpDAE", Util.gettext("dumps the DAE representation of the current transformation state")), - ("dumpDAEXML", Util.gettext("dumps the DAE as xml representation of the current transformation state")) + ("dumpDAEXML", Util.gettext("dumps the DAE as xml representation of the current transformation state")), + ("encapsulateWhenConditions", Util.gettext("This module replaces each when condition with a boolean variable.")) })), Util.gettext("Sets the pre optimization modules to use in the back end. See --help=optmodules for more info.")); @@ -763,6 +765,7 @@ constant ConfigFlag INDEX_REDUCTION_METHOD = CONFIG_FLAG(15, "indexReductionMeth constant ConfigFlag POST_OPT_MODULES = CONFIG_FLAG(16, "postOptModules", NONE(), EXTERNAL(), STRING_LIST_FLAG({ + "removeInitializationStuff", "lateInlineFunction", "simplifyConstraints", "CSE", @@ -775,7 +778,6 @@ constant ConfigFlag POST_OPT_MODULES = CONFIG_FLAG(16, "postOptModules", "removeSimpleEquations", "simplifyComplexFunction", "symEuler", - "encapsulateWhenConditions", // must called after remove simple equations "reshufflePost", "reduceDynamicOptimization", // before tearing "tearingSystem", // must be the last one, otherwise the torn systems are lost when throw away the matching information @@ -798,7 +800,7 @@ constant ConfigFlag POST_OPT_MODULES = CONFIG_FLAG(16, "postOptModules", //"addInitialStmtsToAlgorithms", }), SOME(STRING_DESC_OPTION({ - ("encapsulateWhenConditions", Util.gettext("Replace each condition/relation with a boolean variable.")), + ("removeInitializationStuff", Util.gettext("Does simplifications by removing initialization information like homotopy(..) and initial().")), ("lateInlineFunction", Util.gettext("Perform function inlining for function with annotation LateInline=true.")), ("removeSimpleEquations", removeSimpleEquationDesc), ("evaluateFinalParameters", Util.gettext("Structural parameters and parameters declared as final are removed and replaced with their value. They may no longer be changed in the init file.")), diff --git a/SimulationRuntime/c/simulation/solver/initialization/initialization.c b/SimulationRuntime/c/simulation/solver/initialization/initialization.c index 9e47b5f4a3..07733f3030 100644 --- a/SimulationRuntime/c/simulation/solver/initialization/initialization.c +++ b/SimulationRuntime/c/simulation/solver/initialization/initialization.c @@ -627,18 +627,17 @@ int initialization(DATA *data, threadData_t *threadData, const char* pInitMethod dumpInitialSolution(data); infoStreamPrint(LOG_INIT, 0, "### END INITIALIZATION ###"); - data->simulationInfo.initial = 0; - /* initialization is done */ - overwriteOldSimulationData(data); /* overwrite the whole ring-buffer with initialized values */ storePreValues(data); /* save pre-values */ updateDiscreteSystem(data, threadData); /* evaluate discrete variables (event iteration) */ saveZeroCrossings(data, threadData); + data->simulationInfo.initial = 0; + /* initialization is done */ + initSample(data, threadData, data->simulationInfo.startTime, data->simulationInfo.stopTime); data->callback->function_storeDelayed(data, threadData); data->callback->function_updateRelations(data, threadData, 1); - initSynchronous(data, threadData, data->simulationInfo.startTime); printRelations(data, LOG_EVENTS); diff --git a/SimulationRuntime/c/simulation/solver/model_help.h b/SimulationRuntime/c/simulation/solver/model_help.h index 2ddcfff881..4ff7c8c970 100644 --- a/SimulationRuntime/c/simulation/solver/model_help.h +++ b/SimulationRuntime/c/simulation/solver/model_help.h @@ -37,7 +37,8 @@ extern "C" { #include "simulation_data.h" /* lochel: I guess this is used for discrete relations */ -#define RELATION(res,exp1,exp2,index,op_w) { \ +#define RELATION(res,exp1,exp2,index,op_w) \ +{ \ if(data->simulationInfo.initial) \ { \ res = ((op_w)((exp1),(exp2))); \ @@ -55,7 +56,8 @@ extern "C" { } /* lochel: I guess this is used for continuous relations */ -#define RELATIONHYSTERESIS(res,exp1,exp2,index,op_w) { \ +#define RELATIONHYSTERESIS(res,exp1,exp2,index,op_w) \ +{ \ if(data->simulationInfo.initial) \ { \ res = ((op_w)((exp1),(exp2))); \