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,417 @@
|
|
|
1
|
+
import matplotlib.pyplot as plt
|
|
2
|
+
import numpy as np
|
|
3
|
+
import pandas as pd
|
|
4
|
+
from scipy.interpolate import PchipInterpolator
|
|
5
|
+
|
|
6
|
+
from typing import Literal, Optional, Tuple, Sequence
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def plot_data_with_overlay(
|
|
10
|
+
df: pd.DataFrame,
|
|
11
|
+
sim=None,
|
|
12
|
+
mcmc_sims=None,
|
|
13
|
+
overlay: Literal["splines", "model", "both"] | None = "splines",
|
|
14
|
+
time_col: Optional[str] = None,
|
|
15
|
+
x_cols: Optional[Sequence[str]] = None,
|
|
16
|
+
s_cols: Optional[Sequence[str]] = None,
|
|
17
|
+
x_err_cols: Optional[Sequence[str]] = None,
|
|
18
|
+
s_err_cols: Optional[Sequence[str]] = None,
|
|
19
|
+
n_spline_points: int = 400,
|
|
20
|
+
shade_percentiles: bool = False,
|
|
21
|
+
percentiles: Tuple[float, float] = (2.5, 97.5),
|
|
22
|
+
thin_alpha: float = 0.25,
|
|
23
|
+
thin_lw: float = 0.75,
|
|
24
|
+
thick_lw: float = 2.5,
|
|
25
|
+
title: Optional[str] = None,
|
|
26
|
+
save_prefix: Optional[str] = None,
|
|
27
|
+
**kwargs,
|
|
28
|
+
):
|
|
29
|
+
"""
|
|
30
|
+
Plot the data in the given dataframe, interpreting certain columns as
|
|
31
|
+
species (X), metabolites (S), or time. If given a simulation, can plot it
|
|
32
|
+
along with the data.
|
|
33
|
+
|
|
34
|
+
:param df: The input dataframe used for fitting the model
|
|
35
|
+
:param sim:
|
|
36
|
+
A predicted simulation to plot along with the data. Should be a
|
|
37
|
+
dictionary or a ``SimpleNamespace`` object that is produced by one of
|
|
38
|
+
the ``predict`` or ``simulate`` methods in the package.
|
|
39
|
+
:param mcmc_sims: A set of MCMC simulations to visualize
|
|
40
|
+
:param overlay:
|
|
41
|
+
Whether to draw the model simulation and, additionally, whether to
|
|
42
|
+
connect the given datapoints with splines.
|
|
43
|
+
:param time_col: The name of the time column in the data
|
|
44
|
+
:param x_cols: The names of species (X) columns
|
|
45
|
+
:param s_cols: The names of metabolite (S) columns
|
|
46
|
+
:param x_err_cols: The names of species (X) error columns
|
|
47
|
+
:param s_err_cols: The names of metabolite (S) error columns
|
|
48
|
+
:param n_spline_points: Number of points to generate for the spline visualization
|
|
49
|
+
:param shade_percentiles: Whether to add colored shading to percentile bands
|
|
50
|
+
:param percentiles: What range of percentiles to shade
|
|
51
|
+
:param thin_alpha: Transparency of thin lines used to represent uncertainty
|
|
52
|
+
:param thin_lw: Line width of thin lines used to represent uncertainty
|
|
53
|
+
:param thick_lw: Line width of thick lines for splines and model simulation
|
|
54
|
+
:param title: Title of the chart
|
|
55
|
+
:param save_prefix: If given, will save images as filenames with the given prefix
|
|
56
|
+
"""
|
|
57
|
+
def compute_percentile_band(sims, key, col, t_grid, p_lo, p_hi):
|
|
58
|
+
curves = []
|
|
59
|
+
for s in sims:
|
|
60
|
+
val = _get_sim_data(s, key)
|
|
61
|
+
t_val = _get_sim_data(s, "t")
|
|
62
|
+
if val is None or t_val is None:
|
|
63
|
+
continue
|
|
64
|
+
|
|
65
|
+
y = np.asarray(val, float)
|
|
66
|
+
# Ensure shape (Time, Features)
|
|
67
|
+
if y.shape[0] != len(t_val):
|
|
68
|
+
y = y.T
|
|
69
|
+
|
|
70
|
+
if y.ndim == 1:
|
|
71
|
+
y = y[:, None]
|
|
72
|
+
if y.shape[1] <= col:
|
|
73
|
+
continue
|
|
74
|
+
|
|
75
|
+
t, y = np.asarray(t_val, float), y[:, col]
|
|
76
|
+
m = np.isfinite(t) & np.isfinite(y)
|
|
77
|
+
if m.sum() < 2:
|
|
78
|
+
continue
|
|
79
|
+
y_interp = np.maximum(
|
|
80
|
+
PchipInterpolator(t[m], y[m], extrapolate=True)(t_grid), 0.0
|
|
81
|
+
)
|
|
82
|
+
curves.append(y_interp)
|
|
83
|
+
if not curves:
|
|
84
|
+
return None
|
|
85
|
+
M = np.vstack(curves)
|
|
86
|
+
return (
|
|
87
|
+
t_grid,
|
|
88
|
+
np.nanpercentile(M, p_lo, axis=0),
|
|
89
|
+
np.nanpercentile(M, p_hi, axis=0),
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
def draw_panel(
|
|
93
|
+
ax,
|
|
94
|
+
t,
|
|
95
|
+
y,
|
|
96
|
+
name,
|
|
97
|
+
t1=None,
|
|
98
|
+
y1=None,
|
|
99
|
+
t2=None,
|
|
100
|
+
y2=None,
|
|
101
|
+
err=None,
|
|
102
|
+
ylabel=None,
|
|
103
|
+
xlabel=None,
|
|
104
|
+
thin=None,
|
|
105
|
+
band=None,
|
|
106
|
+
band_label=None,
|
|
107
|
+
):
|
|
108
|
+
if y is not None:
|
|
109
|
+
if err is not None:
|
|
110
|
+
ax.errorbar(t, y, yerr=err, fmt="o", capsize=2, label="data", zorder=100)
|
|
111
|
+
else:
|
|
112
|
+
ax.plot(t, y, "o", label="data", zorder=100)
|
|
113
|
+
if thin:
|
|
114
|
+
for tx, ty in thin:
|
|
115
|
+
ax.plot(
|
|
116
|
+
tx, ty, "-", lw=thin_lw, alpha=thin_alpha, color="0.8", zorder=5
|
|
117
|
+
)
|
|
118
|
+
if band is not None:
|
|
119
|
+
tb, lo, hi = band
|
|
120
|
+
ax.fill_between(tb, lo, hi, alpha=0.2, label=band_label, zorder=10)
|
|
121
|
+
if t1 is not None and y1 is not None:
|
|
122
|
+
ax.plot(t1, y1, "-", lw=thick_lw, label="spline", zorder=20)
|
|
123
|
+
if t2 is not None and y2 is not None:
|
|
124
|
+
ax.plot(t2, y2, "-", lw=thick_lw, label="model", zorder=30)
|
|
125
|
+
ax.set_title(name)
|
|
126
|
+
if ylabel:
|
|
127
|
+
ax.set_ylabel(ylabel)
|
|
128
|
+
if xlabel:
|
|
129
|
+
ax.set_xlabel(xlabel)
|
|
130
|
+
ax.legend()
|
|
131
|
+
|
|
132
|
+
# Prepare Data
|
|
133
|
+
t_data = np.asarray(df[time_col], float)
|
|
134
|
+
X_data = np.column_stack([df[c].astype(float) for c in x_cols])
|
|
135
|
+
X_err = None
|
|
136
|
+
if x_err_cols:
|
|
137
|
+
X_err = np.column_stack([(df[c].astype(float) if c in df else np.nan) for c in x_err_cols])
|
|
138
|
+
|
|
139
|
+
valid_scols = [c for c in (s_cols or []) if c in df.columns]
|
|
140
|
+
S_data = (
|
|
141
|
+
np.column_stack([df[c].astype(float) for c in valid_scols])
|
|
142
|
+
if valid_scols
|
|
143
|
+
else None
|
|
144
|
+
)
|
|
145
|
+
S_err = None
|
|
146
|
+
if s_err_cols:
|
|
147
|
+
S_err = (
|
|
148
|
+
np.column_stack([(df[c].astype(float) if c in df else np.nan) for c in s_err_cols])
|
|
149
|
+
if valid_scols
|
|
150
|
+
else None
|
|
151
|
+
)
|
|
152
|
+
n, m_data = X_data.shape[1], 0 if S_data is None else S_data.shape[1]
|
|
153
|
+
|
|
154
|
+
# Prepare Model
|
|
155
|
+
t_model = X_model = S_model = None
|
|
156
|
+
if overlay in ("model", "both"):
|
|
157
|
+
if sim is None:
|
|
158
|
+
raise ValueError("overlay='model' or 'both' requires a sim dict/object.")
|
|
159
|
+
|
|
160
|
+
t_model = np.asarray(_get_sim_data(sim, "t"), float)
|
|
161
|
+
X_temp = np.asarray(_get_sim_data(sim, "X"), float)
|
|
162
|
+
S_temp = _get_sim_data(sim, "S")
|
|
163
|
+
S_temp = np.asarray(S_temp, float) if S_temp is not None else None
|
|
164
|
+
|
|
165
|
+
# FIX: Auto-Transpose if shapes are flipped
|
|
166
|
+
# We expect (Time, Species). If we get (Species, Time), flip it.
|
|
167
|
+
if X_temp.shape[0] != len(t_model):
|
|
168
|
+
X_temp = X_temp.T
|
|
169
|
+
if S_temp is not None and S_temp.shape[0] != len(t_model):
|
|
170
|
+
S_temp = S_temp.T
|
|
171
|
+
|
|
172
|
+
X_model = np.clip(X_temp, 0, None)
|
|
173
|
+
S_model = np.clip(S_temp, 0, None) if S_temp is not None else None
|
|
174
|
+
|
|
175
|
+
m_model = 0 if S_model is None else S_model.shape[1]
|
|
176
|
+
m = max(m_data, m_model)
|
|
177
|
+
metab_names = (s_cols or valid_scols or [f"S{j}" for j in range(m)])[:m]
|
|
178
|
+
|
|
179
|
+
t_dense = np.linspace(np.nanmin(t_data), np.nanmax(t_data), n_spline_points)
|
|
180
|
+
X_splines = (
|
|
181
|
+
[_nonneg_pchip(t_data, X_data[:, i])(t_dense) for i in range(n)]
|
|
182
|
+
if overlay in ("splines", "both")
|
|
183
|
+
else None
|
|
184
|
+
)
|
|
185
|
+
S_splines = (
|
|
186
|
+
[_nonneg_pchip(t_data, S_data[:, j])(t_dense) for j in range(m_data)]
|
|
187
|
+
if S_data is not None and overlay in ("splines", "both")
|
|
188
|
+
else None
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
# Prepare MCMC Thin Lines
|
|
192
|
+
thin_species = []
|
|
193
|
+
thin_metabs = [[] for _ in range(m)]
|
|
194
|
+
if mcmc_sims:
|
|
195
|
+
for s in mcmc_sims:
|
|
196
|
+
t_s = _get_sim_data(s, "t")
|
|
197
|
+
X_s = _get_sim_data(s, "X")
|
|
198
|
+
S_s = _get_sim_data(s, "S")
|
|
199
|
+
|
|
200
|
+
# Auto-Transpose MCMC samples too
|
|
201
|
+
if X_s.shape[0] != len(t_s):
|
|
202
|
+
X_s = X_s.T
|
|
203
|
+
if S_s is not None and S_s.shape[0] != len(t_s):
|
|
204
|
+
S_s = S_s.T
|
|
205
|
+
|
|
206
|
+
if "X" in s:
|
|
207
|
+
for i in range(min(n, X_s.shape[1])):
|
|
208
|
+
thin_species.append((t_s, X_s[:, i]))
|
|
209
|
+
if "S" in s:
|
|
210
|
+
for j in range(min(m, S_s.shape[1])):
|
|
211
|
+
thin_metabs[j].append((t_s, S_s[:, j]))
|
|
212
|
+
|
|
213
|
+
band_lbl = f"{percentiles[0]}–{percentiles[1]}% band"
|
|
214
|
+
species_bands = [None] * n
|
|
215
|
+
metab_bands = [None] * m
|
|
216
|
+
if mcmc_sims and shade_percentiles:
|
|
217
|
+
p_lo, p_hi = percentiles
|
|
218
|
+
tgrid_sp = t_model if t_model is not None else t_dense
|
|
219
|
+
for i in range(n):
|
|
220
|
+
species_bands[i] = compute_percentile_band(
|
|
221
|
+
mcmc_sims, "X", i, tgrid_sp, p_lo, p_hi
|
|
222
|
+
)
|
|
223
|
+
if m:
|
|
224
|
+
tgrid_met = t_model if S_model is not None else t_dense
|
|
225
|
+
for j in range(m):
|
|
226
|
+
metab_bands[j] = compute_percentile_band(
|
|
227
|
+
mcmc_sims, "S", j, tgrid_met, p_lo, p_hi
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
# Plot Species
|
|
231
|
+
ncols, nrows = min(3, n), int(np.ceil(n / min(3, n)))
|
|
232
|
+
fig, axes = plt.subplots(
|
|
233
|
+
nrows, ncols, figsize=(6 * ncols, 3.2 * nrows), sharex=True
|
|
234
|
+
)
|
|
235
|
+
axes = np.atleast_1d(axes).ravel()
|
|
236
|
+
for i, ax in enumerate(axes[:n]):
|
|
237
|
+
t1, y1 = (t_dense, X_splines[i]) if X_splines else (None, None)
|
|
238
|
+
t2, y2 = (
|
|
239
|
+
(t_model, X_model[:, i])
|
|
240
|
+
if X_model is not None and X_model.shape[1] > i
|
|
241
|
+
else (None, None)
|
|
242
|
+
)
|
|
243
|
+
err = None
|
|
244
|
+
if X_err is not None:
|
|
245
|
+
err = X_err[:, i]
|
|
246
|
+
draw_panel(
|
|
247
|
+
ax,
|
|
248
|
+
t_data,
|
|
249
|
+
X_data[:, i],
|
|
250
|
+
x_cols[i],
|
|
251
|
+
t1,
|
|
252
|
+
y1,
|
|
253
|
+
t2,
|
|
254
|
+
y2,
|
|
255
|
+
err,
|
|
256
|
+
"counts",
|
|
257
|
+
time_col,
|
|
258
|
+
thin_species,
|
|
259
|
+
species_bands[i],
|
|
260
|
+
band_lbl if species_bands[i] else None,
|
|
261
|
+
)
|
|
262
|
+
for ax in axes[n:]:
|
|
263
|
+
ax.axis("off")
|
|
264
|
+
if title:
|
|
265
|
+
fig.suptitle(title)
|
|
266
|
+
|
|
267
|
+
if save_prefix:
|
|
268
|
+
plt.savefig(f"{save_prefix}_species.png", dpi=300, bbox_inches="tight")
|
|
269
|
+
|
|
270
|
+
fig.tight_layout()
|
|
271
|
+
|
|
272
|
+
# Plot Metabolites
|
|
273
|
+
if m > 0:
|
|
274
|
+
ncols, nrows = min(3, m), int(np.ceil(m / min(3, m)))
|
|
275
|
+
fig, axes = plt.subplots(
|
|
276
|
+
nrows, ncols, figsize=(6 * ncols, 3.2 * nrows), sharex=True
|
|
277
|
+
)
|
|
278
|
+
axes = np.atleast_1d(axes).ravel()
|
|
279
|
+
for j, ax in enumerate(axes[:m]):
|
|
280
|
+
y_data = S_data[:, j] if S_data is not None and j < m_data else None
|
|
281
|
+
err = S_err[:, j] if S_err is not None and j < m_data else None
|
|
282
|
+
t1, y1 = (
|
|
283
|
+
(t_dense, S_splines[j])
|
|
284
|
+
if S_splines and j < len(S_splines)
|
|
285
|
+
else (None, None)
|
|
286
|
+
)
|
|
287
|
+
t2, y2 = (
|
|
288
|
+
(t_model, S_model[:, j])
|
|
289
|
+
if S_model is not None and S_model.shape[1] > j
|
|
290
|
+
else (None, None)
|
|
291
|
+
)
|
|
292
|
+
thin_j = thin_metabs[j] if thin_metabs and j < len(thin_metabs) else None
|
|
293
|
+
draw_panel(
|
|
294
|
+
ax,
|
|
295
|
+
t_data,
|
|
296
|
+
y_data,
|
|
297
|
+
metab_names[j],
|
|
298
|
+
t1,
|
|
299
|
+
y1,
|
|
300
|
+
t2,
|
|
301
|
+
y2,
|
|
302
|
+
err,
|
|
303
|
+
"concentration",
|
|
304
|
+
time_col,
|
|
305
|
+
thin_j,
|
|
306
|
+
metab_bands[j],
|
|
307
|
+
band_lbl if metab_bands[j] else None,
|
|
308
|
+
)
|
|
309
|
+
for ax in axes[m:]:
|
|
310
|
+
ax.axis("off")
|
|
311
|
+
if title:
|
|
312
|
+
fig.suptitle(title)
|
|
313
|
+
fig.tight_layout()
|
|
314
|
+
|
|
315
|
+
if save_prefix:
|
|
316
|
+
plt.savefig(f"{save_prefix}_metabolites.png", dpi=300, bbox_inches="tight")
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def plot_mcmc_error_evolution(sschain, save_prefix=None):
|
|
320
|
+
"""
|
|
321
|
+
Plot a visualization of the sum-of-squares error chain produced as the
|
|
322
|
+
result of a MCMC fitting process.
|
|
323
|
+
|
|
324
|
+
:param sschain: The chain object generated by MCMC functions in the package
|
|
325
|
+
:param save_prefix: If given, will save images as filenames with the given prefix
|
|
326
|
+
"""
|
|
327
|
+
|
|
328
|
+
if sschain is None:
|
|
329
|
+
print("No sschain provided; skipping error plot.")
|
|
330
|
+
return
|
|
331
|
+
plt.figure(figsize=(6, 3.8))
|
|
332
|
+
plt.plot(np.asarray(sschain).ravel())
|
|
333
|
+
plt.xlabel("iteration")
|
|
334
|
+
plt.ylabel("sum-of-squares (error)")
|
|
335
|
+
plt.title("MCMC error evolution")
|
|
336
|
+
plt.tight_layout()
|
|
337
|
+
|
|
338
|
+
if save_prefix:
|
|
339
|
+
plt.savefig(f"{save_prefix}.png", dpi=300, bbox_inches="tight")
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def plot_parameter_distributions(
|
|
343
|
+
post,
|
|
344
|
+
theta_mle: Optional[Sequence[float]] = None,
|
|
345
|
+
names: Optional[Sequence[str]] = None,
|
|
346
|
+
bins=40,
|
|
347
|
+
save_prefix=None,
|
|
348
|
+
):
|
|
349
|
+
"""
|
|
350
|
+
Plot the posterior parameter distributions found by the MCMC fitting
|
|
351
|
+
process as histograms.
|
|
352
|
+
|
|
353
|
+
:param post:
|
|
354
|
+
Posterior parameter distribution, as generated from the fitting
|
|
355
|
+
functions in the package.
|
|
356
|
+
:param theta_mle: A list of maximum likelihood estimates of the parameters
|
|
357
|
+
:param names: The names of the plotted parameters
|
|
358
|
+
:param bins: Number of bins to use for the histograms
|
|
359
|
+
:param save_prefix: If given, will save images as filenames with the given prefix
|
|
360
|
+
"""
|
|
361
|
+
|
|
362
|
+
post = np.asarray(post, float)
|
|
363
|
+
npar = post.shape[1]
|
|
364
|
+
if names is None:
|
|
365
|
+
names = [f"theta_{i + 1}" for i in range(npar)]
|
|
366
|
+
|
|
367
|
+
ncols = 3 if npar >= 3 else max(1, npar)
|
|
368
|
+
nrows = int(np.ceil(npar / ncols))
|
|
369
|
+
fig, axes = plt.subplots(nrows, ncols, figsize=(4 * ncols, 3.5 * nrows))
|
|
370
|
+
axes = np.atleast_1d(axes).ravel()
|
|
371
|
+
|
|
372
|
+
for i in range(npar):
|
|
373
|
+
ax = axes[i]
|
|
374
|
+
ax.hist(post[:, i], bins=bins, density=True)
|
|
375
|
+
if theta_mle is not None and np.isfinite(theta_mle[i]):
|
|
376
|
+
ax.axvline(float(theta_mle[i]), linestyle="--")
|
|
377
|
+
ax.set_title(names[i])
|
|
378
|
+
ax.set_xlabel("value")
|
|
379
|
+
ax.set_ylabel("density")
|
|
380
|
+
|
|
381
|
+
for k in range(npar, len(axes)):
|
|
382
|
+
fig.delaxes(axes[k])
|
|
383
|
+
|
|
384
|
+
fig.suptitle("Posterior parameter distributions", y=0.98)
|
|
385
|
+
fig.tight_layout()
|
|
386
|
+
|
|
387
|
+
if save_prefix:
|
|
388
|
+
plt.savefig(f"{save_prefix}.png", dpi=300, bbox_inches="tight")
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def _get_sim_data(sim_obj, key):
|
|
392
|
+
"Helper to extract Data from Sim Object"
|
|
393
|
+
|
|
394
|
+
if sim_obj is None:
|
|
395
|
+
return None
|
|
396
|
+
# Handle Dictionary
|
|
397
|
+
if isinstance(sim_obj, dict):
|
|
398
|
+
return sim_obj.get(key)
|
|
399
|
+
# Handle SimpleNamespace (like .t, .X, .S)
|
|
400
|
+
if hasattr(sim_obj, key):
|
|
401
|
+
return getattr(sim_obj, key)
|
|
402
|
+
return None
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def _nonneg_pchip(x, y):
|
|
406
|
+
x, y = np.asarray(x, float), np.asarray(y, float)
|
|
407
|
+
m = np.isfinite(x) & np.isfinite(y)
|
|
408
|
+
if not np.any(m):
|
|
409
|
+
return lambda z: np.zeros_like(np.atleast_1d(z))
|
|
410
|
+
x2, y2 = (
|
|
411
|
+
np.unique(x[m], return_index=False),
|
|
412
|
+
y[m][np.unique(x[m], return_index=True)[1]],
|
|
413
|
+
)
|
|
414
|
+
if len(x2) == 1:
|
|
415
|
+
return lambda z: np.full_like(np.atleast_1d(z), max(y2[0], 0.0))
|
|
416
|
+
p = PchipInterpolator(x2, y2, extrapolate=True)
|
|
417
|
+
return lambda z: np.maximum(p(z), 0.0)
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
import pandas as pd
|
|
5
|
+
|
|
6
|
+
from ..models.base import ModelNames
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def save_simulation_results(sim, names: ModelNames, output_path: str):
|
|
10
|
+
"""
|
|
11
|
+
Universal saver for 1-species or N-species simulations.
|
|
12
|
+
|
|
13
|
+
:param sim:
|
|
14
|
+
A dictionary or SimpleNamespace with .t, .X, and .S properties holding
|
|
15
|
+
simulation values. The `simulate` and `predict` methods of models and
|
|
16
|
+
controllers produce compatible objects.
|
|
17
|
+
:param names:
|
|
18
|
+
A `ModelNames` object containing the column names of consumers (X) and
|
|
19
|
+
substrates (S)
|
|
20
|
+
:param output_path:
|
|
21
|
+
The name of the CSV file to save the data in, e.g. "simulation.csv"
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
# 1. Extract Data safely
|
|
25
|
+
def get_arr(obj, key):
|
|
26
|
+
if isinstance(obj, dict):
|
|
27
|
+
return np.array(obj.get(key, []))
|
|
28
|
+
return np.array(getattr(obj, key)) if hasattr(obj, key) else np.array([])
|
|
29
|
+
|
|
30
|
+
t = get_arr(sim, "t")
|
|
31
|
+
X = get_arr(sim, "X")
|
|
32
|
+
S = get_arr(sim, "S")
|
|
33
|
+
|
|
34
|
+
# 2. Universal Shape Fix (The Critical Change)
|
|
35
|
+
# Ensure t is at least 1D
|
|
36
|
+
t = np.atleast_1d(t)
|
|
37
|
+
|
|
38
|
+
# If X is 1D (Single Species), make it 2D: (N,) -> (N, 1)
|
|
39
|
+
if X.ndim == 1:
|
|
40
|
+
X = X[:, np.newaxis]
|
|
41
|
+
|
|
42
|
+
# If S is 1D, make it 2D
|
|
43
|
+
if S.ndim == 1:
|
|
44
|
+
S = S[:, np.newaxis]
|
|
45
|
+
|
|
46
|
+
# 3. Auto-Transpose
|
|
47
|
+
# Ensure rows = timepoints. If not, flip it.
|
|
48
|
+
if X.shape[0] != len(t):
|
|
49
|
+
X = X.T
|
|
50
|
+
if S.size > 0 and S.shape[0] != len(t):
|
|
51
|
+
S = S.T
|
|
52
|
+
|
|
53
|
+
# 4. Create DataFrame
|
|
54
|
+
data = {"Time (hours)": t}
|
|
55
|
+
|
|
56
|
+
# Species Columns
|
|
57
|
+
for i, name in enumerate(names.X):
|
|
58
|
+
if i < X.shape[1]:
|
|
59
|
+
data[name] = X[:, i]
|
|
60
|
+
|
|
61
|
+
# Metabolite Columns
|
|
62
|
+
for j, name in enumerate(names.S):
|
|
63
|
+
if S.size > 0 and j < S.shape[1]:
|
|
64
|
+
data[name] = S[:, j]
|
|
65
|
+
|
|
66
|
+
# 5. Save
|
|
67
|
+
df_out = pd.DataFrame(data)
|
|
68
|
+
output_path = os.path.abspath(output_path)
|
|
69
|
+
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
|
70
|
+
df_out.to_csv(output_path, index=False)
|
|
71
|
+
print(f"[Saved CSV] {output_path}")
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: mgrowthctrl
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: mgrowthctrl is a software package for modeling, visualization, and control of microbiome growth dynamics. It provides tools to simulate microbial community dynamics, fit predictive models to experimental data, and steer community composition using control and optimization methods.
|
|
5
|
+
Project-URL: Homepage, https://gitlab.com/ComputationalScience/mgrowthctrl
|
|
6
|
+
Project-URL: Documentation, https://mgrowthctrl.readthedocs.io/en/latest/
|
|
7
|
+
Project-URL: Issues, https://gitlab.com/ComputationalScience/mgrowthctrl/-/issues
|
|
8
|
+
Author-email: Indrah Thelaganathan <indrah2003@gmail.com>, Andrew Radev <andrey.radev@gmail.com>, Jiawei Li <pushup-prong-ashen@duck.com>, Lucas Boettcher <l.boettcher@fs.de>
|
|
9
|
+
License: MIT License
|
|
10
|
+
|
|
11
|
+
Copyright (c) 2021 Jiawei Li, Thomas Asikis, Ioannis Fragkos, and Lucas Boettcher
|
|
12
|
+
|
|
13
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
14
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
15
|
+
in the Software without restriction, including without limitation the rights
|
|
16
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
17
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
18
|
+
furnished to do so, subject to the following conditions:
|
|
19
|
+
|
|
20
|
+
The above copyright notice and this permission notice shall be included in all
|
|
21
|
+
copies or substantial portions of the Software.
|
|
22
|
+
|
|
23
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
24
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
25
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
26
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
27
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
28
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
29
|
+
SOFTWARE.
|
|
30
|
+
License-File: LICENSE
|
|
31
|
+
Keywords: dynamic control,growth dynamics,machine learning,microbiome,neural networks
|
|
32
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
33
|
+
Classifier: Operating System :: OS Independent
|
|
34
|
+
Classifier: Programming Language :: Python :: 3
|
|
35
|
+
Requires-Python: >=3.10
|
|
36
|
+
Requires-Dist: matplotlib>=3.7.1
|
|
37
|
+
Requires-Dist: numpy<2.0,>=1.26
|
|
38
|
+
Requires-Dist: pandas>=2.0
|
|
39
|
+
Requires-Dist: pymcmcstat>=1.9.0
|
|
40
|
+
Requires-Dist: requests>=2.31.0
|
|
41
|
+
Requires-Dist: scipy>=1.10
|
|
42
|
+
Requires-Dist: tensorboard>=2.12
|
|
43
|
+
Requires-Dist: torch>=2.5
|
|
44
|
+
Requires-Dist: torchdiffeq>=0.2.2
|
|
45
|
+
Description-Content-Type: text/markdown
|
|
46
|
+
|
|
47
|
+

|
|
48
|
+

|
|
49
|
+
|
|
50
|
+
# mgrowthctrl
|
|
51
|
+
|
|
52
|
+
A Python package for parameter inference, mechanistic microbiome modeling, and control, based on a consumer–resource model (CRM).
|
|
53
|
+
|
|
54
|
+
Detailed documentation is available at [Documentation](https://mgrowthctrl.readthedocs.io/en/latest/).
|
|
55
|
+
|
|
56
|
+
Key features of mgrowthctrl include:
|
|
57
|
+
|
|
58
|
+
- An API for defining and simulating ODE-based microbiome dynamics.
|
|
59
|
+
- A data loader that allows users to retrieve data from [mGrowthDB](https://mgrowthdb.gbiomed.kuleuven.be).
|
|
60
|
+
- A parameter estimation backend offering both least-squares and Markov Chain Monte Carlo (MCMC) optimization.
|
|
61
|
+
- Built-in visualization utilities for evaluating trajectories and analyzing posteriors.
|
|
62
|
+
- A controller framework based on neural ODEs.
|
|
63
|
+
- A modular architecture designed to facilitate the extension and integration of custom models, controllers, and data processing workflows.
|
|
64
|
+
|
|
65
|
+
## Features
|
|
66
|
+
|
|
67
|
+
### Models
|
|
68
|
+
- An implementation of a CRM (`CRModel`).
|
|
69
|
+
- Scalable design supporting both single-species and multi-species systems.
|
|
70
|
+
- A unified engine (`BaseODEModel`) with NumPy and PyTorch backends.
|
|
71
|
+
- Extensible base classes enabling straightforward implementation of custom ODE models.
|
|
72
|
+
|
|
73
|
+
### Controllers
|
|
74
|
+
- `BaseController` provides an abstract interface with `simulate` and `fit` methods.
|
|
75
|
+
- `OpenLoopNeuralController` implements time-dependent control functions.
|
|
76
|
+
- `ClosedLoopNeuralController` implements state-dependent control functions.
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
### Fitting Backend
|
|
80
|
+
- Least-squares parameter optimization (`crm_fit_mechanistic`).
|
|
81
|
+
- Bayesian parameter inference through MCMC sampling (`crm_fit_mcmc`).
|
|
82
|
+
|
|
83
|
+
### Plotting
|
|
84
|
+
- Tools for visualizing coupled metabolite and species population dynamics.
|
|
85
|
+
- Plots of empirical data, spline interpolations, and simulated trajectories.
|
|
86
|
+
- Integration of MCMC outputs to show credible intervals.
|
|
87
|
+
|
|
88
|
+
## Code Structure
|
|
89
|
+
|
|
90
|
+
```graphql
|
|
91
|
+
src/mgrowthctrl/
|
|
92
|
+
│
|
|
93
|
+
├── backends/
|
|
94
|
+
│ ├── array.py # Array backend interfaces for NumPy and PyTorch
|
|
95
|
+
│ └── __init__.py
|
|
96
|
+
│
|
|
97
|
+
├── controllers/
|
|
98
|
+
│ ├── base.py # BaseController interface with simulate and fit methods
|
|
99
|
+
│ ├── closed_loop.py # ClosedLoopNeuralController
|
|
100
|
+
│ └── open_loop.py # OpenLoopNeuralController
|
|
101
|
+
│
|
|
102
|
+
├── models/
|
|
103
|
+
│ ├── base.py # ODE base class (uses dependency injection)
|
|
104
|
+
│ └── crm/
|
|
105
|
+
│ ├── fit.py # LSQ + MCMC fitting engine
|
|
106
|
+
│ ├── model.py # Mechanistic CRM using BaseODEModel
|
|
107
|
+
│ └── utils.py # Shared utilities
|
|
108
|
+
│
|
|
109
|
+
├── utils/
|
|
110
|
+
│ ├── data.py # Data loading functions with a public DataLoader-style API
|
|
111
|
+
│ ├── plot.py # Plotting utilities
|
|
112
|
+
│ ├── save.py # Saving / loading utilities
|
|
113
|
+
│ └── __init__.py
|
|
114
|
+
│
|
|
115
|
+
└── __init__.py
|
|
116
|
+
```
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
mgrowthctrl/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
mgrowthctrl/backends/__init__.py,sha256=6ubxs1aSjOQiISBBQfCnT7DMqVdYHZcGLZQzjIf7stE,163
|
|
3
|
+
mgrowthctrl/backends/array.py,sha256=48NcUdJfQjnadGbDlKtquD6BdAyIzHMl6xPLacMPLgE,4941
|
|
4
|
+
mgrowthctrl/controllers/__init__.py,sha256=dPiZZvEAxclgL3KXvi_paUUYH1RhpBo5LsSKc1mqZrc,236
|
|
5
|
+
mgrowthctrl/controllers/base.py,sha256=VSX2fq6joe7IyI7KZ35XAqo2mspVZ2LmqTtZMTHZd7U,9389
|
|
6
|
+
mgrowthctrl/controllers/closed_loop.py,sha256=u2RUyA_sl4Rll_gj9qdnMhGoKEf9LlGmjTcP3X-zjd8,6798
|
|
7
|
+
mgrowthctrl/controllers/open_loop.py,sha256=7rzhKTf5udispvS42dxOojbUJRYrUd8wm9r8L82EpV8,5685
|
|
8
|
+
mgrowthctrl/models/__init__.py,sha256=OS_BBHaqR3L2RJpXMHWhhRgDwsHMAFSMdRFAXaFbd1U,89
|
|
9
|
+
mgrowthctrl/models/base.py,sha256=IgJt70hjfRl6XWRh3Gxa3SydLDuIb6e1GU8Hg3FVMLk,11092
|
|
10
|
+
mgrowthctrl/models/crm/fit.py,sha256=pNqyezhKVkYtO15HuDi2xbx55IvQDhvP2TeFhJQ5Bvs,15712
|
|
11
|
+
mgrowthctrl/models/crm/model.py,sha256=YO1wttcp_ksyS7AoXliXJAKDiGYpqP79FOCqVJ31Y80,18030
|
|
12
|
+
mgrowthctrl/models/crm/utils.py,sha256=ahmASWue3ETEv0bj9-7XeuqHD17BAhQxr87afNUkrmg,14597
|
|
13
|
+
mgrowthctrl/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
14
|
+
mgrowthctrl/utils/data.py,sha256=5g_kUDyPn386Nah7IddIDmt3DWucvfefrC3xZeYwCJ4,19745
|
|
15
|
+
mgrowthctrl/utils/plot.py,sha256=oZrthpLpPE-i5sKWjtFTlcUGdqrZ5SrZNP0wRY-C4MU,14152
|
|
16
|
+
mgrowthctrl/utils/save.py,sha256=opCkieinFRWt2coqJ3UNm8fYrXoGOPKA8WGAv6_Mdpo,2013
|
|
17
|
+
mgrowthctrl-0.1.0.dist-info/METADATA,sha256=W1UWPvxpCNYD2DMuwjimz6OZZ1Muj-s5SDdj-cfaH0Y,5622
|
|
18
|
+
mgrowthctrl-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
|
|
19
|
+
mgrowthctrl-0.1.0.dist-info/licenses/LICENSE,sha256=1rx2EY_ZFy1gZHPZoQXPzjEhHMXuR6GUF7PewmWRRi4,1118
|
|
20
|
+
mgrowthctrl-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2021 Jiawei Li, Thomas Asikis, Ioannis Fragkos, and Lucas Boettcher
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|