-
Notifications
You must be signed in to change notification settings - Fork 298
/
NBInitialization.mo
445 lines (412 loc) · 19.4 KB
/
NBInitialization.mo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
/*
* This file is part of OpenModelica.
*
* Copyright (c) 1998-2020, Open Source Modelica Consortium (OSMC),
* c/o Linköpings universitet, Department of Computer and Information Science,
* SE-58183 Linköping, Sweden.
*
* All rights reserved.
*
* THIS PROGRAM IS PROVIDED UNDER THE TERMS OF GPL VERSION 3 LICENSE OR
* THIS OSMC PUBLIC LICENSE (OSMC-PL) VERSION 1.2.
* ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES
* RECIPIENT'S ACCEPTANCE OF THE OSMC PUBLIC LICENSE OR THE GPL VERSION 3,
* ACCORDING TO RECIPIENTS CHOICE.
*
* The OpenModelica software and the Open Source Modelica
* Consortium (OSMC) Public License (OSMC-PL) are obtained
* from OSMC, either from the above address,
* from the URLs: http://www.ida.liu.se/projects/OpenModelica or
* http://www.openmodelica.org, and in the OpenModelica distribution.
* GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html.
*
* This program is distributed WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH
* IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS OF OSMC-PL.
*
* See the full OSMC Public License conditions for more details.
*
*/
encapsulated package NBInitialization
"file: NBInitialization.mo
package: NBInitialization
description: This file contains the main data types for the initialization
process.
"
protected
// NF imports
import BackendExtension = NFBackendExtension;
import Call = NFCall;
import ComponentRef = NFComponentRef;
import Dimension = NFDimension;
import Expression = NFExpression;
import Flatten = NFFlatten;
import NFFunction.Function;
import NFFlatten.{FunctionTree, FunctionTreeImpl};
import NFInstNode.InstNode;
import Subscript = NFSubscript;
import Type = NFType;
import Variable = NFVariable;
// Backend imports
import BackendDAE = NBackendDAE;
import BEquation = NBEquation;
import NBEquation.{Equation,EquationPointers,WhenEquationBody};
import BVariable = NBVariable;
import NBVariable.{VariablePointer, VariablePointers};
import Causalize = NBCausalize;
import Jacobian = NBJacobian;
import Module = NBModule;
import Partitioning = NBPartitioning;
import NBSystem;
import NBSystem.System;
import Tearing = NBTearing;
// Util imports
import ClockIndexes;
import DoubleEnded;
import Slice = NBSlice;
public
function main extends Module.wrapper;
protected
BVariable.VariablePointers variables, initialVars;
BEquation.EquationPointers equations, initialEqs;
list<tuple<Module.wrapper, String>> modules;
list<tuple<String, Real>> clocks;
algorithm
try
bdae := match bdae
local
BVariable.VarData varData;
BEquation.EqData eqData;
case BackendDAE.MAIN( varData = varData as BVariable.VAR_DATA_SIM(variables = variables, initials = initialVars),
eqData = eqData as BEquation.EQ_DATA_SIM(equations = equations, initials = initialEqs))
algorithm
// create the equations from fixed variables.
(variables, equations, initialEqs) := createStartEquations(varData.states, variables, equations, initialEqs, eqData.uniqueIndex, "State");
(variables, equations, initialEqs) := createStartEquations(varData.discretes, variables, equations, initialEqs, eqData.uniqueIndex, "Discrete State");
(equations, initialEqs, initialVars) := createParameterEquations(varData.parameters, equations, initialEqs, initialVars, eqData.uniqueIndex);
varData.variables := variables;
varData.initials := initialVars;
eqData.equations := equations;
// clone all simulation equations and add them to the initial equations
eqData.initials := EquationPointers.addList(EquationPointers.toList(initialEqs), EquationPointers.clone(equations, false));
bdae.varData := varData;
bdae.eqData := eqData;
then bdae;
else algorithm
Error.addMessage(Error.INTERNAL_ERROR, {getInstanceName() + " failed to create initial system!"});
then fail();
end match;
// Modules
modules := {
(function Partitioning.main(systemType = NBSystem.SystemType.INI), "Partitioning"),
(cleanup, "Cleanup"),
(function Causalize.main(systemType = NBSystem.SystemType.INI), "Causalize"),
(function Tearing.main(systemType = NBSystem.SystemType.INI), "Tearing")
};
(bdae, clocks) := BackendDAE.applyModules(bdae, modules, ClockIndexes.RT_CLOCK_NEW_BACKEND_INITIALIZATION);
if Flags.isSet(Flags.DUMP_BACKEND_CLOCKS) then
if not listEmpty(clocks) then
print(StringUtil.headline_4("Initialization Backend Clocks:"));
print(stringDelimitList(list(Module.moduleClockString(clck) for clck in clocks), "\n") + "\n");
end if;
end if;
else
Error.addMessage(Error.INTERNAL_ERROR, {getInstanceName() + " failed to apply modules!"});
fail();
end try;
end main;
function createStartEquations
"Creates start equations from fixed start values."
input BVariable.VariablePointers states;
input output BVariable.VariablePointers variables;
input output BEquation.EquationPointers equations;
input output BEquation.EquationPointers initialEqs;
input Pointer<Integer> idx;
input String str "only for debugging dump";
protected
Pointer<list<Pointer<Variable>>> ptr_start_vars = Pointer.create({});
Pointer<list<Pointer<BEquation.Equation>>> ptr_start_eqs = Pointer.create({});
list<Pointer<Variable>> start_vars;
list<Pointer<BEquation.Equation>> start_eqs;
algorithm
_ := BVariable.VariablePointers.mapPtr(states, function createStartEquation(ptr_start_vars = ptr_start_vars, ptr_start_eqs = ptr_start_eqs, idx = idx));
start_vars := Pointer.access(ptr_start_vars);
start_eqs := Pointer.access(ptr_start_eqs);
variables := BVariable.VariablePointers.addList(start_vars, variables);
equations := BEquation.EquationPointers.addList(start_eqs, equations);
initialEqs := BEquation.EquationPointers.addList(start_eqs, initialEqs);
if Flags.isSet(Flags.INITIALIZATION) and not listEmpty(start_eqs) then
print(List.toString(start_eqs, function Equation.pointerToString(str = ""), StringUtil.headline_4("Created " + str + " Start Equations:"), "\t", "\n\t", "", false) + "\n\n");
end if;
end createStartEquations;
function createStartEquation
"creates a start equation for a fixed state or discrete state."
input Pointer<Variable> state;
input Pointer<list<Pointer<Variable>>> ptr_start_vars;
input Pointer<list<Pointer<BEquation.Equation>>> ptr_start_eqs;
input Pointer<Integer> idx;
algorithm
() := match Pointer.access(state)
local
ComponentRef name, start_name;
Pointer<Variable> var_ptr, start_var;
Pointer<BEquation.Equation> start_eq;
// if it is an array create for equation
case Variable.VARIABLE() guard BVariable.isFixed(state) and BVariable.isArray(state) algorithm
createStartEquationSlice(Slice.SLICE(state, {}), ptr_start_vars, ptr_start_eqs, idx);
then ();
// create scalar equation
case Variable.VARIABLE() guard BVariable.isFixed(state) algorithm
name := BVariable.getVarName(state);
(var_ptr, name, start_var, start_name) := createStartVar(state, name, {});
start_eq := BEquation.Equation.makeAssignment(name, Expression.fromCref(start_name), idx, NBEquation.START_STR, {}, NBEquation.EQ_ATTR_DEFAULT_INITIAL);
Pointer.update(ptr_start_vars, start_var :: Pointer.access(ptr_start_vars));
Pointer.update(ptr_start_eqs, start_eq :: Pointer.access(ptr_start_eqs));
then ();
else ();
end match;
end createStartEquation;
function createStartVar
"creates start variable and cref.
for discrete states the variable itself is changed to its
pre variable because they have to be initialized instead!.
normal: var = $START.var
disc state and pre: $PRE.dst = $START.dst"
input output Pointer<Variable> var_ptr;
input output ComponentRef name;
input list<Subscript> subscripts;
output Pointer<Variable> start_var;
output ComponentRef start_name;
protected
Pointer<Variable> disc_state_var;
ComponentRef merged_name;
algorithm
if BVariable.isDiscreteState(var_ptr) then
// for discrete states change the lhs cref to the $PRE cref
merged_name := ComponentRef.mergeSubscripts(subscripts, name, true, true);
name := BVariable.getPreCref(name);
name := ComponentRef.mergeSubscripts(subscripts, name, true, true);
var_ptr := BVariable.getVarPointer(name);
elseif BVariable.isPrevious(var_ptr) then
// for previous change the rhs to the start value of the discrete state
merged_name := BVariable.getDiscreteStateCref(name);
merged_name := ComponentRef.mergeSubscripts(subscripts, merged_name, true, true);
else
// just apply subscripts and make start var
name := ComponentRef.mergeSubscripts(subscripts, name, true, true);
merged_name := name;
end if;
(start_name, start_var) := BVariable.makeStartVar(merged_name);
end createStartVar;
function createParameterEquations
"creates parameter equations of the form param = $START.param for all fixed params."
input BVariable.VariablePointers parameters;
input output BEquation.EquationPointers equations;
input output BEquation.EquationPointers initialEqs;
input output BVariable.VariablePointers initialVars;
input Pointer<Integer> idx;
protected
list<Pointer<BEquation.Equation>> parameter_eqs = {};
list<Pointer<Variable>> initial_param_vars = {};
algorithm
for var in BVariable.VariablePointers.toList(parameters) loop
// only consider non constant parameter bindings
if (BVariable.getBindingVariability(var) > NFPrefixes.Variability.STRUCTURAL_PARAMETER) then
// add variable to initial unknowns
initial_param_vars := var :: initial_param_vars;
// generate equation only if variable is fixed
if BVariable.isFixed(var) then
parameter_eqs := BEquation.Equation.generateBindingEquation(var, idx, true) :: parameter_eqs;
end if;
end if;
end for;
equations := BEquation.EquationPointers.addList(parameter_eqs, equations);
initialEqs := BEquation.EquationPointers.addList(parameter_eqs, initialEqs);
initialVars := BVariable.VariablePointers.addList(initial_param_vars, initialVars);
if Flags.isSet(Flags.INITIALIZATION) and not listEmpty(parameter_eqs) then
print(List.toString(parameter_eqs, function Equation.pointerToString(str = ""), StringUtil.headline_4("Created Parameter Binding Equations:"), "\t", "\n\t", "", false) + "\n\n");
end if;
end createParameterEquations;
function createStartEquationSlice
"creates a start equation for a sliced variable.
usually results in a for equation, but might be scalarized if that is not possible."
input Slice<VariablePointer> state;
input Pointer<list<Pointer<Variable>>> ptr_start_vars;
input Pointer<list<Pointer<BEquation.Equation>>> ptr_start_eqs;
input Pointer<Integer> idx;
protected
Pointer<Variable> var_ptr, start_var;
ComponentRef name, start_name;
list<Dimension> dims;
list<InstNode> iterators;
list<ComponentRef> iter_crefs;
list<Expression> ranges;
list<Subscript> subscripts;
list<tuple<ComponentRef, Expression>> frames;
Pointer<Equation> start_eq;
algorithm
var_ptr := Slice.getT(state);
name := BVariable.getVarName(var_ptr);
dims := Type.arrayDims(ComponentRef.nodeType(name));
(iterators, ranges, subscripts) := Flatten.makeIterators(name, dims);
iter_crefs := list(ComponentRef.makeIterator(iter, Type.INTEGER()) for iter in iterators);
iter_crefs := list(BackendDAE.lowerIteratorCref(iter) for iter in iter_crefs);
subscripts := list(Subscript.mapExp(sub, BackendDAE.lowerIteratorExp) for sub in subscripts);
frames := List.zip(iter_crefs, ranges);
(var_ptr, name, start_var, start_name) := createStartVar(var_ptr, name, subscripts);
start_eq := Equation.makeAssignment(name, Expression.fromCref(start_name), idx, NBEquation.START_STR, frames, NBEquation.EQ_ATTR_DEFAULT_INITIAL);
if not listEmpty(state.indices) then
// empty list indicates full array, slice otherwise
(start_eq, _, _) := Equation.slice(start_eq, state.indices, NONE(), FunctionTreeImpl.EMPTY());
end if;
Pointer.update(ptr_start_vars, start_var :: Pointer.access(ptr_start_vars));
Pointer.update(ptr_start_eqs, start_eq :: Pointer.access(ptr_start_eqs));
end createStartEquationSlice;
function createPreEquation
"creates d = $PRE.d equations"
input Pointer<Variable> disc_state;
input Pointer<list<Pointer<BEquation.Equation>>> ptr_pre_eqs;
input Pointer<Integer> idx;
algorithm
() := match Pointer.access(disc_state)
local
Pointer<Variable> previous;
Pointer<BEquation.Equation> pre_eq;
case Variable.VARIABLE(backendinfo = BackendExtension.BACKEND_INFO(varKind = BackendExtension.VariableKind.DISCRETE_STATE(previous = previous)))
algorithm
pre_eq := BEquation.Equation.makeAssignment(BVariable.getVarName(disc_state), Expression.fromCref(BVariable.getVarName(previous)), idx, NBEquation.PRE_STR, {}, NBEquation.EQ_ATTR_DEFAULT_INITIAL);
Pointer.update(ptr_pre_eqs, pre_eq :: Pointer.access(ptr_pre_eqs));
then ();
else ();
end match;
end createPreEquation;
function createPreEquationSlice
"creates a pre equation for a sliced variable.
usually results in a for equation, but might be scalarized if that is not possible."
input Slice<VariablePointer> disc_state;
input Pointer<list<Pointer<BEquation.Equation>>> ptr_pre_eqs;
input Pointer<Integer> idx;
protected
Pointer<Variable> var_ptr;
ComponentRef name, pre_name;
list<Dimension> dims;
list<InstNode> iterators;
list<Expression> ranges;
list<Subscript> subscripts;
list<tuple<ComponentRef, Expression>> frames;
Pointer<Equation> pre_eq;
algorithm
var_ptr := Slice.getT(disc_state);
name := BVariable.getVarName(var_ptr);
dims := Type.arrayDims(ComponentRef.nodeType(name));
(iterators, ranges, subscripts) := Flatten.makeIterators(name, dims);
frames := List.zip(list(ComponentRef.makeIterator(iter, Type.INTEGER()) for iter in iterators), ranges);
pre_name := BVariable.getPreCref(name);
pre_name := ComponentRef.mergeSubscripts(subscripts, pre_name, true, true);
name := ComponentRef.mergeSubscripts(subscripts, name, true, true);
pre_eq := Equation.makeAssignment(name, Expression.fromCref(pre_name), idx, NBEquation.PRE_STR, frames, NBEquation.EQ_ATTR_DEFAULT_INITIAL);
if not listEmpty(disc_state.indices) then
// empty list indicates full array, slice otherwise
(pre_eq, _, _) := Equation.slice(pre_eq, disc_state.indices, NONE(), FunctionTreeImpl.EMPTY());
end if;
Pointer.update(ptr_pre_eqs, pre_eq :: Pointer.access(ptr_pre_eqs));
end createPreEquationSlice;
function cleanup
"removes calls from the initial problem and marks init_0"
extends Module.wrapper;
protected
Pointer<Boolean> hasHom = Pointer.create(false);
algorithm
bdae := match bdae
case BackendDAE.MAIN() algorithm
// initial() -> false
bdae.ode := list(System.mapEqn(sys, function cleanupInitialCall(init = false)) for sys in bdae.ode);
bdae.algebraic := list(System.mapEqn(sys, function cleanupInitialCall(init = false)) for sys in bdae.algebraic);
bdae.ode_event := list(System.mapEqn(sys, function cleanupInitialCall(init = false)) for sys in bdae.ode_event);
bdae.alg_event := list(System.mapEqn(sys, function cleanupInitialCall(init = false)) for sys in bdae.alg_event);
if Util.isSome(bdae.dae) then
bdae.dae := SOME(list(System.mapEqn(sys, function cleanupInitialCall(init = false)) for sys in Util.getOption(bdae.dae)));
end if;
// initial() -> true
bdae.init := list(System.mapEqn(sys, function cleanupInitialCall(init = true)) for sys in bdae.init);
// homotopy(actual, simplified) -> actual
bdae.ode := list(System.mapExp(sys, function cleanupHomotopy(init = false, hasHom = hasHom)) for sys in bdae.ode);
bdae.algebraic := list(System.mapExp(sys, function cleanupHomotopy(init = false, hasHom = hasHom)) for sys in bdae.algebraic);
bdae.ode_event := list(System.mapExp(sys, function cleanupHomotopy(init = false, hasHom = hasHom)) for sys in bdae.ode_event);
bdae.alg_event := list(System.mapExp(sys, function cleanupHomotopy(init = false, hasHom = hasHom)) for sys in bdae.alg_event);
if Util.isSome(bdae.dae) then
bdae.dae := SOME(list(System.mapExp(sys, function cleanupHomotopy(init = false, hasHom = hasHom)) for sys in Util.getOption(bdae.dae)));
end if;
// create init_0 if homotopy call exists.
if Pointer.access(hasHom) then
bdae.init_0 := SOME(list(System.clone(sys, false) for sys in bdae.init));
bdae.init_0 := SOME(list(System.mapExp(sys, function cleanupHomotopy(init = true, hasHom = hasHom)) for sys in Util.getOption(bdae.init_0)));
end if;
then bdae;
else bdae;
end match;
end cleanup;
function cleanupInitialCall
input output Equation eq;
input Boolean init;
algorithm
eq := match eq
local
WhenEquationBody body;
Pointer<Boolean> simplify;
case Equation.WHEN_EQUATION(body = body) algorithm
simplify := Pointer.create(false);
body.condition := Expression.map(body.condition, function cleanupInitialCallExp(init = init, simplify = simplify));
// TODO simplify when equation if `Pointer.access(simplify)` is true
eq.body := body;
then Equation.simplify(eq);
else eq;
end match;
end cleanupInitialCall;
function cleanupInitialCallExp
input output Expression exp;
input Boolean init;
input Pointer<Boolean> simplify "output, determines if when-equation should be simplified";
algorithm
exp := match exp
local
Expression e;
String name;
Call call;
case Expression.CALL(call = call as Call.TYPED_CALL()) algorithm
name := AbsynUtil.pathString(Function.nameConsiderBuiltin(call.fn));
e := match name
case "initial" algorithm
Pointer.update(simplify, true);
then Expression.BOOLEAN(init);
else exp;
end match;
then e;
else exp;
end match;
end cleanupInitialCallExp;
function cleanupHomotopy
input output Expression exp;
input Boolean init "if init then replace with simplified, else replace with actual";
input Pointer<Boolean> hasHom "output, determines if system contains homotopy()";
algorithm
exp := match exp
local
Expression e;
String name;
Call call;
case Expression.CALL(call = call as Call.TYPED_CALL()) algorithm
name := AbsynUtil.pathString(Function.nameConsiderBuiltin(call.fn));
e := match name
case "homotopy" algorithm
Pointer.update(hasHom, true);
then listGet(Call.arguments(exp.call), if init then 2 else 1);
else exp;
end match;
then e;
else exp;
end match;
end cleanupHomotopy;
annotation(__OpenModelica_Interface="backend");
end NBInitialization;