-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathtest_heavisides.py
More file actions
431 lines (374 loc) · 12 KB
/
test_heavisides.py
File metadata and controls
431 lines (374 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
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
"""Tests for SBML events, including piecewise expressions."""
import numpy as np
import pytest
from util import (
check_trajectories_with_adjoint_sensitivities,
check_trajectories_with_forward_sensitivities,
check_trajectories_without_sensitivities,
)
from amici.testing.models import create_sbml_model, create_amici_model
pytestmark = pytest.mark.filterwarnings(
# https://github.com/AMICI-dev/AMICI/issues/18
"ignore:Adjoint sensitivity analysis for models with discontinuous "
"right hand sides .*:UserWarning",
)
@pytest.fixture(
params=[
"state_and_param_dep_heavisides",
"piecewise_with_boolean_operations",
"piecewise_many_conditions",
]
)
def model(request):
"""Returns the requested AMICI model and analytical expressions."""
(
initial_assignments,
parameters,
rate_rules,
species,
events,
timepoints,
x_expected,
sx_expected,
) = get_model_definition(request.param)
# SBML model
sbml_document, sbml_model = create_sbml_model(
initial_assignments=initial_assignments,
parameters=parameters,
rate_rules=rate_rules,
species=species,
events=events,
# uncomment `to_file` to save SBML model to file for inspection
# to_file=sbml_test_models / (model_name + '.sbml'),
)
# AMICI model
amici_model = create_amici_model(
sbml_model=sbml_model,
model_name=request.param,
)
amici_model.setTimepoints(timepoints)
return amici_model, parameters, timepoints, x_expected, sx_expected
def test_models(model):
amici_model, parameters, timepoints, x_expected, sx_expected = model
result_expected_x = np.array(
[x_expected(t, **parameters) for t in timepoints]
)
result_expected_sx = np.array(
[sx_expected(t, **parameters) for t in timepoints]
)
# Does the AMICI simulation match the analytical solution?
check_trajectories_without_sensitivities(amici_model, result_expected_x)
check_trajectories_with_forward_sensitivities(
amici_model, result_expected_x, result_expected_sx
)
# FIXME: For a few parameters of these models, adjoint sensitivities
# are somewhat off. This needs to be investigated further.
asa_xfail = amici_model.getName() in ("state_and_param_dep_heavisides",)
check_trajectories_with_adjoint_sensitivities(amici_model, asa_xfail)
def get_model_definition(model_name):
if model_name == "state_and_param_dep_heavisides":
return model_definition_state_and_parameter_dependent_heavisides()
elif model_name == "piecewise_with_boolean_operations":
return model_definition_piecewise_with_boolean_operations()
elif model_name == "piecewise_many_conditions":
return model_definition_piecewise_many_conditions()
else:
raise NotImplementedError(
f"Model with name {model_name} is not implemented."
)
def model_definition_state_and_parameter_dependent_heavisides():
"""Test model for state- and parameter-dependent heavisides.
ODEs
----
d/dt x_1:
- { alpha * x_1, t < x_2
- { -beta * x_1, t >= x_2
d/dt x_2:
- { gamma * x_2, t < delta
- { eta, t >= delta
"""
# Model components
species = ["x_1", "x_2"]
initial_assignments = {
"x_1": "zeta",
}
rate_rules = {
"x_1": "piecewise( alpha * x_1, time < x_2, -beta * x_1 )",
"x_2": "piecewise( gamma * x_2, time < delta, eta )",
}
parameters = {
"alpha": float(np.log(2)),
"beta": float(np.log(4)),
"gamma": float(np.log(3)),
"delta": 1,
"eta": 0.5,
"zeta": 0.25,
}
timepoints = np.linspace(0, 10, 100)
events = {}
# Analytical solution
def x_expected(t, alpha, beta, gamma, delta, eta, zeta):
# get x_1
tau_1 = (np.exp(gamma * delta) - delta * eta) / (1 - eta)
if t < tau_1:
x_1 = zeta * np.exp(alpha * t)
else:
x_1 = zeta * np.exp(alpha * tau_1 - beta * (t - tau_1))
# get x_2
tau_2 = delta
if t < tau_2:
x_2 = np.exp(gamma * t)
else:
x_2 = np.exp(gamma * delta) + eta * (t - delta)
return x_1, x_2
def sx_expected(t, alpha, beta, gamma, delta, eta, zeta):
# get sx_1, w.r.t. parameters
tau_1 = (np.exp(gamma * delta) - delta * eta) / (1 - eta)
if t < tau_1:
sx_1_alpha = zeta * t * np.exp(alpha * t)
sx_1_beta = 0
sx_1_gamma = 0
sx_1_delta = 0
sx_1_eta = 0
sx_1_zeta = np.exp(alpha * t)
else:
# Never trust Wolfram Alpha...
sx_1_alpha = (
zeta * tau_1 * np.exp(alpha * tau_1 - beta * (t - tau_1))
)
sx_1_beta = (
zeta * (tau_1 - t) * np.exp(alpha * tau_1 - beta * (t - tau_1))
)
sx_1_gamma = (
zeta
* (alpha + beta)
* delta
* np.exp(gamma * delta)
/ (1 - eta)
* np.exp(alpha * tau_1 - beta * (t - tau_1))
)
sx_1_delta = (
zeta
* (alpha + beta)
* np.exp(alpha * tau_1 - beta * (t - tau_1))
* (gamma * np.exp(gamma * delta) - eta)
/ (1 - eta)
)
sx_1_eta = (
zeta
* (alpha + beta)
* (-delta * (1 - eta) + np.exp(gamma * delta) - delta * eta)
/ (1 - eta) ** 2
* np.exp(alpha * tau_1 - beta * (t - tau_1))
)
sx_1_zeta = np.exp(alpha * tau_1 - beta * (t - tau_1))
# get sx_2, w.r.t. parameters
tau_2 = delta
sx_2_alpha = 0
sx_2_beta = 0
sx_2_zeta = 0
if t < tau_2:
sx_2_gamma = t * np.exp(gamma * t)
sx_2_delta = 0
sx_2_eta = 0
else:
sx_2_gamma = delta * np.exp(gamma * delta)
sx_2_delta = gamma * np.exp(gamma * delta) - eta
sx_2_eta = t - delta
sx_1 = (
sx_1_alpha,
sx_1_beta,
sx_1_gamma,
sx_1_delta,
sx_1_eta,
sx_1_zeta,
)
sx_2 = (
sx_2_alpha,
sx_2_beta,
sx_2_gamma,
sx_2_delta,
sx_2_eta,
sx_2_zeta,
)
return np.array((sx_1, sx_2)).transpose()
return (
initial_assignments,
parameters,
rate_rules,
species,
events,
timepoints,
x_expected,
sx_expected,
)
def model_definition_piecewise_with_boolean_operations():
"""Test model for boolean operations in a piecewise condition.
ODEs
----
d/dt x_1:
- { 1, (alpha <= t and t < beta) or (gamma <= t and t < delta)
- { 0, otherwise
"""
# Model components
species = ["x_1"]
initial_assignments = {"x_1": "x_1_0"}
rate_rules = {
"x_1": (
"piecewise("
"1, " # noqa
"(alpha <= time && time < beta) || " # noqa
"(gamma <= time && time < delta), "
"0"
")"
),
}
parameters = {
"alpha": 1,
"beta": 2,
"gamma": 3,
"delta": 4,
"x_1_0": 1,
}
timepoints = np.linspace(0, 5, 100)
events = {}
# Analytical solution
def x_expected(t, x_1_0, alpha, beta, gamma, delta):
if t < alpha:
return (x_1_0,)
elif alpha <= t < beta:
return (x_1_0 + (t - alpha),)
elif beta <= t < gamma:
return (x_1_0 + (beta - alpha),)
elif gamma <= t < delta:
return (x_1_0 + (beta - alpha) + (t - gamma),)
else:
return (x_1_0 + (beta - alpha) + (delta - gamma),)
def sx_expected(t, x_1_0, alpha, beta, gamma, delta):
# x0 is very simple...
sx_x0 = 1
sx_alpha = -1 if t >= alpha else 0
sx_beta = 1 if t >= beta else 0
sx_gamma = -1 if t >= gamma else 0
sx_delta = 1 if t >= delta else 0
sx = (sx_alpha, sx_beta, sx_gamma, sx_delta, sx_x0)
return np.array((sx,)).transpose()
return (
initial_assignments,
parameters,
rate_rules,
species,
events,
timepoints,
x_expected,
sx_expected,
)
def model_definition_piecewise_many_conditions():
"""Test model for piecewise functions with many pieces.
ODEs
----
d/dt x_1:
- { 1, floor(t) is odd
- { 0, otherwise
"""
# Model components
species = ["x_1"]
initial_assignments = {"x_1": "x_1_0"}
t_final = 5
pieces = "piecewise("
for t in range(t_final):
if t > 0:
pieces += ", "
if t % 2 == 1:
pieces += f"1, time < {t + 1}"
else:
pieces += f"0, time < {t + 1}"
pieces += ", 0)"
rate_rules = {
"x_1": pieces,
}
parameters = {
"x_1_0": 1,
}
timepoints = np.linspace(0, t_final, 100)
events = {}
# Analytical solution
def x_expected(t, x_1_0):
if np.floor(t) % 2 == 1:
return (x_1_0 + (np.floor(t) - 1) / 2 + (t - np.floor(t)),)
else:
return (x_1_0 + np.floor(t) / 2,)
def sx_expected(t, x_1_0):
return np.array(
[
[
1,
],
]
)
return (
initial_assignments,
parameters,
rate_rules,
species,
events,
timepoints,
x_expected,
sx_expected,
)
def test_parse_piecewise_c1_no_heaviside():
"""_parse_piecewise_to_heaviside should keep C1 piecewise expressions."""
import sympy as sp
from amici.import_utils import (
_parse_piecewise_to_heaviside,
amici_time_symbol,
symbol_with_assumptions,
)
t = amici_time_symbol
x = symbol_with_assumptions("x_1")
pw = sp.Piecewise((t * x, t < 1), (x + (t - 1) * x, True))
res = _parse_piecewise_to_heaviside(pw.args, [])
assert isinstance(res, sp.Piecewise)
assert sp.simplify(res - pw) == 0
p = symbol_with_assumptions("p1")
pw_param = sp.Piecewise(
(p**2, p < 1),
((p - 1) ** 2 + 2 * p - 1, True),
)
res_param = _parse_piecewise_to_heaviside(pw_param.args, [p])
assert isinstance(res_param, sp.Piecewise)
assert sp.simplify(res_param - pw_param) == 0
def test_parse_piecewise_discontinuous_to_heaviside():
"""_parse_piecewise_to_heaviside should convert discontinuous piecewise."""
import sympy as sp
from amici.import_utils import (
_parse_piecewise_to_heaviside,
amici_time_symbol,
symbol_with_assumptions,
)
t = amici_time_symbol
x = symbol_with_assumptions("x_1")
pw_state = sp.Piecewise((t * x, x < 1), (2 * t * x, True))
res_state = _parse_piecewise_to_heaviside(pw_state.args, [])
assert not isinstance(res_state, sp.Piecewise)
expected_state = t * x * (
1 - sp.Heaviside(x - 1, 1)
) + 2 * t * x * sp.Heaviside(x - 1, 1)
assert sp.simplify(res_state - expected_state) == 0
p = symbol_with_assumptions("p1")
pw_param = sp.Piecewise((0, p < 1), (1, True))
res_param = _parse_piecewise_to_heaviside(pw_param.args, [p])
assert not isinstance(res_param, sp.Piecewise)
expected_param = sp.Heaviside(p - 1, 1)
assert sp.simplify(res_param - expected_param) == 0
def test_parse_piecewise_c1_constant_zero():
"""Piecewise expressions evaluating to zero should simplify to zero."""
import sympy as sp
from amici.import_utils import (
_parse_piecewise_to_heaviside,
symbol_with_assumptions,
)
p = symbol_with_assumptions("p1")
pw_zero = sp.Piecewise((p - p, p < 1), (0, True), evaluate=False)
res_zero = _parse_piecewise_to_heaviside(pw_zero.args, [p])
assert sp.simplify(res_zero) == 0