/
CodegenFMU.tpl
3334 lines (3082 loc) · 156 KB
/
CodegenFMU.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/MetaModelica code to FMU
// code. They are used in the code generator phase of the compiler to write
// target code.
//
// There are one root template intended to be called from the code generator:
// translateModel. These template 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 CodegenFMU
import interface SimCodeTV;
import CodegenUtil.*;
import CodegenC.*; //unqualified import, no need the CodegenC is optional when calling a template; or mandatory when the same named template exists in this package (name hiding)
template translateModel(SimCode simCode, String FMUVersion, String FMUType)
"Generates C code and Makefile for compiling a FMU of a
Modelica model."
::=
match simCode
case sc as SIMCODE(modelInfo=modelInfo as MODELINFO(__)) then
let guid = getUUIDStr()
let target = simulationCodeTarget()
let &dummy = buffer ""
let()= textFile(simulationLiteralsFile(fileNamePrefix, literals), '<%fileNamePrefix%>_literals.h')
let()= textFile(simulationFunctionsHeaderFile(fileNamePrefix, modelInfo.functions, recordDecls), '<%fileNamePrefix%>_functions.h')
let()= textFile(simulationFunctionsFile(fileNamePrefix, modelInfo.functions, dummy), '<%fileNamePrefix%>_functions.c')
let()= textFile(externalFunctionIncludes(sc.externalFunctionIncludes), '<%fileNamePrefix%>_includes.h')
let()= textFile(recordsFile(fileNamePrefix, recordDecls), '<%fileNamePrefix%>_records.c')
let()= textFile(simulationHeaderFile(simCode,guid), '<%fileNamePrefix%>_model.h')
let _ = generateSimulationFiles(simCode,guid,fileNamePrefix)
let()= textFile(simulationInitFile(simCode,guid), '<%fileNamePrefix%>_init.xml')
let x = covertTextFileToCLiteral('<%fileNamePrefix%>_init.xml','<%fileNamePrefix%>_init.c')
let()= textFile(fmumodel_identifierFile(simCode,guid,FMUVersion), '<%fileNamePrefix%>_FMU.c')
let()= textFile(fmuModelDescriptionFile(simCode,guid,FMUVersion,FMUType), 'modelDescription.xml')
let()= textFile(fmudeffile(simCode,FMUVersion), '<%fileNamePrefix%>.def')
let()= textFile(fmuMakefile(target,simCode,FMUVersion), '<%fileNamePrefix%>_FMU.makefile')
"" // Return empty result since result written to files directly
end translateModel;
template fmuModelDescriptionFile(SimCode simCode, String guid, String FMUVersion, String FMUType)
"Generates code for ModelDescription file for FMU target."
::=
match simCode
case SIMCODE(__) then
<<
<?xml version="1.0" encoding="UTF-8"?>
<%
if isFMIVersion20(FMUVersion) then fmi2ModelDescription(simCode,guid)
else fmiModelDescription(simCode,guid,FMUType)
%>
>>
end fmuModelDescriptionFile;
// Code for generating modelDescription.xml file for FMI 2.0 ModelExchange.
template fmi2ModelDescription(SimCode simCode, String guid)
"Generates code for ModelDescription file for FMU target."
::=
// <%UnitDefinitions(simCode)%>
// <%VendorAnnotations(simCode)%>
match simCode
case SIMCODE(__) then
<<
<fmiModelDescription
<%fmi2ModelDescriptionAttributes(simCode,guid)%>>
<%ModelExchange(simCode)%>
<%TypeDefinitions(modelInfo, "2.0")%>
<LogCategories>
<Category name="logEvents" />
<Category name="logSingularLinearSystems" />
<Category name="logNonlinearSystems" />
<Category name="logDynamicStateSelection" />
<Category name="logStatusWarning" />
<Category name="logStatusDiscard" />
<Category name="logStatusError" />
<Category name="logStatusFatal" />
<Category name="logStatusPending" />
<Category name="logAll" />
<Category name="logFmi2Call" />
</LogCategories>
<%DefaultExperiment(simulationSettingsOpt)%>
<%ModelVariables(modelInfo, "2.0")%>
<%ModelStructureHelper(modelStructure)%>
</fmiModelDescription>
>>
end fmi2ModelDescription;
template fmi2ModelDescriptionAttributes(SimCode simCode, String guid)
"Generates code for ModelDescription file for FMU target."
::=
match simCode
case SIMCODE(modelInfo = MODELINFO(varInfo = vi as VARINFO(__), vars = SIMVARS(stateVars = listStates))) then
let fmiVersion = '2.0'
let modelName = dotPath(modelInfo.name)
let description = modelInfo.description
let generationTool= 'OpenModelica Compiler <%getVersionNr()%>'
let generationDateAndTime = xsdateTime(getCurrentDateTime())
let variableNamingConvention = 'structured'
let numberOfEventIndicators = vi.numZeroCrossings
<<
fmiVersion="<%fmiVersion%>"
modelName="<%modelName%>"
guid="{<%guid%>}"
description="<%description%>"
generationTool="<%generationTool%>"
generationDateAndTime="<%generationDateAndTime%>"
variableNamingConvention="<%variableNamingConvention%>"
numberOfEventIndicators="<%numberOfEventIndicators%>"
>>
end fmi2ModelDescriptionAttributes;
template ModelExchange(SimCode simCode)
"Generates ModelExchange code for ModelDescription file for FMU target."
::=
match simCode
case SIMCODE(__) then
let modelIdentifier = modelNamePrefix(simCode)
<<
<ModelExchange
modelIdentifier="<%modelIdentifier%>">
</ModelExchange>
>>
end ModelExchange;
template ScalarVariableAttribute2(SimVar simVar)
"Generates code for ScalarVariable Attribute file for FMU 2.0 target."
::=
match simVar
case SIMVAR(__) then
let valueReference = '<%System.tmpTick()%>'
let description = if comment then 'description="<%Util.escapeModelicaStringToXmlString(comment)%>"'
let variability = getVariability2(varKind, type_)
let caus = getCausality2(causality, varKind, isValueChangeable)
let initial = getInitialType(varKind, initialValue, causality, isValueChangeable)
<<
name="<%System.stringReplace(crefStrNoUnderscore(name),"$", "_D_")%>"
valueReference="<%valueReference%>"
<%description%>
variability="<%variability%>"
causality="<%caus%>"
initial="<%initial%>"
>>
end ScalarVariableAttribute2;
template getVariability2(VarKind varKind, DAE.Type type_)
"Returns the variability Attribute of ScalarVariable."
::=
match varKind
case DISCRETE(__) then "discrete"
case PARAM(__) then "fixed"
/*case PARAM(__) then "tunable"*/ /*TODO! Don't know how tunable variables are represented in OpenModelica.*/
case CONST(__) then "constant"
else
match type_
case T_REAL(__) then "continuous"
else "discrete"
end getVariability2;
template getCausality2(Causality c, VarKind varKind, Boolean isValueChangeable)
"Returns the Causality Attribute of ScalarVariable."
::=
match c
case NONECAUS(__) then getCausality2Helper(varKind, isValueChangeable)
case INTERNAL(__) then getCausality2Helper(varKind, isValueChangeable)
case OUTPUT(__) then "output"
case INPUT(__) then "input"
/*TODO! Handle "independent" causality.*/
else "local"
end getCausality2;
template getCausality2Helper(VarKind varKind, Boolean isValueChangeable)
::=
match varKind
case PARAM(__) then if isValueChangeable then "parameter" else "calculatedParameter"
else "local"
end getCausality2Helper;
template getInitialType(VarKind varKind, Option<DAE.Exp> initialValue, Causality c, Boolean isValueChangeable)
"Returns the Initial Attribute of ScalarVariable."
::=
match c
case INPUT(__) then "approx"
else
match initialValue
case SOME(exp) then
match varKind
case STATE_DER(__) then "calculated"
case PARAM(__) then if isValueChangeable then "exact" else "calculated"
else "approx"
else "calculated"
end getInitialType;
template ScalarVariableType2(SimVar simvar, list<SimVar> stateVars)
"Generates code for ScalarVariable Type file for FMU 2.0 target.
- Don't generate the units for now since it is wrong. If you generate a unit attribute here then we must add the UnitDefinitions tag section also.
"
::=
match simvar
case SIMVAR(__) then
match type_
case T_REAL(__) then '<Real<%ScalarVariableTypeCommonAttribute2(simvar, stateVars)%>/>'
case T_INTEGER(__) then '<Integer<%ScalarVariableTypeCommonAttribute2(simvar, stateVars)%>/>'
case T_BOOL(__) then '<Boolean<%ScalarVariableTypeCommonAttribute2(simvar, stateVars)%>/>'
case T_STRING(__) then '<String<%ScalarVariableTypeCommonAttribute2(simvar, stateVars)%>/>'
case T_ENUMERATION(__) then '<Enumeration declaredType="<%Absyn.pathString2NoLeadingDot(path, ".")%>"<%ScalarVariableTypeCommonAttribute2(simvar, stateVars)%>/>'
else 'UNKOWN_TYPE'
end ScalarVariableType2;
template ScalarVariableTypeCommonAttribute2(SimVar simvar, list<SimVar> stateVars)
"Generates code for ScalarVariable Type file for FMU 2.0 target."
::=
match simvar
case SIMVAR(varKind = varKind, initialValue = initialValue, isValueChangeable = isValueChangeable, index = index) then
match varKind
case STATE_DER(__) then ' derivative="<%getStateSimVarIndexFromIndex(stateVars, index)%>"'
case PARAM(__) then if isValueChangeable then '<%StartString2(simvar)%><%MinString2(simvar)%><%MaxString2(simvar)%><%NominalString2(simvar)%>' else '<%MinString2(simvar)%><%MaxString2(simvar)%><%NominalString2(simvar)%>'
else '<%StartString2(simvar)%><%MinString2(simvar)%><%MaxString2(simvar)%><%NominalString2(simvar)%>'
end ScalarVariableTypeCommonAttribute2;
template StartString2(SimVar simvar)
::=
match simvar
case SIMVAR(initialValue = initialValue, causality = causality, type_ = type_) then
match initialValue
case SOME(e as ICONST(__)) then ' start="<%initValXml(e)%>"'
case SOME(e as RCONST(__)) then ' start="<%initValXml(e)%>"'
case SOME(e as SCONST(__)) then ' start="<%initValXml(e)%>"'
case SOME(e as BCONST(__)) then ' start="<%initValXml(e)%>"'
case SOME(e as ENUM_LITERAL(__)) then ' start="<%initValXml(e)%>"'
else
match causality
case INPUT(__) then ' start="<%initDefaultValXml(type_)%>"'
else ''
end StartString2;
template MinString2(SimVar simvar)
::=
match simvar
case SIMVAR(minValue = minValue) then
match minValue
case SOME(e as ICONST(__)) then ' min="<%initValXml(e)%>"'
case SOME(e as RCONST(__)) then ' min="<%initValXml(e)%>"'
case SOME(e as SCONST(__)) then ' min="<%initValXml(e)%>"'
case SOME(e as BCONST(__)) then ' min="<%initValXml(e)%>"'
case SOME(e as ENUM_LITERAL(__)) then ' min="<%initValXml(e)%>"'
else ''
end MinString2;
template MaxString2(SimVar simvar)
::=
match simvar
case SIMVAR(maxValue = maxValue) then
match maxValue
case SOME(e as ICONST(__)) then ' max="<%initValXml(e)%>"'
case SOME(e as RCONST(__)) then ' max="<%initValXml(e)%>"'
case SOME(e as SCONST(__)) then ' max="<%initValXml(e)%>"'
case SOME(e as BCONST(__)) then ' max="<%initValXml(e)%>"'
case SOME(e as ENUM_LITERAL(__)) then ' max="<%initValXml(e)%>"'
else ''
end MaxString2;
template NominalString2(SimVar simvar)
::=
match simvar
case SIMVAR(nominalValue = nominalValue) then
match nominalValue
case SOME(e as RCONST(__)) then ' nominal="<%initValXml(e)%>"'
else ''
end NominalString2;
// Code for generating modelDescription.xml file for FMI 1.0 ModelExchange.
template fmiModelDescription(SimCode simCode, String guid, String FMUType)
"Generates code for ModelDescription file for FMU target."
::=
// <%UnitDefinitions(simCode)%>
// <%VendorAnnotations(simCode)%>
match simCode
case SIMCODE(__) then
<<
<fmiModelDescription
<%fmiModelDescriptionAttributes(simCode,guid)%>>
<%TypeDefinitions(modelInfo, "1.0")%>
<%DefaultExperiment(simulationSettingsOpt)%>
<%ModelVariables(modelInfo, "1.0")%>
<%if isFMICSType(FMUType) then Implementation()%>
</fmiModelDescription>
>>
end fmiModelDescription;
template fmiModelDescriptionAttributes(SimCode simCode, String guid)
"Generates code for ModelDescription file for FMU target."
::=
match simCode
case SIMCODE(modelInfo = MODELINFO(varInfo = vi as VARINFO(__), vars = SIMVARS(stateVars = listStates))) then
let fmiVersion = '1.0'
let modelName = dotPath(modelInfo.name)
let modelIdentifier = modelNamePrefix(simCode)
let description = modelInfo.description
let generationTool= 'OpenModelica Compiler <%getVersionNr()%>'
let generationDateAndTime = xsdateTime(getCurrentDateTime())
let variableNamingConvention = 'structured'
let numberOfContinuousStates = if intEq(vi.numStateVars,1) then statesnumwithDummy(listStates) else vi.numStateVars
let numberOfEventIndicators = vi.numZeroCrossings
<<
fmiVersion="<%fmiVersion%>"
modelName="<%modelName%>"
modelIdentifier="<%modelIdentifier%>"
guid="{<%guid%>}"
description="<%description%>"
generationTool="<%generationTool%>"
generationDateAndTime="<%generationDateAndTime%>"
variableNamingConvention="<%variableNamingConvention%>"
numberOfContinuousStates="<%numberOfContinuousStates%>"
numberOfEventIndicators="<%numberOfEventIndicators%>"
>>
end fmiModelDescriptionAttributes;
template statesnumwithDummy(list<SimVar> vars)
" return number of states without dummy vars"
::=
(vars |> var => match var case SIMVAR(__) then if stringEq(crefStr(name),"$dummy") then '0' else '1' ;separator="\n")
end statesnumwithDummy;
template xsdateTime(DateTime dt)
"YYYY-MM-DDThh:mm:ssZ"
::=
match dt
case DATETIME(__) then '<%year%>-<%twodigit(mon)%>-<%twodigit(mday)%>T<%twodigit(hour)%>:<%twodigit(min)%>:<%twodigit(sec)%>Z'
end xsdateTime;
template UnitDefinitions(SimCode simCode)
"Generates code for UnitDefinitions file for FMU target."
::=
match simCode
case SIMCODE(__) then
<<
<UnitDefinitions>
</UnitDefinitions>
>>
end UnitDefinitions;
template TypeDefinitions(ModelInfo modelInfo, String FMUVersion)
"Generates code for TypeDefinitions for FMU target."
::=
match modelInfo
case MODELINFO(vars=SIMVARS(__)) then
<<
<%TypeDefinitionsHelper(SimCodeUtil.getEnumerationTypes(vars), FMUVersion)%>
>>
end TypeDefinitions;
template TypeDefinitionsHelper(list<SimCodeVar.SimVar> vars, String FMUVersion)
"Generates code for TypeDefinitions for FMU target."
::=
if intGt(listLength(vars), 0) then
<<
<TypeDefinitions>
<%vars |> var => TypeDefinition(var,FMUVersion) ;separator="\n"%>
</TypeDefinitions>
>>
end TypeDefinitionsHelper;
template TypeDefinition(SimVar simVar, String FMUVersion)
::=
match simVar
case SIMVAR(__) then
<<
<%TypeDefinitionType(type_,FMUVersion)%>
>>
end TypeDefinition;
template TypeDefinitionType(DAE.Type type_, String FMUVersion)
"Generates code for TypeDefinitions Type file for FMU target."
::=
match type_
case T_ENUMERATION(__) then
if isFMIVersion20(FMUVersion) then
<<
<SimpleType name="<%Absyn.pathString2NoLeadingDot(path, ".")%>">
<Enumeration>
<%names |> name hasindex i0 fromindex 1 => '<Item name="<%name%>" value="<%i0%>"/>' ;separator="\n"%>
</Enumeration>
</SimpleType>
>>
else
<<
<Type name="<%Absyn.pathString2NoLeadingDot(path, ".")%>">
<EnumerationType>
<%names |> name => '<Item name="<%name%>"/>' ;separator="\n"%>
</EnumerationType>
</Type>
>>
end TypeDefinitionType;
template DefaultExperiment(Option<SimulationSettings> simulationSettingsOpt)
"Generates code for DefaultExperiment file for FMU target."
::=
match simulationSettingsOpt
case SOME(v) then
<<
<DefaultExperiment <%DefaultExperimentAttribute(v)%>/>
>>
end DefaultExperiment;
template DefaultExperimentAttribute(SimulationSettings simulationSettings)
"Generates code for DefaultExperiment Attribute file for FMU target."
::=
match simulationSettings
case SIMULATION_SETTINGS(__) then
<<
startTime="<%startTime%>" stopTime="<%stopTime%>" tolerance="<%tolerance%>"
>>
end DefaultExperimentAttribute;
template VendorAnnotations(SimCode simCode)
"Generates code for VendorAnnotations file for FMU target."
::=
match simCode
case SIMCODE(__) then
<<
<VendorAnnotations>
</VendorAnnotations>
>>
end VendorAnnotations;
template ModelVariables(ModelInfo modelInfo, String FMUVersion)
"Generates code for ModelVariables file for FMU target."
::=
match modelInfo
case MODELINFO(vars=SIMVARS(stateVars=stateVars)) then
<<
<ModelVariables>
<%System.tmpTickReset(0)%>
<%vars.stateVars |> var =>
ScalarVariable(stateVars, var, FMUVersion)
;separator="\n"%>
<%vars.derivativeVars |> var =>
ScalarVariable(stateVars, var, FMUVersion)
;separator="\n"%>
<%vars.algVars |> var =>
ScalarVariable(stateVars, var, FMUVersion)
;separator="\n"%>
<%vars.discreteAlgVars |> var =>
ScalarVariable(stateVars, var, FMUVersion)
;separator="\n"%>
<%vars.paramVars |> var =>
ScalarVariable(stateVars, var, FMUVersion)
;separator="\n"%>
<%vars.aliasVars |> var =>
ScalarVariable(stateVars, var, FMUVersion)
;separator="\n"%>
<%System.tmpTickReset(0)%>
<%vars.intAlgVars |> var =>
ScalarVariable(stateVars, var, FMUVersion)
;separator="\n"%>
<%vars.intParamVars |> var =>
ScalarVariable(stateVars, var, FMUVersion)
;separator="\n"%>
<%vars.intAliasVars |> var =>
ScalarVariable(stateVars, var, FMUVersion)
;separator="\n"%>
<%System.tmpTickReset(0)%>
<%vars.boolAlgVars |> var =>
ScalarVariable(stateVars, var, FMUVersion)
;separator="\n"%>
<%vars.boolParamVars |> var =>
ScalarVariable(stateVars, var, FMUVersion)
;separator="\n"%>
<%vars.boolAliasVars |> var =>
ScalarVariable(stateVars, var, FMUVersion)
;separator="\n"%>
<%System.tmpTickReset(0)%>
<%vars.stringAlgVars |> var =>
ScalarVariable(stateVars, var, FMUVersion)
;separator="\n"%>
<%vars.stringParamVars |> var =>
ScalarVariable(stateVars, var, FMUVersion)
;separator="\n"%>
<%vars.stringAliasVars |> var =>
ScalarVariable(stateVars, var, FMUVersion)
;separator="\n"%>
<%System.tmpTickReset(0)%>
<%externalFunctions(modelInfo)%>
</ModelVariables>
>>
end ModelVariables;
template ScalarVariable(list<SimVar> stateVars, SimVar simVar, String FMUVersion)
"Generates code for ScalarVariable file for FMU target."
::=
match simVar
case SIMVAR(__) then
if stringEq(crefStr(name),"$dummy") then
<<>>
else if stringEq(crefStr(name),"der($dummy)") then
<<>>
else if isFMIVersion20(FMUVersion) then
<<
<!-- Index of variable = "<%getVariableIndex(simVar)%>" -->
<ScalarVariable
<%ScalarVariableAttribute2(simVar)%>>
<%ScalarVariableType2(simVar, stateVars)%>
</ScalarVariable>
>>
else
<<
<ScalarVariable
<%ScalarVariableAttribute(simVar)%>>
<%ScalarVariableType(simVar)%>
</ScalarVariable>
>>
end ScalarVariable;
template ScalarVariableAttribute(SimVar simVar)
"Generates code for ScalarVariable Attribute file for FMU target."
::=
match simVar
case SIMVAR(__) then
let valueReference = '<%System.tmpTick()%>'
let variability = getVariability(varKind)
let description = if comment then 'description="<%Util.escapeModelicaStringToXmlString(comment)%>"'
let alias = getAliasVar(aliasvar)
let caus = getCausality(causality)
<<
name="<%System.stringReplace(crefStrNoUnderscore(name),"$", "_D_")%>"
valueReference="<%valueReference%>"
<%description%>
variability="<%variability%>"
causality="<%caus%>"
alias="<%alias%>"
>>
end ScalarVariableAttribute;
template getCausality(Causality c)
"Returns the Causality Attribute of ScalarVariable."
::=
match c
case NONECAUS(__) then "none"
case INTERNAL(__) then "internal"
case OUTPUT(__) then "output"
case INPUT(__) then "input"
end getCausality;
template getVariability(VarKind varKind)
"Returns the variability Attribute of ScalarVariable."
::=
match varKind
case DISCRETE(__) then "discrete"
case PARAM(__) then "parameter"
case CONST(__) then "constant"
else "continuous"
end getVariability;
template getAliasVar(AliasVariable aliasvar)
"Returns the alias Attribute of ScalarVariable."
::=
match aliasvar
case NOALIAS(__) then "noAlias"
/* We don't handle the alias and negatedAlias properly. If a variable is alias it must get the valueReference of the aliased variable. */
/*case ALIAS(__) then "alias"
case NEGATEDALIAS(__) then "negatedAlias"
*/
else "noAlias"
end getAliasVar;
template ScalarVariableType(SimVar simvar)
"Generates code for ScalarVariable Type file for FMU target."
::=
match simvar
case SIMVAR(__) then
match type_
case T_INTEGER(__) then '<Integer<%StartString(simvar)%>/>'
/* Don't generate the units for now since it is wrong. If you generate a unit attribute here then we must add the UnitDefinitions tag section also. */
case T_REAL(__) then '<Real<%StartString(simvar)/*%> <%ScalarVariableTypeRealAttribute(unit,displayUnit)*/%>/>'
case T_BOOL(__) then '<Boolean<%StartString(simvar)%>/>'
case T_STRING(__) then '<String<%StartString(simvar)%>/>'
case T_ENUMERATION(__) then '<Enumeration declaredType="<%Absyn.pathString2NoLeadingDot(path, ".")%>"<%StartString(simvar)%>/>'
else 'UNKOWN_TYPE'
end ScalarVariableType;
template StartString(SimVar simvar)
::=
match simvar
case SIMVAR(initialValue = initialValue, causality = causality, type_ = type_) then
match initialValue
case SOME(e as ICONST(__)) then ' start="<%initValXml(e)%>"'
case SOME(e as RCONST(__)) then ' start="<%initValXml(e)%>"'
case SOME(e as SCONST(__)) then ' start="<%initValXml(e)%>"'
case SOME(e as BCONST(__)) then ' start="<%initValXml(e)%>"'
case SOME(e as ENUM_LITERAL(__)) then ' start="<%initValXml(e)%>"'
else
match causality
case INPUT(__) then ' start="<%initDefaultValXml(type_)%>"'
else ''
end StartString;
template ScalarVariableTypeRealAttribute(String unit, String displayUnit)
"Generates code for ScalarVariable Type Real file for FMU target."
::=
let unit_ = if unit then 'unit="<%unit%>"'
let displayUnit_ = if displayUnit then 'displayUnit="<%displayUnit%>"'
<<
<%unit_%> <%displayUnit_%>
>>
end ScalarVariableTypeRealAttribute;
template externalFunctions(ModelInfo modelInfo)
"Generates external function definitions."
::=
match modelInfo
case MODELINFO(__) then
(functions |> fn => externalFunction(fn) ; separator="\n")
end externalFunctions;
template externalFunction(Function fn)
"Generates external function definitions."
::=
match fn
case EXTERNAL_FUNCTION(dynamicLoad=true) then
let fname = extFunctionName(extName, language)
<<
<ExternalFunction
name="<%fname%>"
valueReference="<%System.tmpTick()%>"/>
>>
end externalFunction;
template Implementation()
"Generate Co-simulation Implementation section"
::=
<<
<Implementation>
<CoSimulation_StandAlone>
<Capabilities
canHandleVariableCommunicationStepSize="true"
canHandleEvents="true"
canBeInstantiatedOnlyOncePerProcess="true"
canInterpolateInputs="true"
maxOutputDerivativeOrder="1"/>
</CoSimulation_StandAlone>
</Implementation>
>>
end Implementation;
template ModelStructure(SimCode simCode, list<JacobianMatrix> jacobianMatrixes)
"Generates Model Structure."
::=
<<
<ModelStructure>
//ModelStructureHelper(getFMIModelStructure(simCode, jacobianMatrixes))
</ModelStructure>
>>
end ModelStructure;
template ModelStructureHelper(Option<FmiModelStructure> fmiModelStructure)
"Helper function to ModelStructure."
::=
match fmiModelStructure
case SOME(fmistruct as FMIMODELSTRUCTURE(__)) then
<<
<ModelStructure>
<%ModelStructureOutputs(fmistruct.fmiOutputs)%>
<%ModelStructureDerivatives(fmistruct.fmiDerivatives)%>
<%ModelStructureInitialUnknowns(fmistruct.fmiInitialUnknowns)%>
</ModelStructure>
>>
else
<<
<ModelStructure>
</ModelStructure>
>>
end ModelStructureHelper;
template ModelStructureOutputs(FmiOutputs fmiOutputs)
"Generates Model Structure Outputs."
::=
match fmiOutputs
case FMIOUTPUTS(__) then
<<
<Outputs>
<%ModelStructureUnknowns(fmiUnknownsList)%>
</Outputs>
>>
end ModelStructureOutputs;
template ModelStructureDerivatives(FmiDerivatives fmiDerivatives)
"Generates Model Structure Derivatives."
::=
match fmiDerivatives
case FMIDERIVATIVES(__) then
<<
<Derivatives>
<%ModelStructureUnknowns(fmiUnknownsList)%>
</Derivatives>
>>
end ModelStructureDerivatives;
template ModelStructureInitialUnknowns(FmiInitialUnknowns fmiInitialUnknowns)
"Generates Model Structure InitialUnknowns."
::=
match fmiInitialUnknowns
case FMIINITIALUNKNOWNS(__) then
<<
<InitialUnknowns>
<%ModelStructureUnknowns(fmiUnknownsList)%>
</InitialUnknowns>
>>
end ModelStructureInitialUnknowns;
template ModelStructureUnknowns(list<FmiUnknown> fmiUnknownsList)
"Generates Model Structure Unknowns"
::=
<<
<%fmiUnknownsList |> fmiUnknown => FmiUnknownAttributes(fmiUnknown) ;separator="\n"%>
>>
end ModelStructureUnknowns;
template FmiUnknownAttributes(FmiUnknown fmiUnknown)
"Generates Model Structure Unknown attributes"
::=
match fmiUnknown
case FMIUNKNOWN(__) then
<<
<Unknown index="<%index%>"<%FmiUnknownDependencies(dependencies)%><%FmiUnknownDependenciesKind(dependenciesKind)%> />
>>
end FmiUnknownAttributes;
template FmiUnknownDependencies(list<Integer> dependencies)
::=
if intGt(listLength(dependencies), 0) then
<<
dependencies="<%dependencies |> dependency => dependency ;separator=" "%>"
>>
end FmiUnknownDependencies;
template FmiUnknownDependenciesKind(list<String> dependenciesKind)
::=
if intGt(listLength(dependenciesKind), 0) then
<<
dependenciesKind="<%dependenciesKind |> dependencyKind => dependencyKind ;separator=" "%>"
>>
end FmiUnknownDependenciesKind;
template fmumodel_identifierFile(SimCode simCode, String guid, String FMUVersion)
"Generates code for ModelDescription file for FMU target."
::=
match simCode
case SIMCODE(__) then
<<
// define class name and unique id
#define MODEL_IDENTIFIER <%modelNamePrefix(simCode)%>
#define MODEL_GUID "{<%guid%>}"
// include fmu header files, typedefs and macros
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include "openmodelica.h"
#include "openmodelica_func.h"
#include "simulation_data.h"
#include "util/omc_error.h"
#include "<%fileNamePrefix%>_functions.h"
#include "<%fileNamePrefix%>_literals.h"
#include "simulation/solver/initialization/initialization.h"
#include "simulation/solver/events.h"
<%if isFMIVersion20(FMUVersion) then
'#include "fmu2_model_interface.h"'
else
'#include "fmu1_model_interface.h"'%>
#ifdef __cplusplus
extern "C" {
#endif
void setStartValues(ModelInstance *comp);
void setDefaultStartValues(ModelInstance *comp);
<%if isFMIVersion20(FMUVersion) then
<<
void eventUpdate(ModelInstance* comp, fmi2EventInfo* eventInfo);
fmi2Real getReal(ModelInstance* comp, const fmi2ValueReference vr);
fmi2Status setReal(ModelInstance* comp, const fmi2ValueReference vr, const fmi2Real value);
fmi2Integer getInteger(ModelInstance* comp, const fmi2ValueReference vr);
fmi2Status setInteger(ModelInstance* comp, const fmi2ValueReference vr, const fmi2Integer value);
fmi2Boolean getBoolean(ModelInstance* comp, const fmi2ValueReference vr);
fmi2Status setBoolean(ModelInstance* comp, const fmi2ValueReference vr, const fmi2Boolean value);
fmi2String getString(ModelInstance* comp, const fmi2ValueReference vr);
fmi2Status setString(ModelInstance* comp, const fmi2ValueReference vr, fmi2String value);
fmi2Status setExternalFunction(ModelInstance* c, const fmi2ValueReference vr, const void* value);
>>
else
<<
void eventUpdate(ModelInstance* comp, fmiEventInfo* eventInfo);
fmiReal getReal(ModelInstance* comp, const fmiValueReference vr);
fmiStatus setReal(ModelInstance* comp, const fmiValueReference vr, const fmiReal value);
fmiInteger getInteger(ModelInstance* comp, const fmiValueReference vr);
fmiStatus setInteger(ModelInstance* comp, const fmiValueReference vr, const fmiInteger value);
fmiBoolean getBoolean(ModelInstance* comp, const fmiValueReference vr);
fmiStatus setBoolean(ModelInstance* comp, const fmiValueReference vr, const fmiBoolean value);
fmiString getString(ModelInstance* comp, const fmiValueReference vr);
fmiStatus setString(ModelInstance* comp, const fmiValueReference vr, fmiString value);
fmiStatus setExternalFunction(ModelInstance* c, const fmiValueReference vr, const void* value);
>>
%>
<%ModelDefineData(modelInfo)%>
// implementation of the Model Exchange functions
<%if isFMIVersion20(FMUVersion) then
' extern void <%symbolName(modelNamePrefix(simCode),"setupDataStruc")%>(DATA *data);
#define fmu2_model_interface_setupDataStruc <%symbolName(modelNamePrefix(simCode),"setupDataStruc")%>
#include "fmu2_model_interface.c"'
else
' extern void <%symbolName(modelNamePrefix(simCode),"setupDataStruc")%>(DATA *data);
#define fmu1_model_interface_setupDataStruc <%symbolName(modelNamePrefix(simCode),"setupDataStruc")%>
#include "fmu1_model_interface.c"'%>
<%setDefaultStartValues(modelInfo)%>
<%setStartValues(modelInfo)%>
<%if isFMIVersion20(FMUVersion) then
<<
<%eventUpdateFunction2(simCode)%>
<%getRealFunction2(modelInfo)%>
<%setRealFunction2(modelInfo)%>
<%getIntegerFunction2(modelInfo)%>
<%setIntegerFunction2(modelInfo)%>
<%getBooleanFunction2(modelInfo)%>
<%setBooleanFunction2(modelInfo)%>
<%getStringFunction2(modelInfo)%>
<%setStringFunction2(modelInfo)%>
<%setExternalFunction2(modelInfo)%>
>>
else
<<
<%eventUpdateFunction(simCode)%>
<%getRealFunction(modelInfo)%>
<%setRealFunction(modelInfo)%>
<%getIntegerFunction(modelInfo)%>
<%setIntegerFunction(modelInfo)%>
<%getBooleanFunction(modelInfo)%>
<%setBooleanFunction(modelInfo)%>
<%getStringFunction(modelInfo)%>
<%setStringFunction(modelInfo)%>
<%setExternalFunction(modelInfo)%>
>>
%>
#ifdef __cplusplus
}
#endif
>>
end fmumodel_identifierFile;
template ModelDefineData(ModelInfo modelInfo)
"Generates global data in simulation file."
::=
match modelInfo
case MODELINFO(varInfo=VARINFO(__), vars=SIMVARS(stateVars = listStates)) then
let numberOfReals = intAdd(intMul(varInfo.numStateVars,2),intAdd(varInfo.numDiscreteReal, intAdd(varInfo.numAlgVars,intAdd(varInfo.numParams,varInfo.numAlgAliasVars))))
let numberOfIntegers = intAdd(varInfo.numIntAlgVars,intAdd(varInfo.numIntParams,varInfo.numIntAliasVars))
let numberOfStrings = intAdd(varInfo.numStringAlgVars,intAdd(varInfo.numStringParamVars,varInfo.numStringAliasVars))
let numberOfBooleans = intAdd(varInfo.numBoolAlgVars,intAdd(varInfo.numBoolParams,varInfo.numBoolAliasVars))
<<
// define model size
#define NUMBER_OF_STATES <%if intEq(varInfo.numStateVars,1) then statesnumwithDummy(listStates) else varInfo.numStateVars%>
#define NUMBER_OF_EVENT_INDICATORS <%varInfo.numZeroCrossings%>
#define NUMBER_OF_REALS <%numberOfReals%>
#define NUMBER_OF_INTEGERS <%numberOfIntegers%>
#define NUMBER_OF_STRINGS <%numberOfStrings%>
#define NUMBER_OF_BOOLEANS <%numberOfBooleans%>
#define NUMBER_OF_EXTERNALFUNCTIONS <%countDynamicExternalFunctions(functions)%>
// define variable data for model
<%System.tmpTickReset(0)%>
<%vars.stateVars |> var => DefineVariables(var) ;separator="\n"%>
<%vars.derivativeVars |> var => DefineVariables(var) ;separator="\n"%>
<%vars.algVars |> var => DefineVariables(var) ;separator="\n"%>
<%vars.discreteAlgVars |> var => DefineVariables(var) ;separator="\n"%>
<%vars.paramVars |> var => DefineVariables(var) ;separator="\n"%>
<%vars.aliasVars |> var => DefineVariables(var) ;separator="\n"%>
<%System.tmpTickReset(0)%>
<%vars.intAlgVars |> var => DefineVariables(var) ;separator="\n"%>
<%vars.intParamVars |> var => DefineVariables(var) ;separator="\n"%>
<%vars.intAliasVars |> var => DefineVariables(var) ;separator="\n"%>
<%System.tmpTickReset(0)%>
<%vars.boolAlgVars |> var => DefineVariables(var) ;separator="\n"%>
<%vars.boolParamVars |> var => DefineVariables(var) ;separator="\n"%>
<%vars.boolAliasVars |> var => DefineVariables(var) ;separator="\n"%>
<%System.tmpTickReset(0)%>
<%vars.stringAlgVars |> var => DefineVariables(var) ;separator="\n"%>
<%vars.stringParamVars |> var => DefineVariables(var) ;separator="\n"%>
<%vars.stringAliasVars |> var => DefineVariables(var) ;separator="\n"%>
// define initial state vector as vector of value references
#define STATES { <%vars.stateVars |> SIMVAR(__) => if stringEq(crefStr(name),"$dummy") then '' else '<%cref(name)%>_' ;separator=", "%> }
#define STATESDERIVATIVES { <%vars.derivativeVars |> SIMVAR(__) => if stringEq(crefStr(name),"der($dummy)") then '' else '<%cref(name)%>_' ;separator=", "%> }
<%System.tmpTickReset(0)%>
<%(functions |> fn => defineExternalFunction(fn) ; separator="\n")%>
>>
end ModelDefineData;
template dervativeNameCStyle(ComponentRef cr)
"Generates the name of a derivative in c style, replaces ( with _"
::=
match cr
case CREF_QUAL(ident = "$DER") then 'der_<%crefStr(componentRef)%>_'
end dervativeNameCStyle;
template DefineVariables(SimVar simVar)
"Generates code for defining variables in c file for FMU target. "
::=
match simVar
case SIMVAR(__) then
let description = if comment then '// "<%comment%>"'
if stringEq(crefStr(name),"$dummy") then
<<>>
else if stringEq(crefStr(name),"der($dummy)") then
<<>>
else
<<
#define <%cref(name)%>_ <%System.tmpTick()%> <%description%>
>>
end DefineVariables;
template defineExternalFunction(Function fn)
"Generates external function definitions."
::=
match fn
case EXTERNAL_FUNCTION(dynamicLoad=true) then
let fname = extFunctionName(extName, language)
<<
#define $P<%fname%> <%System.tmpTick()%>
>>
end defineExternalFunction;
template setDefaultStartValues(ModelInfo modelInfo)
"Generates code in c file for function setStartValues() which will set start values for all variables."
::=
match modelInfo
case MODELINFO(varInfo=VARINFO(numStateVars=numStateVars, numAlgVars= numAlgVars),vars=SIMVARS(__)) then
<<
// Set values for all variables that define a start value
void setDefaultStartValues(ModelInstance *comp) {
<%vars.stateVars |> var => initValsDefault(var,"realVars",0) ;separator="\n"%>
<%vars.derivativeVars |> var => initValsDefault(var,"realVars",numStateVars) ;separator="\n"%>
<%vars.algVars |> var => initValsDefault(var,"realVars",intMul(2,numStateVars)) ;separator="\n"%>
<%vars.discreteAlgVars |> var => initValsDefault(var, "realVars", intAdd(intMul(2,numStateVars), numAlgVars)) ;separator="\n"%>
<%vars.intAlgVars |> var => initValsDefault(var,"integerVars",0) ;separator="\n"%>
<%vars.boolAlgVars |> var => initValsDefault(var,"booleanVars",0) ;separator="\n"%>
<%vars.stringAlgVars |> var => initValsDefault(var,"stringVars",0) ;separator="\n"%>
<%vars.paramVars |> var => initParamsDefault(var,"realParameter") ;separator="\n"%>
<%vars.intParamVars |> var => initParamsDefault(var,"integerParameter") ;separator="\n"%>
<%vars.boolParamVars |> var => initParamsDefault(var,"booleanParameter") ;separator="\n"%>
<%vars.stringParamVars |> var => initParamsDefault(var,"stringParameter") ;separator="\n"%>
}
>>