diff --git a/.gitignore b/.gitignore index 508701febca..065d7fceba4 100644 --- a/.gitignore +++ b/.gitignore @@ -106,6 +106,7 @@ Compiler/Script/OpenModelicaScriptingAPIQt.h Compiler/Template/AbsynDumpTpl.mo Compiler/Template/CodegenAdevs.mo Compiler/Template/CodegenC.mo +Compiler/Template/CodegenCFunctions.mo Compiler/Template/CodegenC.mo.log Compiler/Template/CodegenCSharp.mo Compiler/Template/CodegenCpp.mo @@ -116,6 +117,7 @@ Compiler/Template/CodegenFMU1.mo Compiler/Template/CodegenFMU2.mo Compiler/Template/CodegenFMUCommon.mo Compiler/Template/CodegenFMUCpp.mo +Compiler/Template/CodegenFMUCppHpcom.mo Compiler/Template/CodegenJS.mo Compiler/Template/CodegenJava.mo Compiler/Template/CodegenModelica.mo diff --git a/Compiler/BackEnd/BackendDAEUtil.mo b/Compiler/BackEnd/BackendDAEUtil.mo index 8a288e9fb06..0b976567f7e 100644 --- a/Compiler/BackEnd/BackendDAEUtil.mo +++ b/Compiler/BackEnd/BackendDAEUtil.mo @@ -8232,5 +8232,69 @@ algorithm clocks := arrayCreate(0, DAE.INFERRED_CLOCK()); end emptyClocks; +public function componentsEqual"outputs true if 1 strongly connected components are equal" + input BackendDAE.StrongComponent comp1; + input BackendDAE.StrongComponent comp2; + output Boolean isEqual; +algorithm + isEqual := matchcontinue(comp1,comp2) + local + Integer i1,i2, j1,j2; + list l1,l2,k1,k2; + list>> l3,k3; + case(BackendDAE.SINGLEEQUATION(eqn=i1,var=i2),BackendDAE.SINGLEEQUATION(eqn=j1,var=j2)) + equation + then intEq(i1,j1) and intEq(i2,j2); + + case(BackendDAE.EQUATIONSYSTEM(eqns=l1,vars=l2),BackendDAE.EQUATIONSYSTEM(eqns=k1,vars=k2)) + equation + then List.isEqualOnTrue(l1,k1,intEq) and List.isEqualOnTrue(l2,k2,intEq); + + case(BackendDAE.SINGLEARRAY(eqn=i1,vars=l1),BackendDAE.SINGLEARRAY(eqn=j1,vars=k1)) + equation + then intEq(i1,j1) and List.isEqualOnTrue(l1,k1,intEq); + + case(BackendDAE.SINGLEALGORITHM(eqn=i1,vars=l1),BackendDAE.SINGLEALGORITHM(eqn=j1,vars=k1)) + equation + then intEq(i1,j1) and List.isEqualOnTrue(l1,k1,intEq); + + case(BackendDAE.SINGLECOMPLEXEQUATION(eqn=i1,vars=l1),BackendDAE.SINGLECOMPLEXEQUATION(eqn=j1,vars=k1)) + equation + then intEq(i1,j1) and List.isEqualOnTrue(l1,k1,intEq); + + case(BackendDAE.SINGLEWHENEQUATION(eqn=i1,vars=l1),BackendDAE.SINGLEWHENEQUATION(eqn=j1,vars=k1)) + equation + then intEq(i1,j1) and List.isEqualOnTrue(l1,k1,intEq); + + case(BackendDAE.SINGLEIFEQUATION(eqn=i1,vars=l1),BackendDAE.SINGLEIFEQUATION(eqn=j1,vars=k1)) + equation + then intEq(i1,j1) and List.isEqualOnTrue(l1,k1,intEq); + + case(BackendDAE.TORNSYSTEM(strictTearingSet=BackendDAE.TEARINGSET(tearingvars=l1,residualequations=l2,otherEqnVarTpl=l3)),BackendDAE.TORNSYSTEM(strictTearingSet=BackendDAE.TEARINGSET(tearingvars=k1,residualequations=k2,otherEqnVarTpl=k3))) + equation + then List.isEqualOnTrue(l1,k1,intEq) and List.isEqualOnTrue(l2,k2,intEq) and List.isEqualOnTrue(l3,k3,otherEqnVarTplEqual); + else + then false; + end matchcontinue; +end componentsEqual; + +protected function otherEqnVarTplEqual"compares 2 tpls from otherEqnVarTpl in TearingSets" + input tuple> tpl1; + input tuple> tpl2; + output Boolean isEqual; +algorithm + isEqual := matchcontinue(tpl1,tpl2) + local + Integer i1,i2; + list l1,l2; + case((i1,l1),(i2,l2)) + equation + then intEq(i1,i2) and List.isEqualOnTrue(l1,l2,intEq); + + else + then false; + end matchcontinue; +end otherEqnVarTplEqual; + annotation(__OpenModelica_Interface="backend"); end BackendDAEUtil; diff --git a/Compiler/BackEnd/Causalize.mo b/Compiler/BackEnd/Causalize.mo index 6c6c32e6c8b..82aaa6862d6 100644 --- a/Compiler/BackEnd/Causalize.mo +++ b/Compiler/BackEnd/Causalize.mo @@ -134,28 +134,27 @@ protected function singularSystemCheck1 input tuple matchingAlgorithm; input BackendDAE.StructurallySingularSystemHandlerArg arg; input BackendDAE.Shared iShared; - output BackendDAE.EqSystem outSyst; + output BackendDAE.EqSystem outSyst = iSyst; protected - BackendDAE.Variables vars; - BackendDAE.EquationArray eqns; BackendDAE.IncidenceMatrix m; BackendDAE.IncidenceMatrixT mT; - BackendDAE.StateSets stateSets; list> comps; array ass1,ass2; BackendDAEFunc.matchingAlgorithmFunc matchingFunc; - BackendDAE.BaseClockPartitionKind partitionKind; + BackendDAE.EqSystem syst; algorithm - BackendDAE.EQSYSTEM(orderedVars=vars,orderedEqs=eqns,m=SOME(m),mT=SOME(mT),stateSets=stateSets,partitionKind=partitionKind) := iSyst; + BackendDAE.EQSYSTEM(m=SOME(m), mT=SOME(mT)) := iSyst; (matchingFunc,_) := matchingAlgorithm; // get absolute Incidence Matrix m := BackendDAEUtil.absIncidenceMatrix(m); mT := BackendDAEUtil.absIncidenceMatrix(mT); // try to match - outSyst := BackendDAE.EQSYSTEM(vars,eqns,SOME(m),SOME(mT),BackendDAE.NO_MATCHING(),stateSets,partitionKind); + syst := BackendDAEUtil.setEqSystMatrices(iSyst, SOME(m), SOME(mT)); + syst.matching := BackendDAE.NO_MATCHING(); // do matching - (outSyst as BackendDAE.EQSYSTEM(matching=BackendDAE.MATCHING(ass1=ass1,ass2=ass2)),_,_) := matchingFunc(outSyst,iShared,true,(BackendDAE.INDEX_REDUCTION(),eqnConstr),foundSingularSystem,arg); - outSyst := BackendDAEUtil.setEqSystMatching(iSyst,BackendDAE.MATCHING(ass1,ass2,{})); + (syst as BackendDAE.EQSYSTEM(matching=BackendDAE.MATCHING(ass1=ass1, ass2=ass2)), _, _) := + matchingFunc(syst, iShared, true, (BackendDAE.INDEX_REDUCTION(), eqnConstr), foundSingularSystem, arg); + outSyst.matching := BackendDAE.MATCHING(ass1, ass2, {}); /* print("singularSystemCheck:\n"); BackendDump.printEqSystem(outSyst); @@ -164,7 +163,7 @@ algorithm DumpGraphML.dumpSystem(outSyst,iShared,NONE(),"SingularSystemCheck" + intString(nVars) + ".graphml",false); */ // free states matching information because there it is unkown if the state or the state derivative was matched - ((_,ass1,ass2)) := BackendVariable.traverseBackendDAEVars(vars, freeStateAssignments, (1,ass1,ass2)); + ((_,ass1,ass2)) := BackendVariable.traverseBackendDAEVars(outSyst.orderedVars, freeStateAssignments, (1,ass1,ass2)); end singularSystemCheck1; protected function freeStateAssignments "unset assignments of statevariables." diff --git a/Compiler/BackEnd/ExpressionSolve.mo b/Compiler/BackEnd/ExpressionSolve.mo index fecd5f91357..823d23deab0 100644 --- a/Compiler/BackEnd/ExpressionSolve.mo +++ b/Compiler/BackEnd/ExpressionSolve.mo @@ -98,23 +98,14 @@ protected BackendDAE.StrongComponent c; Integer i = 1; list newVars = {}; - - BackendDAE.Variables vars; - BackendDAE.Matching matching; - BackendDAE.StateSets stateSets; - BackendDAE.BaseClockPartitionKind partitionKind; - BackendDAE.EquationArray eqns; - algorithm for comp in inComps loop (osyst,oshared, newVars) := findSimpleEquationWork(osyst,oshared,comp, i, newVars); i := i + 1; end for; - if not listEmpty(newVars) then - BackendDAE.EQSYSTEM(orderedVars=vars,orderedEqs=eqns,matching=matching,stateSets=stateSets,partitionKind=partitionKind) := osyst; - vars := BackendVariable.addVars(newVars, vars); - osyst := BackendDAE.EQSYSTEM(vars,eqns,NONE(),NONE(),matching,stateSets,partitionKind); + osyst.orderedVars := BackendVariable.addVars(newVars, osyst.orderedVars); + osyst := BackendDAEUtil.setEqSystMatrices(osyst); //BackendDump.printEqSystem(osyst); end if; diff --git a/Compiler/BackEnd/HpcOmEqSystems.mo b/Compiler/BackEnd/HpcOmEqSystems.mo index b7fc94cc061..de90150ddfc 100644 --- a/Compiler/BackEnd/HpcOmEqSystems.mo +++ b/Compiler/BackEnd/HpcOmEqSystems.mo @@ -169,7 +169,8 @@ algorithm list tvarIdcs, resEqIdcs, eqIdcs, varIdcs; list>> otherEqnVarTpl; BackendDAE.BaseClockPartitionKind partitionKind; - BackendDAE.EqSystem systTmp; + BackendDAE.EqSystem syst; + EqSys hpcSyst; BackendDAE.EquationArray eqs; BackendDAE.Jacobian jac; BackendDAE.JacobianType jacType; @@ -182,14 +183,13 @@ algorithm BackendVarTransform.VariableReplacements derRepl; list eqLst, eqsNew, eqsOld, resEqs, addEqs; list varLst,varLstRepl, varsNew, varsOld, tvars, addVars; - EqSys syst; case(_,_,_,_,_,_,_) equation // completed true = listLength(compsIn) < compIdx; then (systIn,tornSysIdxIn); - case(_,_,_,_,_,_,_) + case(_,_,_,_,syst,_,_) equation // strongComponent is a linear tornSystem true = listLength(compsIn) >= compIdx; @@ -204,16 +204,14 @@ algorithm // add the new vars and equations to the original EqSystem BackendDAE.MATCHING(ass1=ass1New, ass2=ass2New, comps=compsNew) = matchingNew; - BackendDAE.EQSYSTEM(orderedVars = vars, orderedEqs = eqs, stateSets = stateSets, partitionKind=partitionKind) = systIn; - varsOld = BackendVariable.varList(vars); - eqsOld = BackendEquation.equationList(eqs); + varsOld = BackendVariable.varList(syst.orderedVars); + eqsOld = BackendEquation.equationList(syst.orderedEqs); varLst = listAppend(varsOld,varsNew); eqLst = listAppend(eqsOld, eqsNew); eqLst = List.fold2(List.intRange(listLength(resEqIdcs)),replaceAtPositionFromList,resEqs,resEqIdcs,eqLst); // replaces the old residualEquations with the new ones - vars = BackendVariable.listVar1(varLst); // !!! BackendVariable.listVar outputs the reversed order therefore listVar1 - eqs = BackendEquation.listEquation(eqLst); - + syst.orderedVars = BackendVariable.listVar1(varLst); // !!! BackendVariable.listVar outputs the reversed order therefore listVar1 + syst.orderedEqs = BackendEquation.listEquation(eqLst); // build the matching ass1All = arrayCreate(listLength(varLst),-1); @@ -231,15 +229,15 @@ algorithm compsNew = listAppend(compsNew, otherComps); compsTmp = List.replaceAtWithList(compsNew,compIdx-1,compsIn); ((ass1All,ass2All)) = List.fold2(List.intRange(arrayLength(ass1New)),updateMatching,(listLength(eqsOld),listLength(varsOld)),(ass1New,ass2New),(ass1All,ass2All)); - matching = BackendDAE.MATCHING(ass1All, ass2All, compsTmp); + syst.matching = BackendDAE.MATCHING(ass1All, ass2All, compsTmp); //build new DAE-EqSystem - systTmp = BackendDAE.EQSYSTEM(vars,eqs,NONE(),NONE(),matching,stateSets,partitionKind); - (systTmp,_,_) = BackendDAEUtil.getIncidenceMatrix(systTmp, BackendDAE.NORMAL(),NONE()); - (systTmp,tornSysIdx) = reduceLinearTornSystem1(compIdx+1+numNewSingleEqs,compsTmp,ass1All,ass2All,systTmp,sharedIn,tornSysIdxIn+1); + syst = BackendDAEUtil.setEqSystMatrices(syst); + (syst,_,_) = BackendDAEUtil.getIncidenceMatrix(syst, BackendDAE.NORMAL(),NONE()); + (syst, tornSysIdx) = reduceLinearTornSystem1(compIdx+1+numNewSingleEqs,compsTmp,ass1All,ass2All,syst,sharedIn,tornSysIdxIn+1); then - (systTmp,tornSysIdx); - case(_,_,_,_,BackendDAE.EQSYSTEM(orderedVars=vars, orderedEqs = eqs, stateSets=stateSets, partitionKind=partitionKind),_,_) + (syst, tornSysIdx); + case(_,_,_,_,syst as BackendDAE.EQSYSTEM(orderedVars=vars, orderedEqs = eqs),_,_) equation // strongComponent is a system of equations true = listLength(compsIn) >= compIdx; @@ -263,9 +261,9 @@ algorithm //BackendDump.dumpEquationList(eqLst,"eqLst"); // build linear system - syst = getEqSystem(eqLst,varLstRepl); - //dumpEqSys(syst); - (eqsNew,addEqs,addVars) = CramerRule(syst); + hpcSyst = getEqSystem(eqLst, varLstRepl); + //dumpEqSys(hpcSyst); + (eqsNew,addEqs,addVars) = CramerRule(hpcSyst); (eqsNew,_) = BackendVarTransform.replaceEquations(eqsNew,derRepl,NONE());//introduce der(.) for $DER. //BackendDump.dumpEquationList(eqsNew,"eqsNew"); @@ -288,8 +286,8 @@ algorithm eqLst = listAppend(eqsOld,addEqs); varLst = listAppend(varsOld,addVars); eqLst = List.fold2(List.intRange(listLength(eqsNew)),replaceAtPositionFromList,eqsNew,eqIdcs,eqLst); // replaces the old residualEquations with the new ones - eqs = BackendEquation.listEquation(eqLst); - vars = BackendVariable.listVar1(varLst); + syst.orderedEqs = BackendEquation.listEquation(eqLst); + syst.orderedVars = BackendVariable.listVar1(varLst); // update assignments ass1All = arrayCreate(listLength(varLst),-1); @@ -297,22 +295,22 @@ algorithm ass1All = Array.copy(ass1,ass1All); // the comps before and after the tornsystem ass2All = Array.copy(ass2,ass2All); List.map2_0(compsNew,updateAssignmentsByComp,ass1All,ass2All); - matching = BackendDAE.MATCHING(ass1All, ass2All, compsTmp); + syst.matching = BackendDAE.MATCHING(ass1All, ass2All, compsTmp); //BackendDump.dumpFullMatching(matching); //build new DAE-EqSystem - systTmp = BackendDAE.EQSYSTEM(vars,eqs,NONE(),NONE(),matching,stateSets,partitionKind); + syst = BackendDAEUtil.setEqSystMatrices(syst); //(systTmp,_,_) = BackendDAEUtil.getIncidenceMatrix(systTmp, BackendDAE.NORMAL(),NONE()); - (systTmp,tornSysIdx) = reduceLinearTornSystem1(compIdx+1,compsTmp,ass1All,ass2All,systTmp,sharedIn,tornSysIdxIn+1); + (syst,tornSysIdx) = reduceLinearTornSystem1(compIdx+1,compsTmp,ass1All,ass2All,syst,sharedIn,tornSysIdxIn+1); then - (systTmp,tornSysIdx); + (syst,tornSysIdx); else // go to next StrongComponent equation - (systTmp,tornSysIdx) = reduceLinearTornSystem1(compIdx+1,compsIn,ass1,ass2,systIn,sharedIn,tornSysIdxIn); + (syst, tornSysIdx) = reduceLinearTornSystem1(compIdx+1,compsIn,ass1,ass2,systIn,sharedIn,tornSysIdxIn); then - (systTmp,tornSysIdx); + (syst, tornSysIdx); end matchcontinue; end reduceLinearTornSystem1; @@ -579,7 +577,7 @@ protected algorithm eqArr := BackendEquation.listEquation(eqsIn); varArr := BackendVariable.listVar1(varsIn); - eqSys := BackendDAE.EQSYSTEM(varArr,eqArr,NONE(),NONE(),BackendDAE.NO_MATCHING(),{},BackendDAE.UNKNOWN_PARTITION()); + eqSys := BackendDAEUtil.createEqSystem(varArr, eqArr); (m,mT) := BackendDAEUtil.incidenceMatrix(eqSys,BackendDAE.ABSOLUTE(),NONE()); size := listLength(eqsIn); (eqIdcs,varIdcs,resEqsOut) := List.fold(List.intRange(size),function simplifyNewEquations1(eqArr=eqArr,varArr=varArr,m=m,mt=mT,numAuxiliaryVars=numAuxiliaryVars),({},{},resEqsIn)); @@ -1044,7 +1042,7 @@ algorithm // get the EQSYSTEM, the incidenceMatrix and a matching vars = BackendVariable.listVar1(inVars); eqArr = BackendEquation.listEquation(inEqs); - sysTmp = BackendDAE.EQSYSTEM(vars,eqArr,NONE(),NONE(),BackendDAE.NO_MATCHING(),{},BackendDAE.UNKNOWN_PARTITION()); + sysTmp = BackendDAEUtil.createEqSystem(vars, eqArr); (sysTmp,m,mt) = BackendDAEUtil.getIncidenceMatrix(sysTmp,BackendDAE.NORMAL(),NONE()); nVars = listLength(inVars); nEqs = listLength(inEqs); @@ -1054,7 +1052,7 @@ algorithm BackendDAEEXT.matching(nVars, nEqs, 5, -1, 0.0, 1); BackendDAEEXT.getAssignment(ass2, ass1); matching = BackendDAE.MATCHING(ass1, ass2, {}); - sysTmp = BackendDAE.EQSYSTEM(vars,eqArr,SOME(m),SOME(mt),matching,{},BackendDAE.UNKNOWN_PARTITION()); + sysTmp = BackendDAEUtil.createEqSystem(vars, eqArr); // perform BLT to order the StrongComponents mapIncRowEqn = listArray(List.intRange(nEqs)); mapEqnIncRow = Array.map(mapIncRowEqn,List.create); diff --git a/Compiler/BackEnd/HpcOmTaskGraph.mo b/Compiler/BackEnd/HpcOmTaskGraph.mo index b3887abe2dc..ff8d8bb6f95 100644 --- a/Compiler/BackEnd/HpcOmTaskGraph.mo +++ b/Compiler/BackEnd/HpcOmTaskGraph.mo @@ -4989,18 +4989,35 @@ protected function validateComponents "author: marcusw input list> systComps; output Boolean res; protected + Boolean isEqual; + Integer i1,i2; + BackendDAE.StrongComponent comp1,comp2; + tuple tpl1,tpl2; list> sortedGraphComps, sortedSystComps; algorithm res := matchcontinue(graphComps,systComps) case(_,_) - equation - sortedGraphComps = List.sort(graphComps,compareComponents); - sortedSystComps = List.sort(systComps,compareComponents); - true = List.isEqual(sortedGraphComps, sortedSystComps, true); + algorithm + sortedGraphComps := List.sort(graphComps,compareComponents); + sortedSystComps := List.sort(systComps,compareComponents); + //true := List.isEqual(sortedGraphComps, sortedSystComps, true); + if intNe(listLength(sortedSystComps),listLength(sortedGraphComps)) then print("the graph and the system have a difference number of components.\n"); end if; + isEqual := true; + while isEqual and not listEmpty(sortedGraphComps) loop + tpl1::sortedGraphComps := sortedGraphComps; + tpl2::sortedSystComps := sortedSystComps; + (comp1,i1) := tpl1; + (comp2,i2) := tpl2; + if BackendDAEUtil.componentsEqual(comp1,comp2) and intEq(i1,i2) then isEqual:= true; + else + isEqual := false; + print("comp"+intString(i1)+BackendDump.printComponent(comp1)+" is not equal to "+"comp"+intString(i2)+BackendDump.printComponent(comp2)+"\n"); + end if; + end while; then true; else equation - print("Different components in graph and system"); + print("Different components in graph and system\n"); then false; end matchcontinue; end validateComponents; diff --git a/Compiler/BackEnd/IndexReduction.mo b/Compiler/BackEnd/IndexReduction.mo index c140410b7d8..f72a46799f7 100644 --- a/Compiler/BackEnd/IndexReduction.mo +++ b/Compiler/BackEnd/IndexReduction.mo @@ -573,8 +573,8 @@ protected function differentiateEqns output array omapIncRowEqn; output list,list,list>> oNotDiffableMSS; algorithm - (osyst,oshared,outAss1,outAss2,outStateOrd,outOrgEqnsLst,omapEqnIncRow,omapIncRowEqn,oNotDiffableMSS):= - match (inEqnsTpl,inEqns,unassignedStates,unassignedEqns,inSystem,inShared,inAss1,inAss2,inStateOrd,inOrgEqnsLst,imapEqnIncRow,imapIncRowEqn,iNotDiffableMSS) + (osyst,oshared,outAss1,outAss2,outStateOrd,outOrgEqnsLst,omapEqnIncRow,omapIncRowEqn,oNotDiffableMSS) := + match (inEqnsTpl, inSystem) local Integer eqnss,eqnss1; BackendDAE.EquationArray eqns_1,eqns; @@ -592,7 +592,7 @@ algorithm DAE.FunctionTree funcs; BackendDAE.BaseClockPartitionKind partitionKind; // all equations are differentiated - case (_::_,_,_,_,BackendDAE.EQSYSTEM(v,eqns,SOME(m),SOME(mt),matching,stateSets,partitionKind),_,_,_,_,_,_,_,_) + case (_::_, syst as BackendDAE.EQSYSTEM(orderedVars=v, orderedEqs=eqns, m=SOME(m), mT=SOME(mt))) equation eqnss = BackendDAEUtil.equationArraySize(eqns); (v1,eqns_1,so,ilst,orgEqnsLst) = replaceDifferentiatedEqns(inEqnsTpl,v,eqns,inStateOrd,mt,imapIncRowEqn,{},inOrgEqnsLst); @@ -605,7 +605,8 @@ algorithm // set changed variables assignments to zero ass1 = List.fold1r(ilst,arrayUpdate,-1,inAss1); eqnslst1 = collectVarEqns(ilst,{},mt,arrayLength(mt),arrayLength(m)); - syst = BackendDAE.EQSYSTEM(v1,eqns_1,SOME(m),SOME(mt),matching,stateSets,partitionKind); + syst.orderedVars = v1; + syst.orderedEqs = eqns_1; eqnslst1 = List.map1r(eqnslst1,arrayGet,imapIncRowEqn); eqnslst1 = List.uniqueIntN(listAppend(inEqns,eqnslst1),eqnss1); eqnslst1 = listAppend(eqnslst1,eqnslst); @@ -614,11 +615,12 @@ algorithm BackendDump.debuglst(eqnslst1,intString," ","\n"); end if; funcs = BackendDAEUtil.getFunctions(inShared); - (syst,mapEqnIncRow,mapIncRowEqn) = BackendDAEUtil.updateIncidenceMatrixScalar(syst, BackendDAE.SOLVABLE() , SOME(funcs), eqnslst1, imapEqnIncRow, imapIncRowEqn); + (syst,mapEqnIncRow,mapIncRowEqn) = + BackendDAEUtil.updateIncidenceMatrixScalar(syst, BackendDAE.SOLVABLE(), SOME(funcs), eqnslst1, imapEqnIncRow, imapIncRowEqn); then (syst,inShared,ass1,ass2,so,orgEqnsLst,mapEqnIncRow,mapIncRowEqn,iNotDiffableMSS); // not all equations are differentiated - case ({},_,_,_,_,_,_,_,_,_,_,_,_) + case ({},_) then (inSystem,inShared,inAss1,inAss2,inStateOrd,inOrgEqnsLst,imapEqnIncRow,imapIncRowEqn,(inEqns,unassignedStates,unassignedEqns)::iNotDiffableMSS); end match; @@ -948,47 +950,46 @@ protected function handleundifferntiableMSS output array omapIncRowEqn; algorithm (osyst,oshared,outAss1,outAss2,outStateOrd,outOrgEqnsLst,omapEqnIncRow,omapIncRowEqn):= - matchcontinue (b,statesWithUnusedDer,inEqns,unassignedStates,unassignedEqns,inSystem,inShared,inAss1,inAss2,inStateOrd,inOrgEqnsLst,imapEqnIncRow,imapIncRowEqn) + matchcontinue (b,statesWithUnusedDer,inEqns,unassignedStates,unassignedEqns,inSystem) local Integer i; BackendDAE.EquationArray eqns; - list ilst,eqnslst,eqnslst1; + list ilst, eqnslst, eqnslst1; BackendDAE.Variables v,v1; BackendDAE.IncidenceMatrix m; BackendDAE.IncidenceMatrix mt; BackendDAE.EqSystem syst; - BackendDAE.Matching matching; - array ass1,ass2,mapIncRowEqn; + array ass1, ass2, mapIncRowEqn; array> mapEqnIncRow; list varlst; BackendDAE.Var var; - BackendDAE.StateSets stateSets; - BackendDAE.BaseClockPartitionKind partitionKind; DAE.FunctionTree funcs; // 1th try to replace final parameter - case (_,_,_,_,_,BackendDAE.EQSYSTEM(v,eqns,SOME(m),SOME(mt),matching,stateSets,partitionKind),_,_,_,_,_,_,_) + case (_,_,_,_,_,syst as BackendDAE.EQSYSTEM(m=SOME(_), mT=SOME(_))) equation - ((eqns,eqnslst as _::_,_)) = List.fold1(inEqns,replaceFinalVars,BackendVariable.daeKnVars(inShared),(eqns,{},BackendVarTransform.emptyReplacements())); + ((eqns, eqnslst as _::_, _)) = List.fold1( inEqns, replaceFinalVars, BackendVariable.daeKnVars(inShared), + (syst.orderedEqs, {}, BackendVarTransform.emptyReplacements())); + syst.orderedEqs = eqns; // unassign changed equations and assigned vars - eqnslst1 = List.flatten(List.map1r(eqnslst,arrayGet,imapEqnIncRow)); - ilst = List.map1r(eqnslst1,arrayGet,inAss2); - ilst = List.select1(ilst,intGt,0); - ass2 = List.fold1r(eqnslst1,arrayUpdate,-1,inAss2); - ass1 = List.fold1r(ilst,arrayUpdate,-1,inAss1); + eqnslst1 = List.flatten(List.map1r(eqnslst, arrayGet, imapEqnIncRow)); + ilst = List.map1r(eqnslst1, arrayGet, inAss2); + ilst = List.select1(ilst, intGt, 0); + ass2 = List.fold1r(eqnslst1, arrayUpdate, -1, inAss2); + ass1 = List.fold1r(ilst, arrayUpdate, -1, inAss1); // update IncidenceMatrix if Flags.isSet(Flags.BLT_DUMP) then print("Replaced final Parameter in Eqns\n"); print("Update Incidence Matrix: "); - BackendDump.debuglst(eqnslst,intString," ","\n"); + BackendDump.debuglst(eqnslst, intString, " ", "\n"); end if; - syst = BackendDAE.EQSYSTEM(v,eqns,SOME(m),SOME(mt),matching,stateSets,partitionKind); funcs = BackendDAEUtil.getFunctions(inShared); - (syst,mapEqnIncRow,mapIncRowEqn) = BackendDAEUtil.updateIncidenceMatrixScalar(syst, BackendDAE.SOLVABLE(), SOME(funcs), eqnslst, imapEqnIncRow, imapIncRowEqn); + (syst, mapEqnIncRow, mapIncRowEqn) = + BackendDAEUtil.updateIncidenceMatrixScalar(syst, BackendDAE.SOLVABLE(), SOME(funcs), eqnslst, imapEqnIncRow, imapIncRowEqn); then - (syst,inShared,ass1,ass2,inStateOrd,inOrgEqnsLst,mapEqnIncRow,mapIncRowEqn); + (syst, inShared, ass1, ass2, inStateOrd, inOrgEqnsLst, mapEqnIncRow, mapIncRowEqn); // if size of unmatched eqns is equal to size of states without used derivative change all to algebraic - case (true,_::_,_,_,_,BackendDAE.EQSYSTEM(v,eqns,SOME(m),SOME(mt),matching,stateSets,partitionKind),_,_,_,_,_,_,_) + case (true,_::_,_,_,_,syst as BackendDAE.EQSYSTEM(orderedVars=v, m=SOME(m), mT=SOME(mt))) equation // change varKind varlst = List.map1r(statesWithUnusedDer,BackendVariable.getVarAt,v); @@ -996,12 +997,11 @@ algorithm print("Change varKind to algebraic for\n"); BackendDump.printVarList(varlst); end if; - varlst = BackendVariable.setVarsKind(varlst,BackendDAE.VARIABLE()); - v1 = BackendVariable.addVars(varlst,v); + varlst = BackendVariable.setVarsKind(varlst, BackendDAE.VARIABLE()); + syst.orderedVars = BackendVariable.addVars(varlst, syst.orderedVars); // update IncidenceMatrix - eqnslst1 = collectVarEqns(statesWithUnusedDer,{},mt,arrayLength(mt),arrayLength(m)); - eqnslst1 = List.map1r(eqnslst1,arrayGet,imapIncRowEqn); - syst = BackendDAE.EQSYSTEM(v1,eqns,SOME(m),SOME(mt),matching,stateSets,partitionKind); + eqnslst1 = collectVarEqns(statesWithUnusedDer, {}, mt, arrayLength(mt), arrayLength(m)); + eqnslst1 = List.map1r(eqnslst1, arrayGet, imapIncRowEqn); if Flags.isSet(Flags.BLT_DUMP) then print("Update Incidence Matrix: "); BackendDump.debuglst(eqnslst1,intString," ","\n"); @@ -1012,7 +1012,7 @@ algorithm (syst,inShared,inAss1,inAss2,inStateOrd,inOrgEqnsLst,mapEqnIncRow,mapIncRowEqn); /* Debugging case - case (false,_,_,_,_,BackendDAE.EQSYSTEM(v,eqns,SOME(m),SOME(mt),matching,stateSets),_,_,_,_,_,_,_) + case (false,_,_,_,_,BackendDAE.EQSYSTEM(v,eqns,SOME(m),SOME(mt),matching,stateSets)) equation varlst = BackendEquation.equationsLstVars(notDiffedEquations,v); varlst = List.select(varlst,BackendVariable.isStateVar); @@ -1027,7 +1027,7 @@ algorithm // if size of unmatched eqns is not equal to size of states without used derivative change first to algebraic // until I have a better sulution - case (false,i::ilst,_,_,_,BackendDAE.EQSYSTEM(v,eqns,SOME(m),SOME(mt),matching,stateSets,partitionKind),_,_,_,_,_,_,_) + case (false,i::ilst,_,_,_,syst as BackendDAE.EQSYSTEM(orderedVars=v, m=SOME(m), mT=SOME(mt))) equation // change varKind var = BackendVariable.getVarAt(v,i); @@ -1037,16 +1037,15 @@ algorithm BackendDump.printVarList(varlst); end if; varlst = BackendVariable.setVarsKind(varlst,BackendDAE.VARIABLE()); - v1 = BackendVariable.addVars(varlst,v); - varlst = List.map1r(ilst,BackendVariable.getVarAt,v); + syst.orderedVars = BackendVariable.addVars(varlst, v); if Flags.isSet(Flags.BLT_DUMP) then + varlst = List.map1r(ilst, BackendVariable.getVarAt, v); print("Other Candidates are\n"); BackendDump.printVarList(varlst); end if; // update IncidenceMatrix - eqnslst1 = collectVarEqns({i},{},mt,arrayLength(mt),arrayLength(m)); - eqnslst1 = List.map1r(eqnslst1,arrayGet,imapIncRowEqn); - syst = BackendDAE.EQSYSTEM(v1,eqns,SOME(m),SOME(mt),matching,stateSets,partitionKind); + eqnslst1 = collectVarEqns({i}, {}, mt, arrayLength(mt), arrayLength(m)); + eqnslst1 = List.map1r(eqnslst1, arrayGet, imapIncRowEqn); if Flags.isSet(Flags.BLT_DUMP) then print("Update Incidence Matrix: "); BackendDump.debuglst(eqnslst1,intString," ","\n"); @@ -1057,7 +1056,7 @@ algorithm (syst,inShared,inAss1,inAss2,inStateOrd,inOrgEqnsLst,mapEqnIncRow,mapIncRowEqn); // if no state with unused derivative is in the set check global - case (_,{},_,_,_,BackendDAE.EQSYSTEM(v,_,SOME(_),SOME(mt),_,_,_),_,_,_,_,_,_,_) + case (_,{},_,_,_,syst as BackendDAE.EQSYSTEM(orderedVars=v, m=SOME(_), mT=SOME(mt))) equation ilst = Matching.getUnassigned(BackendVariable.varsSize(v), inAss1, {}); ilst = List.fold1(ilst, statesWithUnusedDerivative, mt, {}); @@ -1074,7 +1073,7 @@ algorithm then (syst,oshared,outAss1,outAss2,outStateOrd,outOrgEqnsLst,omapEqnIncRow,omapIncRowEqn); - case (_,_,_,_,_,BackendDAE.EQSYSTEM(v,_,SOME(_),SOME(_),_,_,_),_,_,_,_,_,_,_) + case (_,_,_,_,_,BackendDAE.EQSYSTEM(orderedVars=v, m=SOME(_), mT=SOME(_))) equation varlst = List.map1r(unassignedStates,BackendVariable.getVarAt,v); if Flags.isSet(Flags.BLT_DUMP) then @@ -1538,20 +1537,21 @@ protected function addStateSets algorithm (oSetIndex,oSystem) := match(iTplLst,inSystem) local + BackendDAE.EqSystem syst; + Integer setIndex; + BackendDAE.EquationArray eqs; BackendDAE.Variables vars; - BackendDAE.EquationArray eqns; - Option om; - Option omT; - BackendDAE.Matching matching; BackendDAE.StateSets stateSets; - BackendDAE.BaseClockPartitionKind partitionKind; - Integer setIndex; case ({},_) then (iSetIndex,inSystem); - case (_::_,BackendDAE.EQSYSTEM(vars,eqns,om,omT,matching,stateSets,partitionKind)) + case (_::_, syst) equation - (setIndex,vars,eqns,stateSets) = generateStateSets(iTplLst,iSetIndex,vars,eqns,stateSets); + (setIndex, vars, eqs, stateSets) = + generateStateSets(iTplLst, iSetIndex, syst.orderedVars, syst.orderedEqs, syst.stateSets); + syst.orderedVars = vars; + syst.orderedEqs = eqs; + syst.stateSets = stateSets; then - (setIndex,BackendDAE.EQSYSTEM(vars,eqns,om,omT,matching,stateSets,partitionKind)); + (setIndex, syst); end match; end addStateSets; @@ -1998,7 +1998,7 @@ algorithm // sort vars with heuristic hovvars = BackendVariable.listVar1(statecandidates); eqns1 = BackendEquation.listEquation(eqnslst); - syst = BackendDAE.EQSYSTEM(hovvars,eqns1,NONE(),NONE(),BackendDAE.NO_MATCHING(),{},BackendDAE.UNKNOWN_PARTITION()); + syst = BackendDAEUtil.createEqSystem(hovvars, eqns1); (me,meT,_,_) = BackendDAEUtil.getAdjacencyMatrixEnhancedScalar(syst,inShared,false); m1 = incidenceMatrixfromEnhanced2(me,hovvars); mT1 = BackendDAEUtil.transposeMatrix(m1,nfreeStates); @@ -2055,7 +2055,7 @@ algorithm eqns = BackendEquation.addEquations(eqnslst1, eqns); vars = BackendVariable.listVar1(vlst); vars = BackendVariable.addVars(BackendVariable.varList(hovvars), vars); - syst = BackendDAE.EQSYSTEM(vars,eqns,NONE(),NONE(),BackendDAE.NO_MATCHING(),{},BackendDAE.UNKNOWN_PARTITION()); + syst = BackendDAEUtil.createEqSystem(vars, eqns); // get advanced incidence Matrix (me,meT,mapEqnIncRow,mapIncRowEqn) = BackendDAEUtil.getAdjacencyMatrixEnhancedScalar(syst,inShared,false); if Flags.isSet(Flags.BLT_DUMP) then @@ -2524,7 +2524,7 @@ algorithm (eqnlst,varlst,ass1,ass2,eqns1) := getSetSystem(assigned,inMapEqnIncRow,inMapIncRowEqn,vec1,iVars,eqns1,flag,nassigned,eqnlst,varlst,ass1,ass2); eqns := BackendEquation.listEquation(eqnlst); vars := BackendVariable.listVar1(varlst); - syst := BackendDAE.EQSYSTEM(vars,eqns,NONE(),NONE(),BackendDAE.NO_MATCHING(),{},BackendDAE.UNKNOWN_PARTITION()); + syst := BackendDAEUtil.createEqSystem(vars, eqns); // BackendDump.printEqSystem(syst); // BackendDump.dumpMatching(listArray(ass1)); // BackendDump.dumpMatching(listArray(ass2)); @@ -3347,37 +3347,36 @@ protected function replaceHigherDerivatives "author: Frenkel TUD 2013-01 change for var:STATE(2): der(var,2) to der($DER.var), der(var) -> DER.var, add Var $DER.var:STATE(1)" input BackendDAE.EqSystem inSystem; - output BackendDAE.EqSystem osyst; + output BackendDAE.EqSystem osyst = inSystem; protected BackendDAE.Variables vars; - BackendDAE.EquationArray eqns; - Option om,omT; - BackendDAE.Matching matching; - BackendDAE.StateSets stateSets; HashTableCrIntToExp.HashTable ht; list dummyvars; - array ass1,ass2; + array ass1, ass2; list> addassign; - Integer nv1,nv; - BackendDAE.BaseClockPartitionKind partitionKind; + Integer nv1, nv; algorithm - BackendDAE.EQSYSTEM(orderedVars=vars,orderedEqs=eqns,m=om,mT=omT,matching=BackendDAE.MATCHING(ass1=ass1,ass2=ass2),stateSets=stateSets,partitionKind=partitionKind) := inSystem; // traverse vars and generate dummy vars and replacement rules ht := HashTableCrIntToExp.emptyHashTable(); - nv := BackendVariable.varsSize(vars); - (vars,(_,_,nv1,addassign,dummyvars,ht)) := BackendVariable.traverseBackendDAEVarsWithUpdate(vars,makeHigherStatesRepl,(vars,1,nv,{},{},ht)); + nv := BackendVariable.varsSize(osyst.orderedVars); + BackendDAE.MATCHING(ass1=ass1, ass2=ass2) := osyst.matching; + + (vars, (_, _, nv1, addassign, dummyvars, ht)) := + BackendVariable.traverseBackendDAEVarsWithUpdate( osyst.orderedVars, makeHigherStatesRepl, + (osyst.orderedVars, 1, nv, {}, {}, ht) ); // BaseHashTable.dumpHashTable(ht); // add dummy Vars; dummyvars := listReverse(dummyvars); - vars := BackendVariable.addVars(dummyvars,vars); + vars := BackendVariable.addVars(dummyvars, vars); // perform replacement rules - (vars,_) := BackendVariable.traverseBackendDAEVarsWithUpdate(vars,replaceDummyDerivativesVar,ht); - _ := BackendDAEUtil.traverseBackendDAEExpsEqnsWithUpdate(eqns,Expression.traverseSubexpressionsHelper,(replaceDummyDerivativesExp,ht)); + (osyst.orderedVars, _) := BackendVariable.traverseBackendDAEVarsWithUpdate(vars, replaceDummyDerivativesVar, ht); + BackendDAEUtil.traverseBackendDAEExpsEqnsWithUpdate( osyst.orderedEqs, Expression.traverseSubexpressionsHelper, + (replaceDummyDerivativesExp, ht) ); // extend assignments ass1 := Array.expand(nv1-nv, ass1, -1); // set the new assignments - List.map2_0(addassign,setHigerDerivativeAssignment,ass1,ass2); - osyst := BackendDAE.EQSYSTEM(vars,eqns,om,omT,BackendDAE.MATCHING(ass1,ass2,{}),stateSets,partitionKind); + List.map2_0(addassign, setHigerDerivativeAssignment, ass1, ass2); + osyst.matching := BackendDAE.MATCHING(ass1, ass2, {}); end replaceHigherDerivatives; protected function setHigerDerivativeAssignment @@ -3492,27 +3491,23 @@ protected function addAllDummyStates input BackendDAE.EqSystem inSystem; input BackendDAE.StateOrder so; input HashTableCrIntToExp.HashTable iHt; - output BackendDAE.EqSystem osyst; + output BackendDAE.EqSystem osyst = inSystem; output HashTableCrIntToExp.HashTable oHt; protected BackendDAE.Variables vars; - BackendDAE.EquationArray eqns; - Option om,omT; - BackendDAE.Matching matching; - BackendDAE.StateSets stateSets; list dummvars; - BackendDAE.BaseClockPartitionKind partitionKind; algorithm - BackendDAE.EQSYSTEM(orderedVars=vars,orderedEqs=eqns,m=om,mT=omT,matching=matching,stateSets=stateSets,partitionKind=partitionKind) := inSystem; // traverse vars and generate dummy vars and replacement rules - (vars,(_,_,dummvars,oHt)) := BackendVariable.traverseBackendDAEVarsWithUpdate(vars,makeAllDummyVarandDummyDerivativeRepl,(vars,so,{},iHt)); + (vars, (_, _, dummvars, oHt)) := + BackendVariable.traverseBackendDAEVarsWithUpdate( osyst.orderedVars, makeAllDummyVarandDummyDerivativeRepl, + (osyst.orderedVars, so, {}, iHt) ); // BaseHashTable.dumpHashTable(oHt); // add dummy Vars; vars := BackendVariable.addVars(dummvars,vars); // perform replacement rules - (vars,_) := BackendVariable.traverseBackendDAEVarsWithUpdate(vars,replaceDummyDerivativesVar,oHt); - _ := BackendDAEUtil.traverseBackendDAEExpsEqnsWithUpdate(eqns,Expression.traverseSubexpressionsHelper,(replaceDummyDerivativesExp,oHt)); - osyst := BackendDAE.EQSYSTEM(vars,eqns,om,omT,matching,stateSets,partitionKind); + (osyst.orderedVars, _) := BackendVariable.traverseBackendDAEVarsWithUpdate(vars, replaceDummyDerivativesVar, oHt); + BackendDAEUtil.traverseBackendDAEExpsEqnsWithUpdate( osyst.orderedEqs, Expression.traverseSubexpressionsHelper, + (replaceDummyDerivativesExp, oHt) ); end addAllDummyStates; protected function makeAllDummyVarandDummyDerivativeRepl @@ -3667,26 +3662,27 @@ protected function addDummyStates output BackendDAE.EqSystem osyst; output HashTableCrIntToExp.HashTable oHt; algorithm - (osyst,oHt) := - match (dummyStates, level, repl, inSystem, iHt) + (osyst,oHt) := match (dummyStates, inSystem) local HashTableCrIntToExp.HashTable ht; BackendDAE.Variables vars; BackendDAE.EquationArray eqns; Option om,omT; BackendDAE.Matching matching; - BackendDAE.StateSets stateSets; + BackendDAE.EqSystem syst; BackendDAE.BaseClockPartitionKind partitionKind; - case ({},_,_,_,_) then (inSystem,iHt); - case (_,_,_,BackendDAE.EQSYSTEM(orderedVars=vars,orderedEqs=eqns,m=om,mT=omT,matching=matching,stateSets=stateSets,partitionKind=partitionKind),_) + case ({}, _) + then (inSystem, iHt); + case (_, syst) equation // create dummy_der vars and change deselected states to dummy states - ((vars,ht)) = List.fold1(dummyStates,makeDummyVarandDummyDerivative,level,(vars,iHt)); - (vars,_) = BackendVariable.traverseBackendDAEVarsWithUpdate(vars,replaceDummyDerivativesVar,ht); - _ = BackendDAEUtil.traverseBackendDAEExpsEqnsWithUpdate(eqns,Expression.traverseSubexpressionsHelper,(replaceDummyDerivativesExp,ht)); - _ = BackendDAEUtil.traverseBackendDAEExpsEqnsWithUpdate(eqns,Expression.traverseSubexpressionsHelper,(replaceFirstOrderDerivativesExp,repl)); - then - (BackendDAE.EQSYSTEM(vars,eqns,om,omT,matching,stateSets,partitionKind),ht); + ((vars, ht)) = List.fold1(dummyStates, makeDummyVarandDummyDerivative, level, (syst.orderedVars, iHt)); + (syst.orderedVars, _) = BackendVariable.traverseBackendDAEVarsWithUpdate(vars, replaceDummyDerivativesVar, ht); + _ = BackendDAEUtil.traverseBackendDAEExpsEqnsWithUpdate( syst.orderedEqs, Expression.traverseSubexpressionsHelper, + (replaceDummyDerivativesExp, ht) ); + _ = BackendDAEUtil.traverseBackendDAEExpsEqnsWithUpdate( syst.orderedEqs, Expression.traverseSubexpressionsHelper, + (replaceFirstOrderDerivativesExp, repl) ); + then (syst, ht); end match; end addDummyStates; @@ -4173,20 +4169,11 @@ end findStateOrder; protected function findStateOrderWork "author Frenkel TUD 2013-01" input BackendDAE.EqSystem inSystem; - output BackendDAE.EqSystem outSystem; -protected - BackendDAE.Variables vars; - BackendDAE.EquationArray eqns; - Option m; - Option mT; - BackendDAE.Matching matching; - BackendDAE.StateSets stateSets; - BackendDAE.BaseClockPartitionKind partitionKind; + output BackendDAE.EqSystem outSystem = inSystem; algorithm - BackendDAE.EQSYSTEM(vars, eqns, m, mT, matching, stateSets, partitionKind) := inSystem; // find der(s) = v - vars := BackendEquation.traverseEquationArray(eqns, traverseFindStateOrder, vars); - outSystem := BackendDAE.EQSYSTEM(vars, eqns, m, mT, matching, stateSets, partitionKind); + outSystem.orderedVars := BackendEquation.traverseEquationArray( inSystem.orderedEqs, traverseFindStateOrder, + inSystem.orderedVars ); end findStateOrderWork; protected function traverseFindStateOrder diff --git a/Compiler/BackEnd/Initialization.mo b/Compiler/BackEnd/Initialization.mo index 083ade6906b..e54b3949993 100644 --- a/Compiler/BackEnd/Initialization.mo +++ b/Compiler/BackEnd/Initialization.mo @@ -86,22 +86,14 @@ protected BackendDAE.BackendDAE initdae; BackendDAE.EqSystem initsyst; BackendDAE.EqSystems systs; - BackendDAE.EquationArray inieqns, eqns, reeqns; - BackendDAE.ExtraInfo ei; + BackendDAE.EquationArray eqns, reeqns; BackendDAE.Shared shared; BackendDAE.Variables initVars; - BackendDAE.Variables knvars, vars, fixvars, avars; - Boolean b, b1, b2; - Boolean useHomotopy; - DAE.FunctionTree functionTree; - FCore.Cache cache; - FCore.Graph graph; + BackendDAE.Variables vars, fixvars; + Boolean b, b1, b2, useHomotopy; HashSet.HashSet hs "contains all pre variables"; list removedEqns; list dumpVars, dumpVars2; - list tempVar; - list classAttrs; - list constraints; list> pastOptModules; tuple daeHandler; tuple matchingAlgorithm; @@ -117,15 +109,6 @@ algorithm (initVars, outPrimaryParameters, outAllPrimaryParameters) := selectInitializationVariablesDAE(dae); // fcall2(Flags.DUMP_INITIAL_SYSTEM, BackendDump.dumpVariables, initVars, "selected initialization variables"); hs := collectPreVariables(dae); - BackendDAE.DAE(systs, shared as BackendDAE.SHARED(knownVars=knvars, - aliasVars=avars, - initialEqs=inieqns, - constraints=constraints, - classAttrs=classAttrs, - cache=cache, - graph=graph, - functionTree=functionTree, - info=ei)) := dae; // collect vars and eqns for initial system vars := BackendVariable.emptyVars(); @@ -133,13 +116,13 @@ algorithm eqns := BackendEquation.emptyEqns(); reeqns := BackendEquation.emptyEqns(); - ((vars, fixvars, eqns, _)) := BackendVariable.traverseBackendDAEVars(avars, introducePreVarsForAliasVariables, (vars, fixvars, eqns, hs)); - ((vars, fixvars, eqns, _)) := BackendVariable.traverseBackendDAEVars(knvars, collectInitialVars, (vars, fixvars, eqns, hs)); - ((eqns, reeqns)) := BackendEquation.traverseEquationArray(inieqns, collectInitialEqns, (eqns, reeqns)); + ((vars, fixvars, eqns, _)) := BackendVariable.traverseBackendDAEVars(dae.shared.aliasVars, introducePreVarsForAliasVariables, (vars, fixvars, eqns, hs)); + ((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"); - ((vars, fixvars, eqns, reeqns, _)) := List.fold(systs, collectInitialVarsEqnsSystem, ((vars, fixvars, eqns, reeqns, hs))); + ((vars, fixvars, eqns, reeqns, _)) := List.fold(dae.eqs, collectInitialVarsEqnsSystem, ((vars, fixvars, eqns, reeqns, hs))); ((eqns, reeqns)) := BackendVariable.traverseBackendDAEVars(vars, collectInitialBindings, (eqns, reeqns)); @@ -148,11 +131,11 @@ algorithm vars := BackendVariable.rehashVariables(vars); fixvars := BackendVariable.rehashVariables(fixvars); - shared := BackendDAEUtil.createEmptyShared(BackendDAE.INITIALSYSTEM(), ei, cache, graph); + shared := BackendDAEUtil.createEmptyShared(BackendDAE.INITIALSYSTEM(), dae.shared.info, dae.shared.cache, dae.shared.graph); shared := BackendDAEUtil.setSharedKnVars(shared, fixvars); - shared := BackendDAEUtil.setSharedOptimica(shared, constraints, classAttrs); + shared := BackendDAEUtil.setSharedOptimica(shared, dae.shared.constraints, dae.shared.classAttrs); shared := BackendDAEUtil.setSharedRemovedEqns(shared, reeqns); - shared := BackendDAEUtil.setSharedFunctionTree(shared, functionTree); + shared := BackendDAEUtil.setSharedFunctionTree(shared, dae.shared.functionTree); // generate initial system and pre-balance it initsyst := BackendDAEUtil.createEqSystem(vars, eqns); @@ -237,6 +220,7 @@ algorithm if Flags.isSet(Flags.ITERATION_VARS) then BackendDAEOptimize.listAllIterationVariables(initdae); end if; + if Flags.isSet(Flags.DUMP_BACKENDDAE_INFO) or Flags.isSet(Flags.DUMP_STATESELECTION_INFO) or Flags.isSet(Flags.DUMP_DISCRETEVARS_INFO) then BackendDump.dumpCompShort(initdae); end if; @@ -342,7 +326,7 @@ algorithm then eqns; // algorithm - case BackendDAE.ALGORITHM(alg=alg, source=source,expand=crefExpand) equation + case BackendDAE.ALGORITHM(alg=alg, source=source, expand=crefExpand) equation DAE.ALGORITHM_STMTS(statementLst=stmts) = alg; (stmts, leftCrs) = inlineWhenForInitializationWhenAlgorithm(stmts, {}, HashSet.emptyHashSetSized(50)); alg = DAE.ALGORITHM_STMTS(stmts); @@ -362,27 +346,17 @@ protected function inlineWhenForInitializationWhenEquation "author: lochel" input BackendDAE.EquationAttributes inEqAttr; input list inEqns; output list outEqns; +protected + DAE.Exp crexp; + BackendDAE.Equation eqn; algorithm - outEqns := matchcontinue(inWEqn) - local - DAE.ComponentRef left; - DAE.Exp condition, right, crexp; - BackendDAE.Equation eqn; - list eqns; - - // active when equation during initialization - case BackendDAE.WHEN_EQ(condition=condition, left=left, right=right) equation - true = Expression.containsInitialCall(condition, false); // do not use Expression.traverseExpBottomUp - crexp = Expression.crefExp(left); - eqn = BackendEquation.generateEquation(crexp, right, inSource, inEqAttr); - then eqn::inEqns; - - // inactive when equation during initialization - case BackendDAE.WHEN_EQ(condition=condition, left=left) equation - false = Expression.containsInitialCall(condition, false); - eqns = generateInactiveWhenEquationForInitialization(ComponentReference.expandCref(left, true), inSource, inEqns); - then eqns; - end matchcontinue; + if Expression.containsInitialCall(inWEqn.condition, false) then + crexp := Expression.crefExp(inWEqn.left); + eqn := BackendEquation.generateEquation(crexp, inWEqn.right, inSource, inEqAttr); + outEqns := eqn::inEqns; + else + outEqns := generateInactiveWhenEquationForInitialization(ComponentReference.expandCref(inWEqn.left, true), inSource, inEqns); + end if; end inlineWhenForInitializationWhenEquation; protected function inlineWhenForInitializationWhenAlgorithm "author: lochel @@ -489,16 +463,13 @@ protected function collectPreVariables "author: lochel" input BackendDAE.BackendDAE inDAE; output HashSet.HashSet outHS; protected - BackendDAE.EquationArray ieqns, removedEqs; //list crefs; algorithm //BackendDump.dumpBackendDAE(inDAE, "inDAE"); - BackendDAE.DAE(shared=BackendDAE.SHARED(removedEqs=removedEqs, initialEqs=ieqns)) := inDAE; - outHS := HashSet.emptyHashSet(); outHS := List.fold(inDAE.eqs, collectPreVariablesEqSystem, outHS); - ((_,outHS)) := BackendDAEUtil.traverseBackendDAEExpsEqns(removedEqs, Expression.traverseSubexpressionsHelper, (collectPreVariablesTraverseExp, outHS)); // ??? - ((_,outHS)) := BackendDAEUtil.traverseBackendDAEExpsEqns(ieqns, Expression.traverseSubexpressionsHelper, (collectPreVariablesTraverseExp, outHS)); + ((_, outHS)) := BackendDAEUtil.traverseBackendDAEExpsEqns(inDAE.shared.removedEqs, Expression.traverseSubexpressionsHelper, (collectPreVariablesTraverseExp, outHS)); // ??? + ((_, outHS)) := BackendDAEUtil.traverseBackendDAEExpsEqns(inDAE.shared.initialEqs, Expression.traverseSubexpressionsHelper, (collectPreVariablesTraverseExp, outHS)); //print("collectPreVariables:\n"); //crefs := BaseHashSet.hashSetList(outHS); @@ -581,7 +552,7 @@ algorithm outWarning := outWarning or warn; // If we found an iteration variable with default zero start attribute but - // +initialization wasn't given, we don't need to continue searching. + // +d=initialization wasn't given, we don't need to continue searching. if warn and not inShowWarnings then return; end if; @@ -628,10 +599,9 @@ algorithm outWarning := true; if inShowWarnings then - Error.addCompilerWarning("Iteration variables with default zero start attribute in " - + err + warnAboutVars2(vars)); + Error.addCompilerWarning("Iteration variables with default zero start attribute in " + err + warnAboutVars2(vars)); else - // If +initialization wasn't given we don't need to continue searching + // If +d=initialization wasn't given we don't need to continue searching // once we've found one. return; end if; @@ -705,7 +675,7 @@ protected function selectInitializationVariablesDAE "author: lochel output list outPrimaryParameters = {}; output list outAllPrimaryParameters = {}; protected - BackendDAE.Variables knownVars, alias, allParameters; + BackendDAE.Variables allParameters; BackendDAE.EquationArray allParameterEqns; BackendDAE.EqSystem paramSystem; BackendDAE.IncidenceMatrix m, mT; @@ -718,15 +688,14 @@ protected BackendDAE.Var p; DAE.Exp bindExp; algorithm - BackendDAE.DAE(shared=BackendDAE.SHARED(knownVars=knownVars, aliasVars=alias)) := inDAE; outVars := selectInitializationVariables(inDAE.eqs); - outVars := BackendVariable.traverseBackendDAEVars(knownVars, selectInitializationVariables2, outVars); - outVars := BackendVariable.traverseBackendDAEVars(alias, selectInitializationVariables2, outVars); + outVars := BackendVariable.traverseBackendDAEVars(inDAE.shared.knownVars, selectInitializationVariables2, outVars); + outVars := BackendVariable.traverseBackendDAEVars(inDAE.shared.aliasVars, selectInitializationVariables2, outVars); // select all parameters allParameters := BackendVariable.emptyVars(); allParameterEqns := BackendEquation.emptyEqns(); - (allParameters, allParameterEqns) := BackendVariable.traverseBackendDAEVars(knownVars, selectParameter2, (allParameters, allParameterEqns)); + (allParameters, allParameterEqns) := BackendVariable.traverseBackendDAEVars(inDAE.shared.knownVars, selectParameter2, (allParameters, allParameterEqns)); nParam := BackendVariable.varsSize(allParameters); if nParam > 0 then @@ -948,7 +917,7 @@ protected function simplifyInitialFunctionsExp output DAE.Exp outExp; output Boolean outUseHomotopy; algorithm - (outExp,outUseHomotopy) := match (inExp,useHomotopy) + (outExp, outUseHomotopy) := match (inExp, useHomotopy) local DAE.Exp e1, e2, e3, actual, simplified; @@ -1217,14 +1186,14 @@ algorithm // get state-index list stateIndices := BackendVariable.getVarIndexFromVariables(inInitVars, inVars); -//print("{" + stringDelimitList(List.map(stateIndices, intString),",") + "}\n"); +//print("{" + stringDelimitList(List.map(stateIndices, intString), ",") + "}\n"); // get initial equation-index list //(initEqs, _) := List.extractOnTrue(BackendEquation.equationList(inEqns), BackendEquation.isInitialEquation); //nInitEqs := BackendDAEUtil.equationSize(BackendEquation.listEquation(initEqs)); ((_, initEqsIndices)) := List.fold(BackendEquation.equationList(inEqns), getInitEqIndex, (1, {})); nInitEqs := listLength(initEqsIndices); -//print("{" + stringDelimitList(List.map(initEqsIndices, intString),",") + "}\n"); +//print("{" + stringDelimitList(List.map(initEqsIndices, intString), ",") + "}\n"); // modify incidence matrix for under-determined systems nAddEqs := intMax(nVars-nEqns + inIndex, inIndex); @@ -1258,10 +1227,10 @@ algorithm // map artificial variables to redundant equations range := if nAddVars > 0 then List.intRange2(nVars+1, nVars+nAddVars) else {}; redundantEqns := mapIndices(range, ass1); -//print("{" + stringDelimitList(List.map(redundantEqns, intString),",") + "}\n"); +//print("{" + stringDelimitList(List.map(redundantEqns, intString), ",") + "}\n"); // symbolic consistency check - (me, _, _, _) := BackendDAEUtil.getAdjacencyMatrixEnhancedScalar(syst, inShared,false); + (me, _, _, _) := BackendDAEUtil.getAdjacencyMatrixEnhancedScalar(syst, inShared, false); (_, _, _) := consistencyCheck(redundantEqns, inEqns, inVars, inShared, nAddVars, m_, me, ass1, ass2, mapIncRowEqn); // remove redundant equations @@ -1273,7 +1242,7 @@ algorithm // map artificial equations to unfixed states range := if nAddEqs > 0 then List.intRange2(nEqns+1, nEqns+nAddEqs) else {}; range := mapIndices(range, ass2); -//print("{" + stringDelimitList(List.map(range, intString),",") + "}\n"); +//print("{" + stringDelimitList(List.map(range, intString), ",") + "}\n"); // introduce additional initial equations initVarList := List.map1r(range, BackendVariable.getVarAt, inVars); @@ -1287,27 +1256,21 @@ protected function fixUnderDeterminedSystem "author: lochel" input Integer inNEqns; input Integer inNAddEqns; output BackendDAE.IncidenceMatrix outM; +protected + list newEqIndices; algorithm - outM := match(inM, inInitVarIndices, inNEqns, inNAddEqns) - local - BackendDAE.IncidenceMatrix m; - list newEqIndices; - - case (_, _, _, 0) - then inM; - - //case (_, {}, _, _) equation - // print("Error!!!!\n"); - //then fail(); - - case (_, _, _, _) equation - true = (inNAddEqns > 0) "just to be careful"; - m = arrayCreate(inNEqns+inNAddEqns, {}); - m = Array.copy(inM, m); - newEqIndices = List.intRange2(inNEqns+1, inNEqns+inNAddEqns); - m = List.fold1(newEqIndices, squareIncidenceMatrix1, inInitVarIndices, m); - then m; - end match; + if inNAddEqns < 0 then + Error.addInternalError("function fixUnderDeterminedSystem failed due to invalid input", sourceInfo()); + fail(); + end if; + + outM := arrayCreate(inNEqns+inNAddEqns, {}); + outM := Array.copy(inM, outM); + + if inNAddEqns > 0 then + newEqIndices := List.intRange2(inNEqns+1, inNEqns+inNAddEqns); + outM := List.fold1(newEqIndices, squareIncidenceMatrix1, inInitVarIndices, outM); + end if; end fixUnderDeterminedSystem; protected function squareIncidenceMatrix1 "author: lochel" @@ -1325,25 +1288,20 @@ protected function fixOverDeterminedSystem "author: lochel" input Integer inNVars; input Integer inNAddVars; output BackendDAE.IncidenceMatrix outM; +protected + list newVarIndices; algorithm - outM := match(inM, inInitEqnIndices, inNVars, inNAddVars) - local - BackendDAE.IncidenceMatrix m; - list newVarIndices; - - case (_, _, _, 0) - then inM; - - //case (_, {}, _, _) equation - // print("Error!!!!\n"); - //then fail(); + if inNAddVars < 0 then + Error.addInternalError("function fixOverDeterminedSystem failed due to invalid input", sourceInfo()); + fail(); + end if; - case (_, _, _, _) equation - true = (inNAddVars > 0) "just to be careful"; - newVarIndices = List.intRange2(inNVars+1, inNVars+inNAddVars); - m = List.fold1(inInitEqnIndices, squareIncidenceMatrix2, newVarIndices, inM); - then m; - end match; + if inNAddVars > 0 then + newVarIndices := List.intRange2(inNVars+1, inNVars+inNAddVars); + outM := List.fold1(inInitEqnIndices, squareIncidenceMatrix2, newVarIndices, inM); + else + outM := inM; + end if; end fixOverDeterminedSystem; protected function squareIncidenceMatrix2 "author: lochel" @@ -1903,7 +1861,7 @@ protected function introducePreVarsForAliasVariables "author: lochel output BackendDAE.Var outVar; output tuple outTpl; algorithm - (outVar,outTpl) := matchcontinue(inVar, inTpl) + (outVar, outTpl) := matchcontinue(inVar, inTpl) local BackendDAE.Var var; DAE.ComponentRef cr; @@ -2301,7 +2259,7 @@ protected function collectInitialBindings "author: lochel output BackendDAE.Var outVar; output tuple outTpl; algorithm - (outVar,outTpl) := match (inVar, inTpl) + (outVar, outTpl) := match (inVar, inTpl) local BackendDAE.Var var; DAE.ComponentRef cr; diff --git a/Compiler/BackEnd/StateMachineFeatures.mo b/Compiler/BackEnd/StateMachineFeatures.mo index d75203b8caf..28a1f0fa274 100644 --- a/Compiler/BackEnd/StateMachineFeatures.mo +++ b/Compiler/BackEnd/StateMachineFeatures.mo @@ -1766,19 +1766,13 @@ protected array> equOptArr; DAE.VarInnerOuter io1, io2; // EQSYSTEM - BackendDAE.Variables orderedVars "ordered Variables, only states and alg. vars"; - BackendDAE.EquationArray orderedEqs "ordered Equations"; - Option m; - Option mT; - BackendDAE.Matching matching; - BackendDAE.StateSets stateSets "the statesets of the system"; - BackendDAE.BaseClockPartitionKind partitionKind; + BackendDAE.Variables orderedVars; algorithm (modes,syst) := inModesSyst; (keyCref,mode) := inCrefMode; - MODE(name,isInitial,edges,eqs,outgoing,outShared,outLocal,crefPrevious) := mode; - BackendDAE.EQUATION_ARRAY(size,numberOfElement,arrSize,equOptArr) := eqs; - BackendDAE.EQSYSTEM(orderedVars,orderedEqs,m,mT,matching,stateSets,partitionKind) := syst; + MODE(name, isInitial, edges, eqs, outgoing, outShared, outLocal, crefPrevious) := mode; + BackendDAE.EQUATION_ARRAY(size, numberOfElement, arrSize, equOptArr) := eqs; + BackendDAE.EQSYSTEM(orderedVars=orderedVars) := syst; outSharedNew := {}; for outVar in outShared loop @@ -1792,18 +1786,18 @@ algorithm if isSome(innerOptCref) then // Remove the equation relating inner and outer - arrayUpdate(equOptArr,i,NONE()); + arrayUpdate(equOptArr, i, NONE()); size := size - 1; //numberOfElement := numberOfElement - 1; - eqs := BackendDAE.EQUATION_ARRAY(size,numberOfElement,arrSize,equOptArr); + eqs := BackendDAE.EQUATION_ARRAY(size, numberOfElement, arrSize, equOptArr); // replace all outer crefs by their corresponding inner cref - (eqs,_) := BackendEquation.traverseEquationArray_WithUpdate(eqs,subsOuterByInnerEq,(outCref,Util.getOption(innerOptCref))); + (eqs,_) := BackendEquation.traverseEquationArray_WithUpdate(eqs, subsOuterByInnerEq, (outCref,Util.getOption(innerOptCref))); // update outSharedNew and use that later to construct MODE - ({innerVar},_) := BackendVariable.getVar(Util.getOption(innerOptCref),orderedVars); + ({innerVar}, _) := BackendVariable.getVar(Util.getOption(innerOptCref), orderedVars); outSharedNew := innerVar :: outSharedNew; // replace possible outer crefs in "crefPrevious" by their corresponding inner - crefPrevious := List.replaceOnTrue(Util.getOption(innerOptCref),crefPrevious,function ComponentReference.crefEqual(inComponentRef1=outCref)); - + crefPrevious := List.replaceOnTrue( Util.getOption(innerOptCref), crefPrevious, + function ComponentReference.crefEqual(inComponentRef1=outCref) ); // Remove variable from BackendDAE variables (the corresponding element in the variable array is set to NONE()) orderedVars := BackendVariable.removeCref(outCref,orderedVars); success := true; @@ -1811,7 +1805,7 @@ algorithm end if; end for; - assert(success, "Expect to find inner variable corresponding to outer variable "+ComponentReference.crefStr(outCref)); + assert(success, "Expect to find inner variable corresponding to outer variable " + ComponentReference.crefStr(outCref)); end for; // Rebuild "orderedVars" in order to eliminate intermediate "NONE()" entries in variable array. @@ -1822,7 +1816,7 @@ algorithm mode := MODE(name,isInitial,edges,eqs,outgoing,listReverse(outSharedNew),outLocal,crefPrevious); modes := BaseHashTable.update((keyCref, mode), modes); - syst := BackendDAE.EQSYSTEM(orderedVars,orderedEqs,m,mT,matching,stateSets,partitionKind); + syst.orderedVars := orderedVars; outModesSyst := (modes,syst); end elaborateMode; diff --git a/Compiler/BackEnd/SymbolicJacobian.mo b/Compiler/BackEnd/SymbolicJacobian.mo index 513c6ed9d3b..f822ea21480 100644 --- a/Compiler/BackEnd/SymbolicJacobian.mo +++ b/Compiler/BackEnd/SymbolicJacobian.mo @@ -370,30 +370,27 @@ protected function replaceStrongComponent "replaces the indexed component with c input Integer idx; input BackendDAE.StrongComponents compsNew; input BackendDAE.StrongComponents compsAdd; - output BackendDAE.EqSystem systOut; + output BackendDAE.EqSystem systOut = systIn; protected BackendDAE.Variables orderedVars; BackendDAE.EquationArray orderedEqs; BackendDAE.Matching matching; - BackendDAE.StateSets stateSets ; - BackendDAE.BaseClockPartitionKind partitionKind; - array ass1,ass2,ass1add,ass2add; + array ass1, ass2, ass1add, ass2add; BackendDAE.StrongComponents comps; algorithm - BackendDAE.EQSYSTEM(orderedVars=orderedVars,orderedEqs=orderedEqs,matching=matching,stateSets=stateSets,partitionKind=partitionKind) := systIn; - BackendDAE.MATCHING(ass1=ass1,ass2=ass2,comps=comps) := matching; + BackendDAE.EQSYSTEM(matching=BackendDAE.MATCHING(ass1=ass1, ass2=ass2, comps=comps)) := systIn; if not listEmpty(compsAdd) then - ass1add := arrayCreate(listLength(compsAdd),0); - ass2add := arrayCreate(listLength(compsAdd),0); - ass1 := arrayAppend(ass1,ass1add); - ass2 := arrayAppend(ass2,ass1add); - List.map2_0(compsAdd,updateAssignment,ass1,ass2); + ass1add := arrayCreate(listLength(compsAdd), 0); + ass2add := arrayCreate(listLength(compsAdd), 0); + ass1 := arrayAppend(ass1, ass1add); + ass2 := arrayAppend(ass2, ass1add); + List.map2_0(compsAdd, updateAssignment, ass1, ass2); end if; - List.map2_0(compsNew,updateAssignment,ass1,ass2); - comps := List.replaceAtWithList(compsNew,idx-1,comps); - comps := listAppend(comps,compsAdd); - matching := BackendDAE.MATCHING(ass1,ass2,comps); - systOut := BackendDAE.EQSYSTEM(orderedVars,orderedEqs,NONE(),NONE(),matching,stateSets,partitionKind); + List.map2_0(compsNew, updateAssignment, ass1, ass2); + comps := List.replaceAtWithList(compsNew, idx-1, comps); + comps := listAppend(comps, compsAdd); + systOut.matching := BackendDAE.MATCHING(ass1, ass2, comps); + systOut := BackendDAEUtil.setEqSystMatrices(systOut); end replaceStrongComponent; protected function updateAssignment @@ -739,8 +736,8 @@ protected function constantLinearSystemWork output Integer sysIdxOut; output Integer compIdxOut; algorithm - (osyst,oshared,outRunMatching,sysIdxOut,compIdxOut):= - matchcontinue (isyst,ishared,comp,sysIdxIn,compIdxIn) + (osyst, oshared, outRunMatching, sysIdxOut, compIdxOut):= + matchcontinue (isyst, ishared, comp) local BackendDAE.Variables vars; BackendDAE.EquationArray eqns; @@ -764,18 +761,22 @@ algorithm BackendDAE.StateSets stateSets; BackendDAE.BaseClockPartitionKind partitionKind; - case (syst as BackendDAE.EQSYSTEM(orderedVars=vars,orderedEqs=eqns), shared,(BackendDAE.EQUATIONSYSTEM(eqns=eindex,vars=vindx,jac=BackendDAE.FULL_JACOBIAN(SOME(jac)),jacType=BackendDAE.JAC_CONSTANT())),_,_) + case (syst, shared, (BackendDAE.EQUATIONSYSTEM( eqns=eindex, vars=vindx, jac=BackendDAE.FULL_JACOBIAN(SOME(jac)), + jacType=BackendDAE.JAC_CONSTANT() ))) equation //the A-matrix and the b-Vector are constant - eqn_lst = BackendEquation.getEqns(eindex,eqns); - var_lst = List.map1r(vindx, BackendVariable.getVarAt, vars); - (syst,shared) = solveLinearSystem(syst,shared,eqn_lst,eindex,var_lst,vindx,jac); + eqn_lst = BackendEquation.getEqns(eindex, syst.orderedEqs); + var_lst = List.map1r(vindx, BackendVariable.getVarAt, syst.orderedVars); + (syst,shared) = solveLinearSystem(syst, shared, eqn_lst, eindex, var_lst, vindx, jac); then (syst,shared,true,sysIdxIn,compIdxIn+1); - case (syst as BackendDAE.EQSYSTEM(orderedVars=vars,orderedEqs=eqns,matching=matching,stateSets=stateSets, partitionKind=partitionKind),shared,(BackendDAE.EQUATIONSYSTEM(eqns=eindex,vars=vindx,jac=BackendDAE.FULL_JACOBIAN(SOME(jac)),jacType=BackendDAE.JAC_LINEAR())),_,_) + + case ( syst as BackendDAE.EQSYSTEM(orderedVars=vars, orderedEqs=eqns), shared, + BackendDAE.EQUATIONSYSTEM( eqns=eindex, vars=vindx, jac=BackendDAE.FULL_JACOBIAN(SOME(jac)), + jacType=BackendDAE.JAC_LINEAR() ) ) equation true = BackendDAEUtil.isSimulationDAE(ishared); //only the A-matrix is constant, apply Gaussian Elimination - eqn_lst = BackendEquation.getEqns(eindex,eqns); + eqn_lst = BackendEquation.getEqns(eindex, eqns); var_lst = List.map1r(vindx, BackendVariable.getVarAt, vars); true = jacobianIsConstant(jac); true = Flags.isSet(Flags.CONSTJAC); @@ -785,7 +786,8 @@ algorithm //BackendDump.dumpEqnsSolved2({comp},eqns,vars); eqn_lst = BackendEquation.getEqns(eindex,eqns); var_lst = List.map1r(vindx, BackendVariable.getVarAt, vars); - (sysEqs,bEqs,bVars,order,sysIdx) = solveConstJacLinearSystem(syst,shared,eqn_lst,eindex,listReverse(var_lst),vindx,jac,sysIdxIn,compIdxIn); + (sysEqs, bEqs, bVars, order, sysIdx) = + solveConstJacLinearSystem(syst, shared, eqn_lst, eindex, listReverse(var_lst), vindx, jac, sysIdxIn, compIdxIn); //print("the b-vector stuff \n"); //BackendDump.printEquationList(bEqs); //BackendDump.printVarList(bVars); @@ -796,28 +798,29 @@ algorithm //print("numberOfElement"+intString(BackendDAEUtil.equationArraySize(eqns))+"\n"); //print("arrSize"+intString(BackendDAEUtil.equationArraySize2(eqns))+"\n"); //print("length"+intString(listLength(BackendEquation.equationList(eqns)))+"\n"); - bVarIdcs = List.intRange2(BackendVariable.varsSize(vars)+1,BackendVariable.varsSize(vars)+listLength(bVars)); - bEqIdcs = List.intRange2(BackendDAEUtil.equationArraySize(eqns)+1,BackendDAEUtil.equationArraySize(eqns)+listLength(bEqs)); - bComps = List.threadMap(bEqIdcs,bVarIdcs,BackendDAEUtil.makeSingleEquationComp); - sysComps = List.threadMap(List.map1(arrayList(order),List.getIndexFirst,eindex),listReverse(vindx),BackendDAEUtil.makeSingleEquationComp); + bVarIdcs = List.intRange2(BackendVariable.varsSize(vars)+1, BackendVariable.varsSize(vars)+listLength(bVars)); + bEqIdcs = List.intRange2(BackendDAEUtil.equationArraySize(eqns)+1, BackendDAEUtil.equationArraySize(eqns)+listLength(bEqs)); + bComps = List.threadMap(bEqIdcs, bVarIdcs, BackendDAEUtil.makeSingleEquationComp); + sysComps = List.threadMap( List.map1(arrayList(order), List.getIndexFirst, eindex), listReverse(vindx), + BackendDAEUtil.makeSingleEquationComp ); //print("bCOMPS\n"); //BackendDump.dumpComponents(bComps); //print("SYSCOMPS\n"); //BackendDump.dumpComponents(sysComps); //build system - vars = List.fold(bVars, BackendVariable.addVar, vars); + syst.orderedVars = List.fold(bVars, BackendVariable.addVar, vars); eqns = List.fold(bEqs, BackendEquation.addEquation, eqns); - eqns = List.threadFold(eindex,sysEqs,BackendEquation.setAtIndexFirst,eqns); - syst = BackendDAE.EQSYSTEM(vars, eqns, NONE(), NONE(), matching, stateSets, partitionKind); + syst.orderedEqs = List.threadFold(eindex, sysEqs, BackendEquation.setAtIndexFirst, eqns); + syst = BackendDAEUtil.setEqSystMatrices(syst); syst = replaceStrongComponent(syst,compIdxIn,sysComps,bComps); //print("compIdxIn"+intString(compIdxIn)+"\n"); - then (syst,ishared,false,sysIdx,compIdxIn+listLength(sysComps)); - else (isyst,ishared,false,sysIdxIn,compIdxIn+1); + then (syst, ishared, false, sysIdx, compIdxIn+listLength(sysComps)); + else (isyst, ishared, false, sysIdxIn, compIdxIn+1); end matchcontinue; end constantLinearSystemWork; protected function solveLinearSystem - input BackendDAE.EqSystem syst; + input BackendDAE.EqSystem inSyst; input BackendDAE.Shared ishared; input list eqn_lst; input list eqn_indxs; @@ -827,39 +830,39 @@ protected function solveLinearSystem output BackendDAE.EqSystem osyst; output BackendDAE.Shared oshared; algorithm - (osyst,oshared):= - match (syst,ishared,eqn_lst,eqn_indxs,var_lst,var_indxs,jac) + (osyst, oshared) := match (inSyst, ishared) local - BackendDAE.Variables vars,vars1,v; - BackendDAE.EquationArray eqns,eqns1, eqns2; + BackendDAE.Variables v; + BackendDAE.EquationArray eqns, eqns1; list beqs; list sources; list rhsVals,solvedVals; list> jacVals; Integer linInfo; list names; - BackendDAE.Matching matching; DAE.FunctionTree funcs; BackendDAE.Shared shared; - BackendDAE.StateSets stateSets; - BackendDAE.BaseClockPartitionKind partitionKind; + BackendDAE.EqSystem syst; - case (BackendDAE.EQSYSTEM(orderedVars=vars,orderedEqs=eqns,matching=matching,stateSets=stateSets,partitionKind=partitionKind),BackendDAE.SHARED(functionTree=funcs),_,_,_,_,_) + case (syst as BackendDAE.EQSYSTEM(), BackendDAE.SHARED(functionTree=funcs)) equation eqns1 = BackendEquation.listEquation(eqn_lst); v = BackendVariable.listVar1(var_lst); - (beqs,sources) = BackendDAEUtil.getEqnSysRhs(eqns1,v,SOME(funcs)); + (beqs, sources) = BackendDAEUtil.getEqnSysRhs(eqns1, v, SOME(funcs)); beqs = listReverse(beqs); - rhsVals = ValuesUtil.valueReals(List.map(beqs,Ceval.cevalSimple)); - jacVals = evaluateConstantJacobian(listLength(var_lst),jac); - (solvedVals,linInfo) = System.dgesv(jacVals,rhsVals); - names = List.map(var_lst,BackendVariable.varCref); - checkLinearSystem(linInfo,names,jacVals,rhsVals,eqn_lst); - sources = List.map1(sources, DAEUtil.addSymbolicTransformation, DAE.LINEAR_SOLVED(names,jacVals,rhsVals,solvedVals)); - (vars1,eqns2,shared) = changeConstantLinearSystemVars(var_lst,solvedVals,sources,var_indxs,vars,eqns,ishared); - eqns = List.fold(eqn_indxs,BackendEquation.equationRemove,eqns2); + rhsVals = ValuesUtil.valueReals(List.map(beqs, Ceval.cevalSimple)); + jacVals = evaluateConstantJacobian(listLength(var_lst), jac); + (solvedVals, linInfo) = System.dgesv(jacVals, rhsVals); + names = List.map(var_lst, BackendVariable.varCref); + checkLinearSystem(linInfo, names, jacVals, rhsVals, eqn_lst); + sources = List.map1( sources, DAEUtil.addSymbolicTransformation, + DAE.LINEAR_SOLVED(names, jacVals, rhsVals, solvedVals) ); + (v, eqns, shared) = changeConstantLinearSystemVars( var_lst, solvedVals, sources, var_indxs, + syst.orderedVars, syst.orderedEqs, ishared ); + syst.orderedVars = v; + syst.orderedEqs = List.fold(eqn_indxs, BackendEquation.equationRemove, eqns); then - (BackendDAE.EQSYSTEM(vars1,eqns,NONE(),NONE(),matching,stateSets,partitionKind),shared); + (BackendDAEUtil.setEqSystMatrices(syst), shared); end match; end solveLinearSystem; @@ -1749,40 +1752,35 @@ protected function optimizeJacobianMatrix "author: wbraun" input list inComRef1 "eqnvars"; input list inComRef2 "vars to differentiate"; output BackendDAE.BackendDAE outJacobian; +protected + array ea = listArray({}); + BackendDAE.Matching eMatching = BackendDAE.MATCHING(ea, ea, {}); algorithm outJacobian := matchcontinue (inBackendDAE,inComRef1,inComRef2) local BackendDAE.BackendDAE backendDAE, backendDAE2; - BackendDAE.Variables v; - BackendDAE.EquationArray e; - + BackendDAE.EqSystem syst; BackendDAE.Shared shared; - array ea; - - Option om,omT; Boolean b; - BackendDAE.StateSets stateSets; - BackendDAE.BaseClockPartitionKind partitionKind; - case (BackendDAE.DAE(BackendDAE.EQSYSTEM(orderedVars=v,orderedEqs=e,m=om,mT=omT,stateSets=stateSets,partitionKind=partitionKind)::{},shared),{},_) + case (BackendDAE.DAE(syst::{}, shared), {}, _) equation - v = BackendVariable.listVar({}); - ea = listArray({}); - then (BackendDAE.DAE(BackendDAE.EQSYSTEM(v,e,om,omT,BackendDAE.MATCHING(ea,ea,{}),stateSets,partitionKind)::{},shared)); - case (BackendDAE.DAE(BackendDAE.EQSYSTEM(orderedVars=v,orderedEqs=e,m=om,mT=omT,stateSets=stateSets,partitionKind=partitionKind)::{},shared),_,{}) + syst.orderedVars = BackendVariable.listVar({}); + syst.matching = eMatching; + then BackendDAE.DAE(syst::{}, shared); + case (BackendDAE.DAE(syst::{}, shared), _, {}) equation - v = BackendVariable.listVar({}); - ea = listArray({}); - then (BackendDAE.DAE(BackendDAE.EQSYSTEM(v,e,om,omT,BackendDAE.MATCHING(ea,ea,{}),stateSets,partitionKind)::{},shared)); - case (backendDAE,_,_) + syst.orderedVars = BackendVariable.listVar({}); + syst.matching = eMatching; + then BackendDAE.DAE(syst::{}, shared); + case (backendDAE, _, _) equation if Flags.isSet(Flags.JAC_DUMP2) then print("analytical Jacobians -> optimize jacobians time: " + realString(clock()) + "\n"); end if; b = Flags.disableDebug(Flags.EXEC_STAT); - if Flags.isSet(Flags.JAC_DUMP) then BackendDump.bltdump("Symbolic Jacobian",backendDAE); end if; @@ -2140,21 +2138,19 @@ algorithm (outSyst, outShared) := match (inSyst, inShared) local BackendDAE.EqSystem syst; - list systs; BackendDAE.Shared shared; array ass1; array ass2; BackendDAE.StrongComponents comps; BackendDAE.Variables vars; BackendDAE.EquationArray eqns; - Option m; - Option mT; - BackendDAE.StateSets stateSets; - BackendDAE.BaseClockPartitionKind partitionKind; - case (BackendDAE.EQSYSTEM(vars, eqns, m, mT, BackendDAE.MATCHING(ass1,ass2,comps), stateSets, partitionKind), shared) equation - (comps, shared) = calculateJacobiansComponents(comps, vars, eqns, shared, {}); - then (BackendDAE.EQSYSTEM(vars, eqns, m, mT, BackendDAE.MATCHING(ass1,ass2,comps), stateSets, partitionKind), shared); + case (syst as BackendDAE.EQSYSTEM( orderedVars=vars, orderedEqs=eqns, + matching=BackendDAE.MATCHING(ass1,ass2,comps) ), shared) + equation + (comps, shared) = calculateJacobiansComponents(comps, vars, eqns, shared, {}); + syst.matching = BackendDAE.MATCHING(ass1, ass2, comps); + then (syst, shared); end match; end calculateEqSystemJacobians; @@ -2568,24 +2564,18 @@ algorithm (outSyst,outShared) := match (inSyst, inShared) local BackendDAE.EqSystem syst; - list systs; BackendDAE.Shared shared; - array ass1; - array ass2; BackendDAE.StrongComponents comps; BackendDAE.Variables vars; BackendDAE.EquationArray eqns; - Option m; - Option mT; BackendDAE.StateSets stateSets; - BackendDAE.Matching matching; - BackendDAE.BaseClockPartitionKind partitionKind; - case (syst as BackendDAE.EQSYSTEM(vars, eqns, m, mT, matching, stateSets, partitionKind), shared) + case (syst as BackendDAE.EQSYSTEM(orderedVars=vars, orderedEqs = eqns, stateSets=stateSets), shared) equation comps = BackendDAEUtil.getStrongComponents(syst); (stateSets, shared) = calculateStateSetsJacobian(stateSets, vars, eqns, comps, shared, {}); - then (BackendDAE.EQSYSTEM(vars, eqns, m, mT, matching, stateSets, partitionKind), shared); + syst.stateSets = stateSets; + then (syst, shared); end match; end calculateEqSystemStateSetsJacobians; diff --git a/Compiler/FrontEnd/DAE.mo b/Compiler/FrontEnd/DAE.mo index a68bb3e4edc..86797b27196 100644 --- a/Compiler/FrontEnd/DAE.mo +++ b/Compiler/FrontEnd/DAE.mo @@ -819,7 +819,17 @@ constant Type T_FUNCTION_DEFAULT = T_FUNCTION({},T_ANYTYPE_DEFAULT,FUNCTION_A constant Type T_METATYPE_DEFAULT = T_METATYPE(T_UNKNOWN_DEFAULT, emptyTypeSource); constant Type T_COMPLEX_DEFAULT = T_COMPLEX(ClassInf.UNKNOWN(Absyn.IDENT("")), {}, NONE(), emptyTypeSource) "default complex with unknown CiState"; constant Type T_COMPLEX_DEFAULT_RECORD = T_COMPLEX(ClassInf.RECORD(Absyn.IDENT("")), {}, NONE(), emptyTypeSource) "default complex with record CiState"; -constant Type T_SOURCEINFO_DEFAULT = T_METAUNIONTYPE({Absyn.QUALIFIED("SourceInfo",Absyn.IDENT("SOURCEINFO"))},true,{"fileName","isReadOnly","lineNumberStart","columnNumberStart","lineNumberEnd","columnNumberEnd","lastModification"},Absyn.IDENT("SourceInfo")::{}); + +constant Type T_SOURCEINFO_DEFAULT_METARECORD = T_METARECORD(Absyn.QUALIFIED("SourceInfo",Absyn.IDENT("SOURCEINFO")), 1, { + TYPES_VAR("fileName", dummyAttrVar, T_STRING_DEFAULT, UNBOUND(), NONE()), + TYPES_VAR("isReadOnly", dummyAttrVar, T_BOOL_DEFAULT, UNBOUND(), NONE()), + TYPES_VAR("lineNumberStart", dummyAttrVar, T_INTEGER_DEFAULT, UNBOUND(), NONE()), + TYPES_VAR("columnNumberStart", dummyAttrVar, T_INTEGER_DEFAULT, UNBOUND(), NONE()), + TYPES_VAR("lineNumberEnd", dummyAttrVar, T_INTEGER_DEFAULT, UNBOUND(), NONE()), + TYPES_VAR("columnNumberEnd", dummyAttrVar, T_INTEGER_DEFAULT, UNBOUND(), NONE()), + TYPES_VAR("lastModification", dummyAttrVar, T_REAL_DEFAULT, UNBOUND(), NONE()) + }, true, emptyTypeSource); +constant Type T_SOURCEINFO_DEFAULT = T_METAUNIONTYPE({Absyn.QUALIFIED("SourceInfo",Absyn.IDENT("SOURCEINFO"))},true,EVAL_SINGLETON_KNOWN_TYPE(T_SOURCEINFO_DEFAULT_METARECORD),Absyn.IDENT("SourceInfo")::{}); // Arrays of unknown dimension, eg. Real[:] public constant Type T_ARRAY_REAL_NODIM = T_ARRAY(T_REAL_DEFAULT,{DIM_UNKNOWN()}, emptyTypeSource); @@ -951,7 +961,7 @@ public uniontype Type "models the different front-end and back-end types" // TODO: You can't trust these fields as it seems MetaUtil.fixUniontype is sent empty elements when running dependency analysis list paths; Boolean knownSingleton "The runtime system (dynload), does not know if the value is a singleton. But optimizations are safe if this is true."; - list singletonFields "The field names of the singleton"; + EvaluateSingletonType singletonType; TypeSource source; end T_METAUNIONTYPE; @@ -1001,6 +1011,23 @@ public uniontype CodeType end C_VARIABLENAMES; end CodeType; +uniontype EvaluateSingletonType "Is here because constants are not allowed to contain function pointers for some reason" + record EVAL_SINGLETON_TYPE_FUNCTION + EvaluateSingletonTypeFunction fun; + end EVAL_SINGLETON_TYPE_FUNCTION; + + record EVAL_SINGLETON_KNOWN_TYPE + Type ty; + end EVAL_SINGLETON_KNOWN_TYPE; + + record NOT_SINGLETON + end NOT_SINGLETON; +end EvaluateSingletonType; + +partial function EvaluateSingletonTypeFunction + output Type ty; +end EvaluateSingletonTypeFunction; + public constant FunctionAttributes FUNCTION_ATTRIBUTES_BUILTIN = FUNCTION_ATTRIBUTES(NO_INLINE(),true,false,false,FUNCTION_BUILTIN(NONE()),FP_NON_PARALLEL()); public constant FunctionAttributes FUNCTION_ATTRIBUTES_DEFAULT = FUNCTION_ATTRIBUTES(NO_INLINE(),true,false,false,FUNCTION_NOT_BUILTIN(),FP_NON_PARALLEL()); public constant FunctionAttributes FUNCTION_ATTRIBUTES_IMPURE = FUNCTION_ATTRIBUTES(NO_INLINE(),false,true,false,FUNCTION_NOT_BUILTIN(),FP_NON_PARALLEL()); @@ -1370,6 +1397,13 @@ uniontype Exp "Expressions Type ty; end TSUB; + record RSUB "Record field indexing" + Exp exp; + Integer ix; // Used when generating code for MetaModelica records + String fieldName; + Type ty; + end RSUB; + record SIZE "The size operator" Exp exp; Option sz; diff --git a/Compiler/FrontEnd/Expression.mo b/Compiler/FrontEnd/Expression.mo index 142fbeefd87..2971e80d60b 100644 --- a/Compiler/FrontEnd/Expression.mo +++ b/Compiler/FrontEnd/Expression.mo @@ -2228,6 +2228,7 @@ algorithm then tp; case (DAE.TSUB(ty = tp)) then tp; + case DAE.RSUB() then inExp.ty; case (DAE.CODE(ty = tp)) then tp; /* array reduction with known size */ case (DAE.REDUCTION(iterators={DAE.REDUCTIONITER(exp=e,guardExp=NONE())},reductionInfo=DAE.REDUCTIONINFO(exprType=ty as DAE.T_ARRAY(dims=dim::_),path = Absyn.IDENT("array")))) @@ -4952,6 +4953,15 @@ algorithm (e, ext_arg) = inFunc(e, ext_arg); then (e, ext_arg); + case e1 as DAE.RSUB() + algorithm + (e1_1, ext_arg) := traverseExpBottomUp(e1.exp, inFunc, inExtArg); + if not referenceEq(e1.exp, e1_1) then + e1.exp := e1_1; + end if; + (e1, ext_arg) := inFunc(e1, ext_arg); + then (e1, ext_arg); + case DAE.SIZE(exp=e1, sz=NONE()) equation (e1_1, ext_arg) = traverseExpBottomUp(e1, inFunc, inExtArg); e = if referenceEq(e1, e1_1) then inExp else DAE.SIZE(e1_1, NONE()); @@ -5492,6 +5502,14 @@ algorithm (e1_1,ext_arg_1) = traverseExpTopDown(e1, rel, ext_arg); then (DAE.TSUB(e1_1,i,tp),ext_arg_1); + case (_,e1 as DAE.RSUB(),rel,ext_arg) + algorithm + (e1_1,ext_arg_1) := traverseExpTopDown(e1.exp, rel, ext_arg); + if not referenceEq(e1.exp, e1_1) then + e1.exp := e1_1; + end if; + then (e1,ext_arg_1); + case (_,(DAE.SIZE(exp = e1,sz = NONE())),rel,ext_arg) equation (e1_1,ext_arg_1) = traverseExpTopDown(e1, rel, ext_arg); @@ -5572,7 +5590,7 @@ algorithm else equation str = ExpressionDump.printExpStr(inExp); - str = "Expression.traverseExpTopDown1 not implemented correctly: " + str; + str = getInstanceName() + " or " + System.dladdr(func) + "not implemented correctly: " + str; Error.addMessage(Error.INTERNAL_ERROR, {str}); then fail(); end match; diff --git a/Compiler/FrontEnd/ExpressionSimplify.mo b/Compiler/FrontEnd/ExpressionSimplify.mo index e6a99f593f8..7d122df0eb2 100644 --- a/Compiler/FrontEnd/ExpressionSimplify.mo +++ b/Compiler/FrontEnd/ExpressionSimplify.mo @@ -1681,12 +1681,13 @@ protected function simplifyCref algorithm exp := matchcontinue (origExp, inCREF, inType) local - Type t,t2; + Type t,t2,t3; list ssl; ComponentRef cr; - Ident idn; + Ident idn,idn2; list expl_1; DAE.Exp expCref; + Integer index; case(_,DAE.CREF_IDENT(idn,t2,(ssl as ((DAE.SLICE(DAE.ARRAY(_,_,_))) :: _))),t) equation @@ -1694,6 +1695,31 @@ algorithm expCref = Expression.makeCrefExp(cr,t); exp = simplifyCref2(expCref,ssl); then exp; + +/* + case (_, DAE.CREF_QUAL(idn,t2 as DAE.T_METATYPE(DAE.T_METAARRAY()),ssl,DAE.CREF_IDENT(idn2,t3)),t) + equation + exp = DAE.ASUB(DAE.CREF(DAE.CREF_IDENT(idn,t2,{}),t2), list(Expression.subscriptIndexExp(s) for s in ssl)); + print(ExpressionDump.printExpStr(exp) + "\n"); + index = match tt as Types.metaArrayElementType(t2) + // case DAE.T_METARECORD() then t2.fields; + case DAE.T_METAUNIONTYPE() then List.position(idn2, tt.singletonFields); + end match; + exp = DAE.RSUB(exp, index, idn2, t); + print(ExpressionDump.printExpStr(origExp) + "\n"); + print(ExpressionDump.printExpStr(exp) + "\n"); + print("CREF_QUAL: " + idn + "\n"); + print("CREF_QUAL: " + Types.unparseType(t2) + "\n"); + print("CREF_QUAL: " + Types.unparseType(t) + "\n"); + print("CREF_QUAL: " + Types.unparseType(t3) + "\n"); + then exp; +*/ + case (_, DAE.CREF_QUAL(idn, DAE.T_METATYPE(ty=t2), ssl, cr), t) + equation + exp = simplifyCrefMM1(idn, t2, ssl); + exp = simplifyCrefMM(exp, Expression.typeof(exp), cr); + then exp; + else origExp; end matchcontinue; end simplifyCref; @@ -1740,6 +1766,55 @@ algorithm end matchcontinue; end simplifyCref2; +protected function simplifyCrefMM_index + input DAE.Exp inExp; + input String ident; + input DAE.Type ty; + output DAE.Exp exp; +protected + Integer index; + DAE.Type nty,ty2; + list fields; +algorithm + fields := Types.getMetaRecordFields(ty); + index := Types.findVarIndex(ident, fields)+1; + DAE.TYPES_VAR(ty=nty) := listGet(fields, index); + exp := DAE.RSUB(inExp, index, ident, nty); +end simplifyCrefMM_index; + +protected function simplifyCrefMM + input DAE.Exp inExp; + input DAE.Type inType; + input ComponentRef inCref; + output DAE.Exp exp; +algorithm + exp := match inCref + case DAE.CREF_IDENT() + algorithm + exp := simplifyCrefMM_index(inExp, inCref.ident, inType); + exp := if listEmpty(inCref.subscriptLst) then exp else DAE.ASUB(exp, list(Expression.subscriptIndexExp(s) for s in inCref.subscriptLst)); + then exp; + case DAE.CREF_QUAL() + algorithm + exp := simplifyCrefMM_index(inExp, inCref.ident, inType); + exp := if listEmpty(inCref.subscriptLst) then exp else DAE.ASUB(exp, list(Expression.subscriptIndexExp(s) for s in inCref.subscriptLst)); + exp := simplifyCrefMM(exp, Expression.typeof(exp), inCref.componentRef); + then exp; + end match; +end simplifyCrefMM; + +protected function simplifyCrefMM1 + input String ident; + input DAE.Type ty; + input list ssl; + output DAE.Exp outExp; +algorithm + outExp := match (ssl) + case {} then DAE.CREF(DAE.CREF_IDENT(ident,ty,{}),ty); + else DAE.ASUB(DAE.CREF(DAE.CREF_IDENT(ident,ty,{}),ty), list(Expression.subscriptIndexExp(s) for s in ssl)); + end match; +end simplifyCrefMM1; + public function simplify2 "Advanced simplifications covering several terms or factors, like a +2a +3a = 5a " diff --git a/Compiler/FrontEnd/Inst.mo b/Compiler/FrontEnd/Inst.mo index 256c8834036..5ecd170912b 100644 --- a/Compiler/FrontEnd/Inst.mo +++ b/Compiler/FrontEnd/Inst.mo @@ -2004,12 +2004,12 @@ protected function instClassdef2 " output Connect.Sets outSets; output ClassInf.State outState; output list outTypesVarLst; - output Option outTypesTypeOption; + output Option oty; output Option optDerAttr; output DAE.EqualityConstraint outEqualityConstraint; output ConnectionGraph.ConnectionGraph outGraph; algorithm - (outCache,outEnv,outIH,outStore,outDae,outSets,outState,outTypesVarLst,outTypesTypeOption,optDerAttr,outEqualityConstraint,outGraph):= + (outCache,outEnv,outIH,outStore,outDae,outSets,outState,outTypesVarLst,oty,optDerAttr,outEqualityConstraint,outGraph):= matchcontinue (inCache,inEnv,inIH,inStore,inMod2,inPrefix3,inState5,className,inClassDef6,inRestriction7,inVisibility,inPartialPrefix,inEncapsulatedPrefix,inInstDims9,inBoolean10,inCallingScope,inGraph,inSets,instSingleCref,comment,info,stopInst) local list cdefelts,compelts,extendselts,els,extendsclasselts,compelts_2_elem; @@ -2318,8 +2318,9 @@ algorithm // Search for equalityConstraint eqConstraint = InstUtil.equalityConstraint(env5, els, info); ci_state6 = if isSome(ed) then ClassInf.assertTrans(ci_state6,ClassInf.FOUND_EXT_DECL(),info) else ci_state6; + (cache,oty) = MetaUtil.fixUniontype(cache, env5, ci_state6, inClassDef6); then - (cache,env5,ih,store,dae,csets5,ci_state6,vars,MetaUtil.fixUniontype(ci_state6,inClassDef6),NONE(),eqConstraint,graph); + (cache,env5,ih,store,dae,csets5,ci_state6,vars,oty,NONE(),eqConstraint,graph); // This rule describes how to instantiate class definition derived from an enumeration case (cache,env,ih,store,mods,pre,_,_, @@ -2607,9 +2608,9 @@ algorithm re,vis,partialPrefix,encapsulatedPrefix,inst_dims,impl,_,graph,_,_,_,_,_) equation str = Util.assoc(str,{("List","list"),("Tuple","tuple"),("Array","array")}); - (outCache,outEnv,outIH,outStore,outDae,outSets,outState,outTypesVarLst,outTypesTypeOption,optDerAttr,outEqualityConstraint,outGraph) + (outCache,outEnv,outIH,outStore,outDae,outSets,outState,outTypesVarLst,oty,optDerAttr,outEqualityConstraint,outGraph) = instClassdef2(cache,env,ih,store,mods,pre,ci_state,className,SCode.DERIVED(Absyn.TCOMPLEX(Absyn.IDENT(str),tSpecs,NONE()),mod,DA),re,vis,partialPrefix,encapsulatedPrefix,inst_dims,impl,inCallingScope,graph,inSets,instSingleCref,comment,info,stopInst); - then (outCache,outEnv,outIH,outStore,outDae,outSets,outState,outTypesVarLst,outTypesTypeOption,optDerAttr,outEqualityConstraint,outGraph); + then (outCache,outEnv,outIH,outStore,outDae,outSets,outState,outTypesVarLst,oty,optDerAttr,outEqualityConstraint,outGraph); case (_,_,_,_,_,_,_,_, SCode.DERIVED(typeSpec=tSpec as Absyn.TCOMPLEX(path=cn,typeSpecs=tSpecs)), diff --git a/Compiler/FrontEnd/Lookup.mo b/Compiler/FrontEnd/Lookup.mo index b49edcfc8e5..f6263ce656d 100644 --- a/Compiler/FrontEnd/Lookup.mo +++ b/Compiler/FrontEnd/Lookup.mo @@ -2747,23 +2747,18 @@ algorithm // componentEnv = FGraph.setScope(componentEnv, List.create(FGraph.lastScopeRef(componentEnv))); (attr,ty,binding,cnstForRange,componentEnv,name) := match tyParent - case DAE.T_METARECORD(fields=fields) + case DAE.T_METAARRAY() algorithm - {} := ss; - DAE.CREF_IDENT(ident=id2,subscriptLst={}) := ids; - DAE.TYPES_VAR(name,attr,ty,binding,cnstForRange) := listGet(fields,Types.findVarIndex(id2,fields)+1); + true := listLength(Types.getDimensions(tyParent)) == listLength(ss); + (cache,attr,ty,binding,cnstForRange,name) := lookupVarFMetaModelica(cache, componentEnv, ids, Types.metaArrayElementType(tyParent)); splicedExpData := InstTypes.SPLICEDEXPDATA(NONE(),ty); then (attr,ty,binding,cnstForRange,componentEnv,name); - case DAE.T_METAUNIONTYPE(knownSingleton=true, paths={p}) + case _ guard Types.isBoxedType(tyParent) and not Types.isUnknownType(tyParent) algorithm {} := ss; - DAE.CREF_IDENT(ident=id2,subscriptLst={}) := ids; - (cache, DAE.T_METARECORD(fields=fields), _) := lookupType(cache, componentEnv, p, NONE()); - DAE.TYPES_VAR(name,attr,ty,binding,cnstForRange) := listGet(fields,Types.findVarIndex(id2,fields)+1); + (cache,attr,ty,binding,cnstForRange,name) := lookupVarFMetaModelica(cache, componentEnv, ids, tyParent); splicedExpData := InstTypes.SPLICEDEXPDATA(NONE(),ty); then (attr,ty,binding,cnstForRange,componentEnv,name); - case DAE.T_METAUNIONTYPE() - then fail(); else algorithm (cache,DAE.ATTR(ct,prl,vt,di,io,vis),tyChild,binding,cnstForRange,InstTypes.SPLICEDEXPDATA(texp,idTp),_,componentEnv,name) := lookupVar(cache, componentEnv, ids); @@ -2794,6 +2789,49 @@ algorithm end match; end lookupVarF; +protected function lookupVarFMetaModelica + input FCore.Cache inCache; + input FCore.Graph inEnv; + input DAE.ComponentRef cr; + input DAE.Type inType; + output FCore.Cache cache = inCache; + output DAE.Attributes attr; + output DAE.Type ty; + output DAE.Binding binding; + output Option cnstForRange; + output String name; +algorithm + (attr,ty,binding,cnstForRange,name) := match cr + local + list fields; + Absyn.Path p; + DAE.Type tt; + case DAE.CREF_IDENT() + algorithm + fields := Types.getMetaRecordFields(inType); + DAE.TYPES_VAR(name,attr,ty,binding,cnstForRange) := listGet(fields,Types.findVarIndex(cr.ident,fields)+1); + for s in cr.subscriptLst loop + ty := match ty + case DAE.T_METAARRAY() then ty.ty; + end match; + end for; + ty := Types.getMetaRecordIfSingleton(ty); + then (attr,ty,binding,cnstForRange,name); + case DAE.CREF_QUAL() + algorithm + fields := Types.getMetaRecordFields(inType); + DAE.TYPES_VAR(name,attr,ty,binding,cnstForRange) := listGet(fields,Types.findVarIndex(cr.ident,fields)+1); + for s in cr.subscriptLst loop + ty := match ty + case DAE.T_METAARRAY() then ty.ty; + end match; + end for; + ty := Types.getMetaRecordIfSingleton(ty); + (cache,attr,ty,binding,cnstForRange,name) := lookupVarFMetaModelica(cache, inEnv, cr.componentRef, ty); + then (attr,ty,binding,cnstForRange,name); + end match; +end lookupVarFMetaModelica; + protected function lookupBinding "@author: adrpo this function uses the binding of the parent @@ -3048,7 +3086,7 @@ algorithm end sliceDimensionType; -protected function buildMetaRecordType "common function when looking up the type of a metarecord" +public function buildMetaRecordType "common function when looking up the type of a metarecord" input FCore.Cache inCache; input FCore.Graph inEnv; input SCode.Element cdef; diff --git a/Compiler/FrontEnd/MetaUtil.mo b/Compiler/FrontEnd/MetaUtil.mo index e073c273d46..c18e07d975a 100644 --- a/Compiler/FrontEnd/MetaUtil.mo +++ b/Compiler/FrontEnd/MetaUtil.mo @@ -35,15 +35,21 @@ encapsulated package MetaUtil description: Different MetaModelica extension functions. " -public import Absyn; -public import ClassInf; -public import DAE; -public import SCode; +import Absyn; +import ClassInf; +import DAE; +import FCore; +import SCode; -protected import Config; -protected import Flags; -protected import List; -protected import Types; +protected + +import Config; +import Error; +import FGraph; +import Flags; +import List; +import Lookup; +import Types; public function createMetaClassesInProgram "This function goes through a program and changes all records inside of @@ -265,17 +271,23 @@ algorithm end fixElementItems; public function fixUniontype + input FCore.Cache inCache; + input FCore.Graph inEnv; input ClassInf.State inState; input SCode.ClassDef inClassDef; + output FCore.Cache cache = inCache; output Option outType; algorithm outType := match (inState, inClassDef) local Boolean b; - Absyn.Path p; + Absyn.Path p,p2; list paths; - list names, singletonFields; + list names; DAE.TypeSource ts; + DAE.EvaluateSingletonType singletonType; + SCode.Element c; + FCore.Graph env_1; case (ClassInf.META_UNIONTYPE(), SCode.PARTS()) algorithm @@ -284,18 +296,37 @@ algorithm paths := list(Absyn.pathReplaceIdent(p, n) for n in names); b := listLength(paths)==1; if b then - singletonFields := SCode.componentNames(listGet(inClassDef.elementLst, 1)); + p2 := listGet(paths, 1); + singletonType := DAE.EVAL_SINGLETON_TYPE_FUNCTION(function fixUniontype2(arr=arrayCreate(1, (cache,inEnv,p2,NONE())))); else - singletonFields := {}; + singletonType := DAE.NOT_SINGLETON(); end if; ts := Types.mkTypeSource(SOME(p)); then - SOME(DAE.T_METAUNIONTYPE(paths,b,singletonFields,ts)); + SOME(DAE.T_METAUNIONTYPE(paths,b,singletonType,ts)); else NONE(); end match; end fixUniontype; +protected function fixUniontype2 + input array>> arr; + output DAE.Type singletonType; +protected + FCore.Cache cache; + FCore.Graph env; + Absyn.Path p; + Option ot; +algorithm + (cache,env,p,ot) := arrayGet(arr, 1); + if isNone(ot) then + (_, singletonType) := Lookup.lookupType(cache, env, p, SOME(sourceInfo())); + arrayUpdate(arr, 1, (cache,env,p,SOME(singletonType))); + else + SOME(singletonType) := ot; + end if; +end fixUniontype2; + public function checkArrayType "Checks that an array type is valid." input DAE.Type inType; diff --git a/Compiler/FrontEnd/Types.mo b/Compiler/FrontEnd/Types.mo index aca9df80301..4fca3e7f5f7 100644 --- a/Compiler/FrontEnd/Types.mo +++ b/Compiler/FrontEnd/Types.mo @@ -5797,7 +5797,7 @@ algorithm case (DAE.T_METARECORD(knownSingleton=false,utPath = path1), DAE.T_METARECORD(knownSingleton=false,utPath=path2)) equation true = Absyn.pathEqual(path1,path2); - then DAE.T_METAUNIONTYPE({},false,{},{path1}); + then DAE.T_METAUNIONTYPE({},false,DAE.NOT_SINGLETON(),{path1}); case (DAE.T_INTEGER(),DAE.T_REAL()) then DAE.T_REAL_DEFAULT; @@ -8221,7 +8221,7 @@ algorithm local Boolean b; Absyn.Path p; - case DAE.T_METARECORD(utPath=p,knownSingleton=b) then DAE.T_METAUNIONTYPE({},b,if b then list(varName(v) for v in inTy.fields) else {},{p}); + case DAE.T_METARECORD(utPath=p,knownSingleton=b) then DAE.T_METAUNIONTYPE({},b,if b then DAE.EVAL_SINGLETON_KNOWN_TYPE(inTy) else DAE.NOT_SINGLETON(),{p}); else inTy; end match; end getUniontypeIfMetarecord; @@ -8240,7 +8240,7 @@ protected function getUniontypeIfMetarecordTraverse output Integer odummy = dummy; algorithm oty := match ty - case DAE.T_METARECORD() then DAE.T_METAUNIONTYPE({},ty.knownSingleton,if ty.knownSingleton then list(varName(v) for v in ty.fields) else {},{ty.utPath}); + case DAE.T_METARECORD() then DAE.T_METAUNIONTYPE({},ty.knownSingleton,if ty.knownSingleton then DAE.EVAL_SINGLETON_KNOWN_TYPE(ty) else DAE.NOT_SINGLETON(),{ty.utPath}); else ty; end match; end getUniontypeIfMetarecordTraverse; @@ -8881,5 +8881,46 @@ protected function unboxedTypeTraverseHelper output T odummy = dummy; end unboxedTypeTraverseHelper; +public function getMetaRecordFields + input DAE.Type ty; + output list fields; +algorithm + fields := match ty + local + DAE.EvaluateSingletonTypeFunction fun; + case DAE.T_METARECORD(fields=fields) then fields; + case DAE.T_METAUNIONTYPE(knownSingleton=false) + algorithm + Error.addInternalError(getInstanceName() + " called on a non-singleton uniontype: " + unparseType(ty), sourceInfo()); + then fail(); + case DAE.T_METAUNIONTYPE(singletonType=DAE.EVAL_SINGLETON_KNOWN_TYPE(ty=DAE.T_METARECORD(fields=fields))) then fields; + case DAE.T_METAUNIONTYPE(singletonType=DAE.EVAL_SINGLETON_TYPE_FUNCTION(fun=fun)) + algorithm + DAE.T_METARECORD(fields=fields) := fun(); + then fields; + else + algorithm + Error.addInternalError(getInstanceName() + " called on a non-singleton uniontype: " + unparseType(ty), sourceInfo()); + then fail(); + end match; +end getMetaRecordFields; + +public function getMetaRecordIfSingleton + input DAE.Type ty; + output DAE.Type oty; +algorithm + oty := match ty + local + DAE.EvaluateSingletonTypeFunction fun; + case DAE.T_METAUNIONTYPE(knownSingleton=false) then ty; + case DAE.T_METAUNIONTYPE(singletonType=DAE.EVAL_SINGLETON_KNOWN_TYPE(ty=oty)) then oty; + case DAE.T_METAUNIONTYPE(singletonType=DAE.EVAL_SINGLETON_TYPE_FUNCTION(fun=fun)) + algorithm + oty := fun(); + then oty; + else ty; + end match; +end getMetaRecordIfSingleton; + annotation(__OpenModelica_Interface="frontend"); end Types; diff --git a/Compiler/SimCode/HpcOmSimCodeMain.mo b/Compiler/SimCode/HpcOmSimCodeMain.mo index 164af6e321b..2f8dd627689 100644 --- a/Compiler/SimCode/HpcOmSimCodeMain.mo +++ b/Compiler/SimCode/HpcOmSimCodeMain.mo @@ -329,9 +329,9 @@ algorithm //Apply filters //------------- - (taskGraphDaeSimplified,taskGraphDataDaeSimplified) = (taskGraphDae,taskGraphDataDae); - (taskGraphOdeSimplified,taskGraphDataOdeSimplified) = applyGRS(taskGraphOde,taskGraphDataOde, sccSimEqMapping, inBackendDAE); - (taskGraphZeroFuncSimplified,taskGraphDataZeroFuncSimplified) = (taskGraphZeroFuncs,taskGraphDataZeroFuncs); + (taskGraphDaeSimplified,taskGraphDataDaeSimplified) = applyGRS(taskGraphDae,taskGraphDataDae); + (taskGraphOdeSimplified,taskGraphDataOdeSimplified) = applyGRS(taskGraphOde,taskGraphDataOde); + (taskGraphZeroFuncSimplified,taskGraphDataZeroFuncSimplified) = applyGRS(taskGraphZeroFuncs,taskGraphDataZeroFuncs); SimCodeUtil.execStat("hpcom GRS"); fileName = ("taskGraph"+filenamePrefix+"ODE_merged.graphml"); @@ -348,8 +348,19 @@ algorithm (numProc,_) = setNumProc(numProc,cpCostsWoC,taskGraphDataOde);//in case n-flag is not set (scheduleDae,simCode,taskGraphDaeScheduled,taskGraphDataDaeScheduled,sccSimEqMapping) = createSchedule(taskGraphDaeSimplified,taskGraphDataDaeSimplified,daeSccSimEqMapping,simVarMapping,filenamePrefix,numProc,simCode,scheduledTasksDae,"DAE system",Flags.getConfigString(Flags.HPCOM_SCHEDULER)); + //criticalPathInfo = HpcOmScheduler.analyseScheduledTaskGraph(scheduleDae,numProc,taskGraphDaeScheduled,taskGraphDataDaeScheduled,"DAE system"); + //schedulerInfo = HpcOmScheduler.convertScheduleStrucToInfo(scheduleDae,arrayLength(taskGraphDaeScheduled)); + //HpcOmTaskGraph.dumpAsGraphMLSccLevel(taskGraphDaeScheduled, taskGraphDataDaeScheduled, fileName+"_schedDAE.graphml", criticalPathInfo, HpcOmTaskGraph.convertNodeListToEdgeTuples(listHead(criticalPaths)), HpcOmTaskGraph.convertNodeListToEdgeTuples(listHead(criticalPathsWoC)), sccSimEqMapping, schedulerInfo, HpcOmTaskGraph.GRAPHDUMPOPTIONS(false,false,false,false)); + (scheduleOde,simCode,taskGraphOdeScheduled,taskGraphDataOdeScheduled,sccSimEqMapping) = createSchedule(taskGraphOdeSimplified,taskGraphDataOdeSimplified,sccSimEqMapping,simVarMapping,filenamePrefix,numProc,simCode,scheduledTasksOde,"ODE system",Flags.getConfigString(Flags.HPCOM_SCHEDULER)); + //criticalPathInfo = HpcOmScheduler.analyseScheduledTaskGraph(scheduleOde,numProc,taskGraphOdeScheduled,taskGraphDataOdeScheduled,"DAE system"); + //schedulerInfo = HpcOmScheduler.convertScheduleStrucToInfo(scheduleOde,arrayLength(taskGraphOdeScheduled)); + //HpcOmTaskGraph.dumpAsGraphMLSccLevel(taskGraphOdeScheduled, taskGraphDataOdeScheduled, fileName+"_schedODE.graphml", criticalPathInfo, HpcOmTaskGraph.convertNodeListToEdgeTuples(listHead(criticalPaths)), HpcOmTaskGraph.convertNodeListToEdgeTuples(listHead(criticalPathsWoC)), sccSimEqMapping, schedulerInfo, HpcOmTaskGraph.GRAPHDUMPOPTIONS(false,false,false,false)); + (scheduleZeroFunc,simCode,taskGraphZeroFuncScheduled,taskGraphDataZeroFuncScheduled,sccSimEqMapping) = createSchedule(taskGraphZeroFuncSimplified,taskGraphDataZeroFuncSimplified,daeSccSimEqMapping,simVarMapping,filenamePrefix,numProc,simCode,scheduledTasksZeroFunc,"ZeroFunc system",Flags.getConfigString(Flags.HPCOM_SCHEDULER)); + //criticalPathInfo = HpcOmScheduler.analyseScheduledTaskGraph(scheduleZeroFunc,numProc,taskGraphZeroFuncScheduled,taskGraphDataZeroFuncScheduled,"DAE system"); + //schedulerInfo = HpcOmScheduler.convertScheduleStrucToInfo(scheduleZeroFunc,arrayLength(taskGraphZeroFuncScheduled)); + //HpcOmTaskGraph.dumpAsGraphMLSccLevel(taskGraphZeroFuncScheduled, taskGraphDataZeroFuncScheduled, fileName+"_schedZE.graphml", criticalPathInfo, HpcOmTaskGraph.convertNodeListToEdgeTuples(listHead(criticalPaths)), HpcOmTaskGraph.convertNodeListToEdgeTuples(listHead(criticalPathsWoC)), sccSimEqMapping, schedulerInfo, HpcOmTaskGraph.GRAPHDUMPOPTIONS(false,false,false,false)); SimCode.SIMCODE( modelInfo, simCodeLiterals, simCodeRecordDecls, simCodeExternalFunctionIncludes, allEquations, odeEquations, algebraicEquations, partitionsKind, baseClocks, useHomotopy, initialEquations, removedInitialEquations, startValueEquations, @@ -378,7 +389,7 @@ algorithm System.realtimeTick(ClockIndexes.RT_CLOCK_EXECSTAT_HPCOM_MODULES); //HpcOmTaskGraph.printTaskGraphMeta(taskGraphDataScheduled); - checkOdeSystemSize(taskGraphDataOdeScheduled,odeEquations); + checkOdeSystemSize(taskGraphDataOdeScheduled,odeEquations,sccSimEqMapping); SimCodeFunctionUtil.execStat("hpcom check ODE system size"); //Create Memory-Map and Sim-Code @@ -483,8 +494,6 @@ public function applyGRS"applies several task graph rewriting rules to merge tas author:Waurich 2014-11" input HpcOmTaskGraph.TaskGraph iTaskGraph; input HpcOmTaskGraph.TaskGraphMeta iTaskGraphMeta; - input array> iSccSimEqMapping; - input BackendDAE.BackendDAE iBackendDAE; output HpcOmTaskGraph.TaskGraph oTaskGraph; output HpcOmTaskGraph.TaskGraphMeta oTaskGraphMeta; protected @@ -1249,8 +1258,10 @@ Remark: this can occur when asserts are added to the ode-system. author:marcusw" input HpcOmTaskGraph.TaskGraphMeta iTaskGraphMeta; input list> iOdeEqs; + input array> iSccSimEqMapping; output Boolean oIsCorrect; protected + Integer scc; list sccs; Integer actualSizePre, actualSize; Integer targetSize; @@ -1261,12 +1272,18 @@ algorithm if(intNe(actualSizePre, actualSize)) then print("There are simCode-equations multiple times in the graph structure.\n"); end if; + actualSize := 0; + for scc in sccs loop + actualSize := actualSize + listLength(arrayGet(iSccSimEqMapping, scc)); + end for; + targetSize := listLength(List.flatten(iOdeEqs)); oIsCorrect := intEq(targetSize,actualSize); if(oIsCorrect) then //print("the ODE-system size is correct("+intString(actualSize)+")\n"); else - print("the size should be "+intString(targetSize)+" but it is "+intString(actualSize)+"!\n"); + print("the size of the ODE-system should be "+intString(targetSize)+" but it is "+intString(actualSize)+"!\n"); + print("expected the following sim code equations: " + stringDelimitList(List.map(List.map(List.flatten(iOdeEqs), SimCodeUtil.simEqSystemIndex), intString), ",") + "\n"); print("the ODE-system is NOT correct\n"); end if; end checkOdeSystemSize; diff --git a/Compiler/SimCode/SimCodeMain.mo b/Compiler/SimCode/SimCodeMain.mo index c36b225e843..7aaf61b3440 100644 --- a/Compiler/SimCode/SimCodeMain.mo +++ b/Compiler/SimCode/SimCodeMain.mo @@ -62,6 +62,7 @@ import CevalScriptBackend; import CodegenC; import CodegenFMU; import CodegenFMUCpp; +import CodegenFMUCppHpcom; import CodegenQSS; import CodegenAdevs; import CodegenSparseFMI; @@ -142,7 +143,7 @@ algorithm fileDir := CevalScriptBackend.getFileDir(a_cref, p); (libs,libPaths,includes, includeDirs, recordDecls, functions, outIndexedBackendDAE, _, literals) := SimCodeUtil.createFunctions(p, dae, inBackendDAE, className); - (simCode,_) := SimCodeUtil.createSimCode(outIndexedBackendDAE, + simCode := createSimCode(outIndexedBackendDAE, className, filenamePrefix, fileDir, functions, includes, includeDirs, libs, libPaths,simSettingsOpt, recordDecls, literals,Absyn.FUNCTIONARGS({},{})); timeSimCode := System.realtimeTock(ClockIndexes.RT_CLOCK_SIMCODE); SimCodeFunctionUtil.execStat("SimCode"); @@ -574,7 +575,11 @@ algorithm then (); case (_,"Cpp") equation - Tpl.tplNoret3(CodegenFMUCpp.translateModel, simCode, FMUVersion, FMUType); + if(Flags.isSet(Flags.HPCOM)) then + Tpl.tplNoret3(CodegenFMUCppHpcom.translateModel, simCode, FMUVersion, FMUType); + else + Tpl.tplNoret3(CodegenFMUCpp.translateModel, simCode, FMUVersion, FMUType); + end if; then (); else equation diff --git a/Compiler/SimCode/SimCodeUtil.mo b/Compiler/SimCode/SimCodeUtil.mo index 18ac58ae3a3..0ab44158dbf 100644 --- a/Compiler/SimCode/SimCodeUtil.mo +++ b/Compiler/SimCode/SimCodeUtil.mo @@ -148,7 +148,7 @@ public function createSimCode "entry point to create SimCode from BackendDAE." input BackendDAE.BackendDAE inBackendDAE; input Absyn.Path inClassName; input String filenamePrefix; - input String inString11; + input String inFileDir; input list functions; input list externalFunctionIncludes; input list includeDirs; @@ -159,323 +159,314 @@ public function createSimCode "entry point to create SimCode from BackendDAE." input tuple> literals; input Absyn.FunctionArgs args; output SimCode.SimCode simCode; - output tuple>> oMapping; //The highest simEqIndex in the mapping and the mapping simEq-Index -> scc-Index itself + output tuple>> outMapping; //The highest simEqIndex in the mapping and the mapping simEq-Index -> scc-Index itself +protected + BackendDAE.BackendDAE dlow; + BackendDAE.BackendDAE initDAE; + BackendDAE.EqSystems systs; + BackendDAE.EquationArray removedEqs; + BackendDAE.Shared shared; + BackendDAE.SymbolicJacobians symJacs; + BackendDAE.Variables knownVars; + Boolean ifcpp; + Boolean useHomotopy; // true if homotopy(...) is used during initialization + DAE.FunctionTree functionTree; + 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; + Integer numberofLinearSys, numberofNonLinearSys, numberofMixedSys; + Option modelStruct; + SimCode.BackendMapping backendMapping; + SimCode.ExtObjInfo extObjInfo; + SimCode.HashTableCrefToSimVar crefToSimVarHT; + SimCode.MakefileParams makefileParams; + SimCode.ModelInfo modelInfo; + array baseClocks; + array systemIndexMap; + list partitionsKind; + list removedInitialEquationLst, paramAsserts, remEqLst; + list timeEvents; + list allPrimaryParameters "already sorted"; + list primaryParameters "already sorted"; + list zeroCrossings, sampleZC, relations; + list classAttributes; + list discreteModelVars; + list constraints; + list lits; + list LinearMatrices, SymbolicJacs, SymbolicJacsTemp, SymbolicJacsStateSelect, SymbolicJacsNLS; + list algorithmAndEquationAsserts; + list allEquations; + list equationsForZeroCrossings; + list initialEquations; // --> initial_equations + list jacobianEquations; + list maxValueEquations; // --> updateBoundMaxValues + list minValueEquations; // --> updateBoundMinValues + list nominalValueEquations; // --> updateBoundNominalValues + list paramAssertSimEqs; + list parameterEquations; // --> updateBoundParameters + list removedEquations; + list removedInitialEquations; // --> + list startValueEquations; // --> updateBoundStartValues + list whenClauses; + list stateSets; + list mixedArrayVars; + list tempvars, jacobianSimvars; + list> algebraicEquations; // --> functionAlgebraics + list> odeEquations; // --> functionODE + list>> delayedExps; + list> equationSccMapping, eqBackendSimCodeMapping; algorithm - (simCode,oMapping) := - matchcontinue (inBackendDAE, inClassName, filenamePrefix, inString11, functions, externalFunctionIncludes, includeDirs, libs,libPaths, simSettingsOpt, recordDecls, literals, args) - local - String cname, fileDir; - Integer maxDelayedExpIndex, uniqueEqIndex, numberofEqns, numStateSets, numberOfJacobians; - Integer numberofLinearSys, numberofNonLinearSys, numberofMixedSys; - BackendDAE.BackendDAE dlow; - BackendDAE.BackendDAE initDAE; - DAE.FunctionTree functionTree; - BackendDAE.SymbolicJacobians symJacs; - Absyn.Path class_; - // new variables - SimCode.ModelInfo modelInfo; - list allEquations; - list> odeEquations; // --> functionODE - list> algebraicEquations; // --> functionAlgebraics - Boolean useHomotopy; // true if homotopy(...) is used during initialization - list initialEquations; // --> initial_equations - list removedInitialEquations; // --> - list startValueEquations; // --> updateBoundStartValues - list nominalValueEquations; // --> updateBoundNominalValues - list minValueEquations; // --> updateBoundMinValues - list maxValueEquations; // --> updateBoundMaxValues - list parameterEquations; // --> updateBoundParameters - list removedEquations; - list algorithmAndEquationAsserts; - list equationsForZeroCrossings; - list jacobianEquations; - // list algorithmAndEquationAsserts; - list constraints; - list classAttributes; - list zeroCrossings, sampleZC, relations; - list whenClauses; - list discreteModelVars; - SimCode.ExtObjInfo extObjInfo; - SimCode.MakefileParams makefileParams; - list>> delayedExps; - - list partitionsKind; - array baseClocks; - - list LinearMatrices, SymbolicJacs, SymbolicJacsTemp, SymbolicJacsStateSelect, SymbolicJacsNLS; - SimCode.HashTableCrefToSimVar crefToSimVarHT; - Boolean ifcpp; - BackendDAE.EqSystems systs; - BackendDAE.Shared shared; - BackendDAE.EquationArray removedEqs; - BackendDAE.Variables knownVars; - list removedInitialEquationLst, paramAsserts, remEqLst; - list paramAssertSimEqs; - - list lits; - list tempvars, jacobianSimvars; - - list stateSets; - array systemIndexMap; - list timeEvents; - list> equationSccMapping, eqBackendSimCodeMapping; - Integer highestSimEqIndex; - SimCode.BackendMapping backendMapping; - list primaryParameters "already sorted"; - list allPrimaryParameters "already sorted"; - - Option modelStruct; - list mixedArrayVars; - HashTableCrIListArray.HashTable varToArrayIndexMapping; //maps each array-variable to a array of positions - HashTableCrILst.HashTable varToIndexMapping; //maps each variable to an array position - case (dlow, class_, _, fileDir, _,_, _, _, _, _, _, _, _) equation - System.tmpTickReset(0); - uniqueEqIndex = 1; - ifcpp = stringEqual(Config.simCodeTarget(), "Cpp"); - - if Flags.isSet(Flags.VECTORIZE) then - // prepare the equations - dlow = BackendDAEUtil.mapEqSystem(dlow, Vectorization.prepareVectorizedDAE0); - end if; + try + dlow := inBackendDAE; + System.tmpTickReset(0); + uniqueEqIndex := 1; + ifcpp := stringEqual(Config.simCodeTarget(), "Cpp"); - backendMapping = setUpBackendMapping(inBackendDAE); - if Flags.isSet(Flags.VISUAL_XML) then - VisualXML.visualizationInfoXML(dlow, filenamePrefix); - end if; + if Flags.isSet(Flags.VECTORIZE) then + // prepare the equations + dlow := BackendDAEUtil.mapEqSystem(dlow, Vectorization.prepareVectorizedDAE0); + end if; - // fcall(Flags.FAILTRACE, print, "is that Cpp? : " + Dump.printBoolStr(ifcpp) + "\n"); - // generate initDAE before replacing pre(alias)! - (initDAE, useHomotopy, removedInitialEquationLst, primaryParameters, allPrimaryParameters) = Initialization.solveInitialSystem(dlow); + backendMapping := setUpBackendMapping(inBackendDAE); + if Flags.isSet(Flags.VISUAL_XML) then + VisualXML.visualizationInfoXML(dlow, filenamePrefix); + end if; - if Flags.isSet(Flags.ITERATION_VARS) then - BackendDAEOptimize.listAllIterationVariables(dlow); - 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; - // replace pre(alias) in time-equations - dlow = BackendDAEOptimize.simplifyTimeIndepFuncCalls(dlow); - - // initialization stuff - (initialEquations, removedInitialEquations, uniqueEqIndex, tempvars) = createInitialEquations(initDAE, removedInitialEquationLst, uniqueEqIndex, {}); - - // addInitialStmtsToAlgorithms - dlow = BackendDAEOptimize.addInitialStmtsToAlgorithms(dlow); - - BackendDAE.DAE(systs, shared as BackendDAE.SHARED(knownVars=knownVars, - removedEqs=removedEqs, - constraints=constraints, - classAttrs=classAttributes, - symjacs=symJacs, - partitionsInfo=BackendDAE.PARTITIONS_INFO(baseClocks), - eventInfo=BackendDAE.EVENT_INFO(timeEvents=timeEvents))) = dlow; - - - // created event suff e.g. zeroCrossings, samples, ... - whenClauses = createSimWhenClauses(dlow); - zeroCrossings = if ifcpp then FindZeroCrossings.getRelations(dlow) else FindZeroCrossings.getZeroCrossings(dlow); - relations = FindZeroCrossings.getRelations(dlow); - sampleZC = FindZeroCrossings.getSamples(dlow); - zeroCrossings = if ifcpp then listAppend(zeroCrossings, sampleZC) else zeroCrossings; - - // equation generation for euler, dassl2, rungekutta - ( uniqueEqIndex, odeEquations, algebraicEquations, allEquations, equationsForZeroCrossings, tempvars, - equationSccMapping, eqBackendSimCodeMapping, backendMapping) = - createEquationsForSystems( systs, shared, uniqueEqIndex, {}, {}, {}, {}, zeroCrossings, tempvars, 1, {}, {},backendMapping); - highestSimEqIndex = uniqueEqIndex; - - //(remEqLst,paramAsserts) = List.fold1(BackendEquation.equationList(removedEqs), getParamAsserts,knownVars,({},{})); - //((uniqueEqIndex, removedEquations)) = BackendEquation.traverseEquationArray(BackendEquation.listEquation(remEqLst), traversedlowEqToSimEqSystem, (uniqueEqIndex, {})); - ((uniqueEqIndex, removedEquations)) = BackendEquation.traverseEquationArray(removedEqs, traversedlowEqToSimEqSystem, (uniqueEqIndex, {})); - // Assertions and crap - // create parameter equations - partitionsKind = BackendDAEUtil.foldEqSystem(dlow, collectPartitions, {}); - ((uniqueEqIndex, startValueEquations)) = BackendDAEUtil.foldEqSystem(dlow, createStartValueEquations, (uniqueEqIndex, {})); - ((uniqueEqIndex, nominalValueEquations)) = BackendDAEUtil.foldEqSystem(dlow, createNominalValueEquations, (uniqueEqIndex, {})); - ((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, paramAssertSimEqs)) = BackendEquation.traverseEquationArray(BackendEquation.listEquation(paramAsserts), traversedlowEqToSimEqSystem, (uniqueEqIndex, {})); - //parameterEquations = listAppend(parameterEquations,paramAssertSimEqs); - - ((uniqueEqIndex, algorithmAndEquationAsserts)) = BackendDAEUtil.foldEqSystem(dlow, createAlgorithmAndEquationAsserts, (uniqueEqIndex, {})); - discreteModelVars = BackendDAEUtil.foldEqSystem(dlow, extractDiscreteModelVars, {}); - makefileParams = SimCodeFunctionUtil.createMakefileParams(includeDirs, libs, libPaths,false); - (delayedExps, maxDelayedExpIndex) = extractDelayedExpressions(dlow); - - // append removed equation to all equations, since these are actually - // just the algorithms without outputs - - algebraicEquations = listAppend(algebraicEquations, removedEquations::{}); - allEquations = listAppend(allEquations, removedEquations); - - // state set stuff - (dlow, stateSets, uniqueEqIndex, tempvars, numStateSets) = createStateSets(dlow, {}, uniqueEqIndex, tempvars); - - // create model info - if Flags.isSet(Flags.VECTORIZE) then - // prepare the variables - //dlow = BackendDAEUtil.mapEqSystem(dlow, Vectorization.prepareVectorizedDAE1); - dlow = BackendDAEUtil.mapEqSystem(dlow, Vectorization.enlargeIteratedArrayVars); - end if; + // generate initDAE before replacing pre(alias)! + (initDAE, useHomotopy, removedInitialEquationLst, primaryParameters, allPrimaryParameters) := Initialization.solveInitialSystem(dlow); - modelInfo = createModelInfo(class_, dlow, functions, {}, numStateSets, fileDir); - modelInfo = addTempVars(tempvars, modelInfo); + try + if Flags.isSet(Flags.ITERATION_VARS) then + BackendDAEOptimize.listAllIterationVariables(dlow); + end if; - // external objects - extObjInfo = createExtObjInfo(shared); + // replace pre(alias) in time-equations + dlow := BackendDAEOptimize.simplifyTimeIndepFuncCalls(dlow); + + // initialization stuff + (initialEquations, removedInitialEquations, uniqueEqIndex, tempvars) := createInitialEquations(initDAE, removedInitialEquationLst, uniqueEqIndex, {}); + + // addInitialStmtsToAlgorithms + dlow := BackendDAEOptimize.addInitialStmtsToAlgorithms(dlow); + + BackendDAE.DAE(shared=shared as BackendDAE.SHARED(knownVars=knownVars, + removedEqs=removedEqs, + constraints=constraints, + classAttrs=classAttributes, + symjacs=symJacs, + partitionsInfo=BackendDAE.PARTITIONS_INFO(baseClocks), + eventInfo=BackendDAE.EVENT_INFO(timeEvents=timeEvents))) := dlow; + + // created event suff e.g. zeroCrossings, samples, ... + whenClauses := createSimWhenClauses(dlow); + zeroCrossings := if ifcpp then FindZeroCrossings.getRelations(dlow) else FindZeroCrossings.getZeroCrossings(dlow); + relations := FindZeroCrossings.getRelations(dlow); + sampleZC := FindZeroCrossings.getSamples(dlow); + zeroCrossings := if ifcpp then listAppend(zeroCrossings, sampleZC) else zeroCrossings; + + // equation generation for euler, dassl2, rungekutta + ( uniqueEqIndex, odeEquations, algebraicEquations, allEquations, equationsForZeroCrossings, tempvars, + equationSccMapping, eqBackendSimCodeMapping, backendMapping) := + createEquationsForSystems(dlow.eqs, shared, uniqueEqIndex, {}, {}, {}, {}, zeroCrossings, tempvars, 1, {}, {},backendMapping); + outMapping := (uniqueEqIndex /* highestSimEqIndex */, equationSccMapping); + + //(remEqLst,paramAsserts) := List.fold1(BackendEquation.equationList(removedEqs), getParamAsserts, knownVars,({},{})); + //((uniqueEqIndex, removedEquations)) := BackendEquation.traverseEquationArray(BackendEquation.listEquation(remEqLst), traversedlowEqToSimEqSystem, (uniqueEqIndex, {})); + ((uniqueEqIndex, removedEquations)) := BackendEquation.traverseEquationArray(removedEqs, traversedlowEqToSimEqSystem, (uniqueEqIndex, {})); + // Assertions and crap + // create parameter equations + partitionsKind := BackendDAEUtil.foldEqSystem(dlow, collectPartitions, {}); + ((uniqueEqIndex, startValueEquations)) := BackendDAEUtil.foldEqSystem(dlow, createStartValueEquations, (uniqueEqIndex, {})); + ((uniqueEqIndex, nominalValueEquations)) := BackendDAEUtil.foldEqSystem(dlow, createNominalValueEquations, (uniqueEqIndex, {})); + ((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, paramAssertSimEqs)) := BackendEquation.traverseEquationArray(BackendEquation.listEquation(paramAsserts), traversedlowEqToSimEqSystem, (uniqueEqIndex, {})); + //parameterEquations := listAppend(parameterEquations,paramAssertSimEqs); + + ((uniqueEqIndex, algorithmAndEquationAsserts)) := BackendDAEUtil.foldEqSystem(dlow, createAlgorithmAndEquationAsserts, (uniqueEqIndex, {})); + discreteModelVars := BackendDAEUtil.foldEqSystem(dlow, extractDiscreteModelVars, {}); + makefileParams := SimCodeFunctionUtil.createMakefileParams(includeDirs, libs, libPaths,false); + (delayedExps, maxDelayedExpIndex) := extractDelayedExpressions(dlow); + + // append removed equation to all equations, since these are actually + // just the algorithms without outputs + + algebraicEquations := listAppend(algebraicEquations, removedEquations::{}); + allEquations := listAppend(allEquations, removedEquations); + + // state set stuff + (dlow, stateSets, uniqueEqIndex, tempvars, numStateSets) := createStateSets(dlow, {}, uniqueEqIndex, tempvars); + + // create model info + if Flags.isSet(Flags.VECTORIZE) then + // prepare the variables + //dlow := BackendDAEUtil.mapEqSystem(dlow, Vectorization.prepareVectorizedDAE1); + dlow := BackendDAEUtil.mapEqSystem(dlow, Vectorization.enlargeIteratedArrayVars); + end if; - // update index of zero-Crossings after equations are created - zeroCrossings = updateZeroCrossEqnIndex(zeroCrossings, eqBackendSimCodeMapping, BackendDAEUtil.daeSize(dlow)); + modelInfo := createModelInfo(inClassName, dlow, functions, {}, numStateSets, inFileDir); + modelInfo := addTempVars(tempvars, modelInfo); - // update indexNonLinear in SES_NONLINEAR and count - SymbolicJacsNLS = {}; - (initialEquations, numberofLinearSys, numberofNonLinearSys, numberofMixedSys, numberOfJacobians, SymbolicJacsTemp) = countandIndexAlgebraicLoops(initialEquations, 0, 0, 0, 0, {}); - SymbolicJacsNLS = listAppend(SymbolicJacsTemp, SymbolicJacsNLS); - (parameterEquations, numberofLinearSys, numberofNonLinearSys, numberofMixedSys, numberOfJacobians, SymbolicJacsTemp) = countandIndexAlgebraicLoops(parameterEquations, numberofLinearSys, numberofNonLinearSys, numberofMixedSys, numberOfJacobians, {}); - SymbolicJacsNLS = listAppend(SymbolicJacsTemp, SymbolicJacsNLS); - (allEquations, numberofLinearSys, numberofNonLinearSys, numberofMixedSys, numberOfJacobians, SymbolicJacsTemp) = countandIndexAlgebraicLoops(allEquations, numberofLinearSys, numberofNonLinearSys, numberofMixedSys, numberOfJacobians, {}); - SymbolicJacsNLS = listAppend(SymbolicJacsTemp, SymbolicJacsNLS); + // external objects + extObjInfo := createExtObjInfo(shared); - if Flags.isSet(Flags.DYNAMIC_TEARING_INFO) then - print("\n\n*********************\n* SimCode Equations *\n*********************\n\ninitialEquations:\n=================\n" + dumpSimEqSystemLst(initialEquations) + "\n"); - print("\n\nparameterEquations:\n===================\n" + dumpSimEqSystemLst(parameterEquations) + "\n"); - print("\n\nallEquations:\n=============\n" + dumpSimEqSystemLst(allEquations) + "\n\n"); - end if; + // update index of zero-Crossings after equations are created + zeroCrossings := updateZeroCrossEqnIndex(zeroCrossings, eqBackendSimCodeMapping, BackendDAEUtil.daeSize(dlow)); - // collect symbolic jacobians from state selection - (stateSets, SymbolicJacsStateSelect, numberOfJacobians) = indexStateSets(stateSets, {}, numberOfJacobians, {}); - - // generate jacobian or linear model matrices - (LinearMatrices,uniqueEqIndex) = createJacobianLinearCode(symJacs, modelInfo, uniqueEqIndex); - - // collect jacobian equation only for equantion info file - jacobianEquations = collectAllJacobianEquations(LinearMatrices, {}); - - // collect symbolic jacobians in linear loops of the overall jacobians - (_, numberofLinearSys, numberofNonLinearSys, numberofMixedSys, numberOfJacobians, SymbolicJacs) = countandIndexAlgebraicLoops({}, numberofLinearSys, numberofNonLinearSys, numberofMixedSys, numberOfJacobians, LinearMatrices); - - jacobianEquations = collectAllJacobianEquations(SymbolicJacsStateSelect, jacobianEquations); - SymbolicJacsNLS = listAppend(SymbolicJacsNLS, SymbolicJacsStateSelect); - SymbolicJacs = listAppend(SymbolicJacsNLS, SymbolicJacs); - jacobianSimvars = collectAllJacobianVars(SymbolicJacs, {}); - modelInfo = setJacobianVars(jacobianSimvars, modelInfo); - - // map index also odeEquations and algebraicEquations - systemIndexMap = List.fold(allEquations, getSystemIndexMap, arrayCreate(uniqueEqIndex, -1)); - odeEquations = List.mapList1_1(odeEquations, setSystemIndexMap, systemIndexMap); - algebraicEquations = List.mapList1_1(algebraicEquations, setSystemIndexMap, systemIndexMap); - numberofEqns = uniqueEqIndex; /* This is a *much* better estimate than the guessed number of equations */ - - // create model info - modelInfo = addNumEqnsandNumofSystems(modelInfo, numberofEqns, numberofLinearSys, numberofNonLinearSys, numberofMixedSys, numberOfJacobians); - - // replace div operator with div operator with check of Division by zero - allEquations = List.map(allEquations, addDivExpErrorMsgtoSimEqSystem); - odeEquations = List.mapList(odeEquations, addDivExpErrorMsgtoSimEqSystem); - algebraicEquations = List.mapList(algebraicEquations, addDivExpErrorMsgtoSimEqSystem); - startValueEquations = List.map(startValueEquations, addDivExpErrorMsgtoSimEqSystem); - nominalValueEquations = List.map(nominalValueEquations, addDivExpErrorMsgtoSimEqSystem); - minValueEquations = List.map(minValueEquations, addDivExpErrorMsgtoSimEqSystem); - maxValueEquations = List.map(maxValueEquations, addDivExpErrorMsgtoSimEqSystem); - parameterEquations = List.map(parameterEquations, addDivExpErrorMsgtoSimEqSystem); - removedEquations = List.map(removedEquations, addDivExpErrorMsgtoSimEqSystem); - initialEquations = List.map(initialEquations, addDivExpErrorMsgtoSimEqSystem); - removedInitialEquations = List.map(removedInitialEquations, addDivExpErrorMsgtoSimEqSystem); - - odeEquations = makeEqualLengthLists(odeEquations, Config.noProc()); - algebraicEquations = makeEqualLengthLists(algebraicEquations, Config.noProc()); - - // Filter out empty systems to improve code generation - odeEquations = List.filterOnFalse(odeEquations, listEmpty); - algebraicEquations = List.filterOnFalse(algebraicEquations, listEmpty); - - if Flags.isSet(Flags.EXEC_HASH) then - print("*** SimCode -> generate cref2simVar hastable: " + realString(clock()) + "\n"); - end if; - (crefToSimVarHT,mixedArrayVars) = createCrefToSimVarHT(modelInfo); - modelInfo = setMixedArrayVars(mixedArrayVars, modelInfo); - if Flags.isSet(Flags.EXEC_HASH) then - print("*** SimCode -> generate cref2simVar hastable done!: " + realString(clock()) + "\n"); - end if; + // update indexNonLinear in SES_NONLINEAR and count + SymbolicJacsNLS := {}; + (initialEquations, numberofLinearSys, numberofNonLinearSys, numberofMixedSys, numberOfJacobians, SymbolicJacsTemp) := countandIndexAlgebraicLoops(initialEquations, 0, 0, 0, 0, {}); + SymbolicJacsNLS := listAppend(SymbolicJacsTemp, SymbolicJacsNLS); + (parameterEquations, numberofLinearSys, numberofNonLinearSys, numberofMixedSys, numberOfJacobians, SymbolicJacsTemp) := countandIndexAlgebraicLoops(parameterEquations, numberofLinearSys, numberofNonLinearSys, numberofMixedSys, numberOfJacobians, {}); + SymbolicJacsNLS := listAppend(SymbolicJacsTemp, SymbolicJacsNLS); + (allEquations, numberofLinearSys, numberofNonLinearSys, numberofMixedSys, numberOfJacobians, SymbolicJacsTemp) := countandIndexAlgebraicLoops(allEquations, numberofLinearSys, numberofNonLinearSys, numberofMixedSys, numberOfJacobians, {}); + SymbolicJacsNLS := listAppend(SymbolicJacsTemp, SymbolicJacsNLS); - backendMapping = setBackendVarMapping(inBackendDAE,crefToSimVarHT,modelInfo,backendMapping); - //dumpBackendMapping(backendMapping); - - modelStruct = createFMIModelStructure(symJacs, modelInfo); - - (varToArrayIndexMapping, varToIndexMapping) = createVarToArrayIndexMapping(modelInfo); - //print("HASHTABLE MAPPING\n\n"); - //BaseHashTable.dumpHashTable(varToArrayIndexMapping); - //print("END MAPPING\n\n"); - - simCode = SimCode.SIMCODE(modelInfo, - {}, // Set by the traversal below... - recordDecls, - externalFunctionIncludes, - allEquations, - odeEquations, - algebraicEquations, - partitionsKind, arrayList(baseClocks), - useHomotopy, - initialEquations, - removedInitialEquations, - startValueEquations, - nominalValueEquations, - minValueEquations, - maxValueEquations, - parameterEquations, - removedEquations, - algorithmAndEquationAsserts, - equationsForZeroCrossings, - jacobianEquations, - stateSets, - constraints, - classAttributes, - zeroCrossings, - relations, - timeEvents, - whenClauses, - discreteModelVars, - extObjInfo, - makefileParams, - SimCode.DELAYED_EXPRESSIONS(delayedExps, maxDelayedExpIndex), - SymbolicJacs, - simSettingsOpt, - filenamePrefix, - HpcOmSimCode.emptyHpcomData, - varToArrayIndexMapping, - varToIndexMapping, - crefToSimVarHT, - SOME(backendMapping), - modelStruct); - - (simCode, (_, _, lits)) = traverseExpsSimCode(simCode, SimCodeFunctionUtil.findLiteralsHelper, literals); - - simCode = setSimCodeLiterals(simCode, listReverse(lits)); - - if Flags.isSet(Flags.VECTORIZE) then - // update simCode equations - simCode = Vectorization.updateSimCode(simCode); - end if; + if Flags.isSet(Flags.DYNAMIC_TEARING_INFO) then + print("\n\n*********************\n* SimCode Equations *\n*********************\n\ninitialEquations:\n:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=\n" + dumpSimEqSystemLst(initialEquations) + "\n"); + print("\n\nparameterEquations:\n:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=\n" + dumpSimEqSystemLst(parameterEquations) + "\n"); + print("\n\nallEquations:\n:=:=:=:=:=:=:=:=:=:=:=:=:=\n" + dumpSimEqSystemLst(allEquations) + "\n\n"); + end if; - //dumpCrefToSimVarHashTable(crefToSimVarHT); - // print("*** SimCode -> collect all files started: " + realString(clock()) + "\n"); - // adrpo: collect all the files from SourceInfo and DAE.ElementSource - // simCode = collectAllFiles(simCode); - // print("*** SimCode -> collect all files done!: " + realString(clock()) + "\n"); + // collect symbolic jacobians from state selection + (stateSets, SymbolicJacsStateSelect, numberOfJacobians) := indexStateSets(stateSets, {}, numberOfJacobians, {}); + + // generate jacobian or linear model matrices + (LinearMatrices,uniqueEqIndex) := createJacobianLinearCode(symJacs, modelInfo, uniqueEqIndex); + + // collect jacobian equation only for equantion info file + jacobianEquations := collectAllJacobianEquations(LinearMatrices, {}); + + // collect symbolic jacobians in linear loops of the overall jacobians + (_, numberofLinearSys, numberofNonLinearSys, numberofMixedSys, numberOfJacobians, SymbolicJacs) := countandIndexAlgebraicLoops({}, numberofLinearSys, numberofNonLinearSys, numberofMixedSys, numberOfJacobians, LinearMatrices); + + jacobianEquations := collectAllJacobianEquations(SymbolicJacsStateSelect, jacobianEquations); + SymbolicJacsNLS := listAppend(SymbolicJacsNLS, SymbolicJacsStateSelect); + SymbolicJacs := listAppend(SymbolicJacsNLS, SymbolicJacs); + jacobianSimvars := collectAllJacobianVars(SymbolicJacs, {}); + modelInfo := setJacobianVars(jacobianSimvars, modelInfo); + + // map index also odeEquations and algebraicEquations + systemIndexMap := List.fold(allEquations, getSystemIndexMap, arrayCreate(uniqueEqIndex, -1)); + odeEquations := List.mapList1_1(odeEquations, setSystemIndexMap, systemIndexMap); + algebraicEquations := List.mapList1_1(algebraicEquations, setSystemIndexMap, systemIndexMap); + numberofEqns := uniqueEqIndex; /* This is a *much* better estimate than the guessed number of equations */ + + // create model info + modelInfo := addNumEqnsandNumofSystems(modelInfo, numberofEqns, numberofLinearSys, numberofNonLinearSys, numberofMixedSys, numberOfJacobians); + + // replace div operator with div operator with check of Division by zero + allEquations := List.map(allEquations, addDivExpErrorMsgtoSimEqSystem); + odeEquations := List.mapList(odeEquations, addDivExpErrorMsgtoSimEqSystem); + algebraicEquations := List.mapList(algebraicEquations, addDivExpErrorMsgtoSimEqSystem); + startValueEquations := List.map(startValueEquations, addDivExpErrorMsgtoSimEqSystem); + nominalValueEquations := List.map(nominalValueEquations, addDivExpErrorMsgtoSimEqSystem); + minValueEquations := List.map(minValueEquations, addDivExpErrorMsgtoSimEqSystem); + maxValueEquations := List.map(maxValueEquations, addDivExpErrorMsgtoSimEqSystem); + parameterEquations := List.map(parameterEquations, addDivExpErrorMsgtoSimEqSystem); + removedEquations := List.map(removedEquations, addDivExpErrorMsgtoSimEqSystem); + initialEquations := List.map(initialEquations, addDivExpErrorMsgtoSimEqSystem); + removedInitialEquations := List.map(removedInitialEquations, addDivExpErrorMsgtoSimEqSystem); + + odeEquations := makeEqualLengthLists(odeEquations, Config.noProc()); + algebraicEquations := makeEqualLengthLists(algebraicEquations, Config.noProc()); + + // Filter out empty systems to improve code generation + odeEquations := List.filterOnFalse(odeEquations, listEmpty); + algebraicEquations := List.filterOnFalse(algebraicEquations, listEmpty); + + if Flags.isSet(Flags.EXEC_HASH) then + print("*** SimCode -> generate cref2simVar hastable: " + realString(clock()) + "\n"); + end if; + (crefToSimVarHT,mixedArrayVars) := createCrefToSimVarHT(modelInfo); + modelInfo := setMixedArrayVars(mixedArrayVars, modelInfo); + if Flags.isSet(Flags.EXEC_HASH) then + print("*** SimCode -> generate cref2simVar hastable done!: " + realString(clock()) + "\n"); + end if; + backendMapping := setBackendVarMapping(inBackendDAE,crefToSimVarHT,modelInfo,backendMapping); + //dumpBackendMapping(backendMapping); + + modelStruct := createFMIModelStructure(symJacs, modelInfo); + + (varToArrayIndexMapping, varToIndexMapping) := createVarToArrayIndexMapping(modelInfo); + //print("HASHTABLE MAPPING\n\n"); + //BaseHashTable.dumpHashTable(varToArrayIndexMapping); + //print("END MAPPING\n\n"); + + simCode := SimCode.SIMCODE(modelInfo, + {}, // Set by the traversal below... + recordDecls, + externalFunctionIncludes, + allEquations, + odeEquations, + algebraicEquations, + partitionsKind, arrayList(baseClocks), + useHomotopy, + initialEquations, + removedInitialEquations, + startValueEquations, + nominalValueEquations, + minValueEquations, + maxValueEquations, + parameterEquations, + removedEquations, + algorithmAndEquationAsserts, + equationsForZeroCrossings, + jacobianEquations, + stateSets, + constraints, + classAttributes, + zeroCrossings, + relations, + timeEvents, + whenClauses, + discreteModelVars, + extObjInfo, + makefileParams, + SimCode.DELAYED_EXPRESSIONS(delayedExps, maxDelayedExpIndex), + SymbolicJacs, + simSettingsOpt, + filenamePrefix, + HpcOmSimCode.emptyHpcomData, + varToArrayIndexMapping, + varToIndexMapping, + crefToSimVarHT, + SOME(backendMapping), + modelStruct); + + (simCode, (_, _, lits)) := traverseExpsSimCode(simCode, SimCodeFunctionUtil.findLiteralsHelper, literals); + + simCode := setSimCodeLiterals(simCode, listReverse(lits)); + + if Flags.isSet(Flags.VECTORIZE) then + // update simCode equations + simCode := Vectorization.updateSimCode(simCode); + end if; - if Flags.isSet(Flags.DUMP_SIMCODE) then - dumpSimCode(simCode); - end if; - then (simCode, (highestSimEqIndex, equationSccMapping)); + // dumpCrefToSimVarHashTable(crefToSimVarHT); + // print("*** SimCode -> collect all files started: " + realString(clock()) + "\n"); + // adrpo: collect all the files from SourceInfo and DAE.ElementSource + // simCode := collectAllFiles(simCode); + // print("*** SimCode -> collect all files done!: " + realString(clock()) + "\n"); - else equation - Error.addInternalError("function createSimCode failed [Transformation from optimised DAE to simulation code structure failed]", sourceInfo()); - then fail(); - end matchcontinue; + if Flags.isSet(Flags.DUMP_SIMCODE) then + dumpSimCode(simCode); + end if; + else + Error.addInternalError("function createSimCode failed [Transformation from optimised DAE to simulation code structure failed]", sourceInfo()); + fail(); + end try; end createSimCode; public function createFunctions @@ -1790,21 +1781,21 @@ end updateZeroCrossEqnIndexHelp; protected function convertListMappingToArray input list> iMapping; // input Integer numOfBackendEqs; - output array oMapping; + output array outMapping; algorithm - oMapping := arrayCreate(numOfBackendEqs, -1); - oMapping := List.fold(iMapping, convertListMappingToArray1, oMapping); + outMapping := arrayCreate(numOfBackendEqs, -1); + outMapping := List.fold(iMapping, convertListMappingToArray1, outMapping); end convertListMappingToArray; protected function convertListMappingToArray1 input tuple iMapping; // input array iMappingArray; - output array oMappingArray; + output array outMappingArray; protected Integer simEqIdx,BackendEqnIdx; algorithm (simEqIdx,BackendEqnIdx) := iMapping; - oMappingArray := arrayUpdate(iMappingArray,BackendEqnIdx,simEqIdx); + outMappingArray := arrayUpdate(iMappingArray,BackendEqnIdx,simEqIdx); end convertListMappingToArray1; protected function convertListIndx @@ -3468,11 +3459,8 @@ algorithm local BackendDAE.Variables vars; BackendDAE.EquationArray eqns; - Option m; - Option mT; - BackendDAE.Matching matching; BackendDAE.StateSets stateSets; - BackendDAE.BaseClockPartitionKind partitionKind; + BackendDAE.EqSystem syst; list equations; Integer uniqueEqIndex, numStateSets; list tempvars; @@ -3480,12 +3468,14 @@ algorithm // no stateSet case (BackendDAE.EQSYSTEM(stateSets={}), _) then (isyst, inTpl); // sets - case (BackendDAE.EQSYSTEM(orderedVars=vars, orderedEqs=eqns, m=m, mT=mT, matching=matching as BackendDAE.MATCHING(comps=comps), stateSets=stateSets, partitionKind=partitionKind), + case (syst as BackendDAE.EQSYSTEM(orderedVars=vars, orderedEqs=eqns, matching=BackendDAE.MATCHING(comps=comps), stateSets=stateSets), (equations, uniqueEqIndex, tempvars, numStateSets)) equation - (vars, equations, uniqueEqIndex, tempvars, numStateSets) = createStateSetsSets(stateSets, vars, eqns, inShared, comps, equations, uniqueEqIndex, tempvars, numStateSets); + (vars, equations, uniqueEqIndex, tempvars, numStateSets) = + createStateSetsSets(stateSets, vars, eqns, inShared, comps, equations, uniqueEqIndex, tempvars, numStateSets); + syst.orderedVars = vars; then - (BackendDAE.EQSYSTEM(vars, eqns, m, mT, matching, stateSets, partitionKind), (equations, uniqueEqIndex, tempvars, numStateSets)); + (syst, (equations, uniqueEqIndex, tempvars, numStateSets)); end match; end createStateSetsSystem; @@ -5753,25 +5743,21 @@ author:Waurich TUD 2015-01" protected list varMap; array varMapArr; - BackendDAE.Variables vars,allVars,vars1; - BackendDAE.EquationArray eqs,eqs1; + BackendDAE.Variables vars, allVars, vars1; + BackendDAE.EquationArray eqs, eqs1; BackendDAE.Matching matching; BackendDAE.IncidenceMatrix mStart; BackendDAE.IncidenceMatrixT mTStart; - Option m; - Option mT; BackendDAE.StrongComponents comps; - BackendDAE.StateSets stateSets; - BackendDAE.BaseClockPartitionKind partitionKind; BackendDAE.EqSystem syst; list eqLst; - list varLst,noStartVarLst; + list varLst, noStartVarLst; list> stateInfo; list stateIdcs; list stateKinds; algorithm - BackendDAE.EQSYSTEM(orderedVars=vars, orderedEqs=eqs, m=m, mT=mT, stateSets=stateSets, partitionKind=partitionKind, matching=matching) := systIn; + BackendDAE.EQSYSTEM(orderedVars=vars, orderedEqs=eqs) := systIn; // set the varkInd for states to variable, reverse this later with the help of the stateinfo stateInfo := List.fold1(List.intRange(BackendVariable.varsSize(vars)),getStateInfo,vars,{});// which var is a state and save the kind (vars,_) := BackendVariable.traverseBackendDAEVarsWithUpdate(vars,setVarKindForStates,BackendDAE.VARIABLE()); @@ -5786,24 +5772,24 @@ algorithm // insert start values for crefs and build incidence matrix //BackendDump.dumpVariables(vars,"VAR BEFORE"); //BackendDump.dumpEquationList(eqLst,"EQS BEFORE"); - (eqLst,_) := BackendEquation.traverseExpsOfEquationList(eqLst,replaceCrefWithStartValue,allVars); + (eqLst, _) := BackendEquation.traverseExpsOfEquationList(eqLst,replaceCrefWithStartValue,allVars); //BackendDump.dumpEquationList(eqLst,"EQS AFTER"); eqs1 := BackendEquation.listEquation(eqLst); vars1 := BackendVariable.listVar1(noStartVarLst); - syst := BackendDAE.EQSYSTEM(vars1,eqs1,NONE(),NONE(),BackendDAE.NO_MATCHING(),stateSets,partitionKind); - (syst,mStart,mTStart) := BackendDAEUtil.getIncidenceMatrix(syst,BackendDAE.NORMAL(),NONE()); + syst := BackendDAEUtil.createEqSystem(vars1, eqs1); + (syst, mStart, mTStart) := BackendDAEUtil.getIncidenceMatrix(syst,BackendDAE.NORMAL(),NONE()); //BackendDump.dumpIncidenceMatrix(mStart); //BackendDump.dumpIncidenceMatrixT(mTStart); // solve equations for new start values and assign start values to variables varMapArr := listArray(varMap); - vars := preCalculateStartValues1(List.intRange(arrayLength(mStart)),mStart,mTStart,varMapArr,eqs1,vars); + vars := preCalculateStartValues1(List.intRange(arrayLength(mStart)), mStart, mTStart, varMapArr, eqs1, vars); // reset the varKinds for the states - stateIdcs := List.map(stateInfo,Util.tuple21); - stateKinds := List.map(stateInfo,Util.tuple22); - vars := List.threadFold(stateIdcs,stateKinds,BackendVariable.setVarKindForVar,vars); + stateIdcs := List.map(stateInfo, Util.tuple21); + stateKinds := List.map(stateInfo, Util.tuple22); + vars := List.threadFold(stateIdcs, stateKinds,BackendVariable.setVarKindForVar, vars); //BackendDump.dumpVariables(vars,"VAR AFTER"); - systOut := BackendDAE.EQSYSTEM(vars, eqs,m, mT, matching, stateSets, partitionKind); + systOut := BackendDAEUtil.setEqSystVars(systIn, vars); end preCalculateStartValues; protected function preCalculateStartValues1"try to solve the start equation for a var and set the resulting start value for it." @@ -10057,20 +10043,44 @@ algorithm end getVarToArrayIndexByType; public function getVarIndexListByMapping "author: marcusw + Return the variable indices stored for the given variable in the mapping-table. If the variable is part of an array, all array indices are returned. This function is used by susan." + input HashTableCrIListArray.HashTable iVarToArrayIndexMapping; + input DAE.ComponentRef iVarName; + input String iIndexForUndefinedReferences; + output list oVarIndexList; //if the variable is part of an array, all array indices are returned in this list (the list contains one element if the variable is a scalar) +algorithm + ((oVarIndexList,_)) := getVarIndexInfosByMapping(iVarToArrayIndexMapping, iVarName, iIndexForUndefinedReferences); +end getVarIndexListByMapping; + +public function getVarIndexByMapping "author: marcusw + Return the variable index stored for the given variable in the mapping-table. This function is used by susan." + input HashTableCrIListArray.HashTable iVarToArrayIndexMapping; + input DAE.ComponentRef iVarName; + input String iIndexForUndefinedReferences; + output String oConcreteVarIndex; //the scalar index of the variable (this value is always part of oVarIndexList) +algorithm + ((_,oConcreteVarIndex)) := getVarIndexInfosByMapping(iVarToArrayIndexMapping, iVarName, iIndexForUndefinedReferences); +end getVarIndexByMapping; + +protected function getVarIndexInfosByMapping "author: marcusw Return the variable indices stored for the given variable in the mapping-table. This function is used by susan." input HashTableCrIListArray.HashTable iVarToArrayIndexMapping; input DAE.ComponentRef iVarName; input String iIndexForUndefinedReferences; - output list oVarIndexList; + output list oVarIndexList; //if the variable is part of an array, all array indices are returned in this list (the list contains one element if the variable is a scalar) + output String oConcreteVarIndex; //the scalar index of the variable (this value is always part of oVarIndexList) protected DAE.ComponentRef varName = iVarName; - Integer arrayIdx, idx, arraySize; + Integer arrayIdx, idx, arraySize, concreteVarIndex; array varIndices; list tmpVarIndexListNew = {}; + list arraySubscripts; + list arrayDimensions; algorithm + arraySubscripts := ComponentReference.crefLastSubs(varName); varName := ComponentReference.crefStripLastSubs(varName);//removeSubscripts(varName); if(BaseHashTable.hasKey(varName, iVarToArrayIndexMapping)) then - ((_,varIndices)) := BaseHashTable.get(varName, iVarToArrayIndexMapping); + ((arrayDimensions,varIndices)) := BaseHashTable.get(varName, iVarToArrayIndexMapping); arraySize := arrayLength(varIndices); for arrayIdx in 0:(arraySize-1) loop idx := arrayGet(varIndices, arraySize-arrayIdx); @@ -10085,13 +10095,28 @@ algorithm end if; end if; end for; + ((concreteVarIndex,_,_)) := List.fold(listReverse(arraySubscripts), getUnrolledArrayIndex, (0, 1, listReverse(arrayDimensions))); + + // ignore all values that are undefined references and part of the same array + idx := 1; + while intLe (idx, concreteVarIndex) loop + if(intLt(arrayGet(varIndices, idx), 1)) then + concreteVarIndex := concreteVarIndex - 1; + end if; + idx := idx + 1; + end while; + + concreteVarIndex := intAbs(arrayGet(varIndices, 1)) - 1 + concreteVarIndex; + oConcreteVarIndex := intString(concreteVarIndex); end if; if(listEmpty(tmpVarIndexListNew)) then Error.addMessage(Error.INTERNAL_ERROR, {"GetVarIndexListByMapping: No Element for " + ComponentReference.printComponentRefStr(varName) + " found!"}); tmpVarIndexListNew := {iIndexForUndefinedReferences}; + oConcreteVarIndex := iIndexForUndefinedReferences; end if; + //print("SimCodeUtil.getVarIndexInfosByMapping: Variable " + ComponentReference.printComponentRefStr(iVarName) + " has variable indices {" + stringDelimitList(tmpVarIndexListNew, ",") + "} and concrete index " + oConcreteVarIndex + "\n"); oVarIndexList := tmpVarIndexListNew; -end getVarIndexListByMapping; +end getVarIndexInfosByMapping; public function isVarIndexListConsecutive "author: marcusw Check if all variable indices of the given variables, stored in the hash table, are consecutive." @@ -10172,7 +10197,7 @@ end getUnrolledArrayIndex; public function createIdxSCVarMapping "author: marcusw Create a mapping from the SCVar-Index (array-Index) to the SCVariable, as it is used in the c-runtime." input SimCodeVar.SimVars simVars; - output array> oMapping; + output array> outMapping; protected Integer numStateVars; list stateVars; @@ -10241,7 +10266,7 @@ algorithm mappingArray := arrayCreate(highestIdx, NONE()); mappingArray := List.fold(idxSimVarMappingTplList, createAllSCVarMapping1, mappingArray); - oMapping := mappingArray; + outMapping := mappingArray; end createIdxSCVarMapping; protected function createAllSCVarMapping0 "author: marcusw @@ -10268,13 +10293,13 @@ protected function createAllSCVarMapping1 "author: marcusw Set the arrayIndex (iMapping) to the value given by the tuple." input tuple iSimVarIdxTpl; // input array> iMapping; - output array> oMapping; + output array> outMapping; protected Integer simVarIdx; SimCodeVar.SimVar simVar; algorithm (simVarIdx,simVar) := iSimVarIdxTpl; - oMapping := arrayUpdate(iMapping,simVarIdx,SOME(simVar)); + outMapping := arrayUpdate(iMapping,simVarIdx,SOME(simVar)); end createAllSCVarMapping1; public function getEnumerationTypes @@ -11632,7 +11657,7 @@ protected function getDaeEqsNotPartOfOdeSystem0 "Add the given equation system o author: marcusw" input SimCode.SimEqSystem iEqSystem; input tuple>, Integer> iMappingWithHighestIdx; // SimEqSystem, highestIdx> - output tuple>, Integer> oMappingWithHighestIdx; + output tuple>, Integer> outMappingWithHighestIdx; protected Integer index, highestIdx; list> allEqIdxMapping; @@ -11641,7 +11666,7 @@ algorithm (allEqIdxMapping, highestIdx) := iMappingWithHighestIdx; allEqIdxMapping := (index, iEqSystem)::allEqIdxMapping; highestIdx := intMax(highestIdx, index); - oMappingWithHighestIdx := (allEqIdxMapping, highestIdx); + outMappingWithHighestIdx := (allEqIdxMapping, highestIdx); end getDaeEqsNotPartOfOdeSystem0; protected function getDaeEqsNotPartOfOdeSystem1 "Set the array at position simEqIdx to the simEqSystem-object. diff --git a/Compiler/Template/CodegenCFunctions.tpl b/Compiler/Template/CodegenCFunctions.tpl index b96c8b05d29..b54b4feb114 100644 --- a/Compiler/Template/CodegenCFunctions.tpl +++ b/Compiler/Template/CodegenCFunctions.tpl @@ -2398,27 +2398,16 @@ template algStmtAssign(DAE.Statement stmt, Context context, Text &varDecls, Text << <%preExp%> >> - case STMT_ASSIGN(exp1=CREF(componentRef=cr as CREF_QUAL(identType=T_METATYPE(ty=t1 as T_METARECORD(__)), componentRef=cr2 as CREF_IDENT(__)),ty=t2)) then + case STMT_ASSIGN(exp1=RSUB(exp=explhs as CREF(ty=t1 as T_METARECORD(__)), fieldName=fieldName)) + case STMT_ASSIGN(exp1=RSUB(exp=explhs as CREF(ty=t1 as T_METAUNIONTYPE(__)), fieldName=fieldName)) + case STMT_ASSIGN(exp1=explhs as CREF(componentRef=CREF_QUAL(identType=T_METATYPE(ty=t1 as T_METAUNIONTYPE(__)), componentRef=cr2 as CREF_IDENT(ident=fieldName)), ty=t2)) + case STMT_ASSIGN(exp1=explhs as CREF(componentRef=CREF_QUAL(identType=T_METATYPE(ty=t1 as T_METARECORD(__)), componentRef=cr2 as CREF_IDENT(ident=fieldName)),ty=t2)) then let &preExp = buffer "" let tmp = tempDecl("modelica_metatype",&varDecls) - let varPart = '_<%cr.ident%>' // So it only works in function context? + let varPart = daeExp(explhs, context, &preExp, &varDecls, &auxFunction) let expPart = daeExp(exp, context, &preExp, &varDecls, &auxFunction) - let indexInRecord = intAdd(1, lookupIndexInMetaRecord(t1.fields, cr2.ident)) - let len = intAdd(2, listLength(t1.fields)) - << - <%preExp%> - <%tmp%> = MMC_TAGPTR(mmc_alloc_words(<%len%>)); - memcpy(MMC_UNTAGPTR(<%tmp%>), MMC_UNTAGPTR(<%varPart%>), <%len%>*sizeof(modelica_metatype)); - ((modelica_metatype*)MMC_UNTAGPTR(<%tmp%>))[<%indexInRecord%>] = <%expPart%>; - <%varPart%> = <%tmp%>; - >> - case STMT_ASSIGN(exp1=CREF(componentRef=cr as CREF_QUAL(identType=T_METATYPE(ty=t1 as T_METAUNIONTYPE(__)), componentRef=cr2 as CREF_IDENT(__)),ty=t2)) then - let &preExp = buffer "" - let tmp = tempDecl("modelica_metatype",&varDecls) - let varPart = '_<%cr.ident%>' // So it only works in function context? - let expPart = daeExp(exp, context, &preExp, &varDecls, &auxFunction) - let indexInRecord = intAdd(1, position(cr2.ident, t1.singletonFields)) - let len = intAdd(2, listLength(t1.singletonFields)) + let indexInRecord = intAdd(1, lookupIndexInMetaRecord(getMetaRecordFields(t1), fieldName)) + let len = intAdd(2, listLength(getMetaRecordFields(t1))) << <%preExp%> <%tmp%> = MMC_TAGPTR(mmc_alloc_words(<%len%>)); @@ -2426,6 +2415,10 @@ template algStmtAssign(DAE.Statement stmt, Context context, Text &varDecls, Text ((modelica_metatype*)MMC_UNTAGPTR(<%tmp%>))[<%indexInRecord%>] = <%expPart%>; <%varPart%> = <%tmp%>; >> + + case STMT_ASSIGN(exp1=RSUB(__)) then + error(sourceInfo(), 'Code generation not implemented for lhs assignment <%printExpStr(exp1)%>') + case STMT_ASSIGN(exp1=CREF(ty = T_FUNCTION_REFERENCE_VAR(__))) case STMT_ASSIGN(exp1=CREF(ty = T_FUNCTION_REFERENCE_FUNC(__))) then let &preExp = buffer "" @@ -2672,7 +2665,7 @@ match stmt let call = daeExpCallTuple(exp, lhsCrefs2, context, &preExp, &varDecls, &auxFunction) let callassign = algStmtAssignWithRhsExpStr(firstexp, call, context, &preExp, &postExp, &varDecls, &auxFunction) << - /* tuple assignment <%expExpLst |> e => Util.escapeModelicaStringToCString(printExpStr(e)) ; separator=", "%>*/ + /* tuple assignment <%expExpLst |> e => escapeCComments(printExpStr(e)) ; separator=", "%>*/ <%preExp%> <%callassign%> <%postExp%> @@ -2990,6 +2983,7 @@ template algStmtForGeneric_impl(Exp exp, Ident iterator, String type, <% match type case "modelica_metatype" then (match typeof(exp) + case T_METAARRAY(__) case T_METATYPE(ty=T_METAARRAY(__)) then let tmp = tempDecl("modelica_integer",&varDecls) let len = tempDecl("modelica_integer",&varDecls) @@ -3000,6 +2994,7 @@ template algStmtForGeneric_impl(Exp exp, Ident iterator, String type, <%body%> } >> + case T_METALIST(__) case T_METATYPE(ty=T_METALIST(__)) then << for (<%tvar%> = <%evar%>; !listEmpty(<%tvar%>); <%tvar%>=listRest(<%tvar%>)) @@ -3616,6 +3611,7 @@ template expTypeFromExpFlag(Exp exp, Integer flag) case META_OPTION(__) case MATCHEXPRESSION(__) case METARECORDCALL(__) + case RSUB(__) case BOX(__) then match flag case 1 then "metatype" else "modelica_metatype" case c as UNBOX(__) then expTypeFlag(c.ty, flag) case c as SHARED_LITERAL(__) then expTypeFromExpFlag(c.exp, flag) @@ -4153,6 +4149,7 @@ end getTempDeclMatchOutputName; case e as CAST(__) then daeExpCast(e, context, &preExp, &varDecls, &auxFunction) case e as ASUB(__) then daeExpAsub(e, context, &preExp, &varDecls, &auxFunction) case e as TSUB(__) then daeExpTsub(e, context, &preExp, &varDecls, &auxFunction) + case e as RSUB(__) then daeExpRsub(e, context, &preExp, &varDecls, &auxFunction) case e as SIZE(__) then daeExpSize(e, context, &preExp, &varDecls, &auxFunction) case e as REDUCTION(__) then daeExpReduction(e, context, &preExp, &varDecls, &auxFunction) case e as TUPLE(__) then daeExpTuple(e, context, &preExp, &varDecls, &auxFunction) @@ -4386,11 +4383,9 @@ template daeExpCrefRhs(Exp exp, Context context, Text &preExp, 'boxvar_<%crefFunctionName(cr)%>' case CREF(componentRef = cr, ty = T_FUNCTION_REFERENCE_VAR(__)) then '((modelica_fnptr) _<%crefStr(cr)%>)' + case CREF(componentRef = cr as CREF_QUAL(subscriptLst={}, identType = T_METATYPE(ty=ty as T_METAUNIONTYPE(__)), componentRef=cri as CREF_IDENT(__))) case CREF(componentRef = cr as CREF_QUAL(subscriptLst={}, identType = T_METATYPE(ty=ty as T_METARECORD(__)), componentRef=cri as CREF_IDENT(__))) then - let offset = intAdd(findVarIndex(cri.ident,ty.fields),2) // 0-based - '(MMC_FETCH(MMC_OFFSET(MMC_UNTAGPTR(_<%cr.ident%>), <%offset%>)))' - case CREF(componentRef = cr as CREF_QUAL(subscriptLst={}, identType = T_METATYPE(ty=ty as T_METAUNIONTYPE(__)), componentRef=cri as CREF_IDENT(__))) then - let offset = intAdd(position(cri.ident,ty.singletonFields),1) // 1-based + let offset = intAdd(findVarIndex(cri.ident,getMetaRecordFields(ty)),2) // 0-based '(MMC_FETCH(MMC_OFFSET(MMC_UNTAGPTR(_<%cr.ident%>), <%offset%>)))' else match context @@ -5899,6 +5894,19 @@ template daeExpTsub(Exp inExp, Context context, Text &preExp, error(sourceInfo(), '<%printExpStr(inExp)%>: TSUB only makes sense if the subscripted expression is a function call of tuple type') end daeExpTsub; +template daeExpRsub(Exp inExp, Context context, Text &preExp, + Text &varDecls, Text &auxFunction) + "Generates code for an tsub expression." +::= + match inExp + case RSUB(__) then + let res = daeExp(exp, context, &preExp, &varDecls, &auxFunction) + let offset = intAdd(ix,1) // 1-based + '(MMC_FETCH(MMC_OFFSET(MMC_UNTAGPTR(<%res%>), <%offset%>)))' + case RSUB(__) then + error(sourceInfo(), '<%printExpStr(inExp)%>: failed') +end daeExpRsub; + template daeExpAsub(Exp inExp, Context context, Text &preExp, Text &varDecls, Text &auxFunction) "Generates code for an asub expression." diff --git a/Compiler/Template/CodegenCpp.tpl b/Compiler/Template/CodegenCpp.tpl index da464966e4e..29f1134f7a8 100644 --- a/Compiler/Template/CodegenCpp.tpl +++ b/Compiler/Template/CodegenCpp.tpl @@ -26,8 +26,8 @@ template translateModel(SimCode simCode) '<%numRealVars%> - 1', '<%numIntVars%> - 1', '<%numBoolVars%> - 1', &extraFuncs, &extraFuncsDecl, className, "", "", "", stateDerVectorName, false), 'OMCpp<%fileNamePrefix%>.cpp') let()= textFile(simulationHeaderFile(simCode , contextOther,&extraFuncs , &extraFuncsDecl, className, "", "", "", - memberVariableDefine(modelInfo, varToArrayIndexMapping, '<%numRealVars%> - 1', '<%numIntVars%> - 1', '<%numBoolVars%> - 1', false), - memberVariableDefinePreVariables(modelInfo, varToArrayIndexMapping, '<%numRealVars%> - 1', '<%numIntVars%> - 1', '<%numBoolVars%> - 1', false), + memberVariableDefine(modelInfo, varToArrayIndexMapping, '<%numRealVars%> - 1', '<%numIntVars%> - 1', '<%numBoolVars%> - 1', Flags.isSet(Flags.GEN_DEBUG_SYMBOLS), false), + memberVariableDefinePreVariables(modelInfo, varToArrayIndexMapping, '<%numRealVars%> - 1', '<%numIntVars%> - 1', '<%numBoolVars%> - 1', Flags.isSet(Flags.GEN_DEBUG_SYMBOLS), false), false), 'OMCpp<%fileNamePrefix%>.h') let()= textFile(simulationTypesHeaderFile(simCode, &extraFuncs, &extraFuncsDecl, "", modelInfo.functions, literals, stateDerVectorName, false), 'OMCpp<%fileNamePrefix%>Types.h') let()= textFile(simulationMakefile(target,simCode , &extraFuncs , &extraFuncsDecl, "","","","","",false), '<%fileNamePrefix%>.makefile') @@ -58,7 +58,7 @@ template translateModel(SimCode simCode) let()= textFile(simulationWriteOutputParameterCppFile(simCode , &extraFuncs , &extraFuncsDecl, "", false),'OMCpp<%fileNamePrefix%>WriteOutputParameter.cpp') let()= textFile(simulationWriteOutputAliasVarsCppFile(simCode , &extraFuncs , &extraFuncsDecl, "", stateDerVectorName, false),'OMCpp<%fileNamePrefix%>WriteOutputAliasVars.cpp') let()= textFile(simulationFactoryFile(simCode , &extraFuncs , &extraFuncsDecl, ""),'OMCpp<%fileNamePrefix%>FactoryExport.cpp') - let()= textFile(modelInitXMLFile(simCode, numRealVars, numIntVars, numBoolVars),'OMCpp<%fileNamePrefix%>Init.xml') + //let()= textFile(modelInitXMLFile(simCode, numRealVars, numIntVars, numBoolVars),'OMCpp<%fileNamePrefix%>Init.xml') let()= textFile(simulationMainRunScript(simCode , &extraFuncs , &extraFuncsDecl, "", "", "", "exec"), '<%fileNamePrefix%><%simulationMainRunScriptSuffix(simCode , &extraFuncs , &extraFuncsDecl, "")%>') let jac = (jacobianMatrixes |> (mat, _, _, _, _, _, _) => (mat |> (eqs,_,_) => algloopfiles(eqs,simCode , &extraFuncs , &extraFuncsDecl, "",contextAlgloopJacobian, stateDerVectorName, false) ;separator="") @@ -143,7 +143,7 @@ let initeqs = generateEquationMemberFuncDecls(initialEquations,"initEquation") void initializeIntAlgVars(); void initializeBoolAlgVars(); - <%List.partition(vars.aliasVars, 100) |> ls hasindex idx => 'void initializeAliasVars_<%idx%>();';separator="\n"%> + <%/*List.partition(vars.aliasVars, 100) |> ls hasindex idx => 'void initializeAliasVars_<%idx%>();';separator="\n"*/%> <%List.partition(vars.stringAliasVars, 100) |> ls hasindex idx => 'void initializeStringAliasVars_<%idx%>();';separator="\n"%> void initializeStringAliasVars(); void initializeAliasVars(); @@ -568,9 +568,9 @@ case modelInfo as MODELINFO(vars=SIMVARS(__)) then let &varDecls9 = buffer "" /*BUFD*/ let &varDecls10 = buffer "" /*BUFD*/ let &varDecls11 = buffer "" /*BUFD*/ - let init7 = initAliasValstWithSplit("Real", '<%lastIdentOfPath(modelInfo.name)%>Initialize::initializeAliasVars', vars.aliasVars, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, contextOther, stateDerVectorName, useFlatArrayNotation) - let init8 = initAliasValst(varDecls8, "Int", vars.intAliasVars, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, contextOther, stateDerVectorName, useFlatArrayNotation) - let init9 = initValst(varDecls9, "Bool",vars.boolAliasVars, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, contextOther, stateDerVectorName, useFlatArrayNotation) + let init7 = ""//initAliasValstWithSplit("Real", '<%lastIdentOfPath(modelInfo.name)%>Initialize::initializeAliasVars', vars.aliasVars, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, contextOther, stateDerVectorName, useFlatArrayNotation) + let init8 = ""//initAliasValst(varDecls8, "Int", vars.intAliasVars, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, contextOther, stateDerVectorName, useFlatArrayNotation) + let init9 = ""//initValst(varDecls9, "Bool",vars.boolAliasVars, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, contextOther, stateDerVectorName, useFlatArrayNotation) let init10 = initStringAliasValstWithSplit("String", '<%lastIdentOfPath(modelInfo.name)%>Initialize::initializeStringAliasVars', vars.stringAliasVars, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, contextOther, stateDerVectorName, useFlatArrayNotation) @@ -733,10 +733,11 @@ case SIMCODE(modelInfo = MODELINFO(__)) then void <%lastIdentOfPath(modelInfo.name)%>WriteOutput::initialize() { - _historyImpl->init(); - - - _historyImpl->clear(); + if(getGlobalSettings()->getOutputPointType()!= OPT_NONE) + { + _historyImpl->init(); + _historyImpl->clear(); + } } <%writeoutput(simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%> >> @@ -1510,7 +1511,8 @@ template simulationMainRunScript(SimCode simCode ,Text& extraFuncs,Text& extraFu let solver = settings.method let moLib = makefileParams.compileDir let home = makefileParams.omhome - let execParameters = '-s <%start%> -e <%end%> -f <%stepsize%> -v <%intervals%> -y <%tol%> -i <%solver%> -r <%simulationLibDir(simulationCodeTarget(),simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)%> -m <%moLib%> -R <%simulationResults(getRunningTestsuite(),simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)%> -o <%settings.outputFormat%>' + let execParameters = '-s <%start%> -e <%end%> -f <%stepsize%> -v <%intervals%> -y <%tol%> -i <%solver%> -r <%simulationLibDir(simulationCodeTarget(),simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)%> -m <%moLib%> -R <%simulationResults(getRunningTestsuite(),simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)%>' + let outputParameter = if (stringEq(settings.outputFormat, "empty")) then "-O none" else "" let fileNamePrefixx = fileNamePrefix let libFolder =simulationLibDir(simulationCodeTarget(),simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace) @@ -1522,7 +1524,7 @@ template simulationMainRunScript(SimCode simCode ,Text& extraFuncs,Text& extraFu << #!/bin/sh <%preRunCommandLinux%> - <%execCommandLinux%> ./<%fileNamePrefixx%> <%execParameters%> $* + <%execCommandLinux%> ./<%fileNamePrefixx%> <%execParameters%> <%outputParameter%> $* >> case "win32" case "win64" then @@ -1531,7 +1533,7 @@ template simulationMainRunScript(SimCode simCode ,Text& extraFuncs,Text& extraFu <%preRunCommandWindows%> REM ::export PATH=<%libFolder%>:$PATH REPLACE C: with /C/ SET PATH=<%home%>/bin;<%libFolder%>;<%libPaths%>;%PATH% - <%moLib%>/<%fileNamePrefixx%>.exe <%execParameters%> + <%moLib%>/<%fileNamePrefixx%>.exe <%execParameters%> <%outputParameter%> >> end match end match @@ -1980,8 +1982,7 @@ case SIMCODE(modelInfo=MODELINFO(__), makefileParams=MAKEFILE_PARAMS(__), simula opts["-r"] = "<%simulationLibDir(simulationCodeTarget(),simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)%>"; opts["-m"] = "<%moLib%>"; opts["-R"] = "<%simulationResults(getRunningTestsuite(),simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)%>"; - opts["-o"] = "<%settings.outputFormat%>"; - + <%if (stringEq(settings.outputFormat, "empty")) then 'opts["-O"] = "none";' else ""%> <% match(getConfigString(PROFILING_LEVEL)) case("none") then '//no profiling used' @@ -3020,7 +3021,7 @@ match simCode case SIMCODE(modelInfo = MODELINFO(__)) then let className = lastIdentOfPath(modelInfo.name) let &additionalConstructorVarDefsBuffer = buffer additionalConstructorVarDefs - let memberVariableInitialize = memberVariableInitialize(modelInfo, varToArrayIndexMapping, indexForUndefinedReferencesReal, indexForUndefinedReferencesInt, indexForUndefinedReferencesBool, useFlatArrayNotation, additionalConstructorVarDefsBuffer, extraFuncsDecl) + let memberVariableInitialize = memberVariableInitialize(modelInfo, varToArrayIndexMapping, indexForUndefinedReferencesReal, indexForUndefinedReferencesInt, indexForUndefinedReferencesBool, Flags.isSet(Flags.GEN_DEBUG_SYMBOLS), useFlatArrayNotation, additionalConstructorVarDefsBuffer, extraFuncsDecl) let constVariableInitialize = simulationInitFile(simCode, &extraFuncsDecl, stateDerVectorName, false) << #if defined(__TRICORE__) || defined(__vxworks) @@ -6065,41 +6066,41 @@ case SIMCODE(modelInfo = MODELINFO(__),simulationSettingsOpt = SOME(settings as writeDerivativeVarsResultNames(varsnames); <% - match settings.outputFormat case "mat" - then - << - writeParametertNames(paramnames); - writeIntParameterNames(paramnames); - writeBoolParameterNames(paramnames); - writeAlgVarsResultDescription(vardescs); - writeDiscreteAlgVarsResultDescription(vardescs); - writeIntAlgVarsResultDescription(vardescs); - writeBoolAlgVarsResultDescription(vardescs); - writeAliasVarsResultDescription(vardescs); - writeIntAliasVarsResultDescription(vardescs); - writeBoolAliasVarsResultDescription(vardescs); - writeStateVarsResultDescription(vardescs); - writeDerivativeVarsResultDescription(vardescs); - writeParameterDescription(paramdecs); - writeIntParameterDescription(paramdecs); - writeBoolParameterDescription(paramdecs); - >> + match settings.outputFormat + case "mat" then + << + writeParametertNames(paramnames); + writeIntParameterNames(paramnames); + writeBoolParameterNames(paramnames); + writeAlgVarsResultDescription(vardescs); + writeDiscreteAlgVarsResultDescription(vardescs); + writeIntAlgVarsResultDescription(vardescs); + writeBoolAlgVarsResultDescription(vardescs); + writeAliasVarsResultDescription(vardescs); + writeIntAliasVarsResultDescription(vardescs); + writeBoolAliasVarsResultDescription(vardescs); + writeStateVarsResultDescription(vardescs); + writeDerivativeVarsResultDescription(vardescs); + writeParameterDescription(paramdecs); + writeIntParameterDescription(paramdecs); + writeBoolParameterDescription(paramdecs); + >> %> _historyImpl->write(varsnames,vardescs,paramnames,paramdecs); <% - match settings.outputFormat case "mat" - then - << + match settings.outputFormat + case "mat" then + << HistoryImplType::value_type_p params; writeParams(params); - >> - else - << - HistoryImplType::value_type_p params; - >> + >> + else + << + HistoryImplType::value_type_p params; + >> %> - _historyImpl->write(params,_global_settings->getStartTime(),_global_settings->getEndTime()); + _historyImpl->write(params,_global_settings->getStartTime(),_global_settings->getEndTime()); } //Write the current values else @@ -7070,7 +7071,7 @@ case SIMCODE(modelInfo = MODELINFO(__)) then end generateAlgloopMethodDeclarationCode; template memberVariableDefine(ModelInfo modelInfo, HashTableCrIListArray.HashTable varToArrayIndexMapping, Text indexForUndefinedReferencesReal, Text indexForUndefinedReferencesInt, - Text indexForUndefinedReferencesBool, Boolean useFlatArrayNotation) + Text indexForUndefinedReferencesBool, Boolean createDebugCode, Boolean useFlatArrayNotation) /*Define membervariable in simulation file.*/ ::= match modelInfo @@ -7078,49 +7079,49 @@ case MODELINFO(vars=SIMVARS(__)) then << /*parameter real vars*/ <%vars.paramVars |> var => - memberVariableDefine2(var, varToArrayIndexMapping, indexForUndefinedReferencesReal, useFlatArrayNotation, "Real", true) + memberVariableDefine2(var, varToArrayIndexMapping, indexForUndefinedReferencesReal, useFlatArrayNotation, createDebugCode, "Real", true) ;separator="\n"%> /*parameter int vars*/ <%vars.intParamVars |> var => - memberVariableDefine2(var, varToArrayIndexMapping, indexForUndefinedReferencesInt, useFlatArrayNotation, "Int", true) + memberVariableDefine2(var, varToArrayIndexMapping, indexForUndefinedReferencesInt, useFlatArrayNotation, createDebugCode, "Int", true) ;separator="\n"%> /*parameter bool vars*/ <%vars.boolParamVars |> var => - memberVariableDefine2(var, varToArrayIndexMapping, indexForUndefinedReferencesBool, useFlatArrayNotation, "Bool", true) + memberVariableDefine2(var, varToArrayIndexMapping, indexForUndefinedReferencesBool, useFlatArrayNotation, createDebugCode, "Bool", true) ;separator="\n"%> /*string parameter variables*/ <%vars.stringParamVars |> var => - memberVariableDefine2(var, varToArrayIndexMapping, "0", useFlatArrayNotation, "String", false) + memberVariableDefine2(var, varToArrayIndexMapping, "0", useFlatArrayNotation, createDebugCode, "String", false) ;separator="\n"%> /*string alias variables*/ <%vars.stringAliasVars |> var => - memberVariableDefine2(var, varToArrayIndexMapping, "0", useFlatArrayNotation, "String", false) + memberVariableDefine2(var, varToArrayIndexMapping, "0", useFlatArrayNotation, createDebugCode, "String", false) ;separator="\n"%> /*external variables*/ <%vars.extObjVars |> var => - memberVariableDefine2(var, varToArrayIndexMapping, indexForUndefinedReferencesReal, useFlatArrayNotation, "Real", false) + memberVariableDefine2(var, varToArrayIndexMapping, indexForUndefinedReferencesReal, useFlatArrayNotation, createDebugCode, "Real", false) ;separator="\n"%> /*alias real vars*/ <%vars.aliasVars |> var => - memberVariableDefine2(var, varToArrayIndexMapping, indexForUndefinedReferencesReal, useFlatArrayNotation, "Real", true) + memberVariableDefine2(var, varToArrayIndexMapping, indexForUndefinedReferencesReal, useFlatArrayNotation, createDebugCode, "Real", true) ;separator="\n"%> /*alias int vars*/ <%vars.intAliasVars |> var => - memberVariableDefine2(var, varToArrayIndexMapping, indexForUndefinedReferencesInt, useFlatArrayNotation, "Int", true) + memberVariableDefine2(var, varToArrayIndexMapping, indexForUndefinedReferencesInt, useFlatArrayNotation, createDebugCode, "Int", true) ;separator="\n"%> /*alias bool vars*/ <%vars.boolAliasVars |> var => - memberVariableDefine2(var, varToArrayIndexMapping, indexForUndefinedReferencesBool, useFlatArrayNotation, "Bool", true) + memberVariableDefine2(var, varToArrayIndexMapping, indexForUndefinedReferencesBool, useFlatArrayNotation, createDebugCode, "Bool", true) ;separator="\n"%> /*string algvars*/ <%vars.stringAlgVars |> var => - memberVariableDefine2(var, varToArrayIndexMapping, "0", useFlatArrayNotation, "String", true) + memberVariableDefine2(var, varToArrayIndexMapping, "0", useFlatArrayNotation, createDebugCode, "String", true) ;separator="\n"%> >> end memberVariableDefine; template memberVariableDefinePreVariables(ModelInfo modelInfo, HashTableCrIListArray.HashTable varToArrayIndexMapping, Text indexForUndefinedReferencesReal, Text indexForUndefinedReferencesInt, - Text indexForUndefinedReferencesBool, Boolean useFlatArrayNotation) + Text indexForUndefinedReferencesBool, Boolean createDebugCode, Boolean useFlatArrayNotation) "Define membervariable in simulation file." ::= match modelInfo @@ -7129,29 +7130,29 @@ case MODELINFO(vars=SIMVARS(__)) then //Variables saved for pre, edge and change operator /*real algvars*/ <%vars.algVars |> var => - memberVariableDefine2(var, varToArrayIndexMapping, indexForUndefinedReferencesReal, useFlatArrayNotation, "Real", true) + memberVariableDefine2(var, varToArrayIndexMapping, indexForUndefinedReferencesReal, useFlatArrayNotation, createDebugCode, "Real", true) ;separator="\n"%> /*discrete algvars*/ <%vars.discreteAlgVars |> var => - memberVariableDefine2(var, varToArrayIndexMapping, indexForUndefinedReferencesReal, useFlatArrayNotation, "Real", true) + memberVariableDefine2(var, varToArrayIndexMapping, indexForUndefinedReferencesReal, useFlatArrayNotation, createDebugCode, "Real", true) ;separator="\n"%> /*int algvars*/ <%vars.intAlgVars |> var => - memberVariableDefine2(var, varToArrayIndexMapping, indexForUndefinedReferencesInt, useFlatArrayNotation, "Int", true) + memberVariableDefine2(var, varToArrayIndexMapping, indexForUndefinedReferencesInt, useFlatArrayNotation, createDebugCode, "Int", true) ;separator="\n"%> /*bool algvars*/ <%vars.boolAlgVars |> var => - memberVariableDefine2(var, varToArrayIndexMapping, indexForUndefinedReferencesBool, useFlatArrayNotation, "Bool", true) + memberVariableDefine2(var, varToArrayIndexMapping, indexForUndefinedReferencesBool, useFlatArrayNotation, createDebugCode, "Bool", true) ;separator="\n"%> /*mixed array variables*/ <%vars.mixedArrayVars |> var => - memberVariableDefine2(var, varToArrayIndexMapping, indexForUndefinedReferencesReal, useFlatArrayNotation, "Real", true) + memberVariableDefine2(var, varToArrayIndexMapping, indexForUndefinedReferencesReal, useFlatArrayNotation, createDebugCode, "Real", true) ;separator="\n"%> >> end memberVariableDefinePreVariables; template memberVariableInitialize(ModelInfo modelInfo, HashTableCrIListArray.HashTable varToArrayIndexMapping, Text indexForUndefinedReferencesReal, Text indexForUndefinedReferencesInt, - Text indexForUndefinedReferencesBool, Boolean useFlatArrayNotation, Text& additionalConstructorVariables, Text& additionalFunctionDefinitions) + Text indexForUndefinedReferencesBool, Boolean createDebugCode, Boolean useFlatArrayNotation, Text& additionalConstructorVariables, Text& additionalFunctionDefinitions) ::= match modelInfo case MODELINFO(vars=SIMVARS(__),name=name) then @@ -7172,8 +7173,8 @@ template memberVariableInitialize(ModelInfo modelInfo, HashTableCrIListArray.Has << //AlgVars <%List.partition(vars.algVars, 100) |> varPartition hasindex i0 => - memberVariableInitializeWithSplit(varPartition, i0, "defineAlgVars", classname, varToArrayIndexMapping, indexForUndefinedReferencesReal, useFlatArrayNotation, "Real", - true, additionalAlgVarFunctionCalls,additionalConstructorVariables,additionalFunctionDefinitions) ;separator="\n"%> + memberVariableInitializeWithSplit(varPartition, i0, "defineAlgVars", classname, varToArrayIndexMapping, indexForUndefinedReferencesReal, useFlatArrayNotation, createDebugCode, "Real", + additionalAlgVarFunctionCalls,additionalConstructorVariables,additionalFunctionDefinitions) ;separator="\n"%> void <%classname%>::defineAlgVars() { @@ -7182,8 +7183,8 @@ template memberVariableInitialize(ModelInfo modelInfo, HashTableCrIListArray.Has //DiscreteAlgVars <%List.partition(vars.discreteAlgVars, 100) |> varPartition hasindex i0 => - memberVariableInitializeWithSplit(varPartition, i0, "defineDiscreteAlgVars", classname, varToArrayIndexMapping, indexForUndefinedReferencesReal, useFlatArrayNotation, "Real", - true, additionalDiscreteAlgVarFunctionCalls,additionalConstructorVariables,additionalFunctionDefinitions) ;separator="\n"%> + memberVariableInitializeWithSplit(varPartition, i0, "defineDiscreteAlgVars", classname, varToArrayIndexMapping, indexForUndefinedReferencesReal, useFlatArrayNotation, createDebugCode, "Real", + additionalDiscreteAlgVarFunctionCalls,additionalConstructorVariables,additionalFunctionDefinitions) ;separator="\n"%> void <%classname%>::defineDiscreteAlgVars() { @@ -7192,8 +7193,8 @@ template memberVariableInitialize(ModelInfo modelInfo, HashTableCrIListArray.Has //IntAlgVars <%List.partition(vars.intAlgVars, 100) |> varPartition hasindex i0 => - memberVariableInitializeWithSplit(varPartition, i0, "defineIntAlgVars", classname, varToArrayIndexMapping, indexForUndefinedReferencesInt, useFlatArrayNotation, "Int", - true, additionalIntAlgVarFunctionCalls,additionalConstructorVariables,additionalFunctionDefinitions) ;separator="\n"%> + memberVariableInitializeWithSplit(varPartition, i0, "defineIntAlgVars", classname, varToArrayIndexMapping, indexForUndefinedReferencesInt, useFlatArrayNotation, createDebugCode, "Int", + additionalIntAlgVarFunctionCalls,additionalConstructorVariables,additionalFunctionDefinitions) ;separator="\n"%> void <%classname%>::defineIntAlgVars() { <%additionalIntAlgVarFunctionCalls%> @@ -7201,8 +7202,8 @@ template memberVariableInitialize(ModelInfo modelInfo, HashTableCrIListArray.Has //BoolAlgVars <%List.partition(vars.boolAlgVars, 100) |> varPartition hasindex i0 => - memberVariableInitializeWithSplit(varPartition, i0, "defineBoolAlgVars", classname, varToArrayIndexMapping, indexForUndefinedReferencesBool, useFlatArrayNotation, "Bool", - true, additionalBoolAlgVarFunctionCalls,additionalConstructorVariables,additionalFunctionDefinitions) ;separator="\n"%> + memberVariableInitializeWithSplit(varPartition, i0, "defineBoolAlgVars", classname, varToArrayIndexMapping, indexForUndefinedReferencesBool, useFlatArrayNotation, createDebugCode, "Bool", + additionalBoolAlgVarFunctionCalls,additionalConstructorVariables,additionalFunctionDefinitions) ;separator="\n"%> void <%classname%>::defineBoolAlgVars() { <%additionalBoolAlgVarFunctionCalls%> @@ -7210,8 +7211,8 @@ template memberVariableInitialize(ModelInfo modelInfo, HashTableCrIListArray.Has //ParameterRealVars <%List.partition(vars.paramVars, 100) |> varPartition hasindex i0 => - memberVariableInitializeWithSplit(varPartition, i0, "defineParameterRealVars", classname, varToArrayIndexMapping, indexForUndefinedReferencesReal, useFlatArrayNotation, "Real", - true, additionalParameterRealVarFunctionCalls,additionalConstructorVariables,additionalFunctionDefinitions) ;separator="\n"%> + memberVariableInitializeWithSplit(varPartition, i0, "defineParameterRealVars", classname, varToArrayIndexMapping, indexForUndefinedReferencesReal, useFlatArrayNotation, createDebugCode, "Real", + additionalParameterRealVarFunctionCalls,additionalConstructorVariables,additionalFunctionDefinitions) ;separator="\n"%> void <%classname%>::defineParameterRealVars() { <%additionalParameterRealVarFunctionCalls%> @@ -7219,8 +7220,8 @@ template memberVariableInitialize(ModelInfo modelInfo, HashTableCrIListArray.Has //ParameterIntVars <%List.partition(vars.intParamVars, 100) |> varPartition hasindex i0 => - memberVariableInitializeWithSplit(varPartition, i0, "defineParameterIntVars", classname, varToArrayIndexMapping, indexForUndefinedReferencesInt, useFlatArrayNotation, "Int", - true, additionalParameterIntVarFunctionCalls,additionalConstructorVariables,additionalFunctionDefinitions) ;separator="\n"%> + memberVariableInitializeWithSplit(varPartition, i0, "defineParameterIntVars", classname, varToArrayIndexMapping, indexForUndefinedReferencesInt, useFlatArrayNotation, createDebugCode, "Int", + additionalParameterIntVarFunctionCalls,additionalConstructorVariables,additionalFunctionDefinitions) ;separator="\n"%> void <%classname%>::defineParameterIntVars() { <%additionalParameterIntVarFunctionCalls%> @@ -7228,8 +7229,8 @@ template memberVariableInitialize(ModelInfo modelInfo, HashTableCrIListArray.Has //ParameterBoolVars <%List.partition(vars.boolParamVars, 100) |> varPartition hasindex i0 => - memberVariableInitializeWithSplit(varPartition, i0, "defineParameterBoolVars", classname, varToArrayIndexMapping, indexForUndefinedReferencesBool, useFlatArrayNotation, "Bool", - true, additionalParameterBoolVarFunctionCalls,additionalConstructorVariables,additionalFunctionDefinitions) ;separator="\n"%> + memberVariableInitializeWithSplit(varPartition, i0, "defineParameterBoolVars", classname, varToArrayIndexMapping, indexForUndefinedReferencesBool, useFlatArrayNotation, createDebugCode, "Bool", + additionalParameterBoolVarFunctionCalls,additionalConstructorVariables,additionalFunctionDefinitions) ;separator="\n"%> void <%classname%>::defineParameterBoolVars() { <%additionalParameterBoolVarFunctionCalls%> @@ -7237,8 +7238,8 @@ template memberVariableInitialize(ModelInfo modelInfo, HashTableCrIListArray.Has //AliasRealVars <%List.partition(vars.aliasVars, 100) |> varPartition hasindex i0 => - memberVariableInitializeWithSplit(varPartition, i0, "defineAliasRealVars", classname, varToArrayIndexMapping, indexForUndefinedReferencesReal, useFlatArrayNotation, "Real", - true, additionalAliasRealVarFunctionCalls,additionalConstructorVariables,additionalFunctionDefinitions) ;separator="\n"%> + memberVariableInitializeWithSplit(varPartition, i0, "defineAliasRealVars", classname, varToArrayIndexMapping, indexForUndefinedReferencesReal, useFlatArrayNotation, createDebugCode, "Real", + additionalAliasRealVarFunctionCalls,additionalConstructorVariables,additionalFunctionDefinitions) ;separator="\n"%> void <%classname%>::defineAliasRealVars() { <%additionalAliasRealVarFunctionCalls%> @@ -7246,8 +7247,8 @@ template memberVariableInitialize(ModelInfo modelInfo, HashTableCrIListArray.Has //AliasIntVars <%List.partition(vars.intAliasVars, 100) |> varPartition hasindex i0 => - memberVariableInitializeWithSplit(varPartition, i0, "defineAliasIntVars", classname, varToArrayIndexMapping, indexForUndefinedReferencesInt, useFlatArrayNotation, "Int", - true, additionalAliasIntVarFunctionCalls,additionalConstructorVariables,additionalFunctionDefinitions) ;separator="\n"%> + memberVariableInitializeWithSplit(varPartition, i0, "defineAliasIntVars", classname, varToArrayIndexMapping, indexForUndefinedReferencesInt, useFlatArrayNotation, createDebugCode, "Int", + additionalAliasIntVarFunctionCalls,additionalConstructorVariables,additionalFunctionDefinitions) ;separator="\n"%> void <%classname%>::defineAliasIntVars() { <%additionalAliasIntVarFunctionCalls%> @@ -7255,8 +7256,8 @@ template memberVariableInitialize(ModelInfo modelInfo, HashTableCrIListArray.Has //AliasBoolVars <%List.partition(vars.boolAliasVars, 100) |> varPartition hasindex i0 => - memberVariableInitializeWithSplit(varPartition, i0, "defineAliasBoolVars", classname, varToArrayIndexMapping, indexForUndefinedReferencesBool, useFlatArrayNotation, "Bool", - true, additionalAliasBoolVarFunctionCalls,additionalConstructorVariables,additionalFunctionDefinitions) ;separator="\n"%> + memberVariableInitializeWithSplit(varPartition, i0, "defineAliasBoolVars", classname, varToArrayIndexMapping, indexForUndefinedReferencesBool, useFlatArrayNotation, createDebugCode, "Bool", + additionalAliasBoolVarFunctionCalls,additionalConstructorVariables,additionalFunctionDefinitions) ;separator="\n"%> void <%classname%>::defineAliasBoolVars() { <%additionalAliasBoolVarFunctionCalls%> @@ -7264,8 +7265,8 @@ template memberVariableInitialize(ModelInfo modelInfo, HashTableCrIListArray.Has //MixedArrayVars <%List.partition(vars.mixedArrayVars, 100) |> varPartition hasindex i0 => - memberVariableInitializeWithSplit(varPartition, i0, "defineMixedArrayVars", classname, varToArrayIndexMapping, indexForUndefinedReferencesReal, useFlatArrayNotation, "Real", - true, additionalMixedArrayVarFunctionCalls,additionalConstructorVariables,additionalFunctionDefinitions) ;separator="\n"%> + memberVariableInitializeWithSplit(varPartition, i0, "defineMixedArrayVars", classname, varToArrayIndexMapping, indexForUndefinedReferencesReal, useFlatArrayNotation, createDebugCode, "Real", + additionalMixedArrayVarFunctionCalls,additionalConstructorVariables,additionalFunctionDefinitions) ;separator="\n"%> void <%classname%>::defineMixedArrayVars() { <%additionalMixedArrayVarFunctionCalls%> @@ -7274,7 +7275,7 @@ template memberVariableInitialize(ModelInfo modelInfo, HashTableCrIListArray.Has end memberVariableInitialize; template memberVariableInitializeWithSplit(list simVars, Text idx, Text functionPrefix, Text className, HashTableCrIListArray.HashTable varToArrayIndexMapping, Text indexForUndefinedReferences, Boolean useFlatArrayNotation, - String type, Boolean createRefVar, Text& additionalFunctionCalls, Text& additionalConstructorVariables, Text& additionalFunctionDefinitions) + Boolean createDebugCode, String type, Text& additionalFunctionCalls, Text& additionalConstructorVariables, Text& additionalFunctionDefinitions) ::= let &additionalFunctionCalls += ' <%functionPrefix%>_<%idx%>();<%\n%>' let &additionalFunctionDefinitions += 'void <%functionPrefix%>_<%idx%>();<%\n%>' @@ -7282,23 +7283,25 @@ template memberVariableInitializeWithSplit(list simVars, Text idx, Text void <%className%>::<%functionPrefix%>_<%idx%>() { <%simVars |> var => - memberVariableInitialize2(var, varToArrayIndexMapping, indexForUndefinedReferences, useFlatArrayNotation, type, createRefVar, additionalConstructorVariables) + memberVariableInitialize2(var, varToArrayIndexMapping, indexForUndefinedReferences, useFlatArrayNotation, createDebugCode, type, additionalConstructorVariables) ;separator="\n"%> } >> end memberVariableInitializeWithSplit; template memberVariableInitialize2(SimVar simVar, HashTableCrIListArray.HashTable varToArrayIndexMapping, Text indexForUndefinedReferences, Boolean useFlatArrayNotation, - String type, Boolean createRefVar, Text& additionalConstructorVariables) + Boolean createDebugCode, String type, Text& additionalConstructorVariables) ::= - -match simVar + match simVar case SIMVAR(numArrayElement={},arrayCref=NONE(),name=CREF_IDENT(subscriptLst=_::_)) then '' - case SIMVAR(numArrayElement={},arrayCref=NONE()) then - //let index = '<%listHead(SimCodeUtil.getVarIndexListByMapping(varToArrayIndexMapping,name,indexForUndefinedReferences))%>' - //let &additionalConstructorVariables += ',<%cref(name,useFlatArrayNotation)%>(_sim_vars->init<%type%>Var(<%index%>))<%\n%>' - "" + case SIMVAR(numArrayElement={},arrayCref=NONE(),name=name) then + match(createDebugCode) + case true then + let index = '<%listHead(SimCodeUtil.getVarIndexListByMapping(varToArrayIndexMapping,name,indexForUndefinedReferences))%>' + let &additionalConstructorVariables += ',<%cref(name,useFlatArrayNotation)%>(_sim_vars->init<%type%>Var(<%index%>))<%\n%>' + "" + else "" case v as SIMVAR(name=CREF_IDENT(__),arrayCref=SOME(_),numArrayElement=num) case v as SIMVAR(name=CREF_QUAL(__),arrayCref=SOME(_),numArrayElement=num) then let &dims = buffer "" /*BUFD*/ @@ -7311,9 +7314,12 @@ match simVar else match dims case "0" then - //let index = '<%listHead(SimCodeUtil.getVarIndexListByMapping(varToArrayIndexMapping,name,indexForUndefinedReferences))%>' - //let& additionalConstructorVariables += ',<%arrayName%>(_sim_vars->init<%type%>Var(<%index%>))' - "" + match(createDebugCode) + case true then + let index = '<%listHead(SimCodeUtil.getVarIndexListByMapping(varToArrayIndexMapping,name,indexForUndefinedReferences))%>' + let& additionalConstructorVariables += ',<%arrayName%>(_sim_vars->init<%type%>Var(<%index%>))' + "" + else "" else let size = Util.mulStringDelimit2Int(array_num_elem,",") if SimCodeUtil.isVarIndexListConsecutive(varToArrayIndexMapping,name) then @@ -7336,9 +7342,12 @@ match simVar let varType = variableType(type_) match dims case "0" then - //let index = '<%listHead(SimCodeUtil.getVarIndexListByMapping(varToArrayIndexMapping,name,indexForUndefinedReferences))%>' - //let& additionalConstructorVariables += ',<%varName%>(_sim_vars->init<%type%>Var(<%index%>))' - "" + match createDebugCode + case true then + let index = '<%listHead(SimCodeUtil.getVarIndexListByMapping(varToArrayIndexMapping,name,indexForUndefinedReferences))%>' + let& additionalConstructorVariables += ',<%varName%>(_sim_vars->init<%type%>Var(<%index%>))' + "" + else "" else '' end match end memberVariableInitialize2; @@ -7533,24 +7542,25 @@ end memberVariableDefineReference; template memberVariableDefine2(SimVar simVar, HashTableCrIListArray.HashTable varToArrayIndexMapping, Text indexForUndefinedReferences, - Boolean useFlatArrayNotation, String type, Boolean createRefVar) + Boolean useFlatArrayNotation, Boolean createDebugCode, String type, Boolean createRefVar) ::= match simVar case SIMVAR(numArrayElement={},arrayCref=NONE(),name=CREF_IDENT(subscriptLst=_::_)) then '' - case SIMVAR(numArrayElement={},arrayCref=NONE()) then - /* - << - <%variableType(type_)%><%if createRefVar then '&' else ''%> <%cref(name,useFlatArrayNotation)%>; - >> - */ - if createRefVar then - let index = '<%listHead(SimCodeUtil.getVarIndexListByMapping(varToArrayIndexMapping,name,indexForUndefinedReferences))%>' - << - #define <%cref(name,useFlatArrayNotation)%> _pointerTo<%type%>Vars[<%index%>] - >> - else - '<%variableType(type_)%> <%cref(name,useFlatArrayNotation)%>;' + case SIMVAR(numArrayElement={},arrayCref=NONE(),name=name,type_=type_) then + match createDebugCode + case true then + << + <%variableType(type_)%><%if createRefVar then '&' else ''%> <%cref(name,useFlatArrayNotation)%>; + >> + else + if createRefVar then + let index = '<%listHead(SimCodeUtil.getVarIndexListByMapping(varToArrayIndexMapping,name,indexForUndefinedReferences))%>' + << + #define <%cref(name,useFlatArrayNotation)%> _pointerTo<%type%>Vars[<%index%>] + >> + else + '<%variableType(type_)%> <%cref(name,useFlatArrayNotation)%>;' case v as SIMVAR(name=CREF_IDENT(__),arrayCref=SOME(_),numArrayElement=num) case v as SIMVAR(name=CREF_QUAL(__),arrayCref=SOME(_),numArrayElement=num) then @@ -7560,18 +7570,19 @@ template memberVariableDefine2(SimVar simVar, HashTableCrIListArray.HashTable va let array_dimensions = arrayextentDims(name, v.numArrayElement) match dims case "0" then - /* - << - <%typeString%><%if createRefVar then '&' else ''%> <%arrayName%>; - >> - */ - if createRefVar then - let index = '<%listHead(SimCodeUtil.getVarIndexListByMapping(varToArrayIndexMapping,name,indexForUndefinedReferences))%>' - << - #define <%arrayName%> _pointerTo<%type%>Vars[<%index%>] - >> - else - '<%typeString%> <%arrayName%>;' + match createDebugCode + case true then + << + <%typeString%><%if createRefVar then '&' else ''%> <%arrayName%>; + >> + else + if createRefVar then + let index = '<%listHead(SimCodeUtil.getVarIndexListByMapping(varToArrayIndexMapping,name,indexForUndefinedReferences))%>' + << + #define <%arrayName%> _pointerTo<%type%>Vars[<%index%>] + >> + else + '<%typeString%> <%arrayName%>;' else if SimCodeUtil.isVarIndexListConsecutive(varToArrayIndexMapping,name) then << @@ -7588,12 +7599,15 @@ template memberVariableDefine2(SimVar simVar, HashTableCrIListArray.HashTable va let varType = variableType(type_) match dims case "0" then - //'<%varType%><%if createRefVar then '&' else ''%> <%varName%>;' - if createRefVar then - let index = '<%listHead(SimCodeUtil.getVarIndexListByMapping(varToArrayIndexMapping,name,indexForUndefinedReferences))%>' - '#define <%varName%> _pointerTo<%type%>Vars[<%index%>]' - else - '<%varType%> <%varName%>;' + match createDebugCode + case true then + '<%varType%><%if createRefVar then '&' else ''%> <%varName%>;' + else + if createRefVar then + let index = '<%listHead(SimCodeUtil.getVarIndexListByMapping(varToArrayIndexMapping,name,indexForUndefinedReferences))%>' + '#define <%varName%> _pointerTo<%type%>Vars[<%index%>]' + else + '<%varType%> <%varName%>;' else '' end match end memberVariableDefine2; @@ -14954,9 +14968,6 @@ template algStatement(DAE.Statement stmt, Context context, Text &varDecls,SimCod <%res%> <%endModelicaLine()%> >> - - - end algStatement; template algStmtWhile(DAE.Statement stmt, Context context, Text &varDecls /*BUFP*/,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation) diff --git a/Compiler/Template/CodegenCppHpcom.tpl b/Compiler/Template/CodegenCppHpcom.tpl index e674dcbcf88..ac7d348954b 100644 --- a/Compiler/Template/CodegenCppHpcom.tpl +++ b/Compiler/Template/CodegenCppHpcom.tpl @@ -25,10 +25,10 @@ template translateModel(SimCode simCode) let useMemoryOptimization = Flags.isSet(Flags.HPCOM_MEMORY_OPT) let className = lastIdentOfPath(modelInfo.name) - let numRealVars = numRealvars(modelInfo, hpcomData.hpcOmMemory) - let numIntVars = numIntvars(modelInfo, hpcomData.hpcOmMemory) - let numBoolVars = numBoolvars(modelInfo, hpcomData.hpcOmMemory) - let numPreVars = getPreVarsCount(modelInfo, hpcomData.hpcOmMemory) + let numRealVars = numRealvarsHpcom(modelInfo, hpcomData.hpcOmMemory) + let numIntVars = numIntvarsHpcom(modelInfo, hpcomData.hpcOmMemory) + let numBoolVars = numBoolvarsHpcom(modelInfo, hpcomData.hpcOmMemory) + let numPreVars = numPreVarsHpcom(modelInfo, hpcomData.hpcOmMemory) let() = textFile(simulationMainFile(target, simCode, &extraFuncs, &extraFuncsDecl, "", (if Flags.isSet(USEMPI) then "#include " else ""), @@ -36,19 +36,19 @@ template translateModel(SimCode simCode) (if Flags.isSet(USEMPI) then mpiFinalize() else ""), numRealVars, numIntVars, numBoolVars, numPreVars), 'OMCpp<%fileNamePrefix%>Main.cpp') - let() = textFile(simulationCppFile(simCode, contextOther, update(allEquations, whenClauses, simCode, &extraFuncs, &extraFuncsDecl, "", contextOther, stateDerVectorName, false), + let() = textFile(simulationCppFile(simCode, contextOther, updateHpcom(allEquations, whenClauses, simCode, &extraFuncs, &extraFuncsDecl, "", contextOther, stateDerVectorName, false), '<%numRealVars%>-1', '<%numIntVars%>-1', '<%numBoolVars%>-1', &extraFuncs, &extraFuncsDecl, className, - generateAdditionalConstructorDefinitions(hpcomData.schedules), - generateAdditionalConstructorBodyStatements(hpcomData.schedules, className, dotPath(modelInfo.name)), - generateAdditionalDestructorBodyStatements(hpcomData.schedules), + additionalHpcomConstructorDefinitions(hpcomData.schedules), + additionalHpcomConstructorBodyStatements(hpcomData.schedules, className, dotPath(modelInfo.name)), + additionalHpcomDestructorBodyStatements(hpcomData.schedules), stateDerVectorName, false), 'OMCpp<%fileNamePrefix%>.cpp') let() = textFile(simulationHeaderFile(simCode ,contextOther, &extraFuncs, &extraFuncsDecl, "", - generateAdditionalIncludes(simCode, &extraFuncs, &extraFuncsDecl, className, false), + additionalHpcomIncludes(simCode, &extraFuncs, &extraFuncsDecl, className, false), "", - generateAdditionalProtectedMemberDeclaration(simCode, &extraFuncs, &extraFuncsDecl, "", false), - memberVariableDefine(modelInfo, varToArrayIndexMapping, '<%numRealVars%>-1', '<%numIntVars%>-1', '<%numBoolVars%>-1', false), - memberVariableDefinePreVariables(modelInfo, varToArrayIndexMapping, '<%numRealVars%>-1', '<%numIntVars%>-1', '<%numBoolVars%>-1', false), false), + additionalHpcomProtectedMemberDeclaration(simCode, &extraFuncs, &extraFuncsDecl, "", false), + memberVariableDefine(modelInfo, varToArrayIndexMapping, '<%numRealVars%>-1', '<%numIntVars%>-1', '<%numBoolVars%>-1', Flags.isSet(Flags.GEN_DEBUG_SYMBOLS), false), + memberVariableDefinePreVariables(modelInfo, varToArrayIndexMapping, '<%numRealVars%>-1', '<%numIntVars%>-1', '<%numBoolVars%>-1', Flags.isSet(Flags.GEN_DEBUG_SYMBOLS), false), false), //CodegenCpp.MemberVariablePreVariables(modelInfo,false), false), 'OMCpp<%fileNamePrefix%>.h') @@ -93,18 +93,18 @@ template translateModel(SimCode simCode) end translateModel; // HEADER -template generateAdditionalIncludes(SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Boolean useFlatArrayNotation) +template additionalHpcomIncludes(SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Boolean useFlatArrayNotation) "Generates code for header file for simulation target." ::= match simCode case SIMCODE(__) then << - <%generateAdditionalIncludesForParallelCode(simCode, extraFuncs, extraFuncsDecl, extraFuncsNamespace)%> + <%additionalHpcomIncludesForParallelCode(simCode, extraFuncs, extraFuncsDecl, extraFuncsNamespace)%> >> end match -end generateAdditionalIncludes; +end additionalHpcomIncludes; -template generateAdditionalIncludesForParallelCode(SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace) +template additionalHpcomIncludesForParallelCode(SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace) ::= let type = getConfigString(HPCOM_CODE) match type @@ -139,9 +139,9 @@ template generateAdditionalIncludesForParallelCode(SimCode simCode, Text& extraF #include >> end match -end generateAdditionalIncludesForParallelCode; +end additionalHpcomIncludesForParallelCode; -template generateAdditionalProtectedMemberDeclaration(SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Boolean useFlatArrayNotation) +template additionalHpcomProtectedMemberDeclaration(SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Boolean useFlatArrayNotation) "Generates class declarations." ::= match simCode @@ -196,7 +196,7 @@ template generateAdditionalProtectedMemberDeclaration(SimCode simCode, Text& ext >>%> >> end match -end generateAdditionalProtectedMemberDeclaration; +end additionalHpcomProtectedMemberDeclaration; template generateAdditionalStructHeaders(Schedule odeSchedule) ::= @@ -407,7 +407,7 @@ template generateThreadFunctionHeaderDecl(Integer threadIdx) >> end generateThreadFunctionHeaderDecl; -template generateAdditionalConstructorDefinitions(Option> scheduleOpt) +template additionalHpcomConstructorDefinitions(Option> scheduleOpt) ::= let type = getConfigString(HPCOM_CODE) match scheduleOpt @@ -435,9 +435,9 @@ template generateAdditionalConstructorDefinitions(Option> schedulesOpt, String modelNamePrefixStr, String fullModelName) +template additionalHpcomConstructorBodyStatements(Option> schedulesOpt, String modelNamePrefixStr, String fullModelName) ::= let type = getConfigString(HPCOM_CODE) match schedulesOpt @@ -524,7 +524,7 @@ template generateAdditionalConstructorBodyStatements(Option> end destroyArrayLocks; -template generateAdditionalDestructorBodyStatements(Option> schedulesOpt) +template additionalHpcomDestructorBodyStatements(Option> schedulesOpt) ::= let type = getConfigString(HPCOM_CODE) match schedulesOpt @@ -694,29 +694,27 @@ template generateAdditionalDestructorBodyStatements(Option allEquationsPlusWhen, list whenClauses, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Context context, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation) +template updateHpcom(list allEquationsPlusWhen, list whenClauses, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Context context, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation) ::= let &varDecls = buffer "" /*BUFD*/ match simCode case SIMCODE(modelInfo = MODELINFO(__), hpcomData=HPCOMDATA(__)) then - let parCode = generateParallelEvaluate(allEquationsPlusWhen, modelInfo.name, whenClauses, simCode, extraFuncs ,extraFuncsDecl, extraFuncsNamespace, hpcomData.schedules, context, stateDerVectorName, lastIdentOfPath(modelInfo.name), useFlatArrayNotation) + let &extraFuncsPar = buffer "" + let parCode = generateParallelEvaluate(allEquationsPlusWhen, modelInfo.name, whenClauses, simCode, extraFuncsPar ,extraFuncsDecl, extraFuncsNamespace, hpcomData.schedules, context, stateDerVectorName, lastIdentOfPath(modelInfo.name), useFlatArrayNotation) << <%equationFunctions(allEquations,whenClauses, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, contextSimulationDiscrete,stateDerVectorName,useFlatArrayNotation,false)%> <%createEvaluateConditions(allEquations,whenClauses, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, contextOther, stateDerVectorName, useFlatArrayNotation)%> - /* - <%createEvaluateZeroFuncs(equationsForZeroCrossings,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,contextOther)%> - <%createEvaluateAll(allEquations,whenClauses,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,contextOther, stateDerVectorName, useFlatArrayNotation, boolNot(stringEq(getConfigString(PROFILING_LEVEL),"none")))%> - */ <%parCode%> + + <%extraFuncsPar%> >> end match -end update; +end updateHpcom; template generateParallelEvaluate(list allEquationsPlusWhen, Absyn.Path name, list whenClauses, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Option> schedulesOpt, Context context, Text stateDerVectorName /*=__zDot*/, @@ -1880,41 +1878,41 @@ template simulationMakefile(String target, SimCode simCode, Text& extraFuncs, Te additionalLinkerFlags_MSVC, Flags.isSet(Flags.USEMPI)) end simulationMakefile; -template getPreVarsCount(ModelInfo modelInfo, Option hpcOmMemoryOpt) +template numPreVarsHpcom(ModelInfo modelInfo, Option hpcOmMemoryOpt) ::= match(hpcOmMemoryOpt) case(SOME(hpcomMemory as MEMORYMAP_ARRAY(floatArraySize=floatArraySize,intArraySize=intArraySize,boolArraySize=boolArraySize))) then '<%floatArraySize%> + <%intArraySize%> + <%boolArraySize%>' else CodegenCpp.getPreVarsCount(modelInfo) -end getPreVarsCount; +end numPreVarsHpcom; -template numRealvars(ModelInfo modelInfo, Option hpcOmMemoryOpt) +template numRealvarsHpcom(ModelInfo modelInfo, Option hpcOmMemoryOpt) ::= match(hpcOmMemoryOpt) case(SOME(hpcomMemory as MEMORYMAP_ARRAY(floatArraySize=floatArraySize))) then '<%floatArraySize%>' else '<%CodegenCpp.numRealvars(modelInfo)%>' -end numRealvars; +end numRealvarsHpcom; -template numIntvars(ModelInfo modelInfo, Option hpcOmMemoryOpt) +template numIntvarsHpcom(ModelInfo modelInfo, Option hpcOmMemoryOpt) ::= match(hpcOmMemoryOpt) case(SOME(hpcomMemory as MEMORYMAP_ARRAY(intArraySize=intArraySize))) then '<%intArraySize%>' else CodegenCpp.numIntvars(modelInfo) -end numIntvars; +end numIntvarsHpcom; -template numBoolvars(ModelInfo modelInfo, Option hpcOmMemoryOpt) +template numBoolvarsHpcom(ModelInfo modelInfo, Option hpcOmMemoryOpt) ::= match(hpcOmMemoryOpt) case(SOME(hpcomMemory as MEMORYMAP_ARRAY(boolArraySize=boolArraySize))) then '<%boolArraySize%>' else CodegenCpp.numBoolvars(modelInfo) -end numBoolvars; +end numBoolvarsHpcom; annotation(__OpenModelica_Interface="backend"); end CodegenCppHpcom; diff --git a/Compiler/Template/CodegenCppInit.tpl b/Compiler/Template/CodegenCppInit.tpl index b605d929f3d..9a8a766ca02 100644 --- a/Compiler/Template/CodegenCppInit.tpl +++ b/Compiler/Template/CodegenCppInit.tpl @@ -1,55 +1,77 @@ package CodegenCppInit import interface SimCodeTV; +import interface SimCodeBackendTV; import CodegenUtil.*; +import CodegenFMUCommon; +import CodegenFMU2; +import CodegenFMU1; -template modelInitXMLFile(SimCode simCode, String numRealVars, String numIntVars, String numBoolVars) +template modelInitXMLFile(SimCode simCode, String numRealVars, String numIntVars, String numBoolVars, String FMUVersion, String FMUType, String FMUGuid, Boolean generateFMUModelDescription, String generatorComments) + "Generate a xml file that contains informations for initialization or for the FMU-structure" ::= match simCode case SIMCODE(modelInfo = MODELINFO(__)) then - let variables = modelVariablesXML(modelInfo, varToArrayIndexMapping, '<%numRealVars%> - 1', '<%numIntVars%> - 1', '<%numBoolVars%> - 1') + let variables = modelVariablesXML(modelInfo, varToArrayIndexMapping, '<%numRealVars%> - 1', '<%numIntVars%> - 1', '<%numBoolVars%> - 1', generateFMUModelDescription) let algLoops = (listAppend(allEquations,initialEquations) |> eq => algLoopXML(eq, simCode, varToArrayIndexMapping, '<%numRealVars%> - 1') ;separator="\n") let jacobianMatrixes = jacobianMatrixesXML(simCode.jacobianMatrixes) + let descriptionTag = if generateFMUModelDescription then "fmiModelDescription" else "ModelDescription" + let fmiDescriptionAttributes = if generateFMUModelDescription then fmuDescriptionAttributes(simCode, FMUVersion, FMUType, FMUGuid) else 'modelName="<%dotPath(modelInfo.name)%>"' + let fmiTypeDefinitions = if generateFMUModelDescription then CodegenFMUCommon.fmiTypeDefinitions(modelInfo, FMUVersion) + let fmiDefaultExperiment = if generateFMUModelDescription then CodegenFMUCommon.DefaultExperiment(simulationSettingsOpt) << - - + + + <<%descriptionTag%> <%fmiDescriptionAttributes%>> + <%fmiTypeDefinitions%> + <%fmiDefaultExperiment%> <%variables%> + <%if boolNot(generateFMUModelDescription) then + << <%algLoops%> <%jacobianMatrixes%> - + >> + %> + > >> end modelInitXMLFile; -template modelVariablesXML(ModelInfo modelInfo, HashTableCrIListArray.HashTable varToArrayIndexMapping, String indexForUndefinedReferencesReal, String indexForUndefinedReferencesInt, String indexForUndefinedReferencesBool) +template fmuDescriptionAttributes(SimCode simCode, String FMUVersion, String FMUType, String FMUGuid) +::= + if isFMIVersion20(FMUVersion) then CodegenFMU2.fmiModelDescriptionAttributes(simCode,FMUGuid) + else CodegenFMU1.fmiModelDescriptionAttributes(simCode,FMUGuid) +end fmuDescriptionAttributes; + +template modelVariablesXML(ModelInfo modelInfo, HashTableCrIListArray.HashTable varToArrayIndexMapping, String indexForUndefinedReferencesReal, String indexForUndefinedReferencesInt, String indexForUndefinedReferencesBool, Boolean generateFMUModelDescription) "Generates the xml code for the variable defintions." ::= match modelInfo case MODELINFO(vars=SIMVARS(__),varInfo=VARINFO(numAlgVars= numAlgVars, numDiscreteReal = numDiscreteReal, numOptimizeConstraints = numOptimizeConstraints)) then << - <%vars.stateVars |> var => scalarVariableXML(var, varToArrayIndexMapping, indexForUndefinedReferencesReal) ;separator="\n";empty%> - <%vars.derivativeVars |> var => scalarVariableXML(var, varToArrayIndexMapping, indexForUndefinedReferencesReal) ;separator="\n";empty%> - <%vars.algVars |> var => scalarVariableXML(var, varToArrayIndexMapping, indexForUndefinedReferencesReal) ;separator="\n";empty%> - <%vars.discreteAlgVars |> var => scalarVariableXML(var, varToArrayIndexMapping, indexForUndefinedReferencesReal) ;separator="\n";empty%> + <%vars.stateVars |> var => scalarVariableXML(var, varToArrayIndexMapping, indexForUndefinedReferencesReal, generateFMUModelDescription) ;separator="\n";empty%> + <%vars.derivativeVars |> var => scalarVariableXML(var, varToArrayIndexMapping, indexForUndefinedReferencesReal, generateFMUModelDescription) ;separator="\n";empty%> + <%vars.algVars |> var => scalarVariableXML(var, varToArrayIndexMapping, indexForUndefinedReferencesReal, generateFMUModelDescription) ;separator="\n";empty%> + <%vars.discreteAlgVars |> var => scalarVariableXML(var, varToArrayIndexMapping, indexForUndefinedReferencesReal, generateFMUModelDescription) ;separator="\n";empty%> <%/*vars.realOptimizeConstraintsVars - |> var hasindex i0 => scalarVariableXML(var,varToArrayIndexMapping, indexForUndefinedReferencesReal) ;separator="\n";empty*/%> + |> var hasindex i0 => scalarVariableXML(var,varToArrayIndexMapping, indexForUndefinedReferencesReal, generateFMUModelDescription) ;separator="\n";empty*/%> <%/*vars.realOptimizeFinalConstraintsVars - |> var => scalarVariableXML(var,varToArrayIndexMapping, indexForUndefinedReferencesReal) ;separator="\n";empty*/%> - <%vars.paramVars |> var => scalarVariableXML(var,varToArrayIndexMapping, indexForUndefinedReferencesReal) ;separator="\n";empty%> - <%vars.aliasVars |> var => scalarVariableXML(var,varToArrayIndexMapping, indexForUndefinedReferencesReal) ;separator="\n";empty%> + |> var => scalarVariableXML(var,varToArrayIndexMapping, indexForUndefinedReferencesReal, generateFMUModelDescription) ;separator="\n";empty*/%> + <%vars.paramVars |> var => scalarVariableXML(var,varToArrayIndexMapping, indexForUndefinedReferencesReal, generateFMUModelDescription) ;separator="\n";empty%> + <%vars.aliasVars |> var => scalarVariableXML(var,varToArrayIndexMapping, indexForUndefinedReferencesReal, generateFMUModelDescription) ;separator="\n";empty%> - <%vars.intAlgVars |> var => scalarVariableXML(var,varToArrayIndexMapping, indexForUndefinedReferencesInt) ;separator="\n";empty%> - <%vars.intParamVars |> var => scalarVariableXML(var,varToArrayIndexMapping, indexForUndefinedReferencesInt) ;separator="\n";empty%> - <%vars.intAliasVars |> var => scalarVariableXML(var,varToArrayIndexMapping, indexForUndefinedReferencesInt) ;separator="\n";empty%> + <%vars.intAlgVars |> var => scalarVariableXML(var,varToArrayIndexMapping, indexForUndefinedReferencesInt, generateFMUModelDescription) ;separator="\n";empty%> + <%vars.intParamVars |> var => scalarVariableXML(var,varToArrayIndexMapping, indexForUndefinedReferencesInt, generateFMUModelDescription) ;separator="\n";empty%> + <%vars.intAliasVars |> var => scalarVariableXML(var,varToArrayIndexMapping, indexForUndefinedReferencesInt, generateFMUModelDescription) ;separator="\n";empty%> - <%vars.boolAlgVars |> var => scalarVariableXML(var,varToArrayIndexMapping, indexForUndefinedReferencesBool) ;separator="\n";empty%> - <%vars.boolParamVars |> var => scalarVariableXML(var,varToArrayIndexMapping, indexForUndefinedReferencesBool) ;separator="\n";empty%> - <%vars.boolAliasVars |> var => scalarVariableXML(var,varToArrayIndexMapping, indexForUndefinedReferencesBool) ;separator="\n";empty%> + <%vars.boolAlgVars |> var => scalarVariableXML(var,varToArrayIndexMapping, indexForUndefinedReferencesBool, generateFMUModelDescription) ;separator="\n";empty%> + <%vars.boolParamVars |> var => scalarVariableXML(var,varToArrayIndexMapping, indexForUndefinedReferencesBool, generateFMUModelDescription) ;separator="\n";empty%> + <%vars.boolAliasVars |> var => scalarVariableXML(var,varToArrayIndexMapping, indexForUndefinedReferencesBool, generateFMUModelDescription) ;separator="\n";empty%> >> /* <%vars.stringAlgVars |> var hasindex i0 => ScalarVariable(var,i0,"sAlg") ;separator="\n";empty%> @@ -58,31 +80,46 @@ template modelVariablesXML(ModelInfo modelInfo, HashTableCrIListArray.HashTable */ end modelVariablesXML; -template scalarVariableXML(SimVar simVar, HashTableCrIListArray.HashTable varToArrayIndexMapping, String indexForUndefinedReferences) +template scalarVariableXML(SimVar simVar, HashTableCrIListArray.HashTable varToArrayIndexMapping, String indexForUndefinedReferences, Boolean generateFMUModelDescription) "Generates code for ScalarVariable file for FMU target." ::= match simVar case SIMVAR(__) then + let variableCode = if generateFMUModelDescription then CodegenFMUCommon.ScalarVariableType(simVar) else + ScalarVariableType(unit, displayUnit, minValue, maxValue, initialValue, nominalValue, isFixed, type_) << - > - <%ScalarVariableType(unit, displayUnit, minValue, maxValue, initialValue, nominalValue, isFixed, type_)%> + > + <%variableCode%> >> end scalarVariableXML; -template scalarVariableAttributeXML(SimVar simVar, HashTableCrIListArray.HashTable varToArrayIndexMapping, String indexForUndefinedReferences) +template scalarVariableAttributeXML(SimVar simVar, HashTableCrIListArray.HashTable varToArrayIndexMapping, String indexForUndefinedReferences, Boolean generateFMUModelDescription) "Generates code for ScalarVariable Attribute file for FMU target." ::= match simVar case SIMVAR(source = SOURCE(info = info)) then - let valueReference = SimCodeUtil.getVarIndexListByMapping(varToArrayIndexMapping,name,indexForUndefinedReferences) + let valueReference = SimCodeUtil.getVarIndexByMapping(varToArrayIndexMapping,name,indexForUndefinedReferences) + let alias = getAliasVar(aliasvar) + let causalityAtt = CodegenFMUCommon.getCausality(causality) let variability = getVariablity(varKind) - let description = if comment then 'description = "<%Util.escapeModelicaStringToXmlString(comment)%>"' + let description = if comment then 'description="<%Util.escapeModelicaStringToXmlString(comment)%>"' + let additionalAttributes = if generateFMUModelDescription then '' else 'isProtected="<%isProtected%>' << - name = "<%Util.escapeModelicaStringToXmlString(crefStrNoUnderscore(name))%>" valueReference = "<%valueReference%>" <%description%> variability = "<%variability%>" isProtected = "<%isProtected%>" + name="<%Util.escapeModelicaStringToXmlString(crefStrNoUnderscore(name))%>" valueReference="<%valueReference%>" <%description%> variability="<%variability%>" causality="<%causalityAtt%>" alias="<%alias%>" <%additionalAttributes%> >> end scalarVariableAttributeXML; +template getAliasVar(AliasVariable aliasvar) + "Returns the alias Attribute of ScalarVariable." + ::= + match aliasvar + case NOALIAS(__) then "noAlias" + case ALIAS(__) then "alias" + case NEGATEDALIAS(__) then "negatedAlias" + else "noAlias" +end getAliasVar; + template algLoopXML(SimEqSystem eqs, SimCode simCode, HashTableCrIListArray.HashTable varToArrayIndexMapping, String indexForUndefinedReferences) ::= << diff --git a/Compiler/Template/CodegenFMUCppHpcom.tpl b/Compiler/Template/CodegenFMUCppHpcom.tpl new file mode 100644 index 00000000000..93b433ba862 --- /dev/null +++ b/Compiler/Template/CodegenFMUCppHpcom.tpl @@ -0,0 +1,109 @@ +// This file defines templates for transforming Modelica/MetaModelica code to FMU +// code. They are used in the code generator phase of the compiler to write +// target code. +// +// There are one root template intended to be called from the code generator: +// translateModel. These template do not return any +// result but instead write the result to files. All other templates return +// text and are used by the root templates (most of them indirectly). +// +// To future maintainers of this file: +// +// - A line like this +// # var = "" /*BUFD*/ +// declares a text buffer that you can later append text to. It can also be +// passed to other templates that in turn can append text to it. In the new +// version of Susan it should be written like this instead: +// let &var = buffer "" +// +// - A line like this +// ..., Text var /*BUFP*/, ... +// declares that a template takes a text buffer as input parameter. In the +// new version of Susan it should be written like this instead: +// ..., Text &var, ... +// +// - A line like this: +// ..., var /*BUFC*/, ... +// passes a text buffer to a template. In the new version of Susan it should +// be written like this instead: +// ..., &var, ... +// +// - Style guidelines: +// +// - Try (hard) to limit each row to 80 characters +// +// - Code for a template should be indented with 2 spaces +// +// - Exception to this rule is if you have only a single case, then that +// single case can be written using no indentation +// +// This single case can be seen as a clarification of the input to the +// template +// +// - Code after a case should be indented with 2 spaces if not written on the +// same line + +package CodegenFMUCppHpcom + + + +import interface SimCodeBackendTV; +import interface SimCodeTV; +import CodegenFMUCpp.*; +import CodegenCppHpcom.*; +import CodegenUtil; +import CodegenCpp; +import CodegenCppInit; + +template translateModel(SimCode simCode, String FMUVersion, String FMUType) + "Generates C++ code and Makefile for compiling an FMU of a Modelica model. + Calls CodegenCpp.translateModel for the actual model code." +::= + match simCode + case SIMCODE(modelInfo = MODELINFO(__), makefileParams = MAKEFILE_PARAMS(__), hpcomData = HPCOMDATA(__)) then + let guid = getUUIDStr() + let target = simulationCodeTarget() + let stateDerVectorName = "__zDot" + let &extraFuncs = buffer "" /*BUFD*/ + let &extraFuncsDecl = buffer "" /*BUFD*/ + + let className = CodegenCpp.lastIdentOfPath(modelInfo.name) + let numRealVars = numRealvarsHpcom(modelInfo, hpcomData.hpcOmMemory) + let numIntVars = numIntvarsHpcom(modelInfo, hpcomData.hpcOmMemory) + let numBoolVars = numBoolvarsHpcom(modelInfo, hpcomData.hpcOmMemory) + let numPreVars = numPreVarsHpcom(modelInfo, hpcomData.hpcOmMemory) + + let()= textFile(CodegenCppInit.modelInitXMLFile(simCode, numRealVars, numIntVars, numBoolVars, FMUVersion, FMUType, guid, true, "hpcom cpp-runtime"), 'modelDescription.xml') + let cpp = CodegenCpp.translateModel(simCode) + let()= textFile(fmuWriteOutputHeaderFile(simCode , &extraFuncs , &extraFuncsDecl, ""),'OMCpp<%fileNamePrefix%>WriteOutput.h') + let()= textFile(fmuModelHeaderFile(simCode, extraFuncs, extraFuncsDecl, "",guid, FMUVersion), 'OMCpp<%fileNamePrefix%>FMU.h') + let()= textFile(fmuModelCppFile(simCode, extraFuncs, extraFuncsDecl, "",guid, FMUVersion), 'OMCpp<%fileNamePrefix%>FMU.cpp') + //let()= textFile(modelInitXMLFile(simCode, numRealVars, numIntVars, numBoolVars, true, FMUVersion, FMUType, guid), '') + // Def file is only used on windows, to define exported symbols + //let()= textFile(fmudeffile(simCode, FMUVersion), '<%fileNamePrefix%>.def') + let()= textFile(fmuMakefile(target,simCode, extraFuncs, extraFuncsDecl, "", FMUVersion), '<%fileNamePrefix%>_FMU.makefile') + let()= textFile(fmuCalcHelperMainfile(simCode), 'OMCpp<%fileNamePrefix%>CalcHelperMain.cpp') + + let() = textFile(CodegenCpp.simulationCppFile(simCode, contextOther, updateHpcom(allEquations, whenClauses, simCode, &extraFuncs, &extraFuncsDecl, "", contextOther, stateDerVectorName, false), + '<%numRealVars%>-1', '<%numIntVars%>-1', '<%numBoolVars%>-1', &extraFuncs, &extraFuncsDecl, className, + additionalHpcomConstructorDefinitions(hpcomData.schedules), + additionalHpcomConstructorBodyStatements(hpcomData.schedules, className, CodegenUtil.dotPath(modelInfo.name)), + additionalHpcomDestructorBodyStatements(hpcomData.schedules), + stateDerVectorName, false), 'OMCpp<%fileNamePrefix%>.cpp') + + let() = textFile(CodegenCpp.simulationHeaderFile(simCode ,contextOther, &extraFuncs, &extraFuncsDecl, "", + additionalHpcomIncludes(simCode, &extraFuncs, &extraFuncsDecl, className, false), + "", + additionalHpcomProtectedMemberDeclaration(simCode, &extraFuncs, &extraFuncsDecl, "", false), + CodegenCpp.memberVariableDefine(modelInfo, varToArrayIndexMapping, '<%numRealVars%>-1', '<%numIntVars%>-1', '<%numBoolVars%>-1', Flags.isSet(Flags.GEN_DEBUG_SYMBOLS), false), + CodegenCpp.memberVariableDefinePreVariables(modelInfo, varToArrayIndexMapping, '<%numRealVars%>-1', '<%numIntVars%>-1', '<%numBoolVars%>-1', Flags.isSet(Flags.GEN_DEBUG_SYMBOLS), false), false), + 'OMCpp<%fileNamePrefix%>.h') + "" + // empty result of the top-level template .., only side effects + end match +end translateModel; + +annotation(__OpenModelica_Interface="backend"); +end CodegenFMUCppHpcom; + +// vim: filetype=susan sw=2 sts=2 \ No newline at end of file diff --git a/Compiler/Template/ExpressionDumpTV.mo b/Compiler/Template/ExpressionDumpTV.mo index 0b021de8cdb..b5b3bb518a5 100644 --- a/Compiler/Template/ExpressionDumpTV.mo +++ b/Compiler/Template/ExpressionDumpTV.mo @@ -349,6 +349,12 @@ package DAE Type ty; end TSUB; + record RSUB + Exp exp; + String fieldName; + Type ty; + end RSUB; + record SIZE Exp exp; Option sz; diff --git a/Compiler/Template/ExpressionDumpTpl.tpl b/Compiler/Template/ExpressionDumpTpl.tpl index a40d99a324e..ea1c8a2e930 100644 --- a/Compiler/Template/ExpressionDumpTpl.tpl +++ b/Compiler/Template/ExpressionDumpTpl.tpl @@ -92,6 +92,12 @@ match exp let rparen = if needs_paren then ")" let exp_str = dumpExp(exp, stringDelimiter) '<%lparen%><%exp_str%><%rparen%>[<%ix%>]' + case RSUB(__) then + let needs_paren = parenthesizeSubExp(exp) + let lparen = if needs_paren then "(" + let rparen = if needs_paren then ")" + let exp_str = dumpExp(exp, stringDelimiter) + '<%if typeinfo() then '/*RSUB: <%unparseType(ty)%>*/'%><%lparen%><%exp_str%><%rparen%>.<%fieldName%>' case SIZE(__) then let exp_str = dumpExp(exp, stringDelimiter) let dim_str = match sz case SOME(dim) then ', <%dumpExp(dim, stringDelimiter)%>' diff --git a/Compiler/Template/Makefile.common b/Compiler/Template/Makefile.common index cd07f0dd911..c8015fb593d 100644 --- a/Compiler/Template/Makefile.common +++ b/Compiler/Template/Makefile.common @@ -1,6 +1,6 @@ .PHONY : all -GENERATED_FILES=AbsynDumpTpl.mo CodegenUtil.mo CodegenC.mo CodegenCFunctions.mo CodegenFMUCommon.mo CodegenFMU.mo CodegenFMU1.mo CodegenFMU2.mo CodegenCSharp.mo CodegenQSS.mo CodegenCpp.mo CodegenCppHpcom.mo CodegenFMUCpp.mo CodegenCppInit.mo CodegenModelica.mo DAEDumpTpl.mo ExpressionDumpTpl.mo GraphvizDump.mo GraphMLDumpTpl.mo NFInstDumpTpl.mo SimCodeDump.mo Unparsing.mo SCodeDumpTpl.mo CodegenAdevs.mo CodegenSparseFMI.mo CodegenXML.mo CodegenJava.mo CodegenJS.mo TplCodegen.mo TaskSystemDump.mo GenerateAPIFunctionsTpl.mo VisualXMLTpl.mo +GENERATED_FILES=AbsynDumpTpl.mo CodegenUtil.mo CodegenC.mo CodegenCFunctions.mo CodegenFMUCommon.mo CodegenFMU.mo CodegenFMU1.mo CodegenFMU2.mo CodegenCSharp.mo CodegenQSS.mo CodegenCpp.mo CodegenCppHpcom.mo CodegenFMUCpp.mo CodegenFMUCppHpcom.mo CodegenCppInit.mo CodegenModelica.mo DAEDumpTpl.mo ExpressionDumpTpl.mo GraphvizDump.mo GraphMLDumpTpl.mo NFInstDumpTpl.mo SimCodeDump.mo Unparsing.mo SCodeDumpTpl.mo CodegenAdevs.mo CodegenSparseFMI.mo CodegenXML.mo CodegenJava.mo CodegenJS.mo TplCodegen.mo TaskSystemDump.mo GenerateAPIFunctionsTpl.mo VisualXMLTpl.mo all : $(GENERATED_FILES) @@ -56,6 +56,14 @@ CodegenFMU2.mo : CodegenFMU2.tpl CodegenFMUCommon.tpl CodegenFMUCommon.mo SimCod @echo " ** CodegenFMU2 template compilation ** " $(OMC) $< > $@.log || (cat $@.log && false) @echo " " +CodegenFMUCpp.mo : CodegenFMUCpp.tpl SimCodeTV.mo SimCodeBackendTV.mo CodegenC.tpl CodegenUtil.tpl CodegenCpp.tpl CodegenFMU.tpl + @echo " ** CodegenFMUCpp template compilation ** " + $(OMC) $< > $@.log || (cat $@.log && false) + @echo " " +CodegenFMUCppHpcom.mo : CodegenFMUCppHpcom.tpl CodegenFMUCpp.tpl SimCodeTV.mo SimCodeBackendTV.mo CodegenCppHpcom.tpl CodegenUtil.tpl CodegenCpp.tpl CodegenFMU.tpl + @echo " ** CodegenFMUCppHpcom template compilation ** " + $(OMC) $< > $@.log || (cat $@.log && false) + @echo " " CodegenModelica.mo : CodegenModelica.tpl @echo " ** CodegenModelica template compilation ** " @@ -97,12 +105,7 @@ CodegenCppHpcom.mo : CodegenCppHpcom.tpl SimCodeTV.mo SimCodeBackendTV.mo Codege $(OMC) $< > $@.log || (cat $@.log && false) @echo " " -CodegenFMUCpp.mo : CodegenFMUCpp.tpl SimCodeTV.mo SimCodeBackendTV.mo CodegenC.tpl CodegenUtil.tpl CodegenCpp.tpl CodegenFMU.tpl - @echo " ** CodegenFMUCpp template compilation ** " - $(OMC) $< > $@.log || (cat $@.log && false) - @echo " " - -CodegenCppInit.mo : CodegenCppInit.tpl SimCodeTV.mo CodegenUtil.tpl +CodegenCppInit.mo : CodegenCppInit.tpl SimCodeTV.mo SimCodeBackendTV.mo CodegenUtil.tpl CodegenFMUCommon.tpl @echo " ** CodegenCppInit template compilation ** " $(OMC) $< > $@.log || (cat $@.log && false) @echo " " diff --git a/Compiler/Template/SimCodeTV.mo b/Compiler/Template/SimCodeTV.mo index a919f777608..7431c7afee8 100644 --- a/Compiler/Template/SimCodeTV.mo +++ b/Compiler/Template/SimCodeTV.mo @@ -813,6 +813,13 @@ package SimCodeUtil output list oVarIndexList; end getVarIndexListByMapping; + function getVarIndexByMapping + input HashTableCrIListArray.HashTable iVarToArrayIndexMapping; + input DAE.ComponentRef iVarName; + input String iIndexForUndefinedReferences; + output String oVarIndex; + end getVarIndexByMapping; + function isVarIndexListConsecutive input HashTableCrIListArray.HashTable iVarToArrayIndexMapping; input DAE.ComponentRef iVarName; @@ -1364,6 +1371,12 @@ package DAE Integer ix; Type ty; end TSUB; + record RSUB + Exp exp; + Integer ix; + String fieldName; + Type ty; + end RSUB; record SIZE Exp exp; Option sz; @@ -1873,7 +1886,6 @@ package DAE record T_METAUNIONTYPE "MetaModelica Uniontype, added by simbj" list paths; Boolean knownSingleton "The runtime system (dynload), does not know if the value is a singleton. But optimizations are safe if this is true."; - list singletonFields "The field names of the singleton"; TypeSource source; end T_METAUNIONTYPE; @@ -3189,6 +3201,10 @@ package Types input DAE.Type ty; output Boolean b; end isArrayWithUnknownDimension; + function getMetaRecordFields + input DAE.Type ty; + output list fields; + end getMetaRecordFields; end Types; package HashTableCrIListArray diff --git a/Compiler/Util/List.mo b/Compiler/Util/List.mo index 512ac0daf9f..b6c17391f60 100644 --- a/Compiler/Util/List.mo +++ b/Compiler/Util/List.mo @@ -4667,9 +4667,9 @@ algorithm if valueEq(e, inElement) then return; end if; - outPosition := outPosition + 1; end for; + fail(); end position; public function positionOnTrue diff --git a/Compiler/boot/LoadCompilerSources.mos b/Compiler/boot/LoadCompilerSources.mos index 0d6238bad3b..9a084f080cc 100644 --- a/Compiler/boot/LoadCompilerSources.mos +++ b/Compiler/boot/LoadCompilerSources.mos @@ -299,6 +299,7 @@ if true then /* Suppress output */ "../Template/CodegenFMU2.mo", "../Template/CodegenFMUCommon.mo", "../Template/CodegenFMUCpp.mo", + "../Template/CodegenFMUCppHpcom.mo", "../Template/CodegenJava.mo", "../Template/CodegenJS.mo", "../Template/CodegenModelica.mo", diff --git a/SimulationRuntime/cpp/Core/SimController/SimController.cpp b/SimulationRuntime/cpp/Core/SimController/SimController.cpp index 24e0132dc07..58142c90750 100644 --- a/SimulationRuntime/cpp/Core/SimController/SimController.cpp +++ b/SimulationRuntime/cpp/Core/SimController/SimController.cpp @@ -187,7 +187,6 @@ void SimController::StartVxWorks(SimSettings simsettings,string modelKey) global_settings->setSelectedLinSolver(simsettings.linear_solver_name); global_settings->setSelectedNonLinSolver(simsettings.nonlinear_solver_name); global_settings->setSelectedSolver(simsettings.solver_name); - global_settings->setOutputFormat(simsettings.outputFormat); global_settings->setAlarmTime(simsettings.timeOut); global_settings->setLogSettings(simsettings.logSettings); global_settings->setOutputPointType(simsettings.outputPointType); @@ -240,7 +239,6 @@ void SimController::Start(SimSettings simsettings, string modelKey) global_settings->setSelectedLinSolver(simsettings.linear_solver_name); global_settings->setSelectedNonLinSolver(simsettings.nonlinear_solver_name); global_settings->setSelectedSolver(simsettings.solver_name); - global_settings->setOutputFormat(simsettings.outputFormat); global_settings->setLogSettings(simsettings.logSettings); global_settings->setAlarmTime(simsettings.timeOut); global_settings->setOutputPointType(simsettings.outputPointType); @@ -277,29 +275,28 @@ void SimController::Start(SimSettings simsettings, string modelKey) boost::shared_ptr writeoutput_system = boost::dynamic_pointer_cast(mixedsystem); - if((global_settings->getOutputFormat()==OF_BUFFER) && writeoutput_system) + boost::shared_ptr simData = getSimData(modelKey).lock(); + //get history object to query simulation results + IHistory* history = writeoutput_system->getHistory(); + //simulation results (output variables) + ublas::matrix Ro; + //query simulation result otuputs + history->getOutputResults(Ro); + vector output_names; + history->getOutputNames(output_names); + string name; + int j=0; + + BOOST_FOREACH(name,output_names) { - boost::shared_ptr simData = getSimData(modelKey).lock(); - //get history object to query simulation results - IHistory* history = writeoutput_system->getHistory(); - //simulation results (output variables) - ublas::matrix Ro; - //query simulation result otuputs - history->getOutputResults(Ro); - vector output_names; - history->getOutputNames(output_names); - string name; - int j=0; - BOOST_FOREACH(name,output_names) - { - ublas::vector o_j; - o_j = ublas::row(Ro,j); - simData->addOutputResults(name,o_j); - j++; - } - vector time_values = history->getTimeEntries(); - simData->addTimeEntries(time_values); + ublas::vector o_j; + o_j = ublas::row(Ro,j); + simData->addOutputResults(name,o_j); + j++; } + + vector time_values = history->getTimeEntries(); + simData->addTimeEntries(time_values); } catch(ModelicaSimulationError & ex) { diff --git a/SimulationRuntime/cpp/Core/SimulationSettings/GlobalSettings.cpp b/SimulationRuntime/cpp/Core/SimulationSettings/GlobalSettings.cpp index 5bb325f0010..31fe5efcb94 100644 --- a/SimulationRuntime/cpp/Core/SimulationSettings/GlobalSettings.cpp +++ b/SimulationRuntime/cpp/Core/SimulationSettings/GlobalSettings.cpp @@ -19,7 +19,6 @@ GlobalSettings::GlobalSettings() , _selected_nonlin_solver("Newton") , _resultsfile_name("results.csv") , _endless_sim(false) - , _outputFormat(OF_EMPTY) , _outputPointType(OPT_ALL) , _alarm_time(0) { @@ -72,16 +71,6 @@ void GlobalSettings::useEndlessSim(bool endles) _endless_sim = endles; } -OutputFormat GlobalSettings::getOutputFormat() -{ - return _outputFormat; -} - -void GlobalSettings::setOutputFormat(OutputFormat format) -{ - _outputFormat = format; -} - OutputPointType GlobalSettings::getOutputPointType() { return _outputPointType; diff --git a/SimulationRuntime/cpp/Core/Solver/SolverDefaultImplementation.cpp b/SimulationRuntime/cpp/Core/Solver/SolverDefaultImplementation.cpp index 695803281a2..39c0dc2daf7 100644 --- a/SimulationRuntime/cpp/Core/Solver/SolverDefaultImplementation.cpp +++ b/SimulationRuntime/cpp/Core/Solver/SolverDefaultImplementation.cpp @@ -111,7 +111,7 @@ void SolverDefaultImplementation::initialize() timeevent_system->setTime(_tCurrent); - if(_settings->getGlobalSettings()->getOutputPointType() != OPT_EMPTY && _settings->getGlobalSettings()->getOutputFormat() != OF_EMPTY) + if(_settings->getGlobalSettings()->getOutputPointType() != OPT_NONE) writeoutput_system->writeOutput(IWriteOutput::HEAD_LINE); // Allocate array with values of zero functions @@ -192,7 +192,7 @@ void SolverDefaultImplementation::writeToFile(const int& stp, const double& t, c } #endif - if(_settings->getGlobalSettings()->getOutputFormat()!= OF_EMPTY) + if(_settings->getGlobalSettings()->getOutputPointType()!= OPT_NONE) { IWriteOutput* writeoutput_system = dynamic_cast(_system); diff --git a/SimulationRuntime/cpp/Include/Core/SimController/ISimController.h b/SimulationRuntime/cpp/Include/Core/SimController/ISimController.h index 54bba21b02d..94b41cec575 100644 --- a/SimulationRuntime/cpp/Include/Core/SimController/ISimController.h +++ b/SimulationRuntime/cpp/Include/Core/SimController/ISimController.h @@ -16,7 +16,6 @@ struct SimSettings double upper_limit; double tolerance; string outputfile_name; - OutputFormat outputFormat; unsigned int timeOut; OutputPointType outputPointType; LogSettings logSettings; diff --git a/SimulationRuntime/cpp/Include/Core/SimulationSettings/GlobalSettings.h b/SimulationRuntime/cpp/Include/Core/SimulationSettings/GlobalSettings.h index 071e2035c7f..7c3dda87998 100644 --- a/SimulationRuntime/cpp/Include/Core/SimulationSettings/GlobalSettings.h +++ b/SimulationRuntime/cpp/Include/Core/SimulationSettings/GlobalSettings.h @@ -32,8 +32,6 @@ class GlobalSettings : public IGlobalSettings ///path for simulation results in textfile virtual string getOutputPath(); virtual void setOutputPath(string); - virtual OutputFormat getOutputFormat(); - virtual void setOutputFormat(OutputFormat format); virtual OutputPointType getOutputPointType(); virtual void setOutputPointType(OutputPointType); virtual LogSettings getLogSettings(); @@ -71,7 +69,6 @@ class GlobalSettings : public IGlobalSettings _selected_nonlin_solver, _resultsfile_name, _runtimeLibraryPath; - OutputFormat _outputFormat; OutputPointType _outputPointType; LogSettings _log_settings; unsigned int _alarm_time; diff --git a/SimulationRuntime/cpp/Include/Core/SimulationSettings/IGlobalSettings.h b/SimulationRuntime/cpp/Include/Core/SimulationSettings/IGlobalSettings.h index 815a2abf065..0a153fd2395 100644 --- a/SimulationRuntime/cpp/Include/Core/SimulationSettings/IGlobalSettings.h +++ b/SimulationRuntime/cpp/Include/Core/SimulationSettings/IGlobalSettings.h @@ -25,11 +25,10 @@ using std::string; #include -enum OutputFormat {OF_CSV, OF_MAT, OF_BUFFER, OF_EMPTY}; - - enum LogCategory {LC_INIT = 0, LC_NLS = 1, LC_LS = 2, LC_SOLV = 3, LC_OUT = 4, LC_EVT = 5, LC_OTHER = 6, LC_MOD = 7}; enum LogLevel {LL_ERROR = 0, LL_WARNING = 1, LL_INFO = 2, LL_DEBUG = 3}; +enum OutputPointType {OPT_ALL, OPT_STEP, OPT_NONE}; + struct LogSettings { std::vector modes; @@ -46,7 +45,6 @@ struct LogSettings } }; -enum OutputPointType {OPT_ALL, OPT_STEP, OPT_EMPTY}; class IGlobalSettings { public: @@ -63,8 +61,6 @@ class IGlobalSettings ///< Write out results ([false,true]; default: true) virtual bool getResultsOutput() = 0; virtual void setResultsOutput(bool) = 0; - virtual OutputFormat getOutputFormat() = 0; - virtual void setOutputFormat(OutputFormat) = 0; virtual OutputPointType getOutputPointType() = 0; virtual void setOutputPointType(OutputPointType) = 0; virtual LogSettings getLogSettings() = 0; diff --git a/SimulationRuntime/cpp/Include/FMU/FMUGlobalSettings.h b/SimulationRuntime/cpp/Include/FMU/FMUGlobalSettings.h index fbce7a666fd..205565a0b05 100644 --- a/SimulationRuntime/cpp/Include/FMU/FMUGlobalSettings.h +++ b/SimulationRuntime/cpp/Include/FMU/FMUGlobalSettings.h @@ -27,12 +27,10 @@ class FMUGlobalSettings : public IGlobalSettings virtual bool getInfoOutput() { return false; } virtual void setInfoOutput(bool) {} virtual string getOutputPath() { return "./"; } - virtual OutputFormat getOutputFormat(){return OF_EMPTY;} virtual LogSettings getLogSettings() {return LogSettings();} virtual void setLogSettings(LogSettings) {} virtual OutputPointType getOutputPointType() { return OPT_ALL; }; virtual void setOutputPointType(OutputPointType) {}; - virtual void setOutputFormat(OutputFormat) {} virtual void setOutputPath(string) {} virtual string getSelectedSolver() { return "euler"; } virtual void setSelectedSolver(string) {} diff --git a/SimulationRuntime/cpp/Include/FMU2/FMU2GlobalSettings.h b/SimulationRuntime/cpp/Include/FMU2/FMU2GlobalSettings.h index ef6d7f84d4e..dd581fc2347 100644 --- a/SimulationRuntime/cpp/Include/FMU2/FMU2GlobalSettings.h +++ b/SimulationRuntime/cpp/Include/FMU2/FMU2GlobalSettings.h @@ -63,12 +63,10 @@ class FMU2GlobalSettings : public IGlobalSettings virtual bool getInfoOutput() { return false; } virtual void setInfoOutput(bool) {} virtual string getOutputPath() { return "./"; } - virtual OutputFormat getOutputFormat() { return OF_EMPTY; } virtual LogSettings getLogSettings() { return LogSettings(); } virtual void setLogSettings(LogSettings) {} virtual OutputPointType getOutputPointType() { return OPT_ALL; }; virtual void setOutputPointType(OutputPointType) {}; - virtual void setOutputFormat(OutputFormat) {} virtual void setOutputPath(string) {} virtual string getSelectedSolver() { return "euler"; } virtual void setSelectedSolver(string) {} diff --git a/SimulationRuntime/cpp/SimCoreFactory/OMCFactory/OMCFactory.cpp b/SimulationRuntime/cpp/SimCoreFactory/OMCFactory/OMCFactory.cpp index 925e918e2b6..75329880305 100644 --- a/SimulationRuntime/cpp/SimCoreFactory/OMCFactory/OMCFactory.cpp +++ b/SimulationRuntime/cpp/SimCoreFactory/OMCFactory/OMCFactory.cpp @@ -55,28 +55,26 @@ SimSettings OMCFactory::readSimulationParameter(int argc, const char* argv[]) { int opt; int portnum; - std::map outputFormatMap = map_list_of("csv", OF_CSV)("mat", OF_MAT)("buffer", OF_BUFFER)("empty", OF_EMPTY); - std::map logCatMap = map_list_of("init", LC_INIT)("nls", LC_NLS)("ls",LC_LS)("solv", LC_SOLV)("output", LC_OUT)("event",LC_EVT)("modell",LC_MOD)("other",LC_OTHER); + std::map logCatMap = map_list_of("init", LC_INIT)("nls", LC_NLS)("ls",LC_LS)("solv", LC_SOLV)("output", LC_OUT)("event",LC_EVT)("model",LC_MOD)("other",LC_OTHER); std::map logLvlMap = map_list_of("error", LL_ERROR)("warning", LL_WARNING)("info", LL_INFO)("debug", LL_DEBUG); - std::map outputPointTypeMap = map_list_of("all", OPT_ALL)("step", OPT_STEP)("empty", OPT_EMPTY); + std::map outputPointTypeMap = map_list_of("all", OPT_ALL)("step", OPT_STEP)("none", OPT_NONE); po::options_description desc("Allowed options"); desc.add_options() ("help", "produce help message") - ("emit_protected", "emits protected variables to the result file") + //("emit_protected", "emits protected variables to the result file") ("runtime-library,r", po::value(),"path to cpp runtime libraries") ("Modelica-system-library,m", po::value(), "path to Modelica library") ("results-file,R", po::value(),"name of results file") - ("config-path,c", po::value< string >(), "path to xml files") + //("config-path,c", po::value< string >(), "path to xml files") ("start-time,s", po::value< double >()->default_value(0.0), "simulation start time") ("stop-time,e", po::value< double >()->default_value(1.0), "simulation stop time") ("step-size,f", po::value< double >()->default_value(0.0), "simulation step size") ("solver,i", po::value< string >()->default_value("euler"), "solver method") ("lin-solver,L", po::value< string >()->default_value(_defaultLinSolver), "linear solver method") ("non-lin-solver,N", po::value< string >()->default_value(_defaultNonLinSolver), "non linear solver method") - ("OutputFormat,o", po::value< string >()->default_value("csv"), "output Format [csv,mat,empty]") ("number-of-intervals,v", po::value< int >()->default_value(500), "number of intervals") ("tolerance,y", po::value< double >()->default_value(1e-6), "solver tolerance") - ("log-settings,l", po::value< std::vector >(), "log information: init, nls, ls, solv, output, event, modell, other") + ("log-settings,l", po::value< std::vector >(), "log information: init, nls, ls, solv, output, event, model, other") ("alarm,a", po::value()->default_value(360), "sets timeout in seconds for simulation") ("output-type,O", po::value< string >()->default_value("all"), "the points in time written to result file: all (output steps + events), step (just output points), none") ("OMEdit", po::value >(), "OMEdit options") @@ -107,9 +105,11 @@ SimSettings OMCFactory::readSimulationParameter(int argc, const char* argv[]) string modelica_lib_path; double starttime = vm["start-time"].as(); double stoptime = vm["stop-time"].as(); - double stepsize =vm["step-size"].as(); - if (!(stepsize > 0.0)) - stepsize = stoptime/vm["number-of-intervals"].as(); + double stepsize =vm["step-size"].as(); + + if (!(stepsize > 0.0)) + stepsize = stoptime/vm["number-of-intervals"].as(); + double tolerance =vm["tolerance"].as(); string solver = vm["solver"].as(); string nonLinSolver = vm["non-lin-solver"].as(); @@ -150,23 +150,6 @@ SimSettings OMCFactory::readSimulationParameter(int argc, const char* argv[]) throw ModelicaSimulationError(MODEL_FACTORY,"results-filename is not set"); } - string outputFormat_str; - OutputFormat outputFomat; - if (vm.count("OutputFormat")) - { - //cout << "results file: " << vm["results-file"].as() << std::endl; - outputFormat_str = vm["OutputFormat"].as(); - outputFomat = outputFormatMap[outputFormat_str]; - if(!((outputFomat==OF_CSV) || (outputFomat==OF_EMPTY) || (outputFomat==OF_BUFFER) || (outputFomat==OF_MAT))) - { - std::string eception_msg = "The output format is not supported yet. Please use outputFormat=\"csv\" or outputFormat=\"empty\" or outputFormat=\"matlab\"in simulate command "; - throw ModelicaSimulationError(MODEL_FACTORY,eception_msg.c_str()); - } - } - else - { - throw ModelicaSimulationError(MODEL_FACTORY,"results-filename is not set"); - } string outputPointType_str; OutputPointType outputPointType; @@ -207,13 +190,6 @@ SimSettings OMCFactory::readSimulationParameter(int argc, const char* argv[]) } - /*fs::path results_file_path = fs::path( resultsfilename) ; - if(!(results_file_path.extension().string() == ".csv")) - { - std::string eception_msg = "The output format is not supported yet. Please use outputFormat=\"csv\" in simulate command "; - throw ModelicaSimulationError(MODEL_FACTORY,eception_msg.c_str(); - - }*/ fs::path libraries_path = fs::path( runtime_lib_path) ; fs::path modelica_path = fs::path( modelica_lib_path) ; @@ -223,7 +199,7 @@ SimSettings OMCFactory::readSimulationParameter(int argc, const char* argv[]) - SimSettings settings = {solver,linSolver,nonLinSolver,starttime,stoptime,stepsize,1e-24,0.01,tolerance,resultsfilename,outputFomat,time_out,outputPointType,logSet}; + SimSettings settings = {solver,linSolver,nonLinSolver,starttime,stoptime,stepsize,1e-24,0.01,tolerance,resultsfilename,time_out,outputPointType,logSet}; _library_path = libraries_path; @@ -247,7 +223,7 @@ std::vector OMCFactory::modifyArguments(int argc, const char* argv else if (strncmp(argv[i], "-override=", 10) == 0) { std::map supported = map_list_of ("startTime", "-s")("stopTime", "-e")("stepSize", "-f") - ("tolerance", "-y")("solver", "-i")("outputFormat", "-o"); + ("tolerance", "-y")("solver", "-i"); std::vector strs; boost::split(strs, argv[i], boost::is_any_of(",=")); for (int j = 1; j < strs.size(); j++) { diff --git a/SimulationRuntime/cpp/Solver/CVode/CVode.cpp b/SimulationRuntime/cpp/Solver/CVode/CVode.cpp index 0f58e15cda1..e492c63850f 100644 --- a/SimulationRuntime/cpp/Solver/CVode/CVode.cpp +++ b/SimulationRuntime/cpp/Solver/CVode/CVode.cpp @@ -315,7 +315,7 @@ void Cvode::initialize() void Cvode::solve(const SOLVERCALL action) { bool writeEventOutput = (_settings->getGlobalSettings()->getOutputPointType() == OPT_ALL); - bool writeOutput = !(_settings->getGlobalSettings()->getOutputFormat() == OF_EMPTY) && !(_settings->getGlobalSettings()->getOutputPointType() == OPT_EMPTY); + bool writeOutput = !(_settings->getGlobalSettings()->getOutputPointType() == OPT_NONE); #ifdef RUNTIME_PROFILING MEASURETIME_REGION_DEFINE(cvodeSolveFunctionHandler, "solve"); @@ -455,7 +455,7 @@ void Cvode::CVodeCore() throw ModelicaSimulationError(SOLVER,"CVode::ReInit"); bool writeEventOutput = (_settings->getGlobalSettings()->getOutputPointType() == OPT_ALL); - bool writeOutput = !(_settings->getGlobalSettings()->getOutputFormat() == OF_EMPTY) && !(_settings->getGlobalSettings()->getOutputPointType() == OPT_EMPTY); + bool writeOutput = !(_settings->getGlobalSettings()->getOutputPointType() == OPT_NONE); while (_solverStatus & ISolver::CONTINUE && !_interrupt ) { diff --git a/SimulationRuntime/cpp/Solver/IDA/IDA.cpp b/SimulationRuntime/cpp/Solver/IDA/IDA.cpp index 1e30735117e..01dcc5e8c0b 100644 --- a/SimulationRuntime/cpp/Solver/IDA/IDA.cpp +++ b/SimulationRuntime/cpp/Solver/IDA/IDA.cpp @@ -283,7 +283,7 @@ void Ida::initialize() void Ida::solve(const SOLVERCALL action) { bool writeEventOutput = (_settings->getGlobalSettings()->getOutputPointType() == OPT_ALL); - bool writeOutput = !(_settings->getGlobalSettings()->getOutputFormat() == OF_EMPTY) && !(_settings->getGlobalSettings()->getOutputPointType() == OPT_EMPTY); + bool writeOutput = !(_settings->getGlobalSettings()->getOutputPointType() == OPT_NONE); #ifdef RUNTIME_PROFILING MEASURETIME_REGION_DEFINE(idaSolveFunctionHandler, "solve"); @@ -423,7 +423,7 @@ void Ida::IDACore() throw std::runtime_error("IDA::ReInit"); bool writeEventOutput = (_settings->getGlobalSettings()->getOutputPointType() == OPT_ALL); - bool writeOutput = !(_settings->getGlobalSettings()->getOutputFormat() == OF_EMPTY) && !(_settings->getGlobalSettings()->getOutputPointType() == OPT_EMPTY); + bool writeOutput = !(_settings->getGlobalSettings()->getOutputPointType() == OPT_NONE); while (_solverStatus & ISolver::CONTINUE && !_interrupt ) {