/
Initialization.mo
2398 lines (2079 loc) · 98.5 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;
public import BackendDAE;
public import BackendDAEFunc;
public import DAE;
public import FCore;
public import HashSet;
public import Util;
protected import Array;
protected import BackendDAEEXT;
protected import BackendDAEOptimize;
protected import BackendDAEUtil;
protected import BackendDump;
protected import BackendEquation;
protected import BackendVarTransform;
protected import BackendVariable;
protected import BaseHashSet;
protected import CheckModel;
protected import ComponentReference;
protected import DAEUtil;
protected import Error;
protected import Expression;
protected import ExpressionDump;
protected import ExpressionSimplify;
protected import Flags;
protected import List;
protected import Matching;
protected import Sorting;
protected import SimCodeFunctionUtil;
// =============================================================================
// 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 Boolean outUseHomotopy;
output list<BackendDAE.Equation> outRemovedInitialEquations;
output list<BackendDAE.Var> outPrimaryParameters "already sorted";
output list<BackendDAE.Var> outAllPrimaryParameters "already sorted";
protected
BackendDAE.BackendDAE dae;
BackendDAE.BackendDAE initdae;
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;
HashSet.HashSet hs "contains all pre variables";
HashSet.HashSet clkHS "contains all clocked variables";
list<BackendDAE.Equation> removedEqns;
list<BackendDAE.Var> dumpVars, dumpVars2;
list<tuple<BackendDAEFunc.postOptimizationDAEModule, String, Boolean>> initOptModules;
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;
SimCodeFunctionUtil.execStat("inlineWhenForInitialization (initialization)");
(initVars, outPrimaryParameters, outAllPrimaryParameters) := selectInitializationVariablesDAE(dae);
//if Flags.isSet(Flags.DUMP_INITIAL_SYSTEM) then
// BackendDump.dumpVariables(initVars, "selected initialization variables");
//end if;
SimCodeFunctionUtil.execStat("selectInitializationVariablesDAE (initialization)");
hs := collectPreVariables(dae);
clkHS := collectClkVariables(dae);
SimCodeFunctionUtil.execStat("collectPreVariables (initialization)");
// collect vars and eqns for initial system
vars := BackendVariable.emptyVars();
fixvars := BackendVariable.emptyVars();
eqns := BackendEquation.emptyEqns();
reeqns := BackendEquation.emptyEqns();
((vars, fixvars, eqns, _)) := BackendVariable.traverseBackendDAEVars(dae.shared.aliasVars, introducePreVarsForAliasVariables, (vars, fixvars, eqns, hs));
((vars, fixvars, eqns, _, _)) := BackendVariable.traverseBackendDAEVars(dae.shared.knownVars, collectInitialVars, (vars, fixvars, eqns, hs, clkHS));
((eqns, reeqns)) := BackendEquation.traverseEquationArray(dae.shared.initialEqs, collectInitialEqns, (eqns, reeqns));
//if Flags.isSet(Flags.DUMP_INITIAL_SYSTEM) then
// BackendDump.dumpEquationArray(eqns, "initial equations");
//end if;
SimCodeFunctionUtil.execStat("collectInitialEqns (initialization)");
((vars, fixvars, eqns, reeqns, _, _)) := List.fold(dae.eqs, collectInitialVarsEqnsSystem, ((vars, fixvars, eqns, reeqns, hs, clkHS)));
((eqns, reeqns)) := BackendVariable.traverseBackendDAEVars(vars, collectInitialBindings, (eqns, reeqns));
SimCodeFunctionUtil.execStat("collectInitialBindings (initialization)");
// replace initial(), sample(...), delay(...) and homotopy(...)
useHomotopy := BackendDAEUtil.traverseBackendDAEExpsEqnsWithUpdate(eqns, simplifyInitialFunctions, false);
SimCodeFunctionUtil.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.removedEqs := inDAE.shared.removedEqs;
shared := BackendDAEUtil.setSharedKnVars(shared, fixvars);
shared := BackendDAEUtil.setSharedOptimica(shared, dae.shared.constraints, dae.shared.classAttrs);
shared := BackendDAEUtil.setSharedFunctionTree(shared, dae.shared.functionTree);
SimCodeFunctionUtil.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);
SimCodeFunctionUtil.execStat("preBalanceInitialSystem (initialization)");
// split the initial system into independend subsystems
initdae := BackendDAE.DAE({initsyst}, shared);
if Flags.isSet(Flags.OPT_DAE_DUMP) then
print(stringAppendList({"\ncreated initial system:\n\n"}));
BackendDump.printBackendDAE(initdae);
end if;
(systs, shared) := BackendDAEOptimize.partitionIndependentBlocksHelper(initsyst, shared, Error.getNumErrorMessages(), true);
initdae := BackendDAE.DAE(systs, shared);
SimCodeFunctionUtil.execStat("partitionIndependentBlocks (initialization)");
if Flags.isSet(Flags.OPT_DAE_DUMP) then
print(stringAppendList({"\npartitioned initial system:\n\n"}));
BackendDump.printBackendDAE(initdae);
end if;
// initdae := BackendDAE.DAE({initsyst}, shared);
// fix over- and under-constrained subsystems
(initdae, dumpVars2, removedEqns) := analyzeInitialSystem(initdae, initVars);
dumpVars := listAppend(dumpVars, dumpVars2);
SimCodeFunctionUtil.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);
SimCodeFunctionUtil.execStat("solveInitialSystemEqSystem (initialization)");
// transform and optimize DAE
initOptModules := BackendDAEUtil.getInitOptModules(NONE());
matchingAlgorithm := BackendDAEUtil.getMatchingAlgorithm(NONE());
daeHandler := BackendDAEUtil.getIndexReductionMethod(NONE());
// solve system
initdae := BackendDAEUtil.transformBackendDAE(initdae, SOME((BackendDAE.NO_INDEX_REDUCTION(), BackendDAE.EXACT())), NONE(), NONE());
// simplify system
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;
// warn about selected default initial conditions
b1 := not listEmpty(dumpVars);
b2 := not listEmpty(removedEqns);
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.addCompilerWarning("Assuming redundant initial conditions for the following " + intString(listLength(removedEqns)) + " initial equations:\n" + warnAboutEqns2(removedEqns));
end if;
else
if b1 then
Error.addCompilerWarning("The initial conditions are not fully specified. Use +d=initialization for more information.");
end if;
if b2 then
Error.addCompilerWarning("The initial conditions are over specified. Use +d=initialization for more information.");
end if;
end if;
// warn about iteration variables with default zero start attribute
b := warnAboutIterationVariablesWithDefaultZeroStartAttribute(initdae);
if b and (not Flags.isSet(Flags.INITIALIZATION)) then
Error.addCompilerWarning("There are iteration variables with default zero start attribute. Use +d=initialization for more information.");
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;
outUseHomotopy := useHomotopy;
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;
algorithm
outDAE.eqs := List.map(inDAE.eqs, inlineWhenForInitializationSystem);
end inlineWhenForInitialization;
protected function inlineWhenForInitializationSystem "author: lochel"
input BackendDAE.EqSystem inEqSystem;
output BackendDAE.EqSystem outEqSystem;
protected
list<BackendDAE.Equation> eqnlst;
algorithm
eqnlst := BackendEquation.traverseEquationArray(inEqSystem.orderedEqs, inlineWhenForInitializationEquation, {});
//print("Before: " + intString(listLength(eqnlst)) + "\n");
eqnlst := List.uniqueOnTrue(eqnlst, BackendEquation.equationEqual) "hack for #3209";
//print("After: " + intString(listLength(eqnlst)) + "\n");
outEqSystem := BackendDAEUtil.setEqSystEqs(inEqSystem, BackendEquation.listEquation(eqnlst));
outEqSystem := BackendDAEUtil.clearEqSyst(outEqSystem);
end inlineWhenForInitializationSystem;
protected function inlineWhenForInitializationEquation "author: lochel"
input BackendDAE.Equation inEq;
input list<BackendDAE.Equation> inAccEq;
output BackendDAE.Equation outEq = inEq;
output list<BackendDAE.Equation> outAccEq;
algorithm
outAccEq := match (inEq)
local
DAE.ElementSource source;
DAE.Algorithm alg;
Integer size;
list< DAE.Statement> stmts;
list< BackendDAE.Equation> eqns;
BackendDAE.WhenEquation weqn;
list< DAE.ComponentRef> crefLst;
HashSet.HashSet leftCrs;
DAE.Expand crefExpand;
BackendDAE.EquationAttributes eqAttr;
// when equation
case BackendDAE.WHEN_EQUATION(whenEquation=weqn, source=source, attr=eqAttr) equation
eqns = inlineWhenForInitializationWhenEquation(weqn, source, eqAttr, inAccEq);
then eqns;
// algorithm
case BackendDAE.ALGORITHM(alg=alg, source=source, expand=crefExpand) equation
DAE.ALGORITHM_STMTS(statementLst=stmts) = alg;
(stmts, leftCrs) = inlineWhenForInitializationWhenAlgorithm(stmts, {}, HashSet.emptyHashSetSized(50));
alg = DAE.ALGORITHM_STMTS(stmts);
size = listLength(CheckModel.checkAndGetAlgorithmOutputs(alg, source, crefExpand));
crefLst = BaseHashSet.hashSetList(leftCrs);
eqns = generateInactiveWhenEquationForInitialization(crefLst, source, inAccEq);
eqns = List.consOnTrue(not listEmpty(stmts), BackendDAE.ALGORITHM(size, alg, source, crefExpand, BackendDAE.EQ_ATTR_DEFAULT_DYNAMIC), eqns);
then eqns;
else inEq::inAccEq;
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;
output list<BackendDAE.Equation> outEqns;
protected
DAE.Exp crexp, condition, e;
BackendDAE.Equation eqn;
list<BackendDAE.WhenOperator> whenStmtLst;
DAE.ComponentRef cr;
algorithm
outEqns := match(inWEqn)
case BackendDAE.WHEN_STMTS(condition=condition,whenStmtLst=whenStmtLst) algorithm
for stmt in whenStmtLst loop
_ := match stmt
case BackendDAE.ASSIGN(left = cr, right = e) equation
if Expression.containsInitialCall(condition, false) then
crexp = Expression.crefExp(cr);
eqn = BackendEquation.generateEquation(crexp, e, inSource, inEqAttr);
outEqns = eqn::inEqns;
else
outEqns = generateInactiveWhenEquationForInitialization(ComponentReference.expandCref(cr, true), inSource, inEqns);
end if;
then ();
end match;
end for;
then outEqns;
else inEqns;
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) := matchcontinue(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 matchcontinue;
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) := matchcontinue(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) equation
true = Expression.containsInitialCall(condition, false);
stmts = List.foldr(stmts, List.consr, inAcc);
then (stmts, inLeftCrs);
// inactive when equation during initialization
case DAE.STMT_WHEN(exp=condition, statementLst=stmts, elseWhen=NONE()) equation
false = Expression.containsInitialCall(condition, false);
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=condition, statementLst=stmts, elseWhen=SOME(stmt)) equation
false = Expression.containsInitialCall(condition, false);
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 matchcontinue;
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 collectClkVariables "author: rfranke"
input BackendDAE.BackendDAE inDAE;
output HashSet.HashSet outHS;
algorithm
//BackendDump.dumpBackendDAE(inDAE, "inDAE");
outHS := List.fold(inDAE.eqs, collectClkVariablesEqSystem, HashSet.emptyHashSet());
((_, outHS)) := BackendDAEUtil.traverseBackendDAEExpsEqns( inDAE.shared.initialEqs, Expression.traverseSubexpressionsHelper,
(collectClkVariablesTraverseExp, outHS) );
((_, outHS)) := BackendDAEUtil.traverseBackendDAEExpsEqns( inDAE.shared.removedEqs, Expression.traverseSubexpressionsHelper,
(collectClkVariablesTraverseExp, outHS) );
end collectClkVariables;
public function collectClkVariablesEqSystem
input BackendDAE.EqSystem inSyst;
input HashSet.HashSet inHS;
output HashSet.HashSet outHS;
algorithm
((_, outHS)) := BackendDAEUtil.traverseBackendDAEExpsEqns( inSyst.orderedEqs, Expression.traverseSubexpressionsHelper,
(collectClkVariablesTraverseExp, inHS) );
((_, outHS)) := BackendDAEUtil.traverseBackendDAEExpsEqns( inSyst.removedEqs, Expression.traverseSubexpressionsHelper,
(collectClkVariablesTraverseExp, outHS) );
end collectClkVariablesEqSystem;
public function collectClkVariablesTraverseExp
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="previous")) equation
(_, outHS) = Expression.traverseExpBottomUp(inExp, collectPreVariablesTraverseExp2, inHS);
then outHS;
else inHS;
end match;
end collectClkVariablesTraverseExp;
// =============================================================================
// warn about iteration variables with default zero start attribute
//
// =============================================================================
protected function warnAboutIterationVariablesWithDefaultZeroStartAttribute "author: lochel
This function ... read the function name."
input BackendDAE.BackendDAE inDAE;
output Boolean outWarning;
algorithm
outWarning := warnAboutIterationVariablesWithDefaultZeroStartAttribute0(inDAE.eqs, Flags.isSet(Flags.INITIALIZATION));
end warnAboutIterationVariablesWithDefaultZeroStartAttribute;
protected function warnAboutIterationVariablesWithDefaultZeroStartAttribute0 "author: lochel"
input list<BackendDAE.EqSystem> inEqs;
input Boolean inShowWarnings;
output Boolean outWarning = false;
protected
Boolean warn;
algorithm
for eqs in inEqs loop
warn := warnAboutIterationVariablesWithDefaultZeroStartAttribute1(eqs, inShowWarnings);
outWarning := outWarning or warn;
// If we found an iteration variable with default zero start attribute but
// +d=initialization wasn't given, we don't need to continue searching.
if warn and not inShowWarnings then
return;
end if;
end for;
end warnAboutIterationVariablesWithDefaultZeroStartAttribute0;
protected function warnAboutIterationVariablesWithDefaultZeroStartAttribute1 "author: lochel"
input BackendDAE.EqSystem inEqSystem;
input Boolean inShowWarnings;
output Boolean outWarning = false "True if any warnings were printed.";
protected
BackendDAE.StrongComponents comps;
list<Integer> vlst = {};
list<BackendDAE.Var> vars;
String err;
algorithm
BackendDAE.EQSYSTEM(matching=BackendDAE.MATCHING(comps=comps)) := inEqSystem;
// Go through all the strongly connected components.
for comp in comps loop
// Get the component's variables and select the correct error message.
(err, vlst) := matchcontinue(comp)
case BackendDAE.EQUATIONSYSTEM(vars = vlst, jacType = BackendDAE.JAC_NONLINEAR())
then ("nonlinear equation system:\n", vlst);
case BackendDAE.EQUATIONSYSTEM(vars = vlst, jacType = BackendDAE.JAC_GENERIC())
then ("equation system w/o analytic Jacobian:\n", vlst);
case BackendDAE.EQUATIONSYSTEM(vars = vlst, jacType = BackendDAE.JAC_NO_ANALYTIC())
then ("equation system w/o analytic Jacobian:\n", vlst);
case BackendDAE.TORNSYSTEM(BackendDAE.TEARINGSET(tearingvars = vlst), linear = false)
then ("torn nonlinear equation system:\n", vlst);
// If the component is none of these types, do nothing.
else ("", {});
end matchcontinue;
if not listEmpty(vlst) then
// Filter out the variables that are missing start values.
vars := List.map1r(vlst, BackendVariable.getVarAt, inEqSystem.orderedVars);
//vars := list(BackendVariable.getVarAt(inEqSystem.orderedVars, idx) for idx in vlst);
vars := list(v for v guard(not BackendVariable.varHasStartValue(v)) in vars);
//vars := List.filterOnTrue(vars, BackendVariable.varHasStartValue);
// Print a warning if we found any variables with missing start values.
if not listEmpty(vars) then
outWarning := true;
if inShowWarnings then
Error.addCompilerWarning("Iteration variables with default zero start attribute in " + err + warnAboutVars2(vars));
else
// If +d=initialization wasn't given we don't need to continue searching
// once we've found one.
return;
end if;
end if;
end if;
end for;
end warnAboutIterationVariablesWithDefaultZeroStartAttribute1;
protected function warnAboutVars2 "author: lochel
TODO: Replace this with an general BackendDump implementation."
input list<BackendDAE.Var> inVars;
output String outString;
algorithm
outString := match(inVars)
local
BackendDAE.Var v;
list<BackendDAE.Var> vars;
String crStr;
String str;
case ({}) then "";
case (v::{}) equation
crStr = " " + BackendDump.varString(v);
then crStr;
case (v::vars) equation
crStr = BackendDump.varString(v);
str = " " + crStr + "\n" + warnAboutVars2(vars);
then str;
end match;
end warnAboutVars2;
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."
input BackendDAE.BackendDAE inDAE;
output BackendDAE.Variables outVars;
output list<BackendDAE.Var> outPrimaryParameters = {};
output list<BackendDAE.Var> outAllPrimaryParameters = {};
protected
BackendDAE.Variables allParameters;
BackendDAE.EquationArray allParameterEqns;
BackendDAE.EqSystem paramSystem;
BackendDAE.IncidenceMatrix m, mT;
array<Integer> ass1 "eqn := ass1[var]";
array<Integer> ass2 "var := ass2[eqn]";
list<list<Integer>> comps;
list<Integer> flatComps;
Integer nParam;
array<Integer> secondary;
BackendDAE.Var p;
DAE.Exp bindExp;
algorithm
outVars := selectInitializationVariables(inDAE.eqs);
outVars := BackendVariable.traverseBackendDAEVars(inDAE.shared.knownVars, selectInitializationVariables2, outVars);
outVars := BackendVariable.traverseBackendDAEVars(inDAE.shared.aliasVars, selectInitializationVariables2, outVars);
// select all parameters
allParameters := BackendVariable.emptyVars();
allParameterEqns := BackendEquation.emptyEqns();
(allParameters, allParameterEqns) := BackendVariable.traverseBackendDAEVars(inDAE.shared.knownVars, selectParameter2, (allParameters, allParameterEqns));
nParam := BackendVariable.varsSize(allParameters);
if nParam > 0 then
//BackendDump.dumpVariables(allParameters, "all parameters");
//BackendDump.dumpEquationArray(allParameterEqns, "all parameter equations");
paramSystem := BackendDAEUtil.createEqSystem(allParameters, allParameterEqns);
(m, mT) := BackendDAEUtil.incidenceMatrix(paramSystem, BackendDAE.NORMAL(), NONE());
//BackendDump.dumpIncidenceMatrix(m);
//BackendDump.dumpIncidenceMatrixT(mT);
// match the system
// ass1 and ass2 should be {1, 2, ..., nParam}
(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, allParameters) for comp in comps);
//BackendDump.dumpIncidenceRow(flatComps);
// select secondary parameters
secondary := arrayCreate(nParam, 0);
secondary := selectSecondaryParameters(flatComps, allParameters, mT, secondary);
//BackendDump.dumpMatchingVars(secondary);
// get primary and secondary parameters
for i in flatComps loop
p := BackendVariable.getVarAt(allParameters, i);
if 1 == secondary[i] then
outVars := BackendVariable.addVar(p, outVars);
else
outAllPrimaryParameters := p::outAllPrimaryParameters;
try
bindExp := BackendVariable.varBindExpStartValue(p);
if not Expression.isConst(bindExp) then
outPrimaryParameters := p::outPrimaryParameters;
end if;
else
end try;
end if;
end for;
outPrimaryParameters := listReverse(outPrimaryParameters);
outAllPrimaryParameters := listReverse(outAllPrimaryParameters);
end if;
end selectInitializationVariablesDAE;
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.IncidenceMatrix 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 (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;
protected 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 selectParameter2 "author: lochel"
input BackendDAE.Var inVar;
input tuple<BackendDAE.Variables, BackendDAE.EquationArray> inTpl;
output BackendDAE.Var outVar = inVar;
output tuple<BackendDAE.Variables, BackendDAE.EquationArray> outTpl;
algorithm
outTpl := match (inVar, inTpl)
local
BackendDAE.Variables vars;
BackendDAE.EquationArray eqns;
DAE.Exp bindExp, crefExp, startValue;
BackendDAE.Equation eqn;
DAE.ComponentRef cref;
// parameter without binding
case (BackendDAE.VAR(varKind=BackendDAE.PARAM(), bindExp=NONE()), (vars, eqns)) equation
vars = BackendVariable.addVar(inVar, vars);
cref = BackendVariable.varCref(inVar);
crefExp = Expression.crefExp(cref);
startValue = BackendVariable.varStartValue(inVar);
eqn = BackendDAE.EQUATION(crefExp, startValue, DAE.emptyElementSource, BackendDAE.EQ_ATTR_DEFAULT_INITIAL);
eqns = BackendEquation.addEquation(eqn, eqns);
then ((vars, eqns));
// parameter with binding
case (BackendDAE.VAR(varKind=BackendDAE.PARAM(), bindExp=SOME(bindExp)), (vars, eqns)) equation
vars = BackendVariable.addVar(inVar, vars);
cref = BackendVariable.varCref(inVar);
crefExp = Expression.crefExp(cref);
eqn = BackendDAE.EQUATION(crefExp, bindExp, DAE.emptyElementSource, BackendDAE.EQ_ATTR_DEFAULT_INITIAL);
eqns = BackendEquation.addEquation(eqn, eqns);
then ((vars, eqns));
else inTpl;
end match;
end selectParameter2;
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;
// unfixed state
case (BackendDAE.VAR(varKind=BackendDAE.STATE()), vars) equation
false = BackendVariable.varFixed(inVar);
vars = BackendVariable.addVar(inVar, vars);
then (inVar, vars);
// unfixed discrete -> pre(vd)
case (BackendDAE.VAR(varName=cr, varKind=BackendDAE.DISCRETE(), varType=ty, arryDim=arryDim), vars) equation
false = BackendVariable.varFixed(inVar);
preCR = ComponentReference.crefPrefixPre(cr); // cr => $PRE.cr
preVar = BackendDAE.VAR(preCR, BackendDAE.VARIABLE(), DAE.BIDIR(), DAE.NON_PARALLEL(), ty, NONE(), NONE(), arryDim, DAE.emptyElementSource, NONE(), NONE(), NONE(), DAE.NON_CONNECTOR(), DAE.NOT_INNER_OUTER(), false);
vars = BackendVariable.addVar(preVar, vars);
then (inVar, vars);
else (inVar, inVars);
end matchcontinue;
end selectInitializationVariables2;
// =============================================================================
// section for simplifying initial functions
//
// =============================================================================
protected function simplifyInitialFunctions
input DAE.Exp inExp;
input Boolean inUseHomotopy;
output DAE.Exp exp;
output Boolean useHomotopy;
algorithm
(exp, useHomotopy) := Expression.traverseExpBottomUp(inExp, simplifyInitialFunctionsExp, inUseHomotopy);
end simplifyInitialFunctions;
protected function simplifyInitialFunctionsExp
input DAE.Exp inExp;
input Boolean useHomotopy;
output DAE.Exp outExp;
output Boolean outUseHomotopy;
algorithm
(outExp, outUseHomotopy) := match (inExp, useHomotopy)
local
DAE.Exp e1, e2, e3, actual, simplified;
case (DAE.CALL(path = Absyn.IDENT(name="initial")), _)
then (DAE.BCONST(true), useHomotopy);
case (DAE.CALL(path = Absyn.IDENT(name="sample")), _)
then (DAE.BCONST(false), useHomotopy);