-
Notifications
You must be signed in to change notification settings - Fork 299
/
NBEvents.mo
1057 lines (961 loc) · 39.8 KB
/
NBEvents.mo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is part of OpenModelica.
*
* Copyright (c) 1998-2020, Open Source Modelica Consortium (OSMC),
* c/o Linköpings universitet, Department of Computer and Information Science,
* SE-58183 Linköping, Sweden.
*
* All rights reserved.
*
* THIS PROGRAM IS PROVIDED UNDER THE TERMS OF GPL VERSION 3 LICENSE OR
* THIS OSMC PUBLIC LICENSE (OSMC-PL) VERSION 1.2.
* ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES
* RECIPIENT'S ACCEPTANCE OF THE OSMC PUBLIC LICENSE OR THE GPL VERSION 3,
* ACCORDING TO RECIPIENTS CHOICE.
*
* The OpenModelica software and the Open Source Modelica
* Consortium (OSMC) Public License (OSMC-PL) are obtained
* from OSMC, either from the above address,
* from the URLs: http://www.ida.liu.se/projects/OpenModelica or
* http://www.openmodelica.org, and in the OpenModelica distribution.
* GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html.
*
* This program is distributed WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH
* IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS OF OSMC-PL.
*
* See the full OSMC Public License conditions for more details.
*
*/
encapsulated package NBEvents
"file: NBEvents.mo
package: NBEvents
description: This file contains the functions for the event collection module.
"
public
import Module = NBModule;
protected
// OF
import DAE;
// NF
import Builtin = NFBuiltin;
import Call = NFCall;
import ComponentRef = NFComponentRef;
import Expression = NFExpression;
import NFFlatten.{FuncTreeImpl, FunctionTree};
import Operator = NFOperator;
import Prefixes = NFPrefixes;
import Statement = NFStatement;
import Subscript = NFSubscript;
import Type = NFType;
import Variable = NFVariable;
// OB
import OldBackendDAE = BackendDAE;
import OldTree = ZeroCrossings.Tree;
import OldZeroCrossings = ZeroCrossings;
// New Backend
import BackendDAE = NBackendDAE;
import BEquation = NBEquation;
import NBEquation.{Equation, Frame, Iterator, EqData, EquationAttributes, EquationKind, EquationPointers, IfEquationBody};
import Solve = NBSolve;
import System = NBSystem;
import BVariable = NBVariable;
import NBVariable.VarData;
import NBVariable.VariablePointers;
import NBEquation.WhenEquationBody;
// SimCode
import NSimGenericCall.SimIterator;
import OldSimIterator = BackendDAE.SimIterator;
import Block = NSimStrongComponent.Block;
// Util
import BackendUtil = NBBackendUtil;
import DoubleEnded;
import StringUtil;
import BuiltinSystem = System;
// =========================================================================
// MAIN ROUTINE, PLEASE DO NOT CHANGE
// =========================================================================
public
function main
"Wrapper function for any event collection function. This will be
called during simulation and gets the corresponding subfunction from
Config."
extends Module.wrapper;
protected
Module.eventsInterface func;
algorithm
func := getModule();
bdae := match bdae
local
VarData varData;
EqData eqData;
EventInfo eventInfo;
case BackendDAE.MAIN()
algorithm
(varData, eqData, eventInfo) := func(bdae.varData, bdae.eqData, bdae.eventInfo, bdae.funcTree);
bdae.varData := varData;
bdae.eqData := eqData;
bdae.eventInfo := eventInfo;
then bdae;
else algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed."});
then fail();
end match;
end main;
function getModule
"Returns the module function that was chosen by the user."
output Module.eventsInterface func;
protected
String flag = "default"; //Flags.getConfigString(Flags.ZERO_CROSSINGS)
algorithm
(func) := match flag
case "default" then (eventsDefault);
/* ... New detect states modules have to be added here */
else fail();
end match;
end getModule;
// =========================================================================
// TYPES, UNIONTYPES AND MEMBER FUNCTIONS
// =========================================================================
uniontype EventInfo
record EVENT_INFO
UnorderedSet<TimeEvent> time_set "tracks compact time events (SINGLE or SAMPLE)";
UnorderedMap<Condition, CompositeEvent> time_map "tracks full time events of the form $TEV_11 = ...";
UnorderedMap<Condition, StateEvent> state_map "tracks full state events of the form $SEV_4 = ...";
Integer numberMathEvents "stores the number of math function that trigger events e.g. floor, ceil, integer, ...";
end EVENT_INFO;
function toString
input EventInfo eventInfo;
output String str = "";
protected
list<TimeEvent> tev_lst;
list<tuple<Condition, CompositeEvent>> cev_lst;
list<tuple<Condition, StateEvent>> sev_lst;
function tplString<T1, T2>
input tuple<T1, T2> tpl;
input F1 f1;
input F2 f2;
output String str;
protected
T1 t1;
T2 t2;
partial function F1 input T1 t1; output String str; end F1;
partial function F2 input T2 t2; output String str; end F2;
algorithm
(t1, t2) := tpl;
str := f2(t2) + " = " + f1(t1);
end tplString;
algorithm
if not isEmpty(eventInfo) then
(tev_lst, cev_lst, sev_lst) := toLists(eventInfo);
str := StringUtil.headline_2("Event Info") + "\n";
str := str + StringUtil.headline_4("Time Events") + List.toString(tev_lst, function TimeEvent.toString(printIndex = true), "", "", "\n", "") + "\n\n";
str := str + StringUtil.headline_4("Composite Events") + List.toString(cev_lst, function tplString(f1 = Condition.toString, f2 = CompositeEvent.toString), "", "", "\n", "") + "\n\n";
str := str + StringUtil.headline_4("State Events") + List.toString(sev_lst, function tplString(f1 = Condition.toString, f2 = StateEvent.toString), "", "", "\n", "") + "\n\n";
end if;
end toString;
function toLists
input EventInfo eventInfo;
output list<TimeEvent> tev_lst;
output list<tuple<Condition, CompositeEvent>> cev_lst;
output list<tuple<Condition, StateEvent>> sev_lst;
algorithm
tev_lst := List.sort(UnorderedSet.toList(eventInfo.time_set), TimeEvent.indexGt);
cev_lst := List.sort(UnorderedMap.toList(eventInfo.time_map), CompositeEvent.indexGt);
sev_lst := List.sort(UnorderedMap.toList(eventInfo.state_map), StateEvent.indexGt);
end toLists;
function create
input Bucket bucket;
input VariablePointers variables;
input Pointer<Integer> idx;
output EventInfo eventInfo;
output list<Pointer<Variable>> auxiliary_vars = {};
output list<Pointer<Equation>> auxiliary_eqns = {};
protected
String context = "EVT";
list<TimeEvent> tev_lst = UnorderedSet.toList(bucket.time_set);
list<tuple<Condition, CompositeEvent>> cev_lst = UnorderedMap.toList(bucket.time_map);
list<tuple<Condition, StateEvent>> sev_lst = UnorderedMap.toList(bucket.state_map);
ComponentRef lhs_cref;
Expression rhs;
Iterator iterator;
list<ComponentRef> iter;
list<Expression> range;
Pointer<Variable> aux_var;
Pointer<Equation> aux_eqn;
TimeEvent tev;
CompositeEvent cev;
StateEvent sev;
Condition cond;
algorithm
// get auxiliary eqns and vars from composite events
for tpl in cev_lst loop
(cond, cev) := tpl;
if not BVariable.isDummyVariable(cev.auxiliary) then
aux_eqn := Equation.fromLHSandRHS(Expression.fromCref(BVariable.getVarName(cev.auxiliary)), cond.exp, idx, context, EquationAttributes.default(EquationKind.DISCRETE, false));
auxiliary_vars := cev.auxiliary :: auxiliary_vars;
auxiliary_eqns := aux_eqn :: auxiliary_eqns;
end if;
end for;
// get auxiliary eqns and vars from state events
for tpl in sev_lst loop
(cond, sev) := tpl;
if not BVariable.isDummyVariable(sev.auxiliary) then
(iter, range) := Equation.Iterator.getFrames(cond.iter);
// lower the subscripts (containing iterators)
lhs_cref := ComponentRef.mapSubscripts(BVariable.getVarName(sev.auxiliary), function Subscript.mapExp(func = function BackendDAE.lowerComponentReferenceExp(variables = variables)));
aux_eqn := Equation.makeAssignment(Expression.fromCref(lhs_cref), cond.exp, idx, context, Iterator.fromFrames(List.zip(iter, range)), EquationAttributes.default(EquationKind.DISCRETE, false));
auxiliary_vars := sev.auxiliary :: auxiliary_vars;
auxiliary_eqns := aux_eqn :: auxiliary_eqns;
end if;
end for;
eventInfo := EVENT_INFO(
time_set = bucket.time_set,
time_map = bucket.time_map,
state_map = bucket.state_map, // ToDo: StateEvent.updateIndices(stateEvents),
numberMathEvents = 0 // ToDo
);
if Flags.isSet(Flags.DUMP_EVENTS) then
print(toString(eventInfo));
print(List.toString(auxiliary_eqns, function Equation.pointerToString(str = " "), StringUtil.headline_4("Event Equations"), "", "\n", "\n\n"));
end if;
end create;
function empty
output EventInfo eventInfo;
algorithm
eventInfo := EVENT_INFO(
time_set = UnorderedSet.new(TimeEvent.hash, TimeEvent.isEqual),
time_map = UnorderedMap.new<CompositeEvent>(Condition.hash, Condition.isEqual),
state_map = UnorderedMap.new<StateEvent>(Condition.hash, Condition.isEqual),
numberMathEvents = 0
);
end empty;
function isEmpty
input EventInfo eventInfo;
output Boolean b;
algorithm
b := UnorderedSet.isEmpty(eventInfo.time_set) and UnorderedMap.isEmpty(eventInfo.time_map) and UnorderedMap.isEmpty(eventInfo.state_map) and eventInfo.numberMathEvents == 0;
end isEmpty;
function convert
input EventInfo eventInfo;
output list<OldBackendDAE.ZeroCrossing> zeroCrossings;
output list<OldBackendDAE.ZeroCrossing> relations "== zeroCrossings for the most part (only eq pointer different?)";
output list<OldBackendDAE.TimeEvent> timeEvents;
input UnorderedMap<ComponentRef, Block> equation_map;
protected
list<TimeEvent> tev_lst;
list<tuple<Condition, CompositeEvent>> cev_lst;
list<tuple<Condition, StateEvent>> sev_lst;
algorithm
// add composite at some point?
(tev_lst, cev_lst, sev_lst) := toLists(eventInfo);
zeroCrossings := list(StateEvent.convert(sev_tpl, equation_map) for sev_tpl in sev_lst);
relations := zeroCrossings;
timeEvents := list(TimeEvent.convert(tev) for tev in tev_lst);
end convert;
end EventInfo;
uniontype TimeEvent
record SINGLE "e.g. time > 0.5"
Integer index "unique sample index";
Expression trigger "single point in time that triggers it";
end SINGLE;
record SAMPLE "e.g. sample(1, 1)"
Integer index "unique sample index";
Expression start "first trigger point";
Expression interval "equidistant intervals";
end SAMPLE;
function toString
input TimeEvent timeEvent;
input Boolean printIndex = true "for hashing we want to supress index";
output String str;
algorithm
str := match timeEvent
case SINGLE() then "time > " + Expression.toString(timeEvent.trigger);
case SAMPLE() then "sample(" + intString(timeEvent.index) + ", " + Expression.toString(timeEvent.start) + ", " + Expression.toString(timeEvent.interval) + ")";
else algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed!"});
then fail();
end match;
if printIndex then
str := "(" + intString(getIndex(timeEvent)) + ") " + str;
end if;
end toString;
function toStringList
input list<TimeEvent> events_lst;
output String str;
algorithm
str := StringUtil.headline_4("Time Events");
if listEmpty(events_lst) then
str := str + "\t<No Time Events>\n";
else
str := str + stringDelimitList(list(toString(te) for te in events_lst), "\n");
end if;
end toStringList;
function hash
input TimeEvent tev;
output Integer h = stringHashDjb2(toString(tev, false));
end hash;
function isEqual
input TimeEvent tev1;
input TimeEvent tev2;
output Boolean b;
algorithm
b := match (tev1, tev2)
case (SINGLE(), SINGLE()) then Expression.isEqual(tev1.trigger, tev2.trigger);
case (SAMPLE(), SAMPLE()) then Expression.isEqual(tev1.start, tev2.start) and Expression.isEqual(tev1.interval, tev2.interval);
else false;
end match;
end isEqual;
function indexGt
input TimeEvent tev1;
input TimeEvent tev2;
output Boolean b = getIndex(tev1) > getIndex(tev2);
end indexGt;
function create
input output Expression exp;
input output Bucket bucket;
input Iterator iter;
input Pointer<Equation> eqn;
input FunctionTree funcTree;
input Boolean createAux;
output Boolean failed = false "returns true if time event list could not be created";
algorithm
(exp, bucket, failed) := match exp
local
Expression exp1, exp2;
Boolean b1, b2;
case Expression.LBINARY()
guard(Operator.getMathClassification(exp.operator) == NFOperator.MathClassification.LOGICAL)
algorithm
(exp1, bucket, b1) := create(exp.exp1, bucket, iter, eqn, funcTree, createAux);
(exp2, bucket, b2) := create(exp.exp2, bucket, iter, eqn, funcTree, createAux);
failed := (b1 or b2);
if not failed then
// we could simplify here
exp.exp1 := exp1;
exp.exp2 := exp2;
end if;
then (exp, bucket, failed);
else createSingleOrSample(exp, bucket, iter, eqn, funcTree);
end match;
if not failed then
(exp, bucket) := CompositeEvent.add(Condition.CONDITION(exp, iter), bucket, createAux);
end if;
end create;
function createSingleOrSample
"The cases:
1. creates a single time event from a comparing binary expression which
has to only depend on time
2. creates a sample time event from a sample operator
3. fails for anything else
NOTE: create sample from sin and cos functions?"
input output Expression exp "has to be LBINARY() with comparing operator or a sample CALL()";
input output Bucket bucket "bucket containing the events";
input Iterator iter;
input Pointer<Equation> eqn;
input FunctionTree funcTree "function tree for differentiation (solve)";
output Boolean failed "true if it did not work to create a compact time event";
algorithm
(exp, failed) := match exp
local
Equation tmpEqn;
Solve.Status status;
Boolean invert, can_trigger;
Call call;
Expression trigger, new_exp;
TimeEvent timeEvent;
Pointer<Boolean> containsTime = Pointer.create(false);
// check for "sample" call
case Expression.CALL() algorithm
(call, bucket, failed) := createSample(exp.call, bucket);
exp.call := call;
then (exp, failed);
// try to extract single time event
case Expression.RELATION()
guard(Operator.getMathClassification(exp.operator) == NFOperator.MathClassification.RELATION)
algorithm
// create auxiliary equation and solve for TIME
tmpEqn := Pointer.access(Equation.fromLHSandRHS(exp.exp1, exp.exp2, Pointer.create(0), "TMP"));
_ := Equation.map(tmpEqn, function containsTimeTraverseExp(b = containsTime), SOME(function containsTimeTraverseCref(b = containsTime)));
if Pointer.access(containsTime) then
(tmpEqn, _, status, invert) := Solve.solveBody(tmpEqn, NFBuiltin.TIME_CREF, funcTree);
if status == NBSolve.Status.EXPLICIT then
trigger := Equation.getRHS(tmpEqn);
exp.operator := if invert then Operator.invert(exp.operator) else exp.operator;
if Equation.isWhenEquation(eqn) then
// if it is a when equation check if it can even trigger
can_trigger := match exp.operator.op
case NFOperator.Op.GREATER then true;
case NFOperator.Op.GREATEREQ then true;
else false;
end match;
// if it can trigger replace it by the sample call, otherwise just make the trigger false
new_exp := if can_trigger then Expression.CALL(Call.makeTypedCall(
fn = NFBuiltinFuncs.SAMPLE,
args = {Expression.INTEGER(bucket.timeEventIndex + 1), trigger, Expression.REAL(BuiltinSystem.realMaxLit())},
variability = NFPrefixes.Variability.DISCRETE,
purity = NFPrefixes.Purity.PURE
)) else Expression.BOOLEAN(false);
else
// inside if can always trigger, keep the expression as is
can_trigger := true;
new_exp := exp;
end if;
// create and add the time event
if can_trigger then
timeEvent := SINGLE(bucket.timeEventIndex, trigger);
if not UnorderedSet.contains(timeEvent, bucket.time_set) then
bucket.timeEventIndex := bucket.timeEventIndex + 1;
UnorderedSet.add(timeEvent, bucket.time_set);
end if;
end if;
failed := false;
else
failed := true;
new_exp := exp;
end if;
else
failed := true;
new_exp := exp;
end if;
then (new_exp, failed);
else (exp, true);
end match;
end createSingleOrSample;
function createSample
input output Call call;
input output Bucket bucket;
output Boolean failed;
algorithm
failed := match Call.getNameAndArgs(call)
local
Integer value;
Expression start, interval;
TimeEvent timeEvent;
case ("sample", {start, interval}) algorithm
timeEvent := SAMPLE(bucket.timeEventIndex, start, interval);
if not UnorderedSet.contains(timeEvent, bucket.time_set) then
bucket.timeEventIndex := bucket.timeEventIndex + 1;
UnorderedSet.add(timeEvent, bucket.time_set);
end if;
// add index to sample interface
call := Call.setArguments(call, {Expression.INTEGER(getIndex(timeEvent) + 1), start, interval});
then false;
case ("sample", _) algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed for sample operator: " + Call.toString(call)});
then fail();
// Maybe add funky sin/cos stuff here
else true;
end match;
end createSample;
function createSampleTraverse
"used only for StateEvent traversal to encapsulate sample operators"
input output Expression exp "has to be LBINARY() with comparing operator or a sample CALL()";
input output Bucket bucket "bucket containing the events";
algorithm
exp := match exp
local
Call call;
case Expression.CALL(call = call) algorithm
(call, bucket, _) := createSample(call, bucket);
exp.call := call;
then exp;
else exp;
end match;
end createSampleTraverse;
function getIndex
input TimeEvent timeEvent;
output Integer index;
algorithm
index := match timeEvent
case SINGLE() then timeEvent.index;
case SAMPLE() then timeEvent.index;
end match;
end getIndex;
function setIndex
input output TimeEvent timeEvent;
input Integer index;
algorithm
timeEvent := match timeEvent
case SINGLE() algorithm timeEvent.index := index; then timeEvent;
case SAMPLE() algorithm timeEvent.index := index; then timeEvent;
else timeEvent;
end match;
end setIndex;
function convert
input TimeEvent timeEvent;
output OldBackendDAE.TimeEvent oldTimeEvent;
algorithm
oldTimeEvent := match timeEvent
// treat single time events as sample time events with maximum integer as interval
case SINGLE() then OldBackendDAE.TimeEvent.SAMPLE_TIME_EVENT(
index = timeEvent.index,
startExp = Expression.toDAE(timeEvent.trigger),
intervalExp = DAE.RCONST(BuiltinSystem.intMaxLit()));
case SAMPLE() then OldBackendDAE.TimeEvent.SAMPLE_TIME_EVENT(
index = timeEvent.index,
startExp = Expression.toDAE(timeEvent.start),
intervalExp = Expression.toDAE(timeEvent.interval));
else algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed."});
then fail();
end match;
end convert;
end TimeEvent;
uniontype StateEvent
record STATE_EVENT
Integer index "index for simcode";
Pointer<Variable> auxiliary "auxiliary variable representing the relation";
list<Pointer<Equation>> eqns "list of equations where the function occurs";
end STATE_EVENT;
function toString
input StateEvent sev;
output String str = "(" + intString(sev.index) + ") " + BVariable.toString(Pointer.access(sev.auxiliary));
end toString;
function toStringList
input list<StateEvent> events_lst;
output String str;
algorithm
str := StringUtil.headline_4("State Events");
if listEmpty(events_lst) then
str := str + "\t<No State Events>\n";
else
str := str + stringDelimitList(list(toString(te) for te in events_lst), "\n");
end if;
end toStringList;
function indexGt
input tuple<Condition, StateEvent> tpl1;
input tuple<Condition, StateEvent> tpl2;
output Boolean b;
protected
StateEvent sev1, sev2;
algorithm
(_, sev1) := tpl1;
(_, sev2) := tpl2;
b := sev1.index > sev2.index;
end indexGt;
function fromStatement
input Statement stmt;
input Pointer<Bucket> bucket_ptr;
input Pointer<Equation> eqn;
input FunctionTree funcTree;
input list<Frame> frames = {};
algorithm
() := match stmt
local
ComponentRef name;
Expression range;
list<Frame> new_frames;
Iterator iter;
case Statement.FOR(range = SOME(range)) algorithm
name := ComponentRef.fromNode(stmt.iterator, Type.INTEGER());
new_frames := (name, range) :: frames;
for elem in stmt.body loop
fromStatement(elem, bucket_ptr, eqn, funcTree, frames);
end for;
then ();
else algorithm
iter := Iterator.fromFrames(listReverse(frames));
_ := Statement.mapExp(stmt, function Expression.mapReverse(
func = function collectEventsTraverse(
bucket_ptr = bucket_ptr,
iter = iter,
eqn = eqn,
funcTree = funcTree,
createAux = false)));
then ();
end match;
end fromStatement;
function create
input output Expression exp;
input output Bucket bucket;
input Iterator iter;
input Pointer<Equation> eqn;
input Boolean createAux;
protected
Condition condition;
Option<StateEvent> sev_opt;
StateEvent sev;
Pointer<Variable> aux_var;
ComponentRef aux_cref;
algorithm
// collect possible sample events from exp
(exp, bucket) := Expression.mapFold(exp, TimeEvent.createSampleTraverse, bucket);
condition := Condition.CONDITION(exp, iter);
sev_opt := UnorderedMap.get(condition, bucket.state_map);
if Util.isSome(sev_opt) then
// if the state event already exist update the equations it belongs to
SOME(sev) := sev_opt;
sev.eqns := eqn :: sev.eqns;
UnorderedMap.add(condition, sev, bucket.state_map);
// return the auxiliary instead of the zero crossing
if not BVariable.isDummyVariable(sev.auxiliary) then
exp := Expression.fromCref(BVariable.getVarName(sev.auxiliary));
end if;
else
if createAux then
// make a new auxiliary variable and return the expression which replaces the zero crossing
(aux_var, aux_cref) := BVariable.makeEventVar(NBVariable.STATE_EVENT_STR, bucket.auxiliaryStateEventIndex, iter);
exp := Expression.fromCref(aux_cref);
else
// make no auxiliary and return the original zero crossing
aux_var := Pointer.create(NBVariable.DUMMY_VARIABLE);
exp := condition.exp;
end if;
// add the new event to the map
sev := STATE_EVENT(bucket.auxiliaryStateEventIndex, aux_var, {eqn});
bucket.auxiliaryStateEventIndex := bucket.auxiliaryStateEventIndex + 1;
UnorderedMap.add(condition, sev, bucket.state_map);
end if;
end create;
function convert
input tuple<Condition, StateEvent> sev_tpl;
input UnorderedMap<ComponentRef, Block> equation_map;
output OldBackendDAE.ZeroCrossing oldZc;
protected
Condition cond;
StateEvent sev; // don't even need state event? only condition relevant
Option<list<OldSimIterator>> iter;
algorithm
(cond, sev) := sev_tpl;
iter := if Iterator.isEmpty(cond.iter) then NONE() else SOME(list(SimIterator.convert(it) for it in SimIterator.fromIterator(cond.iter)));
oldZc := OldBackendDAE.ZERO_CROSSING(
index = sev.index,
relation_ = Expression.toDAE(cond.exp),
occurEquLst = list(Block.getIndex(UnorderedMap.getSafe(Equation.getEqnName(eqn), equation_map, sourceInfo())) for eqn in sev.eqns), //ToDo: low priority - only for debugging
iter = iter
);
end convert;
end StateEvent;
uniontype CompositeEvent
record COMPOSITE_EVENT
Integer index;
Pointer<Variable> auxiliary;
end COMPOSITE_EVENT;
function toString
input CompositeEvent cev;
output String str = "(" + intString(cev.index) + ") " + BVariable.pointerToString(cev.auxiliary);
end toString;
function indexGt
input tuple<Condition, CompositeEvent> tpl1;
input tuple<Condition, CompositeEvent> tpl2;
output Boolean b;
protected
CompositeEvent cev1, cev2;
algorithm
(_, cev1) := tpl1;
(_, cev2) := tpl2;
b := cev1.index > cev2.index;
end indexGt;
function create
"Find special events of the form: sample(t0, dt) and (f(x) > 0)
These events can only occur at the sample times. At that time the additional condition
is checked only once, no state event necessary!
NOTE: This does not work for SIMPLE_TIME, e.g. (time > 0.2) and (f(x) > 0)"
input output Expression exp;
input output Bucket bucket;
input Iterator iter;
input Boolean createAux;
output Boolean failed = false "returns true if composite event list could not be created";
protected
Pointer<Variable> aux_var;
ComponentRef aux_cref;
algorithm
(exp, bucket, failed) := match exp
local
Expression exp1, exp2;
Call call;
// base case: sample is the left operand to AND
case Expression.LBINARY(exp1 = exp1 as Expression.CALL(call = call), operator = Operator.OPERATOR(op = NFOperator.Op.AND))
guard BackendUtil.isOnlyTimeDependent(exp1)
algorithm
(call, exp2, bucket, failed) := checkDirectComposite(call, exp.exp2, bucket, iter, createAux);
if not failed then
exp1.call := call;
exp.exp1 := exp1;
if not referenceEq(exp2, exp.exp2) then
exp.exp2 := exp2;
end if;
end if;
then (exp, bucket, failed);
// base case: sample is the right operand to AND
case Expression.LBINARY(exp2 = exp2 as Expression.CALL(call = call), operator = Operator.OPERATOR(op = NFOperator.Op.AND))
guard BackendUtil.isOnlyTimeDependent(exp2)
algorithm
(call, exp1, bucket, failed) := checkDirectComposite(call, exp.exp1, bucket, iter, createAux);
if not failed then
exp2.call := call;
exp.exp2 := exp2;
if not referenceEq(exp1, exp.exp1) then
exp.exp1 := exp1;
end if;
end if;
then (exp, bucket, failed);
// recursion: sample might be nested (all parent operators have to be AND)
// e.g. (sample(t0, dt) and f1(x)) and f2(x)
case Expression.LBINARY(operator = Operator.OPERATOR(op = NFOperator.Op.AND))
algorithm
(exp1, bucket, failed) := create(exp.exp1, bucket, iter, createAux);
if not failed then
exp.exp1 := exp1;
(exp2, bucket, failed) := create(exp.exp2, bucket, iter, createAux);
if not failed then
// TODO what if there is more than one sample()?
exp.exp2 := exp2;
end if;
failed := false; // we know we have a composite time event in the first half
else
(exp2, bucket, failed) := create(exp.exp2, bucket, iter, createAux);
if not failed then
exp.exp2 := exp2;
end if;
end if;
then (exp, bucket, failed);
else (exp, bucket, true);
end match;
if not failed then
(exp, bucket) := add(Condition.CONDITION(exp, iter), bucket, createAux);
end if;
end create;
function checkDirectComposite
"Checks if call is a sample call and if it is creates the appropriate events.
Also checks the rest exp for composite events, not sure if this is necessary."
input output Call call "sample call";
input output Expression exp;
input output Bucket bucket;
input Iterator iter;
input Boolean createAux;
output Boolean failed;
protected
Boolean failed2;
algorithm
(call, bucket, failed) := TimeEvent.createSample(call, bucket);
if not failed then
(exp, bucket, failed2) := create(exp, bucket, iter, createAux);
if not failed2 then
// TODO what if there is more than one sample()? Can we simplify this?
end if;
end if;
end checkDirectComposite;
function add
input Condition condition;
output Expression exp;
input output Bucket bucket;
input Boolean createAux;
protected
Option<CompositeEvent> cev_opt;
CompositeEvent cev;
Pointer<Variable> aux_var;
ComponentRef aux_cref;
algorithm
cev_opt := UnorderedMap.get(condition, bucket.time_map);
if Util.isSome(cev_opt) then
// time event already exists, just get the identifier
SOME(cev) := cev_opt;
if not BVariable.isDummyVariable(cev.auxiliary) then
exp := Expression.fromCref(BVariable.getVarName(cev.auxiliary));
else
exp := condition.exp;
end if;
else
if createAux then
// make a new auxiliary variable and return the expression which replaces the zero crossing
(aux_var, aux_cref) := BVariable.makeEventVar(NBVariable.TIME_EVENT_STR, bucket.auxiliaryTimeEventIndex);
exp := Expression.fromCref(aux_cref);
else
// make no auxiliary and return the original zero crossing
aux_var := Pointer.create(NBVariable.DUMMY_VARIABLE);
exp := condition.exp;
end if;
// add the new event to the map
cev := CompositeEvent.COMPOSITE_EVENT(bucket.auxiliaryTimeEventIndex, aux_var);
bucket.auxiliaryTimeEventIndex := bucket.auxiliaryTimeEventIndex + 1;
UnorderedMap.add(condition, cev, bucket.time_map);
end if;
end add;
end CompositeEvent;
uniontype Condition
record CONDITION
Expression exp;
Iterator iter;
end CONDITION;
function toString
input Condition cond;
output String str;
algorithm
str := Expression.toString(cond.exp);
if not Iterator.isEmpty(cond.iter) then
str := str + " for {" + Iterator.toString(cond.iter) + "}";
end if;
end toString;
function hash
input Condition cond;
output Integer h = stringHashDjb2(toString(cond));
end hash;
function isEqual
input Condition cond1;
input Condition cond2;
output Boolean b = Expression.isEqual(cond1.exp, cond2.exp) and Iterator.isEqual(cond1.iter, cond2.iter);
end isEqual;
function size
input Condition cond;
output Integer s = Iterator.size(cond.iter);
end size;
end Condition;
// =========================================================================
// PROTECTED UNIONTYPES AND FUNCTIONS
// =========================================================================
protected
uniontype Bucket
record BUCKET
UnorderedSet<TimeEvent> time_set "tracks compact time events (SINGLE or SAMPLE)";
UnorderedMap<Condition, CompositeEvent> time_map "tracks full time events of the form $TEV_11 = ...";
UnorderedMap<Condition, StateEvent> state_map "tracks full state events of the form $SEV_4 = ...";
Integer timeEventIndex "used for internal indexing of time events";
Integer auxiliaryTimeEventIndex "used for indexing new $TEV vars";
Integer auxiliaryStateEventIndex "used for indexing new $SEV vars";
end BUCKET;
end Bucket;
function eventsDefault extends Module.eventsInterface;
protected
Bucket bucket = BUCKET(
time_set = UnorderedSet.new(TimeEvent.hash, TimeEvent.isEqual),
time_map = UnorderedMap.new<CompositeEvent>(Condition.hash, Condition.isEqual),
state_map = UnorderedMap.new<StateEvent>(Condition.hash, Condition.isEqual),
timeEventIndex = 0,
auxiliaryTimeEventIndex = 0,
auxiliaryStateEventIndex = 0);
Pointer<Bucket> bucket_ptr;
list<Pointer<Variable>> auxiliary_vars;
list<Pointer<Equation>> auxiliary_eqns;
algorithm
eventInfo := match (varData, eqData)
case (BVariable.VAR_DATA_SIM(), BEquation.EQ_DATA_SIM()) algorithm
// collect event info and replace all conditions with auxiliary variables
bucket_ptr := Pointer.create(bucket);
EquationPointers.mapPtr(eqData.equations, function collectEvents(bucket_ptr = bucket_ptr, funcTree = funcTree));
bucket := Pointer.access(bucket_ptr);
(eventInfo, auxiliary_vars, auxiliary_eqns) := EventInfo.create(bucket, varData.variables, eqData.uniqueIndex);
// add auxiliary variables
varData.variables := VariablePointers.addList(auxiliary_vars, varData.variables);
varData.unknowns := VariablePointers.addList(auxiliary_vars, varData.unknowns);
varData.initials := VariablePointers.addList(auxiliary_vars, varData.initials);
varData.discretes := VariablePointers.addList(auxiliary_vars, varData.discretes);
// add auxiliary equations
eqData.equations := EquationPointers.addList(auxiliary_eqns, eqData.equations);
eqData.simulation := EquationPointers.addList(auxiliary_eqns, eqData.simulation);
eqData.initials := EquationPointers.addList(auxiliary_eqns, eqData.initials);
eqData.discretes := EquationPointers.addList(auxiliary_eqns, eqData.discretes);
then eventInfo;
else algorithm
Error.addMessage(Error.INTERNAL_ERROR,{getInstanceName() + " failed."});
then fail();
end match;
end eventsDefault;
function collectEvents
"collects all events from an equation pointer."
input output Pointer<Equation> eqn_ptr;
input Pointer<Bucket> bucket_ptr;
input FunctionTree funcTree;
protected
Equation eqn = Pointer.access(eqn_ptr);
Iterator iter;
Boolean createAux = not Equation.isAlgorithm(eqn_ptr);
algorithm
eqn := match eqn
case Equation.ALGORITHM() algorithm
for stmt in eqn.alg.statements loop
StateEvent.fromStatement(stmt, bucket_ptr, eqn_ptr, funcTree);
end for;
then eqn;
else algorithm
iter := Equation.getForIterator(eqn);
then Equation.map(eqn, function collectEventsTraverse(
bucket_ptr = bucket_ptr,
iter = iter,
eqn = eqn_ptr,
funcTree = funcTree,
createAux = createAux),
NONE(), Expression.mapReverse);
end match;
if not referenceEq(eqn, Pointer.access(eqn_ptr)) then
Pointer.update(eqn_ptr, eqn);
end if;
end collectEvents;
function collectEventsTraverse
"checks expressions if they are a zero crossing.
can be used on any expression with Exression.mapReverse
(reverse is necessary so the subexpressions are not traversed first)"
input output Expression exp;
input Pointer<Bucket> bucket_ptr;
input Iterator iter;
input Pointer<Equation> eqn;
input FunctionTree funcTree;
input Boolean createAux;
algorithm
exp := match exp
local
Bucket bucket;
// logical binarys: e.g. (a and b)
// Todo: this might not always be correct -> check with something like "contains relation?"
case Expression.LBINARY() algorithm
(exp, bucket) := collectEventsCondition(exp, Pointer.access(bucket_ptr), iter, eqn, funcTree, createAux);
Pointer.update(bucket_ptr, bucket);
then exp;
// relations: e.g. (a > b)
case Expression.RELATION() algorithm
(exp, bucket) := collectEventsCondition(exp, Pointer.access(bucket_ptr), iter, eqn, funcTree, createAux);
Pointer.update(bucket_ptr, bucket);
then exp;
// sample functions