/
SimCodegen.mo
8719 lines (8185 loc) · 348 KB
/
SimCodegen.mo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is part of OpenModelica.
*
* Copyright (c) 1998-2008, Linköpings University,
* Department of Computer and Information Science,
* SE-58183 Linköping, Sweden.
*
* All rights reserved.
*
* THIS PROGRAM IS PROVIDED UNDER THE TERMS OF THIS OSMC PUBLIC
* LICENSE (OSMC-PL). ANY USE, REPRODUCTION OR DISTRIBUTION OF
* THIS PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THE OSMC
* PUBLIC LICENSE.
*
* The OpenModelica software and the Open Source Modelica
* Consortium (OSMC) Public License (OSMC-PL) are obtained
* from Linköpings University, either from the above address,
* from the URL: http://www.ida.liu.se/projects/OpenModelica
* and in the OpenModelica distribution.
*
* This program is distributed WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH
* IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS
* OF OSMC-PL.
*
* See the full OSMC Public License conditions for more details.
*
*/
package SimCodegen
" file: SimCodegen.mo
package: SimCodegen
description: Generate Simulation code for connecting to solver.
This can be done in two different ways.
1. Generation of simulation code on residual form. This will generate
code on the form g(\\dot{x},x,y,t)=0.
2. Generation of simulation code on solved form. This will generate
code on ode form. \\dot{x} = f(x,y,t). This means that \"function\" f will
contain code for solving states from equations, some of them might be
system of equations, linear or non-linear.
RCS: $Id$
Outputs: the simulation code in C/C++ to a given filename.
Input: DAELow
Uses: DAELow, Absyn, Exp "
public import DAE;
public import DAELow;
public import Absyn;
public import Exp;
public import SCode;
public type HelpVarInfo = tuple<Integer, Exp.Exp, Integer>; // helpvarindex, expression, whenclause index
protected
type CFunction = Codegen.CFunction;
protected constant String TAB=" ";
protected constant String stateNames="state_names" "TAB is four whitespaces" ;
protected constant String derivativeNames="derivative_names";
protected constant String algvarsNames="algvars_names";
protected constant String inputNames="input_names";
protected constant String outputNames="output_names";
protected constant String paramNames="param_names";
protected constant String stringParamNames="string_param_names";
protected constant String stringAlgNames="string_alg_names";
protected constant String stateComments="state_comments";
protected constant String derivativeComments="derivative_comments";
protected constant String algvarsComments="algvars_comments";
protected constant String inputComments="input_comments";
protected constant String outputComments="output_comments";
protected constant String paramComments="param_comments";
protected constant String stringParamComments="string_param_comments";
protected constant String stringAlgComments="string_alg_comments";
protected constant String paramInGetNameFunction="ptr";
protected import Util;
protected import RTOpts;
protected import Debug;
protected import System;
protected import Values;
protected import Codegen;
protected import Print;
protected import ModUtil;
protected import VarTransform;
protected import Dump;
protected import Inst;
protected import Error;
protected import Settings;
protected import Algorithm;
protected import Types;
protected import Env;
protected import Ceval;
public function generateMakefile
"function: generateMakefile
This function generates a makefile for the simulation code.
It uses:
- OPENMODELICAHOME/include as a reference to includes and
- OPENMODELICAHOME/lib as a reference to library files"
input String inMakefileName;
input String inFilenamePrefix;
input list<String> inLibs;
input String inFileDir;
algorithm
_:=
matchcontinue (inMakefileName,inFilenamePrefix,inLibs,inFileDir)
local
String cpp_file,libs_1,omhome_1,omhome,str,filename,cname,file_dir,MakefileHeader;
list<String> libs;
case (filename,cname,libs,"") /* filename classname libs directory for mo-file */
equation
MakefileHeader = Ceval.generateMakefileHeader();
cpp_file = Util.stringAppendList({cname,".cpp"});
libs_1 = Util.stringDelimitList(libs, " ");
omhome_1 = Settings.getInstallationDirectoryPath();
omhome = System.trim(omhome_1, "\"");
str = Util.stringAppendList({MakefileHeader,
"\n.PHONY: ",cname,"\n",
cname,": ",cpp_file,"\n","\t $(CXX)",
" $(CFLAGS)",
" -I.",
" -o ",cname,"$(EXEEXT) ",cpp_file,
" -lsim",
" $(LDFLAGS)",
" -lf2c",
" ${SENDDATALIBS} ",
libs_1,
"\n"});
System.writeFile(filename, str);
then
();
case (filename,cname,libs,file_dir)
equation
MakefileHeader = Ceval.generateMakefileHeader();
cpp_file = Util.stringAppendList({cname,".cpp"});
libs_1 = Util.stringDelimitList(libs, " ");
omhome_1 = Settings.getInstallationDirectoryPath();
omhome = System.trim(omhome_1, "\"");
str = Util.stringAppendList(
{MakefileHeader,
"\n.PHONY: ",cname,"\n",
cname,": ",cpp_file,"\n","\t $(CXX)",
" $(CFLAGS)",
" -I.",
" -I\"",file_dir,"\"",
" -o ",cname,"$(EXEEXT) ",cpp_file,
" -L\"",file_dir,"\"",
" -lsim",
" $(LDFLAGS)",
" -lf2c",
" ${SENDDATALIBS} ",
libs_1,
"\n"});
System.writeFile(filename, str);
then
();
end matchcontinue;
end generateMakefile;
public function generateSimulationCode "function: generateSimulationCode
Outputs simulation code from a DAELow suitable for connection to DASSL.
The state calculations are generated on residual form, i.e.
g(\\dot{x},x,y,t) = 0.
and on explicit ode form, \\dot{x}=f(x,y,t)
"
input DAE.DAElist inDAElist1;
input DAELow.DAELow inDAELow2;
input Integer[:] inIntegerArray3;
input Integer[:] inIntegerArray4;
input DAELow.IncidenceMatrix inIncidenceMatrix5;
input DAELow.IncidenceMatrixT inIncidenceMatrixT6;
input list<list<Integer>> inIntegerLstLst7;
input Absyn.Path inPath8;
input String inString9;
input String inString10;
input String inString11;
algorithm
_:=
matchcontinue (inDAElist1,inDAELow2,inIntegerArray3,inIntegerArray4,inIncidenceMatrix5,inIncidenceMatrixT6,inIntegerLstLst7,inPath8,inString9,inString10,inString11)
local
String cname,out_str,in_str,c_eventchecking,s_code2,s_code3,cglobal,coutput,cstate,c_ode,s_code,cwhen,
czerocross,res,filename,funcfilename,fileDir;
String extObjInclude; list<String> extObjIncludes;
list<list<Integer>> blt_states,blt_no_states,comps;
Integer n_o,n_i,n_h,nres;
list<HelpVarInfo> helpVarInfo,helpVarInfo1;
DAE.DAElist dae;
DAELow.DAELow dlow,dlow2;
Integer[:] ass1,ass2;
list<Integer>[:] m,mt;
Absyn.Path class_;
case (dae,dlow,ass1,ass2,m,mt,comps,class_,filename,funcfilename,fileDir)
equation
cname = Absyn.pathString(class_);
(blt_states,blt_no_states) = DAELow.generateStatePartition(comps, dlow, ass1, ass2, m, mt);
Debug.fcall("bltdump",print," state blocks (dynamic section):");
Debug.fcall("bltdump",DAELow.dumpComponents,blt_states);
Debug.fcall("bltdump",print," algebraic blocks (accepted section):");
Debug.fcall("bltdump",DAELow.dumpComponents,blt_no_states);
(c_eventchecking,helpVarInfo1) = generateEventCheckingCode(dlow, comps, ass1, ass2, m, mt, class_);
(helpVarInfo,dlow2) = generateHelpVarsForWhenStatements(helpVarInfo1,dlow);
(out_str,n_o) = generateOutputFunctionCode(dlow2);
(in_str,n_i) = generateInputFunctionCode(dlow2);
n_h = listLength(helpVarInfo);
(s_code2,nres) = generateInitialValueCode2(dlow2,ass1,ass2);
(s_code3) = generateInitialBoundParameterCode(dlow2);
cglobal = generateGlobalData(class_, dlow2, n_o, n_i, n_h, nres,fileDir);
coutput = generateComputeOutput(cname, dae, dlow2, ass1, ass2,m,mt, blt_no_states);
cstate = generateComputeResidualState(cname, dae, dlow2, ass1, ass2, blt_states);
c_ode = generateOdeCode(dlow2, blt_states, ass1, ass2, m, mt, class_);
s_code = generateInitialValueCode(dlow2);
cwhen = generateWhenClauses(cname, dae, dlow2, ass1, ass2, comps);
czerocross = generateZeroCrossing(cname, dae, dlow2, ass1, ass2, comps, helpVarInfo);
(extObjIncludes,_) = generateExternalObjectIncludes(dlow2);
extObjInclude = Util.stringDelimitList(extObjIncludes,"\n");
res = Util.stringAppendList(
{"//Simulation code for ",cname,
"\n//Generated by OpenModelica.\n","\n#include \"modelica.h\"\n",
"\n#include \"assert.h\"\n",
"\n#include \"string.h\"\n",
"\n#include \"simulation_runtime.h\"\n","\n#include \"",funcfilename,"\"\n",
"extern \"C\" {\n",extObjInclude,"\n}\n",
cglobal,coutput,in_str,out_str,
cstate,czerocross,cwhen,c_ode,s_code,s_code2,s_code3,c_eventchecking});
System.writeFile(filename, res);
then
();
case (_,_,_,_,_,_,_,_,_,_,_)
equation
Error.addMessage(Error.INTERNAL_ERROR,
{"Generation of simulation code failed"});
then
fail();
end matchcontinue;
end generateSimulationCode;
protected function generateHelpVarsForWhenStatements
input list<HelpVarInfo> inHelpVarInfo;
input DAELow.DAELow inDAELow;
output list<HelpVarInfo> outHelpVarInfo;
output DAELow.DAELow outDAELow;
algorithm
(outHelpVarInfo,outDAELow) :=
matchcontinue (inHelpVarInfo,inDAELow)
local
list<HelpVarInfo> helpvars, helpvars1;
DAELow.Variables orderedVars;
DAELow.Variables knownVars;
DAELow.Variables externalObjects;
DAELow.EquationArray orderedEqs;
DAELow.EquationArray removedEqs;
DAELow.EquationArray initialEqs;
DAELow.MultiDimEquation[:] arrayEqs;
Algorithm.Algorithm[:] algorithms,algorithms2;
list<Algorithm.Algorithm> algLst;
DAELow.EventInfo eventInfo;
DAELow.ExternalObjectClasses extObjClasses;
case (helpvars,DAELow.DAELOW(orderedVars,knownVars,externalObjects,orderedEqs,
removedEqs,initialEqs,arrayEqs,algorithms,eventInfo,extObjClasses))
equation
(helpvars1,algLst,_) = generateHelpVarsInAlgorithms(listLength(helpvars),arrayList(algorithms));
algorithms2 = listArray(algLst);
then (listAppend(helpvars,helpvars1),DAELow.DAELOW(orderedVars,knownVars,externalObjects,orderedEqs,
removedEqs,initialEqs,arrayEqs,algorithms2,eventInfo,extObjClasses));
case (_,_)
equation
Error.addMessage(Error.INTERNAL_ERROR,
{"generateHelpVarsForWhenStatements failed"});
then
fail();
end matchcontinue;
end generateHelpVarsForWhenStatements;
protected function generateHelpVarsInAlgorithms
input Integer nextInd "Index of next help variable";
input list<Algorithm.Algorithm> inAlgLst;
output list<HelpVarInfo> outHelpVars;
output list<Algorithm.Algorithm> outAlgLst;
output Integer n2;
algorithm
(outHelpVars,outAlgLst,n2) := matchcontinue(nextInd,inAlgLst)
local
Integer nextInd,nextInd2,nextInd3;
list<Algorithm.Statement> stmts, stmts2;
list<Algorithm.Algorithm> rest,rest2;
list<HelpVarInfo> helpvars1,helpvars2,helpvars;
case (nextInd, {}) then ({},{},nextInd);
case (nextInd, (Algorithm.ALGORITHM(stmts))::rest)
equation
(helpvars1,rest2,nextInd2) = generateHelpVarsInAlgorithms(nextInd,rest);
(helpvars2,stmts2,nextInd3) = generateHelpVarsInStatements(nextInd2,stmts);
helpvars = listAppend(helpvars1,helpvars2);
then (helpvars,Algorithm.ALGORITHM(stmts2)::rest2,nextInd3);
case (_,_)
equation
Error.addMessage(Error.INTERNAL_ERROR,
{"generateHelpVarsInAlgorithms failed"});
then
fail();
end matchcontinue;
end generateHelpVarsInAlgorithms;
protected function generateHelpVarsInStatements
input Integer n "Index of next help variable";
input list<Algorithm.Statement> inStmtLst;
output list<HelpVarInfo> outHelpVars;
output list<Algorithm.Statement> outStmtLst;
output Integer n1;
algorithm
(outHelpVars,outStmtLst,n1) := matchcontinue(n,inStmtLst)
local
list<Algorithm.Statement> rest, rest1;
Integer nextInd, nextInd1, nextInd2;
Algorithm.Statement statement,statement1;
list<HelpVarInfo> helpvars,helpvars1,helpvars2;
case (nextInd, {}) then ({},{},nextInd);
case (nextInd, statement::rest)
equation
(helpvars1,rest1,nextInd1) = generateHelpVarsInStatements(nextInd,rest);
(helpvars2,statement1,nextInd2) = generateHelpVarsInStatement(nextInd1,statement);
helpvars = listAppend(helpvars1,helpvars2);
then (helpvars,statement1::rest1,nextInd2);
case (_,_)
equation
Error.addMessage(Error.INTERNAL_ERROR,
{"generateHelpVarsInStatements failed"});
then
fail();
end matchcontinue;
end generateHelpVarsInStatements;
protected function generateHelpVarsInStatement
input Integer n "Index of next help variable";
input Algorithm.Statement inStmt;
output list<HelpVarInfo> outHelpVars;
output Algorithm.Statement outStmt;
output Integer n1;
algorithm
(outHelpVars,outStmt,n1) := matchcontinue(n,inStmt)
local
list<Algorithm.Statement> rest, rest1;
Integer nextInd, nextInd1, nextInd2;
list<Integer> helpVarIndices, helpVarIndices1;
Exp.Exp condition;
list<Exp.Exp> el, el1;
list<Algorithm.Statement> statementLst;
Algorithm.Statement statement;
Algorithm.Statement elseWhen;
list<HelpVarInfo> helpvars,helpvars1,helpvars2;
String newIdent;
String nextIndStr;
Exp.Type ty;
Boolean scalar;
list<Integer> helpVarIndices1,helpVarIndices;
case (nextInd, Algorithm.WHEN(Exp.ARRAY(ty,scalar,el),statementLst,NONE,_))
equation
(helpvars1,el1,nextInd1) = generateHelpVarsInArrayCondition(nextInd,el);
helpVarIndices1 = Util.listIntRange(nextInd1-nextInd);
helpVarIndices = Util.listMap1(helpVarIndices1,intAdd,nextInd-1);
then (helpvars1,Algorithm.WHEN(Exp.ARRAY(ty,scalar,el1), statementLst,NONE,helpVarIndices),nextInd1);
case (nextInd, Algorithm.WHEN(condition,statementLst,NONE,_))
then ({(nextInd,condition,-1)},Algorithm.WHEN(condition, statementLst,NONE,{nextInd}),nextInd+1);
case (nextInd, Algorithm.WHEN(Exp.ARRAY(ty,scalar,el),statementLst,SOME(elseWhen),_))
equation
(helpvars1,el1,nextInd1) = generateHelpVarsInArrayCondition(nextInd,el);
helpVarIndices1 = Util.listIntRange(nextInd1-nextInd);
helpVarIndices = Util.listMap1(helpVarIndices1,intAdd,nextInd-1);
(helpvars2,statement,nextInd2) = generateHelpVarsInStatement(nextInd1,elseWhen);
helpvars = listAppend(helpvars1,helpvars2);
then (helpvars,Algorithm.WHEN(Exp.ARRAY(ty,scalar,el1), statementLst,SOME(statement),helpVarIndices),nextInd1);
case (nextInd, Algorithm.WHEN(condition,statementLst,SOME(elseWhen),_))
equation
(helpvars1,statement,nextInd1) = generateHelpVarsInStatement(nextInd+1,elseWhen);
then ((nextInd,condition,-1)::helpvars1,
Algorithm.WHEN(condition, statementLst,SOME(statement),{nextInd}),nextInd1);
case (nextInd, statement) then ({},statement,nextInd);
case (_,_)
equation
Error.addMessage(Error.INTERNAL_ERROR,
{"generateHelpVarsInStatements failed"});
then
fail();
end matchcontinue;
end generateHelpVarsInStatement;
protected function generateHelpVarsInArrayCondition
input Integer n "Index of next help variable";
input list<Exp.Exp> inExp;
output list<HelpVarInfo> outHelpVars;
output list<Exp.Exp> outExp;
output Integer n1;
algorithm
(outHelpVars,outExp,n2) := matchcontinue(n,inExp)
local
list<Exp.Exp> rest, el, el1;
Integer nextInd, nextInd1;
Exp.Exp condition;
list<HelpVarInfo> helpvars1;
String newIdent;
String nextIndStr;
case (nextInd, {}) then ({},{},nextInd);
case (nextInd, condition::rest)
equation
(helpvars1,el1,nextInd1) = generateHelpVarsInArrayCondition(nextInd+1,rest);
then ((nextInd,condition,-1)::helpvars1,condition::el1,nextInd1);
case (_,_)
equation
Error.addMessage(Error.INTERNAL_ERROR,
{"generateHelpVarsInArrayCondition failed"});
then
fail();
end matchcontinue;
end generateHelpVarsInArrayCondition;
protected function filterNg "function: filterNg
This function sets the number of zero crossings to zero if events are disabled
"
input Integer inInteger;
output Integer outInteger;
algorithm
outInteger:=
matchcontinue (inInteger)
local Integer ng;
case _
equation
false = useZerocrossing();
then
0;
case ng then ng;
end matchcontinue;
end filterNg;
protected function generateGlobalData
"
This function generates the C-code for the global data: arrays for states,
derivatives and algebraic variables, etc.
arg1
arg2
arg3 an int which shows the number of output variables on top level
arg4 an int which shows the number of input variables on top level
arg5 an int which shows the number of help variables
arg5 integer - number of residuals in initialization function.
arg6 String - the directory where the model is saved
"
input Absyn.Path class_ "Path to the instatiated model";
input DAELow.DAELow loweredDAE "The lowered DAE";
input Integer numberOfOutputVariables "The number of output variables on top level";
input Integer numberOfInputVariables "The number of input variables on top level";
input Integer numberOfHelpVariables "The number of help variables";
input Integer numberOfResidulas "Number of residuals in initialization function";
input String fileDir "The directory where the model is saved";
output String outString;
algorithm
outString:=
matchcontinue (class_,loweredDAE,numberOfOutputVariables,numberOfInputVariables,numberOfHelpVariables,numberOfResidulas,fileDir)
local
Integer nx,ny,np,ng,ng_1,no,ni,nh,nres,next,ny_string,np_string;
String initDeinitDataStructFunction,class_str,nx_str,ny_str,np_str,ng_str,no_str,ni_str,nh_str;
String nres_str,c_code2_str,c_code3_str,c_code_str,macros_str,global_bufs,str1,str,next_str;
String nystring_str, npstring_str;
list<String> c_code;
Absyn.Path class_;
DAELow.DAELow dlow;
String trimmedFileDir;
case (class_,dlow,no,ni,nh,nres,fileDir)
equation
(nx,ny,np,ng,next,ny_string,np_string) = DAELow.calculateSizes(dlow);
//DAELow.dump(dlow);
ng_1 = filterNg(ng);
class_str = Absyn.pathString(class_);
nx_str = intString(nx);
ny_str = intString(ny);
np_str = intString(np);
ng_str = intString(ng_1);
no_str = intString(no);
ni_str = intString(ni);
nh_str = intString(nh);
nres_str = intString(nres);
next_str = intString(next);
nystring_str = intString(ny_string);
npstring_str = intString(np_string);
c_code = generateVarNamesAndComments(dlow, nx, ny, ni, no, np,next,ny_string,np_string);
initDeinitDataStructFunction = generateInitializeDeinitializationDataStruc(dlow);
(c_code2_str) = generateFixedVector(dlow, nx, ny, np);
(c_code3_str) = generateAttrVector(dlow, nx, ny, np);
c_code_str = Util.stringDelimitList(c_code, "\n");
macros_str = generateMacros();
global_bufs = generateGlobalBufs();
// take of the quotes "
trimmedFileDir = System.trim(fileDir, "\"");
// and transform it to a C string: \ replaced by \\
// trimmedFileDir = System.stringReplace(trimmedFileDir, "\\", "\\\\");
str1 = Util.stringAppendList(
{"\n","#define NHELP ",nh_str,"\n","#define NG ",ng_str,"//number of zero crossing",
"\n","#define NX ",nx_str,"\n","#define NY ",ny_str,"\n","#define NP ",
np_str," // number of parameters\n","#define NO ",no_str,
" // number of outputvar on topmodel\n","#define NI ",ni_str," // number of inputvar on topmodel\n",
"#define NR ",nres_str," // number of residuals for initialialization function\n",
"#define NEXT ", next_str," // number of external objects\n",
"#define MAXORD 5\n",
"#define NYSTR ",nystring_str, " // number of alg. string variables\n",
"#define NPSTR ",npstring_str, " // number of alg. string variables\n",
"\n",
global_bufs,
"char *model_name=\"",class_str,"\";\n",
"char *model_dir=\"",trimmedFileDir,"\";\n",
c_code_str,c_code2_str,"\n",c_code3_str,"\n"});
str = Util.stringAppendList({str1,macros_str,"\n",initDeinitDataStructFunction,"\n"}) "this is done here and not in the above Util.string_append_list VC7.1 cannot compile too complicated c-programs this is removed for now \"typedef struct equation {\\n\", \" char equation;\\n\", \" char fileName;\\n\", \" int lineNumber;\\n\", \"} equation;\\n\"," ;
then
str;
case (_,_,_,_,_,_,_)
equation
Error.addMessage(Error.INTERNAL_ERROR, {"generate_global_data failed"});
then
fail();
end matchcontinue;
end generateGlobalData;
protected function generateExternalObjectDestructorCalls "generate destructor calls for external objects"
input Integer cg_in;
input DAELow.DAELow daelow;
output CFunction outCFunction;
output Integer cg_out;
algorithm
(outCFunction,outInteger) := matchcontinue(cg_in,daelow)
case (cg_in,DAELow.DAELOW(externalObjects = evars, extObjClasses = eclasses))
local
DAELow.Variables evars;
list<DAELow.Var> evarLst;
DAELow.ExternalObjectClasses eclasses;
list<String> strs;
equation
evarLst = DAELow.varList(evars);
(outCFunction,cg_out) = generateExternalObjectDestructorCalls2(cg_in,evarLst,eclasses);
then (outCFunction,cg_out);
end matchcontinue;
end generateExternalObjectDestructorCalls;
protected function generateExternalObjectDestructorCalls2 "
help function to generateExternalObjectDestructorCalls"
input Integer cg_in;
input list<DAELow.Var> varLst;
input DAELow.ExternalObjectClasses eclasses;
output CFunction outCFunction;
output Integer cg_out;
algorithm
(outCFunction,cg_out) := matchcontinue(cg_in,varLst,eclasses)
local DAELow.Var v;
list<DAELow.Var> vs;
Codegen.CFunction cfunc,cfunc2;
case (cg_in,{},eclasses)
then (Codegen.cEmptyFunction,cg_in);
case (cg_in,v::vs,eclasses) equation
(cfunc,cg_out) = generateExternalObjectDestructorCalls2(cg_in,vs,eclasses);
(cfunc2,cg_out) = generateExternalObjectDestructorCall(cg_out,v,eclasses);
cfunc = Codegen.cMergeFns({cfunc2,cfunc});
then (cfunc,cg_out);
end matchcontinue;
end generateExternalObjectDestructorCalls2;
protected function generateExternalObjectDestructorCall "help function to generateExternalObjectDestructorCalls"
input Integer cg_in;
input DAELow.Var var;
input DAELow.ExternalObjectClasses eclasses;
output CFunction outCFunction;
output Integer cg_out;
algorithm
(outCFunction,cg_out) := matchcontinue (cg_in,var,eclasses)
case (_,_,{}) equation print("generateExternalObjectDestructorCall failed\n"); then fail();
// found class
case (cg_in,DAELow.VAR(varName = name,varKind = DAELow.EXTOBJ(path1)), DAELow.EXTOBJCLASS(path=path2,destructor=destr)::_)
local
DAE.Element destr;
Exp.ComponentRef name;
Absyn.Path path1,path2;
Codegen.CFunction cfunc;
equation
true = ModUtil.pathEqual(path1,path2);
(cfunc,cg_out) = generateExternalObjectDestructorCall2(cg_in,name,destr);
then (cfunc,cg_out);
// Try next class.
case (cg_in,var,_::eclasses)
local Codegen.CFunction cfunc;
equation
(cfunc,cg_out) = generateExternalObjectDestructorCall(cg_in,var,eclasses);
then (cfunc,cg_out);
end matchcontinue;
end generateExternalObjectDestructorCall;
protected function generateExternalObjectDestructorCall2 "Help funciton to generateExternalObjectDestructorCall"
input Integer cg_in;
input Exp.ComponentRef varName;
input DAE.Element destructor;
output CFunction outCFunction;
output Integer cg_out;
algorithm
(cg_out,outCFunction) := matchcontinue(cg_in,varName,destructor)
case (cg_in,varName,destructor as DAE.EXTFUNCTION(externalDecl = DAE.EXTERNALDECL(ident=funcStr)))
local String vStr,funcStr,str;
Codegen.CFunction cfunc;
equation
vStr = Exp.printComponentRefStr(varName);
str = Util.stringAppendList({" ",funcStr,"(",vStr,");"});
cfunc = Codegen.cAddStatements(Codegen.cEmptyFunction,{str});
then (cfunc,cg_in);
end matchcontinue;
end generateExternalObjectDestructorCall2;
protected function generateExternalObjectConstructorCalls " generates constructor calls of all external objects"
input Integer cg_in;
input DAELow.DAELow daelow;
output CFunction outCFunction;
output Integer cg_out;
algorithm
str := matchcontinue(cg_in,daelow)
case (cg_in,DAELow.DAELOW(externalObjects = evars, extObjClasses = eclasses))
local
DAELow.Variables evars;
list<DAELow.Var> evarLst;
DAELow.ExternalObjectClasses eclasses;
list<String> strs;
equation
evarLst = DAELow.varList(evars);
(outCFunction,cg_out) = generateExternalObjectConstructorCalls2(cg_in,evarLst,eclasses);
then (outCFunction,cg_out);
end matchcontinue;
end generateExternalObjectConstructorCalls;
protected function generateExternalObjectConstructorCalls2 "
help function to generateExternalObjectConstructorCalls"
input Integer cg_in;
input list<DAELow.Var> varLst;
input DAELow.ExternalObjectClasses eclasses;
output CFunction outCFunction;
output Integer cg_out;
algorithm
(outCFunction,cg_out) := matchcontinue(cg_in,varLst,eclasses)
local DAELow.Var v;
list<DAELow.Var> vs;
Codegen.CFunction cfunc,cfunc2;
case (cg_in,{},eclasses)
then (Codegen.cEmptyFunction,cg_in);
case (cg_in,v::vs,eclasses) equation
(cfunc,cg_out) = generateExternalObjectConstructorCalls2(cg_in,vs,eclasses);
(cfunc2,cg_out) = generateExternalObjectConstructorCall(cg_out,v,eclasses);
cfunc = Codegen.cMergeFns({cfunc2,cfunc});
then (cfunc,cg_out);
end matchcontinue;
end generateExternalObjectConstructorCalls2;
protected function generateExternalObjectConstructorAliases "Generates codes for external objects that are
aliased to other external object variables. They must be issued after the constructor call. Therefore
this function is called after all constructor calls have been generated."
input Integer cg_in;
input DAELow.DAELow daelow;
output CFunction outCFunction;
output Integer cg_out;
algorithm
str := matchcontinue(cg_in,daelow)
case (cg_in,DAELow.DAELOW(externalObjects = evars))
local
DAELow.Variables evars;
list<DAELow.Var> evarLst;
list<String> strs;
equation
evarLst = DAELow.varList(evars);
(outCFunction,cg_out) = generateExternalObjectConstructorAliases2(cg_in,evarLst);
then (outCFunction,cg_out);
end matchcontinue;
end generateExternalObjectConstructorAliases;
protected function generateExternalObjectConstructorAliases2 "
help function to generateExternalObjectConstructorAliases"
input Integer cg_in;
input list<DAELow.Var> varLst;
output CFunction outCFunction;
output Integer cg_out;
algorithm
(outCFunction,cg_out) := matchcontinue(cg_in,varLst)
local DAELow.Var v;
list<DAELow.Var> vs;
Codegen.CFunction cfunc,cfunc2;
case (cg_in,{})
then (Codegen.cEmptyFunction,cg_in);
case (cg_in,v::vs) equation
(cfunc,cg_out) = generateExternalObjectConstructorAliases2(cg_in,vs);
(cfunc2,cg_out) = generateExternalObjectConstructorAlias(cg_out,v);
cfunc = Codegen.cMergeFns({cfunc2,cfunc});
then (cfunc,cg_out);
end matchcontinue;
end generateExternalObjectConstructorAliases2;
protected function generateExternalObjectConstructorAlias
"Help function to generateExternalObjectConstructorAliases"
input Integer cg_in;
input DAELow.Var var;
output CFunction outCFunction;
output Integer cg_out;
algorithm
(outCFunction,cg_out) := matchcontinue (cg_in,var)
// external object aliased to another external object.
case (cg_in, DAELow.VAR(varName= name,bindExp = SOME(Exp.CREF(cr,_)),varKind = DAELow.EXTOBJ(path1)))
local String stmt,v_str,v_str2;
Codegen.CFunction cfunc;
Exp.ComponentRef cr,name;
Absyn.Path path1;
equation
v_str = Exp.printComponentRefStr(name);
v_str2 = Exp.printComponentRefStr(cr);
stmt = Util.stringAppendList({v_str," = ",v_str2,";\n"});
cfunc = Codegen.cAddStatements(Codegen.cEmptyFunction,{stmt});
then (cfunc,cg_in);
// Skip non-aliases constructors.
case (cg_in,_) then (Codegen.cEmptyFunction,cg_in);
end matchcontinue;
end generateExternalObjectConstructorAlias;
protected function generateExternalObjectConstructorCall "help function to generateExternalObjectConstructorCalls"
input Integer cg_in;
input DAELow.Var var;
input DAELow.ExternalObjectClasses eclasses;
output CFunction outCFunction;
output Integer cg_out;
algorithm
(outCFunction,cg_out) := matchcontinue (cg_in,var,eclasses)
// Skip aliases now, they are handled in generateExternalObjectConstructorAlias
case (cg_in, DAELow.VAR(bindExp = SOME(Exp.CREF(_,_)),varKind = DAELow.EXTOBJ(_)),_)
then (Codegen.cEmptyFunction,cg_in);
case (_,DAELow.VAR(varName = name),{})
local Exp.ComponentRef name;
equation
print("generateExternalObjectConstructorCall for var:");
print(Exp.printComponentRefStr(name));print(" failed\n");
then fail();
// found class
case (cg_in,DAELow.VAR(varName = name,bindExp = SOME(e),varKind = DAELow.EXTOBJ(path1)), DAELow.EXTOBJCLASS(path=path2,constructor=constr)::_)
local
DAE.Element constr;
Exp.ComponentRef name;
Absyn.Path path1,path2;
Exp.Exp e;
Codegen.CFunction cfunc;
equation
true = ModUtil.pathEqual(path1,path2);
(cfunc,cg_out) = generateExternalObjectConstructorCall2(cg_in,name,constr,e);
then (cfunc,cg_out);
// Try next class.
case (cg_in,var,_::eclasses)
local
Codegen.CFunction cfunc;
equation
(cfunc,cg_out) = generateExternalObjectConstructorCall(cg_in,var,eclasses);
then (cfunc,cg_out);
end matchcontinue;
end generateExternalObjectConstructorCall;
protected function generateExternalObjectConstructorCall2 "Help funciton to generateExternalObjectConstructorCall"
input Integer cg_in;
input Exp.ComponentRef varName;
input DAE.Element constructor;
input Exp.Exp constrCallExp;
output CFunction outCFunction;
output Integer cg_out;
algorithm
(outCFunction,cg_out) := matchcontinue(cg_in,varName,constructor,constrCallExp)
case (cg_in,varName,constructor as DAE.EXTFUNCTION(externalDecl = DAE.EXTERNALDECL(ident=funcStr)),Exp.CALL(expLst = args))
local
String vStr,funcStr,argsStr,str;
list<Exp.Exp> args;
list<String> vars1;
Codegen.CFunction cfunc;
equation
vStr = Exp.printComponentRefStr(varName);
/* TODO: cfn1 might contain additional code that is needed, also 0 must be propagated to prevent
resuing same variable name */
(cfunc,vars1,cg_out) = Codegen.generateExpressions(args, cg_in, Codegen.extContext);
argsStr = Util.stringDelimitList(vars1,", ");
str = Util.stringAppendList({" ",vStr," = ",funcStr,"(",argsStr,");"});
cfunc = Codegen.cAddStatements(cfunc,{str});
then (cfunc,cg_out);
end matchcontinue;
end generateExternalObjectConstructorCall2;
protected function generateInitializeDeinitializationDataStruc "
generates initializeDataStruc
to allocate all the different vectors i a DATA-struc
"
input DAELow.DAELow daelow;
output String outString "resulting C code";
protected Codegen.CFunction extObjDestructors,extObjConstructors,extObjConstructorAliases;
String extObjDestructors_str,extObjConstructors_str;
String extObjDestructorsDecl_str,extObjConstructorsDecl_str,extObjConstructorAliases_str;
Integer cg_out;
algorithm
(extObjDestructors,cg_out) := generateExternalObjectDestructorCalls(0,daelow);
(extObjConstructors,cg_out):= generateExternalObjectConstructorCalls(cg_out,daelow);
(extObjConstructorAliases,cg_out):= generateExternalObjectConstructorAliases(cg_out,daelow);
extObjDestructors_str := Codegen.cPrintStatements(extObjDestructors);
extObjConstructors_str := Codegen.cPrintStatements(extObjConstructors);
extObjConstructorAliases_str := Codegen.cPrintStatements(extObjConstructorAliases);
extObjDestructorsDecl_str := Codegen.cPrintDeclarations(extObjDestructors);
extObjConstructorsDecl_str := Codegen.cPrintDeclarations(extObjConstructors);
// Aliases has no declarations, skip printing them
outString:=Util.stringAppendList
(
{
"
void setLocalData(DATA* data)\n{\n
localData = data;\n}\n
DATA* initializeDataStruc(DATA_FLAGS flags)\n{\n",
extObjDestructorsDecl_str,
extObjConstructorsDecl_str,
" DATA* returnData = (DATA*)malloc(sizeof(DATA));\n
if(!returnData) //error check\n
return 0;\n
memset(returnData,0,sizeof(DATA))\n;
returnData->nStates = NX;\n
returnData->nAlgebraic = NY;\n
returnData->nParameters = NP;\n
returnData->nInputVars = NI;\n
returnData->nOutputVars = NO;\n
returnData->nZeroCrossing = NG;\n
returnData->nInitialResiduals = NR;\n
returnData->nHelpVars = NHELP;\n",
" returnData->stringVariables.nParameters = NPSTR;\n
returnData->stringVariables.nAlgebraic = NYSTR;\n",
" if(flags & STATES && returnData->nStates){\n
returnData->states = (double*) malloc(sizeof(double)*returnData->nStates);\n
returnData->oldStates = (double*) malloc(sizeof(double)*returnData->nStates);\n
returnData->oldStates2 = (double*) malloc(sizeof(double)*returnData->nStates);\n
assert(returnData->states&&returnData->oldStates&&returnData->oldStates2);
memset(returnData->states,0,sizeof(double)*returnData->nStates);\n
memset(returnData->oldStates,0,sizeof(double)*returnData->nStates);\n
memset(returnData->oldStates2,0,sizeof(double)*returnData->nStates);\n
}else{\n
returnData->states = 0;\n
returnData->oldStates = 0;\n
returnData->oldStates2 = 0;\n
}\n",
" if(flags & STATESDERIVATIVES && returnData->nStates){\n
returnData->statesDerivatives = (double*) malloc(sizeof(double)*returnData->nStates);\n
returnData->oldStatesDerivatives = (double*) malloc(sizeof(double)*returnData->nStates);\n
returnData->oldStatesDerivatives2 = (double*) malloc(sizeof(double)*returnData->nStates);\n
assert(returnData->statesDerivatives&&returnData->oldStatesDerivatives&&returnData->oldStatesDerivatives2);
memset(returnData->statesDerivatives,0,sizeof(double)*returnData->nStates);\n
memset(returnData->oldStatesDerivatives,0,sizeof(double)*returnData->nStates);\n
memset(returnData->oldStatesDerivatives2,0,sizeof(double)*returnData->nStates);\n
}else{\n
returnData->statesDerivatives = 0;\n
returnData->oldStatesDerivatives = 0;\n
returnData->oldStatesDerivatives2 = 0;\n
}\n",
" if(flags & HELPVARS && returnData->nHelpVars){\n
returnData->helpVars = (double*) malloc(sizeof(double)*returnData->nHelpVars);\n
assert(returnData->helpVars);
memset(returnData->helpVars,0,sizeof(double)*returnData->nHelpVars);
}else{\n
returnData->helpVars = 0;\n
}\n",
" if(flags & ALGEBRAICS && returnData->nAlgebraic){\n
returnData->algebraics = (double*) malloc(sizeof(double)*returnData->nAlgebraic);\n
returnData->oldAlgebraics = (double*) malloc(sizeof(double)*returnData->nAlgebraic);\n
returnData->oldAlgebraics2 = (double*) malloc(sizeof(double)*returnData->nAlgebraic);\n
assert(returnData->algebraics&&returnData->oldAlgebraics&&returnData->oldAlgebraics2);
memset(returnData->algebraics,0,sizeof(double)*returnData->nAlgebraic);\n
memset(returnData->oldAlgebraics,0,sizeof(double)*returnData->nAlgebraic);\n
memset(returnData->oldAlgebraics2,0,sizeof(double)*returnData->nAlgebraic);\n
}else{\n
returnData->algebraics = 0;\n
returnData->oldAlgebraics = 0;\n
returnData->oldAlgebraics2 = 0;\n
returnData->stringVariables.algebraics = 0;
}\n",
"if (flags & ALGEBRAICS && returnData->stringVariables.nAlgebraic) {
returnData->stringVariables.algebraics = (char**)malloc(sizeof(char*)*returnData->stringVariables.nAlgebraic);\n
assert(returnData->stringVariables.algebraics);\n
memset(returnData->stringVariables.algebraics,0,sizeof(char*)*returnData->stringVariables.nAlgebraic);\n
} else {
returnData->stringVariables.algebraics=0;\n
}",
" if(flags & PARAMETERS && returnData->nParameters){\n
returnData->parameters = (double*) malloc(sizeof(double)*returnData->nParameters);\n
assert(returnData->parameters);
memset(returnData->parameters,0,sizeof(double)*returnData->nParameters);
}else{\n
returnData->parameters = 0;\n
}\n",
"if (flags & PARAMETERS && returnData->stringVariables.nParameters) {
returnData->stringVariables.parameters = (char**)malloc(sizeof(char*)*returnData->stringVariables.nParameters);\n
assert(returnData->stringVariables.parameters);\n
memset(returnData->stringVariables.parameters,0,sizeof(char*)*returnData->stringVariables.nParameters);\n
} else {
returnData->stringVariables.parameters=0;\n
}",
" if(flags & OUTPUTVARS && returnData->nOutputVars){\n
returnData->outputVars = (double*) malloc(sizeof(double)*returnData->nOutputVars);\n
assert(returnData->outputVars);
memset(returnData->outputVars,0,sizeof(double)*returnData->nOutputVars);
}else{\n
returnData->outputVars = 0;\n
}\n",
" if(flags & INPUTVARS && returnData->nInputVars){\n
returnData->inputVars = (double*) malloc(sizeof(double)*returnData->nInputVars);\n
assert(returnData->inputVars);
memset(returnData->inputVars,0,sizeof(double)*returnData->nInputVars);
}else{\n
returnData->inputVars = 0;\n
}\n",
" if(flags & INITIALRESIDUALS && returnData->nInitialResiduals){\n
returnData->initialResiduals = (double*) malloc(sizeof(double)*returnData->nInitialResiduals);\n
assert(returnData->initialResiduals);
memset(returnData->initialResiduals,0,sizeof(double)*returnData->nInitialResiduals);
}else{\n
returnData->initialResiduals = 0;\n
}\n",
" if(flags & INITFIXED){\n
returnData->initFixed = init_fixed;\n
}else{\n
returnData->initFixed = 0;\n
}\n","
/* names */\n
if(flags & MODELNAME){\n
returnData->modelName = model_name;\n
}else{\n
returnData->modelName = 0;\n
}\n
if(flags & STATESNAMES){\n
returnData->statesNames = state_names;\n
}else{\n
returnData->statesNames = 0;\n
}\n",
"if(flags & STATESDERIVATIVESNAMES){\n
returnData->stateDerivativesNames = derivative_names;\n
}else{\n
returnData->stateDerivativesNames = 0;\n
}\n",
"if(flags & ALGEBRAICSNAMES){\n
returnData->algebraicsNames = algvars_names;\n
}else{\n
returnData->algebraicsNames = 0;\n
}\n",
"if(flags & PARAMETERSNAMES){\n
returnData->parametersNames = param_names;\n
}else{\n
returnData->parametersNames = 0;\n
}\n",
"if(flags & INPUTNAMES){\n
returnData->inputNames = input_names;\n
}else{\n
returnData->inputNames = 0;\n
}\n",
"if(flags & OUTPUTNAMES){\n
returnData->outputNames = output_names;\n
}else{\n
returnData->outputNames = 0;\n
}\n","
/* comments */\n