mgrowthctrl 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mgrowthctrl/__init__.py +0 -0
- mgrowthctrl/backends/__init__.py +8 -0
- mgrowthctrl/backends/array.py +148 -0
- mgrowthctrl/controllers/__init__.py +9 -0
- mgrowthctrl/controllers/base.py +293 -0
- mgrowthctrl/controllers/closed_loop.py +208 -0
- mgrowthctrl/controllers/open_loop.py +174 -0
- mgrowthctrl/models/__init__.py +2 -0
- mgrowthctrl/models/base.py +354 -0
- mgrowthctrl/models/crm/fit.py +544 -0
- mgrowthctrl/models/crm/model.py +555 -0
- mgrowthctrl/models/crm/utils.py +539 -0
- mgrowthctrl/utils/__init__.py +0 -0
- mgrowthctrl/utils/data.py +549 -0
- mgrowthctrl/utils/plot.py +417 -0
- mgrowthctrl/utils/save.py +71 -0
- mgrowthctrl-0.1.0.dist-info/METADATA +116 -0
- mgrowthctrl-0.1.0.dist-info/RECORD +20 -0
- mgrowthctrl-0.1.0.dist-info/WHEEL +4 -0
- mgrowthctrl-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,544 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
from typing import Callable, Dict, List, Optional, Tuple, Union, Literal
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
import scipy
|
|
6
|
+
from scipy.optimize import least_squares
|
|
7
|
+
|
|
8
|
+
# PATCH: SciPy >= 1.14 removed top-level pi/sin/cos, breaking pymcmcstat->mcmcplot
|
|
9
|
+
if not hasattr(scipy, "pi"):
|
|
10
|
+
scipy.pi = np.pi
|
|
11
|
+
scipy.sin = np.sin
|
|
12
|
+
scipy.cos = np.cos
|
|
13
|
+
|
|
14
|
+
from pymcmcstat.MCMC import MCMC
|
|
15
|
+
|
|
16
|
+
from .utils import (
|
|
17
|
+
_broadcast_nm,
|
|
18
|
+
_first_finite_by_col,
|
|
19
|
+
_safe_pchip,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
# Types & Aliases
|
|
23
|
+
ArrayLike = np.ndarray
|
|
24
|
+
# simulate_fn(params, X0, S0, t_eval) -> {"t": (T,), "X": (T, n), "S": (T, m)}
|
|
25
|
+
SimulateFn = Callable[
|
|
26
|
+
[Dict[str, np.ndarray], np.ndarray, np.ndarray, np.ndarray], Dict[str, np.ndarray]
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
# FitContext Class
|
|
31
|
+
@dataclass
|
|
32
|
+
class FitContext:
|
|
33
|
+
"""
|
|
34
|
+
Encapsulate all information needed to fit a CRM via least-squares or MCMC.
|
|
35
|
+
|
|
36
|
+
This class is deliberately model-agnostic: it only assumes that `simulate_fn`
|
|
37
|
+
takes (params_dict, X0, S0, t_eval) and returns a dict with keys 't', 'X', 'S'.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
# Raw Data
|
|
41
|
+
t_data: np.ndarray # (T,)
|
|
42
|
+
X_data: np.ndarray # (T, n)
|
|
43
|
+
S_data: np.ndarray # (T, m) or (T, 0)
|
|
44
|
+
|
|
45
|
+
# Problem Dimensions & Masks
|
|
46
|
+
n: int
|
|
47
|
+
m: int
|
|
48
|
+
U_idx: np.ndarray # indices of free r_ij (flattened C-order)
|
|
49
|
+
Y_idx: np.ndarray # indices of free b_ij
|
|
50
|
+
A_idx: np.ndarray # indices of free a_ij
|
|
51
|
+
|
|
52
|
+
# Simulation Setup
|
|
53
|
+
t_eval: np.ndarray # (Teval,)
|
|
54
|
+
X0: np.ndarray # (n,)
|
|
55
|
+
S0: np.ndarray # (m,)
|
|
56
|
+
|
|
57
|
+
# Fixed Parameters
|
|
58
|
+
K_ij: np.ndarray # (n, m)
|
|
59
|
+
S_in: np.ndarray # (m,)
|
|
60
|
+
D: Union[float, Callable[[float], float]]
|
|
61
|
+
|
|
62
|
+
# Scaling Factors
|
|
63
|
+
sX: np.ndarray # (n,)
|
|
64
|
+
sS: np.ndarray # (m,)
|
|
65
|
+
|
|
66
|
+
# Initial Full-Shaped Parameters
|
|
67
|
+
A0: np.ndarray # (n, m)
|
|
68
|
+
r0: np.ndarray # (n, m)
|
|
69
|
+
b0: np.ndarray # (n, m)
|
|
70
|
+
k0: np.ndarray # (n,)
|
|
71
|
+
|
|
72
|
+
include_metabolites: bool
|
|
73
|
+
simulate_fn: SimulateFn
|
|
74
|
+
|
|
75
|
+
# Packing / Unpacking Methods
|
|
76
|
+
def pack(
|
|
77
|
+
self, r: np.ndarray, b: np.ndarray, k: np.ndarray, a: np.ndarray
|
|
78
|
+
) -> np.ndarray:
|
|
79
|
+
"""Flatten (r, b, k, a) into a parameter vector respecting the masks."""
|
|
80
|
+
parts: List[np.ndarray] = []
|
|
81
|
+
if self.U_idx.size:
|
|
82
|
+
parts.append(r.ravel(order="C")[self.U_idx])
|
|
83
|
+
if self.Y_idx.size:
|
|
84
|
+
parts.append(b.ravel(order="C")[self.Y_idx])
|
|
85
|
+
|
|
86
|
+
parts.append(k.ravel())
|
|
87
|
+
|
|
88
|
+
if self.A_idx.size:
|
|
89
|
+
parts.append(a.ravel(order="C")[self.A_idx])
|
|
90
|
+
|
|
91
|
+
return np.concatenate(parts) if parts else np.array([], float)
|
|
92
|
+
|
|
93
|
+
def unpack(
|
|
94
|
+
self, theta: np.ndarray
|
|
95
|
+
) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
|
|
96
|
+
"""Reconstruct full (r, b, k, a) arrays from a parameter vector."""
|
|
97
|
+
r = np.zeros((self.n, self.m), float)
|
|
98
|
+
b = np.zeros((self.n, self.m), float)
|
|
99
|
+
a = self.A0.copy()
|
|
100
|
+
k = np.zeros(self.n, float)
|
|
101
|
+
|
|
102
|
+
pos = 0
|
|
103
|
+
|
|
104
|
+
# Unpack r
|
|
105
|
+
if self.U_idx.size:
|
|
106
|
+
r.ravel(order="C")[self.U_idx] = theta[pos : pos + self.U_idx.size]
|
|
107
|
+
pos += self.U_idx.size
|
|
108
|
+
|
|
109
|
+
# Unpack b
|
|
110
|
+
if self.Y_idx.size:
|
|
111
|
+
b.ravel(order="C")[self.Y_idx] = theta[pos : pos + self.Y_idx.size]
|
|
112
|
+
pos += self.Y_idx.size
|
|
113
|
+
|
|
114
|
+
# Unpack k
|
|
115
|
+
k = np.asarray(theta[pos : pos + self.n], float).ravel()
|
|
116
|
+
pos += self.n
|
|
117
|
+
|
|
118
|
+
# Unpack a
|
|
119
|
+
if self.A_idx.size:
|
|
120
|
+
a.ravel(order="C")[self.A_idx] = theta[pos : pos + self.A_idx.size]
|
|
121
|
+
pos += self.A_idx.size
|
|
122
|
+
|
|
123
|
+
return r, b, k, a
|
|
124
|
+
|
|
125
|
+
def params_from_theta(self, theta: np.ndarray) -> Dict[str, np.ndarray]:
|
|
126
|
+
"""Convert theta -> parameter dict expected by simulate_fn."""
|
|
127
|
+
r, b, k, a = self.unpack(theta)
|
|
128
|
+
return dict(
|
|
129
|
+
r=r,
|
|
130
|
+
b=b,
|
|
131
|
+
k=k,
|
|
132
|
+
a=a,
|
|
133
|
+
K_ij=self.K_ij,
|
|
134
|
+
S_in=self.S_in,
|
|
135
|
+
D=self.D,
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
# Residuals / Sum of Squares
|
|
139
|
+
def residuals(self, theta: np.ndarray) -> np.ndarray:
|
|
140
|
+
"""
|
|
141
|
+
Compute time-series residuals for a given parameter vector.
|
|
142
|
+
|
|
143
|
+
Species and (optionally) metabolites are interpolated to measurement times
|
|
144
|
+
using PCHIP, then scaled by sX/sS.
|
|
145
|
+
"""
|
|
146
|
+
params = self.params_from_theta(theta)
|
|
147
|
+
sim = self.simulate_fn(params, self.X0, self.S0, self.t_eval) # {"t","X","S"}
|
|
148
|
+
|
|
149
|
+
res: List[np.ndarray] = []
|
|
150
|
+
|
|
151
|
+
# Species Residuals
|
|
152
|
+
for j in range(self.n):
|
|
153
|
+
mask = np.isfinite(self.t_data) & np.isfinite(self.X_data[:, j])
|
|
154
|
+
if not mask.any():
|
|
155
|
+
continue
|
|
156
|
+
p = _safe_pchip(sim["t"], sim["X"][:, j])
|
|
157
|
+
res.append((p(self.t_data[mask]) - self.X_data[mask, j]) / self.sX[j])
|
|
158
|
+
|
|
159
|
+
# Metabolite Residuals
|
|
160
|
+
if self.include_metabolites and self.m:
|
|
161
|
+
for j in range(self.m):
|
|
162
|
+
mask = np.isfinite(self.t_data) & np.isfinite(self.S_data[:, j])
|
|
163
|
+
if not mask.any():
|
|
164
|
+
continue
|
|
165
|
+
p = _safe_pchip(sim["t"], sim["S"][:, j])
|
|
166
|
+
res.append((p(self.t_data[mask]) - self.S_data[mask, j]) / self.sS[j])
|
|
167
|
+
|
|
168
|
+
out = np.concatenate(res) if res else np.zeros_like(theta)
|
|
169
|
+
return np.nan_to_num(out, nan=0.0, posinf=0.0, neginf=0.0)
|
|
170
|
+
|
|
171
|
+
def sos(self, theta: np.ndarray) -> float:
|
|
172
|
+
"""Sum of squared residuals."""
|
|
173
|
+
r = self.residuals(theta)
|
|
174
|
+
return float(np.dot(r, r))
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
# Context Builder
|
|
178
|
+
def prepare_fit_context(
|
|
179
|
+
df,
|
|
180
|
+
time_col: str,
|
|
181
|
+
x_cols: List[str],
|
|
182
|
+
s_cols: List[str],
|
|
183
|
+
simulate_fn: SimulateFn,
|
|
184
|
+
params0: Optional[Dict[str, np.ndarray]] = None,
|
|
185
|
+
lb_factor: float = 0.0,
|
|
186
|
+
ub_factor: float = 10.0,
|
|
187
|
+
X0: Optional[np.ndarray] = None,
|
|
188
|
+
S0: Optional[np.ndarray] = None,
|
|
189
|
+
include_metabolites: bool = True,
|
|
190
|
+
weight: Literal["median", "equal"] = "median",
|
|
191
|
+
n_time: int = 300,
|
|
192
|
+
fit_a: bool = False,
|
|
193
|
+
) -> Tuple[FitContext, np.ndarray, np.ndarray, np.ndarray]:
|
|
194
|
+
"""
|
|
195
|
+
Build a FitContext and (theta0, lb, ub) from a DataFrame and initial params.
|
|
196
|
+
"""
|
|
197
|
+
params0 = params0 or {}
|
|
198
|
+
|
|
199
|
+
# Data Extraction
|
|
200
|
+
t_data = np.asarray(df[time_col], float)
|
|
201
|
+
X_data = np.column_stack([np.asarray(df[c], float) for c in x_cols])
|
|
202
|
+
S_data = (
|
|
203
|
+
np.column_stack([np.asarray(df[c], float) for c in s_cols])
|
|
204
|
+
if s_cols
|
|
205
|
+
else np.zeros((len(df), 0))
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
n = X_data.shape[1]
|
|
209
|
+
m = S_data.shape[1]
|
|
210
|
+
|
|
211
|
+
# Time Grid
|
|
212
|
+
tmin, tmax = np.nanmin(t_data), np.nanmax(t_data)
|
|
213
|
+
if not np.isfinite(tmin) or not np.isfinite(tmax) or tmin == tmax:
|
|
214
|
+
tmin, tmax = 0.0, 1.0
|
|
215
|
+
t_eval = np.linspace(float(tmin), float(tmax), max(int(n_time), 2))
|
|
216
|
+
|
|
217
|
+
# Initial Conditions
|
|
218
|
+
if X0 is None:
|
|
219
|
+
X0 = _first_finite_by_col(X_data, 1.0)
|
|
220
|
+
if S0 is None and m:
|
|
221
|
+
S0 = _first_finite_by_col(S_data, 1.0)
|
|
222
|
+
if S0 is None:
|
|
223
|
+
S0 = np.zeros(0)
|
|
224
|
+
|
|
225
|
+
# Parameter Broadcasting
|
|
226
|
+
A0 = _broadcast_nm(params0.get("a"), n, m, 0.0)
|
|
227
|
+
r0 = _broadcast_nm(params0.get("r"), n, m, 1.0)
|
|
228
|
+
b0 = _broadcast_nm(params0.get("b"), n, m, 1e-2)
|
|
229
|
+
|
|
230
|
+
U_idx = np.flatnonzero(r0.ravel(order="C") != 0)
|
|
231
|
+
Y_idx = np.flatnonzero(b0.ravel(order="C") != 0)
|
|
232
|
+
A_idx = np.flatnonzero(A0.ravel(order="C") != 0) if fit_a else np.array([], dtype=int)
|
|
233
|
+
|
|
234
|
+
if "K_ij" in params0:
|
|
235
|
+
K_ij = _broadcast_nm(params0["K_ij"], n, m, 1.0)
|
|
236
|
+
else:
|
|
237
|
+
cm = np.nanmax(S_data, axis=0) if m else np.array([])
|
|
238
|
+
if m:
|
|
239
|
+
cm[~np.isfinite(cm)] = 0.0
|
|
240
|
+
K_ij = (
|
|
241
|
+
np.broadcast_to((2 * np.maximum(cm, 1e-12)).reshape(1, m), (n, m))
|
|
242
|
+
if m
|
|
243
|
+
else np.zeros((n, 0))
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
S_in = (
|
|
247
|
+
np.asarray(params0.get("S_in", np.zeros(m, float)), float) if m else np.zeros(0)
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
D_param = params0.get("D", 0.0)
|
|
251
|
+
D = D_param if callable(D_param) else float(D_param)
|
|
252
|
+
|
|
253
|
+
k0 = np.asarray(params0.get("k", np.full(n, 0.05)), float).ravel()
|
|
254
|
+
if k0.size == 1:
|
|
255
|
+
k0 = np.full(n, float(k0[0]))
|
|
256
|
+
if k0.size != n:
|
|
257
|
+
raise ValueError(f"k has length {k0.size}; expected 1 or {n}.")
|
|
258
|
+
|
|
259
|
+
# Scaling Weights
|
|
260
|
+
if weight == "median":
|
|
261
|
+
sX = np.nanmedian(np.clip(X_data, 1e-12, None), axis=0)
|
|
262
|
+
sX[~np.isfinite(sX) | (sX <= 0)] = 1.0
|
|
263
|
+
|
|
264
|
+
if m:
|
|
265
|
+
sS = np.nanmedian(np.clip(S_data, 1e-12, None), axis=0)
|
|
266
|
+
sS[~np.isfinite(sS) | (sS <= 0)] = 1.0
|
|
267
|
+
else:
|
|
268
|
+
sS = np.ones(0)
|
|
269
|
+
elif weight == "equal":
|
|
270
|
+
sX = np.ones(n)
|
|
271
|
+
sS = np.ones(m)
|
|
272
|
+
else:
|
|
273
|
+
raise ValueError(f"Unknown `weight` parameter, must be one of `median`, `equal`, was: {weight}")
|
|
274
|
+
|
|
275
|
+
# Build Context
|
|
276
|
+
ctx = FitContext(
|
|
277
|
+
t_data=t_data,
|
|
278
|
+
X_data=X_data,
|
|
279
|
+
S_data=S_data,
|
|
280
|
+
n=n,
|
|
281
|
+
m=m,
|
|
282
|
+
U_idx=U_idx,
|
|
283
|
+
Y_idx=Y_idx,
|
|
284
|
+
A_idx=A_idx,
|
|
285
|
+
t_eval=t_eval,
|
|
286
|
+
X0=X0,
|
|
287
|
+
S0=S0,
|
|
288
|
+
K_ij=K_ij,
|
|
289
|
+
S_in=S_in,
|
|
290
|
+
D=D,
|
|
291
|
+
sX=sX,
|
|
292
|
+
sS=sS,
|
|
293
|
+
A0=A0,
|
|
294
|
+
r0=r0,
|
|
295
|
+
b0=b0,
|
|
296
|
+
k0=k0,
|
|
297
|
+
include_metabolites=include_metabolites,
|
|
298
|
+
simulate_fn=simulate_fn,
|
|
299
|
+
)
|
|
300
|
+
|
|
301
|
+
theta0 = ctx.pack(r0, b0, k0, A0)
|
|
302
|
+
lb = lb_factor * theta0
|
|
303
|
+
ub = ub_factor * theta0
|
|
304
|
+
|
|
305
|
+
zero = theta0 == 0
|
|
306
|
+
lb = np.where(zero, np.nextafter(0.0, -np.inf), lb)
|
|
307
|
+
ub = np.where(zero, np.nextafter(0.0, np.inf), ub)
|
|
308
|
+
|
|
309
|
+
return ctx, theta0, lb, ub
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
# Least-Squares Wrapper
|
|
313
|
+
def crm_fit_mechanistic(
|
|
314
|
+
df,
|
|
315
|
+
time_col: str,
|
|
316
|
+
x_cols: List[str],
|
|
317
|
+
s_cols: List[str],
|
|
318
|
+
simulate_fn: SimulateFn,
|
|
319
|
+
params0: Optional[Dict[str, np.ndarray]] = None,
|
|
320
|
+
lb_factor: float = 0.0,
|
|
321
|
+
ub_factor: float = 10.0,
|
|
322
|
+
X0: Optional[np.ndarray] = None,
|
|
323
|
+
S0: Optional[np.ndarray] = None,
|
|
324
|
+
include_metabolites: bool = True,
|
|
325
|
+
weight: str = "median",
|
|
326
|
+
n_time: int = 300,
|
|
327
|
+
fit_a: bool = False,
|
|
328
|
+
):
|
|
329
|
+
"""
|
|
330
|
+
High-level least-squares fit for CRM parameters.
|
|
331
|
+
"""
|
|
332
|
+
ctx, theta0, lb, ub = prepare_fit_context(
|
|
333
|
+
df=df,
|
|
334
|
+
time_col=time_col,
|
|
335
|
+
x_cols=x_cols,
|
|
336
|
+
s_cols=s_cols,
|
|
337
|
+
simulate_fn=simulate_fn,
|
|
338
|
+
params0=params0,
|
|
339
|
+
lb_factor=lb_factor,
|
|
340
|
+
ub_factor=ub_factor,
|
|
341
|
+
X0=X0,
|
|
342
|
+
S0=S0,
|
|
343
|
+
include_metabolites=include_metabolites,
|
|
344
|
+
weight=weight,
|
|
345
|
+
n_time=n_time,
|
|
346
|
+
fit_a=fit_a,
|
|
347
|
+
)
|
|
348
|
+
|
|
349
|
+
ls = least_squares(
|
|
350
|
+
ctx.residuals,
|
|
351
|
+
theta0,
|
|
352
|
+
bounds=(lb, ub),
|
|
353
|
+
xtol=1e-10,
|
|
354
|
+
ftol=1e-10,
|
|
355
|
+
gtol=1e-10,
|
|
356
|
+
verbose=0,
|
|
357
|
+
)
|
|
358
|
+
|
|
359
|
+
r_opt, b_opt, k_opt, a_opt = ctx.unpack(ls.x)
|
|
360
|
+
params_opt = dict(
|
|
361
|
+
r=r_opt,
|
|
362
|
+
a=a_opt,
|
|
363
|
+
b=b_opt,
|
|
364
|
+
K_ij=ctx.K_ij,
|
|
365
|
+
k=k_opt,
|
|
366
|
+
S_in=ctx.S_in,
|
|
367
|
+
D=ctx.D,
|
|
368
|
+
)
|
|
369
|
+
sim_opt = simulate_fn(params_opt, ctx.X0, ctx.S0, ctx.t_eval)
|
|
370
|
+
|
|
371
|
+
info = dict(
|
|
372
|
+
success=ls.success,
|
|
373
|
+
message=ls.message,
|
|
374
|
+
cost=ls.cost,
|
|
375
|
+
nfev=ls.nfev,
|
|
376
|
+
theta0=theta0,
|
|
377
|
+
theta_opt=ls.x,
|
|
378
|
+
t_eval=ctx.t_eval,
|
|
379
|
+
)
|
|
380
|
+
return ls.x, params_opt, sim_opt, info
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
# MCMC Helpers & Main Function
|
|
384
|
+
def make_mcmc_primitives(ctx: FitContext, theta0: np.ndarray):
|
|
385
|
+
"""Return (residuals_fn, sos_fn, param_names) for an external MCMC library."""
|
|
386
|
+
|
|
387
|
+
def residuals_for_theta(theta: np.ndarray) -> np.ndarray:
|
|
388
|
+
return ctx.residuals(theta)
|
|
389
|
+
|
|
390
|
+
def sos_function(theta: np.ndarray, data=None) -> float:
|
|
391
|
+
# data arg for pymcmcstat-style APIs
|
|
392
|
+
return ctx.sos(theta)
|
|
393
|
+
|
|
394
|
+
param_names = [f"theta_{i + 1}" for i in range(theta0.size)]
|
|
395
|
+
return residuals_for_theta, sos_function, param_names
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def posterior_from_chain(chain: np.ndarray, burn: float = 0.3) -> np.ndarray:
|
|
399
|
+
"""Drop a burn-in fraction from the MCMC chain."""
|
|
400
|
+
chain = np.asarray(chain, float)
|
|
401
|
+
b = int(burn * chain.shape[0])
|
|
402
|
+
b = max(0, min(b, chain.shape[0] - 1))
|
|
403
|
+
return chain[b:, :]
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def sample_posterior_indices(
|
|
407
|
+
npost: int, nsamp: int = 200, seed: int = 1234
|
|
408
|
+
) -> np.ndarray:
|
|
409
|
+
"""Pick a subset of posterior samples for simulation/plotting."""
|
|
410
|
+
ns = int(min(nsamp, max(20, npost // 20)))
|
|
411
|
+
rng = np.random.default_rng(seed)
|
|
412
|
+
return np.sort(rng.choice(npost, size=ns, replace=False))
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
def sims_from_chain(
|
|
416
|
+
ctx: FitContext, post: np.ndarray, picks: np.ndarray
|
|
417
|
+
) -> List[Dict[str, np.ndarray]]:
|
|
418
|
+
"""Simulate trajectories for selected posterior samples."""
|
|
419
|
+
sims: List[Dict[str, np.ndarray]] = []
|
|
420
|
+
for k in picks:
|
|
421
|
+
theta_k = post[k, :]
|
|
422
|
+
params_k = ctx.params_from_theta(theta_k)
|
|
423
|
+
sim_k = ctx.simulate_fn(params_k, ctx.X0, ctx.S0, ctx.t_eval)
|
|
424
|
+
sims.append(sim_k)
|
|
425
|
+
return sims
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def crm_fit_mcmc(
|
|
429
|
+
ctx: FitContext,
|
|
430
|
+
theta0: np.ndarray,
|
|
431
|
+
nsimu: int = 10_000,
|
|
432
|
+
sigma2: float = 12.0,
|
|
433
|
+
burn: float = 0.8,
|
|
434
|
+
nsamp: int = 200,
|
|
435
|
+
seed: int = 1234,
|
|
436
|
+
):
|
|
437
|
+
"""
|
|
438
|
+
Run MCMC around a given FitContext/theta0. See the documentation of the
|
|
439
|
+
pymcmcstat package for more details.
|
|
440
|
+
|
|
441
|
+
Parameters:
|
|
442
|
+
:param theta0: Initial values
|
|
443
|
+
:param nsimu: Number of simulations in each chain
|
|
444
|
+
:param sigma2: Initial observation error
|
|
445
|
+
:param burn: Fraction of samples to drop as burn-in
|
|
446
|
+
:param nsamp: Number of posterior samples to pick
|
|
447
|
+
:param seed: Random seed
|
|
448
|
+
|
|
449
|
+
Returns:
|
|
450
|
+
dict containing: post, chain, sschain, param_names, picks, mcmc_sims
|
|
451
|
+
"""
|
|
452
|
+
residuals_for_theta, sos_function, param_names = make_mcmc_primitives(ctx, theta0)
|
|
453
|
+
|
|
454
|
+
mc = MCMC(rngseed=seed)
|
|
455
|
+
mc.data.add_data_set(np.array([0.0]), np.array([0.0]))
|
|
456
|
+
mc.model_settings.define_model_settings(sos_function=sos_function, sigma2=sigma2)
|
|
457
|
+
mc.simulation_options.define_simulation_options(nsimu=nsimu, updatesigma=False)
|
|
458
|
+
|
|
459
|
+
for i, v in enumerate(theta0):
|
|
460
|
+
mc.parameters.add_model_parameter(
|
|
461
|
+
name=param_names[i],
|
|
462
|
+
theta0=v,
|
|
463
|
+
minimum=0,
|
|
464
|
+
prior_mu=v,
|
|
465
|
+
prior_sigma=max(1e-6, 0.1 * abs(v)),
|
|
466
|
+
)
|
|
467
|
+
|
|
468
|
+
mc.run_simulation()
|
|
469
|
+
|
|
470
|
+
res = mc.simulation_results.results
|
|
471
|
+
chain = np.asarray(res.get("chain"), float)
|
|
472
|
+
sschain = np.asarray(res.get("sschain"), float)
|
|
473
|
+
|
|
474
|
+
post = posterior_from_chain(chain, burn=burn)
|
|
475
|
+
picks = sample_posterior_indices(post.shape[0], nsamp=nsamp, seed=seed)
|
|
476
|
+
mcmc_sims = sims_from_chain(ctx, post, picks)
|
|
477
|
+
|
|
478
|
+
return dict(
|
|
479
|
+
post=post,
|
|
480
|
+
chain=chain,
|
|
481
|
+
sschain=sschain,
|
|
482
|
+
param_names=param_names,
|
|
483
|
+
picks=picks,
|
|
484
|
+
mcmc_sims=mcmc_sims,
|
|
485
|
+
)
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
def crm_fit_mcmc_from_df(
|
|
489
|
+
df,
|
|
490
|
+
time_col: str,
|
|
491
|
+
x_cols: List[str],
|
|
492
|
+
s_cols: List[str],
|
|
493
|
+
simulate_fn: SimulateFn,
|
|
494
|
+
params0: Optional[Dict[str, np.ndarray]] = None,
|
|
495
|
+
*,
|
|
496
|
+
lb_factor: float = 0.0,
|
|
497
|
+
ub_factor: float = 10.0, # kept for symmetry, even if not used by MCMC
|
|
498
|
+
X0: Optional[np.ndarray] = None,
|
|
499
|
+
S0: Optional[np.ndarray] = None,
|
|
500
|
+
include_metabolites: bool = True,
|
|
501
|
+
weight: str = "median",
|
|
502
|
+
n_time: int = 300,
|
|
503
|
+
fit_a: bool = False,
|
|
504
|
+
nsimu: int = 10_000,
|
|
505
|
+
sigma2: float = 12.0,
|
|
506
|
+
burn: float = 0.8,
|
|
507
|
+
nsamp: int = 200,
|
|
508
|
+
seed: int = 1234,
|
|
509
|
+
):
|
|
510
|
+
"""
|
|
511
|
+
High-level MCMC fit for CRM parameters starting from params0.
|
|
512
|
+
|
|
513
|
+
Mirrors `crm_fit_mechanistic`, but runs MCMC and returns (ctx, result_dict).
|
|
514
|
+
"""
|
|
515
|
+
# Build context and theta0 from df and params0
|
|
516
|
+
ctx, theta0, lb, ub = prepare_fit_context(
|
|
517
|
+
df=df,
|
|
518
|
+
time_col=time_col,
|
|
519
|
+
x_cols=x_cols,
|
|
520
|
+
s_cols=s_cols,
|
|
521
|
+
simulate_fn=simulate_fn,
|
|
522
|
+
params0=params0,
|
|
523
|
+
lb_factor=lb_factor,
|
|
524
|
+
ub_factor=ub_factor,
|
|
525
|
+
X0=X0,
|
|
526
|
+
S0=S0,
|
|
527
|
+
include_metabolites=include_metabolites,
|
|
528
|
+
weight=weight,
|
|
529
|
+
n_time=n_time,
|
|
530
|
+
fit_a=fit_a,
|
|
531
|
+
)
|
|
532
|
+
|
|
533
|
+
# Run MCMC around this theta0
|
|
534
|
+
mcmc_result = crm_fit_mcmc(
|
|
535
|
+
ctx=ctx,
|
|
536
|
+
theta0=theta0,
|
|
537
|
+
nsimu=nsimu,
|
|
538
|
+
sigma2=sigma2,
|
|
539
|
+
burn=burn,
|
|
540
|
+
nsamp=nsamp,
|
|
541
|
+
seed=seed,
|
|
542
|
+
)
|
|
543
|
+
|
|
544
|
+
return ctx, mcmc_result
|