/
SynchronousFeatures.mo
3275 lines (3072 loc) · 124 KB
/
SynchronousFeatures.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 SynchronousFeatures
" file: SynchronousFeatures.mo
package: SynchronousFeatures
description: This package contains functions that belong to synchronous features.
- base-clock partitioning
- sub-clock partitioning"
public import Absyn;
public import BackendDAE;
public import DAE;
protected import BackendDAEOptimize;
protected import BackendDAEUtil;
protected import BackendDump;
protected import ExpressionDump;
protected import BackendEquation;
protected import BackendVariable;
protected import ComponentReference;
protected import DAEUtil;
protected import DAEDump;
protected import Error;
protected import Flags;
protected import List;
protected import Util;
protected import Types;
protected import Expression;
protected import HashTable;
protected import MMath;
// =============================================================================
// clock partitioning
//
// =============================================================================
public function clockPartitioning
"Finds independent partitions of the equation system by base-clock partitioning and TLM."
input BackendDAE.BackendDAE inDAE;
output BackendDAE.BackendDAE outDAE;
algorithm
outDAE := match inDAE
local
BackendDAE.EqSystem syst;
BackendDAE.Shared shared;
case (BackendDAE.DAE({syst}, shared))
then clockPartitioning1(syst, shared);
// TODO: Improve support for partitioned systems of equations
else equation
BackendDAE.DAE({syst}, shared) = BackendDAEOptimize.collapseIndependentBlocks(inDAE);
then clockPartitioning1(syst, shared);
end match;
end clockPartitioning;
public function synchronousFeatures
input BackendDAE.BackendDAE inDAE;
output BackendDAE.BackendDAE outDAE;
protected
BackendDAE.EqSystems systs, contSysts, clockedSysts;
BackendDAE.Shared shared;
algorithm
(clockedSysts, contSysts) := List.splitOnTrue(inDAE.eqs, BackendDAEUtil.isClockedSyst);
if not listEmpty(clockedSysts) then
shared := inDAE.shared;
(clockedSysts, shared) := treatClockedStates(clockedSysts, shared);
systs := listAppend(contSysts, clockedSysts);
outDAE := BackendDAE.DAE(systs, shared);
if Flags.isSet(Flags.DUMP_SYNCHRONOUS) then
print("synchronous features post-phase: synchronousFeatures\n\n");
BackendDump.dumpEqSystems(systs, "clock partitioning");
BackendDump.dumpBasePartitions(shared.partitionsInfo.basePartitions, "Base clocks");
BackendDump.dumpSubPartitions(shared.partitionsInfo.subPartitions, "Sub clocks");
end if;
else
outDAE := inDAE;
end if;
end synchronousFeatures;
public function contPartitioning
input BackendDAE.BackendDAE inDAE;
output BackendDAE.BackendDAE outDAE;
protected
BackendDAE.EqSystems systs, clockedSysts, clockedSysts1;
BackendDAE.Shared shared;
BackendDAE.EqSystem syst;
list<BackendDAE.Equation> unpartRemEqs;
algorithm
(clockedSysts, systs) := List.splitOnTrue(inDAE.eqs, BackendDAEUtil.isClockedSyst);
shared := inDAE.shared;
if not listEmpty(systs) then
BackendDAE.DAE({syst}, shared) := BackendDAEOptimize.collapseIndependentBlocks(BackendDAE.DAE(systs, shared));
(systs, clockedSysts1, unpartRemEqs) := baseClockPartitioning(syst, shared);
assert(listLength(clockedSysts1) == 0, "Get clocked system in SynchronousFeatures.addContVarsEqs");
shared.removedEqs := BackendEquation.addList(unpartRemEqs, shared.removedEqs);
end if;
outDAE := BackendDAE.DAE(listAppend(systs, clockedSysts), shared);
end contPartitioning;
protected function clockPartitioning1
input BackendDAE.EqSystem inSyst;
input BackendDAE.Shared inShared;
output BackendDAE.BackendDAE outDAE;
protected
BackendDAE.EqSystem syst;
list<BackendDAE.EqSystem> contSysts, clockedSysts;
BackendDAE.Shared shared = inShared;
list<BackendDAE.EqSystem> systs;
list<DAE.ComponentRef> holdComps;
list<BackendDAE.Equation> unpartRemEqs;
algorithm
syst := substitutePartitionOpExps(inSyst, inShared);
(contSysts, clockedSysts, unpartRemEqs) := baseClockPartitioning(syst, shared);
(contSysts, holdComps) := removeHoldExpsSyst(contSysts);
(clockedSysts, shared) := subClockPartitioning1(clockedSysts, shared, holdComps);
unpartRemEqs := createBoolClockWhenClauses(shared, unpartRemEqs);
shared.removedEqs := BackendEquation.addList(unpartRemEqs, shared.removedEqs);
systs := listAppend(contSysts, clockedSysts);
outDAE := BackendDAE.DAE(systs, shared);
if Flags.isSet(Flags.DUMP_SYNCHRONOUS) then
print("synchronous features pre-phase: synchronousFeatures\n\n");
BackendDump.dumpEqSystems(systs, "clock partitioning");
BackendDump.dumpBasePartitions(shared.partitionsInfo.basePartitions, "Base clocks");
BackendDump.dumpSubPartitions(shared.partitionsInfo.subPartitions, "Sub clocks");
end if;
end clockPartitioning1;
protected function createBoolClockWhenClauses
input BackendDAE.Shared inShared;
input list<BackendDAE.Equation> inRemovedEqs;
output list<BackendDAE.Equation> outRemovedEqs = inRemovedEqs;
protected
BackendDAE.BasePartition basePartition;
algorithm
for i in 1:arrayLength(inShared.partitionsInfo.basePartitions) loop
basePartition := inShared.partitionsInfo.basePartitions[i];
outRemovedEqs := match basePartition.clock
local
DAE.Exp c, e;
BackendDAE.WhenEquation whenEq;
BackendDAE.Equation eq;
case DAE.BOOLEAN_CLOCK(c, _)
equation
e = DAE.CALL(Absyn.IDENT("$_clkfire"), {DAE.ICONST(i)}, DAE.callAttrBuiltinOther);
whenEq = BackendDAE.WHEN_STMTS(c, {BackendDAE.NORETCALL(e, DAE.emptyElementSource)}, NONE());
eq = BackendDAE.WHEN_EQUATION(0, whenEq, DAE.emptyElementSource, BackendDAE.EQ_ATTR_DEFAULT_DYNAMIC);
then eq::outRemovedEqs;
else outRemovedEqs;
end match;
end for;
end createBoolClockWhenClauses;
protected function treatClockedStates
"Convert continuous equations in clocked partitions to clocked equations
and call markClockedStates. author: rfranke"
input list<BackendDAE.EqSystem> inSysts;
input BackendDAE.Shared inShared;
output list<BackendDAE.EqSystem> outSysts = {};
output BackendDAE.Shared shared = inShared;
algorithm
for syst1 in inSysts loop
syst1 := match syst1
local
BackendDAE.EquationArray eqs;
Integer idx;
BackendDAE.SubPartition subPartition;
String solverMethod;
BackendDAE.EqSystem syst;
list<BackendDAE.Equation> lstEqs = {};
BackendDAE.Equation eq;
list<DAE.ComponentRef> derVars = {};
BackendDAE.Var var;
DAE.Exp exp, exp2;
DAE.Type ty;
case syst as BackendDAE.EQSYSTEM(orderedEqs = eqs)
algorithm
BackendDAE.CLOCKED_PARTITION(idx) := syst.partitionKind;
subPartition := shared.partitionsInfo.subPartitions[idx];
solverMethod := BackendDump.optionString(getSubClockSolverOpt(subPartition.clock));
// check solverMethod
if stringLength(solverMethod) > 7 and substring(solverMethod, 1, 8) == "Explicit" then
if solverMethod <> "ExplicitEuler" then
Error.addMessage(Error.CLOCK_SOLVERMETHOD, {"ExplicitEuler", solverMethod});
solverMethod := "ExplicitEuler";
end if;
elseif stringLength(solverMethod) > 0 and solverMethod <> "ImplicitEuler"
and solverMethod <> "SemiImplicitEuler" and solverMethod <> "ImplicitTrapezoid" then
Error.addMessage(Error.CLOCK_SOLVERMETHOD, {"ImplicitEuler", solverMethod});
solverMethod := "ImplicitEuler";
end if;
// replace der(x) with $DER.x and collect derVars x
for i in 1:BackendEquation.getNumberOfEquations(eqs) loop
eq := BackendEquation.get(eqs, i);
(eq, (derVars, _)) := BackendEquation.traverseExpsOfEquation(eq, getDerVars1, (derVars, BackendEquation.getForEquationIterIdent(eq)));
lstEqs := eq :: lstEqs;
end for;
// add all $DER.x as additional variables
for derVar in derVars loop
var := listGet(BackendVariable.getVar(derVar, syst.orderedVars), 1);
var := BackendDAE.VAR(ComponentReference.crefPrefixDer(derVar), BackendDAE.VARIABLE(), DAE.BIDIR(), DAE.NON_PARALLEL(), var.varType, NONE(), NONE(), var.arryDim, DAE.emptyElementSource, NONE(), NONE(), DAE.BCONST(false), NONE(), DAE.NON_CONNECTOR(), DAE.NOT_INNER_OUTER(), false);
syst.orderedVars := BackendVariable.addVar(var, syst.orderedVars);
end for;
// add defining equations for $DER.x, depending on solverMethod
for derVar in derVars loop
var := listGet(BackendVariable.getVar(derVar, syst.orderedVars), 1);
ty := var.varType;
// add forIter subscript and use element type if var is array
derVar := match var.varType
case DAE.T_ARRAY(ty = ty)
then ComponentReference.crefSetLastSubs(derVar, {DAE.INDEX(DAE.CREF(DAE.CREF_IDENT("i", DAE.T_INTEGER_DEFAULT, {}), DAE.T_INTEGER_DEFAULT))});
else derVar;
end match;
exp := DAE.CALL(Absyn.IDENT(name = "der"), {DAE.CREF(derVar, ty)}, DAE.callAttrBuiltinImpureReal);
exp := substituteFiniteDifference(exp);
exp2 := DAE.CREF(ComponentReference.crefPrefixDer(derVar), ty);
if solverMethod == "ExplicitEuler" then
// introduce states to delay derivatives; see MLS 3.3, section 16.8.2 Solver Methods
exp2 := DAE.CALL(Absyn.IDENT(name = "previous"), {exp2}, DAE.callAttrBuiltinImpureReal);
elseif solverMethod == "ImplicitTrapezoid" then
// evaluate derivatives at beginning and end of interval; see MLS 3.3, section 16.8.2 Solver Methods
exp2 := DAE.BINARY(exp2, DAE.ADD(DAE.T_REAL_DEFAULT),
DAE.CALL(Absyn.IDENT(name = "previous"), {exp2}, DAE.callAttrBuiltinImpureReal));
exp2 := DAE.BINARY(DAE.RCONST(0.5), DAE.MUL(DAE.T_REAL_DEFAULT), exp2);
end if;
// clocked continuous states are fixed at first tick
exp2 := DAE.IFEXP(DAE.CALL(Absyn.IDENT(name = "firstTick"), {}, DAE.callAttrBuiltinImpureBool),
DAE.RCONST(0), exp2);
// create for-equation or regular equation
eq := match var.varType
local
DAE.Dimension dim;
case DAE.T_ARRAY(dims = {dim})
then BackendDAE.FOR_EQUATION(
DAE.CREF(DAE.CREF_IDENT("i", DAE.T_INTEGER_DEFAULT, {}), DAE.T_INTEGER_DEFAULT),
DAE.ICONST(1), DAEUtil.dimExp(dim),
exp, exp2, var.source, BackendDAE.EQ_ATTR_DEFAULT_DYNAMIC);
else BackendDAE.EQUATION(exp, exp2, var.source, BackendDAE.EQ_ATTR_DEFAULT_DYNAMIC);
end match;
lstEqs := eq :: lstEqs;
end for;
syst.orderedEqs := BackendEquation.listEquation(listReverse(lstEqs));
if solverMethod == "SemiImplicitEuler" then
// access previous values of clocked continuous states
for i in 1:BackendEquation.getNumberOfEquations(eqs) loop
eq := BackendEquation.get(eqs, i);
(eq, _) := BackendEquation.traverseExpsOfEquation(eq, shiftDerVars1, derVars);
eqs := BackendEquation.setAtIndex(eqs, i, eq);
end for;
end if;
shared := markClockedStates(syst, shared, derVars);
then syst;
end match;
outSysts := BackendDAEUtil.clearEqSyst(syst1) :: outSysts;
end for;
outSysts := listReverse(outSysts);
end treatClockedStates;
protected function getDerVars1 "helper to getDerVars"
input DAE.Exp inExp;
input tuple<list<DAE.ComponentRef>, Option<DAE.Ident>> inDerVars;
output DAE.Exp outExp;
output tuple<list<DAE.ComponentRef>, Option<DAE.Ident>> outDerVars;
algorithm
(outExp, outDerVars) := Expression.traverseExpBottomUp(inExp, getDerVars, inDerVars);
end getDerVars1;
protected function getDerVars
"Get all crefs that appear in a der() operator and replace der(x) with $DER.x.
author: rfranke"
input DAE.Exp inExp;
input tuple<list<DAE.ComponentRef>, Option<DAE.Ident>> inDerVars;
output DAE.Exp outExp;
output tuple<list<DAE.ComponentRef>, Option<DAE.Ident>> outDerVars = inDerVars;
algorithm
outExp := match inExp
local
list<DAE.ComponentRef> derVars;
Option<DAE.Ident> optForIter;
DAE.Ident forIter;
DAE.ComponentRef x;
DAE.Type ty;
DAE.Exp der_x;
case DAE.CALL(path = Absyn.IDENT(name = "der"),
expLst = {DAE.CREF(componentRef = x, ty = ty)})
algorithm
// build $DER.x
der_x := DAE.CREF(ComponentReference.crefPrefixDer(x), ty);
// strip optional forIter and append x to derVars
(derVars, optForIter) := inDerVars;
_ := match optForIter
case SOME(forIter)
algorithm
x := ComponentReference.crefStripIterSub(x, forIter);
then ();
else ();
end match;
if not ComponentReference.crefInLst(x, derVars) then
derVars := x :: derVars;
end if;
outDerVars := (derVars, optForIter);
then der_x;
else inExp;
end match;
end getDerVars;
protected function shiftDerVars1 "helper to shiftDerVars"
input DAE.Exp inExp;
input list<DAE.ComponentRef> inDerVars;
output DAE.Exp outExp;
output list<DAE.ComponentRef> outDerVars;
algorithm
(outExp, outDerVars) := Expression.traverseExpBottomUp(inExp, shiftDerVars, inDerVars);
end shiftDerVars1;
protected function shiftDerVars
"Apply previous() operator to all inDerVars.
author: rfranke"
input DAE.Exp inExp;
input list<DAE.ComponentRef> inDerVars;
output DAE.Exp outExp;
output list<DAE.ComponentRef> outDerVars = inDerVars;
algorithm
outExp := match inExp
local
List<DAE.Exp> expLst;
DAE.CallAttributes attr;
DAE.ComponentRef x;
DAE.Type ty;
DAE.Exp exp;
// introduce previous()
case DAE.CREF(componentRef = x)
guard ComponentReference.crefInLst(x, inDerVars)
algorithm
exp := DAE.CALL(Absyn.IDENT(name = "previous"), {inExp}, DAE.callAttrBuiltinImpureReal);
then exp;
// check for possibly introduced der(previous())
case DAE.CALL(path = Absyn.IDENT(name = "der"),
expLst = {DAE.CALL(path = Absyn.IDENT(name = "previous"), expLst = expLst)},
attr = attr as DAE.CALL_ATTR())
algorithm
exp := DAE.CALL(Absyn.IDENT(name = "der"), expLst, attr);
then exp;
// check for possibly introduced previous(previous())
case DAE.CALL(path = Absyn.IDENT(name = "previous"),
expLst = {DAE.CALL(path = Absyn.IDENT(name = "previous"), expLst = expLst)},
attr = attr as DAE.CALL_ATTR())
algorithm
exp := DAE.CALL(Absyn.IDENT(name = "previous"), expLst, attr);
then exp;
// do nothing per default
else inExp;
end match;
end shiftDerVars;
protected function substituteFiniteDifference1 "helper to substituteFiniteDifference"
input DAE.Exp inExp;
input list<DAE.ComponentRef> inDerVars;
output DAE.Exp outExp;
output list<DAE.ComponentRef> outDerVars;
algorithm
(outExp, outDerVars) := Expression.traverseExpBottomUp(inExp, substituteFiniteDifference, inDerVars);
end substituteFiniteDifference1;
protected function substituteFiniteDifference
"Convert continous-time to clocked expression by replacing
der(x) -> (x - previous(x)) / interval().
author: rfranke"
input DAE.Exp inExp;
input list<DAE.ComponentRef> inDerVars = {};
output DAE.Exp outExp;
output list<DAE.ComponentRef> outDerVars;
algorithm
(outExp, outDerVars) := match inExp
local
List<DAE.Exp> expLst;
DAE.CallAttributes attr;
DAE.ComponentRef x;
DAE.Type ty;
DAE.Exp exp;
case DAE.CALL(path = Absyn.IDENT(name = "der"),
expLst = expLst as {DAE.CREF(componentRef = x)},
attr = attr as DAE.CALL_ATTR(ty = ty))
algorithm
exp := DAE.CALL(Absyn.IDENT(name = "previous"), expLst, attr);
exp := DAE.BINARY(DAE.CREF(x, ty), DAE.SUB(DAE.T_REAL_DEFAULT), exp);
exp := DAE.BINARY(exp, DAE.DIV(DAE.T_REAL_DEFAULT),
DAE.CALL(Absyn.IDENT(name = "interval"), {},
DAE.callAttrBuiltinImpureReal));
then (exp, x :: inDerVars);
else (inExp, inDerVars);
end match;
end substituteFiniteDifference;
protected function markClockedStates
"Collect discrete states and mark them for further processing.
Use VarKind CLOCKED_STATE. Moreover set the isStartFixed flag,
the fixed attribute and list the crefs of all discrete states in
outShared.partitionsInfo.subPartitions[subPartIdx].prevVars."
input BackendDAE.EqSystem inSyst;
input BackendDAE.Shared inShared;
input list<DAE.ComponentRef> derVars;
output BackendDAE.Shared outShared = inShared;
protected
BackendDAE.Equation eq;
list<DAE.ComponentRef> prevVars = {};
array<Boolean> isPrevVarArr, isDerVarArr;
list<Integer> varIxs;
BackendDAE.Var var;
Integer idx;
BackendDAE.SubPartition subPartition;
algorithm
BackendDAE.CLOCKED_PARTITION(idx) := inSyst.partitionKind;
subPartition := outShared.partitionsInfo.subPartitions[idx];
isPrevVarArr := arrayCreate(BackendVariable.varsSize(inSyst.orderedVars), false);
isDerVarArr := arrayCreate(BackendVariable.varsSize(inSyst.orderedVars), false);
for cr in derVars loop
varIxs := getVarIxs(cr, inSyst.orderedVars);
for idx in varIxs loop
arrayUpdate(isDerVarArr, idx, true);
end for;
end for;
for i in 1:BackendEquation.getNumberOfEquations(inSyst.orderedEqs) loop
eq := BackendEquation.get(inSyst.orderedEqs, i);
(_, (prevVars, _)) := BackendEquation.traverseExpsOfEquation(eq, collectPrevVars, (prevVars, BackendEquation.getForEquationIterIdent(eq)));
end for;
for i in 1:BackendEquation.getNumberOfEquations(inSyst.removedEqs) loop
eq := BackendEquation.get(inSyst.removedEqs, i);
(_, (prevVars, _)) := BackendEquation.traverseExpsOfEquation(eq, collectPrevVars, (prevVars, BackendEquation.getForEquationIterIdent(eq)));
end for;
for cr in prevVars loop
varIxs := getVarIxs(cr, inSyst.orderedVars);
for idx in varIxs loop
arrayUpdate(isPrevVarArr, idx, true);
end for;
end for;
prevVars := {};
for i in 1:arrayLength(isPrevVarArr) loop
if isPrevVarArr[i] then
var := BackendVariable.getVarAt(inSyst.orderedVars, i);
var := BackendVariable.setVarKind(var, BackendDAE.CLOCKED_STATE(
previousName = ComponentReference.crefPrefixPrevious(var.varName),
isStartFixed = isDerVarArr[i]));
var := BackendVariable.setVarFixed(var, true);
BackendVariable.setVarAt(inSyst.orderedVars, i, var);
prevVars := var.varName::prevVars;
end if;
end for;
subPartition.prevVars := prevVars;
arrayUpdate(outShared.partitionsInfo.subPartitions, idx, subPartition);
end markClockedStates;
protected function collectPrevVars
input DAE.Exp inExp;
input tuple<list<DAE.ComponentRef>, Option<DAE.Ident>> inPrevVars;
output DAE.Exp outExp;
output tuple<list<DAE.ComponentRef>, Option<DAE.Ident>> outPrevVars;
algorithm
(outExp, outPrevVars) := Expression.traverseExpBottomUp(inExp, collectPrevVars1, inPrevVars);
end collectPrevVars;
protected function collectPrevVars1
"Append cref found in previous(cref) to outPrevVars.
Optionally strip for iterator to get array variable (no NF_SCALARIZE)."
input DAE.Exp inExp;
input tuple<list<DAE.ComponentRef>, Option<DAE.Ident>> inPrevVars;
output DAE.Exp outExp = inExp;
output tuple<list<DAE.ComponentRef>, Option<DAE.Ident>> outPrevVars;
algorithm
outPrevVars := match inExp
local
list<DAE.ComponentRef> inPrevCompRefs;
Option<DAE.Ident> inForIter;
DAE.Ident forIter;
DAE.ComponentRef cr;
case DAE.CALL(path=Absyn.IDENT("previous"), expLst={DAE.CREF(cr, _)})
algorithm
(inPrevCompRefs, inForIter) := inPrevVars;
_ := match inForIter
case SOME(forIter)
algorithm
cr := ComponentReference.crefStripIterSub(cr, forIter);
then ();
else ();
end match;
then (cr :: inPrevCompRefs, inForIter);
else inPrevVars;
end match;
end collectPrevVars1;
protected function subClockPartitioning1
"Do subclock partitioning and inferencing and create clocked partitions and base clocks array."
input list<BackendDAE.EqSystem> inSysts;
input BackendDAE.Shared inShared;
input list<DAE.ComponentRef> inHoldComps;
output list<BackendDAE.EqSystem> outSysts = {};
output BackendDAE.Shared outShared = inShared;
protected
DAE.ClockKind baseClock;
HashTable.HashTable varsPartition;
Integer i, j, n, nBaseClocks;
DAE.ComponentRef cr;
array<Boolean> hasHoldOperator;
list<BackendDAE.EqSystem> systs;
list<BackendDAE.SubClock> lstSubClocks1, lstSubClocks = {};
BackendDAE.PartitionsInfo partitionsInfo;
array<BackendDAE.BasePartition> basePartitions;
array<BackendDAE.SubPartition> subPartitions;
algorithm
nBaseClocks := listLength(inSysts);
basePartitions := arrayCreate(nBaseClocks, BackendDAE.BASE_PARTITION(DAE.INFERRED_CLOCK(), 0));
varsPartition := HashTable.emptyHashTable();
i := 0; j := 1;
for syst in inSysts loop
(systs, baseClock, lstSubClocks1) := subClockPartitioning(syst, outShared, i);
n := listLength(systs);
arrayUpdate(basePartitions, j, BackendDAE.BASE_PARTITION(baseClock, n));
outSysts := listAppend(outSysts, systs);
lstSubClocks := listAppend(lstSubClocks, lstSubClocks1);
i := i + n;
j := j + 1;
end for;
hasHoldOperator := arrayCreate(listLength(lstSubClocks), false);
//Create hash cr -> subpartition index
i := 1;
for syst in outSysts loop
for j in 1:BackendVariable.varsSize(syst.orderedVars) loop
BackendDAE.VAR(varName=cr) := BackendVariable.getVarAt(syst.orderedVars, j);
varsPartition := BaseHashTable.add((cr, i), varsPartition);
end for;
i := i + 1;
end for;
//Detect subpartitions whose variables are used in hold operator
for cr in inHoldComps loop
i := BaseHashTable.get(cr, varsPartition);
arrayUpdate(hasHoldOperator, i, true);
end for;
i := 1;
subPartitions := arrayCreate( listLength(lstSubClocks),
BackendDAE.SUB_PARTITION(BackendDAE.DEFAULT_SUBCLOCK, false, {}) );
for subclock in lstSubClocks loop
arrayUpdate(subPartitions, i, BackendDAE.SUB_PARTITION(subclock, hasHoldOperator[i], {}));
i := i + 1;
end for;
partitionsInfo := outShared.partitionsInfo;
partitionsInfo.basePartitions := basePartitions;
partitionsInfo.subPartitions := subPartitions;
outShared.partitionsInfo := partitionsInfo;
end subClockPartitioning1;
protected function removeHoldExpsSyst
"Collect clocked variable, which used in continuous partition.
Replace expression hold(expr_i) -> $getPart(expr_i)."
input list<BackendDAE.EqSystem> inSysts;
output list<BackendDAE.EqSystem> outSysts = {};
output list<DAE.ComponentRef> outHoldComps = {};
algorithm
for syst1 in inSysts loop
syst1 := match syst1
local
BackendDAE.EquationArray eqs;
BackendDAE.Variables vars;
BackendDAE.EqSystem syst;
list<BackendDAE.Equation> lstEqs;
Integer i;
BackendDAE.Equation eq;
case syst as BackendDAE.EQSYSTEM(orderedEqs = eqs)
algorithm
lstEqs := {};
for i in 1:BackendEquation.getNumberOfEquations(eqs) loop
eq := BackendEquation.get(eqs, i);
(eq, outHoldComps) := BackendEquation.traverseExpsOfEquation(eq, removeHoldExp1, outHoldComps);
lstEqs := eq::lstEqs;
end for;
syst.orderedEqs := BackendEquation.listEquation(listReverse(lstEqs));
then syst;
end match;
outSysts := BackendDAEUtil.clearEqSyst(syst1) :: outSysts;
end for;
end removeHoldExpsSyst;
protected function removeHoldExp1
input DAE.Exp inExp;
input list<DAE.ComponentRef> inComps;
output DAE.Exp outExp;
output list<DAE.ComponentRef> outComps;
algorithm
(outExp, outComps) := Expression.traverseExpBottomUp(inExp, removeHoldExp, inComps);
end removeHoldExp1;
protected function removeHoldExp
input DAE.Exp inExp;
input list<DAE.ComponentRef> inComps;
output DAE.Exp outExp;
output list<DAE.ComponentRef> outComps;
algorithm
(outExp, outComps) := match inExp
local
DAE.Exp e;
DAE.ComponentRef cr;
case DAE.CALL(Absyn.IDENT("hold"), {e}, _)
equation DAE.CREF(cr, _) = e;
then (substGetPartition(e), cr::inComps);
else (inExp, inComps);
end match;
end removeHoldExp;
protected function getSubPartitionAdjacency
"gets the adjacency matrix for the sub clock partitions and a dependency graph which is used to determine the execution order.
The edge weights are the sub-clocks resulting from the sub clock interfaces.
The sub clock interfaces are both original and inverted to get from one partition to another.
The dependency graph is based on the causality of the sub partition interface functions.
author: vwaurich 2017-06"
input Integer numPartitions;
input Integer baseClockEq;
input list<Integer> subPartitionInterfaceEqs;
input array<Integer> eqPartMap;
input array<Integer> varPartMap;
input array<Boolean> clockedVarsMask;
input BackendDAE.EquationArray eqs;
input BackendDAE.Variables vars;
output array<list<tuple<Integer,BackendDAE.SubClock>>> partAdjacency;//idx: partition, entries: connections to other partitions with subclocks
output array<Integer> order;
protected
Boolean infered;
Integer part, part1, part2, var1, var2;
list<Integer> partLst,orderLst;
BackendDAE.SubClock subClk1,subClk2;
array<Boolean> partIsAssigned;
list<tuple<Integer,BackendDAE.SubClock>> adjParts;
array<Integer> partitionParents;
array<Boolean> partitionParentsVisited;
algorithm
//build adjacency matrix for subclock partitions and dependency (parent) graph
partAdjacency := arrayCreate(numPartitions,{});
partitionParents := arrayCreate(numPartitions,-1);
for subPartEq in subPartitionInterfaceEqs loop
//part1,subClk1 is the output of the sub partition interface function calls, this is used for ordering
(infered,part1,var1,subClk1,part2,var2,subClk2) := getConnectedSubPartitions(BackendEquation.get(eqs,subPartEq),varPartMap,vars);
//for adjacency relations, check only concrete sub partition interfaces not infered ones
if not intEq(part1,0) and not intEq(part2,0) then
addPartAdjacencyEdge(part1,subClk1,part2,subClk2,partAdjacency);
end if;
//to get the parent relations, check only sub partition interfaces which don't interface clock-variables
if clockedVarsMask[var1] and clockedVarsMask[var2] then
partitionParents[part1]:= part2;
end if;
end for;
/*
for i in 1:numPartitions loop
for j in arrayGet(partAdjacency,i) loop
print("partition "+intString(i)+" is connected to partition "+intString(Util.tuple21(j))+" with subCLock "+BackendDump.subClockString(Util.tuple22(j))+"\n");
end for;
end for;
for i in 1:numPartitions loop
print("partition "+intString(i)+" has parent "+intString(partitionParents[i])+"\n");
end for;
*/
//get the order
partLst := List.intRange(numPartitions);
partitionParentsVisited := arrayCreate(numPartitions,false);
orderLst := {};
while not listEmpty(partLst) loop
part::partLst := partLst;
if not partitionParentsVisited[part] then
//partition without parent, not yet visited
if intEq(partitionParents[part],-1) then
orderLst := part::orderLst;
partitionParentsVisited[part] := true;
//partition with parents, parent not yet visited
elseif intNe(partitionParents[part],-1) and intNe(partitionParents[part],part)and not partitionParentsVisited[partitionParents[part]] then
partLst := part::partLst;
partLst := partitionParents[part]::partLst;
//partition with parents, parent visited
elseif intNe(partitionParents[part],-1) and partitionParentsVisited[partitionParents[part]] then
orderLst := part::orderLst;
partitionParentsVisited[part] := true;
end if;
end if;
end while;
order := listArray(listReverse(orderLst));
end getSubPartitionAdjacency;
protected function getSubClockForClkConstructor
"gets the corresponding subclock between 2 clock constructors
author: vwaurich 2017-06"
input DAE.ClockKind refClock;
input DAE.ClockKind clk;
output BackendDAE.SubClock subClk;
algorithm
subClk := match(refClock,clk)
local
Integer i1,i2,i3,i4;
Real r1,r2;
case(DAE.INTEGER_CLOCK(DAE.ICONST(i1),DAE.ICONST(i2)), DAE.INFERRED_CLOCK())
algorithm
then BackendDAE.SUBCLOCK(MMath.RATIONAL(i2,i1), MMath.RAT0,NONE());
case(DAE.INTEGER_CLOCK(DAE.ICONST(i1),DAE.ICONST(i2)), DAE.INTEGER_CLOCK(DAE.ICONST(i3),DAE.ICONST(i4)))
algorithm
then BackendDAE.SUBCLOCK(MMath.divRational(MMath.RATIONAL(i2,i1),MMath.RATIONAL(i4,i3)),MMath.RAT0,NONE());
case(DAE.REAL_CLOCK(DAE.RCONST(r1)), DAE.INFERRED_CLOCK())
algorithm
then BackendDAE.SUBCLOCK(MMath.RATIONAL(1, realInt(1.0/r1)), MMath.RAT0, NONE());
case(DAE.REAL_CLOCK(DAE.RCONST(r1)), DAE.REAL_CLOCK(DAE.RCONST(r2)))
algorithm
then BackendDAE.SUBCLOCK(MMath.divRational(MMath.RATIONAL(1, realInt(1.0/r1)),MMath.RATIONAL(1,realInt(1.0/r2))), MMath.RAT0, NONE());
else
algorithm
//Please add the missing cases.
Error.addMessage(Error.INTERNAL_ERROR, {"SynchrnonousFeatures.getSubClockForClkConstructor failed.\n"});
then fail();
end match;
end getSubClockForClkConstructor;
protected function setSolverSubClock
"if the base clock is a solver clock, put the solver in the subclock and clean the base clock from the solver clock
author: vwaurich 2017-06"
input DAE.ClockKind baseClkIn;
input BackendDAE.SubClock inSubClock;
output DAE.ClockKind baseClkOut;
output BackendDAE.SubClock outSubClock;
algorithm
(baseClkOut, outSubClock) := match(baseClkIn, inSubClock)
local
String solver;
DAE.ClockKind clk;
case(DAE.SOLVER_CLOCK(c = DAE.CLKCONST(clk=clk), solverMethod=DAE.SCONST(solver)), _)
algorithm
outSubClock := setSubClockSolver(inSubClock, SOME(solver));
then (clk, outSubClock);
else
then (baseClkIn, inSubClock);
end match;
end setSolverSubClock;
protected function findSubClocks
"gets the sub clocks for each partition by coloring the partition adjacency starting by the real and bool clocks.
author: vwaurich 2017-06"
input Integer numPartitions;
input Integer baseClockEq;
input DAE.ClockKind baseClk;
input list<Integer> baseClockConstructors;
input list<Integer> subPartitionInterfaceEqs;
input array<Integer> eqPartMap;
input array<Integer> varPartMap;
input BackendDAE.EquationArray eqs;
input array<list<tuple<Integer,BackendDAE.SubClock>>> partAdjacency;//idx: partition, entries: connections to other partitions with subclocks
output DAE.ClockKind baseClkOut;
output array<BackendDAE.SubClock> outSubClocks;
protected
Integer part1,part2,ord;
list<Integer> partLst;
BackendDAE.SubClock subClk1,subClk2;
DAE.ClockKind clk;
array<Boolean> partIsAssigned;
list<tuple<Integer,BackendDAE.SubClock>> adjParts;
algorithm
outSubClocks := arrayCreate(numPartitions,BackendDAE.DEFAULT_SUBCLOCK);
partIsAssigned := arrayCreate(numPartitions, false); //mark which partition is assigned
//if there are multiple clock constructors in the sub partition, refer them to the base clock, ignore infered clocks
for clockEq in baseClockConstructors loop
if not intEq(baseClockEq, clockEq) and not intEq(baseClockEq,-1) then
part1 := arrayGet(eqPartMap,clockEq);
clk := getBaseClock(BackendEquation.get(eqs,clockEq));
if not isInferedBaseClock(clk) then
subClk1 := getSubClockForClkConstructor(baseClk, clk);
arrayUpdate(outSubClocks, part1, subClk1);
arrayUpdate(partIsAssigned, part1, true);
end if;
end if;
end for;
//assign subclock partitions
if isInferedBaseClock(baseClk) then
baseClkOut := baseClk;
partLst := List.intRange(numPartitions); //traverse all partitions, start with base clock partition
else
part1 := arrayGet(eqPartMap,baseClockEq);
partLst := part1::List.intRange(numPartitions); //traverse all partitions, start with base clock partition
//if the baseClk is a solver clock, set the corresponding subClock solver
(baseClkOut, subClk1) := setSolverSubClock(baseClk, outSubClocks[part1]);
arrayUpdate(outSubClocks, part1, subClk1); //set the solver clock
arrayUpdate(partIsAssigned, part1, true);
end if;
while not listEmpty(partLst) loop
part1::partLst := partLst;
adjParts := arrayGet(partAdjacency, part1);
//check adjacent partitions
for adjPart in adjParts loop
part2 := Util.tuple21(adjPart);
if not arrayGet(partIsAssigned, part2) then
subClk1 := arrayGet(outSubClocks, part1);
subClk2 := Util.tuple22(adjPart);
subClk2 := computeAbsoluteSubClock(subClk1,subClk2);
if not isInferedSubClock(subClk2) then
arrayUpdate(outSubClocks, part2, subClk2);
arrayUpdate(partIsAssigned, part2, true);
partLst := part2::partLst;
end if;
end if;
end for;
end while;
end findSubClocks;
protected function computeAbsoluteSubClock
"merges 2 subsequent sub clocks.
author: vwaurich 2017-06"
input BackendDAE.SubClock preClock;//the known subpartition clock
input BackendDAE.SubClock subSeqClock; //the sub partitin clock which shall be determined
output BackendDAE.SubClock subClk = BackendDAE.DEFAULT_SUBCLOCK;
algorithm
subClk := match(preClock, subSeqClock)
local
MMath.Rational f1,f2;
MMath.Rational s1,s2;
Option<String> solver1,solver2;
case(BackendDAE.SUBCLOCK(f1,s1,solver1),BackendDAE.SUBCLOCK(f2,s2,solver2))
algorithm
solver1 := mergeSolver(solver1,solver2);
then BackendDAE.SUBCLOCK(MMath.divRational(f1, f2), MMath.addRational(MMath.multRational(s1, f2), s2), solver1);
case(BackendDAE.SUBCLOCK(_,_,_),BackendDAE.INFERED_SUBCLOCK())
then subSeqClock;
else
algorithm
Error.addMessage(Error.INTERNAL_ERROR, {"SynchrnonousFeatures.computeAbsoluteSubClock failed\n"});
then fail();
end match;
end computeAbsoluteSubClock;
protected function mergeSolver
"merges the solver methods of 2 sub clocks.
author: vwaurich 2017-06"
input Option<String> solver1;
input Option<String> solver2;
output Option<String> sOut;
algorithm
sOut := match(solver1,solver2)
local
String s1,s2;
case(NONE(),SOME(s2))
then SOME(s2);
case(SOME(s1),NONE())
then SOME(s1);
case(SOME(s1),SOME(s2))
algorithm
if not stringEq(s1,s2) then Error.addCompilerNotification("Infered sub clock partitions have different solvers:"+s1+" <->"+s2+".\n"); end if;
then SOME(s1);
else
then NONE();
end match;
end mergeSolver;
protected function addPartAdjacencyEdge
"add an edge between 2 partitions in the partition adjacency matrix.
author: vwaurich 2017-06"
input Integer part1;
input BackendDAE.SubClock sub1;
input Integer part2;
input BackendDAE.SubClock sub2;
input array<list<tuple<Integer,BackendDAE.SubClock>>> partAdjacency;
protected
list<tuple<Integer,BackendDAE.SubClock>> partEdges;
algorithm
if intGt(part1,0) and intGt(part2,0) then
//from first partition to secod partition
partEdges := arrayGet(partAdjacency,part1);
for edge in partEdges loop
//there is already a connection to this partition
if intEq(Util.tuple21(edge),part2) then
//if not subClkEqual(Util.tuple22(edge),sub2) then Error.addCompilerNotification("Multiple subclock-interfaces between sub clock partitions.\n");end if;
end if;
end for;
arrayUpdate(partAdjacency,part1,(part2,sub1)::partEdges);
//from second partition to first partition
partEdges := arrayGet(partAdjacency,part2);
arrayUpdate(partAdjacency,part2,(part1,sub2)::partEdges);
end if;
end addPartAdjacencyEdge;
protected function setSubClockFactor
"sets the factor of a sub clock
author: vwaurich 2017-06"
input BackendDAE.SubClock subClk;
input MMath.Rational factor;
output BackendDAE.SubClock subClkOut;
algorithm
subClkOut := match(subClk)
local
MMath.Rational shift;
Option<String> solver;
case(BackendDAE.SUBCLOCK(_,shift,solver))
then BackendDAE.SUBCLOCK(factor,shift,solver);
else
then subClk;
end match;
end setSubClockFactor;
protected function getSubClockFactor
"gets the factor of a sub clock
author: vwaurich 2017-06"
input BackendDAE.SubClock subClk;
output MMath.Rational factor;
algorithm
factor := match(subClk)
local
MMath.Rational shift;
Option<String> solver;
case(BackendDAE.SUBCLOCK(factor,_,_))
then factor;
else
then MMath.RAT1;
end match;
end getSubClockFactor;
protected function getSubClockShift
"gets the shift value of a sub clock
author: vwaurich 2017-06"
input BackendDAE.SubClock subClk;
output MMath.Rational shift;
algorithm
shift := match(subClk)
local
MMath.Rational factor;
Option<String> solver;
case(BackendDAE.SUBCLOCK(_,shift,_))
then shift;
else
then MMath.RAT1;
end match;
end getSubClockShift;
protected function getSubClockSolverOpt
"gets the solver method option of a sub clock
author: vwaurich 2017-06"
input BackendDAE.SubClock subClk;
output Option<String> solver;
algorithm
solver := match(subClk)
local
MMath.Rational factor,shift;
case(BackendDAE.SUBCLOCK(_,_,solver))
then solver;
else
then NONE();
end match;
end getSubClockSolverOpt;
protected function setSubClockShift