-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel.py
More file actions
1605 lines (1228 loc) · 56.9 KB
/
model.py
File metadata and controls
1605 lines (1228 loc) · 56.9 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
import numpy as np
import time
import matplotlib.pyplot as plt
class Model(object):
""" Defines biological or chemical system """
def __init__(self, signs=None):
if not signs:
self.signs = ["+", "->", "*", "-", "**"]
def __repr__(self):
if hasattr(self, 'params'):
params = self.params
else:
params = None
if hasattr(self, 'components'):
components = self.components
else:
components = None
if hasattr(self, 'ROC_'):
ROC_ = self.ROC_
else:
ROC_ = None
if hasattr(self, 'react_names'):
react_names = self.react_names
else:
react_names = None
if hasattr(self, 'reacts_'):
reacts_ = self.reacts_
else:
reacts_ = None
if hasattr(self, 'coeffs_'):
coeffs_ = self.coeffs_
else:
coeffs_ = None
if hasattr(self, 'react_sps'):
react_sps = self.react_sps
else:
react_sps = None
if hasattr(self, 'rates_'):
rates_ = self.rates_
else:
rates_ = None
return (f"Model: {self.signs}, {params}, {components}, {ROC_}, "
f"{react_names}, {reacts_}, {coeffs_}, {react_sps}, {rates_}")
def reset(self):
self.params = None
self.components = None
self.ROC_ = None
self.react_names = None
self.reacts_ = None
self.coeffs_ = None
self.reset_sps = None
self.rates = None
def parameters(self, params):
"""
params: A dictionary containing all rate constants in the system.
Each key represents a rate constant (e.g., K1, K2, ..., Kn),
and each corresponding value represents the value of that rate constant.
"""
if not isinstance(params, dict):
raise TypeError("params must be a dictionary.")
self.params = params
setattr(self, "param_names", list(params.keys()))
for key, val in params.items():
setattr(self, key, val)
def species(self, components, rate_change):
"""
components: A dictionary containing all species in the system.
Each key represents a specie (e.g. A, B, ...), and
each corresponding value represents the initial concentration.
rate_change: A dictionary containing rate of change for each component.
"""
if not isinstance(components, dict):
raise TypeError("components must be a dictionary.")
if not isinstance(rate_change, dict):
raise TypeError("rate_change must be a dictionary.")
setattr(self, "components", list(components.keys()))
for key, val in components.items():
setattr(self, key, val)
ROC_ = dict()
for key, val in rate_change.items():
roc = []
val = val.replace('+', ' + ').replace('->', ' -> ').replace('*', ' * ').replace('-', ' - ').replace('**', ' ** ')
val = val.split()
for v in val:
if v in self.components or v in self.params.keys():
roc.append(v)
elif v in self.signs:
roc.append(v)
else:
try:
roc.append(float(v))
except ValueError:
print(f"This part of the rate_change ({v}) is not valid!")
roc = " ".join([str(r) for r in roc])
ROC_[key] = roc
setattr(self, "ROC_", ROC_)
def reactions(self, reacts, rates):
"""
reactions: A dictionary containing reaction equation for each reaction.
Each key represents the reaction name, and each value represents the reaction equation.
exp:
{"reaction1": "A + B -> C", ...}
rates: A dictionary containing rate equations (or propensity functions) for each reaction.
Each key represents the reaction name, and each value represents the rate equation of that reaction.
exp:
{reaction1: "K1 * A * B", ...}
"""
if not isinstance(reacts, dict):
raise TypeError("reacts must be a dictionary.")
if not isinstance(rates, dict):
raise TypeError("rates must be a dictionary.")
setattr(self, "react_names", list(reacts.keys()))
if not self.params or not self.components:
raise ValueError("Please define Species and Parameters before Reactions!")
reacts_ = dict()
coefficients = dict()
react_sps = dict()
for reaction, formula in reacts.items():
react = []
react_eq = formula.replace('+', ' + ').replace('->', ' -> ').replace('*', ' * ').replace('**', ' ** ')
components = react_eq.split()
if '->' not in formula:
raise ValueError(f"Missing '->' in the reaction equation for {reaction}.")
if formula.count('->') != 1:
raise ValueError(
f"Each reaction should have exactly one '->', but there are {formula.count('->')} in {reaction}.")
for component in components:
if component in self.components or component in self.params:
react.append(component)
elif component in self.signs:
react.append(component)
else:
try:
react.append(float(component))
except ValueError:
print(f"Unexpected component '{component}' in the reaction equation for {reaction}.")
comp = []
for component in components:
if component in self.components:
comp.append(component)
react = " ".join([str(r) for r in react])
reacts_[reaction] = react
react_sps[reaction] = comp
coefficient = dict()
index = [index for index, value in enumerate(components) if value == '->']
if len(index) > 1:
print(f"Each reaction should have exactly one '->', but there are more than one in the {reaction}.")
for i in range(index[0]):
if components[i] in self.components:
if components[i-1] not in self.signs and components[i-1] not in self.components:
coefficient[components[i]] = - eval(components[i-1])
else:
coefficient[components[i]] = - 1
for j in range(index[0]+1, len(components)):
if components[j] in self.components:
if components[j-1] not in self.signs and components[j-1] not in self.components:
coefficient[components[j]] = eval(components[j - 1])
else:
coefficient[components[j]] = 1
coefficients[reaction] = coefficient
setattr(self, "reacts_", reacts_)
setattr(self, "coeffs_", coefficients)
setattr(self, "react_sps", react_sps)
rates_ = dict()
for reaction, rate in rates.items():
rate_equation = []
rate_eq = rate.replace('*', ' * ').replace('+', ' + ').replace('->', ' -> ').replace('**', ' ** ')
components = rate_eq.split()
for component in components:
if component in self.components or component in self.params:
rate_equation.append(component)
elif component in self.signs:
rate_equation.append(component)
else:
try:
rate_equation.append(float(component))
except ValueError:
print(f"This component {component} is not valid!")
rate_equation = " ".join([str(rate) for rate in rate_equation])
try:
if reaction in self.reacts_.keys():
rates_[reaction] = rate_equation
except ValueError:
print("Reactions and rates do not match!")
setattr(self, "rates_", rates_)
class EulerSimulator(object):
""" Simulation using Euler method """
def __init__(
self,
model=None,
start=0,
stop=10,
epochs=1000,
seed=42,
model_name="Euler Method",
**kwargs
):
self.model = model
self.start = start
self.stop = stop
self.epochs = epochs
self.seed = seed
self.model_name = model_name
if self.model:
model_attributes = vars(self.model)
self.__dict__.update(model_attributes)
else:
raise ValueError(
"Before simulating a model, please ensure that you have instantiated the biostoch.model.Model() object.")
self.species = {}
self.parameters = {}
self.time = {}
"""
Args:
model: a class created by "biostoch.model.Model",
contains all necessary information used in simulation with SSA.
start: an integer or a float that defines the start time of the simulation.
stop: an integer or a float that defines the stop time of the simulation.
epochs: an integer defines the number of iterations.
seed: an integer parameter used to initialize the random number generator.
model_name: the name of the simulation method "Stochastic Simulation Algorithm".
**kwargs: a special parameter that allows passing additional keyword arguments to the function.
species: an empty dictionary in which the calculated concentrations of the species are stored.
parameters: an empty dictionary in which the rate constants of the model are stored.
time: an empty dictionary in which the simulation duration is stored.
"""
def reset(self):
""" Resets the model species and parameters dictionaries"""
self.species = {}
self.parameters = {}
self.time = {}
def initialize_parameters(self, model, start, stop, epochs):
"""
Initializes the model species dictionary
Args:
model: a class created by "biostoch.model.Model"
contains all necessary information used in simulation with SSA.
start: an integer or a float that defines the start time of the simulation.
stop: an integer or a float that defines the stop time of the simulation.
epochs: an integer defines the number of iterations.
Returns:
species: a dictionary contains initialized concentration of each
species and also initialized simulation time in the system.
each dictionary's key is the name of one species
and each value the corresponding initialized concentration.
parameters: a dictionary contains the rate constant of each reaction each key
correspond to the name of the rate constant and each value is its value.
"""
species = {}
parameters = {}
species["Time"] = np.linspace(start, stop, epochs)
for specie in model.components:
species[specie] = np.zeros(epochs)
species[specie][0] = getattr(model, specie)
for parameter in model.params:
parameters[parameter] = getattr(model, parameter)
return species, parameters
def compute_rates(self, species, model, step):
"""
Args:
species: a dictionary in which the calculated concentrations of the species are stored.
model: a class created by "biostoch.model.Model".
step: integer that represents the current iteration number or time step in the simulation process.
Returns:
rates: a dictionary containing the calculated rates of each reaction at the current time step.
"""
rates = {}
for specie in species.keys():
if specie != "Time":
rate = ""
split_rate = model.ROC_[specie].split()
for component in split_rate:
if component in self.model.params.keys():
rate += " " + str(self.model.params[component])
elif component in model.signs:
rate += " " + component
elif component in self.model.components:
rate += " " + str(species[component][step - 1])
else:
ValueError(f"This component: {component} is not a valid component!")
rates[specie] = rate
return rates
def simulate(self):
"""Runs the simulation"""
start_simulation = time.time()
species, parameters = self.initialize_parameters(
model=self.model,
start=self.start,
stop=self.stop,
epochs=self.epochs
)
tau = species["Time"][3] - species["Time"][2]
for i in range(1, self.epochs):
rates = self.compute_rates(
species=species,
model=self.model,
step=i
)
for specie, concentration in species.items():
if specie != "Time":
if specie in rates.keys():
species[specie][i] = species[specie][i - 1] + (eval(rates[specie]) * tau)
else:
raise ValueError(f"The rate equation for '{specie}' is not defined!")
self.species = species
self.parameters = parameters
stop_simulation = time.time()
self.time["Simulation Duration"] = stop_simulation - start_simulation
class RungeKuttaSimulator(object):
""" Simulation using Runge Kutta method """
def __init__(
self,
model=None,
start=0,
stop=10,
epochs=1000,
seed=42,
model_name="Runge-Kutta Algorithm",
**kwargs
):
self.model = model
self.start = start
self.stop = stop
self.epochs = epochs
self.seed = seed
self.model_name = model_name
if self.model:
model_attributes = vars(self.model)
self.__dict__.update(model_attributes)
else:
raise ValueError(
"Before simulating a model, please ensure that you have instantiated the biostoch.model.Model() object.")
self.species = {}
self.parameters = {}
self.time = {}
"""
Args:
model: a class created by "biostoch.model.Model",
contains all necessary information used in simulation with SSA.
start: an integer or a float that defines the start time of the simulation.
stop: an integer or a float that defines the stop time of the simulation.
epochs: an integer defines the number of iterations.
seed: an integer parameter used to initialize the random number generator.
model_name: the name of the simulation method "Stochastic Simulation Algorithm".
**kwargs: a special parameter that allows passing additional keyword arguments to the function.
species: an empty dictionary in which the calculated concentrations of the species are stored.
parameters: an empty dictionary in which the rate constants of the model are stored.
time: an empty dictionary in which the simulation duration is stored.
"""
def reset(self):
""" Resets the model species and parameters dictionaries"""
self.species = {}
self.parameters = {}
self.time = {}
def initialize_parameters(self, model, start, stop, epochs):
"""
Initializes the model species dictionary
Args:
model: a class created by "biostoch.model.Model"
contains all necessary information used in simulation with SSA.
start: an integer or a float that defines the start time of the simulation.
stop: an integer or a float that defines the stop time of the simulation.
epochs: an integer defines the number of iterations.
Returns:
species: a dictionary contains initialized concentration of each
species and also initialized simulation time in the system.
each dictionary's key is the name of one species
and each value the corresponding initialized concentration.
parameters: a dictionary contains the rate constant of each reaction each key
correspond to the name of the rate constant and each value is its value.
"""
species = {}
parameters = {}
species["Time"] = np.linspace(start, stop, epochs)
for specie in model.components:
species[specie] = np.zeros(epochs)
species[specie][0] = getattr(model, specie)
for parameter in model.params:
parameters[parameter] = getattr(model, parameter)
return species, parameters
def compute_rates(self, species, model, step):
"""
Args:
species: a dictionary in which the calculated concentrations of the species are stored.
model: a class created by "biostoch.model.Model".
step: integer that represents the current iteration number or time step in the simulation process.
Returns:
rates: a dictionary containing the calculated rates of each reaction at the current time step.
"""
rates = {}
for specie in species.keys():
if specie != "Time":
rate = ""
split_rate = model.ROC_[specie].split()
for component in split_rate:
if component in self.model.params.keys():
rate += " " + str(self.model.params[component])
elif component in model.signs:
rate += " " + component
elif component in self.model.components:
rate += " " + str(species[component][step - 1])
else:
ValueError(f"This component: {component} is not a valid component!")
rates[specie] = rate
return rates
def simulate(self):
"""Runs the simulation"""
start_simulation = time.time()
species, parameters = self.initialize_parameters(
model=self.model,
start=self.start,
stop=self.stop,
epochs=self.epochs
)
tau = species["Time"][3] - species["Time"][2]
for i in range(1, self.epochs):
rates = self.compute_rates(
species=species,
model=self.model,
step=i
)
k1 = {}
k2 = {}
k3 = {}
k4 = {}
for specie, concentration in species.items():
if specie != "Time":
k1[specie] = eval(rates[specie]) * tau
k2[specie] = eval(rates[specie]) * tau
k3[specie] = eval(rates[specie]) * tau
k4[specie] = eval(rates[specie]) * tau
for specie, concentration in species.items():
if specie != "Time":
species[specie][i] = species[specie][i - 1] + (1 / 6) * (
k1[specie] + 2 * k2[specie] + 2 * k3[specie] + k4[specie])
self.species = species
self.parameters = parameters
stop_simulation = time.time()
self.time["Simulation Duration"] = stop_simulation - start_simulation
class TauLeaping(object):
""" Simulation using Tau-Leaping method """
def __init__(
self,
model=None,
start=0.0,
stop=10.0,
max_epochs=100,
seed=42,
steady_state=False,
epsilon=0.03,
call_tau=False,
model_name="Tau-Leaping Algorithm",
**kwargs
):
self.model = model
self.start = start
self.stop = stop
self.max_epochs = max_epochs
self.seed = seed
self.steady_state = steady_state
self.epsilon = epsilon
self.tau = (self.stop - self.start) / self.max_epochs
self.call_tau = call_tau
self.model_name = model_name
if self.model:
model_attributes = vars(self.model)
self.__dict__.update(model_attributes)
else:
raise ValueError(
"Before simulating a model, please ensure that you have instantiated the biostoch.model.Model() object.")
self.species = {}
self.parameters = {}
self.time = {}
"""
Args:
model: a class created by "biostoch.model.Model",
contains all necessary information used in simulation with SSA.
start: an integer or a float that defines the start time of the simulation.
stop: an integer or a float that defines the stop time of the simulation.
max_epochs: an integer defines the maximum number of iterations.
seed: an integer parameter used to initialize the random number generator.
steady_state: Boolean value (True or False); if true,
the simulation is stopped as soon as the model has reached the steady state.
epsilon: a float value that is less than one and is used as a fixed tolerance for the calculation of tau.
tau: a float or an integer that represents the time step size.
cal_tau: Boolean value (True or False); if true, tau is calculated in each step.
model_name: the name of the simulation method "Tau-Leaping Algorithm".
**kwargs: a special parameter that allows passing additional keyword arguments to the function.
species: an empty dictionary in which the calculated concentrations of the species are stored.
parameters: an empty dictionary in which the rate constants of the model are stored.
time: an empty dictionary in which the simulation duration is stored.
"""
def reset(self):
""" Resets the model species and parameters dictionaries"""
self.species = {}
self.parameters = {}
self.time = {}
def initialize_parameters(self, model, start):
"""
Initializes the model species dictionary
Args:
model: a class created by "biostoch.model.Model"
contains all necessary information used in simulation with Tau Leaping Algorithm.
start: an integer or a float that defines the start time of the simulation.
Returns:
species: a dictionary contains initialized concentration of each
species and also initialized simulation time in the system.
each dictionary's key is the name of one species
and each value the corresponding initialized concentration.
parameters: a dictionary contains the rate constant of each reaction each key
correspond to the name of the rate constant and each value is its value.
"""
species = {}
parameters = {}
species["Time"] = [start]
for specie in model.components:
species[specie] = [getattr(model, specie)]
for parameter in self.model.params:
parameters[parameter] = getattr(model, parameter)
return species, parameters
def compute_propensity_sum(self, propensities, species, parameters):
"""
Computes sum of the propensities
Args:
propensities: a dictionary contains propensity functions of the reactions.
species: a dictionary in which the calculated concentrations of the species are stored.
parameters: a dictionary in which the rate constants of the model are stored.
Returns:
propensity_sum: a float value, sum of the propensities.
propensities_: a dictionary contains the propensity values of the reactions.
"""
propensity_sum = 0.0
propensities_ = {}
last_step = {}
for specie, concentration in species.items():
if specie != "Time":
last_step[specie] = concentration[-1]
for parameter, value in parameters.items():
last_step[parameter] = value
for reaction, propensity in propensities.items():
propensity_ = eval(propensity, last_step)
propensity_sum += propensity_
propensities_[reaction] = propensity_
return propensity_sum, propensities_
def compute_tau(self, species, model, epsilon):
"""
Args:
species: a dictionary in which the calculated concentrations of the species are stored.
model: a class created by "biostoch.model.Model"
epsilon: a float value that is less than one and is used as a fixed tolerance for the calculation of tau.
Returns:
tau: a float or an integer, calculated tau.
"""
X = np.array([species[con][-1] for con in species.keys() if con != "Time"])
v = []
for key, val in model.coeffs_.items():
d = []
for sp in model.react_sps[key]:
d.append(val[sp])
v.append(d)
v = np.array(v)
R = []
comp = model.params
X1 = {key: val[-1] for key, val in species.items() if key != "Time"}
comp.update(X1)
s = 0
for react, rate in model.rates_.items():
if react == model.react_names[s]:
R.append(eval(rate, comp))
s += 1
R = np.array(R)
mu_values = []
sigma_squared_values = []
for i in range(len(X)):
mu_i = np.sum(v[i] * R)
sigma_squared_i = np.sum((v[i] ** 2) * R)
mu_values.append(mu_i)
sigma_squared_values.append(sigma_squared_i)
g_values = [np.argmax(v[i]) + 1 for i in range(len(X))]
tau_values = []
for i in range(len(X)):
tau_i = min(max(epsilon * X[i] / g_values[i], 1) / abs(mu_values[i]),
max(epsilon * X[i] / g_values[i], 1) ** 2 / sigma_squared_values[i])
tau_values.append(tau_i)
return min(tau_values)
def compute_lambdas(self, species, parameters, propensities, tau):
"""
Args:
species: a dictionary in which the calculated concentrations of the species are stored.
parameters: a dictionary in which the rate constants of the model are stored.
propensities: a dictionary contains the propensity values of the reactions.
tau: a float or an integer that represents the time step size.
Returns:
lambda: calculated poisson distribution parameter (lambda),
(the mean number of events within a given interval of time or space)
"""
last_step = {}
for specie, concentration in species.items():
if specie != "Time":
last_step[specie] = concentration[-1]
for parameter, value in parameters.items():
last_step[parameter] = value
lambdas = {}
for reaction, propensity in propensities.items():
lambda_value = eval(propensity, last_step) * tau
if lambda_value < 0.0:
lambdas[reaction] = 0
else:
lambdas[reaction] = lambda_value
return lambdas
def num_reaction(self, lambdas):
"""
Args: poisson distribution parameter (lambda)
lambdas:
Returns:
num_reaction_: a dictionary contains number of times ach reaction occurred in the time interval (tau).
"""
num_reaction_ = {}
for reaction, lambda_ in lambdas.items():
num_reaction_[reaction] = np.random.poisson(lambda_)
return num_reaction_
def update(self, species, model, num_reaction, tau):
"""
Args:
species: a dictionary in which the calculated concentrations of the species are stored.
model: a class created by "biostoch.model.Model".
num_reaction: an integer value that indicates the number of reaction in the system.
tau: a float or an integer, calculated tau.
Returns:
species: a dictionary in which the calculated concentrations of the species are stored.
"""
species["Time"].append(species["Time"][-1] + tau)
for reaction, formula in model.reacts_.items():
split_formula = formula.split()
index = [index for index, value in enumerate(split_formula) if value == '->']
if len(index) != 1:
print(f"Error: Each reaction should have exactly one '->', but there are {len(index)} in {reaction}.")
component_reaction = {}
for component in model.components:
num_reaction_ = sum(
[num_reaction[reaction_] * model.coeffs_[reaction_][component] for reaction_ in model.react_names if
component in model.react_sps[reaction_]])
component_reaction[component] = num_reaction_
for component, value in component_reaction.items():
species[component].append(species[component][-1] + value)
return species
def simulate(self):
"""Runs the simulation"""
start_simulation = time.time()
species, parameters = self.initialize_parameters(
model=self.model,
start=self.start
)
step = 2
while species["Time"][-1] <= self.stop:
propensity_sum, propensities_ = self.compute_propensity_sum(
species=species,
parameters=parameters,
propensities=self.model.rates_
)
if propensity_sum == 0 and self.steady_state:
print(f"Simulation reached steady state (iteration: {step}). No further changes are occurring.")
break
if self.call_tau:
tau = self.compute_tau(
species=species,
model=self.model,
epsilon=self.epsilon
)
else:
tau = self.tau
lambdas = self.compute_lambdas(
species=species,
parameters=self.model.params,
propensities=self.model.rates_,
tau=tau
)
num_reaction = self.num_reaction(
lambdas=lambdas
)
species = self.update(
species=species,
model=self.model,
num_reaction=num_reaction,
tau=tau
)
step += 1
if step == self.max_epochs:
print(f"Simulation reached the maximum iteration (max_epochs={self.max_epochs})!")
break
self.species = species
self.parameters = parameters
stop_simulation = time.time()
self.time["Simulation Duration"] = stop_simulation - start_simulation
class ChemicalLangevin(object):
""" Simulation using Chemical Langevin Equation """
def __init__(
self,
model=None,
start=0.0,
stop=10.0,
max_epochs=100,
seed=42,
steady_state=False,
model_name="Chemical Langevin Equation",
**kwargs
):
self.model = model
self.start = start
self.stop = stop
self.max_epochs = max_epochs
self.seed = seed
self.steady_state = steady_state
self.model_name = model_name
self.tau = (self.stop - self.start) / self.max_epochs
if self.model:
model_attributes = vars(self.model)
self.__dict__.update(model_attributes)
else:
raise ValueError(
"Before simulating a model, please ensure that you have instantiated the biostoch.model.Model() object.")
self.species = {}
self.parameters = {}
self.time = {}
"""
Args:
model: a class created by "biostoch.model.Model",
contains all necessary information used in simulation with SSA.
start: an integer or a float that defines the start time of the simulation.
stop: an integer or a float that defines the stop time of the simulation.
max_epochs: an integer defines the maximum number of iterations.
seed: an integer parameter used to initialize the random number generator.
steady_state: Boolean value (True or False); if true,
the simulation is stopped as soon as the model has reached the steady state.
model_name: the name of the simulation method "Tau-Leaping Algorithm".
**kwargs: a special parameter that allows passing additional keyword arguments to the function.
tau: a float or an integer that represents the time step size.
species: an empty dictionary in which the calculated concentrations of the species are stored.
parameters: an empty dictionary in which the rate constants of the model are stored.
time: an empty dictionary in which the simulation duration is stored.
"""
def reset(self):
""" Resets the model species and parameters dictionaries"""
self.species = {}
self.parameters = {}
self.time = {}
def initialize_parameters(self, model, start):
"""
Initializes the model species dictionary
Args:
model: a class created by "biostoch.model.Model"
contains all necessary information used in simulation with SSA.
start: an integer or a float that defines the start time of the simulation.
Returns:
species: a dictionary contains initialized concentration of each
species and also initialized simulation time in the system.
each dictionary's key is the name of one species
and each value the corresponding initialized concentration.
parameters: a dictionary contains the rate constant of each reaction each key
correspond to the name of the rate constant and each value is its value.
"""
species = {}
parameters = {}
species["Time"] = [start]
for specie in model.components:
species[specie] = [getattr(model, specie)]
for parameter in self.model.params:
parameters[parameter] = getattr(model, parameter)
return species, parameters
def compute_change(self, model, species, tau):