-
-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathSBMLRateRuleConverter.cpp
More file actions
1412 lines (1267 loc) · 37.7 KB
/
SBMLRateRuleConverter.cpp
File metadata and controls
1412 lines (1267 loc) · 37.7 KB
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
/**
* @file SBMLRateRuleConverter.cpp
* @brief Implementation of SBMLRateRuleConverter, a converter from raterule to reaction
* @author Sarah Keating
*
* <!--------------------------------------------------------------------------
* This file is part of libSBML. Please visit http://sbml.org for more
* information about SBML, and the latest version of libSBML.
*
* Copyright (C) 2013-2018 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
* 3. University of Heidelberg, Heidelberg, Germany
*
* Copyright (C) 2009-2013 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. EMBL European Bioinformatics Institute (EMBL-EBI), Hinxton, UK
*
* Copyright (C) 2006-2008 by the California Institute of Technology,
* Pasadena, CA, USA
*
* Copyright (C) 2002-2005 jointly by the following organizations:
* 1. California Institute of Technology, Pasadena, CA, USA
* 2. Japan Science and Technology Agency, Japan
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online as http://sbml.org/software/libsbml/license.html
* ------------------------------------------------------------------------ -->
*/
#include <sbml/conversion/SBMLRateRuleConverter.h>
#include <sbml/conversion/SBMLConverterRegistry.h>
#include <sbml/conversion/SBMLConverterRegister.h>
#include <sbml/math/ASTNode.h>
#include <sbml/math/L3Parser.h>
#include <sbml/AlgebraicRule.h>
#include <sbml/AssignmentRule.h>
#include <sbml/RateRule.h>
#include <sbml/InitialAssignment.h>
#include <sbml/SBMLDocument.h>
#include <sbml/Model.h>
#include <sbml/ModifierSpeciesReference.h>
#include <sbml/conversion/ExpressionAnalyser.h>
#include <sbml/math/L3FormulaFormatter.h>
#ifdef __cplusplus
#include <algorithm>
#include <string>
#include <vector>
#include <map>
using namespace std;
LIBSBML_CPP_NAMESPACE_BEGIN
static void print_vectors(setCoeff co)
{
unsigned int noTerms = co.size();
for (unsigned int n = 0; n < noTerms; n++)
{
ASTNode* term = co.at(n).first;
std::vector<double> values = co.at(n).second;
unsigned int noValues = values.size();
cout << SBML_formulaToL3String(term) << ": Coefficients [";
for (unsigned int l = 0; l < noValues; l++)
{
cout << values.at(l) << ", ";
}
cout << "]\n";
}
}
void print_vectors_bool(std::vector<std::vector<bool>> co)
{
unsigned int noTerms = co.size();
for (unsigned int n = 0; n < noTerms; n++)
{
std::vector<bool> values = co.at(n);
unsigned int noValues = values.size();
cout << "term " << n << ": boolean value [";
for (unsigned int l = 0; l < noValues; l++)
{
cout << values.at(l) << ", ";
}
cout << "]\n";
}
}
void SBMLRateRuleConverter::print_rn_coefficients(setRnCoeffs co)
{
unsigned int noTerms = co.size();
for (unsigned int n = 0; n < noTerms; n++)
{
cout << "Coefficients for " << SBML_formulaToL3String(mTerms.at(n)) << " \n";
std::vector<double> values = co.at(n);
unsigned int noValues = values.size();
for (unsigned int l = 0; l < mODEs.size(); l++)
{
cout << "variable: " << mODEs.at(l).first << ":Coefficients [";
for (unsigned int k = 0; k < noValues; k++)
{
cout << values.at(k) << ", ";
}
cout << "]\n";
}
}
}
/** @cond doxygenLibsbmlInternal */
void SBMLRateRuleConverter::init()
{
SBMLRateRuleConverter converter;
SBMLConverterRegistry::getInstance().addConverter(&converter);
}
/** @endcond */
SBMLRateRuleConverter::SBMLRateRuleConverter()
: SBMLConverter("SBML RateRule Converter")
, mODEs ()
, mTerms ()
, mCoefficients ()
, mPosDerivative ()
, mNegDerivative ()
, mDerivSign (POSITIVE_DERIVATIVE)
, mMathNotSupported (false)
, mProducts ()
, mReactants ()
, mModifiers ()
{
}
SBMLRateRuleConverter::SBMLRateRuleConverter(const SBMLRateRuleConverter& orig) :
SBMLConverter(orig)
, mODEs(orig.mODEs)
, mTerms(orig.mTerms)
, mCoefficients(orig.mCoefficients)
, mPosDerivative(orig.mPosDerivative)
, mNegDerivative(orig.mNegDerivative)
, mDerivSign(POSITIVE_DERIVATIVE)
, mMathNotSupported(orig.mMathNotSupported)
, mProducts(orig.mProducts)
, mReactants(orig.mReactants)
, mModifiers(orig.mModifiers)
{
}
/*
* Assignment operator for SBMLLevelVersionConverter.
*/
SBMLRateRuleConverter&
SBMLRateRuleConverter::operator=(const SBMLRateRuleConverter& rhs)
{
if (&rhs != this)
{
this->SBMLConverter::operator =(rhs);
//, mODEs(NULL)
// , mTerms(NULL)
// , mCoefficients(NULL)
mPosDerivative = rhs.mPosDerivative;
mNegDerivative = rhs.mNegDerivative;
mDerivSign = rhs.mDerivSign;
mMathNotSupported = rhs.mMathNotSupported;
mProducts = rhs.mProducts;
mReactants = rhs.mReactants;
mModifiers = rhs.mModifiers;
}
return *this;
}
SBMLRateRuleConverter*
SBMLRateRuleConverter::clone() const
{
return new SBMLRateRuleConverter(*this);
}
/*
* Destroy this object.
*/
SBMLRateRuleConverter::~SBMLRateRuleConverter ()
{
for (std::vector<std::pair<std::string, ASTNode*> >::iterator it = mODEs.begin(); it != mODEs.end(); ++it)
{
if (it->second != NULL)
{
delete it->second;
it->second = NULL;
}
}
mODEs.clear();
for (std::vector<ASTNode*>::iterator it = mTerms.begin(); it != mTerms.end(); ++it)
{
delete *it;
}
mTerms.clear();
for (std::vector<std::pair<ASTNode*, std::vector<double> > >::iterator it = mCoefficients.begin(); it != mCoefficients.end(); ++it)
{
// the ASTNode* is the pointer to the term which has been destroyed above
//if (it->first != NULL)
//{
// delete it->first;
// it->first = NULL;
//}
it->second.clear();
}
mCoefficients.clear();
mPosDerivative.clear();
mNegDerivative.clear();
mProducts.clear();
mReactants.clear();
mModifiers.clear();
}
ConversionProperties
SBMLRateRuleConverter::getDefaultProperties() const
{
static ConversionProperties prop;
static bool init = false;
if (init)
{
return prop;
}
else
{
prop.addOption("inferReactions", true,
"Infer reactions from rateRules in the model");
prop.addOption("useStoichiometryFromMath", true,
"If a number appears in the math use it as the stoichiometry");
init = true;
return prop;
}
}
bool
SBMLRateRuleConverter::matchesProperties(const ConversionProperties &props) const
{
if (!props.hasOption("inferReactions"))
return false;
return true;
}
int
SBMLRateRuleConverter::setDocument(const SBMLDocument* doc)
{
if (SBMLConverter::setDocument(doc) == LIBSBML_OPERATION_SUCCESS)
{
if (mDocument != NULL && mDocument->getModel() != NULL)
{
mOriginalModel = mDocument->getModel()->clone();
return LIBSBML_OPERATION_SUCCESS;
}
else
{
return LIBSBML_OPERATION_SUCCESS;
}
}
else
{
return LIBSBML_OPERATION_FAILED;
}
}
int
SBMLRateRuleConverter::setDocument(SBMLDocument* doc)
{
if (SBMLConverter::setDocument(doc) == LIBSBML_OPERATION_SUCCESS)
{
if (mDocument != NULL && mDocument->getModel() != NULL)
{
mOriginalModel = mDocument->getModel()->clone();
return LIBSBML_OPERATION_SUCCESS;
}
else
{
return LIBSBML_OPERATION_SUCCESS;
}
}
else
{
return LIBSBML_OPERATION_FAILED;
}
}
int
SBMLRateRuleConverter::convert()
{
// if we cannot do the conversion - dont try
OperationReturnValues_t returnValue;
if (!isDocumentAppropriate(returnValue))
{
return returnValue;
}
// Fages algo 3.6 Steps 1-2
populateInitialODEinfo();
populateODEinfo();
if (getMathNotSupportedFlag() == true)
{
return LIBSBML_OPERATION_FAILED;
}
// Fages algo 3.6 Step 3-4a-d
populateReactionCoefficients();
// Fages algo 3.6 Step 4e
reconstructModel();
return LIBSBML_OPERATION_SUCCESS;
}
/** @cond doxygenIgnored */
bool
SBMLRateRuleConverter::checkDocumentValidity()
{
bool valid = true;
/* check consistency of model */
/* since this function will write to the error log we should
* clear anything in the log first
*/
mDocument->getErrorLog()->clearLog();
unsigned char origValidators = mDocument->getApplicableValidators();
mDocument->setApplicableValidators(AllChecksON);
mDocument->checkConsistency();
/* replace original consistency checks */
mDocument->setApplicableValidators(origValidators);
if (mDocument->getErrorLog()->getNumFailsWithSeverity(LIBSBML_SEV_ERROR) != 0)
{
valid = false;
}
return valid;
}
/** @endcond */
/** @cond doxygenIgnored */
bool
SBMLRateRuleConverter::isDocumentAppropriate(OperationReturnValues_t& returnValue)
{
// there are a number of scenarios that the converter will not handle
// 1. document is null or model is null
if (mDocument == NULL)
{
returnValue = LIBSBML_OPERATION_FAILED;
return false;
}
Model* mModel = mDocument->getModel();
if (mModel == NULL)
{
mDocument->getErrorLog()->logError(DocumentOrModelIsNull, mDocument->getLevel(),
mDocument->getVersion(), "The source document or model is null.");
returnValue = LIBSBML_OPERATION_FAILED;
return false;
}
// 2. there are no rate rules/already reactions/multiple compartments
if (mModel->getNumRules() == 0)
{
mDocument->getErrorLog()->logError(ModelContainsNoRateRules, mDocument->getLevel(),
mDocument->getVersion(), "There are no rate rules present.");
returnValue = LIBSBML_OPERATION_SUCCESS;
return true;
}
else
{
bool rateRule = false;
unsigned int n = 0;
while (!rateRule && n < mModel->getNumRules())
{
if (mModel->getRule(n)->getType() == RULE_TYPE_RATE)
{
rateRule = true;
}
n++;
}
if (!rateRule)
{
mDocument->getErrorLog()->logError(ModelContainsNoRateRules, mDocument->getLevel(),
mDocument->getVersion(), "There are no rate rules present.");
returnValue = LIBSBML_OPERATION_SUCCESS;
return false;
}
}
if (mModel->getNumReactions() > 0)
{
mDocument->getErrorLog()->logError(ModelAlreadyContainsReactions, mDocument->getLevel(),
mDocument->getVersion(), "There are already reactions present.");
returnValue = LIBSBML_OPERATION_FAILED;
return false;
}
if (mModel->getNumCompartments() > 1)
{
if (speciesFromMultipleCompartmentsInSameRateRule())
{
mDocument->getErrorLog()->logError(ModelContainsMultipleCompartments, mDocument->getLevel(),
mDocument->getVersion(), "There are multiple compartments with species in the same rate rule.");
returnValue = LIBSBML_OPERATION_FAILED;
return false;
}
returnValue = LIBSBML_OPERATION_SUCCESS;
return true;
}
// 3. the document is invalid
if (checkDocumentValidity() == false)
{
returnValue = LIBSBML_OPERATION_FAILED;
return false;
}
return true;
}
/** @endcond */
/** @cond doxygenIgnored */
bool
SBMLRateRuleConverter::speciesFromMultipleCompartmentsInSameRateRule()
{
listPairString compartmentSpeciesPairs = getCompartmentSpeciesPairs();
listPairString variablesRateRulePairs = getVariablesRateRulePairs();
for (listPairStringIt it_c = compartmentSpeciesPairs.begin();
it_c != compartmentSpeciesPairs.end(); ++it_c)
{
for (listPairStringIt it_r = variablesRateRulePairs.begin();
it_r != variablesRateRulePairs.end(); ++it_r)
{
if (it_c->second == it_r->second)
{
// species from compartment it_c->first is a participant in a rule it_r
std::string ruleVar = it_r->first;
std::string compartmentId = it_c->first;
// check that the variable for this rule is in a same compartment
for (listPairStringIt it_c1 = compartmentSpeciesPairs.begin();
it_c1 != compartmentSpeciesPairs.end(); ++it_c1)
{
if (it_c1 == it_c)
{
// skip the pair we have already considered
continue;
}
if (it_c1->second == ruleVar)
{
if (it_c1->first != compartmentId)
{
// variable in different compartment
return true;
}
}
}
}
}
}
return false;
}
listPairString
SBMLRateRuleConverter::getCompartmentSpeciesPairs()
{
listPairString compartmentSpeciesPairs;
for (unsigned int n = 0; n < mDocument->getModel()->getNumCompartments(); n++)
{
Compartment* comp = mDocument->getModel()->getCompartment(n);
std::string compId = comp->getId();
for (unsigned int m = 0; m < mDocument->getModel()->getNumSpecies(); m++)
{
Species* spec = mDocument->getModel()->getSpecies(m);
if (spec->getCompartment() != compId)
{
continue;
}
pairString pair(comp->getId(), spec->getId());
compartmentSpeciesPairs.push_back(pair);
}
}
return compartmentSpeciesPairs;
}
listPairString
SBMLRateRuleConverter::getVariablesRateRulePairs()
{
listPairString variablesRateRulePairs;
for (unsigned int n = 0; n < mDocument->getModel()->getNumRules(); n++)
{
Rule* rule = mDocument->getModel()->getRule(n);
if (rule->getType() != RULE_TYPE_RATE)
{
continue;
}
std::string varId = rule->getVariable();
const ASTNode* math = rule->getMath();
List* variables = math->getListOfNodes(ASTNode_isName);
for (ListIterator it = variables->begin(); it != variables->end(); ++it)
{
ASTNode* m = static_cast<ASTNode*>(*it);
std::string mId = m->getName();
pairString pair(varId, mId);
variablesRateRulePairs.push_back(pair);
}
}
return variablesRateRulePairs;
}
void
SBMLRateRuleConverter::addODEPair(std::string id, Model* model)
{
ASTNode * zeroNode = SBML_parseL3Formula("0");
Rule* rr = model->getRateRuleByVariable(id);
if (rr!= NULL && rr->getType() == RULE_TYPE_RATE)
{
ASTNode * math;
if (rr->isSetMath())
{
math = replaceAssignedVariablesWithMath(rr->getMath()->deepCopy());
// TO DO return boolean to check this worked
}
else
{
math = zeroNode->deepCopy();
}
mODEs.push_back(std::make_pair(id, math));
}
delete zeroNode;
}
void SBMLRateRuleConverter::populateTerms()
{ // Fages algo 3.6 Step 1
//create set of non decomposable terms used in ODES
// catch any repeats so a term is only present once but may appear in
// multiple ODEs; numerical multipliers are ignored
// ODEs[0] = [S1, -k1*S1]
// ODES[1] = [S2, k1*S1]
// ODES[2] = [S3, k2*S3]
//
// results in
//
// mTerms[0] = k1*S1
// mTerms[1] = k2*S3
for (unsigned int n = 0; n < mODEs.size(); n++)
{
ASTNode* node = mODEs.at(n).second;
node->decompose();
// Fages algo 3.6 Step 2
createTerms(node);
}
//for (unsigned int n = 0; n < mTerms.size(); n++)
//{
// ASTNode* node = mTerms.at(n);
// cout << "Term " << n << ": " << SBML_formulaToL3String(node) << endl;
//}
//print_vectors(mCoefficients);
}
void SBMLRateRuleConverter::createAnalysisVectors()
{// cooefficients
// these are a set of numerical coefficients of each term as it occurs in each ODE
// vector < pair < ASTNode*, vector<double> >
//
// mCoefficients[0] = [mTerms[0], [-1, 1, 0]] - coeff of k1*S1 in -k1*S1, k1*S1, k2*S3
// mCoefficients[1] = [mTerms[1], [0, 0, 1]] - coeff of k2*S3 in -k1*S1, k1*S1, k2*S3
// coefficients are now sorted during the creation of terms
//
// posDerivative/negDerivative
// vector < vector<bool> >
// these are vector of booleans for each term's derivative wrt each variable
// posDerivative - true if the derivative of positive term will always be > 0
// negDerivative - true if the derivative of negative term will always be > 0
//
// in the example
// posDerivative = [[true, false, false], [false, false, true]]
// corresponding to
// d(mTerms[0])/dODEs[0].first > 0 ie d(k1S1)/dS1 = k1 > 0 (true
// d(mTerms[0])/dODEs[1].first > 0 ie d(k1S1)/dS2 = 0 > 0 (false
// d(mTerms[0])/dODEs[2].first > 0 ie d(k1S1)/dS3 = 0 > 0 (false
// d(mTerms[1])/dODEs[0].first > 0 ie d(k2S3)/dS1 = 0 > 0 (false
// d(mTerms[1])/dODEs[1].first > 0 ie d(k2S3)/dS2 = 0 > 0 (false
// d(mTerms[1])/dODEs[2].first > 0 ie d(k2S3)/dS3 = k2 > 0 (true
//
// negDerivative = [[false, false, false], [false, false, false]]
// corresponding to
// d(-1*mTerms[0])/dODEs[0].first > 0 ie d(-k1S1)/dS1 = -k1 > 0 (false
// d(-1*mTerms[0])/dODEs[1].first > 0 ie d(-k1S1)/dS2 = 0 > 0 (false
// d(-1*mTerms[0])/dODEs[2].first > 0 ie d(-k1S1)/dS3 = 0 > 0 (false
// d(-1*mTerms[1])/dODEs[0].first > 0 ie d(-k2S3)/dS1 = 0 > 0 (false
// d(-1*mTerms[1])/dODEs[1].first > 0 ie d(-k2S3)/dS2 = 0 > 0 (false
// d(-1*mTerms[1])/dODEs[2].first > 0 ie d(-k2S3)/dS3 = -k2 > 0 (false
//
// NOTE: variable values are considered positive
for (unsigned int n = 0; n < mTerms.size(); n++)
{
ASTNode* node = mTerms.at(n);
std::vector<double> coeffVector = populateCoefficientVector(n);
mCoefficients.push_back(std::make_pair(node, coeffVector));
mDerivSign = POSITIVE_DERIVATIVE;
std::vector<bool> posDerVector = populateDerivativeVector(n);
mPosDerivative.push_back(posDerVector);
mDerivSign = NEGATIVE_DERIVATIVE;
std::vector<bool> negDerVector = populateDerivativeVector(n);
mNegDerivative.push_back(negDerVector);
}
/*print_vectors(mCoefficients);
print_vectors_bool(mPosDerivative);
print_vectors_bool(mNegDerivative);*/
}
unsigned int
SBMLRateRuleConverter::locateTerm(ASTNode * node)
{
unsigned int index = 0;
for (std::vector<ASTNode*>::iterator it = mTerms.begin(); it != mTerms.end(); ++it)
{
if (node->exactlyEqual(**it))
{
break;
}
else
{
index++;
}
}
return index;
}
bool
SBMLRateRuleConverter::determineCoefficient(ASTNode* ode, unsigned int termN, double& coeff)
{
bool found = false;
coeff = 0;
ASTNode* ode_node = ode->deepCopy();
// we have decomposed nodes so that if it is times the
// first child should be a number
// take it out of the term
// it will be used as a coefficient
// unless we do not want it used as stoichiometry
if (ode_node->getType() == AST_TIMES && ode_node->getNumChildren() > 0)
{
if (ode_node->getChild(0)->isNumber())
{
coeff = ode_node->getChild(0)->getValue();
ode_node->removeChild(0, true);
// we don't want to be left with the times node if it has only one child
if (ode_node->getNumChildren() == 1)
{
ASTNode* child = ode_node->getChild(0)->deepCopy();
delete ode_node;
ode_node = child;
}
}
else
{
coeff = 1;
}
}
else if (ode->getType() == AST_PLUS)
{
unsigned int i = 0;
while (!found && i < ode->getNumChildren())
{
found = determineCoefficient(ode->getChild(i), termN, coeff);
i++;
}
}
else if (ode->getType() == AST_MINUS)
{
if (ode->getNumChildren() == 1)
{
found = determineCoefficient(ode->getChild(0), termN, coeff);
if (found)
{
if (util_isEqual(coeff, 0.0))
{
coeff = -1.0;
}
else
{
coeff *= -1.0;
}
}
}
else
{
found = determineCoefficient(ode->getChild(0), termN, coeff);
if (!found)
{
found = determineCoefficient(ode->getChild(1), termN, coeff);
if (found)
{
if (util_isEqual(coeff, 0.0))
{
coeff = -1.0;
}
else
{
coeff *= -1.0;
}
}
}
}
}
else
{
coeff = 1.0;
}
if (!found)
{
unsigned int index = locateTerm(ode_node);
if (index == termN)
{
found = true;
}
else
{
coeff = 0.0;
}
}
delete ode_node;
return found;
}
std::vector<double>
SBMLRateRuleConverter::populateCoefficientVector(unsigned int termN)
{
std::vector<double> coeffs;
for (unsigned int n = 0; n < mODEs.size(); ++n)
{
ASTNode* ode = mODEs.at(n).second;
double coeff;
determineCoefficient(ode, termN, coeff);
coeffs.push_back(coeff);
}
return coeffs;
}
bool
SBMLRateRuleConverter::determineDerivativeSign(std::string variable, ASTNode* term, bool& derivativeSign)
{
// we need to know whether (d(term[termN])/dvariable) > 0
// we already know that term is non-decomposable - so it will not be a top-level +/-
// and any possible +/- have been expanded
// but the derivative will have an explicit +/- number if it encountered variable
bool found = false;
derivativeSign = false;
bool signDetermined = false;
ASTNode* deriv = NULL;
// if variable is not in term that derivative not > 0
List* names;
names = term->getListOfNodes((ASTNodePredicate)ASTNode_isName);
ListIterator it = names->begin();
while (!found && it != names->end())
{
if (strcmp(variable.c_str(),((ASTNode *)(*it))->getName()) == 0)
{
found = true;
}
++it;
}
if (!found)
{
derivativeSign = false;
signDetermined = true;
}
else
{
if (mDerivSign == NEGATIVE_DERIVATIVE)
{
ASTNode* minus_one = new ASTNode(AST_REAL);
minus_one->setValue(-1.0);
ASTNode* minus = new ASTNode(AST_TIMES);
minus->addChild(minus_one);
minus->addChild(term);
ASTNode* deriv = minus->derivative(variable);
if (deriv != NULL) deriv->decompose();
//cout << "derive: " << SBML_formulaToL3String(minus) << " var: " << variable << " = " <<SBML_formulaToL3String(deriv) << endl;
signDetermined = checkDerivativeSign(deriv, derivativeSign);
//cout << "sign determined: " << derivativeSign << endl;
delete deriv;
}
else
{
ASTNode* deriv = term->derivative(variable);
if (deriv != NULL) deriv->decompose();
//cout << "derive: " << SBML_formulaToL3String(term) << " var: " << variable << " = " << SBML_formulaToL3String(deriv) << endl;
signDetermined = checkDerivativeSign(deriv, derivativeSign);
//cout << "sign determined: " << derivativeSign << endl;
delete deriv;
}
if (!signDetermined)
{
// TO DO log an error
//getDocument()->getErrorLog()->add()
}
delete deriv;
}
delete names;
return signDetermined;
}
bool
SBMLRateRuleConverter::checkDerivativeSign(const ASTNode* node, bool& derivativeSign)
{
bool signDetermined = false;
if (!node)
return signDetermined;
// node will be refactored so should be able to detect sign from first child
ASTNodeType_t type = node->getType();
// posDerivative - true if the derivative of positive term will always be > 0
// negDerivative - true if the derivative of negative term will always be > 0
if (type == AST_REAL)
{
if (util_isEqual(node->getValue(), 0.0))
{
derivativeSign = false;
}
else if (node->getValue() > 0)
{
derivativeSign = true;
}
else
{
derivativeSign = false;
}
signDetermined = true;
}
else if (type == AST_NAME)
{
// variable first always consider >0
derivativeSign = true;
signDetermined = true;
}
unsigned int n = 0;
while (!signDetermined && n < node->getNumChildren())
{
signDetermined = checkDerivativeSign(node->getChild(n), derivativeSign);
n++;
}
return signDetermined;
}
std::vector<bool>
SBMLRateRuleConverter::populateDerivativeVector(unsigned int termN)
{
std::vector<bool> derivatives;
for (unsigned int n = 0; n < mODEs.size(); ++n)
{
std::string variable = mODEs.at(n).first;
bool derivativeSign;
bool determined = determineDerivativeSign(variable, mTerms.at(termN), derivativeSign);
if (!determined)
{
mMathNotSupported = true;
}
derivatives.push_back(derivativeSign);
}
return derivatives;
}
void
SBMLRateRuleConverter::createTerms(ASTNode* node, bool isToplevel)
{
if (node->getType() == AST_PLUS || node->getType() == AST_MINUS)
{
for (unsigned int i = 0; i < node->getNumChildren(); i++)
{
createTerms(node->getChild(i), false);
}
}
else
{
addToTerms(node, isToplevel);
}
}
void
SBMLRateRuleConverter::addToTerms(ASTNode* node, bool isToplevel)
{
// double coefficient = 0.0;
//std::vector<double> coefficients;
if (node == NULL)
{
mMathNotSupported = true;
return;
}
ASTNode* term = node->deepCopy();
// we have decomposed nodes so that if it is times the
// first child should be a number
// take it out of the term
// it will be used as a coefficient
if (term->getType() == AST_TIMES && term->getNumChildren() > 0)
{
if (term->getChild(0)->isNumber())
{
// coefficient = term->getChild(0)->getValue();
//coefficients.push_back(coefficient);
term->removeChild(0, true);
}
// if we are just left with * 1 child remove times
if (term->getNumChildren() == 1)
{
ASTNode* child = term->getChild(0)->deepCopy();
term = child;
// if term is +/- then go back to create term and do not process further
if (term->getType() == AST_PLUS || term->getType() == AST_MINUS)
{
createTerms(term, false);
delete term;
return;
}
}
}
else if (term->isNumber())
{
// here we need to deal with the case where the term is just a number
// if it is the top level but not equal to zero then we need to add it
// if not top level we delete the term
// if it is the top level but equal zero
if (isToplevel)
{
if (util_isEqual(term->getValue(), 0.0))
{
delete term;
return;
}
}
else
{
delete term;
return;
}
}
if (mTerms.size() == 0)
{
mTerms.push_back(term);
//mCoefficients.push_back(std::make_pair(term, coefficients));
}
else
{
bool equivalent = false;
std::vector<ASTNode*>::iterator it = mTerms.begin();