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.
@@ -0,0 +1,555 @@
1
+ from dataclasses import dataclass
2
+ from types import SimpleNamespace
3
+ from typing import Callable, Dict, List, Literal, Optional, Union, Any
4
+
5
+ import numpy as np
6
+ import pandas as pd
7
+
8
+ from ...backends import ArrayBackend, ArrayLike
9
+ from ..base import BaseODEModel, ModelNames
10
+ from .fit import crm_fit_mcmc_from_df, crm_fit_mechanistic
11
+ from .utils import init_params_single_species
12
+
13
+ DType = float | Callable[[float], float]
14
+ "The type of the D parameter: Either a constant value or a function of time"
15
+
16
+ ParamsDict = Dict[str, np.ndarray | DType]
17
+ """
18
+ The type of the param dictionary, with most of its values as ndarrays and the
19
+ dilution rate given as a float or time-dependent value.
20
+ """
21
+
22
+ @dataclass
23
+ class CRModelParams:
24
+ """
25
+ Container for CRM parameters.
26
+
27
+ Dimensions:
28
+ * n = number of species (consumers)
29
+ * m = number of resources (metabolites)
30
+ """
31
+
32
+ r: np.ndarray
33
+ "Max growth rates (n, m)"
34
+
35
+ a: np.ndarray
36
+ "Resource uptake rates per unit growth (n, m)"
37
+
38
+ b: np.ndarray
39
+ "Metabolic byproduct secretion rates (n, m)"
40
+
41
+ K_ij: np.ndarray
42
+ "Half-saturation constants (n, m)"
43
+
44
+ k: np.ndarray
45
+ "Maintenance/death rates per species (n,)"
46
+
47
+ S_in: np.ndarray
48
+ "Inflow resource concentrations (m,)"
49
+
50
+ D: DType
51
+ "Dilution rate (outflow), either as a constant, or as a function of time"
52
+
53
+ @staticmethod
54
+ def from_shapes(
55
+ n: int, m: int, *, init: float = 0.0, D: float = 0.0
56
+ ) -> "CRModelParams":
57
+ """Initialize parameters with simple constants."""
58
+ z_nm = np.full((n, m), init, dtype=float)
59
+ return CRModelParams(
60
+ r=z_nm.copy(),
61
+ a=z_nm.copy(),
62
+ b=z_nm.copy(),
63
+ K_ij=np.full((n, m), 1.0, dtype=float),
64
+ k=np.full(n, init, dtype=float),
65
+ S_in=np.full(m, 0.0, dtype=float),
66
+ D=D,
67
+ )
68
+
69
+ def as_dict(self) -> ParamsDict:
70
+ """Return params as a dict compatible with crm_fit_backend."""
71
+ return {
72
+ "r": self.r,
73
+ "a": self.a,
74
+ "b": self.b,
75
+ "K_ij": self.K_ij,
76
+ "k": self.k,
77
+ "S_in": self.S_in,
78
+ "D": self.D,
79
+ }
80
+
81
+
82
+ class CRModel(BaseODEModel):
83
+ """
84
+ Monod-style Consumer–Resource model using the BaseODEModel.
85
+ """
86
+
87
+ def __init__(
88
+ self,
89
+ names: ModelNames,
90
+ params: CRModelParams,
91
+ backend: Union[str, ArrayBackend] = "numpy",
92
+ ):
93
+ super().__init__(backend=backend, names=names)
94
+ self.set_params(params)
95
+ self._fit_info: Optional[Dict] = None
96
+
97
+ @staticmethod
98
+ def from_dict(
99
+ d: Dict[str, Any],
100
+ backend: str = "numpy"
101
+ ) -> "CRModel":
102
+ """Rebuild a CRModel from a dict produced by to_dict()."""
103
+ names = ModelNames(X=list(d["names"]["X"]), S=list(d["names"]["S"]))
104
+ params = CRModelParams(
105
+ r=np.asarray(d["r"], dtype=float),
106
+ a=np.asarray(d["a"], dtype=float),
107
+ b=np.asarray(d["b"], dtype=float),
108
+ K_ij=np.asarray(d["K_ij"], dtype=float),
109
+ k=np.asarray(d["k"], dtype=float),
110
+ S_in=np.asarray(d["S_in"], dtype=float),
111
+ D=d["D"],
112
+ )
113
+ return CRModel(names=names, params=params, backend=backend)
114
+
115
+ @classmethod
116
+ def from_single_species_data(
117
+ cls,
118
+ df,
119
+ time_col: str,
120
+ x_col: str,
121
+ s_cols: List[str],
122
+ *,
123
+ K_prefactor: float = 2.0,
124
+ fit_a: bool = True,
125
+ n_spline_points: int = 400,
126
+ r_mask=None,
127
+ b_mask=None,
128
+ a_mask=None,
129
+ backend: Union[str, ArrayBackend] = "numpy",
130
+ ) -> "CRModel":
131
+ """
132
+ Build a single-species CRM with mechanistic initial parameters derived
133
+ from data. This also attaches the data (_df, _time_col, _x_cols,
134
+ _s_cols) to the model instance so subsequent .fit() calls don't need
135
+ arguments.
136
+ """
137
+ init = init_params_single_species(
138
+ df=df,
139
+ time_col=time_col,
140
+ x_col=x_col,
141
+ s_cols=s_cols,
142
+ K_prefactor=K_prefactor,
143
+ fit_a=fit_a,
144
+ n_spline_points=n_spline_points,
145
+ r_mask=r_mask,
146
+ b_mask=b_mask,
147
+ a_mask=a_mask,
148
+ )
149
+ p = init["params"]
150
+ names = ModelNames(X=[x_col], S=list(s_cols))
151
+ params = CRModelParams(
152
+ r=np.asarray(p["r"], dtype=float),
153
+ a=np.asarray(p["a"], dtype=float),
154
+ b=np.asarray(p["b"], dtype=float),
155
+ K_ij=np.asarray(p["K_ij"], dtype=float),
156
+ k=np.asarray(p["k"], dtype=float),
157
+ S_in=np.asarray(p["S_in"], dtype=float),
158
+ D=p["D"],
159
+ )
160
+
161
+ model = cls(names=names, params=params, backend=backend)
162
+
163
+ # Attach data for convenience defaults later
164
+ model._df = df
165
+ model._time_col = time_col
166
+ model._x_cols = [x_col]
167
+ model._s_cols = s_cols
168
+
169
+ return model
170
+
171
+ # Parameter Management
172
+ def set_params(self, params: CRModelParams) -> "CRModel":
173
+ """Set internal parameter arrays from a CRModelParams instance."""
174
+ n, m = self.n, self.m
175
+ self.r = np.asarray(params.r, dtype=float).reshape(n, m)
176
+ self.a = np.asarray(params.a, dtype=float).reshape(n, m)
177
+ self.b = np.asarray(params.b, dtype=float).reshape(n, m)
178
+ self.K_ij = np.asarray(params.K_ij, dtype=float).reshape(n, m)
179
+ self.k = np.asarray(params.k, dtype=float).reshape(n)
180
+ self.S_in = np.asarray(params.S_in, dtype=float).reshape(m)
181
+ self.D = params.D
182
+ return self
183
+
184
+ def get_params(self) -> CRModelParams:
185
+ """Return a copy of the current parameters."""
186
+ return CRModelParams(
187
+ r=self.r.copy(),
188
+ a=self.a.copy(),
189
+ b=self.b.copy(),
190
+ K_ij=self.K_ij.copy(),
191
+ k=self.k.copy(),
192
+ S_in=self.S_in.copy(),
193
+ D=self.D,
194
+ )
195
+
196
+ def _set_params_from_dict(self, p: Dict[str, Any]) -> None:
197
+ """Helper: set params from a dict coming from crm_fit_backend."""
198
+ n, m = self.n, self.m
199
+ self.r = np.asarray(p["r"], dtype=float).reshape(n, m)
200
+ self.a = np.asarray(p["a"], dtype=float).reshape(n, m)
201
+ self.b = np.asarray(p["b"], dtype=float).reshape(n, m)
202
+ self.K_ij = np.asarray(p["K_ij"], dtype=float).reshape(n, m)
203
+ self.k = np.asarray(p["k"], dtype=float).reshape(n)
204
+ self.S_in = np.asarray(p["S_in"], dtype=float).reshape(m)
205
+ self.D = p["D"]
206
+
207
+ def _D_at(self, t):
208
+ return self.D(t) if callable(self.D) else float(self.D)
209
+
210
+ # RHS Implementation (NumPy + Torch)
211
+ def compute_rhs(self, t, X, S):
212
+ """
213
+ Compute dX/dt, dS/dt given X, S using current parameters.
214
+ """
215
+ B = self.backend
216
+ X = B.ensure_1d(X)
217
+ S = B.ensure_1d(S)
218
+
219
+ D = self._D_at(t)
220
+
221
+ # NumPy Backend
222
+ if B.xp_name == "numpy":
223
+ Srow = np.asarray(S)[None, :] # Shape: 1×m
224
+ mon_frac = Srow / (Srow + self.K_ij) # Shape: n×m
225
+ mon = self.r * mon_frac # Shape: n×m
226
+ growth = mon.sum(axis=1) # Shape: (n,)
227
+
228
+ dX_dt = (growth - self.k - D) * np.asarray(X)
229
+
230
+ # Secretion sum over species (columns) -> (m,)
231
+ secretion = (self.b * np.asarray(X)[:, None]).sum(axis=0)
232
+ # Uptake sum over species -> (m,)
233
+ uptake = (self.a * mon * np.asarray(X)[:, None]).sum(axis=0)
234
+
235
+ dS_dt = secretion - uptake + D * (self.S_in - np.asarray(S))
236
+ return dX_dt, dS_dt
237
+ # Torch Backend
238
+ elif B.xp_name == "torch":
239
+ import torch
240
+
241
+ Srow = B.unsqueeze0(S)
242
+ K = B.as_array(self.K_ij)
243
+ r = B.as_array(self.r)
244
+ a = B.as_array(self.a)
245
+ b = B.as_array(self.b)
246
+ k = B.as_array(self.k)
247
+ S_in = B.as_array(self.S_in)
248
+
249
+ mon_frac = Srow / (Srow + K)
250
+ mon = r * mon_frac
251
+ growth = torch.sum(mon, dim=1)
252
+ dX_dt = (growth - k - D) * B.as_array(X)
253
+
254
+ secretion = torch.sum(b * B.as_array(X).unsqueeze(1), dim=0)
255
+ uptake = torch.sum(a * mon * B.as_array(X).unsqueeze(1), dim=0)
256
+ dS_dt = secretion - uptake + D * (S_in - B.as_array(S))
257
+
258
+ return dX_dt, dS_dt
259
+ else:
260
+ raise ValueError(f"Unsupported backend: {B.xp_name}")
261
+
262
+ # Simulation Adapter
263
+ def _simulate_fn(
264
+ self,
265
+ params: ParamsDict,
266
+ X0: np.ndarray,
267
+ S0: np.ndarray,
268
+ t_eval: np.ndarray,
269
+ ) -> Dict[str, np.ndarray]:
270
+ """
271
+ Adapter: takes params dict + initial conditions and returns {"t", "X", "S"}.
272
+ Used by crm_fit_backend.
273
+ """
274
+ old_params = self.get_params()
275
+ try:
276
+ self._set_params_from_dict(params)
277
+ y0 = np.concatenate([X0, S0])
278
+ sol = self.predict(y0=y0, t_eval=t_eval)
279
+ return {
280
+ "t": sol.t,
281
+ "X": sol.X.T, # (T, n)
282
+ "S": sol.S.T, # (T, m)
283
+ }
284
+ finally:
285
+ self.set_params(old_params)
286
+
287
+ # Helper: Resolve Fitting Arguments
288
+ def _resolve_fit_args(self, df, time_col, x_cols, s_cols):
289
+ """Helper to resolve defaults for all fit methods."""
290
+ # 1. Resolve DataFrame
291
+ if df is None:
292
+ if not hasattr(self, "_df"):
293
+ raise ValueError(
294
+ "No dataframe provided and no data attached to modelfrom_si."
295
+ )
296
+ df = self._df
297
+ # If time_col wasn't provided, see if we have a default attached
298
+ if time_col is None:
299
+ time_col = getattr(self, "_time_col", None)
300
+
301
+ if time_col is None:
302
+ raise ValueError("time_col must be specified or attached to model.")
303
+
304
+ # 2. Resolve Columns
305
+ if x_cols is None:
306
+ x_cols = self.names.X
307
+ if s_cols is None:
308
+ s_cols = self.names.S
309
+
310
+ # 3. Validation
311
+ missing_cols = [
312
+ c for c in (x_cols + s_cols + [time_col]) if c not in df.columns
313
+ ]
314
+ if missing_cols:
315
+ raise ValueError(
316
+ f"The following columns are missing from the DataFrame: {missing_cols}"
317
+ )
318
+
319
+ return df, time_col, x_cols, s_cols
320
+
321
+ # Fitting API
322
+ def fit(
323
+ self,
324
+ df: pd.DataFrame,
325
+ time_col: Optional[str] = None,
326
+ x_cols: Optional[List[str]] = None,
327
+ s_cols: Optional[List[str]] = None,
328
+ method: Literal["least_squares", "mcmc"] = "least_squares",
329
+ *,
330
+ params0: Optional[ParamsDict] = None,
331
+ lb_factor: float = 0.0,
332
+ ub_factor: float = 10.0,
333
+ X0: Optional[np.ndarray] = None,
334
+ S0: Optional[np.ndarray] = None,
335
+ include_metabolites: bool = True,
336
+ weight: Literal["median", "equal"] = "median",
337
+ n_time: int = 300,
338
+ fit_a: bool = True,
339
+ nsimu: int = 10_000,
340
+ sigma2: float = 12.0,
341
+ burn: float = 0.8,
342
+ nsamp: int = 200,
343
+ seed: int = 1234,
344
+ ) -> "CRModel":
345
+ """
346
+ High-level fit method. The given parameters are passed along to other
347
+ functions based on the given ``method``. See the documentation of the
348
+ relevant ``fit_`` methods for details.
349
+
350
+ Fits the model in place and returns self. Description of the parameters
351
+ shared by all the "fit" functions:
352
+
353
+ :param df: The DataFrame to fit data to
354
+ :param time_col: The name of the time column in ``df``
355
+ :param x_cols: The names of the consumer (X) columns in ``df``
356
+ :param s_cols: The names of the substrate (S) columns in ``df``
357
+ :param method: The fitting method to use
358
+ :param params0:
359
+ A dictionary of initial paramater values that will be used to
360
+ instantiate a ``CRModelParams`` instance if no params have been
361
+ given at construction time.
362
+ """
363
+ shared_params = dict(
364
+ df=df,
365
+ time_col=time_col,
366
+ x_cols=x_cols,
367
+ s_cols=s_cols,
368
+ params0=params0,
369
+ fit_a=fit_a,
370
+ )
371
+
372
+ if method == "least_squares":
373
+ self.fit_least_squares(
374
+ **shared_params,
375
+ lb_factor=lb_factor,
376
+ ub_factor=ub_factor,
377
+ X0=X0,
378
+ S0=S0,
379
+ include_metabolites=include_metabolites,
380
+ weight=weight,
381
+ n_time=n_time,
382
+ )
383
+ return self
384
+
385
+ elif method == "mcmc":
386
+ self.fit_mcmc(
387
+ **shared_params,
388
+ nsimu=nsimu,
389
+ sigma2=sigma2,
390
+ burn=burn,
391
+ nsamp=nsamp,
392
+ seed=seed,
393
+ )
394
+ return self
395
+
396
+ else:
397
+ raise ValueError(f"Unknown fit method: {method}")
398
+
399
+ def fit_least_squares(
400
+ self,
401
+ df=None,
402
+ time_col: Optional[str] = None,
403
+ x_cols: Optional[List[str]] = None,
404
+ s_cols: Optional[List[str]] = None,
405
+ *,
406
+ params0: Optional[ParamsDict] = None,
407
+ lb_factor: float = 0.0,
408
+ ub_factor: float = 10.0,
409
+ X0: Optional[np.ndarray] = None,
410
+ S0: Optional[np.ndarray] = None,
411
+ include_metabolites: bool = True,
412
+ weight: Literal["median", "equal"] = "median",
413
+ n_time: int = 300,
414
+ fit_a: bool = True,
415
+ ):
416
+ """
417
+ Mechanistic least-squares fit. All arguments (df, time_col, x_cols,
418
+ s_cols) default to attached/internal values if None.
419
+
420
+ A description of the least-squares-specific parameters:
421
+
422
+ :param lb_factor: Lower bound factor, multiplied with starting parameters to
423
+ determine the lower bound of the estimation.
424
+ :param ub_factor: Upper bound factor, multiplied with starting parameters to
425
+ determine the upper bound of the estimation.
426
+ :param X0: Initial X values, will be estimated from the data if not given
427
+ :param S0: Initial S values, will be estimated from the data if not given
428
+ :param include_metabolites: Whether to calculate time-series residuals for
429
+ metabolites (S) or only for species (X).
430
+ :param weight: Per-species/per-metabolite weighting. If "median", scales
431
+ weights based on the median value of the data. If "equal", does not
432
+ scale weights.
433
+ """
434
+ df, time_col, x_cols, s_cols = self._resolve_fit_args(
435
+ df, time_col, x_cols, s_cols
436
+ )
437
+
438
+ if params0 is None:
439
+ params0 = self.get_params().as_dict()
440
+
441
+ theta_opt, params_opt, sim_opt, info = crm_fit_mechanistic(
442
+ df=df,
443
+ time_col=time_col,
444
+ x_cols=x_cols,
445
+ s_cols=s_cols,
446
+ simulate_fn=self._simulate_fn,
447
+ params0=params0,
448
+ lb_factor=lb_factor,
449
+ ub_factor=ub_factor,
450
+ X0=X0,
451
+ S0=S0,
452
+ include_metabolites=include_metabolites,
453
+ weight=weight,
454
+ n_time=n_time,
455
+ fit_a=fit_a,
456
+ )
457
+
458
+ self._set_params_from_dict(params_opt)
459
+ self.theta_opt_ = theta_opt
460
+ self.sim_opt_ = sim_opt
461
+ self._fit_info = info
462
+
463
+ return theta_opt, sim_opt, info
464
+
465
+ def fit_mcmc(
466
+ self,
467
+ df=None,
468
+ time_col: Optional[str] = None,
469
+ x_cols: Optional[List[str]] = None,
470
+ s_cols: Optional[List[str]] = None,
471
+ params0: Optional[ParamsDict] = None,
472
+ fit_a: bool = True,
473
+ nsimu: int = 10_000,
474
+ sigma2: float = 12.0,
475
+ burn: float = 0.8,
476
+ nsamp: int = 200,
477
+ seed: int = 1234,
478
+ ):
479
+ """
480
+ Run MCMC parameter estimation. All arguments (df, time_col, x_cols,
481
+ s_cols) default to attached/internal values if None.
482
+
483
+ A description of the MCMC-specific parameters:
484
+
485
+ :param nsimu: Number of simulations in each chain
486
+ :param sigma2: Initial observation error
487
+ :param burn: Fraction of samples to drop as burn-in
488
+ :param nsamp: Number of posterior samples to pick
489
+ :param seed: Random seed
490
+ """
491
+ df, time_col, x_cols, s_cols = self._resolve_fit_args(
492
+ df, time_col, x_cols, s_cols
493
+ )
494
+
495
+ if params0 is None:
496
+ params0 = self.get_params().as_dict()
497
+
498
+ ctx, result = crm_fit_mcmc_from_df(
499
+ df=df,
500
+ time_col=time_col,
501
+ x_cols=x_cols,
502
+ s_cols=s_cols,
503
+ simulate_fn=self._simulate_fn,
504
+ params0=params0,
505
+ fit_a=fit_a,
506
+ nsimu=nsimu,
507
+ sigma2=sigma2,
508
+ burn=burn,
509
+ nsamp=nsamp,
510
+ seed=seed,
511
+ )
512
+
513
+ self._mcmc_ctx = ctx
514
+ self._mcmc_result = result
515
+ self.mcmc_sims_ = result["mcmc_sims"]
516
+ self.chain_ = result["chain"]
517
+ self.post_ = result["post"]
518
+ self.sschain_ = result["sschain"]
519
+
520
+ return result
521
+
522
+ # Convenience Wrappers / I/O
523
+ def simulate(
524
+ self,
525
+ y0: ArrayLike,
526
+ t: ArrayLike,
527
+ *,
528
+ log_space: bool = False,
529
+ method: Optional[str] = None,
530
+ solver_options: Optional[Dict] = None,
531
+ ) -> SimpleNamespace:
532
+ """
533
+ A convenience wrapper for ``BaseODEModel.predict``
534
+ """
535
+ return self.predict(
536
+ y0=y0,
537
+ t_eval=t,
538
+ log_space=log_space,
539
+ method=method,
540
+ solver_options=solver_options,
541
+ )
542
+
543
+ def to_dict(self) -> Dict[str, Union[float, list]]:
544
+ """Serialize model to a dict."""
545
+ p = self.get_params()
546
+ return {
547
+ "r": p.r.tolist(),
548
+ "a": p.a.tolist(),
549
+ "b": p.b.tolist(),
550
+ "K_ij": p.K_ij.tolist(),
551
+ "k": p.k.tolist(),
552
+ "S_in": p.S_in.tolist(),
553
+ "D": p.D,
554
+ "names": {"X": self.names.X, "S": self.names.S},
555
+ }