-
Notifications
You must be signed in to change notification settings - Fork 1
/
OMOctave.m
1060 lines (982 loc) · 32.9 KB
/
OMOctave.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
% PR-DC OpenModelica Octave Interface
% Author: Milos Petrasinovic <[email protected]>
% PR-DC, Republic of Serbia
%
% --------------------
%
% OMOctave - the OpenModelica Octave API is a free, open source,
% highly portable Octave-based interactive session handler for Modelica
% scripting. It provides the modeler with components for creating a complete
% Modelica modeling, compilation and simulation environment based on the latest
% OpenModelica library standard available. OMOctave is architectured to combine
% both the solving strategy and model building. So domain experts (people
% writing the models) and computational engineers (people writing the solver
% code) can work on one unified tool that is industrially viable for
% optimization of Modelica models, while offering a flexible platform for
% algorithm development and research. OMOctave is not a standalone package,
% it depends upon the OpenModelica installation.
% OMOctave is implemented in Octave and depends on ZeroMQ - high performance
% asynchronous messaging library via Octave Forge zeromq package and it
% supports the Modelica Standard Library version 3.2 that is included in
% starting with OpenModelica 1.9.2.
%
% To install OMOctave follow the instructions at
% https://github.com/PR-DC/OMOctave
%
% --------------------
%
% Copyright (C) 2021 PR-DC <[email protected]>
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as
% published by the Free Software Foundation, either version 3 of the
% License, or (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU Lesser General Public License for more details.
%
% You should have received a copy of the GNU Lesser General Public License
% along with this program. If not, see <https://www.gnu.org/licenses/>.
%
% --------------------
%
% This file is based on OMMatlab.m that is part of OpenModelica.
% Copyright (c) 1998-CurrentYear, Open Source Modelica Consortium (OSMC),
% c/o Linkopings universitet, Department of Computer and Information Science,
% SE-58183 Linkoping, 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 OMOctave < handle
properties (Access = public)
pid = 0
active
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', ...
'numberOfIntervals', '500', 'stepSize', '0.002', 'tolerance', '1e-6')
linearfile
linearFlag = false
linearmodelname
linearinputs
linearoutputs
linearstates
linearquantitylist
end
methods
function obj = OMOctave(omcpath)
obj.pkgForgeCheck('zeromq', '1.5.2')
% Prevent buffer output
more off
[~, randomstring] = fileparts(tempname);
if(ispc)
if nargin ~= 1
omhome = getenv('OPENMODELICAHOME');
omhomepath = strrep(fullfile(omhome, 'bin', 'omc.exe'), ...
'\', '/');
else
omhomepath = omcpath;
[omhome, ~] = fileparts(fileparts(omcpath));
end
% Add omhome to path environment variabel
path1 = getenv('PATH');
setenv('PATH', [path1 omhome]);
cmd = ['START /b "" "' omhomepath ...
'" --interactive=zmq +z=octave.' randomstring];
portfile = strcat('openmodelica.port.octave.', randomstring);
else
if(ismac && system("which omc") ~= 0)
if nargin ~= 1
omhome = '/opt/openmodelica/bin/omc';
else
omhome = omcpath;
end
cmd = [omhome ' --interactive=zmq -z=octave.' randomstring ' &'];
else
if(v)
omhome = 'omc';
else
omhome = omcpath;
end
cmd = [omhome ' --interactive=zmq -z=octave.' randomstring ' &'];
end
portfile = strcat('openmodelica.', getenv('USER'), ...
'.port.octave.', randomstring);
end
if(ispc)
[~, msg1] = system("tasklist");
pids1 = cell2mat(cell2mat(regexp(regexp(msg1, ...
'omc.exe[ ]+[0-9]+ Console', 'match'), '[0-9]+', 'match')));
end
system([cmd " >nul 2>nul"]);
if(ispc)
[~, msg2] = system("tasklist");
pids2 = cell2mat(cell2mat(regexp(regexp(msg2, ...
'omc.exe[ ]+[0-9]+ Console', 'match'), '[0-9]+', 'match')));
I = ismember(pids2, pids1);
obj.pid = pids2(find(~I));
end
obj.portfile = strrep(fullfile(tempdir, portfile), '\', '/');
while true
pause(0.01);
if(isfile(obj.portfile))
filedata = fileread(obj.portfile);
break;
end
end
try
obj.active = true;
obj.requester = zmq_socket(ZMQ_REQ);
zmq_connect(obj.requester, filedata);
catch
obj.active = false;
end
end
function reply = sendExpression(obj, expr, len)
if(obj.active)
if(nargin == 2)
len = 2^32;
end
zmq_send(obj.requester, expr, 0);
data = char(zmq_recv(obj.requester, len, 0));
% Parse replay and return in appropriate Octave
% structure if possible, otherwise return as normal strings
reply = obj.parseExpression(data);
else
error(["No connection with OMC. Create a new "...
"instance of OMOctave session"]);
reply = false;
end
end
function ModelicaSystem(obj, filename, modelname, libraries, ...
commandLineOptions)
if(nargin < 2)
error('Not enough arguments, filename and classname is required');
end
if(nargin == 1)
error([filename " does not exist"]);
end
% Check for commandLineOptions
if(nargin == 5)
exp = ["setCommandLineOptions(""" commandLineOptions """)"];
cmdExp = obj.sendExpression(exp);
if(iscell(cmdExp) && strcmp(cmdExp{1}, "false"))
disp(obj.sendExpression("getErrorString()"));
return;
end
end
filepath = strrep(filename, '\', '/');
loadfilemsg = obj.sendExpression(["loadFile( """ filepath """)"]);
if(iscell(loadfilemsg) && strcmp(loadfilemsg{1}, "false"))
disp(obj.sendExpression("getErrorString()"));
return;
end
% Check for libraries
if(nargin > 3)
for n = 1:length(libraries)
if(isfile(libraries{n}))
libmsg = obj.sendExpression(["loadFile( """ libraries{n} """)"]);
else
libmsg = obj.sendExpression(["[loadModel(" libraries{n} ")"]);
end
if(iscell(libmsg) && strcmp(libmsg{1}, "false"))
disp(obj.sendExpression("getErrorString()"));
return;
end
end
end
obj.filename = filename;
obj.modelname = modelname;
obj.mattempdir = strrep(tempname, '\', '/');
mkdir(obj.mattempdir);
obj.sendExpression(["cd(""" obj.mattempdir """)"]);
obj.BuildModelicaModel();
end
function BuildModelicaModel(obj)
buildModelResult = obj.sendExpression(["buildModel(" obj.modelname ")"]);
if(isempty(buildModelResult{1}))
disp(obj.sendExpression("getErrorString()"));
return;
end
xmlpath = fullfile(obj.mattempdir, char(buildModelResult(2)));
obj.xmlfile = strrep(xmlpath, '\', '/');
obj.xmlparse();
end
function workdir = getWorkDirectory(obj)
workdir = obj.mattempdir;
end
function xmlparse(obj)
if(isfile(obj.xmlfile))
xDoc = omxmlread(obj.xmlfile);
h = waitbar(0, 'Reading DefaultExperiment...', ...
'Name', 'OMOctave: xmlparse()');
% DefaultExperiment
allexperimentitems = ...
xDoc.getElementsByTagName('DefaultExperiment');
obj.simulationoptions.('startTime') = ...
char(allexperimentitems.getAttribute(1, 'startTime'));
obj.simulationoptions.('stopTime') = ...
char(allexperimentitems.getAttribute(1, 'stopTime'));
obj.simulationoptions.('stepSize') = ...
char(allexperimentitems.getAttribute(1, 'stepSize'));
obj.simulationoptions.('tolerance') = ...
char(allexperimentitems.getAttribute(1, 'tolerance'));
obj.simulationoptions.('solver') = ...
char(allexperimentitems.getAttribute(1, 'solver'));
% ScalarVariables
allvaritem = xDoc.getElementsByTagName('ScalarVariable');
N = allvaritem.getLength;
t = tic;
fields = {'name', 'isValueChangeable', 'description', ...
'variability', 'causality', 'alias', 'aliasVariable'};
for k = 1:N
if(k ==1 || ~mod(k, round(N/100)))
frac = k/N;
waitbar(frac, h, ['Reading ScalarVariables ' ...
num2str(frac*100, '%.0f') '% [' num2str(k) '/' ...
num2str(N) '] dt = ' num2str(toc(t), '%.1f') ' s...']);
t = tic;
end
scalar = struct();
item = allvaritem.item(k);
[~, s_idx] = ismember(fields, item.attribute_keys);
for i = 1:length(fields);
if(s_idx(i))
scalar.(fields{i}) = item.attributes(s_idx(i)).value;
else
scalar.(fields{i}) = [];
end
end
if(length(item.children))
sub = xDoc.item(item.children(1));
if(strcmp(sub.tag, 'Real'))
[~, s_idx] = ismember('start', sub.attribute_keys);
if(s_idx)
scalar.('value') = char(sub.attributes(s_idx).value);
else
scalar.('value') = '';
end
else
scalar.('value') = '';
end
end
% Check for variability parameter and add to parameter list
if(obj.linearFlag == false)
name = scalar.('name');
value = scalar.('value');
if(strcmp(scalar.('variability'), 'parameter'))
try
obj.parameterlist.(name) = value;
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)];
end
if(name(2) == 'u')
obj.linearinputs = [obj.linearinputs, name(4:end-1)];
end
if(name(2) == 'y')
obj.linearoutputs = [obj.linearoutputs, name(4:end-1)];
end
end
obj.linearquantitylist = [obj.linearquantitylist, scalar];
else
obj.quantitieslist = [obj.quantitieslist, scalar];
end
end
close(h);
else
error("xmlfile is not generated");
end
end
function result = getQuantities(obj, args)
if(nargin > 1)
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 = tmpresult;
else
result = obj.quantitieslist;
end
end
function result = getLinearQuantities(obj, args)
if(nargin > 1)
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 = tmpresult;
else
result = obj.linearquantitylist;
end
end
function result = getParameters(obj, args)
if(nargin > 1)
if(iscell(args))
param = {};
for n = 1:length(args)
param{n} = obj.parameterlist.(args{n});
end
else
param = obj.parameterlist.(args);
end
result = param;
else
result = obj.parameterlist;
end
end
function result = getInputs(obj, args)
if(nargin > 1)
if(iscell(args))
inputs = {};
for n = 1:length(args)
inputs{n} = obj.inputlist.(args{n});
end
else
inputs = obj.inputlist.(args);
end
result = inputs;
else
result = obj.inputlist;
end
end
function result = getOutputs(obj, args)
if(nargin > 1)
if(iscell(args))
outputs = {};
for n = 1:length(args)
outputs{n} = obj.outputlist.(args{n});
end
else
outputs = obj.outputlist.(args);
end
result = outputs;
else
result = obj.outputlist;
end
end
function result = getContinuous(obj, args)
if(nargin > 1)
if(iscell(args))
continuous = {};
for n = 1:length(args)
continuous{n} = obj.continuouslist.(args{n});
end
else
continuous = obj.continuouslist.(args);
end
result = continuous;
else
result = obj.continuouslist;
end
end
function result = getSimulationOptions(obj, args)
if(nargin > 1)
if(iscell(args))
simoptions = {};
for n = 1:length(args)
simoptions{n} = obj.simulationoptions.(args{n});
end
else
simoptions = obj.simulationoptions.(args);
end
result = simoptions;
else
result = obj.simulationoptions;
end
end
function result = getLinearizationOptions(obj, args)
if(nargin > 1)
if(iscell(args))
linoptions = {};
for n = 1:length(args)
linoptions{n} = obj.linearOptions.(args{n});
end
else
linoptions = obj.linearOptions.(args);
end
result = linoptions;
else
result = obj.linearOptions;
end
end
% Set Methods
function setParameters(obj, args)
if(nargin > 1)
if(~iscell(args))
args = {args};
end
for n = 1:length(args)
val = strrep(args{n}, " ", "");
value = strsplit(val, "=");
if(isfield(obj.parameterlist, char(value{1})))
obj.parameterlist.(value{1}) = value{2};
obj.overridevariables.(value{1}) = value{2};
else
disp([value{1} " is not a parameter"]);
end
end
end
end
function setSimulationOptions(obj, args)
if(nargin > 1)
if(~iscell(args))
args = {args};
end
for n = 1:length(args)
val = strrep(args{n}, " ", "");
value = strsplit(val, "=");
if(isfield(obj.simulationoptions, char(value{1})))
obj.simulationoptions.(value{1}) = value{2};
obj.simoptoverride.(value{1}) = value{2};
else
disp([value{1} " is not a Simulation Option"]);
end
end
end
end
function setLinearizationOptions(obj, args)
if(nargin > 1)
if(~iscell(args))
args = {args};
end
for n = 1:length(args)
val = strrep(args{n}, " ", "");
value = strsplit(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"]);
end
end
end
end
function setInputs(obj, args)
if(nargin > 1)
if(~iscell(args))
args = {args};
end
for n = 1:length(args)
val = strrep(args{n}, " ", "");
value = strsplit(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"]);
end
end
end
end
function createcsvData(obj)
obj.csvfile = strrep(fullfile(obj.mattempdir, ...
[char(obj.modelname) '.csv']), '\', '/');
fileID = fopen(obj.csvfile, "w");
fprintf(fileID, ['time,' strjoin(fieldnames(obj.inputlist), ",") ...
',end\n']);
fields = fieldnames(obj.inputlist);
time = [];
count = 1;
tmpcsvdata = struct;
for i = 1:length(fieldnames(obj.inputlist))
var = obj.inputlist.(fields{i});
if(isempty(var))
var = "0";
end
s1 = eval(strrep(strrep(strrep(strrep(var, "[", "{"), ...
"]", "}"), "(", "{"), ")", "}"));
tmpcsvdata.(char(fields(i))) = s1;
if(length(s1) > 1)
for j = 1:length(s1)
t = s1(j);
time = [time, t{1}{1}];
count = count+1;
end
end
end
if(isempty(time))
time = [str2double(obj.simulationoptions.('startTime')), ...
str2double(obj.simulationoptions.('stopTime'))];
end
t1 = struct2cell(tmpcsvdata);
sortedtime = sort(time);
previousvalue = struct;
for t = 1:length(sortedtime)
fprintf(fileID, [num2str(sortedtime(t)) ',']);
listcount = 1;
for i = 1:length(t1)
tmp1 = t1{i};
if(iscell(tmp1))
found = false;
for k = 1:length(tmp1)
if(sortedtime(t) == tmp1{k}{1})
data = tmp1{k}{2};
fprintf(fileID, [num2str(data) ',']);
pfieldname = ["x" char(listcount)];
previousvalue.(pfieldname) = data;
tmp1(k) = [];
t1{i} = tmp1;
found = true;
break;
end
end
if(found == false)
tmpfieldname = ["x" char(listcount)];
data = previousvalue.(tmpfieldname);
fprintf(fileID, [num2str(data) ',']);
end
else
fprintf(fileID, [num2str(t1{i}) ',']);
end
listcount = listcount+1;
end
fprintf(fileID, [num2str(0) '\n']);
end
fclose(fileID);
end
function simulate(obj, resultfile, simflags)
if(nargin > 1)
if(~isempty(resultfile))
r = [' -r=' char(resultfile)];
obj.resultfile=strrep(fullfile(obj.mattempdir, ...
char(resultfile)), '\', '/');
else
r = '';
end
else
r = '';
obj.resultfile = strrep(fullfile(obj.mattempdir, ...
[char(obj.modelname) '_res.mat']), '\', '/');
end
if(nargin > 2)
simflags = [' ' char(simflags)];
else
simflags = '';
end
if(isfile(obj.xmlfile))
if(ispc)
getexefile = strrep(fullfile(obj.mattempdir, ...
[char(obj.modelname) '.exe']), '\', '/');
else
getexefile = strrep(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 = {};
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})];
end
overridevar = [' -override=' char(strjoin(tmpoverride1, ','))];
else
overridevar = '';
end
if(obj.inputflag == true)
obj.createcsvData()
csvinput = [' -csvInput=' obj.csvfile];
else
csvinput = '';
end
finalsimulationexe = [getexefile, overridevar, csvinput, ...
r, simflags];
system(finalsimulationexe);
else
disp("Model cannot be Simulated: executable not found")
end
cd(curdir)
else
disp("Model cannot be Simulated: xmlfile not found")
end
end
function result = linearize(obj)
linres = obj.sendExpression(...
"setCommandLineOptions(""+generateSymbolicLinearization"")");
if(iscell(linres) && strcmp(linres{1}, "false"))
disp(["Linearization cannot be performed"...
obj.sendExpression("getErrorString()")]);
return;
end
fields = fieldnames(obj.overridevariables);
tmpoverride1 = {};
for i = 1:length(fields)
tmpoverride1{i} = [fields{i} "=" ...
obj.overridevariables.(fields{i})];
end
if(~isempty(tmpoverride1))
tmpoverride2 = [' -override=', char(strjoin(tmpoverride1, ','))];
else
tmpoverride2 = "";
end
linfields = fieldnames(obj.linearOptions);
tmpoverride1lin = {};
for i = 1:length(linfields)
tmpoverride1lin{i} = [linfields{i} "="...
obj.linearOptions.(linfields{i})];
end
overridelinear = char(strjoin(tmpoverride1lin, ','));
if(obj.inputflag == true)
obj.createcsvData()
csvinput = ['-csvInput=' obj.csvfile];
else
csvinput = "";
end
linexpr = strcat('linearize(', obj.modelname, ',', ...
overridelinear, ',', 'simflags=', '"', ...
csvinput, ' ', tmpoverride2, '")');
res = obj.sendExpression(linexpr);
obj.resultfile = res.("resultFile");
obj.linearmodelname = strcat('linear_', obj.modelname);
obj.linearfile = strrep(fullfile(obj.mattempdir, ...
[char(obj.linearmodelname) '.mo']), '\', '/');
if(isfile(obj.linearfile))
loadmsg = obj.sendExpression(["loadFile(""" obj.linearfile """)"]);
if(iscell(loadmsg) && strcmp(loadmsg{1}, "false"))
disp(obj.sendExpression("getErrorString()"));
return;
end
cNames = obj.sendExpression("getClassNames()");
buildmodelexpr = ["buildModel(" cNames{1} ")"];
buildModelmsg = obj.sendExpression(buildmodelexpr);
if(~isempty(buildModelmsg{1}))
obj.linearFlag = true;
obj.xmlfile = strrep(...
fullfile(obj.mattempdir, char(buildModelmsg(2))), '\', '/');
obj.linearquantitylist = [];
obj.linearinputs = "";
obj.linearoutputs = "";
obj.linearstates = "";
obj.xmlparse();
result = obj.getLinearMatrix();
else
disp(omc.sendExpression("getErrorString()"));
end
end
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;
end
function result = getLinearMatrixValues(~, matrix_name)
if(~isempty(matrix_name))
fields = fieldnames(matrix_name);
t = fields{end};
rows = str2double(t(3));
columns = str2double(t(5));
tmpMatrix = zeros(rows, columns, 'double');
for i = 1:length(fields)
n = fields{i};
r = str2double(n(3));
c = str2double(n(5));
val = str2double(matrix_name.(fields{i}));
format shortG
tmpMatrix(r, c) = val;
end
result = tmpMatrix;
else
result = 0;
end
end
function result = getLinearInputs(obj)
if(obj.linearFlag == true)
result = obj.linearinputs;
else
disp("Model is not Linearized");
result = false;
end
end
function result = getLinearOutputs(obj)
if(obj.linearFlag == true)
result = obj.linearoutputs;
else
disp("Model is not Linearized");
result = false;
end
end
function result = getLinearStates(obj)
if(obj.linearFlag == true)
result = obj.linearstates;
else
disp("Model is not Linearized");
result = false;
end
end
function result = getSolutions(obj, args, resultfile)
if(nargin > 2)
resfile = char(resultfile);
else
resfile = obj.resultfile;
end
if(isfile(resfile))
if(nargin > 1 && ~isempty(args))
tmp1 = strjoin(cellstr(args), ',');
tmp2 = ['{', tmp1, '}'];
simresult = obj.sendExpression([ ...
"readSimulationResult(""" resfile """," tmp2 ")"]);
obj.sendExpression("closeSimulationResultFile()");
result = simresult;
else
tmp = obj.sendExpression(["readSimulationResultVars(""" ...
resfile """)"]);
obj.sendExpression("closeSimulationResultFile()");
result = tmp;
end
else
result = ["Result File does not exist! " char(resfile)];
disp(result);
end
end
function createValidNames(obj, name, value, structname)
% Function which creates valid field name as Octave
% 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
tmpname = matlab.lang.makeValidName(name);
obj.mappednames.(tmpname) = name;
if(strcmp(structname, 'continuous'))
obj.continuouslist.(tmpname) = value;
end
if(strcmp(structname, 'parameter'))
obj.parameterlist.(tmpname) = value;
end
if(strcmp(structname, 'input'))
obj.inputlist.(tmpname) = value;
end
if(strcmp(structname, 'output'))
obj.outputlist.(tmpname) = value;
end
end
function result = parseExpression(obj, args)
final = regexp(args, '"(.*?)"|[{}()=]|[a-zA-Z0-9_.]+', 'match');
if(length(final) > 1)
if(strcmp(char(final{1}), "{") && ~strcmp(char(final{2}), "{"))
buff = {};
count = 1;
for i = 1:length(final)
if(~any(ismember(char(final{i}), {"{", "}", ")", "(", ","})))
value = strrep(final{i}, """", "");
buff{count} = value;
count = count+1;
end
end
result = buff;
elseif(strcmp(char(final{1}), "{") && strcmp(char(final{2}), "{"))
buff = {};
tmpcount = 1;
count = 1;
for i = 2:length(final)-1
if(strcmp(char(final{i}), "{"))
if(isnan(str2double(final{i+1})))
tmp = "";
else
tmp = [];
end
elseif(strcmp(char(final{i}), "}"))
buff{tmpcount} = tmp;
tmp = {};
count = 1;
tmpcount = tmpcount+1;
else
tmp{count} = char(final{i});
count = count+1;
end
end
result = buff;
elseif(strcmp(final{1}, "record"))
result = struct;
for i = 3:length(final)-2
if(strcmp(char(final{i}), "="))
value = strrep(final{i+1}, """", "");
result.(final{i-1}) = value;
end
end
elseif(strcmp(final{1}, "fail"))
result = obj.sendExpression("getErrorString()");
else
result = strrep(args, """", "");
end
elseif(length(final) == 1)
result = strrep(final, """", "");