-
Notifications
You must be signed in to change notification settings - Fork 296
/
CodegenCSharp.tpl
3106 lines (2778 loc) · 110 KB
/
CodegenCSharp.tpl
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 code to C# code.
package CodegenCSharp
import interface SimCodeTV;
import ExpressionDumpTpl;
// SECTION: SIMULATION TARGET, ROOT TEMPLATE
template translateModel(SimCode simCode) ::=
match simCode
case SIMCODE(modelInfo = MODELINFO(__)) then
let()= textFile(simulationFile(simCode), '<%dotPath(modelInfo.name)%>.cs')
//let()= textFile(simulationFunctionsFile(simCode), '<%modelInfo.name%>_functions.cs')
"" // empty result of the top-level template .., only side effects
end translateModel;
template wrapIntoExtraFileIfModelTooBig(Text txtCode, String fileNamePostfix, SimCode simCode) ::=
match simCode
case SIMCODE(modelInfo = MODELINFO(__)) then
if isModelTooBigForCSharpInOneFile(simCode) then
let wrappedCode =
<<
// Simulation code for <%dotPath(modelInfo.name)%> generated by the OpenModelica Compiler.
using System;
using System.Collections.Generic;
using Bodylight.Solvers;
namespace Bodylight.Models<%modelNameSpace(modelInfo.name)%>
{
public partial class <%lastIdentOfPath(modelInfo.name)%> : DAESystem
{
<% txtCode %>
}
}
>>
let fileName = '<%dotPath(modelInfo.name)%>_<%fileNamePostfix%>.cs'
let()= textFile(wrappedCode, fileName)
<<
//-----------------------------------
//#include <%fileName%>
//-----------------------------------
>>
else
txtCode
end wrapIntoExtraFileIfModelTooBig;
// SECTION: SIMULATION TARGET, C# FILE SPECIFIC TEMPLATES
template simulationFile(SimCode simCode) ::=
match simCode
case SIMCODE(modelInfo = MODELINFO(__)) then
<<
// Simulation code for <%dotPath(modelInfo.name)%> generated by the OpenModelica Compiler.
using System;
using System.Collections.Generic;
using Bodylight.Solvers;
namespace Bodylight.Models<%modelNameSpace(modelInfo.name)%>
{
public partial class <%lastIdentOfPath(modelInfo.name)%> : DAESystem
{
<%modelDescription(modelInfo, simCode)%>
<%wrapIntoExtraFileIfModelTooBig(
<<
<%modelMetadata(modelInfo, simCode)%>
<%sharedLiteralDefinitions(literals, simCode)%>
>>
, "MetaData", simCode)
%>
<%let fbody = simulationFunctionsBody(simCode)
if fbody then
<<
#region Functions
<%fbody%>
#endregion
>>
else "//** No functions **"
%>
<%functionCallExternalObjectConstructors(extObjInfo, simCode)%>
<%functionCallExternalObjectDestructors(extObjInfo, simCode)%>
<% wrapIntoExtraFileIfModelTooBig(
<<
<%functionNonlinearResiduals(initialEquations, contextAlgloopInitialisation, simCode)%>
<%functionNonlinearResiduals(parameterEquations, contextAlgloop, simCode)%>
<%functionNonlinearResiduals(allEquations, contextAlgloop, simCode)%>
<%functionInitialNonLinearSystems(initialEquations, parameterEquations, allEquations, simCode)%>
>>
, "Residuals", simCode)
%>
<%functionInput(modelInfo, simCode)%>
<%functionOutput(modelInfo, simCode)%>
<%functionInitSample(timeEvents, simCode)%>
<%functionStoreDelayed(simCode)%>
<%functionUpdateBoundStartValues(startValueEquations, simCode)%>
<% wrapIntoExtraFileIfModelTooBig(
functionInitialEquations(initialEquations, simCode),
"InitialEquations", simCode) %>
<%functionUpdateBoundParameters(parameterEquations, simCode)%>
<% wrapIntoExtraFileIfModelTooBig(
functionODE(odeEquations, simCode),
"FunctionODE", simCode) %>
<%functionAlgebraic(algebraicEquations, simCode)%>
<% wrapIntoExtraFileIfModelTooBig(
functionDAE(allEquations, simCode),
"FunctionDAE", simCode) %>
<%functionZeroCrossing(zeroCrossings, simCode)%>
<%functionRelations(relations, simCode)%>
<%functionCheckForDiscreteChanges(simCode)%>
<%/*functionAssertsforCheck(algorithmAndEquationAsserts)*/%>
}
}
>>
end simulationFile;
template modelNameSpace(Path modelName) ::=
match modelName
case QUALIFIED(__) then '.<%name%><%modelNameSpace(path)%>'
case FULLYQUALIFIED(__) then modelNameSpace(path)
end modelNameSpace;
template lastIdentOfPath(Path modelName) ::=
match modelName
case QUALIFIED(__) then lastIdentOfPath(path)
case IDENT(__) then name
case FULLYQUALIFIED(__) then lastIdentOfPath(path)
end lastIdentOfPath;
template sharedLiteralDefinitions(list<Exp> literals, SimCode simCode)
::=
<<
<%literals |> literal hasindex i0 fromindex 0 => literalExpConst(literal, i0, simCode) ; separator="\n";empty%>
>>
end sharedLiteralDefinitions;
template literalExpConst(Exp lit, Integer index, SimCode simCode)
::=
let name = '_OMC_LIT<%index%>'
match lit
case SCONST(__) then
let escstr = Util.escapeModelicaStringToCString(string)
<<
const string <%name%> = "<%Util.escapeModelicaStringToCString(string)%>";
>>
case lit as MATRIX(ty=ty as T_ARRAY(__))
case lit as ARRAY(ty=ty as T_ARRAY(__)) then
let arrType = expTypeArray(ty, listLength(getDimensionSizes(ty)))
let sty = expTypeShort(ty)
let dims = (getDimensionSizes(ty) |> dim => dim ;separator=", ")
let data = flattenArrayExpToList(lit) |> exp => literalExpConstArrayVal(exp) ; separator=", "
<<
static <%arrType%> <%name%> = new <%arrType%>(<%dims%>,-1, new <%sty%>[] { <%data%> });
>>
else error(sourceInfo(), 'literalExpConst failed: <%ExpressionDumpTpl.dumpExp(lit,"\"")%>')
end literalExpConst;
//should be identical to call daeExp()
//but it is more specific, maybe can catch an illegal exp which is expected to be a constant
template literalExpConstArrayVal(Exp lit)
::=
match lit
case ICONST(__) then integer
case BCONST(__) then if bool then "true" else "false"
case RCONST(__) then real
case ENUM_LITERAL(__) then '<%index%>/*ENUM:<%dotPath(name)%>*/'
case SHARED_LITERAL(__) then '_OMC_LIT<%index%>'
else error(sourceInfo(), 'literalExpConstArrayVal failed: <%ExpressionDumpTpl.dumpExp(lit,"\"")%>')
end literalExpConstArrayVal;
template simulationFunctionsBody(SimCode simCode) ::=
match simCode
case SIMCODE(modelInfo = modelInfo as MODELINFO(__)) then
(modelInfo.functions |> fn => match fn
case FUNCTION(__) then functionBodyRegularFunction(fn, simCode)
case EXTERNAL_FUNCTION(__) then functionBodyExternalFunction(fn, simCode) //'EXTERNAL_FUN_NOT_IMPLEMETED(name=<%dotPath(name)%>)'
case RECORD_CONSTRUCTOR(__) then 'RECORD_CONSTRUCTOR_NOT_IMPLEMENTED(name=<%dotPath(name)%>)'
else "UNKNOWN_FUNCTION"
;separator="\n")
end simulationFunctionsBody;
/*
//not used now
template simulationFunctionsFile(SimCode simCode) ::=
match simCode
case SIMCODE(modelInfo = MODELINFO(__)) then
<<
// Simulation functions code for <%modelInfo.name%> generated by the OpenModelica Compiler.
using System;
using Bodylight.Solvers;
namespace Bodylight.Models
{
public partial class <%dotPath(modelInfo.name)%> : DAESystem
{
<%simulationFunctionsBody(simCode)%>
}
}
>>
end simulationFunctionsFile;
*/
template recordDeclaration(RecordDeclaration recDecl, SimCode simCode)
"Generates structs for a record declaration."
::=
match recDecl
case RECORD_DECL_FULL(__) then
<<
struct <%name%> {
<%variables |> var as VARIABLE(__) => '<%varType(var)%> <%crefStr(var.name,simCode)%>;' ;separator="\n"%>
};
>>
case RECORD_DECL_DEF(__) then "RECORD_DECL_DEF_NOT_SUPPORTED"
else "UNKNOWN_RECORD_DECL_"
end recordDeclaration;
template functionBodyRegularFunction(Function fn, SimCode simCode)
"Generates the body for a Modelica/MetaModelica function."
::=
match fn
case FUNCTION(__) then
let()= System.tmpTickReset(1)
let fname = underscorePath(name)
let retType = match outVars //a hack, only one output var for now
case fv :: _ then varType(fv)
else "void"
let retVar = match outVars
case (fv as VARIABLE(__)) :: _ then crefStr(fv.name,simCode)
let varInits = variableDeclarations |> var => varInit(var, simCode)
;separator="\n" //TODO:special end of line,see varInit
let bodyPart = funStatement(body, simCode)
<<
<%retType%> _<%fname%>(<%functionArguments |> var => funArgDefinition(var,simCode) ;separator=", "%>)
{
<%varInits%>
<%bodyPart%>
_return:
<%if outVars then 'return <%retVar%>;'%>
}
>>
end functionBodyRegularFunction;
template functionBodyExternalFunction(Function fn, SimCode simCode)
"Generates the body for an external function (just a wrapper)."
::=
match fn
case efn as EXTERNAL_FUNCTION(__) then
let()= System.tmpTickReset(1)
let fname = underscorePath(name)
let retType = match outVars
case fv :: _ then varType(fv)
else "void"
let &preExp = buffer "" /*BUFD*/
let callPart = //extFunCall(fn, &preExp /*BUFC*/, &varDecls /*BUFD*/)
let args = (extArgs |> arg => extArg(arg, &preExp, simCode) ;separator=", ")
let lib = hackGetFirstExternalFunctionLib(libs) // match libs case fnLib::_ then fnLib else "NO_EXT_LIB"
'Bodylight.Solvers.ExternalLibraries.<%lib%>.<%extName%>(<%args%>);'
<<
static <%retType%> _<%fname%>(<%funArgs |> var => funArgDefinition(var,simCode) ;separator=", "%>)
{
<%preExp%>
<%if outVars then "return "
%><%callPart%>
}
>>
end functionBodyExternalFunction;
template extArg(SimExtArg extArg, Text &preExp, SimCode simCode)
"Helper to extFunCall."
::=
match extArg
case SIMEXTARG(cref=c, outputIndex=oi, isArray=true, type_=t) then
let name = if oi then 'NOT_SUPPORTED_out.targ<%oi%>' else crefStr(c,simCode)
name
//let shortTypeStr = expTypeShort(t)
//'(<%extType(t,isInput,true)%>) data_of_<%shortTypeStr%>_array(&(<%name%>))'
case SIMEXTARG(cref=c, isInput=ii, outputIndex=0, type_=t) then
let cr = crefStr(c,simCode)
cr
case SIMEXTARG(cref=c, isInput=ii, outputIndex=oi, type_=t) then
'NOT_SUPPORTED_ext<%oi%>'
case SIMEXTARGEXP(__) then
daeExp(exp, contextFunction, &preExp, simCode)
case SIMEXTARGSIZE(cref=c) then
let name = if outputIndex then 'NOT_SUPPORTED_SIZE_out.targ<%outputIndex%>' else crefStr(c,simCode)
match exp
case ICONST(__) then
'<%name%>.size<%integer%>'
else
'<%name%>.size(<%daeExp(exp, contextFunction, &preExp, simCode)%>)'
end extArg;
template varInit(Variable var, SimCode simCode)
"Generates code to initialize variables."
::=
match var
case var as VARIABLE(__) then
if instDims then
let varName = crefStr(var.name,simCode)
let &preDimsExp = buffer ""
let instDimsInit = (var.instDims |> exp =>
daeExp(exp, contextFunction, &preDimsExp, simCode)
;separator=", ")
<<
<%preDimsExp%>
var <%varName%> = new <%expTypeArray(var.ty,listLength(instDims))%>(<%instDimsInit%>);<%
//special \n solution ... the new line is dependent on this line, but the varInit as a whole does not put \n
match var.value case SOME(CREF(componentRef = cr)) then
'<%\n%><%varName%>.CopyFrom(<%crefStr(cr,simCode)%>);'
%>
>>
else
<<
<%varType(var)%> <%crefStr(var.name,simCode)%>;
>>
else "UNSUPPORTED_VARIABLE_varInit"
end varInit;
template funArgDefinition(Variable var, SimCode simCode)
::=
match var
case VARIABLE(__) then '<%varType(var)%> <%crefStr(name,simCode)%>'
case FUNCTION_PTR(__) then 'funArgDefinition_UNSUPPORTED_fnptr <%name%>'
else "UNSUPPORTED_VARIABLE_funArgDefinition"
end funArgDefinition;
template funStatement(list<DAE.Statement> statementLst, SimCode simCode)
"Generates function statements."
::=
statementLst |> stmt => algStatement(stmt, contextFunction, simCode)
end funStatement;
constant String localRepresentationArrayDefines =
"var X = States; var Xd = StatesDerivatives; var Y = Algebraics; var YI = AlgebraicsInt; var YB = AlgebraicsBool;
var P = Parameters; var PI = ParametersInt; var PB = ParametersBool; var PS = ParametersString; var EO = ExternalObjects;
var preX = PreStates; var preXd = PreStatesDerivatives; var preY = PreAlgebraics; var preYI = PreAlgebraicsInt; var preYB = PreAlgebraicsBool;
var mathEVPre = MathEventsValuePre;
/*TODO: HACK FOR non-time varying params*/ var preP = P; var prePI = PI; var prePB = PB;";
template modelDescription(ModelInfo modelInfo, SimCode simCode) ::=
match modelInfo
case MODELINFO(varInfo = VARINFO(__), vars = SIMVARS(__)) then
<<
#region Model description
const int
NG = <%varInfo.numZeroCrossings%>,
NREL = <%varInfo.numRelations%>,
NM = <%varInfo.numMathEventFunctions%>,
NG_SAM = <%varInfo.numTimeEvents%>,
NX = <%varInfo.numStateVars%>,
NY = <%varInfo.numAlgVars%> + <%varInfo.numDiscreteReal%>,
NA = <%varInfo.numAlgAliasVars%>, // number of alias variables
NP = <%varInfo.numParams%>,
NO = <%varInfo.numOutVars%>,
NI = <%varInfo.numInVars%>,
NEXT = <%varInfo.numExternalObjects%>,
//NFUNC = <%listLength(functions)%>, // number of functions used by the simulation
NYSTR = <%varInfo.numStringAlgVars%>,
NASTR = <%varInfo.numStringAliasVars%>, // number of alias string variables
NYI = <%varInfo.numIntAlgVars%>,
NAI = <%varInfo.numIntAliasVars%>, // number of alias int variables
NYB = <%varInfo.numBoolAlgVars%>,
NAB = <%varInfo.numBoolAliasVars%>, // number of alias bool variables
NPI = <%varInfo.numIntParams%>,
NPB = <%varInfo.numBoolParams%>,
NPSTR = <%varInfo.numStringParamVars%>,
NAAll = NA+NAI+NAB+NASTR, // number of all aliases
NLS = <%varInfo.numLinearSystems%>,
NNLS = <%varInfo.numNonLinearSystems%>,
NMIXS = <%varInfo.numMixedSystems%>;
private class <%lastIdentOfPath(name)%>Metadata : DAESystemMetadata
{
public override int ZeroCrossingsCount { get { return NG; } }
public override int RelationsCount { get { return NREL; } }
public override int MathEventsCount { get { return NM; } }
public override int SampleTypesCount { get { return NG_SAM; } }
public override int OutputsCount { get { return NO; } }
public override int InputsCount { get { return NI; } }
public override int ExternalObjectsCount { get { return NEXT; } }
public override int LinearSystemsCount { get { return NLS; } }
public override int NonLinearSystemsCount { get { return NNLS; } }
public override int MixedSystemsCount { get { return NMIXS; } }
public <%lastIdentOfPath(name)%>Metadata(VarData[][] varData, AliasVarData[] aliasVarData, Dictionary<string, int> fullVarDictionary,
Dictionary<int, double> startValues, Dictionary<int, int> startValuesInt, Dictionary<int, bool> startValuesBool,
string[] startParameterString)
: base("<%dotPath(name)%>", varData, aliasVarData, fullVarDictionary, startValues, startValuesInt, startValuesBool, startParameterString)
{}
public override DAESystem NewSystem()
{
return new <%lastIdentOfPath(name)%>();
}
}
public static readonly DAESystemMetadata SystemMetadata;
public <%lastIdentOfPath(name)%>() : base(<%lastIdentOfPath(name)%>.SystemMetadata)
{}
#endregion
>>
end modelDescription;
template modelMetadata(ModelInfo modelInfo, SimCode simCode) ::=
match modelInfo
case MODELINFO(varInfo = VARINFO(__), vars = SIMVARS(__)) then
<<
static <%lastIdentOfPath(name)%>() {
var varData = new VarData[(int)SimVarType.NonAliasTypesCnt][];
VarData[] vd;
<%{
varInfos("State", vars.stateVars, varInfo.numStateVars, simCode),
varInfos("StateDer", vars.derivativeVars, varInfo.numStateVars, simCode),
varInfosAlgebraic("Algebraic", vars.algVars, vars.discreteAlgVars, varInfo.numAlgVars, varInfo.numDiscreteReal, simCode),
//may be later:
//varInfos("Algebraic", vars.algVars, varInfo.numAlgVars, simCode),
//varInfos("AlgebraicDiscrete", vars.discreteAlgVars, varInfo.numDiscreteReal, simCode),
varInfos("AlgebraicInt", vars.intAlgVars, varInfo.numIntAlgVars, simCode),
varInfos("AlgebraicBool", vars.boolAlgVars, varInfo.numBoolAlgVars, simCode),
varInfos("AlgebraicString", vars.stringAlgVars, varInfo.numStringAlgVars, simCode),
varInfos("Parameter", vars.paramVars, varInfo.numParams, simCode),
varInfos("ParameterInt", vars.intParamVars, varInfo.numIntParams, simCode),
varInfos("ParameterBool", vars.boolParamVars, varInfo.numBoolParams, simCode),
varInfos("ParameterString", vars.stringParamVars, varInfo.numStringParamVars, simCode)
} ;separator="\n\n"%>
#region *** all aliases ***
var fvd = Bodylight.Solvers.SystemMetadata.SetupVariableNamesLookup(varData, NAAll);
var ad = new AliasVarData[NAAll];
<%{
aliasVarInfos("alias Algebraic", vars.aliasVars, /*varInfo.numAlgAliasVars,*/ "", simCode),
aliasVarInfos("alias AlgebraicInt", vars.intAliasVars, /*varInfo.numIntAliasVars,*/ "NA+", simCode),
aliasVarInfos("alias AlgebraicBool", vars.boolAliasVars, /*varInfo.numBoolAliasVars,*/ "NA+NAI+", simCode),
aliasVarInfos("alias AlgebraicString", vars.stringAliasVars, /*varInfo.numStringAliasVars,*/ "NA+NAI+NAB+", simCode)
} ;separator="\n\n"%>
#endregion
#region *** start values ***
var svs = new Dictionary<int, double>();
var svsI = new Dictionary<int, int>();
var svsB = new Dictionary<int, bool>();
var svsS = new string[NPSTR];
<%initVals("svs", "State", vars.stateVars, simCode)%>
<%initVals("svs", "StateDer", vars.derivativeVars, simCode)%>
<%initVals("svs", "Algebraic", vars.algVars, simCode)%>
<%initVals("svs", "Algebraic", vars.discreteAlgVars, simCode)%>
<%initVals("svs", "Parameter", vars.paramVars, simCode)%>
<%initVals("svsI", "AlgebraicInt", vars.intAlgVars, simCode)%>
<%initVals("svsI", "ParameterInt", vars.intParamVars, simCode)%>
<%initVals("svsB", "AlgebraicBool", vars.boolAlgVars, simCode)%>
<%initVals("svsB", "ParameterBool", vars.boolParamVars, simCode)%>
// *** AlgebraicStrings not fully supported ***
<%/*initVals("AlgebraicString", vars.stringAlgVars, simCode)*/%>
<%initValsString("svsS", "ParameterString", vars.stringParamVars, simCode)%>
#endregion
SystemMetadata = new <%lastIdentOfPath(name)%>Metadata(varData, ad, fvd, svs, svsI, svsB, svsS);
}
>>
end modelMetadata;
template simVarTypeName(VarKind varKind, Type type_) ::=
match varKind
case VARIABLE(__) then "Algebraic" + simVarTypeNamePostfix(type_)
case STATE(__) then "State"
case STATE_DER(__) then "StateDer"
case DUMMY_DER(__) //then "Algebraic"
case DUMMY_STATE(__) then "Algebraic"
case DISCRETE(__) then 'Algebraic<%simVarTypeNamePostfix(type_)%>/*d*/'
case PARAM(__) then "Parameter" + simVarTypeNamePostfix(type_)
else error(sourceInfo(), "Unexpected simVarTypeName varKind")
//case EXTOBJ(__) then "EO"
//case CONST(__) then "CONST_VAR_KIND"
end simVarTypeName;
template simVarTypeNamePostfix(Type type_) ::=
match type_
case T_INTEGER(__) then "Int"
case T_REAL(__) then ""
case T_BOOL(__) then "Bool"
case T_STRING(__) then "String"
case T_ENUMERATION(__) then "/*Enum*/"
//case T_COMPLEX(__) then "Complex"
//case T_ARRAY(__) then "Array"
//case T_OTHER(__) then "Other"
else error(sourceInfo(), "Unknown simVarTypeNamePostfix")
end simVarTypeNamePostfix;
template varInfos(String regionName, list<SimVar> varsLst, Integer varsCnt, SimCode simCode) ::=
//if varsLst then
//we need all of them to initialize also empty arrays
<<
#region *** (<%varsCnt%>) <%regionName%> variable data ***
vd = new VarData[<%varsCnt%>];
<% varsLst |> sv as SIMVAR(__) =>
<<
vd[<%index%>] = new VarData("<%crefStrWithDerOnLast(name, simCode)%>", "<%Util.escapeModelicaStringToCString(comment)%>"<%noaliasSimVarInfoRest(sv)%>);
>>
;separator="\n"
%>
varData[(int)SimVarType.<%regionName%>] = vd;
#endregion<%\n%>
>>
end varInfos;
template varInfosAlgebraic(String regionName, list<SimVar> varsLstAlg, list<SimVar> varsLstDisc, Integer varsCntAlg, Integer varsCntDisc, SimCode simCode) ::=
//A hack to temorarily handle discrete algebraics
//TODO: fix it
//if varsLst then
//we need all of them to initialize also empty arrays
<<
#region *** (<%varsCntAlg%> + <%varsCntDisc%>) algebraic and discrete algebraic variable data ***
vd = new VarData[<%varsCntAlg%> + <%varsCntDisc%>];
<% varsLstAlg |> sv as SIMVAR(__) =>
<<
vd[<%index%>] = new VarData("<%crefStrWithDerOnLast(name, simCode)%>", "<%Util.escapeModelicaStringToCString(comment)%>"<%noaliasSimVarInfoRest(sv)%>);
>>
;separator="\n"
%>
<% varsLstDisc |> sv as SIMVAR(__) =>
<<
vd[<%varsCntAlg%> + <%index%>] = new VarData("<%crefStrWithDerOnLast(name, simCode)%>", "<%Util.escapeModelicaStringToCString(comment)%>"<%noaliasSimVarInfoRest(sv)%>);
>>
;separator="\n"
%>
varData[(int)SimVarType.<%regionName%>] = vd;
#endregion<%\n%>
>>
end varInfosAlgebraic;
//rather hacky ... when more attributes, use named members initalization
template noaliasSimVarInfoRest(SimVar simVar) ::=
match simVar
case sv as SIMVAR(__) then
if initialValue then
match nominalValue
case SOME(exp as RCONST(__)) then ', new SimVarAttributes(<%exp.real%>, true, <%sv.isFixed%>)'
case SOME(__) then error(sourceInfo(), "Unexpected expression for nominal value.")
else ', SimVarAttributes.DefaultUseStart<%if sv.isFixed then "Fixed"%>'
else
match nominalValue
case SOME(exp as RCONST(__)) then ', new SimVarAttributes(<%exp.real%>, false, <%sv.isFixed%>)'
case SOME(__) then "Error-other-nominal-value-than-real-constant-not-supported"
else if sv.isFixed then ", SimVarAttributes.DefaultFixed"
//else nothing ...
end noaliasSimVarInfoRest;
template aliasVarInfos(String regionName, list<SimVar> varsLst, /*Integer varsCnt,*/ String offset, SimCode simCode) ::=
if varsLst then
<<
#region *** (<%listLength(varsLst)%>) <%regionName%> variable infos ***
<% varsLst |> sv as SIMVAR(__) hasindex i0 =>
let strNameCmt = '"<%crefStrWithDerOnLast(name, simCode)%>", "<%Util.escapeModelicaStringToCString(comment)%>"'
let aliasLookup =
match aliasvar
case NOALIAS(__) then
error(sourceInfo(), "Unexpected non-alias variable amongst aliases.")
case ALIAS(__) then
'fvd["<%crefStrWithDerOnLast(varName, simCode)%>"]'
case NEGATEDALIAS(__) then
'-fvd["<%crefStrWithDerOnLast(varName, simCode)%>"]'
<<
ad[<%offset%><%i0%>] = new AliasVarData("<%crefStrWithDerOnLast(name, simCode)%>", "<%Util.escapeModelicaStringToCString(comment)%>", <%aliasLookup%>);
>>
;separator="\n"
%>
#endregion<%\n%>
>>
end aliasVarInfos;
//template nominalVal(DAE.Exp nomExp) ::=
// match nomExp
// case RCONST(__) then real
// else 'other nominal value than real const not supported'
//end nominalVal;
template initVals(String arrName, String typName, list<SimVar> varsLst, SimCode simCode) ::=
if varsLst then
<<
#region **** <%typName%> start values *****
<%
varsLst |> sv as SIMVAR(__) =>
match initialValue
case SOME(v) then
match v
case ICONST(__)
case RCONST(__)
case SCONST(__)
case BCONST(__)
case ENUM_LITERAL(__) then
let &preExp = buffer "" //dummy ... the value should be always a constant
match daeExp(v, contextOther, &preExp, simCode)
case vStr as "0"
case vStr as "0.0"
case vStr as "false"
case vStr as "(0)" then
'//<%arrName%>[<%sv.index%>] = <%vStr%>; //<%crefStr(sv.name, simCode)%> --> zero val'
//case "true" then //a hack for now
// '<%arrName%>[<%sv.index%>] = 1.0; //true //<%crefStr(sv.name, simCode)%>'
case vStr then
'<%arrName%>[(int)SimVarType.<%typName%>+(<%sv.index%><<4)] = <%vStr%>; //<%crefStr(sv.name, simCode)%>'
end match
else '//<%arrName%>[<%sv.index%>] = 0.0; //<%crefStr(sv.name, simCode)%> --> default val'
;separator="\n"
%>
#endregion
>>
end initVals;
template initValsString(String arrName, String typName, list<SimVar> varsLst, SimCode simCode) ::=
if varsLst then
<<
#region **** (<%listLength(varsLst)%>) <%typName%> start values *****
<%
varsLst |> sv as SIMVAR(__) =>
match initialValue
case SOME(v) then
let &preExp = buffer "" //dummy ... the value should be always a constant
let val = daeExp(v, contextOther, &preExp, simCode)
'<%arrName%>[<%sv.index%>] = <%val%>; //<%crefStr(sv.name, simCode)%>'
else '<%arrName%>[<%sv.index%>] = ""; //<%crefStr(sv.name, simCode)%> --> default val'
;separator="\n"
%>
#endregion
>>
end initValsString;
/*
template initFixed(list<SimVar> simVarLst, String varType, Boolean defaultIsTrue, SimCode simCode) ::=
simVarLst |> SIMVAR(__) =>
<<
<%if defaultIsTrue then (if isFixed then "//")
else (if not isFixed then "//")
%><%varType%>InitialFixed[<%index%>] = <%isFixed%>; /* <%crefStr(name, simCode)%> */
>>
;separator="\n"
end initFixed;
*/
template functionCallExternalObjectConstructors(ExtObjInfo extObjInfo, SimCode simCode)
"Generates external objects construction calls."
::=
match extObjInfo
case EXTOBJINFO(__) then
<<
public override void FunCallExternalObjectConstructors() {
<% localRepresentationArrayDefines %>
<% vars |> var as SIMVAR(initialValue=SOME(exp)) =>
let &preExp = buffer "" /*BUFD*/
let arg = daeExp(exp, contextOther, &preExp, simCode)
<<
<%preExp%>
<%cref(var.name, simCode)%> = <%arg%>;
>>
%>
<%aliases |> (var1, var2) => '<%cref(var1,simCode)%> = <%cref(var2,simCode)%>;' ;separator="\n"%>
}
>>
end functionCallExternalObjectConstructors;
template functionCallExternalObjectDestructors(ExtObjInfo extObjInfo, SimCode simCode)
"Generates external objects construction calls."
::=
match extObjInfo
case EXTOBJINFO(__) then
<<
public override void FunCallExternalObjectDestructors() {
<% localRepresentationArrayDefines %>
<% vars |> var as SIMVAR(varKind=ext as EXTOBJ(__)) =>
<<
_<%underscorePath(ext.fullClassName)%>_destructor(<%cref(var.name, simCode)%>);
>>
;separator="\n"
%>
}
>>
end functionCallExternalObjectDestructors;
template functionAlgebraic(list<list<SimEqSystem>> algebraicEquations, SimCode simCode) ::=
let()= System.tmpTickReset(1)
<<
public override void FunAlgebraics()
{
<% localRepresentationArrayDefines %>
var preRels = PreRelations;
<% List.flatten(algebraicEquations) |> it => equation_(it,contextSimulationNonDiscrete, simCode) ;separator="\n"%>
}
>>
end functionAlgebraic;
template functionInput(ModelInfo modelInfo, SimCode simCode) ::=
match modelInfo
case MODELINFO(varInfo = VARINFO(__), vars = SIMVARS(__)) then
<<
public override void InputFun()
{
<% localRepresentationArrayDefines %>
<%vars.inputVars |> SIMVAR(__) hasindex i0 =>
<<
<%cref(name, simCode)%> = inputVars[<%i0%>];
>> ;separator="\n"%>
}
>>
end functionInput;
template functionOutput(ModelInfo modelInfo, SimCode simCode) ::=
match modelInfo
case MODELINFO(varInfo = VARINFO(__), vars = SIMVARS(__)) then
<<
public override void OutputFun()
{
<% localRepresentationArrayDefines %>
// * not yet
<%vars.outputVars |> SIMVAR(__) hasindex i0 =>
<<
//outputVars[<%i0%>] = <%cref(name, simCode)%>;
>> ;separator="\n"%>
}
>>
end functionOutput;
template functionInitSample(list<BackendDAE.TimeEvent> timeEvents, SimCode simCode)
"Generates function initSample() in simulation file."
::=
/* Initializes the raw time events of the simulation using the now
calcualted parameters. */
<<
public override void FunSampleInit()
{
<% localRepresentationArrayDefines %>
var SA = SampleHeap.Samples;
<%(timeEvents |> timeEvent =>
match timeEvent
case SAMPLE_TIME_EVENT(__) then
let &preExp = buffer "" /*BUFD*/
let startE = daeExp(startExp, contextOther, &preExp, simCode)
let intervalE = daeExp(intervalExp, contextOther, &preExp, simCode)
<<
<%preExp%>
/* $P$sample<%index%> */
SA[i++] = new OneSample(<%intervalE%>, <%startE%>, <%intSub(index, 1)%>, false);
>>
else ''
)%>
}
>>
end functionInitSample;
template functionDAE(list<SimEqSystem> allEquationsPlusWhen, SimCode simCode)
::=
let()= System.tmpTickReset(1)
<<
public override bool FunDAE()
{
<% localRepresentationArrayDefines %>
var rels = Relations; var preRels = PreRelations; var relsHE = RelationsHysteresisEnabled; var relsZC = RelationsZeroCrossing;
var needToIterate = false;
<%allEquationsPlusWhen |> eq => equation_(eq, contextSimulationDiscrete, simCode) ;separator="\n"%>
return needToIterate;
}
>>
end functionDAE;
template whenConditions(list<ComponentRef> conditions, SimCode simCode)
" Generates reinit statemeant"
::=
//if conditions then
(conditions |> cr => '<%cref(cr, simCode)%> && !<%preCref(cr, simCode)%> /* edge */';separator=" || ")
//else "false"
end whenConditions;
template infoArgs(builtin.SourceInfo info)
::=
match info
case SOURCEINFO(__) then '"<%fileName%>",<%lineNumberStart%>,<%columnNumberStart%>,<%lineNumberEnd%>,<%columnNumberEnd%>,<%if isReadOnly then 1 else 0%>'
end infoArgs;
template assertCommon(Exp condition, Exp message, builtin.SourceInfo info, Context context, SimCode simCode)
"Generates an assert statement."
::=
let &preExpCond = buffer ""
let &preExpMsg = buffer ""
let condVar = daeExp(condition, context, &preExpCond, simCode)
let msgVar = daeExp(message, context, &preExpMsg, simCode)
<<
<%preExpCond%>
if (!<%condVar%>) {
<%preExpMsg%>
//<%infoArgs(info)%>
throw new Exception(<%msgVar%>);
}
>>
end assertCommon;
template functionZeroCrossing(list<ZeroCrossing> zeroCrossingLst, SimCode simCode) ::=
let()= System.tmpTickReset(1)
<<
public override void FunZeroCrossings(double time, double[] gout) //TODO:??time in original is *t only ... how is it called?
{
<% localRepresentationArrayDefines %>
var rels = Relations; var relsHE = RelationsHysteresisEnabled; var relsZC = RelationsZeroCrossing;
<%zeroCrossingLst |> ZERO_CROSSING(__) hasindex i0 =>
let &preExp = buffer ""
let zc = zeroCrossing(relation_, &preExp, simCode)
<<
//ZC for: <%ExpressionDumpTpl.dumpExp(relation_,"\"")%>
<%preExp%>
gout[<%i0%>] = <%zc%>;
>>
;separator="\n"%>
}
>>
end functionZeroCrossing;
template zeroCrossing(Exp zcExp, Text &preExp, SimCode simCode) ::=
match zcExp
case RELATION(index=-1) then
//probably a discrete only relation (e.g., with parameter against a constant)
//should be used only in a logical expression (not a proper zero crossing)
//going like logical unary only
//no need for hysteresis there as it should be constant during continuous intervals
let e1 = daeExp(zcExp, contextZeroCross, &preExp, simCode)
'(<%e1%>)?1:-1'
case RELATION(__) then
let e1 = daeExp(exp1, contextZeroCross, &preExp, simCode)
let e2 = daeExp(exp2, contextZeroCross, &preExp, simCode)
zeroCrossingValue(zcExp, e1, e2)
case (LBINARY(exp1=CALL(path=IDENT(name="initial"), expLst={}), operator=OR(__) ))
case (LBINARY(exp1=LUNARY( operator=NOT(__),exp=CALL(path=IDENT(name="initial"), expLst={}) ), operator=AND(__) ))
then
'/*opt out initial()*/<%zeroCrossing(exp2, &preExp, simCode)%>'
case (LBINARY(__))
case (LUNARY(__))
then
let e1 = daeExp(zcExp, contextZeroCross, &preExp, simCode)
'(<%e1%>) ? 1:-1'
case CALL(path=IDENT(name="integer"), expLst={exp1, idx})
case CALL(path=IDENT(name="floor"), expLst={exp1, idx})
then
let e1 = daeExp(exp1, contextZeroCross, &preExp, simCode)
let indx = daeExp(idx, contextZeroCross, &preExp, simCode)
'(Math.Floor(<%e1%>) != mathEVPre[<%indx%>]) ? 1:-1'
case CALL(path=IDENT(name="ceil"), expLst={exp1, idx}) then
let e1 = daeExp(exp1, contextZeroCross, &preExp, simCode)
let indx = daeExp(idx, contextZeroCross, &preExp, simCode)
'(Math.Ceil(<%e1%>) != mathEVPre[<%indx%>]) ? 1:-1'
case CALL(path=IDENT(name="div"), expLst={exp1, exp2, idx}) then
let e1 = daeExp(exp1, contextZeroCross, &preExp, simCode)
let e2 = daeExp(exp2, contextZeroCross, &preExp, simCode)
let indx = daeExp(idx, contextZeroCross, &preExp, simCode)
'( (int)(<%e1%>/<%e2%>) != (int)mathEVPre[<%indx%>] ) ? 1:-1'
/** these were attemt to use Min/Max as "logical" zero crossing operators,
** but failed to work due to non-equivalence of g > 0 and -g <= 0
** when used in Min and Max ... it would work with both-sided epsilon on hysteresis (as C runtime uses),
** but not with epsilon only on the > side (to allow equality to be found precisely)
** so, sadly, this won't work ...
** instead, we should find every relation change and then decide if it is an event (a condition changed)
case (LBINARY(operator=AND(__))) then
<<Math.Min(
(<%zeroCrossing(exp1, &preExp, simCode)%>),
(<%zeroCrossing(exp2, &preExp, simCode)%>)
)>>
case (LBINARY(operator=OR(__))) then
<<Math.Max(
(<%zeroCrossing(exp1, &preExp, simCode)%>),
(<%zeroCrossing(exp2, &preExp, simCode)%>)
)>>
case (LUNARY(__)) then
let e1 = daeExp(zcExp, contextOther, &preExp, simCode)
//the very high number is to assure a good chance for root finding to take advantage of interpolation
//in cases this is combined via Min or Max with something else
'(<%e1%>)?1e12:-1e12'
**/
else
error(sourceInfo(), 'Unexpected zero crossing expression: <%ExpressionDumpTpl.dumpExp(zcExp,"\"")%>')
end zeroCrossing;
template zeroCrossingOpFunc(Operator it) ::=
match it
case LESS(__) then "Less"
case GREATER(__) then "Greater"
case LESSEQ(__) then "LessEq"
case GREATEREQ(__) then "GreaterEq"
case EQUAL(__) then "!!!Equal"
case NEQUAL(__) then "!!!NEqual"
else "!!!unsupported ZC operator!!!"
end zeroCrossingOpFunc;
template functionRelations(list<ZeroCrossing> relations, SimCode simCode) "template functionRelations
Generates function in simulation file.
This is a helper of template simulationFile."
::=
let &varDecls = buffer "" /*BUFD*/
//using only contextOther, here, only relation operands are genereted
let relationsCode = relationsTpl(relations, contextOther, simCode)
//let relationsCodeElse = relationsTpl(relations, contextOther, simCode)
<<
public override void FunUpdateRelations()
{
<% localRepresentationArrayDefines %>
var rels = Relations; var relsHE = RelationsHysteresisEnabled; var relsZC = RelationsZeroCrossing;
<%relationsCode%>
}
>>
end functionRelations;
template relationsTpl(list<ZeroCrossing> relations, Context context, SimCode simCode)
"Generates code for zero crossings."
::=
(relations |> ZERO_CROSSING(__) hasindex i0 =>
relationTpl(i0, relation_, context, simCode)
;separator="\n";empty)
end relationsTpl;
template relationTpl(Integer index1, Exp relationExp, Context context, SimCode simCode)
"Generates code for a zero crossing."
::=
match relationExp
case RELATION(__) then
let &preExp = buffer ""
let e1 = daeExp(exp1, context, &preExp, simCode)
let e2 = daeExp(exp2, context, &preExp, simCode)
<<
//relation[<%index%>]: <%ExpressionDumpTpl.dumpExp(relationExp,"\"")%>
<%preExp%>