forked from LoLab-MSM/pysb
-
Notifications
You must be signed in to change notification settings - Fork 1
/
base.py
1358 lines (1176 loc) · 56 KB
/
base.py
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
from abc import ABCMeta, abstractmethod
import numpy as np
import itertools
import sympy
import collections
from collections.abc import Mapping, Sequence
import numbers
from pysb.core import MonomerPattern, ComplexPattern, as_complex_pattern, \
Parameter, Expression, Model, ComponentSet
from pysb.logging import get_logger, EXTENDED_DEBUG
import pickle
from pysb.export.json import JsonExporter
from pysb.importers.json import model_from_json
from pysb import __version__ as PYSB_VERSION
from datetime import datetime
import dateutil.parser
import copy
from warnings import warn
from pysb.pattern import SpeciesPatternMatcher
from contextlib import contextmanager
import weakref
try:
import pandas as pd
except ImportError:
pd = None
try:
import h5py
except ImportError:
h5py = None
class SimulatorException(Exception):
pass
class InconsistentParameterError(SimulatorException, ValueError):
def __init__(self, parameter_name, value, reason):
super(InconsistentParameterError, self).__init__(
f'Value {value} that was passed for parameter {parameter_name} '
f'was inconsistent with that parameters assumption: {reason}'
)
class Simulator(object):
"""An abstract base class for numerical simulation of models.
.. warning::
The interface for this class is considered experimental and may
change without warning as PySB is updated.
Parameters
----------
model : pysb.Model
Model to simulate.
tspan : vector-like, optional
Time values over which to simulate. The first and last values define
the time range. Returned trajectories are sampled at every value unless
the simulation is interrupted for some reason, e.g., due to
satisfaction
of a logical stopping criterion (see 'tout' below).
initials : vector-like or dict, optional
Values to use for the initial condition of all species. Ordering is
determined by the order of model.species. If not specified, initial
conditions will be taken from model.initials (with initial condition
parameter values taken from `param_values` if specified).
param_values : vector-like or dict, optional
Values to use for every parameter in the model. Ordering is
determined by the order of model.parameters.
If passed as a dictionary, keys must be parameter names.
If not specified, parameter values will be taken directly from
model.parameters.
verbose : bool or int, optional (default: False)
Sets the verbosity level of the logger. See the logging levels and
constants from Python's logging module for interpretation of integer
values. False is equal to the PySB default level (currently WARNING),
True is equal to DEBUG.
Attributes
----------
verbose: bool
Verbosity flag passed to the constructor.
model : pysb.Model
Model passed to the constructor.
tspan : vector-like
Time values passed to the constructor.
Notes
-----
If ``tspan`` is not defined, it may be defined in the call to the
``run`` method.
The dimensionality of ``tout`` depends on whether a single simulation
or multiple simulations are run.
The dimensionalities of ``y``, ``yobs``, ``yobs_view``, ``yexpr``, and
``yexpr_view`` depend on the number of simulations being run as well
as on the type of simulation, i.e., spatial vs. non-spatial.
"""
__metaclass__ = ABCMeta
_supports = { 'multi_initials' : False,
'multi_param_values' : False }
@abstractmethod
def __init__(self, model, tspan=None, initials=None,
param_values=None, verbose=False, **kwargs):
# Get or create base a PySB logger for this module and model
self._logger = get_logger(self.__module__, model=model,
log_level=verbose)
self._logger.debug('Simulator created')
self._model = model
self.verbose = verbose
self.tout = None
# Per-run initial conditions/parameter/tspan override
self._tspan = tspan
# Per-run tspan, initials and param_values
self._run_tspan = None
self._run_initials = None
self._run_params = None
# Base initials and param values
self._params = None
self.param_values = param_values
self._initials = None
self.initials = initials
# Store init kwargs and run kwargs if needed for saving results
self._init_kwargs = kwargs
self._run_kwargs = None
@property
def model(self):
return self._model
@property
def tspan(self):
return self._run_tspan if self._run_tspan is not None else self._tspan
@tspan.setter
def tspan(self, new_tspan):
self._tspan = new_tspan
@staticmethod
def _num_sims_calc(initials_or_params):
""" Calculate number of simulations implied by initials or param
values """
if initials_or_params is None:
return None
if isinstance(initials_or_params, np.ndarray):
return len(initials_or_params)
first_entry = next(iter(initials_or_params.values()))
try:
return len(first_entry) # First entry is iterable
except TypeError:
return 1 # First entry is non-iterable, e.g. int, float
@property
def initials_length(self):
try:
return len(self.initials)
except SimulatorException:
# Network free simulators
if self._initials:
return len(list(self._initials.values())[0])
elif self._run_initials:
return len(list(self._run_initials.values())[0])
else:
return len(self.param_values)
def _update_initials_dict(self, initials_dict, initials_source, subs=None):
if isinstance(initials_source, Mapping):
# Can't just use .update() as we need to test
# equality with .is_equivalent_to()
for cp, value_obj in initials_source.items():
cp = as_complex_pattern(cp)
if any(existing_cp.is_equivalent_to(cp)
for existing_cp in initials_dict):
continue
if isinstance(value_obj, (Sequence, np.ndarray))\
and all(isinstance(v, numbers.Number) for v in value_obj):
value = value_obj
elif isinstance(value_obj, Expression):
value = [value_obj.expand_expr().xreplace(subs[sim]) for sim in range(len(subs))]
elif isinstance(value_obj, Parameter):
# Set parameter using param_values
pi = self._model.parameters.index(value_obj)
value = [self.param_values[sim][pi] for sim in range(len(self.param_values))]
else:
raise TypeError("Unexpected initial condition "
"value type: %s" % type(value_obj))
initials_dict[cp] = value
elif initials_source is not None:
# Update from array-like structure, which we can only do if we
# have the species available (e.g. not in network-free simulations)
if not self.model.species:
raise ValueError(
'Cannot update initials from an array-like source without '
'model species.')
for cp_idx, cp in enumerate(self.model.species):
if any(existing_cp.is_equivalent_to(cp) for existing_cp in
initials_dict):
continue
initials_dict[cp] = [initials_source[n][cp_idx]
for n in range(len(initials_source))]
return initials_dict
@property
def initials_dict(self):
n_sims = self._check_run_initials_vs_base_initials_length()
if n_sims == 1:
n_sims = len(self.param_values)
# Apply any per-run initial overrides
initials_dict = self._update_initials_dict({}, self._run_initials)
# Apply any base initial overrides
initials_dict = self._update_initials_dict(initials_dict,
self._initials)
model_initials = {ic.pattern: ic.value
for ic in self.model.initials}
# Otherwise, populate initials from the model
n_sims_params = len(self.param_values)
n_sims_actual = max(n_sims_params, n_sims)
# Get remaining initials from the model itself and
# self.param_values, if necessary
subs = None
if any(isinstance(v, Expression) for v in model_initials.values()):
# Only need parameter substitutions if model initials include
# expressions
subs = [
dict((p, pv[i]) for i, p in
enumerate(self._model.parameters))
for pv in self.param_values]
if len(subs) == 1 and n_sims_actual > 1:
subs = list(itertools.repeat(subs[0], n_sims_actual))
initials_dict = self._update_initials_dict(
initials_dict, model_initials, subs=subs
)
return initials_dict
def _check_run_initials_vs_base_initials_length(self):
# Otherwise, build the list from the model, and any overrides
# specified in self._initials and self._run_initials
n_sims_initials = self._num_sims_calc(self._initials)
n_sims_run = self._num_sims_calc(self._run_initials)
if n_sims_initials is not None and n_sims_run is not None \
and n_sims_run != n_sims_initials:
raise ValueError(
"The base initials set with self.initials imply {} "
"simulations, but the run() initials imply {} simulations."
" Either set self.initials=None, or change the number of "
"simulations in the run() initials".format(
n_sims_initials, n_sims_run))
if n_sims_initials is not None:
return n_sims_initials
elif n_sims_run is not None:
return n_sims_run
else:
return 1
@property
def initials(self):
if not self.model.species:
raise SimulatorException('No model species list - either '
'generate the model equations or use '
'initials_dict() for network-free '
'simulations')
# Check potential quick return options
if self._run_initials is not None:
if not isinstance(self._run_initials, Mapping) and \
self._initials is None:
return self._run_initials
elif not isinstance(self._initials, Mapping) and \
self._initials is not None:
return self._initials
# At this point (after dimensionality check), we can return
# self._run_initials if it's not a dictionary and not None
if self._run_initials is not None and not isinstance(
self._run_initials, Mapping):
return self._run_initials
n_sims_initials = self._check_run_initials_vs_base_initials_length()
n_sims_params = len(self.param_values)
n_sims_actual = max(n_sims_params, n_sims_initials)
y0 = np.full((n_sims_actual, len(self.model.species)), 0.0)
for species, vals in self.initials_dict.items():
species_index = self._model.get_species_index(species)
y0[:, species_index] = vals
return y0
@initials.setter
def initials(self, new_initials):
self._initials = self._process_incoming_initials(new_initials)
def _process_incoming_initials(self, new_initials):
if new_initials is None:
return None
# If new_initials is a pandas dataframe, convert to a dict
if pd and isinstance(new_initials, pd.DataFrame):
new_initials = new_initials.to_dict(orient='list')
# If new_initials is a list, convert to numpy array
if isinstance(new_initials, list):
new_initials = np.array(new_initials, copy=False)
# Check if new_initials is a dict, and if so validate the keys
# (ComplexPatterns)
if isinstance(new_initials, dict):
n_sims = 1
if len(new_initials) > 0:
n_sims = self._num_sims_calc(new_initials)
for cplx_pat, val in new_initials.items():
if not isinstance(cplx_pat, (MonomerPattern,
ComplexPattern)):
raise ValueError('Dictionary key %s is not a '
'MonomerPattern or ComplexPattern' %
repr(cplx_pat))
# if val is a number, convert it to a single-element array
if not isinstance(val, (Sequence, np.ndarray)):
val = [val]
new_initials[cplx_pat] = np.array(val)
# otherwise, check whether simulator supports multiple
# initial values :
if len(val) != n_sims:
raise ValueError("all arrays in new_initials dictionary "
"must be equal length")
if not np.isfinite(val).all():
raise ValueError('Please check initial {} for non-finite '
'values'.format(cplx_pat))
elif isinstance(new_initials, np.ndarray):
# if new_initials is a 1D array, convert to a 2D array of length 1
if len(new_initials.shape) == 1:
new_initials = np.resize(new_initials, (1, len(new_initials)))
n_sims = new_initials.shape[0]
# make sure number of initials values equals len(model.species)
if new_initials.shape[1] != len(self._model.species):
raise ValueError("new_initials must be the same length as "
"model.species")
if not np.isfinite(new_initials).all():
raise ValueError('Please check initials array '
'for non-finite values')
else:
raise ValueError(
'Implicit conversion of data type "{}" is not '
'supported. Please supply initials as a numpy array, list, '
'or a pandas DataFrame.'.format(type(new_initials)))
if n_sims > 1:
if not self._supports['multi_initials']:
raise ValueError(
self.__class__.__name__ +
" does not support multiple initial values at this time.")
if 1 < len(self.param_values) != n_sims:
raise ValueError(
'Cannot set initials for {} simulations '
'when param_values has been set for {} '
'simulations'.format(
n_sims, len(self.param_values)))
return new_initials
@property
def param_values(self):
if not self.model._derived_parameters:
if self._params is not None and \
not isinstance(self._params, dict) and \
self._run_params is None:
return self._params
elif self._run_params is not None and \
not isinstance(self._run_params, dict) and \
self._params is None:
return self._run_params
# create parameter vector from the values in the model
param_values_dict = {}
n_sims = self._num_sims_calc(self._params)
if isinstance(self._params, dict):
param_values_dict.update(self._params)
elif isinstance(self._params, np.ndarray):
param_values_dict = dict(zip(
[p.name for p in self._model.parameters], self._params.T))
n_sims_run = self._num_sims_calc(self._run_params)
if n_sims is None:
n_sims = n_sims_run
elif n_sims_run is not None and n_sims_run != n_sims:
raise ValueError(
"The base parameters set with self.param_values imply "
"{} simulations, but the run() params imply {} "
"simulations. Either set self.param_values=None, or "
"change the number of simulations in the run() params"
.format(n_sims, n_sims_run))
# At this point (after dimensionality check) we can return the
# _run_params, if it's not a dict
if self._run_params is not None:
if not isinstance(self._run_params, dict):
if not self._model._derived_parameters:
return self._run_params
else:
param_values_dict.update(dict(zip(
self.model.parameters.keys(), self._run_params
)))
else:
param_values_dict.update(self._run_params)
if n_sims is None:
n_sims = 1
# Get the base parameters from the model
param_values = np.array(
[p.value for p in self._model.parameters] +
[p.value for p in self._model._derived_parameters]
)
param_values = np.repeat([param_values], n_sims, axis=0)
# Process overrides
for key in param_values_dict.keys():
try:
pi = self._model.parameters.index(
self._model.parameters[key])
except KeyError:
raise IndexError("new_params dictionary has unknown "
"parameter name (%s)" % key)
# loop over n_sims
for n in range(n_sims):
param_values[n][pi] = param_values_dict[key][n]
return param_values
@param_values.setter
def param_values(self, new_params):
self._params = self._process_incoming_params(new_params)
def _process_incoming_params(self, new_params):
if new_params is None:
return None
# Convert pandas dataframe to dictionary
if pd and isinstance(new_params, pd.DataFrame):
new_params = new_params.to_dict(orient='list')
# If new_params is a list, convert to numpy array
if isinstance(new_params, list):
new_params = np.array(new_params)
if isinstance(new_params, dict):
n_sims = 1
if len(new_params) > 0:
n_sims = self._num_sims_calc(new_params)
for key, val in new_params.items():
if key not in self._model.parameters.keys():
raise IndexError("new_params dictionary has unknown "
"parameter name (%s)" % key)
# if val is a number, convert it to a single-element array
if not isinstance(val, Sequence):
val = [val]
new_params[key] = np.array(val)
# Check all elements are the same length
if len(val) != n_sims:
raise ValueError("all arrays in params dictionary "
"must be equal length")
for value in val:
try:
self._model.parameters[key].check_value(value)
except ValueError as e:
raise InconsistentParameterError(
key, value, str(e)
)
elif isinstance(new_params, np.ndarray):
# if new_params is a 1D array, convert to a 2D array of length 1
if len(new_params.shape) == 1:
new_params = np.resize(new_params, (1, len(new_params)))
n_sims = new_params.shape[0]
# make sure number of param values equals len(model.parameters)
if new_params.shape[1] != len(self._model.parameters):
raise ValueError("new_params must be the same length as "
"model.parameters")
for isim in range(n_sims):
for param, value in zip(self._model.parameters,
new_params[isim, :]):
try:
param.check_value(value)
except ValueError as e:
raise InconsistentParameterError(
param.name, value, str(e)
)
else:
raise ValueError(
'Implicit conversion of data type "{}" is not '
'supported. Please supply parameters as a numpy array, list, '
'or a pandas DataFrame.'.format(type(new_params)))
# Check whether simulator supports multiple param_values
if n_sims > 1 and not self._supports['multi_param_values']:
raise ValueError(
self.__class__.__name__ +
" does not support multiple parameter values at this time.")
return new_params
def _reset_run_overrides(self):
"""
Reset any single-run tspan, initials, param_values
When calling run(), the user can specify tspan, initials and
param_values, which are only used for a single run. This method
resets those overrides after the run is complete (called from
:func:`SimulationResult.__init__`).
"""
self._run_tspan = None
self._run_initials = None
self._run_params = None
@abstractmethod
def run(self, tspan=None, initials=None, param_values=None,
_run_kwargs=None):
"""Run a simulation.
Notes for developers implementing Simulator subclasses:
Implementations should return a :class:`.SimulationResult` object.
Subclasses should pass any additional arguments run as a dictonary
to the `_run_kwargs` argument when calling the superclass's run
method. If the run method has variable keyword arguments, this can
be achieved by passing `_run_kwargs=locals()` to the superclass's
run method. The run kwargs are used for reference when saving and
loading SimulationResults to disk. They aren't compulsory, but not
including them will generate a warning. To suppress (e.g. if there
are no additional arguments), set `_run_kwargs=[]`.
"""
self._logger.info('Simulation(s) started')
if _run_kwargs:
# Don't store these arguments twice
_run_kwargs.pop('self')
_run_kwargs.pop('initials', None)
_run_kwargs.pop('param_values', None)
_run_kwargs.pop('tspan', None)
self._run_kwargs = _run_kwargs
elif _run_kwargs is None:
self._logger.warning(
'{} has not passed any additional run arguments to '
'_run_kwargs. Instructions are included in the Simulation '
'base class run method docstring.'.format(
self.__class__.__name__))
self._run_tspan = tspan
if self.tspan is None:
raise ValueError("tspan must be defined before "
"simulation can run")
self._run_params = self._process_incoming_params(param_values)
self._run_initials = self._process_incoming_initials(initials)
# If only one set of param_values, run all simulations
# with the same parameters
if len(self.param_values) == 1 and self.initials_length > 1:
new_params = np.repeat(self.param_values,
self.initials_length,
axis=0)
self._run_params = new_params
# Error checks on 'param_values' and 'initials'
if len(self.param_values) != self.initials_length:
raise ValueError(
"'param_values' and 'initials' must be equal lengths.\n"
"len(param_values): %d\n"
"len(initials): %d" %
(len(self.param_values), self.initials_length))
elif len(self.param_values.shape) != 2 or \
self.param_values.shape[1] != (
len(self._model.parameters) +
len(self._model._derived_parameters)):
raise ValueError(
"'param_values' must be a 2D array of dimension N_SIMS x "
"len(model.parameters).\n"
"param_values.shape: " + str(self.param_values.shape) +
"\nlen(model.parameters): %d" %
len(self._model.parameters))
if self.model.species and (len(self.initials.shape) != 2 or
self.initials.shape[1] != len(self._model.species)):
raise ValueError(
"'initials' must be a 2D array of dimension N_SIMS x "
"len(model.species).\n"
"initials.shape: " + str(self.initials.shape) +
"\nlen(model.species): %d" % len(self._model.species))
return None
class SimulationResult(object):
"""
Results of a simulation with properties and methods to access them.
.. warning::
Please note that the interface for this class is considered
experimental and may change without warning as PySB is updated.
Notes
-----
In the attribute descriptions, a "trajectory set" is a 2D numpy array,
species on first axis and time on second axis, with each element
containing the concentration or count of the species at the specified time.
A list of trajectory sets contains a trajectory set for each simulation.
Parameters
----------
simulator : Simulator
The simulator object that generated the trajectories
tout: list-like
Time points returned by the simulator (may be different from ``tspan``
if simulation is interrupted for some reason).
trajectories : list or numpy.ndarray
A set of species trajectories from a simulation. Should either be a
list of 2D numpy arrays or a single 3D numpy array.
squeeze : bool, optional (default: True)
Return trajectories as a 2D array, rather than a 3d array, if only
a single simulation was performed.
simulations_per_param_set : int
Number of trajectories per parameter set. Typically always 1 for
deterministic simulators (e.g. ODE), but with stochastic simulators
multiple trajectories per parameter/initial condition set are often
desired.
model: pysb.Model
initials: numpy.ndarray
param_values: numpy.ndarray
model, initials, param_values are an alternative constructor
mechanism used when loading SimulationResults from files (see
:func:`SimulationResult.load`). Setting just the simulator argument
instead of these arguments is recommended.
Examples
--------
The following examples use a simple model with three observables and one
expression, with a single simulation.
>>> from pysb.examples.expression_observables import model
>>> from pysb.simulator import ScipyOdeSimulator
>>> import numpy as np
>>> np.set_printoptions(precision=4)
>>> sim = ScipyOdeSimulator(model, tspan=np.linspace(0, 40, 10), \
integrator_options={'atol': 1e-20})
>>> simulation_result = sim.run()
``simulation_result`` is a :class:`SimulationResult` object. An
observable can be accessed like so:
>>> print(simulation_result.observables['Bax_c0']) \
#doctest: +NORMALIZE_WHITESPACE
[1.0000e+00 1.1744e-02 1.3791e-04 1.6196e-06 1.9020e-08
2.2337e-10 2.6232e-12 3.0806e-14 3.6178e-16 4.2492e-18]
It is also possible to retrieve the value of all observables at a
particular time point, e.g. the final concentrations:
>>> print(simulation_result.observables[-1]) \
#doctest: +SKIP
(4.2492e-18, 1.6996e-16, 1.)
Expressions are read in the same way as observables:
>>> print(simulation_result.expressions['NBD_signal']) \
#doctest: +NORMALIZE_WHITESPACE
[0. 4.7847 4.9956 4.9999 5. 5. 5. 5. 5. 5. ]
The species trajectories can be accessed as a numpy ndarray:
>>> print(simulation_result.species) #doctest: +NORMALIZE_WHITESPACE
[[1.0000e+00 0.0000e+00 0.0000e+00]
[1.1744e-02 5.2194e-02 9.3606e-01]
[1.3791e-04 1.2259e-03 9.9864e-01]
[1.6196e-06 2.1595e-05 9.9998e-01]
[1.9020e-08 3.3814e-07 1.0000e+00]
[2.2337e-10 4.9637e-09 1.0000e+00]
[2.6232e-12 6.9951e-11 1.0000e+00]
[3.0806e-14 9.5840e-13 1.0000e+00]
[3.6178e-16 1.2863e-14 1.0000e+00]
[4.2492e-18 1.6996e-16 1.0000e+00]]
Species, observables and expressions can be combined into a single numpy
ndarray and accessed similarly. Here, the initial concentrations of all
these entities are examined:
>>> print(simulation_result.all[0]) #doctest: +SKIP
( 1., 0., 0., 1., 0., 0., 0.)
The ``all`` array can be accessed as a pandas DataFrame object,
which allows for more convenient indexing and access to pandas advanced
functionality, such as indexing and slicing. Here, the concentrations of
the observable ``Bax_c0`` and the expression ``NBD_signal`` are read at
time points between 5 and 15 seconds:
>>> df = simulation_result.dataframe
>>> print(df.loc[5:15, ['Bax_c0', 'NBD_signal']]) \
#doctest: +NORMALIZE_WHITESPACE
Bax_c0 NBD_signal
time
8.888889 0.000138 4.995633
13.333333 0.000002 4.999927
"""
CUSTOM_ATTR_PREFIX = 'usrattr_'
def __init__(self, simulator, tout, trajectories=None,
observables_and_expressions=None, squeeze=True,
simulations_per_param_set=1,
model=None, initials=None, param_values=None):
if simulator:
simulator._logger.debug('SimulationResult constructor started')
self._param_values = simulator.param_values.copy()
try:
self._initials = simulator.initials.copy()
except SimulatorException:
# Network free simulations don't have initials list, only dict
self._initials = simulator.initials_dict.copy()
self._model = copy.deepcopy(simulator._model)
self.simulator_class = simulator.__class__
self.init_kwargs = copy.deepcopy(simulator._init_kwargs)
self.run_kwargs = copy.deepcopy(simulator._run_kwargs)
else:
self._param_values = param_values
self._initials = initials
self._model = model
self.simulator_class = None
self.init_kwargs = {}
self.run_kwargs = {}
self.squeeze = squeeze
self.tout = tout
self._yfull = None
self.n_sims_per_parameter_set = simulations_per_param_set
self.pysb_version = PYSB_VERSION
self.timestamp = datetime.now()
self.custom_attrs = {}
if trajectories is None and observables_and_expressions is None:
raise ValueError('Need to supply at least one of species '
'trajectories or observables_and_expressions')
if trajectories is not None and len(trajectories) > 0:
# Validate incoming trajectories
if getattr(trajectories, 'ndim', None) == 3:
# trajectories is a 3D array, create a list of 2D arrays
# This is just a view and doesn't copy the data
self._y = [tr for tr in trajectories]
else:
# Not a 3D array, check for a list of 2D arrays
try:
if any(tr.ndim != 2 for tr in trajectories):
raise AttributeError
except (AttributeError, TypeError):
raise ValueError("trajectories should be a 3D array or a "
"list of 2D arrays")
self._y = trajectories
self._nsims = len(self._y)
if len(self.tout) != self.nsims:
raise ValueError("Simulator tout should be the same length as "
"trajectories")
for i in range(self.nsims):
if len(self.tout[i]) != self._y[i].shape[0]:
raise ValueError("The number of time points in tout[{0}] "
"should match the trajectories array for "
"simulation {0}".format(i))
if self._y[i].shape[1] != len(self._model.species):
raise ValueError("The number of species in trajectory {0} "
"should match length of "
"model.species".format(i))
else:
self._y = None
# Calculate ``yobs`` and ``yexpr`` based on values of ``y``
exprs = self._model.expressions_dynamic(include_local=False)
expr_names = [expr.name for expr in exprs]
model_obs = self._model.observables
obs_names = list(model_obs.keys())
param_names = list(p.name for p in self._model.parameters)
if not _allow_unicode_recarray():
for name_list, name_type in zip(
(expr_names, obs_names, param_names),
('Expression', 'Observable', 'Parameter')):
for i, name in enumerate(name_list):
try:
name_list[i] = name.encode('ascii')
except UnicodeEncodeError:
error_msg = 'Non-ASCII compatible ' + \
'%s names not allowed' % name_type
raise ValueError(error_msg)
yobs_dtype = (list(zip(obs_names, itertools.repeat(float)))
if obs_names else float)
yexpr_dtype = (list(zip(expr_names, itertools.repeat(float)))
if expr_names else float)
if observables_and_expressions:
# Observables and expression values are used as supplied
self._nsims = len(observables_and_expressions)
self._yobs_view = [observables_and_expressions[n][:, 0:(len(
self._model.observables))] for n in range(self.nsims)]
self._yexpr_view = [observables_and_expressions[n][:, (len(
self._model.observables)):] for n in range(self.nsims)]
self._yobs = [self._yobs_view[n].reshape(
len(tout[n]) * len(obs_names)).view(dtype=yobs_dtype) for n
in range(self.nsims)]
self._yexpr = [self._yexpr_view[n].reshape(
len(tout[n]) * len(expr_names)).view(dtype=yexpr_dtype) for n
in range(self.nsims)]
else:
self._yobs = [np.ndarray((len(self.tout[n]),), dtype=yobs_dtype) if obs_names
else np.ndarray((len(self.tout[n]), 0), dtype=yobs_dtype)
for n in range(self.nsims)]
self._yobs_view = [self._yobs[n].view(float).
reshape(len(self._yobs[n]), -1) for n in range(
self.nsims)]
self._yexpr = [np.ndarray((len(self.tout[n]),), dtype=yexpr_dtype) if expr_names
else np.ndarray((len(self.tout[n]), 0), dtype=yexpr_dtype)
for n in range(self.nsims)]
self._yexpr_view = [self._yexpr[n].view(float).reshape(len(
self._yexpr[n]), -1) for n in range(self.nsims)]
# loop over simulations
sym_names = obs_names + param_names
expanded_exprs = [sympy.lambdify(sym_names, expr.expand_expr(),
"numpy") for expr in exprs]
for n in range(self.nsims):
if simulator:
simulator._logger.log(EXTENDED_DEBUG,
'Evaluating exprs/obs %d/%d'
% (n + 1, self.nsims))
# observables
for i, obs in enumerate(model_obs):
self._yobs_view[n][:, i] = (
self._y[n][:, obs.species] * obs.coefficients).sum(axis=1)
# expressions
sym_dict = dict((k, self._yobs[n][k]) for k in obs_names)
sym_dict.update(dict((p.name, self.param_values[
n // self.n_sims_per_parameter_set][i]) for i, p in
enumerate(self._model.parameters)))
for i, expr in enumerate(exprs):
self._yexpr_view[n][:, i] = expanded_exprs[i](**sym_dict)
if simulator:
simulator._reset_run_overrides()
simulator._logger.debug('SimulationResult constructor finished')
def _squeeze_output(self, trajectories):
"""
Reduces trajectories to a 2D matrix if only one simulation present
Can be disabled by setting self.squeeze to False
"""
if self.nsims == 1 and self.squeeze:
return trajectories[0]
else:
return trajectories
@property
def nsims(self):
""" The number of simulations in this SimulationResult """
return self._nsims
@property
def all(self):
"""
Aggregate species, observables, and expressions trajectories into
a numpy.ndarray with record-style data-type for return to the user.
"""
if self._yfull is None:
if self._y is None:
yfull_dtype = []
else:
sp_names = ['__s%d' % i
for i in range(len(self._model.species))]
yfull_dtype = list(zip(sp_names, itertools.repeat(float)))
if len(self._model.observables):
yfull_dtype += self._yobs[0].dtype.descr
if len(self._model.expressions_dynamic()):
yfull_dtype += self._yexpr[0].dtype.descr
yfull = []
# loop over simulations
for n in range(self.nsims):
yfull.append(np.ndarray(len(self.tout[n]), yfull_dtype))
yfull_view = yfull[n].view(float).reshape((len(yfull[n]), -1))
n_sp = self._y[n].shape[1] if self._y else 0
n_ob = self._yobs_view[n].shape[1]
n_ex = self._yexpr_view[n].shape[1]
if self._y:
yfull_view[:, :n_sp] = self._y[n]
yfull_view[:, n_sp:n_sp + n_ob] = self._yobs_view[n]
yfull_view[:, n_sp + n_ob:n_sp + n_ob + n_ex] = \
self._yexpr_view[n]
self._yfull = yfull
return self._squeeze_output(self._yfull)
@property
def dataframe(self):
"""
A conversion of the trajectory sets (species, observables and
expressions for all simulations) into a single
:py:class:`pandas.DataFrame`.
"""
if pd is None:
raise Exception('Please "pip install pandas" for this feature')
sim_ids = (np.repeat(range(self.nsims), [len(t) for t in self.tout]))
times = np.concatenate(self.tout)
if self.nsims == 1 and self.squeeze:
idx = pd.Index(times, name='time')
else:
idx = pd.MultiIndex.from_tuples(list(zip(sim_ids, times)),
names=['simulation', 'time'])
simdata = self.all
if not isinstance(simdata, np.ndarray):
simdata = np.concatenate(simdata)
return pd.DataFrame(simdata, index=idx)
@property
def species(self):
"""
List of trajectory sets. The first dimension contains species.
"""
if self._y is None:
raise ValueError('No trajectories are available for network-free '
'simulations')
return self._squeeze_output(self._y)
@property
def observables(self):
"""
List of trajectory sets. The first dimension contains observables.
"""
if not self._model.observables:
raise ValueError('Model has no observables')
return self._squeeze_output(self._yobs)
def observable(self, pattern):
"""
Calculate a pattern's trajectories without adding to model
This method calculates an observable "on demand" using
any supplied MonomerPattern or ComplexPattern against the simulation
result, without re-running the simulation.
Note that the monomers within the supplied pattern are reconciled
with the SimulationResult's internal copy of the model by name. This
method only works on simulations which calculate species
trajectories (i.e. it will not work on network-free simulations).
Raises a ValueError if the pattern does not match at least one species.
Parameters
----------
pattern: pysb.MonomerPattern or pysb.ComplexPattern
An observable pattern to match
Returns
-------
pandas.Series
Series containing the simulation trajectories for the specified
observable
Examples
--------
>>> from pysb import ANY
>>> from pysb.examples import earm_1_0
>>> from pysb.simulator import ScipyOdeSimulator
>>> simres = ScipyOdeSimulator(earm_1_0.model, tspan=range(5)).run()
>>> m = earm_1_0.model.monomers
Observable of bound Bid:
>>> simres.observable(m.Bid(b=ANY))
time