/
BackendDAEUtil.mo
9062 lines (8287 loc) · 340 KB
/
BackendDAEUtil.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 BackendDAEUtil
" file: BackendDAEUtil.mo
package: BackendDAEUtil
description: BackendDAEUtil comprised functions for BackendDAE data types.
This module is a lowered form of a DAE including equations
and simple equations in
two separate lists. The variables are split into known variables
parameters and constants, and unknown variables,
states and algebraic variables.
The module includes the BLT sorting algorithm which sorts the
equations into blocks, and the index reduction algorithm using
dummy derivatives for solving higher index problems.
It also includes the tarjan algorithm to detect strong components
in the BLT sorting."
import Absyn;
import AvlSetInt;
import AvlSetPath;
import BackendDAE;
import BackendDAEFunc;
import DAE;
import FCore;
import Util;
protected
import Algorithm;
import Array;
import BackendDAEOptimize;
import BackendDAETransform;
import BackendDump;
import BackendEquation;
import BackendDAEEXT;
import BackendInline;
import BackendVarTransform;
import BackendVariable;
import BinaryTree;
import Causalize;
import CheckModel;
import ClassInf;
import ClockIndexes;
import CommonSubExpression;
import ComponentReference;
import Config;
import DAEDump;
import DAEUtil;
import Debug;
import Differentiate;
import DumpGraphML;
import DynamicOptimization;
import ElementSource;
import Error;
import ErrorExt;
import EvaluateFunctions;
import EvaluateParameter;
import ExecStat.execStat;
import ExpandableArray;
import Expression;
import ExpressionDump;
import ExpressionSimplify;
import ExpressionSolve;
import FindZeroCrossings;
import Flags;
import Global;
import HpcOmEqSystems;
import IndexReduction;
import Initialization;
import Inline;
import InlineArrayEquations;
import List;
import Matching;
import MetaModelica.Dangerous;
import OnRelaxation;
import RemoveSimpleEquations;
import ResolveLoops;
import SCode;
import Sorting;
import StackOverflow;
import SymbolicImplicitSolver;
import SymbolicJacobian;
import SynchronousFeatures;
import System;
import Tearing;
import Types;
import UnitCheck;
import Values;
import XMLDump;
import ZeroCrossings;
public function isInitializationDAE
input BackendDAE.Shared inShared;
output Boolean res;
algorithm
res := match(inShared)
case (BackendDAE.SHARED(backendDAEType=BackendDAE.INITIALSYSTEM())) then true;
else false;
end match;
end isInitializationDAE;
public function isSimulationDAE
input BackendDAE.Shared inShared;
output Boolean res;
algorithm
res := match(inShared)
case (BackendDAE.SHARED(backendDAEType=BackendDAE.SIMULATION())) then true;
else false;
end match;
end isSimulationDAE;
/*************************************************
* checkBackendDAE and stuff
************************************************/
public function checkBackendDAEWithErrorMsg "author: Frenkel TUD
run checkDEALow and prints all errors"
input BackendDAE.BackendDAE inBackendDAE;
protected
list<tuple<DAE.Exp, list<DAE.ComponentRef>>> expCrefs;
list<BackendDAE.Equation> wrongEqns;
algorithm
if not Flags.isSet(Flags.CHECK_BACKEND_DAE) then return; end if;
_ := matchcontinue (inBackendDAE)
local
Integer nVars, nEqns;
Boolean samesize;
BackendDAE.Variables vars;
BackendDAE.EquationArray orderedEqs;
case (BackendDAE.DAE(eqs=BackendDAE.EQSYSTEM(orderedVars=vars, orderedEqs=orderedEqs)::{})) equation
//true = Flags.isSet(Flags.CHECK_BACKEND_DAE);
//Check for correct size
nVars = BackendVariable.varsSize(vars);
nEqns = BackendEquation.equationArraySize(orderedEqs);
samesize = nVars == nEqns;
if Flags.isSet(Flags.CHECK_BACKEND_DAE) then
print("No. of Equations: " + intString(nVars) + " No. of BackendDAE.Variables: " + intString(nEqns) + " Samesize: " + boolString(samesize) + "\n");
end if;
(expCrefs, wrongEqns) = checkBackendDAE(inBackendDAE);
printcheckBackendDAEWithErrorMsg(expCrefs, wrongEqns);
then ();
else equation
Error.addMessage(Error.INTERNAL_ERROR, {"./Compiler/BackEnd/BackendDAEUtil.mo: function checkBackendDAEWithErrorMsg failed"});
then fail();
end matchcontinue;
end checkBackendDAEWithErrorMsg;
public function printcheckBackendDAEWithErrorMsg"author: Frenkel TUD
helper for checkDEALowWithErrorMsg"
input list<tuple<DAE.Exp,list<DAE.ComponentRef>>> inExpCrefs;
input list<BackendDAE.Equation> inWrongEqns;
algorithm
_ := match (inExpCrefs,inWrongEqns)
local
DAE.Exp e;
list<DAE.ComponentRef> crefs;
list<tuple<DAE.Exp,list<DAE.ComponentRef>>> res;
list<String> strcrefs;
String crefstring, expstr,scopestr;
BackendDAE.Equation eqn;
list<BackendDAE.Equation> wrongEqns;
case ({},{}) then ();
case ({},eqn::wrongEqns)
equation
printEqnSizeError(eqn);
printcheckBackendDAEWithErrorMsg({},wrongEqns);
then ();
case (((e,crefs))::res,wrongEqns)
equation
strcrefs = List.map(crefs,ComponentReference.crefStr);
crefstring = stringDelimitList(strcrefs,", ");
expstr = ExpressionDump.printExpStr(e);
scopestr = stringAppendList({crefstring," from Expression: ",expstr});
Error.addMessage(Error.LOOKUP_VARIABLE_ERROR, {scopestr,"BackendDAE object"});
printcheckBackendDAEWithErrorMsg(res,wrongEqns);
then
();
end match;
end printcheckBackendDAEWithErrorMsg;
protected function printEqnSizeError"author: Frenkel TUD 2010-12"
input BackendDAE.Equation inEqn;
algorithm
_ := matchcontinue(inEqn)
local
BackendDAE.Equation eqn;
DAE.Exp e1, e2;
DAE.ComponentRef cr;
DAE.Type t1,t2;
String eqnstr, t1str, t2str, tstr;
DAE.ElementSource source;
case (eqn as BackendDAE.EQUATION(exp=e1,scalar=e2,source=source))
equation
eqnstr = BackendDump.equationString(eqn);
t1 = Expression.typeof(e1);
t2 = Expression.typeof(e2);
t1str = Types.unparseTypeNoAttr(t1);
t2str = Types.unparseTypeNoAttr(t2);
tstr = stringAppendList({t1str," != ", t2str});
Error.addSourceMessage(Error.EQUATION_TYPE_MISMATCH_ERROR, {eqnstr,tstr}, ElementSource.getElementSourceFileInfo(source));
then ();
case (eqn as BackendDAE.SOLVED_EQUATION(componentRef=cr,exp=e1,source=source))
equation
eqnstr = BackendDump.equationString(eqn);
t1 = Expression.typeof(e1);
t2 = ComponentReference.crefLastType(cr);
t1str = Types.unparseTypeNoAttr(t1);
t2str = Types.unparseTypeNoAttr(t2);
tstr = stringAppendList({t1str," != ", t2str});
Error.addSourceMessage(Error.EQUATION_TYPE_MISMATCH_ERROR, {eqnstr,tstr}, ElementSource.getElementSourceFileInfo(source));
then ();
//
else ();
end matchcontinue;
end printEqnSizeError;
public function checkBackendDAE "author: Frenkel TUD
This function checks the BackendDAE object if
- all component refercences used in the expressions are
part of the BackendDAE object.
- all variables that are reinit are states
Returns all component references which not part of the BackendDAE object."
input BackendDAE.BackendDAE inBackendDAE;
output list<tuple<DAE.Exp,list<DAE.ComponentRef>>> outExpCrefs;
output list<BackendDAE.Equation> outWrongEqns;
algorithm
(outExpCrefs,outWrongEqns) := matchcontinue inBackendDAE
local
BackendDAE.EqSystem syst;
BackendDAE.Shared shared;
BackendDAE.Variables allvars;
list<tuple<DAE.Exp,list<DAE.ComponentRef>>> expcrefs;
list<BackendDAE.Equation> wrongEqns;
case BackendDAE.DAE(syst::{}, shared)
equation
allvars = BackendVariable.mergeVariables(syst.orderedVars, shared.globalKnownVars);
((_, expcrefs)) = traverseBackendDAEExpsVars(syst.orderedVars, checkBackendDAEExp, (allvars, {}));
((_, expcrefs)) = traverseBackendDAEExpsEqns(shared.removedEqs, checkBackendDAEExp, (allvars, expcrefs));
((_, expcrefs)) = traverseBackendDAEExpsVars(shared.globalKnownVars, checkBackendDAEExp, (allvars, expcrefs));
((_, expcrefs)) = traverseBackendDAEExpsEqns(syst.orderedEqs, checkBackendDAEExp, (allvars, expcrefs));
((_, expcrefs)) = traverseBackendDAEExpsEqns(syst.removedEqs, checkBackendDAEExp, (allvars, expcrefs));
((_, expcrefs)) = traverseBackendDAEExpsEqns(shared.initialEqs, checkBackendDAEExp, (allvars, expcrefs));
wrongEqns = BackendEquation.traverseEquationArray(syst.orderedEqs, checkEquationSize, {});
wrongEqns = BackendEquation.traverseEquationArray(shared.removedEqs, checkEquationSize, wrongEqns);
wrongEqns = BackendEquation.traverseEquationArray(syst.removedEqs, checkEquationSize, wrongEqns);
wrongEqns = BackendEquation.traverseEquationArray(shared.initialEqs, checkEquationSize, wrongEqns);
then
(expcrefs, wrongEqns);
else
equation
true = Flags.isSet(Flags.FAILTRACE);
Debug.trace("- BackendDAEUtil.checkBackendDAE failed\n");
then
fail();
end matchcontinue;
end checkBackendDAE;
protected function checkBackendDAEExp
input DAE.Exp inExp;
input tuple<BackendDAE.Variables,list<tuple<DAE.Exp,list<DAE.ComponentRef>>>> inTpl;
output DAE.Exp outExp;
output tuple<BackendDAE.Variables,list<tuple<DAE.Exp,list<DAE.ComponentRef>>>> outTpl;
algorithm
(outExp,outTpl) := matchcontinue (inExp,inTpl)
local
DAE.Exp exp;
BackendDAE.Variables vars;
list<DAE.ComponentRef> crefs;
list<tuple<DAE.Exp,list<DAE.ComponentRef>>> lstExpCrefs,lstExpCrefs1;
case (exp,(vars,lstExpCrefs))
equation
(_,(_,crefs)) = Expression.traverseExpBottomUp(exp,traversecheckBackendDAEExp,(vars,{}));
then (exp, if not listEmpty(crefs) then (vars,(exp,crefs)::lstExpCrefs) else inTpl);
else (inExp,inTpl);
end matchcontinue;
end checkBackendDAEExp;
protected function traversecheckBackendDAEExp
input DAE.Exp inExp;
input tuple<BackendDAE.Variables,list<DAE.ComponentRef>> inTuple;
output DAE.Exp outExp;
output tuple<BackendDAE.Variables,list<DAE.ComponentRef>> outTuple;
algorithm
(outExp,outTuple) := matchcontinue (inExp,inTuple)
local
DAE.Exp e,e1;
BackendDAE.Variables vars,vars1;
DAE.ComponentRef cr;
list<DAE.ComponentRef> crefs,crefs1;
list<DAE.Exp> expl;
list<DAE.Var> varLst;
list<BackendDAE.Var> backendVars;
DAE.ReductionIterators riters;
tuple<BackendDAE.Variables,list<DAE.ComponentRef>> tp;
// special case for time, it is never part of the equation system
case (e as DAE.CREF(componentRef = DAE.CREF_IDENT(ident="time")),_)
then (e, inTuple);
// Special Case for Records
case (e as DAE.CREF(componentRef = cr,ty= DAE.T_COMPLEX(varLst=varLst,complexClassType=ClassInf.RECORD(_))),_)
equation
expl = List.map1(varLst,Expression.generateCrefsExpFromExpVar,cr);
(_,tp) = Expression.traverseExpList(expl,traversecheckBackendDAEExp,inTuple);
then (e, tp);
// Special Case for Arrays
case (e as DAE.CREF(ty = DAE.T_ARRAY()),_)
equation
(e1,true) = Expression.extendArrExp(e,false);
(_,tp) = Expression.traverseExpBottomUp(e1,traversecheckBackendDAEExp,inTuple);
then (e, tp);
// case for Reductions
case (e as DAE.REDUCTION(iterators = riters),(vars,crefs))
equation
// add idents to vars
backendVars = List.map(riters,makeIterVariable);
vars = BackendVariable.addVars(backendVars,vars);
then (e, (vars,crefs));
// case for functionpointers
case (e as DAE.CREF(ty=DAE.T_FUNCTION_REFERENCE_FUNC()),_)
then (e, inTuple);
case (e as DAE.CREF(componentRef = cr),(vars,_))
equation
(_,_) = BackendVariable.getVar(cr, vars);
then (e, inTuple);
case (e as DAE.CREF(componentRef = cr),(vars,crefs))
//failed before, so no need to getVar() again
//failure((_,_) = BackendVariable.getVar(cr, vars));
then (e, (vars,cr::crefs));
else (inExp,inTuple);
end matchcontinue;
end traversecheckBackendDAEExp;
protected function makeIterVariable
input DAE.ReductionIterator iter;
output BackendDAE.Var backendVar;
protected
String name;
DAE.ComponentRef cr;
algorithm
name := Expression.reductionIterName(iter);
cr := ComponentReference.makeCrefIdent(name,DAE.T_INTEGER_DEFAULT,{});
backendVar := BackendDAE.VAR(cr, BackendDAE.VARIABLE(), DAE.BIDIR(), DAE.NON_PARALLEL(), DAE.T_INTEGER_DEFAULT, NONE(), NONE(), {}, DAE.emptyElementSource, NONE(), NONE(), DAE.BCONST(false), NONE(), DAE.NON_CONNECTOR(), DAE.NOT_INNER_OUTER(), false);
end makeIterVariable;
protected function checkEquationSize"author: Frenkel TUD 2010-12
- check if the left hand side and the rigth hand side have equal types."
input BackendDAE.Equation inEq;
input list<BackendDAE.Equation> inEqs;
output BackendDAE.Equation outEq;
output list<BackendDAE.Equation> outEqs;
algorithm
(outEq,outEqs) := matchcontinue (inEq,inEqs)
local
BackendDAE.Equation e;
list<BackendDAE.Equation> wrongEqns,wrongEqns1;
DAE.Exp e1, e2;
DAE.ComponentRef cr;
DAE.Type t1,t2;
Boolean b;
case (e as BackendDAE.EQUATION(exp=e1,scalar=e2),wrongEqns)
equation
t1 = Expression.typeof(e1);
t2 = Expression.typeof(e2);
b = Expression.equalTypes(t1,t2);
wrongEqns1 = List.consOnTrue(not b,e,wrongEqns);
then (e,wrongEqns1);
case (e as BackendDAE.SOLVED_EQUATION(componentRef=cr,exp=e1),wrongEqns)
equation
t1 = Expression.typeof(e1);
t2 = ComponentReference.crefLastType(cr);
b = Expression.equalTypes(t1,t2);
wrongEqns1 = List.consOnTrue(not b,e,wrongEqns);
then (e,wrongEqns1);
//
else (inEq,inEqs);
end matchcontinue;
end checkEquationSize;
public function checkAssertCondition "Succeds if condition of assert is not constant false"
input DAE.Exp cond;
input DAE.Exp message;
input DAE.Exp level;
input SourceInfo info;
algorithm
// Don't check assertions when checking models
if Flags.getConfigBool(Flags.CHECK_MODEL) then return; end if;
_ := matchcontinue(cond,message,level,info)
local
String messageStr;
case (_,_,_,_)
guard
not Expression.isConstFalse(cond)
then ();
case (_,_,_,_)
equation
failure(DAE.ENUM_LITERAL(index=1) = level);
then ();
case(_,_,_,_)
equation
true = Expression.isConstFalse(cond);
messageStr = ExpressionDump.printExpStr(message);
Error.addSourceMessage(Error.ASSERT_CONSTANT_FALSE_ERROR,{messageStr},info);
then fail();
end matchcontinue;
end checkAssertCondition;
// =============================================================================
// Util function at Backend using for lowering and other stuff
//
// =============================================================================
public function copyBackendDAE "author: Frenkel TUD, wbraun
Copy the dae to avoid changes in vectors."
input BackendDAE.BackendDAE inDAE;
output BackendDAE.BackendDAE outDAE;
algorithm
outDAE := mapEqSystem(inDAE, copyEqSystemAndShared);
end copyBackendDAE;
public function copyEqSystemAndShared
input BackendDAE.EqSystem inSystem;
input BackendDAE.Shared inShared;
output BackendDAE.EqSystem outSystem;
output BackendDAE.Shared outShared;
algorithm
outSystem := copyEqSystem(inSystem);
outShared := copyBackendDAEShared(inShared);
end copyEqSystemAndShared;
public function copyEqSystem
input BackendDAE.EqSystem inSystem;
output BackendDAE.EqSystem outSystem;
protected
BackendDAE.Variables vars;
BackendDAE.EquationArray eqns, removedEqs;
Option<BackendDAE.IncidenceMatrix> m, mt;
BackendDAE.Matching matching;
algorithm
vars := BackendVariable.copyVariables(inSystem.orderedVars);
eqns := BackendEquation.copyEquationArray(inSystem.orderedEqs);
removedEqs := BackendEquation.copyEquationArray(inSystem.removedEqs);
m := copyIncidenceMatrix(inSystem.m);
mt := copyIncidenceMatrix(inSystem.mT);
matching := copyMatching(inSystem.matching);
outSystem := BackendDAE.EQSYSTEM(vars, eqns, m, mt, matching, inSystem.stateSets, inSystem.partitionKind, removedEqs);
end copyEqSystem;
public function copyEqSystems
input BackendDAE.EqSystems inSystems;
output BackendDAE.EqSystems outSystems = {};
algorithm
for e in inSystems loop
outSystems := copyEqSystem(e) :: outSystems;
end for;
end copyEqSystems;
public function mergeEqSystems
input BackendDAE.EqSystem System1;
input output BackendDAE.EqSystem System2;
algorithm
System2.orderedEqs := BackendEquation.merge(System1.orderedEqs,System2.orderedEqs);
System2.orderedVars := BackendVariable.mergeVariables(System1.orderedVars,System2.orderedVars);
end mergeEqSystems;
public function copyBackendDAEShared
" author: Frenkel TUD, wbraun
Copy the shared part of an BackendDAE to avoid changes in
vectors."
input BackendDAE.Shared inShared;
output BackendDAE.Shared outShared;
algorithm
outShared:=
match (inShared)
local
BackendDAE.Shared shared;
case shared as BackendDAE.SHARED()
equation
shared.globalKnownVars = BackendVariable.copyVariables(shared.globalKnownVars);
shared.externalObjects = BackendVariable.copyVariables(shared.externalObjects);
shared.initialEqs = BackendEquation.copyEquationArray(shared.initialEqs);
shared.removedEqs = BackendEquation.copyEquationArray(shared.removedEqs);
then
shared;
end match;
end copyBackendDAEShared;
public function copyMatching
input BackendDAE.Matching inMatching;
output BackendDAE.Matching outMatching;
algorithm
outMatching := match (inMatching)
local
array<Integer> ass1, cass1, ass2, cass2;
BackendDAE.StrongComponents comps;
case (BackendDAE.NO_MATCHING()) then BackendDAE.NO_MATCHING();
case (BackendDAE.MATCHING(ass1=ass1,ass2=ass2,comps=comps))
equation
cass1 = arrayCopy(ass1);
cass2 = arrayCopy(ass2);
then BackendDAE.MATCHING(cass1,cass2,comps);
end match;
end copyMatching;
public function getCompsOfMatching "author: mwalther
Get all strong connected components of the given matching. If the matching
has the concrete type NO_MATCHING, the returned list is empty."
input BackendDAE.Matching inMatching;
output BackendDAE.StrongComponents outComps;
algorithm
outComps := match (inMatching)
local
BackendDAE.StrongComponents comps;
case (BackendDAE.MATCHING(comps=comps))
then comps;
else
then {};
end match;
end getCompsOfMatching;
public function addVarsToEqSystem
input BackendDAE.EqSystem syst;
input list<BackendDAE.Var> varlst;
output BackendDAE.EqSystem osyst;
protected
BackendDAE.Variables vars;
algorithm
BackendDAE.EQSYSTEM(orderedVars=vars) := syst;
osyst := setEqSystVars(syst, BackendVariable.addVars(varlst, vars));
end addVarsToEqSystem;
public function numberOfZeroCrossings "author: lochel"
input BackendDAE.BackendDAE inBackendDAE;
output Integer outNumZeroCrossings "number of ordinary zero crossings" ;
output Integer outNumTimeEvents "number of zero crossings that are time events" ;
output Integer outNumRelations;
output Integer outNumMathEventFunctions;
protected
BackendDAE.EventInfo eventInfo = inBackendDAE.shared.eventInfo;
algorithm
outNumZeroCrossings := ZeroCrossings.length(eventInfo.zeroCrossings);
outNumTimeEvents := listLength(eventInfo.timeEvents);
outNumRelations := DoubleEndedList.length(eventInfo.relations);
outNumMathEventFunctions := eventInfo.numberMathEvents;
end numberOfZeroCrossings;
public function numberOfDiscreteVars "author: lochel"
input BackendDAE.BackendDAE inBackendDAE;
output Integer outNumDiscreteReal;
algorithm
outNumDiscreteReal := countDiscreteVars(inBackendDAE);
end numberOfDiscreteVars;
protected function countDiscreteVars "author: lochel"
input BackendDAE.BackendDAE inDAE;
output Integer outNumDiscreteVars;
protected
BackendDAE.Variables globalKnownVars, alias;
algorithm
BackendDAE.SHARED(globalKnownVars=globalKnownVars, aliasVars=alias) := inDAE.shared;
outNumDiscreteVars := countDiscreteVars1(inDAE.eqs);
outNumDiscreteVars := BackendVariable.traverseBackendDAEVars(globalKnownVars, countDiscreteVars3, outNumDiscreteVars);
outNumDiscreteVars := BackendVariable.traverseBackendDAEVars(alias, countDiscreteVars3, outNumDiscreteVars);
end countDiscreteVars;
protected function countDiscreteVars1 "author: lochel"
input BackendDAE.EqSystems inEqSystems;
output Integer outNumDiscreteVars;
algorithm
outNumDiscreteVars := 0;
outNumDiscreteVars := List.fold(inEqSystems, countDiscreteVars2, outNumDiscreteVars);
end countDiscreteVars1;
protected function countDiscreteVars2 "author: lochel"
input BackendDAE.EqSystem inEqSystem;
input Integer inNumDiscreteVars;
output Integer outNumDiscreteVars;
protected
BackendDAE.Variables vars;
algorithm
BackendDAE.EQSYSTEM(orderedVars=vars) := inEqSystem;
outNumDiscreteVars := BackendVariable.traverseBackendDAEVars(vars, countDiscreteVars3, inNumDiscreteVars);
end countDiscreteVars2;
protected function countDiscreteVars3 "author: lochel"
input BackendDAE.Var var;
input Integer nDiscreteVars;
output BackendDAE.Var outVar;
output Integer outCount;
algorithm
(outVar,outCount) := match (var,nDiscreteVars)
// discrete
case (BackendDAE.VAR(varKind=BackendDAE.DISCRETE(), varType=DAE.T_REAL()), _)
then (var, nDiscreteVars+1);
else (var,nDiscreteVars);
end match;
end countDiscreteVars3;
public function replaceCrefsWithValues
input DAE.Exp inExp;
input tuple<BackendDAE.Variables, DAE.ComponentRef> inTuple;
output DAE.Exp outExp;
output tuple<BackendDAE.Variables, DAE.ComponentRef> outTuple;
algorithm
(outExp,outTuple) := matchcontinue (inExp,inTuple)
local
DAE.Exp e;
BackendDAE.Variables vars;
DAE.ComponentRef cr, cr_orign;
case (DAE.CREF(cr, _), (vars, cr_orign))
guard
not ComponentReference.crefEqualNoStringCompare(cr, cr_orign)
equation
({BackendDAE.VAR(bindExp = SOME(e))}, _) = BackendVariable.getVar(cr, vars);
(e, _) = Expression.traverseExpBottomUp(e, replaceCrefsWithValues, (vars, cr_orign));
then (e, (vars,cr_orign));
else (inExp,inTuple);
end matchcontinue;
end replaceCrefsWithValues;
public function makeExpType
"Transforms a BackendDAE.Type to DAE.Type"
input BackendDAE.Type inType;
output DAE.Type outType;
algorithm
outType := inType;
end makeExpType;
public function hasExpContinuousParts
"Returns true if expression has contiuous parts,
and false if the expression is completely discrete.
Used to detect if an expression is a ZeroCrossing."
input DAE.Exp inExp;
input BackendDAE.Variables inVariables;
input BackendDAE.Variables inKnvars;
output Boolean outBoolean;
algorithm
(_,(_, _, outBoolean)) := Expression.traverseExpTopDown(inExp, traversingContinuousExpFinder, (inVariables, inKnvars, false));
end hasExpContinuousParts;
protected function traversingContinuousExpFinder "Helper for isDiscreteExp"
input DAE.Exp inExp;
input tuple<BackendDAE.Variables,BackendDAE.Variables,Boolean> inTpl;
output DAE.Exp outExp;
output Boolean cont;
output tuple<BackendDAE.Variables,BackendDAE.Variables,Boolean> outTpl;
algorithm
(outExp, cont, outTpl) := matchcontinue (inExp, inTpl)
local
BackendDAE.Variables vars, globalKnownVars;
DAE.ComponentRef cr;
DAE.Exp e;
Boolean blst;
BackendDAE.Var backendVar;
Absyn.Ident name;
case (e as DAE.CREF(componentRef=cr), (vars, globalKnownVars, _)) equation
((backendVar::_), _) = BackendVariable.getVar(cr, vars);
false = BackendVariable.isVarDiscrete(backendVar);
then (e, false, (vars, globalKnownVars, true));
// builtin variable time is not discrete
case (e as DAE.CREF(componentRef=DAE.CREF_IDENT(ident="time")), (vars, globalKnownVars, _))
then (e, false, (vars, globalKnownVars, true));
// Known variables that are input are continuous
case (e as DAE.CREF(componentRef=cr), (vars, globalKnownVars, _)) equation
(backendVar::_, _) = BackendVariable.getVar(cr, globalKnownVars);
true = BackendVariable.isInput(backendVar);
then (e, false, (vars, globalKnownVars, true));
case (e as DAE.CALL(path=Absyn.IDENT(name=name)), (vars, globalKnownVars, blst))
guard stringEq("pre", name) or
stringEq("change", name) or
stringEq("ceil", name) or
stringEq("floor", name) or
stringEq("div", name) or
stringEq("mod", name) or
stringEq("rem", name)
then (e, false, (vars, globalKnownVars, blst));
case (e as DAE.CALL(path=Absyn.IDENT(name="noEvent")), (vars, globalKnownVars, _))
then (e, false, (vars, globalKnownVars, false));
case (e, (vars, globalKnownVars, blst))
then (e, true, (vars, globalKnownVars, blst));
end matchcontinue;
end traversingContinuousExpFinder;
public function statesAndVarsExp
"This function investigates an expression and returns as subexpressions
that are variable names or derivatives of state names or states
inputs: (DAE.Exp, BackendDAE.Variables)
outputs: DAE.Exp list"
input DAE.Exp inExp;
input BackendDAE.Variables inVariables;
output list<DAE.Exp> exps;
algorithm
(_,(_,exps)) := Expression.traverseExpTopDown(inExp, traversingstatesAndVarsExpFinder, (inVariables,{}));
end statesAndVarsExp;
public function traversingstatesAndVarsExpFinder "
Author: Frenkel TUD 2010-10
Helper for statesAndVarsExp"
input DAE.Exp inExp;
input tuple<BackendDAE.Variables,list<DAE.Exp>> inTpl;
output DAE.Exp outExp;
output Boolean cont;
output tuple<BackendDAE.Variables,list<DAE.Exp>> outTpl;
algorithm
(outExp,cont,outTpl) := matchcontinue (inExp,inTpl)
local
DAE.ComponentRef cr;
list<DAE.Exp> expl,res,creexps;
DAE.Exp e,e1;
list<DAE.Var> varLst;
BackendDAE.Variables vars;
// Special Case for Records
case ((e as DAE.CREF(componentRef = cr,ty= DAE.T_COMPLEX(varLst=varLst,complexClassType=ClassInf.RECORD(_)))),(vars,_))
equation
creexps = List.map1(varLst,Expression.generateCrefsExpFromExpVar,cr);
(_,(_,res)) = Expression.traverseExpListTopDown(creexps, traversingstatesAndVarsExpFinder, inTpl);
then (e,true,(vars,res));
// Special Case for unextended arrays
case ((e as DAE.CREF(ty = DAE.T_ARRAY())),(vars,_))
equation
(e1,true) = Expression.extendArrExp(e,false);
(_,(_,res)) = Expression.traverseExpTopDown(e1, traversingstatesAndVarsExpFinder, inTpl);
then (e,true,(vars,res));
// Special Case for time variable
//case (((e as DAE.CREF(componentRef = DAE.CREF_IDENT(ident="time"))),(vars,expl)))
// then ((e,false,(vars,e::expl)));
case ((e as DAE.CREF(componentRef = cr)),(vars,expl))
equation
(_,_) = BackendVariable.getVar(cr, vars);
then (e,false,(vars,e::expl));
case ((e as DAE.CALL(path = Absyn.IDENT(name = "der"),expLst = {DAE.CREF(componentRef = cr)})),(vars,expl))
equation
((BackendDAE.VAR(varKind = BackendDAE.STATE())::_),_) = BackendVariable.getVar(cr, vars);
then (e,false,(vars,e::expl));
// is this case right?
case (e as DAE.CALL(path = Absyn.IDENT(name = "der"),expLst = {DAE.CREF(componentRef = cr)}),(vars,_))
equation
(_,_) = BackendVariable.getVar(cr, vars);
then (e,false,inTpl);
else (inExp,true,inTpl);
end matchcontinue;
end traversingstatesAndVarsExpFinder;
public function isLoopDependent
"Checks if an expression is a variable that depends on a loop iterator,
ie. for i loop
V[i] = ... // V depends on i
end for;
Used by lowerStatementInputsOutputs in STMT_FOR case."
input DAE.Exp varExp;
input DAE.Exp iteratorExp;
output Boolean isDependent;
algorithm
isDependent := matchcontinue(varExp, iteratorExp)
local
list<DAE.Exp> subscript_exprs;
list<DAE.Subscript> subscripts;
DAE.ComponentRef cr;
case (DAE.CREF(componentRef = cr), _)
equation
subscripts = ComponentReference.crefSubs(cr);
subscript_exprs = List.map(subscripts, Expression.subscriptIndexExp);
true = isLoopDependentHelper(subscript_exprs, iteratorExp);
then true;
case (DAE.ASUB(sub = subscript_exprs), _)
then isLoopDependentHelper(subscript_exprs, iteratorExp);
else false;
end matchcontinue;
end isLoopDependent;
protected function isLoopDependentHelper
"Helper for isLoopDependent.
Checks if a list of subscripts contains a certain iterator expression."
input list<DAE.Exp> subscripts;
input DAE.Exp iteratorExp;
output Boolean isDependent = false;
algorithm
for subscript in subscripts loop
try
if Expression.expContains(subscript, iteratorExp) then
isDependent := true;
return;
end if;
else
// go on with iteration
end try;
end for;
end isLoopDependentHelper;
public function devectorizeArrayVar
input DAE.Exp arrayVar;
output DAE.Exp newArrayVar;
algorithm
newArrayVar := matchcontinue(arrayVar)
local
DAE.ComponentRef cr;
DAE.Type ty;
list<DAE.Exp> subs;
DAE.Exp e;
case (DAE.ASUB(exp = DAE.ARRAY(array = (DAE.CREF(componentRef = cr)::_)), sub = subs))
equation
cr = ComponentReference.crefStripLastSubs(cr);
e = Expression.crefExp(cr);
then
// adrpo: TODO! FIXME! check if this is TYPE correct!
// shouldn't we change the type using the subs?
Expression.makeASUB(e, subs);
case (DAE.ASUB(exp = DAE.MATRIX(matrix = (((DAE.CREF(componentRef = cr))::_)::_)), sub = subs))
equation
cr = ComponentReference.crefStripLastSubs(cr);
e = Expression.crefExp(cr);
then
// adrpo: TODO! FIXME! check if this is TYPE correct!
// shouldn't we change the type using the subs?
Expression.makeASUB(e, subs);
case (_) then arrayVar;
end matchcontinue;
end devectorizeArrayVar;
public function explodeArrayVars
"Explodes an array variable into its elements. Takes a variable that is a CREF
or ASUB, the name of the iterator variable and a range expression that the
iterator iterates over."
input DAE.Exp arrayVar;
input DAE.Exp iteratorExp;
input DAE.Exp rangeExpr;
input BackendDAE.Variables vars;
output list<DAE.Exp> arrayElements;
algorithm
arrayElements := matchcontinue(arrayVar, iteratorExp, rangeExpr, vars)
local
list<DAE.Exp> clonedElements, newElements;
list<DAE.Exp> indices;
DAE.ComponentRef cref;
list<DAE.ComponentRef> varCrefs;
list<DAE.Exp> varExprs;
DAE.Exp daeExp;
list<BackendDAE.Var> bvars;
case (DAE.CREF(), _, _, _)
equation
indices = rangeExprs(rangeExpr);
clonedElements = List.fill(arrayVar, listLength(indices));
newElements = generateArrayElements(clonedElements, indices, iteratorExp);
then newElements;
case (DAE.ASUB(exp = DAE.CREF()), _, _, _)
equation
// If the range is constant, then we can use it to generate only those
// array elements that are actually used.
indices = rangeExprs(rangeExpr);
clonedElements = List.fill(arrayVar, listLength(indices));
newElements = generateArrayElements(clonedElements, indices, iteratorExp);
then newElements;
case (DAE.CREF(componentRef = cref), _, _, _)
equation
(bvars, _) = BackendVariable.getVar(cref, vars);
varExprs = List.map(bvars, BackendVariable.varExp);
//varCrefs = List.map(bvars, BackendVariable.varCref);
//varExprs = List.map(varCrefs, Expression.crefExp);
then varExprs;
case (DAE.ASUB(exp = DAE.CREF(componentRef = cref)), _, _, _)
equation
// If the range is not constant, then we just extract all array elements
// of the array.
(bvars, _) = BackendVariable.getVar(cref, vars);
varExprs = List.map(bvars, BackendVariable.varExp);
//varCrefs = List.map(bvars, BackendVariable.varCref);
//varExprs = List.map(varCrefs, Expression.crefExp);
then varExprs;
case (DAE.ASUB(exp = daeExp), _, _, _)
equation
varExprs = Expression.flattenArrayExpToList(daeExp);
then
varExprs;
end matchcontinue;
end explodeArrayVars;
protected function rangeExprs
"Tries to convert a range to a list of integer expressions. Returns a list of
integer expressions if possible, or fails. Used by explodeArrayVars."
input DAE.Exp inRange;
output list<DAE.Exp> outValues;
algorithm
outValues := match inRange
local
list<DAE.Exp> arrayElements;
Integer start, stop;
list<Integer> vals;
case DAE.ARRAY(array = arrayElements) then arrayElements;
case DAE.RANGE() then Expression.expandRange(inRange);
end match;
end rangeExprs;
public function daeSize
"author: Frenkel TUD
Returns the size of the dae system, which correspondents to the number of variables."
input BackendDAE.BackendDAE inDAE;
output Integer sz;
algorithm
sz := sum(systemSize(s) for s in inDAE.eqs);
end daeSize;
public function systemSize
"Returns the size of the dae system, the size of the equations in an BackendDAE.EquationArray,
which not corresponds to the number of equations in a system."
input BackendDAE.EqSystem inEqSystem;
output Integer outSize = BackendEquation.equationArraySize(inEqSystem.orderedEqs);
end systemSize;
public function maxSizeOfEqSystems
"Returns the maximum system size of given EqSystems"
input list<BackendDAE.EqSystem> inEqSystems;
output Integer outSize = 0;
protected
Integer i;
algorithm
for eqSyst in inEqSystems loop
i := systemSize(eqSyst);
if intGt(i, outSize) then
outSize := i;
end if;
end for;
end maxSizeOfEqSystems;
public function numOfComps "Returns the number of StrongComponents in the EqSystem
author: waurich TUD"
input BackendDAE.EqSystem inEqSystem;
output Integer num;
protected
BackendDAE.StrongComponents comps;
algorithm
BackendDAE.MATCHING(comps=comps) := inEqSystem.matching;
num := listLength(comps);
end numOfComps;
public function equationArraySizeBDAE
"author: Frenkel TUD
Returns the size of the dae system, which correspondents to the number of variables."