-
Notifications
You must be signed in to change notification settings - Fork 4
/
OMMatlab.m
1088 lines (1030 loc) · 47.1 KB
/
OMMatlab.m
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-CurrentYear, Open Source Modelica Consortium (OSMC),
% c/o Linköpings universitet, Department of Computer and Information Science,
% SE-58183 Linköping, Sweden.
%
% All rights reserved.
%
% THIS PROGRAM IS PROVIDED UNDER THE TERMS OF THE BSD NEW LICENSE OR THE
% GPL VERSION 3 LICENSE OR THE OSMC PUBLIC LICENSE (OSMC-PL) VERSION 1.2.
% ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES
% RECIPIENT'S ACCEPTANCE OF THE OSMC PUBLIC LICENSE OR THE GPL VERSION 3,
% ACCORDING TO RECIPIENTS CHOICE.
%
% The OpenModelica software and the OSMC (Open Source Modelica Consortium)
% Public License (OSMC-PL) are obtained from OSMC, either from the above
% address, from the URLs: http://www.openmodelica.org or
% http://www.ida.liu.se/projects/OpenModelica, and in the OpenModelica
% distribution. GNU version 3 is obtained from:
% http://www.gnu.org/copyleft/gpl.html. The New BSD License is obtained from:
% http://www.opensource.org/licenses/BSD-3-Clause.
%
% 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.
classdef OMMatlab < handle
properties (Access = private)
process
context
requester
portfile
filename
modelname
xmlfile
resultfile=''
csvfile=''
mattempdir=''
simulationoptions=struct
quantitieslist
parameterlist=struct
continuouslist=struct
inputlist=struct
outputlist=struct
mappednames=struct
overridevariables=struct
simoptoverride=struct
inputflag=false
linearOptions=struct('startTime','0.0','stopTime','1.0','stepSize','0.002','tolerance','1e-6')
linearfile
linearFlag=false
linearmodelname
linearinputs
linearoutputs
linearstates
linearStateIndex
linearInputIndex
linearOutputIndex
linearquantitylist
varFilter
%fileid
end
methods
function obj = OMMatlab(omcpath)
%randomstring = char(97 + floor(26 .* rand(10,1)))';
[~,randomstring]=fileparts(tempname);
if ispc
if ~exist('omcpath', 'var')
omhome = getenv('OPENMODELICAHOME');
omhomepath = replace(fullfile(omhome,'bin','omc.exe'),'\','/');
%add omhome to path environment variabel
%path1 = getenv('PATH');
%path1 = [path1, ';', fullfile(omhome,'bin')];
%disp(path1)
%setenv('PATH', path1);
%cmd ="START /b "+omhomepath +" --interactive=zmq +z=matlab."+randomstring;
cmd = ['START /b',' ',omhomepath,' --interactive=zmq -z=matlab.',randomstring];
else
[dirname1,~]=fileparts(fileparts(omcpath));
%disp(dirname1)
cmd = ['START /b',' ',omcpath,' --interactive=zmq -z=matlab.',randomstring];
end
portfile = strcat('openmodelica.port.matlab.',randomstring);
else
if ismac && system("which omc") ~= 0
%cmd =['/opt/openmodelica/bin/omc --interactive=zmq -z=matlab.',randomstring,' &'];
if ~exist('omcpath', 'var')
cmd =['/opt/openmodelica/bin/omc --interactive=zmq -z=matlab.',randomstring, ' >log.txt', ' &'];
else
cmd =[omcpath, ' --interactive=zmq -z=matlab.',randomstring, ' >log.txt', ' &'];
end
else
%cmd =['omc --interactive=zmq -z=matlab.',randomstring,' &'];
if ~exist('omcpath', 'var')
cmd =['omc --interactive=zmq -z=matlab.',randomstring, ' >log.txt', ' &'];
else
cmd =[omcpath, ' --interactive=zmq -z=matlab.',randomstring, ' >log.txt', ' &'];
end
end
portfile = strcat('openmodelica.',getenv('USER'),'.port.matlab.',randomstring);
end
%disp(cmd)
system(cmd);
%pause(0.2);
obj.portfile = replace(fullfile(tempdir,portfile),'\','/');
while true
pause(0.01);
if(isfile(obj.portfile))
filedata=fileread(obj.portfile);
break;
end
end
import org.zeromq.*
obj.context=ZMQ.context(1);
obj.requester =obj.context.socket(ZMQ.REQ);
%obj.portfile=replace(fullfile(tempdir,portfile),'\','/');
%obj.fileid=fileread(obj.portfile);
obj.requester.connect(filedata);
end
function reply = sendExpression(obj,expr)
%%TODO check for omc process is running or not in a generic way
%if(~obj.process.HasExited)
obj.requester.send(expr,0);
data=obj.requester.recvStr(0);
% Parse java string object and return in appropriate matlab
% structure if possible, otherwise return as normal strings
reply=parseExpression(obj,string(data));
%else
%disp("Process Exited, No connection with OMC. Create a new instance of OMMatlab session");
%return
%end
end
function ModelicaSystem(obj,filename,modelname,libraries,commandLineOptions,variableFilter,customBuildDirectory)
if (nargin < 2)
error('Not enough arguments, filename and classname is required');
end
if ~exist(filename, 'file')
msg=filename +" does not exist";
error(msg);
return;
end
% check for commandLineOptions
if exist('commandLineOptions', 'var') && ~isempty(commandLineOptions)
exp=join(["setCommandLineOptions(","""",commandLineOptions,"""",")"]);
cmdExp=obj.sendExpression(exp);
if(cmdExp == "false")
disp(obj.sendExpression("getErrorString()"));
return;
end
end
% set default command Line Options for linearization as
% linearize() will use the simulation executable and runtime
% flag -l to perform linearization
obj.sendExpression("setCommandLineOptions(""--linearizationDumpLanguage=matlab"")");
obj.sendExpression("setCommandLineOptions(""--generateSymbolicLinearization"")")
filepath = replace(filename,'\','/');
%disp(filepath);
loadfilemsg=obj.sendExpression("loadFile( """+ filepath +""")");
if (loadfilemsg=="false")
disp(obj.sendExpression("getErrorString()"));
return;
end
% check for libraries
if exist('libraries', 'var') && ~isempty(libraries)
%disp("library given");
if isa(libraries, 'struct')
fields=fieldnames(libraries);
for i=1:length(fieldnames(libraries))
loadLibraryHelper(obj, fields(i), libraries.(fields{i}));
end
elseif isa(libraries, 'string')
for n=1:length(libraries)
loadLibraryHelper(obj, libraries{n});
end
elseif isa(libraries, 'cell')
for n=1:length(libraries)
if isa(libraries{n}, 'struct')
fields=fieldnames(libraries{n});
for i=1:length(fieldnames(libraries{n}))
loadLibraryHelper(obj, fields(i), libraries{n}.(fields{i}));
end
elseif isa(libraries{n}, 'string')
loadLibraryHelper(obj, libraries{n});
end
end
else
fprintf("| info | loadLibrary() failed, Unknown type detected:, The following patterns are supported \n1).""Modelica""\n2).[""Modelica"", ""PowerSystems""]\n3).struct(""Modelica"", ""3.2.3"")\n");
return;
end
end
obj.filename = filename;
obj.modelname = modelname;
%tmpdirname = char(97 + floor(26 .* rand(15,1)))';
if exist('variableFilter', 'var') && ~isempty(variableFilter)
obj.varFilter = join(["variableFilter=","""", variableFilter, """"]);
else
obj.varFilter = join(["variableFilter=","""",".*",""""]);
end
if exist('customBuildDirectory', 'var') && ~isempty(customBuildDirectory)
if ~isfolder(customBuildDirectory)
error(customBuildDirectory, " does not exist");
return
end
obj.mattempdir = replace(char(customBuildDirectory),'\','/');
else
obj.mattempdir = replace(tempname,'\','/');
mkdir(obj.mattempdir);
end
obj.sendExpression("cd("""+ obj.mattempdir +""")")
buildModel(obj)
end
function loadLibraryHelper(obj, libname, version)
if(isfile(libname))
libmsg = obj.sendExpression("loadFile( """+ libname +""")");
if (libmsg=="false")
disp(obj.sendExpression("getErrorString()"));
return;
end
else
if exist('version', 'var')
libname = strcat("loadModel(", libname, ", ", "{", """", version, """", "}", ")");
else
libname = strcat("loadModel(", libname, ")");
end
%disp(libname)
libmsg = obj.sendExpression(libname);
if (libmsg=="false")
disp(obj.sendExpression("getErrorString()"));
return;
end
end
end
function buildModel(obj)
buildmodelexpr = join(["buildModel(",obj.modelname,", ", replace(obj.varFilter," ",""),")"]);
%disp(buildmodelexpr);
buildModelResult = obj.sendExpression(buildmodelexpr);
%r2=split(erase(string(buildModelResult),["{","}",""""]),",");
%disp(r2);
if(isempty(char(buildModelResult(1))))
disp(obj.sendExpression("getErrorString()"));
return;
end
%xmlpath =strcat(obj.mattempdir,'\',r2{2});
xmlpath=fullfile(obj.mattempdir,char(buildModelResult(2)));
obj.xmlfile = replace(xmlpath,'\','/');
xmlparse(obj);
end
function workdir = getWorkDirectory(obj)
workdir = obj.mattempdir;
return;
end
function xmlparse(obj)
if isfile(obj.xmlfile)
xDoc=xmlread(obj.xmlfile);
% DefaultExperiment %
allexperimentitems = xDoc.getElementsByTagName('DefaultExperiment');
obj.simulationoptions.('startTime') = char(allexperimentitems.item(0).getAttribute('startTime'));
obj.simulationoptions.('stopTime') = char(allexperimentitems.item(0).getAttribute('stopTime'));
obj.simulationoptions.('stepSize') = char(allexperimentitems.item(0).getAttribute('stepSize'));
obj.simulationoptions.('tolerance') = char(allexperimentitems.item(0).getAttribute('tolerance'));
obj.simulationoptions.('solver') = char(allexperimentitems.item(0).getAttribute('solver'));
% ScalarVariables %
allvaritem = xDoc.getElementsByTagName('ScalarVariable');
for k = 0:allvaritem.getLength-1
scalar=struct;
scalar.('name')=char(allvaritem.item(k).getAttribute('name'));
scalar.('changeable')=char(allvaritem.item(k).getAttribute('isValueChangeable'));
scalar.('description')=char(allvaritem.item(k).getAttribute('description'));
scalar.('variability')=char(allvaritem.item(k).getAttribute('variability'));
scalar.('causality') =char(allvaritem.item(k).getAttribute('causality'));
scalar.('alias')=char(allvaritem.item(k).getAttribute('alias'));
scalar.('aliasVariable')=char(allvaritem.item(k).getAttribute('aliasVariable'));
scalar.('aliasVariableId')=char(allvaritem.item(k).getAttribute('aliasVariableId'));
% iterate subchild to find start values of all types
childNode = getFirstChild(allvaritem.item(k));
while ~isempty(childNode)
if childNode.getNodeType == childNode.ELEMENT_NODE
if childNode.hasAttribute('start')
%disp(name + "=" + char(childNode.getAttribute('start')) + "=" + attr)
scalar.('start') = char(childNode.getAttribute('start'));
else
scalar.('start') = 'None';
end
if childNode.hasAttribute('min')
scalar.('min') = char(childNode.getAttribute('min'));
else
scalar.('min') = 'None';
end
if childNode.hasAttribute('max')
scalar.('max') = char(childNode.getAttribute('max'));
else
scalar.('max') = 'None';
end
%scalar.('value')=value;
end
childNode = getNextSibling(childNode);
end
% check for variability parameter and add to parameter list
if(obj.linearFlag==false)
name=scalar.('name');
value=scalar.('start');
if(strcmp(scalar.('variability'),'parameter'))
try
if isfield(obj.overridevariables, name)
obj.parameterlist.(name) = obj.overridevariables.(name);
else
obj.parameterlist.(name) = value;
end
catch ME
createvalidnames(obj,name,value,"parameter");
end
end
% check for variability continuous and add to continuous list
if(strcmp(scalar.('variability'),'continuous'))
try
obj.continuouslist.(name) = value;
catch ME
createvalidnames(obj,name,value,"continuous");
end
end
% check for causality input and add to input list
if(strcmp(scalar.('causality'),'input'))
try
obj.inputlist.(name) = value;
catch ME
createvalidnames(obj,name,value,"input");
end
end
% check for causality output and add to output list
if(strcmp(scalar.('causality'),'output'))
try
obj.outputlist.(name) = value;
catch ME
createvalidnames(obj,name,value,"output");
end
end
end
if(obj.linearFlag==true)
if(scalar.('alias')=="alias")
name=scalar.('name');
if (name(2) == 'x')
obj.linearstates=[obj.linearstates,name(4:end-1)];
obj.linearStateIndex=[obj.linearStateIndex, str2double(char(scalar.('aliasVariableId')))];
end
if (name(2) == 'u')
obj.linearinputs=[obj.linearinputs,name(4:end-1)];
obj.linearInputIndex=[obj.linearInputIndex, str2double(char(scalar.('aliasVariableId')))];
end
if (name(2) == 'y')
obj.linearoutputs=[obj.linearoutputs,name(4:end-1)];
obj.linearOutputIndex=[obj.linearOutputIndex, str2double(char(scalar.('aliasVariableId')))];
end
end
obj.linearquantitylist=[obj.linearquantitylist,scalar];
else
obj.quantitieslist=[obj.quantitieslist,scalar];
end
end
else
msg="xmlfile is not generated";
error(msg);
return;
end
end
function result= getQuantities(obj,args)
if isempty(obj.quantitieslist)
result = [];
return;
end
if exist('args', 'var')
tmpresult=[];
for n=1:length(args)
for q=1:length(obj.quantitieslist)
if(strcmp(obj.quantitieslist(q).name,args(n)))
tmpresult=[tmpresult;obj.quantitieslist(q)];
end
end
end
result=struct2table(tmpresult,'AsArray',true);
else
result=struct2table(obj.quantitieslist,'AsArray',true);
end
return;
end
function result= getLinearQuantities(obj,args)
if exist('args', 'var')
tmpresult=[];
for n=1:length(args)
for q=1:length(obj.linearquantitylist)
if(strcmp(obj.linearquantitylist(q).name,args(n)))
tmpresult=[tmpresult;obj.linearquantitylist(q)];
end
end
end
result=struct2table(tmpresult,'AsArray',true);
else
result=struct2table(obj.linearquantitylist,'AsArray',true);
end
return;
end
function result = getParameters(obj,args)
if exist('args', 'var')
param=strings(1,length(args));
for n=1:length(args)
param(n) = obj.parameterlist.(args(n));
end
result = param;
else
result = obj.parameterlist;
end
return;
end
function result = getInputs(obj,args)
if exist('args', 'var')
inputs=strings(1,length(args));
for n=1:length(args)
inputs(n) = obj.inputlist.(args(n));
end
result = inputs;
else
result = obj.inputlist;
end
return;
end
function result = getOutputs(obj,args)
if exist('args', 'var')
outputs=strings(1,length(args));
for n=1:length(args)
outputs(n) = obj.outputlist.(args(n));
end
result = outputs;
else
result = obj.outputlist;
end
return;
end
function result = getContinuous(obj,args)
if exist('args', 'var')
continuous=strings(1,length(args));
for n=1:length(args)
continuous(n) = obj.continuouslist.(args(n));
end
result = continuous;
else
result = obj.continuouslist;
end
return;
end
function result = getSimulationOptions(obj,args)
if exist('args', 'var')
simoptions=strings(1,length(args));
for n=1:length(args)
simoptions(n) = obj.simulationoptions.(args(n));
end
result = simoptions;
else
result = obj.simulationoptions;
end
return;
end
function result = getLinearizationOptions(obj,args)
if exist('args', 'var')
linoptions=strings(1,length(args));
for n=1:length(args)
linoptions(n) = obj.linearOptions.(args(n));
end
result = linoptions;
else
result = obj.linearOptions;
end
return;
end
% Set Methods
function setParameters(obj,args)
if exist('args', 'var')
for n=1:length(args)
val=replace(args(n)," ","");
value=split(val,"=");
if(isfield(obj.parameterlist,char(value(1))))
if isParameterChangeable(obj, value(1), value(2))
obj.parameterlist.(value(1))= value(2);
obj.overridevariables.(value(1))= value(2);
end
else
disp(value(1) + " is not a parameter");
return;
end
end
end
end
% check for parameter modifiable or not
function result = isParameterChangeable(obj, name, value)
if (isfield(obj.mappednames, char(name)))
tmpname = obj.mappednames.(name);
else
tmpname = name;
end
q = getQuantities(obj, string(tmpname));
if q.changeable{1} == "false"
disp("| info | setParameters() failed : It is not possible to set the following signal " + """" + name + """" + ", It seems to be structural, final, protected or evaluated or has a non-constant binding, use sendExpression(setParameterValue("+ obj.modelname + ", " + name + ", " + value + "), parsed=false)" + " and rebuild the model using buildModel() API")
result = false;
return;
end
result = true;
return;
end
function setSimulationOptions(obj,args)
if exist('args', 'var')
for n=1:length(args)
val=replace(args(n)," ","");
value=split(val,"=");
if(isfield(obj.simulationoptions,char(value(1))))
obj.simulationoptions.(value(1))= value(2);
obj.simoptoverride.(value(1)) = value(2);
%obj.overridevariables.(value(1))= value(2);
else
disp(value(1) + " is not a Simulation Option");
return;
end
end
end
end
function setLinearizationOptions(obj,args)
if exist('args', 'var')
for n=1:length(args)
val=replace(args(n)," ","");
value=split(val,"=");
if(isfield(obj.linearOptions,char(value(1))))
obj.linearOptions.(value(1))= value(2);
obj.linearOptions.(value(1))= value(2);
else
disp(value(1) + " is not a Linearization Option");
return;
end
end
end
end
function setInputs(obj,args)
if exist('args', 'var')
for n=1:length(args)
val=replace(args(n)," ","");
value=split(val,"=");
if(isfield(obj.inputlist,char(value(1))))
obj.inputlist.(value(1))= value(2);
obj.inputflag=true;
else
disp(value(1) + " is not a Input");
return;
end
end
end
end
function createcsvData(obj, startTime, stopTime)
obj.csvfile = replace(fullfile(obj.mattempdir,[char(obj.modelname),'.csv']),'\','/');
fileID = fopen(obj.csvfile,"w");
%disp(strjoin(fieldnames(obj.inputlist),","));
fields=fieldnames(obj.inputlist);
% check for mapped names incase of array vars
fprintf(fileID, "time,");
for i=1:length(fields)
if (isfield(obj.mappednames, char(fields(i))))
mappedNames = obj.mappednames.(fields{i});
else
mappedNames = char(fields(i));
end
fprintf(fileID, [mappedNames, ',']);
end
fprintf(fileID, "end\n");
%csvdata = obj.inputlist;
%time=strings(1,length(csvdata));
time=[];
count=1;
tmpcsvdata=struct;
for i=1:length(fieldnames(obj.inputlist))
%disp(fields(i));
%disp(obj.inputlist.(fields{i}));
%disp("loop"+ num2str(i))
%disp(fields{i})
var = obj.inputlist.(fields{i});
if(isempty(var))
var="0";
end
s1 = eval(replace(replace(replace(replace(var,"[","{"),"]","}"),"(","{"),")","}"));
tmpcsvdata.(char(fields(i))) = s1;
%csvdata.()=s1;
%disp(length(s1));
if(length(s1)>1)
for j=1:length(s1)
t = s1(j);
%disp(t{1}{1});
%time(count)=t{1}{1};
time=[time,t{1}{1}];
count=count+1;
end
end
end
%disp(tmpcsvdata)
%disp(length(time))
if(isempty(time))
time=[str2double(startTime),str2double(stopTime)];
end
t1=struct2cell(tmpcsvdata);
%disp(length(t1))
sortedtime=sort(time);
previousvalue=struct;
for t=1:length(sortedtime)
fprintf(fileID,[num2str(sortedtime(t)),',']);
%fprintf(fileID,[char(sortedtime(t)),',']);
listcount=1;
for i=1:length(t1)
tmp1=t1{i};
if(iscell(tmp1))
%disp("length is :" + length(tmp1))
found=false;
for k=1:length(tmp1)
if(sortedtime(t)==tmp1{k}{1})
%disp(sortedtime(t)+ "=>" + tmp1{k}{1})
data=tmp1{k}{2};
%disp(sortedtime(t)+ "=>" + data)
fprintf(fileID,[num2str(data),',']);
%pfieldname=matlab.lang.makeValidName(string(listcount));
pfieldname="x"+string(listcount);
previousvalue.(pfieldname)=data;
tmp1(k)=[];
t1{i}=tmp1;
found=true;
break;
end
end
if(found==false)
%disp(previousvalue)
%disp(string(listcount))
tmpfieldname="x"+string(listcount);
%disp("false loop" + previousvalue.(tmpfieldname))
data=previousvalue.(tmpfieldname);
fprintf(fileID,[num2str(data),',']);
end
else
%disp("strings found" + t1{i})
%disp(class(t1{i}))
%fprintf(fileID,'%s',t1{i},',');
fprintf(fileID,[num2str(t1{i}),',']);
end
listcount=listcount+1;
end
fprintf(fileID,[num2str(0),'\n']);
%disp(sortedtime(t) + "****************************")
end
fclose(fileID);
end
function simulate(obj,resultfile,simflags)
if exist('resultfile', 'var')
%disp(resultfile);
if ~isempty(resultfile)
r=join([' -r=',char(resultfile)]);
obj.resultfile=replace(fullfile(obj.mattempdir,char(resultfile)),'\','/');
else
r='';
end
else
r='';
obj.resultfile=replace(fullfile(obj.mattempdir,[char(obj.modelname),'_res.mat']),'\','/');
end
if exist('simflags', 'var')
simflags=join([' ',char(simflags)]);
else
simflags='';
end
if(isfile(obj.xmlfile))
if (ispc)
getexefile = replace(fullfile(obj.mattempdir,[char(obj.modelname),'.exe']),'\','/');
%disp(getexefile)
else
getexefile = replace(fullfile(obj.mattempdir,char(obj.modelname)),'\','/');
end
curdir=pwd;
if(isfile(getexefile))
cd(obj.mattempdir)
if(~isempty(fieldnames(obj.overridevariables)) || ~isempty(fieldnames(obj.simoptoverride)))
names = [fieldnames(obj.overridevariables); fieldnames(obj.simoptoverride)];
tmpstruct = cell2struct([struct2cell(obj.overridevariables); struct2cell(obj.simoptoverride)], names, 1);
fields=fieldnames(tmpstruct);
tmpoverride1=strings(1,length(fields));
overridefile = replace(fullfile(obj.mattempdir,[char(obj.modelname),'_override.txt']),'\','/');
fileID = fopen(overridefile,"w");
for i=1:length(fields)
if (isfield(obj.mappednames,fields(i)))
name=obj.mappednames.(fields{i});
else
name=fields(i);
end
tmpoverride1(i)=name+"="+tmpstruct.(fields{i});
fprintf(fileID,tmpoverride1(i));
fprintf(fileID,"\n");
end
fclose(fileID);
%disp(overridefile)
overridevar=join([' -overrideFile=',overridefile]);
else
overridevar='';
end
if(obj.inputflag==true)
obj.createcsvData(obj.simulationoptions.('startTime'), obj.simulationoptions.('stopTime'))
csvinput=join([' -csvInput=',obj.csvfile]);
else
csvinput='';
end
finalsimulationexe = [getexefile,overridevar,csvinput,r,simflags];
%disp(finalsimulationexe);
if ispc
omhome = getenv('OPENMODELICAHOME');
%set dll path needed for windows simulation
dllpath = [replace(fullfile(omhome,'bin'),'\','/'),';',replace(fullfile(omhome,'lib/omc'),'\','/'),';',replace(fullfile(omhome,'lib/omc/cpp'),'\','/'),';',replace(fullfile(omhome,'lib/omc/omsicpp'),'\','/'),';',getenv('PATH')];
%disp(dllpath);
system(['set PATH=' dllpath ' && ' finalsimulationexe])
else
system(finalsimulationexe);
end
%obj.resultfile=replace(fullfile(obj.mattempdir,[char(obj.modelname),'_res.mat']),'\','/');
else
disp("Model cannot be Simulated: executable not found")
end
cd(curdir)
%disp(pwd)
else
disp("Model cannot be Simulated: xmlfile not found")
end
end
function result = linearize(obj, lintime, simflags)
%linearize(SeborgCSTR.ModSeborgCSTRorg,startTime=0.0,stopTime=1.0,numberOfIntervals=500,stepSize=0.002,tolerance=1e-6,simflags="-csvInput=C:/Users/arupa54/AppData/Local/Temp/jl_59DA.tmp/SeborgCSTR.ModSeborgCSTRorg.csv -override=a=2.0")
if exist('simflags', 'var')
simflags=join([' ',char(simflags)]);
else
simflags='';
end
% check for override variables and their associated mapping
names = [fieldnames(obj.overridevariables); fieldnames(obj.linearOptions)];
tmpstruct = cell2struct([struct2cell(obj.overridevariables); struct2cell(obj.linearOptions)], names, 1);
fields=fieldnames(tmpstruct);
tmpoverride1=strings(1,length(fields));
overridelinearfile = replace(fullfile(obj.mattempdir,[char(obj.modelname),'_override_linear.txt']),'\','/');
fileID = fopen(overridelinearfile,"w");
for i=1:length(fields)
if (isfield(obj.mappednames,fields(i)))
name=obj.mappednames.(fields{i});
else
name=fields(i);
end
tmpoverride1(i)=name+"="+tmpstruct.(fields{i});
fprintf(fileID,tmpoverride1(i));
fprintf(fileID,"\n");
end
fclose(fileID);
if(~isempty(tmpoverride1))
tmpoverride2=join([' -overrideFile=',overridelinearfile]);
else
tmpoverride2='';
end
if(obj.inputflag==true)
obj.createcsvData(obj.linearOptions.('startTime'), obj.linearOptions.('stopTime'))
csvinput=join([' -csvInput=',obj.csvfile]);
else
csvinput='';
end
if(isfile(obj.xmlfile))
if (ispc)
getexefile = replace(fullfile(obj.mattempdir,[char(obj.modelname),'.exe']),'\','/');
%disp(getexefile)
else
getexefile = replace(fullfile(obj.mattempdir,char(obj.modelname)),'\','/');
end
else
disp("Linearization cannot be performed as : " + obj.xmlfile + " not found, which means the model is not buid")
end
%linexpr=strcat('linearize(',obj.modelname,',',overridelinear,',','simflags=','"',csvinput,' ',tmpoverride2,'")');
if exist('lintime', 'var')
linruntime=join([getexefile, ' -l=', char(lintime)]);
else
linruntime=join([getexefile, ' -l=', char(obj.linearOptions.('stopTime'))]);
end
finallinearizationexe =[linruntime,tmpoverride2,csvinput,simflags];
%disp(finallinearizationexe)
curdir=pwd;
cd(obj.mattempdir);
if ispc
omhome = getenv('OPENMODELICAHOME');
%set dll path needed for windows simulation
dllpath = [replace(fullfile(omhome,'bin'),'\','/'),';',replace(fullfile(omhome,'lib/omc'),'\','/'),';',replace(fullfile(omhome,'lib/omc/cpp'),'\','/'),';',replace(fullfile(omhome,'lib/omc/omsicpp'),'\','/'),';',getenv('PATH')];
%disp(dllpath);
system(['set PATH=' dllpath ' && ' finallinearizationexe])
else
system(finallinearizationexe);
end
%obj.resultfile=res.("resultFile");
obj.linearmodelname=strcat('linearized_model');
obj.linearfile=replace(fullfile(obj.mattempdir,[char(obj.linearmodelname),'.m']),'\','/');
% support older openmodelica versions before OpenModelica v1.16.2
% where linearize() generates "linear_modelname.mo" file
if(~isfile(obj.linearfile))
obj.linearmodelname=strcat('linear_',obj.modelname);
obj.linearfile=replace(fullfile(obj.mattempdir,[char(obj.linearmodelname),'.m']),'\','/');
end
if(isfile(obj.linearfile))
%addpath(obj.getWorkDirectory());
% this function is called from the generated matlab code
% linearized_model.m
[A, B, C, D, stateVars, inputVars, outputVars] = linearized_model();
result = {A, B, C, D};
obj.linearstates = replace(stateVars,{'(',')'},{'[',']'});
obj.linearinputs = replace(inputVars,{'(',')'},{'[',']'});
obj.linearoutputs = replace(outputVars,{'(',')'},{'[',']'});
obj.linearFlag = true;
else
disp("Linearization failed: " + obj.linearfile + " not found")
disp(obj.sendExpression("getErrorString()"))
return;
end
cd(curdir);
end
function result = getLinearMatrix(obj)
matrix_A=struct;
matrix_B=struct;
matrix_C=struct;
matrix_D=struct;
for i=1:length(obj.linearquantitylist)
name=obj.linearquantitylist(i).("name");
value= obj.linearquantitylist(i).("value");
if( obj.linearquantitylist(i).("variability")=="parameter")
if(name(1)=='A')
tmpname=matlab.lang.makeValidName(name);
matrix_A.(tmpname)=value;
end
if(name(1)=='B')
tmpname=matlab.lang.makeValidName(name);
matrix_B.(tmpname)=value;
end
if(name(1)=='C')
tmpname=matlab.lang.makeValidName(name);
matrix_C.(tmpname)=value;
end
if(name(1)=='D')
tmpname=matlab.lang.makeValidName(name);
matrix_D.(tmpname)=value;
end
end
end
FullLinearMatrix={};
tmpMatrix_A=getLinearMatrixValues(obj,matrix_A);
tmpMatrix_B=getLinearMatrixValues(obj,matrix_B);
tmpMatrix_C=getLinearMatrixValues(obj,matrix_C);
tmpMatrix_D=getLinearMatrixValues(obj,matrix_D);
FullLinearMatrix{1}=tmpMatrix_A;
FullLinearMatrix{2}=tmpMatrix_B;
FullLinearMatrix{3}=tmpMatrix_C;
FullLinearMatrix{4}=tmpMatrix_D;
result=FullLinearMatrix;
return;
end
function result = getLinearMatrixValues(~,matrix_name)
if(~isempty(fieldnames(matrix_name)))
fields=fieldnames(matrix_name);
t=fields{end};
rows_char=extractBetween(t,string(t(1:2)),"_");
rows=str2double(rows_char);
columns_char=extractBetween(t,string(rows_char)+"_","_");
columns=str2double(columns_char);
tmpMatrix=zeros(rows,columns,'double');
for i=1:length(fields)
n=fields{i};
r_char=extractBetween(n,string(n(1:2)),"_");
r=str2double(r_char);
c_char=extractBetween(n,string(r_char)+"_","_");
c=str2double(c_char);
val=str2double(matrix_name.(fields{i}));
format shortG
tmpMatrix(r,c)=val;
end
result=tmpMatrix;
else
result=zeros(0,0);
end
end
function result = getLinearInputs(obj)
if(obj.linearFlag==true)
%[sortedinput, index] = sort(obj.linearInputIndex);
result=obj.linearinputs();
else
disp("Model is not Linearized");
end
return;
end
function result = getLinearOutputs(obj)
if(obj.linearFlag==true)
%[sortedoutput, index] = sort(obj.linearOutputIndex);
result=obj.linearoutputs();
else
disp("Model is not Linearized");
end
return;
end
function result = getLinearStates(obj)
if(obj.linearFlag==true)
%[sortedstates, index] = sort(obj.linearStateIndex);
result=obj.linearstates();
else
disp("Model is not Linearized");
end
return;
end
function result = getSolutions(obj,args,resultfile)
if exist('resultfile', 'var')
resfile = char(resultfile);
else
resfile = obj.resultfile;
end
if(isfile(resfile))
tmp1=obj.sendExpression("readSimulationResultVars(""" + resfile + """)");
obj.sendExpression("closeSimulationResultFile()");
if exist('args', 'var') && ~isempty(args)
for i=1:length(args)
if (~ismember(args(i), tmp1) && ~strcmp(args(i),"time"))
disp(char(args(i))+ " does not exist in result file " + char(resfile));
return;
end
end
tmp1=strjoin(cellstr(args),',');
tmp2=['{',tmp1,'}'];
simresult=obj.sendExpression("readSimulationResult(""" + resfile + ""","+tmp2+")");
obj.sendExpression("closeSimulationResultFile()");
result=simresult;
else
result = tmp1;
end
return;
else
result= "Result File does not exist! " + char(resfile);
disp(result);
return;
end
end
% function which creates valid field name as matlab
% does not allow der(h) to be a valid name, also map
% the changed names to mappednames struct, inorder to
% keep track of the original names as it is needed to query
% simulation results