/
cellmltextviewconverter.cpp
2549 lines (1987 loc) · 94.7 KB
/
cellmltextviewconverter.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 <http://www.gnu.org/licenses/>.
*******************************************************************************/
//==============================================================================
// Raw CellML to CellML Text converter
//==============================================================================
#include "cellmlfile.h"
#include "cellmltextviewconverter.h"
#include "corecliutils.h"
//==============================================================================
#include <QDomDocument>
#include <QRegularExpression>
//==============================================================================
namespace OpenCOR {
namespace CellMLTextView {
//==============================================================================
CellMLTextViewConverterWarning::CellMLTextViewConverterWarning(const QString &pMessage,
int pLineNumber,
int pColumnNumber) :
mMessage(pMessage),
mLineNumber(pLineNumber),
mColumnNumber(pColumnNumber)
{
}
//==============================================================================
QString CellMLTextViewConverterWarning::message() const
{
// Return our message
return mMessage;
}
//==============================================================================
int CellMLTextViewConverterWarning::lineNumber() const
{
// Return our line number
return mLineNumber;
}
//==============================================================================
int CellMLTextViewConverterWarning::columnNumber() const
{
// Return our column number
return mColumnNumber;
}
//==============================================================================
CellMLTextViewConverter::CellMLTextViewConverter() :
mMappings(QMap<QString, QString>()),
mMathmlNodeTypes(QMap<QString, MathmlNodeType>())
{
// Reset our internals
reset();
// Mappings for relational operators
mMathmlNodeTypes.insert("eq", EqMathmlNode);
mMappings.insert("neq", " <> "); mMathmlNodeTypes.insert("neq", NeqMathmlNode);
mMappings.insert("lt", " < "); mMathmlNodeTypes.insert("lt", LtMathmlNode);
mMappings.insert("leq", " <= "); mMathmlNodeTypes.insert("leq", LeqMathmlNode);
mMappings.insert("geq", " >= "); mMathmlNodeTypes.insert("geq", GeqMathmlNode);
mMappings.insert("gt", " > "); mMathmlNodeTypes.insert("gt", GtMathmlNode);
// Mappings for arithmetic operators
mMappings.insert("plus", "+"); mMathmlNodeTypes.insert("plus", PlusMathmlNode);
mMappings.insert("minus", "-"); mMathmlNodeTypes.insert("minus", MinusMathmlNode);
mMappings.insert("times", "*"); mMathmlNodeTypes.insert("times", TimesMathmlNode);
mMappings.insert("divide", "/"); mMathmlNodeTypes.insert("divide", DivideMathmlNode);
mMappings.insert("ceiling", "ceil");
mMappings.insert("floor", "floor");
mMappings.insert("factorial", "fact");
// Mappings for arithmetic operators
mMappings.insert("and", " and "); mMathmlNodeTypes.insert("and", AndMathmlNode);
mMappings.insert("or", " or "); mMathmlNodeTypes.insert("or", OrMathmlNode);
mMappings.insert("xor", " xor "); mMathmlNodeTypes.insert("xor", XorMathmlNode);
// Mappings for constants
mMappings.insert("true", "true");
mMappings.insert("false", "false");
mMappings.insert("notanumber", "nan");
mMappings.insert("pi", "pi");
mMappings.insert("infinity", "inf");
mMappings.insert("exponentiale", "e");
// Mappings for trigonometric operators
mMappings.insert("arcsin", "asin");
mMappings.insert("arccos", "acos");
mMappings.insert("arctan", "atan");
mMappings.insert("arcsec", "asec");
mMappings.insert("arccsc", "acsc");
mMappings.insert("arccot", "acot");
mMappings.insert("arcsinh", "asinh");
mMappings.insert("arccosh", "acosh");
mMappings.insert("arctanh", "atanh");
mMappings.insert("arcsech", "asech");
mMappings.insert("arccsch", "acsch");
mMappings.insert("arccoth", "acoth");
}
//==============================================================================
bool CellMLTextViewConverter::execute(const QString &pRawCellml)
{
// Reset our internals
reset();
// Convert the raw CellML to CellML Text by first getting a DOM
// representation of it
QDomDocument domDocument;
if (domDocument.setContent(pRawCellml, true,
&mErrorMessage, &mErrorLine, &mErrorColumn)) {
// Process the DOM document's children, skipping the first one since
// it corresponds to a CellML file's processing instruction
for (QDomNode domNode = domDocument.firstChild().nextSibling();
!domNode.isNull(); domNode = domNode.nextSibling()) {
if (domNode.isComment()) {
processCommentNode(domNode);
} else if (rdfNode(domNode)) {
processRdfNode(domNode);
} else if (cellmlNode(domNode, "model")) {
if (!processModelNode(domNode)) {
mOutput = pRawCellml;
return false;
}
} else if (!processUnknownNode(domNode, true)) {
mOutput = pRawCellml;
return false;
}
}
return true;
} else {
mOutput = pRawCellml;
return false;
}
}
//==============================================================================
QString CellMLTextViewConverter::output() const
{
// Return our output
return mOutput;
}
//==============================================================================
QString CellMLTextViewConverter::errorMessage() const
{
// Return our error message
return mErrorMessage;
}
//==============================================================================
int CellMLTextViewConverter::errorLine() const
{
// Return our error line
return mErrorLine;
}
//==============================================================================
int CellMLTextViewConverter::errorColumn() const
{
// Return our error column
return mErrorColumn;
}
//==============================================================================
bool CellMLTextViewConverter::hasWarnings() const
{
// Return whether we have warnings
return mWarnings.count();
}
//==============================================================================
CellMLTextViewConverterWarnings CellMLTextViewConverter::warnings() const
{
// Return our warnings
return mWarnings;
}
//==============================================================================
QDomNode CellMLTextViewConverter::documentationNode() const
{
// Return our documentation ndoe
return mDocumentationNode;
}
//==============================================================================
QDomDocument CellMLTextViewConverter::rdfNodes() const
{
// Return our RDF nodes
return mRdfNodes;
}
//==============================================================================
void CellMLTextViewConverter::reset()
{
// Reset our internals
mOutput = QString();
mPrevIndent = QString();
mIndent = QString();
mLastOutputType = None;
mErrorMessage = QString();
mErrorLine = -1;
mErrorColumn = -1;
mWarnings = CellMLTextViewConverterWarnings();
mModelNode = QDomNode();
mDocumentationNode = QDomNode();
mTopMathmlNode = QDomNode();
mRdfNodes = QDomDocument(QString());
mAssignmentDone = false;
mOldPiecewiseStatementUsed = false;
mPiecewiseStatementUsed = false;
}
//==============================================================================
static const auto Indent = QStringLiteral(" ");
//==============================================================================
void CellMLTextViewConverter::indent(bool pForceTracking)
{
// Indent our output and keep track of it, if required
mIndent += Indent;
if (pForceTracking)
mPrevIndent = mIndent;
}
//==============================================================================
void CellMLTextViewConverter::unindent()
{
// Unindent our output
mIndent.chop(Indent.size());
}
//==============================================================================
void CellMLTextViewConverter::outputString(OutputType pOutputType,
const QString &pString)
{
// Output the given string
if (pString.isEmpty()) {
if (mLastOutputType != EmptyLine)
mOutput += '\n';
} else {
if (pOutputType == Comment) {
// When converting a comment that is within a piecewise equation,
// mIndent will be wrong (since it will have been 'incremented'), so
// we need to rely on the indent that we previously used
mOutput += mPrevIndent+pString+"\n";
} else {
mOutput += mIndent+pString+"\n";
mPrevIndent = mIndent;
}
}
mLastOutputType = pOutputType;
}
//==============================================================================
bool CellMLTextViewConverter::rdfNode(const QDomNode &pDomNode) const
{
// Return whether the given node is an RDF node
return !pDomNode.localName().compare("RDF")
&& !pDomNode.namespaceURI().compare(CellMLSupport::RdfNamespace);
}
//==============================================================================
bool CellMLTextViewConverter::cellmlNode(const QDomNode &pDomNode,
const QString &pName) const
{
// Return whether the given node is a CellML node with the given name
return !pDomNode.localName().compare(pName)
&& ( !pDomNode.namespaceURI().compare(CellMLSupport::Cellml_1_0_Namespace)
|| !pDomNode.namespaceURI().compare(CellMLSupport::Cellml_1_1_Namespace));
}
//==============================================================================
bool CellMLTextViewConverter::mathmlNode(const QDomNode &pDomNode,
const QString &pName) const
{
// Return whether the given node is a MathML node with the given name
return !pDomNode.localName().compare(pName)
&& !pDomNode.namespaceURI().compare(CellMLSupport::MathmlNamespace);
}
//==============================================================================
QString CellMLTextViewConverter::cmetaId(const QDomNode &pDomNode) const
{
// Return the converted cmeta:id, if any, of the given node
QString cmetaIdValue = attributeNodeValue(pDomNode, CellMLSupport::CmetaIdNamespace, "id", false);
if (!cmetaIdValue.isEmpty())
return QString("{%1}").arg(cmetaIdValue);
else
return QString();
}
//==============================================================================
QString CellMLTextViewConverter::attributeNodeValue(const QDomNode &pDomNode,
const QString &pNamespace,
const QString &pName,
bool pMustBePresent) const
{
// Return the trimmed value of the requested attribute using the given
// namespace
// Note: there is an issue with QDomNamedNodeMap::namedItemNS(). Indeed, if
// the attribute that defines the namespace is after the attribute
// itself, then the attribute will only be accessible without using a
// namespace (see https://bugreports.qt.io/browse/QTBUG-59932)...
QDomNamedNodeMap domNodeAttributes = pDomNode.attributes();
QDomNode attributeNode = domNodeAttributes.namedItemNS(pNamespace, pName);
if (attributeNode.isNull())
attributeNode = domNodeAttributes.namedItem(pName);
QString res = attributeNode.nodeValue().trimmed();
if (res.isEmpty())
return pMustBePresent?"???":res;
else
return res;
}
//==============================================================================
QString CellMLTextViewConverter::cellmlAttributeNodeValue(const QDomNode &pDomNode,
const QString &pName,
bool pMustBePresent) const
{
// Return the requested CellML attribute using the CellML 1.0 namespace or,
// if needed, the CellML 1.1 namespace
QString res = attributeNodeValue(pDomNode, CellMLSupport::Cellml_1_0_Namespace, pName, false);
if (res.isEmpty())
res = attributeNodeValue(pDomNode, CellMLSupport::Cellml_1_1_Namespace, pName, false);
if (res.isEmpty())
return pMustBePresent?"???":res;
else
return res;
}
//==============================================================================
CellMLTextViewConverter::MathmlNodeType CellMLTextViewConverter::mathmlNodeType(const QDomNode &pDomNode) const
{
// Return the MathML type of the given node
if ( !pDomNode.localName().compare("apply")
&& !pDomNode.namespaceURI().compare(CellMLSupport::MathmlNamespace)) {
return mMathmlNodeTypes.value(childNode(pDomNode, 0).localName());
} else {
return mMathmlNodeTypes.value(pDomNode.localName());
}
}
//==============================================================================
bool CellMLTextViewConverter::processModelNode(const QDomNode &pDomNode)
{
// Start processing the given model node
if (mLastOutputType == Comment)
outputString();
outputString(DefModel,
QString("def model%1 %2 as").arg(cmetaId(pDomNode))
.arg(cellmlAttributeNodeValue(pDomNode, "name")));
indent();
// Keep track of the given model node and of its attributes
mModelNode = pDomNode;
mAttributes = pDomNode.attributes();
// Process the given model node's children
for (QDomNode domNode = pDomNode.firstChild();
!domNode.isNull(); domNode = domNode.nextSibling()) {
if (domNode.isComment()) {
processCommentNode(domNode);
} else if (rdfNode(domNode)) {
processRdfNode(domNode);
} else if (cellmlNode(domNode, "import")) {
if (!processImportNode(domNode))
return false;
} else if (cellmlNode(domNode, "units")) {
if (!processUnitsNode(domNode))
return false;
} else if (cellmlNode(domNode, "component")) {
if (!processComponentNode(domNode))
return false;
} else if (cellmlNode(domNode, "group")) {
if (!processGroupNode(domNode))
return false;
} else if (cellmlNode(domNode, "connection")) {
if (!processConnectionNode(domNode))
return false;
} else if (!processUnknownNode(domNode, false)) {
return false;
}
}
// Finish processing the given model node
unindent();
outputString(EndDef, "enddef;");
return true;
}
//==============================================================================
QString CellMLTextViewConverter::processCommentString(const QString &pComment)
{
// An empty comment will have been serialised as "<!-- -->", which means
// that pComment will be equal to " ", in which case we need to return an
// empty string
if (!pComment.compare(" "))
return QString();
// We cannot have "--" in an XML comment, so those were replaced with
// "--", which means that we need to convert them back
QString realComment = pComment;
realComment.replace("--", "--");
// If newComment ends with "- ", it's because the comment ends with a dash,
// but that a space had to be added to it to avoid problems with the end of
// an XML comment ("-->"), so we need to chop that space to get the real
// comment
if (realComment.endsWith("- "))
realComment.chop(1);
// We are all done, so we can now return our real comment
return realComment;
}
//==============================================================================
void CellMLTextViewConverter::processCommentNode(const QDomNode &pDomNode)
{
// Process the given comment node
QStringList commentLines = pDomNode.nodeValue().remove('\r').split('\n');
// Note #1: we don't know which end of line string is used by the file, so
// the above code ensures that we can handle both "\r\n" on Windows
// and "\n" on Linux/macOS...
// Note #2: unlike for other nodes, we don't trim its value since leading
// spaces may be used in a comment...
if ( (mLastOutputType == Comment)
|| (mLastOutputType == Comp) || (mLastOutputType == DefBaseUnit)
|| (mLastOutputType == EndComp) || (mLastOutputType == EndDef)
|| (mLastOutputType == Equation) || (mLastOutputType == ImportComp)
|| (mLastOutputType == ImportUnit) || (mLastOutputType == Unit)
|| (mLastOutputType == Var) || (mLastOutputType == Vars)) {
outputString();
}
for (const auto &commentLine : commentLines)
outputString(Comment, QString("//%1").arg(processCommentString(commentLine)));
}
//==============================================================================
void CellMLTextViewConverter::processRdfNode(const QDomNode &pDomNode)
{
// Process the given RDF node by keeping track of it
mRdfNodes.appendChild(pDomNode.cloneNode());
}
//==============================================================================
bool CellMLTextViewConverter::processImportNode(const QDomNode &pDomNode)
{
// Start processing the given import node
if ( (mLastOutputType == Comment)
|| (mLastOutputType == EndDef)) {
outputString();
}
outputString(DefImport,
QString("def import%1 using \"%2\" for").arg(cmetaId(pDomNode))
.arg(attributeNodeValue(pDomNode, CellMLSupport::XlinkNamespace, "href")));
indent();
// Process the given import node's children
for (QDomNode domNode = pDomNode.firstChild();
!domNode.isNull(); domNode = domNode.nextSibling()) {
if (domNode.isComment()) {
processCommentNode(domNode);
} else if (rdfNode(domNode)) {
processRdfNode(domNode);
} else if (cellmlNode(domNode, "units")) {
if (!processUnitsNode(domNode, true))
return false;
} else if (cellmlNode(domNode, "component")) {
if (!processComponentNode(domNode, true))
return false;
} else if (!processUnknownNode(domNode, false)) {
return false;
}
}
// Finish processing the given group node
unindent();
outputString(EndDef, "enddef;");
return true;
}
//==============================================================================
bool CellMLTextViewConverter::processUnitsNode(const QDomNode &pDomNode,
bool pInImportNode)
{
// Start processing the given units node
QString baseUnits = cellmlAttributeNodeValue(pDomNode, "base_units", false);
if (!baseUnits.isEmpty() && baseUnits.compare("yes") && baseUnits.compare("no")) {
mErrorMessage = tr("A 'base_units' attribute must have a value of 'yes' or 'no'.");
mErrorLine = pDomNode.lineNumber();
mErrorColumn = pDomNode.columnNumber();
return false;
}
bool isBaseUnits = !baseUnits.compare("yes");
if (!pInImportNode && !isBaseUnits) {
if ( (mLastOutputType == Comment)
|| (mLastOutputType == DefBaseUnit) || (mLastOutputType == EndDef)
|| (mLastOutputType == Equation) || (mLastOutputType == Var)) {
outputString();
}
outputString(DefUnit,
QString("def unit%1 %2 as").arg(cmetaId(pDomNode))
.arg(cellmlAttributeNodeValue(pDomNode, "name")));
indent();
}
// Process the given units node's children
for (QDomNode domNode = pDomNode.firstChild();
!domNode.isNull(); domNode = domNode.nextSibling()) {
if (domNode.isComment()) {
processCommentNode(domNode);
} else if (rdfNode(domNode)) {
processRdfNode(domNode);
} else if (!isBaseUnits && !pInImportNode && cellmlNode(domNode, "unit")) {
if (!processUnitNode(domNode))
return false;
} else if (!processUnknownNode(domNode, false)) {
return false;
}
}
// Finish processing the given units node
if (pInImportNode) {
if ( (mLastOutputType == Comment)
|| (mLastOutputType == ImportComp)) {
outputString();
}
outputString(ImportUnit,
QString("unit%1 %2 using unit %3;").arg(cmetaId(pDomNode))
.arg(cellmlAttributeNodeValue(pDomNode, "name"))
.arg(cellmlAttributeNodeValue(pDomNode, "units_ref")));
} else if (isBaseUnits) {
if ( (mLastOutputType == Comment)
|| (mLastOutputType == EndDef) || (mLastOutputType == Equation)
|| (mLastOutputType == Var)) {
outputString();
}
outputString(DefBaseUnit,
QString("def unit%1 %2 as base unit;").arg(cmetaId(pDomNode))
.arg(cellmlAttributeNodeValue(pDomNode, "name")));
} else {
unindent();
outputString(EndDef, "enddef;");
}
return true;
}
//==============================================================================
bool CellMLTextViewConverter::processUnitNode(const QDomNode &pDomNode)
{
// Process the given unit node's children
// Note #1: unlike for most nodes, we process the node's children before
// processing the node itself since it only outputs one line, so
// it's not like we can put a comment within a def...enddef;
// statement...
// Note #2: when parsed back, comments will not be in the unit node anymore,
// but in its parent...
for (QDomNode domNode = pDomNode.firstChild();
!domNode.isNull(); domNode = domNode.nextSibling()) {
if (domNode.isComment())
processCommentNode(domNode);
else if (rdfNode(domNode))
processRdfNode(domNode);
else if (!processUnknownNode(domNode, false))
return false;
}
// Process the given unit node
QString parameters = QString();
QString prefix = cellmlAttributeNodeValue(pDomNode, "prefix", false);
QString exponent = cellmlAttributeNodeValue(pDomNode, "exponent", false);
QString multiplier = cellmlAttributeNodeValue(pDomNode, "multiplier", false);
QString offset = cellmlAttributeNodeValue(pDomNode, "offset", false);
if (!prefix.isEmpty())
parameters += "pref: "+prefix;
if (!exponent.isEmpty())
parameters += (parameters.isEmpty()?QString():", ")+"expo: "+exponent;
if (!multiplier.isEmpty())
parameters += (parameters.isEmpty()?QString():", ")+"mult: "+multiplier;
if (!offset.isEmpty())
parameters += (parameters.isEmpty()?QString():", ")+"off: "+offset;
if (mLastOutputType == Comment)
outputString();
outputString(Unit,
QString("unit%1 %2%3;").arg(cmetaId(pDomNode))
.arg(cellmlAttributeNodeValue(pDomNode, "units"))
.arg(parameters.isEmpty()?QString():" {"+parameters+"}"));
return true;
}
//==============================================================================
bool CellMLTextViewConverter::processComponentNode(const QDomNode &pDomNode,
bool pInImportNode)
{
// Start processing the given component node
if (!pInImportNode) {
if ( (mLastOutputType == Comment)
|| (mLastOutputType == EndDef)) {
outputString();
}
outputString(DefComp,
QString("def comp%1 %2 as").arg(cmetaId(pDomNode))
.arg(cellmlAttributeNodeValue(pDomNode, "name")));
indent();
}
// Process the given component node's children
for (QDomNode domNode = pDomNode.firstChild();
!domNode.isNull(); domNode = domNode.nextSibling()) {
if (domNode.isComment()) {
processCommentNode(domNode);
} else if (rdfNode(domNode)) {
processRdfNode(domNode);
} else if (!pInImportNode && cellmlNode(domNode, "units")) {
if (!processUnitsNode(domNode))
return false;
} else if (!pInImportNode && cellmlNode(domNode, "variable")) {
if (!processVariableNode(domNode))
return false;
} else if (!pInImportNode && mathmlNode(domNode, "math")) {
if (!processMathNode(domNode))
return false;
} else if (!pInImportNode && cellmlNode(domNode, "reaction")) {
if (!processReactionNode(domNode))
return false;
} else if (!processUnknownNode(domNode, false)) {
return false;
}
}
// Finish processing the given component node
if (pInImportNode) {
if ( (mLastOutputType == Comment)
|| (mLastOutputType == ImportUnit)) {
outputString();
}
outputString(ImportComp,
QString("comp%1 %2 using comp %3;").arg(cmetaId(pDomNode))
.arg(cellmlAttributeNodeValue(pDomNode, "name"))
.arg(cellmlAttributeNodeValue(pDomNode, "component_ref")));
} else {
unindent();
outputString(EndDef, "enddef;");
}
return true;
}
//==============================================================================
bool CellMLTextViewConverter::processVariableNode(const QDomNode &pDomNode)
{
// Process the given variable node's children
// Note #1: unlike for most nodes, we process the node's children before
// processing the node itself since it only outputs one line, so
// it's not like we can put a comment within a def...enddef;
// statement...
// Note #2: when parsed back, comments will not be in the variable node
// anymore, but in its parent...
for (QDomNode domNode = pDomNode.firstChild();
!domNode.isNull(); domNode = domNode.nextSibling()) {
if (domNode.isComment())
processCommentNode(domNode);
else if (rdfNode(domNode))
processRdfNode(domNode);
else if (!processUnknownNode(domNode, false))
return false;
}
// Process the given variable node
QString parameters = QString();
QString initialValue = cellmlAttributeNodeValue(pDomNode, "initial_value", false);
QString publicInterface = cellmlAttributeNodeValue(pDomNode, "public_interface", false);
QString privateInterface = cellmlAttributeNodeValue(pDomNode, "private_interface", false);
if (!initialValue.isEmpty())
parameters += "init: "+initialValue;
if (!publicInterface.isEmpty())
parameters += (parameters.isEmpty()?QString():", ")+"pub: "+publicInterface;
if (!privateInterface.isEmpty())
parameters += (parameters.isEmpty()?QString():", ")+"priv: "+privateInterface;
if ( (mLastOutputType == Comment)
|| (mLastOutputType == DefBaseUnit) || (mLastOutputType == EndDef)
|| (mLastOutputType == Equation)) {
outputString();
}
outputString(Var,
QString("var%1 %2: %3%4;").arg(cmetaId(pDomNode))
.arg(cellmlAttributeNodeValue(pDomNode, "name"))
.arg(cellmlAttributeNodeValue(pDomNode, "units"))
.arg(parameters.isEmpty()?QString():" {"+parameters+"}"));
return true;
}
//==============================================================================
bool CellMLTextViewConverter::processMathNode(const QDomNode &pDomNode)
{
// Process the given math node's children
QString equation;
bool hasError;
for (QDomNode domNode = pDomNode.firstChild();
!domNode.isNull(); domNode = domNode.nextSibling()) {
if (domNode.isComment()) {
processCommentNode(domNode);
} else if (rdfNode(domNode)) {
processRdfNode(domNode);
} else {
mOldPiecewiseStatementUsed = mPiecewiseStatementUsed;
mAssignmentDone = mPiecewiseStatementUsed = hasError = false;
mTopMathmlNode = domNode;
equation = processMathmlNode(domNode, hasError);
if (hasError) {
return false;
} else if (!equation.isEmpty()) {
// Note: should one or several warnings be generated, then it may be
// possible that no equation has been generated, hence our
// check...
if ( (mLastOutputType == Comment)
|| (mLastOutputType == DefBaseUnit)
|| (mLastOutputType == EndDef)
|| (mLastOutputType == Var)
|| mPiecewiseStatementUsed
|| (mPiecewiseStatementUsed != mOldPiecewiseStatementUsed)) {
outputString();
}
outputString(Equation, equation+";");
}
}
}
return true;
}
//==============================================================================
int CellMLTextViewConverter::childNodesCount(const QDomNode &pDomNode) const
{
// Return the number of child elements in the given node
int res = 0;
QDomNodeList childNodes = pDomNode.childNodes();
for (int i = 0, iMax = childNodes.count(); i < iMax; ++i) {
if (!childNodes.item(i).isComment())
++res;
}
return res;
}
//==============================================================================
QDomNode CellMLTextViewConverter::childNode(const QDomNode &pDomNode,
int pChildNodeIndex) const
{
// Return the nth child element of the given node
int childNodeIndex = 0;
QDomNodeList childNodes = pDomNode.childNodes();
for (int i = 0, iMax = childNodes.count(); i < iMax; ++i) {
if (!childNodes.item(i).isComment()) {
if (childNodeIndex == pChildNodeIndex)
return childNodes.item(i);
else
++childNodeIndex;
}
}
return QDomNode();
}
//==============================================================================
QString CellMLTextViewConverter::processMathmlNode(const QDomNode &pDomNode,
bool &pHasError)
{
// Make sure that we are not coming here with an error
if (pHasError)
return QString();
// Process the given MathML node and its children, if any
QDomNode domNode = pDomNode;
int currentChildNodesCount = childNodesCount(pDomNode);
// Basic content elements
if (domNode.isComment()) {
processCommentNode(domNode);
return QString();
} else if (mathmlNode(domNode, "apply")) {
// Make sure that we have at least one child
if (!currentChildNodesCount) {
mErrorMessage = tr("An '%1' element must have at least one child element.").arg(domNode.localName());
} else {
domNode = childNode(domNode, 0);
// Relational operators
if (mathmlNode(domNode, "eq")) {
if (currentChildNodesCount != 3) {
mErrorMessage = tr("An '%1' element must have two siblings.").arg(domNode.localName());
} else if (mAssignmentDone) {
return processOperatorNode(" == ", pDomNode, pHasError);
} else {
mAssignmentDone = true;
return processOperatorNode(QString(" =%1 ").arg(cmetaId(pDomNode)), pDomNode, pHasError);
}
} else if ( mathmlNode(domNode, "neq")
|| mathmlNode(domNode, "lt")
|| mathmlNode(domNode, "leq")) {
if (currentChildNodesCount != 3)
mErrorMessage = tr("An '%1' element must have two siblings.").arg(domNode.localName());
else
return processOperatorNode(mMappings.value(domNode.localName()), pDomNode, pHasError);
} else if ( mathmlNode(domNode, "gt")
|| mathmlNode(domNode, "geq")) {
if (currentChildNodesCount != 3)
mErrorMessage = tr("A '%1' element must have two siblings.").arg(domNode.localName());
else
return processOperatorNode(mMappings.value(domNode.localName()), pDomNode, pHasError);