Skip to content

Commit

Permalink
Compiler/BackEnd/Initialization.mo
Browse files Browse the repository at this point in the history
  - fix for when-statements in algorithm sections
  - remove flag TRACE_INITIAL_SYSTEM
  - remove function analyzeInitialSystem1 (fix discrete vars to get rid of unneeded pre-vars)
  - fix under-determined systems with zero initial equations
SimulationRuntime/c/simulation/solver/initialization/initialization.c
  - fix initialization of ringbuffer
SimulationRuntime/c/
  - some improvements for the readability of LOG_EVENT, LOG_SOLVER, LOG_DDASRT, ...
  - some minor formatting changes
testsuite/simulation/modelica/algorithms-functions
  - adjust expected output to new initialization (symbolic)


git-svn-id: https://openmodelica.org/svn/OpenModelica/trunk@14329 f25d12d1-65f4-0310-ae8a-bbce733d8d8e
  • Loading branch information
lochel committed Dec 11, 2012
1 parent 7f13b68 commit c0a91aa
Show file tree
Hide file tree
Showing 71 changed files with 3,330 additions and 3,358 deletions.
39 changes: 19 additions & 20 deletions Compiler/BackEnd/BackendDAE.mo
Original file line number Diff line number Diff line change
Expand Up @@ -265,27 +265,26 @@ end BackendDAE;

uniontype Shared "Data shared for all equation-systems"
record SHARED
Variables knownVars "knownVars ; Known variables, i.e. constants and parameters" ;
Variables externalObjects "External object variables";
Variables aliasVars "Data originating from removed simple equations needed to build
variables' lookup table (in C output).

In that way, double buffering of variables in pre()-buffer, extrapolation
buffer and results caching, etc., is avoided, but in C-code output all the
data about variables' names, comments, units, etc. is preserved as well as
pinter to their values (trajectories).
";
EquationArray initialEqs "initialEqs ; Initial equations" ;
EquationArray removedEqs "these are equations that cannot solve for a variable. for example assertions, external function calls, algorithm sections without effect" ;
array< .DAE.Constraint> constraints "constraints (Optimica extension)";
Variables knownVars "knownVars ; Known variables, i.e. constants and parameters" ;
Variables externalObjects "External object variables";
Variables aliasVars "Data originating from removed simple equations needed to build
variables' lookup table (in C output).

In that way, double buffering of variables in pre()-buffer, extrapolation
buffer and results caching, etc., is avoided, but in C-code output all the
data about variables' names, comments, units, etc. is preserved as well as
pinter to their values (trajectories).";
EquationArray initialEqs "initialEqs ; Initial equations" ;
EquationArray removedEqs "these are equations that cannot solve for a variable. for example assertions, external function calls, algorithm sections without effect" ;
array< .DAE.Constraint> constraints "constraints (Optimica extension)";
array< .DAE.ClassAttributes> classAttrs "class attributes (Optimica extension)";
.Env.Cache cache;
.Env.Env env;
.DAE.FunctionTree functionTree "functions for Backend";
EventInfo eventInfo "eventInfo" ;
ExternalObjectClasses extObjClasses "classes of external objects, contains constructor & destructor";
BackendDAEType backendDAEType "indicate for what the BackendDAE is used";
SymbolicJacobians symjacs "Symbolic Jacobians";
Env.Cache cache;
Env.Env env;
.DAE.FunctionTree functionTree "functions for Backend";
EventInfo eventInfo "eventInfo" ;
ExternalObjectClasses extObjClasses "classes of external objects, contains constructor & destructor";
BackendDAEType backendDAEType "indicate for what the BackendDAE is used";
SymbolicJacobians symjacs "Symbolic Jacobians";
end SHARED;
end Shared;

Expand Down
24 changes: 21 additions & 3 deletions Compiler/BackEnd/BackendDAECreate.mo
Original file line number Diff line number Diff line change
Expand Up @@ -124,10 +124,28 @@ algorithm
clsattrsarra := listArray(clsAttrs);
einfo := BackendDAE.EVENT_INFO(whenclauses_1, {}, {}, {}, 0, 0);
symjacs := {(NONE(),({},({},{})),{}),(NONE(),({},({},{})),{}),(NONE(),({},({},{})),{}),(NONE(),({},({},{})),{})};
outBackendDAE := BackendDAE.DAE(BackendDAE.EQSYSTEM(vars_1,eqnarr,NONE(),NONE(),BackendDAE.NO_MATCHING())::{},BackendDAE.SHARED(knvars,extVars,aliasVars,ieqnarr,reqnarr,constrarra,clsattrsarra,inCache,inEnv,functionTree,einfo,extObjCls,BackendDAE.SIMULATION(),symjacs));
outBackendDAE := BackendDAE.DAE(BackendDAE.EQSYSTEM(vars_1,
eqnarr,
NONE(),
NONE(),
BackendDAE.NO_MATCHING())::{},
BackendDAE.SHARED(knvars,
extVars,
aliasVars,
ieqnarr,
reqnarr,
constrarra,
clsattrsarra,
inCache,
inEnv,
functionTree,
einfo,
extObjCls,
BackendDAE.SIMULATION(),
symjacs));
BackendDAEUtil.checkBackendDAEWithErrorMsg(outBackendDAE);
Debug.fcall(Flags.DUMP_BACKENDDAE_INFO,print,"No. of Equations: " +& intString(BackendDAEUtil.equationSize(eqnarr)) +& "\nNo. of Variables: " +& intString(BackendVariable.varsSize(vars_1)) +& "\n");
Debug.execStat("generate Backend Data Structure",BackendDAE.RT_CLOCK_EXECSTAT_BACKEND_MODULES);
Debug.fcall(Flags.DUMP_BACKENDDAE_INFO, print, "No. of Equations: " +& intString(BackendDAEUtil.equationSize(eqnarr)) +& "\nNo. of Variables: " +& intString(BackendVariable.varsSize(vars_1)) +& "\n");
Debug.execStat("generate Backend Data Structure", BackendDAE.RT_CLOCK_EXECSTAT_BACKEND_MODULES);
end lower;

protected function lower2
Expand Down
159 changes: 34 additions & 125 deletions Compiler/BackEnd/Initialization.mo
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,9 @@ protected
algorithm
dae := inlineWhenForInitialization(inDAE);

Debug.fcall(Flags.DUMP_INITIAL_SYSTEM, print, "\n##################\n# inlineWhenForInitialization #\n##################\n\n");
Debug.fcall(Flags.DUMP_INITIAL_SYSTEM, BackendDump.dumpBackendDAE, dae);

initVars := selectInitializationVariablesDAE(dae);
Debug.fcall2(Flags.DUMP_INITIAL_SYSTEM, BackendDump.dumpVariables, initVars, "selected initialization variables");

Expand Down Expand Up @@ -212,9 +215,9 @@ algorithm
then stmts;

// inactive when equation during initialization
case DAE.STMT_WHEN(exp=condition, statementLst=stmts, source=source)::rest equation
case ((stmt as (DAE.STMT_WHEN(exp=condition, source=source)))::rest) equation
false = Expression.containsInitialCall(condition, false);
crefLst = CheckModel.algorithmStatementListOutputs(stmts);
crefLst = CheckModel.algorithmStatementListOutputs({stmt});
stmts = List.map1(crefLst, generateInactiveWhenAlgStatementForInitialization, source);
rest = generateInitialWhenAlg(rest);
stmts = listAppend(stmts, rest);
Expand Down Expand Up @@ -388,15 +391,16 @@ algorithm
((vars, fixvars)) = BackendVariable.traverseBackendDAEVars(knvars, collectInitialVars, (vars, fixvars));
((eqns, reeqns)) = BackendEquation.traverseBackendDAEEqns(inieqns, collectInitialEqns, (eqns, reeqns));

Debug.fcall(Flags.TRACE_INITIAL_SYSTEM, print, "\ninitial equations (" +& intString(BackendDAEUtil.equationSize(eqns)) +& ")\n=================\n");
Debug.fcall(Flags.TRACE_INITIAL_SYSTEM, BackendDump.dumpEqnsArray, eqns);
Debug.fcall(Flags.DUMP_INITIAL_SYSTEM, print, "initial equations (" +& intString(BackendDAEUtil.equationSize(eqns)) +& ")\n=================\n");
Debug.fcall(Flags.DUMP_INITIAL_SYSTEM, BackendDump.dumpEqnsArray, eqns);
Debug.fcall(Flags.DUMP_INITIAL_SYSTEM, print, "\n");

((vars, fixvars, eqns, reeqns)) = List.fold(systs, collectInitialVarsEqnsSystem, ((vars, fixvars, eqns, reeqns)));
((eqns, reeqns)) = BackendVariable.traverseBackendDAEVars(vars, collectInitialBindings, (eqns, reeqns));

// collect pre(var) from alias
//((_, vars, fixvars)) = traverseBackendDAEExpsEqns(eqns, collectAliasPreVars, (avars, vars, fixvars));
//((_, vars, fixvars)) = traverseBackendDAEExpsEqns(reeqns, collectAliasPreVars, (avars, vars, fixvars));
// ((_, vars, fixvars)) = traverseBackendDAEExpsEqns(eqns, collectAliasPreVars, (avars, vars, fixvars));
// ((_, vars, fixvars)) = traverseBackendDAEExpsEqns(reeqns, collectAliasPreVars, (avars, vars, fixvars));

// generate initial system
initsyst = BackendDAE.EQSYSTEM(vars, eqns, NONE(), NONE(), BackendDAE.NO_MATCHING());
Expand Down Expand Up @@ -461,8 +465,7 @@ algorithm
nEqns = BackendDAEUtil.equationSize(eqns);
true = intGt(nEqns, nVars);

Debug.fcall(Flags.PEDANTIC, Error.addCompilerWarning, "It was not possible to solve the over-determined initial system (" +& intString(nEqns) +& " equations and " +& intString(nVars) +& " variables)");
Debug.fcall(Flags.TRACE_INITIAL_SYSTEM, print, "\nover-determined initial system (" +& intString(nEqns) +& " equations and " +& intString(nVars) +& " variables)\n");
Debug.fcall(Flags.PEDANTIC, Error.addCompilerWarning, "It was not possible to solve the over-determined initial system (" +& intString(nEqns) +& " equations and " +& intString(nVars) +& " variables)");
then fail();

// equal
Expand Down Expand Up @@ -491,8 +494,7 @@ algorithm
nEqns = BackendDAEUtil.equationSize(inEqns);
true = intLt(nEqns, nVars);

Debug.fcall(Flags.PEDANTIC, Error.addCompilerWarning, "It was not possible to solve the under-determined initial system (" +& intString(nEqns) +& " equations and " +& intString(nVars) +& " variables)");
Debug.fcall(Flags.TRACE_INITIAL_SYSTEM, print, "\nunder-determined initial system (" +& intString(nEqns) +& " equations and " +& intString(nVars) +& " variables)\n");
Debug.fcall(Flags.PEDANTIC, Error.addCompilerWarning, "It was not possible to solve the under-determined initial system (" +& intString(nEqns) +& " equations and " +& intString(nVars) +& " variables)");
then fail();
end matchcontinue;
end solveInitialSystem2;
Expand All @@ -508,91 +510,11 @@ protected
BackendDAE.EqSystem system;
BackendDAE.IncidenceMatrix m, mt;
algorithm
(system, m, mt) := BackendDAEUtil.getIncidenceMatrix(inSystem, BackendDAE.NORMAL());
// system := analyzeInitialSystem1(system, mt, 1); // fix discrete vars to get rid of unneeded pre-vars
(system, m, mt) := BackendDAEUtil.getIncidenceMatrix(inSystem, BackendDAE.NORMAL());
system := analyzeInitialSystem2(system, inDAE, inInitVars); // fix unbalanced initial system if it is definite
(outSystem, _, _) := BackendDAEUtil.getIncidenceMatrix(system, BackendDAE.NORMAL());
end analyzeInitialSystem;

protected function analyzeInitialSystem1 "protected function analyzeInitialSystem1
author: lochel"
input BackendDAE.EqSystem inSystem;
input BackendDAE.IncidenceMatrix inMT; // IncidenceMatrix = array<list<IncidenceMatrixElementEntry>>;
input Integer inI; // current row (var-index)
output BackendDAE.EqSystem outSystem;
algorithm
outSystem := matchcontinue(inSystem, inMT, inI)
local
BackendDAE.EqSystem system;
Integer nVars;
Integer nIncidences;
BackendDAE.Variables vars;
BackendDAE.Var var;
DAE.ComponentRef cr, preCR;
BackendDAE.EquationArray orderedEqs "orderedEqs ; ordered Equations" ;

BackendDAE.Equation eqn;
DAE.Exp startExp, preExp;
DAE.Type tp;
String crStr;

case (BackendDAE.EQSYSTEM(orderedVars=vars, orderedEqs=orderedEqs), _, _) equation
nVars = arrayLength(inMT);
true = intGt(inI, nVars);
then inSystem;

case (_, _, _) equation
nIncidences = listLength(inMT[inI]);
true = intGt(nIncidences, 0);

system = analyzeInitialSystem1(inSystem, inMT, inI+1);
then system;

case (BackendDAE.EQSYSTEM(orderedVars=vars, orderedEqs=orderedEqs), _, _) equation
nIncidences = listLength(inMT[inI]);
true = intEq(nIncidences, 0);

var = BackendVariable.getVarAt(vars, inI);
preCR = BackendVariable.varCref(var);
true = ComponentReference.isPreCref(preCR);
cr = ComponentReference.popPreCref(preCR);

crStr = ComponentReference.crefStr(cr);
Debug.fcall(Flags.PEDANTIC, Error.addCompilerWarning, "pre(" +& crStr +& ") does not appear in the initialization system. Assuming fixed start value for " +& crStr);

tp = BackendVariable.varType(var);

startExp = Expression.crefExp(cr);
tp = Expression.typeof(startExp);
startExp = Expression.makeBuiltinCall("$_start", {startExp}, tp);

preExp = Expression.crefExp(preCR);

eqn = BackendDAE.EQUATION(preExp, startExp, DAE.emptyElementSource);
orderedEqs = BackendEquation.equationAdd(eqn, orderedEqs);

system = BackendDAE.EQSYSTEM(vars, orderedEqs, NONE(), NONE(), BackendDAE.NO_MATCHING());
system = analyzeInitialSystem1(system, inMT, inI+1);
then system;

case (BackendDAE.EQSYSTEM(orderedVars=vars, orderedEqs=orderedEqs), _, _) equation
nIncidences = listLength(inMT[inI]);
true = intEq(nIncidences, 0);

var = BackendVariable.getVarAt(vars, inI);
cr = BackendVariable.varCref(var);
false = ComponentReference.isPreCref(cr);

crStr = "Following variable does not appear in any of the equations of the initialization system: " +& ComponentReference.crefStr(cr);
Error.addMessage(Error.INTERNAL_ERROR, {crStr});
then fail();

else equation
Error.addMessage(Error.INTERNAL_ERROR, {"./Compiler/BackEnd/Initialization.mo: function analyzeInitialSystem1 failed"});
then fail();
end matchcontinue;
end analyzeInitialSystem1;

protected function analyzeInitialSystem2 "function analyzeInitialSystem2
author lochel"
input BackendDAE.EqSystem inSystem;
Expand Down Expand Up @@ -643,59 +565,46 @@ protected function fixUnderDeterminedInitialSystem "function fixUnderDeterminedI
output BackendDAE.EquationArray outEqns;
algorithm
(outSucceed, outVars, outEqns) := matchcontinue(inDAE, inVars, inEqns, inInitVars)
local
BackendDAE.SparsePattern sparsityPattern;
BackendDAE.BackendDAE dae;
list< DAE.ComponentRef> someStates;
list<BackendDAE.Var> outputs; // $res1 ... $resN (initial equations)
list<BackendDAE.Var> states;
BackendDAE.EqSystems systs;
BackendDAE.Variables ivars;
Integer nVars, nStates, nEqns;
BackendDAE.EquationArray eqns;
local
BackendDAE.EquationArray eqns;
Integer nVars, nInitVars, nEqns;
list<BackendDAE.Var> initVarList;
BackendDAE.BackendDAE dae;
BackendDAE.SparsePattern sparsityPattern;
list<BackendDAE.Var> outputs; // $res1 ... $resN (initial equations)
list<tuple< DAE.ComponentRef, list< DAE.ComponentRef>>> dep;
list< DAE.ComponentRef> selectedVars;

// fix all free variables
case(_, _, eqns, _) equation
(dae, outputs) = BackendDAEOptimize.generateInitialMatricesDAE(inDAE);

BackendDAE.DAE(eqs=systs) = inDAE;
//ivars = selectInitializationVariables(systs);
ivars = inInitVars;
states = BackendVariable.varList(ivars);

nStates = BackendVariable.varsSize(ivars);
nInitVars = BackendVariable.varsSize(inInitVars);
nVars = BackendVariable.varsSize(inVars);
nEqns = BackendDAEUtil.equationSize(eqns);
true = intEq(nVars, nEqns+nStates);
nEqns = BackendDAEUtil.equationSize(inEqns);
true = intEq(nVars, nEqns+nInitVars);

Debug.fcall(Flags.PEDANTIC, Error.addCompilerWarning, "Assuming fixed start value for the following " +& intString(nVars-nEqns) +& " variables:");
eqns = addStartValueEquations(states, eqns);
Debug.fcall(Flags.PEDANTIC, Error.addCompilerWarning, "Assuming fixed start value for the following " +& intString(nVars-nEqns) +& " variables:");
initVarList = BackendVariable.varList(inInitVars);
eqns = addStartValueEquations(initVarList, eqns);
then (true, inVars, eqns);

// fix a subset of unfixed variables
case(_, _, eqns, _) equation
(dae, outputs) = BackendDAEOptimize.generateInitialMatricesDAE(inDAE);

BackendDAE.DAE(eqs=systs) = inDAE;
//ivars = selectInitializationVariables(systs);
ivars = inInitVars;
states = BackendVariable.varList(ivars);

nVars = BackendVariable.varsSize(inVars);
nEqns = BackendDAEUtil.equationSize(eqns);
true = intLt(nEqns, nVars);

(sparsityPattern, _) = BackendDAEOptimize.generateSparsePattern(dae, states, outputs);
initVarList = BackendVariable.varList(inInitVars);
(dae, outputs) = BackendDAEOptimize.generateInitialMatricesDAE(inDAE);
(sparsityPattern, _) = BackendDAEOptimize.generateSparsePattern(dae, initVarList, outputs);

(dep, _) = sparsityPattern;
someStates = collectIndependentVars(dep, {});
selectedVars = collectIndependentVars(dep, {});

Debug.fcall(Flags.DUMP_INITIAL_SYSTEM, BackendDump.dumpSparsityPattern, sparsityPattern);

true = intEq(nVars-nEqns, listLength(someStates)); // fix only if it is definite
true = intEq(nVars-nEqns, listLength(selectedVars)); // fix only if it is definite

Debug.fcall(Flags.PEDANTIC, Error.addCompilerWarning, "Assuming fixed start value for the following " +& intString(nVars-nEqns) +& " variables:");
eqns = addStartValueEquations1(someStates, eqns);
eqns = addStartValueEquations1(selectedVars, eqns);
then (true, inVars, eqns);

else equation
Expand Down
5 changes: 1 addition & 4 deletions Compiler/Util/Flags.mo
Original file line number Diff line number Diff line change
Expand Up @@ -389,8 +389,6 @@ constant DebugFlag SHOW_PROGRAM_CHANGES = DEBUG_FLAG(111, "showProgramChanges",
Util.gettext("prints the replacements to be done on program to remove redeclares (only works with +d=scodeInstShortcut)"));
constant DebugFlag SHOW_EQUATION_SOURCE = DEBUG_FLAG(112, "showEquationSource",
Util.gettext("display the element source information in the dumped DAE for easier debugging"));
constant DebugFlag TRACE_INITIAL_SYSTEM = DEBUG_FLAG(113, "traceinitialsystem",
Util.gettext("dumps information during the steps generating the symbolic initial equation system"));

// This is a list of all debug flags, to keep track of which flags are used. A
// flag can not be used unless it's in this list, and the list is checked at
Expand Down Expand Up @@ -508,8 +506,7 @@ constant list<DebugFlag> allDebugFlags = {
PEDANTIC,
SHOW_REDECLARE_ANALYSIS,
SHOW_PROGRAM_CHANGES,
SHOW_EQUATION_SOURCE,
TRACE_INITIAL_SYSTEM
SHOW_EQUATION_SOURCE
};

// CONFIGURATION FLAGS
Expand Down
4 changes: 2 additions & 2 deletions SimulationRuntime/c/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ IF(SUNDIALS_INCLUDE_DIR)

INCLUDE_DIRECTORIES(${SUNDIALS_INCLUDE_DIR})

if (SUNDIALS_LIBRARY_CVODE AND
if(SUNDIALS_LIBRARY_CVODE AND
SUNDIALS_LIBRARY_IDA AND
SUNDIALS_LIBRARY_NVEC AND
SUNDIALS_KINSOL)
Expand All @@ -51,7 +51,7 @@ ENDIF(SUNDIALS_LIBRARY_CVODE AND
SUNDIALS_LIBRARY_NVEC AND
SUNDIALS_KINSOL)

if (SUNDIALS_LIBRARY_CVODED AND
if(SUNDIALS_LIBRARY_CVODED AND
SUNDIALS_LIBRARY_IDAD AND
SUNDIALS_LIBRARY_NVECD AND
SUNDIALS_KINSOLD)
Expand Down

0 comments on commit c0a91aa

Please sign in to comment.