-
Notifications
You must be signed in to change notification settings - Fork 49
/
Model.cpp
1442 lines (1176 loc) · 44.7 KB
/
Model.cpp
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 GPL VERSION 3 LICENSE OR
* THIS 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 Open Source Modelica
* Consortium (OSMC) Public License (OSMC-PL) are obtained
* from OSMC, either from the above address,
* from the URLs: http://www.ida.liu.se/projects/OpenModelica or
* http://www.openmodelica.org, and in the OpenModelica distribution.
* GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html.
*
* 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.
*
*/
#include "Model.h"
#include "Component.h"
#include "CSVWriter.h"
#include "Flags.h"
#include "MATWriter.h"
#include "OMSFileSystem.h"
#include "OMSString.h"
#include "Scope.h"
#include "ssd/Tags.h"
#include "System.h"
#include <minizip.h>
#include <thread>
oms::Model::Model(const oms::ComRef& cref, const std::string& tempDir)
: cref(cref), tempDir(tempDir), resultFilename(std::string(cref) + "_res.mat")
{
if (!Flags::SuppressPath())
logInfo("New model \"" + std::string(cref) + "\" with corresponding temp directory \"" + tempDir + "\"");
elements.push_back(NULL);
elements.push_back(NULL);
}
oms::Model::~Model()
{
terminate();
if (system)
delete system;
// delete temp directory
if (Flags::DeleteTempFiles())
{
if (!tempDir.empty() && filesystem::is_directory(tempDir))
{
try
{
filesystem::remove_all(tempDir);
logDebug("removed temp directory: \"" + tempDir + "\"");
}
catch (const std::exception& e)
{
logWarning("temp directory \"" + tempDir + "\" couldn't be removed\n" + e.what());
}
}
}
}
oms::Model* oms::Model::NewModel(const oms::ComRef& cref)
{
if (!cref.isValidIdent())
{
logError_InvalidIdent(cref);
return NULL;
}
filesystem::path tempDir = (filesystem::path(Scope::GetInstance().getTempDirectory().c_str()) / oms_unique_path(std::string(cref))).string();
if (filesystem::is_directory(tempDir))
{
logError("Unique temp directory does already exist. Clean up the temp directory \"" + Scope::GetInstance().getTempDirectory() + "\" and try again.");
return NULL;
}
if (!filesystem::create_directory(tempDir))
{
logError("Failed to create unique temp directory for the model \"" + std::string(cref) + "\"");
return NULL;
}
if (!filesystem::create_directory(tempDir / "temp"))
{
logError("Failed to create temp directory for the model \"" + std::string(cref) + "\"");
return NULL;
}
if (!filesystem::create_directory(tempDir / "resources"))
{
logError("Failed to create resources directory for the model \"" + std::string(cref) + "\"");
return NULL;
}
oms::Model* model = new oms::Model(cref, tempDir.string());
return model;
}
oms_status_enu_t oms::Model::rename(const oms::ComRef& cref)
{
if (!cref.isValidIdent())
return logError(std::string(cref) + " is not a valid ident");
this->cref = cref;
if (system)
{
system->renameConnectors();
for (const auto & it:system->getSubSystems())
it.second->renameConnectors();
}
return oms_status_ok;
}
oms_status_enu_t oms::Model::rename(const ComRef& cref, const ComRef& newCref)
{
if (!newCref.isValidIdent())
return logError(std::string(newCref) + " is not a valid ident");
if (!system)
return logError("Model \"" + std::string(getCref()) + "\" does not contain any system");
// renaming the model
if (cref.isEmpty())
return this->rename(newCref);
// renaming any subcomponent
oms::ComRef tail(cref);
oms::ComRef front = tail.pop_front();
if (system->getCref() == front)
return system->rename(tail, newCref);
return logError("Model \"" + std::string(getCref()) + "\" does not contain system \"" + std::string(front) + "\"");
}
oms_status_enu_t oms::Model::loadSnapshot(const pugi::xml_node& node)
{
// This method will not change the name of the model.
// If a renaming is requested then it will happen in Scope::loadSnapshot.
if (!validState(oms_modelState_virgin))
return logError_ModelInWrongState(getCref());
System* old_root_system = system;
system = NULL;
Snapshot snapshot; // this is a temporary workaroud, loadSnapshot will be removed later
snapshot.importResourceNode("SystemStructure.ssd", node);
//snapshot.debugPrintAll();
bool old_copyResources = copyResources();
copyResources(false);
oms_status_enu_t status = importFromSnapshot(snapshot);
copyResources(old_copyResources);
if (oms_status_ok != status)
{
system = old_root_system;
return logError("loading snapshot failed");
}
if (old_root_system)
{
delete old_root_system;
old_root_system = NULL;
}
return oms_status_ok;
}
oms_status_enu_t oms::Model::duplicateVariant(const ComRef& crefA, const ComRef& crefB)
{
if (!crefA.isEmpty())
return logError("only top level model is allowed");
// copy the current snapshot
char* fullsnapshot = NULL;
exportSnapshot("", &fullsnapshot);
listVariants.push_back(fullsnapshot);
// set the current variantName
this->variantName = std::string(crefB) + ".ssd";
this->signalFilterFilename = "resources/signalFilter_" + std::string(crefB) + ".xml";
return oms_status_ok;
}
oms_status_enu_t oms::Model::importSnapshot(const char* snapshot_, char** newCref)
{
if (!validState(oms_modelState_virgin))
return logError_ModelInWrongState(getCref());
Snapshot snapshot;
snapshot.import(snapshot_);
//snapshot.debugPrintAll();
// get the new root cref from the snapshot, this should be done here
// at the top before importing the full snapshot, as the new cref
// will be overwritten
new_root_cref = snapshot.getRootCref();
if (snapshot.isPartialSnapshot())
{
char* fullsnapshot;
// get full snapshot
exportSnapshot("", &fullsnapshot);
snapshot.importPartialSnapshot(fullsnapshot);
free(fullsnapshot);
}
// get ssd:SystemStructureDescription
pugi::xml_node ssdNode = snapshot.getResourceNode("SystemStructure.ssd");
ComRef new_cref = ComRef(ssdNode.attribute("name").as_string());
std::string ssdVersion = ssdNode.attribute("version").as_string();
// check new_cref exists in scope
if (new_cref != getCref() && Scope::GetInstance().getModel(new_cref))
return logError("Renaming the model \"" + std::string(getCref()) + "\" to \"" + std::string(new_cref) + "\" failed because another model with the same name already exists in the scope.");
if (ssdVersion != "Draft20180219" && ssdVersion != "1.0")
logWarning("Unknown SSD version: " + ssdVersion);
System* old_root_system = system;
system = NULL;
bool old_copyResources = copyResources();
copyResources(false);
oms_status_enu_t status = importFromSnapshot(snapshot);
copyResources(old_copyResources);
if (oms_status_ok != status)
{
system = old_root_system;
return logError("loading snapshot failed");
}
if (old_root_system)
{
delete old_root_system;
old_root_system = NULL;
}
if (newCref)
*newCref = (char*)new_root_cref.c_str();
// rename model
if (new_cref != getCref())
Scope::GetInstance().renameModel(getCref(), new_cref);
return oms_status_ok;
}
oms::System* oms::Model::getSystem(const oms::ComRef& cref)
{
if (!system)
return NULL;
if (cref.isEmpty())
return system;
oms::ComRef tail(cref);
oms::ComRef front = tail.pop_front();
if (this->system->getCref() == front)
return system->getSystem(tail);
return NULL;
}
oms::Component* oms::Model::getComponent(const oms::ComRef& cref)
{
if (!system)
return NULL;
oms::ComRef tail(cref);
oms::ComRef front = tail.pop_front();
if (this->system->getCref() == front)
return system->getComponent(tail);
return NULL;
}
oms_status_enu_t oms::Model::delete_(const oms::ComRef& cref)
{
oms::ComRef tail(cref);
oms::ComRef front = tail.pop_front();
if (!system || front != system->getCref())
return oms_status_error;
if (tail.isEmpty())
{
delete system;
system = NULL;
return oms_status_ok;
}
else
return system->delete_(tail);
}
oms_status_enu_t oms::Model::list(const oms::ComRef& cref, char** contents)
{
struct xmlStringWriter : pugi::xml_writer
{
std::string result;
virtual void write(const void* data, size_t size)
{
result += std::string(static_cast<const char*>(data), size);
}
};
xmlStringWriter writer;
pugi::xml_document doc;
Snapshot snapshot;
// check for toplevelSystem or Model to update parameterbindings in ssd
bool isTopSystemOrModel = false;
// list model
if (cref.isEmpty())
{
isTopSystemOrModel = true;
exportToSSD(snapshot);
doc.append_copy(snapshot.getResourceNode("SystemStructure.ssd"));
}
else
{
// list system
if (!system)
return logError("Model \"" + std::string(getCref()) + "\" does not contain any system");
System* subsystem = getSystem(cref);
// check for topLevel System, to update parameterBindings in ssd
if (cref.isValidIdent())
isTopSystemOrModel = true;
if (subsystem)
{
pugi::xml_node ssdNode = snapshot.getTemplateResourceNodeSSD("SystemStructure.ssd", this->getCref());
pugi::xml_node system_node = ssdNode.append_child(oms::ssp::Draft20180219::ssd::system);
subsystem->exportToSSD(system_node, snapshot, this->variantName);
doc.append_copy(snapshot.getResourceNode("SystemStructure.ssd").first_child());
}
else
{
// list component
Component* component = getComponent(cref);
if (!component)
return logError("error");
pugi::xml_node ssdNode = snapshot.getTemplateResourceNodeSSD("SystemStructure.ssd", this->getCref());
pugi::xml_node system_node = ssdNode.append_child(oms::ssp::Draft20180219::ssd::system);
component->exportToSSD(system_node, snapshot, this->variantName);
doc.append_copy(snapshot.getResourceNode("SystemStructure.ssd").first_child());
}
}
doc.save(writer);
*contents = mallocAndCopyString(writer.result);
if (!*contents)
return oms_status_fatal;
return oms_status_ok;
}
oms_status_enu_t oms::Model::exportSnapshot(const oms::ComRef& cref, char** contents)
{
Snapshot snapshot;
exportToSSD(snapshot);
exportSignalFilter(snapshot);
if (cref.isEmpty())
return snapshot.writeDocument(contents);
// query for partial snapshot
Snapshot partialSnapshot(true);
snapshot.exportPartialSnapshot(cref, partialSnapshot);
return partialSnapshot.writeDocument(contents);
}
oms_status_enu_t oms::Model::exportSSVTemplate(const oms::ComRef& cref, const std::string& filename)
{
oms::ComRef tail(cref);
oms::ComRef front = tail.pop_front();
pugi::xml_document ssvdoc;
// generate XML declaration for ssm file
pugi::xml_node ssvDeclarationNode = ssvdoc.append_child(pugi::node_declaration);
ssvDeclarationNode.append_attribute("version") = "1.0";
ssvDeclarationNode.append_attribute("encoding") = "UTF-8";
std::string extension = "";
if (filename.length() > 4)
extension = filename.substr(filename.length() - 4);
if (extension != ".ssv")
return logError("filename extension must be \".ssv\"; no other formats are supported");
Snapshot snapshot;
pugi::xml_node ssvNode = snapshot.getTemplateResourceNodeSSV("template.ssv", "modelDescriptionStartValues");
for (const auto& component : system->getComponents())
{
if(component.first == tail || cref.isEmpty() || cref.isValidIdent()) // allow querying single component or whole model
{
if (oms_status_ok != component.second->exportToSSVTemplate(ssvNode, snapshot))
{
return logError("export of ssv template failed for component " + std::string(system->getFullCref()+std::string(component.first)));
}
}
}
// check in subsystems
ComRef tailA(tail);
ComRef frontA = tailA.pop_front();
//std::cout <<"\n subsystem: " << tailA.c_str() << "==>" << frontA.c_str() << "==>" << cref.c_str();
for (const auto &subsytem : system->getSubSystems())
{
for (const auto &component : subsytem.second->getComponents())
{
if (component.first == tailA || cref.isEmpty() || (system->getSystem(frontA) && tailA.isEmpty()))
{
if (oms_status_ok != component.second->exportToSSVTemplate(ssvNode, snapshot))
{
return logError("export of ssv template failed for component " + std::string(system->getFullCref() + std::string(component.first)));
}
}
}
}
//ssvdoc.save(std::cout);
ssvdoc.append_copy(snapshot.getResourceNode("template.ssv"));
if (!ssvdoc.save_file(filename.c_str(), " ", pugi::format_indent|pugi::format_indent_attributes, pugi::encoding_utf8))
return logError("failed to export \"" + filename + "\" (for model \"" + std::string(this->getCref()) + "\")");
return oms_status_ok;
}
oms_status_enu_t oms::Model::exportSSMTemplate(const oms::ComRef& cref, const std::string& filename)
{
oms::ComRef tail(cref);
oms::ComRef front = tail.pop_front();
pugi::xml_document ssmdoc;
// generate XML declaration for ssm file
pugi::xml_node ssmDeclarationNode = ssmdoc.append_child(pugi::node_declaration);
ssmDeclarationNode.append_attribute("version") = "1.0";
ssmDeclarationNode.append_attribute("encoding") = "UTF-8";
std::string extension = "";
if (filename.length() > 4)
extension = filename.substr(filename.length() - 4);
if (extension != ".ssm")
return logError("filename extension must be \".ssm\"; no other formats are supported");
Snapshot snapshot;
pugi::xml_node ssmNode = snapshot.getTemplateResourceNodeSSM("template.ssm");
for (const auto& component : system->getComponents())
{
if(component.first == tail || cref.isEmpty()) // allow querying single component or whole model
{
if (oms_status_ok != component.second->exportToSSMTemplate(ssmNode))
{
return logError("export of ssm template failed for component " + std::string(system->getFullCref()+std::string(component.first)));
}
}
}
//ssmdoc.save(std::cout);
ssmdoc.append_copy(snapshot.getResourceNode("template.ssm"));
if (!ssmdoc.save_file(filename.c_str(), " ", pugi::format_indent|pugi::format_indent_attributes, pugi::encoding_utf8))
return logError("failed to export \"" + filename + "\" (for model \"" + std::string(this->getCref()) + "\")");
return oms_status_ok;
}
/*
* This function update the ParameterBindings in SSD, to link with a SSV file, (e.g)
* <ssd:ParameterBindings>
* <ssd:ParameterBinding source="resources/import_export_parameters.ssv" />
* </ssd:ParameterBindings>
*/
oms_status_enu_t oms::Model::updateParameterBindingsToSSD(pugi::xml_node& node, bool isTopSystemOrModel) const
{
// check parameter bindings exist and export to ssv file and also update the ssd file with parameterBindings at the top level
if (isTopSystemOrModel)
{
// update the ssd with the top level parameterBindings (e.g) <ParameterBinding source="resources/ControlledTemperature.ssv">
for(pugi::xml_node_iterator it = node.begin(); it != node.end(); ++it)
{
if (std::string(it->name()) == oms::ssp::Draft20180219::ssd::elements) // insert the parameter bindings after top-level connectors node
{
pugi::xml_node node_parameters_bindings = node.insert_child_before(oms::ssp::Version1_0::ssd::parameter_bindings, *it);
pugi::xml_node node_parameter_binding = node_parameters_bindings.append_child(oms::ssp::Version1_0::ssd::parameter_binding);
std::string ssvFileName = "resources/" + std::string(this->getCref()) + ".ssv";
node_parameter_binding.append_attribute("source") = ssvFileName.c_str();
break;
}
}
}
return oms_status_ok;
}
oms_status_enu_t oms::Model::newResources(const oms::ComRef& cref)
{
ComRef subCref(cref);
const std::string fileName = subCref.pop_suffix();
if (fileName.empty())
return logError("resource file not provided for \"" + std::string(getCref()+cref) + "\", Provide a valid reference file eg: \"model.root:test1.ssv\"");
std::string extension = "";
if (fileName.length() > 4)
extension = fileName.substr(fileName.length() - 4);
if (extension != ".ssv")
return logError("filename extension for \"" + std::string(getCref() + cref) + "\" must be \".ssv\", no other formats are supported");
if (system)
return system->newResources(subCref, fileName);
return oms_status_ok;
}
oms_status_enu_t oms::Model::addResources(const oms::ComRef& cref, const std::string& path)
{
filesystem::path path_ = oms_canonical(path);
if (!filesystem::exists(path_))
return logError("file does not exist: \"" + path + "\"");
ComRef subCref(cref);
std::string fileName = subCref.pop_suffix();
// get the filename from path, if no name provided
if (fileName.empty())
{
filesystem::path path_(path);
fileName = path_.filename().generic_string();
}
// copy the file to temp directory
filesystem::path temp_root(getTempDirectory());
filesystem::path temp_temp = temp_root / "temp";
filesystem::path relFMUPath = filesystem::path("resources/" + fileName);
filesystem::path absFMUPath = temp_root / relFMUPath;
oms_copy_file(filesystem::path(path), absFMUPath);
// push to external resources
externalResources.push_back("resources/"+ fileName);
return oms_status_ok;
}
oms_status_enu_t oms::Model::referenceResources(const oms::ComRef& cref, const std::string& ssmFile)
{
ComRef subCref(cref);
std::string fileName = subCref.pop_suffix();
if (fileName.empty())
return logError("reference file not provided for \"" + std::string(getCref() + cref) + "\", hence switching reference file to a new \".ssv\" or \".ssm\" cannot be done.");
std::string ssvExtension = "";
if (fileName.length() > 4)
ssvExtension = fileName.substr(fileName.length() - 4);
if (ssvExtension != ".ssv")
return logError("filename extension for \"" + std::string(getCref() + cref) + "\" must be \".ssv\", no other formats are supported");
if (!ssmFile.empty())
{
std::string ssmExtension = "";
if (ssmFile.length() > 4)
ssmExtension = ssmFile.substr(ssmFile.length() - 4);
if (ssmExtension != ".ssm")
return logError("filename extension for \"" + ssmFile + "\" must be \".ssm\", no other formats are supported");
}
if (system)
return system->newResources(subCref, fileName, ssmFile, true);
return oms_status_ok;
}
oms_status_enu_t oms::Model::reduceSSV(const std::string& ssvfile, const std::string& ssmfile, const std::string& filepath)
{
filesystem::path ssvpath_ = oms_canonical(ssvfile);
if (!filesystem::exists(ssvfile))
return logError("ssvfile does not exist: \"" + ssvfile + "\"");
filesystem::path ssmpath_ = oms_canonical(ssmfile);
if (!filesystem::exists(ssmfile))
return logError("ssmfile does not exist: \"" + ssmfile + "\"");
std::string ssvFilename = ssvpath_.filename().generic_string();
std::string ssmFilename = ssmpath_.filename().generic_string();
Snapshot snapshot;
snapshot.importResourceFile(ssvFilename, ssvpath_.remove_filename());
snapshot.importResourceFile(ssmFilename, ssmpath_.remove_filename());
values.importFromSnapshot(snapshot, ssvFilename, ssmFilename);
//snapshot.debugPrintAll();
pugi::xml_document ssvdoc;
// generate XML declaration for ssm file
pugi::xml_node ssvDeclarationNode = ssvdoc.append_child(pugi::node_declaration);
ssvDeclarationNode.append_attribute("version") = "1.0";
ssvDeclarationNode.append_attribute("encoding") = "UTF-8";
std::string savePath = "";
if (filepath.empty())
savePath = "reduced.ssv";
else
savePath = filepath;
pugi::xml_node ssvNode = snapshot.getTemplateResourceNodeSSV(savePath, "reducedSSV");
values.exportReduceSSV(ssvNode, this->getCref());
ssvdoc.append_copy(snapshot.getResourceNode(savePath));
if (!ssvdoc.save_file(savePath.c_str(), " ", pugi::format_indent|pugi::format_indent_attributes, pugi::encoding_utf8))
return logError("failed to export \"" + savePath + "\" (for model \"" + std::string(this->getCref()) + "\")");
return oms_status_ok;
}
oms_status_enu_t oms::Model::deleteReferencesInSSD(const oms::ComRef& cref)
{
ComRef subCref(cref);
std::string fileName = subCref.pop_suffix();
if (fileName.empty())
return logError("reference file not provided for \"" + std::string(getCref()+cref) + "\", hence deleting reference file cannot be done. Provide a valid reference file eg: \"model.root:test1.ssv\"");
std::string extension = "";
if (fileName.length() > 4)
extension = fileName.substr(fileName.length() - 4);
if (extension != ".ssv" && extension != ".ssm")
return logError("filename extension for \"" + std::string(getCref() + cref) + "\" must be \".ssv\" or \".ssm\", no other formats are supported");
if (system)
return system->deleteReferencesInSSD(subCref, fileName);
return oms_status_ok;
}
oms_status_enu_t oms::Model::deleteResourcesInSSP(const std::string & fileName)
{
if (fileName.empty())
return logError("reference file not provided for \"" + std::string(getCref()) + "\", hence deleting resource file cannot be done. Provide a valid reference file eg: \"model:test1.ssv\"");
std::string extension = "";
if (fileName.length() > 4)
extension = fileName.substr(fileName.length() - 4);
if (extension != ".ssv" && extension != ".ssm")
return logError("filename extension for \"" + std::string(getCref()) + ":" + fileName + "\" must be \".ssv\" or \".ssm\", no other formats are supported");
if (system)
return system->deleteResourcesInSSP(fileName);
return oms_status_ok;
}
oms_status_enu_t oms::Model::addSystem(const oms::ComRef& cref, oms_system_enu_t type)
{
if (cref.isValidIdent() && !system)
{
system = System::NewSystem(cref, type, this, NULL);
if (system)
{
elements[0] = system->getElement();
return oms_status_ok;
}
return oms_status_error;
}
if (!system)
return logError("Model \"" + std::string(getCref()) + "\" does not contain any system");
oms::ComRef tail(cref);
oms::ComRef front = tail.pop_front();
if (system->getCref() == front)
return system->addSubSystem(tail, type);
return logError("wrong input \"" + std::string(front) + "\" != \"" + std::string(system->getCref()) + "\"");
}
oms_status_enu_t oms::Model::exportToSSD(Snapshot& snapshot) const
{
pugi::xml_node ssdNode;
// check for variants
if (this->variantName == "SystemStructure.ssd")
ssdNode = snapshot.getTemplateResourceNodeSSD("SystemStructure.ssd", this->getCref());
else
ssdNode = snapshot.getTemplateResourceNodeSSD(this->variantName, ComRef(this->variantName).pop_front());
if (system)
{
pugi::xml_node system_node = ssdNode.append_child(oms::ssp::Draft20180219::ssd::system);
if (oms_status_ok != system->exportToSSD(system_node, snapshot, this->variantName))
return logError("export of system failed");
}
exportUnitDefinitionsToSSD(ssdNode);
pugi::xml_node default_experiment = ssdNode.append_child(oms::ssp::Draft20180219::ssd::default_experiment);
default_experiment.append_attribute("startTime") = std::to_string(startTime).c_str();
default_experiment.append_attribute("stopTime") = std::to_string(stopTime).c_str();
// export openmodelica_default_experiment as vendor annotations
pugi::xml_node node_annotations = default_experiment.append_child(oms::ssp::Draft20180219::ssd::annotations);
pugi::xml_node node_annotation = node_annotations.append_child(oms::ssp::Version1_0::ssc::annotation);
node_annotation.append_attribute("type") = oms::ssp::Draft20180219::annotation_type;
pugi::xml_node oms_annotation_node = node_annotation.append_child(oms::ssp::Version1_0::oms_annotations);
pugi::xml_node oms_simulation_information = oms_annotation_node.append_child(oms::ssp::Version1_0::simulation_information);
//pugi::xml_node oms_default_experiment = oms_simulation_information.append_child("DefaultExperiment");
oms_simulation_information.append_attribute("resultFile") = resultFilename.c_str();
oms_simulation_information.append_attribute("loggingInterval") = std::to_string(loggingInterval).c_str();
oms_simulation_information.append_attribute("bufferSize") = std::to_string(bufferSize).c_str();
oms_simulation_information.append_attribute("signalFilter") = signalFilterFilename.c_str();
return oms_status_ok;
}
oms_status_enu_t oms::Model::importFromSnapshot(const Snapshot& snapshot)
{
pugi::xml_node ssdNode = snapshot.getResourceNode("SystemStructure.ssd");
if (!ssdNode)
return logError("loading <oms:file> \"SystemStructure.ssd\" from <oms:snapshot> failed");
std::string sspVersion = ssdNode.attribute("version").as_string();
if(sspVersion == "Draft20180219")
{
logWarning_deprecated;
}
for(pugi::xml_node_iterator it = ssdNode.begin(); it != ssdNode.end(); ++it)
{
std::string name = it->name();
if (name == oms::ssp::Draft20180219::ssd::system)
{
ComRef systemCref = ComRef(it->attribute("name").as_string());
// lochel: I guess that can somehow be improved
oms_system_enu_t systemType = getSystemType(*it, sspVersion);
if (oms_status_ok != addSystem(systemCref, systemType))
return oms_status_error;
System* system = getSystem(systemCref);
if (!system)
return oms_status_error;
if (oms_status_ok != system->importFromSnapshot(*it, sspVersion, snapshot))
return oms_status_error;
}
else if (name == oms::ssp::Draft20180219::ssd::units)
{
// allow importing unitDefinitions, the unitDefinitions are handled in Values.cpp importFromSnapshot
}
else if (name == oms::ssp::Draft20180219::ssd::default_experiment)
{
startTime = it->attribute("startTime").as_double(0.0);
stopTime = it->attribute("stopTime").as_double(1.0);
// import oms::DefaultExperiment from oms:simulationInformation
pugi::xml_node annotations = it->child(oms::ssp::Draft20180219::ssd::annotations);
pugi::xml_node annotation_node;
annotation_node = annotations.child(oms::ssp::Version1_0::ssc::annotation);
// check for ssd:annotation to support older version, which is a bug
if(!annotation_node)
{
annotation_node = annotations.child(oms::ssp::Draft20180219::ssd::annotation);
logWarning_deprecated;
}
if (annotation_node && std::string(annotation_node.attribute("type").as_string()) == oms::ssp::Draft20180219::annotation_type)
{
pugi::xml_node oms_annotation_node = annotation_node.child(oms::ssp::Version1_0::oms_annotations);
// support older <ssc:annotation>
if (!oms_annotation_node)
{
oms_annotation_node = annotation_node;
logWarning_deprecated;
}
for(pugi::xml_node_iterator itAnnotations = oms_annotation_node.begin(); itAnnotations != oms_annotation_node.end(); ++itAnnotations)
{
name = itAnnotations->name();
// check for oms_default_experiment from version 1.0
if (std::string(name) == oms::ssp::Version1_0::simulation_information && sspVersion == "1.0")
{
resultFilename = itAnnotations->attribute("resultFile").as_string();
loggingInterval = itAnnotations->attribute("loggingInterval").as_double();
bufferSize = itAnnotations->attribute("bufferSize").as_int();
if (oms_status_ok == importSignalFilter(itAnnotations->attribute("signalFilter").as_string(), snapshot))
this->signalFilterFilename = itAnnotations->attribute("signalFilter").as_string();
}
}
}
}
else
return logError("wrong xml schema detected");
}
return oms_status_ok;
}
oms_system_enu_t oms::Model::getSystemType(const pugi::xml_node& node, const std::string& sspVersion)
{
oms_system_enu_t systemType = oms_system_none;
for(pugi::xml_node_iterator itElements = node.begin(); itElements != node.end(); ++itElements)
{
std::string name = itElements->name();
/* To handle version = "Draft20180219"*/
if (name == oms::ssp::Draft20180219::ssd::simulation_information && sspVersion == "Draft20180219")
{
systemType = getSystemTypeHelper(*itElements, sspVersion);
}
/* from Version "1.0" simulationInformation is handled in vendor annotation */
if (name == oms::ssp::Draft20180219::ssd::annotations && sspVersion == "1.0")
{
pugi::xml_node annotation_node;
annotation_node = itElements->child(oms::ssp::Version1_0::ssc::annotation);
// check for ssd:annotation to support older version, which is a bug
if (!annotation_node)
{
annotation_node = itElements->child(oms::ssp::Draft20180219::ssd::annotation);
logWarning_deprecated;
}
if (annotation_node && std::string(annotation_node.attribute("type").as_string()) == oms::ssp::Draft20180219::annotation_type)
{
pugi::xml_node oms_annotation_node;
oms_annotation_node = annotation_node.child(oms::ssp::Version1_0::oms_annotations);
// support older <ssc:annotation>
if (!oms_annotation_node)
{
oms_annotation_node = annotation_node;
logWarning_deprecated;
}
for(pugi::xml_node_iterator itAnnotations = oms_annotation_node.begin(); itAnnotations != oms_annotation_node.end(); ++itAnnotations)
{
std::string annotationName = itAnnotations->name();
if (std::string(annotationName) == oms::ssp::Version1_0::simulation_information) // check for oms:simulationInformation from version 1.0
{
systemType = getSystemTypeHelper(*itAnnotations, sspVersion);
}
}
}
}
}
return systemType;
}
oms_system_enu_t oms::Model::getSystemTypeHelper(const pugi::xml_node& node, const std::string& sspVersion)
{
oms_system_enu_t systemType = oms_system_tlm;
if (std::string(node.child(oms::ssp::Version1_0::VariableStepSolver).attribute("description").as_string()) != "" || std::string(node.child("VariableStepSolver").attribute("description").as_string()) !="")
{
systemType = oms_system_sc;
}
else if (std::string(node.child("oms:FixedStepSolver").attribute("description").as_string()) != "" || std::string(node.child("FixedStepSolver").attribute("description").as_string()) != "")
{
systemType = oms_system_sc;
}
else if (std::string(node.child(oms::ssp::Version1_0::VariableStepMaster).attribute("description").as_string()) != "" || std::string(node.child("VariableStepMaster").attribute("description").as_string()) != "")
{
systemType = oms_system_wc;
}
else if (std::string(node.child(oms::ssp::Version1_0::FixedStepMaster).attribute("description").as_string()) != "" || std::string(node.child("FixedStepMaster").attribute("description").as_string()) != "")
{
systemType = oms_system_wc;
}
return systemType;
}
oms_status_enu_t oms::Model::exportToFile(const std::string& filename) const
{
Snapshot snapshot;
std::string extension = "";
if (filename.length() > 4)
extension = filename.substr(filename.length() - 4);
if (extension != ".ssp")
return logError("filename extension must be \".ssp\"; no other formats are supported");
exportToSSD(snapshot);
exportSignalFilter(snapshot);
// Usage: minizip [-o] [-a] [-0 to -9] [-p password] [-j] file.zip [files_to_add]
// -o Overwrite existing file.zip
// -a Append to existing file.zip
// -0 Store only
// -1 Compress faster
// -9 Compress better
// -j exclude path. store only the file name
std::vector<std::string> resources;
writeAllResourcesToFilesystem(resources, snapshot);
/*
* remove duplicates resources which is basically a fmu with multiple instances
* eg. tank1 => resources/001_tank1.fmu
* tank2 => resources/001_tank1.fmu
*/
resources.erase(std::unique(resources.begin(), resources.end()), resources.end());
std::string cd = Scope::GetInstance().getWorkingDirectory();
Scope::GetInstance().setWorkingDirectory(tempDir);
int argc = 4 + resources.size();
char **argv = new char*[argc];
int i=0;
argv[i++] = (char*)"minizip";
argv[i++] = (char*)"-o";
argv[i++] = (char*)"-1";
argv[i++] = (char*)"temp/model.ssp";
for (const auto& file : resources)
argv[i++]=(char*)file.c_str();
minizip(argc, argv);
delete[] argv;
Scope::GetInstance().setWorkingDirectory(cd);
filesystem::path full_path = filesystem::path(tempDir) / "temp/model.ssp";
oms_copy_file(full_path, filesystem::path(filename));
return oms_status_ok;
}
void oms::Model::writeAllResourcesToFilesystem(std::vector<std::string>& resources, Snapshot& snapshot) const
{
// get all files from snapshot and save the document (eg.) ssd, ssv and signalFilter
snapshot.getResources(resources);
for (auto const &filename : resources)
{
if (oms_status_ok != snapshot.writeResourceNode(filename, filesystem::path(tempDir)))
logError("failed to export \"" + filename + " to directory " + tempDir);
}
// get all the variants and its resources
// TODO how to handle mutiple resouces with same file name (e.g) resources/signalFilter.xml and other ssv resouces
for (auto const & variant : listVariants)
{
std::vector<std::string> variantResources;
Snapshot snapshot_;
snapshot_.import(variant);
snapshot_.getResources(variantResources);
//snapshot_.debugPrintAll();
for (auto const &variantfilename : variantResources)
{
//std::cout << "\n variant resources : " << variantfilename;
auto file = std::find(resources.begin(), resources.end(), variantfilename);
if (file == resources.end())
{
resources.push_back(variantfilename);
snapshot_.writeResourceNode(variantfilename, filesystem::path(tempDir));
}