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
mgrowthctrl/__init__.py
ADDED
|
File without changes
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
from typing import Iterable, Optional, Protocol, TypeAlias, Union
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
# Runtime Imports (Safe)
|
|
6
|
+
try:
|
|
7
|
+
import torch
|
|
8
|
+
|
|
9
|
+
TORCH_AVAILABLE = True
|
|
10
|
+
except ImportError:
|
|
11
|
+
TORCH_AVAILABLE = False
|
|
12
|
+
torch = None # type: ignore
|
|
13
|
+
|
|
14
|
+
# Use string "torch.Tensor" to avoid runtime errors if torch is missing
|
|
15
|
+
ArrayLike: TypeAlias = Union[np.ndarray, "torch.Tensor", list, tuple, float, int]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class ArrayBackend(Protocol):
|
|
19
|
+
"""
|
|
20
|
+
A shared type that unifies numpy and torch backends. The ``xp_name``
|
|
21
|
+
attribute determines which of the two backends are instantiated, but
|
|
22
|
+
ideally, users should use the shared methods.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
def as_array(self, x: ArrayLike) -> ArrayLike: ...
|
|
26
|
+
def zeros_like(self, x: ArrayLike) -> ArrayLike: ...
|
|
27
|
+
def exp(self, x: ArrayLike) -> ArrayLike: ...
|
|
28
|
+
def log(self, x: ArrayLike) -> ArrayLike: ...
|
|
29
|
+
def sum(self, x: ArrayLike, axis: int) -> ArrayLike: ...
|
|
30
|
+
def concat0(self, parts: Iterable[ArrayLike]) -> ArrayLike: ...
|
|
31
|
+
def unsqueeze0(self, x: ArrayLike) -> ArrayLike: ...
|
|
32
|
+
def detach_to_numpy(self, x: ArrayLike) -> np.ndarray: ...
|
|
33
|
+
def ensure_1d(self, x: ArrayLike) -> ArrayLike: ...
|
|
34
|
+
def clip(
|
|
35
|
+
self, x: ArrayLike, min_: float = -np.inf, max_: float = np.inf
|
|
36
|
+
) -> ArrayLike: ...
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class NumpyBackend(ArrayBackend):
|
|
40
|
+
"""
|
|
41
|
+
The default array backend implementation using numpy ndarrays. Calculations
|
|
42
|
+
are always performed on the CPU.
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
xp_name = "numpy"
|
|
46
|
+
|
|
47
|
+
def as_array(self, x: ArrayLike) -> np.ndarray:
|
|
48
|
+
return np.array(x, dtype=float)
|
|
49
|
+
|
|
50
|
+
def zeros_like(self, x: ArrayLike) -> np.ndarray:
|
|
51
|
+
return np.zeros_like(x, dtype=float)
|
|
52
|
+
|
|
53
|
+
def exp(self, x: ArrayLike) -> np.ndarray:
|
|
54
|
+
return np.exp(x)
|
|
55
|
+
|
|
56
|
+
def log(self, x: ArrayLike) -> np.ndarray:
|
|
57
|
+
return np.log(x)
|
|
58
|
+
|
|
59
|
+
def sum(self, x: ArrayLike, axis: int) -> np.ndarray:
|
|
60
|
+
return np.sum(x, axis=axis)
|
|
61
|
+
|
|
62
|
+
def concat0(self, parts: Iterable[ArrayLike]) -> np.ndarray:
|
|
63
|
+
return np.concatenate([np.asarray(p) for p in parts], axis=0)
|
|
64
|
+
|
|
65
|
+
def unsqueeze0(self, x: ArrayLike) -> np.ndarray:
|
|
66
|
+
xx = np.asarray(x)
|
|
67
|
+
return xx[None, :]
|
|
68
|
+
|
|
69
|
+
def detach_to_numpy(self, x: ArrayLike) -> np.ndarray:
|
|
70
|
+
return np.asarray(x)
|
|
71
|
+
|
|
72
|
+
def ensure_1d(self, x: ArrayLike) -> np.ndarray:
|
|
73
|
+
return np.asarray(x).reshape(-1)
|
|
74
|
+
|
|
75
|
+
def clip(
|
|
76
|
+
self, x: ArrayLike, min_: float = -np.inf, max_: float = np.inf
|
|
77
|
+
) -> np.ndarray:
|
|
78
|
+
return np.clip(np.asarray(x), min_, max_)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class TorchBackend(ArrayBackend):
|
|
82
|
+
"""
|
|
83
|
+
Arrays implemented as torch tensors. Allows storing data on the GPU by
|
|
84
|
+
providing a ``device`` attribute.
|
|
85
|
+
"""
|
|
86
|
+
|
|
87
|
+
xp_name = "torch"
|
|
88
|
+
|
|
89
|
+
def __init__(
|
|
90
|
+
self,
|
|
91
|
+
device: Optional[Union[str, "torch.device"]] = None,
|
|
92
|
+
dtype: Optional["torch.dtype"] = None,
|
|
93
|
+
):
|
|
94
|
+
# Runtime check is required here!
|
|
95
|
+
if not TORCH_AVAILABLE:
|
|
96
|
+
raise ImportError("PyTorch not available.")
|
|
97
|
+
|
|
98
|
+
# We can safely use 'torch' here because we checked TORCH_AVAILABLE
|
|
99
|
+
self.device = (
|
|
100
|
+
torch.device(device) if device is not None else torch.device("cpu")
|
|
101
|
+
)
|
|
102
|
+
self.dtype = dtype if dtype is not None else torch.float32
|
|
103
|
+
|
|
104
|
+
def as_array(self, x: ArrayLike) -> "torch.Tensor":
|
|
105
|
+
if isinstance(x, torch.Tensor):
|
|
106
|
+
return x.to(device=self.device, dtype=self.dtype)
|
|
107
|
+
return torch.tensor(x, device=self.device, dtype=self.dtype)
|
|
108
|
+
|
|
109
|
+
def zeros_like(self, x: ArrayLike) -> "torch.Tensor":
|
|
110
|
+
t = self.as_array(x)
|
|
111
|
+
return torch.zeros_like(t)
|
|
112
|
+
|
|
113
|
+
def exp(self, x: ArrayLike) -> "torch.Tensor":
|
|
114
|
+
return torch.exp(self.as_array(x))
|
|
115
|
+
|
|
116
|
+
def log(self, x: ArrayLike) -> "torch.Tensor":
|
|
117
|
+
return torch.log(self.as_array(x))
|
|
118
|
+
|
|
119
|
+
def sum(self, x: ArrayLike, axis: int) -> "torch.Tensor":
|
|
120
|
+
return torch.sum(self.as_array(x), dim=axis)
|
|
121
|
+
|
|
122
|
+
def concat0(self, parts: Iterable[ArrayLike]) -> "torch.Tensor":
|
|
123
|
+
ts = [self.as_array(p) for p in parts]
|
|
124
|
+
return torch.cat(ts, dim=0)
|
|
125
|
+
|
|
126
|
+
def unsqueeze0(self, x: ArrayLike) -> "torch.Tensor":
|
|
127
|
+
return self.as_array(x).unsqueeze(0)
|
|
128
|
+
|
|
129
|
+
def detach_to_numpy(self, x: ArrayLike) -> np.ndarray:
|
|
130
|
+
t = self.as_array(x)
|
|
131
|
+
return t.detach().cpu().numpy()
|
|
132
|
+
|
|
133
|
+
def ensure_1d(self, x: ArrayLike) -> "torch.Tensor":
|
|
134
|
+
t = self.as_array(x)
|
|
135
|
+
return t.reshape(-1)
|
|
136
|
+
|
|
137
|
+
def clip(
|
|
138
|
+
self, x: ArrayLike, min_: float = -np.inf, max_: float = np.inf
|
|
139
|
+
) -> "torch.Tensor":
|
|
140
|
+
t = self.as_array(x)
|
|
141
|
+
# torch.clip does not accept ±inf; guard explicitly
|
|
142
|
+
if np.isneginf(min_) and np.isposinf(max_):
|
|
143
|
+
return t
|
|
144
|
+
if np.isneginf(min_):
|
|
145
|
+
return torch.minimum(t, torch.tensor(max_, device=t.device, dtype=t.dtype))
|
|
146
|
+
if np.isposinf(max_):
|
|
147
|
+
return torch.maximum(t, torch.tensor(min_, device=t.device, dtype=t.dtype))
|
|
148
|
+
return torch.clamp(t, min=float(min_), max=float(max_))
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
from abc import ABC, abstractmethod
|
|
2
|
+
from types import SimpleNamespace
|
|
3
|
+
from typing import Any, Callable, List, Optional, Sequence, Tuple
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
import torch
|
|
7
|
+
from torch import nn
|
|
8
|
+
|
|
9
|
+
from ..models.base import BaseODEModel
|
|
10
|
+
|
|
11
|
+
LossFunction = Callable[
|
|
12
|
+
[torch.Tensor, "BaseController", BaseODEModel], Tuple[torch.Tensor, Any]
|
|
13
|
+
]
|
|
14
|
+
"""
|
|
15
|
+
Type alias for loss functions. "LossFunction" is a function that takes
|
|
16
|
+
(Trajectory, Controller, Model) and returns (Loss, AuxData)
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class BaseController(nn.Module, ABC):
|
|
21
|
+
"""
|
|
22
|
+
Controller baseclass.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
def __init__(self, criterion: LossFunction = None):
|
|
26
|
+
super().__init__()
|
|
27
|
+
|
|
28
|
+
self.criterion: LossFunction = criterion
|
|
29
|
+
"""
|
|
30
|
+
Used as a loss function. As an alternative, you can override the
|
|
31
|
+
``compute_loss`` method instead and leave this to its default of None.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
# Will be populated by child classes or helper methods
|
|
35
|
+
self.x_idx: List[int] = []
|
|
36
|
+
"""
|
|
37
|
+
Indices of species to control (add/inject).
|
|
38
|
+
Default is None (control no species).
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
self.s_idx: List[int] = []
|
|
42
|
+
"""
|
|
43
|
+
Indices of substrates to control (add/inject).
|
|
44
|
+
|
|
45
|
+
- If None: controls ALL substrates.
|
|
46
|
+
- If []: controls NO substrates.
|
|
47
|
+
- If [i, j]: controls specific substrates i and j.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
self.n_species: int = 0
|
|
51
|
+
"Number of species (X)"
|
|
52
|
+
|
|
53
|
+
self.n_resources: int = 0
|
|
54
|
+
"Number of resources (S)"
|
|
55
|
+
|
|
56
|
+
@abstractmethod
|
|
57
|
+
def forward(
|
|
58
|
+
self,
|
|
59
|
+
model: BaseODEModel,
|
|
60
|
+
t: torch.Tensor,
|
|
61
|
+
X: torch.Tensor,
|
|
62
|
+
S: torch.Tensor,
|
|
63
|
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
|
64
|
+
pass
|
|
65
|
+
|
|
66
|
+
@abstractmethod
|
|
67
|
+
def get_input_history(
|
|
68
|
+
self, trajectory: torch.Tensor, model: BaseODEModel
|
|
69
|
+
) -> torch.Tensor:
|
|
70
|
+
"""
|
|
71
|
+
Reconstructs the full control schedule u(t).
|
|
72
|
+
Subclasses should implement this.
|
|
73
|
+
"""
|
|
74
|
+
pass
|
|
75
|
+
|
|
76
|
+
def predict_u(self, t, X, S, model) -> torch.Tensor:
|
|
77
|
+
"""
|
|
78
|
+
Optional method to return raw control signal 'u' instead of dXc, dSc.
|
|
79
|
+
Useful for logging.
|
|
80
|
+
"""
|
|
81
|
+
raise NotImplementedError("Subclasses should implement predict_u if needed")
|
|
82
|
+
|
|
83
|
+
def compute_loss(
|
|
84
|
+
self, trajectory: torch.Tensor, model: BaseODEModel
|
|
85
|
+
) -> Tuple[torch.Tensor, Any]:
|
|
86
|
+
"""
|
|
87
|
+
Delegates the loss calculation to the user-provided function: ``self.criterion``
|
|
88
|
+
"""
|
|
89
|
+
if self.criterion is None:
|
|
90
|
+
raise ValueError("No criterion function provided to this controller.")
|
|
91
|
+
|
|
92
|
+
# Pass 'self' so the function can ask the controller to recover inputs
|
|
93
|
+
return self.criterion(trajectory, self, model)
|
|
94
|
+
|
|
95
|
+
def simulate(
|
|
96
|
+
self,
|
|
97
|
+
model: BaseODEModel,
|
|
98
|
+
y0: Any,
|
|
99
|
+
t_eval: Any,
|
|
100
|
+
t_span: Optional[Tuple[float, float]] = None,
|
|
101
|
+
**kwargs,
|
|
102
|
+
):
|
|
103
|
+
"""
|
|
104
|
+
Simulate the closed-loop system (Controller + Model).
|
|
105
|
+
|
|
106
|
+
:param y0: Starting state
|
|
107
|
+
:param t_eval: Time values in an array-like input
|
|
108
|
+
:param t_span:
|
|
109
|
+
Start and end time values to simulate, defaults to first and last
|
|
110
|
+
values of ``t_eval``
|
|
111
|
+
:return:
|
|
112
|
+
``SimpleNamespace`` with .t, .Y, .X, .S, properties and a .raw
|
|
113
|
+
property that contains the raw solution result given by the model.
|
|
114
|
+
"""
|
|
115
|
+
if t_span is None and t_eval is not None:
|
|
116
|
+
t_span = (t_eval[0], t_eval[-1])
|
|
117
|
+
|
|
118
|
+
# Create control callback
|
|
119
|
+
def control_wrapper(t, X, S):
|
|
120
|
+
# Ensure scalar time for the controller if needed
|
|
121
|
+
if not isinstance(t, torch.Tensor) and hasattr(X, "device"):
|
|
122
|
+
t = torch.tensor(float(t), device=X.device, dtype=X.dtype)
|
|
123
|
+
|
|
124
|
+
# Call forward with new signature: forward(model, t, X, S)
|
|
125
|
+
dXc, dSc = self.forward(model, t, X, S)
|
|
126
|
+
return dXc, dSc
|
|
127
|
+
|
|
128
|
+
# Pass control_fn to the model.solve method
|
|
129
|
+
sol = model.solve(
|
|
130
|
+
y0, t_span=t_span, t_eval=t_eval, control_fn=control_wrapper, **kwargs
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
t = np.asarray(sol.t)
|
|
134
|
+
y = np.asarray(sol.y)
|
|
135
|
+
|
|
136
|
+
X = y[: model.n, :]
|
|
137
|
+
S = y[model.n : model.n + model.m, :]
|
|
138
|
+
|
|
139
|
+
return SimpleNamespace(t=t, y=y, X=X, S=S, raw=sol)
|
|
140
|
+
|
|
141
|
+
def fit(
|
|
142
|
+
self,
|
|
143
|
+
model: BaseODEModel,
|
|
144
|
+
y0: torch.Tensor,
|
|
145
|
+
t_eval: Any,
|
|
146
|
+
t_span: Optional[Tuple[float, float]] = None,
|
|
147
|
+
epochs: int = 100,
|
|
148
|
+
lr: float = 0.01,
|
|
149
|
+
log_fn: Optional[
|
|
150
|
+
Callable[
|
|
151
|
+
[BaseODEModel, int, torch.Tensor, torch.Tensor, torch.Tensor], None
|
|
152
|
+
]
|
|
153
|
+
] = None,
|
|
154
|
+
):
|
|
155
|
+
"""
|
|
156
|
+
Train the controller against the model using a simple Adam optimizer loop.
|
|
157
|
+
|
|
158
|
+
:param y0: Starting state
|
|
159
|
+
:param t_eval: Time values in an array-like input
|
|
160
|
+
:param t_span:
|
|
161
|
+
Start and end time values to solve for, defaults to first and last
|
|
162
|
+
values of ``t_eval``
|
|
163
|
+
:param epochs: Number of epochs to train
|
|
164
|
+
:param lr: passed to the Adam optimizer from torch
|
|
165
|
+
:param log_fn:
|
|
166
|
+
Logging function that can be used for debugging purposes. Called on
|
|
167
|
+
every loop with (model, epoch, loss, U_trajectory, sol_tensor).
|
|
168
|
+
"""
|
|
169
|
+
optimizer = torch.optim.Adam(self.parameters(), lr=lr)
|
|
170
|
+
|
|
171
|
+
if t_span is None and t_eval is not None:
|
|
172
|
+
t_span = (t_eval[0], t_eval[-1])
|
|
173
|
+
|
|
174
|
+
# Create control callback
|
|
175
|
+
def control_wrapper(t, X, S):
|
|
176
|
+
if not isinstance(t, torch.Tensor) and hasattr(X, "device"):
|
|
177
|
+
t = torch.tensor(float(t), device=X.device, dtype=X.dtype)
|
|
178
|
+
dXc, dSc = self.forward(model, t, X, S)
|
|
179
|
+
return dXc, dSc
|
|
180
|
+
|
|
181
|
+
for epoch in range(epochs + 1):
|
|
182
|
+
optimizer.zero_grad()
|
|
183
|
+
|
|
184
|
+
# Solve the ODE (forward pass through time)
|
|
185
|
+
# return_raw_tensors=True gives (Steps, State_Dim) tensor
|
|
186
|
+
# Pass control_fn!
|
|
187
|
+
sol_tensor = model.solve(
|
|
188
|
+
y0,
|
|
189
|
+
t_span=t_span,
|
|
190
|
+
t_eval=t_eval,
|
|
191
|
+
return_raw_tensors=True,
|
|
192
|
+
control_fn=control_wrapper,
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
# Compute loss
|
|
196
|
+
loss, U_trajectory = self.compute_loss(sol_tensor, model)
|
|
197
|
+
|
|
198
|
+
# Backpropagate through time (via generic ODE solver or adjoint)
|
|
199
|
+
loss.backward()
|
|
200
|
+
optimizer.step()
|
|
201
|
+
|
|
202
|
+
if log_fn is not None:
|
|
203
|
+
log_fn(model, epoch, loss, U_trajectory, sol_tensor)
|
|
204
|
+
|
|
205
|
+
def _resolve_indices(
|
|
206
|
+
self,
|
|
207
|
+
n_species: int,
|
|
208
|
+
n_resources: int,
|
|
209
|
+
x_idx: Optional[Sequence[int]] = None,
|
|
210
|
+
s_idx: Optional[Sequence[int]] = None,
|
|
211
|
+
target_substrate_idx: Optional[int] = None,
|
|
212
|
+
):
|
|
213
|
+
"""
|
|
214
|
+
Helper to resolve which species/substrates to control.
|
|
215
|
+
Stores result in self.x_idx and self.s_idx.
|
|
216
|
+
"""
|
|
217
|
+
self.n_species = int(n_species)
|
|
218
|
+
self.n_resources = int(n_resources)
|
|
219
|
+
|
|
220
|
+
# Determine Species Targets (X)
|
|
221
|
+
if x_idx is None:
|
|
222
|
+
self.x_idx = []
|
|
223
|
+
else:
|
|
224
|
+
self.x_idx = [int(j) for j in x_idx]
|
|
225
|
+
|
|
226
|
+
# Determine Substrate Targets (S)
|
|
227
|
+
# Logic: s_idx takes precedence.
|
|
228
|
+
# If None, check shortcut target_substrate_idx.
|
|
229
|
+
# If both None, control ALL substrates (Consistency Fix).
|
|
230
|
+
if s_idx is not None:
|
|
231
|
+
self.s_idx = [int(j) for j in s_idx]
|
|
232
|
+
elif target_substrate_idx is not None:
|
|
233
|
+
self.s_idx = [int(target_substrate_idx)]
|
|
234
|
+
else:
|
|
235
|
+
# Default to controlling ALL substrates if nothing specified
|
|
236
|
+
self.s_idx = list(range(self.n_resources))
|
|
237
|
+
|
|
238
|
+
self.out_dim = len(self.x_idx) + len(self.s_idx)
|
|
239
|
+
"Total control output dimension."
|
|
240
|
+
|
|
241
|
+
def _build_mlp(
|
|
242
|
+
self,
|
|
243
|
+
input_dim: int,
|
|
244
|
+
output_dim: int,
|
|
245
|
+
hidden_dims: List[int],
|
|
246
|
+
activation: nn.Module,
|
|
247
|
+
injection_only: bool,
|
|
248
|
+
) -> nn.Sequential:
|
|
249
|
+
"""
|
|
250
|
+
Helper to build a simple MLP with Softplus output.
|
|
251
|
+
"""
|
|
252
|
+
layers = []
|
|
253
|
+
current_dim = input_dim
|
|
254
|
+
|
|
255
|
+
for h_dim in hidden_dims:
|
|
256
|
+
layers.append(nn.Linear(current_dim, h_dim))
|
|
257
|
+
layers.append(activation)
|
|
258
|
+
current_dim = h_dim
|
|
259
|
+
|
|
260
|
+
# Output Layer
|
|
261
|
+
layers.append(nn.Linear(current_dim, output_dim))
|
|
262
|
+
|
|
263
|
+
# If injection_only, use Softplus to ensure non-negative output
|
|
264
|
+
# i.e. cannot remove mass, only add injection
|
|
265
|
+
if injection_only:
|
|
266
|
+
layers.append(nn.Softplus())
|
|
267
|
+
|
|
268
|
+
return nn.Sequential(*layers)
|
|
269
|
+
|
|
270
|
+
def _scatter_to_state(
|
|
271
|
+
self, u: torch.Tensor, X_template: torch.Tensor, S_template: torch.Tensor
|
|
272
|
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
|
273
|
+
"""
|
|
274
|
+
Maps the flat control vector 'u' to the full state dXc, dSc using
|
|
275
|
+
the stored indices self.x_idx and self.s_idx.
|
|
276
|
+
"""
|
|
277
|
+
dXc = torch.zeros_like(X_template)
|
|
278
|
+
dSc = torch.zeros_like(S_template)
|
|
279
|
+
|
|
280
|
+
# Handle batch dimension if present
|
|
281
|
+
# u shape: (..., out_dim)
|
|
282
|
+
# X shape: (..., n_species)
|
|
283
|
+
|
|
284
|
+
k = 0
|
|
285
|
+
for idx in self.x_idx:
|
|
286
|
+
# u[..., k] handles both (out_dim,) and (Batch, out_dim)
|
|
287
|
+
dXc[..., idx] = u[..., k]
|
|
288
|
+
k += 1
|
|
289
|
+
for idx in self.s_idx:
|
|
290
|
+
dSc[..., idx] = u[..., k]
|
|
291
|
+
k += 1
|
|
292
|
+
|
|
293
|
+
return dXc, dSc
|
|
@@ -0,0 +1,208 @@
|
|
|
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 ClosedLoopNeuralController(BaseController):
|
|
11
|
+
"""
|
|
12
|
+
Closed-Loop Neural Controller (State-Dependent Policy).
|
|
13
|
+
|
|
14
|
+
This controller learns a feedback policy u(X, S) from the current biological
|
|
15
|
+
state. Unlike the open-loop controller, the output depends on the current
|
|
16
|
+
observed state rather than time.
|
|
17
|
+
|
|
18
|
+
The controller outputs positive injection rates (via Softplus when enabled)
|
|
19
|
+
which are added directly to the ODE derivatives:
|
|
20
|
+
|
|
21
|
+
- dX/dt += u_x(X, S) (Probiotic injection)
|
|
22
|
+
- dS/dt += u_s(X, S) (Nutrient/Prebiotic injection)
|
|
23
|
+
|
|
24
|
+
Parameters
|
|
25
|
+
----------
|
|
26
|
+
state_dim : int
|
|
27
|
+
Total dimension of the full biological state (n_species + n_resources).
|
|
28
|
+
|
|
29
|
+
n_species : int
|
|
30
|
+
Number of species in the system (dimension of X).
|
|
31
|
+
|
|
32
|
+
n_resources : int
|
|
33
|
+
Number of substrates in the system (dimension of S).
|
|
34
|
+
|
|
35
|
+
hidden_dims : Optional[Sequence[int]]
|
|
36
|
+
Architecture of the neural network (neurons per hidden layer).
|
|
37
|
+
Default: [16, 16].
|
|
38
|
+
|
|
39
|
+
activation : nn.Module
|
|
40
|
+
Activation function for hidden layers.
|
|
41
|
+
|
|
42
|
+
criterion : Optional[LossFunction]
|
|
43
|
+
The objective function used for training. If not provided, you should
|
|
44
|
+
override the ``compute_loss`` method.
|
|
45
|
+
Signature: (trajectory, controller, model) -> (loss, aux_data).
|
|
46
|
+
|
|
47
|
+
injection_only : bool
|
|
48
|
+
If True, applies Softplus to the network output so controls are
|
|
49
|
+
nonnegative.
|
|
50
|
+
|
|
51
|
+
x_idx : Optional[Sequence[int]]
|
|
52
|
+
Indices of species to control (add/inject).
|
|
53
|
+
Default is None (control no species).
|
|
54
|
+
|
|
55
|
+
s_idx : Optional[Sequence[int]]
|
|
56
|
+
Indices of substrates to control (add/inject).
|
|
57
|
+
|
|
58
|
+
- If None: controls ALL substrates.
|
|
59
|
+
- If []: controls NO substrates.
|
|
60
|
+
- If [i, j]: controls specific substrates i and j.
|
|
61
|
+
|
|
62
|
+
target_substrate_idx : Optional[int]
|
|
63
|
+
Convenience argument. If s_idx is None and this is set,
|
|
64
|
+
the controller controls only this substrate index.
|
|
65
|
+
|
|
66
|
+
obs_x_idx : Optional[Sequence[int]]
|
|
67
|
+
Indices of species observed by the controller.
|
|
68
|
+
Default is None (observe all species).
|
|
69
|
+
|
|
70
|
+
obs_s_idx : Optional[Sequence[int]]
|
|
71
|
+
Indices of substrates observed by the controller.
|
|
72
|
+
Default is None (observe all substrates).
|
|
73
|
+
"""
|
|
74
|
+
|
|
75
|
+
def __init__(
|
|
76
|
+
self,
|
|
77
|
+
state_dim: int,
|
|
78
|
+
n_species: int,
|
|
79
|
+
n_resources: int,
|
|
80
|
+
*,
|
|
81
|
+
hidden_dims: Optional[Sequence[int]] = None,
|
|
82
|
+
activation: nn.Module = nn.ReLU(),
|
|
83
|
+
criterion: Optional[LossFunction] = None,
|
|
84
|
+
injection_only: bool = True,
|
|
85
|
+
x_idx: Optional[Sequence[int]] = None,
|
|
86
|
+
s_idx: Optional[Sequence[int]] = None,
|
|
87
|
+
target_substrate_idx: Optional[int] = None,
|
|
88
|
+
obs_x_idx: Optional[Sequence[int]] = None,
|
|
89
|
+
obs_s_idx: Optional[Sequence[int]] = None,
|
|
90
|
+
):
|
|
91
|
+
super().__init__(criterion=criterion)
|
|
92
|
+
|
|
93
|
+
if hidden_dims is None:
|
|
94
|
+
hidden_dims = [16, 16]
|
|
95
|
+
|
|
96
|
+
self.state_dim = int(state_dim)
|
|
97
|
+
|
|
98
|
+
if self.state_dim != n_species + n_resources:
|
|
99
|
+
raise ValueError(
|
|
100
|
+
f"state_dim mismatch: {state_dim} vs {n_species} + {n_resources}"
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
self._resolve_indices(
|
|
104
|
+
n_species, n_resources, x_idx, s_idx, target_substrate_idx
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
if self.out_dim == 0:
|
|
108
|
+
raise ValueError("Controller has no targets (x_idx=[] and s_idx=[]).")
|
|
109
|
+
|
|
110
|
+
self.obs_x_idx = (
|
|
111
|
+
list(range(n_species)) if obs_x_idx is None else [int(j) for j in obs_x_idx]
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
self.obs_s_idx = (
|
|
115
|
+
list(range(n_resources))
|
|
116
|
+
if obs_s_idx is None
|
|
117
|
+
else [int(j) for j in obs_s_idx]
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
self.obs_dim = len(self.obs_x_idx) + len(self.obs_s_idx)
|
|
121
|
+
"Total observed input dimension."
|
|
122
|
+
|
|
123
|
+
if self.obs_dim == 0:
|
|
124
|
+
raise ValueError("Controller has no observed inputs.")
|
|
125
|
+
|
|
126
|
+
self.net = self._build_mlp(
|
|
127
|
+
input_dim=self.obs_dim,
|
|
128
|
+
output_dim=self.out_dim,
|
|
129
|
+
hidden_dims=hidden_dims,
|
|
130
|
+
activation=activation,
|
|
131
|
+
injection_only=injection_only,
|
|
132
|
+
)
|
|
133
|
+
"The neural network mapping observed state -> control signal u."
|
|
134
|
+
|
|
135
|
+
def forward(
|
|
136
|
+
self, model: BaseODEModel, t: torch.Tensor, X: torch.Tensor, S: torch.Tensor
|
|
137
|
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
|
138
|
+
"""
|
|
139
|
+
Calculates the control signal from the current observed state.
|
|
140
|
+
|
|
141
|
+
Parameters
|
|
142
|
+
----------
|
|
143
|
+
model : BaseODEModel
|
|
144
|
+
The metadata wrapper for the system (unused, required by API).
|
|
145
|
+
t : torch.Tensor
|
|
146
|
+
Current simulation time (unused by this controller).
|
|
147
|
+
X, S : torch.Tensor
|
|
148
|
+
Current biological state.
|
|
149
|
+
|
|
150
|
+
Returns
|
|
151
|
+
-------
|
|
152
|
+
dXc : torch.Tensor
|
|
153
|
+
Additive change to biomass derivatives (same shape as X).
|
|
154
|
+
dSc : torch.Tensor
|
|
155
|
+
Additive change to substrate derivatives (same shape as S).
|
|
156
|
+
"""
|
|
157
|
+
parts = []
|
|
158
|
+
if len(self.obs_x_idx) > 0:
|
|
159
|
+
parts.append(X[..., self.obs_x_idx])
|
|
160
|
+
if len(self.obs_s_idx) > 0:
|
|
161
|
+
parts.append(S[..., self.obs_s_idx])
|
|
162
|
+
|
|
163
|
+
y = parts[0] if len(parts) == 1 else torch.cat(parts, dim=-1)
|
|
164
|
+
|
|
165
|
+
y_log = torch.log(y.clamp_min(1e-6))
|
|
166
|
+
u = self.net(y_log)
|
|
167
|
+
|
|
168
|
+
return self._scatter_to_state(u, X, S)
|
|
169
|
+
|
|
170
|
+
def get_input_history(
|
|
171
|
+
self, trajectory: torch.Tensor, model: BaseODEModel
|
|
172
|
+
) -> torch.Tensor:
|
|
173
|
+
"""
|
|
174
|
+
Reconstructs the full control trajectory u(X_obs, S_obs) for visualization.
|
|
175
|
+
|
|
176
|
+
The control signal is evaluated along the provided trajectory using only
|
|
177
|
+
the observed components of the state.
|
|
178
|
+
|
|
179
|
+
Parameters
|
|
180
|
+
----------
|
|
181
|
+
trajectory : torch.Tensor
|
|
182
|
+
Shape (Steps, State_Dim), where State_Dim = n_species + n_resources.
|
|
183
|
+
|
|
184
|
+
Returns
|
|
185
|
+
-------
|
|
186
|
+
U_tensor : torch.Tensor
|
|
187
|
+
Shape (Steps, Output_Dim). The control signal at each time step.
|
|
188
|
+
"""
|
|
189
|
+
U_list = []
|
|
190
|
+
|
|
191
|
+
for t_idx in range(trajectory.shape[0]):
|
|
192
|
+
y = trajectory[t_idx]
|
|
193
|
+
X = y[: self.n_species]
|
|
194
|
+
S = y[self.n_species : self.n_species + self.n_resources]
|
|
195
|
+
|
|
196
|
+
parts = []
|
|
197
|
+
if len(self.obs_x_idx) > 0:
|
|
198
|
+
parts.append(X[self.obs_x_idx])
|
|
199
|
+
if len(self.obs_s_idx) > 0:
|
|
200
|
+
parts.append(S[self.obs_s_idx])
|
|
201
|
+
|
|
202
|
+
y_obs = parts[0] if len(parts) == 1 else torch.cat(parts, dim=-1)
|
|
203
|
+
|
|
204
|
+
y_log = torch.log(y_obs.clamp_min(1e-6))
|
|
205
|
+
u = self.net(y_log).reshape(-1)
|
|
206
|
+
U_list.append(u)
|
|
207
|
+
|
|
208
|
+
return torch.stack(U_list, dim=0)
|