/
sedmlfile.cpp
1492 lines (1117 loc) · 67.3 KB
/
sedmlfile.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
/*******************************************************************************
Copyright (C) The University of Auckland
OpenCOR is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenCOR 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://gnu.org/licenses>.
*******************************************************************************/
//==============================================================================
// SED-ML file
//==============================================================================
#include "cellmlfile.h"
#include "centralwidget.h"
#include "corecliutils.h"
#include "coreguiutils.h"
#include "filemanager.h"
#include "interfaces.h"
#include "sedmlfile.h"
#include "sedmlsupport.h"
#include "solverinterface.h"
//==============================================================================
#include <QDir>
#include <QRegularExpression>
#include <QTemporaryFile>
//==============================================================================
#include "libsedmlbegin.h"
#include "sedml/SedAlgorithm.h"
#include "sedml/SedCurve.h"
#include "sedml/SedDocument.h"
#include "sedml/SedOneStep.h"
#include "sedml/SedPlot2D.h"
#include "sedml/SedReader.h"
#include "sedml/SedRepeatedTask.h"
#include "sedml/SedTask.h"
#include "sedml/SedWriter.h"
#include "sedml/SedUniformTimeCourse.h"
#include "sedml/SedVectorRange.h"
#include "libsedmlend.h"
//==============================================================================
namespace OpenCOR {
namespace SEDMLSupport {
//==============================================================================
SedmlFile::SedmlFile(const QString &pFileName, const QString &pOwnerFileName,
bool pNew) :
StandardSupport::StandardFile(pFileName),
mOwnerFileName(pOwnerFileName)
{
// Override our inherited value of mNew with our given one
mNew = pNew;
// Reset ourselves
reset();
}
//==============================================================================
SedmlFile::SedmlFile(const QString &pFileName, bool pNew) :
SedmlFile(pFileName, QString(), pNew)
{
}
//==============================================================================
SedmlFile::~SedmlFile()
{
// Reset ourselves
reset();
}
//==============================================================================
void SedmlFile::reset()
{
// Don't reset ourselves if we were updated
if (mUpdated) {
mUpdated = false;
return;
}
// Ask our file manager to unmanage our corresponding CellML file, if we
// have previously retrieved it, and if it is a remote one (indeed, it will
// have been managed by cellmlFile() below, so that CellML 1.1 files can be
// properly instantiated)
if (mCellmlFile != nullptr) {
Core::FileManager *fileManagerInstance = Core::FileManager::instance();
QString cellmlFileName = mCellmlFile->fileName();
if (fileManagerInstance->isRemote(cellmlFileName)) {
fileManagerInstance->unmanage(cellmlFileName);
}
}
// Reset all of our properties
delete mSedmlDocument;
mSedmlDocument = nullptr;
mLoadingNeeded = true;
delete mCellmlFile;
mCellmlFile = nullptr;
mIssues.clear();
}
//==============================================================================
libsedml::SedDocument * SedmlFile::sedmlDocument()
{
// Return the SED-ML document associated with our SED-ML file, after loading
// ourselves if necessary
load();
return mSedmlDocument;
}
//==============================================================================
bool SedmlFile::isSedmlFile() const
{
// Return whether our current SED-ML document is indeed a SED-ML file
// Note: a non-SED-ML file results in our SED-ML document having at least
// one error, the first of which being of id
// libsedml::SedNotSchemaConformant (e.g. a CellML file, i.e. an XML
// file, but not a SED-ML one) or XMLContentEmpty (e.g. a COMBINE
// archive, i.e. not an XML file). So, we use this fact to determine
// whether our current SED-ML document is indeed a SED-ML file...
return (mSedmlDocument->getNumErrors() == 0)
|| ( (mSedmlDocument->getError(0)->getErrorId() != libsedml::SedNotSchemaConformant)
&& (mSedmlDocument->getError(0)->getErrorId() != XMLContentEmpty));
}
//==============================================================================
bool SedmlFile::hasErrors() const
{
// Return whether our current SED-ML document has errors, be they normal
// errors or fatal errors
return (mSedmlDocument->getNumErrors(libsedml::LIBSEDML_SEV_ERROR) != 0)
|| (mSedmlDocument->getNumErrors(libsedml::LIBSEDML_SEV_FATAL) != 0);
}
//==============================================================================
bool SedmlFile::load()
{
// Check whether the file is already loaded and without any (fatal) errors
if (!mLoadingNeeded) {
return isSedmlFile();
}
mLoadingNeeded = false;
// Create a new L1V3 SED-ML document, if needed, or try to load our file
mSedmlDocument = mNew?
new libsedml::SedDocument(1, 3):
libsedml::readSedML(mFileName.toUtf8().constData());
return isSedmlFile();
}
//==============================================================================
bool SedmlFile::save(const QString &pFileName)
{
// Make sure that we are properly loaded and have no (fatal) errors
if (mLoadingNeeded || hasErrors()) {
return false;
}
// Save ourselves, after having reformatted ourselves, and stop considering
// ourselves as new anymore (in case we were), if the saving went fine
QDomDocument domDocument;
domDocument.setContent(QString(libsedml::writeSedMLToString(mSedmlDocument)));
if (Core::writeFile(pFileName.isEmpty()?mFileName:pFileName,
Core::serialiseDomDocument(domDocument))) {
mNew = false;
return StandardFile::save(pFileName);
}
return false;
}
//==============================================================================
bool SedmlFile::update(const QString &pFileName)
{
// Our SED-ML file has been updated (e.g. through the Simulation Experiment
// view) and we want to update ourselves accordingly, so save ourselves and
// keep track of the fact that we were 'simply' updated
mUpdated = save(pFileName);
return mUpdated;
}
//==============================================================================
void SedmlFile::forceNew()
{
// Force our SED-ML file to act as if it was 'new'
mNew = true;
delete mSedmlDocument;
mSedmlDocument = nullptr;
mLoadingNeeded = true;
}
//==============================================================================
bool SedmlFile::isValid(const QString &pFileContents, SedmlFileIssues &pIssues)
{
// Make sure that we are loaded, if the given file contents is empty (i.e.
// we want to validate ourselves rather than some given file contents)
if (pFileContents.isEmpty()) {
load();
}
// Check whether our SED-ML document or the given file contents is SED-ML
// valid and, if not, populate pIssues with the problems found (after having
// emptied its contents)
// Note: in case we have to validate the given file contents, we would
// normally create a temporary SED-ML document using
// libsedml::readSedMLFromString(), but if the given file contents
// doesn't start with:
// <?xml version='1.0' encoding='UTF-8'?>
// then libsedml::readSedMLFromString() will prepend it to our given
// file contents, which is not what we want. So, instead, we create a
// temporary file which contents is that of our given file contents,
// and simply call libsedml::readSedML()...
pIssues.clear();
libsedml::SedDocument *sedmlDocument = mSedmlDocument;
if (!pFileContents.isEmpty()) {
QTemporaryFile file;
QByteArray fileContentsByteArray = pFileContents.toUtf8();
file.open();
file.write(fileContentsByteArray);
file.flush();
sedmlDocument = libsedml::readSedML(file.fileName().toUtf8().constData());
file.close();
}
for (uint i = 0, iMax = sedmlDocument->getNumErrors(); i < iMax; ++i) {
const libsedml::SedError *error = sedmlDocument->getError(i);
SedmlFileIssue::Type issueType = SedmlFileIssue::Type::Fatal;
switch (error->getSeverity()) {
case LIBSBML_SEV_INFO:
issueType = SedmlFileIssue::Type::Information;
break;
case LIBSBML_SEV_ERROR:
issueType = SedmlFileIssue::Type::Error;
break;
case LIBSBML_SEV_WARNING:
issueType = SedmlFileIssue::Type::Warning;
break;
case LIBSBML_SEV_FATAL:
issueType = SedmlFileIssue::Type::Fatal;
break;
}
// Add the issue to our list, but only if it's not already in there
// Note: indeed, for some reasons, libSEDML may generate several copies
// of the same error...
static const QRegularExpression TrailingEmptyLinesRegEx = QRegularExpression("[\\n]*$");
SedmlFileIssue issue = SedmlFileIssue(issueType,
int(error->getLine()),
int(error->getColumn()),
QString::fromStdString(error->getMessage()).remove(TrailingEmptyLinesRegEx));
if (!pIssues.contains(issue)) {
pIssues << issue;
}
}
// Only consider our SED-ML document valid if it has no (fatal) errors
bool res = !hasErrors();
if (!pFileContents.isEmpty()) {
delete sedmlDocument;
}
return res;
}
//==============================================================================
bool SedmlFile::isValid()
{
// Return whether we are valid
return isValid(QString(), mIssues);
}
//==============================================================================
SolverInterface * SedmlFile::solverInterface(const QString &pKisaoId)
{
// Retrieve and return the solver interface for the given KiSAO id and make
// sure that it's of the type we want
for (auto solverInterface : Core::solverInterfaces()) {
if (solverInterface->id(pKisaoId) == solverInterface->solverName()) {
if (solverInterface->solverType() != Solver::Type::Ode) {
mIssues << SedmlFileIssue(SedmlFileIssue::Type::Information,
tr("%1 (%2) is an NLA solver while an ODE solver is expected").arg(solverInterface->solverName(),
pKisaoId));
return nullptr;
}
return solverInterface;
}
}
mIssues << SedmlFileIssue(SedmlFileIssue::Type::Information,
tr("unsupported algorithm (%1)").arg(pKisaoId));
return nullptr;
}
//==============================================================================
bool SedmlFile::validAlgorithmParameters(const libsedml::SedListOfAlgorithmParameters *pSedmlAlgorithmParameters,
SolverInterface *pSolverInterface)
{
// Make sure that we have a solver interface
if (pSolverInterface == nullptr) {
return false;
}
// Recursively check whether the parameters of the given algorithm are valid
for (uint i = 0, iMax = pSedmlAlgorithmParameters->getNumAlgorithmParameters(); i < iMax; ++i) {
QString parameterKisaoId = QString::fromStdString(pSedmlAlgorithmParameters->get(i)->getKisaoID());
QString id = pSolverInterface->id(parameterKisaoId);
if (id.isEmpty() || (id == pSolverInterface->solverName())) {
mIssues << SedmlFileIssue(SedmlFileIssue::Type::Information,
tr("unsupported algorithm parameter (%1)").arg(parameterKisaoId));
return false;
}
}
return true;
}
//==============================================================================
bool SedmlFile::validListPropertyValue(const libsbml::XMLNode &pPropertyNode,
const QString &pPropertyNodeValue,
const QString &pPropertyName,
const QStringList &pValuesList)
{
// Check whether the given list property is valid
if (!pValuesList.contains(pPropertyNodeValue)) {
QString values;
int i = -1;
int lastValueIndex = pValuesList.count()-1;
for (const auto &lineStyle : pValuesList) {
if (++i != 0) {
values += (i == lastValueIndex)?" "+tr("or")+" ":", ";
}
values += "'"+lineStyle+"'";
}
mIssues << SedmlFileIssue(SedmlFileIssue::Type::Error,
int(pPropertyNode.getLine()),
int(pPropertyNode.getColumn()),
tr("the '%1' property must have a value of %2").arg(pPropertyName,
values));
return false;
}
return true;
}
//==============================================================================
bool SedmlFile::validColorPropertyValue(const libsbml::XMLNode &pPropertyNode,
const QString &pPropertyNodeValue,
const QString &pPropertyName)
{
// Check whether the given color property is valid
static const QRegularExpression ColorRegEx = QRegularExpression("^#([[:xdigit:]]{6}|[[:xdigit:]]{8})$");
if (!ColorRegEx.match(pPropertyNodeValue).hasMatch()) {
mIssues << SedmlFileIssue(SedmlFileIssue::Type::Error,
int(pPropertyNode.getLine()),
int(pPropertyNode.getColumn()),
tr("the '%1' property must have a value of '#RRGGBB' or '#AARRGGBB'").arg(pPropertyName));
return false;
}
return true;
}
//==============================================================================
bool SedmlFile::isSupported()
{
// Make sure that we are valid
if (!isValid()) {
return false;
}
// Make sure that there is only one model
if (mSedmlDocument->getNumModels() != 1) {
mIssues << SedmlFileIssue(SedmlFileIssue::Type::Information,
tr("only SED-ML files with one model are supported"));
return false;
}
// Make sure that the model is of CellML type
libsedml::SedModel *model = mSedmlDocument->getModel(0);
QString language = QString::fromStdString(model->getLanguage());
if ( (language != Language::Cellml)
&& (language != Language::Cellml_1_0)
&& (language != Language::Cellml_1_1)) {
mIssues << SedmlFileIssue(SedmlFileIssue::Type::Information,
tr("only SED-ML files with a CellML file are supported"));
return false;
}
// Make sure that there is either one or two simulations
uint nbOfSimulations = mSedmlDocument->getNumSimulations();
if ((nbOfSimulations != 1) && (nbOfSimulations != 2)) {
mIssues << SedmlFileIssue(SedmlFileIssue::Type::Information,
tr("only SED-ML files with one or two simulations are supported"));
return false;
}
// Make sure that the first simulation is a uniform time course simulation
libsedml::SedSimulation *firstSimulation = mSedmlDocument->getSimulation(0);
if (firstSimulation->getTypeCode() != libsedml::SEDML_SIMULATION_UNIFORMTIMECOURSE) {
mIssues << SedmlFileIssue(SedmlFileIssue::Type::Information,
tr("only SED-ML files with a uniform time course as a (first) simulation are supported"));
return false;
}
// Make sure that the initial time and output start time are the same, that
// the output start time and output end time are different, and that the
// number of points is greater than zero
auto uniformTimeCourse = static_cast<libsedml::SedUniformTimeCourse *>(firstSimulation);
double initialTime = uniformTimeCourse->getInitialTime();
double outputStartTime = uniformTimeCourse->getOutputStartTime();
double outputEndTime = uniformTimeCourse->getOutputEndTime();
int nbOfPoints = uniformTimeCourse->getNumberOfPoints();
if (!qFuzzyCompare(initialTime, outputStartTime)) {
mIssues << SedmlFileIssue(SedmlFileIssue::Type::Information,
tr("only SED-ML files with the same values for 'initialTime' and 'outputStartTime' are supported"));
return false;
}
if (qFuzzyCompare(outputStartTime, outputEndTime)) {
mIssues << SedmlFileIssue(SedmlFileIssue::Type::Error,
tr("the values for 'outputStartTime' and 'outputEndTime' must be different"));
return false;
}
if (nbOfPoints <= 0) {
mIssues << SedmlFileIssue(SedmlFileIssue::Type::Error,
tr("the value for 'numberOfPoints' must be greater than zero"));
return false;
}
// Make sure that we have an algorithm for the first simulation
libsedml::SedAlgorithm *firstSimulationAlgorithm = firstSimulation->getAlgorithm();
libsbml::XMLNode *annotation = nullptr;
if (firstSimulationAlgorithm != nullptr) {
// Make sure that the algorithm relies on an algorithm that we support
// and that its parameters are also supported
if (!validAlgorithmParameters(firstSimulationAlgorithm->getListOfAlgorithmParameters(),
solverInterface(QString::fromStdString(firstSimulationAlgorithm->getKisaoID())))) {
return false;
}
// Make sure that the first simulation algorithm annotation, if any,
// contains at least the kind of information we would expect, i.e.
// solver properties that somehow don't have KiSAO ids
annotation = firstSimulationAlgorithm->getAnnotation();
if (annotation != nullptr) {
for (uint i = 0, iMax = annotation->getNumChildren(); i < iMax; ++i) {
libsbml::XMLNode &solverPropertiesNode = annotation->getChild(i);
if ( (QString::fromStdString(solverPropertiesNode.getURI()) == OpencorNamespace)
&& (QString::fromStdString(solverPropertiesNode.getName()) == SolverProperties)) {
bool validSolverProperties = true;
for (uint j = 0, jMax = solverPropertiesNode.getNumChildren(); j < jMax; ++j) {
libsbml::XMLNode &solverPropertyNode = solverPropertiesNode.getChild(j);
if ( (QString::fromStdString(solverPropertyNode.getURI()) == OpencorNamespace)
&& (QString::fromStdString(solverPropertyNode.getName()) == SolverProperty)) {
int idIndex = solverPropertyNode.getAttrIndex(Id.toStdString());
int valueIndex = solverPropertyNode.getAttrIndex(Value.toStdString());
if ( (idIndex == -1) || (valueIndex == -1)
|| solverPropertyNode.getAttrValue(idIndex).empty()
|| solverPropertyNode.getAttrValue(valueIndex).empty()) {
validSolverProperties = false;
break;
}
}
}
if (!validSolverProperties) {
mIssues << SedmlFileIssue(SedmlFileIssue::Type::Information,
int(solverPropertiesNode.getLine()),
int(solverPropertiesNode.getColumn()),
tr("incomplete algorithm annotation (missing algorithm property information)"));
return false;
}
}
}
}
// Make sure that the first simulation annotation, if any, contains at
// least the kind of information we would expect
annotation = firstSimulation->getAnnotation();
if (annotation != nullptr) {
bool hasNlaSolver = false;
for (uint i = 0, iMax = annotation->getNumChildren(); i < iMax; ++i) {
libsbml::XMLNode &nlaSolverNode = annotation->getChild(i);
if ( (QString::fromStdString(nlaSolverNode.getURI()) == OpencorNamespace)
&& (QString::fromStdString(nlaSolverNode.getName()) == NlaSolver)) {
int nameIndex = nlaSolverNode.getAttrIndex(Name.toStdString());
if ((nameIndex != -1) && !nlaSolverNode.getAttrValue(nameIndex).empty()) {
if (hasNlaSolver) {
mIssues << SedmlFileIssue(SedmlFileIssue::Type::Error,
tr("only one NLA solver is allowed"));
return false;
}
hasNlaSolver = true;
} else {
mIssues << SedmlFileIssue(SedmlFileIssue::Type::Error,
int(nlaSolverNode.getLine()),
int(nlaSolverNode.getColumn()),
tr("incomplete simulation annotation (missing NLA solver name)"));
return false;
}
}
}
}
} else {
mIssues << SedmlFileIssue(SedmlFileIssue::Type::Information,
tr("only SED-ML files with one or two simulations with an algorithm are supported"));
return false;
}
// Check whether there is a second simulation
libsedml::SedSimulation *secondSimulation = mSedmlDocument->getSimulation(1);
if (secondSimulation != nullptr) {
// Make sure that the second simulation is a one-step simulation
if (secondSimulation->getTypeCode() != libsedml::SEDML_SIMULATION_ONESTEP) {
mIssues << SedmlFileIssue(SedmlFileIssue::Type::Information,
tr("only SED-ML files with a one-step simulation as a second simulation are supported"));
return false;
}
// Make sure that its step is greater than zero
if (static_cast<libsedml::SedOneStep *>(secondSimulation)->getStep() <= 0) {
mIssues << SedmlFileIssue(SedmlFileIssue::Type::Error,
tr("the value for step must be greater than zero"));
return false;
}
// Make sure that its algorithm and annotation(s), if any, are the same
// as for the first simulation
std::stringstream firstStream;
std::stringstream secondStream;
libsbml::XMLOutputStream firstXmlStream(firstStream);
libsbml::XMLOutputStream secondXmlStream(secondStream);
libsedml::SedAlgorithm *secondSimulationAlgorithm = secondSimulation->getAlgorithm();
firstSimulationAlgorithm->write(firstXmlStream);
if (secondSimulationAlgorithm != nullptr) {
secondSimulationAlgorithm->write(secondXmlStream);
}
libsbml::XMLNode *firstAnnotation = firstSimulationAlgorithm->getAnnotation();
libsbml::XMLNode *secondAnnotation = secondSimulationAlgorithm->getAnnotation();
if (firstAnnotation != nullptr) {
firstAnnotation->write(firstXmlStream);
}
if (secondAnnotation != nullptr) {
secondAnnotation->write(secondXmlStream);
}
firstAnnotation = firstSimulation->getAnnotation();
secondAnnotation = secondSimulation->getAnnotation();
if (firstAnnotation != nullptr) {
firstAnnotation->write(firstXmlStream);
}
if (secondAnnotation != nullptr) {
secondAnnotation->write(secondXmlStream);
}
if (firstStream.str() != secondStream.str()) {
mIssues << SedmlFileIssue(SedmlFileIssue::Type::Information,
tr("only SED-ML files with two simulations with the same algorithm are supported"));
return false;
}
}
// Make sure that we have only one repeated task, which aim is to execute
// each simulation (using a sub-task) once
uint totalNbOfTasks = (secondSimulation != nullptr)?3:2;
if (mSedmlDocument->getNumTasks() != totalNbOfTasks) {
mIssues << SedmlFileIssue(SedmlFileIssue::Type::Information,
tr("only SED-ML files that execute one or two simulations once are supported"));
return false;
}
libsedml::SedRepeatedTask *repeatedTask = nullptr;
bool repeatedTaskOk = false;
std::string repeatedTaskFirstSubTaskId;
std::string repeatedTaskSecondSubTaskId;
bool firstSubTaskOk = false;
std::string firstSubTaskId;
bool secondSubTaskOk = false;
std::string secondSubTaskId;
for (uint i = 0; i < totalNbOfTasks; ++i) {
auto task = static_cast<libsedml::SedTask *>(mSedmlDocument->getTask(i));
if (task->getTypeCode() == libsedml::SEDML_TASK_REPEATEDTASK) {
// Make sure that the repeated task asks for the model to be reset,
// that it has one range, no task change and one/two sub-task/s
repeatedTask = reinterpret_cast<libsedml::SedRepeatedTask *>(task);
if ( repeatedTask->getResetModel()
&& (repeatedTask->getNumRanges() == 1)
&& (repeatedTask->getNumTaskChanges() == 0)
&& (repeatedTask->getNumSubTasks() == totalNbOfTasks-1)) {
// Make sure that the range is a vector range and that it's the
// one referenced in the repeated task
libsedml::SedRange *range = repeatedTask->getRange(0);
if ( (range->getTypeCode() == libsedml::SEDML_RANGE_VECTORRANGE)
&& (repeatedTask->getRangeId() == range->getId())) {
// Make sure that the vector range has one value that is
// equal to 1
auto vectorRange = static_cast<libsedml::SedVectorRange *>(range);
if ( (vectorRange->getNumValues() == 1)
&& (qFuzzyCompare(vectorRange->getValues().front(), 1.0))) {
// Make sure that the one/two sub-tasks have the correct
// order and retrieve their id
for (uint j = 0, jMax = totalNbOfTasks-1; j < jMax; ++j) {
libsedml::SedSubTask *subTask = repeatedTask->getSubTask(j);
if (subTask->getOrder() == 1) {
repeatedTaskFirstSubTaskId = subTask->getTask();
} else if (subTask->getOrder() == 2) {
repeatedTaskSecondSubTaskId = subTask->getTask();
}
}
repeatedTaskOk = true;
}
}
}
} else if (task->getTypeCode() == libsedml::SEDML_TASK) {
// Make sure the sub-task references the correct model and
// simulation
if ( (task->getModelReference() == model->getId())
&& (task->getSimulationReference() == firstSimulation->getId())) {
firstSubTaskOk = true;
firstSubTaskId = task->getId();
} else if ( (secondSimulation != nullptr)
&& (task->getModelReference() == model->getId())
&& (task->getSimulationReference() == secondSimulation->getId())) {
secondSubTaskOk = true;
secondSubTaskId = task->getId();
}
}
}
if ( !repeatedTaskOk
|| !firstSubTaskOk || (repeatedTaskFirstSubTaskId != firstSubTaskId)
|| ( (secondSimulation != nullptr)
&& (!secondSubTaskOk || (repeatedTaskSecondSubTaskId != secondSubTaskId)))) {
mIssues << SedmlFileIssue(SedmlFileIssue::Type::Information,
tr("only SED-ML files that execute one or two simulations once are supported"));
return false;
}
// Make sure that all the data generators have one variable that references
// the repeated task, that follows the correct CellML format for their
// target (and OpenCOR format for their degree, if any), and that is not
// modified
for (uint i = 0, iMax = mSedmlDocument->getNumDataGenerators(); i < iMax; ++i) {
libsedml::SedDataGenerator *dataGenerator = mSedmlDocument->getDataGenerator(i);
if ((dataGenerator->getNumVariables() != 1) || (dataGenerator->getNumParameters() != 0)) {
mIssues << SedmlFileIssue(SedmlFileIssue::Type::Information,
tr("only SED-ML files with data generators for one variable are supported"));
return false;
}
libsedml::SedVariable *variable = dataGenerator->getVariable(0);
if (!variable->getSymbol().empty() || !variable->getModelReference().empty()) {
mIssues << SedmlFileIssue(SedmlFileIssue::Type::Information,
tr("only SED-ML files with data generators for one variable with a target and a task reference are supported"));
return false;
}
if (variable->getTaskReference() != repeatedTask->getId()) {
mIssues << SedmlFileIssue(SedmlFileIssue::Type::Information,
tr("only SED-ML files with data generators for one variable with a reference to a repeated task are supported"));
return false;
}
static const QRegularExpression TargetStartRegEx = QRegularExpression(R"(^\/cellml:model\/cellml:component\[@name=')");
static const QRegularExpression TargetMiddleRegEx = QRegularExpression(R"(']\/cellml:variable\[@name=')");
static const QRegularExpression TargetEndRegEx = QRegularExpression(R"('\]$)");
bool referencingCellmlVariable = false;
QString target = QString::fromStdString(variable->getTarget());
if (target.contains(TargetStartRegEx) && target.contains(TargetEndRegEx)) {
static const QString Separator = "|";
target.remove(TargetStartRegEx);
target.replace(TargetMiddleRegEx, Separator);
target.remove(TargetEndRegEx);
QStringList identifiers = target.split(Separator);
if (identifiers.count() == 2) {
static const QRegularExpression IdentifierRegEx = QRegularExpression("^[[:alpha:]_][[:alnum:]_]*$");
QString componentName = identifiers.first();
QString variableName = identifiers.last();
referencingCellmlVariable = IdentifierRegEx.match(componentName).hasMatch()
&& IdentifierRegEx.match(variableName).hasMatch();
}
}
if (!referencingCellmlVariable) {
mIssues << SedmlFileIssue(SedmlFileIssue::Type::Information,
tr("only SED-ML files with data generators for one variable with a reference to a CellML variable are supported"));
return false;
}
annotation = variable->getAnnotation();
if (annotation != nullptr) {
for (uint j = 0, jMax = annotation->getNumChildren(); j < jMax; ++j) {
libsbml::XMLNode &variableDegreeNode = annotation->getChild(j);
if ( (QString::fromStdString(variableDegreeNode.getURI()) == OpencorNamespace)
&& (QString::fromStdString(variableDegreeNode.getName()) == VariableDegree)) {
bool validVariableDegree = false;
if (variableDegreeNode.getNumChildren() == 1) {
bool conversionOk;
int variableDegree = QString::fromStdString(variableDegreeNode.getChild(0).getCharacters()).toInt(&conversionOk);
validVariableDegree = conversionOk && (variableDegree >= 0);
}
if (!validVariableDegree) {
mIssues << SedmlFileIssue(SedmlFileIssue::Type::Information,
int(variableDegreeNode.getLine()),
int(variableDegreeNode.getColumn()),
tr("only SED-ML files with data generators for one variable that is derived or not are supported"));
return false;
}
}
}
}
const libsbml::ASTNode *mathNode = dataGenerator->getMath();
if ( (mathNode->getType() != libsbml::AST_NAME)
|| (variable->getId() != mathNode->getName())) {
mIssues << SedmlFileIssue(SedmlFileIssue::Type::Information,
tr("only SED-ML files with data generators for one variable that is not modified are supported"));
return false;
}
}
// Make sure that all the outputs are 2D outputs
for (uint i = 0, iMax = mSedmlDocument->getNumOutputs(); i < iMax; ++i) {
libsedml::SedOutput *output = mSedmlDocument->getOutput(i);
if (output->getTypeCode() != libsedml::SEDML_OUTPUT_PLOT2D) {
mIssues << SedmlFileIssue(SedmlFileIssue::Type::Information,
tr("only SED-ML files with 2D outputs are supported"));
return false;
}
static const QRegularExpression IntegerGt0RegEx = QRegularExpression("^[+]?[1-9]\\d*$");
static const QString TrueValue = "true";
static const QString FalseValue = "false";
annotation = output->getAnnotation();
if (annotation != nullptr) {
for (uint j = 0, jMax = annotation->getNumChildren(); j < jMax; ++j) {
libsbml::XMLNode &plot2dPropertiesNode = annotation->getChild(j);
if ( (QString::fromStdString(plot2dPropertiesNode.getURI()) == OpencorNamespace)
&& (QString::fromStdString(plot2dPropertiesNode.getName()) == Properties)) {
for (uint k = 0, kMax = plot2dPropertiesNode.getNumChildren(); k < kMax; ++k) {
// Note: we don't need to check for the title since it is a
// string and that it can therefore have any value...
libsbml::XMLNode &plot2dPropertyNode = plot2dPropertiesNode.getChild(k);
QString plot2dPropertyNodeName = QString::fromStdString(plot2dPropertyNode.getName());
QString plot2dPropertyNodeValue = QString::fromStdString(plot2dPropertyNode.getChild(0).getCharacters());
if ( (plot2dPropertyNodeName == BackgroundColor)
&& !validColorPropertyValue(plot2dPropertyNode, plot2dPropertyNodeValue, BackgroundColor)) {
return false;
}
if ( (plot2dPropertyNodeName == FontSize)
&& !IntegerGt0RegEx.match(plot2dPropertyNodeValue).hasMatch()) {
mIssues << SedmlFileIssue(SedmlFileIssue::Type::Error,
int(plot2dPropertyNode.getLine()),
int(plot2dPropertyNode.getColumn()),
tr("the '%1' property value must be an integer greater than zero").arg(plot2dPropertyNodeName));
return false;
}
if ( (plot2dPropertyNodeName == ForegroundColor)
&& !validColorPropertyValue(plot2dPropertyNode, plot2dPropertyNodeValue, ForegroundColor)) {
return false;
}
if ( (plot2dPropertyNodeName == Height)
&& !IntegerGt0RegEx.match(plot2dPropertyNodeValue).hasMatch()) {
mIssues << SedmlFileIssue(SedmlFileIssue::Type::Error,
int(plot2dPropertyNode.getLine()),
int(plot2dPropertyNode.getColumn()),
tr("the '%1' property value must be an integer greater than zero").arg(plot2dPropertyNodeName));
return false;
}
// Grid lines
if ( (QString::fromStdString(plot2dPropertyNode.getURI()) == OpencorNamespace)
&& (QString::fromStdString(plot2dPropertyNode.getName()) == GridLines)) {
for (uint l = 0, lMax = plot2dPropertyNode.getNumChildren(); l < lMax; ++l) {
libsbml::XMLNode &gridLinesPropertyNode = plot2dPropertyNode.getChild(l);
QString gridLinesPropertyNodeName = QString::fromStdString(gridLinesPropertyNode.getName());
QString gridLinesPropertyNodeValue = QString::fromStdString(gridLinesPropertyNode.getChild(0).getCharacters());
if ( (gridLinesPropertyNodeName == Style)
&& !validListPropertyValue(gridLinesPropertyNode, gridLinesPropertyNodeValue, Style, lineStyles())) {
return false;
}
if ( (gridLinesPropertyNodeName == Width)
&& !IntegerGt0RegEx.match(gridLinesPropertyNodeValue).hasMatch()) {
mIssues << SedmlFileIssue(SedmlFileIssue::Type::Error,
int(gridLinesPropertyNode.getLine()),
int(gridLinesPropertyNode.getColumn()),
tr("the '%1' property value must be a number greater than zero").arg(gridLinesPropertyNodeName));
return false;
}