-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimecourse.py
More file actions
319 lines (287 loc) · 12 KB
/
Copy pathtimecourse.py
File metadata and controls
319 lines (287 loc) · 12 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
'''Represents a time course and related properties.'''
import src.constants as cn # type: ignore
from src.model import Model # type: ignore
from src.simulator import Simulator, SimulationResult # type: ignore
from src.biomodels_iterator import getBiomodelsEndtimes # type: ignore
from src.plot_options import PlotOptions # type: ignore
import matplotlib.pyplot as plt # type: ignore
import numpy as np # type: ignore
import pickle
import os
import pandas as pd # type: ignore
from typing import List, Optional, cast
class Timecourse(object):
def __init__(self, model: Model,
start_time: float = cn.START_TIME,
end_time: Optional[float] = None,
num_point: int = cn.NUM_POINT,
timecourse_df: pd.DataFrame = pd.DataFrame(),
perturbation_value_fraction: float = cn.PERTURBATION_VALUE_FRACTION,
perturbation_species_fraction: float = cn.PERTURBATION_SPECIES_FRACTION,
modifable_species_names: Optional[List[str]] = None,
) -> None:
"""
Parameters
----------
model : Model
The model to simulate.
start_time : float
Time to start the simulation.
end_time : float
Time to end the simulation.
num_points : int
Number of time points to simulate.
timecourse_df : pd.DataFrame
Optional pre-computed timecourse DataFrame (index: time, columns: species).
perturbation_value_fraction : float
Amount of perturbation of initial values as a fraction of the original value.
May be positive or negative.
perturbation_species_fraction : float
Fraction of non-zero initial values that are perturbed
modifable_species_names : Optional[List[str]]
Optional list of species names that are modifiable. If not provided, it will be determined
"""
self.model = model
self.start_time = start_time
self.end_time = self._updateEndtime(end_time)
self.num_point = num_point
self.perturbation_value_fraction = perturbation_value_fraction
self.perturbation_species_fraction = perturbation_species_fraction
self.modifable_species_names = modifable_species_names
#
self._timecourse_df = timecourse_df
def makePerturbationTimecourse(self,
perturbation_value_fraction: float,
perturbation_species_fraction: float) -> "Timecourse":
"""Create a new Timecourse with perturbed initial values.
"""
return type(self)(
model=self.model,
start_time=self.start_time,
end_time=self.end_time,
num_point=self.num_point,
perturbation_value_fraction=perturbation_value_fraction,
perturbation_species_fraction=perturbation_species_fraction
)
def __eq__(self, other: object) -> bool:
if not isinstance(other, Timecourse):
return NotImplemented
return (self.model == other.model and
bool(np.isclose(self.start_time, other.start_time)) and
(self.end_time == other.end_time
if self.end_time is None or other.end_time is None
else bool(np.isclose(self.end_time, other.end_time))) and
self.num_point == other.num_point and
bool(np.allclose(self.timecourse_df.values,
other.timecourse_df.values, equal_nan=True))
)
def _updateEndtime(self, end_time: Optional[float]=None):
"""Determine the end time and its source."""
if end_time is not None:
return end_time
if self.model.model_name.startswith("BIOMD"):
endtime_dct = getBiomodelsEndtimes()
csv_end_time = endtime_dct.get(self.model.model_name, None)
if csv_end_time is not None:
return csv_end_time
return end_time
@property
def timecourse_df(self) -> pd.DataFrame:
"""_summary_
Returns:
pd.DataFrame: _description_
"""
if self._timecourse_df.empty:
simulation_result = self._simulate()
self._timecourse_df = simulation_result.timecourse_df
return self._timecourse_df
@property
def num_timepoint(self) -> int:
"""Number of time points in the timecourse."""
return self.timecourse_df.shape[0]
def _simulate(self) -> SimulationResult:
"""Delegate simulation to a Simulator instance.
end_time resolution order:
1. Caller-supplied value (source: user_specified).
2. BioModels CSV lookup (source: sedml).
3. Auto-detection via _updateEndtime (source: set by that method).
Returns
-------
SimulationResult
"""
simulator = Simulator(
model=self.model,
start_time=self.start_time,
end_time=cast(float, self.end_time),
num_point=self.num_point,
perturbation_value_fraction=self.perturbation_value_fraction,
perturbation_species_fraction=self.perturbation_species_fraction,
)
return simulator.simulate()
def serialize(self) -> str:
"""
Serialize the Timecourse to a file
Returns:
str: The path to the serialized file.
"""
if not self.model.model_name:
raise ValueError("Model must have a name to serialize Timecourse.")
path = self.makeBiomodelSerializePath(self.model.model_name)
dct = {
"model": self.model,
"start_time": self.start_time,
"end_time": self.end_time,
"num_point": self.num_point,
"timecourse_df": self.timecourse_df,
}
with open(path, 'wb') as f:
pickle.dump(dct, f)
return path
@staticmethod
def makeBiomodelSerializePath(model_name: str) -> str:
"""
Get the expected path for a serialized Timecourse of a BioModel.
Parameters:
model_name (str): The name of the BioModel.
"""
return os.path.join(cn.TIMECOURSE_SERIALIZATION_DIR, f"{model_name}_timecourse.pkl")
@classmethod
def deserialize(cls, path: str = "", model_name: str = "") -> 'Timecourse':
"""
Deserialize a Timecourse from a file
At least one of `path` or `model_name` must be provided.
If both are provided, `path` takes precedence.
Parameters:
path (str): The path to the serialized file.
model_name (str): The name of the BioModel (used if path is not specified).
Returns:
Timecourse: The deserialized Timecourse object.
"""
if not path and not model_name:
raise ValueError("At least one of `path` or `model_name` must be provided.")
if not path:
path = cls.makeBiomodelSerializePath(model_name)
# Check if the file exists
if not os.path.isfile(path):
raise FileNotFoundError(f"No serialized Timecourse found at {path}")
# Deserialize
with open(path, 'rb') as f:
dct = pickle.load(f)
# Make sure that columns don't have square brackets (e.g., "[species]") which can happen due to RoadRunner's output formatting
df = dct['timecourse_df']
new_column_names = [c[1:-1] if c[0] == "[" else c for c in df.columns]
df.columns = new_column_names
return cls(
model=dct['model'],
start_time=dct['start_time'],
end_time=dct['end_time'],
num_point=dct['num_point'],
timecourse_df=df,
)
def plot(self, species_names: Optional[List[str]] = None, **kwargs) -> PlotOptions:
"""Plot the simulated timecourse for all species.
Parameters
----------
species_names : Optional[List[str]]
List of species names to plot. If None, all species are plotted.
**kwargs
Passed to PlotOptions. Supported keys: ax, fig, title, xlabel,
ylabel, legend, xlim, ylim, model_name.
Returns
-------
PlotOptions
"""
plot_options = PlotOptions(**kwargs)
ax = plot_options.ax
if species_names is None:
species_names = list(self.timecourse_df.columns)
for i, name in enumerate(species_names):
ax.plot( # type: ignore
self.timecourse_df.index,
self.timecourse_df[name],
color=f"C{i}",
label=name,
)
plot_options.apply()
return plot_options
@classmethod
def makeBiomodelDF(cls, model_name: str, num_point: int = 1000,
end_time: Optional[float] = None) -> "Timecourse":
"""Create a dataframe for a BioModel.
Parameters
----------
model_name : str
BioModel identifier (e.g. 'BIOMD0000000001'). Must start with 'BIOMD'.
num_point : int
Number of points in the timecourse.
Returns
-------
Timecourse
"""
model = Model.makeBiomodel(model_name)
timecourse = cls(model=model, num_point=num_point, end_time=end_time)
return timecourse
@classmethod
def makeTimecourses(cls, model: Model,
start_time: float = cn.START_TIME,
end_time: Optional[float] = None,
num_point: int = cn.NUM_POINT,
perturbation_value_fraction: List[float] = [0.0],
perturbation_species_fraction: List[float] = [1.0],
is_plot: bool = True,
) -> List["Timecourse"]:
"""Create one Timecourse for every combination of perturbation parameters.
Constructs a subplot that contains each species. Values are plotted as a scatter plot.
Parameters
----------
model : Model
start_time : float
end_time : Optional[float]
None uses BioModels CSV lookup or leaves end_time unset.
num_point : int
perturbation_value_fraction : List[float]
Each value is the fractional shift applied to perturbed initial values.
perturbation_species_fraction : List[float]
Each value is the fraction of species whose initial values are perturbed.
Returns
-------
List[Timecourse]
One Timecourse per combination of perturbation parameters.
"""
timecourses: List[Timecourse] = []
perturbation_names: List[str] = []
for value_frac in perturbation_value_fraction:
for species_frac in perturbation_species_fraction:
timecourse = cls(
model=model,
start_time=start_time,
end_time=end_time,
num_point=num_point,
perturbation_value_fraction=value_frac,
perturbation_species_fraction=species_frac,
)
timecourses.append(timecourse)
perturbation_names.append(f"vfrc:{value_frac}__sfrc:{species_frac}")
if is_plot:
num_species = model.num_species
num_col = 4
num_row = (num_species + num_col - 1) // num_col
fig, axes = plt.subplots(num_row, num_col, figsize=(4 * num_col, 4 * num_row),
squeeze=False)
for i, name in enumerate(model.species_names):
irow = i // num_col
icol = i % num_col
ax = axes[irow, icol] # type: ignore
for tc in timecourses:
ax.plot(tc.timecourse_df.index, tc.timecourse_df[name])
ax.legend(perturbation_names)
ax.set_title(name)
ax.set_xlabel("time")
ax.set_ylabel("concentration")
for i in range(num_row):
for j in range(num_col):
if i * num_col + j >= num_species:
fig.delaxes(axes[i, j]) # type: ignore
fig.tight_layout()
plt.show()
return timecourses