This repository was archived by the owner on May 18, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathCodegenAdevs.tpl
More file actions
5579 lines (5102 loc) · 202 KB
/
CodegenAdevs.tpl
File metadata and controls
5579 lines (5102 loc) · 202 KB
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 defines templates for transforming Modelica/MetaModelica code to C
// code. They are used in the code generator phase of the compiler to write
// target code.
//
// There are two root templates intended to be called from the code generator:
// translateModel and translateFunctions. These templates do not return any
// result but instead write the result to files. All other templates return
// text and are used by the root templates (most of them indirectly).
//
// To future maintainers of this file:
//
// - A line like this
// # var = "" /*BUFD*/
// declares a text buffer that you can later append text to. It can also be
// passed to other templates that in turn can append text to it. In the new
// version of Susan it should be written like this instead:
// let &var = buffer ""
//
// - A line like this
// ..., Text var /*BUFP*/, ...
// declares that a template takes a text buffer as input parameter. In the
// new version of Susan it should be written like this instead:
// ..., Text &var, ...
//
// - A line like this:
// ..., var /*BUFC*/, ...
// passes a text buffer to a template. In the new version of Susan it should
// be written like this instead:
// ..., &var, ...
//
// - Style guidelines:
//
// - Try (hard) to limit each row to 80 characters
//
// - Code for a template should be indented with 2 spaces
//
// - Exception to this rule is if you have only a single case, then that
// single case can be written using no indentation
//
// This single case can be seen as a clarification of the input to the
// template
//
// - Code after a case should be indented with 2 spaces if not written on the
// same line
package CodegenAdevs
import interface SimCodeTV;
import CodegenUtil.*;
import ExpressionDumpTpl;
template translateModel(SimCode simCode)
"Generates Cpp code and header file for an adevs model."
::=
match simCode
case SIMCODE(modelInfo=modelInfo as MODELINFO(__)) then
let()= textFile(simulationHeaderFile(simCode), '<%lastIdentOfPath(modelInfo.name)%>.h')
let()= textFile(simulationCppFile(simCode), '<%lastIdentOfPath(modelInfo.name)%>.cpp')
//this top-level template always returns an empty result
//since generated texts are written to files directly
""
end translateModel;
template simulationHeaderFile(SimCode simCode)
"Generates code for header file for simulation target."
::=
match simCode
case SIMCODE(modelInfo = MODELINFO(varInfo = vi as VARINFO(__))) then
<<
#ifndef __omc_<%lastIdentOfPath(modelInfo.name)%>_h_
#define __omc_<%lastIdentOfPath(modelInfo.name)%>_h_
#include "adevs.h"
#include "adevs_public_modelica_runtime.h"
/**
* Define the input and output type of the adevs models.
*/
#ifndef OMC_ADEVS_IO_TYPE
#define OMC_ADEVS_IO_TYPE double
#endif
/**
* Simulation code for <%lastIdentOfPath(modelInfo.name)%>
* generated by the OpenModelica Compiler.
*/
class <%lastIdentOfPath(modelInfo.name)%>:
public adevs::ode_system<OMC_ADEVS_IO_TYPE>
{
public:
/**
* Constructor. New state events can be added to the model by
* passing the number of new event conditions to the constructor
* and then extending the state_event_func method. Your state
* events will begin at the index returned by numStateEvents().
* You can also set the hysteresis value for the event surfaces
* by passing a value for eventHys.
*/
<%lastIdentOfPath(modelInfo.name)%>(int extra_state_events = 0, double eventHys = 1E-4);
/// Destructor
~<%lastIdentOfPath(modelInfo.name)%>();
/// Index of the first extra state event
int numStateEvents() const { return numZeroCrossings(); }
/**
* These methods are generated by the OpenModelica compiler.
*/
void init(double* q);
void der_func(const double* q, double* dq);
void postStep(double* q);
void state_event_func(const double* q, double* z);
/**
* These methods may be overridden by any derived class.
*/
virtual void extra_state_event_funcs(double* z){}
double time_event_func(const double* q);
void internal_event(double* q, const bool* state_event);
void external_event(double* q, double e,
const adevs::Bag<OMC_ADEVS_IO_TYPE>& xb){}
void confluent_event(double *q, const bool* state_event,
const adevs::Bag<OMC_ADEVS_IO_TYPE>& xb)
{
internal_event(q,state_event);
}
void output_func(const double *q, const bool* state_event,
adevs::Bag<OMC_ADEVS_IO_TYPE>& yb){}
void gc_output(adevs::Bag<OMC_ADEVS_IO_TYPE>& gb){}
/**
* These methods are used to access variables and
* parameters in the modelica model by name.
*/
double getEventEpsilon() const { return epsilon; }
<%makeGetAccessors(modelInfo)%>
/// These methods are for solving non-linear algebraic eqns
<%declareExtraResiduals(allEquations)%>
// Calculate the minimization function for initializing reals
void initial_objective_func(double* w, double* f, double lambda);
private:
<%makeMemberVariables(simCode)%>
<%makeStateSelectHeader(stateSets)%>
double epsilon;
// These must be accessed via a pointer to localVal
double timeValue, _PRE_timeValue;
// Are we at an event?
bool atEvent;
// Are we initializing the model?
bool atInit;
// Zero crossing variables
int *zc;
int numZeroCrossings() const {
return numRelations()+2*numMathEvents();
}
int numRelations() const { return <%vi.numRelations%>; }
int numMathEvents() const { return <%vi.numMathEventFunctions%>; }
// Initial unknowns via solution to least squares
void solve_for_initial_unknowns();
std::vector<double*> init_unknown_vars;
void bound_params();
void save_vars();
void restore_vars();
void clear_event_flags();
bool check_for_new_events();
bool initial() const { return atInit; }
void calc_vars(const double* q = NULL, bool doReinit = false);
AdevsSampleData** samples;
int numTimeEvents() const { return <%vi.numTimeEvents%>; }
bool sample(int index, double tStart, double tInterval);
AdevsDelayData** delays;
int numDelays() const { return <%match simCode.delayedExps case DELAYED_EXPRESSIONS(__) then maxDelayedIndex%>; }
double calcDelay(int index, double expr, double t, double delay);
void saveDelay(int index, double expr, double t, double maxdelay);
AdevsMathEventFunc** eventFuncs;
double floor(double expr, int index);
double div(double x, double y, int index);
int integer(double expr, int index);
double ceil(double expr, int index);
bool selectStateVars();
protected:
/**
* Calculate the values of the state and algebraic variables.
* State variables will be initialized to q if provided,
* or left unchanged if not. This should be called after your
* event handler modifies any state variables that
* appear in the Modelica equations.
*/
void update_vars(const double* q = NULL, bool doReinit = false)
{
calc_vars(q,doReinit);
for (int i = 0; i < numMathEvents(); i++)
if (eventFuncs[i] != NULL)
eventFuncs[i]->setInit(false);
save_vars();
}
/**
* These methods may be used to change paramters
* and state variables at events. Remember to call
* update_vars(q,true) if you change anything.
*/
<%makeSetAccessors(modelInfo)%>
};
#endif
>>
end simulationHeaderFile;
template makeGetAccessors(ModelInfo modelInfo)
::=
match modelInfo
case MODELINFO(vars = vars as SIMVARS(__)) then
<<
double get_time() const { return timeValue; }
<%(vars.stateVars |> v =>
'<%declareGetMethod(v)%>'); separator="\n"%>
<%(vars.derivativeVars |> v =>
'<%declareGetMethod(v)%>'); separator="\n"%>
<%(vars.algVars |> v =>
'<%declareGetMethod(v)%>'); separator="\n"%>
<%(vars.discreteAlgVars |> v =>
'<%declareGetMethod(v)%>'); separator="\n"%>
<%(vars.intAlgVars |> v =>
'<%declareGetMethod(v)%>'); separator="\n"%>
<%(vars.boolAlgVars |> v =>
'<%declareGetMethod(v)%>'); separator="\n"%>
<%(vars.paramVars |> v =>
'<%declareGetMethod(v)%>'); separator="\n"%>
<%(vars.intParamVars |> v =>
'<%declareGetMethod(v)%>'); separator="\n"%>
<%(vars.boolParamVars |> v =>
'<%declareGetMethod(v)%>'); separator="\n"%>
<%(vars.aliasVars |> v =>
'<%declareGetMethod(v)%>'); separator="\n"%>
<%(vars.intAliasVars |> v =>
'<%declareGetMethod(v)%>'); separator="\n"%>
<%(vars.boolAliasVars |> v =>
'<%declareGetMethod(v)%>'); separator="\n"%>
>>
end makeGetAccessors;
template makeSetAccessors(ModelInfo modelInfo)
::=
match modelInfo
case MODELINFO(vars = vars as SIMVARS(__)) then
<<
<%(vars.stateVars |> v =>
'<%declareSetMethod(v)%>'); separator="\n"%>
<%(vars.paramVars |> v =>
'<%declareSetMethod(v)%>'); separator="\n"%>
<%(vars.intParamVars |> v =>
'<%declareSetMethod(v)%>'); separator="\n"%>
<%(vars.boolParamVars |> v =>
'<%declareSetMethod(v)%>'); separator="\n"%>
>>
end makeSetAccessors;
template makeMemberVariables(SimCode simCode)
::=
match simCode
case SIMCODE(modelInfo = MODELINFO(vars = vars as SIMVARS(__))) then
<<
// State variables
<%(vars.stateVars |> v =>
'<%declareCref(v,"")%> <%declareCref(v,"_PRE")%>');separator="\n"%>
// Derivative variables
<%(vars.derivativeVars |> v =>
'<%declareCref(v,"")%> <%declareCref(v,"_PRE")%>');separator="\n"%>
// Non discrete Real Algebraic variables
<%(vars.algVars |> v =>
'<%declareCref(v,"")%> <%declareCref(v,"_PRE")%>');separator="\n"%>
// Discrete Real Algebraic variables
<%(vars.discreteAlgVars |> v =>
'<%declareCref(v,"")%> <%declareCref(v,"_PRE")%>');separator="\n"%>
// Integer algebraic variables
<%(vars.intAlgVars |> v =>
'<%declareCref(v,"")%> <%declareCref(v,"_PRE")%>');separator="\n"%>
// Boolean algebraic variables
<%(vars.boolAlgVars |> v =>
'<%declareCref(v,"")%> <%declareCref(v,"_PRE")%>');separator="\n"%>
// Alias variables
<%(vars.aliasVars |> v =>
'<%declareCref(v,"")%> <%declareCref(v,"_PRE")%>');separator="\n"%>
// Integer alias variables
<%(vars.intAliasVars |> v =>
'<%declareCref(v,"")%> <%declareCref(v,"_PRE")%>');separator="\n"%>
// Boolean alias variables
<%(vars.boolAliasVars |> v =>
'<%declareCref(v,"")%> <%declareCref(v,"_PRE")%>');separator="\n"%>
// Parameter variables
<%(vars.paramVars |> v =>
'<%declareCref(v,"")%> <%declareCref(v,"_PRE")%>');separator="\n"%>
// Integer parameter variables
<%(vars.intParamVars |> v =>
'<%declareCref(v,"")%> <%declareCref(v,"_PRE")%>');separator="\n"%>
// Boolean parameter variables
<%(vars.boolParamVars |> v =>
'<%declareCref(v,"")%> <%declareCref(v,"_PRE")%>');separator="\n"%>
// String variables
<%(vars.stringAlgVars |> v =>
'<%declareCref(v,"")%> <%declareCref(v,"_PRE")%>');separator="\n"%>
// String parameters
<%(vars.stringParamVars |> v =>
'<%declareCref(v,"")%> <%declareCref(v,"_PRE")%>');separator="\n"%>
// External object variables
<%(vars.extObjVars |> v =>
'<%declareCref(v,"")%> <%declareCref(v,"_PRE")%>');separator="\n"%>
// Constants
<%(vars.constVars |> v =>
'<%declareCref(v,"")%> <%declareCref(v,"_PRE")%>');separator="\n"%>
// Integer constants
<%(vars.intConstVars |> v =>
'<%declareCref(v,"")%> <%declareCref(v,"_PRE")%>');separator="\n"%>
// Boolean constants
<%(vars.boolConstVars |> v =>
'<%declareCref(v,"")%> <%declareCref(v,"_PRE")%>');separator="\n"%>
// String constants
<%(vars.stringConstVars |> v =>
'<%declareCref(v,"")%> <%declareCref(v,"_PRE")%>');separator="\n"%>
>>
end makeMemberVariables;
template simulationCppFile(SimCode simCode)
"Generates code for main cpp file for simulation target."
::=
match simCode
case SIMCODE(modelInfo = MODELINFO(varInfo = vi as VARINFO(__))) then
<<
#include "<%lastIdentOfPath(modelInfo.name)%>.h"
#include "adevs_modelica_runtime.h"
using namespace adevs;
// This is used by the residual functions
static <%lastIdentOfPath(modelInfo.name)%>* active_model;
<%makeExtraFunctionsAndRecords(simCode)%>
<%makeBoundParams(simCode)%>
<%lastIdentOfPath(modelInfo.name)%>::<%lastIdentOfPath(modelInfo.name)%>(
int extra_state_events, double eventHys):
ode_system<OMC_ADEVS_IO_TYPE>(
<%vi.numStateVars%>+1, // Number of state variables plus one for the clock
<%vi.numRelations%>+2*<%vi.numMathEventFunctions%>+extra_state_events // Number of state event functions
),
epsilon(eventHys),
zc(NULL),
samples(NULL),
delays(NULL),
eventFuncs(NULL)
{
timeValue = 0.0;
if (numRelations() > 0)
zc = new int[numRelations()];
if (numTimeEvents() > 0)
{
samples = new AdevsSampleData*[numTimeEvents()];
for (int i = 0; i < numTimeEvents(); i++)
samples[i] = NULL;
}
if (numDelays() > 0)
{
delays = new AdevsDelayData*[numDelays()];
for (int i = 0; i < numDelays(); i++)
delays[i] = NULL;
}
if (numMathEvents() > 0)
{
eventFuncs = new AdevsMathEventFunc*[numMathEvents()];
for (int i = 0; i < numMathEvents(); i++)
eventFuncs[i] = NULL;
}
}
<%lastIdentOfPath(modelInfo.name)%>::~<%lastIdentOfPath(modelInfo.name)%>()
{
if (zc != NULL) delete [] zc;
if (samples != NULL)
{
for (int i = 0; i < numTimeEvents(); i++)
if (samples[i] != NULL) delete samples[i];
delete [] samples;
}
if (delays != NULL)
{
for (int i = 0; i < numDelays(); i++)
if (delays[i] != NULL) delete delays[i];
delete [] delays;
}
if (eventFuncs != NULL)
{
for (int i = 0; i < numMathEvents(); i++)
if (eventFuncs[i] != NULL) delete eventFuncs[i];
delete [] eventFuncs;
}
}
<%makeExtraResiduals(allEquations,lastIdentOfPath(modelInfo.name))%>
<%makeInitialResidueMethod(simCode)%>
<%makeInit(simCode)%>
<%makeDerFunc(simCode)%>
<%makePostStep(simCode)%>
<%makeSaveMemberVariables(simCode)%>
<%makeRestoreMemberVariables(modelInfo)%>
<%makeDerFuncCalculator(simCode)%>
<%makeEventFunc(simCode)%>
<%makeJacobianStateSetFuncs(simCode.stateSets,lastIdentOfPath(modelInfo.name))%>
<%makeSelectStateMethod(simCode)%>
double <%lastIdentOfPath(modelInfo.name)%>::calcDelay(int index, double expr, double t, double delay)
{
if (delays[index] == NULL || !delays[index]->isEnabled()) return expr;
else return delays[index]->sample(t-delay);
}
void <%lastIdentOfPath(modelInfo.name)%>::saveDelay(int index, double expr, double t, double max_delay)
{
if (delays[index] == NULL)
delays[index] = new AdevsDelayData(max_delay);
delays[index]->insert(t,expr);
}
>>
end simulationCppFile;
template declareExtraResiduals(list<SimEqSystem> allEquations)
::=
(allEquations |> eqn => (match eqn
case eq as SES_MIXED(__) then declareExtraResiduals(fill(eq.cont,1))
case eq as SES_NONLINEAR(nlSystem=nls as NONLINEARSYSTEM(__)) then
<<
void residualFunc<%nls.index%>_cpp(double* y, double* res);
void solve_residualFunc<%nls.index%>_cpp();
>>
)
;separator="\n")
end declareExtraResiduals;
template makeExtraResiduals(list<SimEqSystem> allEquations, String name)
"Generates functions in simulation file."
::=
(allEquations |> eqn => (match eqn
case eq as SES_MIXED(__) then makeExtraResiduals(fill(eq.cont,1),name)
case eq as SES_NONLINEAR(nlSystem=nls as NONLINEARSYSTEM(__)) then
let size = listLength(nls.crefs)
let &varDecls = buffer "" /*BUFD*/
let algs = (nls.eqs |> eq2 as SES_ALGORITHM(__) =>
equation_(eq2, contextSimulationDiscrete, &varDecls /*BUFD*/)
;separator="\n")
let prebody = (nls.eqs |> eq2 as SES_SIMPLE_ASSIGN(__) =>
equation_(eq2, contextOther, &varDecls /*BUFD*/)
;separator="\n")
let arrayprebody = (nls.eqs |> eq2 as SES_ARRAY_CALL_ASSIGN(__) =>
equation_(eq2, contextOther, &varDecls /*BUFD*/)
;separator="\n")
let body = (nls.eqs |> eq2 as SES_RESIDUAL(__) hasindex i0 =>
let &preExp = buffer "" /*BUFD*/
let expPart = daeExp(eq2.exp, contextSimulationDiscrete,
&preExp /*BUFC*/, &varDecls /*BUFD*/)
'<%preExp%>res[<%i0%>] = <%expPart%>;'
;separator="\n")
<<
static int residualFunc<%nls.index%>(N_Vector y, N_Vector f, void*)
{
double* yd = NV_DATA_S(y);
double* fd = NV_DATA_S(f);
active_model->residualFunc<%nls.index%>_cpp(yd,fd);
return 0;
}
void <%name%>::residualFunc<%nls.index%>_cpp(double* y, double* res)
{
<%nls.crefs |> name hasindex i0 =>
<<
<%cref(name)%> = y[<%i0%>];
>>
;separator="\n"%>
<%varDecls%>
<%algs%>
<%prebody%>
<%arrayprebody%>
<%body%>
}
void <%name%>::solve_residualFunc<%nls.index%>_cpp()
{
int flag;
int NEQ = <%size%>;
N_Vector y = N_VNew_Serial(NEQ);
N_Vector scale = N_VNew_Serial(NEQ);
void* kmem = KINCreate();
active_model = this;
assert(kmem != NULL);
flag = KINInit(kmem, residualFunc<%nls.index%>, y);
assert(flag == KIN_SUCCESS);
flag = KINDense(kmem, NEQ);
assert(flag == KIN_SUCCESS);
N_VConst_Serial(1.0,scale);
<%nls.crefs |> name hasindex i0 =>
<<
NV_Ith_S(y,<%i0%>) = <%cref(name)%>;
>>
;separator="\n"%>
flag = KINSol(kmem,y,KIN_LINESEARCH,scale,scale);
// Save the outcome and calculate any dependent variables
residualFunc<%nls.index%>(y,scale,NULL);
N_VDestroy_Serial(y);
N_VDestroy_Serial(scale);
KINFree(&kmem);
}
>>
)
;separator="\n\n")
end makeExtraResiduals;
template makeExtraFunctionsAndRecords(SimCode simCode)
::=
match simCode
case SIMCODE(modelInfo = MODELINFO(vars = vars as SIMVARS(__))) then
<<
<%recordDecls |> rd => recordDeclaration(rd) ;separator="\n"%>
<%functionHeaders(modelInfo.functions)%>
<%functionBodies(modelInfo.functions)%>
>>
end makeExtraFunctionsAndRecords;
template makeEventFunc(SimCode simCode)
::=
match simCode
case SIMCODE(modelInfo = MODELINFO(vars = vars as SIMVARS(__))) then
<<
bool <%lastIdentOfPath(modelInfo.name)%>::check_for_new_events()
{
bool result = false;
double* z = new double[numZeroCrossings()];
<%zeroCrossingEqns(zeroCrossings,relations)%>
for (int i = 0; i < numRelations() && !result; i++)
{
if (z[i] < 0.0 && zc[i] == 1) result = true;
else if (z[i] > 0.0 && zc[i] == 0) result = true;
}
for (int i = numRelations(); i < numZeroCrossings() && !result; i += 2)
{
if (z[i] < 0.0 || z[i+1] < 0.0) result = true;
}
delete [] z;
return result;
}
void <%lastIdentOfPath(modelInfo.name)%>::state_event_func(const double* q, double* z)
{
calc_vars(q);
<%zeroCrossingEqns(zeroCrossings,relations)%>
extra_state_event_funcs(&(z[numStateEvents()]));
restore_vars();
}
bool <%lastIdentOfPath(modelInfo.name)%>::sample(int index, double tStart, double tInterval)
{
index--;
assert(index >= 0);
if (samples[index] == NULL)
samples[index] = new AdevsSampleData(tStart,tInterval);
return samples[index]->atEvent(timeValue,epsilon);
}
double <%lastIdentOfPath(modelInfo.name)%>::time_event_func(const double* q)
{
double ttgMin = adevs_inf<double>();
for (int i = 0; i < numTimeEvents(); i++)
{
double ttg = samples[i]->timeToEvent(timeValue);
if (ttg < ttgMin) ttgMin = ttg;
}
for (int i = 0; i < numDelays(); i++)
{
double ttg = delays[i]->getMaxDelay();
if (ttg < ttgMin) ttgMin = ttg;
}
return ttgMin;
}
void <%lastIdentOfPath(modelInfo.name)%>::internal_event(double* q, const bool* state_event)
{
atEvent = true;
for (int i = 0; i < numTimeEvents(); i++)
{
assert(samples[i] != NULL);
samples[i]->setEnabled(true);
}
calc_vars(q);
for (int i = 0; i < numTimeEvents(); i++)
{
samples[i]->update(timeValue,epsilon);
samples[i]->setEnabled(false);
}
save_vars(); // save the new state of the model
// Reinitialize state variables that need to be reinitialized
<%(vars.stateVars |> SIMVAR(__) => 'q[<%index%>]=<%cref(name)%>;') ;separator="\n"%>
for (int i = 0; i < numMathEvents(); i++)
if (eventFuncs[i] != NULL) eventFuncs[i]->setInit(false);
atEvent = false;
}
double <%lastIdentOfPath(modelInfo.name)%>::floor(double expr, int index)
{
if (eventFuncs[index] == NULL)
eventFuncs[index] = new AdevsFloorFunc(epsilon);
return eventFuncs[index]->calcValue(expr);
}
double <%lastIdentOfPath(modelInfo.name)%>::div(double x, double y, int index)
{
if (eventFuncs[index] == NULL)
eventFuncs[index] = new AdevsDivFunc(epsilon);
return eventFuncs[index]->calcValue(x/y);
}
int <%lastIdentOfPath(modelInfo.name)%>::integer(double expr, int index)
{
if (eventFuncs[index] == NULL)
eventFuncs[index] = new AdevsFloorFunc(epsilon);
return int(eventFuncs[index]->calcValue(expr));
}
double <%lastIdentOfPath(modelInfo.name)%>::ceil(double expr, int index)
{
if (eventFuncs[index] == NULL)
eventFuncs[index] = new AdevsCeilFunc(epsilon);
return eventFuncs[index]->calcValue(expr);
}
>>
end makeEventFunc;
template zeroCrossingEqns(list<ZeroCrossing> zeroCrossings, list<ZeroCrossing> relations)
"Generates function in simulation file."
::=
let &varDecls = buffer "" /*BUFD*/
let RelationsCode = zeroCrossingsRelationsTpl(relations, &varDecls /*BUFD*/)
let EventFuncCode = zeroCrossingsEventFunctionsTpl(zeroCrossings, &varDecls /*BUFD*/)
<<
<%varDecls%>
<%RelationsCode%>
<%EventFuncCode%>
>>
end zeroCrossingEqns;
template makeSaveMemberVariables(SimCode simCode)
::=
match simCode
case SIMCODE(modelInfo = MODELINFO(vars = vars as SIMVARS(__))) then
<<
void <%lastIdentOfPath(modelInfo.name)%>::save_vars()
{
_PRE_timeValue = timeValue;
<%(vars.stateVars |> SIMVAR(__) =>
'_PRE<%cref(name)%>=<%cref(name)%>;') ;separator="\n"%>
<%(vars.derivativeVars |> SIMVAR(__) =>
'_PRE<%cref(name)%>=<%cref(name)%>;') ;separator="\n"%>
<%(vars.algVars |> SIMVAR(__) =>
'_PRE<%cref(name)%>=<%cref(name)%>;') ;separator="\n"%>
<%(vars.discreteAlgVars |> SIMVAR(__) =>
'_PRE<%cref(name)%>=<%cref(name)%>;') ;separator="\n"%>
<%(vars.intAlgVars |> SIMVAR(__) =>
'_PRE<%cref(name)%>=<%cref(name)%>;') ;separator="\n"%>
<%(vars.boolAlgVars |> SIMVAR(__) =>
'_PRE<%cref(name)%>=<%cref(name)%>;') ;separator="\n"%>
<%(vars.aliasVars |> SIMVAR(__) =>
'_PRE<%cref(name)%>=<%cref(name)%>;') ;separator="\n"%>
<%(vars.intAliasVars |> SIMVAR(__) =>
'_PRE<%cref(name)%>=<%cref(name)%>;') ;separator="\n"%>
<%(vars.boolAliasVars |> SIMVAR(__) =>
'_PRE<%cref(name)%>=<%cref(name)%>;') ;separator="\n"%>
<%(vars.paramVars |> SIMVAR(__) =>
'_PRE<%cref(name)%>=<%cref(name)%>;') ;separator="\n"%>
<%makeSaveDelays(delayedExps)%>
}
>>
end makeSaveMemberVariables;
template makeSaveDelays(DelayedExpression delayed)
"Generates function in simulation file."
::=
let &varDecls = buffer "" /*BUFD*/
let storePart = (match delayed case DELAYED_EXPRESSIONS(__) then (delayedExps |> (id, (e, d, delayMax)) =>
let &preExp = buffer "" /*BUFD*/
let eRes = daeExp(e, contextSimulationNonDiscrete,
&preExp /*BUFC*/, &varDecls /*BUFD*/)
let delayExp = daeExp(d, contextSimulationNonDiscrete, &preExp /*BUFC*/, &varDecls /*BUFD*/)
let delayExpMax = daeExp(delayMax, contextSimulationNonDiscrete, &preExp /*BUFC*/, &varDecls /*BUFD*/)
<<
<%preExp%>
saveDelay(<%id%>, <%eRes%>, timeValue, <%delayExpMax%>);<%\n%>
>>
))
<<
<%varDecls%>
<%storePart%>
>>
end makeSaveDelays;
template makeRestoreMemberVariables(ModelInfo modelInfo)
::=
match modelInfo
case MODELINFO(vars = SIMVARS(__)) then
<<
void <%lastIdentOfPath(name)%>::restore_vars()
{
timeValue = _PRE_timeValue;
<%(vars.stateVars |> SIMVAR(__) =>
'<%cref(name)%>=_PRE<%cref(name)%>;') ;separator="\n"%>
<%(vars.derivativeVars |> SIMVAR(__) =>
'<%cref(name)%>=_PRE<%cref(name)%>;') ;separator="\n"%>
<%(vars.algVars |> SIMVAR(__) =>
'<%cref(name)%>=_PRE<%cref(name)%>;') ;separator="\n"%>
<%(vars.discreteAlgVars |> SIMVAR(__) =>
'<%cref(name)%>=_PRE<%cref(name)%>;') ;separator="\n"%>
<%(vars.intAlgVars |> SIMVAR(__) =>
'<%cref(name)%>=_PRE<%cref(name)%>;') ;separator="\n"%>
<%(vars.boolAlgVars |> SIMVAR(__) =>
'<%cref(name)%>=_PRE<%cref(name)%>;') ;separator="\n"%>
<%(vars.aliasVars |> SIMVAR(__) =>
'<%cref(name)%>=_PRE<%cref(name)%>;') ;separator="\n"%>
<%(vars.intAliasVars |> SIMVAR(__) =>
'<%cref(name)%>=_PRE<%cref(name)%>;') ;separator="\n"%>
<%(vars.boolAliasVars |> SIMVAR(__) =>
'<%cref(name)%>=_PRE<%cref(name)%>;') ;separator="\n"%>
<%(vars.paramVars |> SIMVAR(__) =>
'<%cref(name)%>=_PRE<%cref(name)%>;') ;separator="\n"%>
}
>>
end makeRestoreMemberVariables;
template makeInit(SimCode simCode)
::=
match simCode
case SIMCODE(modelInfo = MODELINFO(vars = vars as SIMVARS(__))) then
let varDecls=""
let init1 = initValst(varDecls,vars.paramVars)
let init2 = initValst(varDecls,vars.intParamVars)
let init3 = initValst(varDecls,vars.boolParamVars)
let init4 = initValst(varDecls,vars.stateVars)
let init5 = initValst(varDecls,vars.algVars)
let init6 = initValst(varDecls,vars.discreteAlgVars)
let init7 = initValst(varDecls,vars.intAlgVars)
let init8 = initValst(varDecls,vars.boolAlgVars)
let init9 = initValst(varDecls,vars.derivativeVars)
let init10 = makeInitialEqns(varDecls,startValueEquations)
<<
void <%lastIdentOfPath(modelInfo.name)%>::clear_event_flags()
{
for (int i = 0; i < numRelations(); i++) zc[i] = -1;
for (int i = 0; i < numMathEvents(); i++)
if (eventFuncs[i] != NULL) eventFuncs[i]->setInit(true);
}
void <%lastIdentOfPath(modelInfo.name)%>::init(double* q)
{
atInit = true;
atEvent = false;
timeValue = q[numVars()-1] = 0.0;
clear_event_flags();
<%allocArrays(vars.paramVars)%>
<%allocArrays(vars.intParamVars)%>
<%allocArrays(vars.boolParamVars)%>
<%allocArrays(vars.stateVars)%>
<%allocArrays(vars.algVars)%>
<%allocArrays(vars.discreteAlgVars)%>
<%allocArrays(vars.intAlgVars)%>
<%allocArrays(vars.boolAlgVars)%>
<%allocArrays(vars.derivativeVars)%>
<%allocArrays(vars.aliasVars)%>
// Get initial values as given in the model
<%varDecls%>
<%initStateSets(stateSets)%>
<%init1%>
<%init2%>
<%init3%>
<%init4%>
<%init5%>
<%init6%>
<%init7%>
<%init8%>
<%init9%>
// Save these to the old values so that pre() and edge() work
save_vars();
// Calculate any equations that provide initial values
<%init10%>
bound_params();
// Solve for any remaining unknowns
solve_for_initial_unknowns();
selectStateVars();
calc_vars(NULL,true);
save_vars();
<%(vars.stateVars |> SIMVAR(__) => 'q[<%index%>]=<%cref(name)%>;') ;separator="\n"%>
atInit = false;
for (int i = 0; i < numMathEvents(); i++)
if (eventFuncs[i] != NULL) eventFuncs[i]->setInit(false);
}
>>
end makeInit;
template makeInitialEqns(Text& varDecls, list<SimEqSystem> startValueEquations)
::=
let eqPart = (startValueEquations |> eq as SES_SIMPLE_ASSIGN(__) =>
equation_(eq, contextOther, &varDecls /*BUFD*/)
;separator="\n")
<<
<%eqPart%>
>>
end makeInitialEqns;
template initialResidualFixedVars(list<SimVar> varsLst) ::=
let res = (varsLst |> SIMVAR(__) =>
if isFixed then
'r=<%cref(name)%>-_PRE<%cref(name)%>; *f+=r*r;'
;separator="\n")
<<
<%res%>
>>
end initialResidualFixedVars;
template selectInitialFreeVars(list<SimVar> varsLst) ::=
let res = (varsLst |> SIMVAR(__) =>
if not isFixed then
'init_unknown_vars.push_back(&<%cref(name)%>);'
;separator="\n")
<<
<%res%>
>>
end selectInitialFreeVars;
template makeBoundParams(SimCode simCode)
::=
match simCode
case SIMCODE(modelInfo = MODELINFO(vars = vars as SIMVARS(__))) then
<<
void <%lastIdentOfPath(modelInfo.name)%>::bound_params()
{
<%functionBoundParameters(parameterEquations)%>
}
>>
end makeBoundParams;
template makeDerFunc(SimCode simCode)
::=
match simCode
case SIMCODE(modelInfo = MODELINFO(vars = vars as SIMVARS(__))) then
<<
void <%lastIdentOfPath(modelInfo.name)%>::der_func(const double* q, double* dq)
{
calc_vars(q);
<%(vars.derivativeVars |> SIMVAR(__) => 'dq[<%index%>]=<%cref(name)%>;') ;separator="\n"%>
dq[numVars()-1] = 1.0;
restore_vars();
}
>>
end makeDerFunc;
template initStateSets(list<StateSet> stateSets)
::=
(stateSets |> SES_STATESET(__) =>
<<
for (int jj = 0; jj < <%nCandidates%>; jj++)
colSelect<%crefarray(crA)%>[jj] = jj;
for (int jj = 0; jj < <%nStates%>; jj++)
rowSelect<%crefarray(crA)%>[jj] = jj;
>>
;separator="\n")
end initStateSets;
template makeStateSelectHeader(list<StateSet> stateSets)
::=
(stateSets |> stateSet as SES_STATESET(__) hasindex i0 =>
let jacDecl =
(stateSet.jacobianMatrix |> JAC_MATRIX(seedVars=seedVars, matrixName=name) =>
'<%declareJacobians2(name,seedVars)%>'
;separator="\n")
<<
<%jacDecl%>
long int colSelect<%crefarray(crA)%>[<%nCandidates%>];
long int rowSelect<%crefarray(crA)%>[<%nStates%>];
>>
; separator="\n")
end makeStateSelectHeader;
template makeReinitDynamicState(DAE.ComponentRef stateVar, list<DAE.ComponentRef> statescandidates, ComponentRef crA, Integer nStates, Integer rowIndex)
::=
let eq = (statescandidates |> var hasindex i0 => '<%cref(var)%>*<%accessCrA(crA,nStates,rowIndex,i0)%>';separator="+")
<<
<%cref(stateVar)%> = <%eq%>;
>>
end makeReinitDynamicState;
template accessCrA(DAE.ComponentRef crA, Integer numRows, String rowIndex, String colIndex)
::=
match numRows
case 1 then '<%crefarray(crA)%>.get(<%colIndex%>)'
else '<%crefarray(crA)%>.get(<%rowIndex%>,<%colIndex%>)'
end accessCrA;
template selectState(list<DAE.ComponentRef> states, list<DAE.ComponentRef> statescandidates, DAE.ComponentRef crA, Integer nCandidates, Integer nStates, JacobianMatrix jacobianMatrix)
::=
let newStateAssign = (states |> stateVar hasindex i0 => '<%makeReinitDynamicState(stateVar,statescandidates,crA,nStates,i0)%>';separator="\n")
<<
calc_Jacobian_<%(jacobianMatrix |> JAC_MATRIX(matrixName=name) => '<%name%>')%>();
if (selectDynamicStates(_Jacobian_<%(jacobianMatrix |> JAC_MATRIX(matrixName=name) => '<%name%>')%>,<%nStates%>,<%nCandidates%>,rowSelect<%crefarray(crA)%>,colSelect<%crefarray(crA)%>))
{
for (int row = 0; row < <%nStates%>; row++)
for (int col = 0; col < <%nCandidates%>; col++)
<%accessCrA(crA,nStates,"row","col")%> = 0;
for (int row = 0; row < <%nStates%>; row++)
{
int rowIndex = rowSelect<%crefarray(crA)%>[(<%nStates%>-1)-row];
int colIndex = colSelect<%crefarray(crA)%>[(<%nCandidates%>-1)-row];
<%accessCrA(crA,nStates,"rowIndex","colIndex")%> = 1;
}
doReinit = true;
}
<%newStateAssign%>
>>
end selectState;
template makeStateSelection(list<StateSet> stateSets, list<SimVar> stateVars)
::=
let selectCode =
(stateSets |> stateSet as SES_STATESET(__) =>
selectState(states,statescandidates,crA,nCandidates,nStates,jacobianMatrix) ; separator="\n")
<<
bool doReinit = false;
<%selectCode%>
return doReinit;
>>
end makeStateSelection;
template makeSelectStateMethod(SimCode simCode)
::=
match simCode
case SIMCODE(modelInfo = MODELINFO(vars = vars as SIMVARS(__))) then
let stateSelect = makeStateSelection(stateSets,vars.stateVars)
<<
bool <%lastIdentOfPath(modelInfo.name)%>::selectStateVars()
{
<%stateSelect%>
}
>>
end makeSelectStateMethod;
template makePostStep(SimCode simCode)
::=
match simCode
case SIMCODE(modelInfo = MODELINFO(vars = vars as SIMVARS(__))) then
let reassignCode = (vars.stateVars |> SIMVAR(__) =>
'q[<%index%>] = <%cref(name)%>;';separator="\n")
<<
void <%lastIdentOfPath(modelInfo.name)%>::postStep(double* q)
{
calc_vars(q);
if (selectStateVars())
{
<%reassignCode%>
calc_vars(q,true);
}
save_vars();
}
>>
end makePostStep;
template makeDerFuncCalculator(SimCode simCode)
::=
match simCode
case SIMCODE(modelInfo = MODELINFO(vars = vars as SIMVARS(__))) then
let aliasAssign = (vars.aliasVars |> v as SIMVAR(__) =>
match aliasvar
case ALIAS(__) then '<%cref(v.name)%> = <%cref(varName)%>;'
case NEGATEDALIAS(__) then '<%cref(v.name)%> = <%cref(varName)%>;'
;separator="\n")
let intAliasAssign = (vars.intAliasVars |> v as SIMVAR(__) =>
match aliasvar
case ALIAS(__) then '<%cref(v.name)%> = <%cref(varName)%>;'
case NEGATEDALIAS(__) then '<%cref(v.name)%> = <%cref(varName)%>;'
;separator="\n")