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,539 @@
1
+ """
2
+ Utilities for mechanistic parameter initialization in consumer–resource models (CRMs).
3
+
4
+ This module provides:
5
+ - Robust string normalization and safe spline interpolation helpers.
6
+ - Mechanistic metabolite & species aliasing → masks for uptake (r_ij) and production (b_ij).
7
+ - Single-species mechanistic initialization:
8
+ * Estimation of dilution rate k.
9
+ * Estimation of production b_j.
10
+ * Crude estimation of uptake r_j and growth coupling a_j.
11
+ * Initialization of Monod half-saturation constants K_j.
12
+
13
+ The goal is to generate data-informed, biologically consistent initial parameters
14
+ that warm-start the nonlinear CRM fitting procedure.
15
+ """
16
+
17
+ import numpy as np
18
+ from scipy.interpolate import PchipInterpolator
19
+
20
+ __all__ = [
21
+ # Shared utilities
22
+ "_norm",
23
+ "_safe_pchip",
24
+ "_first_finite_by_col",
25
+ "_broadcast_nm",
26
+ "_met_idx_map",
27
+ "mechanistic_masks",
28
+ # Single-species init helpers
29
+ "build_mech_masks_single",
30
+ "make_time_windows",
31
+ "build_splines_single",
32
+ "estimate_k_log_slope",
33
+ "estimate_b_init",
34
+ "init_ra_crude",
35
+ "init_params_single_species",
36
+ ]
37
+
38
+
39
+ def _norm(s):
40
+ """
41
+ Normalize a column name string for fuzzy matching.
42
+
43
+ Returns:
44
+ Lowercased, stripped, zero-width-space removed string.
45
+ """
46
+ return str(s).strip().lower().replace("\u200b", "")
47
+
48
+
49
+ def _safe_pchip(x, y):
50
+ """
51
+ Return a robust PCHIP interpolator which works even for degenerate data.
52
+
53
+ Handles cases where:
54
+ - All values are non-finite → returns a constant zero function.
55
+ - Only one unique x-coordinate → returns a constant function.
56
+ - Usual case → returns PchipInterpolator(xu, yu).
57
+
58
+ Returns:
59
+ interpolator: Callable with .__call__(t) and .derivative() methods.
60
+ """
61
+ x = np.asarray(x, float)
62
+ y = np.asarray(y, float)
63
+ mask = np.isfinite(x) & np.isfinite(y)
64
+ x2, y2 = x[mask], y[mask]
65
+
66
+ # Case 1: No valid points → zero function
67
+ if x2.size == 0:
68
+
69
+ class ZeroFunc:
70
+ def __call__(self, t):
71
+ t = np.atleast_1d(t)
72
+ return np.zeros_like(t)
73
+
74
+ def derivative(self, n=1):
75
+ return lambda t: np.zeros_like(np.atleast_1d(t))
76
+
77
+ return ZeroFunc()
78
+
79
+ # Case 2: One unique x → constant function
80
+ xu, idx = np.unique(x2, return_index=True)
81
+ yu = y2[idx]
82
+
83
+ if xu.size == 1:
84
+ c = float(yu[0])
85
+
86
+ class ConstFunc:
87
+ def __call__(self, t):
88
+ t = np.atleast_1d(t)
89
+ return np.full_like(t, c)
90
+
91
+ def derivative(self, n=1):
92
+ return lambda t: np.zeros_like(np.atleast_1d(t))
93
+
94
+ return ConstFunc()
95
+
96
+ # Case 3: Valid full PCHIP
97
+ return PchipInterpolator(xu, yu, extrapolate=True)
98
+
99
+
100
+ def _first_finite_by_col(A, default=1.0):
101
+ """
102
+ Return the first finite value in each column of A.
103
+
104
+ Parameters
105
+ ----------
106
+ A : array_like, shape (T, M)
107
+ Input data with NaNs.
108
+ default : float
109
+ Value used if a column has no finite entries.
110
+
111
+ Returns
112
+ -------
113
+ out : ndarray, shape (M,)
114
+ """
115
+ A = np.asarray(A, float)
116
+ out = np.full(A.shape[1], float(default))
117
+
118
+ for j in range(A.shape[1]):
119
+ col = A[:, j]
120
+ m = np.isfinite(col)
121
+ if m.any():
122
+ out[j] = float(col[m][0])
123
+
124
+ return out
125
+
126
+
127
+ def _broadcast_nm(arr, n, m, fill=0.0):
128
+ """
129
+ Broadcast an array to shape (n, m) with flexible input shapes.
130
+
131
+ Accepts scalars, vectors (length n or m), or various 2D shapes.
132
+ """
133
+ if arr is None:
134
+ return np.full((n, m), float(fill))
135
+
136
+ A = np.asarray(arr, float)
137
+
138
+ # Scalar
139
+ if A.ndim == 0:
140
+ return np.full((n, m), float(A))
141
+
142
+ # 1D Array
143
+ if A.ndim == 1:
144
+ if A.size == m:
145
+ return np.broadcast_to(A.reshape(1, m), (n, m))
146
+ if A.size == n:
147
+ return np.repeat(A.reshape(n, 1), m, axis=1)
148
+ if A.size == n * m:
149
+ return A.reshape(n, m)
150
+
151
+ # 2D Array
152
+ if A.ndim == 2:
153
+ if A.shape == (n, m):
154
+ return A
155
+ if A.shape == (1, m):
156
+ return np.broadcast_to(A, (n, m))
157
+ if A.shape == (m, 1):
158
+ return np.broadcast_to(A.T, (n, m))
159
+ if A.shape == (m, n):
160
+ return A.T
161
+
162
+ raise ValueError(f"Unsupported shape for broadcast to {(n, m)}: {A.shape}")
163
+
164
+
165
+ # METABOLITE/SPECIES ALIASING AND MECHANISTIC MASKS
166
+
167
+ _MET_ALIASES = {
168
+ "lac": ("lactate", "lactic"),
169
+ "ace": ("acetate", "acetic"),
170
+ "but": ("butyrate", "butyric"),
171
+ "for": ("formate", "formic"),
172
+ "glu": ("glucose",),
173
+ "pyr": ("pyruvate", "pyruvic"),
174
+ "suc": ("succinate", "succinic"),
175
+ "tre": ("trehalose",),
176
+ }
177
+
178
+
179
+ def _met_idx_map(s_cols):
180
+ """
181
+ Map canonical metabolite aliases ("ace", "lac", ...) to indices in s_cols.
182
+ """
183
+ lo = [_norm(c) for c in s_cols]
184
+
185
+ def find_any(names):
186
+ for i, s in enumerate(lo):
187
+ if any(n in s for n in names):
188
+ return i
189
+ return None
190
+
191
+ return {k: find_any(v) for k, v in _MET_ALIASES.items()}
192
+
193
+
194
+ def _present_species_multi(x_cols):
195
+ """
196
+ Detect species presence from column names via substring matching.
197
+
198
+ Returns:
199
+ dict: Map from species labels ("BT", "BH", ...) to their index or None.
200
+ """
201
+ lo = [_norm(c) for c in x_cols]
202
+
203
+ def find(*keys):
204
+ for i, s in enumerate(lo):
205
+ if any(k in s for k in keys):
206
+ return i
207
+ return None
208
+
209
+ return {
210
+ "BT": find("bt", "thetaiota", "bacteroides"),
211
+ "BH": find("bh", "hydrogenotrophica", "blautia"),
212
+ "RI": find("ri", "intestinalis", "roseburia"),
213
+ "BF": find("bf", "fragilis", "bacteroides"),
214
+ "EC": find("ec", "coli", "escherichia"),
215
+ "FD": find("fd", "faecalibacterium", "duncaniae"),
216
+ }
217
+
218
+
219
+ def mechanistic_masks(s_cols, x_cols):
220
+ """
221
+ Construct mechanistic masks for uptake (C) and production (P).
222
+
223
+ Species-specific biochemical assumptions determine where r_ij and b_ij
224
+ are allowed to be non-zero.
225
+
226
+ Returns
227
+ -------
228
+ C : ndarray of bool, shape (n, m)
229
+ Uptake mask (True where r_ij can vary).
230
+ P : ndarray of bool, shape (n, m)
231
+ Production mask (True where b_ij can vary).
232
+ """
233
+ m, n = len(s_cols), len(x_cols)
234
+ C = np.zeros((n, m), bool)
235
+ P = np.zeros((n, m), bool)
236
+
237
+ idx = _met_idx_map(s_cols)
238
+ sp = _present_species_multi(x_cols)
239
+
240
+ def set_cols(mat, rows, keys):
241
+ """Set mask entries mat[rows, js] = True for metabolite aliases."""
242
+ js = [idx[k] for k in keys if idx[k] is not None]
243
+ if js:
244
+ mat[np.atleast_1d(rows)[:, None], np.array(js)] = True
245
+
246
+ # Species-specific rules
247
+ if sp["BT"] is not None:
248
+ i = sp["BT"]
249
+ set_cols(C, i, ("glu", "pyr", "tre"))
250
+ set_cols(P, i, ("ace", "lac", "suc", "for"))
251
+
252
+ if sp["BH"] is not None:
253
+ i = sp["BH"]
254
+ set_cols(C, i, ("glu", "pyr", "tre", "for"))
255
+ set_cols(P, i, ("ace", "lac"))
256
+
257
+ if sp["RI"] is not None:
258
+ i = sp["RI"]
259
+ set_cols(C, i, ("glu", "ace", "lac"))
260
+ set_cols(P, i, ("ace", "lac", "but", "for"))
261
+
262
+ if sp["BF"] is not None:
263
+ i = sp["BF"]
264
+ set_cols(C, i, ("glu", "pyr", "tre"))
265
+ set_cols(P, i, ("ace", "lac", "suc", "for"))
266
+
267
+ if sp["EC"] is not None:
268
+ i = sp["EC"]
269
+ set_cols(C, i, ("glu", "pyr", "tre"))
270
+ set_cols(P, i, ("ace", "lac", "suc", "for"))
271
+
272
+ if sp["FD"] is not None:
273
+ i = sp["FD"]
274
+ set_cols(C, i, ("glu", "ace"))
275
+ set_cols(P, i, ("ace", "but", "for", "lac"))
276
+
277
+ return C, P
278
+
279
+
280
+ # SINGLE-SPECIES INITIALIZATION
281
+
282
+
283
+ def build_mech_masks_single(s_cols, x_col_name=None):
284
+ """
285
+ Convenience wrapper for single-species CRM masks.
286
+ """
287
+ C, P = mechanistic_masks(s_cols, [x_col_name or ""])
288
+ r = C[0].copy()
289
+ b = P[0].copy()
290
+ a = r.copy()
291
+ return r, b, a
292
+
293
+
294
+ def make_time_windows(time, t_early=None, t_late=None, n_spline_points=400):
295
+ """
296
+ Build a dense time grid and masks for early/late regions.
297
+
298
+ The early region is used for estimating r_j and a_j (growth phase).
299
+ The late region is used for estimating k (decay/dilution).
300
+
301
+ Parameters
302
+ ----------
303
+ time : array-like
304
+ t_early : tuple, bool array, or None
305
+ t_late : float, bool array, or None
306
+ n_spline_points : int
307
+
308
+ Returns
309
+ -------
310
+ t_eval : ndarray
311
+ mask_early : ndarray (boolean)
312
+ mask_late : ndarray (boolean)
313
+ """
314
+ time = np.asarray(time, float)
315
+ t_eval = np.linspace(
316
+ float(np.nanmin(time)), float(np.nanmax(time)), int(n_spline_points)
317
+ )
318
+
319
+ span = time.max() - time.min()
320
+ if span >= 80:
321
+ default_early = (time.min(), min(time.min() + 20.0, time.max()))
322
+ default_late = time.min() + 60.0
323
+ else:
324
+ default_early = (time.min(), time.min() + 0.2 * span)
325
+ default_late = time.min() + 0.8 * span
326
+
327
+ def to_mask_early(te, spec):
328
+ if spec is None:
329
+ spec = default_early
330
+ if isinstance(spec, tuple):
331
+ return (te >= spec[0]) & (te <= spec[1])
332
+ spec = np.asarray(spec)
333
+ if spec.dtype == bool and spec.shape == te.shape:
334
+ return spec
335
+ raise ValueError("t_early must be (tmin, tmax) or boolean mask on t_eval")
336
+
337
+ def to_mask_late(te, spec):
338
+ if spec is None:
339
+ spec = default_late
340
+ if np.isscalar(spec):
341
+ return te >= float(spec)
342
+ spec = np.asarray(spec)
343
+ if spec.dtype == bool and spec.shape == te.shape:
344
+ return spec
345
+ raise ValueError("t_late must be scalar start or boolean mask on t_eval")
346
+
347
+ return t_eval, to_mask_early(t_eval, t_early), to_mask_late(t_eval, t_late)
348
+
349
+
350
+ def build_splines_single(time, X, S_mat):
351
+ """
352
+ Construct PCHIP splines for single-species X(t) and S_j(t).
353
+ """
354
+ X_spl = _safe_pchip(time, X)
355
+ dX_spl = X_spl.derivative()
356
+
357
+ m = S_mat.shape[1]
358
+ S_spl = [_safe_pchip(time, S_mat[:, j]) for j in range(m)]
359
+ dS_spl = [s.derivative() for s in S_spl]
360
+
361
+ return X_spl, dX_spl, S_spl, dS_spl
362
+
363
+
364
+ def estimate_k_log_slope(t_eval, X_spl, mask_late, eps=1e-9, k_floor=1e-6):
365
+ """
366
+ Estimate dilution/decay rate k via slope of log(X) in the late region.
367
+ k ≈ -median( d/dt log X(t) )
368
+ """
369
+ tw = t_eval[mask_late]
370
+ if tw.size < 3:
371
+ return float(k_floor)
372
+
373
+ dlogX = X_spl.derivative()(tw) / np.clip(X_spl(tw), eps, None)
374
+
375
+ if np.any(np.isfinite(dlogX)):
376
+ k = -np.median(dlogX[np.isfinite(dlogX)])
377
+ return float(max(k, k_floor))
378
+
379
+ return float(k_floor)
380
+
381
+
382
+ def estimate_b_init(t_eval, X_spl, dS_spl, b_mask, mask_early, m, eps=1e-9):
383
+ """
384
+ Estimate metabolite production rates b_j from early-time slopes.
385
+ dS_j/dt ≈ b_j * X
386
+ """
387
+ b0 = np.zeros(m, float)
388
+ te = t_eval[mask_early]
389
+
390
+ if te.size < 2:
391
+ return b0
392
+
393
+ Xe = np.clip(X_spl(te), eps, None)
394
+
395
+ for j in range(m):
396
+ if not b_mask[j]:
397
+ continue
398
+ ds = dS_spl[j](te)
399
+ ratio = ds / Xe
400
+ ratio = ratio[np.isfinite(ratio)]
401
+ b0[j] = float(np.sqrt(np.mean(ratio**2))) if ratio.size >= 2 else 0.0
402
+
403
+ return b0
404
+
405
+
406
+ def init_ra_crude(
407
+ t_eval, X_spl, dX_spl, S_spl, dS_spl, K_vec, k_est, r_mask, mask_early, m, eps=1e-9
408
+ ):
409
+ """
410
+ Crude moment-based estimates for uptake r_j and growth yield a_j.
411
+ """
412
+ r0 = np.zeros(m, float)
413
+ a0 = np.zeros(m, float)
414
+
415
+ te = t_eval[mask_early]
416
+ if te.size < 2:
417
+ return r0, a0
418
+
419
+ XW = np.clip(X_spl(te), eps, None)
420
+ dXW = dX_spl(te)
421
+
422
+ for j in range(m):
423
+ if not r_mask[j]:
424
+ continue
425
+
426
+ Sj = S_spl[j](te)
427
+ dSj = dS_spl[j](te)
428
+ Sjg = np.clip(Sj, eps, None)
429
+
430
+ fj = np.clip(Sj / (Sj + K_vec[j] + eps), eps, None)
431
+ good = np.isfinite(XW) & np.isfinite(dXW) & np.isfinite(Sj) & np.isfinite(dSj)
432
+
433
+ if good.sum() < 2:
434
+ continue
435
+
436
+ Xg = XW[good]
437
+ dXg = dXW[good]
438
+ Sjg2 = Sjg[good]
439
+ fjg = fj[good]
440
+ dSjg = dSj[good]
441
+
442
+ # Moment-based estimators
443
+ ar_est = -np.mean(dSjg) / (np.mean(Xg) * np.mean(fjg))
444
+ r_est = np.mean(((dXg / Xg) + k_est) * ((Sjg2 + K_vec[j]) / Sjg2))
445
+
446
+ r0[j] = max(float(r_est), 0.0) if np.isfinite(r_est) else 0.0
447
+ a0[j] = max(float(ar_est) / r0[j], 0.0) if r0[j] > 0 else 0.0
448
+
449
+ return r0, a0
450
+
451
+
452
+ def init_params_single_species(
453
+ df,
454
+ time_col,
455
+ x_col,
456
+ s_cols,
457
+ K_prefactor=2.0,
458
+ t_early=None,
459
+ t_late=None,
460
+ fit_a=True,
461
+ n_spline_points=400,
462
+ r_mask=None,
463
+ b_mask=None,
464
+ a_mask=None,
465
+ ):
466
+ """
467
+ Initialize mechanistic CRM parameters for a single species.
468
+
469
+ Returns dict containing:
470
+ - params: {r, a, b, k, K_ij, S_in, D}
471
+ - masks: {r_mask, b_mask, a_mask}
472
+ - t_eval, mask_early, mask_late
473
+ """
474
+ # 1. Parse Data
475
+ time = np.asarray(df[time_col], float)
476
+ X = np.asarray(df[x_col], float)
477
+ S = (
478
+ np.column_stack([np.asarray(df[c], float) for c in s_cols])
479
+ if s_cols
480
+ else np.zeros((len(df), 0))
481
+ )
482
+ m = S.shape[1]
483
+
484
+ # 2. Build Masks
485
+ default_r, default_b, default_a = build_mech_masks_single(s_cols, x_col_name=x_col)
486
+
487
+ if r_mask is None:
488
+ r_mask = default_r
489
+ if b_mask is None:
490
+ b_mask = default_b
491
+ if a_mask is None:
492
+ a_mask = default_a
493
+
494
+ if not fit_a:
495
+ a_mask[:] = False
496
+
497
+ # 3. Setup Splines & Windows
498
+ t_eval, mask_early, mask_late = make_time_windows(
499
+ time, t_early, t_late, n_spline_points=n_spline_points
500
+ )
501
+ X_spl, dX_spl, S_spl, dS_spl = build_splines_single(time, X, S)
502
+
503
+ # 4. K_ij Initial Values
504
+ K_vec = (K_prefactor * df[s_cols].max().to_numpy()) if m else np.zeros(0)
505
+
506
+ # 5. Core Parameter Estimations
507
+ k0 = estimate_k_log_slope(t_eval, X_spl, mask_late)
508
+
509
+ b0 = (
510
+ estimate_b_init(t_eval, X_spl, dS_spl, b_mask, mask_early, m)
511
+ if m
512
+ else np.array([])
513
+ )
514
+
515
+ r0, a0 = (
516
+ init_ra_crude(
517
+ t_eval, X_spl, dX_spl, S_spl, dS_spl, K_vec, k0, r_mask, mask_early, m
518
+ )
519
+ if m
520
+ else (np.array([]), np.array([]))
521
+ )
522
+
523
+ S_in = np.zeros(m, float)
524
+
525
+ return dict(
526
+ params=dict(
527
+ r=r0.reshape(1, -1),
528
+ a=a0.reshape(1, -1),
529
+ b=b0.reshape(1, -1),
530
+ k=np.array([float(k0)]),
531
+ K_ij=K_vec.reshape(1, -1),
532
+ S_in=S_in,
533
+ D=0.0,
534
+ ),
535
+ masks=dict(r_mask=r_mask, b_mask=b_mask, a_mask=a_mask),
536
+ t_eval=t_eval,
537
+ mask_early=mask_early,
538
+ mask_late=mask_late,
539
+ )
File without changes