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,174 @@
1
+ from typing import Optional, Sequence, Tuple
2
+
3
+ import torch
4
+ from torch import nn
5
+
6
+ from ..models.base import BaseODEModel
7
+ from .base import BaseController, LossFunction
8
+
9
+
10
+ class OpenLoopNeuralController(BaseController):
11
+ """
12
+ Open-Loop Neural Controller (Time-Dependent Policy).
13
+
14
+ This controller learns a fixed schedule of interventions `u(t)` based solely on the
15
+ current time `t`. It does not observe the current biological state (X, S) during execution.
16
+
17
+ This is analogous to a "blind archer" or a pre-calculated drug dosing schedule.
18
+
19
+ The controller outputs positive injection rates (via Softplus) which are added
20
+ directly to the ODE derivatives:
21
+
22
+ - dX/dt += u_x(t) (Probiotic injection)
23
+ - dS/dt += u_s(t) (Nutrient/Prebiotic injection)
24
+
25
+ Parameters
26
+ ----------
27
+ total_time : float
28
+ The maximum time (T_final) of the experiment.
29
+ Inputs are normalized to the range [0, 1] as t_norm = t / total_time.
30
+
31
+ n_species : int
32
+ Number of species in the system (dimension of X).
33
+
34
+ n_resources : int
35
+ Number of substrates in the system (dimension of S).
36
+
37
+ hidden_dims : Sequence[int], optional
38
+ Architecture of the neural network (neurons per hidden layer).
39
+ Default: [16, 16].
40
+
41
+ activation : nn.Module
42
+ Activation function for hidden layers.
43
+
44
+ criterion : LossFunction, optional
45
+ The objective function used for training.
46
+ Signature: (trajectory, controller, model) -> (loss, aux_data).
47
+
48
+ injection_only : bool
49
+ If True, applies Softplus to the network output so controls are
50
+ nonnegative.
51
+
52
+ x_idx : Sequence[int], optional
53
+ Indices of species (X) to control (add/inject).
54
+ Default is None (control no species).
55
+
56
+ s_idx : Sequence[int], optional
57
+ Indices of substrates (S) to control (add/inject).
58
+
59
+ - If None: controls ALL substrates.
60
+ - If []: controls NO substrates.
61
+ - If [i, j]: controls specific substrates i and j.
62
+
63
+ target_substrate_idx : int, optional
64
+ Convenience argument. If s_idx is None and this is set,
65
+ the controller controls only this substrate index.
66
+ """
67
+
68
+ def __init__(
69
+ self,
70
+ total_time: float,
71
+ n_species: int,
72
+ n_resources: int,
73
+ *,
74
+ hidden_dims: Optional[Sequence[int]] = None,
75
+ activation: nn.Module = nn.Tanh(),
76
+ criterion: Optional[LossFunction] = None,
77
+ injection_only: bool = True,
78
+ x_idx: Optional[Sequence[int]] = None,
79
+ s_idx: Optional[Sequence[int]] = None,
80
+ target_substrate_idx: Optional[int] = None,
81
+ ):
82
+ super().__init__(criterion=criterion)
83
+
84
+ if hidden_dims is None:
85
+ hidden_dims = [16, 16]
86
+
87
+ self.total_time = float(total_time)
88
+
89
+ # 1. Resolve Indices (Shared Logic)
90
+ self._resolve_indices(
91
+ n_species, n_resources, x_idx, s_idx, target_substrate_idx
92
+ )
93
+
94
+ if self.out_dim == 0:
95
+ raise ValueError("Controller has no targets (x_idx=[] and s_idx=[]).")
96
+
97
+ # 2. Build Network (Shared Logic)
98
+ # Input is Time (scalar) -> 1
99
+ self.net = self._build_mlp(
100
+ input_dim=1,
101
+ output_dim=self.out_dim,
102
+ hidden_dims=hidden_dims,
103
+ activation=activation,
104
+ injection_only=injection_only,
105
+ )
106
+ "The neural network mapping time `t` to control signal `u`"
107
+
108
+ def forward(
109
+ self, model: BaseODEModel, t: torch.Tensor, X: torch.Tensor, S: torch.Tensor
110
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
111
+ """
112
+ Calculates control signal at time t.
113
+
114
+ Parameters
115
+ ----------
116
+ model : BaseODEModel
117
+ The metadata wrapper for the system (used for dimensions, etc.).
118
+ t : torch.Tensor
119
+ Current simulation time.
120
+ X, S : torch.Tensor
121
+ Current biological state (Ignored by OpenLoopNeuralController, but required by API).
122
+
123
+ Returns
124
+ -------
125
+ dXc : torch.Tensor
126
+ Additive change to biomass derivatives (same shape as X).
127
+ dSc : torch.Tensor
128
+ Additive change to substrate derivatives (same shape as S).
129
+ """
130
+ if not isinstance(t, torch.Tensor):
131
+ t = torch.tensor(t)
132
+
133
+ device = next(self.net.parameters()).device
134
+ dtype = next(self.net.parameters()).dtype
135
+ t = t.to(device=device, dtype=dtype)
136
+
137
+ t_norm = t / self.total_time
138
+ t_input = t_norm.reshape(-1, 1)
139
+
140
+ u = self.net(t_input)
141
+ return self._scatter_to_state(u, X, S)
142
+
143
+ def get_input_history(
144
+ self, trajectory: torch.Tensor, model: BaseODEModel
145
+ ) -> torch.Tensor:
146
+ """
147
+ Reconstructs the full control schedule u(t) for visualization.
148
+
149
+ Since this is an Open Loop controller, the schedule is fixed and
150
+ independent of the actual bacterial state trajectory.
151
+
152
+ Parameters
153
+ ----------
154
+ trajectory : torch.Tensor
155
+ Shape (Steps, State_Dim). Used to determine the time grid resolution.
156
+
157
+ Returns
158
+ -------
159
+ U_tensor : torch.Tensor
160
+ Shape (Steps, Output_Dim). The control signal at each time step.
161
+ """
162
+ steps = trajectory.shape[0]
163
+ U_list = []
164
+
165
+ device = next(self.net.parameters()).device
166
+ dtype = next(self.net.parameters()).dtype
167
+ times = torch.linspace(0, self.total_time, steps, device=device, dtype=dtype)
168
+
169
+ for i in range(steps):
170
+ t_norm = times[i] / self.total_time
171
+ u = self.net(t_norm.view(1, 1)).reshape(-1)
172
+ U_list.append(u)
173
+
174
+ return torch.stack(U_list, dim=0)
@@ -0,0 +1,2 @@
1
+ from .base import BaseODEModel, ModelNames
2
+ from .crm.model import CRModel, CRModelParams
@@ -0,0 +1,354 @@
1
+ from abc import ABC, abstractmethod
2
+ from dataclasses import dataclass, field
3
+ from types import SimpleNamespace
4
+ from typing import Callable, Dict, List, Optional, Tuple, Union, Literal
5
+
6
+ import numpy as np
7
+
8
+ from ..backends import ArrayBackend, ArrayLike, NumpyBackend, TorchBackend
9
+
10
+ try:
11
+ import torch
12
+ from torchdiffeq import odeint as torch_odeint
13
+
14
+ TORCH_AVAILABLE = True
15
+ TORCHDIFFEQ_AVAILABLE = True
16
+ except ImportError:
17
+ TORCH_AVAILABLE = False
18
+ TORCHDIFFEQ_AVAILABLE = False
19
+
20
+ try:
21
+ from scipy.integrate import solve_ivp
22
+
23
+ SCIPY_AVAILABLE = True
24
+ except ImportError:
25
+ SCIPY_AVAILABLE = False
26
+
27
+
28
+ @dataclass
29
+ class ModelNames:
30
+ "A convenience container for DataFrame column names"
31
+
32
+ X: List[str]
33
+ "Consumer (strain) column names"
34
+
35
+ S: List[str]
36
+ "Resource (metabolite) column names"
37
+
38
+ X_err: List[str] = field(default_factory=list)
39
+ "Optional consumer (strain) error column names"
40
+
41
+ S_err: List[str] = field(default_factory=list)
42
+ "Optional resource (metabolite) error column names"
43
+
44
+
45
+ DEFAULT_METHODS = {
46
+ "numpy": "BDF",
47
+ "torch": "dopri5",
48
+ }
49
+ "Default solver methods for supported backends"
50
+
51
+
52
+ class BaseODEModel(ABC):
53
+ """
54
+ Base class for microbiome ODE models supporting NumPy+SciPy and PyTorch+torchdiffeq.
55
+
56
+ Subclasses must implement the method `compute_rhs`:
57
+
58
+ compute_rhs(self, t, X, S) -> (dX_dt, dS_dt)
59
+
60
+ Controller support is intentionally NOT implemented here; keep those in a
61
+ separate module. Subclasses may optionally override `control_rhs` to inject
62
+ exogenous inputs, but the default is no control.
63
+
64
+ :param backend: The type of arrays the model will work with, either numpy or torch
65
+ :param names: Consumer (X) and substrate (S) column names in the data
66
+ """
67
+
68
+ def __init__(
69
+ self,
70
+ backend: Union[Literal["numpy", "torch"], ArrayBackend],
71
+ names: ModelNames,
72
+ ):
73
+ if isinstance(backend, str):
74
+ if backend == "numpy":
75
+ self.backend: ArrayBackend = NumpyBackend()
76
+ elif backend == "torch":
77
+ self.backend = TorchBackend()
78
+ else:
79
+ raise ValueError(
80
+ "backend must be 'numpy', 'torch', or a backend instance."
81
+ )
82
+ else:
83
+ self.backend = backend
84
+
85
+ self.names = names
86
+ self.n, self.m = len(names.X), len(names.S)
87
+
88
+ @abstractmethod
89
+ def compute_rhs(self, t, X, S):
90
+ """
91
+ Compute the right-hand side (RHS) of the ODE: dX/dt, dS/dt given X, S
92
+ using current parameters. Expected to return a tuple (dX_dt, dS_dt)
93
+ with the same dimensionality as the inputs.
94
+ """
95
+ raise NotImplementedError
96
+
97
+ def control_rhs(self, t, X, S):
98
+ """
99
+ Optional: override this method to inject control inputs u(t, y) with
100
+ the same dimensionality as X and S. Expected to return a tuple (u_X,
101
+ u_S).
102
+
103
+ The default implementation returns zeroes.
104
+ """
105
+ n, m = self.n, self.m
106
+ if self.backend.xp_name == "numpy":
107
+ return np.zeros(n), np.zeros(m)
108
+ else:
109
+ return (
110
+ torch.zeros(n, device=X.device, dtype=X.dtype),
111
+ torch.zeros(m, device=S.device, dtype=S.dtype),
112
+ )
113
+
114
+ def solve(
115
+ self,
116
+ y0: ArrayLike,
117
+ t_span: Tuple[float, float],
118
+ t_eval: ArrayLike,
119
+ *,
120
+ log_space: bool = False,
121
+ return_raw_tensors: bool = False,
122
+ method: Optional[str] = None,
123
+ solver_options: Optional[Dict] = None,
124
+ control_fn: Optional[Callable] = None,
125
+ ):
126
+ """
127
+ Integrate the ODE system in either normal or log-space for X. The
128
+ return values are different depending on the backend:
129
+
130
+ - NumPy: returns SciPy OdeResult
131
+ - Torch: returns either raw (T, state) tensor or a SimpleNamespace with .t/.y numpy arrays
132
+ """
133
+ backend = self.backend.xp_name
134
+ method = method or DEFAULT_METHODS[backend]
135
+
136
+ solver_options = solver_options or {}
137
+
138
+ n = self.n
139
+
140
+ if backend == "numpy":
141
+ if not SCIPY_AVAILABLE:
142
+ raise ImportError("scipy is required for NumPy backend integration.")
143
+ y0_np = np.asarray(y0, dtype=float).reshape(-1)
144
+
145
+ if log_space:
146
+ X0 = np.clip(y0_np[:n], 1e-30, np.inf)
147
+ y0_np = np.concatenate([np.log(X0), y0_np[n:]])
148
+
149
+ def wrapped_rhs(t, y):
150
+ if log_space:
151
+ return self._log_ode_rhs(t, y, control_fn)
152
+ return self._ode_rhs(t, y, control_fn)
153
+
154
+ sol = solve_ivp(
155
+ wrapped_rhs,
156
+ t_span,
157
+ y0_np,
158
+ t_eval=np.asarray(t_eval, dtype=float),
159
+ method=method,
160
+ **solver_options,
161
+ )
162
+ if log_space:
163
+ sol.y[:n, :] = np.exp(sol.y[:n, :])
164
+ return sol
165
+
166
+ # Torch backend
167
+ if not TORCH_AVAILABLE or not TORCHDIFFEQ_AVAILABLE:
168
+ raise ImportError(
169
+ "torch and torchdiffeq are required for torch backend integration."
170
+ )
171
+
172
+ t_eval_t = self.backend.as_array(t_eval).reshape(-1)
173
+ y0_t = self.backend.ensure_1d(y0)
174
+
175
+ if log_space:
176
+ X0 = self.backend.clip(self.backend.as_array(y0_t[:n]), 1e-30, np.inf)
177
+ logX0 = self.backend.log(X0)
178
+ y0_t = self.backend.concat0([logX0, y0_t[n:]])
179
+
180
+ def wrapped_rhs_torch(t, y):
181
+ if log_space:
182
+ return self._log_ode_rhs(t, y, control_fn)
183
+ return self._ode_rhs(t, y, control_fn)
184
+
185
+ out = torch_odeint(
186
+ wrapped_rhs_torch,
187
+ y0_t,
188
+ t_eval_t,
189
+ method=method,
190
+ options=solver_options,
191
+ ) # (T, state)
192
+
193
+ if log_space:
194
+ out[:, :n] = torch.exp(out[:, :n])
195
+
196
+ if return_raw_tensors:
197
+ return out
198
+
199
+ return SimpleNamespace(
200
+ t=self.backend.detach_to_numpy(t_eval_t),
201
+ y=self.backend.detach_to_numpy(out.T), # (state, T)
202
+ )
203
+
204
+ def predict(
205
+ self,
206
+ y0: ArrayLike,
207
+ t_eval: ArrayLike,
208
+ *,
209
+ log_space: bool = False,
210
+ method: Optional[str] = None,
211
+ solver_options: Optional[Dict] = None,
212
+ ) -> SimpleNamespace:
213
+ """
214
+ Simulate model predictions for the timepoints given in ``t_eval``.
215
+ Returns a ``SimpleNamespace`` object with .t, .y, .X, .S properties as
216
+ numpy arrays.
217
+ """
218
+ t_eval_arr = np.asarray(t_eval, dtype=float)
219
+ sol = self.solve(
220
+ y0=y0,
221
+ t_span=(float(t_eval_arr[0]), float(t_eval_arr[-1])),
222
+ t_eval=t_eval_arr,
223
+ log_space=log_space,
224
+ method=method,
225
+ solver_options=solver_options,
226
+ )
227
+
228
+ # SciPy OdeResult vs SimpleNamespace unified handling
229
+ if isinstance(sol, SimpleNamespace):
230
+ t = np.asarray(sol.t)
231
+ y = np.asarray(sol.y)
232
+ else: # OdeResult
233
+ t = np.asarray(sol.t)
234
+ y = np.asarray(sol.y)
235
+
236
+ X = y[: self.n, :]
237
+ S = y[self.n : self.n + self.m, :]
238
+
239
+ return SimpleNamespace(t=t, y=y, X=X, S=S)
240
+
241
+ def evaluate(
242
+ self,
243
+ y_true: ArrayLike,
244
+ y0: ArrayLike,
245
+ t_eval: ArrayLike,
246
+ *,
247
+ metric: Literal["sse", "mse", "mae"] | Callable[[np.ndarray, np.ndarray], float] = "sse",
248
+ observed: Literal["y", "X", "S"] = "y",
249
+ log_space: bool = False,
250
+ sample_weight: Optional[ArrayLike] = None,
251
+ ) -> float:
252
+ """
253
+ Evaluate model fit to time-series data.
254
+
255
+ Parameters:
256
+
257
+ :param y_true: Ground-truth trajectory. Accepts (state, T) or (T, state).
258
+ :param y0: Initial state used for prediction (state,).
259
+ :param t_eval: Times corresponding to y_true samples (T,).
260
+ :param metric: Either a specific metric from the list of options or a
261
+ callable that takes ``y_true`` values, ``y_pred`` values and returns
262
+ the error.
263
+ :param observed: Which part of the state to compare.
264
+ :param log_space: Integrate in log-space for X (prediction only).
265
+ :param sample_weight: optional (T,) weights over time.
266
+ """
267
+ pred = self.predict(y0=y0, t_eval=t_eval, log_space=log_space)
268
+
269
+ y_true_arr = np.asarray(y_true, dtype=float)
270
+ # Make (state, T)
271
+ if y_true_arr.ndim == 1:
272
+ y_true_arr = y_true_arr.reshape(-1, 1)
273
+
274
+ if (
275
+ y_true_arr.shape[0] != self.n + self.m
276
+ and y_true_arr.shape[1] == self.n + self.m
277
+ ):
278
+ y_true_arr = y_true_arr.T
279
+
280
+ if observed.lower() == "x":
281
+ y_pred = pred.X
282
+ y_obs = y_true_arr[: self.n, :]
283
+ elif observed.lower() == "s":
284
+ y_pred = pred.S
285
+ y_obs = y_true_arr[self.n : self.n + self.m, :]
286
+ else:
287
+ y_pred = pred.y
288
+ y_obs = y_true_arr
289
+
290
+ if y_obs.shape != y_pred.shape:
291
+ raise ValueError(
292
+ f"Shape mismatch: y_true {y_obs.shape} vs y_pred {y_pred.shape}"
293
+ )
294
+
295
+ if sample_weight is not None:
296
+ w = np.asarray(sample_weight, dtype=float).reshape(1, -1)
297
+ if w.shape[1] != y_pred.shape[1]:
298
+ raise ValueError(
299
+ "sample_weight must have length equal to number of time points"
300
+ )
301
+ diff = (y_pred - y_obs) * w
302
+ else:
303
+ diff = y_pred - y_obs
304
+
305
+ if isinstance(metric, str):
306
+ m = metric.lower()
307
+ if m == "sse":
308
+ return float(np.nansum(diff**2))
309
+ if m == "mse":
310
+ return float(np.nanmean(diff**2))
311
+ if m == "mae":
312
+ return float(np.nanmean(np.abs(diff)))
313
+ raise ValueError(
314
+ "Unknown metric string. Use 'sse', 'mse', 'mae', or provide a callable."
315
+ )
316
+ else:
317
+ return float(metric(y_obs, y_pred))
318
+
319
+ def _ode_rhs(self, t, y, control_fn=None):
320
+ X, S = self._split_state(y)
321
+ dX_dt, dS_dt = self.compute_rhs(t, X, S)
322
+
323
+ if control_fn:
324
+ dXc, dSc = control_fn(t, X, S)
325
+ else:
326
+ dXc, dSc = self.control_rhs(t, X, S)
327
+
328
+ return self.backend.concat0([dX_dt + dXc, dS_dt + dSc])
329
+
330
+ def _log_ode_rhs(self, t, y, control_fn=None):
331
+ log_X, S = self._split_state(y)
332
+ X = self.backend.exp(log_X)
333
+ dX_dt, dS_dt = self.compute_rhs(t, X, S)
334
+ dlogX_dt = dX_dt / (X + 1e-30)
335
+
336
+ if control_fn:
337
+ dXc, dSc = control_fn(t, X, S)
338
+ else:
339
+ dXc, dSc = self.control_rhs(t, X, S)
340
+
341
+ dlogX_dt = dlogX_dt + dXc / (X + 1e-30)
342
+ return self.backend.concat0([dlogX_dt, dS_dt + dSc])
343
+
344
+ def _split_state(self, y):
345
+ y1d = self.backend.ensure_1d(y)
346
+ X = y1d[: self.n]
347
+ S = y1d[self.n:self.n + self.m]
348
+ return X, S
349
+
350
+
351
+ __all__ = [
352
+ "ModelNames",
353
+ "BaseODEModel",
354
+ ]