forked from draeger-lab/SBSCL
-
Notifications
You must be signed in to change notification settings - Fork 0
/
EquationSystem.java
1907 lines (1753 loc) · 74.4 KB
/
EquationSystem.java
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
package org.simulator.sbml;
import org.sbml.jsbml.ASTNode;
import org.sbml.jsbml.AssignmentRule;
import org.sbml.jsbml.CallableSBase;
import org.sbml.jsbml.Compartment;
import org.sbml.jsbml.Constraint;
import org.sbml.jsbml.Event;
import org.sbml.jsbml.EventAssignment;
import org.sbml.jsbml.FunctionDefinition;
import org.sbml.jsbml.InitialAssignment;
import org.sbml.jsbml.KineticLaw;
import org.sbml.jsbml.LocalParameter;
import org.sbml.jsbml.Model;
import org.sbml.jsbml.Parameter;
import org.sbml.jsbml.RateRule;
import org.sbml.jsbml.Reaction;
import org.sbml.jsbml.Rule;
import org.sbml.jsbml.SBMLException;
import org.sbml.jsbml.Species;
import org.sbml.jsbml.SpeciesReference;
import org.sbml.jsbml.Symbol;
import org.sbml.jsbml.validator.ModelOverdeterminedException;
import org.sbml.jsbml.validator.OverdeterminationValidator;
import org.simulator.math.RNG;
import org.simulator.math.odes.*;
import org.simulator.sbml.astnode.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.MessageFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public abstract class EquationSystem
implements SBMLValueHolder, DelayedDESystem, EventDESystem,
FastProcessDESystem, RichDESystem, PropertyChangeListener {
/**
* A {@link Logger}.
*/
private static final transient Logger logger = Logger.getLogger(EquationSystem.class.getName());
/**
* Key to memorize user objects in {@link ASTNode}
*/
public static final String TEMP_VALUE = "SBML_SIMULATION_TEMP_VALUE";
/**
* Contains a list of all algebraic rules transformed to assignment rules for
* further processing
*/
protected List<AssignmentRule> algebraicRules;
/**
* Hashes the id of all species located in a compartment to the position of
* their compartment in the Y vector. When a species has no compartment, it is
* hashed to null.
*/
protected Map<String, Integer> compartmentHash;
/**
* This field is necessary to also consider local parameters of the current
* reaction because it is not possible to access these parameters from the
* model. Hence we have to memorize an additional reference to the Reaction
* and thus to the list of these parameters.
*/
protected Reaction currentReaction;
/**
* Holds the current time of the simulation
*/
protected double currentTime;
/**
* This array stores for every event an object of {@link SBMLEventInProgress} that is used
* to handle event processing during simulation
*/
protected SBMLEventInProgress events[];
/**
* This set stores the priorities of the currently processed events.
*/
protected HashSet<Double> priorities;
/**
* An array, which stores all computed initial values of the model. If this
* model does not contain initial assignments, the initial values will only be
* taken once from the information stored in the model. Otherwise they have to
* be computed again as soon as the parameter values of this model are
* changed, because the parameters may influence the return values of the
* initial assignments.
*/
protected double[] initialValues;
/**
* A {@link List} of {@link ConstraintListener}, which deal with violation
* of {@link Constraint}s during simulation.
*/
protected List<ConstraintListener> listOfConstraintListeners;
/**
* An array that stores derivatives of each species in the model system at
* current time.
*/
public double[] changeRate;
/**
* The model to be simulated.
*/
protected Model model;
/**
* Hashes the id of all {@link Compartment}s, {@link Species}, global
* {@link Parameter}s, and, if necessary, {@link SpeciesReference}s in
* {@link RateRule}s to an value object which contains the position in the
* {@link #Y} vector
*/
protected Map<String, Integer> symbolHash;
/**
* Hashes the id of all {@link Compartment}s, {@link Species}, global
* {@link Parameter}s, and, if necessary, {@link SpeciesReference}s in
* {@link RateRule}s to an boolean object which contains whether it is
* constant or not
*/
protected Map<String, Boolean> constantHash;
/**
* An array of strings that memorizes at each position the identifier of the
* corresponding element in the Y array.
*/
protected String[] symbolIdentifiers;
/**
* An array of the velocities of each reaction within the model system.
* Holding this globally saves many new memory allocations during simulation
* time.
*/
protected double[] v;
/**
* This {@link Map} saves the current stoichiometric coefficients for those
* {@link SpeciesReference} objects that are a target to an Assignment
* .
*/
protected Map<String, Double> stoichiometricCoefHash;
/**
* An array of the state variables within the model including species and parameters.
*/
protected double[] Y;
/**
* A boolean indicating whether the solver is currently processing fast
* reactions or not
*/
protected boolean isProcessingFastReactions = false;
/**
* A boolean indicating whether a model has fast reactions or not.
*/
protected boolean hasFastReactions = false;
/**
* Stores the indices of the {@link Event}s triggered for the current point
* in time.
*/
protected List<Integer> runningEvents;
/**
* Stores the indices of the events triggered for a future point in time.
*/
protected List<Integer> delayedEvents;
/**
* Map for faster access to species.
*/
protected Map<String, Species> speciesMap;
/**
* {@link Species} with the unit given in mol/volume for which it has to be
* considered that the change rate should always be only in mol/time
*/
protected Set<String> inConcentration;
/**
* List of kinetic laws given as ASTNodeObjects
*/
protected ASTNodeValue[] kineticLawRoots;
/**
* List of constraints given as {@link ASTNodeValue} objects
*/
protected List<ASTNodeValue> constraintRoots;
/**
* List of all occurring {@link ASTNode}s
*/
protected List<ASTNode> nodes;
/**
* Node interpreter taking the time into consideration
*/
protected ASTNodeInterpreter nodeInterpreter;
/**
* List of all occuring stoichiometries
*/
protected StoichiometryValue[] stoichiometryValues;
/**
* Array that stores which reactions are fast
*/
protected boolean[] reactionFast;
/**
* Array that stores which reactions are reversible
*/
protected boolean[] reactionReversible;
/**
* List of the assignment rules (as AssignmentRuleObjects)
*/
protected List<AssignmentRuleValue> assignmentRulesRoots;
/**
* List of the rate rules (as RateRuleObjects)
*/
protected List<RateRuleValue> rateRulesRoots;
/**
* Map for getting the raterule index (in the rateRulesRoots ArrayList)
* of particular id
*/
protected Map<String, Integer> rateRuleHash;
/**
* Current time for the ASTNode processing (not equal to the simulation time!)
*/
protected double astNodeTime;
/**
* Value holder for computation of delayed values
*/
protected DelayValueHolder delayValueHolder;
/**
* List which is used for choosing the next event to process
*/
protected List<Integer> highOrderEvents;
/**
* Array of the conversionFactors given (default value: 1)
*/
protected double[] conversionFactors;
/**
* Flag which stores whether the model contains any events
*/
protected boolean modelHasEvents;
/**
* Number of rate rules
*/
protected int nRateRules;
/**
* Number of assignment rules
*/
protected int nAssignmentRules;
/**
* List of the {@link InitialAssignment} (as {@link AssignmentRuleValue} objects)
*/
protected List<AssignmentRuleValue> initialAssignmentRoots;
/**
* Flag which is true if no changes (in rate rules and kinetic laws) occur in the model
*/
protected boolean noDerivatives;
/**
* Array that shows whether a division by the compartment size is necessary after computation of the derivatives.
*/
protected boolean[] inConcentrationValues;
/**
* Contains the compartment indexes of the species in the Y vector.
*/
protected int[] compartmentIndexes;
/**
* Are the stoichiometries in the stoichiometry values set?
*/
protected boolean[] stoichiometrySet;
/**
* Are the stoichiometries in the stoichiometry values constant?
*/
protected boolean[] constantStoichiometry;
/**
* Is the stoichiometry value referring to a species whose value does not change?
*/
protected boolean[] zeroChange;
/**
* Is the stoichiometry value referring to a reactant?
*/
protected boolean[] isReactant;
/**
* The indices of the reactions the stoichiometry values are referring to
*/
protected int[] reactionIndex;
/**
* The species indices of the stoichiometry values
*/
protected int[] speciesIndex;
/**
* The current stoichiometries of the stoichiometry values
*/
protected double[] stoichiometry;
/**
* Is the SBase in the Y vector an amount?
*/
protected boolean[] isAmount;
/**
* Are delays included in the computation?
*/
protected boolean delaysIncluded;
/**
* The number of repetitions for the processing of assignment rules
*/
protected int numberOfAssignmentRulesLoops;
/**
* Array for saving older Y values
*/
protected double[] oldY;
/**
* Array for saving older Y values (when computing delayed values)
*/
protected double[] oldY2;
protected boolean containsDelays;
/**
* The value of the latest time point
*/
protected double latestTimePoint;
/**
* The value of the previous time point
*/
protected double previousTimePoint;
/**
* An array of the concentration of each species at latest processed time point
* within the model system.
*/
protected double[] latestTimePointResult;
/**
* Property name for getting the latest result processed.
*/
private static final String RESULT = "result";
public EquationSystem(Model model){
this.model = model;
}
/**
* This method initializes the differential equation system for simulation.
* The user can tell whether the tree of {@link ASTNode}s has to be
* refreshed, give some default values and state whether a {@link Species}
* is seen as an amount or a concentration.
*
* @param renewTree
* @param defaultSpeciesValue
* @param defaultParameterValue
* @param defaultCompartmentValue
* @param amountHash
* @throws ModelOverdeterminedException
* @throws SBMLException
*/
public void init(boolean renewTree, double defaultSpeciesValue, double defaultParameterValue,
double defaultCompartmentValue, Map<String, Boolean> amountHash) throws ModelOverdeterminedException {
v = new double[this.model.getNumReactions()];
symbolHash = new HashMap<>();
constantHash = new HashMap<>();
compartmentHash = new HashMap<>();
stoichiometricCoefHash = new HashMap<>();
speciesMap = new HashMap<>();
rateRuleHash = new HashMap<>();
priorities = new HashSet<>();
inConcentration = new HashSet<>();
currentTime = 0d;
astNodeTime = 0d;
latestTimePoint = 0d;
reactionFast = new boolean[this.model.getReactionCount()];
reactionReversible = new boolean[this.model.getReactionCount()];
highOrderEvents = new LinkedList<>();
listOfConstraintListeners = new LinkedList<>();
nodes = new LinkedList<>();
delaysIncluded = true;
containsDelays = false;
noDerivatives = false;
nodeInterpreter = new ASTNodeInterpreter(this);
int i;
int compartmentIndex, yIndex = 0;
if ((model.getReactionCount() == 0) && (constraintRoots == null)) {
noDerivatives = true;
for (int k = 0; k < model.getRuleCount(); k++) {
Rule rule = model.getRule(k);
if (rule.isRate()) {
noDerivatives = false;
}
}
}
Map<String, Integer> speciesReferenceToRateRule = new HashMap<>();
int speciesReferencesInRateRules = 0;
for (int k = 0; k < model.getRuleCount(); k++) {
Rule rule = model.getRule(k);
if (rule.isRate()) {
RateRule rr = (RateRule) rule;
SpeciesReference sr = model.findSpeciesReference(rr.getVariable());
if ((sr != null) && !sr.isConstant()) {
speciesReferencesInRateRules++;
speciesReferenceToRateRule.put(sr.getId(), k);
}
}
}
int sizeY = model.getCompartmentCount() + model.getSpeciesCount() + model.getParameterCount() + speciesReferencesInRateRules;
Y = new double[sizeY];
oldY = new double[sizeY];
oldY2 = new double[sizeY];
changeRate = new double[sizeY];
isAmount = new boolean[sizeY];
compartmentIndexes = new int[sizeY];
conversionFactors = new double[sizeY];
inConcentrationValues = new boolean[sizeY];
Arrays.fill(conversionFactors, 1d);
symbolIdentifiers = new String[sizeY];
initialValues = new double[sizeY];
latestTimePointResult = new double[sizeY];
/*
* Save starting values of the model's compartment in Y
*/
for (i = 0; i < model.getCompartmentCount(); i++) {
Compartment c = model.getCompartment(i);
if (!c.isSetValue()) {
Y[yIndex] = defaultCompartmentValue;
} else {
Y[yIndex] = c.getSize();
}
symbolHash.put(c.getId(), yIndex);
constantHash.put(c.getId(), c.isConstant());
symbolIdentifiers[yIndex] = c.getId();
yIndex++;
}
// Due to unset initial amount or concentration of species try to set
// one of them
Species majority = determineMajorSpeciesAttributes();
/*
* Save starting values of the model's species in Y and link them with their
* compartment
*/
for (i = 0; i < model.getSpeciesCount(); i++) {
Species s = model.getSpecies(i);
speciesMap.put(s.getId(), s);
if (!s.getBoundaryCondition() && !s.isConstant()) {
Parameter convParameter = s.getConversionFactorInstance();
if (convParameter == null) {
convParameter = model.getConversionFactorInstance();
}
if (convParameter != null) {
conversionFactors[yIndex] = convParameter.getValue();
}
}
compartmentIndex = symbolHash.get(s.getCompartment());
// Set initial amount or concentration when not already done
if (!s.isSetInitialAmount() && !s.isSetInitialConcentration()) {
if (majority.isSetInitialAmount()) {
s.setInitialAmount(0d);
} else {
s.setInitialConcentration(0d);
}
s.setHasOnlySubstanceUnits(majority.getHasOnlySubstanceUnits());
}
//determine whether amount or concentration is set
if ((amountHash != null)) {
if (amountHash.containsKey(s.getId())) {
isAmount[yIndex] = amountHash.get(s.getId());
} else {
isAmount[yIndex] = s.isSetInitialAmount();
}
} else {
isAmount[yIndex] = s.isSetInitialAmount();
}
if (!s.isSetValue()) {
Y[yIndex] = defaultSpeciesValue;
} else {
if (s.isSetInitialAmount()) {
if (isAmount[yIndex]) {
Y[yIndex] = s.getInitialAmount();
} else {
Y[yIndex] = s.getInitialAmount() / Y[compartmentIndex];
}
} else {
if (!isAmount[yIndex]) {
Y[yIndex] = s.getInitialConcentration();
} else {
Y[yIndex] = s.getInitialConcentration() * Y[compartmentIndex];
}
}
}
symbolHash.put(s.getId(), yIndex);
constantHash.put(s.getId(), s.isConstant());
compartmentHash.put(s.getId(), compartmentIndex);
compartmentIndexes[yIndex] = compartmentIndex;
symbolIdentifiers[yIndex] = s.getId();
yIndex++;
}
/*
* Save starting values of the stoichiometries
*/
for (String id : speciesReferenceToRateRule.keySet()) {
SpeciesReference sr = model.findSpeciesReference(id);
Y[yIndex] = sr.getStoichiometry();
symbolHash.put(id, yIndex);
constantHash.put(id, sr.isConstant());
symbolIdentifiers[yIndex] = id;
yIndex++;
}
/*
* Save starting values of the model's parameter in Y
*/
for (i = 0; i < model.getParameterCount(); i++) {
Parameter p = model.getParameter(i);
if (!p.isSetValue()) {
Y[yIndex] = defaultParameterValue;
} else {
Y[yIndex] = p.getValue();
}
symbolHash.put(p.getId(), yIndex);
constantHash.put(p.getId(), p.isConstant());
symbolIdentifiers[yIndex] = p.getId();
yIndex++;
}
/*
* Check for fast reactions & update math of kinetic law to avoid wrong
* links concerning local parameters
*/
if (reactionFast.length != model.getReactionCount()) {
reactionFast = new boolean[model.getReactionCount()];
}
int reactionIndex = 0;
boolean fastReactions = false;
for (Reaction r : model.getListOfReactions()) {
if (r.isSetFast()) {
reactionFast[reactionIndex] = r.getFast();
} else {
reactionFast[reactionIndex] = false;
}
reactionReversible[reactionIndex] = r.isReversible();
if (r.isSetFast() && r.getFast()) {
fastReactions = true;
}
if (r.getKineticLaw() != null) {
if (r.getKineticLaw().getListOfLocalParameters().size() > 0 && r.getKineticLaw().isSetMath()) {
r.getKineticLaw().getMath().updateVariables();
}
}
Species species;
String speciesID;
for (SpeciesReference speciesRef : r.getListOfReactants()) {
speciesID = speciesRef.getSpecies();
species = speciesMap.get(speciesID);
if (species != null) {
if (!isAmount[symbolHash.get(speciesID)]) {
inConcentration.add(speciesID);
}
}
}
for (SpeciesReference speciesRef : r.getListOfProducts()) {
speciesID = speciesRef.getSpecies();
species = speciesMap.get(speciesID);
if (species != null) {
if (!isAmount[symbolHash.get(speciesID)]) {
inConcentration.add(speciesID);
}
}
}
reactionIndex++;
}
if (fastReactions) {
hasFastReactions = true;
}
for (i = 0; i != inConcentrationValues.length; i++) {
if (inConcentration.contains(symbolIdentifiers[i])) {
inConcentrationValues[i] = true;
} else {
inConcentrationValues[i] = false;
}
}
/*
* Algebraic Rules
*/
boolean containsAlgebraicRules = false;
for (i = 0; i < model.getRuleCount(); i++) {
if (model.getRule(i).isAlgebraic() && model.getRule(i).isSetMath()) {
containsAlgebraicRules = true;
break;
}
}
if (containsAlgebraicRules) {
evaluateAlgebraicRules();
}
/*
* Initialize Events
*/
if (model.getEventCount() > 0) {
// this.events = new ArrayList<EventWithPriority>();
if (events == null) {
events = new SBMLEventInProgress[model.getEventCount()];
}
runningEvents = new ArrayList<Integer>();
delayedEvents = new ArrayList<Integer>();
initEvents();
modelHasEvents = true;
} else {
modelHasEvents = false;
}
if (renewTree) {
createSimplifiedSyntaxTree();
} else {
refreshSyntaxTree();
}
// save the initial values of this system, necessary at this point for the delay function
if (initialValues.length != Y.length) {
initialValues = new double[Y.length];
}
System.arraycopy(Y, 0, initialValues, 0, initialValues.length);
/*
* Evaluate Constraints
*/
if (model.getConstraintCount() > 0) {
// TODO: This is maybe not the best solution because callers can hardly influence that because this init method is called upon creation of this object.
if (getConstraintListenerCount() == 0) {
addConstraintListener(new SimpleConstraintListener());
}
checkConstraints(0d);
}
}
/**
* Creates the syntax tree and simplifies it.
*/
private void createSimplifiedSyntaxTree() {
nodes.clear();
initializeKineticLaws();
initializeRules();
initializeConstraints();
initializeEvents();
}
/**
* Refreshes the syntax tree (e.g., resets the ASTNode time)
*/
protected void refreshSyntaxTree() {
for (ASTNode node : nodes) {
((ASTNodeValue) node.getUserObject(TEMP_VALUE)).reset();
}
for (int i = 0; i != stoichiometryValues.length; i++) {
stoichiometryValues[i].refresh();
stoichiometrySet[i] = stoichiometryValues[i].getStoichiometrySet();
}
}
/**
* Includes the math of the kinetic laws in the syntax tree.
*/
private void initializeKineticLaws() {
int reaction = 0;
List<Boolean> isReactantList = new ArrayList<Boolean>();
List<Integer> speciesIndexList = new ArrayList<Integer>();
List<Integer> reactionIndexList = new ArrayList<Integer>();
List<Boolean> zeroChangeList = new ArrayList<Boolean>();
List<Boolean> constantStoichiometryList = new ArrayList<Boolean>();
List<StoichiometryValue> stoichiometriesList = new ArrayList<StoichiometryValue>();
List<ASTNodeValue> kineticLawRootsList = new ArrayList<ASTNodeValue>();
for (Reaction r : model.getListOfReactions()) {
KineticLaw kl = r.getKineticLaw();
if (kl != null && kl.isSetMath()) {
ASTNodeValue currentLaw = (ASTNodeValue) copyAST(kl.getMath(), true, null, null).getUserObject(TEMP_VALUE);
kineticLawRootsList.add(currentLaw);
kl.getMath().putUserObject(TEMP_VALUE, currentLaw);
for (SpeciesReference speciesRef : r.getListOfReactants()) {
String speciesID = speciesRef.getSpecies();
int speciesIndex = symbolHash.get(speciesID);
int srIndex = -1;
if (model.getLevel() >= 3) {
String id = speciesRef.getId();
if (id != null) {
if (symbolHash.containsKey(id)) {
srIndex = symbolHash.get(id);
}
}
}
//Value for stoichiometry math
ASTNodeValue currentMathValue = null;
if (speciesRef.isSetStoichiometryMath() && speciesRef.getStoichiometryMath().isSetMath()) {
@SuppressWarnings("deprecation") ASTNode currentMath = speciesRef.getStoichiometryMath().getMath();
currentMathValue = (ASTNodeValue) copyAST(currentMath, true, null, null).getUserObject(TEMP_VALUE);
currentMath.putUserObject(TEMP_VALUE, currentMathValue);
}
boolean constantStoichiometry = false;
if (speciesRef.isSetConstant()) {
constantStoichiometry = speciesRef.getConstant();
} else if ((!speciesRef.isSetId()) && (!speciesRef.isSetStoichiometryMath())) {
constantStoichiometry = true;
}
boolean zeroChange = false;
Species s = speciesRef.getSpeciesInstance();
if (s != null) {
if (s.getBoundaryCondition()) {
zeroChange = true;
}
if (s.getConstant()) {
zeroChange = true;
}
}
zeroChangeList.add(zeroChange);
constantStoichiometryList.add(constantStoichiometry);
reactionIndexList.add(reaction);
speciesIndexList.add(speciesIndex);
isReactantList.add(true);
stoichiometriesList.add(new StoichiometryValue(speciesRef, srIndex, stoichiometricCoefHash, Y, currentMathValue));
}
for (SpeciesReference speciesRef : r.getListOfProducts()) {
String speciesID = speciesRef.getSpecies();
int speciesIndex = symbolHash.get(speciesID);
int srIndex = -1;
if (model.getLevel() >= 3) {
String id = speciesRef.getId();
if (id != null) {
if (symbolHash.containsKey(id)) {
srIndex = symbolHash.get(id);
}
}
}
//Value for stoichiometry math
ASTNodeValue currentMathValue = null;
if (speciesRef.isSetStoichiometryMath() && speciesRef.getStoichiometryMath().isSetMath()) {
@SuppressWarnings("deprecation") ASTNode currentMath = speciesRef.getStoichiometryMath().getMath();
currentMathValue = (ASTNodeValue) copyAST(currentMath, true, null, null).getUserObject(TEMP_VALUE);
currentMath.putUserObject(TEMP_VALUE, currentMathValue);
}
boolean constantStoichiometry = false;
if (speciesRef.isSetConstant()) {
constantStoichiometry = speciesRef.getConstant();
} else if ((!speciesRef.isSetId()) && (!speciesRef.isSetStoichiometryMath())) {
constantStoichiometry = true;
}
boolean zeroChange = false;
Species s = speciesRef.getSpeciesInstance();
if (s != null) {
if (s.getBoundaryCondition()) {
zeroChange = true;
}
if (s.getConstant()) {
zeroChange = true;
}
}
zeroChangeList.add(zeroChange);
constantStoichiometryList.add(constantStoichiometry);
reactionIndexList.add(reaction);
speciesIndexList.add(speciesIndex);
isReactantList.add(false);
stoichiometriesList.add(new StoichiometryValue(speciesRef, srIndex, stoichiometricCoefHash, Y, currentMathValue));
}
} else {
kineticLawRootsList.add(new ASTNodeValue(nodeInterpreter, new ASTNode(0d)));
}
reaction++;
}
int stoichiometriesSize = stoichiometriesList.size();
stoichiometryValues = stoichiometriesList.toArray(new StoichiometryValue[stoichiometriesSize]);
kineticLawRoots = kineticLawRootsList.toArray(new ASTNodeValue[v.length]);
isReactant = new boolean[stoichiometriesSize];
speciesIndex = new int[stoichiometriesSize];
reactionIndex = new int[stoichiometriesSize];
zeroChange = new boolean[stoichiometriesSize];
constantStoichiometry = new boolean[stoichiometriesSize];
stoichiometrySet = new boolean[stoichiometriesSize];
stoichiometry = new double[stoichiometriesSize];
for (int i = 0; i != stoichiometriesSize; i++) {
isReactant[i] = isReactantList.get(i);
speciesIndex[i] = speciesIndexList.get(i);
reactionIndex[i] = reactionIndexList.get(i);
zeroChange[i] = zeroChangeList.get(i);
constantStoichiometry[i] = constantStoichiometryList.get(i);
stoichiometrySet[i] = stoichiometryValues[i].getStoichiometrySet();
stoichiometry[i] = stoichiometryValues[i].getStoichiometry();
}
}
/**
* Includes the math of the rules in the syntax tree.
*/
private void initializeRules() {
Set<AssignmentRuleValue> assignmentRulesRootsInit = new HashSet<AssignmentRuleValue>();
initialAssignmentRoots = new ArrayList<AssignmentRuleValue>();
rateRulesRoots = new ArrayList<RateRuleValue>();
Integer symbolIndex;
for (int i = 0; i < model.getRuleCount(); i++) {
Rule rule = model.getRule(i);
if (rule.isAssignment()) {
AssignmentRule as = (AssignmentRule) rule;
symbolIndex = symbolHash.get(as.getVariable());
if (symbolIndex != null) {
Species sp = model.getSpecies(as.getVariable());
if (sp != null) {
Compartment c = sp.getCompartmentInstance();
boolean hasZeroSpatialDimensions = true;
if ((c != null) && (c.getSpatialDimensions() > 0)) {
hasZeroSpatialDimensions = false;
}
if (as.isSetMath()) {
assignmentRulesRootsInit.add(new AssignmentRuleValue((ASTNodeValue) copyAST(as.getMath(), true, null, null).getUserObject(TEMP_VALUE), symbolIndex, sp, compartmentHash.get(sp.getId()), hasZeroSpatialDimensions, this, isAmount[symbolIndex]));
}
} else {
if (as.isSetMath()) {
assignmentRulesRootsInit.add(new AssignmentRuleValue((ASTNodeValue) copyAST(as.getMath(), true, null, null).getUserObject(TEMP_VALUE), symbolIndex));
}
}
} else if (model.findSpeciesReference(as.getVariable()) != null) {
SpeciesReference sr = model.findSpeciesReference(as.getVariable());
if (!sr.isConstant() && as.isSetMath()) {
assignmentRulesRootsInit.add(new AssignmentRuleValue((ASTNodeValue) copyAST(as.getMath(), true, null, null).getUserObject(TEMP_VALUE), sr.getId(), stoichiometricCoefHash));
}
}
} else if (rule.isRate()) {
RateRule rr = (RateRule) rule;
symbolIndex = symbolHash.get(rr.getVariable());
if (symbolIndex != null) {
Species sp = model.getSpecies(rr.getVariable());
if (sp != null) {
Compartment c = sp.getCompartmentInstance();
boolean hasZeroSpatialDimensions = true;
if ((c != null) && (c.getSpatialDimensions() > 0)) {
hasZeroSpatialDimensions = false;
}
if (rr.isSetMath()) {
rateRulesRoots.add(new RateRuleValue((ASTNodeValue) copyAST(rr.getMath(), true, null, null).getUserObject(TEMP_VALUE), symbolIndex, sp, compartmentHash.get(sp.getId()), hasZeroSpatialDimensions, this, rr.getVariable(), isAmount[symbolIndex]));
rateRuleHash.put(rr.getVariable(), rateRulesRoots.size() - 1);
}
} else if (compartmentHash.containsValue(symbolIndex)) {
List<Integer> speciesIndices = new LinkedList<Integer>();
for (Map.Entry<String, Integer> entry : compartmentHash.entrySet()) {
if (entry.getValue().equals(symbolIndex)) {
Species s = model.getSpecies(entry.getKey());
int speciesIndex = symbolHash.get(entry.getKey());
if ((!isAmount[speciesIndex]) && (!s.isConstant())) {
speciesIndices.add(speciesIndex);
}
}
}
if (rr.isSetMath()) {
rateRulesRoots.add(new RateRuleValue((ASTNodeValue) copyAST(rr.getMath(), true, null, null).getUserObject(TEMP_VALUE), symbolIndex, speciesIndices, this, rr.getVariable()));
rateRuleHash.put(rr.getVariable(), rateRulesRoots.size() - 1);
}
} else {
if (rr.isSetMath()) {
rateRulesRoots.add(new RateRuleValue((ASTNodeValue) copyAST(rr.getMath(), true, null, null).getUserObject(TEMP_VALUE), symbolIndex, rr.getVariable()));
rateRuleHash.put(rr.getVariable(), rateRulesRoots.size() - 1);
}
}
}
}
}
/*
* Traversing through all the rate rules for finding if species
* are present in changing compartment. Traversing is done again as the
* the compartment rate rules in the SBML models can be declared after the
* species rate rule.
*/
for (int i = 0; i < model.getRuleCount(); i++) {
Rule rr = model.getRule(i);
if (rr.isRate()) {
RateRule rateRule = (RateRule) rr;
symbolIndex = symbolHash.get(rateRule.getVariable());
if (symbolIndex != null) {
Species sp = model.getSpecies(rateRule.getVariable());
if (sp != null) {
Compartment c = sp.getCompartmentInstance();
if ((c != null) && (rateRuleHash.get(c.getId()) != null)) {
rateRulesRoots.get(rateRuleHash.get(sp.getId())).setCompartmentRateRule(rateRulesRoots.get(rateRuleHash.get(c.getId())));
}
}
}
}
}
if (algebraicRules != null) {
for (AssignmentRule as : algebraicRules) {
symbolIndex = symbolHash.get(as.getVariable());
if (symbolIndex != null) {
Species sp = model.getSpecies(as.getVariable());
if (sp != null) {
Compartment c = sp.getCompartmentInstance();
boolean hasZeroSpatialDimensions = true;
if ((c != null) && (c.getSpatialDimensions() > 0)) {
hasZeroSpatialDimensions = false;
}
if (as.isSetMath()) {
assignmentRulesRootsInit.add(new AssignmentRuleValue((ASTNodeValue) copyAST(as.getMath(), true, null, null).getUserObject(TEMP_VALUE), symbolIndex, sp, compartmentHash.get(sp.getId()), hasZeroSpatialDimensions, this, isAmount[symbolIndex]));
}
} else {
if (as.isSetMath()) {
assignmentRulesRootsInit.add(new AssignmentRuleValue((ASTNodeValue) copyAST(as.getMath(), true, null, null).getUserObject(TEMP_VALUE), symbolIndex));
}
}
} else if (model.findSpeciesReference(as.getVariable()) != null) {
SpeciesReference sr = model.findSpeciesReference(as.getVariable());
if (!sr.isConstant() && as.isSetMath()) {
assignmentRulesRootsInit.add(new AssignmentRuleValue((ASTNodeValue) copyAST(as.getMath(), true, null, null).getUserObject(TEMP_VALUE), sr.getId(), stoichiometricCoefHash));
}
}
}
}
assignmentRulesRoots = new ArrayList<AssignmentRuleValue>();
if (assignmentRulesRootsInit.size() <= 1) {
for (AssignmentRuleValue rv : assignmentRulesRootsInit) {
assignmentRulesRoots.add(rv);
numberOfAssignmentRulesLoops = 1;
}
} else {
// Determine best order of assignment rule roots
Map<String, Set<String>> neededRules = new HashMap<String, Set<String>>();
Map<String, AssignmentRuleValue> sBaseMap = new HashMap<String, AssignmentRuleValue>();
Set<String> variables = new HashSet<String>();
for (AssignmentRuleValue rv : assignmentRulesRootsInit) {
assignmentRulesRoots.add(rv);
if (rv.getIndex() != -1) {
variables.add(symbolIdentifiers[rv.getIndex()]);
sBaseMap.put(symbolIdentifiers[rv.getIndex()], rv);
} else if (rv.getSpeciesReferenceID() != null) {
variables.add(rv.getSpeciesReferenceID());
sBaseMap.put(rv.getSpeciesReferenceID(), rv);
}
}
for (String variable : variables) {
for (String dependentVariable : getSetOfVariables(sBaseMap.get(variable).getMath(), variables, new HashSet<String>())) {
Set<String> currentSet = neededRules.get(dependentVariable);
if (currentSet == null) {
currentSet = new HashSet<String>();
neededRules.put(dependentVariable, currentSet);
}
currentSet.add(variable);
}
}
int currentPosition = assignmentRulesRootsInit.size() - 1;
Set<String> toRemove = new HashSet<String>();
Set<String> keysToRemove = new HashSet<String>();
boolean toContinue = variables.size() > 0;
while (toContinue) {
toContinue = false;
toRemove.clear();
keysToRemove.clear();