-
Notifications
You must be signed in to change notification settings - Fork 297
/
NBackendDAE.mo
1367 lines (1214 loc) · 57.7 KB
/
NBackendDAE.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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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 uniontype NBackendDAE
"file: NBackendDAE.mo
package: NBackendDAE
description: This file contains the main data type for the backend containing
all data. It further contains the lower and solve main function.
"
public
import BVariable = NBVariable;
import BEquation = NBEquation;
import NBEquation.{Equation, EquationPointer, EquationPointers, EqData, EquationAttributes, EquationKind, IfEquationBody, Iterator};
import NBVariable.{VariablePointer, VariablePointers, VarData};
import Events = NBEvents;
import NFFlatten.FunctionTree;
import Jacobian = NBJacobian;
import NBJacobian.{SparsityPattern, SparsityColoring};
import StrongComponent = NBStrongComponent;
import NBStrongComponent.CountCollector;
import NBSystem;
import NBSystem.System;
protected
// New Frontend imports
import Algorithm = NFAlgorithm;
import BackendExtension = NFBackendExtension;
import Binding = NFBinding;
import Call = NFCall;
import ComponentRef = NFComponentRef;
import ConvertDAE = NFConvertDAE;
import Dimension = NFDimension;
import Expression = NFExpression;
import FEquation = NFEquation;
import FlatModel = NFFlatModel;
import InstNode = NFInstNode.InstNode;
import Prefixes = NFPrefixes;
import Statement = NFStatement;
import Subscript = NFSubscript;
import Type = NFType;
import Variable = NFVariable;
// New Backend imports
import Alias = NBAlias;
import BackendDAE = NBackendDAE;
import Bindings = NBBindings;
import Causalize = NBCausalize;
import DetectStates = NBDetectStates;
import DAEMode = NBDAEMode;
import FunctionAlias = NBFunctionAlias;
import Initialization = NBInitialization;
import Inline = NBInline;
import NBJacobian.JacobianType;
import Module = NBModule;
import Partitioning = NBPartitioning;
import Solve = NBSolve;
import Tearing = NBTearing;
// Util imports
import BuiltinSystem = System;
import ClockIndexes;
import Error;
import ExecStat;
import ExpandableArray;
import Flags;
import StringUtil;
public
record MAIN
list<System> ode "Systems for differential-algebraic equations";
list<System> algebraic "Systems for algebraic equations";
list<System> ode_event "Systems for differential-algebraic event iteration";
list<System> alg_event "Systems for algebraic event iteration";
list<System> init "Systems for initialization";
Option<list<System>> init_0 "Systems for lambda 0 (homotopy) Initialization";
// add init_1 for lambda = 1 (test for efficency)
Option<list<System>> dae "Systems for dae mode";
VarData varData "Variable data.";
EqData eqData "Equation data.";
Events.EventInfo eventInfo "contains time and state events";
FunctionTree funcTree "Function bodies.";
end MAIN;
record JACOBIAN
String name "unique matrix name";
JacobianType jacType "type of jacobian";
VarData varData "Variable data.";
array<StrongComponent> comps "the sorted equations";
Jacobian.SparsityPattern sparsityPattern "Sparsity pattern for the jacobian";
Jacobian.SparsityColoring sparsityColoring "Coloring information";
end JACOBIAN;
record HESSIAN
VarData varData "Variable data.";
EqData eqData "Equation data.";
end HESSIAN;
function toString
input BackendDAE bdae;
input output String str = "";
algorithm
str := match bdae
local
String tmp = "";
case MAIN()
algorithm
if (listEmpty(bdae.ode) and listEmpty(bdae.algebraic) and listEmpty(bdae.ode_event) and listEmpty(bdae.alg_event))
or not Flags.isSet(Flags.BLT_DUMP) then
tmp := StringUtil.headline_1("BackendDAE: " + str) + "\n";
tmp := tmp + VarData.toString(bdae.varData, 2) + "\n" +
EqData.toString(bdae.eqData, 1);
else
tmp := tmp + System.toStringList(bdae.ode, "[ODE] Differential-Algebraic: " + str);
tmp := tmp + System.toStringList(bdae.algebraic, "[ALG] Algebraic: " + str);
tmp := tmp + System.toStringList(bdae.ode_event, "[ODE_EVENT] Event Handling: " + str);
tmp := tmp + System.toStringList(bdae.alg_event, "[ALG_EVENT] Event Handling: " + str);
tmp := tmp + System.toStringList(bdae.init, "[INI] Initialization: " + str);
if isSome(bdae.init_0) then
tmp := tmp + System.toStringList(Util.getOption(bdae.init_0), "[INI_0] Initialization Lambda=0: " + str);
end if;
if isSome(bdae.dae) then
tmp := tmp + System.toStringList(Util.getOption(bdae.dae), "[DAE] DAEMode: " + str);
end if;
end if;
tmp := tmp + Events.EventInfo.toString(bdae.eventInfo);
then tmp;
case JACOBIAN() algorithm
tmp := StringUtil.headline_1(Jacobian.jacobianTypeString(bdae.jacType) + " Jacobian " + bdae.name + ": " + str) + "\n";
tmp := tmp + BVariable.VarData.toString(bdae.varData, 1);
for i in 1:arrayLength(bdae.comps) loop
tmp := tmp + StrongComponent.toString(bdae.comps[i], i) + "\n";
end for;
tmp := tmp + SparsityPattern.toString(bdae.sparsityPattern) + "\n" + SparsityColoring.toString(bdae.sparsityColoring);
then tmp;
case HESSIAN() then StringUtil.headline_1("Hessian: " + str) + "\n" +
VarData.toString(bdae.varData, 1) + "\n" +
EqData.toString(bdae.eqData, 1);
else algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed."});
then fail();
end match;
end toString;
function getVarData
input BackendDAE bdae;
output VarData varData;
algorithm
varData := match bdae
case MAIN() then bdae.varData;
case JACOBIAN() then bdae.varData;
case HESSIAN() then bdae.varData;
else algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed!"});
then fail();
end match;
end getVarData;
function getFunctionTree
input BackendDAE bdae;
output FunctionTree funcTree;
algorithm
funcTree := match bdae
case MAIN(funcTree = funcTree) then funcTree;
else algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed! Only the record type MAIN() has a function tree."});
then fail();
end match;
end getFunctionTree;
function lower
"This function transforms the FlatModel structure to BackendDAE."
input FlatModel flatModel;
input FunctionTree funcTree;
output BackendDAE bdae;
protected
VarData variableData;
EqData equationData;
Events.EventInfo eventInfo = Events.EventInfo.empty();
algorithm
// expand records to its children. Put behind flag?
variableData := lowerVariableData(flatModel.variables);
(equationData, variableData) := lowerEquationData(flatModel.equations, flatModel.algorithms, flatModel.initialEquations, flatModel.initialAlgorithms, variableData);
bdae := MAIN({}, {}, {}, {}, {}, NONE(), NONE(), variableData, equationData, eventInfo, funcTree);
if Flags.isSet(Flags.DUMP_BACKENDDAE_INFO) then
Error.addSourceMessage(Error.BACKENDDAEINFO_LOWER,{
intString(EqData.scalarSize(equationData)) + " (" + intString(EqData.size(equationData)) + ")",
intString(VarData.scalarSize(variableData)) + " (" + intString(VarData.size(variableData)) + ")"},
AbsynUtil.dummyInfo);
end if;
end lower;
function main
input output BackendDAE bdae;
protected
list<tuple<Module.wrapper, String>> preOptModules;
list<tuple<Module.wrapper, String>> mainModules;
list<tuple<Module.wrapper, String>> postOptModules;
list<tuple<String, Real>> preOptClocks;
list<tuple<String, Real>> mainClocks;
list<tuple<String, Real>> postOptClocks;
algorithm
// Pre-Partitioning Modules
// (do not change order SIMPLIFY -> ALIAS -> EVENTS -> DETECTSTATES)
preOptModules := {
(Bindings.main, "Bindings"),
(FunctionAlias.main, "FunctionAlias"),
(function Inline.main(inline_types = {DAE.NORM_INLINE(), DAE.BUILTIN_EARLY_INLINE(), DAE.EARLY_INLINE(), DAE.DEFAULT_INLINE()}), "Early Inline"),
(simplify, "simplify1"),
(Alias.main, "Alias"),
(simplify, "simplify2"), // TODO simplify in Alias only
(Events.main, "Events"),
(DetectStates.main, "Detect States")
};
mainModules := {
(function Partitioning.main(systemType = NBSystem.SystemType.ODE), "Partitioning"),
(function Causalize.main(systemType = NBSystem.SystemType.ODE), "Causalize"),
(function Inline.main(inline_types = {DAE.AFTER_INDEX_RED_INLINE()}), "After Index Reduction Inline"),
(Initialization.main, "Initialization")
};
if Flags.getConfigBool(Flags.DAE_MODE) then
mainModules := (DAEMode.main, "DAE-Mode") :: mainModules;
end if;
// (do not change order SOLVE -> JACOBIAN)
postOptModules := {
(function Tearing.main(systemType = NBSystem.SystemType.ODE), "Tearing"),
(Partitioning.categorize, "Categorize"),
(Solve.main, "Solve"),
(function Jacobian.main(systemType = NBSystem.SystemType.ODE), "Jacobian")
};
(bdae, preOptClocks) := applyModules(bdae, preOptModules, ClockIndexes.RT_CLOCK_NEW_BACKEND_MODULE);
(bdae, mainClocks) := applyModules(bdae, mainModules, ClockIndexes.RT_CLOCK_NEW_BACKEND_MODULE);
(bdae, postOptClocks) := applyModules(bdae, postOptModules, ClockIndexes.RT_CLOCK_NEW_BACKEND_MODULE);
if Flags.isSet(Flags.DUMP_BACKEND_CLOCKS) then
if not listEmpty(preOptClocks) then
print(StringUtil.headline_4("Pre-Opt Backend Clocks:"));
print(stringDelimitList(list(Module.moduleClockString(clck) for clck in preOptClocks), "\n") + "\n");
end if;
if not listEmpty(mainClocks) then
print(StringUtil.headline_4("Main Backend Clocks:"));
print(stringDelimitList(list(Module.moduleClockString(clck) for clck in mainClocks), "\n") + "\n");
end if;
if not listEmpty(postOptClocks) then
print(StringUtil.headline_4("Post-Opt Backend Clocks:"));
print(stringDelimitList(list(Module.moduleClockString(clck) for clck in postOptClocks), "\n") + "\n\n");
end if;
end if;
backenddaeinfo(bdae);
end main;
function applyModules
input output BackendDAE bdae;
input list<tuple<Module.wrapper, String>> modules;
input Integer clock_idx;
output list<tuple<String, Real>> module_clocks = {};
protected
Module.wrapper func;
String name, debugStr;
Real clock_time;
Integer length;
algorithm
for module in modules loop
(func, name) := module;
debugStr := "[failtrace] ........ [" + ClockIndexes.toString(clock_idx) + "] " + name;
debugStr := debugStr + StringUtil.repeat(".", 60 - stringLength(debugStr));
if clock_idx <> -1 then
BuiltinSystem.realtimeClear(clock_idx);
BuiltinSystem.realtimeTick(clock_idx);
try
bdae := func(bdae);
else
if Flags.isSet(Flags.FAILTRACE) then
debugStr := debugStr + " failed\n";
print(debugStr);
end if;
fail();
end try;
clock_time := BuiltinSystem.realtimeTock(clock_idx);
ExecStat.execStat(name);
module_clocks := (name, clock_time) :: module_clocks;
if Flags.isSet(Flags.FAILTRACE) then
debugStr := debugStr + " " + realString(clock_time) + "s\n";
print(debugStr);
end if;
else
bdae := func(bdae);
end if;
if Flags.isSet(Flags.OPT_DAE_DUMP) or (Flags.isSet(Flags.BLT_DUMP) and (name == "Causalize" or name == "Solve")) then
print(toString(bdae, "(" + name + ")"));
end if;
end for;
module_clocks := listReverse(module_clocks);
end applyModules;
function simplify
"ToDo: add simplification for bindings"
input output BackendDAE bdae;
algorithm
// no output needed, all pointers
() := match bdae
local
EquationPointers equations;
case MAIN(eqData = BEquation.EQ_DATA_SIM(equations = equations)) algorithm
_ := EquationPointers.map(equations, function Equation.simplify(name = getInstanceName(), indent = ""));
then ();
else ();
end match;
end simplify;
function getLoopResiduals
input BackendDAE bdae;
output VariablePointers residuals;
algorithm
residuals := match bdae
local
list<Pointer<Variable>> var_lst = {};
case MAIN() algorithm
for syst in bdae.ode loop
var_lst := listAppend(System.getLoopResiduals(syst), var_lst);
end for;
for syst in bdae.algebraic loop
var_lst := listAppend(System.getLoopResiduals(syst), var_lst);
end for;
for syst in bdae.ode_event loop
var_lst := listAppend(System.getLoopResiduals(syst), var_lst);
end for;
for syst in bdae.alg_event loop
var_lst := listAppend(System.getLoopResiduals(syst), var_lst);
end for;
for syst in bdae.init loop
var_lst := listAppend(System.getLoopResiduals(syst), var_lst);
end for;
residuals := VariablePointers.fromList(var_lst);
then residuals;
else VariablePointers.empty();
end match;
end getLoopResiduals;
protected
function lowerVariableData
"Lowers all variables to backend structure.
kabdelhak: Splitting up the creation of the variable array and the variable
pointer arrays in two steps is slightly less effective, but way more readable
and maintainable."
input list<Variable> varList;
output VarData variableData;
protected
Variable lowVar;
list<Variable> vars;
Pointer<Variable> lowVar_ptr, time_ptr, dummy_ptr;
list<Pointer<Variable>> unknowns_lst = {}, knowns_lst = {}, initials_lst = {}, auxiliaries_lst = {}, aliasVars_lst = {}, nonTrivialAlias_lst = {};
list<Pointer<Variable>> states_lst = {}, derivatives_lst = {}, algebraics_lst = {}, discretes_lst = {}, discrete_states_lst = {}, previous_lst = {};
list<Pointer<Variable>> inputs_lst = {}, parameters_lst = {}, constants_lst = {}, records_lst = {}, artificials_lst = {};
VariablePointers variables, unknowns, knowns, initials, auxiliaries, aliasVars, nonTrivialAlias;
VariablePointers states, derivatives, algebraics, discretes, discrete_states, previous;
VariablePointers inputs, parameters, constants, records, artificials;
Pointer<list<Pointer<Variable>>> binding_iter_lst = Pointer.create({});
Boolean scalarized = Flags.isSet(Flags.NF_SCALARIZE);
algorithm
vars := List.flatten(list(Variable.expandChildren(v) for v in varList));
// instantiate variable data (with one more space for time variable);
variables := VariablePointers.empty(listLength(vars) + 1, scalarized);
// create dummy and time var and add then
// needed to make function BVariable.getVarPointer() more universally applicable
dummy_ptr := Pointer.create(NBVariable.DUMMY_VARIABLE);
time_ptr := BVariable.createTimeVar();
variables := VariablePointers.add(dummy_ptr, variables);
variables := VariablePointers.add(time_ptr, variables);
artificials_lst := {dummy_ptr, time_ptr};
// routine to prepare the lists for pointer arrays
for var in listReverse(vars) loop
lowVar_ptr := lowerVariable(var);
lowVar := Pointer.access(lowVar_ptr);
variables := VariablePointers.add(lowVar_ptr, variables);
() := match lowVar.backendinfo.varKind
case _ guard(Variable.isTopLevelInput(var)) algorithm
inputs_lst := lowVar_ptr :: inputs_lst;
knowns_lst := lowVar_ptr :: knowns_lst;
then ();
case BackendExtension.ALGEBRAIC() algorithm
algebraics_lst := lowVar_ptr :: algebraics_lst;
unknowns_lst := lowVar_ptr :: unknowns_lst;
initials_lst := lowVar_ptr :: initials_lst;
then ();
case BackendExtension.STATE() algorithm
states_lst := lowVar_ptr :: states_lst;
knowns_lst := lowVar_ptr :: knowns_lst;
initials_lst := lowVar_ptr :: initials_lst;
then ();
case BackendExtension.STATE_DER() algorithm
derivatives_lst := lowVar_ptr :: derivatives_lst;
unknowns_lst := lowVar_ptr :: unknowns_lst;
initials_lst := lowVar_ptr :: initials_lst;
then ();
case BackendExtension.DISCRETE() algorithm
discretes_lst := lowVar_ptr :: discretes_lst;
unknowns_lst := lowVar_ptr :: unknowns_lst;
initials_lst := lowVar_ptr :: initials_lst;
then ();
case BackendExtension.PREVIOUS() algorithm
previous_lst := lowVar_ptr :: previous_lst;
knowns_lst := lowVar_ptr :: knowns_lst;
initials_lst := lowVar_ptr :: initials_lst;
then ();
case BackendExtension.PARAMETER() algorithm
parameters_lst := lowVar_ptr :: parameters_lst;
knowns_lst := lowVar_ptr :: knowns_lst;
then ();
case BackendExtension.CONSTANT() algorithm
constants_lst := lowVar_ptr :: constants_lst;
knowns_lst := lowVar_ptr :: knowns_lst;
then ();
case BackendExtension.RECORD() algorithm
records_lst := lowVar_ptr :: records_lst;
knowns_lst := lowVar_ptr :: knowns_lst;
then ();
/* other cases should not occur up until now */
else algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed for " + Variable.toString(var)});
then fail();
end match;
end for;
// create pointer arrays
unknowns := VariablePointers.fromList(unknowns_lst, scalarized);
knowns := VariablePointers.fromList(knowns_lst, scalarized);
initials := VariablePointers.fromList(initials_lst, scalarized);
auxiliaries := VariablePointers.fromList(auxiliaries_lst, scalarized);
aliasVars := VariablePointers.fromList(aliasVars_lst, scalarized);
nonTrivialAlias := VariablePointers.fromList(nonTrivialAlias_lst, scalarized);
states := VariablePointers.fromList(states_lst, scalarized);
derivatives := VariablePointers.fromList(derivatives_lst, scalarized);
algebraics := VariablePointers.fromList(algebraics_lst, scalarized);
discretes := VariablePointers.fromList(discretes_lst, scalarized);
discrete_states := VariablePointers.fromList(discrete_states_lst, scalarized);
previous := VariablePointers.fromList(previous_lst, scalarized);
inputs := VariablePointers.fromList(inputs_lst, scalarized);
parameters := VariablePointers.fromList(parameters_lst, scalarized);
constants := VariablePointers.fromList(constants_lst, scalarized);
records := VariablePointers.fromList(records_lst, scalarized);
artificials := VariablePointers.fromList(artificials_lst, scalarized);
/* lower the variable bindings and add binding iterators */
variables := VariablePointers.map(variables, function collectVariableBindingIterators(variables = variables, binding_iter_lst = binding_iter_lst));
variables := VariablePointers.addList(Pointer.access(binding_iter_lst), variables);
knowns := VariablePointers.addList(Pointer.access(binding_iter_lst), knowns);
artificials := VariablePointers.addList(Pointer.access(binding_iter_lst), artificials);
variables := VariablePointers.map(variables, function Variable.mapExp(fn = function lowerComponentReferenceExp(variables = variables)));
/* lower the records to add children */
records := VariablePointers.map(records, function lowerRecordChildren(variables = variables));
/* create variable data */
variableData := BVariable.VAR_DATA_SIM(variables, unknowns, knowns, initials, auxiliaries, aliasVars, nonTrivialAlias,
derivatives, algebraics, discretes, discrete_states, previous, states, inputs, parameters, constants, records, artificials);
end lowerVariableData;
function lowerVariable
input Variable var;
output Pointer<Variable> var_ptr;
protected
BackendExtension.VariableKind varKind;
BackendExtension.VariableAttributes attributes;
BackendExtension.Annotations annotations;
algorithm
// ToDo! extract tearing select option
try
attributes := BackendExtension.VariableAttributes.create(var.typeAttributes, var.ty, var.attributes, var.children, var.comment);
annotations := BackendExtension.Annotations.create(var.comment);
// only change varKind if unset (Iterators are set before)
var.backendinfo := match var.backendinfo
case BackendExtension.BACKEND_INFO(varKind = BackendExtension.FRONTEND_DUMMY()) algorithm
(varKind, attributes) := lowerVariableKind(Variable.variability(var), attributes, var.ty);
then BackendExtension.BACKEND_INFO(varKind, attributes, annotations, NONE());
else BackendExtension.BackendInfo.setAttributes(var.backendinfo, attributes, annotations);
end match;
// Remove old type attribute information since it has been converted.
var.typeAttributes := {};
// This creates a cyclic dependency, be aware of that!
(var_ptr, _) := BVariable.makeVarPtrCyclic(var, var.name);
else
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed for " + Variable.toString(var)});
fail();
end try;
end lowerVariable;
function lowerVariableKind
"ToDo: Merge this part from old backend conversion:
/* Consider toplevel inputs as known unless they are protected. Ticket #5591 */
false := DAEUtil.topLevelInput(inComponentRef, inVarDirection, inConnectorType, protection);"
input Prefixes.Variability variability;
output BackendExtension.VariableKind varKind;
input output BackendExtension.VariableAttributes attributes;
input Type ty;
algorithm
varKind := match(variability, attributes, ty)
local
list<Pointer<Variable>> children = {};
// variable -> artificial state if it has stateSelect = StateSelect.always
case (NFPrefixes.Variability.CONTINUOUS, BackendExtension.VAR_ATTR_REAL(stateSelect = SOME(NFBackendExtension.StateSelect.ALWAYS)), _)
guard(variability == NFPrefixes.Variability.CONTINUOUS)
then BackendExtension.STATE(1, NONE(), false);
// add children pointers for records afterwards
case (_, _, Type.COMPLEX()) then BackendExtension.RECORD({});
case (_, _, _) guard(Type.isComplexArray(ty)) then BackendExtension.RECORD({});
case (NFPrefixes.Variability.CONTINUOUS, _, Type.BOOLEAN()) then BackendExtension.DISCRETE();
case (NFPrefixes.Variability.CONTINUOUS, _, Type.INTEGER()) then BackendExtension.DISCRETE();
case (NFPrefixes.Variability.CONTINUOUS, _, Type.ENUMERATION()) then BackendExtension.DISCRETE();
case (NFPrefixes.Variability.CONTINUOUS, _, _) then BackendExtension.ALGEBRAIC();
case (NFPrefixes.Variability.DISCRETE, _, _) then BackendExtension.DISCRETE();
case (NFPrefixes.Variability.IMPLICITLY_DISCRETE, _, _) then BackendExtension.DISCRETE();
case (NFPrefixes.Variability.PARAMETER, _, _) then BackendExtension.PARAMETER();
case (NFPrefixes.Variability.STRUCTURAL_PARAMETER, _, _) then BackendExtension.PARAMETER(); // CONSTANT ?
case (NFPrefixes.Variability.NON_STRUCTURAL_PARAMETER, _, _) then BackendExtension.PARAMETER();
case (NFPrefixes.Variability.CONSTANT, _, _) then BackendExtension.CONSTANT();
else algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed."});
then fail();
end match;
// make adjustments to attributes based on variable kind
attributes := match varKind
case BackendExtension.PARAMETER() then BackendExtension.VariableAttributes.setFixed(attributes, ty, true, false);
else attributes;
end match;
end lowerVariableKind;
function collectVariableBindingIterators
input output Variable var;
input VariablePointers variables;
input Pointer<list<Pointer<Variable>>> binding_iter_lst;
protected
Option<Expression> exp_opt;
algorithm
BackendExtension.BackendInfo.map(var.backendinfo, function collectBindingIterators(variables = variables, binding_iter_lst = binding_iter_lst));
exp_opt := Binding.typedExp(var.binding);
if isSome(exp_opt) then
Expression.map(Util.getOption(exp_opt), function collectBindingIterators(variables = variables, binding_iter_lst = binding_iter_lst));
end if;
end collectVariableBindingIterators;
function lowerRecordChildren
input output Variable var;
input VariablePointers variables;
algorithm
var := match var
local
BackendExtension.BackendInfo binfo;
BackendExtension.VariableKind varKind;
case Variable.VARIABLE(backendinfo = binfo as BackendExtension.BACKEND_INFO(varKind = varKind as BackendExtension.RECORD())) algorithm
// kabdelhak: why is this list reversed in the frontend? doesnt match input order
varKind.children := listReverse(list(VariablePointers.getVarSafe(variables, ComponentRef.stripSubscriptsAll(child.name)) for child in var.children));
binfo.varKind := varKind;
var.backendinfo := binfo;
then var;
else var;
end match;
end lowerRecordChildren;
function lowerEquationData
"Lowers all equations to backend structure.
kabdelhak: Splitting up the creation of the equation array and the equation
pointer arrays in two steps is slightly less effective, but way more readable
and maintainable."
input list<FEquation> eq_lst;
input list<Algorithm> al_lst;
input list<FEquation> init_eq_lst;
input list<Algorithm> init_al_lst;
output EqData eqData;
input output VarData varData;
protected
list<ComponentRef> iterators = {};
list<Pointer<Equation>> equation_lst, continuous_lst, discretes_lst, initials_lst, auxiliaries_lst, simulation_lst, removed_lst;
EquationPointers equations;
Pointer<Equation> eq;
Pointer<Integer> idx = Pointer.create(0);
algorithm
equation_lst := lowerEquationsAndAlgorithms(eq_lst, al_lst, init_eq_lst, init_al_lst);
for eqn_ptr in equation_lst loop
Equation.createName(eqn_ptr, idx, NBEquation.SIMULATION_STR);
iterators := listAppend(Equation.getForIteratorCrefs(Pointer.access(eqn_ptr)), iterators);
end for;
iterators := List.uniqueOnTrue(iterators, ComponentRef.isEqual);
varData := VarData.addTypedList(varData, list(lowerIterator(iter) for iter in iterators), NBVariable.VarData.VarType.ITERATOR);
equations := EquationPointers.fromList(equation_lst);
equations := lowerComponentReferences(equations, VarData.getVariables(varData));
(simulation_lst, continuous_lst, discretes_lst, initials_lst, auxiliaries_lst, removed_lst) := BEquation.typeList(EquationPointers.toList(equations));
eqData := BEquation.EQ_DATA_SIM(
uniqueIndex = idx,
equations = equations,
simulation = EquationPointers.fromList(simulation_lst),
continuous = EquationPointers.fromList(continuous_lst),
discretes = EquationPointers.fromList(discretes_lst),
initials = EquationPointers.fromList(initials_lst),
auxiliaries = EquationPointers.fromList(auxiliaries_lst),
removed = EquationPointers.fromList(removed_lst)
);
end lowerEquationData;
function lowerEquationsAndAlgorithms
"ToDo! Replace instNode in all Crefs
Converts all frontend equations and algorithms to backend equations."
input list<FEquation> eq_lst;
input list<Algorithm> al_lst;
input list<FEquation> init_eq_lst;
input list<Algorithm> init_al_lst;
output list<Pointer<Equation>> equations = {};
algorithm
// ---------------------------
// convert all equations
// ---------------------------
for eq in eq_lst loop
// returns a list of equations since for and if equations might be split up
equations := listAppend(lowerEquation(eq, false), equations);
end for;
// ---------------------------
// convert all algorithms
// ---------------------------
for alg in al_lst loop
equations := lowerAlgorithm(alg, false) :: equations;
end for;
// ---------------------------
// convert all initial equations
// ---------------------------
for eq in init_eq_lst loop
// returns a list of equations since for and if equations might be split up
equations := listAppend(lowerEquation(eq, true), equations);
end for;
// ---------------------------
// convert all initial algorithms
// ---------------------------
for alg in init_al_lst loop
equations := lowerAlgorithm(alg, true) :: equations;
end for;
end lowerEquationsAndAlgorithms;
function lowerEquation
input FEquation frontend_equation "Original Frontend equation.";
input Boolean init "True if an initial equation should be created.";
output list<Pointer<Equation>> backend_equations "Resulting Backend equations.";
algorithm
backend_equations := match frontend_equation
local
list<Pointer<Equation>> result = {}, new_body = {};
Equation body_elem;
Expression lhs, rhs, range;
ComponentRef lhs_cref, rhs_cref;
list<FEquation> body;
Type ty;
DAE.ElementSource source;
ComponentRef iterator;
list<FEquation.Branch> branches;
EquationAttributes attr;
Integer rec_size;
Statement stmt;
Algorithm alg;
case FEquation.ARRAY_EQUALITY(lhs = lhs, rhs = rhs, ty = ty, source = source)
guard(Type.isArray(ty)) algorithm
attr := lowerEquationAttributes(ty, init);
then {Pointer.create(BEquation.ARRAY_EQUATION(ty, lhs, rhs, source, attr, Type.complexSize(ty)))};
case FEquation.EQUALITY(lhs = lhs, rhs = rhs, ty = ty, source = source) algorithm
attr := lowerEquationAttributes(ty, init);
result := match ty
case Type.ARRAY() then {Pointer.create(BEquation.ARRAY_EQUATION(ty, lhs, rhs, source, attr, Type.complexSize(ty)))};
case Type.COMPLEX() then {Pointer.create(BEquation.RECORD_EQUATION(ty, lhs, rhs, source, attr, Type.sizeOf(ty)))};
case Type.TUPLE() then {Pointer.create(BEquation.RECORD_EQUATION(ty, lhs, rhs, source, attr, Type.sizeOf(ty)))};
else {Pointer.create(BEquation.SCALAR_EQUATION(ty, lhs, rhs, source, attr))};
end match;
then result;
case FEquation.FOR(range = SOME(range)) algorithm
if Expression.rangeSize(range) > 0 then
// Treat each body equation individually because they can have different equation attributes
// E.g.: DISCRETE, EvalStages
iterator := ComponentRef.fromNode(frontend_equation.iterator, Type.INTEGER(), {}, NFComponentRef.Origin.ITERATOR);
for eq in frontend_equation.body loop
new_body := listAppend(lowerEquation(eq, init), new_body);
end for;
for body_elem_ptr in new_body loop
body_elem := Pointer.access(body_elem_ptr);
body_elem := BEquation.FOR_EQUATION(
size = Expression.rangeSize(range) * Equation.size(body_elem_ptr),
iter = Iterator.SINGLE(iterator, range),
body = {body_elem},
source = frontend_equation.source,
attr = Equation.getAttributes(body_elem)
);
// merge iterators of each for equation instead of having nested loops (for {i in 1:10, j in 1:3, k in 1:5})
body_elem := Equation.mergeIterators(body_elem);
// inline if size 1
body_elem := Inline.inlineForEquation(body_elem);
Pointer.update(body_elem_ptr, body_elem);
result := body_elem_ptr :: result;
end for;
else
if Flags.isSet(Flags.FAILTRACE) then
Error.addMessage(Error.COMPILER_WARNING,{getInstanceName()
+ ": Empty for-equation got removed:\n" + FEquation.toString(frontend_equation)});
end if;
end if;
then result;
// if equation
case FEquation.IF() then {Pointer.create(lowerIfEquation(frontend_equation, init))};
// When equation cases
case FEquation.WHEN() then lowerWhenEquation(frontend_equation, init);
case FEquation.ASSERT() then lowerWhenEquation(frontend_equation, init);
// wrap no return call in algorithm
case FEquation.NORETCALL() algorithm
stmt := Statement.NORETCALL(frontend_equation.exp, frontend_equation.source);
alg := Algorithm.ALGORITHM({stmt}, {}, {}, InstNode.EMPTY_NODE(), frontend_equation.source);
alg := Algorithm.setInputsOutputs(alg);
then {lowerAlgorithm(alg, init)};
// These have to be called inside a when equation body since they need
// to get passed a condition from surrounding when equation.
case FEquation.TERMINATE() algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed for TERMINATE expression without condition:\n" + FEquation.toString(frontend_equation)});
then fail();
case FEquation.REINIT() algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed for REINIT expression without condition:\n" + FEquation.toString(frontend_equation)});
then fail();
else algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed for\n" + FEquation.toString(frontend_equation)});
then fail();
end match;
end lowerEquation;
function lowerIfEquation
input FEquation frontend_equation;
input Boolean init;
output Equation backend_equation;
algorithm
backend_equation := match frontend_equation
local
list<FEquation.Branch> branches;
DAE.ElementSource source;
IfEquationBody ifEqBody;
EquationAttributes attr;
case FEquation.IF(branches = branches, source = source)
algorithm
attr := EquationAttributes.default(EquationKind.CONTINUOUS, init);
SOME(ifEqBody) := lowerIfEquationBody(branches, init);
// ToDo: compute correct size
then BEquation.IF_EQUATION(IfEquationBody.size(ifEqBody), ifEqBody, source, attr);
else algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed for\n" + FEquation.toString(frontend_equation)});
then fail();
end match;
end lowerIfEquation;
function lowerIfEquationBody
input list<FEquation.Branch> branches;
input Boolean init;
output Option<IfEquationBody> ifEq;
algorithm
ifEq := match branches
local
FEquation.Branch branch;
list<FEquation.Branch> rest;
list<Pointer<Equation>> eqns;
Expression condition;
Option<IfEquationBody> result;
// lower current branch
case branch::rest
algorithm
(eqns, condition) := lowerIfBranch(branch, init);
if Expression.isTrue(condition) then
// finish recursion when a condition is found to be true because
// following branches can never be reached. Also the last plain else
// case has default Boolean true value in the NF.
result := SOME(BEquation.IF_EQUATION_BODY(Expression.END(), eqns, NONE()));
elseif Expression.isFalse(condition) then
// discard a branch and continue with the rest if a condition is
// found to be false, because it can never be reached.
result := lowerIfEquationBody(rest, init);
else
result := SOME(BEquation.IF_EQUATION_BODY(condition, eqns, lowerIfEquationBody(rest, init)));
end if;
then result;
// We should never get an empty list here since the last condition has to
// be TRUE. If-Equations have to have a plain else case for consistency!
else algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed for:\n"
+ List.toString(branches, function FEquation.Branch.toString(indent = ""), "", "\t", "\n", "\n")});
then fail();
end match;
end lowerIfEquationBody;
function lowerIfBranch
input FEquation.Branch branch;
input Boolean init;
output list<Pointer<Equation>> eqns;
output Expression cond;
algorithm
(eqns, cond) := match branch
local
Expression condition;
list<FEquation.Equation> body;
case FEquation.BRANCH(condition = condition, body = body) guard(not Expression.isFalse(condition))
// ToDo! Use condition variability here to have proper type of the
// auxiliary that will be created for the condition.
then (lowerIfBranchBody(body, init), condition);
// Save some time by not lowering body if condition is false.
case FEquation.BRANCH(condition = condition, body = body) guard(Expression.isFalse(condition))
then ({}, condition);
case FEquation.INVALID_BRANCH() algorithm
// what to do with error message from invalid branch? Is that even needed?
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed for invalid branch that should not exist outside of frontend."});
then fail();
else algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed without proper error message."});
then fail();
end match;
end lowerIfBranch;
function lowerIfBranchBody
input list<FEquation.Equation> body;
input Boolean init;
input output list<Pointer<Equation>> eqns = {};
algorithm
eqns := match body
local
FEquation.Equation elem;
list<FEquation.Equation> rest;
case {} then eqns;
case elem::rest then lowerIfBranchBody(rest, init, listAppend(lowerEquation(elem, init), eqns));
end match;
end lowerIfBranchBody;
function lowerWhenEquation
input FEquation frontend_equation;
input Boolean init;
output list<Pointer<Equation>> backend_equations;
algorithm
backend_equations := match frontend_equation
local
list<FEquation.Branch> branches;
DAE.ElementSource source;
Expression condition, message, level;
BEquation.WhenEquationBody whenEqBody;
list<BEquation.WhenEquationBody> bodies;
EquationAttributes attr;
case FEquation.WHEN(branches = branches, source = source)
algorithm
// When equation inside initial actually not allowed. Throw error?
SOME(whenEqBody) := lowerWhenEquationBody(branches);
bodies := BEquation.WhenEquationBody.split(whenEqBody);
then list(Pointer.create(BEquation.WHEN_EQUATION(
size = BEquation.WhenEquationBody.size(b),
body = b,
source = source,
attr = EquationAttributes.default(if BEquation.WhenEquationBody.size(b) > 0 then EquationKind.DISCRETE else EquationKind.EMPTY, init)
)) for b in bodies);
case FEquation.ASSERT(condition = condition, message = message, level = level, source = source)
algorithm
attr := EquationAttributes.default(EquationKind.EMPTY, init);
whenEqBody := BEquation.WHEN_EQUATION_BODY(condition, {BEquation.ASSERT(condition, message, level, source)}, NONE());
then {Pointer.create(BEquation.WHEN_EQUATION(0, whenEqBody, source, attr))};
else algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed for " + FEquation.toString(frontend_equation)});
then fail();
end match;
end lowerWhenEquation;
function lowerWhenEquationBody
input list<FEquation.Branch> branches;
output Option<BEquation.WhenEquationBody> whenEq;
algorithm
whenEq := match branches
local
FEquation.Branch branch;
list<FEquation.Branch> rest;
list<BEquation.WhenStatement> stmts;
Expression condition;
// End of the line
case {} then NONE();
// lower current branch
case branch::rest
algorithm
(stmts, condition) := lowerWhenBranch(branch);
then SOME(BEquation.WHEN_EQUATION_BODY(condition, stmts, lowerWhenEquationBody(rest)));
else algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed."});
then fail();
end match;
end lowerWhenEquationBody;
function lowerWhenBranch
input FEquation.Branch branch;
output list<BEquation.WhenStatement> stmts;
output Expression cond;
algorithm
(stmts, cond) := match branch
local
Expression condition;
list<FEquation.Equation> body;
case FEquation.BRANCH(condition = condition, body = body)
// ToDo! Use condition variability here to have proper type of the
// auxiliary that will be created for the condition.
then (lowerWhenBranchBody(condition, body), condition);
case FEquation.INVALID_BRANCH() algorithm
// what to do with error message from invalid branch? Is that even needed?