/
DAELow.mo
13326 lines (12402 loc) · 437 KB
/
DAELow.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
package DAELow "
This file is part of OpenModelica.
Copyright (c) 1998-2006, Linköpings universitet, Department of
Computer and Information Science, PELAB
All rights reserved.
(The new BSD license, see also
http://www.opensource.org/licenses/bsd-license.php)
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
Neither the name of Linköpings universitet nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
file: DAELow.mo
module: DAELow
description: DAELow a lower form of DAE including sparse matrises for
BLT decomposition, etc.
RCS: $Id$
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.
"
public import DAE;
public import Exp;
public import Values;
public import Absyn;
public import Algorithm;
public
uniontype VarKind "- Variabile kind"
record VARIABLE end VARIABLE;
record STATE end STATE;
record DUMMY_DER end DUMMY_DER;
record DUMMY_STATE end DUMMY_STATE;
record DISCRETE end DISCRETE;
record PARAM end PARAM;
record CONST end CONST;
record EXTOBJ
Absyn.Path fullClassName;
end EXTOBJ;
end VarKind;
public
uniontype Var "- Variables"
record VAR
Exp.ComponentRef varName "varName ; variable name" ;
VarKind varKind "varKind ; Kind of variable" ;
DAE.VarDirection varDirection "varDirection ; input, output or bidirectional" ;
DAE.Type varType "varType ; builtin type or enumeration" ;
Option<Exp.Exp> bindExp "bindExp ; Binding expression e.g. for parameters" ;
Option<Values.Value> bindValue "bindValue ; binding value for parameters" ;
DAE.InstDims arryDim "arryDim ; array dimensions on nonexpanded var" ;
DAE.StartValue startValue "startValue ; value of start attribute" ;
Integer index "index ; index in impl. vector" ;
Exp.ComponentRef origVarName "origVarName ; original variable name" ;
list<Absyn.Path> className "className ; classname variable belongs to" ;
Option<DAE.VariableAttributes> values "values ; values on builtin attributes" ;
Option<Absyn.Comment> comment "comment ; this contains the comment and annotation from Absyn" ;
DAE.Flow flow_ "flow ; if the var is a flow" ;
end VAR;
end Var;
public
uniontype Equation "- Equation"
record EQUATION
Exp.Exp exp;
Exp.Exp scalar "scalar" ;
end EQUATION;
record ARRAY_EQUATION
Integer index "index ; index in arrayequations 0..n-1" ;
list<Exp.Exp> crefOrDerCref "crefOrDerCref ; CREF or der(CREF)" ;
end ARRAY_EQUATION;
record SOLVED_EQUATION
Exp.ComponentRef componentRef "componentRef" ;
Exp.Exp exp "exp" ;
end SOLVED_EQUATION;
record RESIDUAL_EQUATION
Exp.Exp exp "exp ; not present from front end" ;
end RESIDUAL_EQUATION;
record ALGORITHM
Integer index "Index in algorithms, 0..n-1" ;
list<Exp.Exp> in_ "Inputs CREF or der(CREF)" ;
list<Exp.Exp> out "Outputs CREF or der(CREF)" ;
end ALGORITHM;
record WHEN_EQUATION
WhenEquation whenEquation "whenEquation" ;
end WHEN_EQUATION;
end Equation;
public
uniontype WhenEquation "- When Equation"
record WHEN_EQ
Integer index "Index in when clauses" ;
Exp.ComponentRef left "Left hand side of equation" ;
Exp.Exp right "Right hand side of equation" ;
Option<WhenEquation> elsewhenPart "elsewhen equation with the same cref on the left hand side.";
end WHEN_EQ;
end WhenEquation;
public
uniontype ReinitStatement "- Reinit Statement"
record REINIT
Exp.ComponentRef stateVar "State variable to reinit" ;
Exp.Exp value "Value after reinit" ;
end REINIT;
record EMPTY_REINIT
end EMPTY_REINIT;
end ReinitStatement;
public
uniontype WhenClause "- When Clause"
record WHEN_CLAUSE
Exp.Exp condition "The when-condition" ;
list<ReinitStatement> reinitStmtLst "List of reinit statements associated to the when clause." ;
Option<Integer> elseClause "index of elsewhen clause" ;
// HL only needs to know if it is an elsewhen the equations take care of which clauses are related.
// The equations associated to the clause are linked to this when clause by the index in the
// when clause list where this when clause is stored.
end WHEN_CLAUSE;
end WhenClause;
public
uniontype ZeroCrossing "- Zero Crossing"
record ZERO_CROSSING
Exp.Exp relation_ "function" ;
list<Integer> occurEquLst "List of equations where the function occurs" ;
list<Integer> occurWhenLst "List of when clauses where the function occurs" ;
end ZERO_CROSSING;
end ZeroCrossing;
public
uniontype EventInfo "- EventInfo"
record EVENT_INFO
list<WhenClause> whenClauseLst "List of when clauses. The WhenEquation datatype refer to this list by position" ;
list<ZeroCrossing> zeroCrossingLst "zeroCrossingLst" ;
end EVENT_INFO;
end EventInfo;
public
uniontype DAELow "THE LOWERED DAE consist of variables and equations. The variables are split into
two lists, one for unknown variables states and algebraic and one for known variables
constants and parameters.
The equations are also split into two lists, one with simple equations, a=b, a-b=0, etc., that
are removed from the set of equations to speed up calculations.
- DAELow"
record DAELOW
Variables orderedVars "orderedVars ; ordered Variables, only states and alg. vars" ;
Variables knownVars "knownVars ; Known variables, i.e. constants and parameters" ;
Variables externalObjects "External object variables";
EquationArray orderedEqs "orderedEqs ; ordered Equations" ;
EquationArray removedEqs "removedEqs ; Removed equations a=b" ;
EquationArray initialEqs "initialEqs ; Initial equations" ;
MultiDimEquation[:] arrayEqs "arrayEqs ; Array equations" ;
Algorithm.Algorithm[:] algorithms "algorithms ; Algorithms" ;
EventInfo eventInfo "eventInfo" ;
ExternalObjectClasses extObjClasses "classes of external objects, contains constructor & destructor";
end DAELOW;
end DAELow;
type ExternalObjectClasses = list<ExternalObjectClass> "classes of external objects stored in list";
uniontype ExternalObjectClass "class of external objects"
record EXTOBJCLASS
Absyn.Path path "className of external object";
DAE.Element constructor "constructor is an EXTFUNCTION";
DAE.Element destructor "destructor is an EXTFUNCTION";
end EXTOBJCLASS;
end ExternalObjectClass;
public
uniontype Variables "- Variables"
record VARIABLES
list<CrefIndex>[:] crefIdxLstArr "crefIdxLstArr ; HashTB, cref->indx" ;
list<StringIndex>[:] strIdxLstArr "strIdxLstArr ; HashTB, cref->indx for old names" ;
VariableArray varArr "varArr ; Array of variables" ;
Integer bucketSize "bucketSize ; bucket size" ;
Integer numberOfVars "numberOfVars ; no. of vars" ;
end VARIABLES;
end Variables;
public
uniontype MultiDimEquation "- Multi Dimensional Equation"
record MULTIDIM_EQUATION
list<Integer> dimSize "dimSize ; dimension sizes" ;
Exp.Exp left "left ; lhs" ;
Exp.Exp right "right ; rhs" ;
end MULTIDIM_EQUATION;
end MultiDimEquation;
public
uniontype CrefIndex "- Component Reference Index"
record CREFINDEX
Exp.ComponentRef cref "cref" ;
Integer index "index" ;
end CREFINDEX;
end CrefIndex;
public
uniontype StringIndex "- String Index"
record STRINGINDEX
String str "str" ;
Integer index "index" ;
end STRINGINDEX;
end StringIndex;
public
uniontype VariableArray "array of Equations are expandable, to amortize the cost of adding
equations in a more efficient manner
- Variable Array"
record VARIABLE_ARRAY
Integer numberOfElements "numberOfElements ; no. elements" ;
Integer arrSize "arrSize ; array size" ;
Option<Var>[:] varOptArr "varOptArr" ;
end VARIABLE_ARRAY;
end VariableArray;
public
uniontype EquationArray "- Equation Array"
record EQUATION_ARRAY
Integer numberOfElement "numberOfElement ; no. elements" ;
Integer arrSize "arrSize ; array size" ;
Option<Equation>[:] equOptArr "equOptArr" ;
end EQUATION_ARRAY;
end EquationArray;
public
uniontype Assignments "Assignments of variables to equations and vice versa are implemented by a
expandable array to amortize addition of array elements more efficient
- Assignments"
record ASSIGNMENTS
Integer actualSize "actualSize ; actual size" ;
Integer allocatedSize "allocatedSize ; allocated size >= actual size" ;
Integer[:] arrOfIndices "arrOfIndices ; array of indices" ;
end ASSIGNMENTS;
end Assignments;
public
uniontype BinTree "Generic Binary tree implementation
- Binary Tree"
record TREENODE
Option<TreeValue> value "value ; Value" ;
Option<BinTree> leftSubTree "leftSubTree ; left subtree" ;
Option<BinTree> rightSubTree "rightSubTree ; right subtree" ;
end TREENODE;
end BinTree;
public
uniontype TreeValue "Each node in the binary tree can have a value associated with it.
- Tree Value"
record TREEVALUE
Key key "Key" ;
Value value "Value" ;
end TREEVALUE;
end TreeValue;
public
type Key = Exp.ComponentRef "A key is a Component Reference
- Key" ;
public
type Value = Integer "- Value" ;
public
type IncidenceMatrix = list<Integer>[:];
public
type IncidenceMatrixT = IncidenceMatrix "IncidenceMatrixT : a list of equation indexes (1..n),
one for each variable. Equations that -only-
contain the state variable and not the derivative
has a negative index.
- Incidence Matrix T" ;
public
uniontype JacobianType "- Jacobian Type"
record JAC_CONSTANT "If jacobian has only constant values, for system
of equations this means that it can be solved statically." end JAC_CONSTANT;
record JAC_TIME_VARYING "If jacobian has time varying parts, like parameters or
algebraic variables" end JAC_TIME_VARYING;
record JAC_NONLINEAR "If jacobian contains variables that are solved for,
means that a nonlinear system of equations needs to be
solved" end JAC_NONLINEAR;
record JAC_NO_ANALYTIC "No analytic jacobian available" end JAC_NO_ANALYTIC;
end JacobianType;
public
uniontype IndexReduction "- Index Reduction"
record INDEX_REDUCTION "Use index reduction during matching" end INDEX_REDUCTION;
record NO_INDEX_REDUCTION "do not use index reduction during matching" end NO_INDEX_REDUCTION;
end IndexReduction;
public
uniontype EquationConstraints "- Equation Constraints"
record ALLOW_UNDERCONSTRAINED "for e.g. initial eqns.
where not all variables
have a solution" end ALLOW_UNDERCONSTRAINED;
record EXACT "exact as many equations
as variables" end EXACT;
end EquationConstraints;
public
uniontype EquationReduction
record REMOVE_SIMPLE_EQN end REMOVE_SIMPLE_EQN;
record KEEP_SIMPLE_EQN "removes simple equation after index reduction does not remove simple equations after index reduction" end KEEP_SIMPLE_EQN;
end EquationReduction;
public
type MatchingOptions = tuple<IndexReduction, EquationConstraints, EquationReduction> "- Matching Options" ;
protected import Util;
protected import RTOpts;
protected import DAEEXT;
protected import Print;
protected import Derive;
protected import Debug;
protected import Env;
protected import Builtin;
protected import Ceval;
protected import Types;
protected import SCode;
protected import Dump;
protected import System;
protected import VarTransform;
protected import Error;
protected import SimCodegen;
protected constant BinTree emptyBintree=TREENODE(NONE,NONE,NONE) " Empty binary tree " ;
public constant String derivativeNamePrefix="$derivative";
public function dumpDAELowEqnList
input list<Equation> inDAELowEqnList;
input String header;
input Boolean printExpTree;
algorithm
print(header);
dumpDAELowEqnList2(inDAELowEqnList,printExpTree);
print("===================\n");
end dumpDAELowEqnList;
protected function dumpDAELowEqnList2
input list<Equation> inDAELowEqnList;
input Boolean printExpTree;
algorithm
_ :=
matchcontinue (inDAELowEqnList,printExpTree)
local
Exp.Exp e1_1,e2_1,e1,e2,e_1,e;
String str;
list<String> strList;
list<Equation> res;
list<Exp.Exp> expList,expList2;
case ({},_) then ();
case (EQUATION(e1,e2)::res,printExpTree) /* header */
equation
dumpDAELowEqnList2(res,printExpTree);
print("EQUATION: ");
str = Exp.printExpStr(e1);
print(str);
print("\n");
str = Exp.dumpExpStr(e1,0);
str = Util.if_(printExpTree,str,"");
print(str);
print("\n");
then
();
case (SOLVED_EQUATION(_,e)::res,printExpTree)
equation
dumpDAELowEqnList2(res,printExpTree);
print("SOLVED_EQUATION: ");
str = Exp.printExpStr(e);
print(str);
print("\n");
str = Exp.dumpExpStr(e,0);
str = Util.if_(printExpTree,str,"");
print(str);
print("\n");
then
();
case (RESIDUAL_EQUATION(e)::res,printExpTree)
equation
dumpDAELowEqnList2(res,printExpTree);
print("RESIDUAL_EQUATION: ");
str = Exp.printExpStr(e);
print(str);
print("\n");
str = Exp.dumpExpStr(e,0);
str = Util.if_(printExpTree,str,"");
print(str);
print("\n");
then
();
case (ARRAY_EQUATION(_,expList)::res,printExpTree)
equation
dumpDAELowEqnList2(res,printExpTree);
print("ARRAY_EQUATION: ");
strList = Util.listMap(expList,Exp.printExpStr);
str = Util.stringDelimitList(strList," | ");
print(str);
print("\n");
then
();
case (ALGORITHM(_,expList,expList2)::res,printExpTree)
equation
dumpDAELowEqnList2(res,printExpTree);
print("ALGORITHM: ");
strList = Util.listMap(expList,Exp.printExpStr);
str = Util.stringDelimitList(strList," | ");
print(str);
print("\n");
strList = Util.listMap(expList2,Exp.printExpStr);
str = Util.stringDelimitList(strList," | ");
print(str);
print("\n");
then
();
case (WHEN_EQUATION(WHEN_EQ(_,_,e,_/*TODO handle elsewhe also*/))::res,printExpTree)
equation
dumpDAELowEqnList2(res,printExpTree);
print("WHEN_EQUATION: ");
str = Exp.printExpStr(e);
print(str);
print("\n");
str = Exp.dumpExpStr(e,0);
str = Util.if_(printExpTree,str,"");
print(str);
print("\n");
then
();
case (_::res,printExpTree)
equation
then ();
end matchcontinue;
end dumpDAELowEqnList2;
public function lower "function: lower
This function translates a DAE, which is the result from instantiating a
class, into a more precise form, called DAELow defined in this module.
The DAELow 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: daeList: DAE.DAElist, add_dummy_state: bool)
outputs: DAELow
"
input DAE.DAElist lst;
input Boolean add_dummy;
output DAELow outDAELow;
BinTree s;
Variables vars,knvars,vars_1,extVars;
list<Equation> eqns,reqns,ieqns,algeqns,multidimeqns,eqns_1;
list<MultiDimEquation> aeqns,aeqns1;
list<Algorithm.Algorithm> algs;
list<WhenClause> whenclauses,whenclauses_1;
list<ZeroCrossing> zero_crossings;
EquationArray eqnarr,reqnarr,ieqnarr;
MultiDimEquation[:] arr_md_eqns;
Algorithm.Algorithm[:] algarr;
ExternalObjectClasses extObjCls;
algorithm
s := states(lst, emptyBintree);
(vars,knvars,extVars,eqns,reqns,ieqns,aeqns,algs,whenclauses,extObjCls) := lower2(lst, s, {});
(vars,eqns) := addDummyState(vars, eqns, add_dummy);
whenclauses_1 := listReverse(whenclauses);
algeqns := lowerAlgorithms(vars, algs);
multidimeqns := lowerMultidimeqns(vars, aeqns);
eqns := listAppend(algeqns, eqns);
eqns := listAppend(multidimeqns, eqns);
(vars,knvars,eqns,reqns,ieqns,aeqns1) := removeSimpleEquations(vars, knvars, eqns, reqns, ieqns, aeqns, s);
vars_1 := detectImplicitDiscrete(vars, eqns);
eqns_1 := sortEqn(eqns);
(zero_crossings) := findZeroCrossings(vars_1, eqns_1, whenclauses_1,algs);
eqnarr := listEquation(eqns_1);
reqnarr := listEquation(reqns);
ieqnarr := listEquation(ieqns);
arr_md_eqns := listArray(aeqns1);
algarr := listArray(algs);
outDAELow := DAELOW(vars_1,knvars,extVars,eqnarr,reqnarr,ieqnarr,arr_md_eqns,algarr,
EVENT_INFO(whenclauses_1,zero_crossings),extObjCls);
end lower;
protected function addDummyState "function: addDummyState
In order for the solver to work correctly at least one state variable
must exist in the equation system. This function therefore adds a
dummy state variable and an equation for that variable.
inputs: (vars: Variables, eqns: Equation list, bool)
outputs: (Variables, Equation list)
"
input Variables inVariables;
input list<Equation> inEquationLst;
input Boolean inBoolean;
output Variables outVariables;
output list<Equation> outEquationLst;
algorithm
(outVariables,outEquationLst):=
matchcontinue (inVariables,inEquationLst,inBoolean)
local
Variables v,vars_1,vars;
list<Equation> e,eqns;
case (v,e,false) then (v,e);
case (vars,eqns,true) /* TODO::The dummy variable must be fixed */
equation
vars_1 = addVar(
VAR(Exp.CREF_IDENT("$dummy",{}),STATE(),DAE.BIDIR(),DAE.REAL(),
NONE,NONE,{},NONE,-1,Exp.CREF_IDENT("$dummy",{}),{},
SOME(
DAE.VAR_ATTR_REAL(NONE,NONE,NONE,(NONE,NONE),NONE,SOME(true),NONE,NONE)),NONE,DAE.NON_CONNECTOR()), vars);
then
/* Add equation der(dummy) = sin(time*6628.318530717). This so the solver has something to solve
if the model does not contain states. To prevent the solver from taking larger and larger steps
(which would happen if der(dymmy) = 0) when using automatic, we have a osciallating derivative.
*/
(vars_1,(EQUATION(
Exp.CALL(Absyn.IDENT("der"),
{Exp.CREF(Exp.CREF_IDENT("$dummy",{}),Exp.REAL())},false,true,Exp.REAL()),
Exp.CALL(Absyn.IDENT("sin"),{Exp.BINARY(
Exp.CREF(Exp.CREF_IDENT("time",{}),Exp.REAL()),
Exp.MUL(Exp.REAL()),
Exp.RCONST(628.318530717))},false,true,Exp.REAL())) :: eqns));
end matchcontinue;
end addDummyState;
public function zeroCrossingsEquations "Returns a list of all equations (by their index) that contain a zero crossing
Used e.g. to find out which discrete equations are not part of a zero crossing"
input DAELow dae;
output list<Integer> eqns;
algorithm
eqns := matchcontinue(dae)
case (DAELOW(eventInfo=EVENT_INFO(zeroCrossingLst = zcLst),orderedEqs=eqnArr)) local
list<ZeroCrossing> zcLst;
list<list<Integer>> zcEqns;
list<Integer> wcEqns;
EquationArray eqnArr;
equation
zcEqns = Util.listMap(zcLst,zeroCrossingEquations);
wcEqns = whenEquationsIndices(eqnArr);
eqns = Util.listListUnion(listAppend(zcEqns,{wcEqns}));
then eqns;
end matchcontinue;
end zeroCrossingsEquations;
protected function whenEquationsIndices "Returns all equation-indices that contain a when clause"
input EquationArray eqns;
output list<Integer> res;
algorithm
res := matchcontinue(eqns)
case(eqns) equation
res=whenEquationsIndices2(1,equationSize(eqns),eqns);
then res;
end matchcontinue;
end whenEquationsIndices;
protected function whenEquationsIndices2 "Help function"
input Integer i;
input Integer size;
input EquationArray eqns;
output list<Integer> eqnLst;
algorithm
eqnLst := matchcontinue(i,size,eqns)
case(i,size,eqns) equation
true = (i > size );
then {};
case(i,size,eqns)
equation
WHEN_EQUATION(_) = equationNth(eqns,i-1);
eqnLst = whenEquationsIndices2(i+1,size,eqns);
then i::eqnLst;
case(i,size,eqns)
equation
eqnLst=whenEquationsIndices2(i+1,size,eqns);
then eqnLst;
end matchcontinue;
end whenEquationsIndices2;
protected function zeroCrossingEquations "Returns the list of equations (indices) from a ZeroCrossing"
input ZeroCrossing zc;
output list<Integer> lst;
algorithm
lst := matchcontinue(zc)
case(ZERO_CROSSING(_,lst,_)) then lst;
end matchcontinue;
end zeroCrossingEquations;
protected function dumpZcStr "function: dumpZcStr
Dumps a zerocrossing into a string, for debugging purposes.
"
input ZeroCrossing inZeroCrossing;
output String outString;
algorithm
outString:=
matchcontinue (inZeroCrossing)
local
list<String> eq_s_list,wc_s_list;
String eq_s,wc_s,str,str2;
Exp.Exp e;
list<Value> eq,wc;
case ZERO_CROSSING(relation_ = e,occurEquLst = eq,occurWhenLst = wc)
equation
eq_s_list = Util.listMap(eq, int_string);
eq_s = Util.stringDelimitList(eq_s_list, ",");
wc_s_list = Util.listMap(wc, int_string);
wc_s = Util.stringDelimitList(wc_s_list, ",");
str = Exp.printExpStr(e);
str2 = Util.stringAppendList(
{str," in equations [",eq_s,"] and when conditions [",wc_s,
"]\n"});
then
str2;
end matchcontinue;
end dumpZcStr;
protected function mergeZeroCrossings "function: mergeZeroCrossings
Takes a list of zero crossings and if more than one have identical
function expressions they are merged into one zerocrossing.
In the resulting list all zerocrossing have uniq function expressions.
"
input list<ZeroCrossing> inZeroCrossingLst;
output list<ZeroCrossing> outZeroCrossingLst;
algorithm
outZeroCrossingLst:=
matchcontinue (inZeroCrossingLst)
local
ZeroCrossing zc,same_1;
list<ZeroCrossing> samezc,diff,diff_1,xs;
case {} then {};
case {zc} then {zc};
case (zc :: xs)
equation
samezc = Util.listSelect1(xs, zc, sameZeroCrossing);
diff = Util.listSelect1(xs, zc, differentZeroCrossing);
diff_1 = mergeZeroCrossings(diff);
same_1 = Util.listFold(samezc, mergeZeroCrossing, zc);
then
(same_1 :: diff_1);
end matchcontinue;
end mergeZeroCrossings;
protected function mergeZeroCrossing "function: mergeZeroCrossing
Merges two zero crossings into one by makeing the union of the lists of
equaions and when clauses they appear in.
"
input ZeroCrossing inZeroCrossing1;
input ZeroCrossing inZeroCrossing2;
output ZeroCrossing outZeroCrossing;
algorithm
outZeroCrossing:=
matchcontinue (inZeroCrossing1,inZeroCrossing2)
local
list<Value> eq,zc,eq1,wc1,eq2,wc2;
Exp.Exp e1,e2;
case (ZERO_CROSSING(relation_ = e1,occurEquLst = eq1,occurWhenLst = wc1),ZERO_CROSSING(relation_ = e2,occurEquLst = eq2,occurWhenLst = wc2))
equation
eq = Util.listUnion(eq1, eq2);
zc = Util.listUnion(wc1, wc2);
then
ZERO_CROSSING(e1,eq,zc);
end matchcontinue;
end mergeZeroCrossing;
protected function sameZeroCrossing "function: sameZeroCrossing
Returns true if both zero crossings have the same function expression
"
input ZeroCrossing inZeroCrossing1;
input ZeroCrossing inZeroCrossing2;
output Boolean outBoolean;
algorithm
outBoolean:=
matchcontinue (inZeroCrossing1,inZeroCrossing2)
local
Boolean res;
Exp.Exp e1,e2;
case (ZERO_CROSSING(relation_ = e1),ZERO_CROSSING(relation_ = e2))
equation
res = Exp.expEqual(e1, e2);
then
res;
end matchcontinue;
end sameZeroCrossing;
protected function differentZeroCrossing "function: differentZeroCrossing
Return true if the realation expressions differ.
"
input ZeroCrossing zc1;
input ZeroCrossing zc2;
output Boolean res_1;
Boolean res,res_1;
algorithm
res := sameZeroCrossing(zc1, zc2);
res_1 := boolNot(res);
end differentZeroCrossing;
protected function findZeroCrossings "function: findZeroCrossings
This function finds all zerocrossings in the list of equations and
the list of when clauses. Used in lower2.
"
input Variables vars;
input list<Equation> eq;
input list<WhenClause> wc;
input list<Algorithm.Algorithm> algs;
output list<ZeroCrossing> res_1;
list<ZeroCrossing> res,res_1;
algorithm
res := findZeroCrossings2(vars, eq, 1, wc, 1, algs);
res_1 := mergeZeroCrossings(res);
end findZeroCrossings;
protected function findZeroCrossings2 "function: findZeroCrossings2
Helper function to find_zero_crossing.
"
input Variables inVariables1;
input list<Equation> inEquationLst2;
input Integer inInteger3;
input list<WhenClause> inWhenClauseLst4;
input Integer inInteger5;
input list<Algorithm.Algorithm> algs;
output list<ZeroCrossing> outZeroCrossingLst;
algorithm
outZeroCrossingLst:=
matchcontinue (inVariables1,inEquationLst2,inInteger3,inWhenClauseLst4,inInteger5,algs)
local
Variables v;
list<Exp.Exp> rellst1,rellst2,rel;
list<ZeroCrossing> zc1,zc2,zc3,zc4,res,res1,res2;
Value eq_count_1,eq_count,wc_count_1,wc_count;
Equation e;
Exp.Exp e1,e2;
list<Equation> xs,el;
WhenClause wc;
Integer ind;
case (v,{},_,{},_,_) then {};
case (v,((e as EQUATION(exp = e1,scalar = e2)) :: xs),eq_count,{},_,algs)
equation
rellst1 = findZeroCrossings3(e1, v);
zc1 = makeZeroCrossings(rellst1, {eq_count}, {});
rellst2 = findZeroCrossings3(e2, v);
zc2 = makeZeroCrossings(rellst2, {eq_count}, {});
eq_count_1 = eq_count + 1;
zc3 = findZeroCrossings2(v, xs, eq_count_1, {}, 0,algs);
zc4 = listAppend(zc1, zc2);
res = listAppend(zc3, zc4);
then
res;
case (v,((e as SOLVED_EQUATION(exp = e1)) :: xs),eq_count,{},_,algs)
equation
rellst1 = findZeroCrossings3(e1, v);
zc1 = makeZeroCrossings(rellst1, {eq_count}, {});
eq_count_1 = eq_count + 1;
zc3 = findZeroCrossings2(v, xs, eq_count_1, {}, 0,algs);
res = listAppend(zc3, zc1);
then
res;
case (v,((e as RESIDUAL_EQUATION(exp = e1)) :: xs),eq_count,{},_,algs)
equation
rellst1 = findZeroCrossings3(e1, v);
zc1 = makeZeroCrossings(rellst1, {eq_count}, {});
eq_count_1 = eq_count + 1;
zc3 = findZeroCrossings2(v, xs, eq_count_1, {}, 0,algs);
res = listAppend(zc3, zc1);
then
res;
case (v,((e as ALGORITHM(index = ind)) :: xs),eq_count,{},_,algs)
local
list<Algorithm.Statement> stmts;
equation
eq_count_1 = eq_count + 1;
zc1 = findZeroCrossings2(v, xs, eq_count_1, {}, 0,algs);
Algorithm.ALGORITHM(stmts) = listNth(algs,ind);
rel = Algorithm.getAllExpsStmts(stmts);
rellst1 = Util.listFlatten(Util.listMap1(rel,findZeroCrossings3, v));
zc2 = makeZeroCrossings(rellst1, {eq_count}, {});
res = listAppend(zc2, zc1);
then
res;
case (v,(e :: xs),eq_count,{},_,algs)
equation
eq_count_1 = eq_count + 1;
(res) = findZeroCrossings2(v, xs, eq_count_1, {}, 0,algs);
then
res;
case (v,el,eq_count,((wc as WHEN_CLAUSE(condition = e)) :: xs),wc_count,algs)
local
Exp.Exp e;
list<WhenClause> xs;
equation
wc_count_1 = wc_count + 1;
(res1) = findZeroCrossings2(v, el, eq_count, xs, wc_count_1,algs);
rel = findZeroCrossings3(e, v);
res2 = makeZeroCrossings(rel, {}, {wc_count});
res = listAppend(res1, res2);
then
res;
end matchcontinue;
end findZeroCrossings2;
protected function collectZeroCrossings "function: collectZeroCrossings
Collects zero crossings
"
input tuple<Exp.Exp, tuple<list<Exp.Exp>, Variables>> inTplExpExpTplExpExpLstVariables;
output tuple<Exp.Exp, tuple<list<Exp.Exp>, Variables>> outTplExpExpTplExpExpLstVariables;
algorithm
outTplExpExpTplExpExpLstVariables:=
matchcontinue (inTplExpExpTplExpExpLstVariables)
local
Exp.Exp e,e1,e2,e_1;
Variables vars;
list<Exp.Exp> zeroCrossings,zeroCrossings_1,zeroCrossings_2,zeroCrossings_3,el;
Exp.Operator op;
Exp.Type tp;
Boolean scalar;
case (((e as Exp.CALL(path = Absyn.IDENT(name = "noEvent"))),(zeroCrossings,vars))) then ((e,({},vars)));
case (((e as Exp.CALL(path = Absyn.IDENT(name = "sample"))),(zeroCrossings,vars))) then ((e,((e :: zeroCrossings),vars)));
case (((e as Exp.RELATION(exp1 = e1,operator = op,exp2 = e2)),(zeroCrossings,vars))) /* function with discrete expressions generate no zerocrossing */
equation
true = isDiscreteExp(e1, vars);
true = isDiscreteExp(e2, vars);
then
((e,(zeroCrossings,vars)));
case (((e as Exp.RELATION(exp1 = e1,operator = op,exp2 = e2)),(zeroCrossings,vars)))
equation
then ((e,((e :: zeroCrossings),vars))); /* All other functions generate zerocrossing. */
case (((e as Exp.ARRAY(array = {})),(zeroCrossings,vars)))
equation
then ((e,(zeroCrossings,vars)));
case ((e1 as Exp.ARRAY(ty = tp,scalar = scalar,array = (e :: el)),(zeroCrossings,vars)))
equation
((_,(zeroCrossings_1,vars))) = Exp.traverseExp(e, collectZeroCrossings, (zeroCrossings,vars));
((e_1,(zeroCrossings_2,vars))) = collectZeroCrossings((Exp.ARRAY(tp,scalar,el),(zeroCrossings,vars)));
zeroCrossings_3 = listAppend(zeroCrossings_1, zeroCrossings_2);
then
((e1,(zeroCrossings_3,vars)));
case ((e,(zeroCrossings,vars)))
equation
then ((e,(zeroCrossings,vars)));
end matchcontinue;
end collectZeroCrossings;
public function isVarDiscrete " returns true if variable is discrete"
input Var var;
output Boolean res;
algorithm
res := matchcontinue(var)
case(VAR(varKind=kind)) local VarKind kind;
then isKindDiscrete(kind);
end matchcontinue;
end isVarDiscrete;
protected function isKindDiscrete "function: isKindDiscrete
Returns true if VarKind is discrete.
"
input VarKind inVarKind;
output Boolean outBoolean;
algorithm
outBoolean:=
matchcontinue (inVarKind)
case (DISCRETE()) then true;
case (PARAM()) then true;
case (CONST()) then true;
case (_) then false;
end matchcontinue;
end isKindDiscrete;
protected function isDiscreteExp "function: isDiscreteExp
Returns true if expression is a discrete expression.
"
input Exp.Exp inExp;
input Variables inVariables;
output Boolean outBoolean;
algorithm
outBoolean:=
matchcontinue (inExp,inVariables)
local
Variables vars;
Exp.ComponentRef cr,orig;
VarKind kind;
DAE.VarDirection dir;
DAE.Type vartype;
Option<Exp.Exp> bind,start;
Option<Values.Value> value;
list<Exp.Subscript> dims;
Value ind;
list<Absyn.Path> clname;
Option<DAE.VariableAttributes> attr;
Option<Absyn.Comment> comment;
DAE.Flow flow_;
Boolean res,b1,b2,b3;
Exp.Exp e1,e2,e,e3;
Exp.Operator op;
list<Boolean> blst;
list<Exp.Exp> expl,expl_2;
Exp.Type tp;