Linux GNU 11.4.0 Code Coverage Report


Directory: ./
Coverage: low: ≥ 0% medium: ≥ 75.0% high: ≥ 90.0%
Coverage Exec / Excl / Total
Lines: 66.8% 300 / 0 / 449
Functions: -% 0 / 0 / 0
Branches: -% 0 / 0 / 0

OMCompiler/Compiler/Template/CodegenCpp.tpl
Line Branch Exec Source
1 /*
2 * This file is part of OpenModelica.
3 *
4 * Copyright (c) 1998-2026, Open Source Modelica Consortium (OSMC),
5 * c/o Linköpings universitet, Department of Computer and Information Science,
6 * SE-58183 Linköping, Sweden.
7 *
8 * All rights reserved.
9 *
10 * THIS PROGRAM IS PROVIDED UNDER THE TERMS OF AGPL VERSION 3 LICENSE OR
11 * THIS OSMC PUBLIC LICENSE (OSMC-PL) VERSION 1.8.
12 * ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES
13 * RECIPIENT'S ACCEPTANCE OF THE OSMC PUBLIC LICENSE OR THE GNU AGPL
14 * VERSION 3, ACCORDING TO RECIPIENTS CHOICE.
15 *
16 * The OpenModelica software and the OSMC (Open Source Modelica Consortium)
17 * Public License (OSMC-PL) are obtained from OSMC, either from the above
18 * address, from the URLs:
19 * http://www.openmodelica.org or
20 * https://github.com/OpenModelica/ or
21 * http://www.ida.liu.se/projects/OpenModelica,
22 * and in the OpenModelica distribution.
23 *
24 * GNU AGPL version 3 is obtained from:
25 * https://www.gnu.org/licenses/licenses.html#GPL
26 *
27 * This program is distributed WITHOUT ANY WARRANTY; without
28 * even the implied warranty of MERCHANTABILITY or FITNESS
29 * FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH
30 * IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS OF OSMC-PL.
31 *
32 * See the full OSMC Public License conditions for more details.
33 *
34 */
35
36 package CodegenCpp
37
38 import interface SimCodeTV;
39 import CodegenCppCommon.*;
40 import CodegenUtil.*;
41 import CodegenUtilSimulation.*;
42 import CodegenCppInit.*;
43 import ExpressionDumpTpl;
44
45 //
46 // Generates Modelica system class with the fowling inheritance structure
47 //
48 // Base class : ModelicaSystem -> implements IContinuous, IEvent, IStepEvent, ITime, ISystemProperties
49 // Derived class 1 : ModelicaSystemJacobian -> holds all Jacobian information
50 // Derived class 2 : ModelicaSystemMixed -> implements IMixedSystems
51 // Derived class 3 : ModelicaSystemStateSelection -> implements IStateSelection
52 // Derived class 4 : ModelicaSystemStateWriteOutput -> implements IWriteOutput
53 // Derived class 5 : ModelicaSystemStateInitialize -> implements ISystemInitialization
54 //
55
56
57 48 template translateModel(SimCode simCode)
58 ::=
59 let stateDerVectorName = "__zDot"
60 match simCode
61 case SIMCODE(modelInfo = MODELINFO(__)) then
62 let target = simulationCodeTarget()
63 let &extraFuncs = buffer "" /*BUFD*/
64 let &extraFuncsDecl = buffer "" /*BUFD*/
65 let &extraInitFuncs = buffer ""
66 let &extraInitFuncsDecl = buffer ""
67 let &extraResidualsFuncsDecl = buffer "" /*BUFD*/
68 let &dummyTypeElemCreation = buffer "" //remove this workaround if GCC > 4.4 is the default compiler
69 let &complexStartExpressions = buffer ""
70
71 let className = lastIdentOfPath(modelInfo.name)
72 let numRealVars = numRealvars(modelInfo)
73 let numIntVars = numIntvars(modelInfo)
74 let numBoolVars = numBoolvars(modelInfo)
75 let numStringVars = numStringvars(modelInfo)
76
77 let()= textFile(simulationMainFile(target, simCode, &extraFuncs, &extraFuncsDecl, "", "", "", "", numRealVars, numIntVars, numBoolVars, numStringVars, getPreVarsCount(modelInfo)), 'OMCpp<%fileNamePrefix%>Main.cpp')
78 let()= textFile(modelInitXMLFile(simCode, numRealVars, numIntVars, numBoolVars, numStringVars, "", "", "", false, "", complexStartExpressions, stateDerVectorName),'<%fileNamePrefix%>_init.xml')
79
80 let _ = match boolOr(Flags.isSet(Flags.HARDCODED_START_VALUES), Flags.isSet(Flags.GEN_DEBUG_SYMBOLS))
81 case true then
82 let()= textFile(simulationInitParameterCppFile(simCode, &extraInitFuncs, &extraInitFuncsDecl, '<%className%>Initialize', stateDerVectorName, false),'OMCpp<%fileNamePrefix%>InitializeParameter.cpp')
83 let()= textFile(simulationInitAlgVarsCppFile(simCode, &extraInitFuncs, &extraInitFuncsDecl, '<%className%>Initialize', stateDerVectorName, false),'OMCpp<%fileNamePrefix%>InitializeAlgVars.cpp')
84 ""
85 else
86 ""
87 let()= textFile(simulationInitCppFile(simCode, &extraInitFuncs, &extraInitFuncsDecl, '<%className%>Initialize', dummyTypeElemCreation, stateDerVectorName, false, complexStartExpressions),'OMCpp<%fileNamePrefix%>Initialize.cpp')
88 let()= textFile(simulationInitHeaderFile(simCode, &extraInitFuncs, &extraInitFuncsDecl, '<%className%>Initialize'), 'OMCpp<%fileNamePrefix%>Initialize.h')
89
90 let()= textFile(simulationTypesHeaderFile(simCode, &extraFuncs, &extraFuncsDecl, "", &dummyTypeElemCreation, modelInfo.functions, literals, stateDerVectorName, false), 'OMCpp<%fileNamePrefix%>Types.h')
91 let()= textFile(simulationMakefile(target, simCode, &extraFuncs, &extraFuncsDecl, "", "", "", "", "", false), '<%fileNamePrefix%>.makefile')
92
93 let &extraFuncsFun = buffer "" /*BUFD*/
94 let &extraFuncsDeclFun = buffer "" /*BUFD*/
95 let()= textFile(simulationFunctionsFile(simCode, &extraFuncsFun, &extraFuncsDeclFun, 'Functions', modelInfo.functions, literals, externalFunctionIncludes, stateDerVectorName, false), 'OMCpp<%fileNamePrefix%>Functions.cpp')
96 let()= textFile(simulationFunctionsHeaderFile(simCode, &extraFuncsFun, &extraFuncsDeclFun, 'Functions', modelInfo.functions, literals, stateDerVectorName, false), 'OMCpp<%fileNamePrefix%>Functions.h')
97
98 let &jacobianVarsInit = buffer "" /*BUFD*/
99 let()= textFile(simulationJacobianHeaderFile(simCode, &extraFuncs, &extraFuncsDecl, "", &jacobianVarsInit, Flags.isSet(Flags.GEN_DEBUG_SYMBOLS)), 'OMCpp<%fileNamePrefix%>Jacobian.h')
100 let()= textFile(simulationJacobianCppFile(simCode, &extraFuncs, &extraFuncsDecl, "", &jacobianVarsInit, stateDerVectorName, false), 'OMCpp<%fileNamePrefix%>Jacobian.cpp')
101 let()= textFile(simulationStateSelectionCppFile(simCode, &extraFuncs, &extraFuncsDecl, "", stateDerVectorName, false), 'OMCpp<%fileNamePrefix%>StateSelection.cpp')
102 let()= textFile(simulationStateSelectionHeaderFile(simCode, &extraFuncs, &extraFuncsDecl, ""), 'OMCpp<%fileNamePrefix%>StateSelection.h')
103 let()= textFile(simulationMixedSystemCppFile(simCode, updateResiduals(simCode, extraResidualsFuncsDecl, className, stateDerVectorName /*=__zDot*/, false),
104 &extraFuncs, &extraFuncsDecl, "", stateDerVectorName, false), 'OMCpp<%fileNamePrefix%>Mixed.cpp')
105 let()= textFile(simulationMixedSystemHeaderFile(simCode, &extraResidualsFuncsDecl), 'OMCpp<%fileNamePrefix%>Mixed.h')
106
107 let()= textFile(simulationWriteOutputCppFile(simCode, &extraFuncs, &extraFuncsDecl, "", stateDerVectorName, false), 'OMCpp<%fileNamePrefix%>WriteOutput.cpp')
108 let()= textFile(simulationWriteOutputHeaderFile(simCode, &extraFuncs, &extraFuncsDecl, ""), 'OMCpp<%fileNamePrefix%>WriteOutput.h')
109 let()= textFile(simulationFactoryFile(simCode, &extraFuncs, &extraFuncsDecl, ""),'OMCpp<%fileNamePrefix%>FactoryExport.cpp')
110 let()= textFile(simulationMainRunScript(simCode, &extraFuncs, &extraFuncsDecl, "", "", "", "exec"), '<%fileNamePrefix%><%simulationMainRunScriptSuffix(simCode, &extraFuncs, &extraFuncsDecl, "")%>')
111
112 let jac = (jacobianMatrices |> JAC_MATRIX(columns=mat, partitionIndex=partIdx) =>
113 (mat |> JAC_COLUMN(columnEqns=eqs) => algloopfiles(eqs, simCode, &extraFuncs, &extraFuncsDecl, "", contextAlgloopJacobian, partIdx, stateDerVectorName, false) ;separator="")
114 ;separator="")
115 let alg = algloopfiles(listAppend(allEquations, initialEquations), simCode, &extraFuncs, &extraFuncsDecl, "", contextAlgloop, 0, stateDerVectorName, false)
116 let clk = getSubPartitions(clockedPartitions) |> subPartition hasindex i fromindex 1 =>
117 match subPartition
118 case SUBPARTITION(__) then
119 algloopfiles(listAppend(equations, removedEquations), simCode, &extraFuncs, &extraFuncsDecl, "", contextAlgloop, i, stateDerVectorName, false)
120 ; separator = "\n"
121
122 let() = textFile(algloopMainfile(simCode, &extraFuncs, &extraFuncsDecl, "", contextAlgloop), 'OMCpp<%fileNamePrefix%>AlgLoopMain.cpp')
123 let() = textFile(calcHelperMainfile(simCode, &extraFuncs, &extraFuncsDecl, ""), 'OMCpp<%fileNamePrefix%>CalcHelperMain.cpp')
124
125 // generate main model file last to consider all extraFuncs and extraFuncsDecl
126 let()= textFile(simulationCppFile(simCode, contextOther, update(simCode , &extraFuncs , &extraFuncsDecl, className, stateDerVectorName, false),
127 '<%numRealVars%> - 1', '<%numIntVars%> - 1', '<%numBoolVars%> - 1', '<%numStringVars%> - 1', &extraFuncs, &extraFuncsDecl, className, "", "", "",
128 stateDerVectorName, false), 'OMCpp<%fileNamePrefix%>.cpp')
129 let()= textFile(simulationHeaderFile(simCode, contextOther, &extraFuncs, &extraFuncsDecl, className, "", "", "",
130 memberVariableDefine(modelInfo, varToArrayIndexMapping, '<%numRealVars%> - 1', '<%numIntVars%> - 1', '<%numBoolVars%> - 1', '<%numStringVars%> - 1', Flags.isSet(Flags.GEN_DEBUG_SYMBOLS), false),
131 false), 'OMCpp<%fileNamePrefix%>.h')
132 match target
133 case "vxworks69" then
134 let()= textFile(functionBlock(simCode), '<%fileNamePrefix%>_PLCOPEN.xml')
135 let()= textFile(ftp_script(simCode), '<%fileNamePrefix%>_ftp.bat')
136 ""
137 else ""
138
139 end match
140 end translateModel;
141
142
143 ✗ template translateFunctions(FunctionCode functionCode)
144 "Generates C code and Makefile for compiling and calling Modelica and
145 MetaModelica functions."
146 ::=
147 match functionCode
148 case FUNCTIONCODE(__) then
149
150 "" // Return empty result since result written to files directly
151 end translateFunctions;
152
153 49 template simulationHeaderFile(SimCode simCode ,Context context,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, String additionalIncludes,
154 String additionalPublicMembers, String additionalProtectedMembers, String memberVariableDefinitions, Boolean useFlatArrayNotation)
155 "Generates code for header file for simulation target."
156 ::=
157 match simCode
158 case SIMCODE(__) then
159 <<
160 <%generateHeaderIncludeString(simCode, &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)%>
161 <%additionalIncludes%>
162 <%generateClassDeclarationCode(simCode ,context, &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, additionalPublicMembers, additionalProtectedMembers, memberVariableDefinitions, useFlatArrayNotation)%>
163 >>
164 end simulationHeaderFile;
165
166
167 49 template simulationInitHeaderFile(SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace)
168 "Generates code for header file for simulation target."
169 ::=
170 match simCode
171 case SIMCODE(modelInfo=MODELINFO(vars=SIMVARS(__)),fileNamePrefix=fileNamePrefix) then
172 let initeqs = generateEquationMemberFuncDecls(initialEquations,"initEquation")
173 let initparameqs = generateEquationMemberFuncDecls(parameterEquations,"initParameterEquation")
174 match modelInfo
175 case modelInfo as MODELINFO(vars=SIMVARS(__)) then
176 let functionPrefix = if(Flags.isSet(Flags.HARDCODED_START_VALUES)) then "initialize" else "check"
177 <<
178 #pragma once
179
180 /*****************************************************************************
181 *
182 * Simulation code to initialize the Modelica system
183 *
184 *****************************************************************************/
185
186 class <%lastIdentOfPath(modelInfo.name)%>Initialize : public ISystemInitialization, public <%lastIdentOfPath(modelInfo.name)%>WriteOutput
187 {
188 public:
189 <%lastIdentOfPath(modelInfo.name)%>Initialize(IGlobalSettings* globalSettings, shared_ptr<ISimObjects> simObjects);
190 <%lastIdentOfPath(modelInfo.name)%>Initialize(<%lastIdentOfPath(modelInfo.name)%>Initialize& instance);
191 virtual ~<%lastIdentOfPath(modelInfo.name)%>Initialize();
192 virtual bool initial();
193 virtual void setInitial(bool);
194 virtual void initialize();
195 virtual void initializeMemory();
196 virtual void initializeFreeVariables();
197 virtual void initializeBoundVariables();
198 virtual void initParameterEquations();
199 virtual void initEquations();
200 virtual IMixedSystem* clone();
201 <%if(boolAnd(boolNot(Flags.isSet(Flags.HARDCODED_START_VALUES)), Flags.isSet(Flags.GEN_DEBUG_SYMBOLS))) then
202 <<
203 virtual void checkVariables();
204 virtual void checkParameters();
205 >>
206 %>
207 private:
208 <%initeqs%>
209 <%initparameqs%>
210 <%destructExtObjsDecl(simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, false)%>
211 <%extraFuncsDecl%>
212
213 void InitializeDummyTypeElems();
214
215 <%if(boolOr(Flags.isSet(Flags.HARDCODED_START_VALUES), Flags.isSet(Flags.GEN_DEBUG_SYMBOLS))) then
216 <<
217 <%List.partition(vars.algVars, 100) |> ls hasindex idx => 'void <%functionPrefix%>AlgVars_<%idx%>();';separator="\n"%>
218
219 void <%functionPrefix%>AlgVars();
220 void <%functionPrefix%>DiscreteAlgVars();
221
222 <%List.partition(vars.intAlgVars, 100) |> ls hasindex idx => 'void <%functionPrefix%>IntAlgVars_<%idx%>();';separator="\n"%>
223
224 void <%functionPrefix%>IntAlgVars();
225 void <%functionPrefix%>BoolAlgVars();
226
227 <%List.partition(vars.stringAlgVars, 100) |> ls hasindex idx => 'void <%functionPrefix%>StringAlgVars_<%idx%>();';separator="\n"%>
228
229 void <%functionPrefix%>StringAlgVars();
230
231 <%List.partition(vars.aliasVars, 100) |> ls hasindex idx => 'void <%functionPrefix%>AliasVars_<%idx%>();';separator="\n"%>
232 <%List.partition(vars.stringAliasVars, 100) |> ls hasindex idx => 'void <%functionPrefix%>StringAliasVars_<%idx%>();';separator="\n"%>
233 void <%functionPrefix%>StringAliasVars();
234 void <%functionPrefix%>AliasVars();
235 void <%functionPrefix%>IntAliasVars();
236 void <%functionPrefix%>BoolAliasVars();
237
238 <%List.partition(vars.paramVars, 100) |> ls hasindex idx => 'void <%functionPrefix%>ParameterVars_<%idx%>();';separator="\n"%>
239 <%List.partition(vars.intParamVars, 100) |> ls hasindex idx => 'void <%functionPrefix%>IntParameterVars_<%idx%>();';separator="\n"%>
240 <%List.partition(vars.boolParamVars, 100) |> ls hasindex idx => 'void <%functionPrefix%>BoolParameterVars_<%idx%>();';separator="\n"%>
241 <%List.partition(vars.stringParamVars, 100) |> ls hasindex idx => 'void <%functionPrefix%>StringParameterVars_<%idx%>();';separator="\n"%>
242 void <%functionPrefix%>ParameterVars();
243 void <%functionPrefix%>IntParameterVars();
244 void <%functionPrefix%>BoolParameterVars();
245 void <%functionPrefix%>StringParameterVars();
246 void <%functionPrefix%>StateVars();
247 void <%functionPrefix%>DerVars();
248 >>
249 %>
250 };
251 >>
252 end match
253 end simulationInitHeaderFile;
254
255 49 template simulationJacobianHeaderFile(SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text& jacobianVarsInit, Boolean createDebugCode)
256 "Generates code for header file for simulation target."
257 ::=
258 match simCode
259 case SIMCODE(modelInfo=MODELINFO(__)) then
260 let type = getConfigString(MATRIX_FORMAT)
261 let matrixreturntype = match type
262 case ("dense") then
263 "matrix_t"
264 case ("sparse") then
265 "sparsematrix_t"
266 else "A matrix type is not supported"
267 end match
268
269 <<
270 #pragma once
271
272 /*****************************************************************************
273 *
274 * Simulation code to initialize the Modelica system
275 *
276 *****************************************************************************/
277
278 class <%lastIdentOfPath(modelInfo.name)%>Jacobian : public <%lastIdentOfPath(modelInfo.name)%>
279 {
280 <% (jacobianMatrices |> JAC_MATRIX(columns=mat) hasindex index0 =>
281 (mat |> JAC_COLUMN(columnEqns=eqs) => generatefriendAlgloops(eqs, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace) ;separator="\n")
282 ;separator="")
283 %>
284 public:
285 <%lastIdentOfPath(modelInfo.name)%>Jacobian(IGlobalSettings* globalSettings, shared_ptr<ISimObjects> simObjects);
286 <%lastIdentOfPath(modelInfo.name)%>Jacobian(<%lastIdentOfPath(modelInfo.name)%>Jacobian& instance);
287 virtual ~<%lastIdentOfPath(modelInfo.name)%>Jacobian();
288
289 protected:
290 void initialize();
291 <%
292 let jacobianfunctions = (jacobianMatrices |> JAC_MATRIX(matrixName=name) hasindex index0 =>
293 <<
294
295 void calc<%name%>JacobianColumn();
296 <%matrixreturntype%>& get<%name%>Jacobian();
297 >>
298 ;separator="\n";empty)
299 <<
300 <%jacobianfunctions%>
301 >>
302 %>
303 <%
304 let jacobianvars = (jacobianMatrices |> JAC_MATRIX(matrixName=name) hasindex index0 =>
305 <<
306
307 <%matrixreturntype%> _<%name%>jacobian;
308 ublas::vector<double> _<%name%>jac_y;
309 ublas::vector<double> _<%name%>jac_tmp;
310 ublas::vector<double> _<%name%>jac_x;
311 <%
312 match name
313 case "A" then
314 <<
315 int* _<%name%>ColorOfColumn;
316 int _<%name%>MaxColors;
317 std::vector<int>* _<%name%>ColumnsOfColor;
318 std::vector<int>* _<%name%>DependenciesOfColumn;
319 >>
320 %>
321 >>
322 ;separator="\n";empty)
323 <<
324 <%jacobianvars%>
325 >>
326 %>
327
328 <%variableDefinitionsJacobians_skip(jacobianMatrices, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, &jacobianVarsInit, createDebugCode)%>
329
330 /*testmaessig aus der Cruntime*/
331 void initializeColoredJacobianA();
332
333 };
334 >>
335 end simulationJacobianHeaderFile;
336
337
338 49 template simulationStateSelectionHeaderFile(SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
339 "Generates code for header file for simulation target."
340 ::=
341 match simCode
342 case SIMCODE(modelInfo=MODELINFO(__)) then
343 <<
344 #pragma once
345
346 /*****************************************************************************
347 *
348 * Simulation code to initialize the Modelica system
349 *
350 *****************************************************************************/
351 class <%lastIdentOfPath(modelInfo.name)%>StateSelection: public IStateSelection, public <%lastIdentOfPath(modelInfo.name)%>Mixed
352 {
353 public:
354 <%lastIdentOfPath(modelInfo.name)%>StateSelection(IGlobalSettings* globalSettings, shared_ptr<ISimObjects> simObjects);
355 virtual ~<%lastIdentOfPath(modelInfo.name)%>StateSelection();
356 int getDimStateSets() const;
357 int getDimStates(unsigned int index) const;
358 int getDimCanditates(unsigned int index) const;
359 int getDimDummyStates(unsigned int index) const;
360 void getStates(unsigned int index,double* z);
361 void setStates(unsigned int index,const double* z);
362 void getStateCanditates(unsigned int index,double* z);
363 bool getAMatrix(unsigned int index, DynArrayDim2<int>& A);
364 void setAMatrix(unsigned int index, DynArrayDim2<int>& A);
365 bool getAMatrix(unsigned int index, DynArrayDim1<int>& A);
366 void setAMatrix(unsigned int index, DynArrayDim1<int>& A);
367
368 protected:
369 void initialize();
370 };
371 >>
372 end simulationStateSelectionHeaderFile;
373 /*
374
375 */
376 49 template simulationWriteOutputHeaderFile(SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
377 "Generates code for header file for simulation target."
378 ::=
379 match simCode
380 case SIMCODE(modelInfo=MODELINFO(__),simulationSettingsOpt = SOME(settings as SIMULATION_SETTINGS(__))) then
381 <<
382 #pragma once
383
384
385 /*****************************************************************************
386 *
387 * Simulation code to write simulation file
388 *
389 *****************************************************************************/
390
391 class <%lastIdentOfPath(modelInfo.name)%>WriteOutput : public IWriteOutput,public <%lastIdentOfPath(modelInfo.name)%>StateSelection
392 {
393 public:
394 <%lastIdentOfPath(modelInfo.name)%>WriteOutput(IGlobalSettings* globalSettings, shared_ptr<ISimObjects> simObjects);
395 <%lastIdentOfPath(modelInfo.name)%>WriteOutput(<%lastIdentOfPath(modelInfo.name)%>WriteOutput& instance);
396 virtual ~<%lastIdentOfPath(modelInfo.name)%>WriteOutput();
397
398
399 /// Output routine (to be called by the solver after every successful integration step)
400 virtual void writeOutput(const IWriteOutput::OUTPUT command = IWriteOutput::UNDEF_OUTPUT);
401 virtual IHistory* getHistory();
402
403 protected:
404 void initialize();
405 private:
406 shared_ptr<IHistory> _writeOutput;
407 };
408 >>
409 end simulationWriteOutputHeaderFile;
410
411
412 57 template getPreVarsCount(ModelInfo modelInfo)
413 ::=
414 match modelInfo
415 case MODELINFO(varInfo=VARINFO(__)) then
416 let allVarCount = intAdd(stringInt(numRealvars(modelInfo)), intAdd(stringInt(numIntvars(modelInfo)), stringInt(numBoolvars(modelInfo))))
417 <<
418 <%allVarCount%>
419 >>
420 end match
421 end getPreVarsCount;
422
423
424 49 template simulationMixedSystemHeaderFile(SimCode simCode, Text& extraResidualsFuncsDecl)
425 "Generates code for header file for simulation target."
426 ::=
427 match simCode
428 case SIMCODE(modelInfo=MODELINFO(vars = vars as SIMVARS(__))) then
429 <<
430 #pragma once
431 /*****************************************************************************
432 *
433 * Simulation code
434 *
435 *****************************************************************************/
436 class <%lastIdentOfPath(modelInfo.name)%>Mixed: public IMixedSystem, public <%lastIdentOfPath(modelInfo.name)%>Jacobian
437 {
438 public:
439 <%lastIdentOfPath(modelInfo.name)%>Mixed(IGlobalSettings* globalSettings, shared_ptr<ISimObjects> simObjects);
440 <%lastIdentOfPath(modelInfo.name)%>Mixed(<%lastIdentOfPath(modelInfo.name)%>Mixed &instance);
441 virtual ~ <%lastIdentOfPath(modelInfo.name)%>Mixed();
442
443 /// Provide Jacobian
444 virtual const matrix_t& getJacobian() ;
445 virtual const matrix_t& getJacobian(unsigned int index) ;
446 virtual sparsematrix_t& getSparseJacobian();
447 virtual sparsematrix_t& getSparseJacobian(unsigned int index);
448
449 virtual const matrix_t& getStateSetJacobian(unsigned int index);
450 virtual sparsematrix_t& getStateSetSparseJacobian(unsigned int index);
451 /// Called to handle all events occured at same time
452 virtual bool handleSystemEvents(bool* events);
453 //Saves all variables before an event is handled, is needed for the pre, edge and change operator
454 virtual void saveAll();
455 virtual void getAlgebraicDAEVars(double* y);
456 virtual void setAlgebraicDAEVars(const double* y);
457 virtual void getResidual(double* f);
458 virtual void evaluateDAE(const UPDATETYPE command = UNDEF_UPDATE);
459
460 /// Colored Jacobian
461 /*deprecated*/ virtual void getAColorOfColumn(int* aSparsePatternColorCols, int size);
462 virtual int getAMaxColors();
463 virtual const vector<int>& getAColumnsOfColor(int color);
464 virtual const vector<int>& getADependenciesOfColumn(int idx);
465
466 virtual string getModelName();
467 virtual bool isJacobianSparse();//true if getSparseJacobian is implemented and getJacobian is not, false if getJacobian is implemented and getSparseJacobian is not.
468 virtual bool isAnalyticJacobianGenerated();//true if the flag --generateDynamicJacobian=symbolic, false if not.
469 private:
470 // update residual methods
471 <%extraResidualsFuncsDecl%>
472 <%simulationDAEMethodsDeclaration(simCode)%>
473 };
474 >>
475 end simulationMixedSystemHeaderFile;
476
477
478
479 49 template simulationFactoryFile(SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
480 "Generates code for header file for simulation target."
481 ::=
482 match simCode
483 case SIMCODE(modelInfo=MODELINFO()) then
484 <<
485 #if defined(__TRICORE__) || defined(__vxworks)
486 #include <Core/System/FactoryExport.h>
487 #include <Core/DataExchange/SimData.h>
488 #include <Core/System/SimVars.h>
489 extern "C" IMixedSystem* createModelicaSystem(IGlobalSettings* globalSettings,shared_ptr<ISimObjects> simObjects)
490 {
491 return new <%lastIdentOfPath(modelInfo.name)%>Initialize(globalSettings, simObjects);
492 }
493
494 extern "C" ISimVars* createSimVars(size_t dim_real, size_t dim_int, size_t dim_bool, size_t dim_string, size_t dim_pre_vars, size_t dim_z, size_t z_i)
495 {
496 return new SimVars(dim_real, dim_int, dim_bool, dim_string, dim_pre_vars, dim_z, z_i);
497 }
498
499 extern "C" ISimData* createSimData()
500 {
501 return new SimData();
502 }
503
504 shared_ptr<ISimData> createSimDataFunction()
505 {
506 shared_ptr<ISimData> data( new SimData() );
507 return data;
508 }
509
510 shared_ptr<ISimVars> createSimVarsFunction(size_t dim_real, size_t dim_int, size_t dim_bool, size_t dim_string, size_t dim_pre_vars, size_t dim_z, size_t z_i)
511 {
512 shared_ptr<ISimVars> var( new SimVars(dim_real, dim_int, dim_bool, dim_string, dim_pre_vars, dim_z, z_i) );
513 return var;
514 }
515
516 #elif defined (RUNTIME_STATIC_LINKING)
517 #include <Core/System/FactoryExport.h>
518 #include <Core/DataExchange/SimData.h>
519 #include <Core/System/SimVars.h>
520 shared_ptr<ISimData> createSimDataFunction()
521 {
522 shared_ptr<ISimData> data( new SimData() );
523 return data;
524 }
525
526 shared_ptr<ISimVars> createSimVarsFunction(size_t dim_real, size_t dim_int, size_t dim_bool, size_t dim_string, size_t dim_pre_vars, size_t dim_z, size_t z_i)
527 {
528 shared_ptr<ISimVars> var( new SimVars(dim_real, dim_int, dim_bool, dim_string, dim_pre_vars, dim_z, z_i) );
529 return var;
530 }
531
532 shared_ptr<IMixedSystem> createSystemFunction(IGlobalSettings* globalSettings, shared_ptr<ISimObjects> simObjects)
533 {
534 shared_ptr<IMixedSystem> system( new <%lastIdentOfPath(modelInfo.name)%>Initialize(globalSettings, simObjects) );
535 return system;
536 }
537
538 #else
539
540 BOOST_EXTENSION_TYPE_MAP_FUNCTION
541 {
542 typedef boost::extensions::factory<IMixedSystem,IGlobalSettings*, shared_ptr<ISimObjects> > system_factory;
543 types.get<std::map<std::string, system_factory> >()["<%lastIdentOfPath(modelInfo.name)%>"]
544 .system_factory::set<<%lastIdentOfPath(modelInfo.name)%>Initialize>();
545 }
546 #endif
547 >>
548 end simulationFactoryFile;
549
550
551 49 template simulationInitCppFile(SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text& dummyTypeElemCreation, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation, Text& complexStartExpressions)
552 "Generates code for main cpp file for simulation target."
553 ::=
554 match simCode
555 case SIMCODE(modelInfo = MODELINFO(__)) then
556 <<
557 <%algloopfilesInclude(listAppend(listAppend(allEquations, initialEquations), getClockedEquations(getSubPartitions(clockedPartitions))), simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace)%>
558
559 <%lastIdentOfPath(modelInfo.name)%>Initialize::<%lastIdentOfPath(modelInfo.name)%>Initialize(IGlobalSettings* globalSettings, shared_ptr<ISimObjects> simObjects)
560 : <%lastIdentOfPath(modelInfo.name)%>WriteOutput(globalSettings, simObjects)
561 , _constructedExternalObjects(false)
562 {
563 InitializeDummyTypeElems();
564 }
565
566 <%lastIdentOfPath(modelInfo.name)%>Initialize::<%lastIdentOfPath(modelInfo.name)%>Initialize(<%lastIdentOfPath(modelInfo.name)%>Initialize& instance)
567 : <%lastIdentOfPath(modelInfo.name)%>WriteOutput(instance)
568 {
569 InitializeDummyTypeElems();
570 }
571
572 <%lastIdentOfPath(modelInfo.name)%>Initialize::~<%lastIdentOfPath(modelInfo.name)%>Initialize()
573 {
574 if (_constructedExternalObjects)
575 destructExternalObjects();
576 }
577
578 void <%lastIdentOfPath(modelInfo.name)%>Initialize::InitializeDummyTypeElems()
579 {
580 //This is necessary to prevent linker errors that occur with GCC 4.4 if a complex type is not used in the code and contains arrays
581 <%dummyTypeElemCreation%>
582 }
583
584 IMixedSystem* <%lastIdentOfPath(modelInfo.name)%>Initialize::clone()
585 {
586 return new <%lastIdentOfPath(modelInfo.name)%>Initialize(*this);
587 }
588
589 <%getIntialStatus(simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace)%>
590
591 <%setIntialStatus(simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace)%>
592
593 <%init(simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation, complexStartExpressions)%>
594
595 <%destructExtObjs(simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>
596
597 <%extraFuncs%>
598 >>
599 end simulationInitCppFile;
600
601 10 template simulationInitParameterCppFile(SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
602 "Generates code for main cpp file for simulation target."
603 ::=
604 match simCode
605 case SIMCODE(__) then
606 match modelInfo
607 case modelInfo as MODELINFO(vars=SIMVARS(__)) then
608 let &varDecls10 = buffer "" /*BUFD*/
609 let &varDecls11 = buffer "" /*BUFD*/
610 let &varDecls12 = buffer "" /*BUFD*/
611 let functionPrefix = if(Flags.isSet(Flags.HARDCODED_START_VALUES)) then 'initialize' else 'check'
612 let init10 = initValstWithSplit(varDecls10, "Real", '<%lastIdentOfPath(modelInfo.name)%>Initialize::<%functionPrefix%>ParameterVars', vars.paramVars, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, contextOther, stateDerVectorName, useFlatArrayNotation)
613 let init11 = initValstWithSplit(varDecls11, "Int", '<%lastIdentOfPath(modelInfo.name)%>Initialize::<%functionPrefix%>IntParameterVars', vars.intParamVars, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, contextOther, stateDerVectorName, useFlatArrayNotation)
614 let init12 = initValstWithSplit(varDecls12, "Bool", '<%lastIdentOfPath(modelInfo.name)%>Initialize::<%functionPrefix%>BoolParameterVars', vars.boolParamVars, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, contextOther, stateDerVectorName, useFlatArrayNotation)
615 let init13 = initValstWithSplit(varDecls12, "String", '<%lastIdentOfPath(modelInfo.name)%>Initialize::<%functionPrefix%>StringParameterVars', vars.stringParamVars, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, contextOther, stateDerVectorName, useFlatArrayNotation)
616 <<
617 <%varDecls10%>
618 <%varDecls11%>
619 <%varDecls12%>
620 <%init10%>
621 <%init11%>
622 <%init12%>
623 <%init13%>
624 >>
625 end simulationInitParameterCppFile;
626
627 10 template simulationInitAlgVarsCppFile(SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
628 "Generates code for main cpp file for simulation target."
629 ::=
630 match simCode
631 case SIMCODE(__) then
632 match modelInfo
633 case modelInfo as MODELINFO(vars=SIMVARS(__)) then
634 let &varDecls3 = buffer "" /*BUFD*/
635 let &varDecls4 = buffer "" /*BUFD*/
636 let &varDecls5 = buffer "" /*BUFD*/
637 let &varDecls6 = buffer "" /*BUFD*/
638 let &varDecls7 = buffer "" /*BUFD*/
639 let functionPrefix = if Flags.isSet(Flags.HARDCODED_START_VALUES) then "initialize" else "check"
640
641 let init3 = initValstWithSplit(varDecls3, "Real", '<%lastIdentOfPath(modelInfo.name)%>Initialize::<%functionPrefix%>AlgVars', vars.algVars, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, contextOther, stateDerVectorName, useFlatArrayNotation)
642 let init4 = initValst(varDecls4, "Real", vars.discreteAlgVars, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace,contextOther, stateDerVectorName, useFlatArrayNotation)
643 let init5 = initValstWithSplit(varDecls5, "Int", '<%lastIdentOfPath(modelInfo.name)%>Initialize::<%functionPrefix%>IntAlgVars', vars.intAlgVars, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, contextOther, stateDerVectorName, useFlatArrayNotation)
644 let init6 = initValst(varDecls6, "Bool", vars.boolAlgVars, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, contextOther, stateDerVectorName, useFlatArrayNotation)
645 let init7 = initValstWithSplit(varDecls7, "String", '<%lastIdentOfPath(modelInfo.name)%>Initialize::<%functionPrefix%>StringAlgVars', vars.stringAlgVars, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, contextOther, stateDerVectorName, useFlatArrayNotation)
646
647 <<
648
649 <%init3%>
650
651 void <%lastIdentOfPath(modelInfo.name)%>Initialize::<%functionPrefix%>DiscreteAlgVars()
652 {
653 <%varDecls4%>
654 <%init4%>
655 }
656
657 <%init5%>
658
659 void <%lastIdentOfPath(modelInfo.name)%>Initialize::<%functionPrefix%>BoolAlgVars()
660 {
661 <%varDecls6%>
662 <%init6%>
663 }
664
665 <%init7%>
666 >>
667 end simulationInitAlgVarsCppFile;
668
669
670 49 template simulationJacobianCppFile(SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text &jacobianVarsInit, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
671 "Generates code for main cpp file for simulation target."
672 ::=
673 match simCode
674 case SIMCODE(modelInfo = MODELINFO(__)) then
675 let initialjacMats = (jacobianMatrices |> JAC_MATRIX(columns=mat, seedVars=vars, matrixName=name, sparsity=sparsepattern, coloredCols=colorList, jacobianIndex=jacIndex) =>
676 initialAnalyticJacobians(jacIndex, mat, vars, name, sparsepattern, colorList, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace)
677 ;separator="\n";empty)
678 <<
679
680 <% (jacobianMatrices |> JAC_MATRIX(columns=mat) hasindex index0 =>
681 (mat |> JAC_COLUMN(columnEqns=eqs) => algloopfilesInclude(eqs, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace) ;separator="")
682 ;separator="")
683 %>
684 <%lastIdentOfPath(modelInfo.name)%>Jacobian::<%lastIdentOfPath(modelInfo.name)%>Jacobian(IGlobalSettings* globalSettings, shared_ptr<ISimObjects> simObjects)
685 : <%lastIdentOfPath(modelInfo.name)%>(globalSettings,simObjects)
686 , _AColorOfColumn(NULL)
687 , _AMaxColors(0)
688 , _AColumnsOfColor(NULL)
689 , _ADependenciesOfColumn(NULL)
690 <%initialjacMats%>
691 <%jacobianVarsInit%>
692 {
693 }
694
695 <%lastIdentOfPath(modelInfo.name)%>Jacobian::<%lastIdentOfPath(modelInfo.name)%>Jacobian(<%lastIdentOfPath(modelInfo.name)%>Jacobian& instance)
696 : <%lastIdentOfPath(modelInfo.name)%>(instance)
697 , _AColorOfColumn(NULL)
698 , _AMaxColors(0)
699 , _AColumnsOfColor(NULL)
700 , _ADependenciesOfColumn(NULL)
701 <%initialjacMats%>
702 <%jacobianVarsInit%>
703 {
704 }
705
706 <%lastIdentOfPath(modelInfo.name)%>Jacobian::~<%lastIdentOfPath(modelInfo.name)%>Jacobian()
707 {
708 if (_AColorOfColumn)
709 delete [] _AColorOfColumn;
710 if (_AColumnsOfColor)
711 delete [] _AColumnsOfColor;
712 if (_ADependenciesOfColumn)
713 delete [] _ADependenciesOfColumn;
714 }
715
716 <%functionAnalyticJacobians(modelInfo,jacobianMatrices, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>
717
718 //testmaessig aus der cruntime
719 /* Jacobians */
720
721
722 void <%lastIdentOfPath(modelInfo.name)%>Jacobian::initializeColoredJacobianA()
723 {
724 <%functionAnalyticJacobians2(jacobianMatrices, lastIdentOfPath(modelInfo.name),simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>
725 }
726 <%\n%>
727 >>
728 end simulationJacobianCppFile;
729
730 49 template simulationStateSelectionCppFile(SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
731 "Generates code for main cpp file for simulation target."
732 ::=
733 match simCode
734 case SIMCODE(modelInfo = MODELINFO(__)) then
735 <<
736
737 <%lastIdentOfPath(modelInfo.name)%>StateSelection::<%lastIdentOfPath(modelInfo.name)%>StateSelection(IGlobalSettings* globalSettings, shared_ptr<ISimObjects> simObjects)
738 : <%lastIdentOfPath(modelInfo.name)%>Mixed(globalSettings, simObjects)
739 {
740 }
741
742 <%lastIdentOfPath(modelInfo.name)%>StateSelection::~<%lastIdentOfPath(modelInfo.name)%>StateSelection()
743 {
744 }
745
746 <%functionDimStateSets(stateSets, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace)%>
747 <%functionStateSets(stateSets, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>
748 >>
749 end simulationStateSelectionCppFile;
750
751
752 49 template simulationWriteOutputCppFile(SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
753 "Generates code for main cpp file for simulation target."
754 ::=
755 match simCode
756 case SIMCODE(modelInfo = MODELINFO(__)) then
757 <<
758
759
760 <%lastIdentOfPath(modelInfo.name)%>WriteOutput::<%lastIdentOfPath(modelInfo.name)%>WriteOutput(IGlobalSettings* globalSettings, shared_ptr<ISimObjects> simObjects)
761 : <%lastIdentOfPath(modelInfo.name)%>StateSelection(globalSettings, simObjects)
762 {
763
764
765
766 }
767
768 <%lastIdentOfPath(modelInfo.name)%>WriteOutput::<%lastIdentOfPath(modelInfo.name)%>WriteOutput(<%lastIdentOfPath(modelInfo.name)%>WriteOutput& instance)
769 : <%lastIdentOfPath(modelInfo.name)%>StateSelection(instance.getGlobalSettings(), instance.getSimObjects())
770 {
771
772 }
773
774 <%lastIdentOfPath(modelInfo.name)%>WriteOutput::~<%lastIdentOfPath(modelInfo.name)%>WriteOutput()
775 {
776
777 }
778
779 IHistory* <%lastIdentOfPath(modelInfo.name)%>WriteOutput::getHistory()
780 {
781 return _writeOutput.get();
782 }
783
784 void <%lastIdentOfPath(modelInfo.name)%>WriteOutput::initialize()
785 {
786 if(getGlobalSettings()->getOutputPointType()!= OPT_NONE)
787 {
788 _writeOutput = getSimObjects()->LoadWriter(<%numAlgvars(modelInfo)%> + <%numAliasvars(modelInfo)%> + 2*<%numStatevars(modelInfo)%>).lock();
789 _writeOutput->init();
790 _writeOutput->clear();
791 }
792 }
793
794
795 <%writeoutput(simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>
796 >>
797 end simulationWriteOutputCppFile;
798 /*
799 map<unsigned int,string> var_ouputs_idx;
800 <%outputIndices(modelInfo)%>
801 _writeOutput->setOutputs(var_ouputs_idx);
802 */
803
804
805 ✗ template simulationWriteOutputAlgVarsCppFile(SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
806 "Generates code for main cpp file for simulation target."
807 ::=
808 match simCode
809 case SIMCODE(__) then
810 match modelInfo
811 case modelInfo as MODELINFO(vars=SIMVARS(__)) then
812 let className = lastIdentOfPath(modelInfo.name)
813 let algVarsStart = "1"
814 let discrAlgVarsStart = intAdd(stringInt(algVarsStart), stringInt(numProtectedRealAlgvars(modelInfo)))
815 let intAlgVarsStart = intAdd(stringInt(discrAlgVarsStart), stringInt(numProtectedDiscreteAlgVars(modelInfo)))
816 let boolAlgVarsStart = intAdd(stringInt(intAlgVarsStart), stringInt(numProtectedIntAlgvars(modelInfo)))
817 <<
818 void <%className%>WriteOutput::writeAlgVarsResultNames(vector<string>& names)
819 {
820 <% if protectedVars(vars.algVars) then
821 'names += <%(vars.algVars |> SIMVAR(isProtected=false) =>
822 '"<%crefStrForWriteOutput(name)%>"' ;separator=",";align=10;alignSeparator=";\n names += " )%>;' %>
823
824 }
825 void <%className%>WriteOutput::writeDiscreteAlgVarsResultNames(vector<string>& names)
826 {
827 <% if protectedVars(vars.discreteAlgVars) then
828 'names += <%(vars.discreteAlgVars |> SIMVAR(isProtected=false) =>
829 '"<%crefStrForWriteOutput(name)%>"' ;separator=",";align=10;alignSeparator=";\n names += " )%>;' %>
830
831 }
832 void <%className%>WriteOutput::writeIntAlgVarsResultNames(vector<string>& names)
833 {
834 <% if protectedVars(vars.intAlgVars) then
835 'names += <%(vars.intAlgVars |> SIMVAR(isProtected=false) =>
836 '"<%crefStrForWriteOutput(name)%>"' ;separator=",";align=10;alignSeparator=";\n names += " )%>;' %>
837 }
838 void <%className%>WriteOutput::writeBoolAlgVarsResultNames(vector<string>& names)
839 {
840 <% if protectedVars(vars.boolAlgVars) then
841 'names +=<%(vars.boolAlgVars |> SIMVAR(isProtected=false) =>
842 '"<%crefStrForWriteOutput(name)%>"' ;separator=",";align=10;alignSeparator=";\n names += " )%>;' %>
843 }
844 void <%className%>WriteOutput::writeAlgVarsResultDescription(vector<string>& description)
845 {
846 <% if protectedVars(vars.algVars) then
847 'description += <%(vars.algVars |> SIMVAR(isProtected=false) =>
848 '"<%Util.escapeModelicaStringToCString(comment)%>"' ;separator=",";align=10;alignSeparator=";\n description += " )%>;' %>
849
850 }
851 void <%className%>WriteOutput::writeDiscreteAlgVarsResultDescription(vector<string>& description)
852 {
853 <% if protectedVars(vars.discreteAlgVars) then
854 'description += <%(vars.discreteAlgVars |> SIMVAR(isProtected=false) =>
855 '"<%Util.escapeModelicaStringToCString(comment)%>"' ;separator=",";align=10;alignSeparator=";\n description += " )%>;' %>
856
857 }
858 void <%className%>WriteOutput::writeIntAlgVarsResultDescription(vector<string>& description)
859 {
860 <% if protectedVars(vars.intAlgVars) then
861 'description += <%(vars.intAlgVars |> SIMVAR(isProtected=false) =>
862 '"<%Util.escapeModelicaStringToCString(comment)%>"' ;separator=",";align=10;alignSeparator=";\n description += " )%>;' %>
863 }
864 void <%className%>WriteOutput::writeBoolAlgVarsResultDescription(vector<string>& description)
865 {
866 <% if protectedVars(vars.boolAlgVars) then
867 'description +=<%(vars.boolAlgVars |> SIMVAR(isProtected=false) =>
868 '"<%Util.escapeModelicaStringToCString(comment)%>"' ;separator=",";align=10;alignSeparator=";\n description += " )%>;' %>
869 }
870 <%writeOutputVarsWithSplit("writeAlgVarsValues", protectedVars(vars.algVars), stringInt(algVarsStart), '<%className%>WriteOutput', false, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>
871 <%writeOutputVarsWithSplit("writeDiscreteAlgVarsValues", protectedVars(vars.discreteAlgVars), stringInt(discrAlgVarsStart), '<%className%>WriteOutput', false, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>
872 <%writeOutputVarsWithSplit("writeIntAlgVarsValues", protectedVars(vars.intAlgVars), stringInt(intAlgVarsStart), '<%className%>WriteOutput', false, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>
873 <%writeOutputVarsWithSplit("writeBoolAlgVarsValues", protectedVars(vars.boolAlgVars), stringInt(boolAlgVarsStart), '<%className%>WriteOutput', false, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>
874
875 >>
876 end simulationWriteOutputAlgVarsCppFile;
877
878
879
880 ✗ template simulationWriteOutputParameterCppFile(SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Boolean useFlatArrayNotation)
881 "Generates code for main cpp file for simulation target."
882 ::=
883 match simCode
884 case SIMCODE(__) then
885 match modelInfo
886 case modelInfo as MODELINFO(vars=SIMVARS(__)) then
887 <<
888 void <%lastIdentOfPath(modelInfo.name)%>WriteOutput::writeParametertNames(vector<string>& names)
889 {
890 /*workarround ced*/
891
892 <% if protectedVars(vars.paramVars) then
893 'names += <%(vars.paramVars |> SIMVAR(isProtected=false) =>
894 '"<%crefStrForWriteOutput(name)%>"' ;separator=",";align=10;alignSeparator=";\n names += " )%>;' %>
895
896 }
897
898 void <%lastIdentOfPath(modelInfo.name)%>WriteOutput::writeIntParameterNames(vector<string>& names)
899 {
900 <% if protectedVars(vars.intParamVars) then
901 'names += <%(vars.intParamVars |> SIMVAR(isProtected=false) =>
902 '"<%crefStrForWriteOutput(name)%>"' ;separator=",";align=10;alignSeparator=";\n names += " )%>;' %>
903 }
904 void <%lastIdentOfPath(modelInfo.name)%>WriteOutput::writeBoolParameterNames(vector<string>& names)
905 {
906 <% if protectedVars(vars.boolParamVars) then
907 'names += <%(vars.boolParamVars |> SIMVAR(isProtected=false) =>
908 '"<%crefStrForWriteOutput(name)%>"' ;separator=",";align=10;alignSeparator=";\n names += " )%>;' %>
909 }
910 void <%lastIdentOfPath(modelInfo.name)%>WriteOutput::writeParameterDescription(vector<string>& names)
911 {
912 /*workarround ced*/
913 <% if protectedVars(vars.paramVars) then
914 'names += <%(vars.paramVars |> SIMVAR(isProtected=false) =>
915 '"<%Util.escapeModelicaStringToCString(comment)%>"' ;separator=",";align=10;alignSeparator=";\n names += " )%>;' %>
916
917 }
918
919 void <%lastIdentOfPath(modelInfo.name)%>WriteOutput::writeIntParameterDescription(vector<string>& names)
920 {
921 <% if protectedVars(vars.intParamVars) then
922 'names += <%(vars.intParamVars |> SIMVAR(isProtected=false) =>
923 '"<%Util.escapeModelicaStringToCString(comment)%>"' ;separator=",";align=10;alignSeparator=";\n names += " )%>;' %>
924 }
925
926 void <%lastIdentOfPath(modelInfo.name)%>WriteOutput::writeBoolParameterDescription(vector<string>& names)
927 {
928 <% if protectedVars(vars.boolParamVars) then
929 'names += <%(vars.boolParamVars |> SIMVAR(isProtected=false) =>
930 '"<%Util.escapeModelicaStringToCString(comment)%>"' ;separator=",";align=10;alignSeparator=";\n names += " )%>;' %>
931 }
932 <%writeoutputparams(modelInfo,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,contextOther,useFlatArrayNotation)%>
933 >>
934 end simulationWriteOutputParameterCppFile;
935
936
937 ✗ template simulationWriteOutputAliasVarsCppFile(SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
938 "Generates code for main cpp file for simulation target."
939 ::=
940 match simCode
941 case SIMCODE(__) then
942 match modelInfo
943 case modelInfo as MODELINFO(vars=SIMVARS(__)) then
944 let className = lastIdentOfPath(modelInfo.name)
945 let algVarsStart = "1"
946 let discrAlgVarsStart = intAdd(stringInt(algVarsStart), stringInt(numProtectedRealAlgvars(modelInfo)))
947 let intAlgVarsStart = intAdd(stringInt(discrAlgVarsStart), stringInt(numProtectedDiscreteAlgVars(modelInfo)))
948 let boolAlgVarsStart = intAdd(stringInt(intAlgVarsStart), stringInt(numProtectedIntAlgvars(modelInfo)))
949 let aliasVarsStart = intAdd(stringInt(boolAlgVarsStart), stringInt(numProtectedBoolAlgvars(modelInfo)))
950 let intAliasVarsStart = intAdd(stringInt(aliasVarsStart), stringInt(numProtectedRealAliasvars(modelInfo)))
951 let boolAliasVarsStart = intAdd(stringInt(intAliasVarsStart), stringInt(numProtectedIntAliasvars(modelInfo)))
952 let stateVarsStart = intAdd(stringInt(boolAliasVarsStart), stringInt(numProtectedBoolAliasvars(modelInfo)))
953 <<
954 void <%className%>WriteOutput::writeBoolAliasVarsResultNames(vector<string>& names)
955 {
956 <% if protectedVars(vars.boolAliasVars) then
957 'names += <%(vars.boolAliasVars |> SIMVAR(isProtected=false) =>
958 '"<%crefStrForWriteOutput(name)%>"';separator=",";align=10;alignSeparator=";\n names += " )%>;' %>
959 }
960 void <%className%>WriteOutput::writeAliasVarsResultNames(vector<string>& names)
961 {
962 <% if protectedVars(vars.aliasVars) then
963 'names +=<%(vars.aliasVars |> SIMVAR(isProtected=false) =>
964 '"<%crefStrForWriteOutput(name)%>"' ;separator=",";align=10;alignSeparator=";\n names += " )%>;' %>
965 }
966
967 void <%className%>WriteOutput::writeIntAliasVarsResultNames(vector<string>& names)
968 {
969 <% if protectedVars(vars.intAliasVars) then
970 'names += <%(vars.intAliasVars |> SIMVAR(isProtected=false) =>
971 '"<%crefStrForWriteOutput(name)%>"' ;separator=",";align=10;alignSeparator=";\n names += " )%>;' %>
972 }
973
974
975
976
977
978 void <%className%>WriteOutput::writeAliasVarsResultDescription(vector<string>& description)
979 {
980 <% if protectedVars(vars.aliasVars) then
981 'description +=<%(vars.aliasVars |> SIMVAR(isProtected=false) =>
982 '"<%Util.escapeModelicaStringToCString(comment)%>"' ;separator=",";align=10;alignSeparator=";\n description += " )%>;' %>
983 }
984
985 void <%className%>WriteOutput::writeIntAliasVarsResultDescription(vector<string>& description)
986 {
987 <% if protectedVars(vars.intAliasVars) then
988 'description += <%(vars.intAliasVars |> SIMVAR(isProtected=false) =>
989 '"<%Util.escapeModelicaStringToCString(comment)%>"' ;separator=",";align=10;alignSeparator=";\n description += " )%>;' %>
990 }
991
992 void <%className%>WriteOutput::writeBoolAliasVarsResultDescription(vector<string>& description)
993 {
994 <% if protectedVars(vars.boolAliasVars) then
995 'description += <%(vars.boolAliasVars |> SIMVAR(isProtected=false) =>
996 '"<%Util.escapeModelicaStringToCString(comment)%>"';separator=",";align=10;alignSeparator=";\n description += " )%>;' %>
997 }
998 <%writeOutputVarsWithSplit("writeAliasVarsValues", protectedVars(vars.aliasVars), stringInt(aliasVarsStart), '<%className%>WriteOutput', true, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>
999 <%writeOutputVarsWithSplit("writeIntAliasVarsValues", protectedVars(vars.intAliasVars), stringInt(intAliasVarsStart), '<%className%>WriteOutput', true, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>
1000 <%writeOutputVarsWithSplit("writeBoolAliasVarsValues", protectedVars(vars.boolAliasVars), stringInt(boolAliasVarsStart), '<%className%>WriteOutput', true, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>
1001
1002
1003 >>
1004 end simulationWriteOutputAliasVarsCppFile;
1005
1006 49 template simulationMixedSystemCppFile(SimCode simCode, Text updateResidualFunctionsCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
1007 "Generates code for main cpp file for simulation target."
1008 ::=
1009 match simCode
1010 case SIMCODE(modelInfo = MODELINFO(__)) then
1011
1012 let getJacobianForIndexMethods = (jacobianMatrices |> JAC_MATRIX(columns=mat, matrixName=name, coloredCols=colorList, jacobianIndex=jacIndex) =>
1013 generateJacobianForIndex(simCode, mat, colorList, jacIndex, name, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
1014 ;separator="\n\n";empty)
1015 let classname = lastIdentOfPath(modelInfo.name)
1016 let type = getConfigString(MATRIX_FORMAT)
1017 let getDenseMatrix = match type
1018 case ("dense") then
1019 <<
1020 switch (index)
1021 {
1022 <%getJacobianForIndexMethods%>
1023 default:
1024 throw ModelicaSimulationError(MATH_FUNCTION,"Not supported jacobian matrix index");
1025 }
1026 >>
1027 case ("sparse") then
1028 'throw ModelicaSimulationError(MATH_FUNCTION,"Dense matrix is not activated");'
1029 else "A matrix type is not supported"
1030 end match
1031 let getSparseMatrix = match type
1032 case ("dense") then
1033 'throw ModelicaSimulationError(MATH_FUNCTION,"Sparse matrix is not activated");'
1034 case ("sparse") then
1035 <<
1036 switch (index)
1037 {
1038 <%getJacobianForIndexMethods%>
1039 default:
1040 throw ModelicaSimulationError(MATH_FUNCTION,"Not supported jacobian matrix index");
1041 }
1042 >>
1043 else "A matrix type is not supported"
1044 end match
1045
1046 let getDenseAMatrix = match type
1047 case ("dense") then
1048 <<
1049 return getAJacobian();
1050 >>
1051 case ("sparse") then
1052 'throw ModelicaSimulationError(MATH_FUNCTION,"Dense matrix is not activated");'
1053 else "A matrix type is not supported"
1054 end match
1055 let getSparseAMatrix = match type
1056 case ("dense") then
1057 'throw ModelicaSimulationError(MATH_FUNCTION,"Sparse matrix is not activated");'
1058 case ("sparse") then
1059 <<
1060 return getAJacobian();
1061 >>
1062 else "A matrix type is not supported"
1063 end match
1064
1065 let isJacobianSparse = match type
1066 case("dense") then
1067 'return false;'
1068 case("sparse") then
1069 'return true;'
1070 else "A matrix type is not supported"
1071 end match
1072
1073 let isAnalyticJacobianGenerated = if stringEq(getConfigString(GENERATE_DYNAMIC_JACOBIAN), "symbolic") then 'return true;' else 'return false;'
1074
1075 let statesetjacobian =
1076 (stateSets |> set hasindex i1 fromindex 0 => (match set
1077 case set as SES_STATESET(__) then
1078 match jacobianMatrix case JAC_MATRIX(matrixName=name) then
1079 match type
1080 case ("dense") then
1081 <<
1082 case <%i1%>:
1083 return get<%name%>Jacobian();
1084 break;
1085 >>
1086 case ("sparse") then
1087 <<
1088 case <%i1%>:
1089 throw ModelicaSimulationError(MATH_FUNCTION, "Dense matrix is not activated");'
1090 break;
1091 >>
1092 else "A matrix type is not supported"
1093 )
1094 ;separator="\n")
1095
1096
1097 let statesetsparsejacobian =
1098 (stateSets |> set hasindex i1 fromindex 0 => (match set
1099 case set as SES_STATESET(__) then
1100 match jacobianMatrix case JAC_MATRIX(matrixName=name) then
1101 match type
1102 case ("dense") then
1103 <<
1104 case <%i1%>:
1105 throw ModelicaSimulationError(MATH_FUNCTION, "Sparse matrix is not activated");
1106 break;
1107 >>
1108 case ("sparse") then
1109 <<
1110 case <%i1%>:
1111 return get<%name%>Jacobian();
1112 break;
1113 >>
1114 else "A matrix type is not supported"
1115 )
1116 ;separator="\n")
1117
1118 <<
1119 <%classname%>Mixed::<%classname%>Mixed(IGlobalSettings* globalSettings, shared_ptr<ISimObjects> simObjects)
1120 : <%classname%>Jacobian(globalSettings, simObjects)
1121 {
1122 }
1123
1124 <%classname%>Mixed::<%classname%>Mixed(<%classname%>Mixed& instance)
1125 : <%classname%>Jacobian(instance)
1126 {
1127 }
1128
1129 <%classname%>Mixed::~<%classname%>Mixed()
1130 {
1131 }
1132
1133 bool <%classname%>Mixed::isJacobianSparse(){
1134 <%isJacobianSparse%>
1135 }
1136
1137 bool <%classname%>Mixed::isAnalyticJacobianGenerated(){
1138 <%isAnalyticJacobianGenerated%>
1139 }
1140
1141 const matrix_t& <%classname%>Mixed::getJacobian( )
1142 {
1143 <%getDenseAMatrix%>
1144 }
1145
1146 const matrix_t& <%classname%>Mixed::getJacobian(unsigned int index)
1147 {
1148 <%getDenseMatrix%>
1149 }
1150 sparsematrix_t& <%classname%>Mixed::getSparseJacobian( )
1151 {
1152 <%getSparseAMatrix%>
1153 }
1154
1155 sparsematrix_t& <%classname%>Mixed::getSparseJacobian(unsigned int index)
1156 {
1157 <%getSparseMatrix%>
1158 }
1159
1160 const matrix_t& <%classname%>Mixed::getStateSetJacobian(unsigned int index)
1161 {
1162 switch (index)
1163 {
1164 <%statesetjacobian%>
1165 default:
1166 throw ModelicaSimulationError(MATH_FUNCTION,"Not supported statset index");
1167 }
1168 }
1169 sparsematrix_t& <%classname%>Mixed::getStateSetSparseJacobian(unsigned int index)
1170 {
1171 switch (index)
1172 {
1173 <%statesetsparsejacobian%>
1174 default:
1175 throw ModelicaSimulationError(MATH_FUNCTION,"Not supported statset index");
1176 }
1177 }
1178 <%handleSystemEvents(zeroCrossings,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)%>
1179
1180 void <%classname%>Mixed::saveAll()
1181 {
1182 return <%classname%>::saveAll();
1183 }
1184
1185 /*needed for colored jacobians*/
1186
1187 void <%classname%>Mixed::getAColorOfColumn(int* aSparsePatternColorCols, int size)
1188 {
1189 memcpy(aSparsePatternColorCols, _AColorOfColumn, size * sizeof(int));
1190 }
1191
1192 int <%classname%>Mixed::getAMaxColors()
1193 {
1194 return _AMaxColors;
1195 }
1196
1197 const std::vector<int>& <%classname%>Mixed::getAColumnsOfColor(int color)
1198 {
1199 return _AColumnsOfColor[color - 1];
1200 }
1201
1202 const std::vector<int>& <%classname%>Mixed::getADependenciesOfColumn(int idx)
1203 {
1204 return _ADependenciesOfColumn[idx];
1205 }
1206
1207 string <%classname%>Mixed::getModelName()
1208 {
1209 return "<%fileNamePrefix%>";
1210 }
1211
1212 <%updateResidualFunctionsCode%>
1213 >>
1214 end simulationMixedSystemCppFile;
1215
1216
1217 417 template generateJacobianForIndex(SimCode simCode, list<JacobianColumn> jacobianColumn, list<list<Integer>> colorList,Integer indexJacobian, String matrixName,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
1218 "Generates Matrices for Linear Model."
1219 ::=
1220 match simCode
1221 case SIMCODE(modelInfo = MODELINFO(__)) then
1222
1223 let classname = lastIdentOfPath(modelInfo.name)
1224 match jacobianColumn
1225 case {} then ""
1226 case _ then
1227 match colorList
1228 case {} then ""
1229 case _ then
1230 <<
1231 case <%indexJacobian%>:
1232 {
1233 return get<%matrixName%>Jacobian();
1234 }
1235 >>
1236
1237 /*
1238 (match indexColumn case "1" then ' _<%matrixName%>jacobian(<%crefWithoutIndexOperator(cref)%>$pDER<%matrixName%>$indexdiff,0) = _<%matrixName%>jac_y(0); //1 <%cref(cref)%>'
1239 else ' _<%matrixName%>jacobian(<%index0%>,<%crefWithoutIndexOperator(cref)%>$pDER<%matrixName%>$indexdiff) = _<%matrixName%>jac_y(<%crefWithoutIndexOperator(cref)%>$pDER<%matrixName%>$indexdiff);//2 <%cref(cref)%>'
1240
1241 */
1242 end generateJacobianForIndex;
1243
1244 49 template functionDimStateSets(list<SimCode.StateSet> stateSets,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
1245 "Generates functions in simulation file to initialize the stateset data."
1246 ::=
1247 match simCode
1248 case SIMCODE(modelInfo=MODELINFO(__)) then
1249 let classname = lastIdentOfPath(modelInfo.name)
1250 match stateSets
1251 case {} then
1252 <<
1253 int <%classname%>StateSelection::getDimStateSets() const
1254 {
1255 return 0;
1256 }
1257
1258 int <%classname%>StateSelection::getDimStates(unsigned int index) const
1259 {
1260 return 0;
1261 }
1262
1263 int <%classname%>StateSelection::getDimCanditates(unsigned int index) const
1264 {
1265 return 0;
1266 }
1267
1268 int <%classname%>StateSelection::getDimDummyStates(unsigned int index) const
1269 {
1270 return 0;
1271 }
1272 >>
1273 else
1274 <<
1275 int <%classname%>StateSelection::getDimStateSets() const
1276 {
1277 return <%listLength(stateSets)%>;
1278 }
1279
1280 int <%classname%>StateSelection::getDimStates(unsigned int index) const
1281 {
1282 switch (index)
1283 {
1284 <%(stateSets |> set hasindex i1 fromindex 0 => (match set
1285 case set as SES_STATESET(__) then
1286 <<
1287 case <%i1%>:
1288 return <%nStates%>;
1289
1290 >>
1291 )
1292 ;separator="\n")
1293 %>
1294 default:
1295 throw ModelicaSimulationError(MATH_FUNCTION,"Not supported statset index");
1296 }
1297
1298 }
1299
1300 int <%classname%>StateSelection::getDimCanditates(unsigned int index) const
1301 {
1302 switch (index)
1303 {
1304 <%(stateSets |> set hasindex i1 fromindex 0 => (match set
1305 case set as SES_STATESET(__) then
1306 <<
1307 case <%i1%>:
1308 return <%nCandidates%>;
1309 >>
1310 )
1311 ;separator="\n")
1312 %>
1313 default:
1314 throw ModelicaSimulationError(MATH_FUNCTION,"Not supported statset index");
1315 }
1316
1317 }
1318
1319 int <%classname%>StateSelection::getDimDummyStates(unsigned int index) const
1320 {
1321 switch (index)
1322 {
1323 <%(stateSets |> set hasindex i1 fromindex 0 => (match set
1324 case set as SES_STATESET(__) then
1325 <<
1326 case <%i1%>:
1327 return <%nCandidates%>-<%nStates%>;
1328
1329 >>
1330 )
1331 ;separator="\n")
1332 %>
1333 default:
1334 throw ModelicaSimulationError(MATH_FUNCTION,"Not supported statset index");
1335 }
1336
1337 }
1338 >>
1339 end functionDimStateSets;
1340
1341
1342 2 template createAssignArray(DAE.ComponentRef sourceOrTargetArrayCref, String sourceArrayName, String targetArrayName, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Boolean useFlatArrayNotationSource, Boolean useFlatArrayNotationTarget, String dimsArrayName)
1343 ::=
1344 match cref2simvar(sourceOrTargetArrayCref, simCode)
1345 case v as SIMVAR(numArrayElement=num) then
1346 '<%targetArrayName%>.assign(<%sourceArrayName%>);'
1347 end createAssignArray;
1348
1349 49 template functionStateSets(list<SimCode.StateSet> stateSets, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
1350 "Generates functions in simulation file to initialize the stateset data."
1351 ::=
1352 match simCode
1353 case SIMCODE(modelInfo=MODELINFO(__)) then
1354 let getAMatrix1 = (stateSets |> set hasindex i1 fromindex 0 => (match set
1355 case set as SES_STATESET(__) then
1356 let arrayname1 = arraycref(crA, useFlatArrayNotation)
1357 match nStates case 1 then
1358 'case <%i1%>:
1359 <%createAssignArray(crA, arrayname1, "A", simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, useFlatArrayNotation, false, "dims")%>
1360 return true;
1361 '
1362 else ""
1363 ) ;separator="\n")
1364
1365 let getAMatrix2 = (stateSets |> set hasindex i1 fromindex 0 => (match set
1366 case set as SES_STATESET(__) then
1367 let arrayname1 = arraycref(crA, useFlatArrayNotation)
1368 match nStates case 1 then "" else
1369 'case <%i1%>:
1370 <%createAssignArray(crA, arrayname1, "A", simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, useFlatArrayNotation, false, "dims")%>
1371 return true;
1372 '
1373
1374 ) ;separator="\n")
1375
1376 let setAMatrix1 = (stateSets |> set hasindex i1 fromindex 0 => (match set
1377 case set as SES_STATESET(__) then
1378 let arrayname1 = arraycref(crA, useFlatArrayNotation)
1379 match nStates case 1 then
1380 'case <%i1%>:
1381 <%createAssignArray(crA, "A", arrayname1, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, false, useFlatArrayNotation, "dims")%>
1382 break;
1383 '
1384 else ""
1385 ) ;separator="\n")
1386
1387 let setAMatrix2 = (stateSets |> set hasindex i1 fromindex 0 => (match set
1388 case set as SES_STATESET(__) then
1389 let arrayname1 = arraycref(crA, useFlatArrayNotation)
1390 match nStates case 1 then "" else
1391 'case <%i1%>:
1392 <%createAssignArray(crA, "A", arrayname1, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, false, useFlatArrayNotation, "dims")%>
1393 break;
1394 '
1395
1396 ) ;separator="\n")
1397
1398
1399
1400 let classname = lastIdentOfPath(modelInfo.name)
1401 match stateSets
1402 case {} then
1403 <<
1404 void <%classname%>StateSelection::getStates(unsigned int index, double* z)
1405 {
1406 }
1407
1408 void <%classname%>StateSelection::setStates(unsigned int index, const double* z)
1409 {
1410 }
1411
1412 void <%classname%>StateSelection::getStateCanditates(unsigned int index, double* z)
1413 {
1414
1415 }
1416
1417 bool <%classname%>StateSelection::getAMatrix(unsigned int index, DynArrayDim2<int> & A)
1418 {
1419 return false;
1420 }
1421
1422 bool <%classname%>StateSelection::getAMatrix(unsigned int index, DynArrayDim1<int> & A)
1423 {
1424 return false;
1425 }
1426
1427 void <%classname%>StateSelection::setAMatrix(unsigned int index, DynArrayDim2<int>& A)
1428 {
1429 }
1430
1431 void <%classname%>StateSelection::setAMatrix(unsigned int index, DynArrayDim1<int>& A)
1432 {
1433 }
1434
1435 void <%classname%>StateSelection::initialize()
1436 {
1437 }
1438 >>
1439 else
1440 let &varDeclsCref = buffer "" /*BUFD*/
1441 <<
1442 void <%classname%>StateSelection::getStates(unsigned int index,double* z)
1443 {
1444 switch (index)
1445 {
1446 <%(stateSets |> set hasindex i1 fromindex 0 => (match set
1447 case set as SES_STATESET(__) then
1448 <<
1449 case <%i1%>:
1450 <%(states |> s hasindex i2 fromindex 0 => 'z[<%i2%>]=<%cref1(s, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, contextOther, varDeclsCref, stateDerVectorName, useFlatArrayNotation)%>;' ;separator="\n")%>
1451 break;
1452 >>
1453 )
1454 ;separator="\n")
1455 %>
1456 default:
1457 throw ModelicaSimulationError(MATH_FUNCTION,"Not supported statset index");
1458 }
1459 }
1460
1461 void <%classname%>StateSelection::setStates(unsigned int index,const double* z)
1462 {
1463 switch (index)
1464 {
1465 <%(stateSets |> set hasindex i1 fromindex 0 => (match set
1466 case set as SES_STATESET(__) then
1467 <<
1468 case <%i1%>:
1469 <%(states |> s hasindex i2 fromindex 0 => '<%cref1(s, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, contextOther, varDeclsCref, stateDerVectorName, useFlatArrayNotation)%> = z[<%i2%>];' ;separator="\n")%>
1470 break;
1471 >>
1472 )
1473 ;separator="\n")
1474 %>
1475 default:
1476 throw ModelicaSimulationError(MATH_FUNCTION,"Not supported statset index");
1477 }
1478
1479 }
1480 void <%classname%>StateSelection::getStateCanditates(unsigned int index,double* z)
1481 {
1482
1483 switch (index)
1484 {
1485 <%(stateSets |> set hasindex i1 fromindex 0 => (match set
1486 case set as SES_STATESET(__) then
1487 <<
1488 case <%i1%>:
1489 <%(statescandidates |> cstate hasindex i2 fromindex 0 => 'z[<%i2%>]=<%cref1(cstate, simCode ,&extraFuncs ,&extraFuncsDecl, extraFuncsNamespace, contextOther, varDeclsCref, stateDerVectorName, useFlatArrayNotation)%>;' ;separator="\n")%>
1490 break;
1491 >>
1492 )
1493 ;separator="\n")
1494 %>
1495 default:
1496 throw ModelicaSimulationError(MATH_FUNCTION,"Not supported statset index");
1497 }
1498
1499 }
1500
1501
1502 bool <%classname%>StateSelection::getAMatrix(unsigned int index,DynArrayDim2<int> & A)
1503 {
1504 <%if useFlatArrayNotation then "std::vector<size_t> dims;" %>
1505 <%match getAMatrix2 case "" then 'return false;' else
1506 <<
1507 switch (index)
1508 {
1509 <%getAMatrix2%>
1510 default:
1511 throw ModelicaSimulationError(MATH_FUNCTION,"Not supported statset index");
1512 }
1513 >>
1514 %>
1515 }
1516 bool <%classname%>StateSelection::getAMatrix(unsigned int index,DynArrayDim1<int> & A)
1517 {
1518 <%if useFlatArrayNotation then "std::vector<size_t> dims;" %>
1519 <%match getAMatrix1 case "" then 'return false;' else
1520 <<
1521 switch (index)
1522 {
1523 <%getAMatrix1%>
1524 default:
1525 throw ModelicaSimulationError(MATH_FUNCTION,"Not supported statset index");
1526 }
1527 >>
1528 %>
1529 }
1530
1531 void <%classname%>StateSelection::setAMatrix(unsigned int index,DynArrayDim2<int> & A)
1532 {
1533 <%if useFlatArrayNotation then "std::vector<size_t> dims;" %>
1534 <%match setAMatrix2 case "" then '' else
1535 <<
1536 switch (index)
1537 {
1538 <%setAMatrix2%>
1539 default:
1540 throw ModelicaSimulationError(MATH_FUNCTION,"Not supported statset index");
1541 }
1542 >>
1543 %>
1544 }
1545 void <%classname%>StateSelection::setAMatrix(unsigned int index,DynArrayDim1<int> & A)
1546 {
1547 <%if useFlatArrayNotation then "std::vector<size_t> dims;" %>
1548 <%match setAMatrix1 case "" then '' else
1549 <<
1550 switch (index)
1551 {
1552 <%setAMatrix1%>
1553 default:
1554 throw ModelicaSimulationError(MATH_FUNCTION,"Not supported statset index");
1555 }
1556 >>
1557 %>
1558 }
1559 >>
1560 end functionStateSets;
1561
1562
1563 49 template simulationMainRunScript(SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, String preRunCommandLinux, String preRunCommandWindows, String execCommandLinux)
1564 "Generates code for header file for simulation target."
1565 ::=
1566 match simCode
1567 case SIMCODE(modelInfo = MODELINFO(__), makefileParams = MAKEFILE_PARAMS(__), simulationSettingsOpt = SOME(settings as SIMULATION_SETTINGS(__))) then
1568 let start = settings.startTime
1569 let end = settings.stopTime
1570 let stepsize = settings.stepSize
1571 let intervals = settings.numberOfIntervals
1572 let tol = settings.tolerance
1573 let solver = settings.method
1574 let moLib = makefileParams.compileDir
1575 let home = makefileParams.omhome
1576 let outputformat = settings.outputFormat
1577 let execParameters = '-S <%start%> -E <%end%> -H <%stepsize%> -G <%intervals%> -P <%outputformat%> -T <%tol%> -I <%solver%> -R "<%simulationLibDir(simulationCodeTarget(),simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)%>" -M "<%moLib%>" -r "<%simulationResults(Testsuite.isRunning(),simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)%>"'
1578 let outputParameter = if (stringEq(settings.outputFormat, "empty")) then "-O none" else ""
1579 let fileNamePrefixx = fileNamePrefix
1580
1581 let libFolder = simulationLibDir(simulationCodeTarget(), simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace)
1582 let libPaths = makefileParams.libPaths |> path => path; separator=";"
1583
1584 match makefileParams.platform
1585 case "linux32"
1586 case "linux64" then
1587 <<
1588 #!/bin/sh
1589 <%preRunCommandLinux%>
1590 <%execCommandLinux%> ./<%fileNamePrefixx%> <%execParameters%> <%outputParameter%> $*
1591 >>
1592 case "win32"
1593 case "win64" then
1594 let omPlatform = System.openModelicaPlatform()
1595 let msysPath = if intEq(-1, stringFind(omPlatform, "msvc")) then
1596 'if defined OMDEV set OMC_MSYS=%OMDEV%\\tools\\msys\\<%omPlatform%><%\n%>if not defined OMDEV set OMC_MSYS=<%home%>\\tools\\msys\\<%omPlatform%>'
1597 else ""
1598 let msysPathEntries = if intEq(-1, stringFind(omPlatform, "msvc")) then
1599 ';%OMC_MSYS%\\bin;%OMC_MSYS%\\lib\\gcc\\<%System.gccDumpMachine()%>\\<%System.gccVersion()%>;%OMC_MSYS%\\..\\usr\\bin'
1600 else ""
1601
1602 <<
1603 @echo off
1604 setlocal
1605 <%msysPath%>
1606 SET PATH=<%home%>/bin;<%libFolder%>;<%libPaths%><%msysPathEntries%>;%PATH%
1607 REM ::export PATH=<%libFolder%>:$PATH REPLACE C: with /C/
1608 <%preRunCommandWindows%>
1609 "<%moLib%>/<%fileNamePrefixx%>.exe" <%execParameters%> <%outputParameter%>
1610 endlocal
1611 >>
1612 end match
1613 end match
1614 end simulationMainRunScript;
1615
1616
1617 147 template simulationLibDir(String target, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
1618 "Generates code for header file for simulation target."
1619 ::=
1620 match simCode
1621 case SIMCODE(makefileParams=MAKEFILE_PARAMS(__)) then
1622 '<%makefileParams.omhome%>/lib/<%Config.targetTriple()%>/omc/cpp/'
1623 end match
1624 end simulationLibDir;
1625
1626
1627 98 template simulationResults(Boolean test, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
1628 "Generates code for header file for simulation target."
1629 ::=
1630 match simCode
1631 case SIMCODE(modelInfo=MODELINFO(__),makefileParams=MAKEFILE_PARAMS(__),simulationSettingsOpt = SOME(settings as SIMULATION_SETTINGS(__))) then
1632 let results = if test then "" else '<%makefileParams.compileDir%>'
1633 <<
1634 <%results%><%fileNamePrefix%>_res.<%settings.outputFormat%>
1635 >>
1636 end match
1637 end simulationResults;
1638
1639
1640 49 template simulationMainRunScriptSuffix(SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
1641 "Generates code for header file for simulation target."
1642 ::=
1643 match simCode
1644 case SIMCODE( makefileParams=params as MAKEFILE_PARAMS(__)) then
1645 (match params.platform
1646 case "win32"
1647 case "win64" then
1648 ".bat"
1649 else
1650 ".sh")
1651 end simulationMainRunScriptSuffix;
1652
1653 49 template simulationMainFile(String target, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace,
1654 String additionalIncludes, String additionalPreRunCommands, String additionalPostRunCommands,
1655 String numRealVars, String numIntVars, String numBoolVars, String numStringVars, String numPreVars)
1656 "Generates code for header file for simulation target."
1657 ::=
1658 match target
1659
1660 case "debugrt" then
1661 match simCode
1662 case SIMCODE(modelInfo = MODELINFO(__), makefileParams = MAKEFILE_PARAMS(__), simulationSettingsOpt = SOME(settings as SIMULATION_SETTINGS(__))) then
1663 let modelname = identOfPath(modelInfo.name)
1664 let start = settings.startTime
1665 let end = settings.stopTime
1666 let stepsize = settings.stepSize
1667 let intervals = settings.numberOfIntervals
1668 let tol = settings.tolerance
1669 let solver = settings.method
1670 let moLib = makefileParams.compileDir
1671 let home = makefileParams.omhome
1672 let &includeMeasure = buffer "" /*BUFD*/
1673 <<
1674 //Includes
1675
1676 #include <Core/ModelicaDefine.h>
1677 #include <Core/Modelica.h>
1678 #include <stdio.h>
1679 #include <string>
1680
1681 #include <Core/DataExchange/SimDouble.h>
1682 #include <Core/DataExchange/SimBoolean.h>
1683 #include <Core/SimController/ISimController.h>
1684 #include <Core/System/FactoryExport.h>
1685
1686 #define PATH string
1687
1688 #include <tchar.h>
1689 #include <fstream>
1690
1691 int _tmain(int argc, const _TCHAR* argv[])
1692 {
1693
1694 /*
1695 =============================================================================================================
1696 == Initialization of SimCore
1697 =============================================================================================================
1698 */
1699
1700
1701
1702
1703 //nur testweise
1704 std::map<std::string, std::string> opts;
1705 opts["-s"] = "<%start%>";
1706 opts["-e"] = "<%end%>";
1707 opts["-f"] = "<%stepsize%>";
1708 opts["-v"] = "<%intervals%>";
1709 opts["-y"] = "<%tol%>";
1710 opts["-i"] = "<%solver%>";
1711 opts["-r"] = "<%simulationLibDir(simulationCodeTarget(),simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)%>";
1712 opts["-M"] = "<%moLib%>";
1713 opts["-R"] = "<%simulationResults(Testsuite.isRunning(),simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)%>";
1714
1715
1716
1717
1718
1719 shared_ptr<OMCFactory> _factory = shared_ptr<OMCFactory>(new OMCFactory());
1720
1721 //SimController to start simulation
1722
1723 std::pair<shared_ptr<ISimController>, SimSettings> simulation = _factory->createSimulation(argc, argv, opts);
1724
1725 //create Modelica system
1726 shared_ptr<ISimObjects> simObjects= simulation.first->getSimObjects();
1727 weak_ptr<ISimData> simData = simObjects->LoadSimData("<%lastIdentOfPath(modelInfo.name)%>");
1728 weak_ptr<ISimVars> simVars = simObjects->LoadSimVars("<%lastIdentOfPath(modelInfo.name)%>",<%numRealVars%>,<%numIntVars%>,<%numBoolVars%>,<%numStringVars%>,<%numPreVars%>,<%numStatevars(modelInfo)%>,<%numStateVarIndex(modelInfo)%>);
1729 weak_ptr<IMixedSystem> system = simulation.first->LoadSystem("OMCpp<%fileNamePrefix%><%makefileParams.dllext%> ","<%lastIdentOfPath(modelInfo.name)%>");
1730
1731
1732 // Declare Input specify initial_values if needed!!!
1733 <%defineInputVars(simCode)%>
1734
1735 // Declare Output
1736 <%defineOutputVars(simCode)%>
1737
1738 LogSettings logsetting;
1739 SimSettings settings = {"RTEuler","","newton", 0.0, 100.0, 0.004, 0.0025, 10.0, 0.0001, "<%lastIdentOfPath(modelInfo.name)%>",0,OPT_NONE, logsetting};
1740 // Solver, nonlinearsolver starttime endtime stepsize lower limit upper limit tolerance
1741
1742
1743 try
1744 {
1745 simulation.first->StartVxWorks(settings, "<%lastIdentOfPath(modelInfo.name)%>");
1746 }
1747 catch(ModelicaSimulationError& ex)
1748 {
1749 throw std::runtime_error("error initialize");
1750 }
1751 std::fstream f;
1752 f.open("output_rt.csv", ios::out);
1753
1754
1755 for( int i = 0; i < 1000; i++)
1756 {
1757 try
1758 {
1759 simulation.first->calcOneStep();
1760 <%streamOutputVars(simCode)%>
1761 }
1762 catch(ModelicaSimulationError& ex)
1763 {
1764 f.close();
1765 throw std::runtime_error("error inside step");
1766 }
1767 }
1768 f.close();
1769 return 0;
1770 }
1771
1772
1773
1774 >>
1775 end match
1776 case "vxworks69" then
1777 match simCode
1778 case SIMCODE(modelInfo = MODELINFO(__), makefileParams = MAKEFILE_PARAMS(__), simulationSettingsOpt = SOME(settings as SIMULATION_SETTINGS(__))) then
1779 let modelname = identOfPath(modelInfo.name)
1780 let start = settings.startTime
1781 let end = settings.stopTime
1782 let stepsize = settings.stepSize
1783 let intervals = settings.numberOfIntervals
1784 let tol = settings.tolerance
1785 let solver = settings.method
1786 let moLib = makefileParams.compileDir
1787 let home = makefileParams.omhome
1788 let &includeMeasure = buffer "" /*BUFD*/
1789
1790 <<
1791 //Includes
1792
1793 #include <Core/ModelicaDefine.h>
1794 #include <Core/Modelica.h>
1795 #include <stdio.h>
1796 #include <string>
1797
1798 #include <Core/DataExchange/SimDouble.h>
1799 #include <Core/DataExchange/SimBoolean.h>
1800 #include <Core/SimController/ISimController.h>
1801 #include <Core/System/FactoryExport.h>
1802
1803 #define PATH string
1804
1805 #include <wvLib.h>
1806
1807 #include <util/bundle.h>
1808 #include <util/vxwHelper.h>
1809 #include <util/wchar16.h>
1810
1811 #include <mlpiApiLib.h>
1812 #include <mlpiSystemLib.h>
1813 #include <mlpiTaskLib.h>
1814 #include <mlpiLogicLib.h>
1815 #include <mlpiParameterLib.h>
1816
1817
1818
1819 extern "C" ISimController* createSimController(PATH library_path, PATH modelicasystem_path);
1820
1821 // functions implemented in this file
1822 extern "C" int initSimulation(ISimController* &controller, ISimData* &data, double cycletime);
1823 extern "C" int motionTriggered(ISimController* &controller, ISimData* &data);
1824 extern "C" void runSimulation(void);
1825 extern "C" int getMotionCycle(double &cycletime);
1826
1827 // Structs
1828 <%mlpiStructs(simCode)%>
1829
1830 extern "C" int getMotionCycle(double &cycletime)
1831 {
1832 MLPIHANDLE connection = MLPI_INVALIDHANDLE;
1833 MLPIRESULT result;
1834 ULONG cycletime_us = 0;
1835
1836 result = mlpiApiConnect(MLPI_LOCALHOST, &connection); // replace localhost with control IP to connect to another control
1837 if (MLPI_FAILED(result))
1838 {
1839 printf("\nERROR: failed to connect to MLPI. ErrorCode: 0x%08x", (unsigned) result);
1840 return result;
1841 }
1842
1843 result = mlpiParameterReadDataUlong(connection, 0, MLPI_SIDN_C(400), &cycletime_us);
1844 if (MLPI_FAILED(result))
1845 {
1846 printf("\nERROR: failed to connect to MLPI. ErrorCode: 0x%08x", (unsigned) result);
1847 return result;
1848 }
1849
1850 // Convert mu_s to s
1851 cycletime = (double)cycletime_us/(1e6);
1852
1853 result = mlpiApiDisconnect(&connection);
1854 {
1855 return result;
1856 }
1857 return 0;
1858 }
1859
1860 extern "C" void debugSimulation(void)
1861 {
1862 timespec delay;
1863 delay.tv_sec = 0;
1864 delay.tv_nsec = 10000000;
1865 ISimController* simController;
1866 ISimData* simData;
1867 double cycletime;
1868 getMotionCycle(cycletime);
1869
1870 initSimulation(simController, simData, 0.004);
1871 while(true)
1872 {
1873 try
1874 {
1875 nanosleep( &delay ,NULL);
1876 wvEvent(1,NULL,0);
1877 simController->calcOneStep();
1878 wvEvent(2,NULL,0);
1879 }
1880 catch(ModelicaSimulationError& ex)
1881 {
1882 break;
1883 }
1884 }
1885 delete simController;
1886
1887 }
1888
1889 extern "C" void runSimulation(void)
1890 {
1891 timespec delay;
1892 delay.tv_sec = 1;
1893 delay.tv_nsec = 0;
1894 nanosleep( &delay ,NULL);
1895 // Enable Telnet and Floatingpoint Unit
1896 enableTelnetPrintf();
1897 enableFpuSupport();
1898
1899 ISimController* simController;
1900 ISimData* simData;
1901
1902 double cycletime;
1903 getMotionCycle(cycletime);
1904
1905 initSimulation(simController, simData, cycletime);
1906 motionTriggered(simController, simData);
1907
1908 delete simController;
1909 }
1910
1911 extern "C" void spawnTask(void)
1912 {
1913 taskSpawn("<%lastIdentOfPath(modelInfo.name)%>", // name of task
1914 200, // priority of task
1915 VX_FP_TASK, // options (executes with the floating-point coprocessor)
1916 0x200000, // stacksize
1917 (FUNCPTR)& runSimulation, // entry point (function)
1918 0, // arguments 1
1919 0, // arguments 2
1920 0, // arguments 3
1921 0, // arguments 4
1922 0, // arguments 5
1923 0, // arguments 6
1924 0, // arguments 7
1925 0, // arguments 8
1926 0, // arguments 9
1927 0); // arguments 10
1928 }
1929
1930
1931 extern "C" int initSimulation(ISimController* &controller, ISimData* &data, double cycletime)
1932 {
1933 MLPIHANDLE connection = MLPI_INVALIDHANDLE;
1934 MLPIRESULT result;
1935
1936 // connect to API
1937 result = mlpiApiConnect(MLPI_LOCALHOST, &connection); // replace localhost with control IP to connect to another control
1938 if (MLPI_FAILED(result))
1939 {
1940 printf("\nERROR: failed to connect to MLPI. ErrorCode: 0x%08x", (unsigned) result);
1941 return result;
1942 }
1943
1944
1945 /*
1946 =============================================================================================================
1947 == Initialization of SimCore
1948 =============================================================================================================
1949 */
1950 wvEvent(0,NULL,0);
1951 printf("runSimulation started");
1952
1953 PATH libraries_path = "";
1954 PATH modelicaSystem_path = "";
1955 shared_ptr<VxWorksFactory> factory = shared_ptr<VxWorksFactory>(new VxWorksFactory(libraries_path, modelicaSystem_path));
1956 ISimController* sim_controller = createSimController(libraries_path, modelicaSystem_path);
1957 shared_ptr<ISimObjects> simObjects= sim_controller->getSimObjects();
1958 weak_ptr<ISimData> simData = simObjects->LoadSimData("<%lastIdentOfPath(modelInfo.name)%>");
1959 weak_ptr<ISimVars> simVars = simObjects->LoadSimVars("<%lastIdentOfPath(modelInfo.name)%>",<%numRealVars%>,<%numIntVars%>,<%numBoolVars%>,<%numStringVars%>,<%numPreVars%>,<%numStatevars(modelInfo)%>,<%numStateVarIndex(modelInfo)%>);
1960 weak_ptr<IMixedSystem> system = sim_controller->LoadSystem("<%lastIdentOfPath(modelInfo.name)%>","<%lastIdentOfPath(modelInfo.name)%>");
1961 shared_ptr<ISimData> simData_shared = simData.lock();
1962
1963 // Declare Input specify initial_values if needed!!!
1964 <%defineInputVars(simCode)%>
1965
1966 // Declare Output
1967 <%defineOutputVars(simCode)%>
1968
1969 LogSettings logsetting;
1970 SimSettings settings = {"RTEuler","","newton", 0.0, 100.0, cycletime, 0.0025, 10.0, 0.0001, "<%lastIdentOfPath(modelInfo.name)%>",0,OPT_NONE, logsetting};
1971 // Solver, nonlinearsolver starttime endtime stepsize lower limit upper limit tolerance
1972 try
1973 {
1974 sim_controller->StartVxWorks(settings, "<%lastIdentOfPath(modelInfo.name)%>");
1975 }
1976 catch(ModelicaSimulationError& ex)
1977 {
1978 string arg1 = string("Simulation failed for ") + settings.outputfile_name;
1979 string arg2 = ex.what();//ex.what();
1980 SIMULATION_ERROR arg3 = ex.getErrorID();
1981 std::string error = add_error_info(arg1,arg2,arg3);
1982 int lengthOfString = error.length();
1983 lengthOfString = (int) (lengthOfString / 60 ) + 1;
1984
1985
1986
1987 for (int i = 0 ; i < lengthOfString ; i++ )
1988 {
1989 result = mlpiSystemSetDiagnosis(connection, MLPI_DIAGNOSIS_ERROR_FATAL, 1, A2W16( error.substr(0 + i * 60 ,60 + i * 60).c_str()) );
1990 }
1991 return -1;
1992 }
1993
1994 printf("StartVxWorks finished");
1995 wvEvent(1,NULL,0);
1996 data = simData_shared.get();
1997 controller = sim_controller;
1998 return 0;
1999 }
2000
2001 extern "C" int motionTriggered(ISimController* &controller, ISimData* &data)
2002 {
2003 MLPIHANDLE connection = MLPI_INVALIDHANDLE;
2004
2005 MLPIRESULT result;
2006
2007 // connect to API
2008 result = mlpiApiConnect(MLPI_LOCALHOST, &connection); // replace localhost with control IP to connect to another control
2009 if (MLPI_FAILED(result))
2010 {
2011 printf("\nERROR: failed to connect to MLPI. ErrorCode: 0x%08x", (unsigned) result);
2012 return result;
2013 }
2014
2015
2016 //WCHAR16* application = L"Application";
2017 //MlpiApplicationState state = MLPI_STATE_NONE;
2018 //result = mlpiLogicGetStateOfApplication(connection, application, &state);
2019
2020 // Set Priority of Task
2021 result = mlpiTaskSetCurrentPriority(connection, MLPI_PRIORITY_HIGH_MAX);
2022 if (MLPI_FAILED(result))
2023 {
2024 printf("\ncall of MLPI function failed with 0x%08x!", (unsigned)result);
2025 return result;
2026 }
2027
2028 MlpiSystemMode mode;
2029 // run simulation
2030 while(true)
2031 {
2032 // Wait for motion interrupt
2033 result = mlpiTaskWaitForEvent(connection, MLPI_TASKEVENT_MOTION_CYCLE, MLPI_INFINITE);
2034
2035 //MLPIRESULT result = mlpiLogicGetStateOfApplication(connection, application, &state);
2036
2037 if (MLPI_FAILED(result))
2038 {
2039 printf("\ncall of MLPI function failed with 0x%08x!", (unsigned)result);
2040 return result;
2041 }
2042 // Get Current Mode of PLC
2043 result = mlpiSystemGetCurrentMode(connection, &mode);
2044 if (MLPI_FAILED(result))
2045 {
2046 printf("\ncall of MLPI function failed with 0x%08x!", (unsigned)result);
2047 return result;
2048 }
2049 //if(state == MLPI_STATE_STOP)
2050 //{
2051 // break;
2052 //}
2053
2054 //if(mode == MLPI_SYSTEMMODE_BB) //
2055 //{
2056 //Write input
2057 /* do something with the inputs!*/
2058 /*
2059 <%setInputVars(simCode)%>
2060 */
2061 try
2062 {
2063 controller->calcOneStep();
2064 }
2065 catch(ModelicaSimulationError& ex)
2066 {
2067 string arg1 = string("Simulation failed for ") + "<%lastIdentOfPath(modelInfo.name)%>";
2068 string arg2 = ex.what();//ex.what();
2069 SIMULATION_ERROR arg3 = ex.getErrorID();
2070 std::string error = add_error_info(arg1,arg2,arg3);
2071
2072 int lengthOfString = error.length();
2073 lengthOfString = (int) (lengthOfString / 60 ) + 1;
2074
2075 for (int i = 0 ; i < lengthOfString ; i++ )
2076 {
2077 result = mlpiSystemSetDiagnosis(connection, MLPI_DIAGNOSIS_ERROR_FATAL, 1, A2W16( error.substr(0 + i * 60 ,60 + i * 60).c_str()) );
2078 }
2079 return -1;
2080 }
2081 //Write output
2082 <%getOutputVars(simCode)%>
2083 //}
2084 }
2085
2086 result = mlpiApiDisconnect(&connection);
2087 {
2088 return result;
2089 }
2090
2091 return 0;
2092 }
2093
2094 extern "C" void <%modelname%>__Main(<%modelname%>_Main_struct* p)
2095 {
2096
2097 if (p->instance->controller != NULL)
2098 {
2099
2100 // Eingangswerte aus IndraWorks FB lesen
2101
2102 <%setMainFBInputVars(simCode)%>
2103
2104
2105 // Berechnung eines Controllersteps
2106
2107 try
2108 {
2109 p->instance->controller->calcOneStep();
2110 }
2111 catch(ModelicaSimulationError& ex)
2112 {
2113 MLPIHANDLE connection;
2114 MLPIRESULT result = mlpiApiConnect(MLPI_LOCALHOST, &connection); // replace localhost with control IP to connect to another control
2115 if (MLPI_FAILED(result))
2116 {
2117 printf("\nERROR: failed to connect to MLPI. ErrorCode: 0x%08x", (unsigned) result);
2118 }
2119
2120 string arg1 = string("Simulation failed for ") + "<%lastIdentOfPath(modelInfo.name)%>";
2121 string arg2 = ex.what();//ex.what();
2122 SIMULATION_ERROR arg3 = ex.getErrorID();
2123 std::string error = add_error_info(arg1,arg2,arg3);
2124
2125 int lengthOfString = error.length();
2126 lengthOfString = (int) (lengthOfString / 60 ) + 1;
2127
2128 for (int i = 0 ; i < lengthOfString ; i++ )
2129 {
2130 MLPIRESULT result = mlpiSystemSetDiagnosis(connection, MLPI_DIAGNOSIS_ERROR_FATAL, 1, A2W16( error.substr(0 + i * 60 ,60 + i * 60).c_str()) );
2131 }
2132 result = mlpiApiDisconnect(&connection);
2133 p->instance->bErrorOccured = TRUE;
2134 }
2135
2136 <%setMainFBOutputVars(simCode)%>
2137
2138 }
2139
2140 }
2141
2142 extern "C" void <%modelname%>__FB_Init(<%modelname%>_FB_Init_struct* p)
2143 {
2144 p->instance->bErrorOccured = FALSE;
2145 ISimController* simController;
2146 ISimData* simData;
2147
2148 //double cycletime = p->instance->cycletime;
2149 double cycletime;
2150 getMotionCycle(cycletime);
2151 int result = initSimulation(simController, simData, cycletime);
2152 if (result < 0)
2153 {
2154 p->instance->bErrorOccured = TRUE;
2155 }
2156
2157 p->instance->simdata = simData;
2158 p->instance->controller = simController;
2159 p->instance->bAlreadyInitialized = TRUE;
2160 p->FB_Init = TRUE;
2161 }
2162
2163 extern "C" void <%modelname%>__FB_Reinit(<%modelname%>_FB_Reinit_struct* p)
2164 {
2165 }
2166
2167 extern "C" void <%modelname%>__FB_Exit(<%modelname%>_FB_Exit_struct* p)
2168 {
2169 if (p->instance->controller)
2170 {
2171 delete p->instance->controller;
2172 }
2173 }
2174
2175
2176 BUNDLE_INFO_BEGIN(com_boschrexroth_<%modelname%>)
2177 BUNDLE_INFO_NAME (L"LoadLibraries_Bundle")
2178 BUNDLE_INFO_VENDOR (L"Bosch Rexroth AG")
2179 BUNDLE_INFO_DESCRIPTION (L"Load Libraries of SimCore Bundle")
2180 BUNDLE_INFO_VERSION (1,0,0,0,L"Release 20140114")
2181 BUNDLE_INFO_END(com_boschrexroth_<%modelname%>)
2182
2183 BUNDLE_EXPORT int com_boschrexroth_<%modelname%>_create(int param1, int param2, int param3)
2184 {
2185
2186 MLPIHANDLE connection = MLPI_INVALIDHANDLE;
2187
2188 // connect to API
2189 MLPIRESULT resultconnect = mlpiApiConnect(MLPI_LOCALHOST, &connection); // replace localhost with control IP to connect to another control
2190 if (MLPI_FAILED(resultconnect))
2191 {
2192 printf("\nERROR: failed to connect to MLPI. ErrorCode: 0x%08x", (unsigned) resultconnect);
2193 return resultconnect;
2194 }
2195
2196 WCHAR16 name[MLPI_APPLICATION_MAX_LENGTH_OF_POU_NAME] = L"<%modelname%>__Main";
2197 MLPIPOUFNCPTR function = (MLPIPOUFNCPTR) <%modelname%>__Main;
2198 MLPIRESULT result = mlpiLogicPouExtensionRegister(connection, name, function);
2199 if(MLPI_SUCCEEDED(result))
2200 {
2201 wcscpy16(name, L"<%modelname%>__FB_Init");
2202 function = (MLPIPOUFNCPTR) <%modelname%>__FB_Init;
2203 result = mlpiLogicPouExtensionRegister(connection, name, function);
2204 }
2205 if(MLPI_SUCCEEDED(result))
2206 {
2207 wcscpy16(name, L"<%modelname%>__FB_Reinit");
2208 function = (MLPIPOUFNCPTR) <%modelname%>__FB_Reinit;
2209 result = mlpiLogicPouExtensionRegister(connection, name, function);
2210 }
2211 if(MLPI_SUCCEEDED(result))
2212 {
2213 wcscpy16(name, L"<%modelname%>__FB_Exit");
2214 function = (MLPIPOUFNCPTR) <%modelname%>__FB_Exit;
2215 result = mlpiLogicPouExtensionRegister(connection, name, function);
2216 }
2217 mlpiApiDisconnect(&connection);
2218
2219 printf("\n###################################################################");
2220 printf("\n## onCreate #######################################################");
2221 printf("\n###################################################################");
2222 return 0;
2223 }
2224
2225 BUNDLE_EXPORT int com_boschrexroth_<%modelname%>_start(int param1, int param2, int param3)
2226 {
2227 //spawnTask();
2228 printf("\n###################################################################");
2229 printf("\n## onStart ########################################################");
2230 printf("\n###################################################################");
2231 return 0;
2232 }
2233
2234 BUNDLE_EXPORT int com_boschrexroth_<%modelname%>_stop(int param1, int param2, int param3)
2235 {
2236 printf("\n###################################################################");
2237 printf("\n## onStop #########################################################");
2238 printf("\n###################################################################");
2239 return 0;
2240 }
2241
2242 BUNDLE_EXPORT int com_boschrexroth_<%modelname%>_destroy(int param1, int param2, int param3)
2243 {
2244 printf("\n###################################################################");
2245 printf("\n## onDestroy ######################################################");
2246 printf("\n###################################################################");
2247 return 0;
2248 }
2249 >>
2250 end match
2251 else
2252 match simCode
2253 case SIMCODE(modelInfo=MODELINFO(__), makefileParams=MAKEFILE_PARAMS(__), simulationSettingsOpt = SOME(settings as SIMULATION_SETTINGS(__))) then
2254 let start = settings.startTime
2255 let end = settings.stopTime
2256 let stepsize = settings.stepSize
2257 let intervals = settings.numberOfIntervals
2258 let tol = settings.tolerance
2259 let solver = settings.method
2260 let moLib = makefileParams.compileDir
2261 let home = makefileParams.omhome
2262 let &includeMeasure = buffer "" /*BUFD*/
2263 let outputtype = settings.outputFormat
2264 let variableFilter = settings.variableFilter
2265 <<
2266 #include <Core/ModelicaDefine.h>
2267 #include <Core/Modelica.h>
2268 #include <Core/SimController/ISimController.h>
2269 #include <Core/System/FactoryExport.h>
2270 #include <Core/Utils/extension/logger.hpp>
2271
2272 <%
2273 match(getConfigString(PROFILING_LEVEL))
2274 case("none") then ''
2275 case("all_perf") then
2276 <<
2277 #ifdef USE_SCOREP
2278 #include <Core/Utils/extension/measure_time_scorep.hpp>
2279 #else
2280 #include <Core/Utils/extension/measure_time_papi.hpp>
2281 #endif
2282 >>
2283 case("all_stat") then
2284 <<
2285 #ifdef USE_SCOREP
2286 #include <Core/Utils/extension/measure_time_scorep.hpp>
2287 #else
2288 #include <Core/Utils/extension/measure_time_statistic.hpp>
2289 #endif
2290 >>
2291 else
2292 <<
2293 #ifdef USE_SCOREP
2294 #include <Core/Utils/extension/measure_time_scorep.hpp>
2295 #else
2296 #include <Core/Utils/extension/measure_time_rdtsc.hpp>
2297 #endif
2298 >>
2299 end match
2300 %>
2301 <%additionalIncludes%>
2302 #ifdef RUNTIME_STATIC_LINKING
2303 #include "OMCpp<%fileNamePrefix%>CalcHelperMain.cpp"
2304 #include <SimCoreFactory/OMCFactory/StaticOMCFactory.h>
2305 #endif
2306
2307 static long unsigned int getThreadNumber()
2308 {
2309 return 0;
2310 }
2311
2312 #if defined(_MSC_VER) || defined(__MINGW32__)
2313 #include <tchar.h>
2314 int _tmain(int argc, const _TCHAR* argv[])
2315 #else
2316 int main(int argc, const char* argv[])
2317 #endif
2318 {
2319 // default program options
2320 std::map<std::string, std::string> opts;
2321 opts["-S"] = "<%start%>";
2322 opts["-E"] = "<%end%>";
2323 opts["-H"] = "<%stepsize%>";
2324 opts["-G"] = "<%intervals%>";
2325 opts["-T"] = "<%tol%>";
2326 opts["-I"] = "<%solver%>";
2327 opts["-P"] = "<%outputtype%>";
2328 opts["-R"] = "<%simulationLibDir(simulationCodeTarget(), simCode, &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)%>";
2329 opts["-M"] = "<%moLib%>";
2330 opts["-F"] = "<%simulationResults(Testsuite.isRunning(), simCode, &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)%>";
2331 opts["-B"] = "<%variableFilter%>";
2332 opts["--solver-threads"] = "<%if(intGt(getConfigInt(NUM_PROC), 0)) then getConfigInt(NUM_PROC) else 1%>";
2333 <%if (stringEq(settings.outputFormat, "empty")) then 'opts["-O"] = "none";' else ""%>
2334 <%
2335 match(getConfigString(PROFILING_LEVEL))
2336 case("none") then '//no profiling used'
2337 case("all_perf") then
2338 <<
2339 #ifdef USE_SCOREP
2340 MeasureTimeScoreP::initialize();
2341 #else
2342 MeasureTimePAPI::initialize(getThreadNumber);
2343 #endif
2344 >>
2345 case("all_stat") then
2346 <<
2347 #ifdef USE_SCOREP
2348 MeasureTimeScoreP::initialize();
2349 #else
2350 MeasureTimeStatistic::initialize();
2351 #endif
2352 >>
2353 else
2354 <<
2355 #ifdef USE_SCOREP
2356 MeasureTimeScoreP::initialize();
2357 #else
2358 MeasureTimeRDTSC::initialize();
2359 #endif
2360 >>
2361 end match
2362 %>
2363 try
2364 {
2365 Logger::initialize();
2366 Logger::setEnabled(true);
2367 <%if boolNot(stringEq(getConfigString(PROFILING_LEVEL),"none")) then
2368 <<
2369 std::vector<MeasureTimeData*> *measureTimeArraySimulation = new std::vector<MeasureTimeData*>(size_t(2), NULL); //0 all, 1 setup
2370 (*measureTimeArraySimulation)[0] = new MeasureTimeData("all");
2371 (*measureTimeArraySimulation)[1] = new MeasureTimeData("setup");
2372 MeasureTimeValues *measuredSimStartValues, *measuredSimEndValues, *measuredSetupStartValues, *measuredSetupEndValues;
2373
2374 MeasureTime::addResultContentBlock("<%dotPath(modelInfo.name)%>","main",measureTimeArraySimulation);
2375
2376 measuredSimStartValues = MeasureTime::getZeroValues();
2377 measuredSimEndValues = MeasureTime::getZeroValues();
2378 measuredSetupStartValues = MeasureTime::getZeroValues();
2379 measuredSetupEndValues = MeasureTime::getZeroValues();
2380
2381 <%generateMeasureTimeStartCode('measuredSimStartValues', "all", "")%>
2382 <%generateMeasureTimeStartCode('measuredSetupStartValues', "setup", "")%>
2383
2384 >>
2385 %>
2386 <%additionalPreRunCommands%>
2387
2388 #ifdef RUNTIME_STATIC_LINKING
2389 shared_ptr<StaticOMCFactory> _factory = shared_ptr<StaticOMCFactory>(new StaticOMCFactory());
2390 #else
2391 shared_ptr<OMCFactory> _factory = shared_ptr<OMCFactory>(new OMCFactory());
2392 #endif //RUNTIME_STATIC_LINKING
2393 //SimController to start simulation
2394
2395 std::pair<shared_ptr<ISimController>, SimSettings> simulation = _factory->createSimulation(argc, argv, opts);
2396
2397 //create Modelica system
2398 shared_ptr<ISimObjects> simObjects= simulation.first->getSimObjects();
2399 weak_ptr<ISimData> simData = simObjects->LoadSimData("<%lastIdentOfPath(modelInfo.name)%>");
2400 weak_ptr<ISimVars> simVars = simObjects->LoadSimVars("<%lastIdentOfPath(modelInfo.name)%>",<%numRealVars%>,<%numIntVars%>,<%numBoolVars%>,<%numStringVars%>,<%numPreVars%>,<%numStatevars(modelInfo)%>,<%numStateVarIndex(modelInfo)%>);
2401 weak_ptr<IMixedSystem> system = simulation.first->LoadSystem("OMCpp<%fileNamePrefix%><%makefileParams.dllext%>","<%lastIdentOfPath(modelInfo.name)%>");
2402 <%if boolNot(stringEq(getConfigString(PROFILING_LEVEL),"none")) then
2403 <<
2404 <%generateMeasureTimeEndCode("measuredSetupStartValues", "measuredSetupEndValues", "(*measureTimeArraySimulation)[1]", "setup", "")%>
2405 >>
2406 %>
2407 <%if (Flags.getConfigBool(Flags.LABELED_REDUCTION)) then
2408 <<
2409 simulation.first->StartReduceDAE(simulation.second,"<%identOfPathDot(modelInfo.name)%>", "<%lastIdentOfPath(modelInfo.name)%>", <%Flags.getConfigBool(Flags.LOAD_MSL_MODEL)%>,<%Flags.getConfigBool(Flags.LOAD_PACKAGE_FILE)%>);
2410 >>
2411 else
2412 <<
2413 simulation.first->Start(simulation.second, "<%lastIdentOfPath(modelInfo.name)%>");
2414 >>
2415 %>
2416 <%if boolNot(stringEq(getConfigString(PROFILING_LEVEL),"none")) then
2417 <<
2418 <%generateMeasureTimeEndCode("measuredSimStartValues", "measuredSimEndValues", "(*measureTimeArraySimulation)[0]", "all", "")%>
2419 MeasureTime::getInstance()->writeToJson();
2420 MeasureTime::deinitialize();
2421
2422 delete measuredSimStartValues;
2423 delete measuredSimEndValues;
2424 delete measuredSetupStartValues;
2425 delete measuredSetupEndValues;
2426 >>
2427 %>
2428
2429 Logger::finalize();
2430 return 0;
2431 }
2432 catch (ModelicaSimulationError& ex)
2433 {
2434 if (!ex.isSuppressed())
2435 std::cerr << "Simulation stopped with error in " << error_id_string(ex.getErrorID()) << ": " << ex.what() << std::endl;
2436 Logger::finalize();
2437 return 1;
2438 }
2439 }
2440 >>
2441 end simulationMainFile;
2442
2443 ✗ template defineInputVars(SimCode simCode )
2444 ::=
2445 let &varDecls = buffer "" /*BUFD*/
2446 match simCode
2447 case SIMCODE(modelInfo = MODELINFO(__))
2448 then
2449 let inputs = match simCode
2450 case simCode as SIMCODE(__) then
2451 match modelInfo
2452 case MODELINFO(varInfo=VARINFO(__), vars=SIMVARS(__)) then
2453 let &varOptDecls = buffer "" /*BUFD*/
2454 let &optpreExp = buffer "" /*BUFD*/
2455
2456 let inputnames = vars.inputVars |> SIMVAR(__) hasindex i0 =>
2457 <<
2458 shared_ptr<SimDouble> sim_value_in<%cref(name, false)%>(new SimDouble(0.0)/*set start value here*/);
2459 simData_shared->Add("<%cref(name, false)%>", sim_value_in<%cref(name, false)%>);
2460 >>
2461 ;separator="\n"
2462
2463 <<
2464 <%inputnames%>
2465 >>
2466
2467 <<
2468 <%inputs%>
2469 >>
2470
2471 end defineInputVars;
2472
2473 ✗ template setInputVars(SimCode simCode )
2474 ::=
2475 let &varDecls = buffer "" /*BUFD*/
2476 match simCode
2477 case SIMCODE(modelInfo = MODELINFO(__))
2478 then
2479 let inputs = match simCode
2480 case simCode as SIMCODE(__) then
2481 match modelInfo
2482 case MODELINFO(varInfo=VARINFO(__), vars=SIMVARS(__)) then
2483 let &varOptDecls = buffer "" /*BUFD*/
2484 let &optpreExp = buffer "" /*BUFD*/
2485
2486 let inputnames = vars.inputVars |> SIMVAR(__) hasindex i0 =>
2487 <<
2488 dynamic_cast<SimDouble*>(data->Get("<%cref(name, false)%>"))->getValue() = //place variable here ;
2489 >>
2490 ;separator="\n"
2491
2492 <<
2493 <%inputnames%>
2494 >>
2495
2496 <<
2497 <%inputs%>
2498 >>
2499
2500 end setInputVars;
2501
2502 ✗ template setMainFBOutputVars(SimCode simCode )
2503 ::=
2504 let &varDecls = buffer "" /*BUFD*/
2505 match simCode
2506 case SIMCODE(modelInfo = MODELINFO(__))
2507 then
2508 let outputs = match simCode
2509 case simCode as SIMCODE(__) then
2510 match modelInfo
2511 case MODELINFO(varInfo=VARINFO(__), vars=SIMVARS(__)) then
2512 let &varOptDecls = buffer "" /*BUFD*/
2513 let &optpreExp = buffer "" /*BUFD*/
2514
2515 let outputnames = vars.outputVars |> SIMVAR(__) hasindex i0 =>
2516 <<
2517 p->instance-><%crefST(name, false)%> = dynamic_cast<SimDouble*>(p->instance->simdata->Get("<%cref(name, false)%>"))->getValue();
2518 >>
2519 ;separator="\n"
2520
2521 <<
2522 <%outputnames%>
2523 >>
2524
2525 <<
2526 <%outputs%>
2527 >>
2528
2529 end setMainFBOutputVars;
2530
2531 ✗ template setMainFBInputVars(SimCode simCode )
2532 ::=
2533 let &varDecls = buffer "" /*BUFD*/
2534 match simCode
2535 case SIMCODE(modelInfo = MODELINFO(__))
2536 then
2537 let inputs = match simCode
2538 case simCode as SIMCODE(__) then
2539 match modelInfo
2540 case MODELINFO(varInfo=VARINFO(__), vars=SIMVARS(__)) then
2541 let &varOptDecls = buffer "" /*BUFD*/
2542 let &optpreExp = buffer "" /*BUFD*/
2543
2544 let inputnames = vars.inputVars |> SIMVAR(__) hasindex i0 =>
2545 <<
2546 dynamic_cast<SimDouble*>(p->instance->simdata->Get("<%cref(name, false)%>"))->getValue() = p->instance-><%crefST(name, false)%>;
2547 >>
2548 ;separator="\n"
2549
2550 <<
2551 <%inputnames%>
2552 >>
2553
2554 <<
2555 <%inputs%>
2556 >>
2557
2558 end setMainFBInputVars;
2559
2560 ✗ template spsOutputVars(SimCode simCode )
2561 ::=
2562 let &varDecls = buffer "" /*BUFD*/
2563 match simCode
2564 case SIMCODE(modelInfo = MODELINFO(__))
2565 then
2566 let outputs = match simCode
2567 case simCode as SIMCODE(__) then
2568 match modelInfo
2569 case MODELINFO(varInfo=VARINFO(__), vars=SIMVARS(__)) then
2570 let &varOptDecls = buffer "" /*BUFD*/
2571 let &optpreExp = buffer "" /*BUFD*/
2572
2573 let outputnames = vars.outputVars |> SIMVAR(__) hasindex i0 =>
2574 <<
2575 <variable name= "<%crefST(name, false)%>">
2576 <type>
2577 <<%crefTypeST(name)%>/>
2578 </type>
2579 </variable>
2580 >>
2581 ;separator="\n"
2582
2583 <<
2584 <%outputnames%>
2585 >>
2586
2587 <<
2588 <%outputs%>
2589 >>
2590
2591 end spsOutputVars;
2592
2593 ✗ template spsInputVars(SimCode simCode )
2594 ::=
2595 let &varDecls = buffer "" /*BUFD*/
2596 match simCode
2597 case SIMCODE(modelInfo = MODELINFO(__))
2598 then
2599 let inputs = match simCode
2600 case simCode as SIMCODE(__) then
2601 match modelInfo
2602 case MODELINFO(varInfo=VARINFO(__), vars=SIMVARS(__)) then
2603 let &varOptDecls = buffer "" /*BUFD*/
2604 let &optpreExp = buffer "" /*BUFD*/
2605
2606 let inputnames = vars.inputVars |> SIMVAR(__) hasindex i0 =>
2607 <<
2608 <variable name= "<%crefST(name, false)%>">
2609 <type>
2610 <<%crefTypeST(name)%>/>
2611 </type>
2612 </variable>
2613 >>
2614 ;separator="\n"
2615
2616 <<
2617 <%inputnames%>
2618 >>
2619
2620 <<
2621 <%inputs%>
2622 >>
2623
2624 end spsInputVars;
2625
2626
2627 ✗ template mlpiOutputVars(SimCode simCode )
2628 ::=
2629 let &varDecls = buffer "" /*BUFD*/
2630 match simCode
2631 case SIMCODE(modelInfo = MODELINFO(__))
2632 then
2633 let outputs = match simCode
2634 case simCode as SIMCODE(__) then
2635 match modelInfo
2636 case MODELINFO(varInfo=VARINFO(__), vars=SIMVARS(__)) then
2637 let &varOptDecls = buffer "" /*BUFD*/
2638 let &optpreExp = buffer "" /*BUFD*/
2639
2640 let outputnames = vars.outputVars |> SIMVAR(__) hasindex i0 =>
2641 <<
2642 <%crefTypeMLPI(name)%> <%crefST(name, false)%>;
2643 >>
2644 ;separator="\n"
2645
2646 <<
2647 <%outputnames%>
2648 >>
2649
2650 <<
2651 <%outputs%>
2652 >>
2653
2654 end mlpiOutputVars;
2655
2656 ✗ template mlpiInputVars(SimCode simCode )
2657 ::=
2658 let &varDecls = buffer "" /*BUFD*/
2659 match simCode
2660 case SIMCODE(modelInfo = MODELINFO(__))
2661 then
2662 let inputs = match simCode
2663 case simCode as SIMCODE(__) then
2664 match modelInfo
2665 case MODELINFO(varInfo=VARINFO(__), vars=SIMVARS(__)) then
2666 let &varOptDecls = buffer "" /*BUFD*/
2667 let &optpreExp = buffer "" /*BUFD*/
2668
2669 let inputnames = vars.inputVars |> SIMVAR(__) hasindex i0 =>
2670 <<
2671 <%crefTypeMLPI(name)%> <%crefST(name, false)%>;
2672 >>
2673 ;separator="\n"
2674
2675 <<
2676 <%inputnames%>
2677 >>
2678
2679 <<
2680 <%inputs%>
2681 >>
2682 end mlpiInputVars;
2683
2684 ✗ template defineOutputVars(SimCode simCode )
2685 ::=
2686 let &varDecls = buffer "" /*BUFD*/
2687 match simCode
2688 case SIMCODE(modelInfo = MODELINFO(__))
2689 then
2690 let outputs = match simCode
2691 case simCode as SIMCODE(__) then
2692 match modelInfo
2693 case MODELINFO(varInfo=VARINFO(__), vars=SIMVARS(__)) then
2694 let &varOptDecls = buffer "" /*BUFD*/
2695 let &optpreExp = buffer "" /*BUFD*/
2696
2697 let outputnames = vars.outputVars |> SIMVAR(__) hasindex i0 =>
2698 <<
2699 shared_ptr<SimDouble> sim_value_out<%cref(name, false)%>(new SimDouble(0.0));
2700 simData_shared->Add("<%cref(name, false)%>", sim_value_out<%cref(name, false)%>);
2701 >>
2702 ;separator="\n"
2703
2704 <<
2705 <%outputnames%>
2706 >>
2707
2708 <<
2709 <%outputs%>
2710 >>
2711
2712 end defineOutputVars;
2713
2714
2715 ✗ template getOutputVars(SimCode simCode )
2716 ::=
2717 let &varDecls = buffer "" /*BUFD*/
2718 match simCode
2719 case SIMCODE(modelInfo = MODELINFO(__))
2720 then
2721 let outputs = match simCode
2722 case simCode as SIMCODE(__) then
2723 match modelInfo
2724 case MODELINFO(varInfo=VARINFO(__), vars=SIMVARS(__)) then
2725 let &varOptDecls = buffer "" /*BUFD*/
2726 let &optpreExp = buffer "" /*BUFD*/
2727
2728 let outputnames = vars.outputVars |> SIMVAR(__) hasindex i0 =>
2729 <<
2730 place variable here = dynamic_cast<SimDouble*>(data->Get("<%cref(name, false)%>"))->getValue();
2731 >>
2732 ;separator="\n"
2733
2734 <<
2735 /* do something with the outputs!*/
2736 /*
2737 <%outputnames%>
2738 */
2739 >>
2740
2741 <<
2742 <%outputs%>
2743 >>
2744
2745 end getOutputVars;
2746
2747 ✗ template streamOutputVars(SimCode simCode )
2748 ::=
2749 let &varDecls = buffer "" /*BUFD*/
2750 match simCode
2751 case SIMCODE(modelInfo = MODELINFO(__))
2752 then
2753 let outputs = match simCode
2754 case simCode as SIMCODE(__) then
2755 match modelInfo
2756 case MODELINFO(varInfo=VARINFO(__), vars=SIMVARS(__)) then
2757 let &varOptDecls = buffer "" /*BUFD*/
2758 let &optpreExp = buffer "" /*BUFD*/
2759
2760 let outputnames = vars.outputVars |> SIMVAR(__) hasindex i0 =>
2761 <<
2762 f << dynamic_cast<SimDouble*>(data->Get("<%cref(name, false)%>"))->getValue() << ";" ;
2763 >>
2764 ;separator="\n"
2765
2766 <<
2767 <%outputnames%>
2768
2769 f << endl;
2770 >>
2771
2772 <<
2773 <%outputs%>
2774 >>
2775
2776 end streamOutputVars;
2777
2778
2779 49 template calcHelperMainfile(SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
2780 ::=
2781 match simCode
2782 case SIMCODE(modelInfo = MODELINFO(__)) then
2783 <<
2784 /*****************************************************************************
2785 *
2786 * Helper file that includes all generated calculation files, except the alg loops.
2787 * This file is generated by the OpenModelica Compiler and produced to speed-up the compile time.
2788 *
2789 *****************************************************************************/
2790 #include <Core/ModelicaDefine.h>
2791 #include <Core/Modelica.h>
2792 #include <Core/System/FactoryExport.h>
2793 #include <Core/System/DiscreteEvents.h>
2794 #include <Core/System/EventHandling.h>
2795 #include <Core/DataExchange/XmlPropertyReader.h>
2796 #include <Core/Utils/extension/logger.hpp>
2797
2798 #include "OMCpp<%fileNamePrefix%>Types.h"
2799 #include "OMCpp<%fileNamePrefix%>Functions.h"
2800 #include "OMCpp<%fileNamePrefix%>.h"
2801
2802 #include "OMCpp<%fileNamePrefix%>Jacobian.h"
2803 #include "OMCpp<%fileNamePrefix%>Mixed.h"
2804 #include "OMCpp<%fileNamePrefix%>StateSelection.h"
2805 #include "OMCpp<%fileNamePrefix%>WriteOutput.h"
2806 #include "OMCpp<%fileNamePrefix%>Initialize.h"
2807
2808 #include "OMCpp<%fileNamePrefix%>AlgLoopMain.cpp"
2809 #include "OMCpp<%fileNamePrefix%>FactoryExport.cpp"
2810 #include "OMCpp<%fileNamePrefix%>Mixed.cpp"
2811 #include "OMCpp<%fileNamePrefix%>Functions.cpp"
2812 <%if(boolOr(Flags.isSet(Flags.HARDCODED_START_VALUES), Flags.isSet(Flags.GEN_DEBUG_SYMBOLS))) then
2813 <<
2814 #include "OMCpp<%fileNamePrefix%>InitializeParameter.cpp"
2815 #include "OMCpp<%fileNamePrefix%>InitializeAlgVars.cpp"
2816 >>
2817 %>
2818 #include "OMCpp<%fileNamePrefix%>Initialize.cpp"
2819 #include "OMCpp<%fileNamePrefix%>WriteOutput.cpp"
2820 #include "OMCpp<%fileNamePrefix%>Jacobian.cpp"
2821 #include "OMCpp<%fileNamePrefix%>StateSelection.cpp"
2822 #include "OMCpp<%fileNamePrefix%>.cpp"
2823 >>
2824 end calcHelperMainfile;
2825
2826 121 template algloopHeaderFile(SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace,SimEqSystem eq, Context context, Boolean useFlatArrayNotation)
2827 "Generates code for header file for simulation target."
2828 ::=
2829 match simCode
2830 case SIMCODE(__) then
2831 <<
2832 <%generateAlgloopHeaderInlcudeString(simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,context)%>
2833 <%generateAlgloopClassDeclarationCode(simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,eq,context,useFlatArrayNotation)%>
2834 >>
2835 end algloopHeaderFile;
2836
2837 49 template simulationFunctionsFile(SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, list<SimCodeFunction.Function> functions, list<Exp> literals,list<String> includes, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
2838 "Generates the content of the Cpp file for functions in the simulation case."
2839 ::=
2840 match simCode
2841 case SIMCODE(modelInfo=MODELINFO(__)) then
2842 <<
2843
2844 <%externalFunctionIncludes(includes)%>
2845
2846 //external functions
2847 extern "C" {
2848 <%externfunctionHeaderDefinition(functions)%>
2849 }
2850
2851 Functions::Functions(double& simTime, bool& initial, bool& terminate)
2852 : _simTime(simTime)
2853 , _initial(initial)
2854 , _terminate(terminate)
2855 {
2856 <%literals |> literal hasindex i0 fromindex 0 => literalExpConstImpl(literal,i0) ; separator="\n";empty%>
2857 }
2858
2859 Functions::~Functions()
2860 {
2861 }
2862
2863 void Functions::Assert(bool cond, string msg)
2864 {
2865 if (!cond)
2866 throw ModelicaSimulationError(MODEL_EQ_SYSTEM, msg);
2867 }
2868
2869 <%functionBodies(functions, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>
2870 /*extraFuncs*/
2871 <%extraFuncs%>
2872 >>
2873 end simulationFunctionsFile;
2874
2875
2876 4 template externalFunctionIncludes(list<String> includes)
2877 "Generates external includes part in function files."
2878 ::=
2879 if includes then
2880 <<
2881 #ifdef __cplusplus
2882 extern "C" {
2883 #endif
2884 <% (includes ;separator="\n") %>
2885 #ifdef __cplusplus
2886 }
2887 #endif
2888 >>
2889 end externalFunctionIncludes;
2890
2891 49 template simulationTypesHeaderFile(SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text& dummyElemTypeCreation, list<SimCodeFunction.Function> functions, list<Exp> literals, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
2892 ::=
2893 match simCode
2894 case SIMCODE(modelInfo=MODELINFO(__)) then
2895 <<
2896 #pragma once
2897
2898 /*****************************************************************************
2899 *
2900 * Simulation data types generated by the OpenModelica Compiler.
2901 *
2902 *****************************************************************************/
2903
2904 <%functionHeaderBodies1(functions,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, dummyElemTypeCreation, stateDerVectorName, useFlatArrayNotation)%>
2905 >>
2906 end simulationTypesHeaderFile;
2907
2908
2909 49 template simulationFunctionsHeaderFile(SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace,
2910 list<SimCodeFunction.Function> functions, list<Exp> literals, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
2911 ::=
2912 match simCode
2913
2914 case SIMCODE(modelInfo=MODELINFO(__)) then
2915 <<
2916 #pragma once
2917
2918 /*****************************************************************************
2919 *
2920 * Simulation code for FunctionCall functions generated by the OpenModelica Compiler.
2921 *
2922 *****************************************************************************/
2923
2924 class Functions
2925 {
2926 public:
2927 Functions(double& simTime, bool& initial, bool& terminate);
2928 ~Functions();
2929 //Modelica functions
2930 <%functionHeaderBodies2(functions,simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>
2931
2932 void Assert(bool cond, string msg);
2933
2934 //Literals
2935 <%literals |> literal hasindex i0 fromindex 0 => literalExpConst(literal,i0) ; separator="\n";empty%>
2936 private:
2937 //Function return variables
2938 <%functionHeaderBodies3(functions, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace)%>
2939 double& _simTime;
2940 bool& _terminate;
2941 bool& _initial;
2942 /*extraFuncs*/
2943 <%extraFuncsDecl%>
2944 };
2945 >>
2946 end simulationFunctionsHeaderFile;
2947
2948 ✗ template declFunParams( list<SimCodeFunction.Function> functions, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace,Text stateDerVectorName /*=__zDot*/)
2949 ::=
2950 let params = (functions |> fn => declFunParams2(fn, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,stateDerVectorName) ;separator="\n")
2951 <<
2952 <%params%>
2953 >>
2954 end declFunParams;
2955
2956 ✗ template declFunParams2(SimCodeFunction.Function fn, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace,Text stateDerVectorName /*=__zDot*/)
2957 ::=
2958 match fn
2959 case FUNCTION(__) then
2960 let params = (variableDeclarations |> var hasindex i1 fromindex 1 =>
2961 funParamDecl(var, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName) ; separator="" /* increase the counter! */)
2962 <<
2963 <%params%>
2964 >>
2965 end declFunParams2;
2966
2967 ✗ template funParamDecl(Variable var, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/)
2968 ::=
2969 match var
2970 case VARIABLE(__) then
2971 match kind
2972 case PARAM(__) then
2973 <<
2974 <%varType3(var, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace)%>
2975 >>
2976 else
2977 ''
2978 end match
2979 else
2980 ''
2981 end funParamDecl;
2982
2983
2984 ✗ template initParams1(list<SimCodeFunction.Function> functions, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/)
2985 ::=
2986 let &varDecls = buffer "" /*BUFD*/
2987 let &varInits = buffer "" /*BUFD*/
2988 let _ = (functions |> fn => initParams2(fn, varDecls, varInits, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName) ;separator="\n")
2989 <<
2990 <%varDecls%>
2991 <%varInits%>
2992 >>
2993 end initParams1;
2994
2995 ✗ template initParams2(SimCodeFunction.Function fn, Text &varDecls, Text &varInits, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/)
2996 ::=
2997 match fn
2998 case FUNCTION(__) then
2999 let _ = (variableDeclarations |> var hasindex i1 fromindex 1 =>
3000 paramInit2(var, "", i1, varDecls, varInits, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName) ; separator="" /* increase the counter! */)
3001 ""
3002 end initParams2;
3003
3004 ✗ template paramInit2(Variable var, String outStruct, Integer i, Text &varDecls, Text &varInits, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/)
3005 ::=
3006 match var
3007 case VARIABLE(__) then
3008 match kind
3009 case PARAM(__) then paramInit3(var, "", i, &varDecls, &varInits,simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, false)
3010 else ''
3011 else
3012 ''
3013 end paramInit2;
3014
3015
3016 ✗ template paramInit3(Variable var, String outStruct, Integer i, Text &varDecls, Text &varInits, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl,
3017 Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
3018 ::=
3019 match var
3020 case var as VARIABLE(__) then
3021 let varName = '<%contextCref(var.name, contextFunction, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>'
3022
3023 let instDimsInit = (instDims |> dim => daeDimension(dim, contextFunction, &varInits, &varDecls,simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation);separator=",")
3024
3025 if instDims then
3026 let testinstDimsInit = (instDims |> dim => testDaeDimension(dim);separator="")
3027 let temp = setDims(testinstDimsInit, varName , &varInits, instDimsInit)
3028
3029
3030 (match var.value
3031 case SOME(exp) then
3032
3033 let defaultValue = varDefaultValue(var, outStruct, i, varName, &varDecls, &varInits,simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
3034 let &varInits += defaultValue
3035 let var_name = if outStruct then
3036 '<%extVarName(var.name,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>' else
3037 '<%contextCref(var.name, contextFunction,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>'
3038 let defaultValue1 = '<%var_name%>.assign(<%daeExp(exp, contextFunction, &varInits , &varDecls,simCode , &extraFuncs , &extraFuncsDecl, stateDerVectorName, extraFuncsNamespace, useFlatArrayNotation)%>);<%\n%>'
3039 let &varInits += defaultValue1
3040 ""
3041 else
3042 let defaultValue = varDefaultValue(var, outStruct, i, varName, &varDecls, &varInits, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
3043 let &varInits += defaultValue
3044 ""
3045 )
3046 else
3047 (match var.value
3048 case SOME(exp) then
3049 let defaultValue = '<%contextCref(var.name,contextFunction,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%> = <%daeExp(exp, contextFunction, &varInits, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>;<%\n%>'
3050 let &varInits += defaultValue
3051 " "
3052 else
3053 "")
3054 case var as FUNCTION_PTR(__) then
3055 let &ignore = buffer ""
3056 let &varDecls += functionArg(var,&ignore)
3057 ""
3058
3059 end paramInit3;
3060
3061 ✗ template simulationMainDLLib(SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
3062 ::=
3063 match simCode
3064 case SIMCODE(makefileParams=MAKEFILE_PARAMS(__)) then
3065 <<
3066 <%simulationMainDLLib2(makefileParams.platform)%>
3067 >>
3068 end simulationMainDLLib;
3069
3070 ✗ template simulationMainDLLib2(String platform)
3071 ::=
3072 match platform
3073 case "linux32"
3074 case "linux64" then
3075 <<
3076 "-ldl"
3077 >>
3078 else
3079 ""
3080 end simulationMainDLLib2;
3081
3082
3083 49 template simulationMakefile(String target, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, String additionalLinkerFlags_GCC,
3084 String additionalLinkerFlags_MSVC, String additionalCFlags_GCC,
3085 String additionalCFlags_MSVC, Boolean compileForMPI)
3086 "Generates the contents of the makefile for the simulation case."
3087 ::=
3088 let &timeMeasureLink = buffer "" /*BUFD*/
3089 match getGeneralTarget(target)
3090 case "debugrt"
3091 case "msvc" then
3092 match simCode
3093 case SIMCODE(modelInfo=MODELINFO(__), makefileParams=MAKEFILE_PARAMS(__), simulationSettingsOpt = sopt) then
3094 let dirExtra = if modelInfo.directory then '/LIBPATH:"<%modelInfo.directory%>"' //else ""
3095 let libsStr = (makefileParams.libs |> lib => lib ;separator=" ")
3096 let &timeMeasureLink += "OMCppExtensionUtilities.lib"
3097 let extraCflags = match sopt case SOME(s as SIMULATION_SETTINGS(__)) then
3098 match s.method case "dassljac" then "/D_OMC_JACOBIAN "
3099 <<
3100 # Makefile generated by OpenModelica
3101 # Platform: <%makefileParams.platform%>
3102 #
3103 # For nmake. share/omc/scripts/Compile.bat sets the toolchain up and can
3104 # override CXX (OMC_TOOLCHAIN=clang-cl).
3105
3106 CXX=cl
3107 EXEEXT=.exe
3108 DLLEXT=.dll
3109 OMHOME=<%makefileParams.omhome%>
3110 OMLIB=$(OMHOME)/lib/<%Config.targetTriple()%>/omc
3111 OMCPPLIB=$(OMLIB)/cpp
3112 <% /* Don't use $(OMHOME) with !INCLUDE. NMAKE fails to evaluate it. */ %>
3113 !INCLUDE "<%makefileParams.omhome%>/include/omc/cpp/ModelicaConfig_msvc.inc"
3114 !INCLUDE "<%makefileParams.omhome%>/include/omc/cpp/ModelicaLibraryConfig_msvc.inc"
3115
3116 # SYSTEM_CFLAGS comes from ModelicaConfig_msvc.inc, so the generated code and
3117 # the runtime libraries agree on the defines shaping their shared structs.
3118 OMC_CFLAGS_OPTIMIZATION=/O2
3119 CFLAGS=/nologo /MD $(OMC_CFLAGS_OPTIMIZATION) /EHsc /fp:except /wd4068 /DNOMINMAX /DNO_INTERACTIVE_DEPENDENCY $(SYSTEM_CFLAGS) <%extraCflags%>/I"$(OMHOME)/include/omc/cpp/" /I. /I"$(UMFPACK_INCLUDE)" /I"$(SUNDIALS_INCLUDE)" <%makefileParams.includes ; separator=" "%>
3120 !IF "$(USE_LOGGER)" == "ON"
3121 CFLAGS=$(CFLAGS) /DUSE_LOGGER
3122 !ENDIF
3123 CPPFLAGS=$(CFLAGS)
3124
3125 LDSYSTEMFLAGS=/link /DLL /LIBPATH:"$(OMCPPLIB)" /LIBPATH:"$(OMLIB)" <%dirExtra%> <%libsStr%> OMCppSystem.lib OMCppModelicaUtilities.lib OMCppDataExchange.lib OMCppMath.lib OMCppOMCFactory.lib <%timeMeasureLink%> WSock32.lib Ws2_32.lib
3126 LDMAINFLAGS=/link /LIBPATH:"$(OMCPPLIB)" /LIBPATH:"$(OMLIB)" OMCppOMCFactory.lib OMCppModelicaUtilities.lib <%timeMeasureLink%> WSock32.lib Ws2_32.lib
3127
3128 FILEPREFIX=<%fileNamePrefix%>
3129 MAINFILE=OMCpp<%fileNamePrefix%>Main.cpp
3130 MAINOBJ=$(FILEPREFIX)$(EXEEXT)
3131 SYSTEMOBJ=OMCpp$(FILEPREFIX)$(DLLEXT)
3132 CALCHELPERMAINFILE=OMCpp<%fileNamePrefix%>CalcHelperMain.cpp
3133 ALGLOOPMAINFILE=OMCpp<%fileNamePrefix%>AlgLoopMain.cpp
3134 GENERATEDFILES=$(MAINFILE) $(CALCHELPERMAINFILE) $(ALGLOOPMAINFILE)
3135
3136 omc_main_target:
3137 <%\t%>$(CXX) /MP $(CFLAGS) /Fe$(SYSTEMOBJ) $(CALCHELPERMAINFILE) $(LDSYSTEMFLAGS)
3138 <%\t%>$(CXX) /MP $(CFLAGS) /Fe$(MAINOBJ) $(MAINFILE) $(LDMAINFLAGS)
3139
3140 clean:
3141 <%\t%>@del /q *.obj $(FILEPREFIX).pdb $(FILEPREFIX).ilk 2>NUL
3142 >>
3143 end match
3144 case "gcc" then
3145 match simCode
3146 case SIMCODE(modelInfo=MODELINFO(__), makefileParams=MAKEFILE_PARAMS(__), simulationSettingsOpt = sopt) then
3147 let dirExtra = if modelInfo.directory then '-L"<%modelInfo.directory%>"' //else ""
3148 let libsStr = (makefileParams.libs |> lib => lib ;separator=" ")
3149 let libsPos1 = if not dirExtra then libsStr //else ""
3150 let libsPos2 = if dirExtra then libsStr // else ""
3151 let staticLibs = '-Wl,--start-group -lOMCppOMCFactory_static -lOMCppSystem_static -lOMCppSimController_static -Wl,--end-group -lOMCppSimulationSettings_static -lOMCppDataExchange_static -lOMCppDgesvSolver_static -lOMCppNewton_static -lOMCppLinearSolver_static -lOMCppEuler_static -lOMCppKinsol_static -lOMCppCVode_static -lOMCppIDA_static -lOMCppSolver_static -lOMCppMath_static -lOMCppModelicaUtilities_static -lOMCppExtensionUtilities_static -L$(SUNDIALS_LIBS) -L$(UMFPACK_LIBS) -L$(LAPACK_LIBS)'
3152 let staticIncludes = '-I"$(SUNDIALS_INCLUDE)" -I"$(SUNDIALS_INCLUDE)/kinsol" -I"$(SUNDIALS_INCLUDE)/nvector"'
3153 let _extraCflags = match sopt case SOME(s as SIMULATION_SETTINGS(__)) then ""
3154 let extraCflags = '<%_extraCflags%><% if Flags.isSet(Flags.GEN_DEBUG_SYMBOLS) then " -g"%>'
3155 let papiLibs = ' -lOMCppExtensionUtilities_papi -lpapi'
3156 let CC = if (compileForMPI) then "mpicc" else '<%makefileParams.ccompiler%>'
3157 let CXX = if (compileForMPI) then "mpicxx" else '<%makefileParams.cxxcompiler%>'
3158 let extraCppFlags = (getConfigStringList(CPP_FLAGS) |> flag => '<%flag%>'; separator=" ")
3159 let MPIEnvVars = if (compileForMPI)
3160 then 'OMPI_MPICC=<%makefileParams.ccompiler%> <%\n%>OMPI_MPICXX=<%makefileParams.cxxcompiler%>' else ""
3161 <<
3162 # Makefile generated by OpenModelica
3163 OMHOME=<%if boolOr(stringEq(makefileParams.platform, "win32"),stringEq(makefileParams.platform, "win64")) then '$(OPENMODELICAHOME)' else makefileParams.omhome%>
3164 include $(OMHOME)/include/omc/cpp/ModelicaConfig_gcc.inc
3165 include $(OMHOME)/include/omc/cpp/ModelicaLibraryConfig_gcc.inc
3166
3167 # Simulations use -O0 by default
3168 SIM_OR_DYNLOAD_OPT_LEVEL=-O0
3169 CC=<%CC%>
3170 CXX=<%CXX%>
3171 RUNTIME_STATIC_LINKING=<%if(Flags.isSet(Flags.RUNTIME_STATIC_LINKING)) then 'ON' else 'OFF'%>
3172
3173 ifeq ($(CXX),g++)
3174 $(eval OPENMP_FLAGS=$(if $(findstring libomp,$(OPENMP_FLAGS)),-fopenmp,$(OPENMP_FLAGS)))
3175 endif
3176
3177 <%MPIEnvVars%>
3178
3179 EXEEXT=<%makefileParams.exeext%>
3180 DLLEXT=<%makefileParams.dllext%>
3181
3182 CFLAGS_COMMON=$(OPENMP_FLAGS) <%extraCflags%> -Winvalid-pch $(SYSTEM_CFLAGS) -I"$(SCOREP_INCLUDE)" -I"$(OMHOME)/include/omc/cpp/" -I. <%makefileParams.includes%> -I"$(UMFPACK_INCLUDE)" -I"$(SUNDIALS_INCLUDE)" <%makefileParams.includes ; separator=" "%> <%match sopt case SOME(s as SIMULATION_SETTINGS(__)) then s.cflags %> <%additionalCFlags_GCC%> <%extraCppFlags%>
3183
3184 ifeq ($(USE_SCOREP),ON)
3185 $(eval CC=scorep --user --nocompiler $(CC))
3186 $(eval CXX=scorep --user --nocompiler $(CXX))
3187 else
3188 $(eval CFLAGS_COMMON=$(CFLAGS_COMMON) -DMEASURETIME_PROFILEBLOCKS)
3189 endif
3190
3191 ifeq ($(USE_LOGGER),ON)
3192 $(eval CFLAGS_COMMON=$(CFLAGS_COMMON) -DUSE_LOGGER)
3193 endif
3194
3195 CFLAGS_DYNAMIC=$(CFLAGS_COMMON)
3196 CFLAGS_STATIC=$(CFLAGS_COMMON) <%staticIncludes%> -DRUNTIME_STATIC_LINKING -DENABLE_SUNDIALS_STATIC
3197
3198 MINGW_EXTRA_LIBS=<%if boolOr(stringEq(makefileParams.platform, "win32"),stringEq(makefileParams.platform, "win64")) then ' -lz -lhdf5 ' else ''%>
3199 MODELICA_EXTERNAL_LIBS=-L$(LAPACK_LIBS) $(LAPACK_LIBRARIES) $(MINGW_EXTRA_LIBS)
3200
3201 LDSYSTEMFLAGS_COMMON=-L"$(OMHOME)/lib/<%Config.targetTriple()%>/omc/cpp" $(BASE_LIB) <%additionalLinkerFlags_GCC%> $(SYSTEM_LDFLAGS) -Wl,-rpath,"$(OMHOME)/lib/<%Config.targetTriple()%>/omc/cpp" <%timeMeasureLink%> $(THREAD_LIBRARIES) $(LINUX_LIB_DL)
3202 LDMAINFLAGS_COMMON=-L"$(OMHOME)/lib/<%Config.targetTriple()%>/omc/cpp" -L"$(OMHOME)/bin" $(THREAD_LIBRARIES) $(LINUX_LIB_DL) <%additionalLinkerFlags_GCC%> $(SYSTEM_LDFLAGS) -Wl,-rpath,"$(OMHOME)/lib/<%Config.targetTriple()%>/omc/cpp" <%if boolOr(stringEq(makefileParams.platform, "win32"),stringEq(makefileParams.platform, "win64")) then ' -lwsock32 -lws2_32 ' else ''%>
3203
3204 ifeq ($(USE_PAPI),ON)
3205 $(eval LDMAINFLAGS_COMMON=$(LDMAINFLAGS_COMMON) <%papiLibs%>)
3206 $(eval LDSYSTEMFLAGS_COMMON=$(LDSYSTEMFLAGS_COMMON) <%papiLibs%>)
3207 endif
3208
3209 LDSYSTEMFLAGS_DYNAMIC=-lOMCppSystem -lOMCppModelicaUtilities -lOMCppDataExchange -lOMCppMath -lOMCppExtensionUtilities -lOMCppOMCFactory $(LDSYSTEMFLAGS_COMMON)
3210 LDSYSTEMFLAGS_STATIC=$(LDSYSTEMFLAGS_COMMON) <%staticLibs%>
3211
3212 LDMAINFLAGS_DYNAMIC= -lOMCppOMCFactory -lOMCppModelicaUtilities -lOMCppExtensionUtilities $(LDMAINFLAGS_COMMON)
3213 LDMAINFLAGS_STATIC=$(LDMAINFLAGS_COMMON) <%staticLibs%> $(SUNDIALS_LIBRARIES) $(LAPACK_LIBRARIES)
3214
3215 ifeq ($(RUNTIME_STATIC_LINKING),ON)
3216 $(eval CFLAGS=$(CFLAGS_STATIC))
3217 $(eval LDSYSTEMFLAGS=$(LDSYSTEMFLAGS_STATIC))
3218 $(eval LDMAINFLAGS=$(LDMAINFLAGS_STATIC))
3219 else
3220 $(eval CFLAGS=$(CFLAGS_DYNAMIC))
3221 $(eval LDSYSTEMFLAGS=$(LDSYSTEMFLAGS_DYNAMIC))
3222 $(eval LDMAINFLAGS=$(LDMAINFLAGS_DYNAMIC))
3223 endif
3224
3225 CPPFLAGS=$(CFLAGS)
3226
3227 SYSTEMFILE=OMCpp<%fileNamePrefix%><% if acceptMetaModelicaGrammar() then ".conv"%>.cpp
3228 MAINFILE = OMCpp<%fileNamePrefix%>Main.cpp
3229 MAINOBJ=<%fileNamePrefix%>$(EXEEXT)
3230 SYSTEMOBJ=OMCpp<%fileNamePrefix%>$(DLLEXT)
3231
3232 CALCHELPERMAINFILE=OMCpp<%fileNamePrefix%>CalcHelperMain.cpp
3233 ALGLOOPSMAINFILE=OMCpp<%fileNamePrefix%>AlgLoopMain.cpp
3234
3235 CPPFILES=$(CALCHELPERMAINFILE)
3236 OFILES=$(CPPFILES:.cpp=.o)
3237
3238 .PHONY: <%lastIdentOfPath(modelInfo.name)%> $(CPPFILES)
3239
3240 <%fileNamePrefix%>: $(MAINFILE) $(OFILES)
3241
3242 ifeq ($(RUNTIME_STATIC_LINKING),ON)
3243 <%\t%>$(CXX) $(CFLAGS) -I. -o $(MAINOBJ) $(MAINFILE) $(LDMAINFLAGS) $(MODELICA_EXTERNAL_LIBS)
3244 else
3245 <%\t%>$(CXX) $(OPENMP_FLAGS) -shared -o $(SYSTEMOBJ) $(OFILES) <%dirExtra%> <%libsPos1%> <%libsPos2%> $(LDSYSTEMFLAGS) $(MODELICA_EXTERNAL_LIBS)
3246 <%\t%>$(CXX) $(CFLAGS) -I. -o $(MAINOBJ) $(MAINFILE) $(LDMAINFLAGS)
3247 endif
3248
3249 <%if boolNot(boolOr(stringEq(makefileParams.platform, "win32"),stringEq(makefileParams.platform, "win64"))) then
3250 <<
3251 <%\t%>chmod +x <%fileNamePrefix%>.sh
3252 >>
3253 %>
3254 >>
3255 end match
3256 case "vxworks69" then
3257 match simCode
3258 case SIMCODE(modelInfo=MODELINFO(__), makefileParams=MAKEFILE_PARAMS(__), simulationSettingsOpt = sopt) then
3259 <<
3260 BUILD_SPEC=ATOMgnu
3261 DEBUG_MODE=1
3262 TRACE=1
3263
3264 MODEL_NAME = <%fileNamePrefix%>
3265
3266 OPENMODELICAHOME := $(subst \,/,$(OPENMODELICAHOME))
3267 WIND_HOME := $(subst \,/,$(WIND_HOME))
3268 WIND_BASE := $(WIND_HOME)/customBosch/vxworks-6.9
3269 export WIND_BASE
3270 MLPI_SDK_01 := $(subst \,/,$(MLPI_SDK_01))
3271
3272
3273 all : clean pre_build main_all post_build
3274
3275 _clean ::
3276 <%\t%>@echo "make: removing targets and objects of `pwd`"
3277
3278 TRACE=0
3279 TRACEON=$(TRACE:0=@)
3280 TRACE_FLAG=$(TRACEON:1=)
3281
3282 JOBS?=1
3283 TARGET_JOBS?=$(JOBS)
3284
3285 MAKEFILE := Makefile
3286
3287 FLEXIBLE_BUILD := 1
3288
3289 BUILD_SPEC = ATOMgnu
3290 DEBUG_MODE = 1
3291 ifeq ($(DEBUG_MODE),1)
3292 MODE_DIR := Debug
3293 else
3294 MODE_DIR := NonDebug
3295 endif
3296 OBJ_DIR := .
3297
3298
3299
3300
3301 #Global Build Macros
3302 PROJECT_TYPE = DKM
3303 DEFINES =
3304 EXPAND_DBG = 0
3305
3306
3307 #BuildSpec specific Build Macros
3308 VX_CPU_FAMILY = pentium
3309 CPU = ATOM
3310 TOOL_FAMILY = gnu
3311 TOOL = gnu
3312 TOOL_PATH = $(WIND_HOME)/gnu/4.3.3-vxworks-6.9/x86-win32/bin/
3313 CC_ARCH_SPEC = -march=atom -nostdlib -fno-builtin -fno-defer-pop -fno-implicit-fp
3314 VSB_DIR = $(WIND_BASE)/target/lib
3315 VSB_CONFIG_FILE = $(VSB_DIR)/h/config/vsbConfig.h
3316 LIBPATH =
3317 LIBS =
3318
3319 IDE_INCLUDES = -I$(WIND_BASE)/target/h -I$(WIND_BASE)/target/h/wrn/coreip -I$(MLPI_SDK_01)/mlpiCore/include -I$(OPENMODELICAHOME)/include/omc/cpp -I$(OPENMODELICAHOME)/include/omc/cpp/Core -I$(OPENMODELICAHOME)/include/omc/cpp
3320
3321 IDE_LIBRARIES = $(OPENMODELICAHOME)/lib/omc/cpp/vxworks/SimCore.a
3322
3323 IDE_DEFINES = -DCPU=_VX_$(CPU) -DTOOL_FAMILY=$(TOOL_FAMILY) -DTOOL=$(TOOL) -D_WRS_KERNEL -D_VSB_CONFIG_FILE=\"$(VSB_DIR)/h/config/vsbConfig.h\"
3324
3325
3326
3327 #BuildTool flags
3328 ifeq ($(DEBUG_MODE),1)
3329 DEBUGFLAGS_C-Compiler = -g
3330 DEBUGFLAGS_C++-Compiler = -g
3331 DEBUGFLAGS_Linker = -g
3332 DEBUGFLAGS_Partial-Image-Linker =
3333 DEBUGFLAGS_Librarian =
3334 DEBUGFLAGS_Assembler = -g
3335 else
3336 DEBUGFLAGS_C-Compiler = -O2
3337 DEBUGFLAGS_C++-Compiler = -O2
3338 DEBUGFLAGS_Linker = -O2
3339 DEBUGFLAGS_Partial-Image-Linker =
3340 DEBUGFLAGS_Librarian =
3341 DEBUGFLAGS_Assembler = -O2
3342 endif
3343
3344
3345 #Project Targets
3346 PROJECT_TARGETS = com.boschrexroth.$(MODEL_NAME)/$(MODE_DIR)/com.boschrexroth.$(MODEL_NAME).out \
3347 <%\t%>com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/com.boschrexroth.$(MODEL_NAME)_partialImage.o
3348
3349
3350 #Rules
3351
3352 # com.boschrexroth.$(MODEL_NAME)
3353 ifeq ($(DEBUG_MODE),1)
3354 com.boschrexroth.$(MODEL_NAME)/$(MODE_DIR)/% : DEBUGFLAGS_C-Compiler = -g
3355 com.boschrexroth.$(MODEL_NAME)/$(MODE_DIR)/% : DEBUGFLAGS_C++-Compiler = -g
3356 com.boschrexroth.$(MODEL_NAME)/$(MODE_DIR)/% : DEBUGFLAGS_Linker = -g
3357 com.boschrexroth.$(MODEL_NAME)/$(MODE_DIR)/% : DEBUGFLAGS_Partial-Image-Linker =
3358 com.boschrexroth.$(MODEL_NAME)/$(MODE_DIR)/% : DEBUGFLAGS_Librarian =
3359 com.boschrexroth.$(MODEL_NAME)/$(MODE_DIR)/% : DEBUGFLAGS_Assembler = -g
3360 else
3361 com.boschrexroth.$(MODEL_NAME)/$(MODE_DIR)/% : DEBUGFLAGS_C-Compiler = -O2
3362 com.boschrexroth.$(MODEL_NAME)/$(MODE_DIR)/% : DEBUGFLAGS_C++-Compiler = -O2
3363 com.boschrexroth.$(MODEL_NAME)/$(MODE_DIR)/% : DEBUGFLAGS_Linker = -O2
3364 com.boschrexroth.$(MODEL_NAME)/$(MODE_DIR)/% : DEBUGFLAGS_Partial-Image-Linker =
3365 com.boschrexroth.$(MODEL_NAME)/$(MODE_DIR)/% : DEBUGFLAGS_Librarian =
3366 com.boschrexroth.$(MODEL_NAME)/$(MODE_DIR)/% : DEBUGFLAGS_Assembler = -O2
3367 endif
3368 com.boschrexroth.$(MODEL_NAME)/$(MODE_DIR)/% : IDE_INCLUDES = -I$(WIND_BASE)/target/h -I$(WIND_BASE)/target/h/wrn/coreip -I$(MLPI_SDK_01)/mlpiCore/include -I$(OPENMODELICAHOME)/include/omc/cpp -I$(OPENMODELICAHOME)/include/omc/cpp/Core -I$(OPENMODELICAHOME)/include/omc/cpp
3369 com.boschrexroth.$(MODEL_NAME)/$(MODE_DIR)/% : IDE_LIBRARIES = $(OPENMODELICAHOME)/lib/omc/cpp/vxworks/SimCore.a
3370 com.boschrexroth.$(MODEL_NAME)/$(MODE_DIR)/% : IDE_DEFINES = -DCPU=_VX_$(CPU) -DTOOL_FAMILY=$(TOOL_FAMILY) -DTOOL=$(TOOL) -D_WRS_KERNEL -D_VSB_CONFIG_FILE=\"$(VSB_DIR)/h/config/vsbConfig.h\"
3371 com.boschrexroth.$(MODEL_NAME)/$(MODE_DIR)/% : PROJECT_TYPE = DKM
3372 com.boschrexroth.$(MODEL_NAME)/$(MODE_DIR)/% : DEFINES =
3373 com.boschrexroth.$(MODEL_NAME)/$(MODE_DIR)/% : EXPAND_DBG = 0
3374 com.boschrexroth.$(MODEL_NAME)/$(MODE_DIR)/% : VX_CPU_FAMILY = pentium
3375 com.boschrexroth.$(MODEL_NAME)/$(MODE_DIR)/% : CPU = ATOM
3376 com.boschrexroth.$(MODEL_NAME)/$(MODE_DIR)/% : TOOL_FAMILY = gnu
3377 com.boschrexroth.$(MODEL_NAME)/$(MODE_DIR)/% : TOOL = gnu
3378 com.boschrexroth.$(MODEL_NAME)/$(MODE_DIR)/% : TOOL_PATH = $(WIND_HOME)/gnu/4.3.3-vxworks-6.9/x86-win32/bin/
3379 com.boschrexroth.$(MODEL_NAME)/$(MODE_DIR)/% : CC_ARCH_SPEC = -march=atom -nostdlib -fno-builtin -fno-defer-pop -fno-implicit-fp
3380 com.boschrexroth.$(MODEL_NAME)/$(MODE_DIR)/% : VSB_DIR = $(WIND_BASE)/target/lib
3381 com.boschrexroth.$(MODEL_NAME)/$(MODE_DIR)/% : VSB_CONFIG_FILE = $(VSB_DIR)/h/config/vsbConfig.h
3382 com.boschrexroth.$(MODEL_NAME)/$(MODE_DIR)/% : LIBPATH =
3383 com.boschrexroth.$(MODEL_NAME)/$(MODE_DIR)/% : LIBS =
3384 com.boschrexroth.$(MODEL_NAME)/$(MODE_DIR)/% : OBJ_DIR := com.boschrexroth.$(MODEL_NAME)/$(MODE_DIR)
3385
3386 OBJECTS_com.boschrexroth.$(MODEL_NAME) = com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/com.boschrexroth.$(MODEL_NAME)_partialImage.o
3387
3388 ifeq ($(TARGET_JOBS),1)
3389 com.boschrexroth.$(MODEL_NAME)/$(MODE_DIR)/com.boschrexroth.$(MODEL_NAME).out : $(OBJECTS_com.boschrexroth.$(MODEL_NAME))
3390 <%\t%>$(TRACE_FLAG)if [ ! -d "`dirname "$@"`" ]; then mkdir -p "`dirname "$@"`"; fi;echo "building $@";rm -f "$@";nmpentium $(OBJECTS_com.boschrexroth.$(MODEL_NAME)) | $(WIND_HOME)/workbench-3.3/foundation/x86-win32/bin/tclsh $(WIND_BASE)/host/resource/hutils/tcl/munch.tcl -c pentium -tags $(VSB_DIR)/tags/pentium/ATOM/common/dkm.tags > $(OBJ_DIR)/ctdt.c; $(TOOL_PATH)ccpentium $(DEBUGFLAGS_Linker) $(CC_ARCH_SPEC) -fdollars-in-identifiers -Wall -Wsystem-headers $(ADDED_CFLAGS) $(IDE_INCLUDES) $(ADDED_INCLUDES) $(IDE_DEFINES) $(DEFINES) -o $(OBJ_DIR)/ctdt.o -c $(OBJ_DIR)/ctdt.c; $(TOOL_PATH)ccpentium -r -nostdlib -Wl,-X -T $(WIND_BASE)/target/h/tool/gnu/ldscripts/link.OUT -o "$@" $(OBJ_DIR)/ctdt.o $(OBJECTS_com.boschrexroth.$(MODEL_NAME)) $(IDE_LIBRARIES) $(LIBPATH) $(LIBS) $(ADDED_LIBPATH) $(ADDED_LIBS) && if [ "$(EXPAND_DBG)" = "1" ]; then plink "$@";fi
3391
3392 else
3393 com.boschrexroth.$(MODEL_NAME)/$(MODE_DIR)/com.boschrexroth.$(MODEL_NAME).out : com.boschrexroth.$(MODEL_NAME)/$(MODE_DIR)/com.boschrexroth.$(MODEL_NAME).out_jobs
3394
3395 endif
3396 com.boschrexroth.$(MODEL_NAME)/$(MODE_DIR)/com.boschrexroth.$(MODEL_NAME)_compile_file : $(FILE) ;
3397
3398 _clean :: com.boschrexroth.$(MODEL_NAME)/$(MODE_DIR)/com.boschrexroth.$(MODEL_NAME)_clean
3399
3400 com.boschrexroth.$(MODEL_NAME)/$(MODE_DIR)/com.boschrexroth.$(MODEL_NAME)_clean :
3401 <%\t%>$(TRACE_FLAG)if [ -d "com.boschrexroth.$(MODEL_NAME)" ]; then cd "com.boschrexroth.$(MODEL_NAME)"; rm -rf $(MODE_DIR); fi
3402
3403
3404 # com.boschrexroth.$(MODEL_NAME)_partialImage
3405 ifeq ($(DEBUG_MODE),1)
3406 com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/% : DEBUGFLAGS_C-Compiler = -g
3407 com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/% : DEBUGFLAGS_C++-Compiler = -g
3408 com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/% : DEBUGFLAGS_Linker = -g
3409 com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/% : DEBUGFLAGS_Partial-Image-Linker =
3410 com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/% : DEBUGFLAGS_Librarian =
3411 com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/% : DEBUGFLAGS_Assembler = -g
3412 else
3413 com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/% : DEBUGFLAGS_C-Compiler = -O2
3414 com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/% : DEBUGFLAGS_C++-Compiler = -O2
3415 com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/% : DEBUGFLAGS_Linker = -O2
3416 com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/% : DEBUGFLAGS_Partial-Image-Linker =
3417 com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/% : DEBUGFLAGS_Librarian =
3418 com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/% : DEBUGFLAGS_Assembler = -O2
3419 endif
3420 com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/% : IDE_INCLUDES = -I$(WIND_BASE)/target/h -I$(WIND_BASE)/target/h/wrn/coreip -I$(MLPI_SDK_01)/mlpiCore/include -I$(OPENMODELICAHOME)/include/omc/cpp -I$(OPENMODELICAHOME)/include/omc/cpp/Core -I$(OPENMODELICAHOME)/include/omc/cpp
3421 com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/% : IDE_LIBRARIES = $(OPENMODELICAHOME)/lib/omc/cpp/vxworks/SimCore.a
3422 com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/% : IDE_DEFINES = -DCPU=_VX_$(CPU) -DTOOL_FAMILY=$(TOOL_FAMILY) -DTOOL=$(TOOL) -D_WRS_KERNEL -D_VSB_CONFIG_FILE=\"$(VSB_DIR)/h/config/vsbConfig.h\"
3423 com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/% : PROJECT_TYPE = DKM
3424 com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/% : DEFINES =
3425 com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/% : EXPAND_DBG = 0
3426 com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/% : VX_CPU_FAMILY = pentium
3427 com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/% : CPU = ATOM
3428 com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/% : TOOL_FAMILY = gnu
3429 com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/% : TOOL = gnu
3430 com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/% : TOOL_PATH = $(WIND_HOME)/gnu/4.3.3-vxworks-6.9/x86-win32/bin/
3431 com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/% : CC_ARCH_SPEC = -march=atom -nostdlib -fno-builtin -fno-defer-pop -fno-implicit-fp
3432 com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/% : VSB_DIR = $(WIND_BASE)/target/lib
3433 com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/% : VSB_CONFIG_FILE = $(VSB_DIR)/h/config/vsbConfig.h
3434 com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/% : LIBPATH =
3435 com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/% : LIBS =
3436 com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/% : OBJ_DIR := com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)
3437
3438
3439
3440 com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/Objects/com.boschrexroth.$(MODEL_NAME)/OMCpp$(MODEL_NAME)CalcHelperMain.o : OMCpp$(MODEL_NAME)CalcHelperMain.cpp $(FORCE_FILE_BUILD)
3441 <%\t%>$(TRACE_FLAG)if [ ! -d "`dirname "$@"`" ]; then mkdir -p "`dirname "$@"`"; fi;echo "building $@"; $(TOOL_PATH)ccpentium $(DEBUGFLAGS_C++-Compiler) $(CC_ARCH_SPEC) -ansi -fno-zero-initialized-in-bss -Wall -Wsystem-headers -MD -MP $(IDE_DEFINES) $(DEFINES) $(ADDED_C++FLAGS) $(IDE_INCLUDES) $(ADDED_INCLUDES) -o "$@" -c "$<"
3442
3443
3444 com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/Objects/com.boschrexroth.$(MODEL_NAME)/OMCpp$(MODEL_NAME)Main.o : OMCpp$(MODEL_NAME)Main.cpp $(FORCE_FILE_BUILD)
3445 <%\t%>$(TRACE_FLAG)if [ ! -d "`dirname "$@"`" ]; then mkdir -p "`dirname "$@"`"; fi;echo "building $@"; $(TOOL_PATH)ccpentium $(DEBUGFLAGS_C++-Compiler) $(CC_ARCH_SPEC) -ansi -fno-zero-initialized-in-bss -Wall -Wsystem-headers -MD -MP $(IDE_DEFINES) $(DEFINES) $(ADDED_C++FLAGS) $(IDE_INCLUDES) $(ADDED_INCLUDES) -o "$@" -c "$<"
3446
3447
3448 OBJECTS_com.boschrexroth.$(MODEL_NAME)_partialImage = com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/Objects/com.boschrexroth.$(MODEL_NAME)/OMCpp$(MODEL_NAME)CalcHelperMain.o \
3449 <%\t%>com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/Objects/com.boschrexroth.$(MODEL_NAME)/OMCpp$(MODEL_NAME)Main.o
3450
3451 ifeq ($(TARGET_JOBS),1)
3452 com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/com.boschrexroth.$(MODEL_NAME)_partialImage.o : $(OBJECTS_com.boschrexroth.$(MODEL_NAME)_partialImage)
3453 <%\t%>$(TRACE_FLAG)if [ ! -d "`dirname "$@"`" ]; then mkdir -p "`dirname "$@"`"; fi;echo "building $@"; $(TOOL_PATH)ccpentium -r -nostdlib -Wl,-X -o "$@" $(OBJECTS_com.boschrexroth.$(MODEL_NAME)_partialImage) $(ADDED_OBJECTS) $(IDE_LIBRARIES) $(LIBPATH) $(LIBS) $(ADDED_LIBPATH) $(ADDED_LIBS) && if [ "$(EXPAND_DBG)" = "1" ]; then plink "$@";fi
3454
3455 else
3456 com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/com.boschrexroth.$(MODEL_NAME)_partialImage.o : com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/com.boschrexroth.$(MODEL_NAME)_partialImage.o_jobs
3457
3458 endif
3459 com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/com.boschrexroth.$(MODEL_NAME)_partialImage_compile_file : $(FILE) ;
3460
3461 _clean :: com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/com.boschrexroth.$(MODEL_NAME)_partialImage_clean
3462
3463 com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/com.boschrexroth.$(MODEL_NAME)_partialImage_clean :
3464 <%\t%>$(TRACE_FLAG)if [ -d "com.boschrexroth.$(MODEL_NAME)_partialImage" ]; then cd "com.boschrexroth.$(MODEL_NAME)_partialImage"; rm -rf $(MODE_DIR); fi
3465
3466 force :
3467
3468 TARGET_JOBS_RULE?=echo "Update the makefile template via File > Import > Build Settings : Update makefile template";exit 1
3469 %_jobs :
3470 <%\t%>$(TRACE_FLAG)$(TARGET_JOBS_RULE)
3471
3472 DEP_FILES := com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/Objects/com.boschrexroth.$(MODEL_NAME)/OMCpp$(MODEL_NAME)CalcHelperMain.d com.boschrexroth.$(MODEL_NAME)_partialImage/$(MODE_DIR)/Objects/com.boschrexroth.$(MODEL_NAME)/OMCpp$(MODEL_NAME)Main.d
3473 -include $(DEP_FILES)
3474
3475
3476 WIND_SCOPETOOLS_BASE := $(subst \,/,$(WIND_SCOPETOOLS_BASE))
3477
3478 clean_scopetools :
3479 <%\t%>$(TRACE_FLAG)rm -rf .coveragescope/db
3480
3481 CLEAN_STEP := clean_scopetools
3482
3483
3484 #-include *.makefile
3485
3486 #-include *.makefile
3487
3488 TARGET_JOBS_RULE=$(MAKE) -f $(MAKEFILE) --jobs $(TARGET_JOBS) $(MFLAGS) $* TARGET_JOBS=1
3489 ifeq ($(JOBS),1)
3490 main_all : external_build $(PROJECT_TARGETS)
3491 <%\t%>@echo "make: built targets of `pwd`"
3492 else
3493 main_all : external_build
3494 <%\t%>@$(MAKE) -f $(MAKEFILE) --jobs $(JOBS) $(MFLAGS) $(PROJECT_TARGETS) TARGET_JOBS=1 &&\
3495 <%\t%>echo "make: built targets of `pwd`"
3496 endif
3497
3498 # entry point for extending the build
3499 external_build ::
3500 <%\t%>@echo ""
3501
3502 # main entry point for pre processing prior to the build
3503 pre_build :: $(PRE_BUILD_STEP) generate_sources
3504 <%\t%>@echo ""
3505
3506 # entry point for generating sources prior to the build
3507 generate_sources ::
3508 <%\t%>@echo ""
3509
3510 # main entry point for post processing after the build
3511 post_build :: $(POST_BUILD_STEP) deploy_output
3512 <%\t%>@echo ""
3513
3514 # entry point for deploying output after the build
3515 deploy_output ::
3516 <%\t%>@echo ""
3517
3518 clean :: external_clean $(CLEAN_STEP) _clean
3519
3520 # entry point for extending the build clean
3521 external_clean ::
3522 <%\t%>@echo ""
3523
3524 >>
3525 end match
3526 end simulationMakefile;
3527
3528
3529
3530 49 template simulationCppFile(SimCode simCode, Context context, Text updateFunctionsCode, Text indexForUndefinedReferencesReal, Text indexForUndefinedReferencesInt, Text indexForUndefinedReferencesBool,
3531 Text indexForUndefinedReferencesString, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text additionalConstructorVarDefs, Text additionalConstructorBodyStatements,
3532 Text additionalDestructorBodyStatements, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
3533 /* Generates the c++ code for the model class, containing all equations, the evaluate methods for the time integration algorithm and variable definitions.
3534 Some getter and setter functions are generated as well. Additional functions can be passed via the "extraFuncs" variable. */
3535 ::=
3536 match simCode
3537 case SIMCODE(modelInfo = MODELINFO(__)) then
3538 let className = lastIdentOfPath(modelInfo.name)
3539 let &additionalConstructorVarDefsBuffer = buffer additionalConstructorVarDefs
3540 let memberVariableInitialize = memberVariableInitialize(modelInfo, varToArrayIndexMapping, indexForUndefinedReferencesReal, indexForUndefinedReferencesInt, indexForUndefinedReferencesBool, indexForUndefinedReferencesString, Flags.isSet(Flags.GEN_DEBUG_SYMBOLS), useFlatArrayNotation, additionalConstructorVarDefsBuffer, extraFuncsDecl)
3541 let constVariableInitialize = simulationInitFile(simCode, &extraFuncsDecl, stateDerVectorName, false)
3542 <<
3543 #if defined(__TRICORE__) || defined(__vxworks)
3544 #include <Core/DataExchange/SimDouble.h>
3545 #endif
3546
3547 /* Constructor */
3548 <%className%>::<%className%>(IGlobalSettings* globalSettings, shared_ptr<ISimObjects> simObjects)
3549 : SystemDefaultImplementation(globalSettings, simObjects, "<%className%>")
3550 , _algLoopSolverFactory(simObjects->getAlgLoopSolverFactory())
3551 , _pointerToRealVars(getSimVars()->getRealVarsVector())
3552 , _pointerToIntVars(getSimVars()->getIntVarsVector())
3553 , _pointerToBoolVars(getSimVars()->getBoolVarsVector())
3554 , _pointerToStringVars(getSimVars()->getStringVarsVector())
3555 <%additionalConstructorVarDefsBuffer%>
3556 {
3557 <%generateSimulationCppConstructorContent(simCode, context, extraFuncs, extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>
3558 <%additionalConstructorBodyStatements%>
3559 }
3560
3561 <%className%>::<%className%>(<%className%> &instance) : SystemDefaultImplementation(instance)
3562 , _algLoopSolverFactory(instance.getAlgLoopSolverFactory())
3563 , _pointerToRealVars(getSimVars()->getRealVarsVector())
3564 , _pointerToIntVars(getSimVars()->getIntVarsVector())
3565 , _pointerToBoolVars(getSimVars()->getBoolVarsVector())
3566 , _pointerToStringVars(getSimVars()->getStringVarsVector())
3567 <%additionalConstructorVarDefsBuffer%>
3568 {
3569 <%generateSimulationCppConstructorContent(simCode, context, extraFuncs, extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>
3570 <%additionalConstructorBodyStatements%>
3571 }
3572
3573 /* Destructor */
3574 <%className%>::~<%className%>()
3575 {
3576 deleteObjects();
3577 <%if boolNot(stringEq(getConfigString(PROFILING_LEVEL),"none")) then
3578 let numOfEqs = SimCodeCodegenUtil.getMaxSimEqSystemIndex(simCode)
3579 <<
3580 #ifdef MEASURETIME_PROFILEBLOCKS
3581 delete measuredProfileBlockStartValues;
3582 delete measuredProfileBlockEndValues;
3583 #endif //MEASURETIME_PROFILEBLOCKS
3584
3585 #ifdef MEASURETIME_MODELFUNCTIONS
3586 delete measuredFunctionStartValues;
3587 delete measuredFunctionEndValues;
3588 #endif //MEASURETIME_MODELFUNCTIONS
3589 >>
3590 %>
3591 <%additionalDestructorBodyStatements%>
3592 }
3593
3594 void <%className%>::deleteObjects()
3595 {
3596
3597 if(_functions != NULL)
3598 delete _functions;
3599
3600
3601 }
3602
3603 shared_ptr<IAlgLoopSolverFactory> <%className%>::getAlgLoopSolverFactory()
3604 {
3605 return _algLoopSolverFactory;
3606 }
3607
3608 <%updateFunctionsCode%>
3609
3610 <%DefaultImplementationCode(simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>
3611
3612 <%checkForDiscreteEvents(discreteModelVars, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>
3613 <%giveZeroFunc1(zeroCrossings, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>
3614
3615 <%setConditions(simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace)%>
3616 <%getConditions(simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace)%>
3617 <%isConsistent(simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace)%>
3618
3619 <%generateStepCompleted(listAppend(allEquations, initialEquations), simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>
3620 <%generateStepStarted(listAppend(allEquations, initialEquations), simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, useFlatArrayNotation)%>
3621
3622 <%generateRestoreOldValues(listAppend(allEquations, initialEquations), simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>
3623 <%generateRestoreNewValues(listAppend(allEquations, initialEquations), simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>
3624
3625 <%generateDimTimeEvent(listAppend(allEquations, initialEquations),simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace)%>
3626 <%generateGetTimeEvenData(listAppend(allEquations, initialEquations), simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace)%>
3627 <%generateTimeEvent(timeEvents, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>
3628
3629 <%isODE(simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace)%>
3630 <%dimZeroFunc(simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace)%>
3631
3632 <%getCondition(zeroCrossings, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>
3633
3634 <%saveAll(modelInfo, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>
3635
3636 <%labeledDAE(modelInfo.labels, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>
3637 <%giveVariables(modelInfo, context, useFlatArrayNotation, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace,stateDerVectorName)%>
3638
3639 <%memberVariableInitialize%>
3640 <%constVariableInitialize%>
3641 <%extraFuncs%>
3642 >>
3643 end simulationCppFile;
3644
3645 ✗ template partitionInfoInit(Integer numPartitions, Integer numStates, list<Integer> stateActivators)
3646 ::=
3647 let stateActs = (stateActivators |> act hasindex i0 => '_stateActivator[<%i0%>] = <%intSub(act,1)%>;' ;separator="\n")
3648 <<
3649 //partitioning of the system, all partitions are active at t0
3650 _dimPartitions = <%numPartitions%>;
3651 _partitionActivation = new bool[_dimPartitions]();
3652 memset(_partitionActivation,true,_dimPartitions*sizeof(bool));
3653 _stateActivator = new int[<%numStates%>]();
3654 <%stateActs%>
3655 >>
3656 end partitionInfoInit;
3657
3658 98 template generateSimulationCppConstructorContent(SimCode simCode, Context context, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
3659 ::=
3660 match simCode
3661 case SIMCODE(modelInfo = MODELINFO(varInfo = vi as VARINFO(__)), partitionData=PARTITIONDATA(__)) then
3662 let className = lastIdentOfPath(modelInfo.name)
3663 let partitionInit = if Flags.isSet(Flags.MULTIRATE_PARTITION) then partitionInfoInit(partitionData.numPartitions, vi.numStateVars, partitionData.stateToActivators) else ""
3664 <<
3665 initConstVals();
3666 initStateVars();
3667 initDerivativeVars();
3668 initAlgVars();
3669 initDiscreteAlgVars();
3670 initIntAlgVars();
3671 initBoolAlgVars();
3672 initStringAlgVars();
3673 initParameterRealVars();
3674 initParameterIntVars();
3675 initParameterBoolVars();
3676 initParameterStringVars();
3677 initAliasRealVars();
3678 initAliasIntVars();
3679 initAliasBoolVars();
3680 initAliasStringVars();
3681
3682 //Number of equations
3683 <%dimension1(simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)%>
3684 _dimZeroFunc = <%zeroCrossLength(simCode)%>;
3685 _dimClock = <%listLength(getSubPartitions(clockedPartitions))%>;
3686 // simplified treatment of clocks in model as time events
3687 _dimTimeEvent = <%timeEventLength(simCode)%> + _dimClock;
3688 _timeEventData = (std::pair<double,double>*)calloc(_dimTimeEvent, sizeof(std::pair<double,double>));
3689 _currTimeEvents = (double*)malloc(_dimTimeEvent*sizeof(double));
3690
3691 //Number of residues
3692 _event_handling= shared_ptr<EventHandling>(new EventHandling());
3693 <%if boolNot(stringEq(getConfigString(PROFILING_LEVEL),"none")) then
3694 let numOfEqs = SimCodeCodegenUtil.getMaxSimEqSystemIndex(simCode)
3695 <<
3696 #ifdef MEASURETIME_PROFILEBLOCKS
3697 measureTimeProfileBlocksArray = new std::vector<MeasureTimeData*>(size_t(<%numOfEqs%>), NULL);
3698 for(int i = 0; i < <%numOfEqs%>; i++)
3699 {
3700 ostringstream ss;
3701 ss << (i+1);
3702 (*measureTimeProfileBlocksArray)[i] = new MeasureTimeData(ss.str());
3703 }
3704
3705 MeasureTime::addResultContentBlock("<%dotPath(modelInfo.name)%>","profileBlocks",measureTimeProfileBlocksArray);
3706 measuredProfileBlockStartValues = MeasureTime::getZeroValues();
3707 measuredProfileBlockEndValues = MeasureTime::getZeroValues();
3708 #endif //MEASURETIME_PROFILEBLOCKS
3709
3710 #ifdef MEASURETIME_MODELFUNCTIONS
3711 measureTimeFunctionsArray = new std::vector<MeasureTimeData*>(size_t(5), NULL); //1 evaluateODE ; 2 evaluateAll; 3 writeOutput; 4 handleTimeEvents; 5 evaluateZeroFuncs
3712 MeasureTime::addResultContentBlock("<%dotPath(modelInfo.name)%>","functions",measureTimeFunctionsArray);
3713 (*measureTimeFunctionsArray)[0] = new MeasureTimeData("evaluateODE");
3714 (*measureTimeFunctionsArray)[1] = new MeasureTimeData("evaluateAll");
3715 (*measureTimeFunctionsArray)[2] = new MeasureTimeData("writeOutput");
3716 (*measureTimeFunctionsArray)[3] = new MeasureTimeData("handleTimeEvents");
3717 (*measureTimeFunctionsArray)[4] = new MeasureTimeData("evaluateZeroFuncs");
3718
3719 measuredFunctionStartValues = MeasureTime::getZeroValues();
3720 measuredFunctionEndValues = MeasureTime::getZeroValues();
3721 #endif //MEASURETIME_MODELFUNCTIONS
3722 >>
3723 %>
3724
3725 <%partitionInit%>
3726
3727 //Initialize the state vector
3728 SystemDefaultImplementation::initialize();
3729 //Instantiate auxiliary object for event handling functionality
3730 //_event_handling.getCondition = boost::bind(&<%className%>::getCondition, this, _1);
3731
3732 //Todo: reindex all arrays removed // arrayReindex(modelInfo,useFlatArrayNotation)
3733
3734 _functions = new Functions(_simTime, _initial, _terminate);
3735 >>
3736
3737 end generateSimulationCppConstructorContent;
3738
3739
3740 121 template algloopCppFile(SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace,SimEqSystem eq, Context context, Integer clockIndex, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
3741 "Generates code for main cpp file for algloop system ."
3742 ::=
3743 match simCode
3744 case SIMCODE(modelInfo = MODELINFO(__)) then
3745 let modelname = lastIdentOfPath(modelInfo.name)
3746 let filename = fileNamePrefix
3747 let modelfilename = match context case ALGLOOP_CONTEXT(genInitialisation=false,genJacobian=true) then '<%filename%>Jacobian' else '<%filename%>'
3748 let &varDecls = buffer ""
3749 let &arrayInit = buffer ""
3750 let constructorParams = constructorParamAlgloop(modelInfo, useFlatArrayNotation)
3751 let iniAlgloopParamas = initAlgloopParams(modelInfo,arrayInit,useFlatArrayNotation)
3752 let systemname = match context case ALGLOOP_CONTEXT(genInitialisation=false,genJacobian=true) then '<%modelname%>Jacobian' else '<%modelname%>'
3753 match eq
3754 case SES_LINEAR(lSystem = ls as LINEARSYSTEM(__)) then
3755 <<
3756
3757 <%modelname%>Algloop<%ls.index%>::<%modelname%>Algloop<%ls.index%>(<%systemname%>* system, double* z, double* zDot, bool* conditions, shared_ptr<DiscreteEvents> discrete_events)
3758 : LinearAlgLoopDefaultImplementation()
3759 , _system(system)
3760 , __z(z)
3761 , __zDot(zDot)
3762
3763 <% match eq
3764 case SES_LINEAR(lSystem = ls as LINEARSYSTEM(__)) then
3765 let size = listLength(ls.vars)
3766 let nonzeros = listLength(ls.simJac)
3767 let type = getConfigString(MATRIX_FORMAT)
3768
3769 let inits = match type
3770 case ("dense") then
3771 <<
3772 ,__A(ublas::zero_matrix<double>(<%size%>,<%size%>))
3773 , _conditions(conditions)
3774 , _discrete_events(discrete_events)
3775 , _functions(system->_functions)
3776 {
3777 _useSparseFormat=false;
3778 <%initAlgloopDimension(eq,varDecls)%>
3779
3780 >>
3781 case ("sparse") then
3782 <<
3783 ,__A(<%size%>,<%size%>,<%nonzeros%>)
3784 , _conditions(conditions)
3785 , _discrete_events(discrete_events)
3786 , _functions(system->_functions)
3787 {
3788 _useSparseFormat=true;
3789 <%initAlgloopDimension(eq,varDecls)%>
3790
3791 >>
3792 else "A matrix type is not supported"
3793 end match
3794 <<
3795 <%inits%>
3796 _dimZeroFunc = <%zeroCrossLength(simCode)%>;
3797 <%initAlgloopVarAttributes(eq, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, context, stateDerVectorName, useFlatArrayNotation)%>
3798 >>
3799 %>
3800 }
3801
3802 <%modelname%>Algloop<%ls.index%>::~<%modelname%>Algloop<%ls.index%>()
3803 {
3804
3805 }
3806 int <%modelname%>Algloop<%ls.index%>::getDimZeroFunc() const
3807 {
3808 return _dimZeroFunc;
3809 }
3810 bool <%modelname%>Algloop<%ls.index%>::getFreeVariablesLock()
3811 {
3812 return _system->getFreeVariablesLock();
3813 }
3814
3815 bool <%modelname%>Algloop<%ls.index%>::getUseSparseFormat()
3816 {
3817 return LinearAlgLoopDefaultImplementation::getUseSparseFormat();
3818 }
3819
3820 void <%modelname%>Algloop<%ls.index%>::setUseSparseFormat(bool value)
3821 {
3822 LinearAlgLoopDefaultImplementation::setUseSparseFormat(value);
3823 }
3824
3825 <%algloopRHSCode(simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,eq)%>
3826 /*<%if Flags.isSet(Flags.WRITE_TO_BUFFER) then algloopResiduals(simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,eq) else algloopRHSCode(simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,eq)%>*/
3827 <%initAlgloop(simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, eq, context, clockIndex, stateDerVectorName, useFlatArrayNotation)%>
3828 <%queryDensity(simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,eq,context, useFlatArrayNotation)%>
3829 <%updateAlgloop(simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, eq, context, clockIndex, stateDerVectorName, useFlatArrayNotation)%>
3830 <%updateAlgloopNonLinear(simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, eq, context, clockIndex, stateDerVectorName, useFlatArrayNotation)%>
3831
3832 <%LinearalgloopDefaultImplementationCode(simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, eq, context, stateDerVectorName, useFlatArrayNotation)%>
3833 <%getAMatrixCode(simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,eq)%>
3834 <%isLinearTearingCode(simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,eq)%>
3835
3836 /*Additional member functions*/
3837 <%extraFuncs%>
3838 >>
3839
3840 case SES_NONLINEAR(nlSystem = nls as NONLINEARSYSTEM(__)) then
3841 <<
3842
3843 <%modelname%>Algloop<%nls.index%>::<%modelname%>Algloop<%nls.index%>(<%systemname%>* system, double* z, double* zDot, bool* conditions, shared_ptr<DiscreteEvents> discrete_events)
3844 : NonLinearAlgLoopDefaultImplementation()
3845 , _system(system)
3846 , __z(z)
3847 , __zDot(zDot)
3848 , _conditions(conditions)
3849 , _discrete_events(discrete_events)
3850 , _functions(system->_functions)
3851
3852 {
3853 _useSparseFormat=false;
3854 <%initAlgloopDimension(eq,varDecls)%>
3855 _dimZeroFunc = <%zeroCrossLength(simCode)%>;
3856 <%initAlgloopVarAttributes(eq, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, context, stateDerVectorName, useFlatArrayNotation)%>
3857 }
3858
3859 <%modelname%>Algloop<%nls.index%>::~<%modelname%>Algloop<%nls.index%>()
3860 {
3861
3862 }
3863
3864 int <%modelname%>Algloop<%nls.index%>::getDimZeroFunc() const
3865 {
3866 return _dimZeroFunc;
3867 }
3868
3869 bool <%modelname%>Algloop<%nls.index%>::getUseSparseFormat()
3870 {
3871 return NonLinearAlgLoopDefaultImplementation::getUseSparseFormat();
3872 }
3873
3874 void <%modelname%>Algloop<%nls.index%>::setUseSparseFormat(bool value)
3875 {
3876 NonLinearAlgLoopDefaultImplementation::setUseSparseFormat(value);
3877 }
3878 <%algloopRHSCode(simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,eq)%>
3879 /*<%if Flags.isSet(Flags.WRITE_TO_BUFFER) then algloopResiduals(simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,eq) else algloopRHSCode(simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,eq)%>*/
3880 <%initAlgloop(simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, eq, context, clockIndex, stateDerVectorName, useFlatArrayNotation)%>
3881
3882 <%queryDensity(simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,eq,context, useFlatArrayNotation)%>
3883 <%updateAlgloop(simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, eq, context, clockIndex, stateDerVectorName, useFlatArrayNotation)%>
3884 <%updateAlgloopNonLinear(simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, eq, context, clockIndex, stateDerVectorName, useFlatArrayNotation)%>
3885
3886 <%NonLinearalgloopDefaultImplementationCode(simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, eq, context, stateDerVectorName, useFlatArrayNotation)%>
3887 <%getAMatrixCode(simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,eq)%>
3888 <%isLinearTearingCode(simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,eq)%>
3889
3890 /*Additional member functions*/
3891 <%extraFuncs%>
3892 >>
3893 end algloopCppFile;
3894
3895 121 template queryDensity(SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, SimEqSystem eqn, Context context,Boolean useFlatArrayNotation)
3896 ::=
3897 match simCode
3898 case SIMCODE(modelInfo = MODELINFO(__)) then
3899 let modelname = lastIdentOfPath(modelInfo.name)
3900 match eqn
3901 case eq as SES_NONLINEAR(nlSystem = nls as NONLINEARSYSTEM(__)) then
3902 <<
3903 float <%modelname%>Algloop<%nls.index%>::queryDensity()
3904 {
3905 return -1.;
3906 }
3907 >>
3908 case eq as SES_LINEAR(lSystem = ls as LINEARSYSTEM(__)) then
3909 match ls.jacobianMatrix
3910 case SOME(__) then
3911 <<
3912 float <%modelname%>Algloop<%ls.index%>::queryDensity()
3913 {
3914 return -1.;
3915 }
3916 >>
3917 else
3918 let size=listLength(ls.simJac)
3919 <<
3920 float <%modelname%>Algloop<%ls.index%>::queryDensity()
3921 {
3922 return 100.*<%size%>./_dimAEq/_dimAEq;
3923 }
3924 >>
3925 end queryDensity;
3926
3927
3928 121 template updateAlgloop(SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, SimEqSystem eqn, Context context, Integer clockIndex, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
3929 ::=
3930 match simCode
3931 case SIMCODE(modelInfo = MODELINFO(__)) then
3932 let modelname = lastIdentOfPath(modelInfo.name)
3933 match eqn
3934 /*case eq as SES_NONLINEAR(__) then
3935 <<
3936 void <%modelname%>Algloop<%index%>::evaluate()
3937 {
3938 if(_useSparseFormat)
3939 evaluate(NULL);
3940 else
3941 evaluate(NULL);
3942 }
3943 >>
3944 */
3945 case SES_LINEAR(lSystem = ls as LINEARSYSTEM(__)) then
3946 let type = getConfigString(MATRIX_FORMAT)
3947 match ls.jacobianMatrix
3948 case SOME(__) then
3949 let &varDecls = buffer "" /*BUFD*/
3950
3951 let prebody = (ls.residual |> eq2 =>
3952 functionExtraResidualsPreBody(eq2, &varDecls, context, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
3953 ;separator="\n")
3954 let body = (ls.residual |> eq2 as SES_RESIDUAL(__) hasindex i0 =>
3955 let &preExp = buffer "" /*BUFD*/
3956 let expPart = daeExp(eq2.exp, context, &preExp, &varDecls, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
3957 '<%preExp%>_b[<%i0%>] = <%expPart%>;'
3958
3959 ;separator="\n")
3960 <<
3961
3962 void <%modelname%>Algloop<%ls.index%>::evaluate()
3963 {
3964 <%if intGt(clockIndex, 0) then 'const int clockIndex = <%clockIndex%>;'%>
3965 <%varDecls%>
3966 //prebody
3967 <%prebody%>
3968 //body
3969 <%body%>
3970 }
3971 >>
3972 else
3973
3974 /*<<
3975 void <%modelname%>Algloop<%ls.index%>::evaluate()
3976 {
3977 deactivated: should be generated with code generation flag usematrix_t
3978 if(_useSparseFormat)
3979 {
3980 if(! __Asparse)
3981 __Asparse = shared_ptr<matrix_t>( new matrix_t);
3982
3983 evaluate(__Asparse.get());
3984 }
3985 else
3986 {
3987 if(! __A )
3988 __A = shared_ptr<AMATRIX>( new AMATRIX());
3989
3990 evaluate(__A.get());
3991 }
3992
3993
3994
3995 }
3996 >>*/
3997 let uid = System.tmpTick()
3998 let size = listLength(ls.vars)
3999 let aname = 'A<%uid%>'
4000 let bname = 'b<%uid%>'
4001 let &varDecls = buffer "" /*BUFD*/
4002
4003 let &help = buffer ""
4004 let Amatrix=
4005 (ls.simJac |> (row, col, eq as SES_RESIDUAL(__)) hasindex i0 fromindex 0=>
4006 let &preExp = buffer "" /*BUFD*/
4007 let expPart = daeExp(eq.exp, context, &preExp, &varDecls, simCode, &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
4008 match eq.exp
4009 case e as RCONST(__) then
4010 match type
4011 case "sparse" then
4012 <<
4013 //<%preExp%>__A.value_data()[<%i0%>] = <%expPart%>;
4014 >>
4015 else
4016 <<
4017 <%preExp%>__A(<%row%>,<%col%>)=<%expPart%>;
4018 >>
4019 end match
4020 else
4021 match type case "sparse" then
4022 <<
4023 <%preExp%>
4024 __A.value_data()[<%i0%>] = <%expPart%>;
4025 >>
4026 else
4027 <<
4028 <%preExp%>
4029 __A(<%row%>,<%col%>)=<%expPart%>;
4030 >>
4031 end match
4032
4033 ;separator="\n")
4034
4035 let bvector = (ls.beqs |> exp hasindex i0 fromindex 1 =>
4036 let &preExp = buffer "" /*BUFD*/
4037 let expPart = daeExp(exp, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
4038 <<
4039 <%preExp%>__b(<%i0%>) = <%expPart%>;
4040 >>
4041 ;separator="\n")
4042 <<
4043 void <%modelname%>Algloop<%ls.index%>::evaluate()
4044 {
4045 <%varDecls%>
4046 <%Amatrix%>
4047 <%bvector%>
4048 }
4049 >>
4050 end updateAlgloop;
4051
4052 121 template updateAlgloopNonLinear(SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, SimEqSystem eqn, Context context, Integer clockIndex, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
4053 "Generates functions in simulation file."
4054 ::=
4055 match simCode
4056 case SIMCODE(modelInfo = MODELINFO(__)) then
4057 //let () = System.tmpTickReset(0)
4058 let modelname = lastIdentOfPath(modelInfo.name)
4059 match eqn
4060 //case eq as SES_MIXED(__) then functionExtraResiduals(fill(eq.cont,1),simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)
4061 case eq as SES_NONLINEAR(nlSystem = nls as NONLINEARSYSTEM(__)) then
4062 let &varDecls = buffer "" /*BUFD*/
4063 /*let algs = (nls.eqs |> eq2 as SES_ALGORITHM(__) =>
4064 equation_(eq2, context, &varDecls ,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, useFlatArrayNotation)
4065 ;separator="\n")
4066 let prebody = (nls.eqs |> eq2 as SES_SIMPLE_ASSIGN(__) =>
4067 equation_(eq2, context, &varDecls ,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, useFlatArrayNotation)
4068 ;separator="\n")*/
4069 let prebody = (nls.eqs |> eq2 =>
4070 functionExtraResidualsPreBody(eq2, &varDecls, context, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
4071 ;separator="\n")
4072 let body = (nls.eqs |> eq2 => match eq2
4073 case SES_RESIDUAL(__) then
4074 let &preExp = buffer "" /*BUFD*/
4075 let expPart = daeExp(exp, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
4076 '<%preExp%>_res[<%res_index%>] = <%expPart%>;'
4077 case SES_FOR_RESIDUAL(__) then
4078 // Mirrors CodegenC.tpl's SES_FOR_RESIDUAL case in generateNonLinearResidualFunction:
4079 // emit a real for-loop per iterator and flatten them into one residual-slot offset
4080 // added to res_index (a for-loop-wrapped array-tearing residual has no single
4081 // compile-time position, so hasindex can't be used here).
4082 let &preExp = buffer "" /*BUFD*/
4083 let expPart = daeExp(exp, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
4084 let forPart = (iterators |> iterator =>
4085 forIteratorCpp(iterator, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
4086 ;separator="\n")
4087 let endForPart = (iterators |> iterator => "}" ;separator="\n")
4088 let indexShift = <<<%(iterators |> iterator => forIteratorBodyCpp(iterator, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation) ;separator="")%>0<%(iterators |> iterator => ")" ;separator="")%>>>
4089 let assignment = if isArrayType(typeof(exp))
4090 then CodegenCppCommon.error(sourceInfo(), 'Template error: array-valued SES_FOR_RESIDUAL is not implemented for the Cpp target.')
4091 else '<%preExp%>_res[<%res_index%>+(<%indexShift%>)] = <%expPart%>;'
4092 <<
4093 <%forPart%>
4094 <%assignment%>
4095 <%endForPart%>
4096 >>
4097 ;separator="\n")
4098 <<
4099 <% match eq
4100 case SES_NONLINEAR(nlSystem = nls as NONLINEARSYSTEM(__)) then
4101 <<
4102 void <%modelname%>Algloop<%nls.index%>::evaluate()
4103 >>
4104 %>
4105 {
4106 <%if intGt(clockIndex, 0) then 'const int clockIndex = <%clockIndex%>;'%>
4107 <%varDecls%>
4108 //prebody
4109 <%prebody%>
4110 //body
4111 <%body%>
4112 }
4113 >>
4114 end updateAlgloopNonLinear;
4115
4116 1389 template functionExtraResidualsPreBody(SimEqSystem eq, Text &varDecls, Context context, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl,
4117 Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
4118 "Generates an equation."
4119 ::=
4120 match eq
4121 case e as SES_RESIDUAL(__)
4122 then ""
4123 case e as SES_FOR_RESIDUAL(__)
4124 then ""
4125 else
4126 equation_(eq, context, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
4127 end match
4128 end functionExtraResidualsPreBody;
4129
4130 ✗ template forIteratorCpp(SimIterator iter, Context context, Text &preExp, Text &varDecls, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl,
4131 Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
4132 "Generates a for-loop header (plus any dependent sub_iter bindings) for one SES_FOR_RESIDUAL
4133 iterator. Mirrors CodegenC.tpl's forIterator, but declares the loop variable inline (scoped to
4134 its own for-loop) instead of hoisting it into varDecls, since the same iterator cref (e.g. $i1)
4135 can be reused by other residual equations in the same function."
4136 ::= match iter
4137 case SIM_ITERATOR_RANGE() then
4138 let iter_ = contextCref(name, context, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
4139 let start_ = daeExp(start, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
4140 let step_ = daeExp(step, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
4141 let stop_ = daeExp(stop, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
4142 let subIterDecls = (sub_iter |> si => subIteratorCpp(si, iter_, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation); separator="\n")
4143 <<
4144 for(int <%iter_%>=<%start_%>; <%iter_%><=<%stop_%>; <%iter_%>+=<%step_%>){
4145 <%if subIterDecls then subIterDecls%>
4146 >>
4147 case SIM_ITERATOR_LIST() then
4148 let iter_ = contextCref(name, context, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
4149 let arr = (lst |> elem => '<%elem%>'; separator=", ")
4150 let subIterDecls = (sub_iter |> si => subIteratorCpp(si, '<%iter_%>_+1', context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation); separator="\n")
4151 <<
4152 static const int <%iter_%>_lst[<%size%>] = {<%arr%>};
4153 for(int <%iter_%>_=0; <%iter_%>_<<%size%>; <%iter_%>_++){
4154 int <%iter_%> = <%iter_%>_lst[<%iter_%>_];
4155 <%if subIterDecls then subIterDecls%>
4156 >>
4157 end forIteratorCpp;
4158
4159 ✗ template forIteratorBodyCpp(SimIterator iter, Context context, Text &preExp, Text &varDecls, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl,
4160 Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
4161 "Computes one iterator's contribution to a flattened residual-slot offset. Mirrors
4162 CodegenC.tpl's forIteratorBody, used to build a bijective index into res[] across nested
4163 iterators (a plain sum would collapse most index combinations onto the same slot)."
4164 ::= match iter
4165 case SIM_ITERATOR_RANGE() then
4166 let iter_ = contextCref(name, context, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
4167 let start_ = daeExp(start, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
4168 let step_ = daeExp(step, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
4169 let size_ = daeExp(size, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
4170 <<
4171 (<%iter_%>-<%start_%>)/<%step_%>+<%size_%>*(
4172 >>
4173 case SIM_ITERATOR_LIST() then
4174 let iter_ = contextCref(name, context, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
4175 <<
4176 <%iter_%>_+<%size%>*(
4177 >>
4178 end forIteratorBodyCpp;
4179
4180 11518 template lhsCref(ComponentRef cr, Context context, Text &preExp, Text &varDecls, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl,
4181 Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
4182 "Generates an assignable reference for the left hand side of an equation.
4183 cref1 names the whole variable and, without NF_SCALARIZE, silently drops the subscripts of a
4184 non-scalarized (array-typed) variable. For a cref that is fully subscripted down to a single
4185 element that would name the whole array object, so index it instead, the same way daeExpCref
4186 reads such a cref on the right hand side."
4187 ::=
4188 if boolAnd(boolNot(crefIsScalar(cr, context)),
4189 boolAnd(intEq(listLength(crefSubs(cr)), listLength(crefDims(cr))), crefSubIsScalar(cr)))
4190 then
4191 let arrName = contextCref(crefStripLastSubs(cr), context, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
4192 let subsStr = (crefSubs(cr) |> INDEX(__) =>
4193 daeExp(exp, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
4194 ;separator=",")
4195 '<%arrName%>(<%subsStr%>)'
4196 else
4197 cref1(cr, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, context, varDecls, stateDerVectorName, useFlatArrayNotation)
4198 end lhsCref;
4199
4200 ✗ template subIteratorCpp(tuple<ComponentRef, array<Exp>> iter, String parent_iter, Context context, Text &preExp, Text &varDecls, SimCode simCode,
4201 Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
4202 "Binds a dependent (sub_iter) iterator selected by the enclosing range/list iterator's current
4203 value. Mirrors CodegenCFunctions.tpl's subIterator."
4204 ::= match iter
4205 case (name, range) then
4206 let name_ = contextCref(name, context, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
4207 let range_ = (arrayList(range) |> elem => daeExp(elem, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation); separator=", ")
4208 let size_ = arrayLength(range)
4209 <<
4210 static const int <%name_%>_arr[<%size_%>] = {<%range_%>};
4211 int <%name_%> = <%name_%>_arr[<%parent_iter%>-1];
4212 >>
4213 end subIteratorCpp;
4214
4215 49 template functionBodies(list<SimCodeFunction.Function> functions, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
4216 "Generates the body for a set of functions."
4217 ::=
4218 (functions |> fn => functionBody(fn, false,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation) ;separator="\n")
4219 end functionBodies;
4220
4221 280 template functionBody(SimCodeFunction.Function fn, Boolean inFunc, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
4222 "Generates the body for a function."
4223 ::=
4224 match fn
4225 /*workarround until we support these functions*/
4226 case fn as FUNCTION(__)
4227 case fn as EXTERNAL_FUNCTION(__)
4228 case fn as RECORD_CONSTRUCTOR(__)
4229 then
4230 let fname = underscorePath(name)
4231 match fname
4232 case "OpenModelica_Scripting_regexBool"
4233 then ""
4234 case "Modelica_Utilities_Files_loadResource"
4235 then ""
4236 case "OpenModelica_Scripting_directoryExists"
4237 then ""
4238 case "OpenModelica_Scripting_uriToFilename"
4239 then ""
4240 case "OpenModelica_Scripting_Internal_stat"
4241 then ""
4242 case "OpenModelica_Scripting_realpath"
4243 then ""
4244 case "OpenModelica_Scripting_regex"
4245 then ""
4246 else
4247 /* end workarround */
4248 match fn
4249 case fn as FUNCTION(__) then functionBodyRegularFunction(fn, inFunc,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
4250 case fn as EXTERNAL_FUNCTION(__) then functionBodyExternalFunction(fn, inFunc,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
4251 case fn as RECORD_CONSTRUCTOR(__) then functionBodyRecordConstructor(fn,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,useFlatArrayNotation)
4252 end functionBody;
4253
4254 49 template externfunctionHeaderDefinition(list<SimCodeFunction.Function> functions)
4255 "Generates the body for a set of functions."
4256 ::=
4257 (functions |> fn => extFunDef(fn) ;separator="\n")
4258 end externfunctionHeaderDefinition;
4259
4260 49 template functionHeaderBodies1(list<SimCodeFunction.Function> functions, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text& dummyElemTypeCreation, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
4261 "Generates the body for a set of functions."
4262 ::=
4263 match simCode
4264 case SIMCODE(modelInfo=modelInfo as MODELINFO(__)) then
4265 let recorddecls = (recordDecls |> rd => recordDeclarationHeader(rd,simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, dummyElemTypeCreation, useFlatArrayNotation) ;separator="\n")
4266 let rettypedecls = (functions |> fn => functionHeaderBody1(fn,simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation) ;separator="\n")
4267 <<
4268 <%recorddecls%>
4269 <%rettypedecls%>
4270 >>
4271 end functionHeaderBodies1;
4272
4273 280 template functionHeaderBody1(SimCodeFunction.Function fn, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
4274 "Generates the body for a function."
4275 ::=
4276 match fn
4277 /*workarroung until we support these functions*/
4278 case fn as FUNCTION(__)
4279 case fn as EXTERNAL_FUNCTION(__)
4280 case fn as RECORD_CONSTRUCTOR(__)
4281 then
4282 let fname = underscorePath(name)
4283 match fname
4284 case "OpenModelica_Scripting_regexBool"
4285 then ""
4286 case "Modelica_Utilities_Files_loadResource"
4287 then ""
4288 case "OpenModelica_Scripting_directoryExists"
4289 then ""
4290 case "OpenModelica_Scripting_uriToFilename"
4291 then ""
4292 case "OpenModelica_Scripting_Internal_stat"
4293 then ""
4294 case "OpenModelica_Scripting_realpath"
4295 then ""
4296 case "OpenModelica_Scripting_regex"
4297 then ""
4298 else
4299 /* end workarroung */
4300 match fn
4301 case fn as FUNCTION(__) then functionHeaderRegularFunction1(fn, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
4302 case fn as EXTERNAL_FUNCTION(__) then functionHeaderExternFunction(fn, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace)
4303 case fn as RECORD_CONSTRUCTOR(__) then functionHeaderRegularFunction1(fn, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
4304 end functionHeaderBody1;
4305
4306 49 template functionHeaderBodies2(list<SimCodeFunction.Function> functions,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
4307 "Generates the body for a set of functions."
4308 ::=
4309 (functions |> fn => functionHeaderBody2(fn,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation) ;separator="\n")
4310 end functionHeaderBodies2;
4311
4312 280 template functionHeaderBody2(SimCodeFunction.Function fn,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
4313 "Generates the body for a function."
4314 ::=
4315 match fn
4316 /*workarround until we support these functions*/
4317 case fn as FUNCTION(__)
4318 case fn as EXTERNAL_FUNCTION(__)
4319 case fn as RECORD_CONSTRUCTOR(__)
4320 then
4321 let fname = underscorePath(name)
4322 match fname
4323 case "OpenModelica_Scripting_regexBool"
4324 then ""
4325 case "Modelica_Utilities_Files_loadResource"
4326 then ""
4327 case "OpenModelica_Scripting_directoryExists"
4328 then ""
4329 case "OpenModelica_Scripting_uriToFilename"
4330 then ""
4331 case "OpenModelica_Scripting_Internal_stat"
4332 then ""
4333 case "OpenModelica_Scripting_realpath"
4334 then ""
4335 case "OpenModelica_Scripting_regex"
4336 then ""
4337 else
4338 /* end workarround */
4339 match fn
4340 case fn as FUNCTION(__) then functionHeaderRegularFunction2(fn,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
4341 case fn as EXTERNAL_FUNCTION(__) then functionHeaderRegularFunction2(fn,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
4342 case fn as RECORD_CONSTRUCTOR(__) then functionHeaderRecordConstruct(fn,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, useFlatArrayNotation)
4343 end functionHeaderBody2;
4344
4345 49 template functionHeaderBodies3(list<SimCodeFunction.Function> functions,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
4346 "Generates the body for a set of functions."
4347 ::=
4348 (functions |> fn => functionHeaderBody3(fn,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace) ;separator="\n")
4349 end functionHeaderBodies3;
4350
4351 280 template functionHeaderBody3(SimCodeFunction.Function fn,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
4352 "Generates the body for a function."
4353 ::=
4354 match fn
4355 /*workarroung until we support these functions*/
4356 case fn as FUNCTION(__)
4357 case fn as EXTERNAL_FUNCTION(__)
4358 case fn as RECORD_CONSTRUCTOR(__)
4359 then
4360 let fname = underscorePath(name)
4361 match fname
4362 case "OpenModelica_Scripting_regexBool"
4363 then ""
4364 case "Modelica_Utilities_Files_loadResource"
4365 then ""
4366 case "OpenModelica_Scripting_directoryExists"
4367 then ""
4368 case "OpenModelica_Scripting_uriToFilename"
4369 then ""
4370 case "OpenModelica_Scripting_Internal_stat"
4371 then ""
4372 case "OpenModelica_Scripting_realpath"
4373 then ""
4374 case "OpenModelica_Scripting_regex"
4375 then ""
4376 else
4377 /* end workarroung */
4378 match fn
4379 case fn as FUNCTION(__) then /*Function*/functionHeaderRegularFunction3(fn,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)
4380 case fn as EXTERNAL_FUNCTION(__) then /*External Function*/ functionHeaderRegularFunction3(fn,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)
4381 case fn as RECORD_CONSTRUCTOR(__) then ""
4382 end functionHeaderBody3;
4383
4384
4385 53 template extFunDef(SimCodeFunction.Function fn)
4386 "Generates function header for an external function."
4387 ::=
4388 match fn
4389
4390 case func as EXTERNAL_FUNCTION(extReturn= return) then
4391 let fargsStr = extFunDefArgs(extArgs, language)
4392 match extName
4393 case "OpenModelica_regex"
4394 then ""
4395
4396 else
4397 match fn
4398 case func as EXTERNAL_FUNCTION(__) then
4399 let fargsStrEscaped = '<%escapeCComments(fargsStr)%>'
4400 let includesStr = includes |> i => i ;separator=", "
4401 let fn_name = extFunctionName(extName, language)
4402 /*
4403 * adrpo:
4404 * only declare the external function definition IF THERE WERE NO INCLUDES!
4405 * i did not put includesStr string in the comment below as it might include
4406 * entire files
4407 */
4408 if includes then
4409 <<
4410 /*
4411 * The function has annotation(Include=...>)
4412 * the external function definition should be present
4413 * in one of these files and have this prototype:
4414 * extern <%extReturnType(extReturn)%> <%fn_name%>(<%fargsStrEscaped%>);
4415 */
4416 >>
4417 else
4418 <<
4419 extern <%extReturnType(return)%> <%fn_name%>(<%fargsStr%>);
4420 >>
4421 end match
4422 end extFunDef;
4423
4424
4425 58 template extFunctionName(String name, String language)
4426 ::=
4427 match language
4428 case "C" then '<%name%>'
4429 case "FORTRAN 77" then '<%name%>_'
4430 else CodegenCppCommon.error(sourceInfo(), 'Unsupported external language: <%language%>')
4431 end extFunctionName;
4432
4433 53 template extFunDefArgs(list<SimExtArg> args, String language)
4434 ::=
4435 match language
4436 case "C"
4437 case "FORTRAN 77" then
4438 (args |> arg => extFunDefArg(arg, language); separator=", ")
4439 else CodegenCppCommon.error(sourceInfo(), 'Unsupported external language: <%language%>')
4440 end extFunDefArgs;
4441
4442 171 template extFunDefArg(SimExtArg extArg, String language)
4443 "Generates the definition of an external function argument.
4444 Assume that language is C for now."
4445 ::=
4446 match extArg
4447 case SIMEXTARG(cref=c, isInput=ii, isArray=ia, type_=t) then
4448 let name = contextCref2(c,contextFunction)
4449 let typeStr = extType(t, language, true, ii, ia)
4450 <<
4451 <%typeStr%> /*<%name%>*/
4452 >>
4453 case SIMEXTARGEXP(__) then
4454 let typeStr = extType(type_, language, true, true, false)
4455 <<
4456 <%typeStr%>
4457 >>
4458 case SIMEXTARGSIZE(cref=c) then
4459 let typeStr = match language case "FORTRAN 77" then 'int*' else 'size_t'
4460 <<
4461 <%typeStr%>
4462 >>
4463 end extFunDefArg;
4464
4465
4466 172 template extType(Type type, String language, Boolean isReference,
4467 Boolean isInput, Boolean isArray)
4468 "Generates type for external function argument or return value for C or F77."
4469 ::=
4470 match language
4471 case "C" then extType2(type, isInput, isArray)
4472 case "FORTRAN 77" then extTypeF77(type, isInput, isReference)
4473 else CodegenCppCommon.error(sourceInfo(), 'Unsupported external language: <%language%>')
4474 end extType;
4475
4476
4477 388 template extType2(Type type, Boolean isInput, Boolean isArray)
4478 "Generates type for external function argument or return value."
4479 ::=
4480 let s = match type
4481 case T_INTEGER(__) then "int"
4482 case T_REAL(__) then "double"
4483 case T_STRING(__) then "const char*"
4484 case T_BOOL(__) then "int"
4485 case T_ENUMERATION(__) then "int"
4486 case T_ARRAY(__) then extType2(ty,isInput,true)
4487 case T_COMPLEX(complexClassType=EXTERNAL_OBJ(__))
4488 then "void*"
4489 case T_COMPLEX(complexClassType=RECORD(path=rname))
4490 then '<%underscorePath(rname)%>Type'
4491 case T_METATYPE(__) case T_METABOXED(__) then "modelica_metatype"
4492 else CodegenCppCommon.error(sourceInfo(), 'Unknown external C type <%unparseType(type)%>')
4493 match type case T_ARRAY(__) then s else if isInput then (if isArray then '<%match s case "const char*" then "" else "const "%><%s%>*' else s) else '<%s%>*'
4494 end extType2;
4495
4496
4497 87 template extTypeF77(Type type, Boolean isInput, Boolean isReference)
4498 "Generates type for external function argument or return value for F77."
4499 ::=
4500 let s = match type
4501 case T_INTEGER(__) then "int"
4502 case T_REAL(__) then "double"
4503 case T_STRING(__) then "const char*"
4504 case T_BOOL(__) then "int"
4505 case T_ENUMERATION(__) then "int"
4506 case T_ARRAY(__) then extTypeF77(ty, isInput, true)
4507 else CodegenCppCommon.error(sourceInfo(), 'Unknown external F77 type <%unparseType(type)%>')
4508 match type case T_ARRAY(__) case T_STRING(__) then s else if isReference then '<%if isInput then "const "%><%s%>*' else s
4509 end extTypeF77;
4510
4511
4512 27 template extReturnType(SimExtArg extArg)
4513 "Generates return type for external function."
4514 ::=
4515 match extArg
4516 case ex as SIMEXTARG(__) then extType2(type_,true /*Treat this as an input (pass by value)*/,false)
4517 case SIMNOEXTARG(__) then "void"
4518 case SIMEXTARGEXP(__) then CodegenCppCommon.error(sourceInfo(), 'Expression types are unsupported as return arguments <%ExpressionDumpTpl.dumpExp(exp,"\"")%>')
4519 else CodegenCppCommon.error(sourceInfo(), "Unsupported return argument")
4520 end extReturnType;
4521
4522
4523 244 template functionHeaderRegularFunction1(SimCodeFunction.Function fn, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
4524 ::=
4525 match fn
4526 case FUNCTION(outVars={var}) then
4527 let fname = underscorePath(name)
4528 << /*default return type*/
4529 typedef <%funReturnDefinition1(var,simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace)%> <%fname%>RetType /* functionHeaderRegularFunction1 */;
4530 typedef <%funReturnDefinition2(var,simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%> <%fname%>RefRetType /* functionHeaderRegularFunction1 */;
4531 >>
4532
4533
4534 case FUNCTION(outVars= vars as _::_) then
4535
4536 let fname = underscorePath(name)
4537 << /*tuple return type*/
4538 struct <%fname%>Type/*RecordTypeTest*/
4539 {
4540 typedef tuple< <%vars |> var => funReturnDefinition1(var,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace) ;separator=", "%> > TUPLE_ARRAY;
4541
4542 <%fname%>Type& operator=(const <%fname%>Type& A)
4543 {
4544 <%vars |> var hasindex i0 => tupplearrayassign(var,i0) ;separator="\n "%>
4545 return *this;
4546 }
4547 TUPLE_ARRAY data;
4548 };
4549 typedef <%fname%>Type/*RecordTypeTest*/ <%fname%>RetType /* functionHeaderRegularFunction1 */;
4550 >>
4551
4552 case RECORD_CONSTRUCTOR(__) then
4553
4554 let fname = underscorePath(name)
4555
4556 <<
4557 typedef <%fname%>Type <%fname%>RetType /* functionHeaderRegularFunction1 */;
4558 >>
4559 case PARALLEL_FUNCTION(__) then
4560 let fname = underscorePath(name)
4561 <<
4562 //PARALLEL_FUNCTION
4563 //typedef <%fname%>Type <%fname%>RetType out of functionHeaderRegularFunction1;
4564 >>
4565 case KERNEL_FUNCTION(__) then
4566 let fname = underscorePath(name)
4567 <<
4568 //KERNEL_FUNCTION
4569 //typedef <%fname%>Type <%fname%>RetType out of functionHeaderRegularFunction1;
4570 >>
4571 case EXTERNAL_FUNCTION(__) then
4572 let fname = underscorePath(name)
4573 <<
4574 //EXTERNAL_FUNCTION
4575 //typedef <%fname%>Type <%fname%>RetType out of functionHeaderRegularFunction1;
4576 >>
4577 end functionHeaderRegularFunction1;
4578
4579 81 template tupplearrayassign(Variable var,Integer index)
4580 ::=
4581 match var
4582 case var as VARIABLE(__) then
4583 // previous multi_array if instDims then 'assign_array(get<<%index%>>(data),get<<%index%>>(A.data));' else 'get<<%index%>>(data)= get<<%index%>>(A.data);
4584 if instDims then '(get<<%index%>>(data)).assign(get<<%index%>>(A.data));' else 'get<<%index%>>(data)= get<<%index%>>(A.data);'
4585 end tupplearrayassign;
4586
4587 63 template functionHeaderRecordConstruct(SimCodeFunction.Function fn,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Boolean useFlatArrayNotation)
4588 ::=
4589 match fn
4590 case RECORD_CONSTRUCTOR(__) then
4591 let fname = underscorePath(name)
4592 let funArgsStr = (funArgs |> var as VARIABLE(__) =>
4593 '<%varType1(var,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)%> <%CodegenCppCommon.crefStr(name)%>'
4594 ;separator=", ")
4595 <<
4596 void /*RecordTypetest*/ <%fname%>(<%funArgsStr%><%if funArgs then "," else ""%><%fname%>Type &output );
4597 >>
4598 end functionHeaderRecordConstruct;
4599
4600 32 template functionHeaderExternFunction(SimCodeFunction.Function fn,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
4601 ::=
4602 match fn
4603 case EXTERNAL_FUNCTION(outVars={var}) then
4604
4605 let fname = underscorePath(name)
4606 <<
4607 typedef <%funReturnDefinition1(var,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)%> <%fname%>RetType /* functionHeaderExternFunction */;
4608 >>
4609 case EXTERNAL_FUNCTION(outVars=_::_) then
4610
4611 let fname = underscorePath(name)
4612 << /*tuple return type*/
4613 struct <%fname%>Type
4614 {
4615 typedef tuple< <%outVars |> var => funReturnDefinition1(var,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace) ;separator=", "%> > TUPLE_ARRAY;
4616
4617 <%fname%>Type& operator=(const <%fname%>Type& A)
4618 {
4619 <%outVars |> var hasindex i0 => tupplearrayassign(var,i0) ;separator="\n "%>
4620 return *this;
4621 }
4622 TUPLE_ARRAY data;
4623 };
4624 typedef <%fname%>Type/*RecordTypeTest*/ <%fname%>RetType /* functionHeaderExternFunction */;
4625 >>
4626 /*
4627 <<
4628 typedef tuple< <%outVars |> var => funReturnDefinition1(var,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace) ;separator=", "%> > <%fname%>RetType /* functionHeaderExternFunction */;
4629 >>
4630 */
4631 case FUNCTION(outVars= vars as _::_) then
4632 let fname = underscorePath(name)
4633 <<
4634 //FUNCTION
4635 //typedef <%fname%>Type <%fname%>RetType out of functionHeaderExternFunction;
4636 >>
4637
4638 case RECORD_CONSTRUCTOR(__) then
4639 let fname = underscorePath(name)
4640 <<
4641 //RECORD_CONSTRUCTOR
4642 //typedef <%fname%>Type <%fname%>RetType out of functionHeaderExternFunction;
4643 >>
4644 case PARALLEL_FUNCTION(__) then
4645 let fname = underscorePath(name)
4646 <<
4647 //PARALLEL_FUNCTION
4648 //typedef <%fname%>Type <%fname%>RetType out of functionHeaderExternFunction;
4649 >>
4650 case KERNEL_FUNCTION(__) then
4651 let fname = underscorePath(name)
4652 <<
4653 //KERNEL_FUNCTION
4654 //typedef <%fname%>Type <%fname%>RetType out of functionHeaderExternFunction;
4655 >>
4656
4657 end functionHeaderExternFunction;
4658
4659 64 template recordDeclarationHeader(RecordDeclaration recDecl, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text& dummyElemCreation, Boolean useFlatArrayNotation)
4660 "Generates structs for a record declaration."
4661 ::=
4662 match recDecl
4663 case r as RECORD_DECL_FULL(__) then
4664 match aliasName
4665 case SOME(str) then
4666 let &dummyElemCreation += '<%r.name%>Type dummy<%r.name%>Type;<%\n%>'
4667 <<
4668 typedef <%str%>Type <%r.name%>Type;
4669 >>
4670 else
4671 let &dummyElemCreation += '<%r.name%>Type dummy<%r.name%>Type;<%\n%>'
4672 <<
4673 struct <%r.name%>Type
4674 {
4675 <%r.variables |> var as VARIABLE(__) => '<%varType3(var, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace)%> <%CodegenCppCommon.crefStr(var.name)%>;' ;separator="\n"%>
4676 };
4677 >>
4678 case RECORD_DECL_DEF(__) then
4679 <<
4680 RECORD DECL DEF
4681 >>
4682 end recordDeclarationHeader;
4683
4684 63 template functionBodyRecordConstructor(SimCodeFunction.Function fn,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Boolean useFlatArrayNotation)
4685 "Generates the body for a record constructor."
4686 ::=
4687 match fn
4688 case RECORD_CONSTRUCTOR(__) then
4689 let &varDecls = buffer "" /*BUFD*/
4690 let fname = underscorePath(name)
4691 let retType = '<%fname%>Type'
4692
4693 <<
4694 void Functions::<%fname%>(<%funArgs |> var as VARIABLE(__) => '<%varType1(var, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace)%> <%CodegenCppCommon.crefStr(name)%>' ;separator=", "%><%if funArgs then ", " else ""%><%retType%>& output)
4695 {
4696 //functionBodyRecordConstructor
4697 <%funArgs |> VARIABLE(__) => '(output.<%CodegenCppCommon.crefStr(name)%>) = (<%CodegenCppCommon.crefStr(name)%>);' ;separator="\n"%>
4698 }
4699
4700 >>
4701 end functionBodyRecordConstructor;
4702
4703 269 template functionHeaderRegularFunction2(SimCodeFunction.Function fn,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
4704 ::=
4705 match fn
4706 case FUNCTION(outVars={}) then
4707 let fname = underscorePath(name)
4708 <<
4709 <%functionTemplates(functionArguments)%>
4710 void <%fname%>(<%functionArguments |> var => funArgDefinition(var, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation) ;separator=", "%>);
4711 >>
4712 case FUNCTION(outVars=_) then
4713 let fname = underscorePath(name)
4714 <<
4715 /* functionHeaderRegularFunction2 */
4716 <%functionTemplates(functionArguments)%>
4717 void <%fname%>(<%functionArguments |> var => funArgDefinition(var, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation) ;separator=", "%><%if functionArguments then ", " else ""%><%fname%>RetType& output);
4718 >>
4719 case EXTERNAL_FUNCTION(outVars=var::_) then
4720 let fname = underscorePath(name)
4721 <<
4722 /* functionHeaderRegularFunction2 */
4723 void <%fname%>(<%funArgs |> var => funArgDefinition(var, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation) ;separator=", "%><%if funArgs then ", " else ""%><%fname%>RetType& output);
4724 >>
4725 case EXTERNAL_FUNCTION(outVars={}) then
4726 let fname = underscorePath(name)
4727 <<
4728 void <%fname%>(<%funArgs |> var => funArgDefinition(var, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation) ;separator=", "%>);
4729 >>
4730 end functionHeaderRegularFunction2;
4731
4732 333 template functionHeaderRegularFunction3(SimCodeFunction.Function fn, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace)
4733 ::=
4734 match fn
4735 case FUNCTION(outVars={}) then ""
4736
4737 case FUNCTION(outVars=_) then
4738 let fname = underscorePath(name)
4739 <<
4740 /* functionHeaderRegularFunction3 */
4741 <%fname%>RetType _<%fname%>;
4742 >>
4743 case EXTERNAL_FUNCTION(outVars=var::_) then
4744 let fname = underscorePath(name)
4745 <<
4746 /* functionHeaderRegularFunction3 */
4747 <%fname%>RetType _<%fname%>;
4748 >>
4749 end functionHeaderRegularFunction3;
4750
4751 280 template functionBodyRegularFunction(SimCodeFunction.Function fn, Boolean inFunc, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
4752 "Generates the body for a Modelica/MetaModelica function."
4753 ::=
4754 match fn
4755 case FUNCTION(__) then
4756 //let()= System.tmpTickReset(1)
4757 let fname = underscorePath(name)
4758 let retType = if outVars then '<%fname%>RetType ' else "void" /* functionBodyRegularFunction */
4759 let &varDecls = buffer "" /*BUFD*/
4760
4761
4762 let &varInits = buffer "" /*BUFD*/
4763 //let retVar = if outVars then tempDecl(retType, &varDecls /*BUFD*/)
4764 //let stateVar = if not acceptMetaModelicaGrammar() then tempDecl("state", &varDecls /*BUFD*/)
4765 let _ = (variableDeclarations |> var as VARIABLE(__) hasindex i1 fromindex 1 =>
4766 varInit(var, "", i1, &varDecls, &varInits, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation) ; empty /* increase the counter! */)
4767
4768 //let addRootsInputs = (functionArguments |> var => addRoots(var) ;separator="\n")
4769 //let addRootsOutputs = (outVars |> var => addRoots(var) ;separator="\n")
4770 //let funArgs = (functionArguments |> var => functionArg(var, &varInits) ;separator="\n")
4771 let bodyPart = funStatement(body, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
4772 let &outVarInits = buffer ""
4773 let &outVarCopy = buffer ""
4774 let &outVarAssign = buffer ""
4775 let _ = match outVars case {var} then (outVars |> var hasindex i1 fromindex 0 =>
4776 varOutput(fn, var,i1, &varDecls, &outVarInits, &outVarCopy, &outVarAssign, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
4777 ;separator="\n"; empty /* increase the counter! */
4778 )
4779 else
4780 (outVars |> var hasindex i1 fromindex 0 =>
4781 varOutputTuple(fn, var,i1, &varDecls, &outVarInits, &outVarCopy, &outVarAssign, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
4782 ;separator="\n"; empty /* increase the counter! */
4783 )
4784 <<
4785 <%functionTemplates(functionArguments)%>
4786 void Functions::<%fname%>(<%functionArguments |> var => funArgDefinition(var, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation) ;separator=", "%><%if functionArguments then if outVars then ", " else ""%><%if outVars then '<%retType%>& output'%>)
4787 {
4788 //functionBodyRegularFunction
4789 <%(functionArguments |> var => match var case FUNCTION_PTR(name=fnptrName) then 'typedef double <%fnptrName%>RetType;' ;separator="\n")%>
4790 <%varDecls%>
4791 //outvars
4792 <%outVarInits%>
4793 <%varInits%>
4794 do
4795 {
4796 <%bodyPart%>
4797 }
4798 while(false);
4799 <%outVarAssign%>
4800 }
4801
4802 <% if inFunc then
4803 <<
4804 int in_<%fname%>(type_description * inArgs, type_description * outVar)
4805 {
4806 <%functionArguments |> var => '<%funArgDefinition2(var, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>;' ;separator="\n"%>
4807 <%if outVars then '<%retType%> out;'%>
4808 return 0;
4809 }
4810 >>
4811 %>
4812 >>
4813 end functionBodyRegularFunction;
4814
4815
4816 53 template functionBodyExternalFunction(SimCodeFunction.Function fn, Boolean inFunc,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
4817 "Generates the body for an external function (just a wrapper)."
4818 ::=
4819 match fn
4820 case efn as EXTERNAL_FUNCTION(extArgs=extArgs) then
4821 //let()= System.tmpTickReset(1)
4822 let fname = underscorePath(name)
4823 let retType = if outVars then '<%fname%>RetType' else "void"
4824 let &preExp = buffer "" /*BUFD*/
4825 let &varDeclsInit = buffer "" /*BUFD*/
4826 let &varDeclsExtFunCall = buffer "" /*BUFD*/
4827 let &varDeclsOutput = buffer "" /*BUFD*/
4828 let &varDeclsvOutputTuple = buffer "" /*BUFD*/
4829
4830 let &inputAssign = buffer "" /*BUFD*/
4831 let &outputAssign = buffer "" /*BUFD*/
4832 let retVar = if outVars then match outVars case {var} then funArgName(var) else '_<%fname%>'
4833 let &outVarInits = buffer ""
4834 let callPart = match outVars case {var} then
4835 extFunCall(fn, &preExp, &varDeclsExtFunCall, &inputAssign, &outputAssign, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation, false)
4836 else
4837 extFunCall(fn, &preExp, &varDeclsExtFunCall, &inputAssign, &outputAssign, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation, true)
4838 let _ = ( outVars |> var as VARIABLE(__) hasindex i1 fromindex 1 =>
4839 varInit(var, retVar, i1, &varDeclsInit, &outVarInits, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation) ///TOODOO
4840 ; empty /* increase the counter! */
4841 )
4842 let &outVarAssign = buffer ""
4843 let &outVarCopy = buffer ""
4844 let _ = match outVars
4845
4846 case {var} then
4847 //(outVars |> var hasindex i1 fromindex 0 =>
4848 varOutput(fn, var,0, &varDeclsOutput, &outVarInits, &outVarCopy, &outVarAssign, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
4849 // ;separator="\n"; empty /* increase the counter! */
4850 else
4851 (List.restOrEmpty(outVars) |> var hasindex i1 fromindex 1 => varOutputTuple(fn, var, i1, &varDeclsvOutputTuple, &outVarInits, &outVarCopy, &outVarAssign, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
4852 ;separator="\n"; empty /* increase the counter! */
4853 )
4854 end match
4855
4856 let &outVarCopy1 = buffer ""
4857 let &outVarAssign1 = buffer ""
4858
4859 let _ = match outVars
4860
4861 case {var} then "1"
4862
4863 else
4864 (outVars |> var hasindex i1 fromindex 0 => varOutputTuple(fn, var, i1, &varDeclsvOutputTuple, &outVarInits, &outVarCopy1, &outVarAssign1, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
4865 ;separator="\n"; empty /* increase the counter! */)
4866 end match
4867 let functionBodyExternalFunctionreturn = match outVarAssign1
4868 case "" then <<<%if retVar then 'output = <%retVar%>;' else '/*no output*/' %>>>
4869 else outVarAssign1
4870
4871 let fnBody =
4872 <<
4873 void Functions::<%fname%>(<%funArgs |> var => funArgDefinition(var, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation) ;separator=", "%><%if funArgs then if outVars then ", " else ""%><%if retVar then '<%retType%>& output'%>)
4874 {
4875 /* functionBodyExternalFunction: varDecls */
4876 /*1*/
4877 <%varDeclsInit%>
4878 /*2*/
4879 <%varDeclsExtFunCall%>
4880 /*3*/
4881 <%varDeclsOutput%>
4882 /*4*/
4883 <%varDeclsvOutputTuple%>
4884 /* functionBodyExternalFunction: preExp */
4885 <%preExp%>
4886 /* functionBodyExternalFunction: outVarInits */
4887 <%outVarInits%>
4888 /* functionBodyExternalFunction: callPart */
4889 <%inputAssign%>
4890 <%callPart%>
4891 <%outputAssign%>
4892 /* functionBodyExternalFunction: return */
4893 <%functionBodyExternalFunctionreturn%>
4894 }
4895 >>
4896 <<
4897 <% if dynamicLoad then
4898 <<
4899 ptrT_<%extFunctionName(extName, language)%> ptr_<%extFunctionName(extName, language)%>=NULL;
4900 >> %>
4901 <%fnBody%>
4902
4903 <% if inFunc then
4904 <<
4905 int in_<%fname%>(type_description * inArgs, type_description * outVar)
4906 {
4907 <%funArgs |> VARIABLE(__) => '<%expTypeArrayIf(ty)%> <%contextCref(name,contextFunction,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>;' ;separator="\n"%>
4908 <%retType%> out;
4909 <%funArgs |> arg as VARIABLE(__) => readInVar(arg,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation) ;separator="\n"%>
4910 MMC_TRY_TOP()
4911 out = _<%fname%>(<%funArgs |> VARIABLE(__) => contextCref(name,contextFunction,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation) ;separator=", "%>);
4912 MMC_CATCH_TOP(return 1)
4913 <%outVars |> var as VARIABLE(__) hasindex i1 fromindex 1 => writeOutVar(var, i1) ;separator="\n";empty%>
4914 return 0;
4915 }
4916 >> %>
4917 >>
4918 end functionBodyExternalFunction;
4919
4920 560 template functionTemplates(list<Variable> functionArguments)
4921 "Generates template prefix for functions with function arguments"
4922 ::=
4923 // TODO: generate specific names if type of modelica_fnptr known
4924 let funcPtrs = (functionArguments |> var => match var case FUNCTION_PTR(__) then 'modelica_fnptr' ;separator=", ")
4925 '<%if funcPtrs then 'template <class modelica_fnptr>'%>'
4926 end functionTemplates;
4927
4928 32 template funArgName(Variable var)
4929 ::=
4930 let &auxFunction = buffer ""
4931 match var
4932 case VARIABLE(__) then contextCref2(name,contextFunction)
4933 case FUNCTION_PTR(__) then '_' + name
4934 end funArgName;
4935
4936 ✗ template writeOutVar(Variable var, Integer index)
4937 "Generates code for writing a variable to outVar."
4938
4939 ::=
4940 match var
4941 case VARIABLE(ty=T_COMPLEX(complexClassType=RECORD(__))) then
4942 <<
4943 write_modelica_record(outVar, <%writeOutVarRecordMembers(ty, index, "")%>);
4944 >>
4945 case VARIABLE(__) then
4946
4947 <<
4948 write_<%varType(var)%>(outVar, &out.targTest8<%index%>);
4949 >>
4950 end writeOutVar;
4951
4952
4953 ✗ template writeOutVarRecordMembers(Type type, Integer index, String prefix)
4954 "Helper to writeOutVar."
4955 ::=
4956 match type
4957 case T_COMPLEX(varLst=vl, complexClassType = n) then
4958 let basename = underscorePath(ClassInfUtil.getStateName(n))
4959 let args = (vl |> subvar as TYPES_VAR(__) =>
4960 match ty case T_COMPLEX(__) then
4961 let newPrefix = '<%prefix%>.<%subvar.name%>'
4962 '<%expTypeRW(ty)%>, <%writeOutVarRecordMembers(ty, index, newPrefix)%>'
4963 else
4964 '<%expTypeRW(ty)%>, &(out.targTest7<%index%><%prefix%>.<%subvar.name%>)'
4965 ;separator=", ")
4966 <<
4967 &<%basename%>__desc<%if args then ', <%args%>'%>, TYPE_DESC_NONE
4968 >>
4969 end writeOutVarRecordMembers;
4970 ✗ template expTypeRW(DAE.Type type)
4971 "Helper to writeOutVarRecordMembers."
4972 ::=
4973 match type
4974 case T_INTEGER(__) then "TYPE_DESC_INT"
4975 case T_REAL(__) then "TYPE_DESC_REAL"
4976 case T_STRING(__) then "TYPE_DESC_STRING"
4977 case T_BOOL(__) then "TYPE_DESC_BOOL"
4978 case T_ENUMERATION(__) then "TYPE_DESC_INT"
4979 case T_ARRAY(__) then '<%expTypeRW(ty)%>_ARRAY'
4980 case T_COMPLEX(complexClassType=RECORD(__))
4981 then "TYPE_DESC_RECORD"
4982 case T_METATYPE(__) case T_METABOXED(__) then "TYPE_DESC_MMC"
4983 end expTypeRW;
4984
4985 ✗ template readInVar(Variable var,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
4986 "Generates code for reading a variable from inArgs."
4987 ::=
4988 match var
4989 case VARIABLE(name=cr, ty=T_COMPLEX(complexClassType=RECORD(__))) then
4990 <<
4991 if (read_modelica_record(&inArgs, <%readInVarRecordMembers(ty, contextCref(cr,contextFunction,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation))%>)) return 1;
4992 >>
4993 case VARIABLE(name=cr, ty=T_STRING(__)) then
4994 <<
4995 if (read_<%expTypeArrayIf(ty)%>(&inArgs, <%if not acceptMetaModelicaGrammar() then "(char**)"%> &<%contextCref(name,contextFunction,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>)) return 1;
4996 >>
4997 case VARIABLE(__) then
4998 <<
4999 if (read_<%expTypeArrayIf(ty)%>(&inArgs, &<%contextCref(name,contextFunction,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>)) return 1;
5000 >>
5001 end readInVar;
5002
5003
5004 ✗ template readInVarRecordMembers(Type type, String prefix)
5005 "Helper to readInVar."
5006 ::=
5007 match type
5008 case T_COMPLEX(varLst=vl) then
5009 (vl |> subvar as TYPES_VAR(__) =>
5010 match ty case T_COMPLEX(__) then
5011 let newPrefix = '<%prefix%>.<%subvar.name%>'
5012 readInVarRecordMembers(ty, newPrefix)
5013 else
5014 '&(<%prefix%>.<%subvar.name%>)'
5015 ;separator=", ")
5016 end readInVarRecordMembers;
5017
5018 ✗ template outDecl(String ty, Text &varDecls /*BUFP*/)
5019 "Declares a temporary variable in varDecls and returns the name."
5020 ::=
5021 let newVar = 'out'
5022 let &varDecls += '<%ty%> <%newVar%>;<%\n%>'
5023 newVar
5024 end outDecl;
5025
5026
5027 53 template extFunCall(SimCodeFunction.Function fun, Text &preExp, Text &varDecls, Text &inputAssign, Text &outputAssign, SimCode simCode, Text& extraFuncs,
5028 Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation, Boolean useTuple)
5029 "Generates the call to an external function."
5030 ::=
5031 match fun
5032 case EXTERNAL_FUNCTION(__) then
5033 let _ = (biVars |> bivar =>
5034 extFunCallBiVar(bivar, &preExp, &varDecls, simCode,
5035 &extraFuncs, &extraFuncsDecl, extraFuncsNamespace,
5036 stateDerVectorName, useFlatArrayNotation);
5037 separator="\n")
5038 match language
5039 case "C" then extFunCallC(fun, &preExp, &varDecls, &inputAssign, &outputAssign, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation, useTuple)
5040 case "FORTRAN 77" then extFunCallF77(fun, &preExp, &varDecls, &inputAssign, &outputAssign, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
5041 end extFunCall;
5042
5043
5044 48 template extFunCallC(SimCodeFunction.Function fun, Text &preExp, Text &varDecls, Text &inputAssign, Text &outputAssign, SimCode simCode, Text& extraFuncs,
5045 Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation, Boolean useTuple)
5046 "Generates the call to an external C function."
5047 ::=
5048 match fun
5049 case EXTERNAL_FUNCTION(__) then
5050 /* adpro: 2011-06-24 do vardecls -> extArgs as there might be some sets in there! */
5051 let varDecs = (List.union(extArgs, extArgs) |> arg => extFunCallVardecl(arg, &varDecls /*BUFD*/) ;separator="\n")
5052 //let fname = if dynamicLoad then 'ptr_<%extFunctionName(extName, language)%>' else '<%extName%>'
5053 let fname = underscorePath(name)
5054 let dynamicCheck = if dynamicLoad then
5055 <<
5056 if (<%fname%>==NULL) {
5057 MODELICA_TERMINATE("dynamic external function <%extFunctionName(extName, language)%> not set!")
5058 } else
5059 >>
5060 else ''
5061 let args = (extArgs |> arg =>
5062 extArg(arg, &preExp, &varDecls, &inputAssign, &outputAssign, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
5063 ;separator=", ")
5064 let returnAssign = match extReturn case SIMEXTARG(cref=c, type_=ty) then
5065 let extName = extVarName2(c)
5066 let &outputAssign += '<%contextCref2(c,contextFunction)%> = <%extName%>;<%\n%>'
5067 let &outputAssign += match ty case T_STRING(__) then
5068 '_ModelicaFreeStringIfAllocated(<%extName%>);<%\n%>' else ''
5069 '<%extName%> = '
5070 else
5071 ''
5072 <<
5073 <%varDecs%>
5074 <%match extReturn case SIMEXTARG(__) then extFunCallVardecl(extReturn, &varDecls /*BUFD*/)%>
5075 <%dynamicCheck%>
5076 <%returnAssign%><%extName%>(<%args%>);
5077 >>
5078 end extFunCallC;
5079
5080
5081 ✗ template extFunCallVarcopy(SimExtArg arg, String fnName,Boolean useTuple, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
5082 "Helper to extFunCall."
5083 ::=
5084 match arg
5085 case SIMEXTARG(outputIndex=oi, isArray=false, type_=ty, cref=c) then
5086 match oi case 0 then
5087 "/*no ouput index */"
5088 else
5089 let cr = contextCref2(c,contextFunction)//'<%extVarName2(c)%>'
5090 match useTuple
5091 case true then
5092 let assginBegin = 'get<<%intAdd(-1,oi)%>>('
5093 let assginEnd = ')'
5094
5095
5096 /* <%assginBegin%> output.data<%assginEnd%> = <%cr%>;*/
5097 <<
5098 <%contextCref(c,contextFunction,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%> =(<%expTypeModelica(ty)%>) <%cr%>;
5099 >>
5100 else
5101 <<
5102 _<%fnName%> = <%cr%>;
5103 >>
5104 case SIMEXTARG(outputIndex=oi, isArray=true, type_=ty, cref=c) then
5105 match oi case 0 then
5106 "/*no ouput index */"
5107 else
5108 let cr = contextCref2(c,contextFunction)//'<%extVarName2(c)%>'
5109 match useTuple
5110 case true then
5111 let assginBegin = 'get<<%intAdd(-1,oi)%>>('
5112 let assginEnd = ')'
5113
5114
5115 /* <%assginBegin%> output.data<%assginEnd%> = <%cr%>;*/
5116 <<
5117 /*array assign*/
5118 <%contextCref(c,contextFunction,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>.assign(<%cr%>);
5119 >>
5120
5121 else
5122 <<
5123 /*array assign*/
5124 _<%fnName%>.assign(<%cr%>);
5125 >>
5126
5127 end match
5128 end extFunCallVarcopy;
5129
5130
5131
5132 ✗ template extFunCallVarcopyTuple(SimExtArg arg, String fnName)
5133 "Helper to extFunCall."
5134 ::=
5135 match arg
5136 case SIMEXTARG(outputIndex=oi, isArray=false, type_=ty, cref=c) then
5137 match oi case 0 then
5138 ""
5139 else
5140 let cr = '<%extVarName2(c)%>'
5141 let assginBegin = 'get<<%intAdd(-1,oi)%>>('
5142 let assginEnd = ')'
5143
5144 <<
5145 <%assginBegin%>_<%fnName%>.data<%assginEnd%> = <%cr%> ;
5146 >>
5147
5148 end extFunCallVarcopyTuple;
5149
5150 101 template extArg(SimExtArg extArg, Text &preExp, Text &varDecls, Text &inputAssign, Text &outputAssign, SimCode simCode, Text& extraFuncs,
5151 Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
5152 "Helper to extFunCall."
5153 ::=
5154 match extArg
5155 case SIMEXTARG(isArray=true) then
5156 extCArrayArg(extArg, &preExp, &varDecls, &inputAssign, &outputAssign)
5157
5158 case SIMEXTARG(cref=c, isInput=ii, outputIndex=0, type_=t) then
5159 let cr = '<%contextCref2(c,contextFunction)%>'
5160 let byref = match t case T_COMPLEX(complexClassType=RECORD(__)) then '&'
5161 if acceptMetaModelicaGrammar() then
5162 (match t case T_STRING(__) then 'MMC_STRINGDATA(<%cr%>)' else '<%cr%>_ext')
5163 else
5164 '<%byref%><%cr%><%match t case T_STRING(__) then ".c_str()" else "_ext"%>'
5165 case SIMEXTARG(cref=c, isInput=ii, outputIndex=oi, type_=t) then
5166 let extName = extVarName2(c)
5167 let &outputAssign += '<%contextCref2(c,contextFunction)%> = <%extName%>;<%\n%>'
5168 '&<%extName%>'
5169 case SIMEXTARGEXP(__) then
5170 daeExternalCExp(exp, contextFunction, &preExp /*BUFC*/, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
5171 case SIMEXTARGSIZE(cref=c) then
5172 let typeStr = expTypeShort(type_)
5173 let name = contextCref2(c, contextFunction)
5174 let dim = daeExp(exp, contextFunction, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
5175 '<%name%>.getDim(<%dim%>)'
5176 end extArg;
5177
5178
5179 21 template extCArrayArg(SimExtArg extArg, Text &preExp, Text &varDecls /*BUFP*/, Text &inputAssign /*BUFD*/, Text &outputAssign /*BUFD*/)
5180 "Function to convert arrays to external C"
5181 ::=
5182 match extArg
5183 case SIMEXTARG(cref=c, isInput =iI, outputIndex=oi, isArray=true, type_=t)then
5184 let name = contextCref2(c,contextFunction)
5185 match type_
5186 case T_ARRAY(__)then
5187 let dimStr = listLength(dims)
5188 let dimsStr = checkDimension(dims)
5189 let elType = expTypeShort(ty)
5190 let extType = if stringEq(elType, "string") then elType else extType2(ty, true, false)
5191 if stringEq(elType, "string") then
5192 let extName = extVarName2(c)
5193 let &inputAssign += 'CStrArray <%extName%>(<%name%>);<%\n%>'
5194 let &outputAssign += if intGt(oi, 0) then '<%extName%>.writeBack(<%name%>);<%\n%>'
5195 '<%extName%>'
5196 else if boolOr(intGt(listLength(dims), 1), stringEq(elType, "bool")) then
5197 let tmp = match dimsStr
5198 case "" then
5199 tempDecl('DynArrayDim<%listLength(dims)%><<%extType%>>', &varDecls)
5200 else
5201 tempDecl('StatArrayDim<%dimStr%><<%extType%>, <%dimsStr%>>', &varDecls)
5202 let &inputAssign += 'convertArrayLayout(<%name%>, <%tmp%>);'
5203 let &outputAssign += if intGt(oi, 0) then 'convertArrayLayout(<%tmp%>, <%name%>);'
5204 '<%tmp%>.getData()'
5205 else
5206 <<<%if iI then 'ConstArray(<%name%>).getData()'
5207 else '<%name%>.getData()'%>>>
5208 end extCArrayArg;
5209
5210
5211 1 template daeExternalCExp(Exp exp, Context context, Text &preExp /*BUFP*/,Text &varDecls /*BUFP*/, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
5212 "Like daeExp, but also converts the type to external C"
5213 ::=
5214 match typeof(exp)
5215 case T_ARRAY(__) then // Array-expressions
5216 let shortTypeStr = expTypeShort(typeof(exp))
5217 '<%daeExp(exp, context, &preExp, &varDecls,simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>.getData()'
5218 else daeExp(exp, context, &preExp, &varDecls,simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
5219 end daeExternalCExp;
5220
5221 101 template extFunCallVardecl(SimExtArg arg, Text &varDecls /*BUFP*/)
5222 "Helper to extFunCall."
5223 ::=
5224 match arg
5225 case SIMEXTARG(isInput=true, isArray=false, type_=ty, cref=c) then
5226 match ty case T_STRING(__) then
5227 ""
5228 else
5229 let &varDecls += '<%extType2(ty,true,false)%> <%extVarName2(c)%>;<%\n%> '
5230 <<
5231 <%extVarName2(c)%> = (<%extType2(ty,true,false)%>)<%contextCref2(c,contextFunction)%>;
5232 >>
5233 case SIMEXTARG(outputIndex=oi, isArray=false, type_=ty, cref=c) then
5234 match oi case 0 then
5235 ""
5236 else
5237 let &varDecls += '<%extType2(ty,true,false)%> <%extVarName2(c)%>;<%\n%> '
5238 ""
5239 end extFunCallVardecl;
5240
5241
5242 25 template extFunCallBiVar(Variable var, Text &preExp, Text &varDecls, SimCode simCode,
5243 Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace,
5244 Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
5245 "Declare and initialize a local variable in &preExp"
5246 ::=
5247 match var
5248 case var as VARIABLE(__) then
5249 let varName = contextCref2(name, contextFunction)
5250 let defaultValue = match value
5251 case SOME(v) then
5252 daeExp(v, contextFunction, &preExp, &varDecls, simCode,
5253 &extraFuncs, &extraFuncsDecl, extraFuncsNamespace,
5254 stateDerVectorName, useFlatArrayNotation)
5255 else ""
5256 if instDims then
5257 let nDims = listLength(instDims)
5258 let dims = (instDims |> dim => daeDimension(dim, contextFunction, &preExp, &varDecls, simCode,
5259 &extraFuncs, &extraFuncsDecl, extraFuncsNamespace,
5260 stateDerVectorName, useFlatArrayNotation);
5261 separator=", ")
5262 let initializer = if defaultValue then ' = <%defaultValue%>' else '(<%dims%>)'
5263 let &preExp += 'DynArrayDim<%nDims%><<%varType(var)%>> <%varName%><%initializer%>;<%\n%>'
5264 ''
5265 else
5266 let initializer = if defaultValue then ' = <%defaultValue%>'
5267 let &preExp += '<%varType(var)%> <%varName%><%initializer%>;<%\n%>'
5268 ''
5269 end extFunCallBiVar;
5270
5271
5272 5 template extFunCallF77(SimCodeFunction.Function fun, Text &preExp,
5273 Text &varDecls, Text &inputAssign, Text &outputAssign, SimCode simCode,
5274 Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace,
5275 Text stateDerVectorName /*=__zDot*/,
5276 Boolean useFlatArrayNotation)
5277 "Generates the call to an external F77 function."
5278 ::=
5279 match fun
5280 case EXTERNAL_FUNCTION(__) then
5281 let funName = underscorePath(name)
5282 let args = (extArgs |> arg =>
5283 extArgF77(arg, &preExp, &varDecls, &inputAssign, &outputAssign, simCode,
5284 &extraFuncs, &extraFuncsDecl, extraFuncsNamespace,
5285 stateDerVectorName, useFlatArrayNotation);
5286 separator=", ")
5287 let returnVar = match extReturn
5288 case SIMEXTARG(cref=c) then '<%contextCref2(c, contextFunction)%>'
5289 let returnAssign = if returnVar then '<%returnVar%> = '
5290 <<
5291 <%returnAssign%><%extFunctionName(extName, language)%>(<%args%>);
5292 >>
5293 end extFunCallF77;
5294
5295
5296 24 template extArgF77(SimExtArg extArg, Text &preExp, Text &varDecls,
5297 Text &inputAssign, Text &outputAssign, SimCode simCode, Text& extraFuncs,
5298 Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName,
5299 Boolean useFlatArrayNotation)
5300 "Helper to extFunCall. Creates one F77 call argument."
5301 ::=
5302 match extArg
5303 case SIMEXTARG(cref=c, isInput=iI, outputIndex=oi, isArray=true, type_=t) then
5304 let varName = contextCref2(c, contextFunction)
5305 match type_
5306 case T_ARRAY(__) then
5307 let elType = expTypeShort(ty)
5308 let extType = extTypeF77(ty, false, false)
5309 let extName = '<%varName%>_ext'
5310 let nDims = listLength(dims)
5311 if stringEq(elType, "bool") then
5312 let &varDecls += 'DynArrayDim<%nDims%><<%extType%>> <%extName%>;<%\n%>'
5313 let &inputAssign += 'cast_array<bool, int>(<%varName%>, <%extName%>);<%\n%>'
5314 let &outputAssign += if intGt(oi, 0) then 'cast_array<int, bool>(<%extName%>, <%varName%>);<%\n%>'
5315 <<
5316 <%extName%>.getData()
5317 >>
5318 else
5319 let extName = if iI then 'ConstArray(<%varName%>)' else '<%varName%>'
5320 <<
5321 <%extName%>.getData()
5322 >>
5323 end match
5324 case SIMEXTARG(cref=c, type_=t) then
5325 let varName = contextCref2(c, contextFunction)
5326 let varType = expTypeShort(t)
5327 let extType = extTypeF77(t, false, false)
5328 let extName = '<%varName%>_ext'
5329 if stringEq(varType, "string") then
5330 <<
5331 <%varName%>.c_str()
5332 >>
5333 else if stringEq(varType, extType) then
5334 <<
5335 &<%varName%>
5336 >>
5337 else
5338 let &varDecls += '<%extType%> <%extName%>;<%\n%>'
5339 let &inputAssign += '<%extName%> = <%varName%>;<%\n%>'
5340 <<
5341 &<%extName%>
5342 >>
5343 case SIMEXTARGEXP(type_=t) then
5344 // pass a pointer to a temporary variable
5345 let extType = extTypeF77(t, false, false)
5346 let extName = tempDecl(extType, &varDecls)
5347 let &inputAssign += '<%extName%> = <%daeExp(exp, contextFunction, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>;<%\n%>'
5348 <<
5349 <%match t case T_STRING(__) then '' else '&'%><%extName%>
5350 >>
5351 case SIMEXTARGSIZE(cref=c) then
5352 let varName = contextCref2(c, contextFunction)
5353 let extName = tempDecl('int', &varDecls)
5354 let dim = daeExp(exp, contextFunction, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
5355 let &inputAssign += '<%extName%> = <%varName%>.getDim(<%dim%>);<%\n%>'
5356 <<
5357 &<%extName%>
5358 >>
5359 end extArgF77;
5360
5361
5362 276 template varOutput(SimCodeFunction.Function fn, Variable var, Integer ix, Text &varDecls, Text &varInits, Text &varCopy, Text &varAssign, SimCode simCode,
5363 Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
5364 "Generates code to copy result value from a function to dest."
5365 ::=
5366 match fn
5367 case FUNCTION(__)
5368 case EXTERNAL_FUNCTION(__) then
5369 match var
5370 case var as VARIABLE(__) then
5371 if instDims then
5372 let &varAssign += 'output.assign(<%contextCref(var.name,contextFunction,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>);<%\n%>'
5373 ""
5374 else
5375 let &varAssign += 'output = <%contextCref(var.name,contextFunction,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>;<%\n%>'
5376 ""
5377 case var as FUNCTION_PTR(__) then
5378 let &varAssign += 'ToDo: Function Ptr assign'
5379 ""
5380 else "something"
5381 end varOutput;
5382
5383
5384 95 template varOutputTuple(SimCodeFunction.Function fn, Variable var, Integer ix, Text &varDecls, Text &varInits, Text &varCopy, Text &varAssign, SimCode simCode,
5385 Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
5386 "Generates code to copy result value from a function to dest."
5387 ::=
5388 match fn
5389 case FUNCTION(__)
5390 case EXTERNAL_FUNCTION(__) then
5391 let fname = underscorePath(name)
5392 match var
5393 /* The storage size of arrays is known at call time, so they can be allocated
5394 * before set_memory_state. Strings are not known, so we copy them, etc...
5395 */
5396 /*
5397 case var as VARIABLE(ty = T_STRING(__)) then
5398 if not acceptMetaModelicaGrammar() then
5399 // We need to strdup() all strings, then allocate them on the memory pool again, then free the temporary string
5400 let strVar = tempDecl("string", &varDecls)
5401 let &varAssign +=
5402 <<
5403 output = <%strVar%>;
5404 >>
5405 ""
5406 else
5407 let &varAssign += output= <%contextCref(var.name,contextFunction,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,useFlatArrayNotation)%>;<%\n%>'
5408 ""
5409 */
5410 case var as VARIABLE(__) then
5411 let marker = '<%contextCref(var.name,contextFunction,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>'
5412 let &varInits += '// varOutputTuple varInits(<%marker%>)<%\n%>'
5413 let &varAssign += '// varOutput varAssign(<%marker%>)<%\n%>'
5414 let testinstDimsInit = (instDims |> dim => testDaeDimension(dim);separator="")
5415 let instDimsInit = (instDims |> dim => daeDimension(dim, contextFunction, &varInits, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
5416 ;separator=",")
5417 let assginBegin = 'get<<%ix%>>'
5418 if instDims then
5419 // don't setDims for static or unknown dimensions, treated as "" and "---", respectively
5420 let &varInits += if boolAnd(intGt(stringLength(testinstDimsInit), 0), intEq(-1, stringFind(testinstDimsInit, "---"))) then
5421 '<%assginBegin%>(/*_<%fname%>*/output.data).setDims(<%instDimsInit%>);<%\n%>'
5422 let &varAssign += '<%assginBegin%>(/*_<%fname%>*/output.data)=<%contextCref(var.name,contextFunction,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,stateDerVectorName,useFlatArrayNotation)%>;<%\n%>'
5423 ""
5424 else
5425 // let &varInits += initRecordMembers(var)
5426 let &varAssign += ' <%assginBegin%>(/*_<%fname%>*/output.data) = <%contextCref(var.name,contextFunction,simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>/*TestVarAssign5*/;<%\n%> '
5427 "/*testcase1*/"
5428 case var as FUNCTION_PTR(__) then
5429 let &varAssign += '/*_<%fname%>*/ output = (modelica_fnptr) _<%var.name%>;<%\n%>'
5430 "/*testcase2*/"
5431 else
5432 let &varAssign += '/*iregendwas*/'
5433 "/*testcase3*/"
5434 end varOutputTuple;
5435
5436
5437 1311 template varDeclForVarInit(Variable var,String varName, list<DAE.Dimension> instDims, Text &varDecls, Text &varInits, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
5438 ::=
5439 //let instDimsInit = (instDims |> dim => daeDimension(dim, contextFunction, &varInits, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation);separator=",")
5440 let instDimsInit = checkDimension(instDims)
5441 match var
5442 case var as VARIABLE(__) then
5443 let type = '<%varType(var)%>'
5444 let initVar = match type case "modelica_metatype" then ' = NULL' else ''
5445 let addRoot = match type case "modelica_metatype" then ' mmc_GC_add_root(&<%varName%>, mmc_GC_local_state, "<%varName%>");' else ''
5446 //let testinstDimsInit = (instDims |> dim => testDaeDimension(dim);separator="")
5447 //let instDimsInit = (instDims |> dim => daeDimension(dim, contextFunction, &varInits, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation);separator=",")
5448 let arrayexpression1 = (if instDims then 'StatArrayDim<%listLength(instDims)%><<%expTypeShort(var.ty)%>,<%instDimsInit%>> <%varName%>;/*testarray5*/<%\n%>'
5449 else '<%type%> <%varName%><%initVar%>;<%addRoot%><%\n%>')
5450 let arrayexpression2 = (if instDims then 'DynArrayDim<%listLength(instDims)%><<%expTypeShort(var.ty)%>> <%varName%>;<%\n%>'
5451 else '<%type%> <%varName%><%initVar%>;<%addRoot%><%\n%>'
5452 )
5453
5454 match instDimsInit
5455 case "" then
5456 let &varDecls += arrayexpression2
5457 ""
5458 else
5459 let &varDecls += arrayexpression1
5460 ""
5461 end varDeclForVarInit;
5462
5463
5464 1311 template varInit(Variable var, String outStruct, Integer i, Text &varDecls, Text &varInits, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
5465
5466 "Generates code to initialize variables.
5467 Does not return anything: just appends declarations to buffers."
5468 ::=
5469
5470 match var
5471 case var as VARIABLE(__) then
5472 let varName = '<%contextCref(var.name,contextFunction,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>'
5473 let &preExp = buffer ""
5474 let recordInit = initRecordMembers(var, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
5475 let &varInits += if recordInit then
5476 <<
5477 //initRecordMembers <%varName%>
5478 <%preExp%>
5479 <%recordInit%>
5480 >>
5481 let instDimsInit = (instDims |> dim => daeDimension(dim, contextFunction, &varInits , &varDecls,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation);separator=",")
5482
5483
5484 //let varName = if outStruct then 'ToDo: outStruct not implemented' else '<%contextCref(var.name,contextFunction,simCode , &extraFuncs , &extraFuncsDecl, stateDerVectorName, extraFuncsNamespace)%>'
5485 let _ = varDeclForVarInit(var, varName, instDims, &varDecls, &varInits, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
5486
5487 if instDims then
5488 let testinstDimsInit = (instDims |> dim => testDaeDimension(dim);separator="")
5489 let temp = setDims(testinstDimsInit, varName , &varInits, instDimsInit)
5490
5491
5492 (match var.value
5493 case SOME(exp) then
5494
5495 let defaultValue1 = '<%varName%>.assign(<%daeExp(exp, contextFunction, &varInits, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>);<%\n%>'
5496 let &varInits += defaultValue1
5497 ""
5498 else
5499 let defaultValue = varDefaultValue(var, outStruct, i, varName, &varDecls, &varInits, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
5500
5501 let &varInits += defaultValue
5502 ""
5503 )
5504 else
5505 (match var.value
5506 case SOME(exp) then
5507 let defaultValue = '<%contextCref(var.name, contextFunction, simCode ,&extraFuncs ,&extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%> = <%daeExp(exp, contextFunction, &varInits, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>;<%\n%>'
5508 let &varInits += defaultValue
5509 " "
5510 else
5511 "")
5512 case var as FUNCTION_PTR(__) then
5513 let &ignore = buffer ""
5514 let &varDecls += functionArg(var,&ignore)
5515 ""
5516
5517 end varInit;
5518
5519 122 template initRecordMembers(Variable var, Text &preExp /*BUFP*/, Text &varDecls /*BUFP*/,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
5520 "Initialize members of a record variable"
5521 ::=
5522 match var
5523 case VARIABLE(ty = T_COMPLEX(complexClassType = RECORD(__))) then
5524 let varName = contextCref(name, contextFunction, simCode, extraFuncs, extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
5525 (ty.varLst |> v => recordMemberInit(v, varName, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation) ;separator="\n")
5526 end initRecordMembers;
5527
5528 1184 template recordMemberInit(DAE.Var v, Text varName, Text &preExp /*BUFP*/, Text &varDecls /*BUFP*/,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
5529 "Initialize one record member"
5530 ::=
5531 match v
5532 case TYPES_VAR(__) then
5533 let vn = '<%varName%>.<%name%>_'
5534 let defaultValue =
5535 match binding
5536 case VALBOUND(valBound = val) then
5537 '<%vn%> = <%daeExp(ValuesUtil.valueExpNoOriginal(val), contextOther, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>;'
5538 case EQBOUND(evaluatedExp = SOME(val)) then
5539 '<%vn%> = <%daeExp(ValuesUtil.valueExpNoOriginal(val), contextFunction, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>;'
5540 case EQBOUND(exp = exp) then
5541 '<%vn%> = <%daeExp(exp, contextFunction, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>;'
5542 else
5543 ''
5544 end match
5545 <<
5546 <%defaultValue%>
5547 >>
5548 end recordMemberInit;
5549
5550 200 template setDims(Text testinstDimsInit, String varName , Text &varInits, String instDimsInit)
5551 "call varName.setDims for dynamic and known dimensions"
5552 ::=
5553 match testinstDimsInit
5554 case "" then
5555 ""
5556 else
5557 let &varInits += if intEq(-1, stringFind(testinstDimsInit, "---")) then
5558 '<%varName%>.setDims(<%instDimsInit%>);<%\n%>'
5559 ""
5560 end match
5561 end setDims;
5562
5563
5564 ✗ template functionArg(Variable var, Text &varInit)
5565 "Shared code for function arguments that are part of the function variables and valueblocks.
5566 Valueblocks need to declare a reference to the function while input variables
5567 need to initialize."
5568 ::=
5569 match var
5570 case var as FUNCTION_PTR(__) then
5571 let typelist = (args |> arg => mmcVarType(arg) ;separator=", ")
5572 let rettype = '<%name%>RetType /* functionArg */'
5573 match tys
5574 case {} then
5575 let &varInit += '_<%name%> = (void(*)(<%typelist%>)) <%name%><%\n%>;'
5576 'void(*_<%name%>)(<%typelist%>);<%\n%>'
5577 else
5578
5579 let &varInit += '_<%name%> = (<%rettype%>(*)(<%typelist%>)) <%name%>;<%\n%>'
5580 <<
5581 <% tys |> arg hasindex i1 fromindex 1 => '#define <%rettype%>_<%i1%> targTest2<%i1%>' ; separator="\n" %>
5582 typedef struct <%rettype%>_s
5583 {
5584 <% tys |> ty hasindex i1 fromindex 1 => 'modelica_<%mmcTypeShort(ty)%> targTest1<%i1%>;' ; separator="\n" %>
5585 } <%rettype%>;
5586 <%rettype%>(*_<%name%>)(<%typelist%>);<%\n%>
5587 >>
5588 end match
5589 end functionArg;
5590
5591 ✗ template mmcVarType(Variable var)
5592 ::=
5593 match var
5594 case VARIABLE(__) then 'modelica_<%mmcTypeShort(ty)%>'
5595 case FUNCTION_PTR(__) then 'modelica_fnptr'
5596 end mmcVarType;
5597
5598 ✗ template mmcTypeShort(DAE.Type type)
5599 ::=
5600 match type
5601 case T_INTEGER(__) then "integer"
5602 case T_REAL(__) then "real"
5603 case T_STRING(__) then "string"
5604 case T_BOOL(__) then "integer"
5605 case T_ENUMERATION(__) then "integer"
5606 case T_ARRAY(__) then "array"
5607 case T_METATYPE(__) case T_METABOXED(__) then "metatype"
5608 case T_FUNCTION_REFERENCE_VAR(__) then "fnptr"
5609 else "mmcTypeShort:ERROR"
5610 end mmcTypeShort;
5611
5612 ✗ template extVarName(ComponentRef cr, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
5613 ::= '<%contextCref(cr,contextFunction,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>_ext'
5614 end extVarName;
5615
5616 222 template extVarName2(ComponentRef cr)
5617 ::= '<%contextCref2(cr,contextFunction)%>_ext'
5618 end extVarName2;
5619
5620 91 template varDefaultValue(Variable var, String outStruct, Integer i, String lhsVarName, Text &varDecls, Text &varInits, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
5621 ::=
5622 match var
5623 case var as VARIABLE(__) then
5624 match value
5625 case SOME(CREF(componentRef = cr)) then
5626 '<%contextCref(cr,contextFunction, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%> = <%outStruct%>.targTest9<%i%><%\n%>'
5627 case SOME(arr as ARRAY(__)) then
5628 let arrayExp = '<%daeExp(arr, contextFunction, &varInits, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>'
5629 <<
5630 <%lhsVarName%> = <%arrayExp%>;<%\n%>
5631 >>
5632 end varDefaultValue;
5633
5634
5635 1516 template funArgDefinition(Variable var,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
5636 ::=
5637 match var
5638 case VARIABLE(__) then '<%varType1(var, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)%> <%contextCref(name, contextFunction, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>'
5639 case FUNCTION_PTR(__) then 'modelica_fnptr <%name%>'
5640 end funArgDefinition;
5641
5642 ✗ template funArgDefinition2(Variable var,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
5643 ::=
5644 match var
5645 case VARIABLE(__) then '<%varType3(var, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)%> <%contextCref(name,contextFunction,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>'
5646 case FUNCTION_PTR(__) then 'modelica_fnptr <%name%>'
5647 end funArgDefinition2;
5648
5649 ✗ template funExtArgDefinition(SimExtArg extArg,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
5650 ::=
5651 match extArg
5652 case SIMEXTARG(cref=c, isInput=ii, isArray=ia, type_=t) then
5653 let name = contextCref(c,contextFunction,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
5654 let typeStr = expTypeFlag(t,5)
5655 <<
5656 <%typeStr%> <%name%>
5657 >>
5658 case SIMEXTARGEXP(__) then
5659 let typeStr = expTypeFlag(type_,5)
5660 <<
5661 <%typeStr%>
5662 >>
5663 case SIMEXTARGSIZE(cref=c) then
5664 <<
5665 size_t
5666 >>
5667 end funExtArgDefinition;
5668
5669 357 template funReturnDefinition1(Variable var,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
5670 ::=
5671 match var
5672 case VARIABLE(__) then '<%varType3(var,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)%>'
5673 case FUNCTION_PTR(__) then 'modelica_fnptr <%name%>'
5674 end funReturnDefinition1;
5675
5676 244 template funReturnDefinition2(Variable var, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
5677 ::=
5678 match var
5679 case VARIABLE(__) then '<%varType2(var, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>'
5680 case FUNCTION_PTR(__) then 'modelica_fnptr <%name%>'
5681 end funReturnDefinition2;
5682
5683 1336 template varType(Variable var)
5684 "Generates type for a variable."
5685 ::=
5686 match var
5687 case var as VARIABLE(__) then
5688 if instDims then
5689 expTypeShort(var.ty)
5690 else
5691 expTypeArrayIf(var.ty)
5692 end varType;
5693
5694
5695 3100 template varType1(Variable var, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace)
5696 ::=
5697 match var
5698 case var as VARIABLE(__) then
5699 /*Always use BaseArray as function array argument types */
5700 if instDims then 'BaseArray<<%expTypeShort(ty)%>>&' else expTypeFlag(var.ty, 8)
5701 /* uses StatArrray if possible else Dynarray as function array argument types
5702 let &varDecls = buffer ""
5703 let &varInits = buffer ""
5704 let testinstDimsInit = (instDims |> dim => testDaeDimension(dim);separator="")
5705
5706 match testinstDimsInit
5707 case "" then
5708 let instDimsInit = (instDims |> exp => daeDimensionExp(exp);separator=",")
5709 if instDims then 'StatArrayDim<%listLength(instDims)%>< <%expTypeShort(var.ty)%>, <%instDimsInit%> > ' else expTypeFlag(var.ty, 8)
5710 else
5711 if instDims then 'DynArrayDim<%listLength(instDims)%><<%expTypeShort(var.ty)%>> ' else expTypeFlag(var.ty, 8)
5712
5713 end match
5714 */
5715 end varType1;
5716
5717 244 template varType2(Variable var, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
5718 ::=
5719 match var
5720 case var as VARIABLE(__) then
5721 /*uses StatArrray if possible else Dynarray as function array argument types */
5722 let &varDecls = buffer ""
5723 let &varInits = buffer ""
5724 let testinstDimsInit = (instDims |> dim => testDaeDimension(dim);separator="")
5725 let instDimsInit = (instDims |> dim => daeDimension(dim, contextFunction, &varInits, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation);separator=",")
5726 // check for static and known dimension
5727 if boolAnd(stringEq(testinstDimsInit, ""), intEq(-1, stringFind(testinstDimsInit, "---"))) then
5728 if instDims then 'StatArrayDim<%listLength(instDims)%><<%expTypeShort(var.ty)%>, <%instDimsInit%>>& ' else expTypeFlag(var.ty, 5)
5729 else
5730 if instDims then 'DynArrayDim<%listLength(instDims)%><<%expTypeShort(var.ty)%>>/*<%instDimsInit%>*/&' else expTypeFlag(var.ty, 5)
5731 end varType2;
5732
5733 561 template varType3(Variable var, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace)
5734 ::=
5735 match var
5736 case var as VARIABLE(__) then
5737 let &varDecls = buffer "" // should be empty
5738 let &varInits = buffer "" // should be empty
5739 let testinstDimsInit = (instDims |> dim => testDaeDimension(dim);separator="")
5740 let instDimsInit = (instDims |> dim => daeDimension(dim, contextFunction, &varInits, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, "stateDerVectorName_not_given", false /*is false the default?*/);separator=",")
5741 // check for static and known dimension
5742 if boolAnd(stringEq(testinstDimsInit, ""), intEq(-1, stringFind(testinstDimsInit, "---"))) then
5743 if instDims then 'StatArrayDim<%listLength(instDims)%><<%expTypeShort(var.ty)%>, <%instDimsInit%>> ' else expTypeArrayIf(var.ty)
5744 else
5745 if instDims then 'DynArrayDim<%listLength(instDims)%><<%expTypeShort(var.ty)%>>/*<%instDimsInit%>*/ ' else expTypeArrayIf(var.ty)
5746 end varType3;
5747
5748 280 template funStatement(list<DAE.Statement> statementLst, Text &varDecls, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
5749 "Generates function statements."
5750 ::=
5751 statementLst |> stmt => algStatement(stmt, contextFunction, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation) ; separator="\n"
5752 end funStatement;
5753
5754 49 template destructExtObjs(SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
5755 ::=
5756 match simCode
5757 case SIMCODE(modelInfo = MODELINFO(__)) then
5758 let externalObjsFuncs = functionExternalObjects('<%lastIdentOfPath(modelInfo.name)%>Initialize', extObjInfo, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, useFlatArrayNotation)
5759 <<
5760 <%externalObjsFuncs%>
5761 >>
5762 end match
5763 end destructExtObjs;
5764
5765 49 template destructExtObjsDecl(SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Boolean useFlatArrayNotation)
5766 ::=
5767 match simCode
5768 case SIMCODE(modelInfo = MODELINFO(__)) then
5769 <<
5770
5771 void destructExternalObjects();
5772 bool _constructedExternalObjects;
5773 >>
5774 end match
5775 end destructExtObjsDecl;
5776
5777
5778 49 template init(SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation, Text& complexStartExpressions)
5779 ::=
5780 match simCode
5781 case SIMCODE(modelInfo = MODELINFO(__),makefileParams = MAKEFILE_PARAMS(__)) then
5782 //let () = System.tmpTickReset(0)
5783 let &varDecls = buffer "" /*BUFD*/
5784 let modelname = identOfPathDot(modelInfo.name)
5785 let initFunctions = functionInitial(startValueEquations, varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
5786 let initZeroCrossings = functionOnlyZeroCrossing(zeroCrossings,varDecls,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)
5787 let initEventHandling = eventHandlingInit(simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)
5788 let initClockIntervals = clockIntervalsInit(simCode, &varDecls, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
5789 let initAlgloopSolvers = initAlgloopsolvers(listAppend(listAppend(allEquations, initialEquations), getClockedEquations(getSubPartitions(clockedPartitions))),simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace)
5790
5791 <<
5792 // convenience function for full initialization
5793 void <%lastIdentOfPath(modelInfo.name)%>Initialize::initialize()
5794 {
5795 initializeMemory();
5796 initializeFreeVariables();
5797 initializeBoundVariables();
5798 saveAll();
5799 }
5800
5801 void <%lastIdentOfPath(modelInfo.name)%>Initialize::initializeMemory()
5802 {
5803 _discrete_events = _event_handling->initialize(this,getSimVars());
5804
5805 //create and initialize Algloopsolvers
5806 <%generateAlgloopSystems(listAppend(listAppend(allEquations, initialEquations), getClockedEquations(getSubPartitions(clockedPartitions))), simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace)%>
5807 <%generateAlgloopSolvers(modelInfo,listAppend(listAppend(allEquations, initialEquations), getClockedEquations(getSubPartitions(clockedPartitions))), simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace)%>
5808
5809 <%lastIdentOfPath(modelInfo.name)%>WriteOutput::initialize();
5810 <%lastIdentOfPath(modelInfo.name)%>Jacobian::initialize();
5811 <%lastIdentOfPath(modelInfo.name)%>Jacobian::initializeColoredJacobianA();
5812 }
5813
5814 <%if(boolAnd(boolNot(Flags.isSet(Flags.HARDCODED_START_VALUES)), Flags.isSet(Flags.GEN_DEBUG_SYMBOLS))) then
5815 <<
5816 void <%lastIdentOfPath(modelInfo.name)%>Initialize::checkParameters()
5817 {
5818 checkParameterVars();
5819 checkIntParameterVars();
5820 checkBoolParameterVars();
5821 checkStringParameterVars();
5822 }
5823
5824 void <%lastIdentOfPath(modelInfo.name)%>Initialize::checkVariables()
5825 {
5826 /*check functions are only available if genDebugSymbols was selected*/
5827 checkAlgVars();
5828 checkDiscreteAlgVars();
5829 checkIntAlgVars();
5830 checkBoolAlgVars();
5831 checkStringAlgVars();
5832 //checkStateVars();
5833 //checkDerVars();
5834 }
5835 >>
5836 %>
5837
5838 void <%lastIdentOfPath(modelInfo.name)%>Initialize::initializeFreeVariables()
5839 {
5840 #if !defined(FMU_BUILD)
5841 _reader = shared_ptr<IPropertyReader>(new XmlPropertyReader(_global_settings, "<%fileNamePrefix%>_init.xml"));
5842 _reader->readInitialValues(*this, getSimVars());
5843 #endif
5844
5845 _simTime = 0.0;
5846 _state_var_reinitialized = false;
5847
5848 <%if (Flags.isSet(Flags.HARDCODED_START_VALUES)) then
5849 <<
5850 /*initialize parameter*/
5851 initializeParameterVars();
5852 initializeIntParameterVars();
5853 initializeBoolParameterVars();
5854 initializeStringParameterVars();
5855 initializeAlgVars();
5856 initializeDiscreteAlgVars();
5857 initializeIntAlgVars();
5858 initializeBoolAlgVars();
5859 initializeStateVars();
5860 initializeDerVars();
5861 >>
5862 %>
5863
5864 #if defined(__TRICORE__) || defined(__vxworks)
5865 //init inputs
5866 stepStarted(0.0);
5867 #endif
5868
5869 /* Start complex expressions */
5870 <%complexStartExpressions%>
5871 /* End complex expression */
5872 <%if(boolAnd(boolNot(Flags.isSet(Flags.HARDCODED_START_VALUES)), Flags.isSet(Flags.GEN_DEBUG_SYMBOLS))) then 'checkParameters();' else '//checkParameters();'%>
5873 //delete reader;
5874 }
5875
5876 void <%lastIdentOfPath(modelInfo.name)%>Initialize::initializeBoundVariables()
5877 {
5878 //variable decls
5879 <%varDecls%>
5880
5881 //destruct external objects if already constructed in a previous call
5882 if (_constructedExternalObjects)
5883 destructExternalObjects();
5884
5885 initParameterEquations();
5886
5887 //mark external objects constructed during initParameterEquations
5888 _constructedExternalObjects = true;
5889
5890 //bound start values
5891 <%initFunctions%>
5892
5893 //init event handling
5894 <%initEventHandling%>
5895 <%initClockIntervals%>
5896
5897 //init equations
5898 initEquations();
5899
5900 for(int i = 0; i < _dimZeroFunc; i++)
5901 {
5902 getCondition(i);
5903 }
5904
5905 //initialAnalyticJacobian();
5906
5907 <%functionInitDelay(delayedExps,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>
5908
5909 <%if(boolAnd(boolNot(Flags.isSet(Flags.HARDCODED_START_VALUES)), Flags.isSet(Flags.GEN_DEBUG_SYMBOLS))) then 'checkVariables();' else '//checkVariables();'%>
5910 }
5911
5912 void <%lastIdentOfPath(modelInfo.name)%>Initialize::initEquations()
5913 {
5914 <%(List.partition(initialEquations, 100) |> eqs hasindex i0 =>
5915 createInitWithSplit(i0, contextOther, eqs, "initEquations", "initEquation", simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace)
5916 ; separator="\n")%>
5917 }
5918 <%functionInitialEquations(initialEquations, "initEquation",
5919 simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation, false, true, false)%>
5920 void <%lastIdentOfPath(modelInfo.name)%>Initialize::initParameterEquations()
5921 {
5922 <%(List.partition(parameterEquations, 100) |> eqs hasindex i0 =>
5923 createInitWithSplit(i0, contextOther, eqs, "initParameterEquations", "initParameterEquation", simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace)
5924 ; separator="\n")%>
5925 }
5926 <%functionInitialEquations(parameterEquations, "initParameterEquation",
5927 simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation, false, true, true)%>
5928 <%init2(simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, modelInfo, stateDerVectorName, useFlatArrayNotation)%>
5929 >>
5930 end match
5931 end init;
5932
5933
5934 49 template init2(SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, ModelInfo modelInfo, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
5935 ::=
5936 match modelInfo
5937 case modelInfo as MODELINFO(vars=SIMVARS(__)) then
5938
5939 //let () = System.tmpTickReset(0)
5940 let &varDecls1 = buffer "" /*BUFD*/
5941 let &varDecls2 = buffer "" /*BUFD*/
5942
5943 let functionPrefix = if Flags.isSet(Flags.HARDCODED_START_VALUES) then "initialize" else "check"
5944 let init1 = initValst(varDecls1, "Real", vars.stateVars, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, contextOther, stateDerVectorName, useFlatArrayNotation)
5945 let init2 = initValst(varDecls2, "Real", vars.derivativeVars, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, contextOther, stateDerVectorName, useFlatArrayNotation)
5946
5947 if(boolOr(Flags.isSet(Flags.HARDCODED_START_VALUES), Flags.isSet(Flags.GEN_DEBUG_SYMBOLS))) then
5948 <<
5949 void <%lastIdentOfPath(modelInfo.name)%>Initialize::<%functionPrefix%>StateVars()
5950 {
5951 <%varDecls1%>
5952 <%init1%>
5953 }
5954 void <%lastIdentOfPath(modelInfo.name)%>Initialize::<%functionPrefix%>DerVars()
5955 {
5956 <%varDecls2%>
5957 <%init2%>
5958 }
5959 >>
5960 else ''
5961 end init2;
5962
5963
5964 144 template createInitWithSplit(Integer sectionIndex, Context context, list<SimEqSystem> sectionEquations, String functionName, String functionCallName, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace)
5965 ::=
5966 let init_func_calls = (sectionEquations |> eq =>
5967 equation_function_call(eq, context, simCode, functionCallName)
5968 ;separator="\n")
5969 let &extraFuncs +=
5970 <<
5971 <%\n%>void <%extraFuncsNamespace%>::<%functionName%>_<%sectionIndex%>()
5972 {
5973 <%init_func_calls%>
5974 }
5975 >>
5976 let &extraFuncsDecl +=
5977 <<
5978 void <%functionName%>_<%sectionIndex%>();<%\n%>
5979 >>
5980 <<
5981 <%functionName%>_<%sectionIndex%>();
5982 >>
5983 end createInitWithSplit;
5984
5985
5986 49 template functionExternalObjects(Text className, ExtObjInfo extObjInfo, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Boolean useFlatArrayNotation)
5987 "Generates the method destructExternalObjects."
5988 ::=
5989 match extObjInfo
5990 case EXTOBJINFO(__) then
5991 let dtorCalls = (vars |> var as SIMVAR(varKind=ext as EXTOBJ(), initialValue=SOME(exp)) hasindex idx =>
5992 <<
5993 _functions-><%underscorePath(ext.fullClassName)%>_destructor(<%cref(var.name, useFlatArrayNotation)%>);
5994 >>
5995 ;separator="\n")
5996 <<
5997 void <%className%>::destructExternalObjects()
5998 {
5999 <%dtorCalls%>
6000 }
6001 >>
6002 end match
6003 end functionExternalObjects;
6004
6005
6006 98 template functionInitialEquations(list<SimEqSystem> initalEquations, Text methodName, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation, Boolean createMeasureTime, Boolean assignToStartValues, Boolean overwriteOldStartValues)
6007 "Generates function in simulation file."
6008 ::=
6009 let equation_func_calls = (initalEquations |> eq =>
6010 equation_function_create_single_func(eq, contextOther, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace,methodName, "Initialize", stateDerVectorName, useFlatArrayNotation, createMeasureTime, assignToStartValues, overwriteOldStartValues, "")
6011 ;separator="\n")
6012
6013 <<
6014 <%equation_func_calls%>
6015 >>
6016 end functionInitialEquations;
6017
6018 121 template initAlgloop(SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, SimEqSystem eq, Context context, Integer clockIndex, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
6019 ::=
6020 match simCode
6021 case SIMCODE(modelInfo = MODELINFO(__)) then
6022 let modelname = lastIdentOfPath(modelInfo.name)
6023
6024 match eq
6025 case SES_NONLINEAR(nlSystem = nls as NONLINEARSYSTEM(__)) then
6026 let &varDecls = buffer ""
6027 let &preExp = buffer ""
6028 <<
6029 void <%modelname%>Algloop<%nls.index%>::initialize()
6030 {
6031 <%if intGt(clockIndex, 0) then 'const int clockIndex = <%clockIndex%>;'%>
6032
6033 if(_firstcall)
6034 {
6035 getReal(_x0);
6036 _firstcall=false;
6037 }
6038
6039 }
6040 >>
6041 case SES_LINEAR(lSystem = ls as LINEARSYSTEM(__)) then
6042
6043 match ls.jacobianMatrix
6044 case SOME(__) then
6045 <<
6046 void <%modelname%>Algloop<%ls.index%>::initialize()
6047 {
6048 <%if intGt(clockIndex, 0) then 'const int clockIndex = <%clockIndex%>;'%>
6049
6050 }
6051 >>
6052 else
6053 /* deactivated: should be generated with codegeneration flag usematrix_t
6054 <<
6055 void <%modelname%>Algloop<%ls.index%>::initialize()
6056 {
6057
6058
6059 <%alocateLinearSystem(eq)%>
6060 if(_useSparseFormat)
6061 <%modelname%>Algloop<%ls.index%>::initialize(__Asparse.get());
6062 else
6063 {
6064 fill_array(*__A,0.0);
6065 <%modelname%>Algloop<%ls.index%>::initialize(__A.get());
6066 }
6067
6068
6069 }
6070 >>
6071 */
6072 <<
6073
6074 void <%modelname%>Algloop<%ls.index%>::initialize()
6075 {
6076 <%if intGt(clockIndex, 0) then 'const int clockIndex = <%clockIndex%>;'%>
6077
6078 }
6079 >>
6080 end initAlgloop;
6081
6082 ✗ template initAlgloopTemplate(SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, SimEqSystem eq, Context context, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
6083 ::=
6084 match simCode
6085 case SIMCODE(modelInfo = MODELINFO(__)) then
6086 let modelname = lastIdentOfPath(modelInfo.name)
6087 //let &varDecls = buffer ""
6088 //let &preExp = buffer ""
6089 //let initalgvars = initAlgloopvars(preExp,varDecls,modelInfo,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,context,useFlatArrayNotation)
6090
6091 match eq
6092 /*
6093 case SES_NONLINEAR(__) then
6094 <<
6095 template <typename T>
6096 void <%modelname%>Algloop<%index%>::initialize(T *__A)
6097 {
6098 <%initAlgloopEquation(eq,varDecls,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,context,useFlatArrayNotation)%>
6099 AlgLoopDefaultImplementation::initialize();
6100
6101 // Update the equations once before start of simulation
6102 evaluate();
6103 }
6104 >>
6105 */
6106 case SES_LINEAR(lSystem = ls as LINEARSYSTEM(__)) then
6107 match ls.jacobianMatrix
6108 case SOME(__) then
6109 ""
6110 else
6111 <<
6112 template <typename T>
6113 void <%modelname%>Algloop<%ls.index%>::initialize(T *__A)
6114 {
6115 <%initAlgloopEquation(eq, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, context, stateDerVectorName, useFlatArrayNotation)%>
6116 // Update the equations once before start of simulation
6117 evaluate();
6118 }
6119 >>
6120 end initAlgloopTemplate;
6121
6122
6123 121 template getAMatrixCode(SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, SimEqSystem eq)
6124 ::=
6125 match simCode
6126 case SIMCODE(modelInfo = MODELINFO(__)) then
6127 let modelName = lastIdentOfPath(modelInfo.name)
6128
6129 match eq
6130 /* in case only sparsity pattern is available handle for now as empty */
6131 case SES_NONLINEAR(nlSystem = nls as NONLINEARSYSTEM(jacobianMatrix = SOME(JAC_MATRIX(columns={})))) then
6132 <<
6133
6134 const matrix_t& <%modelName%>Algloop<%nls.index%>::getSystemMatrix()
6135 {
6136 // return empty matrix to indicate that no symbolic Jacobian is available
6137 static matrix_t empty(0, 0);
6138 return empty;
6139 }
6140
6141 sparsematrix_t& <%modelName%>Algloop<%nls.index%>::getSystemSparseMatrix()
6142 {
6143 throw ModelicaSimulationError(MATH_FUNCTION, "Sparse symbolic Jacobian is not suported yet");
6144 }
6145 >>
6146
6147 case SES_NONLINEAR(nlSystem = nls as NONLINEARSYSTEM(jacobianMatrix = SOME(JAC_MATRIX(jacobianIndex=index)))) then
6148 <<
6149
6150 const matrix_t& <%modelName%>Algloop<%nls.index%>::getSystemMatrix()
6151 {
6152 return static_cast<<%modelName%>Mixed*>(_system)->getJacobian(<%index%>);
6153 }
6154
6155 sparsematrix_t& <%modelName%>Algloop<%nls.index%>::getSystemSparseMatrix()
6156 {
6157 throw ModelicaSimulationError(MATH_FUNCTION, "Sparse symbolic Jacobian is not suported yet");
6158 }
6159 >>
6160
6161 case SES_NONLINEAR(nlSystem = nls as NONLINEARSYSTEM(__)) then
6162 <<
6163
6164 const matrix_t& <%modelName%>Algloop<%nls.index%>::getSystemMatrix()
6165 {
6166 // return empty matrix to indicate that no symbolic Jacobian is available
6167 static matrix_t empty(0, 0);
6168 return empty;
6169 }
6170
6171 sparsematrix_t& <%modelName%>Algloop<%nls.index%>::getSystemSparseMatrix()
6172 {
6173 throw ModelicaSimulationError(MATH_FUNCTION, "Sparse symbolic Jacobian is not suported yet");
6174 }
6175 >>
6176
6177 case SES_LINEAR(lSystem = ls as LINEARSYSTEM(__)) then
6178 match ls.jacobianMatrix
6179 case SOME(JAC_MATRIX(jacobianIndex=index)) then
6180 let type = getConfigString(MATRIX_FORMAT)
6181 let getDenseMatrix = match type
6182 case ("dense") then
6183 'return static_cast<<%modelName%>Mixed*>(_system)->getJacobian(<%index%>);'
6184 case ("sparse") then
6185 'throw ModelicaSimulationError(MATH_FUNCTION, "Dense matrix is not activated");'
6186 else "A matrix type is not supported"
6187 end match
6188 let getSparseMatrix = match type
6189 case ("dense") then
6190 'throw ModelicaSimulationError(MATH_FUNCTION, "Sparse matrix is not activated");'
6191 case ("sparse") then
6192 'return static_cast<<%modelName%>Mixed*>(_system)->getSparseJacobian(<%index%>);'
6193 else "A matrix type is not supported"
6194 end match
6195 <<
6196
6197 const matrix_t& <%modelName%>Algloop<%ls.index%>::getAMatrix()
6198 {
6199 <%getDenseMatrix%>
6200 }
6201
6202 sparsematrix_t& <%modelName%>Algloop<%ls.index%>::getSparseAMatrix( )
6203 {
6204 <%getSparseMatrix%>
6205 }
6206 >>
6207
6208 else
6209 let type = getConfigString(MATRIX_FORMAT)
6210 let getDenseMatrix = match type
6211 case ("dense") then
6212 'return __A;'
6213 case ("sparse") then
6214 'throw ModelicaSimulationError(MATH_FUNCTION, "Dense matrix is not activated");'
6215 else "A matrix type is not supported"
6216 end match
6217 let getSparseMatrix = match type
6218 case ("dense") then
6219 'throw ModelicaSimulationError(MATH_FUNCTION, "Sparse matrix is not activated");'
6220 case ("sparse") then
6221 'return __A;'
6222 else "A matrix type is not supported"
6223 end match
6224 <<
6225
6226 const matrix_t& <%modelName%>Algloop<%ls.index%>::getAMatrix()
6227 {
6228 <%getDenseMatrix%>
6229 }
6230
6231 sparsematrix_t& <%modelName%>Algloop<%ls.index%>::getSparseAMatrix()
6232 {
6233 <%getSparseMatrix%>
6234 }
6235 >>
6236
6237 end getAMatrixCode;
6238
6239
6240 242 template algloopRHSCode(SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace,SimEqSystem eq)
6241 ::=
6242 match simCode
6243 case SIMCODE(modelInfo = MODELINFO(__)) then
6244 let modelname = lastIdentOfPath(modelInfo.name)
6245 let &varDecls = buffer ""
6246 let &preExp = buffer ""
6247
6248
6249 match eq
6250 case SES_NONLINEAR(nlSystem = nls as NONLINEARSYSTEM(__)) then
6251 <<
6252 void <%modelname%>Algloop<%nls.index%>::getRHS(double* residuals) const
6253 {
6254 NonLinearAlgLoopDefaultImplementation::getRHS(residuals);
6255 }
6256
6257 >>
6258 case SES_LINEAR(lSystem = ls as LINEARSYSTEM(__)) then
6259 match ls.jacobianMatrix
6260 case SOME(__) then
6261 <<
6262 void <%modelname%>Algloop<%ls.index%>::getb(double* residuals) const
6263 {
6264 LinearAlgLoopDefaultImplementation::getb(residuals);
6265 }
6266
6267 >>
6268 else
6269 <<
6270 void <%modelname%>Algloop<%ls.index%>::getb(double* residuals) const
6271 {
6272 memcpy(residuals,__b.getData(),sizeof(double)* _dimAEq);
6273 }
6274 >>
6275 end algloopRHSCode;
6276
6277 ✗ template algloopResiduals(SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace,SimEqSystem eq)
6278 ::=
6279 match simCode
6280 case SIMCODE(modelInfo = MODELINFO(__)) then
6281 let modelname = lastIdentOfPath(modelInfo.name)
6282 match eq
6283 case SES_LINEAR(lSystem = ls as LINEARSYSTEM(__)) then
6284 <<
6285 void <%modelname%>Algloop<%ls.index%>::getb(double* vars) const
6286 {
6287 LinearAlgLoopDefaultImplementation::getb(vars);
6288 }
6289 >>
6290 case SES_NONLINEAR(nlSystem = nls as NONLINEARSYSTEM(__)) then
6291 <<
6292
6293 void <%modelname%>Algloop<%nls.index%>::getRHS(double* vars) const
6294 {
6295 NonLinearAlgLoopDefaultImplementation::getRHS(vars);
6296 }
6297 >>
6298 case SES_MIXED(__) then algloopResiduals(simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,cont)
6299 end algloopResiduals;
6300
6301 121 template isLinearTearingCode(SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace,SimEqSystem eq)
6302 ::=
6303 match simCode
6304 case SIMCODE(modelInfo = MODELINFO(__)) then
6305 let modelname = lastIdentOfPath(modelInfo.name)
6306 let &varDecls = buffer ""
6307 let &preExp = buffer ""
6308
6309 match eq
6310 case SES_NONLINEAR(nlSystem = nls as NONLINEARSYSTEM(__)) then
6311 <<
6312
6313 bool <%modelname%>Algloop<%nls.index%>::isLinearTearing()
6314 {
6315 return false;
6316 }
6317 >>
6318 case SES_LINEAR(lSystem = ls as LINEARSYSTEM(__)) then
6319 match ls.jacobianMatrix
6320 case SOME(__) then
6321 <<
6322
6323 bool <%modelname%>Algloop<%ls.index%>::isLinearTearing()
6324 {
6325 return true;
6326 }
6327 >>
6328 else
6329 <<
6330
6331 bool <%modelname%>Algloop<%ls.index%>::isLinearTearing()
6332 {
6333 return false;
6334 }
6335 >>
6336 end isLinearTearingCode;
6337
6338
6339 ✗ template initAlgloopEquation(SimEqSystem eq, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Context context, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
6340 "Generates a non linear equation system."
6341 ::=
6342 let &varDeclsCref = buffer "" /*BUFD*/
6343 let type = getConfigString(MATRIX_FORMAT)
6344 match eq
6345 case SES_NONLINEAR(nlSystem = nls as NONLINEARSYSTEM(__)) then
6346 let size = listLength(nls.crefs)
6347 <<
6348
6349 <%nls.crefs |> name hasindex i0 =>
6350 let namestr = contextCref(name, context, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
6351 <<
6352 _res[<%i0%>] = <%namestr%>;
6353 >>
6354 ;separator="\n"%>
6355 >>
6356 case SES_LINEAR(lSystem = ls as LINEARSYSTEM(__)) then
6357 match ls.jacobianMatrix
6358 case SOME(__) then
6359 let &varDecls = buffer "" /*BUFD*/
6360 let prebody = (ls.residual |> eq2 =>
6361 functionExtraResidualsPreBody(eq2, &varDecls, context, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
6362 ;separator="\n")
6363 let body = (ls.residual |> eq2 as SES_RESIDUAL(__) hasindex i0 =>
6364 let &preExp = buffer "" /*BUFD*/
6365 let expPart = daeExp(eq2.exp, context, &preExp, &varDecls, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
6366 '<%preExp%>_b[<%i0%>] = <%expPart%>;'
6367 ;separator="\n")
6368 <<
6369 <%varDecls%>
6370 //prebody
6371 <%prebody%>
6372 //body
6373 <%body%>
6374 >>
6375 else
6376 let &varDecls = buffer "" /*BUFD*/
6377 let Amatrix =
6378 (ls.simJac |> (row, col, eq as SES_RESIDUAL(__)) hasindex i0 fromindex 0 =>
6379 let &preExp = buffer ""
6380 let expPart = daeExp(eq.exp, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
6381 '<%preExp%>__A(<%row%>,<%col%>)=<%expPart%>;'
6382 ;separator="\n")
6383
6384 let bvector = (ls.beqs |> exp hasindex i0 fromindex 1=>
6385 let &preExp = buffer ""
6386 let expPart = daeExp(exp, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
6387 '<%preExp%>__b(<%i0%>)=<%expPart%>;'
6388 ;separator="\n")
6389 <<
6390 <%varDecls%>
6391 <%Amatrix%>
6392 <%bvector%>
6393 >>
6394 end initAlgloopEquation;
6395
6396
6397 121 template getAlgloopVars(SimEqSystem eq, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Context context, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
6398 "Generates a non linear equation system."
6399 ::=
6400 let &varDeclsCref = buffer "" /*BUFD*/
6401 match eq
6402 case SES_NONLINEAR(nlSystem = nls as NONLINEARSYSTEM(__)) then
6403 let size = listLength(nls.crefs)
6404 <<
6405
6406 <%nls.crefs |> name hasindex i0 =>
6407 let &preExpElem = buffer ""
6408 let namestr = lhsCref(name, context, &preExpElem, &varDeclsCref, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
6409 <<
6410 vars[<%i0%>] = <%namestr%>;
6411 >>
6412 ;separator="\n"
6413 %>
6414 >>
6415 case SES_LINEAR(lSystem = ls as LINEARSYSTEM(__)) then
6416 <<
6417 <%ls.vars |> SIMVAR(__) hasindex i0 => 'vars[<%i0%>] = <%cref1(name, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace,context, varDeclsCref, stateDerVectorName, useFlatArrayNotation)%>;' ;separator="\n"%>
6418 >>
6419 end getAlgloopVars;
6420
6421 121 template initAlgloopVarAttributes(SimEqSystem eq, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Context context, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
6422 "Initializes a vector of AlgLoopVar for the equation system."
6423 ::=
6424 let &preExp = buffer ""
6425 let &varDecls = buffer ""
6426 let vars = match eq
6427 case SES_NONLINEAR(nlSystem = nls as NONLINEARSYSTEM(__)) then
6428 (nls.crefs |> cref hasindex i0 =>
6429 let initializer = createAlgloopVarAttributes(cref2simvar(cref, simCode), cref, preExp, varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, context, stateDerVectorName, useFlatArrayNotation)
6430 '_vars[<%i0%>] = <%initializer%>;'
6431 ;separator="\n")
6432 case SES_LINEAR(lSystem = ls as LINEARSYSTEM(__)) then
6433 (ls.vars |> var as SIMVAR(__) hasindex i0 =>
6434 let initializer = createAlgloopVarAttributes(var, name, preExp, varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, context, stateDerVectorName, useFlatArrayNotation)
6435 '_vars[<%i0%>] = <%initializer%>;'
6436 ;separator="\n")
6437 <<
6438 <%varDecls%>
6439 <%preExp%>
6440 <%vars%>
6441 >>
6442 end initAlgloopVarAttributes;
6443
6444 211 template algloopVarAttrElem(Text expPart, Exp exp, ComponentRef elemCr, Context context, Text &preExp, Text &varDecls, SimCode simCode,
6445 Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
6446 "Attribute (nominal/min/max) of one iteration variable. A non-scalarized array variable has a
6447 single array-valued attribute, so pick the element the (fully subscripted) cref selects."
6448 ::=
6449 if boolAnd(isArrayType(typeof(exp)),
6450 boolAnd(intEq(listLength(crefSubs(elemCr)), listLength(crefDims(elemCr))), crefSubIsScalar(elemCr)))
6451 then
6452 let subsStr = (crefSubs(elemCr) |> INDEX(__) =>
6453 daeExp(exp, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
6454 ;separator=",")
6455 '<%expPart%>(<%subsStr%>)'
6456 else
6457 expPart
6458 end algloopVarAttrElem;
6459
6460 381 template createAlgloopVarAttributes(SimVar var, ComponentRef elemCr, Text &preExp, Text &varDecls, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Context context, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
6461 "Returns the initializer for one AlgLoopVar."
6462 ::=
6463 let nameStr = match var case SIMVAR(name=cref) then
6464 crefStrForWriteOutput(cref)
6465
6466 let nominalStr = match var
6467 case SIMVAR(nominalValue=SOME(exp)) then
6468 let expPart = daeExp(exp, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
6469 algloopVarAttrElem(expPart, exp, elemCr, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
6470 // fallback for state derivatives lacking nominal value: use nominal value of state
6471 case SIMVAR(varKind = STATE_DER(), name = CREF_QUAL(componentRef = stateCref)) then
6472 match cref2simvar(stateCref, simCode)
6473 case SIMVAR(nominalValue=SOME(exp)) then
6474 let expPart = daeExp(exp, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
6475 '<%expPart%>'
6476 else
6477 '1.0'
6478 end match
6479 else
6480 '1.0'
6481
6482 let minStr = match var
6483 case SIMVAR(varKind=STATE_DER()) then
6484 '-HUGE_VAL'
6485 case SIMVAR(minValue=SOME(exp)) then
6486 let expPart = daeExp(exp, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
6487 algloopVarAttrElem(expPart, exp, elemCr, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
6488 else
6489 '-HUGE_VAL'
6490
6491 let maxStr = match var
6492 case SIMVAR(varKind=STATE_DER()) then
6493 'HUGE_VAL'
6494 case SIMVAR(maxValue=SOME(exp)) then
6495 let expPart = daeExp(exp, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
6496 algloopVarAttrElem(expPart, exp, elemCr, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
6497 else
6498 'HUGE_VAL'
6499
6500 'AlgloopVarAttributes("<%nameStr%>", <%nominalStr%>, <%minStr%>, <%maxStr%>)'
6501 end createAlgloopVarAttributes;
6502
6503 ✗ template writeAlgloopvars(list<list<SimEqSystem>> continousEquations,list<SimEqSystem> discreteEquations, list<SimEqSystem> parameterEquations,
6504 SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace,Context context, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
6505 ::=
6506 let &varDecls = buffer "" /*BUFD*/
6507 let algloopsolver = (continousEquations |> eqs => (eqs |> eq =>
6508 writeAlgloopvars2(eq, context, &varDecls /*BUFC*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation))
6509 ;separator=" ")
6510
6511 <<
6512 <%algloopsolver%>
6513 >>
6514 end writeAlgloopvars;
6515
6516
6517 ✗ template writeAlgloopvars2(SimEqSystem eq, Context context, Text &varDecls, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
6518 "Generates an equation.
6519 This template should not be used for a SES_RESIDUAL.
6520 Residual equations are handled differently."
6521 ::=
6522 match eq
6523 case e as SES_NONLINEAR(nlSystem = nls as NONLINEARSYSTEM(__)) then
6524 let size = listLength(nls.crefs)
6525 <<
6526 double algloopvars<%nls.index%>[<%size%>];
6527 _algLoop<%nls.index%>->getReal(algloopvars<%nls.index%>);
6528 <%nls.crefs |> name hasindex i0 =>
6529 let namestr = cref(name, useFlatArrayNotation)
6530 <<
6531 <%namestr%> = algloopvars<%nls.index%>[<%i0%>];
6532 >>
6533 ;separator="\n"%>
6534
6535 >>
6536 case e as SES_LINEAR(lSystem = ls as LINEARSYSTEM(__)) then
6537 let size = listLength(ls.vars)
6538 let algloopid = ls.index
6539 let &varDeclsCref = buffer "" /*BUFD*/
6540 <<
6541 double algloopvars<%algloopid%>[<%size%>];
6542 _algLoop<%ls.index%>->getReal(algloopvars<%algloopid%>,NULL,NULL);
6543
6544 <%ls.vars |> SIMVAR(__) hasindex i0 => '<%cref1(name,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,context,varDeclsCref,stateDerVectorName,useFlatArrayNotation)%> = algloopvars<%algloopid%>[<%i0%>];' ;separator="\n"%>
6545
6546
6547 >>
6548 end writeAlgloopvars2;
6549
6550
6551 121 template setAlgloopVars(SimEqSystem eq,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace,Context context, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
6552 "Generates a non linear equation system."
6553 ::=
6554 let &varDeclsCref = buffer "" /*BUFD*/
6555 match eq
6556 case SES_NONLINEAR(nlSystem = nls as NONLINEARSYSTEM(__)) then
6557 let size = listLength(nls.crefs)
6558 <<
6559
6560 <%nls.crefs |> name hasindex i0 =>
6561 let &preExpElem = buffer ""
6562 let namestr = lhsCref(name, context, &preExpElem, &varDeclsCref, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
6563 match name
6564 case CREF_QUAL(ident = "$PRE") then
6565 let varname = '_system-><%cref(componentRef, useFlatArrayNotation)%>'
6566 <<
6567 <%varname%> = vars[<%i0%>];
6568 _discrete_events->save(<%varname%>,<%varname%>);
6569 >>
6570 else
6571 <<
6572 <%namestr%> = vars[<%i0%>];
6573 >>
6574 ;separator="\n"%>
6575 >>
6576 case SES_LINEAR(lSystem = ls as LINEARSYSTEM(__)) then
6577 <<
6578 <%ls.vars |> SIMVAR(__) hasindex i0 => '<%cref1(name, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, context, varDeclsCref, stateDerVectorName, useFlatArrayNotation)%> = vars[<%i0%>];' ;separator="\n"%>
6579 >>
6580 end setAlgloopVars;
6581
6582 121 template initAlgloopDimension(SimEqSystem eq, Text &varDecls /*BUFP*/)
6583 "Generates a non linear equation system."
6584 ::=
6585 match eq
6586 case SES_NONLINEAR(nlSystem = nls as NONLINEARSYSTEM(__)) then
6587 let size = listLength(nls.crefs)
6588 <<
6589 _dimAEq = <%size%>;
6590 NonLinearAlgLoopDefaultImplementation::initialize();
6591 >>
6592 case SES_LINEAR(lSystem = ls as LINEARSYSTEM(__)) then
6593 match ls.jacobianMatrix
6594 case SOME(__) then
6595 let size = listLength(ls.vars)
6596 <<
6597 // Number of unknowns equations
6598 _dimAEq = <%size%>;
6599 LinearAlgLoopDefaultImplementation::initialize();
6600 >>
6601 else
6602 let size = listLength(ls.vars)
6603 <<
6604 // Number of unknowns/equations according to type (0: double, 1: int, 2: bool)
6605 _dimAEq = <%size%>;
6606 LinearAlgLoopDefaultImplementation::initialize();
6607 fill_array(__b, 0.0);
6608 >>
6609 end initAlgloopDimension;
6610
6611 ✗ template alocateLinearSystem(SimEqSystem eq)
6612 "Generates a non linear equation system."
6613 ::=
6614 match eq
6615 case SES_LINEAR(lSystem = ls as LINEARSYSTEM(__)) then
6616 let size = listLength(ls.vars)
6617 <<
6618 if(_useSparseFormat)
6619 __Asparse = shared_ptr<matrix_t> (new matrix_t);
6620 else
6621 __A = shared_ptr<AMATRIX>( new AMATRIX());
6622 >>
6623 end alocateLinearSystem;
6624
6625 48 template update(SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
6626 ::=
6627 match simCode
6628 case SIMCODE(__) then
6629 <<
6630 <%equationFunctions(allEquations, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,contextSimulationDiscrete,stateDerVectorName,useFlatArrayNotation,boolNot(stringEq(getConfigString(PROFILING_LEVEL),"none")))%>
6631
6632 <%clockedFunctions(getSubPartitions(clockedPartitions), simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, contextSimulationDiscrete, stateDerVectorName, useFlatArrayNotation, boolNot(stringEq(getConfigString(PROFILING_LEVEL), "none")))%>
6633
6634 <%createEvaluateAll(allEquations, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,contextOther, stateDerVectorName, useFlatArrayNotation, boolNot(stringEq(getConfigString(PROFILING_LEVEL),"none")))%>
6635
6636 <%createEvaluate(odeEquations, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,contextOther, boolNot(stringEq(getConfigString(PROFILING_LEVEL),"none")))%>
6637
6638 <%createEvaluateZeroFuncs(equationsForZeroCrossings,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,contextOther)%>
6639
6640 <%createEvaluateConditions(allEquations, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,contextOther, stateDerVectorName, useFlatArrayNotation)%>
6641 >>
6642 end update;
6643
6644
6645 49 template writeoutput(SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
6646 ::=
6647 match simCode
6648 case SIMCODE(modelInfo = MODELINFO(__),simulationSettingsOpt = SOME(settings as SIMULATION_SETTINGS(__))) then
6649 let numParamvars = numProtectedParamVars(modelInfo)
6650 <<
6651
6652 void <%lastIdentOfPath(modelInfo.name)%>WriteOutput::writeOutput(const IWriteOutput::OUTPUT command)
6653 {
6654
6655 const output_int_vars_t& outputIntVars = _reader->getIntOutVars();
6656 const output_real_vars_t& outputRealVars = _reader->getRealOutVars();
6657 const output_bool_vars_t& outputBoolVars = _reader->getBoolOutVars();
6658 const output_der_vars_t& outputDerVars = _reader->getDerOutVars();
6659 const output_res_vars_t& outputResVars = _reader->getResOutVars();
6660
6661 //Write head line
6662 if (command & IWriteOutput::HEAD_LINE)
6663 {
6664 const all_names_t outputVarNames = make_tuple(outputRealVars.outputVarNames,outputIntVars.outputVarNames,outputBoolVars.outputVarNames,outputDerVars.outputVarNames,outputResVars.outputVarNames);
6665 const all_description_t outputVarDescription = make_tuple(outputRealVars.outputVarDescription,outputIntVars.outputVarDescription,outputBoolVars.outputVarDescription,outputDerVars.outputVarDescription,outputResVars.outputVarDescription);
6666 <%
6667 match settings.outputFormat
6668 case "mat" then
6669 <<
6670 const all_names_t parameterVarNames = make_tuple(outputRealVars.parameterNames,outputIntVars.parameterNames,outputBoolVars.parameterNames,outputDerVars.outputVarNames,outputResVars.outputVarNames);
6671 const all_description_t parameterVarDescription = make_tuple(outputRealVars.parameterDescription,outputIntVars.parameterDescription,outputBoolVars.parameterDescription,outputDerVars.outputVarDescription,outputResVars.outputVarDescription);
6672 >>
6673 else
6674 <<
6675 const all_names_t parameterVarNames;
6676 const all_description_t parameterVarDescription;
6677 >>
6678 %>
6679 _writeOutput->write(outputVarNames,outputVarDescription,parameterVarNames,parameterVarDescription);
6680 <%
6681 match settings.outputFormat
6682 case "mat" then
6683 <<
6684 const all_vars_t params = make_tuple(outputRealVars.outputParams,outputIntVars.outputParams,outputBoolVars.outputParams,outputDerVars.outputParams,outputResVars.outputParams);
6685 >>
6686 else
6687 <<
6688 const all_vars_t params;
6689 >>
6690 %>
6691 _writeOutput->write(params,_global_settings->getStartTime(),_global_settings->getEndTime());
6692 }
6693 //Write the current values
6694 else
6695 {
6696 <%generateMeasureTimeStartCode("measuredFunctionStartValues", "writeOutput", "MEASURETIME_MODELFUNCTIONS")%>
6697 <%if Flags.isSet(Flags.WRITE_TO_BUFFER) then
6698 <<
6699
6700 <%(allEquations |> eqs => (eqs |> eq => writeoutputAlgloopsolvers(eq,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace));separator="\n")%>
6701 double residues [] = {<%(allEquations |> eqn => writeoutput3(eqn, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation));separator=","%>};
6702 output_res_vars_t _resVars;
6703 for(int i=0;i<<%numResidues(allEquations,modelInfo)%>;i++)
6704 {
6705 double* realVarPtr = &residues[i];
6706 string str;
6707 _resVars.addOutputVar(str, str,realVarPtr, false);
6708
6709 }
6710
6711 <%generateMeasureTimeEndCode("measuredFunctionStartValues", "measuredFunctionEndValues", "(*measureTimeFunctionsArray)[2]", "writeOutput", "MEASURETIME_MODELFUNCTIONS")%>
6712 write_data_t& container = _writeOutput->getFreeContainer();
6713 all_vars_time_t all_vars = make_tuple(outputRealVars.outputVars,outputIntVars.outputVars,outputBoolVars.outputVars,_simTime,outputDerVars.outputVars,_resVars.outputVars);
6714 neg_all_vars_t neg_all_vars = make_tuple(outputRealVars.negateOutputVars,outputIntVars.negateOutputVars,outputBoolVars.negateOutputVars,outputDerVars.negateOutputVars,_resVars.negateOutputVars);
6715 _writeOutput->addContainerToWriteQueue(make_tuple(all_vars,neg_all_vars));
6716
6717 >>
6718 else
6719 <<
6720 <%generateMeasureTimeEndCode("measuredFunctionStartValues", "measuredFunctionEndValues", "(*measureTimeFunctionsArray)[2]", "writeOutput", "MEASURETIME_MODELFUNCTIONS")%>
6721 write_data_t& container = _writeOutput->getFreeContainer();
6722 all_vars_time_t all_vars = make_tuple(outputRealVars.outputVars,outputIntVars.outputVars,outputBoolVars.outputVars,_simTime,outputDerVars.outputVars,outputResVars.outputVars);
6723 neg_all_vars_t neg_all_vars = make_tuple(outputRealVars.negateOutputVars,outputIntVars.negateOutputVars,outputBoolVars.negateOutputVars,outputDerVars.negateOutputVars,outputResVars.negateOutputVars);
6724 _writeOutput->addContainerToWriteQueue(make_tuple(all_vars,neg_all_vars));
6725 >>
6726 %>
6727 }
6728 }
6729 >>
6730 //<%writeAlgloopvars(odeEquations,algebraicEquations, parameterEquations,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)%>
6731 end writeoutput;
6732 /*
6733 <%if Flags.isSet(Flags.WRITE_TO_BUFFER) then
6734 <<
6735
6736 <%(allEquations |> eqs => (eqs |> eq => writeoutputAlgloopsolvers(eq,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace));separator="\n")%>
6737 double residues [] = {<%(allEquations |> eqn => writeoutput3(eqn, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation));separator=","%>};
6738 output_res_vars_t _resVars;
6739 for(int i=0;i<<%numResidues(allEquations)%>;i++)
6740 {
6741 double* realVarPtr = &residues[i];
6742 string str;
6743 _resVars.addOutputVar(str, str,realVarPtr, false);
6744
6745 }
6746
6747 <%generateMeasureTimeEndCode("measuredFunctionStartValues", "measuredFunctionEndValues", "(*measureTimeFunctionsArray)[2]", "writeOutput", "MEASURETIME_MODELFUNCTIONS")%>
6748 write_data_t& container = _writeOutput->getFreeContainer();
6749 all_vars_time_t all_vars = make_tuple(outputRealVars.outputVars,outputIntVars.outputVars,outputBoolVars.outputVars,_simTime,outputDerVars.outputVars,_resVars.outputVars);
6750 neg_all_vars_t neg_all_vars = make_tuple(outputRealVars.negateOutputVars,outputIntVars.negateOutputVars,outputBoolVars.negateOutputVars,outputDerVars.negateOutputVars,_resVars.negateOutputVars);
6751 _writeOutput->addContainerToWriteQueue(make_tuple(all_vars,neg_all_vars));
6752
6753 >>
6754 else
6755 <<
6756 <%generateMeasureTimeEndCode("measuredFunctionStartValues", "measuredFunctionEndValues", "(*measureTimeFunctionsArray)[2]", "writeOutput", "MEASURETIME_MODELFUNCTIONS")%>
6757 write_data_t& container = _writeOutput->getFreeContainer();
6758 all_vars_time_t all_vars = make_tuple(outputRealVars.outputVars,outputIntVars.outputVars,outputBoolVars.outputVars,_simTime,outputDerVars.outputVars,outputResVars.outputVars);
6759 neg_all_vars_t neg_all_vars = make_tuple(outputRealVars.negateOutputVars,outputIntVars.negateOutputVars,outputBoolVars.negateOutputVars,outputDerVars.negateOutputVars,outputResVars.negateOutputVars);
6760 _writeOutput->addContainerToWriteQueue(make_tuple(all_vars,neg_all_vars));
6761 >>
6762 %>
6763 */
6764 ✗ template writeoutputAlgloopsolvers(SimEqSystem eq, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
6765 ::=
6766 match eq
6767 case SES_LINEAR(lSystem = ls as LINEARSYSTEM(__))
6768 then
6769 let num = ls.index
6770 match simCode
6771 case SIMCODE(modelInfo = MODELINFO(__)) then
6772 <<
6773 double* doubleResiduals<%num%> = new double[_algLoop<%num%>->getDimReal()];
6774 _algLoop<%num%>->getb(doubleResiduals<%num%>);
6775 >>
6776 end match
6777 case SES_NONLINEAR(nlSystem = nls as NONLINEARSYSTEM(__))
6778 then
6779 let num = nls.index
6780 match simCode
6781 case SIMCODE(modelInfo = MODELINFO(__)) then
6782 <<
6783 double* doubleResiduals<%num%> = new double[_algLoop<%num%>->getDimReal()];
6784 _algLoop<%num%>->getRHS(doubleResiduals<%num%>);
6785 >>
6786 end match
6787 case SES_MIXED(__)
6788 then
6789 let num = index
6790 match simCode
6791 case SIMCODE(modelInfo = MODELINFO(__)) then
6792 <<
6793 double* doubleResiduals<%num%> = new double[_algLoop<%num%>->getDimReal()];
6794 _algLoop<%num%>->getb(doubleResiduals<%num%>);
6795
6796 >>
6797 end match
6798 else
6799 " "
6800 end match
6801 end writeoutputAlgloopsolvers;
6802
6803 ✗ template writeoutput3(SimEqSystem eqn, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
6804 ::=
6805 match eqn
6806 case SES_RESIDUAL(__) then
6807 <<
6808 >>
6809 case SES_SIMPLE_ASSIGN(__) then
6810 let &varDeclsCref = buffer "" /*BUFD*/
6811 <<
6812 <%cref1(cref,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,contextOther,varDeclsCref,stateDerVectorName,useFlatArrayNotation)%>
6813 >>
6814 case SES_ARRAY_CALL_ASSIGN(__) then
6815 <<
6816 >>
6817 case SES_ALGORITHM(__) then
6818 <<
6819 >>
6820 case e as SES_LINEAR(lSystem = ls as LINEARSYSTEM(__)) then
6821 <<
6822 <%(ls.vars |> var hasindex myindex2 => writeoutput4(ls.index,myindex2));separator=",";empty%>
6823 >>
6824 case e as SES_NONLINEAR(nlSystem = nls as NONLINEARSYSTEM(__)) then
6825 <<
6826 <%(nls.eqs |> eq hasindex myindex2 => writeoutput4(nls.index,myindex2));separator=",";empty%>
6827 >>
6828 case SES_MIXED(__) then writeoutput3(cont,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
6829 case SES_WHEN(__) then
6830 <<
6831 >>
6832 else
6833 <<
6834 >>
6835 end writeoutput3;
6836
6837 ✗ template writeoutput4(Integer index, Integer myindex2)
6838 ::=
6839 <<
6840 *(doubleResiduals<%index%>+<%myindex2%>)
6841 >>
6842 end writeoutput4;
6843
6844 49 template generateHeaderIncludeString(SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
6845 "Generates header part of simulation file."
6846 ::=
6847 match simCode
6848 case SIMCODE(modelInfo=MODELINFO(__), extObjInfo=EXTOBJINFO(__)) then
6849 <<
6850 #pragma once
6851 #if defined(__TRICORE__) || defined(__vxworks)
6852 #define BOOST_EXTENSION_SYSTEM_DECL
6853 #define BOOST_EXTENSION_EVENTHANDLING_DECL
6854 #endif
6855
6856 <%
6857 match(getConfigString(PROFILING_LEVEL))
6858 case("none") then ''
6859 case("all_perf") then
6860 <<
6861 #ifdef USE_SCOREP
6862 #include <Core/Utils/extension/measure_time_scorep.hpp>
6863 #else
6864 #include <Core/Utils/extension/measure_time_papi.hpp>
6865 #endif
6866 >>
6867 case("all_stat") then
6868 <<
6869 #ifdef USE_SCOREP
6870 #include <Core/Utils/extension/measure_time_scorep.hpp>
6871 #else
6872 #include <Core/Utils/extension/measure_time_statistic.hpp>
6873 #endif
6874 >>
6875 else
6876 <<
6877 #ifdef USE_SCOREP
6878 #include <Core/Utils/extension/measure_time_scorep.hpp>
6879 #else
6880 #include <Core/Utils/extension/measure_time_rdtsc.hpp>
6881 #endif
6882 >>
6883 end match
6884 %>
6885
6886 #include <Core/System/SystemDefaultImplementation.h>
6887
6888 //Forward declaration to speed-up the compilation process
6889 class EventHandling;
6890 class DiscreteEvents;
6891 <%algloopForwardDeclaration(listAppend(listAppend(allEquations, initialEquations), getClockedEquations(getSubPartitions(clockedPartitions))), simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace)%>
6892
6893 /*****************************************************************************
6894 *
6895 * Simulation code for <%lastIdentOfPath(modelInfo.name)%> generated by the OpenModelica Compiler.
6896 * System class <%lastIdentOfPath(modelInfo.name)%> implements the Interface IMixedSystem
6897 *
6898 *****************************************************************************/
6899 >>
6900 end generateHeaderIncludeString;
6901
6902
6903
6904 121 template generateAlgloopHeaderInlcudeString(SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace,Context context)
6905 "Generates header part of simulation file."
6906 ::=
6907 match simCode
6908 case SIMCODE(modelInfo=MODELINFO(__), extObjInfo=EXTOBJINFO(__)) then
6909 let modelname = lastIdentOfPath(modelInfo.name)
6910 let systemname = match context case ALGLOOP_CONTEXT(genInitialisation=false,genJacobian=true) then '<%modelname%>Jacobian' else '<%modelname%>'
6911 <<
6912 #pragma once
6913 #if defined(__TRICORE__)
6914 #define BOOST_EXTENSION_ALGLOOPDEFAULTIMPL_DECL
6915 #define BOOST_EXTENSION_EVENTHANDLING_DECL
6916 #endif
6917
6918 //class EventHandling;
6919 class <%systemname%>;
6920 class Functions;
6921 >>
6922 end generateAlgloopHeaderInlcudeString;
6923
6924 49 template generateClassDeclarationCode(SimCode simCode, Context context, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace,
6925 String additionalPublicMembers, String additionalProtectedMembers, String memberVariableDefinitions,
6926 Boolean useFlatArrayNotation)
6927 "Generates class declarations."
6928 ::=
6929 match simCode
6930 case SIMCODE(modelInfo = MODELINFO(__)) then
6931
6932 let friendclasses = generatefriendAlgloops(listAppend(listAppend(allEquations, initialEquations), getClockedEquations(getSubPartitions(clockedPartitions))), simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace)
6933 let algloopsolvers = generateAlgloopsolverVariables(modelInfo,simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace)
6934
6935 let algloopsystems = generateAlgloopsSystemVariables(listAppend(listAppend(allEquations, initialEquations), getClockedEquations(getSubPartitions(clockedPartitions))), simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace )
6936 let jacalgloopsystems = (jacobianMatrices |> JAC_MATRIX(columns=mat) hasindex index0 =>
6937 (mat |> JAC_COLUMN(columnEqns=eqs) => generateAlgloopsSystemVariables(eqs, simCode, &extraFuncs , &extraFuncsDecl, extraFuncsNamespace) ;separator="\n")
6938 ;separator="")
6939
6940 let memberfuncs = generateEquationMemberFuncDecls(allEquations,"evaluate")
6941 let clockedfuncs = generateClockedFuncDecls(getSubPartitions(clockedPartitions), "evaluate")
6942 let conditionvariables = conditionvariable(zeroCrossings, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace)
6943
6944 match modelInfo
6945 case MODELINFO(vars=SIMVARS(__)) then
6946 let getstringvars = (List.partition(listAppend(listAppend(vars.stringAlgVars, vars.stringParamVars), vars.stringAliasVars), 100) |> ls hasindex idx =>
6947 <<
6948 void getString_<%idx%>(string* z);
6949 >>
6950 ;separator="\n")
6951 let auxiliaryVarDecls = match simCode
6952 case SIMCODE(daeModeData=SOME(DAEMODEDATA(auxiliaryVars=auxiliaryVars))) then
6953 (auxiliaryVars |> var =>
6954 (match var
6955 case SIMVAR(__) then
6956 '<%expTypeShort(type_)%> <%cref(name, false)%>;'
6957 end match)
6958 ;separator="\n")
6959
6960 <<
6961 <%if boolNot(stringEq(getConfigString(PROFILING_LEVEL),"none")) then
6962 <<
6963 #define MEASURETIME_MODELFUNCTIONS
6964 >>%>
6965
6966 class <%lastIdentOfPath(modelInfo.name)%>: public SystemDefaultImplementation
6967 {
6968 <%friendclasses%>
6969 public:
6970 <%additionalPublicMembers%>
6971
6972 <%lastIdentOfPath(modelInfo.name)%>(IGlobalSettings* globalSettings, shared_ptr<ISimObjects> simObjects );
6973 <%lastIdentOfPath(modelInfo.name)%>(<%lastIdentOfPath(modelInfo.name)%> &instance);
6974
6975 virtual ~<%lastIdentOfPath(modelInfo.name)%>();
6976
6977 <%generateMethodDeclarationCode(simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)%>
6978 virtual bool getCondition(unsigned int index);
6979
6980 shared_ptr<IAlgLoopSolverFactory> getAlgLoopSolverFactory();
6981
6982 protected:
6983 //Methods:
6984 <% /*match context case FMI_CONTEXT(__) then*/
6985 <<
6986 <%getstringvars%>
6987 >>
6988 %>
6989 bool isConsistent();
6990
6991 //Saves all variables before an event is handled, is needed for the pre, edge and change operator
6992 void saveAll();
6993
6994 void initStateVars();
6995 void initDerivativeVars();
6996 void initAlgVars();
6997 void initDiscreteAlgVars();
6998 void initIntAlgVars();
6999 void initBoolAlgVars();
7000 void initStringAlgVars();
7001 void initParameterRealVars();
7002 void initParameterIntVars();
7003 void initParameterBoolVars();
7004 void initParameterStringVars();
7005 void initAliasRealVars();
7006 void initAliasIntVars();
7007 void initAliasBoolVars();
7008 void initAliasStringVars();
7009
7010 void deleteObjects();
7011
7012 //Variables:
7013 shared_ptr<EventHandling> _event_handling;
7014 shared_ptr<DiscreteEvents> _discrete_events;
7015 bool _state_var_reinitialized;
7016
7017 //pointer to simVars-array to speedup simulation and compile time
7018 double* _pointerToRealVars;
7019 int* _pointerToIntVars;
7020 bool* _pointerToBoolVars;
7021 string* _pointerToStringVars;
7022
7023 int _dimPartitions;
7024 bool* _partitionActivation;
7025 int* _stateActivator;
7026
7027 <%memberVariableDefinitions%>
7028 /*auxiliary DAE variables*/
7029 <%auxiliaryVarDecls%>
7030 <%conditionvariables%>
7031 Functions* _functions;
7032
7033 shared_ptr<IPropertyReader> _reader;
7034 shared_ptr<IAlgLoopSolverFactory> _algLoopSolverFactory; ///< Factory that provides an appropriate solver
7035 <%algloopsolvers%>
7036 <%algloopsystems%>
7037 <%jacalgloopsystems%>
7038 <% if boolNot(stringEq(getConfigString(PROFILING_LEVEL),"none")) then
7039 <<
7040 #ifdef MEASURETIME_PROFILEBLOCKS
7041 std::vector<MeasureTimeData*> *measureTimeProfileBlocksArray;
7042 MeasureTimeValues *measuredProfileBlockStartValues, *measuredProfileBlockEndValues;
7043 #endif //MEASURETIME_PROFILEBLOCKS
7044 #ifdef MEASURETIME_MODELFUNCTIONS
7045 std::vector<MeasureTimeData*> *measureTimeFunctionsArray;
7046 MeasureTimeValues *measuredFunctionStartValues, *measuredFunctionEndValues;
7047 #endif //MEASURETIME_MODELFUNCTIONS
7048 >>%>
7049 /// Equations
7050 <%memberfuncs%>
7051 /// Clocked synchronous equations
7052 void evaluateClocked(int index);
7053 <%clockedfuncs%>
7054 <%additionalProtectedMembers%>
7055 /*Additional member functions*/
7056 <%extraFuncsDecl%>
7057 };
7058 >>
7059 /*! Equations Array. pointers to all the equation functions listed above stored in this
7060 array. It is used to randomly access and evaluate a single equation by index.
7061 */
7062
7063
7064 //void initialize_equations_array();
7065 /*
7066
7067 typedef void (<%lastIdentOfPath(modelInfo.name)%>::*EquFuncPtr)();
7068 boost::array< EquFuncPtr, <%listLength(allEquations)%> > equations_array;
7069 */
7070 end generateClassDeclarationCode;
7071
7072 49 template generateClockedFuncDecls(list<SimCode.SubPartition> subPartitions, Text method)
7073 ::=
7074 let decls = (subPartitions |> subPartition hasindex i fromindex 1 =>
7075 match subPartition case SUBPARTITION(__) then
7076 <<
7077 /// Clocked partition <%i%>
7078 void evaluateClocked<%i%>(const UPDATETYPE command);
7079
7080
7081 <%generateEquationMemberFuncDecls(listAppend(equations, removedEquations), method)%>
7082 >>
7083 ; separator="\n")
7084 '<%decls%>'
7085 end generateClockedFuncDecls;
7086
7087 168 template generateEquationMemberFuncDecls(list<SimEqSystem> allEquations,Text method)
7088 ::=
7089 match allEquations
7090 case _ then
7091 let equation_func_decls = (allEquations |> eq => generateEquationMemberFuncDecls2(eq,method) ;separator="\n")
7092 <<
7093 <%equation_func_decls%>
7094 >>
7095 end match
7096 end generateEquationMemberFuncDecls;
7097
7098 10785 template generateEquationMemberFuncDecls2(SimEqSystem eq,Text method)
7099 ::=
7100 match eq
7101 case e as SES_MIXED(__) then
7102 <<
7103 void <%method%>_<%equationIndex(e.cont)%>();
7104 void <%method%>_<%equationIndex(eq)%>();
7105 >>
7106 else
7107 <<
7108 FORCE_INLINE void <%method%>_<%equationIndex(eq)%>();
7109 >>
7110 end match
7111 end generateEquationMemberFuncDecls2;
7112
7113 121 template generateAlgloopClassDeclarationCode(SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, SimEqSystem eq, Context context, Boolean useFlatArrayNotation)
7114 "Generates class declarations."
7115 ::=
7116 match simCode
7117 case SIMCODE(modelInfo = MODELINFO(__)) then
7118 let modelname = lastIdentOfPath(modelInfo.name)
7119 let systemname = match context case ALGLOOP_CONTEXT(genInitialisation=false,genJacobian=true) then '<%modelname%>Jacobian' else '<%modelname%>'
7120 let amatrix = match eq case SES_LINEAR(lSystem = ls as LINEARSYSTEM(__)) then
7121 let size = listLength(ls.vars)
7122 let type = getConfigString(MATRIX_FORMAT)
7123 match type
7124 case ("dense") then
7125 <<
7126 matrix_t __A; //dense
7127
7128 //b vector
7129 StatArrayDim1<double,<%size%>> __b;
7130 >>
7131 case ("sparse") then
7132 <<
7133 sparsematrix_t __A; //sparse
7134
7135 //b vector
7136 StatArrayDim1<double,<%size%>> __b;
7137 >>
7138 else "A matrix type is not supported"
7139 end match
7140 let algvars = memberVariableAlgloop(modelInfo, useFlatArrayNotation)
7141 let constructorParams = constructorParamAlgloop(modelInfo, useFlatArrayNotation)
7142 match eq
7143 case SES_LINEAR(lSystem = ls as LINEARSYSTEM(__)) then
7144 let type = getConfigString(MATRIX_FORMAT)
7145
7146 <<
7147 class <%modelname%>Algloop<%ls.index%>: public ILinearAlgLoop, public LinearAlgLoopDefaultImplementation
7148 {
7149 public:
7150 <%modelname%>Algloop<%ls.index%>(<%systemname%>* system,
7151 double* z, double* zDot, bool* conditions,
7152 shared_ptr<DiscreteEvents> discrete_events);
7153 virtual ~<%modelname%>Algloop<%ls.index%>();
7154
7155 <%generateAlgloopMethodDeclarationCode(simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace)%>
7156
7157 /// Provide the right hand side (residuals)
7158 virtual void getb(double* vars) const;
7159 virtual const matrix_t& getAMatrix() ;
7160 virtual sparsematrix_t& getSparseAMatrix() ;
7161
7162 bool getFreeVariablesLock();
7163 bool getUseSparseFormat();
7164
7165 void setUseSparseFormat(bool value);
7166 float queryDensity();
7167 virtual int getDimZeroFunc() const;
7168 private:
7169 AlgloopVarAttributes _vars[<%listLength(ls.vars)%>];
7170 Functions* _functions;
7171 //states
7172 double* __z;
7173 //state derivatives
7174 double* __zDot;
7175 // A matrix
7176 <%amatrix%>
7177 bool* _conditions;
7178 shared_ptr<DiscreteEvents> _discrete_events;
7179 <%systemname%>* _system;
7180 /*Additional member functions*/
7181 <%extraFuncsDecl%>
7182 };
7183 >>
7184 case SES_NONLINEAR(nlSystem = nls as NONLINEARSYSTEM(__)) then
7185 <<
7186 class <%modelname%>Algloop<%nls.index%>: public INonLinearAlgLoop, public NonLinearAlgLoopDefaultImplementation
7187 {
7188 public:
7189 <%modelname%>Algloop<%nls.index%>(<%systemname%>* system,
7190 double* z,double* zDot, bool* conditions,
7191 shared_ptr<DiscreteEvents> discrete_events);
7192 virtual ~<%modelname%>Algloop<%nls.index%>();
7193
7194 <%generateAlgloopMethodDeclarationCode(simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace)%>
7195
7196 /// Provide the right hand side (residuals)
7197 virtual void getRHS(double* vars) const;
7198 virtual const matrix_t& getSystemMatrix() ;
7199 virtual sparsematrix_t& getSystemSparseMatrix() ;
7200
7201 bool getUseSparseFormat();
7202 void setUseSparseFormat(bool value);
7203 float queryDensity();
7204 virtual int getDimZeroFunc() const;
7205 private:
7206 AlgloopVarAttributes _vars[<%listLength(nls.crefs)%>];
7207 Functions* _functions;
7208 //states
7209 double* __z;
7210 //state derivatives
7211 double* __zDot;
7212 bool* _conditions;
7213 shared_ptr<DiscreteEvents> _discrete_events;
7214 <%systemname%>* _system;
7215 /*Additional member functions*/
7216 <%extraFuncsDecl%>
7217 };
7218 >>
7219 end generateAlgloopClassDeclarationCode;
7220
7221 49 template DefaultImplementationCode(SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
7222 ::=
7223 match simCode
7224 case SIMCODE(modelInfo = MODELINFO(vars=SIMVARS(stateVars=states))) then
7225 <<
7226 // Release instance
7227 void <%lastIdentOfPath(modelInfo.name)%>::destroy()
7228 {
7229 delete this;
7230 }
7231
7232 // Computes the conditions of time event samplers for the current time
7233 double <%lastIdentOfPath(modelInfo.name)%>::computeNextTimeEvents(double currTime)
7234 {
7235 return SystemDefaultImplementation::computeNextTimeEvents(currTime, getTimeEventData());
7236 }
7237
7238 // Provide number (dimension) of right hand sides (equations and/or residuals) according to the index
7239 int <%lastIdentOfPath(modelInfo.name)%>::getDimRHS() const
7240 {
7241 if(_callType & IContinuous::RANKING)
7242 {
7243 return <%numResidues(allEquations,modelInfo)%>;
7244 }
7245 else
7246 return(SystemDefaultImplementation::getDimRHS());
7247 }
7248
7249 void <%lastIdentOfPath(modelInfo.name)%>::getNominalStates(double* z)
7250 {
7251 <%getNominalStateValues(states, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>
7252 }
7253
7254 // Set variables with given index to the system
7255 void <%lastIdentOfPath(modelInfo.name)%>::setRealStartValue(double& var,double val)
7256 {
7257 SystemDefaultImplementation::setRealStartValue(var, val);
7258 }
7259
7260 void <%lastIdentOfPath(modelInfo.name)%>::setBoolStartValue(bool& var,bool val)
7261 {
7262 SystemDefaultImplementation::setBoolStartValue(var, val);
7263 }
7264
7265 void <%lastIdentOfPath(modelInfo.name)%>::setIntStartValue(int& var,int val)
7266 {
7267 SystemDefaultImplementation::setIntStartValue(var, val);
7268 }
7269
7270 void <%lastIdentOfPath(modelInfo.name)%>::setStringStartValue(string& var,string val)
7271 {
7272 SystemDefaultImplementation::setStringStartValue(var, val);
7273 }
7274
7275 void <%lastIdentOfPath(modelInfo.name)%>::setNumPartitions(int numPartitions)
7276 {
7277 _dimPartitions = numPartitions;
7278 }
7279
7280 int <%lastIdentOfPath(modelInfo.name)%>::getNumPartitions()
7281 {
7282 return _dimPartitions;
7283 }
7284 void <%lastIdentOfPath(modelInfo.name)%>::setPartitionActivation(bool* partitions)
7285 {
7286 _partitionActivation = partitions;
7287 }
7288
7289 void <%lastIdentOfPath(modelInfo.name)%>::getPartitionActivation(bool* partitions)
7290 {
7291 partitions = _partitionActivation;
7292 }
7293
7294 int <%lastIdentOfPath(modelInfo.name)%>::getActivator(int state)
7295 {
7296 return (int)_stateActivator[state];
7297 }
7298 // Provide the right hand side
7299 void <%lastIdentOfPath(modelInfo.name)%>::getRHS(double* f)
7300 {
7301 <%if Flags.isSet(Flags.WRITE_TO_BUFFER) then
7302 <<
7303 if(_callType & IContinuous::RANKING)
7304 {
7305
7306 <%(allEquations |> eqs => (eqs |> eq => writeoutputAlgloopsolvers(eq,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace));separator="\n")%>
7307 double residues [] = {<%(allEquations |> eqn => writeoutput3(eqn, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation));separator=","%>};
7308 for(int i=0;i<<%numResidues(allEquations,modelInfo)%>;i++) *(f+i) = residues[i];
7309 }
7310 else SystemDefaultImplementation::getRHS(f);
7311 >>
7312 else
7313 <<
7314 SystemDefaultImplementation::getRHS(f);
7315 >>%>
7316 }
7317
7318 bool <%lastIdentOfPath(modelInfo.name)%>::isStepEvent()
7319 {
7320 throw ModelicaSimulationError(MODEL_EQ_SYSTEM,"isStepEvent is not yet implemented");
7321 }
7322 void <%lastIdentOfPath(modelInfo.name)%>::setTerminal(bool terminal)
7323 {
7324 _terminal=terminal;
7325 }
7326 bool <%lastIdentOfPath(modelInfo.name)%>::terminal()
7327 {
7328 return _terminal;
7329 }
7330 bool <%lastIdentOfPath(modelInfo.name)%>::isAlgebraic()
7331 {
7332 return false; // Indexreduction is enabled
7333 }
7334 bool <%lastIdentOfPath(modelInfo.name)%>::provideSymbolicJacobian()
7335 {
7336 throw ModelicaSimulationError(MODEL_EQ_SYSTEM,"provideSymbolicJacobian is not yet implemented");
7337 }
7338 void <%lastIdentOfPath(modelInfo.name)%>::handleEvent(const bool* events)
7339 {
7340 <%handleEvent(simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)%>
7341 }
7342 >>
7343 end match
7344 end DefaultImplementationCode;
7345 /*
7346 <%if Flags.isSet(Flags.WRITE_TO_BUFFER) then
7347 <<
7348 if(index == IContinuous::ALL_RESIDUES)
7349 {
7350 <%(allEquations |> eqs => (eqs |> eq => writeoutputAlgloopsolvers(eq,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace));separator="\n")%>
7351 double residues [] = {<%(allEquations |> eqn => writeoutput3(eqn, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation));separator=","%>};
7352 for(int i=0;i<<%numResidues(allEquations)%>;i++) *(f+i) = residues[i];
7353 }
7354 else SystemDefaultImplementation::getRHS(f);
7355 >>
7356 else
7357 <<
7358 SystemDefaultImplementation::getRHS(f);
7359 >>%>
7360 */
7361 49 template getNominalStateValues(list<SimVar> stateVars,SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
7362 ::=
7363 let nominalVars = stateVars |> SIMVAR(index = i) =>
7364 match nominalValue
7365 case SOME(val)
7366 then
7367 let &preExp = buffer "" /*BUFD*/
7368 let &varDecls = buffer "" /*BUFD*/
7369 let value = '<%daeExp(val, contextOther, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>'
7370 <<
7371 <%varDecls%>
7372 <%preExp%>
7373 z[<%i%>] = <%value%>;
7374 >>
7375 else
7376 <<
7377 z[<%i%>] = 1.0;
7378 >>
7379 ;separator="\n"
7380 <<
7381 <%nominalVars%>
7382 >>
7383 end getNominalStateValues;
7384
7385
7386 69 template LinearalgloopDefaultImplementationCode(SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, SimEqSystem eq, Context context, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
7387
7388 ::=
7389 match simCode
7390 case SIMCODE(modelInfo = MODELINFO(__)) then
7391 let modelname = lastIdentOfPath(modelInfo.name)
7392 match eq
7393 case SES_LINEAR(lSystem = ls as LINEARSYSTEM(__)) then
7394 //let size = listLength(ls.vars)//changed by Q.Hua, <%size%> replaced with _dimAEq
7395 let index = ls.index
7396 <<
7397 /// Provide index of equation
7398 int <%modelname%>Algloop<%index%>::getEquationIndex() const
7399 {
7400 return <%index%>;
7401 }
7402
7403 /// Provide number (dimension) of variables according to data type
7404 int <%modelname%>Algloop<%index%>::getDimReal() const
7405 {
7406 return LinearAlgLoopDefaultImplementation::getDimReal();
7407 }
7408
7409 bool <%modelname%>Algloop<%index%>::isConsistent()
7410 {
7411 return _system->isConsistent();
7412 }
7413
7414 /// Provide names of alg loop variables
7415 void <%modelname%>Algloop<%index%>::getNamesReal(const char** names) const
7416 {
7417 for (int i = 0; i < _dimAEq; i++)
7418 names[i] = _vars[i].name;
7419 }
7420
7421 /// Provide nominal values for alg loop variables
7422 void <%modelname%>Algloop<%index%>::getNominalReal(double* nominals) const
7423 {
7424 for (int i = 0; i < _dimAEq; i++)
7425 nominals[i] = _vars[i].nominal;
7426 }
7427
7428 /// Provide min values for alg loop variables
7429 void <%modelname%>Algloop<%index%>::getMinReal(double* mins) const
7430 {
7431 for (int i = 0; i < _dimAEq; i++)
7432 mins[i] = _vars[i].minValue;
7433 }
7434
7435 /// Provide max values for alg loop variables
7436 void <%modelname%>Algloop<%index%>::getMaxReal(double* maxs) const
7437 {
7438 for (int i = 0; i < _dimAEq; i++)
7439 maxs[i] = _vars[i].maxValue;
7440 }
7441
7442 /// Return simulation time
7443 double <%modelname%>Algloop<%index%>::getSimTime() const
7444 {
7445 return _system->_simTime;
7446 }
7447
7448 /// Provide variables with given index to the system
7449 void <%modelname%>Algloop<%index%>::getReal(double* vars) const
7450 {
7451 <%getAlgloopVars(eq, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, context, stateDerVectorName, useFlatArrayNotation)%>
7452 }
7453
7454 /// Set variables with given index to the system
7455 void <%modelname%>Algloop<%index%>::setReal(const double* vars)
7456 {
7457 <%setAlgloopVars(eq,simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, context, stateDerVectorName, useFlatArrayNotation)%>
7458 }
7459 /// Set start values
7460 void <%modelname%>Algloop<%index%>::setRealStartValues()
7461 {
7462 getReal(_x0);
7463 }
7464 void <%modelname%>Algloop<%index%>::getRealStartValues(double* vars) const
7465 {
7466 LinearAlgLoopDefaultImplementation::getRealStartValues(vars);
7467 }
7468 >>
7469 else
7470 CodegenCppCommon.error(sourceInfo(), 'Unsupported equation system type')
7471 end LinearalgloopDefaultImplementationCode;
7472
7473 52 template NonLinearalgloopDefaultImplementationCode(SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, SimEqSystem eq, Context context, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
7474
7475 ::=
7476 match simCode
7477 case SIMCODE(modelInfo = MODELINFO(__)) then
7478 let modelname = lastIdentOfPath(modelInfo.name)
7479 match eq
7480 case SES_NONLINEAR(nlSystem = nls as NONLINEARSYSTEM(__)) then
7481 //let size = listLength(nls.crefs)//changed by Q.Hua, <%size%> replaced with _dimAEq
7482 let index = nls.index
7483 <<
7484 /// Provide index of equation
7485 int <%modelname%>Algloop<%index%>::getEquationIndex() const
7486 {
7487 return <%index%>;
7488 }
7489
7490 /// Provide number (dimension) of variables according to data type
7491 int <%modelname%>Algloop<%index%>::getDimReal() const
7492 {
7493 return NonLinearAlgLoopDefaultImplementation::getDimReal();
7494 }
7495
7496 bool <%modelname%>Algloop<%index%>::isConsistent()
7497 {
7498 return _system->isConsistent();
7499 }
7500
7501 /// Provide names of alg loop variables
7502 void <%modelname%>Algloop<%index%>::getNamesReal(const char** names) const
7503 {
7504 for (int i = 0; i < _dimAEq; i++)
7505 names[i] = _vars[i].name;
7506 }
7507
7508 /// Provide nominal values for alg loop variables
7509 void <%modelname%>Algloop<%index%>::getNominalReal(double* nominals) const
7510 {
7511 for (int i = 0; i < _dimAEq; i++)
7512 nominals[i] = _vars[i].nominal;
7513 }
7514
7515 /// Provide min values for alg loop variables
7516 void <%modelname%>Algloop<%index%>::getMinReal(double* mins) const
7517 {
7518 for (int i = 0; i < _dimAEq; i++)
7519 mins[i] = _vars[i].minValue;
7520 }
7521
7522 /// Provide max values for alg loop variables
7523 void <%modelname%>Algloop<%index%>::getMaxReal(double* maxs) const
7524 {
7525 for (int i = 0; i < _dimAEq; i++)
7526 maxs[i] = _vars[i].maxValue;
7527 }
7528
7529 /// Return simulation time
7530 double <%modelname%>Algloop<%index%>::getSimTime() const
7531 {
7532 return _system->_simTime;
7533 }
7534
7535 /// Provide variables with given index to the system
7536 void <%modelname%>Algloop<%index%>::getReal(double* vars) const
7537 {
7538 <%getAlgloopVars(eq, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, context, stateDerVectorName, useFlatArrayNotation)%>
7539 }
7540
7541 /// Set variables with given index to the system
7542 void <%modelname%>Algloop<%index%>::setReal(const double* vars)
7543 {
7544 <%setAlgloopVars(eq,simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, context, stateDerVectorName, useFlatArrayNotation)%>
7545 }
7546 /// Set start values
7547 void <%modelname%>Algloop<%index%>::setRealStartValues()
7548 {
7549 getReal(_x0);
7550 }
7551 void <%modelname%>Algloop<%index%>::getRealStartValues(double* vars) const
7552 {
7553 NonLinearAlgLoopDefaultImplementation::getRealStartValues(vars);
7554 }
7555 >>
7556 else
7557 CodegenCppCommon.error(sourceInfo(), 'Unsupported equation system type')
7558 end NonLinearalgloopDefaultImplementationCode;
7559
7560 49 template generateMethodDeclarationCode(SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
7561 ::=
7562 match simCode
7563 case SIMCODE(modelInfo = MODELINFO(vars = vars as SIMVARS(__))) then
7564 <<
7565 /// Releases the Modelica System
7566 virtual void destroy();
7567 /// Provide number (dimension) of variables according to the index
7568 // Provide number (dimension) of right hand sides (equations and/or residuals)
7569 virtual int getDimRHS()const;
7570
7571 virtual void setRealStartValue(double& var,double val);
7572 virtual void setBoolStartValue(bool& var,bool val);
7573 virtual void setIntStartValue(int& var,int val);
7574 virtual void setStringStartValue(string& var,string val);
7575
7576 virtual void setNumPartitions(int numPartitions);
7577 virtual int getNumPartitions();
7578 virtual void setPartitionActivation(bool* partitions);
7579 virtual void getPartitionActivation(bool* partitions);
7580 virtual int getActivator(int state);
7581
7582 //Resets all time events
7583
7584 // Provide variables with given index to the system
7585 virtual void getNominalStates(double* z);
7586
7587 // Update transfer behavior of the system of equations according to command given by solver
7588 virtual bool evaluateAll(const UPDATETYPE command = IContinuous::UNDEF_UPDATE);
7589 virtual void evaluateODE(const UPDATETYPE command = IContinuous::UNDEF_UPDATE);
7590 virtual void evaluateZeroFuncs(const UPDATETYPE command = IContinuous::UNDEF_UPDATE);
7591 virtual bool evaluateConditions(const UPDATETYPE command);
7592
7593 // Provide the right hand side (according to the index)
7594 virtual void getRHS(double* f);
7595
7596 //Provide number (dimension) of zero functions
7597 virtual int getDimZeroFunc();
7598 //Provide number (dimension) of zero functions
7599 virtual int getDimClock();
7600 //Provides current values of root/zero functions
7601 virtual void getZeroFunc(double* f);
7602 virtual void setConditions(bool* c);
7603 virtual void getConditions(bool* c);
7604 virtual void getClockConditions(bool* c);
7605
7606 //Called to handle an event
7607 virtual void handleEvent(const bool* events);
7608 //Checks if a discrete variable has changed and triggers an event
7609 virtual bool checkForDiscreteEvents();
7610 virtual bool isStepEvent();
7611 //sets the terminal status
7612 virtual void setTerminal(bool);
7613 //returns the terminal status
7614 virtual bool terminal();
7615
7616
7617
7618 // M is regular
7619 virtual bool isODE();
7620 // M is singular
7621 virtual bool isAlgebraic();
7622
7623 virtual int getDimTimeEvent() const;
7624 virtual std::pair<double,double>* getTimeEventData() const;
7625 virtual double computeNextTimeEvents(double currTime);
7626 //initializes the definition of time event samplers (i.e. starttime and frequency)
7627 virtual void initTimeEventData();
7628
7629 // System is able to provide the Jacobian symbolically
7630 virtual bool provideSymbolicJacobian();
7631
7632 virtual void restoreOldValues();
7633 virtual void restoreNewValues();
7634 virtual bool stepCompleted(double time);
7635 virtual bool stepStarted(double time);
7636
7637 <%if Flags.isSet(Flags.WRITE_TO_BUFFER) then
7638 <<
7639 // Returns labels for a labeled DAE
7640 virtual label_list_type getLabels();
7641 // Sets all algebraic and state varibales for current time
7642 virtual void setVariables(const ublas::vector<double>& variables, const ublas::vector<double>& variables2);
7643 >>
7644 %>
7645
7646 /// Provide boolean variables
7647 virtual void getBoolean(bool* z);
7648 /// Provide integer variables
7649 virtual void getInteger(int* z);
7650 /// Provide real variables
7651 virtual void getReal(double* z);
7652 /// Provide real variables
7653 virtual void getString(std::string* z);
7654 /// Provide boolean variables
7655 virtual void setBoolean(const bool* z);
7656 /// Provide integer variables
7657 virtual void setInteger(const int* z);
7658 /// Provide real variables
7659 virtual void setReal(const double* z);
7660 /// Provide real variables
7661 virtual void setString(const std::string* z);
7662 >>
7663 end generateMethodDeclarationCode;
7664 /*
7665 deactivated: MethodDeclarationCode virtual void saveDiscreteVars();
7666 <%
7667 let discVarCount = intAdd(intAdd(listLength(vars.algVars), listLength(vars.discreteAlgVars)), intAdd( listLength(vars.intAlgVars) , listLength(vars.boolAlgVars )))
7668 let saveDiscreteVarFuncs = (List.partition(List.intRange(stringInt(discVarCount)), 100) |> ls hasindex idx => 'virtual void saveDiscreteVars_<%idx%>(double *discreteVars);';separator="\n")
7669 <<
7670 <%saveDiscreteVarFuncs%>
7671 >>
7672 %>
7673 */
7674
7675 /*! Evaluates only the equations whose indices are passed to it. */
7676 //bool evaluate_selective(const std::vector<int>& indices);
7677
7678 /*! Evaluates only a single equation by index. */
7679 //bool evaluate_single(const int index);
7680 121 template generateAlgloopMethodDeclarationCode(SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
7681
7682 ::=
7683 match simCode
7684 case SIMCODE(modelInfo = MODELINFO(__)) then
7685 <<
7686 /// Provide index of equation
7687 virtual int getEquationIndex() const;
7688 /// Provide number (dimension) of variables according to data type
7689 virtual int getDimReal() const;
7690 /*/// Provide number (dimension) of residuals according to data type
7691 virtual int getDimRHS() const;test*/
7692 /// (Re-) initialize the system of equations
7693 virtual void initialize();
7694
7695 /// Provide names of alg loop variables
7696 virtual void getNamesReal(const char** names) const;
7697 /// Provide nominal values for alg loop variables
7698 virtual void getNominalReal(double* nominals) const;
7699 /// Provide min values for alg loop variables
7700 virtual void getMinReal(double* mins) const;
7701 /// Provide max values for alg loop variables
7702 virtual void getMaxReal(double* maxs) const;
7703
7704 /// Return simulation time
7705 virtual double getSimTime() const;
7706 /// Provide variables with given index to the system
7707 virtual void getReal(double* vars) const;
7708 /// Set variables with given index to the system
7709 virtual void setReal(const double* vars);
7710 virtual void getRealStartValues(double* vars) const;
7711 virtual void setRealStartValues();
7712 /// Evaluate equations for given variables
7713 virtual void evaluate();
7714 virtual bool isLinearTearing();
7715 virtual bool isConsistent();
7716 >>
7717 end generateAlgloopMethodDeclarationCode;
7718 /* after virtual void evaluate();
7719 <%if Flags.isSet(Flags.WRITE_TO_BUFFER) then
7720 <<
7721 /// Provide dimensions of residuals for linear equation systems
7722 virtual int giveDimResiduals(int index);
7723 /// Provide the residuals for linear equation systems
7724 virtual void giveResiduals(double* vars);
7725 >>%>
7726 */
7727 49 template memberVariableDefine(ModelInfo modelInfo, HashTableCrIListArray.HashTable varToArrayIndexMapping, Text indexForUndefinedReferencesReal, Text indexForUndefinedReferencesInt,
7728 Text indexForUndefinedReferencesBool, Text indexForUndefinedReferencesString, Boolean createDebugCode, Boolean useFlatArrayNotation)
7729 /*Define membervariable in simulation file.*/
7730 ::=
7731 match modelInfo
7732 case MODELINFO(vars=SIMVARS(__)) then
7733 <<
7734 /*state vars*/
7735 <%vars.stateVars |> var =>
7736 memberVariableDefine2(var, varToArrayIndexMapping, indexForUndefinedReferencesReal, useFlatArrayNotation, createDebugCode, "Real", true)
7737 ;separator="\n"%>
7738 /*derivative vars*/
7739 <%vars.derivativeVars |> var =>
7740 memberVariableDefine2(var, varToArrayIndexMapping, indexForUndefinedReferencesReal, useFlatArrayNotation, createDebugCode, "Real", true)
7741 ;separator="\n"%>
7742 /*real algvars*/
7743 <%vars.algVars |> var =>
7744 memberVariableDefine2(var, varToArrayIndexMapping, indexForUndefinedReferencesReal, useFlatArrayNotation, createDebugCode, "Real", true)
7745 ;separator="\n"%>
7746 /*discrete algvars*/
7747 <%vars.discreteAlgVars |> var =>
7748 memberVariableDefine2(var, varToArrayIndexMapping, indexForUndefinedReferencesReal, useFlatArrayNotation, createDebugCode, "Real", true)
7749 ;separator="\n"%>
7750 /*int algvars*/
7751 <%vars.intAlgVars |> var =>
7752 memberVariableDefine2(var, varToArrayIndexMapping, indexForUndefinedReferencesInt, useFlatArrayNotation, createDebugCode, "Int", true)
7753 ;separator="\n"%>
7754 /*bool algvars*/
7755 <%vars.boolAlgVars |> var =>
7756 memberVariableDefine2(var, varToArrayIndexMapping, indexForUndefinedReferencesBool, useFlatArrayNotation, createDebugCode, "Bool", true)
7757 ;separator="\n"%>
7758 /*string algvars*/
7759 <%vars.stringAlgVars |> var =>
7760 memberVariableDefine2(var, varToArrayIndexMapping, indexForUndefinedReferencesString, useFlatArrayNotation, createDebugCode, "String", true)
7761 ;separator="\n"%>
7762 /*parameter real vars*/
7763 <%vars.paramVars |> var =>
7764 memberVariableDefine2(var, varToArrayIndexMapping, indexForUndefinedReferencesReal, useFlatArrayNotation, createDebugCode, "Real", true)
7765 ;separator="\n"%>
7766 /*parameter int vars*/
7767 <%vars.intParamVars |> var =>
7768 memberVariableDefine2(var, varToArrayIndexMapping, indexForUndefinedReferencesInt, useFlatArrayNotation, createDebugCode, "Int", true)
7769 ;separator="\n"%>
7770 /*parameter bool vars*/
7771 <%vars.boolParamVars |> var =>
7772 memberVariableDefine2(var, varToArrayIndexMapping, indexForUndefinedReferencesBool, useFlatArrayNotation, createDebugCode, "Bool", true)
7773 ;separator="\n"%>
7774 /*string parameter variables*/
7775 <%vars.stringParamVars |> var =>
7776 memberVariableDefine2(var, varToArrayIndexMapping, indexForUndefinedReferencesString, useFlatArrayNotation, createDebugCode, "String", true)
7777 ;separator="\n"%>
7778 /*alias real vars*/
7779 <%vars.aliasVars |> var =>
7780 memberVariableDefine2(var, varToArrayIndexMapping, indexForUndefinedReferencesReal, useFlatArrayNotation, createDebugCode, "Real", true)
7781 ;separator="\n"%>
7782 /*alias int vars*/
7783 <%vars.intAliasVars |> var =>
7784 memberVariableDefine2(var, varToArrayIndexMapping, indexForUndefinedReferencesInt, useFlatArrayNotation, createDebugCode, "Int", true)
7785 ;separator="\n"%>
7786 /*alias bool vars*/
7787 <%vars.boolAliasVars |> var =>
7788 memberVariableDefine2(var, varToArrayIndexMapping, indexForUndefinedReferencesBool, useFlatArrayNotation, createDebugCode, "Bool", true)
7789 ;separator="\n"%>
7790 /*string alias variables*/
7791 <%vars.stringAliasVars |> var =>
7792 memberVariableDefine2(var, varToArrayIndexMapping, indexForUndefinedReferencesString, useFlatArrayNotation, createDebugCode, "String", true)
7793 ;separator="\n"%>
7794 /*external variables*/
7795 <%vars.extObjVars |> var =>
7796 memberVariableDefine2(var, varToArrayIndexMapping, indexForUndefinedReferencesReal, useFlatArrayNotation, createDebugCode, "Real", false)
7797 ;separator="\n"%>
7798 >>
7799 end memberVariableDefine;
7800
7801 49 template memberVariableInitialize(ModelInfo modelInfo, HashTableCrIListArray.HashTable varToArrayIndexMapping, Text indexForUndefinedReferencesReal, Text indexForUndefinedReferencesInt,
7802 Text indexForUndefinedReferencesBool, Text indexForUndefinedReferencesString, Boolean createDebugCode, Boolean useFlatArrayNotation, Text& additionalConstructorVariables, Text& additionalFunctionDefinitions)
7803 ::=
7804 match modelInfo
7805 case MODELINFO(vars=SIMVARS(__),name=name) then
7806 let classname = lastIdentOfPath(name)
7807 let &additionalStateVarFunctionCalls = buffer ""
7808 let &additionalDerivativeVarFunctionCalls = buffer ""
7809 let &additionalAlgVarFunctionCalls = buffer ""
7810 let &additionalDiscreteAlgVarFunctionCalls = buffer ""
7811 let &additionalIntAlgVarFunctionCalls = buffer ""
7812 let &additionalBoolAlgVarFunctionCalls = buffer ""
7813 let &additionalStringAlgVarFunctionCalls = buffer ""
7814 let &additionalParameterRealVarFunctionCalls = buffer ""
7815 let &additionalParameterIntVarFunctionCalls = buffer ""
7816 let &additionalParameterBoolVarFunctionCalls = buffer ""
7817 let &additionalParameterStringVarFunctionCalls = buffer ""
7818 let &additionalAliasRealVarFunctionCalls = buffer ""
7819 let &additionalAliasIntVarFunctionCalls = buffer ""
7820 let &additionalAliasBoolVarFunctionCalls = buffer ""
7821 let &additionalAliasStringVarFunctionCalls = buffer ""
7822 let &returnValue = buffer ""
7823
7824 <<
7825 //StateVars
7826 <%List.partition(vars.stateVars, 100) |> varPartition hasindex i0 =>
7827 memberVariableInitializeWithSplit(varPartition, i0, "initStateVars", classname, varToArrayIndexMapping, indexForUndefinedReferencesReal, useFlatArrayNotation, createDebugCode, "Real", additionalStateVarFunctionCalls, additionalConstructorVariables, additionalFunctionDefinitions) ;separator="\n"%>
7828
7829 void <%classname%>::initStateVars()
7830 {
7831 <%additionalStateVarFunctionCalls%>
7832 }
7833
7834 //DerivativeVars
7835 <%List.partition(vars.derivativeVars, 100) |> varPartition hasindex i0 =>
7836 memberVariableInitializeWithSplit(varPartition, i0, "initDerivativeVars", classname, varToArrayIndexMapping, indexForUndefinedReferencesReal, useFlatArrayNotation, createDebugCode, "Real", additionalDerivativeVarFunctionCalls, additionalConstructorVariables, additionalFunctionDefinitions) ;separator="\n"%>
7837
7838 void <%classname%>::initDerivativeVars()
7839 {
7840 <%additionalDerivativeVarFunctionCalls%>
7841 }
7842
7843 //AlgVars
7844 <%List.partition(vars.algVars, 100) |> varPartition hasindex i0 =>
7845 memberVariableInitializeWithSplit(varPartition, i0, "initAlgVars", classname, varToArrayIndexMapping, indexForUndefinedReferencesReal, useFlatArrayNotation, createDebugCode, "Real",
7846 additionalAlgVarFunctionCalls,additionalConstructorVariables,additionalFunctionDefinitions) ;separator="\n"%>
7847
7848 void <%classname%>::initAlgVars()
7849 {
7850 <%additionalAlgVarFunctionCalls%>
7851 }
7852
7853 //DiscreteAlgVars
7854 <%List.partition(vars.discreteAlgVars, 100) |> varPartition hasindex i0 =>
7855 memberVariableInitializeWithSplit(varPartition, i0, "initDiscreteAlgVars", classname, varToArrayIndexMapping, indexForUndefinedReferencesReal, useFlatArrayNotation, createDebugCode, "Real",
7856 additionalDiscreteAlgVarFunctionCalls,additionalConstructorVariables,additionalFunctionDefinitions) ;separator="\n"%>
7857
7858 void <%classname%>::initDiscreteAlgVars()
7859 {
7860 <%additionalDiscreteAlgVarFunctionCalls%>
7861 }
7862
7863 //IntAlgVars
7864 <%List.partition(vars.intAlgVars, 100) |> varPartition hasindex i0 =>
7865 memberVariableInitializeWithSplit(varPartition, i0, "initIntAlgVars", classname, varToArrayIndexMapping, indexForUndefinedReferencesInt, useFlatArrayNotation, createDebugCode, "Int",
7866 additionalIntAlgVarFunctionCalls,additionalConstructorVariables,additionalFunctionDefinitions) ;separator="\n"%>
7867 void <%classname%>::initIntAlgVars()
7868 {
7869 <%additionalIntAlgVarFunctionCalls%>
7870 }
7871
7872 //BoolAlgVars
7873 <%List.partition(vars.boolAlgVars, 100) |> varPartition hasindex i0 =>
7874 memberVariableInitializeWithSplit(varPartition, i0, "initBoolAlgVars", classname, varToArrayIndexMapping, indexForUndefinedReferencesBool, useFlatArrayNotation, createDebugCode, "Bool",
7875 additionalBoolAlgVarFunctionCalls,additionalConstructorVariables,additionalFunctionDefinitions) ;separator="\n"%>
7876 void <%classname%>::initBoolAlgVars()
7877 {
7878 <%additionalBoolAlgVarFunctionCalls%>
7879 }
7880
7881 //StringAlgVars
7882 <%List.partition(vars.stringAlgVars, 100) |> varPartition hasindex i0 =>
7883 memberVariableInitializeWithSplit(varPartition, i0, "initStringAlgVars", classname, varToArrayIndexMapping, indexForUndefinedReferencesString, useFlatArrayNotation, createDebugCode, "String",
7884 additionalStringAlgVarFunctionCalls,additionalConstructorVariables,additionalFunctionDefinitions) ;separator="\n"%>
7885 void <%classname%>::initStringAlgVars()
7886 {
7887 <%additionalStringAlgVarFunctionCalls%>
7888 }
7889
7890 //ParameterRealVars
7891 <%List.partition(vars.paramVars, 100) |> varPartition hasindex i0 =>
7892 memberVariableInitializeWithSplit(varPartition, i0, "initParameterRealVars", classname, varToArrayIndexMapping, indexForUndefinedReferencesReal, useFlatArrayNotation, createDebugCode, "Real",
7893 additionalParameterRealVarFunctionCalls,additionalConstructorVariables,additionalFunctionDefinitions) ;separator="\n"%>
7894 void <%classname%>::initParameterRealVars()
7895 {
7896 <%additionalParameterRealVarFunctionCalls%>
7897 }
7898
7899 //ParameterIntVars
7900 <%List.partition(vars.intParamVars, 100) |> varPartition hasindex i0 =>
7901 memberVariableInitializeWithSplit(varPartition, i0, "initParameterIntVars", classname, varToArrayIndexMapping, indexForUndefinedReferencesInt, useFlatArrayNotation, createDebugCode, "Int",
7902 additionalParameterIntVarFunctionCalls,additionalConstructorVariables,additionalFunctionDefinitions) ;separator="\n"%>
7903 void <%classname%>::initParameterIntVars()
7904 {
7905 <%additionalParameterIntVarFunctionCalls%>
7906 }
7907
7908 //ParameterBoolVars
7909 <%List.partition(vars.boolParamVars, 100) |> varPartition hasindex i0 =>
7910 memberVariableInitializeWithSplit(varPartition, i0, "initParameterBoolVars", classname, varToArrayIndexMapping, indexForUndefinedReferencesBool, useFlatArrayNotation, createDebugCode, "Bool",
7911 additionalParameterBoolVarFunctionCalls,additionalConstructorVariables,additionalFunctionDefinitions) ;separator="\n"%>
7912 void <%classname%>::initParameterBoolVars()
7913 {
7914 <%additionalParameterBoolVarFunctionCalls%>
7915 }
7916
7917 //ParameterStringVars
7918 <%List.partition(vars.stringParamVars, 100) |> varPartition hasindex i0 =>
7919 memberVariableInitializeWithSplit(varPartition, i0, "initParameterStringVars", classname, varToArrayIndexMapping, indexForUndefinedReferencesString, useFlatArrayNotation, createDebugCode, "String",
7920 additionalParameterStringVarFunctionCalls,additionalConstructorVariables,additionalFunctionDefinitions) ;separator="\n"%>
7921 void <%classname%>::initParameterStringVars()
7922 {
7923 <%additionalParameterStringVarFunctionCalls%>
7924 }
7925
7926 //AliasRealVars
7927 <%List.partition(vars.aliasVars, 100) |> varPartition hasindex i0 =>
7928 memberVariableInitializeWithSplit(varPartition, i0, "initAliasRealVars", classname, varToArrayIndexMapping, indexForUndefinedReferencesReal, useFlatArrayNotation, createDebugCode, "Real",
7929 additionalAliasRealVarFunctionCalls,additionalConstructorVariables,additionalFunctionDefinitions) ;separator="\n"%>
7930 void <%classname%>::initAliasRealVars()
7931 {
7932 <%additionalAliasRealVarFunctionCalls%>
7933 }
7934
7935 //AliasIntVars
7936 <%List.partition(vars.intAliasVars, 100) |> varPartition hasindex i0 =>
7937 memberVariableInitializeWithSplit(varPartition, i0, "initAliasIntVars", classname, varToArrayIndexMapping, indexForUndefinedReferencesInt, useFlatArrayNotation, createDebugCode, "Int",
7938 additionalAliasIntVarFunctionCalls,additionalConstructorVariables,additionalFunctionDefinitions) ;separator="\n"%>
7939 void <%classname%>::initAliasIntVars()
7940 {
7941 <%additionalAliasIntVarFunctionCalls%>
7942 }
7943
7944 //AliasBoolVars
7945 <%List.partition(vars.boolAliasVars, 100) |> varPartition hasindex i0 =>
7946 memberVariableInitializeWithSplit(varPartition, i0, "initAliasBoolVars", classname, varToArrayIndexMapping, indexForUndefinedReferencesBool, useFlatArrayNotation, createDebugCode, "Bool",
7947 additionalAliasBoolVarFunctionCalls,additionalConstructorVariables,additionalFunctionDefinitions) ;separator="\n"%>
7948 void <%classname%>::initAliasBoolVars()
7949 {
7950 <%additionalAliasBoolVarFunctionCalls%>
7951 }
7952
7953 //AliasStringVars
7954 <%List.partition(vars.stringAliasVars, 100) |> varPartition hasindex i0 =>
7955 memberVariableInitializeWithSplit(varPartition, i0, "initAliasStringVars", classname, varToArrayIndexMapping, indexForUndefinedReferencesString, useFlatArrayNotation, createDebugCode, "String",
7956 additionalAliasStringVarFunctionCalls,additionalConstructorVariables,additionalFunctionDefinitions) ;separator="\n"%>
7957 void <%classname%>::initAliasStringVars()
7958 {
7959 <%additionalAliasStringVarFunctionCalls%>
7960 }
7961 >>
7962 end memberVariableInitialize;
7963
7964 324 template memberVariableInitializeWithSplit(list<SimVar> simVars, Text idx, Text functionPrefix, Text className, HashTableCrIListArray.HashTable varToArrayIndexMapping, Text indexForUndefinedReferences, Boolean useFlatArrayNotation,
7965 Boolean createDebugCode, String type, Text& additionalFunctionCalls, Text& additionalConstructorVariables, Text& additionalFunctionDefinitions)
7966 ::=
7967 let &additionalFunctionCalls += ' <%functionPrefix%>_<%idx%>();<%\n%>'
7968 let &additionalFunctionDefinitions += 'void <%functionPrefix%>_<%idx%>();<%\n%>'
7969 <<
7970 void <%className%>::<%functionPrefix%>_<%idx%>()
7971 {
7972 <%simVars |> var =>
7973 memberVariableInitialize2(var, varToArrayIndexMapping, indexForUndefinedReferences, useFlatArrayNotation, createDebugCode, type, additionalConstructorVariables)
7974 ;separator="\n"%>
7975 }
7976 >>
7977 end memberVariableInitializeWithSplit;
7978
7979 11720 template memberVariableInitialize2(SimVar simVar, HashTableCrIListArray.HashTable varToArrayIndexMapping, Text indexForUndefinedReferences, Boolean useFlatArrayNotation,
7980 Boolean createDebugCode, String type, Text& additionalConstructorVariables)
7981 ::=
7982 match simVar
7983 case SIMVAR(numArrayElement={},arrayCref=NONE(),name=CREF_IDENT(subscriptLst=_::_)) then ''
7984
7985 case SIMVAR(numArrayElement={},arrayCref=NONE(),name=name) then
7986 match(createDebugCode)
7987 case true then
7988 let index = SimCodeCodegenUtil.getVarIndexHeadByMapping(varToArrayIndexMapping,name,true,indexForUndefinedReferences)
7989 let &additionalConstructorVariables += ',<%cref(name,useFlatArrayNotation)%>(getSimVars()->init<%type%>Var(<%index%>))<%\n%>'
7990 ""
7991 else ""
7992 /* newInst with arrays: a non-scalarized whole-array var (T_ARRAY) has no
7993 subscripts on its cref, so the arrayCref=SOME path below would see dims="0"
7994 and skip the init. Handle it here first (mirrors memberVariableDefine2). */
7995 case v as SIMVAR(type_ = T_ARRAY()) then
7996 let& dims = buffer "" /*BUFD*/
7997 let varName = arraycref2(name, dims)
7998 let arrayHeadIdx = SimCodeCodegenUtil.getVarIndexHeadByMapping(varToArrayIndexMapping,name,true,indexForUndefinedReferences)
7999 <<
8000 <%varName%>.init(&_pointerTo<%type%>Vars[<%arrayHeadIdx%>]);
8001 >>
8002 case v as SIMVAR(name=CREF_IDENT(__),arrayCref=SOME(_),numArrayElement=num)
8003 case v as SIMVAR(name=CREF_QUAL(__),arrayCref=SOME(_),numArrayElement=num) then
8004 let &dims = buffer "" /*BUFD*/
8005 let arrayName = arraycref2(name,dims)
8006 let typeString = variableType(type_)
8007 let array_num_elem = arrayNumElements(name, v.numArrayElement)
8008 if(useFlatArrayNotation) then
8009 let &additionalConstructorVariables += '"not implemented"<%\n%>'
8010 ""
8011 else
8012 match dims
8013 case "0" then
8014 match(createDebugCode)
8015 case true then
8016 let index = SimCodeCodegenUtil.getVarIndexHeadByMapping(varToArrayIndexMapping,name,true,indexForUndefinedReferences)
8017 let& additionalConstructorVariables += ',<%arrayName%>(getSimVars()->init<%type%>Var(<%index%>))'
8018 ""
8019 else ""
8020 else
8021 let size = Util.mulStringDelimit2Int(array_num_elem,",")
8022 if SimCodeCodegenUtil.isVarIndexListConsecutive(varToArrayIndexMapping,name) then
8023 let arrayHeadIdx = SimCodeCodegenUtil.getVarIndexHeadByMapping(varToArrayIndexMapping,name,true,indexForUndefinedReferences)
8024 <<
8025 <%arrayName%>.init(&_pointerTo<%type%>Vars[<%arrayHeadIdx%>]);
8026 >>
8027 else
8028 let arrayIndices = SimCodeCodegenUtil.getVarIndexListByMapping(varToArrayIndexMapping,name,true,indexForUndefinedReferences) |> idx => '<%idx%>'; separator=" LIST_SEP "
8029 <<
8030 <%typeString%>* <%arrayName%>_ref_data[<%size%>];
8031 getSimVars()->init<%type%>AliasArray(LIST_OF <%arrayIndices%> LIST_END, <%arrayName%>_ref_data);
8032 <%arrayName%> = RefArrayDim<%dims%><<%typeString%>, <%arrayextentDims(name, v.numArrayElement)%>>(<%arrayName%>_ref_data);
8033 >>
8034 /*special case for variables that marked as array but are not arrays */
8035 case SIMVAR(numArrayElement=_::_) then
8036
8037 let& dims = buffer "" /*BUFD*/
8038 let varName = arraycref2(name,dims)
8039 let varType = variableType(type_)
8040 match dims
8041 case "0" then
8042 match createDebugCode
8043 case true then
8044 let index = SimCodeCodegenUtil.getVarIndexHeadByMapping(varToArrayIndexMapping,name,true,indexForUndefinedReferences)
8045 let& additionalConstructorVariables += ',<%varName%>(getSimVars()->init<%type%>Var(<%index%>))'
8046 ""
8047 else ""
8048 else ''
8049 end match
8050 end memberVariableInitialize2;
8051
8052
8053 121 template memberVariableAlgloop(ModelInfo modelInfo, Boolean useFlatArrayNotation)
8054 "Define membervariable in simulation file."
8055 ::=
8056 match modelInfo
8057 case MODELINFO(vars=SIMVARS(__)) then
8058 << <%vars.algVars |> var =>
8059 memberVariableDefineReference2(var, "algebraics","",useFlatArrayNotation)
8060 ;separator=";\n"%><%if vars.algVars then ";" else ""%>
8061 <%vars.discreteAlgVars |> var =>
8062 memberVariableDefineReference2(var, "algebraics","",useFlatArrayNotation)
8063 ;separator=";\n"%><%if vars.discreteAlgVars then ";" else ""%>
8064 <%vars.paramVars |> var =>
8065 memberVariableDefineReference2(var, "parameters","",useFlatArrayNotation)
8066 ;separator=";\n"%> <%if vars.paramVars then ";" else ""%>
8067 <%vars.aliasVars |> var =>
8068 memberVariableDefineReference2(var, "aliasVars","",useFlatArrayNotation)
8069 ;separator=";\n"%><%if vars.aliasVars then ";" else ""%>
8070 <%vars.intAlgVars |> var =>
8071 memberVariableDefineReference("int", var, "intVariables.algebraics","",useFlatArrayNotation)
8072 ;separator=";\n"%><%if vars.intAlgVars then ";" else ""%>
8073 <%vars.intParamVars |> var =>
8074 memberVariableDefineReference("int", var, "intVariables.parameters","",useFlatArrayNotation)
8075 ;separator=";\n"%><%if vars.intParamVars then ";" else " "%>
8076 <%vars.intAliasVars |> var =>
8077 memberVariableDefineReference("int", var, "intVariables.AliasVars","",useFlatArrayNotation)
8078 ;separator=";\n"%><%if vars.intAliasVars then ";" else " "%>
8079 <%vars.boolAlgVars |> var =>
8080 memberVariableDefineReference("bool",var, "boolVariables.algebraics","",useFlatArrayNotation)
8081 ;separator=";\n"%><%if vars.boolAlgVars then ";" else ""%>
8082 <%vars.boolParamVars |> var =>
8083 memberVariableDefineReference("bool",var, "boolVariables.parameters","",useFlatArrayNotation)
8084 ;separator=";\n"%><%if vars.boolParamVars then ";" else " "%>
8085 <%vars.boolAliasVars |> var =>
8086 memberVariableDefineReference("bool ",var, "boolVariables.AliasVars","",useFlatArrayNotation)
8087 ;separator=";\n"%><%if vars.boolAliasVars then ";" else ""%>
8088 <%vars.stringAlgVars |> var =>
8089 memberVariableDefineReference("string",var, "stringVariables.algebraics","",useFlatArrayNotation)
8090 ;separator=";\n"%><%if vars.stringAlgVars then ";" else ""%>
8091 <%vars.stringParamVars |> var =>
8092 memberVariableDefineReference("string",var, "stringVariables.parameters","",useFlatArrayNotation)
8093 ;separator=";\n"%><%if vars.stringParamVars then ";" else " "%>
8094 <%vars.stringAliasVars |> var =>
8095 memberVariableDefineReference("string",var, "stringVariables.AliasVars","",useFlatArrayNotation)
8096 ;separator=";\n"%><%if vars.stringAliasVars then ";" else ""%>
8097 >>
8098 end memberVariableAlgloop;
8099
8100
8101 242 template constructorParamAlgloop(ModelInfo modelInfo, Boolean useFlatArrayNotation)
8102 "Define membervariable in simulation file."
8103 ::=
8104 match modelInfo
8105 case MODELINFO(vars=SIMVARS(__)) then
8106 <<
8107 <%vars.algVars |> var =>
8108 memberVariableDefineReference2(var, "algebraics","_",useFlatArrayNotation)
8109 ;separator=","%><%if vars.algVars then "," else ""%>
8110 <%vars.discreteAlgVars |> var =>
8111 memberVariableDefineReference2(var, "algebraics","_",useFlatArrayNotation)
8112 ;separator=","%><%if vars.discreteAlgVars then "," else ""%>
8113 <%vars.paramVars |> var =>
8114 memberVariableDefineReference2(var, "parameters","_",useFlatArrayNotation)
8115 ;separator=","%><%if vars.paramVars then "," else ""%>
8116 <%vars.aliasVars |> var =>
8117 memberVariableDefineReference2(var, "aliasVars","_",useFlatArrayNotation)
8118 ;separator=","%><%if vars.aliasVars then "," else ""%>
8119 <%vars.intAlgVars |> var =>
8120 memberVariableDefineReference("int", var, "intVariables.algebraics","_",useFlatArrayNotation)
8121 ;separator=","%> <%if vars.intAlgVars then "," else ""%>
8122 <%vars.intParamVars |> var =>
8123 memberVariableDefineReference("int", var, "intVariables.parameters","_",useFlatArrayNotation)
8124 ;separator=","%> <%if vars.intParamVars then "," else ""%>
8125 <%vars.intAliasVars |> var =>
8126 memberVariableDefineReference("int", var, "intVariables.AliasVars","_",useFlatArrayNotation)
8127 ;separator=","%><%if vars.intAliasVars then "," else ""%>
8128 <%vars.boolAlgVars |> var =>
8129 memberVariableDefineReference("bool",var, "boolVariables.algebraics","_",useFlatArrayNotation)
8130 ;separator=","%><%if vars.boolAlgVars then "," else ""%>
8131 <%vars.boolParamVars |> var =>
8132 memberVariableDefineReference("bool",var, "boolVariables.parameters","_",useFlatArrayNotation)
8133 ;separator=","%><%if vars.boolParamVars then "," else ""%>
8134 <%vars.boolAliasVars |> var =>
8135 memberVariableDefineReference("bool ",var, "boolVariables.AliasVars","_",useFlatArrayNotation)
8136 ;separator=","%><%if vars.boolAliasVars then "," else ""%>
8137 <%vars.stringAlgVars |> var =>
8138 memberVariableDefineReference("string",var, "stringVariables.algebraics","_",useFlatArrayNotation)
8139 ;separator=","%><%if vars.stringAlgVars then "," else "" %>
8140 <%vars.stringParamVars |> var =>
8141 memberVariableDefineReference("string",var, "stringVariables.parameters","_",useFlatArrayNotation)
8142 ;separator=","%><%if vars.stringParamVars then "," else ""%>
8143 <%vars.stringAliasVars |> var =>
8144 memberVariableDefineReference("string",var, "stringVariables.AliasVars","_",useFlatArrayNotation)
8145 ;separator=","%><%if vars.stringAliasVars then "," else ""%>
8146
8147 >>
8148 end constructorParamAlgloop;
8149
8150
8151 121 template initAlgloopParams(ModelInfo modelInfo,Text& arrayInit, Boolean useFlatArrayNotation)
8152 "Define membervariable in simulation file."
8153 ::=
8154 match modelInfo
8155 case MODELINFO(vars=SIMVARS(__)) then
8156
8157 <<
8158 /* vars.algVars */
8159 <%vars.algVars |> var =>
8160 initAlgloopParam(var, "algebraics",arrayInit, useFlatArrayNotation)
8161 ;separator=","%> <%if vars.algVars then "," else ""%>
8162 /* vars.discreteAlgVars */
8163 <%vars.discreteAlgVars |> var =>
8164 initAlgloopParam( var, "algebraics",arrayInit, useFlatArrayNotation)
8165 ;separator=","%> <%if vars.discreteAlgVars then "," else ""%>
8166 /* vars.paramVars */
8167 <%vars.paramVars |> var =>
8168 initAlgloopParam(var, "parameters",arrayInit, useFlatArrayNotation)
8169 ;separator=","%><%if vars.paramVars then "," else ""%>
8170 /* vars.aliasVars */
8171 <%vars.aliasVars |> var =>
8172 initAlgloopParam(var, "aliasVars",arrayInit, useFlatArrayNotation)
8173 ;separator=","%><%if vars.aliasVars then "," else ""%>
8174 /* vars.intAlgVars */
8175 <%vars.intAlgVars |> var =>
8176 initAlgloopParam( var, "intVariables.algebraics",arrayInit, useFlatArrayNotation)
8177 ;separator=","%> <%if vars.intAlgVars then "," else ""%>
8178 /* vars.intParamVars */
8179 <%vars.intParamVars |> var =>
8180 initAlgloopParam( var, "intVariables.parameters",arrayInit, useFlatArrayNotation)
8181 ;separator=","%><%if vars.intParamVars then "," else ""%>
8182 /* vars.intAliasVars */
8183 <%vars.intAliasVars |> var =>
8184 initAlgloopParam( var, "intVariables.AliasVars",arrayInit, useFlatArrayNotation)
8185 ;separator=","%><%if vars.intAliasVars then "," else ""%>
8186 /* vars.boolAlgVars */
8187 <%vars.boolAlgVars |> var =>
8188 initAlgloopParam(var, "boolVariables.algebraics",arrayInit, useFlatArrayNotation)
8189 ;separator=","%><%if vars.boolAlgVars then "," else ""%>
8190 /* vars.boolParamVars */
8191 <%vars.boolParamVars |> var =>
8192 initAlgloopParam(var, "boolVariables.parameters",arrayInit, useFlatArrayNotation)
8193 ;separator=","%> <%if vars.boolParamVars then "," else ""%>
8194 /* vars.boolAliasVars */
8195 <%vars.boolAliasVars |> var =>
8196 initAlgloopParam(var, "boolVariables.AliasVars",arrayInit, useFlatArrayNotation)
8197 ;separator=","%><%if vars.boolAliasVars then "," else ""%>
8198 /* vars.stringAlgVars */
8199 <%if vars.stringAlgVars then "," else ""%>
8200 <%vars.stringAlgVars |> var =>
8201 initAlgloopParam(var, "stringVariables.algebraics",arrayInit, useFlatArrayNotation)
8202 ;separator=","%><%if vars.stringAlgVars then "," else "" %>
8203 /* vars.stringParamVars */
8204 <%vars.stringParamVars |> var =>
8205 initAlgloopParam(var, "stringVariables.parameters",arrayInit, useFlatArrayNotation)
8206 ;separator=","%><%if vars.stringParamVars then "," else "" %>
8207 /* vars.stringAliasVars */
8208 <%vars.stringAliasVars |> var =>
8209 initAlgloopParam(var, "stringVariables.AliasVars",arrayInit, useFlatArrayNotation)
8210 ;separator=","%><%if vars.stringAliasVars then "," else "" %>
8211 >>
8212 end initAlgloopParams;
8213
8214
8215 56361 template memberVariableDefineReference(String type,SimVar simVar, String arrayName,String pre, Boolean useFlatArrayNotation)
8216 ::=
8217 match simVar
8218
8219 case SIMVAR(numArrayElement={},arrayCref=NONE(),name=CREF_IDENT(subscriptLst=_::_)) then ''
8220
8221 case SIMVAR(numArrayElement={}) then
8222 <<
8223 <%type%>& <%pre%><%cref(name,useFlatArrayNotation)%>
8224 >>
8225 case v as SIMVAR(name=CREF_IDENT(__),arrayCref=SOME(_),numArrayElement=num) then
8226 <<
8227 multi_array<<%variableType(type_)%>,<%listLength(num)%>>& <%pre%><%arraycref(name, useFlatArrayNotation)%>
8228 >>
8229 case v as SIMVAR(name=CREF_QUAL(__),arrayCref=SOME(_),numArrayElement=num) then
8230 <<
8231 multi_array<<%variableType(type_)%>,<%listLength(num)%>>& <%pre%><%arraycref(name, useFlatArrayNotation)%>
8232 >>
8233 case SIMVAR(numArrayElement=_::_) then
8234 let& dims = buffer "" /*BUFD*/
8235 let varName = arraycref2(name,dims)
8236 let varType = variableType(type_)
8237 match dims case "0" then ''
8238 end memberVariableDefineReference;
8239
8240
8241 11723 template memberVariableDefine2(SimVar simVar, HashTableCrIListArray.HashTable varToArrayIndexMapping, Text indexForUndefinedReferences,
8242 Boolean useFlatArrayNotation, Boolean createDebugCode, String type, Boolean createRefVar)
8243 ::=
8244 match simVar
8245 case SIMVAR(numArrayElement={},arrayCref=NONE(),name=CREF_IDENT(subscriptLst=_::_)) then ''
8246
8247 case SIMVAR(numArrayElement={},arrayCref=NONE(),name=name,type_=type_) then
8248 match createDebugCode
8249 case true then
8250 <<
8251 <%variableType(type_)%><%if createRefVar then '&' else ''%> <%cref(name,useFlatArrayNotation)%>;
8252 >>
8253 else
8254 if createRefVar then
8255 let index = SimCodeCodegenUtil.getVarIndexHeadByMapping(varToArrayIndexMapping,name,true,indexForUndefinedReferences)
8256 <<
8257 #define <%cref(name,useFlatArrayNotation)%> _pointerTo<%type%>Vars[<%index%>]
8258 >>
8259 else
8260 '<%variableType(type_)%> <%cref(name,useFlatArrayNotation)%>;'
8261
8262 /* newInst with arrays */
8263 case v as SIMVAR(type_ = T_ARRAY()) then
8264 let& dims = buffer "" /*BUFD*/
8265 let varName = arraycref2(name, dims)
8266 let typeString = expTypeShort(type_)
8267 <<
8268 StatArrayDim<%listLength(v.numArrayElement)%><<%typeString%>, <%v.numArrayElement;separator=","%>, <%createRefVar%>> <%varName%>;
8269 >>
8270 case v as SIMVAR(name=CREF_IDENT(__),arrayCref=SOME(_))
8271 case v as SIMVAR(name=CREF_QUAL(__),arrayCref=SOME(_)) then
8272 let &dims = buffer "" /*BUFD*/
8273 let arrayName = arraycref2(name,dims)
8274 let typeString = variableType(type_)
8275 let array_dimensions = arrayextentDims(name, v.numArrayElement)
8276 match dims
8277 case "0" then
8278 match createDebugCode
8279 case true then
8280 <<
8281 <%typeString%><%if createRefVar then '&' else ''%> <%arrayName%>;
8282 >>
8283 else
8284 if createRefVar then
8285 let index = SimCodeCodegenUtil.getVarIndexHeadByMapping(varToArrayIndexMapping,name,true,indexForUndefinedReferences)
8286 <<
8287 #define <%arrayName%> _pointerTo<%type%>Vars[<%index%>]
8288 >>
8289 else
8290 '<%typeString%> <%arrayName%>;'
8291 else
8292 if SimCodeCodegenUtil.isVarIndexListConsecutive(varToArrayIndexMapping,name) then
8293 <<
8294 StatArrayDim<%dims%><<%typeString%>, <%array_dimensions%>, <%createRefVar%>> <%arrayName%>;
8295 >>
8296 else
8297 <<
8298 RefArrayDim<%dims%><<%typeString%>, <%array_dimensions%>> <%arrayName%>;
8299 >>
8300 /*special case for variables that marked as array but are not arrays */
8301 case SIMVAR(numArrayElement=_::_) then
8302 let& dims = buffer "" /*BUFD*/
8303 let varName = arraycref2(name,dims)
8304 let varType = variableType(type_)
8305 match dims
8306 case "0" then
8307 match createDebugCode
8308 case true then
8309 '<%varType%><%if createRefVar then '&' else ''%> <%varName%>;'
8310 else
8311 if createRefVar then
8312 let index = SimCodeCodegenUtil.getVarIndexHeadByMapping(varToArrayIndexMapping,name,true,indexForUndefinedReferences)
8313 '#define <%varName%> _pointerTo<%type%>Vars[<%index%>]'
8314 else
8315 '<%varType%> <%varName%>;'
8316 else ''
8317 end match
8318 end memberVariableDefine2;
8319
8320
8321 196156 template initAlgloopParam(SimVar simVar, String arrayName,Text& arrayInit, Boolean useFlatArrayNotation)
8322 ::=
8323 match simVar
8324 case SIMVAR(numArrayElement={}) then
8325 <<
8326 <%cref(name,useFlatArrayNotation)%>(_<%cref(name,useFlatArrayNotation)%>)
8327 >>
8328 case v as SIMVAR(name=CREF_IDENT(__),arrayCref=SOME(_),numArrayElement=num) then
8329 //let &arrayInit+= ',<%arraycref(name, useFlatArrayNotation)%>=_<%arraycref(name, useFlatArrayNotation)%>'
8330 '<%arraycref(name, useFlatArrayNotation)%>(_<%arraycref(name, useFlatArrayNotation)%>)'
8331 case v as SIMVAR(name=CREF_QUAL(__),arrayCref=SOME(_),numArrayElement=num) then
8332 //let &arrayInit+= ' ,<%arraycref(name, useFlatArrayNotation)%>= _<%arraycref(name, useFlatArrayNotation)%>'
8333 '<%arraycref(name, useFlatArrayNotation)%>( _<%arraycref(name, useFlatArrayNotation)%>)'
8334 /*special case for varibales that marked as array but are not arrays */
8335 case SIMVAR(numArrayElement=_::_) then
8336 let& dims = buffer "" /*BUFD*/
8337 let varName = arraycref2(name,dims)
8338 match dims case "0" then '<%varName%>(_<%varName%>)'
8339 end initAlgloopParam;
8340
8341
8342 532107 template memberVariableDefineReference2(SimVar simVar, String arrayName,String pre, Boolean useFlatArrayNotation)
8343 ::=
8344 match simVar
8345 case SIMVAR(numArrayElement={}) then
8346 <<
8347 <%variableType(type_)%>& <%pre%><%cref(name, useFlatArrayNotation)%>
8348 >>
8349 case v as SIMVAR(name=CREF_IDENT(__),arrayCref=SOME(_),numArrayElement=num) then
8350 <<
8351 multi_array<<%variableType(type_)%>,<%listLength(num)%>>& <%pre%><%arraycref(name, useFlatArrayNotation)%>
8352 >>
8353 case v as SIMVAR(name=CREF_QUAL(__),arrayCref=SOME(_),numArrayElement=num) then
8354 <<
8355 multi_array<<%variableType(type_)%>,<%listLength(num)%>>& <%pre%><%arraycref(name, useFlatArrayNotation)%>
8356 >>
8357 /*special case for varibales that marked as array but are not arrays */
8358 case SIMVAR(numArrayElement=_::_) then
8359 let& dims = buffer "" /*BUFD*/
8360 let varName = arraycref2(name,dims)
8361 let varType = variableType(type_)
8362 match dims case "0" then ''
8363 end memberVariableDefineReference2;
8364
8365
8366 ✗ template arrayConstruct(ModelInfo modelInfo, Boolean useFlatArrayNotation)
8367 ::=
8368 match modelInfo
8369 case MODELINFO(vars = vars as SIMVARS(__))
8370 then
8371 <<
8372 <%arrayConstruct1(vars.algVars, useFlatArrayNotation)%>
8373 <%arrayConstruct1(vars.discreteAlgVars, useFlatArrayNotation)%>
8374 <%arrayConstruct1(vars.intAlgVars, useFlatArrayNotation)%>
8375 <%arrayConstruct1(vars.boolAlgVars, useFlatArrayNotation)%>
8376 <%arrayConstruct1(vars.stringAlgVars, useFlatArrayNotation)%>
8377 <%arrayConstruct1(vars.paramVars, useFlatArrayNotation)%>
8378 <%arrayConstruct1(vars.intParamVars, useFlatArrayNotation)%>
8379 <%arrayConstruct1(vars.boolParamVars, useFlatArrayNotation)%>
8380 <%arrayConstruct1(vars.stringParamVars, useFlatArrayNotation)%>
8381 <%arrayConstruct1(vars.aliasVars, useFlatArrayNotation)%>
8382 <%arrayConstruct1(vars.intAliasVars, useFlatArrayNotation)%>
8383 <%arrayConstruct1(vars.boolAliasVars, useFlatArrayNotation)%>
8384 <%arrayConstruct1(vars.stringAliasVars, useFlatArrayNotation)%>
8385 >>
8386 end arrayConstruct;
8387
8388 ✗ template arrayConstruct1(list<SimVar> varsLst, Boolean useFlatArrayNotation) ::=
8389 varsLst |> v as SIMVAR(arrayCref=SOME(_),numArrayElement=_::_) =>
8390 <<>>
8391 //,<%arraycref(name, useFlatArrayNotation)%>(boost::extents<%boostextentDims(name,v.numArrayElement)%>)
8392 ;separator="\n"
8393 end arrayConstruct1;
8394 //,<%arraycref(name)%>(boost::extents[<%v.numArrayElement;separator="]["%>])
8395 544805 template variableType(DAE.Type type)
8396 "Generates integer for use in arrays in global data section."
8397 ::=
8398 match type
8399 case T_REAL(__) then "double"
8400 case T_STRING(__) then "string"
8401 case T_INTEGER(__) then "int"
8402 case T_BOOL(__) then "bool"
8403 case T_ENUMERATION(__) then "int"
8404 case T_COMPLEX(complexClassType=EXTERNAL_OBJ(__)) then "void*"
8405 end variableType;
8406
8407 60304 template lastIdentOfPath(Absyn.Path modelName) ::=
8408 match modelName
8409 case QUALIFIED(__) then lastIdentOfPath(path)
8410 case IDENT(__) then name
8411 case FULLYQUALIFIED(__) then lastIdentOfPath(path)
8412 end lastIdentOfPath;
8413
8414 ✗ template identOfPath(Absyn.Path modelName) ::=
8415 match modelName
8416 case QUALIFIED(__) then '<%name%>_<%lastIdentOfPath(path)%>'
8417 case IDENT(__) then name
8418 case FULLYQUALIFIED(__) then lastIdentOfPath(path)
8419 end identOfPath;
8420
8421 26 template identOfPathDot(Absyn.Path modelName) ::=
8422 match modelName
8423 case QUALIFIED(__) then '<%name%>.<%lastIdentOfPath(path)%>'
8424 case IDENT(__) then name
8425 case FULLYQUALIFIED(__) then lastIdentOfPath(path)
8426 end identOfPathDot;
8427
8428 11050 template lastIdentOfPathFromSimCode(SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace) ::=
8429 match simCode
8430 case SIMCODE(modelInfo = MODELINFO(__)) then
8431 lastIdentOfPath(modelInfo.name)
8432 end lastIdentOfPathFromSimCode;
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444 /*
8445 template boostextentDims(ComponentRef cr, list<String> StatArrayDims)
8446 ::=
8447 match cr
8448
8449 case CREF_IDENT(subscriptLst={}) then
8450 '<%ident%>_NO_SUBS'
8451 case CREF_IDENT(__) then
8452 '[<%StatArrayDims;separator="]["%>]'
8453 //subscriptsToCStr(subscriptLst)
8454 case CREF_QUAL(componentRef=c) then
8455 match StatArrayDims
8456 case val::dims
8457 then boostextentDims(c,dims)
8458 end match
8459 else "CREF_NOT_IDENT_OR_QUAL"
8460 end boostextentDims;
8461 */
8462
8463 ✗ template boostextentDims(ComponentRef cr, list<String> StatArrayDims)
8464 ::=
8465 match cr
8466 case CREF_IDENT(subscriptLst={}) then
8467 '<%ident%>_NO_SUBS'
8468 //subscriptsToCStr(subscriptLst)
8469 case CREF_IDENT(subscriptLst=dims) then
8470 // '_<%ident%>_INVALID_<%listLength(dims)%>_<%listLength(StatArrayDims)%>'
8471 '[<%List.lastN(StatArrayDims,listLength(dims));separator="]["%>]'
8472 //subscriptsToCStr(subscriptLst)
8473 case CREF_QUAL(componentRef=c) then
8474 boostextentDims(c,StatArrayDims)
8475 else "CREF_NOT_IDENT_OR_QUAL"
8476 end boostextentDims;
8477
8478
8479 3656 template arrayextentDims(ComponentRef cr, list<String> array)
8480 ::=
8481 match cr
8482 case CREF_IDENT(subscriptLst={}) then
8483 '<%ident%>_NO_SUBS'+ "/*hier1*/"
8484 //subscriptsToCStr(subscriptLst)
8485 case CREF_IDENT(subscriptLst=dims) then
8486 // '_<%ident%>_INVALID_<%listLength(dims)%>_<%listLength(array)%>'
8487 '<%List.lastN(array,listLength(dims));separator=","%>'
8488 //subscriptsToCStr(subscriptLst)
8489 case CREF_QUAL(componentRef=c) then
8490 arrayextentDims(c,array)
8491 else "CREF_NOT_IDENT_OR_QUAL"
8492 end arrayextentDims;
8493
8494
8495 2945 template arrayNumElements(ComponentRef cr, list<String> array)
8496 ::=
8497 match cr
8498 case CREF_IDENT(subscriptLst={}) then
8499 '<%ident%>_NO_SUBS'+ "/*hier1*/"
8500 //subscriptsToCStr(subscriptLst)
8501 case CREF_IDENT(subscriptLst=dims) then
8502 // '_<%ident%>_INVALID_<%listLength(dims)%>_<%listLength(array)%>'
8503 '<%List.lastN(array,listLength(dims));separator=","%>'
8504 //subscriptsToCStr(subscriptLst)
8505 case CREF_QUAL(componentRef=c) then
8506 arrayNumElements(c,array)
8507 else "CREF_NOT_IDENT_OR_QUAL"
8508 end arrayNumElements;
8509
8510
8511
8512 /* record CREF_IDENT
8513 Ident ident;
8514 Type identType "type of the identifier, without considering the subscripts";
8515 list<Subscript> subscriptLst;
8516 end CREF_IDENT;
8517
8518 record CREF_ITER "An iterator index; used in local scopes in for-loops and reductions"
8519 Ident ident;
8520 Integer index;
8521 Type identType "type of the identifier, without considering the subscripts";
8522 list<Subscript> subscriptLst;
8523 end CREF_ITER;*/
8524
8525
8526
8527 49 template simulationInitFile(SimCode simCode, Text& extraFuncsDecl, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
8528 ::=
8529 match simCode
8530 case SIMCODE(modelInfo = MODELINFO(varInfo = vi as VARINFO(__), vars = vars as SIMVARS(__), name=name))
8531 then
8532 let className = lastIdentOfPath(name)
8533 let &additionalConstVarFunctionCalls = buffer ""
8534 let &extraFuncsDecl += "void initConstVals();"
8535 <<
8536
8537 //String parameter <%listLength(vars.stringParamVars)%>
8538 <%List.partition(vars.stringParamVars, 100) |> varPartition hasindex i0 =>
8539 initConstValsWithSplit(varPartition, simCode, i0, className, additionalConstVarFunctionCalls, extraFuncsDecl, stateDerVectorName, useFlatArrayNotation) ;separator="\n"%>
8540
8541 void <%className%>::initConstVals()
8542 {
8543 <%additionalConstVarFunctionCalls%>
8544 }
8545 >>
8546 end simulationInitFile;
8547
8548 7 template initConstValsWithSplit(list<SimVar> simVars, SimCode simCode, Text idx, Text className, Text& additionalFunctionCalls, Text& additionalFunctionDefinitions, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
8549 ::=
8550 let &additionalFunctionCalls += ' initConstVals_<%idx%>();<%\n%>'
8551 let &additionalFunctionDefinitions += 'void initConstVals_<%idx%>();<%\n%>'
8552 <<
8553 void <%className%>::initConstVals_<%idx%>()
8554 {
8555 <%simVars |> var =>
8556 initConstValue(var, simCode, stateDerVectorName, useFlatArrayNotation)
8557 ;separator="\n"%>
8558 }
8559 >>
8560 end initConstValsWithSplit;
8561
8562 40 template initConstValue(SimVar var, SimCode simCode, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
8563 ::=
8564 match var
8565 case SIMVAR(numArrayElement=_::_) then ''
8566 case SIMVAR(type_=type,name=name) then
8567 match initialValue
8568 case SOME(v) then
8569 let &preExp = buffer ""
8570 let &varDecls = buffer ""
8571 let initValue = initConstValue2(v, &preExp, &varDecls, simCode, stateDerVectorName, useFlatArrayNotation)
8572 <<
8573 <%varDecls%>
8574 <%preExp%>
8575 <%cref(name, useFlatArrayNotation)%> = <%initValue%>;
8576 >>
8577 else
8578 match type
8579 case T_STRING(__) then '<%cref(name, useFlatArrayNotation)%> = "";'
8580 else '<%cref(name, useFlatArrayNotation)%> = 0;'
8581 end initConstValue;
8582
8583 37 template initConstValue2(Exp initialValue, Text &preExp, Text &varDecls, SimCode simCode, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
8584 ::=
8585 match initialValue
8586 case v then
8587 let &extraFuncs = buffer ""
8588 let &extraFuncsDecl = buffer ""
8589 let &extraFuncsNamespace = buffer ""
8590 match daeExp(v, contextOther, &preExp, &varDecls, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
8591 case vStr as "0"
8592 case vStr as "0.0"
8593 case vStr as "(0)"
8594 case vStr as ""
8595 case vStr then
8596 '<%vStr%>'
8597 end match
8598 end initConstValue2;
8599
8600 ✗ template initializeArrayElements(SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Boolean useFlatArrayNotation)
8601 ::=
8602 match simCode
8603 case SIMCODE(modelInfo = MODELINFO(varInfo = vi as VARINFO(__), vars = vars as SIMVARS(__)))
8604 then
8605 <<
8606 <%initValsArray(vars.constVars,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,useFlatArrayNotation)%>
8607 <%initValsArray(vars.intConstVars,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,useFlatArrayNotation)%>
8608 <%initValsArray(vars.boolConstVars,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,useFlatArrayNotation)%>
8609 <%initValsArray(vars.stringConstVars,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,useFlatArrayNotation)%>
8610 >>
8611 end initializeArrayElements;
8612
8613 ✗ template initValsArray(list<SimVar> varsLst,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace,Boolean useFlatArrayNotation) ::=
8614 varsLst |> SIMVAR(numArrayElement=_::_,initialValue=SOME(v)) =>
8615 <<
8616 <%cref(name,useFlatArrayNotation)%> = <%initVal(v)%>;
8617 >>
8618 ;separator="\n"
8619 end initValsArray;
8620
8621 ✗ template arrayInit(SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Boolean useFlatArrayNotation)
8622 "Generates the contents of the makefile for the simulation case."
8623 ::=
8624 match simCode
8625 case SIMCODE(modelInfo = MODELINFO(varInfo = vi as VARINFO(__), vars = vars as SIMVARS(__)))
8626 then
8627 <<
8628 <%initVals1(vars.paramVars,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, useFlatArrayNotation)%>
8629 <%initVals1(vars.intParamVars,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, useFlatArrayNotation)%>
8630 <%initVals1(vars.boolParamVars,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, useFlatArrayNotation)%>
8631 <%initVals1(vars.stringParamVars,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, useFlatArrayNotation)%>
8632 >>
8633 end arrayInit;
8634
8635 ✗ template initVals1(list<SimVar> varsLst, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Boolean useFlatArrayNotation) ::=
8636 varsLst |> (var as SIMVAR(__)) =>
8637 initVals2(var,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,useFlatArrayNotation)
8638 ;separator="\n"
8639 end initVals1;
8640
8641 ✗ template initVals2(SimVar var, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Boolean useFlatArrayNotation) ::=
8642 match var
8643 case SIMVAR(numArrayElement = {}) then ''
8644 case SIMVAR(__) then '<%cref(name, useFlatArrayNotation)%>=<%match initialValue
8645 case SOME(v) then initVal(v)
8646 else "0"
8647 %>;'
8648 end initVals2;
8649
8650 /*
8651 template arrayReindex(ModelInfo modelInfo, Boolean useFlatArrayNotation)
8652 ::=
8653 match modelInfo
8654 case MODELINFO(vars = vars as SIMVARS(__))
8655 then
8656 <<
8657 <%arrayReindex1(vars.algVars,useFlatArrayNotation)%>
8658 <%arrayReindex1(vars.discreteAlgVars,useFlatArrayNotation)%>
8659 <%arrayReindex1(vars.intAlgVars,useFlatArrayNotation)%>
8660 <%arrayReindex1(vars.boolAlgVars,useFlatArrayNotation)%>
8661 <%arrayReindex1(vars.stringAlgVars,useFlatArrayNotation)%>
8662 <%arrayReindex1(vars.paramVars,useFlatArrayNotation)%>
8663 <%arrayReindex1(vars.intParamVars,useFlatArrayNotation)%>
8664 <%arrayReindex1(vars.boolParamVars,useFlatArrayNotation)%>
8665 <%arrayReindex1(vars.stringParamVars,useFlatArrayNotation)%>
8666 <%arrayReindex1(vars.aliasVars,useFlatArrayNotation)%>
8667 <%arrayReindex1(vars.intAliasVars,useFlatArrayNotation)%>
8668 <%arrayReindex1(vars.boolAliasVars,useFlatArrayNotation)%>
8669 <%arrayReindex1(vars.stringAliasVars,useFlatArrayNotation)%>
8670 <%arrayReindex1(vars.constVars,useFlatArrayNotation)%>
8671 <%arrayReindex1(vars.intConstVars,useFlatArrayNotation)%>
8672 <%arrayReindex1(vars.boolConstVars,useFlatArrayNotation)%>
8673 <%arrayReindex1(vars.stringConstVars,useFlatArrayNotation)%>
8674 >>
8675 end arrayReindex;
8676 */
8677 /*
8678 template arrayReindex1(list<SimVar> varsLst, Boolean useFlatArrayNotation)
8679 ::=
8680 if(boolNot(useFlatArrayNotation)) then (varsLst |> SIMVAR(arrayCref=SOME(_),numArrayElement=_::_) => '<%arraycref(name, useFlatArrayNotation)%>.reindex(1);';separator="\n")
8681 end arrayReindex1;
8682 */
8683
8684 ✗ template initVal(Exp initialValue)
8685 ::=
8686 match initialValue
8687 case ICONST(__) then integer
8688 case RCONST(__) then real
8689 case SCONST(__) then '"<%Util.escapeModelicaStringToCString(string)%>"'
8690 case BCONST(__) then if bool then "true" else "false"
8691 case ENUM_LITERAL(__) then '<%index%>/*ENUM:<%dotPath(name)%>*/'
8692 else "*ERROR* initial value of unknown type"
8693 end initVal;
8694
8695 ✗ template dotPath(Absyn.Path path)
8696 "Generates paths with components separated by dots."
8697 ::=
8698 match path
8699 case QUALIFIED(__) then '<%name%>.<%dotPath(path)%>'
8700
8701 case IDENT(__) then name
8702 case FULLYQUALIFIED(__) then dotPath(path)
8703 end dotPath;
8704
8705 ✗ template writeoutput1(ModelInfo modelInfo)
8706 ::=
8707 match modelInfo
8708 case modelInfo as MODELINFO(vars=SIMVARS(__)) then
8709 <<
8710
8711
8712
8713 void <%lastIdentOfPath(modelInfo.name)%>WriteOutput::writeStateVarsResultNames(vector<string>& names)
8714 {
8715 <% if vars.stateVars then
8716 'names += <%(vars.stateVars |> SIMVAR(__) =>
8717 '"<%crefStrForWriteOutput(name)%>"' ;separator=",";align=10;alignSeparator=";\n names += " )%>;' %>
8718 }
8719
8720 void <%lastIdentOfPath(modelInfo.name)%>WriteOutput::writeDerivativeVarsResultNames(vector<string>& names)
8721 {
8722 <% if vars.derivativeVars then
8723 'names += <%(vars.derivativeVars |> SIMVAR(__) =>
8724 '"<%crefStrForWriteOutput(name)%>"' ;separator=",";align=10;alignSeparator=";\n names += " )%>;' %>
8725 }
8726
8727
8728
8729
8730 void <%lastIdentOfPath(modelInfo.name)%>WriteOutput::writeStateVarsResultDescription(vector<string>& description)
8731 {
8732 <% if vars.stateVars then
8733 'description += <%(vars.stateVars |> SIMVAR(__) =>
8734 '"<%Util.escapeModelicaStringToCString(comment)%>"' ;separator=",";align=10;alignSeparator=";\n description += " )%>;' %>
8735 }
8736
8737 void <%lastIdentOfPath(modelInfo.name)%>WriteOutput::writeDerivativeVarsResultDescription(vector<string>& description)
8738 {
8739 <% if vars.derivativeVars then
8740 'description += <%(vars.derivativeVars |> SIMVAR(__) =>
8741 '"<%Util.escapeModelicaStringToCString(comment)%>"' ;separator=",";align=10;alignSeparator=";\n description += " )%>;' %>
8742 }
8743
8744
8745 >>
8746 end writeoutput1;
8747
8748 49 template numResidues(list<SimCode.SimEqSystem> allEquations,ModelInfo modelInfo)
8749 ::=
8750 match modelInfo
8751 case MODELINFO(varInfo=VARINFO(numStateVars=nStates)) then
8752 let n = getNumContinuousEquations(allEquations,nStates)
8753 '<%n%>'
8754 end numResidues;
8755
8756 ✗ template numResidues2(SimEqSystem eqn)
8757 ::=
8758 match eqn
8759 case SES_RESIDUAL(__) then
8760 <<
8761 >>
8762 case SES_SIMPLE_ASSIGN(__) then
8763 <<
8764 1
8765 >>
8766 case SES_ARRAY_CALL_ASSIGN(__) then
8767 <<
8768 >>
8769 case SES_ALGORITHM(__) then
8770 <<
8771 >>
8772 case lin as SES_LINEAR(lSystem = ls as LINEARSYSTEM(__)) then
8773 <<
8774 <%(ls.vars |> var => '1');separator="+"%>
8775 >>
8776 case SES_NONLINEAR(nlSystem = nls as NONLINEARSYSTEM(__)) then
8777 <<
8778 <%(nls.eqs |> eq => '1');separator="+"%>
8779 >>
8780 case SES_MIXED(__) then numResidues2(cont)
8781 case SES_WHEN(__) then
8782 <<
8783 >>
8784 else
8785 <<
8786 >>
8787 end numResidues2;
8788
8789 107 template numStatevars(ModelInfo modelInfo)
8790 ::=
8791 match modelInfo
8792 case MODELINFO(varInfo=VARINFO(__)) then
8793 <<
8794 <%varInfo.numStateVars%>
8795 >>
8796 end numStatevars;
8797
8798 49 template numAlgvars(ModelInfo modelInfo)
8799 ::=
8800 match modelInfo
8801 case MODELINFO(varInfo=VARINFO(__)) then
8802 <<
8803 <%varInfo.numAlgVars%>+<%varInfo.numDiscreteReal%>+<%varInfo.numIntAlgVars%>+<%varInfo.numBoolAlgVars%>
8804 >>
8805 end numAlgvars;
8806
8807 270 template numRealvars(ModelInfo modelInfo)
8808 ::=
8809 match modelInfo
8810 case MODELINFO(varInfo=VARINFO(__)) then
8811 <<
8812 <%intAdd(intMul(2,varInfo.numStateVars),intAdd(varInfo.numAlgVars,intAdd(varInfo.numParams,varInfo.numDiscreteReal)))
8813 %>
8814 >>
8815 end numRealvars;
8816
8817 //return the start index of the state var vector in the simvars memory
8818 58 template numStateVarIndex(ModelInfo modelInfo)
8819 ::=
8820 match modelInfo
8821 case MODELINFO(varInfo=VARINFO(__)) then
8822 <<
8823 0
8824 >>
8825 end numStateVarIndex;
8826
8827
8828 270 template numIntvars(ModelInfo modelInfo)
8829 ::=
8830 match modelInfo
8831 case MODELINFO(varInfo=VARINFO(__)) then
8832 <<
8833 <%intAdd(varInfo.numIntAlgVars,varInfo.numIntParams)%>
8834 >>
8835 end numIntvars;
8836
8837 270 template numBoolvars(ModelInfo modelInfo)
8838 ::=
8839 match modelInfo
8840 case MODELINFO(varInfo=VARINFO(__)) then
8841 <<
8842 <%intAdd(varInfo.numBoolAlgVars,varInfo.numBoolParams)%>
8843 >>
8844 end numBoolvars;
8845
8846 165 template numStringvars(ModelInfo modelInfo)
8847 ::=
8848 match modelInfo
8849 case MODELINFO(varInfo=VARINFO(__)) then
8850 <<
8851 <%intAdd(varInfo.numStringAlgVars,varInfo.numStringParamVars)%>
8852 >>
8853 end numStringvars;
8854
8855 ✗ template numProtectedAlgvars(ModelInfo modelInfo)
8856 ::=
8857 match modelInfo
8858 case MODELINFO(vars=SIMVARS(__)) then
8859 <<
8860 <%listLength(protectedVars(vars.algVars))%>+<%listLength(protectedVars(vars.discreteAlgVars))%>+<%listLength(protectedVars(vars.intAlgVars))%>+<%listLength(protectedVars(vars.boolAlgVars))%>
8861 >>
8862 end numProtectedAlgvars;
8863
8864 ✗ template numParamVars(ModelInfo modelInfo)
8865 ::=
8866 match modelInfo
8867 case MODELINFO(varInfo=VARINFO(__)) then
8868 let n_vars = intAdd(varInfo.numParams,intAdd(varInfo.numIntParams,varInfo.numBoolParams))
8869 <<
8870 <%n_vars%>
8871 >>
8872 end numParamVars;
8873
8874 49 template numProtectedParamVars(ModelInfo modelInfo)
8875 ::=
8876 match modelInfo
8877 case MODELINFO(vars=SIMVARS(__)) then
8878 let n_vars = intAdd(listLength(protectedVars(vars.paramVars)),intAdd(listLength(protectedVars(vars.intParamVars)),listLength(protectedVars(vars.boolParamVars))))
8879 <<
8880 <%n_vars%>
8881 >>
8882 end numProtectedParamVars;
8883
8884
8885 ✗ template numProtectedRealParamVars(ModelInfo modelInfo)
8886 ::=
8887 match modelInfo
8888 case MODELINFO(vars=SIMVARS(__)) then
8889 let n_vars = listLength(protectedVars(vars.paramVars))
8890 <<
8891 <%n_vars%>
8892 >>
8893 end numProtectedRealParamVars;
8894
8895 ✗ template numProtectedIntParamVars(ModelInfo modelInfo)
8896 ::=
8897 match modelInfo
8898 case MODELINFO(vars=SIMVARS(__)) then
8899 let n_vars = listLength(protectedVars(vars.intParamVars))
8900 <<
8901 <%n_vars%>
8902 >>
8903 end numProtectedIntParamVars;
8904
8905
8906
8907
8908 ✗ template numInOutvars(ModelInfo modelInfo)
8909 ::=
8910 match modelInfo
8911 case MODELINFO(varInfo=VARINFO(__)) then
8912 <<
8913 <%varInfo.numInVars%>+<%varInfo.numOutVars%>
8914 >>
8915 end numInOutvars;
8916
8917 49 template numAliasvars(ModelInfo modelInfo)
8918 ::=
8919 match modelInfo
8920 case MODELINFO(varInfo=VARINFO(__)) then
8921 <<
8922 <%varInfo.numAlgAliasVars%>+<%varInfo.numIntAliasVars%>+<%varInfo.numBoolAliasVars%>
8923 >>
8924 end numAliasvars;
8925
8926 ✗ template numProtectedAliasvars(ModelInfo modelInfo)
8927 ::=
8928 match modelInfo
8929 case MODELINFO(vars=SIMVARS(__)) then
8930 <<
8931 <%listLength(protectedVars(vars.aliasVars))%>+<%listLength(protectedVars(vars.intAliasVars))%>+<%listLength(protectedVars(vars.boolAliasVars))%>
8932 >>
8933 end numProtectedAliasvars;
8934
8935
8936 ✗ template numAlgvar(ModelInfo modelInfo)
8937 ::=
8938 match modelInfo
8939 case MODELINFO(varInfo=VARINFO(__)) then
8940 <<
8941 <%varInfo.numAlgVars%>
8942 >>
8943 end numAlgvar;
8944
8945
8946 ✗ template numProtectedRealAlgvars(ModelInfo modelInfo)
8947 ::=
8948 match modelInfo
8949 case MODELINFO(vars=SIMVARS(__)) then
8950 <<
8951 <%listLength(protectedVars(vars.algVars))%>
8952 >>
8953 end numProtectedRealAlgvars;
8954
8955 ✗ template numDiscreteAlgVar(ModelInfo modelInfo)
8956 ::=
8957 match modelInfo
8958 case MODELINFO(varInfo=VARINFO(__)) then
8959 <<
8960 <%varInfo.numDiscreteReal%>
8961 >>
8962 end numDiscreteAlgVar;
8963
8964 ✗ template numProtectedDiscreteAlgVars(ModelInfo modelInfo)
8965 ::=
8966 match modelInfo
8967 case MODELINFO(vars=SIMVARS(__)) then
8968 <<
8969 <%listLength(protectedVars(vars.discreteAlgVars))%>
8970 >>
8971 end numProtectedDiscreteAlgVars;
8972
8973 ✗ template numIntAlgvar(ModelInfo modelInfo)
8974 ::=
8975 match modelInfo
8976 case MODELINFO(varInfo=VARINFO(__)) then
8977 <<
8978 <%varInfo.numIntAlgVars%>
8979 >>
8980 end numIntAlgvar;
8981
8982 ✗ template numProtectedIntAlgvars(ModelInfo modelInfo)
8983 ::=
8984 match modelInfo
8985 case MODELINFO(vars=SIMVARS(__)) then
8986 <<
8987 <%listLength(protectedVars(vars.intAlgVars))%>
8988 >>
8989 end numProtectedIntAlgvars;
8990
8991 ✗ template numBoolAlgvars(ModelInfo modelInfo)
8992 ::=
8993 match modelInfo
8994 case MODELINFO(varInfo=VARINFO(__)) then
8995 <<
8996 <%varInfo.numBoolAlgVars%>
8997 >>
8998 end numBoolAlgvars;
8999
9000
9001 ✗ template numProtectedBoolAlgvars(ModelInfo modelInfo)
9002 ::=
9003 match modelInfo
9004 case MODELINFO(vars=SIMVARS(__)) then
9005 <<
9006 <%listLength(protectedVars(vars.boolAlgVars))%>
9007 >>
9008 end numProtectedBoolAlgvars;
9009
9010 ✗ template numInputvar(ModelInfo modelInfo)
9011 ::=
9012 match modelInfo
9013 case MODELINFO(varInfo=VARINFO(__)) then
9014 <<
9015 <%varInfo.numInVars%>
9016 >>
9017 end numInputvar;
9018
9019 ✗ template numOutputvar(ModelInfo modelInfo)
9020 ::=
9021 match modelInfo
9022 case MODELINFO(varInfo=VARINFO(__)) then
9023 <<
9024 <%varInfo.numOutVars%>
9025 >>
9026 end numOutputvar;
9027
9028 ✗ template numAliasvar(ModelInfo modelInfo)
9029 ::=
9030 match modelInfo
9031 case MODELINFO(varInfo=VARINFO(__)) then
9032 <<
9033 <%varInfo.numAlgAliasVars%>
9034 >>
9035 end numAliasvar;
9036
9037 ✗ template numProtectedRealAliasvars(ModelInfo modelInfo)
9038 ::=
9039 match modelInfo
9040 case MODELINFO(vars=SIMVARS(__)) then
9041 <<
9042 <%listLength(protectedVars(vars.aliasVars))%>
9043 >>
9044 end numProtectedRealAliasvars;
9045
9046
9047 ✗ template numIntAliasvar(ModelInfo modelInfo)
9048 ::=
9049 match modelInfo
9050 case MODELINFO(varInfo=VARINFO(__)) then
9051 <<
9052 <%varInfo.numIntAliasVars%>
9053 >>
9054 end numIntAliasvar;
9055
9056 ✗ template numProtectedIntAliasvars(ModelInfo modelInfo)
9057 ::=
9058 match modelInfo
9059 case MODELINFO(vars=SIMVARS(__)) then
9060 <<
9061 <%listLength(protectedVars(vars.intAliasVars))%>
9062 >>
9063 end numProtectedIntAliasvars;
9064
9065 ✗ template numBoolAliasvar(ModelInfo modelInfo)
9066 ::=
9067 match modelInfo
9068 case MODELINFO(varInfo=VARINFO(__)) then
9069 <<
9070 <%varInfo.numBoolAliasVars%>
9071 >>
9072 end numBoolAliasvar;
9073
9074
9075 ✗ template numProtectedBoolAliasvars(ModelInfo modelInfo)
9076 ::=
9077 match modelInfo
9078 case MODELINFO(vars=SIMVARS(__)) then
9079 <<
9080 <%listLength(protectedVars(vars.boolAliasVars))%>
9081 >>
9082 end numProtectedBoolAliasvars;
9083
9084 ✗ template numDerivativevars(ModelInfo modelInfo)
9085 ::=
9086 match modelInfo
9087 case MODELINFO(varInfo=VARINFO(__)) then
9088 <<
9089 <%varInfo.numStateVars%>
9090 >>
9091 end numDerivativevars;
9092
9093 ✗ template getAliasSign(SimVar simVar)
9094 "Get sign of alias variable, considering its data type"
9095 ::=
9096 match simVar
9097 case SIMVAR(type_=type_) then
9098 match aliasvar
9099 case NEGATEDALIAS(__) then
9100 match type_ case T_BOOL(__) then '!' else '-'
9101 else ''
9102 end getAliasSign;
9103
9104 ✗ template getAliasCRef(AliasVariable aliasvar, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace,Context context, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
9105 "Returns the alias Attribute of ScalarVariable."
9106 ::=
9107 let &varDeclsCref = buffer "" /*BUFD*/
9108 match aliasvar
9109 case ALIAS(__)
9110 case NEGATEDALIAS(__) then '<%cref1(varName, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, context, varDeclsCref, stateDerVectorName, useFlatArrayNotation)%>'
9111 else 'noAlias'
9112 end getAliasCRef;
9113
9114 //template for write variables for each time step
9115 ✗ template generateWriteOutputFunctionsForVars(ModelInfo modelInfo,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, String className, Boolean useFlatArrayNotation)
9116 ::=
9117 match modelInfo
9118 case MODELINFO(vars=SIMVARS(__)) then
9119 let &varDeclsCref = buffer "" /*BUFD*/
9120 let algVarsStart = "1"
9121 let discrAlgVarsStart = intAdd(stringInt(algVarsStart), stringInt(numProtectedRealAlgvars(modelInfo)))
9122 let intAlgVarsStart = intAdd(stringInt(discrAlgVarsStart), stringInt(numProtectedDiscreteAlgVars(modelInfo)))
9123 let boolAlgVarsStart = intAdd(stringInt(intAlgVarsStart), stringInt(numProtectedIntAlgvars(modelInfo)))
9124 let aliasVarsStart = intAdd(stringInt(boolAlgVarsStart), stringInt(numProtectedBoolAlgvars(modelInfo)))
9125 let intAliasVarsStart = intAdd(stringInt(aliasVarsStart), stringInt(numProtectedRealAliasvars(modelInfo)))
9126 let boolAliasVarsStart = intAdd(stringInt(intAliasVarsStart), stringInt(numProtectedIntAliasvars(modelInfo)))
9127 let stateVarsStart = intAdd(stringInt(boolAliasVarsStart), stringInt(numProtectedBoolAliasvars(modelInfo)))
9128 <<
9129
9130 void <%className%>::writeStateValues(HistoryImplType::value_type_v *v, HistoryImplType::value_type_dv *v2)
9131 {
9132 <%(vars.stateVars |> SIMVAR() hasindex i8 =>'(*v)(<%intAdd(stringInt(stateVarsStart), stringInt(i8))%>)=__z[<%index%>];';separator="\n")%>
9133 <%(vars.derivativeVars |> SIMVAR() hasindex i9 fromindex 1 =>'(*v2)(<%i9%>)=__zDot[<%index%>]; ';separator="\n")%>
9134 }
9135 >>
9136 end generateWriteOutputFunctionsForVars;
9137
9138 /*
9139 const int algVarsStart = <%algVarsStart%>;
9140 const int discrAlgVarsStart = <%discrAlgVarsStart%>;
9141 const int intAlgVarsStart = <%intAlgVarsStart%>;
9142 const int boolAlgVarsStart = <%boolAlgVarsStart%>;
9143 const int aliasVarsStart = <%aliasVarsStart%>;
9144 const int intAliasVarsStart = <%intAliasVarsStart%>;
9145 const int boolAliasVarsStart = <%boolAliasVarsStart%>;
9146 const int stateVarsStart = <%stateVarsStart%>;
9147 */
9148
9149 //template to generate a function that writes all given variables
9150 ✗ template writeOutputVars(String functionName, list<SimVar> vars, Integer startIndex, String className, Boolean areAliasVars, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
9151 ::=
9152 <<
9153 void <%className%>::<%functionName%>(HistoryImplType::value_type_v *v)
9154 {
9155 <%if(areAliasVars) then
9156 <<
9157 <%vars |> simVar as SIMVAR(isProtected=false) hasindex i1 =>'(*v)(<%intAdd(startIndex, stringInt(i1))%>) = <%getAliasSign(simVar)%><%getAliasCRef(aliasvar, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, contextOther, stateDerVectorName, useFlatArrayNotation)%>;';separator="\n"%>
9158 >>
9159 else
9160 <<
9161 <%vars |> SIMVAR(isProtected=false) hasindex i0 =>'(*v)(<%intAdd(startIndex,stringInt(i0))%>)=<%cref(name, useFlatArrayNotation)%>;';separator="\n"%>
9162 >>%>
9163 }
9164 >>
9165 end writeOutputVars;
9166
9167 ✗ template writeOutputVarsWithSplit(String functionName, list<SimVar> vars, Integer startIndex, String className, Boolean areAliasVars, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
9168 ::=
9169 let &funcCalls = buffer "" /*BUFD*/
9170 let funcs = List.partition(vars, 100) |> ls hasindex idx =>
9171 let &varDecls = buffer "" /*BUFD*/
9172 let &funcCalls += '<%className%>::<%functionName%>_<%idx%>(v);'
9173 let init = writeValueValst(ls, startIndex, idx, 100, areAliasVars, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
9174 <<
9175 void <%className%>::<%functionName%>_<%idx%>(HistoryImplType::value_type_v *v)
9176 {
9177 <%varDecls%>
9178 <%init%>
9179 }
9180 >>
9181 ;separator="\n"
9182
9183 <<
9184 <%funcs%>
9185
9186 void <%className%>::<%functionName%>(HistoryImplType::value_type_v *v)
9187 {
9188 //number of vars: <%listLength(vars)%>
9189 <%funcCalls%>
9190 }
9191 >>
9192 end writeOutputVarsWithSplit;
9193
9194 ✗ template writeValueValst(list<SimVar> vars, Integer startIndex, Integer idx, Integer multiplicator, Boolean areAliasVars, SimCode simCode, Text& extraFuncs,
9195 Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
9196 ::=
9197 if(areAliasVars) then
9198 <<
9199 <%vars |> simVar as SIMVAR(isProtected=false) hasindex i1 =>'(*v)(<%intAdd(intMul(idx,multiplicator),intAdd(startIndex, stringInt(i1)))%>) = <%getAliasSign(simVar)%><%getAliasCRef(aliasvar, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, contextOther, stateDerVectorName, useFlatArrayNotation)%>;';separator="\n"%>
9200 >>
9201 else
9202 <<
9203 <%vars |> SIMVAR(isProtected=false) hasindex i0 =>'(*v)(<%intAdd(intMul(idx,multiplicator),intAdd(startIndex, stringInt(i0)))%>)=<%cref(name, useFlatArrayNotation)%>;';separator="\n"%>
9204 >>
9205 end writeValueValst;
9206
9207 //template for write parameter values
9208 ✗ template writeoutputparams(ModelInfo modelInfo,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Context context, Boolean useFlatArrayNotation)
9209
9210 ::=
9211 match modelInfo
9212 case MODELINFO(vars=SIMVARS(__),varInfo=VARINFO(__)) then
9213 let &varDeclsCref = buffer "" /*BUFD*/
9214
9215 /*<<
9216 const int paramVarsStart = 1;
9217 const int intParamVarsStart = paramVarsStart + <%numProtectedRealParamVars(modelInfo)%>;
9218 const int boolparamVarsStart = intParamVarsStart + <%numProtectedIntParamVars(modelInfo)%>;
9219
9220 <%vars.paramVars |> SIMVAR(isProtected=false) hasindex i0 =>'params(paramVarsStart+<%i0%>)=<%cref(name, useFlatArrayNotation)%>;';align=8 %>
9221 <%vars.intParamVars |> SIMVAR(isProtected=false) hasindex i0 =>'params(intParamVarsStart+<%i0%>)=<%cref(name, useFlatArrayNotation)%>;';align=8 %>
9222 <%vars.boolParamVars |> SIMVAR(isProtected=false) hasindex i1 =>'params(boolparamVarsStart+<%i1%>)=<%cref(name, useFlatArrayNotation)%>;';align=8%>
9223 >>*/
9224 let paramVarsStart = 1
9225 let intParamVarsStart = intAdd(1,stringInt(numProtectedRealParamVars(modelInfo)))
9226 let boolparamVarsStart = intAdd(stringInt(intParamVarsStart),stringInt(numProtectedIntParamVars(modelInfo)))
9227 <<
9228 void <%lastIdentOfPath(name)%>WriteOutput::writeParams(HistoryImplType::value_type_p& params)
9229 {
9230 /*const int paramVarsStart = 1;
9231 const int intParamVarsStart = paramVarsStart + <%numProtectedRealParamVars(modelInfo)%>;
9232 const int boolparamVarsStart = intParamVarsStart + <%numProtectedIntParamVars(modelInfo)%>;
9233 */
9234 writeParamsReal(params);
9235 writeParamsInt(params);
9236 writeParamsBool(params);
9237 }
9238 <%writeoutputparamsWithSplit('<%lastIdentOfPath(name)%>WriteOutput::writeParams',stringInt(paramVarsStart),"Real",vars.paramVars,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,context,useFlatArrayNotation)%>
9239 <%writeoutputparamsWithSplit('<%lastIdentOfPath(name)%>WriteOutput::writeParams',stringInt(intParamVarsStart),"Int",vars.intParamVars,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,context,useFlatArrayNotation)%>
9240 <%writeoutputparamsWithSplit('<%lastIdentOfPath(name)%>WriteOutput::writeParams',stringInt(boolparamVarsStart),"Bool",vars.boolParamVars,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,context,useFlatArrayNotation)%>
9241 >>
9242 end writeoutputparams;
9243
9244
9245 ✗ template writeoutputparamsWithSplit(Text funcNamePrefix, Integer startindex,Text type, list<SimVar> varsLst, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Context context, Boolean useFlatArrayNotation) ::=
9246 let &funcCalls = buffer "" /*BUFD*/
9247 let funcs = List.partition(protectedVars(varsLst), 100) |> ls hasindex idx =>
9248 let &varDecls = buffer "" /*BUFD*/
9249 let &funcCalls += '<%funcNamePrefix%><%type%>_<%idx%>(params);'
9250 let init = writeParamValst(ls,startindex,idx,100,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, context, useFlatArrayNotation)
9251 <<
9252 void <%funcNamePrefix%><%type%>_<%idx%>( HistoryImplType::value_type_p& params )
9253 {
9254 <%varDecls%>
9255 <%init%>
9256 }
9257 >>
9258 ;separator="\n"
9259
9260 <<
9261 <%funcs%>
9262
9263 void <%funcNamePrefix%><%type%>(HistoryImplType::value_type_p& params )
9264 {
9265 //number of vars: <%listLength(varsLst)%>
9266 <%funcCalls%>
9267 }
9268 >>
9269 end writeoutputparamsWithSplit;
9270
9271
9272 ✗ template writeParamValst(list<SimVar> varsLst,Integer startindex,Integer idx, Integer multiplicator, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Context context, Boolean useFlatArrayNotation)
9273 ::=
9274 varsLst |> SIMVAR(isProtected=false) hasindex i0 fromindex intAdd(startindex,intMul(idx,multiplicator)) =>'params(<%i0%>)=<%cref(name, useFlatArrayNotation)%>;';align=8
9275 end writeParamValst;
9276
9277
9278 49 template saveAll(ModelInfo modelInfo, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace,Text stateDerVectorName,Boolean useFlatArrayNotation)
9279
9280 ::=
9281 match simCode
9282 case SIMCODE(modelInfo = MODELINFO(vars = vars as SIMVARS(__)))
9283 then
9284 let className = lastIdentOfPath(modelInfo.name)
9285 <<
9286 void <%className%>::saveAll()
9287 {
9288 getSimVars()->savePreVariables();
9289 }
9290 >>
9291
9292 end saveAll;
9293
9294 ✗ template saveDiscreteVars(ModelInfo modelInfo, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Boolean useFlatArrayNotation)
9295 ::=
9296 match simCode
9297 case SIMCODE(modelInfo = MODELINFO(vars = vars as SIMVARS(__)))
9298 then
9299 let n_vars = intAdd(intAdd(listLength(vars.algVars), listLength(vars.discreteAlgVars)), intAdd( listLength(vars.intAlgVars) , listLength(vars.boolAlgVars )))
9300 let className = lastIdentOfPath(modelInfo.name)
9301 match n_vars
9302 case "0" then
9303 <<
9304 void <%className%>::saveDiscreteVars()
9305 {
9306 }
9307 >>
9308 else
9309 let &funcCalls = buffer "" /*BUFD*/
9310 let saveDiscreteVarFuncs = (List.partition(listAppend(vars.algVars, listAppend(vars.discreteAlgVars, listAppend(vars.intAlgVars, vars.boolAlgVars))), 100) |> part hasindex i0 =>
9311 saveDiscreteVars1(part, i0, 100, &funcCalls ,useFlatArrayNotation, className);separator="\n")
9312 <<
9313 <%saveDiscreteVarFuncs%>
9314
9315 void <%className%>::saveDiscreteVars()
9316 {
9317 double discreteVars[<%n_vars%>];
9318
9319 <%funcCalls%>
9320
9321 _event_handling->saveDiscretPreVars(discreteVars,<%n_vars%>);
9322 }
9323
9324 >>
9325 end saveDiscreteVars;
9326
9327 ✗ template saveDiscreteVars1(list<SimCodeVar.SimVar> partVars, Integer partIdx, Integer multiplicator, Text &funcCalls, Boolean useFlatArrayNotation, Text className)
9328 ::=
9329 <<
9330 void <%className%>::saveDiscreteVars_<%partIdx%>(double* discreteVars)
9331 {
9332
9333 }
9334 >>
9335 /*
9336 let &funcCalls += 'saveDiscreteVars_<%partIdx%>(discreteVars);'
9337 Deactivated:
9338 <<
9339 void <%className%>::saveDiscreteVars_<%partIdx%>(double* discreteVars)
9340 {
9341 <%(partVars |> SIMVAR(__) hasindex i0 fromindex (intMul(partIdx, multiplicator)) =>
9342 'discreteVars[<%i0%>] = <%cref(name,useFlatArrayNotation)%>;';separator="\n")%>
9343 }
9344 >>
9345 */
9346 end saveDiscreteVars1;
9347
9348 ✗ template initAlgloopvars(Text &preExp, Text &varDecls, ModelInfo modelInfo, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Context context, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
9349 ::=
9350 match modelInfo
9351 case MODELINFO(vars=SIMVARS(__)) then
9352 let &varDecls = buffer "" /*BUFD*/
9353 let &text = buffer "" /*BUFD*/
9354 let algvars = initValst(varDecls, "Real", vars.algVars, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, context, stateDerVectorName, useFlatArrayNotation)
9355 let discretealgvars = initValst(varDecls, "Real", vars.discreteAlgVars, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, context, stateDerVectorName, useFlatArrayNotation)
9356 let intvars = initValst(varDecls, "Int", vars.intAlgVars, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, context, stateDerVectorName, useFlatArrayNotation)
9357 let boolvars = initValst(varDecls, "Bool", vars.boolAlgVars, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, context, stateDerVectorName, useFlatArrayNotation)
9358 <<
9359 <%varDecls%>
9360 <%algvars%>
9361 <%discretealgvars%>
9362 <%intvars%>
9363 <%boolvars%>
9364 >>
9365 end initAlgloopvars;
9366
9367 ✗ template boundParameters(list<SimEqSystem> parameterEquations, Text &varDecls, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace,
9368 Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
9369 "Generates function in simulation file."
9370 ::=
9371 let &tmp = buffer ""
9372 let body = (parameterEquations |> eq as SES_SIMPLE_ASSIGN(__) =>
9373 equation_(eq, contextSimulationDiscrete, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
9374 ;separator="\n")
9375 let divbody = (parameterEquations |> eq as SES_ALGORITHM(__) =>
9376 equation_(eq, contextSimulationDiscrete, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
9377 ;separator="\n")
9378 <<
9379 <%body%>
9380 <%divbody%>
9381 >>
9382 end boundParameters;
9383
9384
9385 ✗ template outputIndices(ModelInfo modelInfo)
9386 ::= match modelInfo
9387 case MODELINFO(varInfo=VARINFO(__),vars=SIMVARS(__)) then
9388 if varInfo.numOutVars then
9389 <<
9390 var_ouputs_idx = MAP_LIST_OF <%
9391 {(vars.outputVars |> SIMVAR(__) => '<%index%>,"<%CodegenCppCommon.crefStr(name)%>"';separator=",") };separator=" MAP_LIST_SEP "%> MAP_LIST_END;
9392 >>
9393 end outputIndices;
9394
9395
9396 ✗ template isOutput(Causality c, Boolean useFlatArrayNotation)
9397 "Returns the Causality Attribute of a Variable."
9398 ::=
9399 match c
9400 case OUTPUT(__) then "output"
9401 end isOutput;
9402
9403
9404 70 template initValstWithSplit(Text &varDecls, Text type, Text funcNamePrefix, list<SimVar> varsLst, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl,
9405 Text extraFuncsNamespace, Context context, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
9406 ::=
9407 let &funcCalls = buffer "" /*BUFD*/
9408 let funcs = List.partition(varsLst, 100) |> ls hasindex idx =>
9409 let &varDecls = buffer "" /*BUFD*/
9410 let &funcCalls += '<%funcNamePrefix%>_<%idx%>();'
9411 let init = initValst(varDecls, type, ls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, context, stateDerVectorName, useFlatArrayNotation)
9412 <<
9413 void <%funcNamePrefix%>_<%idx%>()
9414 {
9415 <%varDecls%>
9416 <%init%>
9417 }
9418 >>
9419 ;separator="\n"
9420
9421 <<
9422 <%funcs%>
9423
9424 void <%funcNamePrefix%>()
9425 {
9426 <%funcCalls%>
9427 }
9428 >>
9429 end initValstWithSplit;
9430
9431
9432 163 template initValst(Text &varDecls, Text type, list<SimVar> varsLst, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Context context, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
9433 ::=
9434 if(Flags.isSet(Flags.HARDCODED_START_VALUES)) then
9435 (varsLst |> sv as SIMVAR(__) =>
9436 let &preExp = buffer "" /*BUFD*/
9437 let &varDeclsCref = buffer "" /*BUFD*/
9438 let &startValue = buffer ""
9439 let crefStr = cref1(sv.name,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,context,varDeclsCref, stateDerVectorName, useFlatArrayNotation)
9440 match initialValue
9441 case SOME(v) then
9442 let vStr = daeExp(v, contextOther, &preExp, &varDecls,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
9443 <<
9444 <%preExp%>
9445 SystemDefaultImplementation::set<%type%>StartValue(<%crefStr%>, <%vStr%>);
9446 >>
9447 else
9448 <<
9449 <%preExp%>
9450 SystemDefaultImplementation::set<%type%>StartValue(<%crefStr%>, <%startValue(sv.type_)%>);
9451 >>
9452 ;separator="\n")
9453 else
9454 (varsLst |> sv as SIMVAR(__) =>
9455 let &preExp = buffer "" /*BUFD*/
9456 let &varDeclsCref = buffer "" /*BUFD*/
9457 let &startValue = buffer ""
9458 let crefStr = cref1(sv.name, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace,context,varDeclsCref, stateDerVectorName, useFlatArrayNotation)
9459 let checkStr = match initialValue
9460 case SOME(v) then
9461 let &startValue += daeExp(v, contextOther, &preExp, &varDecls,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
9462 '<%preExp%>
9463 if(!IsEqual(SystemDefaultImplementation::get<%type%>StartValue(<%crefStr%>), <%startValue%>))
9464 std::cerr << "Wrong start value for variable <%crefStr%> detected. Got " << SystemDefaultImplementation::get<%type%>StartValue(<%crefStr%>) << " Expected: " << <%startValue%> << std::endl;'
9465 else
9466 let &startValue += startValue(sv.type_)
9467 ''
9468 checkStr;separator="\n")
9469 end initValst;
9470
9471
9472 1259 template startValue(DAE.Type ty)
9473 ::=
9474 match ty
9475 case ty as T_INTEGER(__) then '0'
9476 case ty as T_REAL(__) then '0.0'
9477 case ty as T_BOOL(__) then 'false'
9478 case ty as T_STRING(__) then '"empty"'
9479 case ty as T_ENUMERATION(__) then '0'
9480 case ty as T_ARRAY(ty = elty) then startValue(elty)
9481 else ""
9482 end startValue;
9483
9484
9485 49 template eventHandlingInit(SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
9486
9487 ::=
9488 match simCode
9489 case SIMCODE(modelInfo = MODELINFO(varInfo = vi as VARINFO(__))) then
9490 <<
9491 <%
9492 match vi.numZeroCrossings
9493 case 0 then ""
9494 else
9495 <<
9496 bool events[<%vi.numZeroCrossings%>];
9497 memset(events,true,<%vi.numZeroCrossings%>);
9498 for(int i=0;i<=<%vi.numZeroCrossings%>;++i) { handleEvent(events); }
9499 >>
9500 %>
9501 >>
9502 end eventHandlingInit;
9503
9504
9505 49 template clockIntervalsInit(SimCode simCode, Text& varDecls, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
9506 ::=
9507 match simCode
9508 case SIMCODE(modelInfo = MODELINFO(__), modelStructure = fmims) then
9509 let i = tempDecl('int', &varDecls)
9510 <<
9511 <%i%> = 0;
9512 <%(clockedPartitions |> partition =>
9513 match partition
9514 case CLOCKED_PARTITION(__) then
9515 let &preExp = buffer "" /*BUFD*/
9516 let spec = daeExp(getClockInterval(baseClock), contextOther, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
9517 // use default clock, except for FMI clocks that may be inferred
9518 let intvl = match fmims case SOME(FmiModelStructure) then spec else
9519 match baseClock
9520 case REAL_CLOCK()
9521 case RATIONAL_CLOCK()
9522 case EVENT_CLOCK() then
9523 spec
9524 else "unspecified"
9525 let interval = match intvl case "unspecified" then '1.0' else intvl
9526 let warning = match intvl case "unspecified" then
9527 'LOGGER_WRITE("Using default Clock(1.0)!", LC_MODEL, LL_WARNING);'
9528 let isEventBased = match baseClock case EVENT_CLOCK() then "true"
9529 let subClocks = (subPartitions |> subPartition =>
9530 match subPartition
9531 case SUBPARTITION(subClock=SUBCLOCK(factor=RATIONAL(nom=fnom, denom=fres), shift=RATIONAL(nom=snom, denom=sres))) then
9532 <<
9533 <%preExp%>
9534 <%if isEventBased then
9535 <<
9536 _clockInterval[<%i%>] = DBL_MAX; // determined at runtime
9537 _clockShift[<%i%>] = <%snom%>.0 / <%sres%>.0;
9538 _clockTime[<%i%>] = -DBL_MAX; // determined at runtime
9539 _clockEventBased[<%i%>] = true;
9540 >>
9541 else
9542 <<
9543 _clockInterval[<%i%>] = <%interval%> * <%fnom%>.0 / <%fres%>.0;
9544 _clockShift[<%i%>] = <%snom%>.0 / <%sres%>.0;
9545 _clockTime[<%i%>] = _simTime + _clockShift[<%i%>] * _clockInterval[<%i%>];
9546 >>
9547 %>
9548 _clockStart[<%i%>] = true;
9549 _clockSubactive[<%i%>] = false;
9550 <%i%> ++;
9551 >>
9552 ; separator="\n")
9553 <<
9554 <%subClocks%>
9555 <%warning%>
9556 >>
9557 ; separator="\n")%>
9558 >>
9559 end clockIntervalsInit;
9560
9561
9562 98 template dimension1(SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
9563 ::=
9564 match simCode
9565 case SIMCODE(modelInfo = MODELINFO(varInfo = vi as VARINFO(__)),daeModeData=SOME(DAEMODEDATA(algebraicVars=algebraicVars, residualVars=residualVars)), partitionData = PARTITIONDATA(__))
9566 then
9567 let numRealVars = numRealvars(modelInfo)
9568 let numIntVars = numIntvars(modelInfo)
9569 let numBoolVars = numBoolvars(modelInfo)
9570 let numStringVars = numStringvars(modelInfo)
9571 <<
9572 _dimContinuousStates = <%vi.numStateVars%>;
9573 _dimAE = <%listLength(algebraicVars)%>;
9574 _dimRHS = <%intAdd(vi.numStateVars,listLength(algebraicVars))%>;
9575 _dimBoolean = <%numBoolVars%>;
9576 _dimInteger = <%numIntVars%>;
9577 _dimString = <%numStringVars%>;
9578 _dimReal = <%numRealVars%>;
9579 _dimPartitions = <%partitionData.numPartitions%>;
9580 >>
9581 case SIMCODE(modelInfo = MODELINFO(varInfo = vi as VARINFO(__)),daeModeData=NONE(), partitionData = PARTITIONDATA(__))
9582 then
9583 let numRealVars = numRealvars(modelInfo)
9584 let numIntVars = numIntvars(modelInfo)
9585 let numBoolVars = numBoolvars(modelInfo)
9586 let numStringVars = numStringvars(modelInfo)
9587 <<
9588 _dimContinuousStates = <%vi.numStateVars%>;
9589 _dimRHS = <%vi.numStateVars%>;
9590 _dimBoolean = <%numBoolVars%>;
9591 _dimInteger = <%numIntVars%>;
9592 _dimString = <%numStringVars%>;
9593 _dimReal = <%numRealVars%>;
9594 _dimPartitions = <%partitionData.numPartitions%>;
9595 >>
9596 end dimension1;
9597
9598 49 template isODE(SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
9599 ::=
9600 match simCode
9601 case SIMCODE(modelInfo = MODELINFO(varInfo = vi as VARINFO(__)))
9602 then
9603 <<
9604 bool <%lastIdentOfPath(modelInfo.name)%>::isODE()
9605 {
9606 return <%vi.numStateVars%>>0 ;
9607 }
9608 >>
9609 end isODE;
9610
9611 49 template functionInitial(list<SimEqSystem> startValueEquations, Text &varDecls, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
9612 ::=
9613 let eqPart = (startValueEquations |> eq as SES_SIMPLE_ASSIGN(__) =>
9614 equationInitialization_(eq, contextSimulationDiscrete, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
9615 ;separator="\n")
9616 <<
9617 <%eqPart%>
9618 >>
9619 end functionInitial;
9620
9621 33 template equationInitialization_(SimEqSystem eq, Context context, Text &varDecls, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl,
9622 Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
9623 ::=
9624 equationString(eq, context, varDecls, simCode, extraFuncs, extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation, true, true)
9625 end equationInitialization_;
9626
9627 2153 template equation_(SimEqSystem eq, Context context, Text &varDecls, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl,
9628 Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
9629 ::=
9630 equationString(eq, context, varDecls, simCode, extraFuncs, extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation, false, false)
9631 end equation_;
9632
9633 2181 template equationString(SimEqSystem eq, Context context, Text &varDecls, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl,
9634 Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation, Boolean assignToStartValues, Boolean overwriteOldStartValue)
9635 "Generates an equation.
9636 This template should not be used for a SES_RESIDUAL.
9637 Residual equations are handled differently."
9638 ::=
9639 match eq
9640 case e as SES_SIMPLE_ASSIGN(__)
9641 then equationSimpleAssign(e, context, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation, assignToStartValues, overwriteOldStartValue)
9642 case e as SES_ALGORITHM(__)
9643 then equationAlgorithm(e, context, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
9644 case e as SES_INVERSE_ALGORITHM(__)
9645 then equationAlgorithm(e, context, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
9646 case e as SES_WHEN(__)
9647 then equationWhen(e, context, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
9648 case e as SES_ARRAY_CALL_ASSIGN(__)
9649 then equationArrayCallAssign(e, context, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation, assignToStartValues)
9650 case e as SES_RESIZABLE_ASSIGN(__)
9651 then equationResizableAssign(e, context, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
9652 case e as SES_LINEAR(lSystem = ls as LINEARSYSTEM(__))
9653 then
9654 let i = ls.index
9655 match context
9656 case ALGLOOP_CONTEXT(genInitialisation=true)
9657 then
9658 <<
9659 try
9660 {
9661
9662 _algLoop<%ls.index%>->evaluate();
9663 for(int i=0; i<_dimZeroFunc; i++)
9664 {
9665 getCondition(i);
9666 }
9667 IContinuous::UPDATETYPE calltype = _callType;
9668 _callType = IContinuous::CONTINUOUS;
9669 <%if boolOr(Flags.isSet(HPCOM),boolNot(getConfigBool(SINGLE_INSTANCE_AGLSOLVER)))
9670 then '_algLoopLinearSolver<%ls.index%>->solve();'
9671 else
9672 '_algLoopLinearSolver->solve(_algLoop<%ls.index%>,true);'
9673 %>
9674 _callType = calltype;
9675 }
9676 catch (ModelicaSimulationError& ex)
9677 {
9678 string error = add_error_info("Linear solver <%ls.index%>", ex.what(), ex.getErrorID(), _simTime);
9679 throw ModelicaSimulationError(ALGLOOP_EQ_SYSTEM, error);
9680 }
9681 >>
9682 else
9683 <<
9684 bool restart<%ls.index%> = true;
9685
9686 unsigned int iterations<%ls.index%> = 0;
9687 <%if boolOr(Flags.isSet(HPCOM),boolNot(getConfigBool(SINGLE_INSTANCE_AGLSOLVER)))
9688 then
9689 'double* algloop<%ls.index%>Vars = _algLoopLinearSolver<%ls.index%>->getVariableWorkArray();
9690 bool* conditions0<%ls.index%> = _algLoopLinearSolver<%ls.index%>->getConditionsWorkArray();
9691 bool* conditions1<%ls.index%> = _algLoopLinearSolver<%ls.index%>->getConditions2WorkArray();'
9692 else
9693 'double* algloop<%ls.index%>Vars = _algLoopLinearSolver->getVariableWorkArray();
9694 bool* conditions0<%ls.index%> = _algLoopLinearSolver->getConditionsWorkArray();
9695 bool* conditions1<%ls.index%> = _algLoopLinearSolver->getConditions2WorkArray();'
9696 %>
9697
9698
9699
9700 _algLoop<%ls.index%>->getReal(algloop<%ls.index%>Vars);
9701 bool restatDiscrete<%ls.index%> = false;
9702 try
9703 {
9704 _algLoop<%ls.index%>->evaluate();
9705 if( _callType == IContinuous::DISCRETE )
9706 {
9707 while(restart<%ls.index%> && !(iterations<%ls.index%>++>500))
9708 {
9709 getConditions(conditions0<%ls.index%>);
9710 _callType = IContinuous::CONTINUOUS;
9711
9712 <%if boolOr(Flags.isSet(HPCOM),boolNot(getConfigBool(SINGLE_INSTANCE_AGLSOLVER)))
9713 then '_algLoopLinearSolver<%ls.index%>->solve();'
9714 else
9715 '_algLoopLinearSolver->solve(_algLoop<%ls.index%>,(iterations<%ls.index%>==1));'
9716 %>
9717 _callType = IContinuous::DISCRETE;
9718 for(int i=0;i<_dimZeroFunc;i++)
9719 {
9720 getCondition(i);
9721 }
9722 getConditions(conditions1<%ls.index%>);
9723 restart<%ls.index%> = !std::equal (conditions1<%ls.index%>, conditions1<%ls.index%>+_dimZeroFunc,conditions0<%ls.index%>);
9724 }
9725 }
9726 else
9727 <%if boolOr(Flags.isSet(HPCOM),boolNot(getConfigBool(SINGLE_INSTANCE_AGLSOLVER)))
9728 then '_algLoopLinearSolver<%ls.index%>->solve();'
9729 else
9730 '_algLoopLinearSolver->solve(_algLoop<%ls.index%>,true);'
9731 %>
9732 }
9733 catch(ModelicaSimulationError &ex)
9734 {
9735 restatDiscrete<%ls.index%>=true;
9736 }
9737
9738 if((restart<%ls.index%>&& iterations<%ls.index%> > 0)|| restatDiscrete<%ls.index%>)
9739 {
9740 try
9741 { //workaround: try to solve algoop discrete (evaluate all zero crossing conditions) since we do not have the information which zercrossing contains a algloop var
9742 IContinuous::UPDATETYPE calltype = _callType;
9743 _callType = IContinuous::DISCRETE;
9744 _algLoop<%ls.index%>->setReal(algloop<%ls.index%>Vars );
9745 <%if boolOr(Flags.isSet(HPCOM),boolNot(getConfigBool(SINGLE_INSTANCE_AGLSOLVER)))
9746 then '_algLoopLinearSolver<%ls.index%>->solve();'
9747 else
9748 '_algLoopLinearSolver->solve(_algLoop<%ls.index%>);'
9749 %>
9750 _callType = calltype;
9751 }
9752 catch (ModelicaSimulationError& ex)
9753 {
9754 string error = add_error_info("Linear solver <%ls.index%>", ex.what(), ex.getErrorID(), _simTime);
9755 throw ModelicaSimulationError(ALGLOOP_EQ_SYSTEM,error);
9756 }
9757 }
9758 >>
9759 end match
9760
9761 case e as SES_NONLINEAR(nlSystem = nls as NONLINEARSYSTEM(__))
9762 then
9763 let i = nls.index
9764 match context
9765 case ALGLOOP_CONTEXT(genInitialisation=true)
9766 then
9767 <<
9768 try
9769 {
9770
9771 _algLoop<%nls.index%>->evaluate();
9772 for(int i=0; i<_dimZeroFunc; i++)
9773 {
9774 getCondition(i);
9775 }
9776 IContinuous::UPDATETYPE calltype = _callType;
9777 _callType = IContinuous::CONTINUOUS;
9778
9779 <%if boolOr(Flags.isSet(HPCOM),boolNot(getConfigBool(SINGLE_INSTANCE_AGLSOLVER)))
9780 then '_algLoopNonLinearSolver<%nls.index%>->solve();'
9781 else
9782 '_algLoopNonLinearSolver->solve(_algLoop<%nls.index%>,true);'
9783 %>
9784
9785 _callType = calltype;
9786 }
9787 catch(ModelicaSimulationError& ex)
9788 {
9789 string error = add_error_info("Nonlinear solver <%nls.index%>", ex.what(), ex.getErrorID(), _simTime);
9790 throw ModelicaSimulationError(ALGLOOP_EQ_SYSTEM,error);
9791 }
9792 >>
9793 else
9794 <<
9795 bool restart<%nls.index%> = true;
9796
9797 unsigned int iterations<%nls.index%> = 0;
9798 <%if boolOr(Flags.isSet(HPCOM),boolNot(getConfigBool(SINGLE_INSTANCE_AGLSOLVER)))
9799 then
9800 'double* algloop<%nls.index%>Vars = _algLoopLinearSolver<%nls.index%>->getVariableWorkArray();
9801 bool* conditions0<%nls.index%> = _algLoopLinearSolver<%nls.index%>->getConditionsWorkArray();
9802 bool* conditions1<%nls.index%> = _algLoopLinearSolver<%nls.index%>->getConditions2WorkArray();'
9803 else
9804 'double* algloop<%nls.index%>Vars = _algLoopLinearSolver->getVariableWorkArray();
9805 bool* conditions0<%nls.index%> = _algLoopLinearSolver->getConditionsWorkArray();
9806 bool* conditions1<%nls.index%> = _algLoopLinearSolver->getConditions2WorkArray();'
9807 %>
9808 _algLoop<%nls.index%>->getReal(algloop<%nls.index%>Vars);
9809 bool restatDiscrete<%nls.index%> = false;
9810 try
9811 {
9812 _algLoop<%nls.index%>->evaluate();
9813 if( _callType == IContinuous::DISCRETE )
9814 {
9815 while(restart<%nls.index%> && !(iterations<%nls.index%>++>500))
9816 {
9817 getConditions(conditions0<%nls.index%>);
9818 _callType = IContinuous::CONTINUOUS;
9819
9820 <%if boolOr(Flags.isSet(HPCOM),boolNot(getConfigBool(SINGLE_INSTANCE_AGLSOLVER)))
9821 then '_algLoopNonLinearSolver<%nls.index%>->solve();'
9822 else
9823 '_algLoopNonLinearSolver->solve(_algLoop<%nls.index%>,(iterations<%nls.index%>==1));'
9824 %>
9825
9826 _callType = IContinuous::DISCRETE;
9827 for(int i=0;i<_dimZeroFunc;i++)
9828 {
9829 getCondition(i);
9830 }
9831 getConditions(conditions1<%nls.index%>);
9832 restart<%nls.index%> = !std::equal (_conditions1<%nls.index%>, _conditions1<%nls.index%>+_dimZeroFunc,_conditions0<%nls.index%>);
9833 }
9834 }
9835 else
9836 <%if boolOr(Flags.isSet(HPCOM),boolNot(getConfigBool(SINGLE_INSTANCE_AGLSOLVER)))
9837 then '_algLoopNonLinearSolver<%nls.index%>->solve();'
9838 else
9839 '_algLoopNonLinearSolver->solve(_algLoop<%nls.index%>,true);'
9840 %>
9841 }
9842 catch(ModelicaSimulationError &ex)
9843 {
9844 restatDiscrete<%nls.index%>=true;
9845 }
9846
9847 if((restart<%nls.index%>&& iterations<%nls.index%> > 0)|| restatDiscrete<%nls.index%>)
9848 {
9849 try
9850 { //workaround: try to solve algoop discrete (evaluate all zero crossing conditions) since we do not have the information which zercrossing contains a algloop var
9851 IContinuous::UPDATETYPE calltype = _callType;
9852 _callType = IContinuous::DISCRETE;
9853 _algLoop<%nls.index%>->setReal(algloop<%nls.index%>Vars );
9854 <%if boolOr(Flags.isSet(HPCOM),boolNot(getConfigBool(SINGLE_INSTANCE_AGLSOLVER)))
9855 then '_algLoopNonLinearSolver<%nls.index%>->solve();'
9856 else
9857 '_algLoopNonLinearSolver->solve(_algLoop<%nls.index%>);'
9858 %>
9859 _callType = calltype;
9860 }
9861 catch(ModelicaSimulationError& ex)
9862 {
9863 string error = add_error_info("Nonlinear solver <%nls.index%>", ex.what(), ex.getErrorID(), _simTime);
9864 throw ModelicaSimulationError(ALGLOOP_EQ_SYSTEM,error);
9865 }
9866 }
9867 >>
9868 end match
9869 case e as SES_MIXED(__)
9870 /*<%equationMixed(e, context, &varDecls, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)%>*/
9871 then
9872 <<
9873 throw ModelicaSimulationError(ALGLOOP_EQ_SYSTEM,"Mixed systems are not supported yet");
9874 >>
9875 case e as SES_FOR_LOOP(__)
9876 then
9877 <<
9878 FOR LOOPS ARE NOT IMPLEMENTED
9879 >>
9880 case e as SES_IFEQUATION(__)
9881 then
9882 <<
9883 IF EQUATIONS ARE NOT IMPLEMENTED
9884 >>
9885 else
9886 CodegenCppCommon.error(sourceInfo(), 'NOT IMPLEMENTED EQUATION 2: <%dumpEqs(fill(eq,1))%>')
9887 end equationString;
9888
9889 14191 template equation_function_call(SimEqSystem eq, Context context, SimCode simCode, Text method)
9890 "Generates an equation.
9891 This template should not be used for a SES_RESIDUAL.
9892 Residual equations are handled differently."
9893 ::=
9894 let ix_str = equationIndex(eq)
9895 <<
9896 <%method%>_<%ix_str%>();
9897 >>
9898 end equation_function_call;
9899
9900 10785 template equation_function_create_single_func(SimEqSystem eq, Context context, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace,
9901 Text method,Text classnameext, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation, Boolean createMeasureTime,
9902 Boolean assignToStartValues, Boolean overwriteOldStartValue, String defaultVarDeclsLocal)
9903 ::=
9904 let ix_str = equationIndex(eq)
9905 let ix_str_array = intSub(stringInt(ix_str),1) //equation index - 1
9906 let &varDeclsLocal = buffer defaultVarDeclsLocal /*BUFD*/
9907 let &additionalFuncs = buffer "" /*BUFD*/
9908 let &measureTimeStartVar = buffer "" /*BUFD*/
9909 let &measureTimeEndVar = buffer "" /*BUFD*/
9910
9911 let body = equation_function_create_single_body(eq, context, simCode, extraFuncs, extraFuncsDecl, extraFuncsNamespace,
9912 additionalFuncs, method, classnameext, stateDerVectorName /*=__zDot*/, useFlatArrayNotation,
9913 createMeasureTime, assignToStartValues, overwriteOldStartValue, varDeclsLocal)
9914 let &measureTimeStartVar += if createMeasureTime then generateMeasureTimeStartCode("measuredProfileBlockStartValues", 'evaluate<%ix_str%>', "MEASURETIME_PROFILEBLOCKS") else ""
9915 let &measureTimeEndVar += if createMeasureTime then generateMeasureTimeEndCode("measuredProfileBlockStartValues", "measuredProfileBlockEndValues", '(*measureTimeProfileBlocksArray)[<%ix_str_array%>]', 'evaluate<%ix_str%>', "MEASURETIME_PROFILEBLOCKS") else ""
9916 <<
9917 <%additionalFuncs%>
9918 /*
9919 <%match simCode case SIMCODE(fmuTargetName="") then dumpEqs(fill(eq,1))%>
9920 */
9921 void <%lastIdentOfPathFromSimCode(simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)%><%classnameext%>::<%method%>_<%ix_str%>()
9922 {
9923 <%varDeclsLocal%>
9924 <%if(createMeasureTime) then measureTimeStartVar%>
9925 <%body%>
9926 <%if(createMeasureTime) then measureTimeEndVar%>
9927 }
9928 >>
9929 end equation_function_create_single_func;
9930
9931 9389 template equation_function_create_single_body(SimEqSystem eq, Context context, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace,
9932 Text& additionalFuncs, Text method, Text classnameext, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation,
9933 Boolean createMeasureTime, Boolean assignToStartValues, Boolean overwriteOldStartValue, Text &varDeclsLocal)
9934 ::=
9935 match eq
9936 case e as SES_SIMPLE_ASSIGN(__)
9937 then
9938 equationSimpleAssign(e, context, &varDeclsLocal, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation, assignToStartValues, overwriteOldStartValue)
9939 case e as SES_IFEQUATION(__)
9940 then
9941 equationIfEquation(e, context, &varDeclsLocal, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
9942 case e as SES_ALGORITHM(__)
9943 case e as SES_INVERSE_ALGORITHM(__)
9944 then
9945 equationAlgorithm(e, context, &varDeclsLocal,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
9946 case e as SES_WHEN(__)
9947 then
9948 equationWhen(e, context, &varDeclsLocal, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
9949 case e as SES_ARRAY_CALL_ASSIGN(__)
9950 then
9951 equationArrayCallAssign(e, context, &varDeclsLocal, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation, assignToStartValues)
9952 case e as SES_RESIZABLE_ASSIGN(__)
9953 then
9954 equationResizableAssign(e, context, &varDeclsLocal, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
9955 case e as SES_LINEAR(__)
9956 case e as SES_NONLINEAR(__)
9957 then
9958 equationLinearOrNonLinear(e, context, &varDeclsLocal,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName)
9959 case e as SES_MIXED(__)
9960 then
9961 /*<%equationMixed(e, context, &varDeclsLocal, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)%>*/
9962 let &additionalFuncs += equation_function_create_single_func(e.cont, context, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, method, classnameext, stateDerVectorName, useFlatArrayNotation, createMeasureTime, assignToStartValues, overwriteOldStartValue, "")
9963 "throw ModelicaSimulationError(MODEL_ARRAY_FUNCTION,\"Mixed systems are not supported yet\");"
9964 case e as SES_FOR_LOOP(__)
9965 then
9966 equationForLoop(e, context, &varDeclsLocal,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation, assignToStartValues)
9967 case e as SES_FOR_EQUATION(__)
9968 then
9969 equationForEquation(e, context, &varDeclsLocal, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace,
9970 additionalFuncs, method, classnameext, stateDerVectorName, useFlatArrayNotation,
9971 createMeasureTime, assignToStartValues, overwriteOldStartValue, varDeclsLocal)
9972 case e as SES_ALIAS(__)
9973 then
9974 /* should call alias; duplicate equation code for now
9975 <<
9976 initEquation_<%aliasOf%>();
9977 >>
9978 */
9979 // get equation from initialization system
9980 match simCode
9981 case SIMCODE(__) then
9982 equation_function_create_single_body(getSimEqSysForIndex(e.aliasOf, initialEquations), context, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace,
9983 &additionalFuncs, method, classnameext, stateDerVectorName /*=__zDot*/, useFlatArrayNotation,
9984 createMeasureTime, assignToStartValues, overwriteOldStartValue, &varDeclsLocal)
9985 end match
9986 else
9987 CodegenCppCommon.error(sourceInfo(), 'NOT IMPLEMENTED EQUATION: <%dumpEqs(fill(eq,1))%>')
9988 end match
9989 end equation_function_create_single_body;
9990
9991 ✗ template equationMixed(SimEqSystem eq, Context context, Text &varDecls, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl,
9992 Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
9993 "Generates a mixed equation system."
9994 ::=
9995 match eq
9996 case SES_MIXED(__) then
9997 let contEqs = equation_(cont, context, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
9998 let numDiscVarsStr = listLength(discVars)
9999 // let valuesLenStr = listLength(values)
10000 let &preDisc = buffer "" /*BUFD*/
10001 let num = index
10002 let discvars2 = (discEqs |> SES_SIMPLE_ASSIGN(__) hasindex i0 =>
10003 let expPart = daeExp(exp, context, &preDisc, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
10004 <<
10005 <%cref(cref, useFlatArrayNotation)%> = <%expPart%>;
10006 new_disc_vars<%num%>[<%i0%>] = <%cref(cref, useFlatArrayNotation)%>;
10007 >>
10008 ;separator="\n")
10009 <<
10010 <% /*
10011 bool values<%num%>[<%valuesLenStr%>] = {<%values ;separator=", "%>};
10012 bool pre_disc_vars<%num%>[<%numDiscVarsStr%>];
10013 bool new_disc_vars<%num%>[<%numDiscVarsStr%>];
10014 bool restart<%num%> = true;
10015 int iter<%num%>=0;
10016 int max_iter<%num%> = (<%valuesLenStr%> / <%numDiscVarsStr%>)+1;
10017 while(restart<%num%> && !(iter<%num%> > max_iter<%num%>))
10018 {
10019 <%discVars |> SIMVAR(__) hasindex i0 => 'pre_disc_vars<%num%>[<%i0%>] = <%cref(name, useFlatArrayNotation)%>;' ;separator="\n"%>
10020 <%contEqs%>
10021
10022 <%preDisc%>
10023 <%discvars2%>
10024 bool* cur_disc_vars<%num%>[<%numDiscVarsStr%>]= {<%discVars |> SIMVAR(__) => '&<%cref(name, useFlatArrayNotation)%>' ;separator=", "%>};
10025 restart<%num%>=!(_event_handling->CheckDiscreteValues(values<%num%>,pre_disc_vars<%num%>,new_disc_vars<%num%>,cur_disc_vars<%num%>,<%numDiscVarsStr%>,iter<%num%>,<%valuesLenStr%>));
10026 iter<%num%>++;
10027 }
10028 if(iter<%num%>>max_iter<%num%> && (restart<%num%> == true) )
10029 {
10030 //throw std::runtime_error("Number of iteration steps exceeded for discrete varibales check . ");
10031 cout << "Number of iteration steps exceeded for discrete varibales check at time " << time << std::endl;
10032 }
10033 */ %>
10034 >>
10035 end equationMixed;
10036
10037 49 template generateStepCompleted(list<SimEqSystem> allEquations,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
10038 ::=
10039 let &varDecls = buffer "" /*BUFD*/
10040 let save_algloop_start_values = generateStepCompleted2(allEquations,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)
10041 match simCode
10042 case SIMCODE(modelInfo = MODELINFO(__))
10043 then
10044 let store_delay_expr = functionStoreDelay(delayedExps, simCode ,&extraFuncs ,&extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
10045
10046 let outputBounds = match simCode
10047 case simCode as SIMCODE(__) then
10048 match modelInfo
10049 case MODELINFO(varInfo=VARINFO(__), vars=SIMVARS(__)) then
10050 let &varOptDecls = buffer "" /*BUFD*/
10051 let &optpreExp = buffer "" /*BUFD*/
10052
10053 let outputnames = vars.outputVars |> SIMVAR(__) hasindex i0 =>
10054 'dynamic_cast<SimDouble*>( _simObjects->getSimData(_modelName)->Get("<%cref(name, useFlatArrayNotation)%>"))->getValue() = <%cref(name, useFlatArrayNotation)%>;';separator="\n"
10055 <<
10056 #if defined(__TRICORE__) || defined(__vxworks)
10057 <%outputnames%>
10058 #endif
10059 >>
10060
10061 <<
10062 bool <%lastIdentOfPath(modelInfo.name)%>::stepCompleted(double time)
10063 {
10064
10065 <%store_delay_expr%>
10066 <%save_algloop_start_values%>
10067 <%outputBounds%>
10068
10069 saveAll();
10070 return _terminate;
10071 }
10072 >>
10073
10074 end generateStepCompleted;
10075
10076
10077
10078 49 template generateRestoreOldValues(list<SimEqSystem> allEquations,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
10079 ::=
10080 let &varDecls = buffer "" /*BUFD*/
10081 let algloopsolver = generateRestoreOldValues2(allEquations,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)
10082 match simCode
10083 case SIMCODE(modelInfo = MODELINFO(__))
10084 then
10085 <<
10086 void <%lastIdentOfPath(modelInfo.name)%>::restoreOldValues()
10087 {
10088
10089 }
10090 >>
10091
10092 end generateRestoreOldValues;
10093
10094
10095 98 template generateRestoreOldValues2(list<SimEqSystem> allEquations,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
10096 ::=
10097 let &varDecls = buffer "" /*BUFD*/
10098 let algloopsolver = (allEquations |> eqs => (eqs |> eq =>
10099 generateRestoreOldValues3(eq, contextOther, &varDecls /*BUFC*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace) ;separator="\n")
10100 ;separator="\n")
10101
10102 <<
10103 <%algloopsolver%>
10104 >>
10105
10106 end generateRestoreOldValues2;
10107
10108
10109 136 template generateRestoreOldValues3(SimEqSystem eq, Context context, Text &varDecls, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
10110 "Generates an equation.
10111 This template should not be used for a SES_RESIDUAL.
10112 Residual equations are handled differently."
10113 ::=
10114 match eq
10115 case SES_LINEAR(lSystem = ls as LINEARSYSTEM(__))
10116 then
10117 let num = ls.index
10118 match simCode
10119 case SIMCODE(modelInfo = MODELINFO(__)) then
10120 <<
10121 _algLoopSolver<%num%>->restoreOldValues();
10122 >>
10123 end match
10124 case e as SES_NONLINEAR(nlSystem = nls as NONLINEARSYSTEM(__))
10125 then
10126 let num = nls.index
10127 match simCode
10128 case SIMCODE(modelInfo = MODELINFO(__)) then
10129 <<
10130 _algLoopSolver<%num%>->restoreOldValues();
10131 >>
10132 end match
10133 case e as SES_MIXED(cont = eq_sys)
10134 then
10135 <<
10136 <%generateRestoreOldValues3(eq_sys,context,varDecls,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)%>
10137 >>
10138 else
10139 ""
10140 end generateRestoreOldValues3;
10141
10142
10143 49 template generateRestoreNewValues(list<SimEqSystem> allEquations,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
10144 ::=
10145 let &varDecls = buffer "" /*BUFD*/
10146 let algloopsolver = generateRestoreOldValues2(allEquations,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)
10147 match simCode
10148 case SIMCODE(modelInfo = MODELINFO(__))
10149 then
10150 <<
10151 void <%lastIdentOfPath(modelInfo.name)%>::restoreNewValues()
10152 {
10153
10154 }
10155 >>
10156
10157 end generateRestoreNewValues;
10158
10159
10160
10161
10162 ✗ template generateRestoreNewValues3(SimEqSystem eq, Context context, Text &varDecls, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
10163 "Generates an equation.
10164 This template should not be used for a SES_RESIDUAL.
10165 Residual equations are handled differently."
10166 ::=
10167 match eq
10168 case SES_LINEAR(lSystem = ls as LINEARSYSTEM(__))
10169 then
10170 let num = ls.index
10171 match simCode
10172 case SIMCODE(modelInfo = MODELINFO(__)) then
10173 <<
10174 _algLoopSolver<%num%>->restoreNewValues();
10175 >>
10176 end match
10177 case e as SES_NONLINEAR(nlSystem = nls as NONLINEARSYSTEM(__))
10178 then
10179 let num = nls.index
10180 match simCode
10181 case SIMCODE(modelInfo = MODELINFO(__)) then
10182 <<
10183 _algLoopSolver<%num%>->restoreNewValues();
10184 >>
10185 end match
10186 case e as SES_MIXED(cont = eq_sys)
10187 then
10188 <<
10189 <%generateRestoreNewValues3(eq_sys,context,varDecls,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)%>
10190 >>
10191 else
10192 ""
10193 end generateRestoreNewValues3;
10194
10195
10196
10197 49 template generateStepStarted(list<SimEqSystem> allEquations,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Boolean useFlatArrayNotation)
10198 ::=
10199 let &varDecls = buffer "" /*BUFD*/
10200 match simCode
10201 case SIMCODE(modelInfo = MODELINFO(__))
10202 then
10203 let inputBounds = match simCode
10204 case simCode as SIMCODE(__) then
10205 match modelInfo
10206 case MODELINFO(varInfo=VARINFO(__), vars=SIMVARS(__)) then
10207 let &varOptDecls = buffer "" /*BUFD*/
10208 let &optpreExp = buffer "" /*BUFD*/
10209
10210 let inputnames = vars.inputVars |> SIMVAR(__) hasindex i0 =>
10211 '<%cref(name, useFlatArrayNotation)%> = dynamic_cast<SimDouble*>(_simObjects->getSimData(_modelName)->Get("<%cref(name, useFlatArrayNotation)%>"))->getValue();';separator="\n"
10212 <<
10213 #if defined(__TRICORE__) || defined(__vxworks)
10214 <%inputnames%>
10215 #endif
10216 >>
10217
10218 <<
10219 bool <%lastIdentOfPath(modelInfo.name)%>::stepStarted(double time)
10220 {
10221 <%inputBounds%>
10222
10223 return true;
10224 }
10225 >>
10226
10227 end generateStepStarted;
10228
10229 49 template generateDimTimeEvent(list<SimEqSystem> allEquations,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
10230 ::=
10231 match simCode
10232 case SIMCODE(modelInfo = MODELINFO(__))
10233 then
10234 <<
10235 int <%lastIdentOfPath(modelInfo.name)%>::getDimTimeEvent() const
10236 {
10237 return _dimTimeEvent;
10238 }
10239 >>
10240
10241 end generateDimTimeEvent;
10242
10243 49 template generateGetTimeEvenData(list<SimEqSystem> allEquations,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
10244 ::=
10245 match simCode
10246 case SIMCODE(modelInfo = MODELINFO(__))
10247 then
10248 <<
10249 std::pair<double,double>* <%lastIdentOfPath(modelInfo.name)%>::getTimeEventData() const
10250 {
10251 return _timeEventData;
10252 }
10253 >>
10254
10255 end generateGetTimeEvenData;
10256
10257 49 template generateTimeEvent(list<BackendDAE.TimeEvent> timeEvents, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
10258 ::=
10259 match simCode
10260 case SIMCODE(modelInfo = MODELINFO(__))
10261 then
10262 let &varDecls = buffer "" /*BUFD*/
10263 <<
10264 void <%lastIdentOfPath(modelInfo.name)%>::initTimeEventData()
10265 {
10266 <%(timeEvents |> timeEvent hasindex i1 =>
10267 match timeEvent
10268 case SAMPLE_TIME_EVENT(__) then
10269 let &preExp = buffer "" /*BUFD*/
10270 let e1 = daeExp(startExp, contextOther, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
10271 let e2 = daeExp(intervalExp, contextOther, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
10272 <<
10273 <%preExp%>
10274 _timeEventData[<%i1%>] = std::make_pair(<%e1%>, <%e2%>);
10275 >>
10276 else ''
10277 ;separator="\n\n")%>
10278 // simplified treatment of clocks in model as time events
10279 for (int i = 0; i < _dimClock; i++)
10280 {
10281 _timeEventData[_dimTimeEvent-_dimClock+i] = std::make_pair(_clockShift[i] * _clockInterval[i], _clockInterval[i]);
10282 }
10283 }
10284 >>
10285 end generateTimeEvent;
10286
10287
10288 49 template generateStepCompleted2(list<SimEqSystem> allEquations,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
10289 ::=
10290 let &varDecls = buffer "" /*BUFD*/
10291 let save_algloop_start_values = (allEquations |> eqs => (eqs |> eq =>
10292 generateStepCompleted3(eq, contextOther, &varDecls /*BUFC*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace) ;separator="\n")
10293 ;separator="\n")
10294
10295 <<
10296 <%save_algloop_start_values%>
10297 >>
10298
10299 end generateStepCompleted2;
10300
10301
10302 68 template generateStepCompleted3(SimEqSystem eq, Context context, Text &varDecls, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
10303 "Generates an equation.
10304 This template should not be used for a SES_RESIDUAL.
10305 Residual equations are handled differently."
10306 ::=
10307 match eq
10308 case SES_LINEAR(lSystem = ls as LINEARSYSTEM(__))
10309 then
10310 let num = ls.index
10311 match simCode
10312 case SIMCODE(modelInfo = MODELINFO(__)) then
10313 <<
10314 _algLoop<%num%>->setRealStartValues();
10315 >>
10316 end match
10317 case e as SES_NONLINEAR(nlSystem = nls as NONLINEARSYSTEM(__))
10318 then
10319 let num = nls.index
10320 match simCode
10321 case SIMCODE(modelInfo = MODELINFO(__)) then
10322 <<
10323 _algLoop<%num%>->setRealStartValues();
10324 >>
10325 end match
10326 case e as SES_MIXED(cont = eq_sys)
10327 then
10328 <<
10329 <%generateStepCompleted3(eq_sys,context,varDecls,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)%>
10330 >>
10331 else
10332 ""
10333 end generateStepCompleted3;
10334
10335
10336
10337 147 template generateAlgloopSolvers(ModelInfo modelInfo,list<SimEqSystem> allEquationsPlusWhen,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
10338 ::=
10339 match (boolOr(Flags.isSet(HPCOM),boolNot(getConfigBool(SINGLE_INSTANCE_AGLSOLVER))))
10340 case true then
10341 let &varDecls = buffer "" /*BUFD*/
10342 let algloopsolver = (allEquationsPlusWhen |> eqs => (eqs |> eq =>
10343 generateAlgloopSolvers2(eq, contextOther, &varDecls /*BUFC*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace);separator="\n")
10344 ;separator="\n")
10345 <<
10346
10347 <%algloopsolver%>
10348 >>
10349
10350 case false then
10351 match modelInfo
10352 case MODELINFO(linearSystems=ls,nonLinearSystems=nls)
10353 then
10354 let linearSolver = match(listLength(ls))
10355 case 0
10356 then ""
10357 else "_algLoopLinearSolver= shared_ptr<ILinearAlgLoopSolver>(_algLoopSolverFactory->createLinearAlgLoopSolver());"
10358 end match
10359 let nonlinearSolver = match(listLength(nls))
10360 case 0
10361 then ""
10362 else "_algLoopNonLinearSolver= shared_ptr<INonLinearAlgLoopSolver>(_algLoopSolverFactory->createNonLinearAlgLoopSolver());"
10363 end match
10364 <<
10365 <%linearSolver%>
10366 <%nonlinearSolver%>
10367 >>
10368 end match
10369 end generateAlgloopSolvers;
10370
10371
10372
10373 7054 template generateAlgloopSolvers2(SimEqSystem eq, Context context, Text &varDecls, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
10374 "Generates algloopsolver variables for parallel code e.g for hpcom code generation"
10375 ::=
10376 match eq
10377 case SES_LINEAR(lSystem = ls as LINEARSYSTEM(__))
10378 then
10379 let num = ls.index
10380 match simCode
10381 case SIMCODE(modelInfo = MODELINFO(__)) then
10382 <<
10383 _algLoopLinearSolver<%num%>= shared_ptr<ILinearAlgLoopSolver>(_algLoopSolverFactory->createLinearAlgLoopSolver( _algLoop<%num%>));
10384 >>
10385 end match
10386 case e as SES_NONLINEAR(nlSystem = nls as NONLINEARSYSTEM(__))
10387 then
10388 let num = nls.index
10389 match simCode
10390 case SIMCODE(modelInfo = MODELINFO(__)) then
10391 <<
10392 _algLoopNonLinearSolver<%num%>= shared_ptr<INonLinearAlgLoopSolver>(_algLoopSolverFactory->createNonLinearAlgLoopSolver( _algLoop<%num%>));
10393
10394 >>
10395 end match
10396 else
10397 ""
10398 end generateAlgloopSolvers2;
10399
10400 147 template generateAlgloopSystems(list<SimEqSystem> allEquations,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
10401 ::=
10402 let &varDecls = buffer "" /*BUFD*/
10403 let algloopsolver = (allEquations |> eqs => (eqs |> eq =>
10404 generateAlgloopSystems2(eq, contextOther, &varDecls /*BUFC*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace) ;separator="\n")
10405 ;separator="\n")
10406
10407 <<
10408 <%algloopsolver%>
10409 >>
10410
10411 end generateAlgloopSystems;
10412
10413
10414 147 template generatefriendAlgloops(list<SimEqSystem> allEquations, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
10415 ::=
10416 let friendalgloops = (allEquations |> eqs => (eqs |> eq =>
10417 generatefriendAlgloops2(eq, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace) ;separator="\n")
10418 ;separator="\n")
10419 <<
10420 <%friendalgloops%>
10421 >>
10422 end generatefriendAlgloops;
10423
10424
10425 69 template generatefriendAlgloops2(SimEqSystem eq, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
10426 ::=
10427 match eq
10428 case SES_LINEAR(lSystem = ls as LINEARSYSTEM(__))
10429 then
10430 let num = ls.index
10431 match simCode
10432 case SIMCODE(modelInfo = MODELINFO(__)) then
10433 <<
10434 friend class <%lastIdentOfPath(modelInfo.name)%>Algloop<%num%>;
10435 >>
10436 end match
10437 case e as SES_NONLINEAR(nlSystem = nls as NONLINEARSYSTEM(__))
10438 then
10439 let num = nls.index
10440 match simCode
10441 case SIMCODE(modelInfo = MODELINFO(__)) then
10442 <<
10443 friend class <%lastIdentOfPath(modelInfo.name)%>Algloop<%num%>;
10444 >>
10445 end match
10446 case e as SES_MIXED(cont = eq_sys)
10447 then
10448 <<
10449 <%generatefriendAlgloops2(eq_sys,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)%>
10450 >>
10451 else
10452 ""
10453 end generatefriendAlgloops2;
10454
10455
10456
10457 69 template generateAlgloopSystems2(SimEqSystem eq, Context context, Text &varDecls, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
10458 "Generates an equation.
10459 This template should not be used for a SES_RESIDUAL.
10460 Residual equations are handled differently."
10461 ::=
10462 match eq
10463 case SES_LINEAR(lSystem = ls as LINEARSYSTEM(__))
10464 then
10465 let num = ls.index
10466 match simCode
10467 case SIMCODE(modelInfo = MODELINFO(__)) then
10468 <<
10469 _algLoop<%num%> = shared_ptr<ILinearAlgLoop>(new <%lastIdentOfPath(modelInfo.name)%>Algloop<%num%>(this,__z,__zDot,_conditions,_discrete_events));
10470 >>
10471 end match
10472 case e as SES_NONLINEAR(nlSystem = nls as NONLINEARSYSTEM(__))
10473 then
10474 let num = nls.index
10475 match simCode
10476 case SIMCODE(modelInfo = MODELINFO(__)) then
10477 <<
10478 _algLoop<%num%> = shared_ptr<INonLinearAlgLoop>(new <%lastIdentOfPath(modelInfo.name)%>Algloop<%num%>(this,__z,__zDot,_conditions,_discrete_events));
10479 >>
10480 end match
10481 case e as SES_MIXED(cont = eq_sys)
10482 then
10483 <<
10484 <%generateAlgloopSystems2(eq_sys,context,varDecls,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)%>
10485 >>
10486 else
10487 ""
10488 end generateAlgloopSystems2;
10489 /*
10490 let jacAlgloopsolver = (jacobianMatrices |> (mat, _, _, _, _, _, _) hasindex index0 =>
10491 (mat |> (eqs,_,_) => generateAlgloopsSystemVariables(eqs,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace) ;separator="\n")
10492 ;separator="")
10493 */
10494
10495
10496 49 template generateAlgloopsolverVariables( ModelInfo modelInfo,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
10497 ::=
10498 match (boolOr(Flags.isSet(HPCOM),boolNot(getConfigBool(SINGLE_INSTANCE_AGLSOLVER))))
10499 case true then
10500 generateAlgloopsolverVariables2(simCode , extraFuncs, extraFuncsDecl, extraFuncsNamespace)
10501 case false then
10502 match modelInfo
10503 case MODELINFO(linearSystems=ls,nonLinearSystems=nls)
10504 then
10505 let linearSolver = match(listLength(ls))
10506 case 0
10507 then ""
10508 else "shared_ptr<ILinearAlgLoopSolver> _algLoopLinearSolver; ///< Solver for linear algebraic loop */"
10509 end match
10510 let nonlinearSolver = match(listLength(nls))
10511 case 0
10512 then ""
10513 else "shared_ptr<INonLinearAlgLoopSolver> _algLoopNonLinearSolver; ///< Solver for nonlinear algebraic loop */"
10514 end match
10515 <<
10516 <%linearSolver%>
10517 <%nonlinearSolver%>
10518 >>
10519 end match
10520
10521 end generateAlgloopsolverVariables;
10522
10523 49 template generateAlgloopsolverVariables2( SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
10524 ::=
10525 match simCode
10526 case SIMCODE(__) then
10527 let algloopsolvers = generateAlgloopsolverVariables3(modelInfo,listAppend(listAppend(allEquations, initialEquations), getClockedEquations(getSubPartitions(clockedPartitions))), simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace)
10528 let jacalgloopsolver = (jacobianMatrices |> JAC_MATRIX(columns=mat) hasindex index0 =>
10529 (mat |> JAC_COLUMN(columnEqns=eqs) => generateAlgloopsolverVariables3(modelInfo,eqs,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace) ;separator="\n")
10530 ;separator="")
10531 <<
10532
10533 <%algloopsolvers%>
10534 <%jacalgloopsolver%>
10535
10536
10537 >>
10538 end generateAlgloopsolverVariables2;
10539
10540 147 template generateAlgloopsolverVariables3(ModelInfo modelInfo,list<SimEqSystem> allEquationsPlusWhen,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
10541 ::=
10542 match (boolOr(Flags.isSet(HPCOM),boolNot(getConfigBool(SINGLE_INSTANCE_AGLSOLVER))))
10543 case true then
10544 let &varDecls = buffer "" /*BUFD*/
10545 let algloopsolver = (allEquationsPlusWhen |> eqs => (eqs |> eq =>
10546 generateAlgloopsolverVariables4(eq, contextOther, &varDecls /*BUFC*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace);separator="\n")
10547 ;separator="\n")
10548 <<
10549
10550 <%algloopsolver%>
10551 >>
10552 case false then
10553 match modelInfo
10554 case MODELINFO(linearSystems=ls,nonLinearSystems=nls)
10555 then
10556 let linearSolver = match(listLength(ls))
10557 case 0
10558 then ""
10559 else "shared_ptr<ILinearAlgLoopSolver> _algLoopLinearSolver; ///< Solver for linear algebraic loop */"
10560 end match
10561 let nonlinearSolver = match(listLength(nls))
10562 case 0
10563 then ""
10564 else "shared_ptr<INonLinearAlgLoopSolver> _algLoopNonLinearSolver; ///< Solver for nonlinear algebraic loop */"
10565 end match
10566 <<
10567 <%linearSolver%>
10568 <%nonlinearSolver%>
10569 >>
10570 end match
10571
10572 end generateAlgloopsolverVariables3;
10573
10574 7054 template generateAlgloopsolverVariables4(SimEqSystem eq, Context context, Text &varDecls, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
10575 "Generates algloopsolver variables for parallel code e.g for hpcom code generation"
10576 ::=
10577 match eq
10578 case SES_LINEAR(lSystem = ls as LINEARSYSTEM(__))
10579 then
10580 let num = ls.index
10581 match simCode
10582 case SIMCODE(modelInfo = MODELINFO(__)) then
10583 <<
10584 shared_ptr<ILinearAlgLoopSolver>
10585 _algLoopLinearSolver<%num%>; ///< Solver for algebraic loop */
10586
10587 >>
10588 end match
10589 case e as SES_NONLINEAR(nlSystem = nls as NONLINEARSYSTEM(__))
10590 then
10591 let num = nls.index
10592 match simCode
10593 case SIMCODE(modelInfo = MODELINFO(__)) then
10594 <<
10595 shared_ptr<INonLinearAlgLoopSolver>
10596 _algLoopNonLinearSolver<%num%>; ///< Solver for algebraic loop */
10597 >>
10598 end match
10599 else
10600 ""
10601 end generateAlgloopsolverVariables4;
10602
10603
10604
10605
10606
10607 147 template generateAlgloopsSystemVariables(list<SimEqSystem> allEquationsPlusWhen,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
10608 ::=
10609 let &varDecls = buffer "" /*BUFD*/
10610 let algloopsystems = (allEquationsPlusWhen |> eqs => (eqs |> eq =>
10611 generateAlgloopsSystemVariables2(eq, contextOther, &varDecls /*BUFC*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace);separator="\n")
10612 ;separator="\n")
10613
10614
10615
10616 <<
10617 <%algloopsystems%>
10618
10619 >>
10620 end generateAlgloopsSystemVariables;
10621
10622
10623 69 template generateAlgloopsSystemVariables2(SimEqSystem eq, Context context, Text &varDecls, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
10624 "Generates an equation.
10625 This template should not be used for a SES_RESIDUAL.
10626 Residual equations are handled differently."
10627 ::=
10628 match eq
10629 case SES_LINEAR(lSystem = ls as LINEARSYSTEM(__))
10630 then
10631 let num = ls.index
10632 match simCode
10633 case SIMCODE(modelInfo = MODELINFO(__)) then
10634 <<
10635 shared_ptr<ILinearAlgLoop> //Algloop which holds equation system
10636 _algLoop<%num%>;
10637
10638 >>
10639 end match
10640 case e as SES_NONLINEAR(nlSystem = nls as NONLINEARSYSTEM(__))
10641 then
10642 let num = nls.index
10643 match simCode
10644 case SIMCODE(modelInfo = MODELINFO(__)) then
10645 <<
10646 shared_ptr<INonLinearAlgLoop> //Algloop which holds equation system
10647 _algLoop<%num%>;
10648
10649
10650 >>
10651 end match
10652 case e as SES_MIXED(cont = eq_sys)
10653 then
10654 <<
10655 <%generateAlgloopsSystemVariables2(eq_sys,context,varDecls,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)%>
10656 >>
10657 else
10658 ""
10659 end generateAlgloopsSystemVariables2;
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673 // shared_ptr<<%lastIdentOfPath(modelInfo.name)%>Algloop<%num%>> //Algloop which holds equation system
10674 49 template initAlgloopsolvers(list<SimEqSystem> allEquationsPlusWhen,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
10675 ::=
10676 let &varDecls = buffer "" /*BUFD*/
10677 let algloopsolver = (allEquationsPlusWhen |> eqs => (eqs |> eq =>
10678 initAlgloopsolvers2(eq, contextOther, &varDecls /*BUFC*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace))
10679 ;separator="")
10680
10681 <<
10682 <%algloopsolver%>
10683 >>
10684 end initAlgloopsolvers;
10685
10686
10687 ✗ template initAlgloopsolver(list<SimEqSystem> equations,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
10688 ::=
10689 let &varDecls = buffer "" /*BUFD*/
10690 let algloopsolver = (equations |> eq =>
10691 initAlgloopsolvers2(eq, contextOther, &varDecls /*BUFC*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)
10692 ;separator="")
10693
10694 <<
10695 <%algloopsolver%>
10696 >>
10697 end initAlgloopsolver;
10698
10699
10700 68 template initAlgloopsolvers2(SimEqSystem eq, Context context, Text &varDecls, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
10701 "Generates an equation.
10702 This template should not be used for a SES_RESIDUAL.
10703 Residual equations are handled differently."
10704 ::=
10705 match eq
10706 case SES_LINEAR(lSystem = ls as LINEARSYSTEM(__))
10707 then
10708 let num = ls.index
10709 match simCode
10710 case SIMCODE(modelInfo = MODELINFO(__)) then
10711 <<
10712 if(_algLoopSolver<%num%>)
10713 _algLoopSolver<%num%>->initialize();<%\n%>
10714 >>
10715 end match
10716 case e as SES_NONLINEAR(nlSystem = nls as NONLINEARSYSTEM(__))
10717 then
10718 let num = nls.index
10719 match simCode
10720 case SIMCODE(modelInfo = MODELINFO(__)) then
10721 <<
10722 if(_algLoopSolver<%num%>)
10723 _algLoopSolver<%num%>->initialize();
10724 >>
10725 end match
10726 case e as SES_MIXED(cont = eq_sys)
10727 then
10728 <<
10729 <%initAlgloopsolvers2(eq_sys,context,varDecls,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)%>
10730 >>
10731 else
10732 ""
10733 end initAlgloopsolvers2;
10734
10735
10736
10737
10738
10739
10740 49 template algloopForwardDeclaration(list<SimEqSystem> allEquations,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
10741 ::=
10742 let &varDecls = buffer "" /*BUFD*/
10743 <<
10744 <% allEquations |> eqs => (eqs |> eq =>
10745 algloopForwardDeclaration2(eq, contextOther, &varDecls /*BUFC*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace) ;separator="\n" )
10746 ;separator="\n" %>
10747 >>
10748 end algloopForwardDeclaration;
10749
10750 68 template algloopForwardDeclaration2(SimEqSystem eq, Context context, Text &varDecls, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
10751 ::=
10752 match eq
10753 case SES_LINEAR(lSystem = ls as LINEARSYSTEM(__))
10754 then
10755 let num = ls.index
10756 match simCode
10757 case SIMCODE(modelInfo = MODELINFO(__)) then
10758 <<
10759 class <%lastIdentOfPath(modelInfo.name)%>Algloop<%num%>;
10760 >>
10761 end match
10762 case e as SES_NONLINEAR(nlSystem = nls as NONLINEARSYSTEM(__))
10763 then
10764 let num = nls.index
10765 match simCode
10766 case SIMCODE(modelInfo = MODELINFO(__)) then
10767 <<
10768 class <%lastIdentOfPath(modelInfo.name)%>Algloop<%num%>;
10769 >>
10770 end match
10771 case e as SES_MIXED(cont = eq_sys)
10772 then
10773 <<
10774 <%algloopForwardDeclaration2(eq_sys,context,varDecls,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)%>
10775 >>
10776 else
10777 ""
10778 end algloopForwardDeclaration2;
10779
10780 147 template algloopfilesInclude(list<SimEqSystem> allEquations,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
10781 ::=
10782 let &varDecls = buffer "" /*BUFD*/
10783 <<
10784 <% allEquations |> eqs => (eqs |> eq =>
10785 algloopfilesInclude2(eq, contextOther, &varDecls /*BUFC*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace) ;separator="\n" )
10786 ;separator="\n" %>
10787 >>
10788 end algloopfilesInclude;
10789
10790 69 template algloopfilesInclude2(SimEqSystem eq, Context context, Text &varDecls, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
10791 "Generates an equation.
10792 This template should not be used for a SES_RESIDUAL.
10793 Residual equations are handled differently."
10794 ::=
10795 match eq
10796 case SES_LINEAR(lSystem = ls as LINEARSYSTEM(__))
10797 then
10798 let num = ls.index
10799 match simCode
10800 case SIMCODE(modelInfo = MODELINFO(__)) then
10801 '#include "OMCpp<%fileNamePrefix%>Algloop<%num%>.h"<%\n%>'
10802 end match
10803 case e as SES_NONLINEAR(nlSystem = nls as NONLINEARSYSTEM(__))
10804 then
10805 let num = nls.index
10806 match simCode
10807 case SIMCODE(modelInfo = MODELINFO(__)) then
10808 '#include "OMCpp<%fileNamePrefix%>Algloop<%num%>.h"<%\n%>'
10809 end match
10810 case e as SES_MIXED(cont = eq_sys)
10811 then
10812 <<
10813 <%algloopfilesInclude2(eq_sys,context,varDecls,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)%>
10814 >>
10815 else
10816 ""
10817 end algloopfilesInclude2;
10818
10819
10820 // use allEquations instead of odeEquations, because only allEquations are labeled for reduction algorithms
10821 168 template algloopfiles(list<SimEqSystem> allEquations, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Context context, Integer clockIndex, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
10822 ::=
10823 let &varDecls = buffer "" /*BUFD*/
10824 let algloopsolver = (allEquations |> eqs =>
10825 algloopfiles2(eqs, context, clockIndex, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
10826 ;separator="\n")
10827
10828 <<
10829 <%algloopsolver%>
10830 >>
10831 end algloopfiles;
10832
10833
10834 7054 template algloopfiles2(SimEqSystem eq, Context context, Integer clockIndex, Text &varDecls, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
10835 "Generates an equation.
10836 This template should not be used for a SES_RESIDUAL.
10837 Residual equations are handled differently."
10838 ::=
10839 let &extraFuncsAlg = buffer "" /* extra functions for each algebraic loop */
10840 let &extraFuncsDeclAlg = buffer "" /* extra function declarations for each algebraic loop */
10841 match eq
10842 case SES_LINEAR(lSystem = ls as LINEARSYSTEM(__))
10843 then
10844 let num = ls.index
10845 match simCode
10846 case SIMCODE(modelInfo = MODELINFO(__)) then
10847 let()= textFile(algloopCppFile(simCode, &extraFuncsAlg, &extraFuncsDeclAlg, extraFuncsNamespace, eq, context, clockIndex, stateDerVectorName, useFlatArrayNotation), 'OMCpp<%fileNamePrefix%>Algloop<%num%>.cpp')
10848 let()= textFile(algloopHeaderFile(simCode, &extraFuncsAlg, &extraFuncsDeclAlg, extraFuncsNamespace, eq, context, useFlatArrayNotation), 'OMCpp<%fileNamePrefix%>Algloop<%num%>.h')
10849 " "
10850 end match
10851 case e as SES_NONLINEAR(nlSystem = nls as NONLINEARSYSTEM(__))
10852 then
10853 let num = nls.index
10854 match simCode
10855 case SIMCODE(modelInfo = MODELINFO(__)) then
10856 let()= textFile(algloopCppFile(simCode, &extraFuncsAlg, &extraFuncsDeclAlg, extraFuncsNamespace, eq, context, clockIndex, stateDerVectorName, useFlatArrayNotation), 'OMCpp<%fileNamePrefix%>Algloop<%num%>.cpp')
10857 let()= textFile(algloopHeaderFile(simCode, &extraFuncsAlg, &extraFuncsDeclAlg, extraFuncsNamespace, eq, context, useFlatArrayNotation), 'OMCpp<%fileNamePrefix%>Algloop<%num%>.h')
10858 " "
10859 end match
10860 case e as SES_MIXED(cont = eq_sys)
10861 then
10862 match simCode
10863 case SIMCODE(modelInfo = MODELINFO(__)) then
10864 let()= textFile(algloopCppFile(simCode, &extraFuncsAlg, &extraFuncsDeclAlg, extraFuncsNamespace, eq_sys, context, clockIndex, stateDerVectorName, useFlatArrayNotation), 'OMCpp<%fileNamePrefix%>Algloop<%algloopfilesindex(eq_sys)%>.cpp')
10865 let()= textFile(algloopHeaderFile(simCode, &extraFuncsAlg, &extraFuncsDeclAlg, extraFuncsNamespace, eq_sys,context, useFlatArrayNotation), 'OMCpp<%fileNamePrefix%>Algloop<%algloopfilesindex(eq_sys)%>.h')
10866 " "
10867 end match
10868 else
10869 " "
10870 end algloopfiles2;
10871
10872 49 template algloopMainfile(SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Context context)
10873 ::=
10874 match(simCode )
10875 case SIMCODE(modelInfo = MODELINFO(__)) then
10876 let modelname = lastIdentOfPath(modelInfo.name)
10877 let filename = fileNamePrefix
10878 let modelfilename = match context case ALGLOOP_CONTEXT(genInitialisation=false,genJacobian=true) then '<%filename%>Jacobian' else '<%filename%>'
10879
10880 let jacfiles = (jacobianMatrices |> JAC_MATRIX(columns=mat) hasindex index0 => (mat |> JAC_COLUMN(columnEqns=eqs) => algloopMainfile1(eqs, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, filename) ;separator="") ;separator="")
10881 let algloopfiles = (listAppend(listAppend(allEquations, initialEquations), getClockedEquations(getSubPartitions(clockedPartitions))) |> eqs => algloopMainfile2(eqs, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, filename) ;separator="\n")
10882
10883 <<
10884 /*****************************************************************************
10885 *
10886 * Helper file that includes all alg-loop files.
10887 * This file is generated by the OpenModelica Compiler and produced to speed-up the compile time.
10888 *
10889 *****************************************************************************/
10890 #include <Core/System/LinearAlgLoopDefaultImplementation.h>
10891 #include <Core/System/NonLinearAlgLoopDefaultImplementation.h>
10892 //jac files
10893 <%jacfiles%>
10894 //alg loop files
10895 <%algloopfiles%>
10896 >>
10897 end algloopMainfile;
10898
10899 98 template algloopMainfile1(list<SimEqSystem> allEquations, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, String filename)
10900 ::=
10901 let algloopfiles = (allEquations |> eqs => algloopMainfile2(eqs, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, filename); separator="\n")
10902 <<
10903 <%algloopfiles%>
10904 >>
10905 end algloopMainfile1;
10906
10907 7276 template algloopMainfile2(SimEqSystem eq, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, String filename)
10908 ::=
10909 match eq
10910 case SES_LINEAR(lSystem = ls as LINEARSYSTEM(__)) then
10911 let num = ls.index
10912 <<
10913 #include "OMCpp<%filename%>Algloop<%ls.index%>.h"
10914 #include "OMCpp<%filename%>Algloop<%ls.index%>.cpp"<%\n%>
10915 >>
10916 case e as SES_NONLINEAR(nlSystem = nls as NONLINEARSYSTEM(__)) then
10917 let num = nls.index
10918 <<
10919 #include "OMCpp<%filename%>Algloop<%nls.index%>.h"
10920 #include "OMCpp<%filename%>Algloop<%nls.index%>.cpp"<%\n%>
10921 >>
10922 else
10923 <<
10924 >>
10925 end algloopMainfile2;
10926
10927 ✗ template algloopfilesindex(SimEqSystem eq)
10928 "Generates an index for algloopfile.
10929 "
10930 ::=
10931 match eq
10932 case SES_LINEAR(lSystem = ls as LINEARSYSTEM(__))
10933 then
10934 <<<%ls.index%>>>
10935 case e as SES_NONLINEAR(nlSystem = nls as NONLINEARSYSTEM(__))
10936 then
10937 <<<%nls.index%>>>
10938 case e as SES_MIXED(__)
10939 then
10940 <<<%index%>>>
10941 else
10942 " "
10943 end algloopfilesindex;
10944
10945 ✗ template algloopcppfilenames(list<SimEqSystem> allEquations,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
10946 ::=
10947 let &varDecls = buffer "" /*BUFD*/
10948 let algloopsolver = (allEquations |> eqs => (eqs |> eq =>
10949 algloopcppfilenames2(eq, contextOther, &varDecls /*BUFC*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace))
10950 ;separator="\t" ;align=10;alignSeparator="\\\n\t" )
10951
10952 <<
10953 <%algloopsolver%>
10954 >>
10955 end algloopcppfilenames;
10956
10957
10958 ✗ template algloopcppfilenames2(SimEqSystem eq, Context context, Text &varDecls, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
10959 "Generates an equation.
10960 This template should not be used for a SES_RESIDUAL.
10961 Residual equations are handled differently."
10962 ::=
10963 match eq
10964 case SES_LINEAR(lSystem = ls as LINEARSYSTEM(__))
10965 then
10966 let num = ls.index
10967 match simCode
10968 case SIMCODE(modelInfo = MODELINFO(__)) then
10969 <<
10970 OMCpp<%fileNamePrefix%>Algloop<%num%>.cpp
10971 >>
10972 end match
10973 case e as SES_NONLINEAR(nlSystem = nls as NONLINEARSYSTEM(__))
10974 then
10975 let num = nls.index
10976 match simCode
10977 case SIMCODE(modelInfo = MODELINFO(__)) then
10978 <<
10979 OMCpp<%fileNamePrefix%>Algloop<%num%>.cpp
10980 >>
10981 end match
10982 case e as SES_MIXED(cont = eq_sys)
10983 then
10984 <<
10985 <%algloopcppfilenames2(eq_sys,context,varDecls,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)%>
10986 >>
10987 else
10988 ""
10989 end algloopcppfilenames2;
10990
10991
10992 67 template equationArrayCallAssign(SimEqSystem eq, Context context, Text &varDecls, SimCode simCode, Text& extraFuncs,
10993 Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation, Boolean assignToStartValues)
10994 "Generates equation on form 'cref_array = call(...)'."
10995 ::=
10996 let &varDeclsCref = buffer "" /*BUFD*/
10997 match eq
10998
10999 case eqn as SES_ARRAY_CALL_ASSIGN(lhs=lhs as CREF(__)) then
11000 let startFixedExp = match cref2simvar(lhs.componentRef, simCode)
11001 case SIMVAR(varKind = CLOCKED_STATE(isStartFixed = isStartFixed)) then
11002 'if (<%if isStartFixed then "_clockStart[clockIndex - 1] || "%>_clockSubactive[clockIndex - 1]) return;'
11003 let &preExp = buffer "" /*BUFD*/
11004 let expPart = daeExp(exp, context, &preExp /*BUF let &preExp = buffer "" /*BUFD*/
11005 let &helpInits = buffer "" /*BUFD*/
11006 let helpIf = (conditions |> (e, hidx) =>
11007 let helpInit = daeExp(e, context, &preExp /*BUFC*/, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, useFlatArrayNotation)
11008 let &helpInits += 'localData->helpVars[<%hidx%>] = <%helpInit%>;'
11009 'localData->helpVars[<%hidx%>] && !localData->helpVars_saved[<%hidx%>] /* edge */'
11010 ;separator=" || ")C*/, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
11011 match expTypeFromExpShort(eqn.exp)
11012 case "double" then
11013 <<
11014 <%if not assignToStartValues then '<%startFixedExp%>'%>
11015 <%preExp%>
11016 <%assignDerArray(context, expPart, lhs, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>
11017 >>
11018 else
11019 let lhsStr = cref1(lhs.componentRef, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, context, varDeclsCref, stateDerVectorName, useFlatArrayNotation)
11020 <<
11021 <%if not assignToStartValues then '<%startFixedExp%>'%>
11022 <%preExp%>
11023 <%lhsStr%>.assign(<%expPart%>);
11024 >>
11025 end equationArrayCallAssign;
11026
11027 1 template equationResizableAssign(SimEqSystem eq, Context context, Text &varDecls, SimCode simCode, Text& extraFuncs,
11028 Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
11029 "Generates a non-scalarized resizable array assignment (NewBackend) as an inline,
11030 possibly nested, C++ for-loop. The actual lhs:=rhs body lives in a SINGLE_GENERIC_CALL
11031 referenced by call_index; we look it up in simCode.generic_loop_calls and inline it.
11032 The C runtime emits a separate genericCall_<n>() function for this; in the C++ runtime
11033 equations are model-class members operating on _<var> fields, so inlining fits better."
11034 ::=
11035 match eq
11036 case SES_RESIZABLE_ASSIGN(__) then
11037 let &preExp = buffer "" /*BUFD*/
11038 let header = (iters |> it => cppForIterHeader(it, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation) ; separator="\n")
11039 let tail = (iters |> it => "}" ; separator="\n")
11040 let body = resizableGenericCallBody(call_index, context, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
11041 <<
11042 <%preExp%>
11043 <%header%>
11044 <%body%>
11045 <%tail%>
11046 >>
11047 end equationResizableAssign;
11048
11049 1 template cppForIterHeader(SimIterator iter, Context context, Text &preExp, Text &varDecls, SimCode simCode, Text& extraFuncs,
11050 Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
11051 "One C++ for-loop header for a resizable iterator, including any derived sub-iterators."
11052 ::=
11053 match iter
11054 case SIM_ITERATOR_RANGE(__) then
11055 let iterName = localCref(name, useFlatArrayNotation)
11056 let startVal = daeExp(start, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
11057 let stepVal = daeExp(step, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
11058 let stopVal = daeExp(stop, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
11059 let subIts = (sub_iter |> si => cppSubIter(si, iterName, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation) ; separator="\n")
11060 <<
11061 for (modelica_integer <%iterName%> = <%startVal%>; ((<%stepVal%>) >= 0 ? <%iterName%> <= (<%stopVal%>) : <%iterName%> >= (<%stopVal%>)); <%iterName%> += (<%stepVal%>)) {
11062 <%subIts%>
11063 >>
11064 case SIM_ITERATOR_LIST(__) then
11065 let iterName = localCref(name, useFlatArrayNotation)
11066 let arr = (lst |> e => '<%e%>' ; separator=", ")
11067 let subIts = (sub_iter |> si => cppSubIter(si, iterName, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation) ; separator="\n")
11068 <<
11069 static const modelica_integer <%iterName%>_lst[<%size%>] = {<%arr%>};
11070 for (int <%iterName%>_i = 0; <%iterName%>_i < <%size%>; <%iterName%>_i++) {
11071 modelica_integer <%iterName%> = <%iterName%>_lst[<%iterName%>_i];
11072 <%subIts%>
11073 >>
11074 end cppForIterHeader;
11075
11076 ✗ template cppSubIter(tuple<DAE.ComponentRef, array<DAE.Exp>> sit, Text parentIter, Context context, Text &preExp, Text &varDecls,
11077 SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
11078 "A derived (sub) iterator, used when a multi-dimensional array loop is flattened: the
11079 derived index is a constant table indexed by the (1-based) parent iterator value."
11080 ::=
11081 match sit
11082 case (sname, srange) then
11083 let snm = localCref(sname, useFlatArrayNotation)
11084 let svals = (arrayList(srange) |> se => daeExp(se, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation) ; separator=", ")
11085 let ssize = listLength(arrayList(srange))
11086 <<
11087 static const modelica_integer <%snm%>_arr[<%ssize%>] = {<%svals%>};
11088 modelica_integer <%snm%> = <%snm%>_arr[<%parentIter%>-1];
11089 >>
11090 end cppSubIter;
11091
11092 1 template resizableGenericCallBody(Integer callIndex, Context context, Text &varDecls, SimCode simCode, Text& extraFuncs,
11093 Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
11094 "Find the SINGLE_GENERIC_CALL whose index == callIndex in simCode.generic_loop_calls and inline its lhs:=rhs."
11095 ::=
11096 match simCode
11097 case SIMCODE(__) then
11098 (generic_loop_calls |> call =>
11099 match call
11100 case SINGLE_GENERIC_CALL(index=ci) then
11101 if intEq(ci, callIndex) then resizableLhsRhs(call, context, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
11102 ; separator="")
11103 end resizableGenericCallBody;
11104
11105 1 template resizableLhsRhs(SimGenericCall call, Context context, Text &varDecls, SimCode simCode, Text& extraFuncs,
11106 Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
11107 "Inline body of a single generic call: lhs := rhs, with the iterator crefs rendered as the loop variables."
11108 ::=
11109 match call
11110 case SINGLE_GENERIC_CALL(__) then
11111 let &preExp = buffer "" /*BUFD*/
11112 let rhsPart = daeExp(rhs, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
11113 let assign = match lhs
11114 case CREF(ty = T_ARRAY(__)) then
11115 let lhsPart = daeExpCref(true, lhs, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
11116 '<%lhsPart%>.assign(<%rhsPart%>);'
11117 case CREF(__) then
11118 let lhsPart = daeExpCref(true, lhs, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
11119 '<%lhsPart%> = <%rhsPart%>;'
11120 else
11121 let lhsPart = daeExp(lhs, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
11122 '<%lhsPart%> = <%rhsPart%>;'
11123 <<
11124 <%preExp%>
11125 <%assign%>
11126 >>
11127 end resizableLhsRhs;
11128
11129 65 template assignDerArray(Context context, String arr, Exp lhs_ecr, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
11130 "Assign array considering special treatment of states and Jacobian vars"
11131 ::=
11132 match lhs_ecr
11133 case CREF(componentRef = c, ty = ty) then
11134 let &varDeclsCref = buffer "" /*BUFD*/
11135 let lhsStr = cref1(c, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, context, varDeclsCref, stateDerVectorName, useFlatArrayNotation)
11136 match cref2simvar(c, simCode)
11137 case SIMVAR(varKind=varKind) then
11138 match varKind
11139 /* don't use __zDot due to SIMVAR indexing of new backend
11140 case STATE()
11141 case STATE_DER() then
11142 //STATE vars are flat vectors
11143 <<
11144 // assign to <%cref(c,useFlatArrayNotation)%>
11145 memcpy(&<%lhsStr%>, <%arr%>.getData(), <%arr%>.getNumElems()*sizeof(double));
11146 >>
11147 */
11148 case JAC_VAR()
11149 case JAC_TMP_VAR()
11150 case SEED_VAR() then
11151 <<
11152 <%assignJacArray(lhsStr, arr, ty)%>
11153 >>
11154 else
11155 <<
11156 /*default array assign*/
11157 <%lhsStr%>.assign(<%arr%>);
11158 >>
11159 end assignDerArray;
11160
11161 53 template equationWhen(SimEqSystem eq, Context context, Text &varDecls, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl,
11162 Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
11163 "Generates a when equation."
11164 ::=
11165 let &varDeclsCref = buffer "" /*BUFD*/
11166 let sysderef = match context case ALGLOOP_CONTEXT(__) then '_system->'
11167 match eq
11168 case SES_WHEN(whenStmtLst = whenStmtLst, conditions=conditions, elseWhen=NONE()) then
11169 let helpIf = (conditions |> e => ' || (<%cref1(e, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, context, varDeclsCref, stateDerVectorName, useFlatArrayNotation)%> && !_discrete_events->pre(<%cref1(e, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, context, varDeclsCref, stateDerVectorName, useFlatArrayNotation)%>))')
11170
11171 /*let initial_assign =
11172 if initialCall then
11173 whenAssign(left, typeof(right), right, context, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
11174 else
11175 '<%cref1(left,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, context, varDeclsCref, stateDerVectorName, useFlatArrayNotation)%> = _discrete_events->pre(<%cref1(left,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, context, varDeclsCref, stateDerVectorName, useFlatArrayNotation)%>);'*/
11176 let body = whenOperators(whenStmtLst, context, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
11177 let pre_call = preCall(whenStmtLst, context, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
11178 <<
11179 if (<%sysderef%>_initial)
11180 {
11181 <%pre_call%>
11182 }
11183 else if (0<%helpIf%>)
11184 {
11185 <%body%>
11186 }
11187 else
11188 {
11189 <%pre_call%>
11190 }
11191 >>
11192 case SES_WHEN(whenStmtLst = whenStmtLst, conditions=conditions, elseWhen=SOME(elseWhenEq)) then
11193 let helpIf = (conditions |> e => ' || (<%cref1(e, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, context, varDeclsCref, stateDerVectorName, useFlatArrayNotation)%> && !_discrete_events->pre(<%cref1(e, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, context, varDeclsCref, stateDerVectorName, useFlatArrayNotation)%>))')
11194 let initial_assign =
11195 if initialCall then
11196 whenOperators(whenStmtLst, context, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
11197 else
11198 preCall(whenStmtLst, context, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
11199 let body = whenOperators(whenStmtLst, context, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
11200 let elseWhen = equationElseWhen(elseWhenEq, context, varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
11201 let pre_call = preCall(whenStmtLst, context, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
11202 <<
11203 if (<%sysderef%>_initial)
11204 {
11205 <%initial_assign%>
11206 }
11207 else if(0<%helpIf%>)
11208 {
11209 <%body%>
11210 }
11211 <%elseWhen%>
11212 else
11213 {
11214 <%pre_call%>
11215 }
11216 >>
11217 end equationWhen;
11218
11219
11220 53 template preCall(list<WhenOperator> whenOps, Context context, Text &varDecls, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl,
11221 Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
11222 "Generates assignment for when."
11223 ::=
11224 let body = (whenOps |> whenOp => match whenOp
11225 case whenOp as ASSIGN(__) then
11226 preCallExp(left, right, context, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
11227 else
11228 <<; // nothing to do>>
11229 ;separator="\n")
11230 <<
11231 <%body%>
11232 >>
11233 end preCall;
11234
11235 47 template preCallExp(Exp left, Exp right, Context context, Text &varDecls, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl,
11236 Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
11237 "Generates assignment from pre variable to variable for when."
11238 ::=
11239 match left
11240 case left as DAE.TUPLE(PR = eLst) then
11241 (eLst |> e => preCallExp(e, right, context, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation);separator="\n")
11242 case left as DAE.CREF(componentRef = cr) then
11243 let var = cref1(cr, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, context, varDecls, stateDerVectorName, useFlatArrayNotation)
11244 // ckeck for array element -- var ends with ')'
11245 if intEq(stringGet(var, stringLength(var)), 41) then
11246 <<
11247 <%var%> = _discrete_events->pre(<%var%>);
11248 >>
11249 else
11250 match cref2simvar(cr, simCode)
11251 case SIMVAR(arrayCref = NONE()) then
11252 <<
11253 <%var%> = _discrete_events->pre(<%var%>);
11254 >>
11255 case SIMVAR(numArrayElement = nums) then
11256 let forLoops = nums |> num hasindex i1 fromindex 1 =>
11257 'for (int i<%i1%> = 1; i<%i1%> <= <%num%>; i<%i1%>++)' ;separator=" "
11258 let indices = nums |> num hasindex i1 fromindex 1 =>
11259 'i<%i1%>' ;separator=","
11260 <<
11261 <%forLoops%>
11262 <%var%>(<%indices%>) = _discrete_events->pre(<%var%>(<%indices%>));
11263 >>
11264 end match
11265 else
11266 <<
11267 #error unknown preCallExp <%ExpressionDumpTpl.dumpExp(left, "\"")%>
11268 >>
11269 end match
11270 end preCallExp;
11271
11272 45 template whenAssign(Exp left, Type ty, Exp right, Context context, Text &varDecls, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl,
11273 Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
11274 "Generates assignment for when."
11275 ::=
11276 match left
11277 case left as DAE.CREF(componentRef = cr) then
11278 let &preExp = buffer "" /*BUFD*/
11279 let exp = daeExp(right, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
11280 let lhs = cref1(cr, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, context, varDecls, stateDerVectorName, useFlatArrayNotation)
11281 <<
11282 <%preExp%>
11283 <%lhs%> = <%exp%>;
11284 >>
11285 case left as DAE.TUPLE(PR = expLst) then
11286 let &preExp = buffer "" /*BUFD*/
11287 let crefs = (expLst |> e => ExpressionDumpTpl.dumpExp(e,"\"") ;separator=", ")
11288 let marker = '(<%crefs%>) = <%ExpressionDumpTpl.dumpExp(right,"\"")%>'
11289 let retStruct = daeExp(right, context, &preExp, &varDecls, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
11290 let lhsCrefs = (expLst |> cr hasindex i1 fromindex 0 =>
11291 let rhsStr = 'get<<%i1%>>(<%retStruct%>.data)'
11292 writeLhsCref(cr, rhsStr, context, &preExp, &varDecls, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
11293 ;separator="\n";empty)
11294 <<
11295 // whenAssign: preExp <%marker%>
11296 <%preExp%>
11297 // whenAssign: writeLhsCref
11298 <%lhsCrefs%>
11299 >>
11300 else
11301 <<dont know whenAssign lhs-type>>
11302 end whenAssign;
11303
11304 ✗ template equationIfEquation(SimEqSystem eq, Context context,Text &varDecls /*BUFP*/, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
11305 "Generates an if equation."
11306 ::=
11307 match eq
11308 case SES_IFEQUATION(ifbranches=ifbranches, elsebranch=elsebranch) then
11309 let &preExp = buffer ""
11310 let IfEquation = (ifbranches |> (e, eqns) hasindex index0 =>
11311 let condition = daeExp(e, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
11312 let ifequations = (eqns |> eqn =>
11313 let eqnStr = equation_(eqn, context, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, &extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
11314 <<
11315 <%eqnStr%>
11316 >>
11317 ; separator="\n")
11318 let conditionline = if index0 then 'else if(<%condition%>)' else 'if(<%condition%>)'
11319 <<
11320 <%conditionline%>
11321 {
11322 <%ifequations%>
11323 }
11324 >>
11325 ; separator="\n")
11326 let elseequations = (elsebranch |> eqn =>
11327 let eqnStr = equation_(eqn, context, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, &extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
11328 <<
11329 <%eqnStr%>
11330 >>
11331 ; separator="\n")
11332 <<
11333 <%preExp%>
11334 <%IfEquation%>
11335 else
11336 {
11337 <%elseequations%>
11338 }
11339 >>
11340 end equationIfEquation;
11341
11342 ✗ template equationElseWhen(SimEqSystem eq, Context context, Text &varDecls, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl,
11343 Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
11344 "Generates a else when equation."
11345 ::=
11346 let &varDeclsCref = buffer "" /*BUFD*/
11347 match eq
11348 case SES_WHEN(whenStmtLst = whenStmtLst, conditions=conditions, elseWhen=NONE()) then
11349 let helpIf = (conditions |> e => ' || (<%cref1(e, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, context, varDeclsCref, stateDerVectorName, useFlatArrayNotation)%> && !_discrete_events->pre(<%cref1(e, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, context, varDeclsCref, stateDerVectorName, useFlatArrayNotation)%>))')
11350 let body = whenOperators(whenStmtLst, context, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
11351 <<
11352 else if(0<%helpIf%>)
11353 {
11354 <%body%>
11355 }
11356 >>
11357 case SES_WHEN(whenStmtLst = whenStmtLst, conditions=conditions, elseWhen=SOME(elseWhenEq)) then
11358 let helpIf = (conditions |> e => ' || (<%cref1(e, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, context, varDeclsCref, stateDerVectorName, useFlatArrayNotation)%> && !_discrete_events->pre(<%cref1(e, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, context, varDeclsCref, stateDerVectorName, useFlatArrayNotation)%>))')
11359 let body = whenOperators(whenStmtLst, context, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
11360 let elseWhen = equationElseWhen(elseWhenEq, context, varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
11361 <<
11362 else if(0<%helpIf%>)
11363 {
11364 <%body%>
11365 }
11366 <%elseWhen%>
11367 >>
11368 end equationElseWhen;
11369
11370 53 template whenOperators(list<WhenOperator> whenOps, Context context, Text &varDecls /*BUFP*/, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
11371 "Generates re-init statement for when equation."
11372 ::=
11373 let body = (whenOps |> whenOp =>
11374 match whenOp
11375 case ASSIGN(left = lhs) then whenAssign(lhs, typeof(right), right, context, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
11376 case REINIT(__) then
11377 let &preExp = buffer "" /*BUFD*/
11378 let &varDeclsCref = buffer "" /*BUFD*/
11379 let val = daeExp(value, contextSimulationDiscrete, &preExp /*BUFC*/, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
11380 <<
11381 _state_var_reinitialized = true;
11382 <%preExp%>
11383 <%cref1(stateVar,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,contextOther,varDeclsCref,stateDerVectorName,useFlatArrayNotation)%> = <%val%>;
11384 >>
11385 case TERMINATE(__) then
11386 let &preExp = buffer "" /*BUFD*/
11387 let msgVar = daeExp(message, contextSimulationDiscrete, &preExp /*BUFC*/, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
11388 <<
11389 <%preExp%>
11390 MODELICA_TERMINATE(<%msgVar%>);
11391 >>
11392 case ASSERT(source=SOURCE(info=info)) then
11393 assertCommon(condition, message,level, contextSimulationDiscrete, &varDecls, info,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
11394 case NORETCALL(__) then
11395 let &preExp = buffer ""
11396 let expPart = daeExp(exp, contextSimulationDiscrete, &preExp, &varDecls,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
11397 <<
11398 <%preExp%>
11399 <% if isCIdentifier(expPart) then "" else '<%expPart%>;' %>
11400 >>
11401 ;separator="\n")
11402 <<
11403 <%body%>
11404 >>
11405 end whenOperators;
11406
11407 ✗ template preCref(ComponentRef cr, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Context context, Text stateDerVectorName, Boolean useFlatArrayNotation) ::=
11408 let &varDeclsCref = buffer "" /*BUFD*/
11409 'pre<%representationCref(cr, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,context,varDeclsCref, stateDerVectorName, useFlatArrayNotation)%>'
11410 end preCref;
11411
11412 11570 template equationSimpleAssign(SimEqSystem eq, Context context,Text &varDecls, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace,
11413 Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation, Boolean assignToStartValues, Boolean overwriteOldStartValue)
11414 "Generates an equation that is just a simple assignment."
11415 ::=
11416 match eq
11417 case SES_SIMPLE_ASSIGN(__) then
11418 let startFixedExp = match cref2simvar(cref, simCode)
11419 case SIMVAR(varKind = CLOCKED_STATE(isStartFixed = isStartFixed)) then
11420 'if (<%if isStartFixed then "_clockStart[clockIndex - 1] || "%>_clockSubactive[clockIndex - 1]) return;'
11421 let &preExp = buffer "" /*BUFD*/
11422 let expPart = daeExp(exp, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
11423
11424 match cref
11425 case CREF_QUAL(ident = "$PRE") then
11426 let sysderef = match context case ALGLOOP_CONTEXT(__) then '_system->'
11427 <<
11428 _discrete_events->save(<%sysderef%><%cref(componentRef, useFlatArrayNotation)%>,<%expPart%>);
11429 //_discrete_events->pre(<%cref(componentRef, useFlatArrayNotation)%>)=<%expPart%>;
11430 >>
11431 else
11432 match exp
11433 case CREF(ty = t as T_ARRAY(__)) then
11434 <<
11435 //Array assign
11436 <%cref1(cref, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, context, varDecls, stateDerVectorName, useFlatArrayNotation)%> = <%expPart%>;
11437 >>
11438 else
11439 let startValueType = crefStartValueType(cref)
11440 let lvalue = lhsCref(cref, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
11441 let assignExp = if boolAnd(assignToStartValues, boolNot(stringEq(startValueType, "ExternalObject"))) then
11442 'SystemDefaultImplementation::set<%startValueType%>StartValue(<%lvalue%>, <%expPart%>, <%overwriteOldStartValue%>);' else
11443 '<%lvalue%> = <%expPart%>;'
11444 <<
11445 <%if not assignToStartValues then '<%startFixedExp%>'%>
11446 <%preExp%>
11447 <%assignExp%>
11448 >>
11449 end match
11450 end match
11451 end equationSimpleAssign;
11452
11453
11454 120 template equationLinearOrNonLinear(SimEqSystem eq, Context context,Text &varDecls,
11455 SimCode simCode, Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/)
11456 "Generates an equations for a linear or non linear system."
11457 ::=
11458 match eq
11459 case SES_LINEAR(lSystem = ls as LINEARSYSTEM(__)) then
11460 let i = ls.index
11461 match context
11462 case ALGLOOP_CONTEXT(genInitialisation=true) then
11463 <<
11464 try
11465 {
11466
11467 _algLoop<%ls.index%>->evaluate();
11468 for(int i=0; i<_dimZeroFunc; i++) {
11469 getCondition(i);
11470 }
11471 IContinuous::UPDATETYPE calltype = _callType;
11472 _callType = IContinuous::CONTINUOUS;
11473 <%if boolOr(Flags.isSet(HPCOM),boolNot(getConfigBool(SINGLE_INSTANCE_AGLSOLVER)))
11474 then
11475 '_algLoopLinearSolver<%ls.index%>->solve();'
11476 else
11477 '_algLoopLinearSolver->solve(_algLoop<%ls.index%>,true);'
11478 %>
11479 _callType = calltype;
11480 }
11481 catch(ModelicaSimulationError& ex)
11482 {
11483 string error = add_error_info("Linear solver <%ls.index%>", ex.what(), ex.getErrorID(), _simTime);
11484 throw ModelicaSimulationError(ALGLOOP_EQ_SYSTEM,error);
11485 }
11486 >>
11487 else
11488 <<
11489 bool restart<%ls.index%> = true;
11490 unsigned int iterations<%ls.index%> = 0;
11491 <%if boolOr(Flags.isSet(HPCOM),boolNot(getConfigBool(SINGLE_INSTANCE_AGLSOLVER)))
11492 then
11493 'double* algloop<%ls.index%>Vars = _algLoopLinearSolver<%ls.index%>->getVariableWorkArray();
11494 bool* conditions0<%ls.index%> = _algLoopLinearSolver<%ls.index%>->getConditionsWorkArray();
11495 bool* conditions1<%ls.index%> = _algLoopLinearSolver<%ls.index%>->getConditions2WorkArray();'
11496 else
11497 'double* algloop<%ls.index%>Vars = _algLoopLinearSolver->getVariableWorkArray();
11498 bool* conditions0<%ls.index%> = _algLoopLinearSolver->getConditionsWorkArray();
11499 bool* conditions1<%ls.index%> = _algLoopLinearSolver->getConditions2WorkArray();'
11500 %>
11501 _algLoop<%ls.index%>->getReal(algloop<%ls.index%>Vars );
11502 bool restatDiscrete<%ls.index%>= false;
11503 IContinuous::UPDATETYPE calltype = _callType;
11504 try
11505 {
11506 if( _callType == IContinuous::DISCRETE )
11507 {
11508 _algLoop<%ls.index%>->evaluate();
11509 while(restart<%ls.index%> && !(iterations<%ls.index%>++>500))
11510 {
11511 getConditions(conditions0<%ls.index%>);
11512 _callType = IContinuous::CONTINUOUS;
11513
11514 <%if boolOr(Flags.isSet(HPCOM),boolNot(getConfigBool(SINGLE_INSTANCE_AGLSOLVER)))
11515 then
11516 '_algLoopLinearSolver<%ls.index%>->solve();'
11517 else
11518 '_algLoopLinearSolver->solve(_algLoop<%ls.index%>,(iterations<%ls.index%>==1));'
11519 %>
11520 _callType = IContinuous::DISCRETE;
11521 for(int i=0;i<_dimZeroFunc;i++)
11522 {
11523 getCondition(i);
11524 }
11525
11526 getConditions(conditions1<%ls.index%>);
11527 restart<%ls.index%> = !std::equal (conditions1<%ls.index%>, conditions1<%ls.index%>+_dimZeroFunc,conditions0<%ls.index%>);
11528 }
11529 }
11530 else
11531 <%if boolOr(Flags.isSet(HPCOM),boolNot(getConfigBool(SINGLE_INSTANCE_AGLSOLVER)))
11532 then
11533 '_algLoopLinearSolver<%ls.index%>->solve();'
11534 else
11535 '_algLoopLinearSolver->solve(_algLoop<%ls.index%>,true);'
11536 %>
11537
11538 }
11539 catch(ModelicaSimulationError &ex)
11540 {
11541 restatDiscrete<%ls.index%>=true;
11542 }
11543
11544 if((restart<%ls.index%>&& iterations<%ls.index%> > 0)|| restatDiscrete<%ls.index%>)
11545 {
11546 try
11547 { //workaround: try to solve algoop discrete (evaluate all zero crossing conditions) since we do not have the information which zercrossing contains a algloop var
11548 _callType = IContinuous::DISCRETE;
11549 _algLoop<%ls.index%>->setReal(algloop<%ls.index%>Vars );
11550 <%if boolOr(Flags.isSet(HPCOM),boolNot(getConfigBool(SINGLE_INSTANCE_AGLSOLVER)))
11551 then
11552 '_algLoopLinearSolver<%ls.index%>->solve();'
11553 else
11554 '_algLoopLinearSolver->solve(_algLoop<%ls.index%>);'
11555 %>
11556 _callType = calltype;
11557 }
11558 catch(ModelicaSimulationError& ex)
11559 {
11560 string error = add_error_info("Linear solver <%ls.index%>", ex.what(), ex.getErrorID(), _simTime);
11561 throw ModelicaSimulationError(ALGLOOP_EQ_SYSTEM,error);
11562 }
11563 }
11564 >>
11565 end match
11566
11567 case SES_NONLINEAR(nlSystem = nls as NONLINEARSYSTEM(__)) then
11568 let i = nls.index
11569 match context
11570 case ALGLOOP_CONTEXT(genInitialisation=true) then
11571 <<
11572 try
11573 {
11574
11575 _algLoop<%nls.index%>->evaluate();
11576 for(int i=0; i<_dimZeroFunc; i++) {
11577 getCondition(i);
11578 }
11579 IContinuous::UPDATETYPE calltype = _callType;
11580 _callType = IContinuous::CONTINUOUS;
11581
11582 <%if boolOr(Flags.isSet(HPCOM),boolNot(getConfigBool(SINGLE_INSTANCE_AGLSOLVER)))
11583 then
11584 '_algLoopNonLinearSolver<%nls.index%>->solve();'
11585 else
11586 '_algLoopNonLinearSolver->solve(_algLoop<%nls.index%>,true);'
11587 %>
11588
11589 _callType = calltype;
11590 }
11591 catch(ModelicaSimulationError& ex)
11592 {
11593 string error = add_error_info("Nonlinear solver <%nls.index%>", ex.what(), ex.getErrorID(), _simTime);
11594 throw ModelicaSimulationError(ALGLOOP_EQ_SYSTEM,error);
11595 }
11596 >>
11597 else
11598 <<
11599 bool restart<%nls.index%> = true;
11600 unsigned int iterations<%nls.index%> = 0;
11601 <%if boolOr(Flags.isSet(HPCOM),boolNot(getConfigBool(SINGLE_INSTANCE_AGLSOLVER)))
11602 then
11603 'double* algloop<%nls.index%>Vars = _algLoopNonLinearSolver<%nls.index%>->getVariableWorkArray();
11604 bool* conditions0<%nls.index%> = _algLoopNonLinearSolver<%nls.index%>->getConditionsWorkArray();
11605 bool* conditions1<%nls.index%> = _algLoopNonLinearSolver<%nls.index%>->getConditions2WorkArray();'
11606 else
11607 'double* algloop<%nls.index%>Vars = _algLoopNonLinearSolver->getVariableWorkArray();
11608 bool* conditions0<%nls.index%> = _algLoopNonLinearSolver->getConditionsWorkArray();
11609 bool* conditions1<%nls.index%> = _algLoopNonLinearSolver->getConditions2WorkArray();'
11610 %>
11611 _algLoop<%nls.index%>->getReal(algloop<%nls.index%>Vars );
11612 bool restatDiscrete<%nls.index%>= false;
11613 IContinuous::UPDATETYPE calltype = _callType;
11614 try
11615 {
11616 if( _callType == IContinuous::DISCRETE )
11617 {
11618 _algLoop<%nls.index%>->evaluate();
11619 while(restart<%nls.index%> && !(iterations<%nls.index%>++>500))
11620 {
11621 getConditions(conditions0<%nls.index%>);
11622 _callType = IContinuous::CONTINUOUS;
11623
11624 <%if boolOr(Flags.isSet(HPCOM),boolNot(getConfigBool(SINGLE_INSTANCE_AGLSOLVER)))
11625 then
11626 '_algLoopNonLinearSolver<%nls.index%>->solve();'
11627 else
11628 '_algLoopNonLinearSolver->solve(_algLoop<%nls.index%>,(iterations<%nls.index%>==1));'
11629 %>
11630 _callType = IContinuous::DISCRETE;
11631 for(int i=0;i<_dimZeroFunc;i++)
11632 {
11633 getCondition(i);
11634 }
11635
11636 getConditions(conditions1<%nls.index%>);
11637 restart<%nls.index%> = !std::equal (conditions1<%nls.index%>, conditions1<%nls.index%>+_dimZeroFunc,conditions0<%nls.index%>);
11638 }
11639 }
11640 else
11641 <%if boolOr(Flags.isSet(HPCOM),boolNot(getConfigBool(SINGLE_INSTANCE_AGLSOLVER)))
11642 then
11643 '_algLoopNonLinearSolver<%nls.index%>->solve();'
11644 else
11645 '_algLoopNonLinearSolver->solve(_algLoop<%nls.index%>,true);'
11646 %>
11647
11648 }
11649 catch(ModelicaSimulationError &ex)
11650 {
11651 restatDiscrete<%nls.index%>=true;
11652 }
11653
11654 if((restart<%nls.index%>&& iterations<%nls.index%> > 0)|| restatDiscrete<%nls.index%>)
11655 {
11656 try
11657 { //workaround: try to solve algoop discrete (evaluate all zero crossing conditions) since we do not have the information which zercrossing contains a algloop var
11658 _callType = IContinuous::DISCRETE;
11659 _algLoop<%nls.index%>->setReal(algloop<%nls.index%>Vars );
11660
11661 <%if boolOr(Flags.isSet(HPCOM),boolNot(getConfigBool(SINGLE_INSTANCE_AGLSOLVER)))
11662 then
11663 '_algLoopNonLinearSolver<%nls.index%>->solve();'
11664 else
11665 '_algLoopNonLinearSolver->solve(algLoop<%nls.index%>);'
11666 %>
11667 _callType = calltype;
11668 }
11669 catch(ModelicaSimulationError& ex)
11670 {
11671 string error = add_error_info("Nonlinear solver <%nls.index%>", ex.what(), ex.getErrorID(), _simTime);
11672 throw ModelicaSimulationError(ALGLOOP_EQ_SYSTEM,error);
11673 }
11674 }
11675 >>
11676 end match
11677 end match
11678 end equationLinearOrNonLinear;
11679
11680
11681 17 template equationForLoop(SimEqSystem eq, Context context, Text &varDecls, SimCode simCode, Text &extraFuncs, Text &extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation, Boolean assignToStartValues)
11682 ::=
11683 match eq
11684 case SES_FOR_LOOP(__) then
11685 let startFixedExp = match cref2simvar(cref, simCode)
11686 case SIMVAR(varKind = CLOCKED_STATE(isStartFixed = isStartFixed)) then
11687 'if (<%if isStartFixed then "_clockStart[clockIndex - 1] || "%>_clockSubactive[clockIndex - 1]) return;'
11688 let &preExp = buffer ""
11689 let iterExp = daeExp(iter, context, preExp, varDecls, simCode, extraFuncs, extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, false)
11690 let startExp = daeExp(startIt, context, preExp, varDecls, simCode, extraFuncs, extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, false)
11691 let endExp = daeExp(endIt, context, preExp, varDecls, simCode, extraFuncs, extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, false)
11692 let expPart = daeExp(exp, context, preExp, varDecls, simCode, extraFuncs, extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, false)
11693 let crefPart = daeExpCref(true, crefExp(cref), context, preExp, varDecls, simCode, extraFuncs, extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, false)
11694 <<
11695 <%if not assignToStartValues then '<%startFixedExp%>'%>
11696 for (int <%iterExp%> = <%startExp%>; <%iterExp%> <= <%endExp%>; <%iterExp%>++) {
11697 <%preExp%>
11698 <%if isArrayType(crefTypeFull(cref)) then
11699 '<%crefPart%>.assign(<%expPart%>);'
11700 else
11701 '<%crefPart%> = <%expPart%>;'%>
11702 }
11703 >>
11704 end equationForLoop;
11705
11706 2 template equationForEquation(SimEqSystem eq, Context context, Text &varDecls, SimCode simCode, Text &extraFuncs, Text &extraFuncsDecl, Text extraFuncsNamespace,
11707 Text& additionalFuncs, Text method,Text classnameext, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation,
11708 Boolean createMeasureTime, Boolean assignToStartValues, Boolean overwriteOldStartValue, Text &varDeclsLocal)
11709 ::=
11710 match eq
11711 case SES_FOR_EQUATION(__) then
11712 /*
11713 let startFixedExp = match cref2simvar(cref, simCode)
11714 case SIMVAR(varKind = CLOCKED_STATE(isStartFixed = isStartFixed)) then
11715 'if (<%if isStartFixed then "_clockStart[clockIndex - 1] || "%>_clockSubactive[clockIndex - 1]) return;'
11716 */
11717 let &preExp = buffer ""
11718 let iterExp = daeExp(iter, context, preExp, varDecls, simCode, extraFuncs, extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, false)
11719 let startExp = daeExp(startIt, context, preExp, varDecls, simCode, extraFuncs, extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, false)
11720 let endExp = daeExp(endIt, context, preExp, varDecls, simCode, extraFuncs, extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, false)
11721 let bodyPart = (body |> eq =>
11722 equation_function_create_single_body(eq, context, simCode, extraFuncs, extraFuncsDecl, extraFuncsNamespace,
11723 additionalFuncs, method, classnameext, stateDerVectorName, useFlatArrayNotation,
11724 createMeasureTime, assignToStartValues, overwriteOldStartValue, varDeclsLocal)
11725 ;separator="\n")
11726 // <%if not assignToStartValues then '<%startFixedExp%>'%>
11727 <<
11728 for (int <%iterExp%> = <%startExp%>; <%iterExp%> <= <%endExp%>; <%iterExp%>++) {
11729 <%preExp%>
11730 <%bodyPart%>
11731 }
11732 >>
11733 end equationForEquation;
11734
11735 // Previously unknown dims were set to ICONST(-1) at SimCode creation
11736 // we do not do that anymore.
11737 // This used to return '' for ICONST no matter the value. I am not sure
11738 // if that is the right thing to do. For now we will just call the function
11739 // that was used to convert dims to expressions in SimCode creation
11740 // here as well, i.e., will still return '' for UNKNOWN_DIM since it
11741 // will be converted to DAE.ICONST(-1).
11742 280 template testDaeDimension(DAE.Dimension dim)
11743 "Generates code for an expression."
11744 ::=
11745 testDaeDimensionExp(Expression.dimensionSizeExpHandleUnkown(dim))
11746 end testDaeDimension;
11747
11748 86 template testDaeDimensionExp(Exp exp)
11749 "Generates code for an expression."
11750 ::=
11751 match exp
11752 case ICONST(integer=-1) then '---' // unknown
11753 case ICONST(__) then '' // known static
11754 else '-1' // known dynamic
11755 end testDaeDimensionExp;
11756
11757 290 template daeDimension(DAE.Dimension dim, Context context, Text &preExp, Text &varDecls, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName, Boolean useFlatArrayNotation)
11758 "Generates code for an expression."
11759 ::=
11760 daeExp(Expression.dimensionSizeExpHandleUnkown(dim), context, &preExp, &varDecls, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
11761 end daeDimension;
11762
11763
11764 1166 template assertCommon(Exp condition, Exp message,Exp level, Context context, Text &varDecls, builtin.SourceInfo info, SimCode simCode,
11765 Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
11766 ::=
11767 let &preExpCond = buffer ""
11768 let &preExpMsg = buffer ""
11769 let condVar = daeExp(condition, context, &preExpCond, &varDecls,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
11770 let msgVar = daeExp(message, context, &preExpMsg, &varDecls,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
11771 /* <<
11772 <%preExpCond%>
11773 if (!<%condVar%>) {
11774 <%preExpMsg%>
11775 omc_fileInfo info = {<%infoArgs(info)%>};
11776 MODELICA_ASSERT(info, <%if acceptMetaModelicaGrammar() then 'MMC_STRINGDATA(<%msgVar%>)' else msgVar%>);
11777 }
11778 >>
11779 */
11780 <<
11781
11782 <%if msgVar then
11783 <<
11784 <%preExpCond%>
11785 if (!<%condVar%>)
11786 {
11787 <%preExpMsg%>
11788 <%match level case ENUM_LITERAL(index=1)
11789 then 'LOGGER_WRITE(<%msgVar%>, LC_MODEL, LL_WARNING);'
11790 else 'throw ModelicaSimulationError(MODEL_EQ_SYSTEM, <%msgVar%>);'
11791 %>
11792 }
11793 >>
11794 else
11795 <<
11796 if (!<%condVar%>)
11797 {
11798 <%preExpCond%>
11799 <%preExpMsg%>
11800 <%match level case ENUM_LITERAL(index=1)
11801 then 'LOGGER_WRITE("Assert in model equation", LC_MODEL, LL_WARNING);'
11802 else 'throw ModelicaSimulationError() << error_id(MODEL_EQ_SYSTEM);'
11803 %>
11804 }
11805 >>
11806 %>
11807 >>
11808
11809 end assertCommon;
11810
11811 ✗ template infoArgs(builtin.SourceInfo info)
11812 ::=
11813 match info
11814 case SOURCEINFO(__) then '"<%fileName%>",<%lineNumberStart%>,<%columnNumberStart%>,<%lineNumberEnd%>,<%columnNumberEnd%>,<%isReadOnly%>'
11815 end infoArgs;
11816
11817
11818 ✗ template underscorePrefix(Boolean builtin) ::=
11819 match builtin
11820 case true then ""
11821 case false then "_"
11822 end underscorePrefix;
11823
11824
11825
11826 ✗ template functionBlock(SimCode simCode)
11827 ::=
11828 let inputVars = spsInputVars(simCode)
11829 let outputVars = spsOutputVars(simCode)
11830 match simCode
11831 case SIMCODE(modelInfo = MODELINFO(__)) then
11832 let modelname = identOfPath(modelInfo.name)
11833 '<?xml version="1.0" encoding="utf-8"?>
11834 <project xmlns="http://www.plcopen.org/xml/tc6_0200">
11835 <fileHeader companyName="" productName="IndraLogic" productVersion="indralogic" creationDateTime="2015-11-19T11:21:48.0837805" />
11836 <contentHeader name="<%modelname%>">
11837 <coordinateInfo>
11838 <fbd>
11839 <scaling x="1" y="1" />
11840 </fbd>
11841 <ld>
11842 <scaling x="1" y="1" />
11843 </ld>
11844 <sfc>
11845 <scaling x="1" y="1" />
11846 </sfc>
11847 </coordinateInfo>
11848 <addData>
11849 <data name="http://www.3s-software.com/plcopenxml/projectinformation" handleUnknown="implementation">
11850 <ProjectInformation />
11851 </data>
11852 </addData>
11853 </contentHeader>
11854 <types>
11855 <dataTypes />
11856 <pous>
11857 <pou name="<%modelname%>" pouType="functionBlock">
11858 <interface>
11859 <inputVars>
11860 <%inputVars%>
11861 </inputVars>
11862 <outputVars>
11863 <%outputVars%>
11864 </outputVars>
11865 <localVars>
11866 <variable name="cycletime">
11867 <type>
11868 <LREAL />
11869 </type>
11870 <initialValue>
11871 <simpleValue value="0.004" />
11872 </initialValue>
11873 </variable>
11874 <variable name="bAlreadyInitialized">
11875 <type>
11876 <BOOL />
11877 </type>
11878 </variable>
11879 <variable name="bErrorOccured">
11880 <type>
11881 <BOOL />
11882 </type>
11883 </variable>
11884 <variable name="controller">
11885 <type>
11886 <DWORD />
11887 </type>
11888 </variable>
11889 <variable name="simdata">
11890 <type>
11891 <DWORD />
11892 </type>
11893 </variable>
11894 </localVars>
11895 </interface>
11896 <body>
11897 <ST>
11898 <xhtml xmlns="http://www.w3.org/1999/xhtml" />
11899 </ST>
11900 </body>
11901 <addData>
11902 <data name="http://www.3s-software.com/plcopenxml/method" handleUnknown="implementation">
11903 <Method name="FB_Init" ObjectId="102788a9-c3a0-4650-9ee8-e340b376c772">
11904 <interface>
11905 <returnType>
11906 <BOOL />
11907 </returnType>
11908 <inputVars>
11909 <variable name="bInitRetains">
11910 <type>
11911 <BOOL />
11912 </type>
11913 </variable>
11914 <variable name="bInCopyCode">
11915 <type>
11916 <BOOL />
11917 </type>
11918 </variable>
11919 </inputVars>
11920 <addData>
11921 <data name="http://www.3s-software.com/plcopenxml/attributes" handleUnknown="implementation">
11922 <Attributes>
11923 <Attribute Name="object_name" Value="FB_Init" />
11924 </Attributes>
11925 </data>
11926 </addData>
11927 </interface>
11928 <body>
11929 <ST>
11930 <xhtml xmlns="http://www.w3.org/1999/xhtml" />
11931 </ST>
11932 </body>
11933 <BuildProperties>
11934 <ExternalImplementation>true</ExternalImplementation>
11935 </BuildProperties>
11936 <addData />
11937 </Method>
11938 </data>
11939 <data name="http://www.3s-software.com/plcopenxml/method" handleUnknown="implementation">
11940 <Method name="FB_Reinit" ObjectId="a9db0581-3a33-4426-9a31-453930d13eb7">
11941 <interface>
11942 <returnType>
11943 <BOOL />
11944 </returnType>
11945 <addData>
11946 <data name="http://www.3s-software.com/plcopenxml/attributes" handleUnknown="implementation">
11947 <Attributes>
11948 <Attribute Name="object_name" Value="FB_Reinit" />
11949 </Attributes>
11950 </data>
11951 </addData>
11952 </interface>
11953 <body>
11954 <ST>
11955 <xhtml xmlns="http://www.w3.org/1999/xhtml" />
11956 </ST>
11957 </body>
11958 <BuildProperties>
11959 <ExternalImplementation>true</ExternalImplementation>
11960 </BuildProperties>
11961 <addData />
11962 </Method>
11963 </data>
11964 <data name="http://www.3s-software.com/plcopenxml/method" handleUnknown="implementation">
11965 <Method name="FB_Exit" ObjectId="c3ba1a8d-f305-4c9b-a3bf-e0c31a544d79">
11966 <interface>
11967 <returnType>
11968 <BOOL />
11969 </returnType>
11970 <inputVars>
11971 <variable name="bInCopyCode">
11972 <type>
11973 <BOOL />
11974 </type>
11975 </variable>
11976 </inputVars>
11977 <addData>
11978 <data name="http://www.3s-software.com/plcopenxml/attributes" handleUnknown="implementation">
11979 <Attributes>
11980 <Attribute Name="object_name" Value="FB_Exit" />
11981 </Attributes>
11982 </data>
11983 </addData>
11984 </interface>
11985 <body>
11986 <ST>
11987 <xhtml xmlns="http://www.w3.org/1999/xhtml" />
11988 </ST>
11989 </body>
11990 <BuildProperties>
11991 <ExternalImplementation>true</ExternalImplementation>
11992 </BuildProperties>
11993 <addData />
11994 </Method>
11995 </data>
11996 <data name="http://www.3s-software.com/plcopenxml/buildproperties" handleUnknown="implementation">
11997 <BuildProperties>
11998 <ExternalImplementation>true</ExternalImplementation>
11999 </BuildProperties>
12000 </data>
12001 <data name="http://www.3s-software.com/plcopenxml/objectid" handleUnknown="discard">
12002 <ObjectId>33609c54-38cc-4f33-9fa0-93f0a8b3a3b3</ObjectId>
12003 </data>
12004 </addData>
12005 </pou>
12006 </pous>
12007 </types>
12008 <instances>
12009 <configurations />
12010 </instances>
12011 <addData>
12012 <data name="http://www.3s-software.com/plcopenxml/projectstructure" handleUnknown="discard">
12013 <ProjectStructure>
12014 <Object Name="PController" ObjectId="33609c54-38cc-4f33-9fa0-93f0a8b3a3b3">
12015 <Object Name="FB_Init" ObjectId="102788a9-c3a0-4650-9ee8-e340b376c772" />
12016 <Object Name="FB_Reinit" ObjectId="a9db0581-3a33-4426-9a31-453930d13eb7" />
12017 <Object Name="FB_Exit" s="c3ba1a8d-f305-4c9b-a3bf-e0c31a544d79" />
12018 </Object>
12019 </ProjectStructure>
12020 </data>
12021 </addData>
12022 </project>
12023 '
12024 end functionBlock;
12025
12026 ✗ template mlpiStructs(SimCode simCode)
12027 ::=
12028 let inputVars = mlpiInputVars(simCode)
12029 let outputVars = mlpiOutputVars(simCode)
12030 match simCode
12031 case SIMCODE(modelInfo = MODELINFO(__)) then
12032 let modelname = identOfPath(modelInfo.name)
12033 '
12034 typedef struct <%modelname%>_struct
12035 {
12036 void* __VFTABLEPOINTER;
12037 <%inputVars%>
12038 <%outputVars%>
12039 MLPI_IEC_LREAL cycletime;
12040 MLPI_IEC_BOOL bAlreadyInitialized;
12041 MLPI_IEC_BOOL bErrorOccured;
12042 ISimController* controller;
12043 ISimData* simdata;
12044 }<%modelname%>_struct;
12045
12046 typedef struct <%modelname%>_Main_struct
12047 {
12048 <%modelname%>_struct* instance; // Declaration of instance pointer
12049 }<%modelname%>_Main_struct;
12050
12051 typedef struct <%modelname%>_FB_Init_struct
12052 {
12053 <%modelname%>_struct* instance; // Declaration of instance pointer
12054 MLPI_IEC_BOOL bInitRetains; // Declaration of predefined method input (no matter if using BOOL8)
12055 MLPI_IEC_BOOL bInCopyCode; // Declaration of predefined method input (no matter if using BOOL8)
12056 MLPI_IEC_BOOL FB_Init; // Declaration of implicit method output (no matter if using BOOL8)
12057 }<%modelname%>_FB_Init_struct;
12058
12059 typedef struct <%modelname%>_FB_Reinit_struct
12060 {
12061 <%modelname%>_struct* instance; // Declaration of instance pointer
12062 MLPI_IEC_BOOL FB_Reinit; // Declaration of implicit method output (no matter if using BOOL8)
12063 }<%modelname%>_FB_Reinit_struct;
12064
12065
12066 typedef struct <%modelname%>_FB_Exit_struct
12067 {
12068 <%modelname%>_struct* instance; // Declaration of instance pointer
12069 MLPI_IEC_BOOL bInCopyCode; // Declaration of predefined method input (no matter if using BOOL8)
12070 MLPI_IEC_BOOL FB_Exit; // Declaration of implicit method output (no matter if using BOOL8)
12071 }<%modelname%>_FB_Exit_struct;
12072 '
12073 end mlpiStructs;
12074
12075
12076
12077 ✗ template ftp_script(SimCode simCode)
12078 ::=
12079 match simCode
12080 case SIMCODE(modelInfo = MODELINFO(__)) then
12081 '
12082 echo option confirm off >> script.tmp
12083 echo open ftp:username:password@ip_address >> script.tmp
12084 echo cd "SYSTEM/bundles" >> script.tmp
12085 echo rm com.boschrexroth.<%fileNamePrefix%> >> script.tmp
12086 echo mkdir com.boschrexroth.<%fileNamePrefix%> >> script.tmp
12087 echo cd com.boschrexroth.<%fileNamePrefix%> >> script.tmp
12088 echo put "com.boschrexroth.<%fileNamePrefix%>\Debug\com.boschrexroth.<%fileNamePrefix%>.out" >> script.tmp
12089 echo exit >> script.tmp
12090 "C:\Program Files (x86)\WINSCP\WinSCP.com" /script=script.tmp
12091 del script.tmp
12092 '
12093 end ftp_script;
12094
12095
12096 ✗ template helpvarlength(SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
12097 ::=
12098 match simCode
12099 case SIMCODE(__) then
12100 <<
12101 0
12102 >>
12103 end helpvarlength;
12104
12105
12106 49 template dimZeroFunc(SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
12107 ::=
12108 match simCode
12109 case SIMCODE(modelInfo = MODELINFO(__)) then
12110 <<
12111 int <%lastIdentOfPath(modelInfo.name)%>::getDimZeroFunc()
12112 {
12113 return _dimZeroFunc;
12114 }
12115 int <%lastIdentOfPath(modelInfo.name)%>::getDimClock()
12116 {
12117 return _dimClock;
12118 }
12119 >>
12120 end dimZeroFunc;
12121
12122
12123 49 template setIntialStatus(SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
12124 ::=
12125 match simCode
12126 case SIMCODE(modelInfo = MODELINFO(__)) then
12127 <<
12128 void <%lastIdentOfPath(modelInfo.name)%>Initialize::setInitial(bool status)
12129 {
12130 _initial = status;
12131 if(_initial)
12132 _callType = IContinuous::DISCRETE;
12133 else
12134 _callType = IContinuous::CONTINUOUS;
12135 }
12136 >>
12137 end setIntialStatus;
12138
12139 49 template getIntialStatus(SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
12140 ::=
12141 match simCode
12142 case SIMCODE(modelInfo = MODELINFO(__)) then
12143 <<
12144 bool <%lastIdentOfPath(modelInfo.name)%>Initialize::initial()
12145 {
12146 return _initial;
12147 }
12148 >>
12149 end getIntialStatus;
12150
12151
12152
12153
12154
12155
12156
12157
12158 49 template functionOnlyZeroCrossing(list<ZeroCrossing> zeroCrossings,Text& varDecls,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
12159 "Generates function in simulation file."
12160 ::=
12161
12162 let zeroCrossingsCode = zeroCrossingsTpl2(zeroCrossings, &varDecls /*BUFD*/, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)
12163 <<
12164 <%zeroCrossingsCode%>
12165 >>
12166 end functionOnlyZeroCrossing;
12167
12168
12169 49 template zeroCrossingsTpl2(list<ZeroCrossing> zeroCrossings, Text &varDecls /*BUFP*/,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
12170 "Generates code for zero crossings."
12171 ::=
12172
12173 (zeroCrossings |> ZERO_CROSSING(__) hasindex i0 =>
12174 zeroCrossingTpl2(i0, relation_, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)
12175 ;separator="\n";empty)
12176 end zeroCrossingsTpl2;
12177
12178
12179 147 template zeroCrossingTpl2(Integer index1, Exp relation, Text &varDecls /*BUFP*/,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
12180 "Generates code for a zero crossing."
12181 ::=
12182 match relation
12183 case RELATION(index=zerocrossingIndex) then
12184 <<
12185 checkConditions(<%zerocrossingIndex%>,false);
12186 >>
12187 end zeroCrossingTpl2;
12188
12189
12190 549 template literalExpConst(Exp lit, Integer index) "These should all be declared static X const"
12191 ::=
12192 let name = '_OMC_LIT<%index%>'
12193 let tmp = '_OMC_LIT_STRUCT<%index%>'
12194 let meta = 'static modelica_metatype const <%name%>'
12195
12196 match lit
12197 case SCONST(__) then
12198
12199 <<
12200 string <%name%>;
12201 >>
12202 case lit as MATRIX(ty=ty as T_ARRAY(__))
12203 case lit as ARRAY(ty=ty as T_ARRAY(__)) then
12204 /*<< previous multi_array
12205 multi_array<<%expTypeShort(ty)%>,<%listLength(ty.dims)%>> <%name%>;
12206 >>*/
12207 <<
12208 StatArrayDim<%listLength(ty.dims)%><<%expTypeShort(ty)%>,<%(ty.dims |> dim as DIM_INTEGER(integer=i) => '<%i%>';separator=",")%> > <%name%>;
12209 >>
12210 case BOX(exp=exp as RCONST(__)) then
12211 <<
12212 double <%name%>;
12213 >>
12214 else CodegenCppCommon.error(sourceInfo(), 'literalExpConst failed: <%ExpressionDumpTpl.dumpExp(lit,"\"")%>')
12215 end literalExpConst;
12216
12217 1209 template literalExpConstArrayVal(Exp lit)
12218 ::=
12219 match lit
12220 case ICONST(__) then integer
12221 case lit as BCONST(__) then if lit.bool then 1 else 0
12222 case RCONST(__) then real
12223 case ENUM_LITERAL(__) then index
12224 case lit as SHARED_LITERAL(__) then '_OMC_LIT<%lit.index%>'
12225 else CodegenCppCommon.error(sourceInfo(), 'literalExpConstArrayVal failed: <%ExpressionDumpTpl.dumpExp(lit,"\"")%>')
12226 end literalExpConstArrayVal;
12227
12228 549 template literalExpConstImpl(Exp lit, Integer index) "These should all be declared static X const"
12229 ::=
12230 let name = '_OMC_LIT<%index%>'
12231 let tmp = '_OMC_LIT_STRUCT<%index%>'
12232 let meta = 'static modelica_metatype const <%name%>'
12233
12234 match lit
12235 case SCONST(__) then
12236 let escstr = Util.escapeModelicaStringToCString(string)
12237 <<
12238 <%name%> = "<%escstr%>";
12239 >>
12240 case lit as MATRIX(ty=ty as T_ARRAY(__))
12241 case lit as ARRAY(ty=ty as T_ARRAY(__)) then
12242 let size = listLength(flattenArrayExpToList(lit))
12243 let ndim = listLength(ty.dims)
12244 let arrayTypeStr = expTypeShort(ty)
12245 let dims = (ty.dims |> dim => dimension(dim,contextOther) ;separator=", ")
12246 let instDimsInit = (ty.dims |> exp =>
12247 dimension(exp,contextOther);separator="][")
12248 let data = flattenArrayExpToList(lit) |> exp => literalExpConstArrayVal(exp) ; separator=", "
12249 match listLength(flattenArrayExpToList(lit))
12250 case 0 then ""
12251 else
12252 /*<< previous multi_array
12253 <%name%>.resize((boost::extents[<%instDimsInit%>]));
12254 <%name%>.reindex(1);
12255 <%arrayTypeStr%> <%name%>_data[]={<%data%>};
12256 //test2
12257 <%name%>.assign(<%name%>_data,<%name%>_data+<%size%>);
12258 >>*/
12259 <<
12260 //arrayflats
12261 <%arrayTypeStr%> <%name%>_data[] = {<%data%>};
12262 assignRowMajorData(<%name%>_data, <%name%>);
12263 >>
12264 case BOX(exp=exp as RCONST(__)) then
12265 <<
12266 <%name%> = <%exp.real%>;
12267 >>
12268 else CodegenCppCommon.error(sourceInfo(), 'literalExpConst failed: <%ExpressionDumpTpl.dumpExp(lit,"\"")%>')
12269 end literalExpConstImpl;
12270
12271 49 template handleEvent(SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
12272 ::=
12273 match simCode
12274 case SIMCODE(__) then
12275 <<
12276 >>
12277 end handleEvent;
12278
12279 ✗ template checkConditions(list<ZeroCrossing> zeroCrossings, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
12280 ::=
12281 let &varDecls = buffer "" /*BUFD*/
12282 let zeroCrossingsCode = checkConditions1(zeroCrossings, &varDecls /*BUFD*/, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
12283 match simCode
12284 case SIMCODE(modelInfo = MODELINFO(__)) then
12285 <<
12286 bool <%lastIdentOfPath(modelInfo.name)%>::checkConditions()
12287 {
12288 _callType = IContinuous::DISCRETE;
12289 return _event_handling->checkConditions(0,true);
12290 _callType = IContinuous::CONTINUOUS;
12291 }
12292 >>
12293 end checkConditions;
12294
12295
12296 49 template getCondition(list<ZeroCrossing> zeroCrossings, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
12297 ::=
12298 let &varDecls = buffer "" /*BUFD*/
12299 let zeroCrossingsCode = checkConditions1(zeroCrossings, &varDecls /*BUFD*/, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
12300 match zeroCrossings
12301 case {} then
12302 match simCode
12303 case SIMCODE(modelInfo = MODELINFO(__)) then
12304 <<
12305 bool <%lastIdentOfPath(modelInfo.name)%>::getCondition(unsigned int index)
12306 {
12307 return false;
12308 }
12309 >>
12310 end match
12311 else
12312 match simCode
12313 case SIMCODE(modelInfo = MODELINFO(__)) then
12314 <<
12315 bool <%lastIdentOfPath(modelInfo.name)%>::getCondition(unsigned int index)
12316 {
12317 <%varDecls%>
12318 switch(index)
12319 {
12320 <%zeroCrossingsCode%>
12321 default:
12322 {
12323 string error = string("Wrong condition index ") + to_string(index);
12324 throw ModelicaSimulationError(EVENT_HANDLING, error);
12325 }
12326 };
12327 }
12328 >>
12329 end match
12330 end getCondition;
12331
12332 49 template checkConditions1(list<ZeroCrossing> zeroCrossings, Text &varDecls /*BUFP*/,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
12333 ::=
12334
12335 (zeroCrossings |> ZERO_CROSSING(__) hasindex i0 =>
12336 checkConditions2(i0, relation_, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
12337 ;separator="\n";empty)
12338 end checkConditions1;
12339
12340 147 template checkConditions2(Integer index1, Exp relation, Text &varDecls, SimCode simCode, Text& extraFuncs,Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
12341 ::=
12342 match relation
12343 case RELATION(index=zerocrossingIndex) then
12344 let &preExp = buffer "" /*BUFD*/
12345 let e1 = daeExp(exp1, contextOther, &preExp, &varDecls,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
12346 let op = zeroCrossingOpFunc(operator)
12347 let e2 = daeExp(exp2, contextOther, &preExp, &varDecls,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
12348 let res = tempDecl("bool", &varDecls /*BUFC*/)
12349 <<
12350 case <%zerocrossingIndex%>:
12351 {
12352 if(_callType & IContinuous::DISCRETE)
12353 {
12354 <%preExp%>
12355 <%res%>=(<%e1%><%op%><%e2%>);
12356 _conditions[<%zerocrossingIndex%>]=<%res%>;
12357 return <%res%>;
12358 }
12359 else
12360 return _conditions[<%zerocrossingIndex%>];
12361 }
12362 >>
12363
12364 end checkConditions2;
12365
12366 49 template handleSystemEvents(list<ZeroCrossing> zeroCrossings, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
12367 ::=
12368
12369 match simCode
12370 case SIMCODE(modelInfo = MODELINFO(__)) then
12371 <<
12372 bool <%lastIdentOfPath(modelInfo.name)%>Mixed::handleSystemEvents(bool* events)
12373 {
12374 _callType = IContinuous::DISCRETE;
12375
12376 bool restart = true;
12377 bool state_vars_reinitialized = false;
12378 bool clock_event_detected = false;
12379
12380 int iter = 0;
12381 while(restart && !(iter++ > 100))
12382 {
12383 bool st_vars_reinit = false;
12384 //iterate and handle all events inside the eventqueue
12385 restart = _event_handling->startEventIteration(st_vars_reinit);
12386 state_vars_reinitialized = state_vars_reinitialized || st_vars_reinit;
12387
12388 saveAll();
12389 }
12390
12391 if (iter > 100 && restart) {
12392 string error = string("Number of event iteration steps exceeded at time: ") + to_string(_simTime);
12393 throw ModelicaSimulationError(EVENT_HANDLING, error);
12394 }
12395 _callType = IContinuous::CONTINUOUS;
12396
12397 return state_vars_reinitialized;
12398 }
12399 >>
12400 end handleSystemEvents;
12401
12402 52 template zeroCrossingOpFunc(Operator op)
12403 "Generates zero crossing function name for operator."
12404 ::=
12405 match op
12406 case LESS(__) then "<"
12407 case GREATER(__) then ">"
12408 case LESSEQ(__) then "<="
12409 case GREATEREQ(__) then ">="
12410 case EQUAL(__) then "=="
12411 case NEQUAL(__) then "!="
12412 end zeroCrossingOpFunc;
12413
12414 49 template giveZeroFunc1(list<ZeroCrossing> zeroCrossings,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
12415 ::=
12416 let &varDecls = buffer "" /*BUFD*/
12417 let &prexp = buffer "" /*BUFD*/
12418 let zeroCrossingsCode = giveZeroFunc2(zeroCrossings, &varDecls /*BUFD*/,prexp, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
12419 match simCode
12420 case SIMCODE(modelInfo = MODELINFO(__)) then
12421 <<
12422 void <%lastIdentOfPath(modelInfo.name)%>::getZeroFunc(double* f)
12423 {
12424 <%varDecls%>
12425 <%prexp%>
12426 <%zeroCrossingsCode%>
12427
12428
12429 }
12430 >>
12431 end giveZeroFunc1;
12432
12433 49 template setConditions(SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
12434 ::=
12435 match simCode
12436 case SIMCODE(modelInfo = MODELINFO(__)) then
12437 <<
12438 void <%lastIdentOfPath(modelInfo.name)%>::setConditions(bool* c)
12439 {
12440 SystemDefaultImplementation::setConditions(c);
12441 }
12442 >>
12443 end setConditions;
12444
12445 49 template getConditions(SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
12446 ::=
12447 match simCode
12448 case SIMCODE(modelInfo = MODELINFO(__)) then
12449 <<
12450 void <%lastIdentOfPath(modelInfo.name)%>::getConditions(bool* c)
12451 {
12452 SystemDefaultImplementation::getConditions(c);
12453 }
12454 void <%lastIdentOfPath(modelInfo.name)%>::getClockConditions(bool* c)
12455 {
12456 SystemDefaultImplementation::getClockConditions(c);
12457 }
12458 >>
12459 end getConditions;
12460
12461 49 template isConsistent(SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
12462 ::=
12463 match simCode
12464 case SIMCODE(modelInfo = MODELINFO(__)) then
12465 <<
12466 bool <%lastIdentOfPath(modelInfo.name)%>::isConsistent()
12467 {
12468 return SystemDefaultImplementation::isConsistent();
12469 }
12470 >>
12471 end isConsistent;
12472
12473 ✗ template saveConditions(SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
12474 ::=
12475 match simCode
12476 case SIMCODE(modelInfo = MODELINFO(__)) then
12477 <<
12478 void <%lastIdentOfPath(modelInfo.name)%>::saveConditions()
12479 {
12480 SystemDefaultImplementation::saveConditions();
12481 }
12482 >>
12483 end saveConditions;
12484
12485 49 template giveZeroFunc2(list<ZeroCrossing> zeroCrossings, Text &varDecls /*BUFP*/,Text &preExp,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
12486 ::=
12487
12488 (zeroCrossings |> ZERO_CROSSING(__) hasindex i0 =>
12489 giveZeroFunc3(i0, relation_, &varDecls /*BUFD*/,&preExp,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
12490 ;separator="\n";empty)
12491 end giveZeroFunc2;
12492
12493 147 template giveZeroFunc3(Integer index1, Exp relation, Text &varDecls /*BUFP*/,Text &preExp ,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
12494 ::=
12495
12496 match relation
12497 case rel as RELATION(index=zerocrossingIndex) then
12498 let e1 = daeExp(exp1, contextOther, &preExp /*BUFC*/, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
12499 let e2 = daeExp(exp2, contextOther, &preExp /*BUFC*/, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
12500 match rel.operator
12501
12502 case LESS(__) then
12503 <<
12504 if(_conditions[<%zerocrossingIndex%>])
12505 f[<%index1%>]=(<%e1%> - _zeroTol - <%e2%>);
12506 else
12507 f[<%index1%>]=(<%e2%> - <%e1%> - _zeroTol);
12508 >>
12509 case LESSEQ(__) then
12510 <<
12511 if(_conditions[<%zerocrossingIndex%>])
12512 f[<%index1%>] = (<%e1%> - _zeroTol - <%e2%>);
12513 else
12514 f[<%index1%>] = (<%e2%> - <%e1%> - _zeroTol);
12515 >>
12516 case GREATER(__) then
12517 <<
12518 if(_conditions[<%zerocrossingIndex%>])
12519 f[<%index1%>] = (<%e2%> - <%e1%> - _zeroTol);
12520 else
12521 f[<%index1%>] = (<%e1%> - _zeroTol - <%e2%>);
12522 >>
12523 case GREATEREQ(__) then
12524 <<
12525 if(_conditions[<%zerocrossingIndex%>])
12526 f[<%index1%>] = (<%e2%> - <%e1%> - _zeroTol);
12527 else
12528 f[<%index1%>] = (<%e1%> - _zeroTol - <%e2%>);
12529 >>
12530 case EQUAL(ty = T_INTEGER(__)) then
12531 <<
12532 f[<%index1%>] = std::abs(<%e2%> - <%e1%>);
12533 >>
12534 case EQUAL(ty = T_REAL(__)) then
12535 <<
12536 f[<%index1%>] = std::abs(<%e2%> - _zeroTol - <%e1%>);
12537 >>
12538 else
12539 <<
12540 CodegenCppCommon.error(sourceInfo(), 'Unsupported relation: <%ExpressionDumpTpl.dumpExp(rel,"\"")%> for <%index1%>')
12541 >>
12542 end match
12543 case CALL(path=IDENT(name="sample"), expLst={_, start, interval}) then
12544 //error(sourceInfo(), ' sample not supported for <%index1%> ')
12545 '//sample for <%index1%>'
12546 else
12547 CodegenCppCommon.error(sourceInfo(), 'Unsupported zero crossing at <%index1%>: <%ExpressionDumpTpl.dumpExp(relation, "\"")%>')
12548 end match
12549 end giveZeroFunc3;
12550
12551 49 template conditionvarZero(list<ZeroCrossing> zeroCrossings,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
12552 ::=
12553 (zeroCrossings |> ZERO_CROSSING(__) hasindex i0 =>
12554 conditionvarZero1(i0, relation_, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)
12555 ;separator="\n";empty)
12556 end conditionvarZero;
12557
12558 147 template conditionvarZero1(Integer index1, Exp relation,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
12559 ::=
12560 match relation
12561 case RELATION(index=zerocrossingIndex) then
12562 <<
12563 bool _condition<%zerocrossingIndex%>;
12564 >>
12565 end conditionvarZero1;
12566
12567 ✗ template saveconditionvar(list<ZeroCrossing> zeroCrossings,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
12568 ::=
12569 (zeroCrossings |> ZERO_CROSSING(__) hasindex i0 =>
12570 saveconditionvar1(i0, relation_, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)
12571 ;separator="\n";empty)
12572 end saveconditionvar;
12573
12574 ✗ template saveconditionvar1(Integer index1, Exp relation,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
12575 ::=
12576 match relation
12577 case RELATION(index=zerocrossingIndex) then
12578 <<
12579 _discrete_events->save(_condition<%zerocrossingIndex%>,_condition<%zerocrossingIndex%>);
12580 >>
12581 end saveconditionvar1;
12582
12583
12584
12585
12586 ✗ template conditionvarSample1(Integer index1, Exp relation, Text &varDecls /*BUFP*/,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
12587 ::=
12588 match relation
12589 case CALL(path=IDENT(name="sample"), expLst={ICONST(integer=index), start, interval}) then
12590 let &preExp = buffer "" /*BUFD*/
12591 <<
12592 bool _condition<%intSub(index, 1)%>;
12593 >>
12594 end conditionvarSample1;
12595
12596 49 template conditionvariable(list<ZeroCrossing> zeroCrossings,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
12597 ::=
12598 let conditionvariable = conditionvarZero(zeroCrossings,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)
12599 /*
12600 <<
12601 <%conditionvariable%>
12602 >>
12603 */
12604 <<
12605 >>
12606 end conditionvariable;
12607
12608
12609
12610 49 template checkForDiscreteEvents(list<ComponentRef> discreteModelVars,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/,Boolean useFlatArrayNotation)
12611 ::=
12612 let &preExp = buffer ""
12613 let &varDecls = buffer ""
12614 let changediscreteVars = (discreteModelVars |> var => match var case CREF_QUAL(__) case CREF_IDENT(__) then
12615 'if (_discrete_events->changeDiscreteVar(<%cref(var, useFlatArrayNotation)%>)) { return true; }'
12616 ;separator="\n")
12617 match simCode
12618 case SIMCODE(modelInfo = MODELINFO(__)) then
12619 <<
12620 bool <%lastIdentOfPath(modelInfo.name)%>::checkForDiscreteEvents()
12621 {
12622 <%varDecls%>
12623 <%preExp%>
12624 <%changediscreteVars%>
12625 return false;
12626 }
12627 >>
12628 end checkForDiscreteEvents;
12629
12630
12631 49 template equationFunctions(list<SimEqSystem> allEquationsPlusWhen, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Context context, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation, Boolean enableMeasureTime)
12632 ::=
12633 let equation_func_calls = (allEquationsPlusWhen |> eq =>
12634 equation_function_create_single_func(eq, context/*BUFC*/, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,"evaluate","", stateDerVectorName, useFlatArrayNotation,enableMeasureTime,false,false, "")
12635 ;separator="\n")
12636 <<
12637 <%equation_func_calls%>
12638 >>
12639 end equationFunctions;
12640
12641 49 template clockedFunctions(list<SimCode.SubPartition> subPartitions, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Context context, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation, Boolean enableMeasureTime)
12642 "Evaluate clocked synchronous equations"
12643 ::=
12644 let className = lastIdentOfPathFromSimCode(simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace)
12645
12646
12647 let parts = subPartitions |> subPartition hasindex i fromindex 1 =>
12648 match subPartition
12649 case SUBPARTITION(__) then
12650 clockedPartFunctions(i, vars, listAppend(equations, removedEquations), simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, contextSimulationDiscrete, stateDerVectorName, useFlatArrayNotation, enableMeasureTime)
12651 ; separator = "\n"
12652
12653
12654
12655
12656
12657 let cases = subPartitions |> subPartition hasindex i fromindex 1 =>
12658 <<
12659 case <%i%>:
12660 evaluateClocked<%i%>(IContinuous::UNDEF_UPDATE);
12661 break;
12662 >>; separator = "\n"
12663 <<
12664
12665 <%parts%>
12666
12667 /* Clocked synchronous equations */
12668 void <%className%>::evaluateClocked(int index)
12669 {
12670 switch (index) {
12671 <%cases%>
12672 default:
12673 throw ModelicaSimulationError(MODEL_EQ_SYSTEM, "Unknown partition");
12674 break;
12675 }
12676 }
12677 >>
12678 end clockedFunctions;
12679
12680 21 template clockedPartFunctions(Integer i, list<tuple<SimCodeVar.SimVar, Boolean>> vars, list<SimEqSystem> equations,SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Context context, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation, Boolean enableMeasureTime)
12681 "Evaluate functions that belong to a clocked partition"
12682 ::=
12683 let className = lastIdentOfPathFromSimCode(simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace)
12684 let funcs = equations |> eq =>
12685 equation_function_create_single_func(eq, context/*BUFC*/, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, "evaluate", "", stateDerVectorName, useFlatArrayNotation, enableMeasureTime, false, false, 'const int clockIndex = <%i%>;<%\n%>')
12686 ; separator="\n"
12687 let funcName = 'evaluateClocked<%i%>'
12688 let funcCalls = (List.partition(equations, 100) |> eqs hasindex i0 =>
12689 createEvaluateWithSplit(i0, context, eqs, funcName,"evaluate", className, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace)
12690 ; separator="\n")
12691 let idx = intAdd(i, -1)
12692 <<
12693 <%funcs%>
12694
12695 void <%className%>::<%funcName%>(const UPDATETYPE command)
12696 {
12697 if (_clockTime[<%idx%>] == -DBL_MAX) {
12698 _clockTime[<%idx%>] = _simTime;
12699 }
12700 if (_simTime > _clockTime[<%idx%>]) {
12701 _clockStart[<%idx%>] = false;
12702 _clockInterval[<%idx%>] = _simTime - _clockTime[<%idx%>];
12703 _clockTime[<%idx%>] = _simTime;
12704 }
12705 <%funcCalls%>
12706 }
12707 >>
12708 end clockedPartFunctions;
12709
12710 48 template createEvaluateAll( list<SimEqSystem> allEquationsPlusWhen, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Context context, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation, Boolean createMeasureTime)
12711 ::=
12712 match simCode
12713 case SIMCODE(modelInfo = MODELINFO(__)) then
12714 let className = lastIdentOfPathFromSimCode(simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)
12715
12716 let equation_all_func_calls = (List.partition(allEquationsPlusWhen, 100) |> eqs hasindex i0 =>
12717 createEvaluateWithSplit(i0, context, eqs, "evaluateAll","evaluate", className, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace)
12718 ;separator="\n")
12719
12720 <<
12721 bool <%className%>::evaluateAll(const UPDATETYPE command)
12722 {
12723 <%if createMeasureTime then generateMeasureTimeStartCode("measuredFunctionStartValues", "evaluateAll", "MEASURETIME_MODELFUNCTIONS") else ""%>
12724 <%createTimeConditionTreatments(timeEventLength(simCode), clockedPartitions)%>
12725
12726 // Evaluate Equations
12727 if (_dimAE > 0)
12728 evaluateDAE(command);
12729 <%equation_all_func_calls%>
12730
12731 <%if createMeasureTime then generateMeasureTimeEndCode("measuredFunctionStartValues", "measuredFunctionEndValues", "(*measureTimeFunctionsArray)[1]", "evaluateAll", "MEASURETIME_MODELFUNCTIONS") else ""%>
12732
12733 return _state_var_reinitialized;
12734 }
12735 >>
12736 end createEvaluateAll;
12737
12738 49 template createTimeConditionTreatments(String numberOfTimeEvents, list<ClockedPartition> clockPartitions)
12739 ::=
12740 let booleanSubClocks = (clockPartitions |> baseClock hasindex i0 =>
12741 booleanSubClockActivation1(absoluteClockIdxForBaseClock(intAdd(i0,1),clockPartitions), baseClock, numberOfTimeEvents)
12742 ;separator="\n")
12743 <<
12744 // treatment of clocks in model as time events
12745 for (int i = <%numberOfTimeEvents%>; i < _dimTimeEvent; i++) {
12746 if (_time_conditions[i]) {
12747 evaluateClocked(i - <%numberOfTimeEvents%> + 1);
12748 <%booleanSubClocks%>
12749 _time_conditions[i] = false; // reset clock after one evaluation
12750 _clockSubactive[i - <%numberOfTimeEvents%>] = false;
12751 }
12752 }
12753 >>
12754 end createTimeConditionTreatments;
12755
12756 12 template booleanSubClockActivation1(Integer absBaseClockIdx, ClockedPartition baseClock, String numberOfTimeEvents)
12757 ::=
12758 match baseClock
12759 case CLOCKED_PARTITION(baseClock = EVENT_CLOCK(__)) then
12760 let subClocks = (subPartitions |> subClock hasindex i0 =>
12761 booleanSubClockActivation2(absBaseClockIdx, i0, subClock, numberOfTimeEvents)
12762 ;separator="\n")
12763 <<
12764 //the subclocks <%absBaseClockIdx%>
12765 <%subClocks%>
12766 >>
12767 else
12768 <<
12769 //no subclock <%absBaseClockIdx%>
12770 >>
12771 end match
12772 end booleanSubClockActivation1;
12773
12774 5 template booleanSubClockActivation2(Integer absClockIdx, Integer subClockIdx, SimCode.SubPartition subPartition, String numberOfTimeEvents)
12775 ::=
12776 if intNe(subClockIdx,0) then
12777 let absSubClockIdx = intAdd(absClockIdx,subClockIdx)
12778 <<
12779 // activate boolean triggered subclock <%absSubClockIdx%> if its base clock <%absClockIdx%> is triggered
12780 if (_time_conditions[<%absClockIdx%> -1+<%numberOfTimeEvents%>]) {
12781 if (_clockTime[<%absSubClockIdx%> -1] == -DBL_MAX)
12782 _clockTime[<%absSubClockIdx%> -1] = _clockTime[<%absClockIdx%> -1];
12783 if (!_clockStart[<%absSubClockIdx%> -1] || _simTime >= _clockTime[<%absSubClockIdx%> -1] + _clockShift[<%absSubClockIdx%> -1] * _clockInterval[<%absClockIdx%> -1])
12784 _time_conditions[<%absSubClockIdx%> -1+<%numberOfTimeEvents%>] = (_simTime >= _clockShift[<%absSubClockIdx%> -1]*_clockInterval[<%absClockIdx%> -1]);
12785 }
12786 >>
12787 else
12788 <<
12789
12790 >>
12791 end booleanSubClockActivation2;
12792
12793 49 template createEvaluateConditions( list<SimEqSystem> allEquationsPlusWhen, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Context context, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
12794 ::=
12795 let className = lastIdentOfPathFromSimCode(simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)
12796
12797 let &eqfuncs = buffer ""
12798 let equation_all_func_calls = (allEquationsPlusWhen |> eq =>
12799 equation_function_call(eq, context, simCode, "evaluate")
12800 ;separator="\n")
12801
12802 <<
12803 bool <%className%>::evaluateConditions(const UPDATETYPE command)
12804 {
12805 return evaluateAll(command);
12806 }
12807 >>
12808 end createEvaluateConditions;
12809
12810 48 template createEvaluate(list<list<SimEqSystem>> odeEquations, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Context context, Boolean createMeasureTime)
12811 ::=
12812 match simCode
12813 case SIMCODE(partitionData = PARTITIONDATA(partitions = partitions, activatorsForPartitions=activatorsForPartitions)) then
12814 //case MODELINFO(vars = vars as SIMVARS(__))
12815 let className = lastIdentOfPathFromSimCode(simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)
12816 let &varDecls = buffer "" /*BUFD*/
12817
12818 let equation_ode_func_calls = if not Flags.isSet(Flags.MULTIRATE_PARTITION) then (List.partition(List.flatten(odeEquations), 100) |> eqs hasindex i0 =>
12819 createEvaluateWithSplit(i0, context, eqs, "evaluateODE", "evaluate",className, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace)
12820 ;separator="\n")
12821 else ( List.intRange(partitionData.numPartitions) |> partIdx =>
12822 createEvaluatePartitions(partIdx, context, List.flatten(odeEquations), listGet(partitions, partIdx),
12823 listGet(activatorsForPartitions,partIdx), className,simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace) ;separator="\n")
12824 <<
12825 void <%className%>::evaluateODE(const UPDATETYPE command)
12826 {
12827 <%if createMeasureTime then generateMeasureTimeStartCode("measuredFunctionStartValues", "evaluateODE", "MEASURETIME_MODELFUNCTIONS") else ""%>
12828 <%varDecls%>
12829 // Evaluate Equations
12830 <%equation_ode_func_calls%>
12831 <%if createMeasureTime then generateMeasureTimeEndCode("measuredFunctionStartValues", "measuredFunctionEndValues", "(*measureTimeFunctionsArray)[0]", "evaluateODE", "MEASURETIME_MODELFUNCTIONS") else ""%>
12832 }
12833 >>
12834 end createEvaluate;
12835
12836 ✗ template createEvaluatePartitions(Integer partIdx, Context context, list<SimEqSystem> odeEquations, list<Integer> partition, list<Integer> activators, String className, SimCode simCode, Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
12837 ::=
12838 let condition = partitionCondition(activators)
12839 let equation_func_calls = (SimCodeCodegenUtil.getSimEqSystemsByIndexLst(partition,odeEquations) |> eq =>
12840 equation_function_call(eq, context, simCode, "evaluate")
12841 ;separator="\n")
12842 <<
12843 // Partition <%partIdx%>
12844 if (<%condition%>)
12845 {
12846 <%equation_func_calls%>
12847 }
12848 >>
12849 end createEvaluatePartitions;
12850
12851 ✗ template partitionCondition(list<Integer> partitions)
12852 ::=
12853 let bVec = (partitions |> part => "_partitionActivation[" + intSub(part,1) + "]" ;separator=" || ")
12854 <<
12855 <%bVec%>
12856 >>
12857 end partitionCondition;
12858
12859 48 template createEvaluateZeroFuncs( list<SimEqSystem> equationsForZeroCrossings, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Context context)
12860 ::=
12861 let className = lastIdentOfPathFromSimCode(simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)
12862 let &varDecls = buffer "" /*BUFD*/
12863
12864 let &eqfuncs = buffer ""
12865 let equation_zero_func_calls = (List.partition(equationsForZeroCrossings, 100) |> eqs hasindex i0 =>
12866 createEvaluateWithSplit(i0, context, eqs, "evaluateZeroFuncs","evaluate", className, simCode, &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)
12867 ;separator="\n")
12868
12869 <<
12870 void <%className%>::evaluateZeroFuncs(const UPDATETYPE command)
12871 {
12872 <%varDecls%>
12873 // Evaluate Equations
12874 <%equation_zero_func_calls%>
12875 }
12876 >>
12877 end createEvaluateZeroFuncs;
12878
12879 117 template createEvaluateWithSplit(Integer sectionIndex, Context context, list<SimEqSystem> sectionEquations, String functionName,String functionCallName, String className, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
12880 ::=
12881 let equation_func_calls = (sectionEquations |> eq =>
12882 equation_function_call(eq, context, simCode, functionCallName)
12883 ;separator="\n")
12884 let &extraFuncs +=
12885 <<
12886 <%\n%>void <%className%>::<%functionName%>_<%sectionIndex%>(const UPDATETYPE command)
12887 {
12888 <%equation_func_calls%>
12889 }
12890 >>
12891 let &extraFuncsDecl +=
12892 <<
12893 void <%functionName%>_<%sectionIndex%>(const UPDATETYPE command);<%\n%>
12894 >>
12895 <<
12896 <%functionName%>_<%sectionIndex%>(command);
12897 >>
12898 end createEvaluateWithSplit;
12899
12900
12901 /*
12902 //! Evaluates only the equations whose indexs are passed to it.
12903 bool <%className%>::evaluate_selective(const std::vector<int>& indices) {
12904 std::vector<int>::const_iterator iter = indices.begin();
12905 int offset;
12906 for( ; iter != indices.end(); ++iter) {
12907 int offset = (*iter) - first_equation_index;
12908 (this->*equations_array[offset])();
12909 }
12910 return false;
12911 }
12912
12913 //! Evaluates only a single equation by index.
12914 bool <%className%>::evaluate_single(const int index) {
12915 int offset = index - first_equation_index;
12916 (this->*equations_array[offset])();
12917 return false;
12918 }
12919 */
12920
12921 /*Ranking: removed from update: if(command & IContinuous::RANKING) checkConditions();*/
12922
12923 49 template labeledDAE(list<String> labels, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation) ::=
12924 if Flags.isSet(Flags.WRITE_TO_BUFFER) then match simCode
12925 case SIMCODE(modelInfo = MODELINFO(__))
12926 then
12927 <<
12928
12929
12930 <%if labels then
12931 <<
12932 label_list_type <%lastIdentOfPath(modelInfo.name)%>::getLabels()
12933 {
12934 label_list_type labels = TUPLE_LIST_OF
12935 <%(labels |> label hasindex index0 => '<%index0%>,&_<%label%>_1_,&_<%label%>_2_') ;separator=" TUPLE_LIST_SEP "%> TUPLE_LIST_END;
12936 return labels;
12937 }
12938 >>
12939 else
12940 <<
12941 label_list_type <%lastIdentOfPath(modelInfo.name)%>::getLabels()
12942 {
12943 return label_list_type();
12944 }
12945 >>%>
12946
12947 void <%lastIdentOfPath(modelInfo.name)%>::setVariables(const ublas::vector<double>& variables,const ublas::vector<double>& variables2)
12948 {
12949 <%setVariables(modelInfo, useFlatArrayNotation)%>
12950 }
12951 >>
12952 end labeledDAE;
12953
12954 ✗ template setVariables(ModelInfo modelInfo, Boolean useFlatArrayNotation)
12955 ::=
12956 match modelInfo
12957 case MODELINFO(vars = vars as SIMVARS(__))
12958 then
12959 <<
12960 <%{
12961
12962 (vars.stateVars |> SIMVAR(__) hasindex myindex =>
12963 '__z[<%index%>]=variables(<%myindex%>);'
12964 ;separator="\n"),
12965 (vars.algVars |> SIMVAR(__) hasindex myindex =>
12966 '<%if stringEq(crefStrForSetVariables(name,useFlatArrayNotation), "") then '' else '<%crefStrForSetVariables(name,useFlatArrayNotation)%>=variables(<%numStatevars(modelInfo)%>+<%myindex%>); '%>'
12967 ;separator="\n"),
12968 (vars.derivativeVars |> SIMVAR(__) hasindex myindex =>
12969 '__zDot[<%index%>]=variables2(<%myindex%>);'
12970 ;separator="\n")}
12971 ;separator="\n"%>
12972 >>
12973 end setVariables;
12974
12975
12976 49 template functionAnalyticJacobians2(list<JacobianMatrix> JacobianMatrices,String modelNamePrefix,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation) "template functionAnalyticJacobians
12977 This template generates source code for all given jacobians."
12978 ::=
12979 let &varDecls = buffer "" /*BUFD*/
12980 let initialjacMats = (JacobianMatrices |> JAC_MATRIX(columns=mat, seedVars=vars, matrixName=name, sparsity=sparsepattern, coloredCols=colorList, maxColorCols=maxColor, jacobianIndex=indexJacobian) =>
12981 initialAnalyticJacobians2(mat, vars, name, sparsepattern, colorList, maxColor, modelNamePrefix); separator="\n")
12982
12983 /*
12984 let jacMats = (JacobianMatrices |> (mat, vars, name, sparsepattern, colorList, maxColor, indexJacobian) =>
12985 generateMatrix(mat, vars, name, modelNamePrefix) ;separator="\n")
12986 */
12987 <<
12988 <%initialjacMats%>
12989 >>
12990
12991 //<%jacMats%>
12992
12993 end functionAnalyticJacobians2;
12994
12995
12996 417 template initialAnalyticJacobians2(list<JacobianColumn> jacobianColumn, list<SimVar> seedVars, String matrixname, list<tuple<Integer,list<Integer>>> sparsepattern, list<list<Integer>> colorList, Integer maxColor, String modelNamePrefix)
12997 "template initialAnalyticJacobians
12998 This template generates source code for functions that initialize the sparse-pattern for a single jacobian.
12999 This is a helper of template functionAnalyticJacobians"
13000 ::=
13001 match seedVars
13002 case {} then
13003 <<
13004 >>
13005 case _ then
13006 match sparsepattern
13007 case _ then
13008 match matrixname
13009 case "A" then
13010 let colorArray = (colorList |> (indexes) hasindex index0 =>
13011 let colorCol = ( indexes |> i_index =>
13012 '_<%matrixname%>ColorOfColumn[<%i_index%>] = <%intAdd(index0,1)%>;'
13013 ;separator="\n")
13014 '<%colorCol%>'
13015 ;separator="\n")
13016 let colorColumns = (colorList |> (indexes) hasindex index0 =>
13017 let columns = (indexes |> i_index hasindex index1 =>
13018 '<%i_index%>'
13019 ;separator=", ")
13020 '_AColumnsOfColor[<%index0%>] = {<%columns%>};'
13021 ;separator="\n")
13022 let dependencies = (sparsepattern |> (index,indexes) hasindex index0 =>
13023 let jacCol = (indexes |> i_index hasindex index1 =>
13024 '<%i_index%>'
13025 ;separator=", ")
13026 '_ADependenciesOfColumn[<%index%>] = {<%jacCol%>};'
13027 ;separator="\n")
13028 <<
13029 if(_AColorOfColumn)
13030 delete [] _AColorOfColumn;
13031 _AColorOfColumn = new int[<%listLength(seedVars)%>];
13032 _AMaxColors = <%maxColor%>;
13033 if(_AColumnsOfColor)
13034 delete [] _AColumnsOfColor;
13035 _AColumnsOfColor = new std::vector<int>[<%listLength(colorList)%>];
13036 if(_ADependenciesOfColumn)
13037 delete [] _ADependenciesOfColumn;
13038 _ADependenciesOfColumn = new std::vector<int>[<%listLength(seedVars)%>];
13039
13040 /* write color array (deprecated) */
13041 <%colorArray%>
13042
13043 /* write color to columns mapping */
13044 <%colorColumns%>
13045
13046 /* write dependencies */
13047 <%dependencies%>
13048 >>
13049 end match
13050 end match
13051 end match
13052 end initialAnalyticJacobians2;
13053
13054 ✗ template symbolName(String modelNamePrefix, String symbolName)
13055 "Creates a unique name for the function"
13056 ::=
13057 modelNamePrefix + "_" + symbolName
13058 end symbolName;
13059
13060
13061 ✗ template functionAnalyticJacobiansHeader(list<JacobianMatrix> JacobianMatrices,String modelNamePrefix) "template functionAnalyticJacobians
13062 This template generates source code for all given jacobians."
13063 ::=
13064 let initialjacMats = (JacobianMatrices |> JAC_MATRIX(columns=mat, seedVars=vars, matrixName=name, sparsity=sparsepattern, coloredCols=colorList, maxColorCols=maxColor, jacobianIndex=indexJacobian) =>
13065 initialAnalyticJacobiansHeader(mat, vars, name, sparsepattern, colorList, maxColor, modelNamePrefix); separator="\n")
13066 /*
13067 let jacMats = (JacobianMatrices |> (mat, vars, name, sparsepattern, colorList, maxColor, indexJacobian) =>
13068 generateMatrix(mat, vars, name, modelNamePrefix) ;separator="\n")
13069 */
13070 <<
13071 <%initialjacMats%>
13072 >>
13073
13074
13075 end functionAnalyticJacobiansHeader;
13076
13077 ✗ template initialAnalyticJacobiansHeader(list<JacobianColumn> jacobianColumn, list<SimVar> seedVars, String matrixname, list<tuple<Integer,list<Integer>>> sparsepattern, list<list<Integer>> colorList, Integer maxColor, String modelNamePrefix)
13078 "template initialAnalyticJacobians
13079 This template generates source code for functions that initialize the sparse-pattern for a single jacobian.
13080 This is a helper of template functionAnalyticJacobians"
13081 ::=
13082 match seedVars
13083 case {} then
13084 <<
13085 >>
13086 case _ then
13087 let help = match sparsepattern
13088
13089 case _ then
13090 match matrixname
13091 case "A" then
13092 <<
13093 public:
13094 void initializeColoredJacobian<%matrixname%>();
13095 >>
13096 end match
13097 end match
13098 <<
13099 <%help%>
13100 >>
13101 end match
13102
13103 end initialAnalyticJacobiansHeader;
13104
13105
13106
13107 ✗ template mkSparseFunctionHeader(String matrixname, String matrixIndex, Integer cref, list<Integer> indexes, String modelNamePrefix)
13108 "generate "
13109 ::=
13110 match matrixname
13111 case "A" then
13112 <<
13113 void initializeColumnsColoredJacobian<%matrixname%>_<%matrixIndex%>();<%\n%>
13114 >>
13115 end match
13116 end mkSparseFunctionHeader;
13117
13118 417 template initialAnalyticJacobians(Integer indexJacobian, list<JacobianColumn> jacobianColumn, list<SimVar> seedVars, String matrixName, list<tuple<Integer,list<Integer>>> sparsepattern, list<list<Integer>> colorList, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace)
13119 "Generates function that initialize the sparse-pattern for a jacobian matrix"
13120 ::=
13121 match simCode
13122 case SIMCODE(modelInfo = MODELINFO(__)) then
13123 let classname = lastIdentOfPath(modelInfo.name)
13124
13125 match seedVars
13126 case {} then ""
13127
13128 case _ then
13129 match colorList
13130 case {} then ""
13131
13132 case _ then
13133 let sp_size_index = lengthListElements(unzipSecond(sparsepattern))
13134 let indexColumn = (jacobianColumn |> JAC_COLUMN(numberOfResultVars=nRows) => '<%nRows%>';separator="\n")
13135 let tmpvarsSize = (jacobianColumn |> JAC_COLUMN(columnVars=vars) => listLength(vars);separator="\n")
13136 let index_ = listLength(seedVars)
13137 let type = getConfigString(MATRIX_FORMAT)
13138 let matrixinit = match type
13139 case ("dense") then
13140 'ublas::zero_matrix<double>(<%indexColumn%>,<%index_%>)'
13141 case ("sparse") then
13142 '<%indexColumn%>,<%index_%>,<%sp_size_index%>'
13143 else "A matrix type is not supported"
13144 end match
13145 <<
13146 , _<%matrixName%>jacobian(<%matrixinit%>)
13147 , _<%matrixName%>jac_y(ublas::zero_vector<double>(<%indexColumn%>))
13148 , _<%matrixName%>jac_tmp(ublas::zero_vector<double>(<%tmpvarsSize%>))
13149 , _<%matrixName%>jac_x(ublas::zero_vector<double>(<%index_%>))
13150 >>
13151 end match
13152 end match
13153 end match
13154 end initialAnalyticJacobians;
13155
13156
13157 49 template functionAnalyticJacobians(ModelInfo modelInfo, list<JacobianMatrix> JacobianMatrices, SimCode simCode, Text& extraFuncs,
13158 Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
13159 "Generates Matrices for Linear Model."
13160 ::=
13161
13162 match modelInfo
13163 case MODELINFO(name=name) then
13164 let classname = lastIdentOfPath(name)
13165 let &varDecls = buffer "" /*BUFD*/
13166
13167 let jacMats = (JacobianMatrices |> JAC_MATRIX(columns=mat, seedVars=vars, matrixName=name, sparsity=sparsepattern, coloredCols=colorList, maxColorCols=maxColor, jacobianIndex=jacIndex, partitionIndex=partIdx) =>
13168 generateMatrix(jacIndex, mat, vars, name, sparsepattern, colorList, maxColor, partIdx, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13169 ;separator="\n\n";empty)
13170 /*let initialStateSetJac = (stateSets |> set hasindex i1 fromindex 0 => (match set
13171 case set as SES_STATESET(__) then
13172 match jacobianMatrix case (_,_,name,_,_,_,_) then
13173 'initialAnalytic<%name%>Jacobian();') ;separator="\n")
13174 let initialJacMats = (JacobianMatrices |> (mat, vars, name, (sparsepattern,_), colorList, maxColor, jacIndex) =>
13175 'initialAnalytic<%name%>Jacobian();'
13176 ;separator="\n";empty)
13177 */
13178
13179 let jacalgloopsystems = (JacobianMatrices |> JAC_MATRIX(columns=mat) hasindex index0 =>
13180 (mat |> JAC_COLUMN(columnEqns=eqs) => generateAlgloopSystems(eqs,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace) ;separator="")
13181 ;separator="")
13182
13183 let jacalgloopsolvers= (JacobianMatrices |> JAC_MATRIX(columns=mat) hasindex index0 =>
13184 (mat |> JAC_COLUMN(columnEqns=eqs) => generateAlgloopSolvers(modelInfo,eqs,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace) ;separator="")
13185 ;separator="")
13186
13187 <<
13188
13189 <%jacMats%>
13190
13191 void <%classname%>Jacobian::initialize()
13192 {
13193 //create Algloopsolver for analytical Jacobians
13194 <%jacalgloopsystems%>
13195 <%jacalgloopsolvers%>
13196 }
13197 >>
13198 end functionAnalyticJacobians;
13199
13200
13201
13202
13203 88 template functionJac(list<SimEqSystem> jacEquations, String matrixName, Integer partIdx, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
13204 "Generates function in simulation file."
13205 ::=
13206 match simCode
13207 case SIMCODE(modelInfo = MODELINFO(__)) then
13208 let classname = lastIdentOfPath(modelInfo.name)
13209 let &varDecls = buffer "" /*BUFD*/
13210 let eqns_ = (jacEquations |> eq =>
13211 equation_(eq, contextJacobian, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13212 ;separator="\n")
13213 <<
13214 void <%classname%>Jacobian::calc<%matrixName%>JacobianColumn()
13215 {
13216 <%if intGt(partIdx, 0) then 'const int clockIndex = <%partIdx%>;'%>
13217 <%varDecls%>
13218 <%eqns_%>
13219 }
13220 >>
13221 end match
13222 end functionJac;
13223
13224
13225 417 template generateMatrix(Integer indexJacobian, list<JacobianColumn> jacobianColumn, list<SimVar> seedVars, String matrixname,
13226 SparsityPattern sparsepattern, list<list<Integer>>colorList, Integer maxColor, Integer partIdx,
13227 SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
13228 "Generates Matrices for Linear Model."
13229 ::=
13230 match simCode
13231 case SIMCODE(modelInfo = MODELINFO(__)) then
13232 generateJacobianMatrix(modelInfo, indexJacobian, jacobianColumn, seedVars, matrixname, sparsepattern, colorList, partIdx, maxColor, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13233 end match
13234 end generateMatrix;
13235
13236
13237 417 template generateJacobianMatrix(ModelInfo modelInfo, Integer indexJacobian, list<JacobianColumn> jacobianColumn, list<SimVar> seedVars,
13238 String matrixName, SparsityPattern sparsepattern, list<list<Integer>> colorList, Integer partIdx,
13239 Integer maxColor, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace,
13240 Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
13241 "Generates Matrices for Linear Model."
13242 ::=
13243 match simCode
13244 case SIMCODE(modelInfo = MODELINFO(__)) then
13245 let type = getConfigString(MATRIX_FORMAT)
13246 let matrixreturntype = match type
13247 case ("dense") then
13248 "matrix_t"
13249 case ("sparse") then
13250 "sparsematrix_t"
13251 else "A matrix type is not supported"
13252 end match
13253 let classname = lastIdentOfPath(modelInfo.name)
13254 match jacobianColumn
13255 case {} then
13256 <<
13257 void <%classname%>Jacobian::calc<%matrixName%>JacobianColumn()
13258 {
13259 throw ModelicaSimulationError(MATH_FUNCTION, "Symbolic jacobians not is activated");
13260
13261 }
13262
13263 <%matrixreturntype%>& <%classname%>Jacobian::get<%matrixName%>Jacobian()
13264 {
13265 throw ModelicaSimulationError(MATH_FUNCTION, "Symbolic jacobians not is activated");
13266 }
13267 >>
13268 case _ then
13269 match colorList
13270 case {} then
13271 <<
13272 void <%classname%>Jacobian::calc<%matrixName%>JacobianColumn()
13273 {
13274 throw ModelicaSimulationError(MATH_FUNCTION, "Symbolic jacobians not is activated");
13275 }
13276
13277 <%matrixreturntype%>& <%classname%>Jacobian::get<%matrixName%>Jacobian()
13278 {
13279 throw ModelicaSimulationError(MATH_FUNCTION, "Symbolic jacobians not is activated");
13280 }
13281 >>
13282 case _ then
13283 let jacMats = (jacobianColumn |> JAC_COLUMN(columnEqns=eqs) =>
13284 functionJac(eqs, matrixName, partIdx, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13285 ;separator="\n")
13286 let indexColumn = (jacobianColumn |> JAC_COLUMN(numberOfResultVars=nRows) =>
13287 '<%nRows%>'
13288 ;separator="\n")
13289 let eqsCount = (jacobianColumn |> JAC_COLUMN(columnEqns=eqs) =>
13290 listLength(eqs)
13291 ;separator="+")
13292 let jacvals = if stringEq(eqsCount, "0") then '' else
13293 (sparsepattern |> (index,indexes) hasindex index0 =>
13294 let jaccol = ( indexes |> i_index hasindex index1 =>
13295 (match indexColumn case "1" then '_<%matrixName%>jacobian(0,<%index%>) = _<%matrixName%>jac_y(0);'
13296 else '_<%matrixName%>jacobian(<%i_index%>,<%index%>) = _<%matrixName%>jac_y(<%i_index%>);'
13297 )
13298 ;separator="\n")
13299 <<
13300 <%if intEq(index0, 1) then 'SystemLockFreeVariables slfv(this);'%>
13301 _<%matrixName%>jac_x(<%index0%>) = 1;
13302 calc<%matrixName%>JacobianColumn();
13303 _<%matrixName%>jac_x.clear();
13304 <%jaccol%>
13305 >>
13306 ;separator="\n")
13307 <<
13308 <%jacMats%>
13309
13310 <%matrixreturntype%>& <%classname%>Jacobian::get<%matrixName%>Jacobian()
13311 {
13312 /*Index <%indexJacobian%>*/
13313 <%jacvals%>
13314 return _<%matrixName%>jacobian;
13315 }
13316 >>
13317
13318 /*
13319 (match indexColumn case "1" then ' _<%matrixName%>jacobian(<%crefWithoutIndexOperator(cref)%>$pDER<%matrixName%>$indexdiff,0) = _<%matrixName%>jac_y(0); //1 <%cref(cref)%>'
13320 else ' _<%matrixName%>jacobian(<%index0%>,<%crefWithoutIndexOperator(cref)%>$pDER<%matrixName%>$indexdiff) = _<%matrixName%>jac_y(<%crefWithoutIndexOperator(cref)%>$pDER<%matrixName%>$indexdiff);//2 <%cref(cref)%>'
13321
13322 */
13323 end generateJacobianMatrix;
13324
13325
13326 ✗ template variableDefinitionsJacobians_skip(list<JacobianMatrix> JacobianMatrices, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text &jacobianVarsInit, Boolean createDebugCode)
13327 "Skips generation of defines for jacobian vars."
13328 ::=
13329 ''
13330 end variableDefinitionsJacobians_skip;
13331
13332
13333 ✗ template variableDefinitionsJacobians(list<JacobianMatrix> JacobianMatrices, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text &jacobianVarsInit, Boolean createDebugCode)
13334 "Generates defines for jacobian vars."
13335 ::=
13336 let analyticVars = (JacobianMatrices |> JAC_MATRIX(columns=jacColumn, seedVars=vars, matrixName=name, jacobianIndex=jacIndex) =>
13337 let varsDef = variableDefinitionsJacobians2(jacIndex, jacColumn, seedVars, name, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, &jacobianVarsInit, createDebugCode)
13338 <<
13339 <%varsDef%>
13340 >>
13341 ;separator="\n";empty)
13342
13343 <<
13344 /* Jacobian Variables */
13345 <%analyticVars%>
13346 >>
13347 end variableDefinitionsJacobians;
13348
13349 ✗ template variableDefinitionsJacobians2(Integer indexJacobian, list<JacobianColumn> jacobianColumn, list<SimVar> seedVars, String name, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text& jacobianVarsInit, Boolean createDebugCode)
13350 "Generates Matrices for Linear Model."
13351 ::=
13352 let seedVarsResult = (seedVars |> var hasindex index0 =>
13353 jacobianVarDefine(var, indexJacobian, index0, name, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, &jacobianVarsInit, createDebugCode)
13354 ;separator="\n";empty)
13355 let columnVarsResult = (jacobianColumn |> JAC_COLUMN(columnVars=vars) =>
13356 (vars |> var hasindex index0 => jacobianVarDefine(var, indexJacobian, index0, name, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, &jacobianVarsInit, createDebugCode)
13357 ;separator="\n";empty)
13358 ;separator="\n\n")
13359
13360 <<
13361 <%seedVarsResult%>
13362 <%columnVarsResult%>
13363 >>
13364 end variableDefinitionsJacobians2;
13365
13366
13367 ✗ template jacobianVarDefine(SimVar simVar, Integer indexJac, Integer index0, String matrixName, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text& jacobianVarsInit, Boolean createDebugCode)
13368 ""
13369 ::=
13370 match simVar
13371 case SIMVAR(aliasvar=NOALIAS(),name=name,index=index) then
13372 let jacobianVar = '_<%crefToCStr(name, false)%>'
13373 let typeName = match varKind
13374 case BackendDAE.JAC_VAR() then 'jac_y(<%index%>)'
13375 case BackendDAE.JAC_TMP_VAR() then 'jac_tmp(<%index%>)'
13376 case BackendDAE.SEED_VAR() then 'jac_x(<%index0%>)'
13377 else 'UNKNOWN KIND'
13378 let &jacobianVarsInit += if createDebugCode then ', <%jacobianVar%>(_<%matrixName%><%typeName%>)<%\n%>'
13379 if createDebugCode then
13380 'double& <%jacobianVar%>;' else
13381 '#define <%jacobianVar%> _<%matrixName%><%typeName%>'
13382 end match
13383 end jacobianVarDefine;
13384
13385
13386 1142 template equationAlgorithm(SimEqSystem eq, Context context,Text &varDecls /*BUFP*/,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
13387 "Generates an equation that is an algorithm."
13388 ::=
13389 match eq
13390 case SES_ALGORITHM(__)
13391 case SES_INVERSE_ALGORITHM(__) then
13392 (statements |> stmt =>
13393 algStatement(stmt, context, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13394 ;separator="\n")
13395 end equationAlgorithm;
13396 //Generation of Algorithm section
13397 5102 template algStatement(DAE.Statement stmt, Context context, Text &varDecls,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
13398 ::=
13399 let res = match stmt
13400 case s as STMT_ASSIGN(exp1=PATTERN(__)) then "STMT_ASSIGN Pattern not supported yet"
13401 case s as STMT_ASSIGN(__) then algStmtAssign(s, context, &varDecls /*BUFD*/,simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13402 case s as STMT_ASSIGN_ARR(__) then algStmtAssignArr(s, context, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13403 case s as STMT_TUPLE_ASSIGN(__) then algStmtTupleAssign(s, context, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13404 case s as STMT_IF(__) then algStmtIf(s, context, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13405 case s as STMT_FOR(__) then algStmtFor(s, context, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13406 case s as STMT_WHILE(__) then algStmtWhile(s, context, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13407 case s as STMT_ASSERT(__) then algStmtAssert(s, context, &varDecls ,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13408 case s as STMT_TERMINATE(__) then algStmtTerminate(s, context, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13409 case s as STMT_WHEN(__) then algStmtWhen(s, context, &varDecls ,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13410 case s as STMT_BREAK(__) then 'break;<%\n%>'
13411 case s as STMT_FAILURE(__) then "STMT FAILURE"
13412 case s as STMT_RETURN(__) then "break;/*Todo stmt return*/"
13413 case s as STMT_NORETCALL(__) then algStmtNoretcall(s, context, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13414 case s as STMT_REINIT(__) then algStmtReinit(s, context, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13415 else CodegenCppCommon.error(sourceInfo(), 'ALG_STATEMENT NYI')
13416
13417 <<
13418 <%modelicaLine(ElementSource.getElementSourceFileInfo(getStatementSource(stmt)))%>
13419 <%res%>
13420 <%endModelicaLine()%>
13421 >>
13422 end algStatement;
13423
13424 15 template algStmtWhile(DAE.Statement stmt, Context context, Text &varDecls /*BUFP*/,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
13425 "Generates a while algorithm statement."
13426 ::=
13427 match stmt
13428 case STMT_WHILE(__) then
13429 let &preExp = buffer "" /*BUFD*/
13430 let var = daeExp(exp, context, &preExp /*BUFC*/, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13431 <<
13432 while (1) {
13433 <%preExp%>
13434 if (!<%var%>) break;
13435 <%statementLst |> stmt => algStatement(stmt, context, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation) ;separator="\n"%>
13436 }
13437 >>
13438 end algStmtWhile;
13439
13440 ✗ template algStmtTerminate(DAE.Statement stmt, Context context, Text &varDecls /*BUFP*/,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
13441 "Generates an assert algorithm statement."
13442 ::=
13443 match stmt
13444 case STMT_TERMINATE(__) then
13445 let &preExp = buffer "" /*BUFD*/
13446 let msgVar = daeExp(msg, context, &preExp /*BUFC*/, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13447 <<
13448 <%preExp%>
13449 _terminate=true;
13450 >>
13451 end algStmtTerminate;
13452
13453 4776 template modelicaLine(builtin.SourceInfo info)
13454 ::=
13455 match info
13456 case SOURCEINFO(columnNumberStart=0) then "/* Dummy Line */"
13457 else <<
13458 <% if Flags.isSet(Flags.GEN_DEBUG_SYMBOLS) then '/*#modelicaLine <%infoStr(info)%>*/'%>
13459 >>
13460 end modelicaLine;
13461
13462 5102 template endModelicaLine()
13463 ::=
13464 <<
13465 <% if Flags.isSet(Flags.GEN_DEBUG_SYMBOLS) then "/*#endModelicaLine*/"%>
13466 >>
13467 end endModelicaLine;
13468
13469 3435 template algStmtAssign(DAE.Statement stmt, Context context, Text &varDecls, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
13470 "Generates an assigment algorithm statement."
13471 ::=
13472 match stmt
13473 case STMT_ASSIGN(exp1=CREF(componentRef=WILD(__)), exp=e) then
13474 let &preExp = buffer "" /*BUFD*/
13475 let expPart = daeExp(e, context, &preExp /*BUFC*/, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13476 <<
13477 <%preExp%>
13478 >>
13479 case STMT_ASSIGN(exp1=CREF(ty = T_FUNCTION_REFERENCE_VAR(__)))
13480 case STMT_ASSIGN(exp1=CREF(ty = T_FUNCTION_REFERENCE_FUNC(__))) then
13481 let &preExp = buffer "" /*BUFD*/
13482 let varPart = daeExpCref(true, exp1, context, &preExp /*BUFC*/, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13483 let expPart = daeExp(exp, context, &preExp /*BUFC*/, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13484 <<
13485 <%preExp%>
13486 <%varPart%> = (modelica_fnptr) <%expPart%>;
13487 >>
13488 /* Records need to be traversed, assigning each component by itself */
13489 case STMT_ASSIGN(exp1=CREF(componentRef=cr,ty = T_COMPLEX(varLst = varLst, complexClassType=RECORD(__)))) then
13490 let &preExp = buffer ""
13491 let rec = daeExp(exp, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13492 <<
13493 <%preExp%>
13494 <% varLst |> var as TYPES_VAR(__) =>
13495 let varNameStr = CodegenCppCommon.crefStr(makeUntypedCrefIdent(var.name))
13496 match var.ty
13497 case T_ARRAY(__) then
13498 copyArrayData(var.ty, '<%rec%>.<%varNameStr%>', appendStringCref(var.name, cr), context)
13499 else
13500 let varPart = contextCref(appendStringCref(var.name, cr), context, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13501 '<%varPart%> = <%rec%>.<%varNameStr%>;'
13502 ; separator="\n"
13503 %>
13504 >>
13505 case STMT_ASSIGN(exp1=CALL(path=path,expLst=expLst,attr=CALL_ATTR(ty= T_COMPLEX(varLst = varLst, complexClassType=RECORD(__))))) then
13506 let &preExp = buffer ""
13507 let rec = daeExp(exp, context, &preExp, &varDecls,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13508 <<
13509 <%preExp%>
13510 <% varLst |> var as TYPES_VAR(__) hasindex i1 fromindex 1 =>
13511 let re = daeExp(listGet(expLst,i1), context, &preExp, &varDecls,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13512 '<%re%> = <%rec%>.<%CodegenCppCommon.crefStr(makeUntypedCrefIdent(var.name))%>;'
13513 ; separator="\n"
13514 %>
13515 >>
13516 case STMT_ASSIGN(exp1=CREF(__)) then
13517 let &preExp = buffer "" /*BUFD*/
13518 let varPart = daeExpCref(true, exp1, context, &preExp /*BUFC*/, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13519 let expPart = daeExp(exp, context, &preExp /*BUFC*/, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13520 <<
13521 <%preExp%>
13522 <%varPart%> = <%expPart%>;
13523 >>
13524 case STMT_ASSIGN(exp1=exp1 as ASUB(__),exp=val) then
13525 (match expTypeFromExpShort(exp)
13526 case "metatype" then
13527 // MetaModelica Array
13528 (match exp case ASUB(exp=arr, sub={idx}) then
13529 let &preExp = buffer ""
13530 let arr1 = daeExp(arr, context, &preExp /*BUFC*/, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13531 let idx1 = daeSubscript(idx, context, &preExp /*BUFC*/, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13532 let val1 = daeExp(val, context, &preExp /*BUFC*/, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13533 <<
13534 <%preExp%>
13535 arrayUpdate(<%arr1%>,<%idx1%>,<%val1%>);
13536 >>)
13537 // Modelica Array
13538 else
13539 let &preExp = buffer "" /*BUFD*/
13540 let varPart = daeExpAsub(exp1, context, &preExp /*BUFC*/, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13541 let expPart = daeExp(val, context, &preExp /*BUFC*/, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13542 <<
13543 <%preExp%>
13544 <%varPart%> = <%expPart%>;
13545 >>
13546 )
13547 case STMT_ASSIGN(__) then
13548 let &preExp = buffer "" /*BUFD*/
13549 let expPart1 = daeExp(exp1, context, &preExp /*BUFC*/, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13550 let expPart2 = daeExp(exp, context, &preExp /*BUFC*/, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13551 <<
13552 <%preExp%>
13553 <%expPart1%> = <%expPart2%>;
13554 >>
13555 end algStmtAssign;
13556
13557 1 template copyArrayData(DAE.Type ty, String exp, DAE.ComponentRef cr,
13558 Context context)
13559
13560 ::=
13561 let type = expTypeShort(ty)
13562 let cref = contextArrayCref(cr, context)
13563 '<%cref%>.assign(<%exp%>);'
13564 end copyArrayData;
13565
13566 5 template algStmtWhen(DAE.Statement when, Context context, Text &varDecls /*BUFP*/,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
13567 "Generates a when algorithm statement."
13568 ::=
13569 match context
13570 case SIMULATION_CONTEXT(__) then
13571 match when
13572 case STMT_WHEN(__) then
13573 let &varDeclsCref = buffer "" /*BUFD*/
13574 let helpIf = (conditions |> e => ' || (<%cref1(e, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, context, varDeclsCref,stateDerVectorName,useFlatArrayNotation)%> && !_discrete_events->pre(<%cref1(e, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, context, varDeclsCref, stateDerVectorName, useFlatArrayNotation)%>))')
13575 let statements = (statementLst |> stmt =>
13576 algStatement(stmt, context, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13577 ;separator="\n")
13578 let else = algStatementWhenElse(elseWhen, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,context, stateDerVectorName, useFlatArrayNotation)
13579 <<
13580 if (0<%helpIf%>) {
13581 <%statements%>
13582 }
13583 <%else%>
13584 >>
13585 end match
13586 end match
13587 end algStmtWhen;
13588 4 template algStatementWhenElse(Option<DAE.Statement> stmt, Text &varDecls /*BUFP*/,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace,Context context, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
13589 "Helper to algStmtWhen."
13590 ::=
13591 match stmt
13592 case SOME(when as STMT_WHEN(__)) then
13593 let &varDeclsCref = buffer "" /*BUFD*/
13594 let elseCondStr = (when.conditions |> e => ' || (<%cref1(e, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, context, varDeclsCref, stateDerVectorName, useFlatArrayNotation)%> && !_discrete_events->pre(<%cref1(e, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, context, varDeclsCref, stateDerVectorName, useFlatArrayNotation)%>))')
13595 <<
13596 else if (0<%elseCondStr%>) {
13597 <% when.statementLst |> stmt => algStatement(stmt, contextSimulationDiscrete,&varDecls,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13598 ;separator="\n"%>
13599 }
13600 <%algStatementWhenElse(when.elseWhen, &varDecls,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,context, stateDerVectorName, useFlatArrayNotation)%>
13601 >>
13602 end algStatementWhenElse;
13603
13604 1166 template algStmtAssert(DAE.Statement stmt, Context context, Text &varDecls,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
13605 "Generates an assert algorithm statement."
13606 ::=
13607 match stmt
13608 case STMT_ASSERT(source=SOURCE(info=info)) then
13609 assertCommon(cond, msg, level, context, &varDecls, info,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13610 end algStmtAssert;
13611
13612
13613 ✗ template algStmtReinit(DAE.Statement stmt, Context context, Text &varDecls /*BUFP*/,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
13614 "Generates an assigment algorithm statement."
13615 ::=
13616 match stmt
13617 case STMT_REINIT(__) then
13618 let &preExp = buffer "" /*BUFD*/
13619 let expPart1 = daeExp(var, context, &preExp /*BUFC*/, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13620 let expPart2 = daeExp(value, context, &preExp /*BUFC*/, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13621 /*
13622 <<
13623 $P$PRE<%expPart1%> = <%expPart1%>;
13624 <%preExp%>
13625 <%expPart1%> = <%expPart2%>;
13626 >>
13627 */
13628 <<
13629 _discrete_events->save(<%expPart1%>,<%expPart1%>);
13630 <%preExp%>
13631 <%expPart1%> = <%expPart2%>;
13632 >>
13633 end algStmtReinit;
13634
13635 230 template algStmtIf(DAE.Statement stmt, Context context, Text &varDecls /*BUFP*/,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
13636 "Generates an if algorithm statement."
13637 ::=
13638 match stmt
13639 case STMT_IF(__) then
13640 let &preExp = buffer "" /*BUFD*/
13641 let condExp = daeExp(exp, context, &preExp /*BUFC*/, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13642 <<
13643 <%preExp%>
13644 if <%encloseInParantheses(condExp)%> {
13645 <%statementLst |> stmt => algStatement(stmt, context, &varDecls /*BUFD*/, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation); separator="\n"%>
13646 }
13647 <%elseExpr(else_, context,&preExp , &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>
13648 >>
13649 end algStmtIf;
13650
13651 298 template elseExpr(DAE.Else it, Context context, Text &preExp, Text &varDecls,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace,Text stateDerVectorName /*=__zDot*/,Boolean useFlatArrayNotation) ::=
13652 match it
13653 case NOELSE(__) then ""
13654 case ELSEIF(__) then
13655 let &preExp = buffer ""
13656 let condExp = daeExp(exp, context, &preExp, &varDecls,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13657 <<
13658 else {
13659 <%preExp%>
13660 if <%encloseInParantheses(condExp)%> {
13661 <%statementLst |> it => algStatement(it, context, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation); separator="\n"%>
13662 }
13663 <%elseExpr(else_, context, &preExp, &varDecls, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)%>
13664 }
13665 >>
13666 case ELSE(__) then
13667 <<
13668 else {
13669 <%statementLst |> it => algStatement(it, context, &varDecls,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13670 ;separator="\n"%>
13671 }
13672 >>
13673 end elseExpr;
13674
13675 20 template algStmtFor(DAE.Statement stmt, Context context, Text &varDecls /*BUFP*/,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
13676 "Generates a for algorithm statement."
13677 ::=
13678 match stmt
13679 case s as STMT_FOR(range=rng as RANGE(__)) then
13680 algStmtForRange(s, context, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13681 case s as STMT_FOR(__) then
13682 algStmtForGeneric(s, context, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13683 end algStmtFor;
13684
13685
13686 ✗ template algStmtForGeneric(DAE.Statement stmt, Context context, Text &varDecls /*BUFP*/,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
13687 "Generates a for algorithm statement where range is not RANGE."
13688 ::=
13689 match stmt
13690 case STMT_FOR(__) then
13691 let iterType = expType(type_, iterIsArray)
13692 let arrayType = expTypeShort(type_)
13693
13694
13695 let stmtStr = (statementLst |> stmt =>
13696 algStatement(stmt, context, &varDecls,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation) ;separator="\n")
13697 algStmtForGeneric_impl(range, iter, iterType, arrayType, iterIsArray, stmtStr,
13698 context, &varDecls,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13699 end algStmtForGeneric;
13700
13701
13702 ✗ template algStmtForGeneric_impl(Exp exp, Ident iterator, String type,
13703 String arrayType, Boolean iterIsArray, Text &body, Context context, Text &varDecls,SimCode simCode, Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
13704 "The implementation of algStmtForGeneric, which is also used by daeExpReduction."
13705 ::=
13706 let iterName = contextIteratorName(iterator, context)
13707 //let stateVar = if not acceptMetaModelicaGrammar() then tempDecl("state", &varDecls)
13708 //let tvar = tempDecl("int", &varDecls)
13709 //let ivar = tempDecl(type, &varDecls)
13710 let &preExp = buffer ""
13711 let &tmpVar = buffer ""
13712 let evar = daeExp(exp, context, &preExp, &tmpVar,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13713 //let stmtStuff = if iterIsArray then
13714 // 'simple_index_alloc_<%type%>1(&<%evar%>, <%tvar%>, &<%ivar%>);'
13715 // else
13716 // '<%iterName%> = *(<%arrayType%>_element_addr1(&<%evar%>, 1, <%tvar%>));'
13717 <<
13718 <%preExp%>
13719 FOREACH(<%type%> <%iterName%>, <%evar%>) {
13720 <%body%>
13721 }
13722 >>
13723
13724 end algStmtForGeneric_impl;
13725
13726 31 template algStmtNoretcall(DAE.Statement stmt, Context context, Text &varDecls /*BUFP*/,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
13727 "Generates a no return call algorithm statement."
13728 ::=
13729 match stmt
13730 case STMT_NORETCALL(__) then
13731 let &preExp = buffer "" /*BUFD*/
13732 let expPart = daeExp(exp, context, &preExp /*BUFC*/, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13733 <<
13734 //No retcall
13735 <%preExp%>
13736 <%expPart%>;
13737 >>
13738 end algStmtNoretcall;
13739
13740
13741 20 template algStmtForRange(DAE.Statement stmt, Context context, Text &varDecls /*BUFP*/,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
13742 "Generates a for algorithm statement where range is RANGE."
13743 ::=
13744 match stmt
13745 case STMT_FOR(range=rng as RANGE(__)) then
13746 let identType = expType(type_, iterIsArray)
13747 let identTypeShort = expTypeShort(type_)
13748 let stmtStr = (statementLst |> stmt => algStatement(stmt, context, &varDecls,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13749 ;separator="\n")
13750 algStmtForRange_impl(rng, iter, identType, identTypeShort, stmtStr, context, &varDecls,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13751 end algStmtForRange;
13752
13753
13754 20 template algStmtForRange_impl(Exp range, Ident iterator, String type, String shortType, Text body, Context context, Text &varDecls,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
13755 "The implementation of algStmtForRange, which is also used by daeExpReduction."
13756 ::=
13757 match range
13758 case RANGE(__) then
13759 let type = expTypeShort(ty)
13760 let iterVar = tempDecl('int', &varDecls)
13761 let iterName = contextIteratorName(iterator, context)
13762 let startVar = tempDecl(type, &varDecls)
13763 let stepVar = tempDecl(type, &varDecls)
13764 let stopVar = tempDecl(type, &varDecls)
13765 let &preExp = buffer ""
13766 let startValue = daeExp(start, context, &preExp, &varDecls,simCode, &extraFuncs ,&extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13767 let stepValue = match step case SOME(eo) then
13768 daeExp(eo, context, &preExp, &varDecls,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13769 else
13770 '1'
13771 let stopValue = daeExp(stop, context, &preExp, &varDecls,simCode, &extraFuncs ,&extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13772 <<
13773 <%preExp%>
13774 <%startVar%> = <%startValue%>; <%stepVar%> = <%stepValue%>; <%stopVar%> = <%stopValue%>;
13775 if(!<%stepVar%>)
13776 {
13777
13778
13779 }
13780 else if(!(((<%stepVar%> > 0) && (<%startVar%> > <%stopVar%>)) || ((<%stepVar%> < 0) && (<%startVar%> < <%stopVar%>))))
13781 {
13782 <%type%> <%iterName%>;
13783 int <%iterVar%>_end = <%if stringEq(type, "int") then
13784 '(<%stopVar%> - <%startVar%>) / <%stepVar%>;'
13785 else '(int)((<%stopVar%> - <%startVar%>) / <%stepVar%> + 1e-10);'%>
13786 for (<%iterVar%> = 0; <%iterVar%> <= <%iterVar%>_end; <%iterVar%>++) {
13787 <%iterName%> = <%startVar%> + <%iterVar%> * <%stepVar%>;
13788 <%body%>
13789 }
13790 }
13791 >> /* else we're looping over a zero-length range */
13792 end algStmtForRange_impl;
13793
13794
13795 28 template algStmtAssignArr(DAE.Statement stmt, Context context,
13796 Text &varDecls /*BUFP*/,SimCode simCode, Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
13797 "Generates an array assigment algorithm statement."
13798 ::=
13799 match stmt
13800 case STMT_ASSIGN_ARR(exp=e, lhs=lhsexp as CREF(componentRef=cr), type_=t) then
13801 let &preExp = buffer "" /*BUFD*/
13802 let expPart = daeExp(e, context, &preExp /*BUFC*/, &varDecls /*BUFD*/, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13803 let dest = daeExpCref(true, lhsexp, context, &preExp /*BUFC*/, &varDecls /*BUFD*/, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13804 <<
13805 <%preExp%>
13806 <%dest%>.assign(<%expPart%>);
13807 >>
13808 end algStmtAssignArr;
13809
13810
13811 49 template functionInitDelay(DelayedExpression delayed,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
13812 "Generates function in simulation file."
13813 ::=
13814 let &varDecls = buffer "" /*BUFD*/
13815 let &preExp = buffer "" /*BUFD*/
13816 let delay_id = (match delayed case DELAYED_EXPRESSIONS(__) then (delayedExps |> (id, (e, d, delayMax)) =>
13817 '<%id%>';separator=" LIST_SEP "))
13818 let delay_max = (match delayed case DELAYED_EXPRESSIONS(__) then (delayedExps |> (id, (e, d, delayMax)) =>
13819 let delayExpMax = daeExp(delayMax, contextSimulationNonDiscrete, &preExp /*BUFC*/, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13820 '<%delayExpMax%>';separator=" LIST_SEP "))
13821 if delay_id then
13822 <<
13823 //init delay expressions
13824 <%varDecls%>
13825 <%preExp%>
13826 vector<double> delay_max = LIST_OF <%delay_max%> LIST_END;
13827 vector<unsigned int> delay_ids = LIST_OF <%delay_id%> LIST_END;
13828 intDelay(delay_ids, delay_max);
13829 >>
13830 else " "
13831 end functionInitDelay;
13832
13833
13834 49 template functionStoreDelay(DelayedExpression delayed,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
13835 "Generates function in simulation file."
13836 ::=
13837 let &varDecls = buffer "" /*BUFD*/
13838 let storePart = (match delayed case DELAYED_EXPRESSIONS(__) then (delayedExps |> (id, (e, d, delayMax)) =>
13839 let &preExp = buffer "" /*BUFD*/
13840 let eRes = daeExp(e, contextSimulationNonDiscrete,
13841 &preExp /*BUFC*/, &varDecls /*BUFD*/,simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, stateDerVectorName, useFlatArrayNotation)
13842 <<
13843
13844 <%preExp%>
13845 storeDelay(<%id%>, <%eRes%>,time);<%\n%>
13846 >>
13847 ))
13848 <<
13849
13850 <%varDecls%>
13851 storeTime(time);
13852 <%storePart%>
13853 >>
13854 end functionStoreDelay;
13855 // generate Member Function get Real
13856
13857
13858 ✗ template getVariablesWithSplit(Text funcNamePrefix, Text funcArgs, Text funcParams, list<SimVar> varsLst, Integer indexOffset, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text& funcCalls, Text extraFuncsNamespace, Context context, Text stateDerVectorName /*=__zDot*/ , Boolean useFlatArrayNotation)
13859 ::=
13860 let funcs = List.partition(varsLst, 100) |> ls hasindex idx =>
13861 let &varDecls = buffer "" /*BUFD*/
13862 let &funcCalls += '<%funcNamePrefix%>_<%idx%>(<%funcParams%>);'
13863 let init = getVariablesWithSplit2(ls, simCode ,&varDecls, &extraFuncs , &extraFuncsDecl, extraFuncsNamespace, context, stateDerVectorName,useFlatArrayNotation, idx, 100, indexOffset)
13864 <<
13865 void <%funcNamePrefix%>_<%idx%>(<%funcArgs%>)
13866 {
13867 <%varDecls%>
13868 <%init%>
13869 }
13870 >>
13871 ;separator="\n"
13872
13873
13874 <<
13875 <%funcs%>
13876 >>
13877 end getVariablesWithSplit;
13878
13879
13880 ✗ template getVariablesWithSplit2(list<SimVar> varsLst, SimCode simCode,Text& varDecls,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Context context, Text stateDerVectorName /*=__zDot*/ ,Boolean useFlatArrayNotation, Integer multiplicator, Integer partitionSize, Integer indexOffset)
13881 ::=
13882 <<
13883 <%varsLst |>
13884 var hasindex i0 fromindex (intAdd(indexOffset, intMul(multiplicator, partitionSize))) => giveVariablesDefault(var, i0,simCode,varDecls, extraFuncs,extraFuncsDecl,extraFuncsNamespace,context, stateDerVectorName,useFlatArrayNotation)
13885 ;separator="\n"%>
13886 >>
13887 end getVariablesWithSplit2;
13888
13889
13890
13891 ✗ template setVariablesWithSplit(Text funcNamePrefix, Text funcArgs, Text funcParams, list<SimVar> varsLst, SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Text& funcCalls, Integer indexOffset, Context context, Text stateDerVectorName /*=__zDot*/ , Boolean useFlatArrayNotation) ::=
13892 let funcs = List.partition(varsLst, 100) |> ls hasindex idx =>
13893 let &varDecls = buffer "" /*BUFD*/
13894 let &funcCalls += '<%funcNamePrefix%>_<%idx%>(<%funcParams%>);'
13895 let init = setVariablesWithSplit2(ls, simCode , varDecls,&extraFuncs , &extraFuncsDecl, extraFuncsNamespace, context,stateDerVectorName, useFlatArrayNotation, idx, 100, indexOffset)
13896 <<
13897 void <%funcNamePrefix%>_<%idx%>(<%funcArgs%>)
13898 {
13899 <%varDecls%>
13900 <%init%>
13901 }
13902 >>
13903 ;separator="\n"
13904
13905 <<
13906 <%funcs%>
13907 >>
13908 end setVariablesWithSplit;
13909
13910
13911 ✗ template setVariablesWithSplit2(list<SimVar> varsLst, SimCode simCode ,Text& varDecls,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Context context, Text stateDerVectorName /*=__zDot*/ , Boolean useFlatArrayNotation, Integer multiplicator, Integer partitionSize, Integer indexOffset)
13912 ::=
13913 <<
13914 <%varsLst|>
13915 var hasindex i0 fromindex intMul(multiplicator, partitionSize) => setVariablesDefault(var, i0, indexOffset,simCode, varDecls,extraFuncs,extraFuncsDecl,extraFuncsNamespace,context,stateDerVectorName, useFlatArrayNotation)
13916 ;separator="\n"%>
13917
13918 >>
13919 end setVariablesWithSplit2;
13920
13921
13922 49 template giveVariables(ModelInfo modelInfo, Context context,Boolean useFlatArrayNotation,SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/ )
13923 "Define Memeber Function getReal off Cpp Target"
13924 ::=
13925 //match context case FMI_CONTEXT(__) then
13926 match modelInfo
13927 case MODELINFO(vars=SIMVARS(__)) then
13928 let &realFuncCalls = buffer ""
13929 let &setRealFuncCalls = buffer ""
13930 let &intFuncCalls = buffer ""
13931 let &boolFuncCalls = buffer ""
13932 let &stringFuncCalls = buffer ""
13933 /* changed: handled in SimVars class
13934 let stateVarCount = listLength(vars.stateVars)
13935 let getrealvariable = getVariablesWithSplit(lastIdentOfPath(name)+ "::getReal","double* z","z",listAppend(vars.algVars, listAppend(vars.discreteAlgVars, listAppend(vars.paramVars, vars.aliasVars))), listLength(listAppend(vars.stateVars, vars.derivativeVars)), simCode, &extraFuncs, &extraFuncsDecl, &realFuncCalls, extraFuncsNamespace, context, stateDerVectorName, useFlatArrayNotation)
13936 let setrealvariable = setVariablesWithSplit(lastIdentOfPath(name)+ "::setReal","const double* z","z",listAppend(vars.algVars, listAppend(vars.discreteAlgVars, listAppend(vars.paramVars, vars.aliasVars))), simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, &setRealFuncCalls, listLength(listAppend(vars.stateVars, vars.derivativeVars)), context,stateDerVectorName, useFlatArrayNotation)
13937
13938 let getStateVariables = (vars.stateVars |> var hasindex i0 fromindex 0 => getStateVariables(var, i0, "z", i0) ;separator="\n")
13939 let setStateVariables = (vars.stateVars |> var hasindex i0 fromindex 0 => setStateVariables(var, i0, "z", i0) ;separator="\n")
13940
13941 let getStateDerVariables = (vars.derivativeVars |> var hasindex i0 fromindex 0 => getStateDerivativeVariables(var, i0, "z", i0, stringInt(stateVarCount)) ;separator="\n")
13942 let setStateDerVariables = (vars.derivativeVars |> var hasindex i0 fromindex 0 => setStateDerivativeVariables(var, i0, "z", i0, stringInt(stateVarCount)) ;separator="\n")
13943
13944 let getintvariable = getVariablesWithSplit(lastIdentOfPath(name)+ "::getInteger","int* z","z",listAppend(listAppend( vars.intAlgVars, vars.intParamVars ), vars.intAliasVars ), 0, simCode , &extraFuncs , &extraFuncsDecl, &intFuncCalls, extraFuncsNamespace, context, stateDerVectorName, useFlatArrayNotation)
13945 let getboolvariable = getVariablesWithSplit(lastIdentOfPath(name)+ "::getBoolean","bool* z","z",listAppend(listAppend( vars.boolAlgVars, vars.boolParamVars ), vars.boolAliasVars ), 0, simCode , &extraFuncs , &extraFuncsDecl, &boolFuncCalls, extraFuncsNamespace, context, stateDerVectorName, useFlatArrayNotation)
13946
13947 let getstringvariable = getVariablesWithSplit(lastIdentOfPath(name)+ "::getString","string* z","z",listAppend(listAppend( vars.stringAlgVars, vars.stringParamVars ), vars.stringAliasVars), 0, simCode ,&extraFuncs, &extraFuncsDecl, &stringFuncCalls, extraFuncsNamespace, context, stateDerVectorName, useFlatArrayNotation)
13948 */
13949 let &varDeclsInt = buffer ""
13950 /* changed: handled in SimVars class
13951 let setIntVariables = (listAppend( listAppend( vars.intAlgVars, vars.intParamVars ), vars.intAliasVars ) |>
13952 var hasindex i0 fromindex 0 =>
13953 setVariablesDefault(var, i0, 0,simCode,varDeclsInt, extraFuncs,extraFuncsDecl,extraFuncsNamespace,context, stateDerVectorName,useFlatArrayNotation)
13954 ;separator="\n")
13955 let &varDeclsBool = buffer ""
13956 let setBoolVariables = (listAppend( listAppend( vars.boolAlgVars, vars.boolParamVars ), vars.boolAliasVars ) |>
13957 var hasindex i0 fromindex 0 =>
13958 setVariablesDefault(var, i0,0,simCode,varDeclsBool, extraFuncs,extraFuncsDecl,extraFuncsNamespace,context, stateDerVectorName,useFlatArrayNotation)
13959 ;separator="\n")
13960 */
13961 let &varDeclsString = buffer ""
13962 let setStringVariables = (listAppend(listAppend( vars.stringAlgVars, vars.stringParamVars ), vars.stringAliasVars) |>
13963 var hasindex i0 fromindex 0 =>
13964 setVariablesDefault(var, i0, 0,simCode,varDeclsString, extraFuncs,extraFuncsDecl,extraFuncsNamespace,context, stateDerVectorName,useFlatArrayNotation)
13965 ;separator="\n")
13966
13967 <<
13968
13969 void <%lastIdentOfPath(name)%>::getReal(double* z)
13970 {
13971 const double* real_vars = getSimVars()->getRealVarsVector();
13972 memcpy(z,real_vars,<%numRealvars(modelInfo)%>*sizeof(double));
13973 }
13974
13975 void <%lastIdentOfPath(name)%>::setReal(const double* z)
13976 {
13977 getSimVars()->setRealVarsVector(z);
13978 }
13979
13980 void <%lastIdentOfPath(name)%>::getInteger(int* z)
13981 {
13982 const int* int_vars = getSimVars()->getIntVarsVector();
13983 memcpy(z,int_vars,<%numIntvars(modelInfo)%>*sizeof(int));
13984 }
13985
13986 void <%lastIdentOfPath(name)%>::getBoolean(bool* z)
13987 {
13988 const bool* bool_vars = getSimVars()->getBoolVarsVector();
13989 memcpy(z,bool_vars,<%numBoolvars(modelInfo)%>*sizeof(bool));
13990 }
13991
13992 void <%lastIdentOfPath(name)%>::getString(string* z)
13993 {
13994 <%stringFuncCalls%>
13995 }
13996
13997 void <%lastIdentOfPath(name)%>::setInteger(const int* z)
13998 {
13999 getSimVars()->setIntVarsVector(z);
14000 }
14001
14002 void <%lastIdentOfPath(name)%>::setBoolean(const bool* z)
14003 {
14004 getSimVars()->setBoolVarsVector(z);
14005 }
14006
14007 void <%lastIdentOfPath(name)%>::setString(const string* z)
14008 {
14009 <%setStringVariables%>
14010 }
14011 >>
14012 end match
14013 end giveVariables;
14014
14015 ✗ template getStateVariables(SimVar simVar, Integer valueReference, String arrayName, Integer index)
14016 "Generates code for getting variables in cpp target for use in FMU. "
14017 ::=
14018 match simVar
14019 case SIMVAR(__) then
14020 let description = if comment then '// "<%comment%>"'
14021 <<
14022 <%arrayName%>[<%index%>] = this->__z[<%valueReference%>]; <%description%>
14023 >>
14024 end getStateVariables;
14025
14026 ✗ template setStateVariables(SimVar simVar, Integer valueReference, String arrayName, Integer index)
14027 "Generates code for getting variables in cpp target for use in FMU. "
14028 ::=
14029 match simVar
14030 case SIMVAR(__) then
14031 let description = if comment then '// "<%comment%>"'
14032 <<
14033 this->__z[<%valueReference%>] = <%arrayName%>[<%index%>]; <%description%>
14034 >>
14035 end setStateVariables;
14036
14037 ✗ template getStateDerivativeVariables(SimVar simVar, Integer valueReference, String arrayName, Integer index, Integer indexOffset)
14038 "Generates code for getting variables in cpp target for use in FMU. "
14039 ::=
14040 match simVar
14041 case SIMVAR(__) then
14042 let description = if comment then '// "<%comment%>"'
14043 <<
14044 <%arrayName%>[<%intAdd(index,indexOffset)%>] = this->__zDot[<%valueReference%>]; <%description%>
14045 >>
14046 end getStateDerivativeVariables;
14047
14048 ✗ template setStateDerivativeVariables(SimVar simVar, Integer valueReference, String arrayName, Integer index, Integer indexOffset)
14049 "Generates code for getting variables in cpp target for use in FMU. "
14050 ::=
14051 match simVar
14052 case SIMVAR(__) then
14053 let description = if comment then '// "<%comment%>"'
14054 <<
14055 this->__zDot[<%valueReference%>] = <%arrayName%>[<%intAdd(index,indexOffset)%>]; <%description%>
14056 >>
14057 end setStateDerivativeVariables;
14058
14059 ✗ template giveVariablesDefault(SimVar simVar, Integer valueReference,SimCode simCode,Text& varDecls, Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Context context, Text stateDerVectorName /*=__zDot*/ ,Boolean useFlatArrayNotation)
14060 "Generates code for getting variables in cpp target for use in FMU. "
14061 ::=
14062 match simVar
14063 case SIMVAR(__) then
14064 let description = if comment then '/* <%comment%> */'
14065 let varname = cref1(name, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, context, varDecls, stateDerVectorName, useFlatArrayNotation)
14066 match aliasvar
14067 case ALIAS(__)
14068 case NEGATEDALIAS(__) then 'z[<%valueReference%>] = <%getAliasSign(simVar)%><%cref1(varName, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, context, varDecls, stateDerVectorName, useFlatArrayNotation)%>; <%description%>'
14069 else
14070 <<
14071 z[<%valueReference%>] = <%varname%>; <%description%>
14072 >>
14073 end giveVariablesDefault;
14074
14075 57 template setVariablesDefault(SimVar simVar, Integer valueReference, Integer indexOffset,SimCode simCode,Text& varDecls,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Context context, Text stateDerVectorName /*=__zDot*/ , Boolean useFlatArrayNotation)
14076 "Generates code for getting variables in cpp target for use in FMU. "
14077 ::=
14078 match simVar
14079 case SIMVAR(__) then
14080 let description = if comment then '/* "<%comment%>" */'
14081 let variablename = cref1(name, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, contextOther, varDecls, stateDerVectorName, useFlatArrayNotation)
14082 match aliasvar
14083 case ALIAS(__)
14084 case NEGATEDALIAS(__) then '<%cref1(varName, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace, context, varDecls, stateDerVectorName, useFlatArrayNotation)%> = <%getAliasSign(simVar)%>z[<%intAdd(indexOffset, valueReference)%>]; <%description%>'
14085 else
14086 <<
14087 <%variablename%> = z[<%intAdd(indexOffset, valueReference)%>]; <%description%>
14088 >>
14089 end match
14090 end setVariablesDefault;
14091
14092
14093
14094
14095
14096
14097
14098 56 template generateMeasureTimeStartCode(String varNameStartValues, String sectionName, String defineName)
14099 ::=
14100 if boolNot(stringEq(getConfigString(PROFILING_LEVEL),"none")) then
14101 <<
14102 <%if stringEq(defineName, "") then '' else '#ifdef <%defineName%>'%>
14103 MEASURETIME_REGION_DEFINE(<%sectionName%>, "<%sectionName%>");
14104 MEASURETIME_START(<%varNameStartValues%>, <%sectionName%>, "<%sectionName%>");
14105 <%if stringEq(defineName, "") then '' else '#endif'%>
14106 >>
14107 end generateMeasureTimeStartCode;
14108
14109 56 template generateMeasureTimeEndCode(String varNameStartValues, String varNameEndValues, String varNameTargetValues, String sectionName, String defineName)
14110 ::=
14111 if boolNot(stringEq(getConfigString(PROFILING_LEVEL),"none")) then
14112 <<
14113 <%if stringEq(defineName, "") then '' else '#ifdef <%defineName%>'%>
14114 MEASURETIME_END(<%varNameStartValues%>,<%varNameEndValues%>,<%varNameTargetValues%>, <%sectionName%>);
14115 <%if stringEq(defineName, "") then '' else '#endif'%>
14116 >>
14117 end generateMeasureTimeEndCode;
14118
14119
14120 /*daeMode templates*/
14121
14122 2 template simulationDAEMethodsDeclaration(SimCode simCode)
14123 ::=
14124 match simCode
14125 case SIMCODE(modelInfo=MODELINFO(vars=SIMVARS(__)),
14126 daeModeData=SOME(DAEMODEDATA(daeEquations=daeEquations, sparsityPattern=sparsityPattern,
14127 algebraicVars=algebraicDAEVars, residualVars=residualVars))) then
14128 <<
14129 <%generateDAEEquationMemberFuncDecls(daeEquations, "evaluateDAE")%>
14130 >>
14131 end simulationDAEMethodsDeclaration;
14132
14133 49 template updateResiduals(SimCode simCode, Text& extraResidualsFuncsDecl, Text extraFuncsNamespace, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation)
14134 ::=
14135 let &extraResidualsFuncs = buffer "" /*BUFD*/
14136 <<
14137 <%simulationDAEMethods(simCode, extraResidualsFuncs, extraResidualsFuncsDecl, extraFuncsNamespace, contextOther, stateDerVectorName, useFlatArrayNotation, boolNot(stringEq(getConfigString(PROFILING_LEVEL), "none")))%>
14138
14139 <%extraResidualsFuncs%>
14140 >>
14141 end updateResiduals;
14142
14143 2 template generateDAEEquationMemberFuncDecls(list<list<SimEqSystem>> DAEEquations,Text method)
14144 ::=
14145 match DAEEquations
14146 case _ then
14147 let equation_func_decls = (DAEEquations |> eqsys => (eqsys |> eq =>
14148 generateEquationMemberFuncDecls2(eq,method) ;separator="\n"))
14149 <<
14150 <%equation_func_decls%>
14151 >>
14152 end match
14153 end generateDAEEquationMemberFuncDecls;
14154
14155
14156 47 template simulationDAEMethods(SimCode simCode, Text& extraFuncs, Text& extraFuncsDecl, Text extraFuncsNamespace, Context context, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation, Boolean enableMeasureTime)
14157 "DAEmode equations generation"
14158 ::=
14159 match simCode
14160 case SIMCODE(modelInfo=MODELINFO(vars=SIMVARS(__)),
14161 daeModeData=SOME(DAEMODEDATA(daeEquations=daeEquations, sparsityPattern=sparsityPattern,
14162 algebraicVars=algebraicDAEVars, residualVars=residualVars))) then
14163 let modelNamePrefixStr = lastIdentOfPath(modelInfo.name)
14164
14165 <<
14166 <%algebraicDAEVar(algebraicDAEVars, modelNamePrefixStr)%>
14167 <%evaluateDAEResiduals(daeEquations, simCode, extraFuncs, extraFuncsDecl, extraFuncsNamespace, context, enableMeasureTime)%>
14168 <%equationResidualFunctions(daeEquations, simCode, extraFuncs, extraFuncsDecl, extraFuncsNamespace, context, stateDerVectorName, useFlatArrayNotation, enableMeasureTime)%>
14169 void <%modelNamePrefixStr%>Mixed::getResidual(double* f)
14170 {
14171 SystemDefaultImplementation::getResidual(f);
14172 }
14173 >>
14174 /* adrpo: leave a newline at the end of file to get rid of the warning */
14175 case SIMCODE(modelInfo=MODELINFO(__),daeModeData=NONE()) then
14176 let modelNamePrefixStr = lastIdentOfPath(modelInfo.name)
14177 <<
14178 /* DAE residuals is empty */
14179 void <%modelNamePrefixStr%>Mixed::getResidual(double* f)
14180 {
14181 }
14182 void <%modelNamePrefixStr%>Mixed::setAlgebraicDAEVars(const double* y)
14183 {
14184 }
14185 /* get algebraic variables */
14186 void <%modelNamePrefixStr%>Mixed::getAlgebraicDAEVars( double* y)
14187 {
14188 }
14189 void <%modelNamePrefixStr%>Mixed::evaluateDAE(const UPDATETYPE command )
14190 {
14191 }
14192 >>
14193 end match
14194 end simulationDAEMethods;
14195
14196
14197
14198 2 template algebraicDAEVar(list<SimVar> algVars, String className)
14199 "Generates function in simulation file."
14200 ::=
14201 let setVars = (algVars |> var hasindex i fromindex 0 =>
14202 (match var
14203 case SIMVAR(__) then
14204 '<%cref(name,false)%> = y[<%i%>];'
14205 end match)
14206 ;separator="\n")
14207 let getVars = (algVars |> var hasindex i fromindex 0 =>
14208 (match var
14209 case SIMVAR(__) then
14210 'y[<%i%>] = <%cref(name,false)%>;'
14211 end match)
14212 ;separator="\n")
14213 /*let nominalVars = (algVars |> var hasindex i fromindex 0 =>
14214 (match var
14215 case SIMVAR(__) then
14216 <<
14217 algebraicNominal[<%i%>] = <%crefAttributes(name)%>.nominal * data->simulationInfo->tolerance;
14218 infoStreamPrint(OMC_LOG_SOLVER, 0, "%s -> %g", <%crefVarInfo(name)%>.name, algebraicNominal[<%i%>]);
14219 >>
14220 end match)
14221
14222 ;separator="\n")*/
14223
14224 <<
14225
14226
14227 void <%className%>Mixed::setAlgebraicDAEVars(const double* y)
14228 {
14229
14230 <%setVars%>
14231
14232 }
14233 /* get algebraic variables */
14234 void <%className%>Mixed::getAlgebraicDAEVars( double* y)
14235 {
14236
14237 <%getVars%>
14238
14239 }
14240 >>
14241 end algebraicDAEVar;
14242
14243
14244 2 template evaluateDAEResiduals(list<list<SimEqSystem>> resEquations, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Context context, Boolean createMeasureTime)
14245 "Generates function in simulation file."
14246 ::=
14247 match simCode
14248 case SIMCODE(partitionData = PARTITIONDATA(partitions = partitions, activatorsForPartitions=activatorsForPartitions)) then
14249 //case MODELINFO(vars = vars as SIMVARS(__))
14250 let className = '<%lastIdentOfPathFromSimCode(simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace)%>Mixed'
14251 let &varDecls = buffer ""
14252
14253 let equation_dae_func_calls = if not Flags.isSet(Flags.MULTIRATE_PARTITION) then (List.partition(List.flatten(resEquations), 100) |> eqs hasindex i0 =>
14254 createEvaluateWithSplit(i0, context, eqs, "evaluateDAE", "evaluateDAE", className, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace)
14255 ;separator="\n")
14256 else ( List.intRange(partitionData.numPartitions) |> partIdx =>
14257 createEvaluatePartitions(partIdx, context, List.flatten(resEquations), listGet(partitions, partIdx),
14258 listGet(activatorsForPartitions,partIdx), className, simCode, &extraFuncs, &extraFuncsDecl, extraFuncsNamespace) ;separator="\n")
14259 <<
14260 void <%className%>::evaluateDAE(const UPDATETYPE command )
14261 {
14262 <%if createMeasureTime then generateMeasureTimeStartCode("measuredFunctionStartValues", "evaluateDAE", "MEASURETIME_MODELFUNCTIONS") else ""%>
14263 <%varDecls%>
14264 // Evaluate Equations
14265 <%equation_dae_func_calls%>
14266 <%if createMeasureTime then generateMeasureTimeEndCode("measuredFunctionStartValues", "measuredFunctionEndValues", "(*measureTimeFunctionsArray)[0]", "evaluateDAE", "MEASURETIME_MODELFUNCTIONS") else ""%>
14267 }
14268 >>
14269 end evaluateDAEResiduals;
14270
14271
14272
14273 2 template equationResidualFunctions(list<list<SimEqSystem>> daeEquations, SimCode simCode ,Text& extraFuncs,Text& extraFuncsDecl,Text extraFuncsNamespace, Context context, Text stateDerVectorName /*=__zDot*/, Boolean useFlatArrayNotation, Boolean enableMeasureTime)
14274 ::=
14275
14276 let equation_func_calls = (daeEquations |> eqsys => (eqsys |> eq =>
14277 equation_function_create_single_func(eq, context/*BUFC*/, simCode , &extraFuncs , &extraFuncsDecl, extraFuncsNamespace,"evaluateDAE","Mixed", stateDerVectorName, useFlatArrayNotation,enableMeasureTime,false,false, "")
14278 ;separator="\n"))
14279 <<
14280 <%equation_func_calls%>
14281 >>
14282 end equationResidualFunctions;
14283
14284 /*temporary template functions*/
14285
14286 ✗ template defineSimVarArray(SimVar simVar)
14287 "Generates a define statement for a parameter."
14288 ::=
14289 match simVar
14290 case SIMVAR(arrayCref=SOME(c),aliasvar=NOALIAS()) then
14291 <<
14292 /* <%crefStrNoUnderscore(c)%> */
14293 #define <%CodegenCppCommon.crefStr(c)%> __daeResidual<%index%>]
14294
14295 /* <%crefStrNoUnderscore(name)%> */
14296 #define <%CodegenCppCommon.crefStr(name)%> __daeResidual[<%index%>]
14297
14298 >>
14299 case SIMVAR(aliasvar=NOALIAS()) then
14300 <<
14301 /* <%crefStrNoUnderscore(name)%> */
14302 #define <%CodegenCppCommon.crefStr(name)%> __daeResidual[<%index%>]
14303
14304 >>
14305 end match
14306 end defineSimVarArray;
14307
14308 ✗ template simulationFile_dae_header(SimCode simCode)
14309 "DAEmode header generation"
14310 ::=
14311 match simCode
14312 case simCode as SIMCODE(daeModeData=SOME(DAEMODEDATA(residualVars=residualVars))) then
14313 <<
14314 /* residual variable define for daeMode */
14315 <%residualVars |> var =>
14316 defineSimVarArray(var)
14317 ;separator="\n"%>
14318 >>
14319 /* adrpo: leave a newline at the end of file to get rid of the warning */
14320 case simCode as SIMCODE(__) then
14321 <<
14322 #ifndef <%fileNamePrefix%>_16DAE_H
14323 #define <%fileNamePrefix%>_16DAE_H
14324 #endif
14325 <%\n%>
14326 >>
14327 end match
14328 end simulationFile_dae_header;
14329
14330
14331
14332
14333
14334 /*end daeMode templates*/
14335
14336 annotation(__OpenModelica_Interface="codegen_cpp");
14337 end CodegenCpp;
14338