/
BackendDAECreate.mo
3510 lines (3279 loc) · 146 KB
/
BackendDAECreate.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 BackendDAECreate
" file: BackendDAECreate.mo
package: BackendDAECreate
description: This file contains all functions for transforming the DAE structure to the BackendDAE.
"
public import Absyn;
public import BackendDAE;
public import DAE;
public import FCore;
protected
import BackendDAEUtil;
import BackendDump;
import BackendEquation;
import BackendVariable;
import BackendVarTransform;
import BaseHashTable;
import CheckModel;
import ComponentReference;
import Config;
import ClassInf;
import DAEDump;
import DAEUtil;
import Debug;
import ElementSource;
import Error;
import ErrorExt;
import Expression;
import ExpressionDump;
import ExpressionSimplify;
import ExpressionSolve;
import Flags;
import Global;
import HashTableExpToExp;
import HashTableExpToIndex;
import HashTable;
import HashTableCrToExpSourceTpl;
import Inline;
import List;
import ExecStat.execStat;
import SCode;
import StackOverflow;
import System;
import Types;
import Util;
import VarTransform;
import Vectorization;
import ZeroCrossings;
protected type Functiontuple = tuple<Option<DAE.FunctionTree>,list<DAE.InlineType>>;
public function lower "This function translates a DAE, which is the result from instantiating a
class, into a more precise form, called BackendDAE.BackendDAE defined in this module.
The BackendDAE.BackendDAE representation splits the DAE into equations and variables
and further divides variables into known and unknown variables and the
equations into simple and nonsimple equations.
The variables are inserted into a hash table. This gives a lookup cost of
O(1) for finding a variable. The equations are put in an expandable
array. Where adding a new equation can be done in O(1) time if space
is available.
inputs: lst: DAE.DAElist, inCache: FCore.Cache, inEnv: FCore.Graph
outputs: BackendDAE.BackendDAE"
input DAE.DAElist lst;
input FCore.Cache inCache;
input FCore.Graph inEnv;
input BackendDAE.ExtraInfo inExtraInfo;
output BackendDAE.BackendDAE outBackendDAE;
protected
list<BackendDAE.Var> varlst, globalKnownVarLst, extvarlst;
BackendDAE.Variables vars, globalKnownVars, localKnownVars, vars_1, extVars, aliasVars, extAliasVars;
list<BackendDAE.Equation> eqns, reqns, ieqns;
list<DAE.Constraint> constrs;
list<DAE.ClassAttributes> clsAttrs;
BackendDAE.EquationArray eqnarr, reqnarr, ieqnarr;
BackendDAE.ExternalObjectClasses extObjCls;
BackendDAE.SymbolicJacobians symjacs;
BackendDAE.EventInfo einfo;
list<DAE.Element> elems, aliaseqns;
DAE.FunctionTree functionTree;
list<BackendDAE.TimeEvent> timeEvents;
String neqStr, nvarStr;
Integer varSize, eqnSize, numCheckpoints;
BackendDAE.EqSystem syst;
algorithm
numCheckpoints:=ErrorExt.getNumCheckpoints();
try
StackOverflow.clearStacktraceMessages();
// reset dumped file sequence number
System.tmpTickResetIndex(0, Global.backendDAE_fileSequence);
System.tmpTickResetIndex(1, Global.backendDAE_cseIndex);
System.tmpTickResetIndex(0, Global.strongComponent_index);
functionTree := FCore.getFunctionTree(inCache);
//deactivated because of some codegen errors: functionTree := renameFunctionParameter(functionTree);
(DAE.DAE(elems), functionTree, timeEvents) := processBuiltinExpressions(lst, functionTree);
(varlst, globalKnownVarLst, extvarlst, eqns, reqns, ieqns, constrs, clsAttrs, extObjCls, aliaseqns, _) :=
lower2(listReverse(elems), functionTree, HashTableExpToExp.emptyHashTable());
vars := BackendVariable.listVar(varlst);
globalKnownVars := BackendVariable.listVar(globalKnownVarLst);
localKnownVars := BackendVariable.emptyVars();
extVars := BackendVariable.listVar(extvarlst);
aliasVars := BackendVariable.emptyVars();
if Flags.isSet(Flags.VECTORIZE) then
(varlst,eqns) := Vectorization.collectForLoops(varlst,eqns);
vars := BackendVariable.listVar(varlst);
end if;
// handle alias equations
(vars, globalKnownVars, extVars, aliasVars, eqns, reqns, ieqns) := handleAliasEquations(aliaseqns, vars, globalKnownVars, extVars, aliasVars, eqns, reqns, ieqns);
(ieqns, eqns, extAliasVars, extVars) := getExternalObjectAlias(ieqns, eqns, extVars);
aliasVars := BackendVariable.addVariables(extAliasVars,aliasVars);
vars_1 := detectImplicitDiscrete(vars, globalKnownVars, eqns);
eqnarr := BackendEquation.listEquation(eqns);
reqnarr := BackendEquation.listEquation(reqns);
ieqnarr := BackendEquation.listEquation(ieqns);
einfo := BackendDAE.EVENT_INFO(timeEvents, ZeroCrossings.new(), DoubleEndedList.fromList({}), ZeroCrossings.new(), 0);
symjacs := {(NONE(), ({}, {}, ({}, {}), -1), {}), (NONE(), ({}, {}, ({}, {}), -1), {}), (NONE(), ({}, {}, ({}, {}), -1), {}), (NONE(), ({}, {}, ({}, {}), -1), {})};
syst := BackendDAEUtil.createEqSystem(vars_1, eqnarr, {}, BackendDAE.UNKNOWN_PARTITION(), reqnarr);
outBackendDAE := BackendDAE.DAE(syst::{},
BackendDAE.SHARED(globalKnownVars,
localKnownVars,
extVars,
aliasVars,
ieqnarr,
BackendEquation.emptyEqns(),
constrs,
clsAttrs,
inCache,
inEnv,
functionTree,
einfo,
extObjCls,
BackendDAE.SIMULATION(),
symjacs,inExtraInfo,
BackendDAEUtil.emptyPartitionsInfo(),
BackendDAE.emptyDAEModeData
));
BackendDAEUtil.checkBackendDAEWithErrorMsg(outBackendDAE);
BackendDAEUtil.checkIncidenceMatrixSolvability(syst, functionTree);
if Flags.isSet(Flags.DUMP_BACKENDDAE_INFO) then
Error.addSourceMessage(Error.BACKENDDAEINFO_LOWER,{String(BackendEquation.equationArraySize(syst.orderedEqs)), String(BackendVariable.varsSize(syst.orderedVars))},Absyn.dummyInfo);
end if;
execStat("Generate backend data structure");
return;
else
setGlobalRoot(Global.stackoverFlowIndex, NONE());
ErrorExt.rollbackNumCheckpoints(ErrorExt.getNumCheckpoints()-numCheckpoints);
Error.addInternalError("Stack overflow in "+getInstanceName()+"...\n"+stringDelimitList(StackOverflow.readableStacktraceMessages(), "\n"), sourceInfo());
/* Do not fail or we can loop too much */
StackOverflow.clearStacktraceMessages();
end try annotation(__OpenModelica_stackOverflowCheckpoint=true);
fail();
end lower;
protected function getExternalObjectAlias "Checks equations if there is an alias equation for external objects.
If yes, assign alias var, replace equations, remove alias equation.
author: waurich TUD 2016-10"
input list<BackendDAE.Equation> inInitEqs;
input list<BackendDAE.Equation> inEqs;
input BackendDAE.Variables extVars;
output list<BackendDAE.Equation> oInitEqs;
output list<BackendDAE.Equation> oEqs;
output BackendDAE.Variables extAliasVars;
output BackendDAE.Variables extVarsOut;
protected
list<DAE.ComponentRef> extCrefs;
list<BackendDAE.Equation> aliasEqs;
list<BackendDAE.Var> aliasVarLst;
BackendVarTransform.VariableReplacements repl;
algorithm
//get the crefs of the external vars
extCrefs := BackendVariable.getAllCrefFromVariables(extVars);
// get alias equations for external objects
(oEqs,aliasEqs) := List.fold1(inEqs,getExternalObjectAlias2,extCrefs,({},{}));
(oInitEqs,aliasEqs) := List.fold1(inInitEqs,getExternalObjectAlias2,extCrefs,({},aliasEqs));
if (not listEmpty(aliasEqs)) then
Error.addCompilerWarning("Alias equations of external objects are not Modelica compliant as in:\n "+stringDelimitList(List.map(aliasEqs,BackendDump.equationString),"\n ")+"\n");
end if;
//assign aliasVariables and set new binding
repl := BackendVarTransform.emptyReplacements();
(aliasVarLst,repl) := List.fold1(aliasEqs,getExternalObjectAlias3,extVars,({},repl));
extAliasVars := BackendVariable.listVar1(aliasVarLst);
//remove alias from extVarArray
extVarsOut := BackendVariable.deleteVars(extAliasVars,extVars);
//replace in equations
(oEqs,_) := BackendVarTransform.replaceEquations(oEqs,repl,NONE());
(oInitEqs,_) := BackendVarTransform.replaceEquations(oInitEqs,repl,NONE());
oEqs := listReverse(oEqs);
oInitEqs := listReverse(oInitEqs);
end getExternalObjectAlias;
protected function getExternalObjectAlias3 "Gets the alias var and sim var for the given alias equation and adds a replacement rule
author: waurich TUD 2016-10"
input BackendDAE.Equation eqIn;
input BackendDAE.Variables extVars;
input tuple<list<BackendDAE.Var>,BackendVarTransform.VariableReplacements> tplIn;
output tuple<list<BackendDAE.Var>,BackendVarTransform.VariableReplacements> tplOut;
protected
BackendDAE.Equation eq;
BackendDAE.Var v1,v2,simVar,aliasVar;
list<DAE.ComponentRef> crefs;
list<BackendDAE.Var> extAliasVars;
BackendVarTransform.VariableReplacements repl;
algorithm
(extAliasVars,repl) := tplIn;
({eq},_) := BackendVarTransform.replaceEquations({eqIn},repl,NONE());
try
//get alias and sim var
crefs := BackendEquation.equationCrefs(eq);
({v1,v2},_) := BackendVariable.getVarLst(crefs,extVars);
(simVar,aliasVar) := chooseExternalAlias(v1,v2);
extAliasVars := aliasVar::extAliasVars;
//build replacement rule
repl := BackendVarTransform.addReplacement(repl,BackendVariable.varCref(aliasVar), Expression.crefExp(BackendVariable.varCref(simVar)), NONE());
tplOut := (extAliasVars,repl);
else
Error.addMessage(Error.INTERNAL_ERROR,{"BackendDAECreate.getExternalObjectAlias3 failed for " + BackendDump.equationString(eqIn)});
end try;
end getExternalObjectAlias3;
protected function chooseExternalAlias "Chooses a alias variable depending on which variable has a binding
author: waurich TUD 2016-10"
input BackendDAE.Var var1;
input BackendDAE.Var var2;
output BackendDAE.Var simVar;
output BackendDAE.Var aliasVar;
algorithm
if BackendVariable.varHasBindExp(var1) and not BackendVariable.varHasBindExp(var2)then
simVar := var1;
aliasVar := BackendVariable.setBindExp(var2, SOME(Expression.crefExp(BackendVariable.varCref(simVar))));
elseif BackendVariable.varHasBindExp(var2) and not BackendVariable.varHasBindExp(var1)then
simVar := var2;
aliasVar := BackendVariable.setBindExp(var1, SOME(Expression.crefExp(BackendVariable.varCref(simVar))));
elseif BackendVariable.varHasBindExp(var2) and BackendVariable.varHasBindExp(var1) then
if Expression.isCall(BackendVariable.varBindExp(var1)) then
simVar := var1;
aliasVar := BackendVariable.setBindExp(var2, SOME(Expression.crefExp(BackendVariable.varCref(simVar))));
else
simVar := var2;
aliasVar := BackendVariable.setBindExp(var1, SOME(Expression.crefExp(BackendVariable.varCref(simVar))));
end if;
else
simVar := var1;
aliasVar := BackendVariable.setBindExp(var2, SOME(Expression.crefExp(BackendVariable.varCref(simVar))));
end if;
end chooseExternalAlias;
protected function getExternalObjectAlias2 "Traverser for equations to check if an external alias assignment an be made
author: waurich TUD 2016-10"
input BackendDAE.Equation eqIn;
input list<DAE.ComponentRef> extCrefs;
input tuple<list<BackendDAE.Equation>, list<BackendDAE.Equation>> eqTplIn; //nonAlias and aliasEqs
output tuple<list<BackendDAE.Equation>, list<BackendDAE.Equation>> eqTplOut;
algorithm
eqTplOut := matchcontinue(eqIn,extCrefs,eqTplIn)
local
list<BackendDAE.Equation> noAliasEqs, aliasEqs;
DAE.ComponentRef cr1,cr2;
case(BackendDAE.COMPLEX_EQUATION(left = DAE.CREF(componentRef=cr1), right = DAE.CREF(componentRef=cr2)),_,(noAliasEqs,aliasEqs))
algorithm
true := List.exist1(extCrefs,ComponentReference.crefEqual,cr1) and List.exist1(extCrefs,ComponentReference.crefEqual,cr2);
then (noAliasEqs,eqIn::aliasEqs);
case(BackendDAE.EQUATION(exp = DAE.CREF(componentRef= cr1, ty = DAE.T_COMPLEX(complexClassType = ClassInf.EXTERNAL_OBJ())),
scalar = DAE.CREF(componentRef= cr2, ty = DAE.T_COMPLEX(complexClassType = ClassInf.EXTERNAL_OBJ()))),_,(noAliasEqs,aliasEqs))
algorithm
true := List.exist1(extCrefs,ComponentReference.crefEqual,cr1) and List.exist1(extCrefs,ComponentReference.crefEqual,cr2);
then (noAliasEqs,eqIn::aliasEqs);
else
algorithm
(noAliasEqs,aliasEqs) := eqTplIn;
then (eqIn::noAliasEqs,aliasEqs);
end matchcontinue;
end getExternalObjectAlias2;
protected function lower2
input list<DAE.Element> inElements;
input DAE.FunctionTree inFunctions;
input HashTableExpToExp.HashTable inInlineHT "Workaround to speed up inlining of array parameters.";
input list<BackendDAE.Var> inVars = {};
input list<BackendDAE.Var> inGlobalKnownVars = {};
input list<BackendDAE.Var> inExVars = {};
input list<BackendDAE.Equation> inEqns = {};
input list<BackendDAE.Equation> inREqns = {};
input list<BackendDAE.Equation> inIEqns = {};
input list<DAE.Constraint> inConstraints = {};
input list<DAE.ClassAttributes> inClassAttributes = {};
input list<BackendDAE.ExternalObjectClass> inExtObjClasses = {};
input list<DAE.Element> inAliasEqns = {};
output list<BackendDAE.Var> outVars = inVars "Time dependent variables.";
output list<BackendDAE.Var> outGlobalKnownVars = inGlobalKnownVars "Time independent variables.";
output list<BackendDAE.Var> outExVars = inExVars "External variables.";
output list<BackendDAE.Equation> outEqns = inEqns "Dynamic equations/algorithms.";
output list<BackendDAE.Equation> outREqns = inREqns "Algebraic equations.";
output list<BackendDAE.Equation> outIEqns = inIEqns "Initial equations.";
output list<DAE.Constraint> outConstraints = inConstraints;
output list<DAE.ClassAttributes> outClassAttributes = inClassAttributes;
output list<BackendDAE.ExternalObjectClass> outExtObjClasses = inExtObjClasses;
output list<DAE.Element> outAliasEqns = inAliasEqns "List with all EqualityEquations.";
output HashTableExpToExp.HashTable outInlineHT = inInlineHT;
protected
Absyn.Path path;
DAE.ElementSource src;
list<DAE.Element> dae_elts;
DAE.ClassAttributes class_attrs;
DAE.Constraint constraints;
DAE.Element el;
BackendDAE.EquationAttributes eq_attrs;
Integer whenClkCnt = 1;
DAE.Exp e;
list<BackendDAE.Equation> eqns, reqns;
algorithm
for el in inElements loop
_ := match(el)
// class for external object
case DAE.EXTOBJECTCLASS(path, src)
algorithm
outExtObjClasses := BackendDAE.EXTOBJCLASS(path, src) :: outExtObjClasses;
then
();
// variables
case DAE.VAR()
algorithm
(outVars, outGlobalKnownVars, outExVars, outEqns, outREqns, outInlineHT) :=
lowerVar(el, inFunctions, outVars, outGlobalKnownVars, outExVars, outEqns, outREqns, outInlineHT);
then
();
// scalar equations
case DAE.EQUATION()
algorithm
(outEqns, outREqns, outIEqns) := lowerEqn(el, inFunctions, outEqns, outREqns, outIEqns, false);
then
();
// initial equations
case DAE.INITIALEQUATION()
algorithm
(outEqns, outREqns, outIEqns) := lowerEqn(el, inFunctions, outEqns, outREqns, outIEqns, true);
then
();
// effort variable equality equations, separated to generate alias // variables
case DAE.EQUEQUATION()
algorithm
(outEqns, outREqns, outIEqns) := lowerEqn(el, inFunctions, outEqns, outREqns, outIEqns, false);
then
();
// a solved equation
case DAE.DEFINE()
algorithm
(outEqns, outREqns, outIEqns) := lowerEqn(el, inFunctions, outEqns, outREqns, outIEqns, false);
then
();
// a initial solved equation
case DAE.INITIALDEFINE()
algorithm
(outEqns, outREqns, outIEqns) := lowerEqn(el, inFunctions, outEqns, outREqns, outIEqns, true);
then
();
// complex equations
case DAE.COMPLEX_EQUATION()
algorithm
(outEqns, outREqns, outIEqns) := lowerEqn(el, inFunctions, outEqns, outREqns, outIEqns, false);
then
();
// complex initial equations
case DAE.INITIAL_COMPLEX_EQUATION()
algorithm
(outEqns, outREqns, outIEqns) := lowerEqn(el, inFunctions, outEqns, outREqns, outIEqns, true);
then
();
// array equations
case DAE.ARRAY_EQUATION()
algorithm
(outEqns, outREqns, outIEqns) := lowerEqn(el, inFunctions, outEqns, outREqns, outIEqns, false);
then
();
// initial array equations
case DAE.INITIAL_ARRAY_EQUATION()
algorithm
(outEqns, outREqns, outIEqns) := lowerEqn(el, inFunctions, outEqns, outREqns, outIEqns, true);
then
();
// when equations
case DAE.WHEN_EQUATION(condition = e, equations = dae_elts)
algorithm
if intGe(Flags.getConfigEnum(Flags.LANGUAGE_STANDARD), 33) and Types.isClockOrSubTypeClock(Expression.typeof(e)) then
(outEqns, outVars, eq_attrs) := createWhenClock(whenClkCnt, e, outEqns, outVars);
whenClkCnt := whenClkCnt + 1;
( outVars, outGlobalKnownVars, outExVars, eqns, reqns, outIEqns, outConstraints, outClassAttributes,
outExtObjClasses, outAliasEqns, outInlineHT ) :=
lower2( dae_elts, inFunctions, outInlineHT, outVars, outGlobalKnownVars, outExVars, {}, {}, outIEqns,
outConstraints, outClassAttributes, outExtObjClasses, outAliasEqns );
outEqns := listAppend(List.map1(eqns, BackendEquation.setEquationAttributes, eq_attrs), outEqns);
outREqns := listAppend(List.map1(reqns, BackendEquation.setEquationAttributes, eq_attrs), outREqns);
else
(eqns, reqns) := lowerWhenEqn(el, inFunctions, {}, {});
outEqns := listAppend(outEqns, eqns);
outREqns := listAppend(outREqns, reqns);
end if;
then
();
// if equation
case DAE.IF_EQUATION()
algorithm
(outEqns, outREqns, outIEqns) := lowerEqn(el, inFunctions, outEqns, outREqns, outIEqns, false);
then
();
// initial if equation
case DAE.INITIAL_IF_EQUATION()
algorithm
(outEqns, outREqns, outIEqns) := lowerEqn(el, inFunctions, outEqns, outREqns, outIEqns, true);
then
();
// algorithm
case DAE.ALGORITHM()
algorithm
(outEqns, outREqns, outIEqns) :=
lowerAlgorithm(el, inFunctions, outEqns, outREqns, outIEqns, DAE.EXPAND(), false);
then
();
// initial algorithm
case DAE.INITIALALGORITHM()
algorithm
(outEqns, outREqns, outIEqns) :=
lowerAlgorithm(el, inFunctions, outEqns, outREqns, outIEqns, DAE.EXPAND(), true);
then
();
// flat class / COMP
case DAE.COMP(dAElist = dae_elts)
algorithm
(outVars, outGlobalKnownVars, outExVars, outEqns, outREqns, outIEqns, outConstraints,
outClassAttributes, outExtObjClasses, outAliasEqns, outInlineHT)
:= lower2(listReverse(dae_elts), inFunctions, outInlineHT, outVars,
outGlobalKnownVars, outExVars, outEqns, outREqns, outIEqns, outConstraints,
outClassAttributes, outExtObjClasses, outAliasEqns);
then
();
// assert in equation section is converted to ALGORITHM
case DAE.ASSERT()
algorithm
(outEqns, outREqns, outIEqns) :=
lowerAlgorithm(el, inFunctions, outEqns, outREqns, outIEqns, DAE.NOT_EXPAND(), false);
then
();
case DAE.INITIAL_ASSERT()
algorithm
(outEqns, outREqns, outIEqns) :=
lowerAlgorithm(el, inFunctions, outEqns, outREqns, outIEqns, DAE.NOT_EXPAND(), true);
then
();
// terminate in equation section is converted to ALGORITHM
case DAE.TERMINATE()
algorithm
(outEqns, outREqns, outIEqns) :=
lowerAlgorithm(el, inFunctions, outEqns, outREqns, outIEqns, DAE.NOT_EXPAND(), false);
then
();
case DAE.INITIAL_TERMINATE()
algorithm
(outEqns, outREqns, outIEqns) := lowerAlgorithm(el, inFunctions, outEqns, outREqns, outIEqns, DAE.NOT_EXPAND(), true);
then
();
case DAE.NORETCALL()
algorithm
(outEqns, outREqns, outIEqns) :=
lowerAlgorithm(el, inFunctions, outEqns, outREqns, outIEqns, DAE.NOT_EXPAND(), false);
then
();
// assert in equation section is converted to ALGORITHM
case DAE.INITIAL_NORETCALL()
algorithm
(outEqns, outREqns, outIEqns) :=
lowerAlgorithm(el, inFunctions, outEqns, outREqns, outIEqns, DAE.NOT_EXPAND(), true);
then
();
// constraint (Optimica). Just pass the constraints for now. Should
// anything more be done here?
case DAE.CONSTRAINT(constraints = constraints)
algorithm
outConstraints := constraints :: outConstraints;
then
();
case DAE.CLASS_ATTRIBUTES(classAttrs = class_attrs)
algorithm
outClassAttributes := class_attrs :: outClassAttributes;
then
();
else
algorithm
true := Flags.isSet(Flags.FAILTRACE);
Debug.traceln("- BackendDAECreate.lower2 failed on: " + DAEDump.dumpElementsStr({el}));
then
fail();
end match;
end for;
end lower2;
// =============================================================================
// section for processing builtin expressions
//
// Insert a unique index (starting with 1) before the first arguments of some
// builtin calls. Equal calls will get the same index.
// - delay(expr, delayTime, delayMax)
// => delay(index, expr, delayTime, delayMax)
// - sample(start, interval)
// => sample(index, start, interval)
// =============================================================================
protected function processBuiltinExpressions "author: lochel
Assign some builtin calls with a unique id argument."
input DAE.DAElist inDAE;
input DAE.FunctionTree functionTree;
output DAE.DAElist outDAE;
output DAE.FunctionTree outTree;
output list<BackendDAE.TimeEvent> outTimeEvents;
protected
HashTableExpToIndex.HashTable ht;
algorithm
ht := HashTableExpToIndex.emptyHashTable();
(outDAE, outTree, (_, (_, _, _, outTimeEvents))) := DAEUtil.traverseDAE(inDAE, functionTree, Expression.traverseSubexpressionsHelper, (transformBuiltinExpression, (ht, 0, 0, {})));
end processBuiltinExpressions;
protected function transformBuiltinExpression "author: lochel
Helper for transformBuiltinExpressions"
input DAE.Exp inExp;
input tuple<HashTableExpToIndex.HashTable, Integer /*iDelay*/, Integer /*iSample*/, list<BackendDAE.TimeEvent>> inTuple;
output DAE.Exp outExp;
output tuple<HashTableExpToIndex.HashTable, Integer /*iDelay*/, Integer /*iSample*/, list<BackendDAE.TimeEvent>> outTuple;
algorithm
(outExp,outTuple) := matchcontinue (inExp, inTuple)
local
DAE.Exp start, interval;
list<DAE.Exp> es;
HashTableExpToIndex.HashTable ht;
Integer iDelay, iSample, i;
list<BackendDAE.TimeEvent> timeEvents;
DAE.CallAttributes attr;
// delay [already in ht]
case (DAE.CALL(Absyn.IDENT("delay"), es, attr), (ht, _, _, _)) equation
i = BaseHashTable.get(inExp, ht);
then (DAE.CALL(Absyn.IDENT("delay"), DAE.ICONST(i)::es, attr), inTuple);
// delay [not yet in ht]
case (DAE.CALL(Absyn.IDENT("delay"), es, attr), (ht, iDelay, iSample, timeEvents)) equation
ht = BaseHashTable.add((inExp, iDelay+1), ht);
then (DAE.CALL(Absyn.IDENT("delay"), DAE.ICONST(iDelay)::es, attr), (ht, iDelay+1, iSample, timeEvents));
// sample [already in ht]
case (DAE.CALL(Absyn.IDENT("sample"), es as {_, interval}, attr), (ht, _, _, _))
guard (not Types.isClockOrSubTypeClock(Expression.typeof(interval))) equation
i = BaseHashTable.get(inExp, ht);
then (DAE.CALL(Absyn.IDENT("sample"), DAE.ICONST(i)::es, attr), inTuple);
// sample [not yet in ht]
case (DAE.CALL(Absyn.IDENT("sample"), es as {start, interval}, attr), (ht, iDelay, iSample, timeEvents))
guard (not Types.isClockOrSubTypeClock(Expression.typeof(interval))) equation
iSample = iSample+1;
timeEvents = listAppend(timeEvents, {BackendDAE.SAMPLE_TIME_EVENT(iSample, start, interval)});
ht = BaseHashTable.add((inExp, iSample), ht);
then (DAE.CALL(Absyn.IDENT("sample"), DAE.ICONST(iSample)::es, attr), (ht, iDelay, iSample, timeEvents));
else (inExp,inTuple);
end matchcontinue;
end transformBuiltinExpression;
/*
* lower all variables
*/
public function lowerVars
input list<DAE.Element> inElements;
input DAE.FunctionTree functionTree;
input list<BackendDAE.Var> inVars = {} "The time depend Variables";
input list<BackendDAE.Var> inGlobalKnownVars = {} "The time independend Variables";
input list<BackendDAE.Var> inExVars = {} "The external Variables";
input list<BackendDAE.Equation> inEqns = {} "The dynamic Equations/Algoritms";
input list<BackendDAE.Equation> inREqns = {};
output list<BackendDAE.Var> outVars = inVars;
output list<BackendDAE.Var> outGlobalKnownVars = inGlobalKnownVars;
output list<BackendDAE.Var> outExVars = inExVars;
output list<BackendDAE.Equation> outEqns = inEqns;
output list<BackendDAE.Equation> outREqns = inREqns;
protected
DAE.ComponentRef cr;
DAE.Type arr_ty;
list<DAE.ComponentRef> crefs;
list<DAE.Element> new_vars;
HashTableExpToExp.HashTable inline_ht = HashTableExpToExp.emptyHashTable();
algorithm
for el in inElements loop
try
DAE.VAR(componentRef = cr, ty = DAE.T_ARRAY(ty = arr_ty)) := el;
crefs := ComponentReference.expandCref(cr, false);
el := DAEUtil.replaceTypeInVar(arr_ty, el);
new_vars := list(DAEUtil.replaceCrefInVar(c, el) for c in crefs);
(outVars, outGlobalKnownVars, outExVars, outEqns, outREqns) :=
lowerVars(new_vars, functionTree, outVars, outGlobalKnownVars, outExVars, outEqns, outREqns);
else
(outVars, outGlobalKnownVars, outExVars, outEqns, outREqns) := lowerVar(el, functionTree,
outVars, outGlobalKnownVars, outExVars, outEqns, outREqns, inline_ht);
end try;
end for;
end lowerVars;
protected function lowerVar
input DAE.Element inElement;
input DAE.FunctionTree inFunctions;
input list<BackendDAE.Var> inVars;
input list<BackendDAE.Var> inGlobalKnownVars;
input list<BackendDAE.Var> inExVars;
input list<BackendDAE.Equation> inEqns;
input list<BackendDAE.Equation> inREqns;
input HashTableExpToExp.HashTable inInlineHT;
output list<BackendDAE.Var> outVars = inVars;
output list<BackendDAE.Var> outGlobalKnownVars = inGlobalKnownVars;
output list<BackendDAE.Var> outExVars = inExVars;
output list<BackendDAE.Equation> outEqns = inEqns;
output list<BackendDAE.Equation> outREqns = inREqns;
output HashTableExpToExp.HashTable outInlineHT = inInlineHT;
algorithm
_ := matchcontinue(inElement)
local
DAE.ComponentRef cr;
DAE.ElementSource src;
DAE.Exp e1, e2;
BackendDAE.EquationAttributes attr;
BackendDAE.Var var;
list<BackendDAE.Equation> assert_eqs;
// external object variables
case DAE.VAR(ty = DAE.T_COMPLEX(complexClassType = ClassInf.EXTERNAL_OBJ()))
algorithm
outExVars := lowerExtObjVar(inElement, inFunctions) :: outExVars;
then
();
// variables: states and algebraic variables with binding equation
case DAE.VAR(componentRef = cr, binding = SOME(e2), source = src) guard(isStateOrAlgvar(inElement))
algorithm
// Add the binding as an equation and remove the binding from the variable.
outVars := lowerDynamicVar(inElement, inFunctions) :: outVars;
e1 := Expression.crefExp(cr);
attr := BackendDAE.EQUATION_ATTRIBUTES(false, BackendDAE.BINDING_EQUATION());
outEqns := BackendDAE.EQUATION(e1, e2, src, attr) :: outEqns;
then
();
// variables: states and algebraic variables without binding equation
case DAE.VAR(binding = NONE()) guard(isStateOrAlgvar(inElement))
algorithm
outVars := lowerDynamicVar(inElement, inFunctions) :: outVars;
then
();
// known variables: parameters and constants
case DAE.VAR()
algorithm
(var, outInlineHT, outREqns) :=
lowerKnownVar(inElement, inFunctions, outInlineHT, outREqns);
outGlobalKnownVars := var :: outGlobalKnownVars;
then
();
else
algorithm
Error.addMessage(Error.INTERNAL_ERROR,
{"BackendDAECreate.lowerVar failed for " + DAEDump.dumpElementsStr({inElement})});
then
fail();
end matchcontinue;
end lowerVar;
protected function isStateOrAlgvar
"@author adrpo
check if this variable is a state or algebraic"
input DAE.Element e;
output Boolean out;
algorithm
out := match (e)
case (DAE.VAR(kind = DAE.VARIABLE())) then true;
case (DAE.VAR(kind = DAE.DISCRETE())) then true;
else false;
end match;
end isStateOrAlgvar;
protected function lowerDynamicVar
"Transforms a DAE variable to DAE variable.
Includes changing the ComponentRef name to a simpler form
\'a\'.\'b\'{2}\'c\'{5} becomes
\'a.b{2}.c\' (as CREF_IDENT(\"a.b.c\", {2}) )
inputs: DAE.Element
outputs: Var"
input DAE.Element inElement;
input DAE.FunctionTree functionTree;
output BackendDAE.Var outVar;
algorithm
(outVar) := match (inElement)
local
list<DAE.Dimension> dims;
DAE.ComponentRef name;
BackendDAE.VarKind kind_1;
DAE.VarKind kind;
DAE.VarDirection dir;
DAE.VarParallelism prl;
BackendDAE.Type tp;
DAE.ConnectorType ct;
DAE.ElementSource source;
Option<DAE.VariableAttributes> dae_var_attr;
Option<BackendDAE.TearingSelect> ts;
DAE.Exp hideResult;
Option<SCode.Comment> comment;
DAE.Type t;
DAE.VarVisibility protection;
Boolean b;
Absyn.InnerOuter io;
case DAE.VAR(componentRef = name,
kind = kind,
direction = dir,
parallelism = prl,
protection = protection,
ty = t,
dims = dims,
connectorType = ct,
source = source,
variableAttributesOption = dae_var_attr,
comment = comment,
innerOuter = io)
equation
(kind_1) = lowerVarkind(kind, t, name, dir, ct, dae_var_attr);
tp = lowerType(t);
b = DAEUtil.boolVarVisibility(protection);
dae_var_attr = DAEUtil.setProtectedAttr(dae_var_attr, b);
dae_var_attr = setMinMaxFromEnumeration(t, dae_var_attr);
ts = BackendDAEUtil.setTearingSelectAttribute(comment);
hideResult = BackendDAEUtil.setHideResultAttribute(comment, b, name);
then
(BackendDAE.VAR(name, kind_1, dir, prl, tp, NONE(), NONE(), dims, source, dae_var_attr, ts, hideResult, comment, ct, DAEUtil.toDAEInnerOuter(io), false));
end match;
end lowerDynamicVar;
protected function lowerKnownVar
"Helper function to lower2"
input DAE.Element inElement;
input DAE.FunctionTree functionTree;
input HashTableExpToExp.HashTable iInlineHT "workaround to speed up inlining of array parameters";
input list<BackendDAE.Equation> assrtEqIn;
output BackendDAE.Var outVar;
output HashTableExpToExp.HashTable oInlineHT "workaround to speed up inlining of array parameters";
output list<BackendDAE.Equation> assrtEqOut;
algorithm
(outVar,oInlineHT,assrtEqOut) := matchcontinue (inElement)
local
list<DAE.Dimension> dims;
DAE.ComponentRef name;
BackendDAE.VarKind kind_1;
Option<DAE.Exp> bind, bind1;
DAE.VarKind kind;
DAE.VarDirection dir;
DAE.VarParallelism prl;
BackendDAE.Type tp;
DAE.ConnectorType ct;
DAE.ElementSource source;
Option<DAE.VariableAttributes> dae_var_attr;
Option<BackendDAE.TearingSelect> ts;
DAE.Exp hideResult;
Option<SCode.Comment> comment;
DAE.Type t;
DAE.VarVisibility protection;
Boolean b;
String str;
Functiontuple fnstpl;
HashTableExpToExp.HashTable inlineHT;
list<DAE.Statement> assrtLst;
list<BackendDAE.Equation> eqLst;
Absyn.InnerOuter io;
case DAE.VAR(componentRef = name,
kind = kind,
direction = dir,
parallelism = prl,
protection = protection,
ty = t,
binding = bind,
dims = dims,
connectorType = ct,
source = source,
variableAttributesOption = dae_var_attr,
comment = comment,
innerOuter = io)
equation
kind_1 = lowerKnownVarkind(kind, name, dir, ct);
// bind = fixParameterStartBinding(bind, t, dae_var_attr, kind_1);
tp = lowerType(t);
b = DAEUtil.boolVarVisibility(protection);
dae_var_attr = DAEUtil.setProtectedAttr(dae_var_attr, b);
dae_var_attr = setMinMaxFromEnumeration(t, dae_var_attr);
// build algorithms for the inlined asserts
eqLst = buildAssertAlgorithms({},source,assrtEqIn);
// building an algorithm of the assert
ts = NONE();
hideResult = BackendDAEUtil.setHideResultAttribute(comment, b, name);
then
(BackendDAE.VAR(name, kind_1, dir, prl, tp, bind, NONE(), dims, source, dae_var_attr, ts, hideResult, comment, ct, DAEUtil.toDAEInnerOuter(io), false), iInlineHT, eqLst);
else
equation
str = "BackendDAECreate.lowerKnownVar failed for " + DAEDump.dumpElementsStr({inElement});
Error.addMessage(Error.INTERNAL_ERROR, {str});
then fail();
end matchcontinue;
end lowerKnownVar;
protected function buildAssertAlgorithms "builds BackendDAE.ALGORITHM out of the given assert statements
author:Waurich TUD 2013-10"
input list<DAE.Statement> assrtIn;
input DAE.ElementSource source;
input list<BackendDAE.Equation> eqIn;
output list<BackendDAE.Equation> eqOut = eqIn;
protected
BackendDAE.Equation eq;
algorithm
for assrt in assrtIn loop
eqOut := BackendDAE.ALGORITHM(0, DAE.ALGORITHM_STMTS({assrt}), source,
DAE.EXPAND(), BackendDAE.EQ_ATTR_DEFAULT_DYNAMIC) :: eqOut;
end for;
end buildAssertAlgorithms;
protected function inlineExpOpt
"author Frenkel TUD 2013-02"
input Option<DAE.Exp> iOptExp;
input Functiontuple fnstpl;
input DAE.ElementSource iSource;
input HashTableExpToExp.HashTable iInlineHT "workaround to speed up inlining of array parameters";
output Option<DAE.Exp> oOptExp;
output DAE.ElementSource oSource;
output HashTableExpToExp.HashTable oInlineHT "workaround to speed up inlining of array parameters";
output list<DAE.Statement> assrtLstOut;
algorithm
(oOptExp,oSource,oInlineHT,assrtLstOut) := match(iOptExp,fnstpl,iSource,iInlineHT)
local
DAE.Exp e;
DAE.ElementSource source;
HashTableExpToExp.HashTable inlineHT;
list<DAE.Statement> assrtLst;
case (NONE(),_,_,_) then (iOptExp,iSource,iInlineHT,{});
case (SOME(e),_,_,_)
equation
(e, source, inlineHT,assrtLst) = inlineExpOpt1(e, fnstpl, iSource, iInlineHT);
then (SOME(e),source,inlineHT,assrtLst);
end match;
end inlineExpOpt;
protected function inlineExpOpt1
"author Frenkel TUD 2013-02"
input DAE.Exp iExp;
input Functiontuple fnstpl;
input DAE.ElementSource iSource;
input HashTableExpToExp.HashTable iInlineHT "workaround to speed up inlining of array parameters";
output DAE.Exp oExp;
output DAE.ElementSource oSource;
output HashTableExpToExp.HashTable oInlineHT "workaround to speed up inlining of array parameters";
output list<DAE.Statement> assrtLstOut;
algorithm
(oExp,oSource,oInlineHT,assrtLstOut) := matchcontinue(iExp,fnstpl,iSource,iInlineHT)
local
DAE.Exp e,e1;
list<DAE.Exp> elst;
DAE.ElementSource source;
HashTableExpToExp.HashTable inlineHT;
Boolean inlined;
list<DAE.Statement> assrtLst,assrtLst1,assrtLst2;
case (DAE.CALL(),_,_,_)
equation
e1 = BaseHashTable.get(iExp,iInlineHT);
// print("use chache Inline\n" + ExpressionDump.printExpStr(iExp) + "\n");
source = ElementSource.addSymbolicTransformation(iSource,DAE.OP_INLINE(DAE.PARTIAL_EQUATION(iExp),DAE.PARTIAL_EQUATION(e1)));
then (e1,source,iInlineHT,{});
case (DAE.CALL(),_,_,_)
equation
// print("add chache Inline\n" + ExpressionDump.printExpStr(iExp) + "\n");
(e1, source, inlined,_) = Inline.inlineExp(iExp, fnstpl, iSource);
inlineHT = if inlined then BaseHashTable.add((iExp,e1), iInlineHT) else iInlineHT;
then (e1,source,inlineHT,{});
case (DAE.ASUB(e,elst),_,_,_)
equation
e1 = BaseHashTable.get(e,iInlineHT);
// print("use chache Inline\n" + ExpressionDump.printExpStr(iExp) + "\n");
source = ElementSource.addSymbolicTransformation(iSource,DAE.OP_INLINE(DAE.PARTIAL_EQUATION(e),DAE.PARTIAL_EQUATION(e1)));
(e, source, _,_) = Inline.inlineExp(DAE.ASUB(e1,elst), fnstpl, source);
then (e,source,iInlineHT,{});
case (DAE.ASUB(e,elst),_,_,_)
equation
// print("add chache Inline(1)\n" + ExpressionDump.printExpStr(iExp) + "\n");
(e1, _, inlined,assrtLst1) = Inline.inlineExp(e, fnstpl, iSource);
inlineHT = if inlined then BaseHashTable.add((e,e1), iInlineHT) else iInlineHT;
(e, source, _,assrtLst2) = Inline.inlineExp(DAE.ASUB(e1,elst), fnstpl, iSource);
assrtLst = listAppend(assrtLst1,assrtLst2);
then (e,source,inlineHT,assrtLst);
case (_,_,_,_)
equation
// print("no chache Inline\n" + ExpressionDump.printExpStr(iExp) + "\n");
(e, source, _,_) = Inline.inlineExp(iExp, fnstpl, iSource);
then (e,source,iInlineHT,{});
end matchcontinue;
end inlineExpOpt1;
protected function setMinMaxFromEnumeration
input DAE.Type inType;
input Option<DAE.VariableAttributes> inVarAttr;
output Option<DAE.VariableAttributes> outVarAttr;
algorithm
outVarAttr := matchcontinue (inType, inVarAttr)
local
Option<DAE.Exp> min, max;
list<String> names;
Absyn.Path path;
case (DAE.T_ENUMERATION(path=path, names = names), _)
equation
(min, max) = DAEUtil.getMinMaxValues(inVarAttr);
then
setMinMaxFromEnumeration1(min, max, inVarAttr, path, names);
else inVarAttr;
end matchcontinue;
end setMinMaxFromEnumeration;
protected function setMinMaxFromEnumeration1
input Option<DAE.Exp> inMin;
input Option<DAE.Exp> inMax;