-
Notifications
You must be signed in to change notification settings - Fork 298
/
NBEquation.mo
3823 lines (3477 loc) · 145 KB
/
NBEquation.mo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is part of OpenModelica.
*
* Copyright (c) 1998-2020, Open Source Modelica Consortium (OSMC),
* c/o Linköpings universitet, Department of Computer and Information Science,
* SE-58183 Linköping, Sweden.
*
* All rights reserved.
*
* THIS PROGRAM IS PROVIDED UNDER THE TERMS OF GPL VERSION 3 LICENSE OR
* THIS OSMC PUBLIC LICENSE (OSMC-PL) VERSION 1.2.
* ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES
* RECIPIENT'S ACCEPTANCE OF THE OSMC PUBLIC LICENSE OR THE GPL VERSION 3,
* ACCORDING TO RECIPIENTS CHOICE.
*
* The OpenModelica software and the Open Source Modelica
* Consortium (OSMC) Public License (OSMC-PL) are obtained
* from OSMC, either from the above address,
* from the URLs: http://www.ida.liu.se/projects/OpenModelica or
* http://www.openmodelica.org, and in the OpenModelica distribution.
* GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html.
*
* This program is distributed WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH
* IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS OF OSMC-PL.
*
* See the full OSMC Public License conditions for more details.
*
*/
encapsulated package NBEquation
" file: NBEquation.mo
package: NBEquation
description: This file contains all functions and structures regarding
backend equations.
"
public
// Old Frontend imports
import DAE;
import ElementSource;
// New Frontend imports
import Algorithm = NFAlgorithm;
import BackendDAE = NBackendDAE;
import BackendExtension = NFBackendExtension;
import Binding = NFBinding;
import Call = NFCall;
import Class = NFClass;
import ComponentRef = NFComponentRef;
import Dimension = NFDimension;
import Expression = NFExpression;
import NFFlatten.FunctionTree;
import InstNode = NFInstNode.InstNode;
import Operator = NFOperator;
import NFPrefixes.{Variability, Purity};
import SimplifyExp = NFSimplifyExp;
import Statement = NFStatement;
import Subscript = NFSubscript;
import Type = NFType;
import Variable = NFVariable;
// Old Backend imports
import OldBackendDAE = BackendDAE;
// New Backend imports
import Evaluation = NBEvaluation;
import Inline = NBInline;
import Replacements = NBReplacements;
import StrongComponent = NBStrongComponent;
import Solve = NBSolve;
import BVariable = NBVariable;
import NBVariable.{VariablePointer, VariablePointers};
// Util imports
import BackendUtil = NBBackendUtil;
import BaseHashTable;
import ExpandableArray;
import Slice = NBSlice;
import StringUtil;
import UnorderedMap;
import Util;
constant String SIMULATION_STR = "SIM";
constant String START_STR = "SRT";
constant String PRE_STR = "PRE";
type EquationPointer = Pointer<Equation> "mainly used for mapping purposes";
// used to process different outcomes of slicing from Util/Slice.mo
// have to be defined here and not in Util/Slice.mo because it is a uniontype and not a package
type Frame = tuple<ComponentRef, Expression> "iterator-like tuple for array handling";
type FrameLocation = tuple<array<Integer>, Frame> "sliced frame at specific sub locations";
type SlicingStatus = enumeration(UNCHANGED, TRIVIAL, NONTRIVIAL, FAILURE) "final result of slicing";
type RecollectStatus = enumeration(SUCCESS, FAILURE) "result of sub-routine recollect";
type FrameOrderingStatus = enumeration(UNCHANGED, CHANGED, FAILURE) "result of sub-routine frame ordering";
partial function MapFuncEqn
input output Equation e;
end MapFuncEqn;
partial function MapFuncEqnPtr
input output Pointer<Equation> e;
end MapFuncEqnPtr;
partial function MapFuncExp
input output Expression e;
end MapFuncExp;
partial function MapFuncExpWrapper
input output Expression e;
input MapFuncExp func;
end MapFuncExpWrapper;
partial function MapFuncCref
input output ComponentRef c;
end MapFuncCref;
uniontype Iterator
record SINGLE
ComponentRef name "the name of the iterator";
Expression range "range as <start, step, stop>";
end SINGLE;
record NESTED
array<ComponentRef> names "sorted iterator names";
array<Expression> ranges "sorted ranges as <start, step, stop>";
end NESTED;
record EMPTY
end EMPTY;
function fromFrames
input list<Frame> frames;
output Iterator iter;
protected
list<ComponentRef> names;
list<Expression> ranges;
ComponentRef name;
Expression range;
algorithm
if listEmpty(frames) then
iter := EMPTY();
else
(names, ranges) := List.unzip(frames);
iter := match (names, ranges)
case ({name}, {range}) then SINGLE(name, range);
else NESTED(listArray(names), listArray(ranges));
end match;
end if;
end fromFrames;
function getFrames
input Iterator iter;
output list<ComponentRef> names;
output list<Expression> ranges;
algorithm
(names, ranges) := match iter
case SINGLE() then ({iter.name}, {iter.range});
case NESTED() then (arrayList(iter.names), arrayList(iter.ranges));
case EMPTY() then ({}, {});
end match;
end getFrames;
function merge
"merges multiple iterators to one NESTED() iterator"
input list<Iterator> iterators;
output Iterator result;
protected
list<ComponentRef> tmp_names, names = {};
list<Expression> tmp_ranges, ranges = {};
algorithm
if listLength(iterators) == 1 then
result := List.first(iterators);
else
for iter in listReverse(iterators) loop
(tmp_names, tmp_ranges) := getFrames(iter);
names := listAppend(tmp_names, names);
ranges := listAppend(tmp_ranges, ranges);
end for;
result := NESTED(listArray(names), listArray(ranges));
end if;
end merge;
function split
"splits an operator in its SINGLE() subparts. used for converting to old structure and writing code
NOTE: returns iterators in reverse order!"
input Iterator iterator;
output list<Iterator> result = {};
protected
list<ComponentRef> names;
list<Expression> ranges;
algorithm
(names, ranges) := getFrames(iterator);
for tpl in List.zip(names, ranges) loop
result := Iterator.fromFrames({tpl}) :: result;
end for;
end split;
function rename
input output Iterator iter;
input String newBaseName;
input UnorderedMap<ComponentRef, Expression> replacements;
algorithm
iter := match iter
local
ComponentRef replacor;
case SINGLE() algorithm
replacor := ComponentRef.rename(newBaseName + intString(1), iter.name);
UnorderedMap.add(iter.name, Expression.fromCref(replacor), replacements);
iter.name := replacor;
then iter;
case NESTED() algorithm
for i in 1:arrayLength(iter.names) loop
replacor := ComponentRef.rename(newBaseName + intString(i), iter.names[i]);
UnorderedMap.add(iter.names[i], Expression.fromCref(replacor), replacements);
iter.names[i] := replacor;
end for;
then iter;
end match;
end rename;
function isEqual
"compares two iterators not considering their name!"
input Iterator iter1;
input Iterator iter2;
output Boolean b = true;
algorithm
b := match (iter1, iter2)
case (EMPTY(), EMPTY()) then true;
case (SINGLE(), SINGLE()) then Expression.isEqual(iter1.range, iter2.range);
case (NESTED(), NESTED()) algorithm
if arrayLength(iter1.ranges) == arrayLength(iter2.ranges) then
for i in 1:arrayLength(iter1.ranges) loop
b := Expression.isEqual(iter1.ranges[i], iter2.ranges[i]);
if not b then break; end if;
end for;
else
b := false;
end if;
then b;
else false;
end match;
end isEqual;
function isEmpty
input Iterator iter;
output Boolean b;
algorithm
b := match iter case EMPTY() then true; else false; end match;
end isEmpty;
function intersect
input Iterator iter1;
input Iterator iter2;
output Iterator intersection;
output tuple<Iterator, Iterator> rest1;
output tuple<Iterator, Iterator> rest2;
algorithm
(intersection, rest1, rest2) := match (iter1, iter2)
local
Integer start1, step1, stop1, start2, step2, stop2;
Integer start_min, start_max, stop_min, stop_max;
// ToDo: index shift if mod start1 != start2
case (SINGLE(range = Expression.RANGE(start=Expression.INTEGER(start1), step=SOME(Expression.INTEGER(step1)), stop=Expression.INTEGER(stop1))),
SINGLE(range = Expression.RANGE(start=Expression.INTEGER(start2), step=SOME(Expression.INTEGER(step2)), stop=Expression.INTEGER(stop2))))
guard(step1 == step2 and intMod(start1, step1) == intMod(start2, step2))
algorithm
start_min := intMin(start1, start2);
start_max := intMax(start1, start2);
stop_min := intMin(stop1, stop2);
stop_max := intMax(stop1, stop2);
// create intersection
if start_max >= stop_min then
intersection := EMPTY();
else
intersection := SINGLE(
name = iter1.name,
range = Expression.RANGE(
ty = Expression.typeOf(iter1.range),
start = Expression.INTEGER(start_max),
step = SOME(Expression.INTEGER(step1)),
stop = Expression.INTEGER(stop_min)
)
);
end if;
// create rest
rest1 := intersectRest(iter1.name, start1, step1, stop1, start_max-step1, stop_min+step1);
rest2 := intersectRest(iter2.name, start2, step2, stop2, start_max-step2, stop_min+step2);
then (intersection, rest1, rest2);
// cannot intersect
else (EMPTY(), (iter1, EMPTY()), (EMPTY(), iter2));
end match;
end intersect;
function intersectRest
input ComponentRef name;
input Integer start;
input Integer step;
input Integer stop;
input Integer start_max;
input Integer stop_min;
output tuple<Iterator, Iterator> rest;
protected
Iterator rest_left, rest_right;
algorithm
if start > start_max then
rest_left := EMPTY();
else
rest_left := Iterator.SINGLE(
name = name,
range = Expression.makeRange(
start = Expression.INTEGER(start),
step = SOME(Expression.INTEGER(step)),
stop = Expression.INTEGER(start_max)
)
);
end if;
if stop_min > stop then
rest_right := EMPTY();
else
rest_right := Iterator.SINGLE(
name = name,
range = Expression.makeRange(
start = Expression.INTEGER(stop_min),
step = SOME(Expression.INTEGER(step)),
stop = Expression.INTEGER(stop)
)
);
end if;
rest := (rest_left, rest_right);
end intersectRest;
function sizes
input Iterator iter;
output list<Integer> sizes "outermost first!";
algorithm
sizes := match iter
case SINGLE() then {Expression.rangeSize(iter.range)};
case NESTED() then list(Expression.rangeSize(iter.ranges[i]) for i in 1:arrayLength(iter.ranges));
case EMPTY() then {};
else algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " could not get sizes for: " + toString(iter) + "\n"});
then fail();
end match;
end sizes;
function size
input Iterator iter;
output Integer size = product(i for i in 1 :: sizes(iter));
end size;
function dimensions
input Iterator iter;
output list<Dimension> dims = list(Dimension.fromInteger(s) for s in sizes(iter));
end dimensions;
function createLocationReplacements
"adds replacements rules for a single frame location"
input Iterator iter "iterator to replace";
input array<Integer> location "zero based location";
input UnorderedMap<ComponentRef, Expression> replacements "replacement rules";
algorithm
() := match iter
local
Integer start, step;
case SINGLE() guard(arrayLength(location) == 1) algorithm
(start, step, _) := Expression.getIntegerRange(iter.range);
UnorderedMap.add(iter.name, Expression.INTEGER(start + location[1]*step), replacements);
then ();
case NESTED() guard(arrayLength(location) == arrayLength(iter.ranges)) algorithm
for i in 1:arrayLength(location) loop
(start, step, _) := Expression.getIntegerRange(iter.ranges[i]);
UnorderedMap.add(iter.names[i], Expression.INTEGER(start + location[i]*step), replacements);
end for;
then ();
else algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " could not create replacements for location: "
+ List.toString(arrayList(location), intString) + " and iterator: " + toString(iter) + "\n"});
then fail();
end match;
end createLocationReplacements;
function createReplacement
"adds a replacement rule for one iterator to another.
fails if they do not have the same depth or range size."
input Iterator replacor "replaces";
input Iterator replacee "gets replaced";
input UnorderedMap<ComponentRef, Expression> replacements "replacement rules";
protected
Boolean failed = false;
algorithm
failed := match (replacor, replacee)
case (SINGLE(), SINGLE()) algorithm
failed := createSingleReplacement(replacor.name, replacor.range, replacee.name, replacee.range, replacements);
then failed;
case (NESTED(), NESTED()) algorithm
if arrayLength(replacor.names) == arrayLength(replacee.names) then
for i in 1:arrayLength(replacor.names) loop
failed := createSingleReplacement(replacor.names[i], replacor.ranges[i], replacee.names[i], replacee.ranges[i], replacements);
if failed then break; end if;
end for;
else
failed := true;
end if;
then failed;
else true;
end match;
if failed then
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " could not create replacements for replacor: "
+ toString(replacor) + " and replacee: " + toString(replacee) + "\n"});
fail();
end if;
end createReplacement;
function createSingleReplacement
"helper function for createReplacement()"
input ComponentRef replacor_cref;
input Expression replacor_range;
input ComponentRef replacee_cref;
input Expression replacee_range;
input UnorderedMap<ComponentRef, Expression> replacements "replacement rules";
output Boolean failed = false;
protected
Integer or_start, or_step, or_stop, ee_start, ee_step, ee_stop;
Expression exp;
algorithm
(or_start, or_step, or_stop) := Expression.getIntegerRange(replacor_range);
(ee_start, ee_step, ee_stop) := Expression.getIntegerRange(replacee_range);
// check if same size
if (or_stop-or_start+1)/or_step == (ee_stop-ee_start+1)/ee_step then
// replacee = ee_start + (ee_step/or_step) * (replacor-or_start)
exp := Expression.MULTARY(
arguments = {Expression.REAL(intReal(ee_start)),
Expression.MULTARY(
arguments = {Expression.REAL(intReal(ee_step)/intReal(or_step)),
Expression.MULTARY(
arguments = {Expression.fromCref(replacor_cref)},
inv_arguments = {Expression.REAL(intReal(or_start))},
operator = Operator.makeAdd(Type.REAL()))},
inv_arguments = {},
operator = Operator.makeMul(Type.REAL()))},
inv_arguments = {},
operator = Operator.makeAdd(Type.REAL()));
UnorderedMap.add(replacee_cref, exp, replacements);
else
failed := true;
end if;
end createSingleReplacement;
function extract
"takes an expression and maps it to find all occuring iterators.
returns an iterator if all iterators are equal, fails otherwise.
also replaces all array constructors with indexed expressions."
output Iterator iter;
input output Expression exp;
protected
UnorderedMap<ComponentRef, Expression> replacements = UnorderedMap.new<Expression>(ComponentRef.hash, ComponentRef.isEqual);
algorithm
(exp, iter) := Expression.mapFold(exp, function extractFromCall(replacements = replacements), EMPTY());
exp := Expression.map(exp, function Replacements.applySimpleExp(replacements = replacements));
end extract;
function extractFromCall
"helper function for extract()"
input output Expression exp;
input output Iterator iter;
input UnorderedMap<ComponentRef, Expression> replacements "replacement rules";
algorithm
(exp, iter) := match exp
local
Call call;
list<Frame> frames = {};
InstNode node;
Expression range;
Iterator tmp;
case Expression.CALL(call = call as Call.TYPED_ARRAY_CONSTRUCTOR()) algorithm
for tpl in listReverse(call.iters) loop
(node, range) := tpl;
frames := (ComponentRef.fromNode(node, Type.INTEGER(), {}, NFComponentRef.Origin.ITERATOR), range) :: frames;
end for;
tmp := fromFrames(frames);
if not isEmpty(iter) then
createReplacement(iter, tmp, replacements);
else
iter := tmp;
end if;
then (call.exp, iter);
else (exp, iter);
end match;
end extractFromCall;
function normalizedSubscripts
"creates a normalized subscript list such that the traversed iterators result in
consecutive indices starting at 1."
input Iterator iter;
output list<Subscript> subs;
protected
list<ComponentRef> names;
list<Expression> ranges;
algorithm
(names, ranges) := getFrames(iter);
subs := list(normalizedSubscript(frame) for frame in List.zip(names, ranges));
end normalizedSubscripts;
function normalizedSubscript
"returns subscripts such that traversing the range results in consecutive subscript values 1,2,3....
e.g: i in 10:-2:1 -> x[(i-10)/(-2) + 1] which results in 1,2,3... for i=10,8,6..."
input tuple<ComponentRef, Expression> frame;
output Subscript sub;
protected
ComponentRef iter_name;
Expression range, step, sub_exp;
Type ty = Type.REAL();
algorithm
(iter_name, range) := frame;
sub := match range
// (iterator-start)/step + 1
case Expression.RANGE() algorithm
step := Util.getOptionOrDefault(range.step, Expression.INTEGER(1));
sub_exp := Expression.fromCref(iter_name);
// if start and step are equal to 1, make simple expression (simplify is not strong enough yet)
if not (Expression.isOne(range.start) and Expression.isOne(step)) then
sub_exp := Expression.MULTARY(
arguments = {Expression.MULTARY(
arguments = {Expression.MULTARY(
arguments = {sub_exp},
inv_arguments = {range.start},
operator = Operator.makeAdd(ty))},
inv_arguments = {step},
operator = Operator.makeMul(ty)),
Expression.INTEGER(1)},
inv_arguments = {},
operator = Operator.makeAdd(ty));
sub_exp := SimplifyExp.simplify(sub_exp, true);
sub_exp := Expression.CALL(Call.makeTypedCall(NFBuiltinFuncs.INTEGER_REAL, {sub_exp}, Variability.DISCRETE, Purity.PURE));
end if;
then Subscript.INDEX(sub_exp);
else algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName()
+ " failed because range is no range: " + Expression.toString(range)});
then fail();
end match;
end normalizedSubscript;
function toString
input Iterator iter;
output String str = "";
protected
function singleStr
input ComponentRef name;
input Expression range;
output String str = ComponentRef.toString(name) + " in " + Expression.toString(range);
end singleStr;
algorithm
str := match iter
case SINGLE() then singleStr(iter.name, iter.range);
case NESTED() then "{" + stringDelimitList(list(singleStr(iter.names[i], iter.ranges[i]) for i in 1:arrayLength(iter.names)), ", ") + "}";
case EMPTY() then "<EMPTY ITERATOR>";
else algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed for an unknown reason."});
then fail();
end match;
end toString;
function map
"Traverses all expressions of the iterator range and applies a function to it."
input output Iterator iter;
input MapFuncExp funcExp;
input Option<MapFuncCref> funcCrefOpt = NONE();
input MapFuncExpWrapper mapFunc;
protected
MapFuncCref funcCref;
algorithm
iter := match iter
case SINGLE() algorithm
if Util.isSome(funcCrefOpt) then
funcCref := Util.getOption(funcCrefOpt);
iter.name := funcCref(iter.name);
end if;
iter.range := mapFunc(iter.range, funcExp);
then iter;
case NESTED() algorithm
if Util.isSome(funcCrefOpt) then
funcCref := Util.getOption(funcCrefOpt);
for i in 1:arrayLength(iter.names) loop
iter.names[i] := funcCref(iter.names[i]);
end for;
end if;
for i in 1:arrayLength(iter.ranges) loop
iter.ranges[i] := mapFunc(iter.ranges[i], funcExp);
end for;
then iter;
else algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed for an unknown reason."});
then fail();
end match;
end map;
end Iterator;
uniontype Equation
record SCALAR_EQUATION
Type ty "equality type";
Expression lhs "left hand side expression";
Expression rhs "right hand side expression";
DAE.ElementSource source "origin of equation";
EquationAttributes attr "Additional Attributes";
end SCALAR_EQUATION;
record ARRAY_EQUATION
Type ty "equality type containing dimensions";
Expression lhs "left hand side expression";
Expression rhs "right hand side expression";
DAE.ElementSource source "origin of equation";
EquationAttributes attr "Additional Attributes";
Option<Integer> recordSize "NONE() if not a record";
end ARRAY_EQUATION;
record RECORD_EQUATION
Type ty "equality type";
Expression lhs "left hand side expression";
Expression rhs "right hand side expression";
DAE.ElementSource source "origin of equation";
EquationAttributes attr "Additional Attributes";
Integer recordSize "size of the record";
end RECORD_EQUATION;
record ALGORITHM
Integer size "output size";
Algorithm alg "Algorithm statements";
DAE.ElementSource source "origin of algorithm";
DAE.Expand expand "this algorithm was translated from an equation. we should not expand array crefs!";
EquationAttributes attr "Additional Attributes";
end ALGORITHM;
record IF_EQUATION
Integer size "size of equation";
IfEquationBody body "Actual equation body";
DAE.ElementSource source "origin of equation";
EquationAttributes attr "Additional Attributes";
end IF_EQUATION;
record FOR_EQUATION
Integer size "size of equation";
Iterator iter "list of all: <iterator, range>";
list<Equation> body "iterated equations (only multiples if entwined)";
DAE.ElementSource source "origin of equation";
EquationAttributes attr "Additional Attributes";
end FOR_EQUATION;
record WHEN_EQUATION
Integer size "size of equation";
WhenEquationBody body "Actual equation body";
DAE.ElementSource source "origin of equation";
EquationAttributes attr "Additional Attributes";
end WHEN_EQUATION;
record AUX_EQUATION
"Auxiliary equations are generated when auxiliary variables are generated
that are known to always be solved in this specific equation. E.G. $CSE
The variable binding contains the equation, but this equation is also
allowed to have a body for special cases."
Pointer<Variable> auxiliary "Corresponding auxiliary variable";
Option<Equation> body "Optional body equation"; // -> Expression
end AUX_EQUATION;
record DUMMY_EQUATION
end DUMMY_EQUATION;
function toString
input Equation eq;
input output String str = "";
protected
String s = "(" + intString(Equation.size(Pointer.create(eq))) + ")";
String tupl_recd_str;
algorithm
str := match eq
case SCALAR_EQUATION() then str + "[SCAL] " + s + " " + Expression.toString(eq.lhs) + " = " + Expression.toString(eq.rhs) + EquationAttributes.toString(eq.attr, " ");
case ARRAY_EQUATION() then str + "[ARRY] " + s + " " + Expression.toString(eq.lhs) + " = " + Expression.toString(eq.rhs) + EquationAttributes.toString(eq.attr, " ");
case RECORD_EQUATION() algorithm
tupl_recd_str := if Type.isTuple(eq.ty) then "[TUPL] " else "[RECD] ";
then str + tupl_recd_str + s + " " + Expression.toString(eq.lhs) + " = " + Expression.toString(eq.rhs) + EquationAttributes.toString(eq.attr, " ");
case ALGORITHM() then str + "[ALGO] " + s + EquationAttributes.toString(eq.attr, " ") + "\n" + Algorithm.toString(eq.alg, str + "[----] ");
case IF_EQUATION() then str + IfEquationBody.toString(eq.body, str + "[----] ", "[-IF-] " + s);
case FOR_EQUATION() then str + forEquationToString(eq.iter, eq.body, "", str + "[----] ", "[FOR-] " + s + EquationAttributes.toString(eq.attr, " "));
case WHEN_EQUATION() then str + WhenEquationBody.toString(eq.body, str + "[----] ", "[WHEN] " + s);
case AUX_EQUATION() then str + "[AUX-] " + s + "Auxiliary equation for " + Variable.toString(Pointer.access(eq.auxiliary));
case DUMMY_EQUATION() then str + "[DUMY] (0) Dummy equation.";
else str + "[FAIL] (0) " + getInstanceName() + " failed!";
end match;
end toString;
function pointerToString
input Pointer<Equation> eqn_ptr;
input output String str = "";
algorithm
str := toString(Pointer.access(eqn_ptr), str);
end pointerToString;
function source
input Equation eq;
output DAE.ElementSource src;
algorithm
src := match eq
case SCALAR_EQUATION() then eq.source;
case ARRAY_EQUATION() then eq.source;
case RECORD_EQUATION() then eq.source;
case ALGORITHM() then eq.source;
case IF_EQUATION() then eq.source;
case FOR_EQUATION() then eq.source;
case WHEN_EQUATION() then eq.source;
else algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed for:\n" + toString(eq)});
then fail();
end match;
end source;
function info
input Equation eq;
output SourceInfo info = ElementSource.getInfo(source(eq));
end info;
function size
input Pointer<Equation> eqn_ptr;
output Integer s;
protected
Equation eqn;
algorithm
eqn := Pointer.access(eqn_ptr);
s := match eqn
local
Equation body;
case SCALAR_EQUATION() then 1;
case ARRAY_EQUATION() then Type.sizeOf(eqn.ty);
case RECORD_EQUATION() then Type.sizeOf(eqn.ty);
case ALGORITHM() then eqn.size;
case IF_EQUATION() then eqn.size;
case FOR_EQUATION(body = {body}) then eqn.size;
case WHEN_EQUATION() then eqn.size;
case AUX_EQUATION() then Variable.size(Pointer.access(eqn.auxiliary));
case DUMMY_EQUATION() then 0;
else algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed for:\n" + toString(eqn)});
then fail();
end match;
end size;
function sizes
input Pointer<Equation> eqn_ptr;
output list<Integer> size_lst;
protected
Equation eqn;
algorithm
eqn := Pointer.access(eqn_ptr);
size_lst := match eqn
case SCALAR_EQUATION() then {1};
case ARRAY_EQUATION() then {Type.sizeOf(eqn.ty)}; //needs to be updated to represent the dimensions
case RECORD_EQUATION() then {Type.sizeOf(eqn.ty)};
case ALGORITHM() then {eqn.size};
case IF_EQUATION() then {eqn.size};
case FOR_EQUATION() then listReverse(Iterator.sizes(eqn.iter)); // does only consider frames and not conditions
case WHEN_EQUATION() then {eqn.size};
case AUX_EQUATION() then {Variable.size(Pointer.access(eqn.auxiliary))};
case DUMMY_EQUATION() then {};
else algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed for:\n" + toString(eqn)});
then fail();
end match;
end sizes;
function hash
"only hashes the name"
input Pointer<Equation> eqn;
output Integer i = Variable.hash(Pointer.access(getResidualVar(eqn)));
end hash;
function equalName
input Pointer<Equation> eqn1;
input Pointer<Equation> eqn2;
output Boolean b = ComponentRef.isEqual(getEqnName(eqn1), getEqnName(eqn2));
end equalName;
function isEqualPtrTpl
input tuple<EquationPointer, EquationPointer> tpl;
output Boolean b;
protected
EquationPointer eqn1, eqn2;
algorithm
(eqn1, eqn2) := tpl;
b := isEqualPtr(eqn1, eqn2);
end isEqualPtrTpl;
function isEqualPtr
input Pointer<Equation> eqn1;
input Pointer<Equation> eqn2;
output Boolean b = isEqual(Pointer.access(eqn1), Pointer.access(eqn2));
end isEqualPtr;
function isEqualTpl
input tuple<Equation, Equation> tpl;
output Boolean b;
protected
Equation eqn1, eqn2;
algorithm
(eqn1, eqn2) := tpl;
b := isEqual(eqn1, eqn2);
end isEqualTpl;
function isEqual
input Equation eqn1;
input Equation eqn2;
output Boolean b;
algorithm
b := match (eqn1, eqn2)
case (SCALAR_EQUATION(), SCALAR_EQUATION()) then Expression.isEqual(eqn1.lhs, eqn2.lhs) and Expression.isEqual(eqn1.rhs, eqn2.rhs);
case (ARRAY_EQUATION(), ARRAY_EQUATION()) then Expression.isEqual(eqn1.lhs, eqn2.lhs) and Expression.isEqual(eqn1.rhs, eqn2.rhs);
case (RECORD_EQUATION(), RECORD_EQUATION()) then Expression.isEqual(eqn1.lhs, eqn2.lhs) and Expression.isEqual(eqn1.rhs, eqn2.rhs);
// ToDo: This is wrong! implement the Algorithm.isEqual!
// case (ALGORITHM(), ALGORITHM()) then Algorithm.isEqual(eqn1.alg, eqn2.alg);
case (ALGORITHM(), ALGORITHM()) then equalName(Pointer.create(eqn1), Pointer.create(eqn2));
case (IF_EQUATION(), IF_EQUATION()) then IfEquationBody.isEqual(eqn1.body, eqn2.body);
case (FOR_EQUATION(), FOR_EQUATION()) then Iterator.isEqual(eqn1.iter, eqn2.iter) and List.all(List.zip(eqn1.body, eqn2.body), isEqualTpl);
case (WHEN_EQUATION(), WHEN_EQUATION()) then WhenEquationBody.isEqual(eqn1.body, eqn2.body);
case (AUX_EQUATION(), AUX_EQUATION()) then BVariable.equalName(eqn1.auxiliary, eqn2.auxiliary) and Util.optionEqual(eqn1.body, eqn2.body, isEqual);
case (DUMMY_EQUATION(), DUMMY_EQUATION()) then true;
else false;
end match;
end isEqual;
function getEqnName
input Pointer<Equation> eqn;
output ComponentRef name;
protected
Pointer<Variable> residualVar;
algorithm
residualVar := getResidualVar(eqn);
name := BVariable.getVarName(residualVar);
end getEqnName;
function getResidualVar
input Pointer<Equation> eqn;
output Pointer<Variable> residualVar;
algorithm
try
residualVar := EquationAttributes.getResidualVar(getAttributes(Pointer.access(eqn)));
else
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed because of missing residual variable."});
fail();
end try;
end getResidualVar;
function getSolvedVar
input Equation eqn;
output Variable var;
algorithm
var := match eqn
local
ComponentRef cref;
case SCALAR_EQUATION(lhs = Expression.CREF(cref = cref)) then BVariable.getVar(cref);
case ARRAY_EQUATION(lhs = Expression.CREF(cref = cref)) then BVariable.getVar(cref);
case RECORD_EQUATION(lhs = Expression.CREF(cref = cref)) then BVariable.getVar(cref);
else NBVariable.DUMMY_VARIABLE;
end match;
end getSolvedVar;
function makeAssignment
input Expression lhs;
input Expression rhs;
input Pointer<Integer> idx;
input String str;
input Iterator iter;
input EquationAttributes attr;
output Pointer<Equation> eq;
protected
Equation e;
Type ty = Expression.typeOf(lhs);
algorithm
// match type and create equation accordingly
e := match ty
case Type.ARRAY() then ARRAY_EQUATION(
ty = ty,
lhs = lhs,
rhs = rhs,
source = DAE.emptyElementSource,
attr = attr,
recordSize = NONE()
);
case Type.TUPLE() then RECORD_EQUATION(
ty = ty,
lhs = lhs,
rhs = rhs,
source = DAE.emptyElementSource,
attr = attr,
recordSize = Type.sizeOf(ty)
);
case Type.COMPLEX() then RECORD_EQUATION(
ty = ty,
lhs = lhs,
rhs = rhs,
source = DAE.emptyElementSource,
attr = attr,
recordSize = Type.sizeOf(ty)
);
else SCALAR_EQUATION(
ty = ty,
lhs = lhs,
rhs = rhs,
source = DAE.emptyElementSource,
attr = attr
);
end match;
// create for-loop around it if there is an iterator
if not Iterator.isEmpty(iter) then
e := FOR_EQUATION(
size = Type.sizeOf(ty) * Iterator.size(iter),
iter = iter,
body = {e},
source = DAE.emptyElementSource,
attr = attr
);
// inline if it has size 1
e := Inline.inlineForEquation(e);
end if;
eq := Pointer.create(e);
Equation.createName(eq, idx, str);
end makeAssignment;
function makeAlgorithm
input list<Statement> stmts;
input Boolean init;
output Pointer<Equation> eqn;
protected
Algorithm alg;
algorithm
alg := Algorithm.ALGORITHM(stmts, {}, {}, InstNode.EMPTY_NODE(), DAE.emptyElementSource);
alg := Algorithm.setInputsOutputs(alg);
eqn := BackendDAE.lowerAlgorithm(alg, init);
end makeAlgorithm;
function forEquationToString
input Iterator iter "the iterator variable(s)";
input list<Equation> body "iterated equations";
input output String str = "";
input String indent = "";
input String indicator = "";
protected
String iterators;
algorithm
str := str + indicator + "\n";
str := str + indent + "for " + Iterator.toString(iter) + " loop\n";
for eqn in body loop
str := str + toString(eqn, indent + " ") + "\n";
end for;
str := str + indent + "end for;";
end forEquationToString;
function getAttributes
input Equation eq;
output EquationAttributes attr;
algorithm
attr := match eq
local
Equation body;
case SCALAR_EQUATION() then eq.attr;
case ARRAY_EQUATION() then eq.attr;
case RECORD_EQUATION() then eq.attr;
case ALGORITHM() then eq.attr;
case IF_EQUATION() then eq.attr;
case FOR_EQUATION() then eq.attr;
case WHEN_EQUATION() then eq.attr;
case AUX_EQUATION(body = SOME(body)) then getAttributes(body);
else EquationAttributes.default(EquationKind.UNKNOWN, false);
end match;
end getAttributes;
function setAttributes
input output Equation eq;
input EquationAttributes attr;
algorithm
eq := match eq
local