-
Notifications
You must be signed in to change notification settings - Fork 298
/
SimCodeUtil.mo
14882 lines (13520 loc) · 627 KB
/
SimCodeUtil.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 SimCodeUtil
" file: SimCodeUtil.mo
package: SimCodeUtil
description: Code generation using Susan templates
The entry points to this module are the functions createSimCode and
createFunctions."
// public imports
public
import Absyn;
import BackendDAE;
import Ceval;
import DAE;
import DoubleEnded;
import HashTableCrIListArray;
import HashTableCrILst;
import HashTableExpToIndex;
import SCode;
import SimCode;
import SimCodeVar;
import Tpl;
import Types;
import Unit;
import Values;
import HashSetString;
// protected imports
protected
import Array;
import AbsynUtil;
import AvlSetString;
import BackendDAEOptimize;
import BackendDAETransform;
import BackendDAEUtil;
import BackendDump;
import BackendEquation;
import BackendVariable;
import BackendVarTransform;
import BaseHashSet;
import BaseHashTable;
import Builtin;
import CheckModel;
import ClassInf;
import CommonSubExpression.isCSECref;
import ComponentReference;
import Config;
import DAEDump;
import DAEUtil;
import Debug;
import Differentiate;
import ElementSource;
import Error;
import ExecStat.execStat;
import Expression;
import ExpressionDump;
import ExpressionSimplify;
import ExpressionSolve;
import Flags;
import FlagsUtil;
import FMI;
import GC;
import Global;
import Graph;
import HashSet;
import HashSetExp;
import HashTableCrefSimVar;
import HashTableSimCodeEqCache;
import HpcOmSimCode;
import Inline;
import List;
import Matching;
import MetaModelica.Dangerous;
import Mutable;
import PriorityQueue;
import SimCodeDump;
import SimCodeFunctionUtil;
import SimCodeFunctionUtil.varName;
import SymbolicJacobian;
import System;
import Util;
import ValuesUtil;
import VisualXML;
import ZeroCrossings;
import ReduceDAE;
protected constant String UNDERLINE = "========================================";
protected function compareEqSystems
input SimCode.SimEqSystem eq1;
input SimCode.SimEqSystem eq2;
output Boolean b;
algorithm
b := simEqSystemIndex(eq1) > simEqSystemIndex(eq2);
end compareEqSystems;
public function sortEqSystems
input list<SimCode.SimEqSystem> eqs;
output list<SimCode.SimEqSystem> outEqs;
algorithm
outEqs := List.sort(eqs,compareEqSystems);
end sortEqSystems;
protected function simulationFindLiterals
"Finds all literal expressions in functionsa"
input list<DAE.Function> fns;
output list<DAE.Function> ofns;
output tuple<Integer, HashTableExpToIndex.HashTable, list<DAE.Exp>> literals;
algorithm
(ofns, literals) := DAEUtil.traverseDAEFunctions(
fns, SimCodeFunctionUtil.findLiteralsHelper,
(0, HashTableExpToIndex.emptyHashTableSized(BaseHashTable.bigBucketSize), {}));
// Broke things :(
// ((i, ht, literals)) := BackendDAEUtil.traverseBackendDAEExpsNoCopyWithUpdate(dae, findLiteralsHelper, (i, ht, literals));
end simulationFindLiterals;
public function hashEqSystemMod
input SimCode.SimEqSystem eq;
input Integer mod;
output Integer hash;
algorithm
hash := match eq
local
DAE.Statement stmt;
case SimCode.SES_RESIDUAL() then Expression.hashExpMod(eq.exp, mod);
case SimCode.SES_SIMPLE_ASSIGN() then intMod(ComponentReference.hashComponentRefMod(eq.cref,mod)+7*Expression.hashExpMod(eq.exp, mod), mod);
case SimCode.SES_SIMPLE_ASSIGN_CONSTRAINTS() then intMod(ComponentReference.hashComponentRefMod(eq.cref,mod)+7*Expression.hashExpMod(eq.exp, mod), mod);
case SimCode.SES_ARRAY_CALL_ASSIGN() then intMod(Expression.hashExpMod(eq.lhs, mod)+7*Expression.hashExpMod(eq.exp, mod), mod);
case SimCode.SES_ALGORITHM(statements={stmt as DAE.STMT_ASSERT()}) then intMod(Expression.hashExpMod(stmt.cond, mod)+7*Expression.hashExpMod(stmt.msg, mod)+49*Expression.hashExpMod(stmt.level, mod), mod);
// Whatever; we're not caching these values anyway
else intMod(valueConstructor(eq), mod);
end match;
end hashEqSystemMod;
public function compareEqSystemsEquality "Is true if the equations are the same except the index. If false they might still be the same."
input SimCode.SimEqSystem eq1;
input SimCode.SimEqSystem eq2;
output Boolean b;
algorithm
b := match (eq1,eq2)
local
DAE.Statement stmt1,stmt2;
case (SimCode.SES_SIMPLE_ASSIGN(),SimCode.SES_SIMPLE_ASSIGN())
then if 0==ComponentReference.crefCompareGeneric(eq1.cref, eq2.cref) then Expression.expEqual(eq1.exp, eq2.exp) else false;
case (SimCode.SES_ARRAY_CALL_ASSIGN(),SimCode.SES_ARRAY_CALL_ASSIGN())
then if Expression.expEqual(eq1.lhs, eq2.lhs) then Expression.expEqual(eq1.exp, eq2.exp) else false;
case (SimCode.SES_ALGORITHM(statements={stmt1 as DAE.STMT_ASSERT()}),SimCode.SES_ALGORITHM(statements={stmt2 as DAE.STMT_ASSERT()}))
then if Expression.expEqual(stmt1.cond, stmt2.cond) then (if Expression.expEqual(stmt1.msg, stmt2.msg) then Expression.expEqual(stmt1.level, stmt2.level) else false) else false;
else false;
end match;
end compareEqSystemsEquality;
// =============================================================================
// section to create SimCode from BackendDAE
//
// =============================================================================
public function createSimCode "entry point to create SimCode from BackendDAE."
input BackendDAE.BackendDAE inBackendDAE;
input BackendDAE.BackendDAE inInitDAE;
input Option<BackendDAE.BackendDAE> inInitDAE_lambda0;
input Option<BackendDAE.InlineData> inInlineData;
input list<BackendDAE.Equation> inRemovedInitialEquationLst;
input Absyn.Path inClassName;
input String filenamePrefix;
input String inFileDir;
input list<SimCodeFunction.Function> functions;
input list<String> externalFunctionIncludes;
input list<String> includeDirs;
input list<String> libs;
input list<String> libPaths;
input Absyn.Program program;
input Option<SimCode.SimulationSettings> simSettingsOpt;
input list<SimCodeFunction.RecordDeclaration> recordDecls;
input tuple<Integer, HashTableExpToIndex.HashTable, list<DAE.Exp>> literals;
input Absyn.FunctionArgs args;
input Boolean isFMU=false;
input String FMUVersion="";
input String fmuTargetName="";
input BackendDAE.SymbolicJacobians inFMIDer = {};
output SimCode.SimCode simCode;
output tuple<Integer, list<tuple<Integer, Integer>>> outMapping "the highest simEqIndex in the mapping and the mapping simEq-Index -> scc-Index itself";
protected
BackendDAE.BackendDAE dlow, initDAE_lambda0;
BackendDAE.EquationArray removedEqs;
BackendDAE.EventInfo eventInfo;
BackendDAE.Shared shared;
BackendDAE.SymbolicJacobians symJacs;
BackendDAE.Variables globalKnownVars;
Boolean ifcpp;
HashTableCrIListArray.HashTable varToArrayIndexMapping "maps each array-variable to a array of positions";
HashTableCrILst.HashTable varToIndexMapping "maps each variable to an array position";
Integer maxDelayedExpIndex, uniqueEqIndex, numberofEqns, numStateSets, numberOfJacobians, sccOffset;
Integer numberofLinearSys, numberofNonLinearSys, numberofMixedSys, numberofFixedParameters, reasonableSize;
Option<SimCode.FmiModelStructure> modelStructure = NONE();
Option<SimCode.FmiSimulationFlags> fmiSimulationFlags = NONE();
SimCode.BackendMapping backendMapping;
SimCode.ExtObjInfo extObjInfo;
SimCode.HashTableCrefToSimVar crefToSimVarHT;
SimCodeFunction.MakefileParams makefileParams;
SimCode.ModelInfo modelInfo;
HashTable.HashTable crefToClockIndexHT;
array<Integer> systemIndexMap;
list<BackendDAE.EqSystem> clockedSysts, contSysts;
//list<BackendDAE.Equation> paramAsserts, remEqLst;
list<BackendDAE.Equation> removedInitialEquationLst;
list<BackendDAE.TimeEvent> timeEvents;
BackendDAE.ZeroCrossingSet zeroCrossingsSet, sampleZCSet;
DoubleEnded.MutableList<BackendDAE.ZeroCrossing> de_relations;
list<BackendDAE.ZeroCrossing> zeroCrossings, sampleZC, relations;
list<DAE.ClassAttributes> classAttributes;
list<DAE.ComponentRef> discreteModelVars;
list<DAE.Constraint> constraints;
list<DAE.Exp> lits;
list<SimCode.ClockedPartition> clockedPartitions;
list<SimCode.JacobianMatrix> LinearMatrices, SymbolicJacs, SymbolicJacsTemp, SymbolicJacsStateSelect, SymbolicJacsStateSelectInternal, SymbolicJacsNLS, SymbolicJacsFMI={},SymbolicJacsdatarecon={};
list<SimCode.SimEqSystem> algorithmAndEquationAsserts;
list<SimCode.SimEqSystem> localKnownVars;
list<SimCode.SimEqSystem> allEquations;
list<SimCode.SimEqSystem> equationsForZeroCrossings;
list<SimCode.SimEqSystem> initialEquations; // --> initial_equations
list<SimCode.SimEqSystem> initialEquations_lambda0; // --> initial_equations_lambda0
list<SimCode.SimEqSystem> jacobianEquations;
list<SimCode.SimEqSystem> maxValueEquations; // --> updateBoundMaxValues
list<SimCode.SimEqSystem> minValueEquations; // --> updateBoundMinValues
list<SimCode.SimEqSystem> nominalValueEquations; // --> updateBoundNominalValues
//list<SimCode.SimEqSystem> paramAssertSimEqs;
list<SimCode.SimEqSystem> parameterEquations; // --> updateBoundParameters
list<SimCode.SimEqSystem> removedEquations;
list<SimCode.SimEqSystem> removedInitialEquations; // -->
list<SimCode.SimEqSystem> startValueEquations; // --> updateBoundStartValues
list<SimCode.StateSet> stateSets;
list<SimCodeVar.SimVar> tempvars, jacobianSimvars, seedVars;
list<list<SimCode.SimEqSystem>> algebraicEquations; // --> functionAlgebraics
list<list<SimCode.SimEqSystem>> odeEquations; // --> functionODE
list<list<SimCode.SimEqSystem>> inlineEquationsTemp; // --> symbolicInlineSystemTemp
list<SimCode.SimEqSystem> inlineEquations; // --> symbolicInlineSystem
SimCodeVar.SimVars tmpSimVars;
SimCode.VarInfo varInfo;
list<SimCodeVar.SimVar> sensitivityVars;
Integer countSenParams;
list<tuple<Integer, Integer>> equationSccMapping, eqBackendSimCodeMapping;
list<tuple<Integer, tuple<DAE.Exp, DAE.Exp, DAE.Exp>>> delayedExps;
BackendDAE.InlineData inlineData;
list<SimCodeVar.SimVar> inlineSimKnVars;
BackendDAE.Variables emptyVars;
Integer SymEuler_help = 0;
SimCodeVar.SimVar dtSimVar;
BackendDAE.Var dtVar;
HashTableSimCodeEqCache.HashTable eqCache;
BackendDAE.Jacobian dataReconJac;
BackendDAE.Variables setcVars,datareconinputvars;
list<SimCodeVar.SimVar> tmpsetcVars,tmpdatareconinputvars;
SimCode.JacobianMatrix dataReconSimJac;
String fullPathPrefix;
SimCode.OMSIFunction omsiInitEquations, omsiSimEquations;
Option<SimCode.OMSIData> omsiOptData;
constant Boolean debug = false;
algorithm
try
execStat("Backend phase and start with SimCode phase");
dlow := inBackendDAE;
System.tmpTickReset(0);
uniqueEqIndex := 1;
ifcpp := (stringEqual(Config.simCodeTarget(), "Cpp"));
backendMapping := setUpBackendMapping(inBackendDAE);
if Flags.isSet(Flags.VISUAL_XML) then
dlow := VisualXML.visualizationInfoXML(dlow, filenamePrefix, program);
end if;
if Flags.isSet(Flags.ITERATION_VARS) then
BackendDAEOptimize.listAllIterationVariables(dlow);
end if;
// initialization stuff
// ********************
if not ((Config.simCodeTarget() == "omsic") /*or (Config.simCodeTarget() == "omsicpp")*/)
then
// generate equations for initDAE
(initialEquations, uniqueEqIndex, tempvars) := createInitialEquations(inInitDAE, uniqueEqIndex, {});
// generate equations for initDAE_lambda0
if isSome(inInitDAE_lambda0) then
SOME(initDAE_lambda0) := inInitDAE_lambda0;
(initialEquations_lambda0, uniqueEqIndex, tempvars) := createInitialEquations_lambda0(initDAE_lambda0, uniqueEqIndex, tempvars);
else
initialEquations_lambda0 := {};
end if;
// generate equations for removed initial equations
(removedInitialEquations, uniqueEqIndex, tempvars) := createNonlinearResidualEquations(inRemovedInitialEquationLst, uniqueEqIndex, tempvars, dlow.shared.functionTree);
execStat("simCode: created initialization part");
else
initialEquations_lambda0 :={};
initialEquations := {};
removedInitialEquations := {};
tempvars := {};
// TODO: check createInitialEquations to create additional equations for knownVars, alias, etc.
(omsiInitEquations, uniqueEqIndex) :=
createAllEquationOMSI(inInitDAE.eqs, dlow.shared, {}, uniqueEqIndex);
end if;
shared as BackendDAE.SHARED(globalKnownVars=globalKnownVars,
constraints=constraints,
classAttrs=classAttributes,
symjacs=symJacs,
eventInfo=eventInfo) := dlow.shared;
removedEqs := BackendDAEUtil.collapseRemovedEqs(dlow);
// created event suff e.g. zeroCrossings, samples, ...
timeEvents := eventInfo.timeEvents;
(zeroCrossings,relations,sampleZC) := match eventInfo
case BackendDAE.EVENT_INFO(zeroCrossings=zeroCrossingsSet, relations=de_relations, samples=sampleZCSet)
then (ZeroCrossings.toList(zeroCrossingsSet), DoubleEnded.toListNoCopyNoClear(de_relations), ZeroCrossings.toList(sampleZCSet));
end match;
if ifcpp then
zeroCrossings := listAppend(relations, sampleZC);
end if;
(clockedSysts, contSysts) := List.splitOnTrue(dlow.eqs, BackendDAEUtil.isClockedSyst);
execStat("simCode: created event and clocks part");
// ToDo: fix this ugly flag switchting
if (Flags.getConfigEnum(Flags.SYM_SOLVER) > 0) then
SymEuler_help := Flags.getConfigEnum(Flags.SYM_SOLVER);
FlagsUtil.setConfigEnum(Flags.SYM_SOLVER, 0);
end if;
if not ((Config.simCodeTarget() == "omsic")/*or (Config.simCodeTarget() == "omsicpp")*/)
then
(uniqueEqIndex, odeEquations, algebraicEquations, localKnownVars, allEquations, equationsForZeroCrossings, tempvars,
equationSccMapping, eqBackendSimCodeMapping, backendMapping, sccOffset) :=
createEquationsForSystems(contSysts, shared, uniqueEqIndex, zeroCrossings, tempvars, 1, backendMapping, true);
omsiOptData := NONE();
if debug then execStat("simCode: createEquationsForSystems"); end if;
else
odeEquations :={};
algebraicEquations := {};
localKnownVars := {};
allEquations := {};
equationsForZeroCrossings := {};
equationSccMapping := {};
eqBackendSimCodeMapping := {};
sccOffset := 0;
(omsiSimEquations, uniqueEqIndex) :=
createAllEquationOMSI(contSysts, shared, zeroCrossings, uniqueEqIndex);
// Add removed equations (e.g. reinit)
((uniqueEqIndex, removedEquations)) := BackendEquation.traverseEquationArray(removedEqs, traversedlowEqToSimEqSystem, (uniqueEqIndex, {}));
omsiSimEquations.equations := listAppend(omsiSimEquations.equations, removedEquations);
omsiOptData := SOME(SimCode.OMSI_DATA(simulation=omsiSimEquations, initialization=omsiInitEquations));
// debug print
if debug then
_ := match omsiOptData
local
SimCode.OMSIData omsiData;
case SOME(omsiData as SimCode.OMSI_DATA(__))
algorithm
dumpOMSIData(omsiData, "Dump OMSI Data");
then ();
end match;
end if;
end if;
if (SymEuler_help > 0) then
FlagsUtil.setConfigEnum(Flags.SYM_SOLVER, SymEuler_help);
end if;
//List.map1_0(inlineEquations, dumpSimEqSystemLst,"\n");
if debug then execStat("simCode: createEquationsForSystems for inline module"); end if;
outMapping := (uniqueEqIndex /* highestSimEqIndex */, equationSccMapping);
execStat("simCode: created simulation system equations");
//(remEqLst, paramAsserts) := List.fold1(BackendEquation.equationList(removedEqs), getParamAsserts, globalKnownVars,({},{}));
//((uniqueEqIndex, removedEquations)) := BackendEquation.traverseEquationArray(BackendEquation.listEquation(remEqLst), traversedlowEqToSimEqSystem, (uniqueEqIndex, {}));
((uniqueEqIndex, removedEquations)) := BackendEquation.traverseEquationArray(removedEqs, traversedlowEqToSimEqSystem, (uniqueEqIndex, {}));
if debug then execStat("simCode: traversedlowEqToSimEqSystem"); end if;
(clockedPartitions, uniqueEqIndex, backendMapping, equationSccMapping, eqBackendSimCodeMapping, tempvars) :=
translateClockedEquations(clockedSysts, dlow.shared, sccOffset, uniqueEqIndex,
backendMapping, equationSccMapping, eqBackendSimCodeMapping, tempvars);
if debug then execStat("simCode: translateClockedEquations"); end if;
// Assertions and crap
// create parameter equations
((uniqueEqIndex, startValueEquations, _)) := BackendDAEUtil.foldEqSystem(dlow, createStartValueEquations, (uniqueEqIndex, {}, globalKnownVars));
if debug then execStat("simCode: createStartValueEquations"); end if;
((uniqueEqIndex, nominalValueEquations)) := BackendDAEUtil.foldEqSystem(dlow, createNominalValueEquations, (uniqueEqIndex, {}));
if debug then execStat("simCode: createNominalValueEquations"); end if;
((uniqueEqIndex, minValueEquations)) := BackendDAEUtil.foldEqSystem(dlow, createMinValueEquations, (uniqueEqIndex, {}));
if debug then execStat("simCode: createMinValueEquations"); end if;
((uniqueEqIndex, maxValueEquations)) := BackendDAEUtil.foldEqSystem(dlow, createMaxValueEquations, (uniqueEqIndex, {}));
if debug then execStat("simCode: createMaxValueEquations"); end if;
((uniqueEqIndex, parameterEquations)) := BackendDAEUtil.foldEqSystem(dlow, createVarNominalAssertFromVars, (uniqueEqIndex, {}));
if debug then execStat("simCode: createVarNominalAssertFromVars"); end if;
(uniqueEqIndex, parameterEquations, numberofFixedParameters) := createParameterEquations(uniqueEqIndex, parameterEquations, globalKnownVars);
if debug then execStat("simCode: createParameterEquations"); end if;
//((uniqueEqIndex, paramAssertSimEqs)) := BackendEquation.traverseEquationArray(BackendEquation.listEquation(paramAsserts), traversedlowEqToSimEqSystem, (uniqueEqIndex, {}));
//parameterEquations := listAppend(parameterEquations, paramAssertSimEqs);
((uniqueEqIndex, algorithmAndEquationAsserts)) := BackendDAEUtil.foldEqSystem(dlow, createAlgorithmAndEquationAsserts, (uniqueEqIndex, {}));
if debug then execStat("simCode: createAlgorithmAndEquationAsserts"); end if;
discreteModelVars := BackendDAEUtil.foldEqSystem(dlow, extractDiscreteModelVars, {});
if debug then execStat("simCode: extractDiscreteModelVars"); end if;
makefileParams := SimCodeFunctionUtil.createMakefileParams(includeDirs, libs, libPaths, false, isFMU);
(delayedExps, maxDelayedExpIndex) := extractDelayedExpressions(dlow);
execStat("simCode: created of all other equations (e.g. parameter, nominal, assert, etc)");
// append removed equation to all equations, since these are actually
// just the algorithms without outputs
algebraicEquations := List.appendElt(removedEquations, algebraicEquations);
allEquations := List.append_reverse(allEquations, removedEquations);
// create inline equations if present
if isSome(inInlineData) then
SOME(inlineData) := inInlineData;
(uniqueEqIndex, inlineEquationsTemp, _, _, , _, tempvars, _, _, _, _) :=
createEquationsForSystems(inlineData.inlineSystems,
shared, uniqueEqIndex, {}, tempvars, uniqueEqIndex,
SimCode.NO_MAPPING(), false);
inlineEquations := List.flatten(inlineEquationsTemp);
else
inlineEquations := {};
end if;
// state set stuff
(dlow, stateSets, uniqueEqIndex, tempvars, numStateSets) := createStateSets(dlow, {}, uniqueEqIndex, tempvars);
if debug then execStat("simCode: createStateSets"); end if;
// create model info
modelInfo := createModelInfo(inClassName, program, dlow, inInitDAE, functions, {}, numStateSets, inFileDir, listLength(clockedSysts), tempvars);
if debug then execStat("simCode: createModelInfo and variables"); end if;
//build labels
if(boolAnd(ifcpp,Flags.getConfigBool(Flags.LABELED_REDUCTION))) then
FlagsUtil.setConfigBool(Flags.GENERATE_LABELED_SIMCODE,true);
end if;
if(ifcpp) then
if Flags.getConfigBool(Flags.GENERATE_LABELED_SIMCODE) then
(allEquations,modelInfo) := ReduceDAE.buildLabels(allEquations,modelInfo,{},args);
//FlagsUtil.set(Flags.REDUCE_DAE,true);
if debug then execStat("ReduceDAE: buildLabels"); end if;
end if;
end if;
tmpSimVars := modelInfo.vars;
//reduce terms
if(ifcpp) then
if Flags.getConfigBool(Flags.REDUCE_TERMS) then
(allEquations,modelInfo) := ReduceDAE.reduceTerms(allEquations,modelInfo,args);
FlagsUtil.setConfigBool(Flags.REDUCE_TERMS, false);
FlagsUtil.disableDebug(Flags.REDUCE_DAE);
if debug then execStat("ReduceDAE: reduceTerms"); end if;
end if;
end if;
// external objects
extObjInfo := createExtObjInfo(shared);
// update index of zero-Crossings after equations are created
zeroCrossings := updateZeroCrossEqnIndex(zeroCrossings, eqBackendSimCodeMapping, BackendDAEUtil.equationArraySizeBDAE(dlow));
if debug then execStat("simCode: update zero crossing index"); end if;
// collect all LinearSystem and NonlinearSystem algebraic system in modelInfo and update
// the corresponding index (indexNonLinear, indexLinear) in SES_NONLINEAR and SES_LINEAR
// Also collect all jacobians
SymbolicJacsNLS := {};
(initialEquations, modelInfo, SymbolicJacsTemp) := addAlgebraicLoopsModelInfo(initialEquations, modelInfo);
SymbolicJacsNLS := listAppend(SymbolicJacsTemp, SymbolicJacsNLS);
(initialEquations_lambda0, modelInfo, SymbolicJacsTemp) := addAlgebraicLoopsModelInfo(initialEquations_lambda0, modelInfo);
SymbolicJacsNLS := listAppend(SymbolicJacsTemp, SymbolicJacsNLS);
(parameterEquations, modelInfo, SymbolicJacsTemp) := addAlgebraicLoopsModelInfo(parameterEquations, modelInfo);
SymbolicJacsNLS := listAppend(SymbolicJacsTemp, SymbolicJacsNLS);
(allEquations, modelInfo, SymbolicJacsTemp) := addAlgebraicLoopsModelInfo(allEquations, modelInfo);
SymbolicJacsNLS := listAppend(SymbolicJacsTemp, SymbolicJacsNLS);
(clockedPartitions, modelInfo, SymbolicJacsTemp) := addAlgebraicLoopsClockPartitions(clockedPartitions, modelInfo);
SymbolicJacsNLS := listAppend(SymbolicJacsTemp, SymbolicJacsNLS);
(inlineEquations, modelInfo, SymbolicJacsTemp) := addAlgebraicLoopsModelInfo(inlineEquations, modelInfo);
SymbolicJacsNLS := listAppend(SymbolicJacsTemp, SymbolicJacsNLS);
// Generate jacobian code for DataReconciliation
if Util.isSome(shared.dataReconciliationData) then
BackendDAE.DATA_RECON(dataReconJac,setcVars,datareconinputvars) := Util.getOption(shared.dataReconciliationData);
(SOME(dataReconSimJac), uniqueEqIndex, tempvars) := createSymbolicSimulationJacobian(dataReconJac, uniqueEqIndex, tempvars);
(SymbolicJacsdatarecon, modelInfo, SymbolicJacsTemp) := addAlgebraicLoopsModelInfoSymJacs({dataReconSimJac}, modelInfo);
SymbolicJacsNLS := listAppend(SymbolicJacsTemp, SymbolicJacsNLS);
//SymbolicJacsNLS := dataReconSimJac::SymbolicJacsNLS;
end if;
// collect symbolic jacobians from state selection
(stateSets, modelInfo, SymbolicJacsStateSelect, SymbolicJacsStateSelectInternal) := addAlgebraicLoopsModelInfoStateSets(stateSets, modelInfo);
if debug then execStat("simCode: collect and index LS/NLS in modelInfo"); end if;
// collect fmi partial derivative
if FMI.isFMIVersion20(FMUVersion) then
(SymbolicJacsFMI, modelStructure, modelInfo, SymbolicJacsTemp, uniqueEqIndex) := createFMIModelStructure(inFMIDer, modelInfo, uniqueEqIndex, inInitDAE, inBackendDAE);
SymbolicJacsNLS := listAppend(SymbolicJacsTemp, SymbolicJacsNLS);
if debug then execStat("simCode: create FMI model structure"); end if;
end if;
// Collect FMI sim flags
if isFMU then
fmiSimulationFlags := createFMISimulationFlags();
end if;
// collect symbolic jacobians in linear loops of the overall jacobians
(LinearMatrices, uniqueEqIndex) := createJacobianLinearCode(symJacs, modelInfo, uniqueEqIndex, shared);
(SymbolicJacs, modelInfo, SymbolicJacsTemp) := addAlgebraicLoopsModelInfoSymJacs(LinearMatrices, modelInfo);
// append datareconciliation jacobians equation to SymbolicJacs for correct generation of equations in model_info.json
SymbolicJacs := List.flatten({SymbolicJacsFMI, SymbolicJacs, SymbolicJacsStateSelect, SymbolicJacsdatarecon});
// collect jacobian equation only for equantion info file
jacobianEquations := collectAllJacobianEquations(SymbolicJacs);
if debug then execStat("simCode: create Jacobian linear code"); end if;
SymbolicJacs := List.flatten({listReverse(SymbolicJacsNLS), SymbolicJacs, SymbolicJacsTemp, SymbolicJacsStateSelectInternal});
jacobianSimvars := collectAllJacobianVars(SymbolicJacs);
modelInfo := setJacobianVars(jacobianSimvars, modelInfo);
seedVars := collectAllSeedVars(SymbolicJacs);
modelInfo := setSeedVars(seedVars, modelInfo);
execStat("simCode: created linear, non-linear and system jacobian parts");
// map index also odeEquations and algebraicEquations
systemIndexMap := List.fold(allEquations, getSystemIndexMap, arrayCreate(uniqueEqIndex, -1));
odeEquations := List.mapList1_1(odeEquations, setSystemIndexMap, systemIndexMap);
algebraicEquations := List.mapList1_1(algebraicEquations, setSystemIndexMap, systemIndexMap);
modelInfo := addNumEqns(modelInfo, uniqueEqIndex /* This is a *much* better estimate than the guessed number of equations */ );
odeEquations := makeEqualLengthLists(odeEquations, Config.noProc());
algebraicEquations := makeEqualLengthLists(algebraicEquations, Config.noProc());
// Filter out empty systems to improve code generation
odeEquations := List.filterOnFalse(odeEquations, listEmpty);
algebraicEquations := List.filterOnFalse(algebraicEquations, listEmpty);
if Flags.isSet(Flags.EXEC_HASH) then
print("*** SimCode -> generate cref2simVar hashtable: " + realString(clock()) + "\n");
end if;
// generate cref2simVar hash table
crefToSimVarHT := createCrefToSimVarHT(modelInfo);
if Flags.isSet(Flags.EXEC_HASH) then
print("*** SimCode -> generate cref2simVar hashtable done!: " + realString(clock()) + "\n");
end if;
// add known inline vars to simVarHT
if (Flags.getConfigEnum(Flags.SYM_SOLVER) > 0) then
SOME(inlineData) := inInlineData;
emptyVars := BackendVariable.emptyVars();
inlineSimKnVars := adjustStatesForInlineSolver(modelInfo.vars.stateVars);
// omc dt
({dtVar},_) := BackendVariable.getVar(ComponentReference.makeCrefIdent(BackendDAE.symSolverDT, DAE.T_REAL_DEFAULT, {}), inlineData.knownVariables);
dtSimVar := dlowvarToSimvar(dtVar, NONE(), emptyVars);
dtSimVar.index := listLength(inlineSimKnVars);
inlineSimKnVars := dtSimVar::inlineSimKnVars;
crefToSimVarHT := List.fold(inlineSimKnVars,HashTableCrefSimVar.addSimVarToHashTable,crefToSimVarHT);
end if;
if Flags.getConfigBool(Flags.CALCULATE_SENSITIVITIES) then
tmpSimVars := modelInfo.vars;
(sensitivityVars, countSenParams) := createSimVarsForSensitivities(tmpSimVars.stateVars, tmpSimVars.paramVars, numberofFixedParameters);
sensitivityVars := rewriteIndex(sensitivityVars, 0);
tmpSimVars.sensitivityVars := sensitivityVars;
modelInfo.vars := tmpSimVars;
// set varInfo nSensitivities
varInfo := modelInfo.varInfo;
varInfo.numSensitivityParameters := countSenParams;
modelInfo.varInfo := varInfo;
end if;
// Generates c code for setC-results which calculates c(x,y) for dataReconciliation
if Util.isSome(shared.dataReconciliationData) then
tmpSimVars := modelInfo.vars;
//BackendDAE.DATA_RECON(dataReconJac,setcVars) := Util.getOption(shared.dataReconciliationData);
((tmpsetcVars, _)) := BackendVariable.traverseBackendDAEVars(setcVars, traversingdlowvarToSimvar, ({}, emptyVars));
tmpsetcVars := rewriteIndex(tmpsetcVars, 0);
tmpSimVars.dataReconSetcVars := tmpsetcVars;
modelInfo.vars := tmpSimVars;
//add the input vars for dataReconciliation
((tmpdatareconinputvars, _)) := BackendVariable.traverseBackendDAEVars(datareconinputvars, traversingdlowvarToSimvar, ({}, emptyVars));
tmpdatareconinputvars := rewriteIndex(listReverse(tmpdatareconinputvars), 0);
tmpSimVars.dataReconinputVars := tmpdatareconinputvars;
modelInfo.vars := tmpSimVars;
// set varInfo nsetcvars
varInfo := modelInfo.varInfo;
varInfo.numSetcVars := listLength(tmpsetcVars);
varInfo.numDataReconVars := listLength(tmpdatareconinputvars);
modelInfo.varInfo := varInfo;
//print("\n simcode gen setc:*****"+anyString(tmpsetcVars) + "\n lenght of vars :" +anyString(listLength(tmpsetcVars)));
end if;
//print("\n created model_info:"+ anyString(modelInfo.varInfo.numSetcVars)+ "\n setcvars" + anyString(modelInfo.vars.dataReconSetcVars));
backendMapping := setBackendVarMapping(inBackendDAE, crefToSimVarHT, modelInfo, backendMapping);
//dumpBackendMapping(backendMapping);
(varToArrayIndexMapping, varToIndexMapping) := createVarToArrayIndexMapping(modelInfo);
//print("HASHTABLE MAPPING\n\n");
//BaseHashTable.dumpHashTable(varToArrayIndexMapping);
//print("END MAPPING\n\n");
(crefToClockIndexHT, _) := List.fold(listReverse(inBackendDAE.eqs), collectClockedVars, (HashTable.emptyHashTable(), 1));
execStat("simCode: some other stuff during SimCode phase");
if ((Config.simCodeTarget() <> "Cpp"))then
reasonableSize := Util.nextPrime(10+integer(1.4*(BackendDAEUtil.equationArraySizeBDAE(inBackendDAE)+BackendDAEUtil.equationArraySizeBDAE(inInitDAE)+listLength(parameterEquations))));
eqCache := HashTableSimCodeEqCache.emptyHashTableSized(reasonableSize);
// Alias equations to other equations.
// The C++ codegen does things differently and will not handle this
(allEquations, eqCache) := aliasSimEqs(allEquations, eqCache);
(odeEquations, eqCache) := aliasSimEqSystems(odeEquations, eqCache);
(algebraicEquations, eqCache) := aliasSimEqSystems(algebraicEquations, eqCache);
(initialEquations, eqCache) := aliasSimEqs(initialEquations, eqCache);
(initialEquations_lambda0, eqCache) := aliasSimEqs(initialEquations_lambda0, eqCache);
(removedEquations, eqCache) := aliasSimEqs(removedEquations, eqCache);
(removedInitialEquations, eqCache) := aliasSimEqs(removedInitialEquations, eqCache);
(algorithmAndEquationAsserts, eqCache) := aliasSimEqs(algorithmAndEquationAsserts, eqCache);
(jacobianEquations, eqCache) := aliasSimEqs(jacobianEquations, eqCache);
(parameterEquations, eqCache) := aliasSimEqs(parameterEquations, eqCache);
execStat("simCode: alias equations");
end if;
// Set fullPathPrefix for FMUs
if isFMU then
if (Config.simCodeTarget()=="omsic") /* or (Config.simCodeTarget() == "omsicpp")*/ then
fullPathPrefix := filenamePrefix+".fmutmp";
else
fullPathPrefix := filenamePrefix+".fmutmp/sources/";
end if;
else
fullPathPrefix := "";
end if;
simCode := SimCode.SIMCODE(
modelInfo = modelInfo,
literals = {}, // Set by the traversal below...
recordDecls = recordDecls,
externalFunctionIncludes = externalFunctionIncludes,
localKnownVars = localKnownVars,
allEquations = allEquations,
odeEquations = odeEquations,
algebraicEquations = algebraicEquations,
clockedPartitions = clockedPartitions,
initialEquations = initialEquations,
initialEquations_lambda0 = initialEquations_lambda0,
removedInitialEquations = removedInitialEquations,
startValueEquations = startValueEquations,
nominalValueEquations = nominalValueEquations,
minValueEquations = minValueEquations,
maxValueEquations = maxValueEquations,
parameterEquations = parameterEquations,
removedEquations = removedEquations,
algorithmAndEquationAsserts = algorithmAndEquationAsserts,
equationsForZeroCrossings = equationsForZeroCrossings,
jacobianEquations = jacobianEquations,
stateSets = stateSets,
constraints = constraints,
classAttributes = classAttributes,
zeroCrossings = zeroCrossings,
relations = relations,
timeEvents = timeEvents,
discreteModelVars = discreteModelVars,
extObjInfo = extObjInfo,
makefileParams = makefileParams,
delayedExps = SimCode.DELAYED_EXPRESSIONS(delayedExps, maxDelayedExpIndex),
jacobianMatrixes = SymbolicJacs,
simulationSettingsOpt = simSettingsOpt,
fileNamePrefix = filenamePrefix,
fullPathPrefix = fullPathPrefix,
fmuTargetName = fmuTargetName,
hpcomData = HpcOmSimCode.emptyHpcomData,
valueReferences = if isFMU then getValueReferenceMapping(modelInfo) else AvlTreeCRToInt.EMPTY(),
varToArrayIndexMapping = varToArrayIndexMapping,
varToIndexMapping = varToIndexMapping,
crefToSimVarHT = crefToSimVarHT,
crefToClockIndexHT = crefToClockIndexHT,
backendMapping = SOME(backendMapping),
modelStructure = modelStructure,
fmiSimulationFlags = fmiSimulationFlags,
partitionData = SimCode.emptyPartitionData,
daeModeData = NONE(),
inlineEquations = inlineEquations,
omsiData = omsiOptData
);
(simCode, (_, _, lits)) := traverseExpsSimCode(simCode, SimCodeFunctionUtil.findLiteralsHelper, literals);
simCode := setSimCodeLiterals(simCode, listReverse(lits));
// dumpCrefToSimVarHashTable(crefToSimVarHT);
// print("*** SimCode -> collect all files started: " + realString(clock()) + "\n");
// adrpo: collect all the files from SourceInfo and DAE.ElementSource
// simCode := collectAllFiles(simCode);
// print("*** SimCode -> collect all files done!: " + realString(clock()) + "\n");
execStat("simCode: all other stuff during SimCode phase");
if Flags.isSet(Flags.DUMP_SIMCODE) then
dumpSimCodeDebug(simCode);
end if;
else
Error.addInternalError("function createSimCode failed [Transformation from optimised DAE to simulation code structure failed]", sourceInfo());
fail();
end try;
end createSimCode;
public function createFunctions
input Absyn.Program inProgram;
input DAE.FunctionTree functionTree;
output list<String> outLibs;
output list<String> outLibPaths;
output list<String> outIncludes;
output list<String> outIncludeDirs;
output list<SimCodeFunction.RecordDeclaration> outRecordDecls;
output list<SimCodeFunction.Function> outFunctions;
output tuple<Integer, HashTableExpToIndex.HashTable, list<DAE.Exp>> outLiterals;
protected
list<DAE.Function> funcelems;
list<DAE.Exp> lits;
algorithm
try
// get all the used functions from the function tree
funcelems := DAEUtil.getFunctionList(functionTree);
funcelems := Inline.inlineCallsInFunctions(funcelems, (NONE(), {DAE.NORM_INLINE(), DAE.AFTER_INDEX_RED_INLINE()}));
(funcelems, outLiterals as (_, _, lits)) := simulationFindLiterals(funcelems);
(outFunctions, outRecordDecls, outIncludes, outIncludeDirs, outLibs, outLibPaths) := SimCodeFunctionUtil.elaborateFunctions(inProgram, funcelems, {}, lits, {}); // Do we need metarecords here as well?
else
Error.addInternalError("Creation of Modelica functions failed.", sourceInfo());
fail();
end try;
end createFunctions;
protected function getParamAsserts"splits the equationArray in variable-dependent and parameter-dependent equations.
author: Waurich TUD-2015-04"
input BackendDAE.Equation eqIn;
input BackendDAE.Variables vars;
input tuple<list<BackendDAE.Equation>, list<BackendDAE.Equation>> tplIn; //<var-dependent, param-dependent>
output tuple<list<BackendDAE.Equation>, list<BackendDAE.Equation>> tplOut;
algorithm
tplOut := matchcontinue(eqIn,vars,tplIn)
local
list<DAE.Statement> stmts;
list<DAE.ComponentRef> crefs;
list<BackendDAE.Var> varLst;
list<list<BackendDAE.Var>> varLstLst;
list<BackendDAE.Equation> varDep,paramDep;
case(BackendDAE.ALGORITHM(alg=DAE.ALGORITHM_STMTS(statementLst=stmts)),_,(varDep,paramDep))
algorithm
crefs := List.fold(stmts,DAEUtil.getAssertConditionCrefs,{});
(varLstLst,_) := List.map1_2(crefs,BackendVariable.getVar,vars);
varLst := List.flatten(varLstLst);
true := List.exist(varLst,BackendVariable.isParam);
then ((varDep,eqIn::paramDep));
else
algorithm
(varDep,paramDep) := tplIn;
then ((eqIn::varDep,paramDep));
end matchcontinue;
end getParamAsserts;
protected function translateClockedEquations
input BackendDAE.EqSystems inSysts;
input BackendDAE.Shared inShared;
input Integer iSccOffset;
input Integer iuniqueEqIndex;
input SimCode.BackendMapping iBackendMapping;
input list<tuple<Integer,Integer>> ieqSccMapping;
input list<tuple<Integer,Integer>> ieqBackendSimCodeMapping;
input list<SimCodeVar.SimVar> itempvars;
output list<SimCode.ClockedPartition> outPartitions = {};
output Integer ouniqueEqIndex = iuniqueEqIndex;
output SimCode.BackendMapping oBackendMapping = iBackendMapping;
output list<tuple<Integer,Integer>> oeqSccMapping = ieqSccMapping;
output list<tuple<Integer,Integer>> oeqBackendSimCodeMapping = ieqBackendSimCodeMapping;
output list<SimCodeVar.SimVar> otempvars = itempvars;
protected
Integer baseIdx, subPartIdx, cnt;
BackendDAE.SubClock subClk;
list<SimCode.SimEqSystem> removedEquations, equations, preEquations;
SimCode.SubPartition simSubPartition;
Boolean holdEvents;
array<Integer> ass1, stateeqnsmark, zceqnsmarks;
DAE.FunctionTree funcs;
BackendDAE.StrongComponents comps;
Integer sccOffset = iSccOffset;
list<Integer> varIxs;
DAE.Type ty;
BackendDAE.Var var;
BackendDAE.Equation eq;
SimCodeVar.SimVar simVar;
DAE.ComponentRef cr;
list<SimCodeVar.SimVar> clockedVars;
list<tuple<SimCodeVar.SimVar, Boolean>> prevClockedVars;
array<Option<SimCode.SubPartition>> simSubPartitions;
BackendDAE.SubPartition subPartition;
BackendDAE.Var var;
array<Boolean> isPrevVar;
SimCode.SimEqSystem simEq;
algorithm
simSubPartitions := arrayCreate(arrayLength(inShared.partitionsInfo.subPartitions), NONE());
funcs := BackendDAEUtil.getFunctions(inShared);
for syst in inSysts loop
//syst := preCalculateStartValues(syst, inShared.globalKnownVars, funcs);
BackendDAE.CLOCKED_PARTITION(subPartIdx) := syst.partitionKind;
BackendDAE.MATCHING(ass1=ass1, comps=comps) := syst.matching;
subPartition := inShared.partitionsInfo.subPartitions[subPartIdx];
(syst, _, _) := BackendDAEUtil.getAdjacencyMatrixfromOption(syst, BackendDAE.ABSOLUTE(), SOME(funcs), BackendDAEUtil.isInitializationDAE(inShared));
stateeqnsmark := arrayCreate(BackendDAEUtil.equationArraySizeDAE(syst), 0);
stateeqnsmark := BackendDAEUtil.markStateEquations(syst, stateeqnsmark, ass1);
zceqnsmarks := arrayCreate(BackendDAEUtil.equationArraySizeDAE(syst), 0);
//FIXME: Add continuous clocked systems support
(_, _, equations, _, ouniqueEqIndex, clockedVars, oeqSccMapping, oeqBackendSimCodeMapping, oBackendMapping) :=
createEquationsForSystem(stateeqnsmark, zceqnsmarks, syst, inShared, comps, ouniqueEqIndex, {},
sccOffset, oeqSccMapping, oeqBackendSimCodeMapping, oBackendMapping, true);
sccOffset := listLength(comps) + sccOffset;
//otempvars := listAppend(clockedVars, otempvars);
GC.free(stateeqnsmark);
GC.free(zceqnsmarks);
(ouniqueEqIndex, removedEquations) := BackendEquation.traverseEquationArray(syst.removedEqs, traversedlowEqToSimEqSystem, (ouniqueEqIndex, {}));
prevClockedVars := {};
isPrevVar := arrayCreate(BackendVariable.varsSize(syst.orderedVars), false);
for cr in subPartition.prevVars loop
(_, varIxs) := BackendVariable.getVar(cr, syst.orderedVars);
for i in varIxs loop
arrayUpdate(isPrevVar, i, true);
end for;
end for;
for i in 1:BackendVariable.varsSize(syst.orderedVars) loop
var := BackendVariable.getVarAt(syst.orderedVars, i);
simVar := dlowvarToSimvar(var, SOME(inShared.aliasVars), inShared.globalKnownVars);
prevClockedVars := (simVar, isPrevVar[i])::prevClockedVars;
clockedVars := simVar::clockedVars;
if isPrevVar[i] then
cr := simVar.name;
simVar.name := ComponentReference.crefPrefixPrevious(cr);
clockedVars := simVar::clockedVars;
simEq := SimCode.SES_SIMPLE_ASSIGN(ouniqueEqIndex, simVar.name, DAE.CREF(cr, simVar.type_), DAE.emptyElementSource, BackendDAE.EQ_ATTR_DEFAULT_UNKNOWN);
equations := simEq::equations;
ouniqueEqIndex := ouniqueEqIndex + 1;
end if;
end for;
GC.free(isPrevVar);
//otempvars := listAppend(clockedVars, otempvars);
simSubPartition := SimCode.SUBPARTITION(prevClockedVars, equations, removedEquations, subPartition.clock, subPartition.holdEvents);
assert(isNone(simSubPartitions[subPartIdx]), "SimCodeUtil.translateClockedEquations failed");
arrayUpdate(simSubPartitions, subPartIdx, SOME(simSubPartition));
end for;
outPartitions := createClockedSimPartitions(inShared.partitionsInfo.basePartitions, simSubPartitions);
GC.free(simSubPartitions);
end translateClockedEquations;
protected function createClockedSimPartitions
input array<BackendDAE.BasePartition> basePartitions;
input array<Option<SimCode.SubPartition>> subPartitions;
output list<SimCode.ClockedPartition> clockedPartitions = {};
protected
Integer off = 1;
BackendDAE.BasePartition basePartition;
list<SimCode.SubPartition> simSubPartitions;
algorithm
for i in 1:arrayLength(basePartitions) loop
basePartition := basePartitions[i];
if basePartition.nSubClocks > 0 then
simSubPartitions := List.map(Array.getRange(off, off + basePartition.nSubClocks - 1, subPartitions), Util.getOption);
simSubPartitions := listReverse(simSubPartitions);
else
simSubPartitions := {};
end if;
off := off + basePartition.nSubClocks;
clockedPartitions := SimCode.CLOCKED_PARTITION(basePartition.clock, simSubPartitions)::clockedPartitions;
end for;
clockedPartitions := listReverse(clockedPartitions); // in order to keep the correct indexes for the correct clkfire-calls
end createClockedSimPartitions;
protected function collectClockedVars "author: rfranke
This function collects clocked variables along with their clockIndex"
input BackendDAE.EqSystem inEqSystem;
input tuple<HashTable.HashTable, Integer> inTpl;
output tuple<HashTable.HashTable, Integer> outTpl;
protected
HashTable.HashTable inHT, outHT;
Integer clockIndex;
algorithm
(inHT, clockIndex) := inTpl;
outTpl := match inEqSystem
case BackendDAE.EQSYSTEM(partitionKind = BackendDAE.CLOCKED_PARTITION(_)) equation
(outHT, _) = BackendVariable.traverseBackendDAEVars(inEqSystem.orderedVars, collectClockedVars1, (inHT, clockIndex));
then (outHT, clockIndex + 1);
else inTpl;
end match;
end collectClockedVars;
protected function collectClockedVars1 "author: rfranke
Helper to collectClockedVars"
input BackendDAE.Var inVar;
input tuple<HashTable.HashTable, Integer> inTpl;
output BackendDAE.Var outVar;
output tuple<HashTable.HashTable, Integer> outTpl;
protected
HashTable.HashTable clkHT;
Integer clockIndex;
DAE.ComponentRef cref;
algorithm
(clkHT, clockIndex) := inTpl;
(outVar, outTpl) := match inVar
case BackendDAE.VAR(varName=cref) equation
clkHT = BaseHashTable.add((cref, clockIndex), clkHT);
clkHT = BaseHashTable.add((ComponentReference.crefPrefixPrevious(cref), clockIndex), clkHT);
then (inVar, (clkHT, clockIndex));
else (inVar, inTpl);
end match;
end collectClockedVars1;
public function getClockIndex "author: rfranke
Returns the index of the clock of a variable or zero non-clocked variables"
input SimCodeVar.SimVar simVar;
input SimCode.SimCode simCode;
output Option<Integer> clockIndex;
protected
DAE.ComponentRef cref;
HashTable.HashTable clkHT;
algorithm
cref := getSimVarCompRef(simVar);
clockIndex := match simCode
case SimCode.SIMCODE(crefToClockIndexHT=clkHT) then
if BaseHashTable.hasKey(cref, clkHT)
then SOME(BaseHashTable.get(cref, clkHT))
else NONE();
end match;
end getClockIndex;
protected function getSimVarCompRef
input SimCodeVar.SimVar inVar;
output DAE.ComponentRef outComp;
algorithm
outComp := inVar.name;
end getSimVarCompRef;
public function getSubPartitions
input list<SimCode.ClockedPartition> inPartitions;
output list<SimCode.SubPartition> outSubPartitions;
algorithm
outSubPartitions := List.flatten(List.map(inPartitions, getSubPartition));
end getSubPartitions;
public function getSubPartition
input SimCode.ClockedPartition inPartition;