/
Initialization.mo
2737 lines (2396 loc) · 115 KB
/
Initialization.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-2014, 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 Initialization
" file: Initialization.mo
package: Initialization
description: Initialization.mo contains everything needed to set up the
BackendDAE for the initial system.
"
public
import Absyn;
import BackendDAE;
import BackendDAEFunc;
import DAE;
import HashSet;
import Util;
protected
import Array;
import BackendDAEEXT;
import BackendDAEOptimize;
import BackendDAEUtil;
import BackendDump;
import BackendEquation;
import BackendVarTransform;
import BackendVariable;
import BaseHashSet;
import CheckModel;
import ComponentReference;
import DoubleEnded;
import ElementSource;
import Error;
import ExecStat.execStat;
import Expression;
import ExpressionDump;
import ExpressionSimplify;
import Flags;
import GC;
import IndexReduction;
import List;
import Matching;
import MetaModelica.Dangerous;
import Sorting;
import SymbolicJacobian;
// =============================================================================
// section for all public functions
//
// These are functions that can be used to access the initialization.
// =============================================================================
public function solveInitialSystem "author: lochel
This function generates a algebraic system of equations for the initialization and solves it."
input BackendDAE.BackendDAE inDAE "simulation system";
output BackendDAE.BackendDAE outInitDAE "initialization system";
output Option<BackendDAE.BackendDAE> outInitDAE_lambda0 "initialization system for lambda=0";
output list<BackendDAE.Equation> outRemovedInitialEquations;
output BackendDAE.Variables outGlobalKnownVars;
output BackendDAE.BackendDAE outSimDAE = inDAE "updated with fixed attribute";
protected
BackendDAE.BackendDAE dae;
BackendDAE.BackendDAE initdae;
BackendDAE.BackendDAE initdae0;
BackendDAE.EqSystem initsyst;
BackendDAE.EqSystems systs;
BackendDAE.EquationArray eqns, reeqns;
BackendDAE.Shared shared;
BackendDAE.Variables initVars;
BackendDAE.Variables vars, fixvars;
Boolean b, b1, b2, useHomotopy, datarecon=false;
String msg;
list<String> enabledModules, disabledModules;
HashSet.HashSet hs "contains all pre variables";
list<BackendDAE.Equation> removedEqns;
list<BackendDAE.Var> dumpVars, dumpVars2, outAllPrimaryParameters;
AvlSetCR.Tree allPrimaryParameters;
list<tuple<BackendDAEFunc.optimizationModule, String>> initOptModules, initOptModulesLambda0;
tuple<BackendDAEFunc.StructurallySingularSystemHandlerFunc, String, BackendDAEFunc.stateDeselectionFunc, String> daeHandler;
tuple<BackendDAEFunc.matchingAlgorithmFunc, String> matchingAlgorithm;
algorithm
try
//if Flags.isSet(Flags.DUMP_INITIAL_SYSTEM) then
// BackendDump.dumpBackendDAE(inDAE, "inDAE for initialization");
//end if;
// inline all when equations, if active with body else with lhs=pre(lhs)
dae := inlineWhenForInitialization(inDAE);
//if Flags.isSet(Flags.DUMP_INITIAL_SYSTEM) then
// BackendDump.dumpBackendDAE(dae, "inlineWhenForInitialization");
//end if;
execStat("inlineWhenForInitialization (initialization)");
(dae, initVars, outAllPrimaryParameters, outGlobalKnownVars) := selectInitializationVariablesDAE(dae);
if Flags.isSet(Flags.DUMP_INITIAL_SYSTEM) then
BackendDump.dumpVarList(outAllPrimaryParameters, "selected all primary parameters");
end if;
execStat("selectInitializationVariablesDAE (initialization)");
hs := collectPreVariables(dae);
execStat("collectPreVariables (initialization)");
// collect vars and eqns for initial system
vars := BackendVariable.emptyVars();
// If Cpp runtime is used set fixvars to emptyVars because otherwise Cpp testcases fail
// This is wrong and leads to bigger initialization tearing sets than necessary!!!
// To-Do: Fix the problems with the Cpp runtime
if (stringEq(Config.simCodeTarget(), "Cpp"))then
fixvars := BackendVariable.emptyVars();
else
fixvars := BackendVariable.listVar(outAllPrimaryParameters);
end if;
eqns := BackendEquation.emptyEqnsSized(BackendVariable.varsSize(dae.shared.aliasVars)
+ BackendVariable.varsSize(dae.shared.globalKnownVars)
+ BackendVariable.varsSize(dae.shared.localKnownVars)
+ BackendEquation.getNumberOfEquations(dae.shared.initialEqs)
+ 2*BackendDAEUtil.daeSize(dae));
reeqns := BackendEquation.emptyEqnsSized(BackendEquation.getNumberOfEquations(dae.shared.removedEqs));
allPrimaryParameters := AvlSetCR.EMPTY();
for v in outAllPrimaryParameters loop
allPrimaryParameters := AvlSetCR.add(allPrimaryParameters, BackendVariable.varCref(v));
end for;
// check for datareconciliation and set the Flag, to set the Qualified Component names as TopLevel Input
if Util.isSome(inDAE.shared.dataReconciliationData) then
datarecon := true;
end if;
((vars, fixvars, eqns, _)) := BackendVariable.traverseBackendDAEVars(dae.shared.aliasVars, introducePreVarsForAliasVariables, (vars, fixvars, eqns, hs));
((vars, fixvars, eqns, _, _, _, _)) := BackendVariable.traverseBackendDAEVars(dae.shared.globalKnownVars, collectInitialVars, (vars, fixvars, eqns, arrayCreate(0,0), hs, allPrimaryParameters,datarecon));
((vars, fixvars, eqns, _, _, _, _)) := BackendVariable.traverseBackendDAEVars(dae.shared.localKnownVars, collectInitialVars, (vars, fixvars, eqns, arrayCreate(0,0), hs, allPrimaryParameters,datarecon));
((eqns, reeqns)) := BackendEquation.traverseEquationArray(dae.shared.initialEqs, collectInitialEqns, (eqns, reeqns));
((eqns, reeqns)) := BackendEquation.traverseEquationArray(dae.shared.removedEqs, collectInitialEqns, (eqns, reeqns));
//if Flags.isSet(Flags.DUMP_INITIAL_SYSTEM) then
// BackendDump.dumpEquationArray(eqns, "initial equations");
//end if;
execStat("collectInitialEqns (initialization)");
//((vars, fixvars, eqns, reeqns, _, _)) := List.fold(dae.eqs, collectInitialVarsEqnsSystem, ((vars, fixvars, eqns, reeqns, hs, allPrimaryParameters)));
(vars, fixvars, eqns, reeqns) := collectInitialVarsEqnsSystem(dae.eqs, vars, fixvars, eqns, reeqns, hs, allPrimaryParameters, datarecon);
((eqns, reeqns)) := BackendVariable.traverseBackendDAEVars(vars, collectInitialBindings, (eqns, reeqns));
execStat("collectInitialBindings (initialization)");
// replace initial(), sample(...), delay(...) and homotopy(...)
useHomotopy := BackendDAEUtil.traverseBackendDAEExpsEqns(eqns, simplifyInitialFunctions, false);
execStat("simplifyInitialFunctions (initialization)");
vars := BackendVariable.rehashVariables(vars);
fixvars := BackendVariable.rehashVariables(fixvars);
shared := BackendDAEUtil.createEmptyShared(BackendDAE.INITIALSYSTEM(), dae.shared.info, dae.shared.cache, dae.shared.graph);
shared := BackendDAEUtil.setSharedRemovedEqns(shared, BackendEquation.emptyEqns());
shared := BackendDAEUtil.setSharedGlobalKnownVars(shared, fixvars);
shared := BackendDAEUtil.setSharedOptimica(shared, dae.shared.constraints, dae.shared.classAttrs);
shared := BackendDAEUtil.setSharedFunctionTree(shared, dae.shared.functionTree);
execStat("setup shared object (initialization)");
// generate initial system and pre-balance it
initsyst := BackendDAEUtil.createEqSystem(vars, eqns);
initsyst := BackendDAEUtil.setEqSystRemovedEqns(initsyst, reeqns);
(initsyst, dumpVars) := preBalanceInitialSystem(initsyst);
execStat("preBalanceInitialSystem (initialization)");
// split the initial system into independend subsystems
initdae := BackendDAE.DAE({initsyst}, shared);
if Flags.isSet(Flags.OPT_DAE_DUMP) then
BackendDump.dumpBackendDAE(initdae, "created initial system");
end if;
if Flags.isSet(Flags.PARTITION_INITIALIZATION) then
(systs, shared) := BackendDAEOptimize.partitionIndependentBlocksHelper(initsyst, shared, Error.getNumErrorMessages(), true);
initdae := BackendDAE.DAE(systs, shared);
execStat("partitionIndependentBlocks (initialization)");
end if;
if Flags.isSet(Flags.OPT_DAE_DUMP) then
BackendDump.dumpBackendDAE(initdae, "partitioned initial system");
end if;
// initdae := BackendDAE.DAE({initsyst}, shared);
// fix over- and under-constrained subsystems
(initdae, dumpVars2, removedEqns) := analyzeInitialSystem(initdae, initVars);
dumpVars := listAppend(dumpVars, dumpVars2);
execStat("analyzeInitialSystem (initialization)");
// some debug prints
if Flags.isSet(Flags.DUMP_INITIAL_SYSTEM) then
BackendDump.dumpBackendDAE(initdae, "initial system");
end if;
// now let's solve the system!
initdae := BackendDAEUtil.mapEqSystem(initdae, solveInitialSystemEqSystem);
execStat("solveInitialSystemEqSystem (initialization)");
// solve system
initdae := BackendDAEUtil.transformBackendDAE(initdae, SOME((BackendDAE.NO_INDEX_REDUCTION(), BackendDAE.EXACT())), NONE(), NONE());
execStat("matching and sorting (n="+String(BackendDAEUtil.daeSize(initdae))+") (initialization)");
// add initial assignmnents to all algorithms
initdae := BackendDAEOptimize.addInitialStmtsToAlgorithms(initdae, true);
if useHomotopy then
initdae0 := BackendDAEUtil.copyBackendDAE(initdae);
end if;
// simplify system
initdae := BackendDAEUtil.setDAEGlobalKnownVars(initdae, outGlobalKnownVars);
if useHomotopy then
enabledModules := if Config.adaptiveHomotopy() then {"inlineHomotopy", "generateHomotopyComponents"} else {};
disabledModules := {};
else
enabledModules := {};
disabledModules := {"inlineHomotopy", "generateHomotopyComponents"};
end if;
initOptModules := BackendDAEUtil.getInitOptModules(NONE(), enabledModules, disabledModules);
matchingAlgorithm := BackendDAEUtil.getMatchingAlgorithm(NONE());
daeHandler := BackendDAEUtil.getIndexReductionMethod(SOME("none"));
initdae := BackendDAEUtil.postOptimizeDAE(initdae, initOptModules, matchingAlgorithm, daeHandler);
if Flags.isSet(Flags.DUMP_INITIAL_SYSTEM) then
BackendDump.dumpBackendDAE(initdae, "solved initial system");
if Flags.isSet(Flags.ADDITIONAL_GRAPHVIZ_DUMP) then
BackendDump.graphvizBackendDAE(initdae, "dumpinitialsystem");
end if;
end if;
// compute system for lambda=0
if useHomotopy and Config.globalHomotopy() then
initOptModulesLambda0 := BackendDAEUtil.getInitOptModules(NONE(),{"replaceHomotopyWithSimplified"},{"inlineHomotopy", "generateHomotopyComponents"});
initdae0 := BackendDAEUtil.setFunctionTree(initdae0, BackendDAEUtil.getFunctions(initdae.shared));
initdae0 := BackendDAEUtil.postOptimizeDAE(initdae0, initOptModulesLambda0, matchingAlgorithm, daeHandler);
outInitDAE_lambda0 := SOME(initdae0);
initdae := BackendDAEUtil.setFunctionTree(initdae, BackendDAEUtil.getFunctions(initdae0.shared));
else
outInitDAE_lambda0 := NONE();
end if;
// Remove the globalKnownVars for the initialization set again
initdae.shared := BackendDAEUtil.setSharedGlobalKnownVars(initdae.shared, BackendVariable.emptyVars());
// update the fixed attribute in the simulation DAE
outSimDAE := BackendVariable.traverseBackendDAE(outSimDAE, updateFixedAttribute, BackendVariable.listVar(dumpVars));
// warn about selected default initial conditions
b1 := not listEmpty(dumpVars);
b2 := not listEmpty(removedEqns);
msg := System.gettext("For more information set -d=initialization. In OMEdit Tools->Options->Simulation->OMCFlags, in OMNotebook call setCommandLineOptions(\"-d=initialization\")");
if Flags.isSet(Flags.INITIALIZATION) then
if b1 then
Error.addCompilerWarning("Assuming fixed start value for the following " + intString(listLength(dumpVars)) + " variables:\n" + warnAboutVars2(dumpVars));
end if;
if b2 then
Error.addMessage(Error.INITIALIZATION_OVER_SPECIFIED, {"The following " + intString(listLength(removedEqns)) + " initial equations are redundant, so they are removed from the initialization sytem:\n" + warnAboutEqns2(removedEqns)});
end if;
else
if b1 then
Error.addMessage(Error.INITIALIZATION_NOT_FULLY_SPECIFIED, {msg});
end if;
if b2 then
Error.addMessage(Error.INITIALIZATION_OVER_SPECIFIED, {msg});
end if;
end if;
if Flags.isSet(Flags.DUMP_EQNINORDER) and Flags.isSet(Flags.DUMP_INITIAL_SYSTEM) then
BackendDump.dumpEqnsSolved(initdae, "initial system: eqns in order");
end if;
if Flags.isSet(Flags.ITERATION_VARS) then
BackendDAEOptimize.listAllIterationVariables(initdae);
end if;
if Flags.isSet(Flags.DUMP_BACKENDDAE_INFO) or Flags.isSet(Flags.DUMP_STATESELECTION_INFO) or Flags.isSet(Flags.DUMP_DISCRETEVARS_INFO) then
BackendDump.dumpCompShort(initdae);
end if;
outInitDAE := initdae;
outRemovedInitialEquations := removedEqns;
else
Error.addCompilerError("No system for the symbolic initialization was generated");
fail();
end try;
end solveInitialSystem;
// =============================================================================
// section for helper functions of solveInitialSystem
//
// =============================================================================
protected function solveInitialSystemEqSystem "author: lochel
This solves the generated system."
input BackendDAE.EqSystem isyst;
input BackendDAE.Shared inShared;
output BackendDAE.EqSystem osyst = isyst;
output BackendDAE.Shared outShared = inShared "unused";
protected
Integer nVars, nEqns;
algorithm
nEqns := BackendDAEUtil.systemSize(isyst);
nVars := BackendVariable.varsSize(BackendVariable.daeVars(isyst));
// over-determined system: nEqns > nVars
if intGt(nEqns, nVars) then
if Flags.isSet(Flags.INITIALIZATION) then
Error.addCompilerWarning("It was not possible to solve the over-determined initial system (" + intString(nEqns) + " equations and " + intString(nVars) + " variables)");
BackendDump.dumpEqSystem(isyst, "It was not possible to solve the over-determined initial system (" + intString(nEqns) + " equations and " + intString(nVars) + " variables)");
end if;
fail();
end if;
// under-determined system: nEqns < nVars
if intLt(nEqns, nVars) then
if Flags.isSet(Flags.INITIALIZATION) then
Error.addCompilerWarning("It was not possible to solve the under-determined initial system (" + intString(nEqns) + " equations and " + intString(nVars) + " variables)");
BackendDump.dumpEqSystem(isyst, "It was not possible to solve the under-determined initial system (" + intString(nEqns) + " equations and " + intString(nVars) + " variables)");
end if;
fail();
end if;
end solveInitialSystemEqSystem;
// =============================================================================
// section for inlining when-clauses
//
// This section contains all the helper functions to replace all when-clauses
// from a given BackendDAE to get the initial equation system.
// =============================================================================
protected function inlineWhenForInitialization "author: lochel
This function inlines when-clauses for the initialization."
input BackendDAE.BackendDAE inDAE;
output BackendDAE.BackendDAE outDAE = inDAE;
protected
list<BackendDAE.Equation> eqnlst;
HashSet.HashSet leftCrs = HashSet.emptyHashSet() "dummy hash set - should always be empty";
algorithm
outDAE.eqs := List.map(inDAE.eqs, inlineWhenForInitializationSystem);
(eqnlst, _) := BackendEquation.traverseEquationArray(inDAE.shared.removedEqs, inlineWhenForInitializationEquation, ({}, leftCrs));
outDAE.shared := BackendDAEUtil.setSharedRemovedEqns(outDAE.shared, BackendEquation.listEquation(eqnlst));
end inlineWhenForInitialization;
protected function inlineWhenForInitializationSystem "author: lochel"
input BackendDAE.EqSystem inEqSystem;
output BackendDAE.EqSystem outEqSystem;
protected
list<BackendDAE.Equation> eqnlst;
HashSet.HashSet leftCrs = HashSet.emptyHashSet() "hack for #3209";
list<DAE.ComponentRef> crefLst;
algorithm
(eqnlst, leftCrs) := BackendEquation.traverseEquationArray(inEqSystem.orderedEqs, inlineWhenForInitializationEquation, ({}, leftCrs));
crefLst := BaseHashSet.hashSetList(leftCrs);
eqnlst := generateInactiveWhenEquationForInitialization(crefLst, DAE.emptyElementSource, eqnlst);
outEqSystem := BackendDAEUtil.setEqSystEqs(inEqSystem, BackendEquation.listEquation(eqnlst));
outEqSystem := BackendDAEUtil.clearEqSyst(outEqSystem);
end inlineWhenForInitializationSystem;
protected function inlineWhenForInitializationEquation "author: lochel"
input BackendDAE.Equation inEq;
input tuple<list<BackendDAE.Equation>, HashSet.HashSet> inTpl;
output BackendDAE.Equation outEq = inEq;
output tuple<list<BackendDAE.Equation>, HashSet.HashSet> outTpl;
protected
BackendDAE.EquationAttributes eqAttr;
BackendDAE.WhenEquation weqn;
DAE.Algorithm alg;
DAE.ElementSource source;
DAE.Expand crefExpand;
HashSet.HashSet leftCrs;
Integer size;
list<BackendDAE.Equation> eqns;
list<BackendDAE.Equation> accEq;
list<DAE.Statement> stmts;
algorithm
(accEq, leftCrs) := inTpl;
outTpl := match (inEq)
// when equation
case BackendDAE.WHEN_EQUATION(whenEquation=weqn, source=source, attr=eqAttr) equation
(leftCrs, eqns) = inlineWhenForInitializationWhenEquation(weqn, source, eqAttr, accEq, leftCrs);
then (eqns, leftCrs);
// algorithm
case BackendDAE.ALGORITHM(alg=alg, source=source, expand=crefExpand) equation
DAE.ALGORITHM_STMTS(statementLst=stmts) = alg;
(stmts, leftCrs) = inlineWhenForInitializationWhenAlgorithm(stmts, {}, leftCrs);
alg = DAE.ALGORITHM_STMTS(stmts);
size = listLength(CheckModel.checkAndGetAlgorithmOutputs(alg, source, crefExpand));
eqns = List.consOnTrue(not listEmpty(stmts), BackendDAE.ALGORITHM(size, alg, source, crefExpand, BackendDAE.EQ_ATTR_DEFAULT_DYNAMIC), accEq);
then (eqns, leftCrs);
else (inEq::accEq, leftCrs);
end match;
end inlineWhenForInitializationEquation;
protected function inlineWhenForInitializationWhenEquation "author: lochel"
input BackendDAE.WhenEquation inWEqn;
input DAE.ElementSource inSource;
input BackendDAE.EquationAttributes inEqAttr;
input list<BackendDAE.Equation> inEqns;
input HashSet.HashSet inLeftCrs;
output HashSet.HashSet outLeftCrs = inLeftCrs;
output list<BackendDAE.Equation> outEqns = inEqns;
protected
DAE.Exp lhs, condition, e;
list<DAE.Exp> eLst;
BackendDAE.Equation eqn;
list<BackendDAE.WhenOperator> whenStmtLst;
DAE.ComponentRef cr;
list<DAE.ComponentRef > crefLst;
Boolean active;
DAE.ElementSource source;
algorithm
outEqns := match(inWEqn)
case BackendDAE.WHEN_STMTS(condition=condition,whenStmtLst=whenStmtLst) algorithm
active := Expression.containsInitialCall(condition);
for stmt in whenStmtLst loop
_ := match stmt
case BackendDAE.ASSIGN(left = DAE.CREF(componentRef = cr), right = e) equation
if active then
lhs = Expression.crefExp(cr);
eqn = BackendEquation.generateEquation(lhs, e, inSource, inEqAttr);
outEqns = eqn::outEqns;
else
outLeftCrs = List.fold(ComponentReference.expandCref(cr, true), BaseHashSet.add, outLeftCrs);
end if;
then ();
case BackendDAE.ASSIGN(left = lhs as DAE.TUPLE(PR = eLst), right = e) algorithm
if active then
eqn := BackendEquation.generateEquation(lhs, e, inSource, inEqAttr);
outEqns := eqn::outEqns;
else
crefLst := List.flatten(List.map(eLst,Expression.getAllCrefs));
for cr in crefLst loop
outLeftCrs := List.fold(ComponentReference.expandCref(cr, true), BaseHashSet.add, outLeftCrs);
end for;
end if;
then ();
case BackendDAE.NORETCALL(exp=e, source=source) algorithm
if active then
//eqn := BackendEquation.generateEquation(DAE.CREF(DAE.emptyCref, DAE.T_UNKNOWN_DEFAULT), e, inSource, inEqAttr);
eqn := BackendDAE.ALGORITHM(0, DAE.ALGORITHM_STMTS({DAE.STMT_NORETCALL(e, source)}), inSource, DAE.EXPAND(), BackendDAE.EQ_ATTR_DEFAULT_INITIAL);
outEqns := eqn::outEqns;
end if;
then ();
// Everything else doesn't have to be handled
else ();
end match;
end for;
then outEqns;
else outEqns;
end match;
end inlineWhenForInitializationWhenEquation;
protected function inlineWhenForInitializationWhenAlgorithm "author: lochel
This function generates out of a given when-algorithm, a algorithm for the initialization-problem."
input list< DAE.Statement> inStmts;
input list< DAE.Statement> inAcc "={}";
input HashSet.HashSet inLeftCrs;
output list< DAE.Statement> outStmts;
output HashSet.HashSet outLeftCrs;
algorithm
(outStmts, outLeftCrs) := match(inStmts)
local
DAE.Statement stmt;
list<DAE.Statement> stmts, rest;
HashSet.HashSet leftCrs;
case {}
then (listReverse(inAcc), inLeftCrs);
// when statement
case (stmt as DAE.STMT_WHEN())::rest equation
// for when statements it is not necessary that all branches have the same left hand side variables
// -> take care that for each left hand side an assigment is generated
(stmts, leftCrs) = inlineWhenForInitializationWhenStmt(stmt, inLeftCrs, inAcc);
(stmts, leftCrs) = inlineWhenForInitializationWhenAlgorithm(rest, stmts, leftCrs);
then (stmts, leftCrs);
// no when statement
case stmt::rest equation
(stmts, leftCrs) = inlineWhenForInitializationWhenAlgorithm(rest, stmt::inAcc, inLeftCrs);
then (stmts, leftCrs);
end match;
end inlineWhenForInitializationWhenAlgorithm;
protected function inlineWhenForInitializationWhenStmt "author: lochel
This function generates out of a given when-algorithm, a algorithm for the initialization-problem."
input DAE.Statement inWhenStatement;
input HashSet.HashSet inLeftCrs;
input list< DAE.Statement> inAcc;
output list< DAE.Statement> outStmts;
output HashSet.HashSet outLeftCrs;
algorithm
(outStmts, outLeftCrs) := match(inWhenStatement)
local
DAE.Exp condition;
list<DAE.ComponentRef> crefLst;
DAE.Statement stmt;
list<DAE.Statement> stmts;
HashSet.HashSet leftCrs;
// active when equation during initialization
case DAE.STMT_WHEN(exp=condition, statementLst=stmts) guard
Expression.containsInitialCall(condition)
equation
stmts = List.foldr(stmts, List.consr, inAcc);
then (stmts, inLeftCrs);
// inactive when equation during initialization
case DAE.STMT_WHEN(exp=_, statementLst=stmts, elseWhen=NONE()) equation
crefLst = CheckModel.algorithmStatementListOutputs(stmts, DAE.EXPAND()); // expand as we're in an algorithm
leftCrs = List.fold(crefLst, BaseHashSet.add, inLeftCrs);
then (inAcc, leftCrs);
// inactive when equation during initialization with elsewhen part
case DAE.STMT_WHEN(exp=_, statementLst=stmts, elseWhen=SOME(stmt)) equation
crefLst = CheckModel.algorithmStatementListOutputs(stmts, DAE.EXPAND()); // expand as we're in an algorithm
leftCrs = List.fold(crefLst, BaseHashSet.add, inLeftCrs);
(stmts, leftCrs) = inlineWhenForInitializationWhenStmt(stmt, leftCrs, inAcc);
then (stmts, leftCrs);
else equation
Error.addInternalError("function inlineWhenForInitializationWhenStmt failed", sourceInfo());
then fail();
end match;
end inlineWhenForInitializationWhenStmt;
protected function generateInactiveWhenEquationForInitialization "author: lochel"
input list<DAE.ComponentRef> inCrLst;
input DAE.ElementSource inSource;
input list<BackendDAE.Equation> inEqns;
output list<BackendDAE.Equation> outEqns = inEqns;
protected
DAE.Type identType;
DAE.Exp crefExp, crefPreExp;
BackendDAE.Equation eqn;
algorithm
for cr in inCrLst loop
identType := ComponentReference.crefTypeConsiderSubs(cr);
crefExp := DAE.CREF(cr, identType);
crefPreExp := Expression.makePureBuiltinCall("pre", {crefExp}, DAE.T_BOOL_DEFAULT);
eqn := BackendDAE.EQUATION(crefExp, crefPreExp, inSource, BackendDAE.EQ_ATTR_DEFAULT_DYNAMIC);
outEqns := eqn::outEqns;
end for;
end generateInactiveWhenEquationForInitialization;
// =============================================================================
// section for collecting all variables, of which the left limit is also used.
//
// collect all pre variables in time equations
// =============================================================================
protected function collectPreVariables "author: lochel"
input BackendDAE.BackendDAE inDAE;
output HashSet.HashSet outHS;
protected
//list<DAE.ComponentRef> crefs;
algorithm
//BackendDump.dumpBackendDAE(inDAE, "inDAE");
outHS := List.fold(inDAE.eqs, collectPreVariablesEqSystem, HashSet.emptyHashSet());
((_, outHS)) := BackendDAEUtil.traverseBackendDAEExpsEqns( inDAE.shared.initialEqs, Expression.traverseSubexpressionsHelper,
(collectPreVariablesTraverseExp, outHS) );
((_, outHS)) := BackendDAEUtil.traverseBackendDAEExpsEqns( inDAE.shared.removedEqs, Expression.traverseSubexpressionsHelper,
(collectPreVariablesTraverseExp, outHS) );
//print("collectPreVariables:\n");
//crefs := BaseHashSet.hashSetList(outHS);
//BackendDump.debuglst(crefs, ComponentReference.printComponentRefStr, "\n", "\n");
end collectPreVariables;
public function collectPreVariablesEqSystem
input BackendDAE.EqSystem inSyst;
input HashSet.HashSet inHS;
output HashSet.HashSet outHS;
algorithm
((_, outHS)) := BackendDAEUtil.traverseBackendDAEExpsEqns( inSyst.orderedEqs, Expression.traverseSubexpressionsHelper,
(collectPreVariablesTraverseExp, inHS) );
((_, outHS)) := BackendDAEUtil.traverseBackendDAEExpsEqns( inSyst.removedEqs, Expression.traverseSubexpressionsHelper,
(collectPreVariablesTraverseExp, outHS) );
end collectPreVariablesEqSystem;
public function collectPreVariablesTraverseExp
input DAE.Exp inExp;
input HashSet.HashSet inHS;
output DAE.Exp outExp = inExp;
output HashSet.HashSet outHS;
algorithm
outHS := match (inExp)
case DAE.CALL(path=Absyn.IDENT(name="pre")) equation
(_, outHS) = Expression.traverseExpBottomUp(inExp, collectPreVariablesTraverseExp2, inHS);
then outHS;
case DAE.CALL(path=Absyn.IDENT(name="change")) equation
(_, outHS) = Expression.traverseExpBottomUp(inExp, collectPreVariablesTraverseExp2, inHS);
then outHS;
case DAE.CALL(path=Absyn.IDENT(name="edge")) equation
(_, outHS) = Expression.traverseExpBottomUp(inExp, collectPreVariablesTraverseExp2, inHS);
then outHS;
else inHS;
end match;
end collectPreVariablesTraverseExp;
protected function collectPreVariablesTraverseExp2 "author: lochel"
input DAE.Exp inExp;
input HashSet.HashSet inHS;
output DAE.Exp outExp = inExp;
output HashSet.HashSet outHS;
algorithm
outHS := match inExp
local
list<DAE.ComponentRef> crefs;
DAE.ComponentRef cr;
case DAE.CREF(componentRef=cr) equation
crefs = ComponentReference.expandCref(cr, true);
outHS = List.fold(crefs, BaseHashSet.add, inHS);
then outHS;
else inHS;
end match;
end collectPreVariablesTraverseExp2;
protected function warnAboutVars2 "author: lochel
TODO: Replace this with an general BackendDump implementation."
input list<BackendDAE.Var> vars;
output String outString;
protected
list<String> strs;
Integer len;
Integer size;
algorithm
if listEmpty(vars) then
outString := "";
return;
end if;
strs := list(BackendDump.varString(v) for v in vars);
len := listLength(strs);
size := sum(stringLength(s) for s in strs) + len*10;
outString := warnAboutVars2Work(strs, " ", "\n", size);
end warnAboutVars2;
function warnAboutVars2Work
input list<String> strs;
input String prefix;
input String suffix;
input Integer size;
output String s="";
protected
// Allocate a string of the exact required length
System.StringAllocator sb=System.StringAllocator(size);
Integer i=0;
algorithm
for str in strs loop
System.stringAllocatorStringCopy(sb, prefix, i);
i := i+stringLength(prefix);
System.stringAllocatorStringCopy(sb, str, i);
i := i+stringLength(str);
System.stringAllocatorStringCopy(sb, suffix, i);
i := i+stringLength(suffix);
end for;
// Return the string
s := System.stringAllocatorResult(sb,s);
end warnAboutVars2Work;
protected function warnAboutEqns2 "author: lochel
TODO: Replace this with an general BackendDump implementation."
input list<BackendDAE.Equation> inEqns;
output String outString;
algorithm
outString := match(inEqns)
local
BackendDAE.Equation eq;
list<BackendDAE.Equation> eqns;
String crStr;
String str;
case ({}) then "";
case (eq::{}) equation
crStr = " " + BackendDump.equationString(eq);
then crStr;
case (eq::eqns) equation
crStr = BackendDump.equationString(eq);
str = " " + crStr + "\n" + warnAboutEqns2(eqns);
then str;
end match;
end warnAboutEqns2;
// =============================================================================
// section for selecting initialization variables
//
// - unfixed state
// - secondary parameter
// - unfixed discrete -> pre(vd)
// =============================================================================
protected function selectInitializationVariablesDAE "author: lochel
This function wraps selectInitializationVariables.
All primary parameters get removed from the dae."
input output BackendDAE.BackendDAE dae;
output BackendDAE.Variables outInitVars;
output list<BackendDAE.Var> outAllPrimaryParameters = {};
output BackendDAE.Variables outGlobalKnownVars = dae.shared.globalKnownVars;
protected
BackendDAE.Variables otherVariables, globalKnownVars=dae.shared.globalKnownVars;
BackendDAE.EquationArray globalKnownVarsEqns;
BackendDAE.EqSystem globalKnownVarsSystem;
BackendDAE.AdjacencyMatrix m, mT;
array<Integer> ass1 "eqn := ass1[var]";
array<Integer> ass2 "var := ass2[eqn]";
list<list<Integer>> comps;
list<Integer> flatComps;
Integer nGlobalKnownVars;
array<Integer> secondary;
BackendDAE.Var v;
DAE.Exp bindExp;
HashSet.HashSet hs;
list<DAE.ComponentRef> crefs;
algorithm
// lochel: workaround to align all elements
globalKnownVars := BackendVariable.listVar(BackendVariable.varList(globalKnownVars));
outInitVars := selectInitializationVariables(dae.eqs);
outInitVars := BackendVariable.traverseBackendDAEVars(dae.shared.globalKnownVars, selectInitializationVariables2, outInitVars);
outInitVars := BackendVariable.traverseBackendDAEVars(dae.shared.aliasVars, selectInitializationVariables2, outInitVars);
globalKnownVars := BackendVariable.traverseBackendDAEVars(dae.shared.externalObjects, addExtObjToGlobalKnownVars, globalKnownVars);
nGlobalKnownVars := BackendVariable.varsSize(globalKnownVars);
otherVariables := BackendVariable.emptyVarsSized(nGlobalKnownVars);
globalKnownVarsEqns := BackendEquation.emptyEqnsSized(nGlobalKnownVars);
globalKnownVarsEqns := BackendVariable.traverseBackendDAEVars(globalKnownVars, createGlobalKnownVarsEquations, globalKnownVarsEqns);
if nGlobalKnownVars > 0 then
globalKnownVarsSystem := BackendDAEUtil.createEqSystem(globalKnownVars, globalKnownVarsEqns);
(m, mT) := BackendDAEUtil.adjacencyMatrix(globalKnownVarsSystem, BackendDAE.NORMAL(), NONE(), BackendDAEUtil.isInitializationDAE(dae.shared));
//BackendDump.dumpAdjacencyMatrix(m);
//BackendDump.dumpAdjacencyMatrixT(mT);
// match the system
// ass1 and ass2 should be {1, 2, ..., nGlobalKnownVars}
(ass1, ass2) := Matching.PerfectMatching(m);
//BackendDump.dumpMatchingVars(ass1);
//BackendDump.dumpMatchingEqns(ass2);
comps := Sorting.Tarjan(m, ass1);
//BackendDump.dumpComponentsOLD(comps);
comps := mapListIndices(comps, ass2) "map to var indices (not really needed, since ass2 should be {1, 2, ..., nParam})" ;
//BackendDump.dumpComponentsOLD(comps);
// flattern list and look for cyclic dependencies
flatComps := list(flattenParamComp(comp, globalKnownVars) for comp in comps);
//BackendDump.dumpAdjacencyRow(flatComps);
//BackendDump.dumpVariables(globalKnownVars, "globalKnownVars");
// select secondary parameters
secondary := arrayCreate(nGlobalKnownVars, 0);
secondary := selectSecondaryParameters(flatComps, globalKnownVars, mT, secondary);
// get primary and secondary parameters and variables
hs := HashSet.emptyHashSetSized(2*nGlobalKnownVars+1);
for i in flatComps loop
v := BackendVariable.getVarAt(globalKnownVars, i);
bindExp := BackendVariable.varBindExpStartValueNoFail(v);
crefs := Expression.getAllCrefsExpanded(bindExp);
//BackendDump.dumpVarList({v}, intString(i));
_ := match(v)
// primary parameter
case (BackendDAE.VAR(varKind=BackendDAE.PARAM())) guard 0 == secondary[i] and BaseHashSet.hasAll(crefs, hs)
equation
outAllPrimaryParameters = v::outAllPrimaryParameters;
hs = BaseHashSet.add(BackendVariable.varCref(v), hs);
then ();
// primary external object
case (BackendDAE.VAR(varKind=BackendDAE.EXTOBJ(), bindExp=SOME(bindExp))) guard 0 == secondary[i] and BaseHashSet.hasAll(crefs, hs)
equation
outAllPrimaryParameters = v::outAllPrimaryParameters;
v = BackendVariable.setVarFixed(v, true);
outGlobalKnownVars = BackendVariable.addVar(v, outGlobalKnownVars);
hs = BaseHashSet.add(BackendVariable.varCref(v), hs);
then ();
// secondary parameter
case (BackendDAE.VAR(varKind=BackendDAE.PARAM()))
equation
otherVariables = BackendVariable.addVar(v, otherVariables);
v = BackendVariable.setVarFixed(v, false);
outInitVars = BackendVariable.addVar(v, outInitVars);
outGlobalKnownVars = BackendVariable.addVar(v, outGlobalKnownVars);
then ();
// primary variable
case (_) guard BackendVariable.isVarAlg(v) and 0 == secondary[i] and BaseHashSet.hasAll(crefs, hs)
equation
otherVariables = BackendVariable.addVar(v, otherVariables);
v = BackendVariable.setVarFixed(v, true);
outGlobalKnownVars = BackendVariable.addVar(v, outGlobalKnownVars);
hs = BaseHashSet.add(BackendVariable.varCref(v), hs);
then ();
// secondary variable
case (_) guard BackendVariable.isVarAlg(v)
equation
otherVariables = BackendVariable.addVar(v, otherVariables);
v = BackendVariable.setVarFixed(v, false);
outGlobalKnownVars = BackendVariable.addVar(v, outGlobalKnownVars);
then ();
else
equation
otherVariables = BackendVariable.addVar(v, otherVariables);
then ();
end match;
end for;
GC.free(secondary);
outAllPrimaryParameters := listReverse(outAllPrimaryParameters);
dae := BackendDAEUtil.setDAEGlobalKnownVars(dae, otherVariables);
//BackendDump.dumpVarList(outAllPrimaryParameters, "outAllPrimaryParameters");
//BackendDump.dumpVariables(otherVariables, "otherVariables");
end if;
end selectInitializationVariablesDAE;
function addExtObjToGlobalKnownVars "
Sets fixed=true for external objects with binding and adds them to globalKnownVars
author: ptaeuber"
input output BackendDAE.Var extObj;
input output BackendDAE.Variables globalKnownVars;
algorithm
globalKnownVars := match(extObj)
local
BackendDAE.Var var;
// external object with binding
case (BackendDAE.VAR(varKind=BackendDAE.EXTOBJ(), bindExp=SOME(_))) equation
var = BackendVariable.setVarFixed(extObj, true);
globalKnownVars = BackendVariable.addVar(var, globalKnownVars);
then (globalKnownVars);
end match;
end addExtObjToGlobalKnownVars;
protected function createGlobalKnownVarsEquations
"Creates BackendDAE.EQUATION()s from the globalKnownVars
author: ptaeuber"
input output BackendDAE.Var var;
input output BackendDAE.EquationArray parameterEqns;
protected
DAE.Exp lhs, rhs, startValue;
BackendDAE.Equation eqn;
BackendDAE.Var v;
String s, str;
SourceInfo info;
algorithm
lhs := BackendVariable.varExp(var);
if BackendVariable.isParam(var) and not BackendVariable.varHasBindExp(var) and BackendVariable.varFixed(var) then
s := ExpressionDump.printExpStr(lhs);
startValue := BackendVariable.varStartValue(var);
str := ExpressionDump.printExpStr(startValue);
v := BackendVariable.setVarKind(var, BackendDAE.VARIABLE());
v := BackendVariable.setBindExp(v, SOME(startValue));
v := BackendVariable.setVarFixed(v, true);
info := ElementSource.getElementSourceFileInfo(BackendVariable.getVarSource(v));
Error.addSourceMessage(Error.UNBOUND_PARAMETER_WITH_START_VALUE_WARNING, {s, str}, info);
end if;
try
rhs := BackendVariable.varBindExpStartValue(var);
else
rhs := DAE.RCONST(0.0);
end try;
eqn := BackendDAE.EQUATION(lhs, rhs, DAE.emptyElementSource, BackendDAE.EQ_ATTR_DEFAULT_BINDING);
parameterEqns := BackendEquation.add(eqn, parameterEqns);
end createGlobalKnownVarsEquations;
protected function markIndex
input Integer inIndex;
input array<Integer> inArray;
output array<Integer> outArray = inArray;
algorithm
outArray[inIndex] := 1;
end markIndex;
protected function selectSecondaryParameters
input list<Integer> inOrdering;
input BackendDAE.Variables inParameters;
input BackendDAE.AdjacencyMatrix inM;
input array<Integer> inSecondaryParams;
output array<Integer> outSecondaryParams;
algorithm
outSecondaryParams := match inOrdering
local
Integer i;
array<Integer> secondaryParams;
list<Integer> rest;
BackendDAE.Var param;
case {}
then inSecondaryParams;
// fixed=false
case i::rest equation
param = BackendVariable.getVarAt(inParameters, i);
secondaryParams = if (if BackendVariable.isVarAlg(param) then false else not BackendVariable.varFixed(param)) or 1 == inSecondaryParams[i]
then List.fold(inM[i], markIndex, inSecondaryParams) else inSecondaryParams;
secondaryParams = selectSecondaryParameters(rest, inParameters, inM, secondaryParams);
then secondaryParams;
end match;
end selectSecondaryParameters;
public function flattenParamComp
input list<Integer> paramIndices;
input BackendDAE.Variables inAllParameters;
output Integer outFlatComp;
algorithm
outFlatComp := match paramIndices
local
Integer i;
list<BackendDAE.Var> paramLst;
BackendDAE.Var param;
case {i} then i;
else algorithm
paramLst := {};
for i in paramIndices loop
param := BackendVariable.getVarAt(inAllParameters, i);
paramLst := param::paramLst;
end for;
Error.addCompilerError("Cyclically dependent parameters found:\n" + warnAboutVars2(paramLst));
then fail();
end match;
end flattenParamComp;
protected function selectInitializationVariables "author: lochel"
input list<BackendDAE.EqSystem> inEqSystems;
output BackendDAE.Variables outVars;
algorithm
outVars := BackendVariable.emptyVars();
outVars := List.fold(inEqSystems, selectInitializationVariables1, outVars);
end selectInitializationVariables;
protected function selectInitializationVariables1 "author: lochel"
input BackendDAE.EqSystem inEqSystem;
input BackendDAE.Variables inVars;
output BackendDAE.Variables outVars;
algorithm
outVars := BackendVariable.traverseBackendDAEVars(inEqSystem.orderedVars, selectInitializationVariables2, inVars);
end selectInitializationVariables1;
protected function selectInitializationVariables2 "author: lochel"
input BackendDAE.Var inVar;
input BackendDAE.Variables inVars;
output BackendDAE.Var outVar;
output BackendDAE.Variables outVars;
algorithm
(outVar, outVars) := matchcontinue (inVar, inVars)
local
BackendDAE.Var preVar;
BackendDAE.Variables vars;
DAE.ComponentRef cr, preCR;
DAE.Type ty;
DAE.InstDims arryDim;