diff-renewal-network 1.0.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.
- diff_renewal/__init__.py +211 -0
- diff_renewal/__main__.py +6 -0
- diff_renewal/api.py +654 -0
- diff_renewal/baselines.py +282 -0
- diff_renewal/capping.py +107 -0
- diff_renewal/cli.py +63 -0
- diff_renewal/design.py +129 -0
- diff_renewal/diagnostics.py +188 -0
- diff_renewal/laplace_solver.py +420 -0
- diff_renewal/mean_field.py +256 -0
- diff_renewal/memory.py +154 -0
- diff_renewal/network.py +107 -0
- diff_renewal/neural_clock.py +52 -0
- diff_renewal/observations.py +15 -0
- diff_renewal/phase_type.py +79 -0
- diff_renewal/py.typed +0 -0
- diff_renewal/race.py +274 -0
- diff_renewal/reduction.py +534 -0
- diff_renewal/renewal.py +61 -0
- diff_renewal/semi_markov.py +199 -0
- diff_renewal/sparse_network.py +161 -0
- diff_renewal/traits.py +101 -0
- diff_renewal_network-1.0.0.dist-info/METADATA +421 -0
- diff_renewal_network-1.0.0.dist-info/RECORD +28 -0
- diff_renewal_network-1.0.0.dist-info/WHEEL +5 -0
- diff_renewal_network-1.0.0.dist-info/entry_points.txt +2 -0
- diff_renewal_network-1.0.0.dist-info/licenses/LICENSE +21 -0
- diff_renewal_network-1.0.0.dist-info/top_level.txt +1 -0
diff_renewal/api.py
ADDED
|
@@ -0,0 +1,654 @@
|
|
|
1
|
+
"""High-level user-facing API for Differentiable Renewal Networks (DRNs).
|
|
2
|
+
|
|
3
|
+
Wraps the exact verified JAX/Diffrax primitives in ``diff_renewal`` behind a
|
|
4
|
+
concise, ergonomic interface for building, compiling, simulating, differentiating,
|
|
5
|
+
fitting, compressing, and designing experiments on continuous-time non-Markovian
|
|
6
|
+
renewal networks:
|
|
7
|
+
|
|
8
|
+
- :class:`RenewalNetwork`: Directed graph with competing mixed-Erlang clocks
|
|
9
|
+
compiled via exact marked-race compilation (Proposition 1), supporting forward
|
|
10
|
+
prediction, exact Jacobians, snapshot MLE fitting, Fisher information, and
|
|
11
|
+
scenario-robust A-optimal experimental design.
|
|
12
|
+
- :class:`TalbotRenewalNetwork`: Stiffness- and stage-count-independent node-level
|
|
13
|
+
Laplace--Schur--Talbot solver (Proposition 5) for simultaneous fresh and
|
|
14
|
+
zero-shot aged occupancy prediction on Hyper-Erlang renewal graphs.
|
|
15
|
+
- :func:`calibrate_clock_compressor`: Offline data-free universal positive
|
|
16
|
+
Fisher-sensitivity clock compressor (``Pos-Sens``, Theorems 4--5).
|
|
17
|
+
- :func:`sensitivity_separation_demo`: Exact modal symmetry-reduction diagnostic
|
|
18
|
+
reproducing the paper's prediction-versus-learning separation (Theorems 1--3).
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
from dataclasses import dataclass
|
|
24
|
+
from typing import Sequence
|
|
25
|
+
|
|
26
|
+
import jax
|
|
27
|
+
import jax.numpy as jnp
|
|
28
|
+
import numpy as np
|
|
29
|
+
from scipy.linalg import expm_frechet, helmert
|
|
30
|
+
from scipy.optimize import minimize
|
|
31
|
+
|
|
32
|
+
from .design import optimize_fisher_allocation
|
|
33
|
+
from .diagnostics import multinomial_score_design
|
|
34
|
+
from .laplace_solver import solve_renewal_talbot
|
|
35
|
+
from .network import network_layout, network_state_size, solve_renewal_network
|
|
36
|
+
from .observations import multinomial_nll
|
|
37
|
+
from .race import compact_network_state_size, solve_compact_renewal_network
|
|
38
|
+
from .reduction import calibrate_universal_pos_clock, universal_pos_clock
|
|
39
|
+
from .traits import moment_matched_logits
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class FitResult:
|
|
44
|
+
"""Result returned by :meth:`RenewalNetwork.fit`."""
|
|
45
|
+
|
|
46
|
+
means: np.ndarray
|
|
47
|
+
shapes: np.ndarray
|
|
48
|
+
nll: float
|
|
49
|
+
objective: float
|
|
50
|
+
success: bool
|
|
51
|
+
iterations: int
|
|
52
|
+
message: str
|
|
53
|
+
predicted: np.ndarray
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass(frozen=True)
|
|
57
|
+
class ClockCompressor:
|
|
58
|
+
"""Certified topology-agnostic positive Coxian clock compressor (``Pos-Sens``).
|
|
59
|
+
|
|
60
|
+
Maps any ``(mean, shape)`` pair inside the calibrated cone to a strictly
|
|
61
|
+
Metzler ``stages_red``-stage Coxian chain preserving the exact mean while
|
|
62
|
+
controlling both survival and shape-sensitivity error (Theorems 4--5).
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
psi: np.ndarray
|
|
66
|
+
stages_red: int
|
|
67
|
+
stages_full: int
|
|
68
|
+
cone_min_shape: float
|
|
69
|
+
cone_max_shape: float
|
|
70
|
+
sup_survival_abs_error: float
|
|
71
|
+
sup_shape_sens_abs_error: float
|
|
72
|
+
calibration_seconds: float
|
|
73
|
+
|
|
74
|
+
def clock(self, mean, shape) -> tuple[jax.Array, jax.Array]:
|
|
75
|
+
"""Return ``(stage_rates, entry_weights)`` for a positive Coxian clock."""
|
|
76
|
+
return universal_pos_clock(
|
|
77
|
+
mean,
|
|
78
|
+
shape,
|
|
79
|
+
jnp.asarray(self.psi),
|
|
80
|
+
stages_red=self.stages_red,
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@dataclass(frozen=True)
|
|
85
|
+
class SensitivitySeparationReport:
|
|
86
|
+
"""Exact comparison of full vs. symmetry-reduced cycle occupations and derivatives."""
|
|
87
|
+
|
|
88
|
+
n_nodes: int
|
|
89
|
+
stages: int
|
|
90
|
+
mean: float
|
|
91
|
+
full_states: int
|
|
92
|
+
reduced_states: int
|
|
93
|
+
canceled_modes: int
|
|
94
|
+
max_occupation_error: float
|
|
95
|
+
max_rate_sensitivity_defect: float
|
|
96
|
+
ts: np.ndarray
|
|
97
|
+
full_occ: np.ndarray
|
|
98
|
+
reduced_occ: np.ndarray
|
|
99
|
+
full_sens: np.ndarray
|
|
100
|
+
reduced_sens: np.ndarray
|
|
101
|
+
full_poles: np.ndarray
|
|
102
|
+
reduced_poles: np.ndarray
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class RenewalNetwork:
|
|
106
|
+
"""Differentiable finite-state renewal network with competing mixed-Erlang clocks.
|
|
107
|
+
|
|
108
|
+
Parameters
|
|
109
|
+
----------
|
|
110
|
+
n_nodes : int
|
|
111
|
+
Number of observable macro-states ``V``.
|
|
112
|
+
edges : sequence of (int, int)
|
|
113
|
+
Directed edges ``(source, target)`` with indices in ``0 .. V - 1``.
|
|
114
|
+
stages : int, default=16
|
|
115
|
+
Number of Erlang phases ``K`` per competing edge clock.
|
|
116
|
+
width : float, default=0.5
|
|
117
|
+
Gaussian smoothing width used by differentiable moment matching.
|
|
118
|
+
node_names : sequence of str, optional
|
|
119
|
+
Human-readable labels for the ``V`` observable states.
|
|
120
|
+
"""
|
|
121
|
+
|
|
122
|
+
def __init__(
|
|
123
|
+
self,
|
|
124
|
+
n_nodes: int,
|
|
125
|
+
edges: Sequence[tuple[int, int]],
|
|
126
|
+
*,
|
|
127
|
+
stages: int = 16,
|
|
128
|
+
width: float = 0.5,
|
|
129
|
+
node_names: Sequence[str] | None = None,
|
|
130
|
+
) -> None:
|
|
131
|
+
if not isinstance(stages, int) or isinstance(stages, bool) or stages < 2:
|
|
132
|
+
raise ValueError("stages must be an integer >= 2")
|
|
133
|
+
self.edges, self.outgoing = network_layout(edges, n_nodes)
|
|
134
|
+
if not self.edges:
|
|
135
|
+
raise ValueError("RenewalNetwork requires at least one directed edge")
|
|
136
|
+
self.n_nodes = int(n_nodes)
|
|
137
|
+
self.stages = int(stages)
|
|
138
|
+
self.width = float(width)
|
|
139
|
+
if node_names is not None:
|
|
140
|
+
names = tuple(str(n) for n in node_names)
|
|
141
|
+
if len(names) != self.n_nodes:
|
|
142
|
+
raise ValueError("node_names length must equal n_nodes")
|
|
143
|
+
self.node_names = names
|
|
144
|
+
else:
|
|
145
|
+
self.node_names = tuple(f"node_{i}" for i in range(self.n_nodes))
|
|
146
|
+
|
|
147
|
+
@property
|
|
148
|
+
def n_edges(self) -> int:
|
|
149
|
+
"""Number of directed edges ``E``."""
|
|
150
|
+
return len(self.edges)
|
|
151
|
+
|
|
152
|
+
@property
|
|
153
|
+
def tensor_state_size(self) -> int:
|
|
154
|
+
"""Naive joint tensor state count ``sum_i K**outdegree(i)``."""
|
|
155
|
+
return network_state_size(self.edges, self.n_nodes, self.stages)
|
|
156
|
+
|
|
157
|
+
@property
|
|
158
|
+
def compact_state_size(self) -> int:
|
|
159
|
+
"""Exact marked-race state count ``sum_i (1 + d_i*(K - 1))`` (Proposition 1)."""
|
|
160
|
+
return compact_network_state_size(self.edges, self.n_nodes, self.stages)
|
|
161
|
+
|
|
162
|
+
@property
|
|
163
|
+
def compression_ratio(self) -> float:
|
|
164
|
+
"""State compression ratio ``tensor_state_size / compact_state_size``."""
|
|
165
|
+
return self.tensor_state_size / float(self.compact_state_size)
|
|
166
|
+
|
|
167
|
+
def __repr__(self) -> str:
|
|
168
|
+
return (
|
|
169
|
+
f"RenewalNetwork(n_nodes={self.n_nodes}, n_edges={self.n_edges}, "
|
|
170
|
+
f"stages={self.stages}, compact_states={self.compact_state_size}, "
|
|
171
|
+
f"tensor_states={self.tensor_state_size})"
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
def _solve_single(
|
|
175
|
+
self,
|
|
176
|
+
means: jax.Array,
|
|
177
|
+
logits: jax.Array,
|
|
178
|
+
initial: jax.Array,
|
|
179
|
+
ts: jax.Array,
|
|
180
|
+
*,
|
|
181
|
+
backend: str = "compact",
|
|
182
|
+
rtol: float = 1e-8,
|
|
183
|
+
atol: float = 1e-10,
|
|
184
|
+
) -> jax.Array:
|
|
185
|
+
if backend == "compact":
|
|
186
|
+
return solve_compact_renewal_network(
|
|
187
|
+
means, logits, self.edges, initial, ts, rtol=rtol, atol=atol
|
|
188
|
+
).ys
|
|
189
|
+
if backend == "tensor":
|
|
190
|
+
return solve_renewal_network(
|
|
191
|
+
means, logits, self.edges, initial, ts, rtol=rtol, atol=atol
|
|
192
|
+
).ys
|
|
193
|
+
raise ValueError(f"Unknown backend {backend!r}; expected 'compact' or 'tensor'")
|
|
194
|
+
|
|
195
|
+
def predict(
|
|
196
|
+
self,
|
|
197
|
+
means,
|
|
198
|
+
shapes=None,
|
|
199
|
+
initial=None,
|
|
200
|
+
ts=None,
|
|
201
|
+
*,
|
|
202
|
+
logits=None,
|
|
203
|
+
backend: str = "compact",
|
|
204
|
+
rtol: float = 1e-8,
|
|
205
|
+
atol: float = 1e-10,
|
|
206
|
+
) -> jax.Array:
|
|
207
|
+
"""Compute node occupancy trajectories for one or multiple initial preparations.
|
|
208
|
+
|
|
209
|
+
Parameters
|
|
210
|
+
----------
|
|
211
|
+
means : array_like of shape (E,)
|
|
212
|
+
Positive mean waiting times per directed edge.
|
|
213
|
+
shapes : array_like of shape (E,), optional
|
|
214
|
+
Positive inverse squared CV shape parameters (mapped smoothly to stage
|
|
215
|
+
logits via :func:`moment_matched_logits`). Mutually exclusive with ``logits``.
|
|
216
|
+
initial : array_like of shape (V,) or (P, V)
|
|
217
|
+
Initial node occupancy vector or batch of ``P`` preparations.
|
|
218
|
+
ts : array_like of shape (T,)
|
|
219
|
+
Strictly increasing positive observation times.
|
|
220
|
+
logits : array_like of shape (E, K), optional
|
|
221
|
+
Explicit stage-count logits overriding ``shapes``.
|
|
222
|
+
backend : {'compact', 'tensor'}, default='compact'
|
|
223
|
+
Exact marked-race compiler (Proposition 1) or reference ``K**d`` tensor solver.
|
|
224
|
+
|
|
225
|
+
Returns
|
|
226
|
+
-------
|
|
227
|
+
jax.Array
|
|
228
|
+
Predicted node occupancies of shape ``(T, V)`` for 1D ``initial`` or
|
|
229
|
+
``(P, T, V)`` for 2D ``initial``.
|
|
230
|
+
"""
|
|
231
|
+
if initial is None or ts is None:
|
|
232
|
+
raise ValueError("initial and ts must be provided")
|
|
233
|
+
if (shapes is None) == (logits is None):
|
|
234
|
+
raise ValueError("Provide exactly one of `shapes` or `logits`")
|
|
235
|
+
means_j = jnp.asarray(means)
|
|
236
|
+
logits_j = (
|
|
237
|
+
moment_matched_logits(shapes, stages=self.stages, width=self.width)
|
|
238
|
+
if logits is None
|
|
239
|
+
else jnp.asarray(logits)
|
|
240
|
+
)
|
|
241
|
+
init_j = jnp.asarray(initial)
|
|
242
|
+
ts_j = jnp.asarray(ts)
|
|
243
|
+
if init_j.ndim == 1:
|
|
244
|
+
return self._solve_single(
|
|
245
|
+
means_j, logits_j, init_j, ts_j, backend=backend, rtol=rtol, atol=atol
|
|
246
|
+
)
|
|
247
|
+
if init_j.ndim == 2:
|
|
248
|
+
return jax.vmap(
|
|
249
|
+
lambda y0: self._solve_single(
|
|
250
|
+
means_j, logits_j, y0, ts_j, backend=backend, rtol=rtol, atol=atol
|
|
251
|
+
)
|
|
252
|
+
)(init_j)
|
|
253
|
+
raise ValueError("initial must have shape (V,) or (P, V)")
|
|
254
|
+
|
|
255
|
+
def jacobian(
|
|
256
|
+
self,
|
|
257
|
+
means,
|
|
258
|
+
shapes,
|
|
259
|
+
initial,
|
|
260
|
+
ts,
|
|
261
|
+
*,
|
|
262
|
+
backend: str = "compact",
|
|
263
|
+
log_space: bool = True,
|
|
264
|
+
rtol: float = 1e-8,
|
|
265
|
+
atol: float = 1e-10,
|
|
266
|
+
) -> tuple[jax.Array, jax.Array]:
|
|
267
|
+
"""Return ``(probabilities, jacobian)`` with respect to ``(means, shapes)``.
|
|
268
|
+
|
|
269
|
+
When ``log_space=True`` (default), derivatives are taken with respect to
|
|
270
|
+
``theta = concat([log(means), log(shapes)])`` of length ``2*E``.
|
|
271
|
+
"""
|
|
272
|
+
m_j = jnp.asarray(means)
|
|
273
|
+
k_j = jnp.asarray(shapes)
|
|
274
|
+
e_cnt = self.n_edges
|
|
275
|
+
|
|
276
|
+
def _aux(theta):
|
|
277
|
+
if log_space:
|
|
278
|
+
m_cur, k_cur = jnp.exp(theta[:e_cnt]), jnp.exp(theta[e_cnt:])
|
|
279
|
+
else:
|
|
280
|
+
m_cur, k_cur = theta[:e_cnt], theta[e_cnt:]
|
|
281
|
+
probs = self.predict(
|
|
282
|
+
m_cur, k_cur, initial, ts, backend=backend, rtol=rtol, atol=atol
|
|
283
|
+
)
|
|
284
|
+
return probs, probs
|
|
285
|
+
|
|
286
|
+
theta0 = jnp.concatenate([jnp.log(m_j), jnp.log(k_j)]) if log_space else jnp.concatenate([m_j, k_j])
|
|
287
|
+
jac, probs = jax.jacrev(_aux, has_aux=True)(theta0)
|
|
288
|
+
return probs, jac
|
|
289
|
+
|
|
290
|
+
def nll(
|
|
291
|
+
self,
|
|
292
|
+
means,
|
|
293
|
+
shapes,
|
|
294
|
+
initial,
|
|
295
|
+
ts,
|
|
296
|
+
counts,
|
|
297
|
+
*,
|
|
298
|
+
backend: str = "compact",
|
|
299
|
+
probability_floor: float = 1e-12,
|
|
300
|
+
) -> jax.Array:
|
|
301
|
+
"""Exact count-weighted multinomial snapshot negative log-likelihood."""
|
|
302
|
+
probs = self.predict(means, shapes, initial, ts, backend=backend)
|
|
303
|
+
return multinomial_nll(probs, counts, probability_floor=probability_floor)
|
|
304
|
+
|
|
305
|
+
def fit(
|
|
306
|
+
self,
|
|
307
|
+
initial,
|
|
308
|
+
ts,
|
|
309
|
+
counts,
|
|
310
|
+
*,
|
|
311
|
+
init_means=None,
|
|
312
|
+
init_shapes=None,
|
|
313
|
+
l2_reg: float = 0.0,
|
|
314
|
+
mean_bounds: tuple[float, float] = (0.1, 50.0),
|
|
315
|
+
shape_bounds: tuple[float, float] | None = None,
|
|
316
|
+
maxiter: int = 200,
|
|
317
|
+
ftol: float = 1e-11,
|
|
318
|
+
gtol: float = 1e-7,
|
|
319
|
+
backend: str = "compact",
|
|
320
|
+
rtol: float = 1e-8,
|
|
321
|
+
atol: float = 1e-10,
|
|
322
|
+
) -> FitResult:
|
|
323
|
+
"""Fit edge ``(means, shapes)`` to multinomial snapshot counts via L-BFGS-B.
|
|
324
|
+
|
|
325
|
+
Parameters
|
|
326
|
+
----------
|
|
327
|
+
initial : array_like of shape (V,) or (P, V)
|
|
328
|
+
Initial node distribution(s).
|
|
329
|
+
ts : array_like of shape (T,)
|
|
330
|
+
Observation times.
|
|
331
|
+
counts : array_like of shape (T, V) or (P, T, V)
|
|
332
|
+
Observed cell/event counts matching the output shape of :meth:`predict`.
|
|
333
|
+
init_means, init_shapes : array_like of shape (E,), optional
|
|
334
|
+
Starting parameter guesses (defaults: ``means = 2.0``, ``shapes = min(4.0, K-1)``).
|
|
335
|
+
l2_reg : float, default=0.0
|
|
336
|
+
Optional quadratic regularization penalty on ``theta - theta0`` in log space.
|
|
337
|
+
mean_bounds : (float, float), default=(0.1, 50.0)
|
|
338
|
+
Lower and upper bounds on edge mean waiting times.
|
|
339
|
+
shape_bounds : (float, float), optional
|
|
340
|
+
Lower and upper bounds on edge shapes. Defaults to ``(1.5, 0.8 * stages)``.
|
|
341
|
+
maxiter : int, default=200
|
|
342
|
+
Maximum L-BFGS-B iterations.
|
|
343
|
+
"""
|
|
344
|
+
e_cnt = self.n_edges
|
|
345
|
+
counts_j = jnp.asarray(counts, dtype=jnp.float64)
|
|
346
|
+
init_j = jnp.asarray(initial, dtype=jnp.float64)
|
|
347
|
+
ts_j = jnp.asarray(ts, dtype=jnp.float64)
|
|
348
|
+
|
|
349
|
+
m0 = np.full(e_cnt, 2.0, dtype=float) if init_means is None else np.asarray(init_means, dtype=float)
|
|
350
|
+
k_default = min(4.0, max(1.6, 0.5 * self.stages))
|
|
351
|
+
k0 = np.full(e_cnt, k_default, dtype=float) if init_shapes is None else np.asarray(init_shapes, dtype=float)
|
|
352
|
+
if m0.shape != (e_cnt,) or k0.shape != (e_cnt,):
|
|
353
|
+
raise ValueError(f"init_means and init_shapes must have shape ({e_cnt},)")
|
|
354
|
+
|
|
355
|
+
k_lo, k_hi = (1.25, max(1.5, 0.85 * self.stages)) if shape_bounds is None else shape_bounds
|
|
356
|
+
m_lo, m_hi = mean_bounds
|
|
357
|
+
theta0 = np.concatenate([np.log(m0), np.log(k0)])
|
|
358
|
+
theta0_j = jnp.asarray(theta0)
|
|
359
|
+
bounds = [(np.log(m_lo), np.log(m_hi))] * e_cnt + [(np.log(k_lo), np.log(k_hi))] * e_cnt
|
|
360
|
+
|
|
361
|
+
def _loss(th):
|
|
362
|
+
probs = self.predict(
|
|
363
|
+
jnp.exp(th[:e_cnt]),
|
|
364
|
+
jnp.exp(th[e_cnt:]),
|
|
365
|
+
init_j,
|
|
366
|
+
ts_j,
|
|
367
|
+
backend=backend,
|
|
368
|
+
rtol=rtol,
|
|
369
|
+
atol=atol,
|
|
370
|
+
)
|
|
371
|
+
val = multinomial_nll(probs, counts_j)
|
|
372
|
+
if l2_reg > 0.0:
|
|
373
|
+
val = val + l2_reg * jnp.sum((th - theta0_j) ** 2)
|
|
374
|
+
return val
|
|
375
|
+
|
|
376
|
+
vg = jax.jit(jax.value_and_grad(_loss))
|
|
377
|
+
|
|
378
|
+
def _obj(z):
|
|
379
|
+
v, g = vg(jnp.asarray(z))
|
|
380
|
+
return float(v), np.asarray(g, dtype=float)
|
|
381
|
+
|
|
382
|
+
res = minimize(
|
|
383
|
+
_obj,
|
|
384
|
+
theta0,
|
|
385
|
+
method="L-BFGS-B",
|
|
386
|
+
jac=True,
|
|
387
|
+
bounds=bounds,
|
|
388
|
+
options={"maxiter": maxiter, "ftol": ftol, "gtol": gtol},
|
|
389
|
+
)
|
|
390
|
+
m_hat = np.exp(res.x[:e_cnt])
|
|
391
|
+
k_hat = np.exp(res.x[e_cnt:])
|
|
392
|
+
pred = np.asarray(
|
|
393
|
+
self.predict(m_hat, k_hat, init_j, ts_j, backend=backend, rtol=rtol, atol=atol),
|
|
394
|
+
dtype=float,
|
|
395
|
+
)
|
|
396
|
+
nll_val = float(multinomial_nll(pred, np.asarray(counts_j)))
|
|
397
|
+
return FitResult(
|
|
398
|
+
means=m_hat,
|
|
399
|
+
shapes=k_hat,
|
|
400
|
+
nll=nll_val,
|
|
401
|
+
objective=float(res.fun),
|
|
402
|
+
success=bool(res.success),
|
|
403
|
+
iterations=int(res.nit),
|
|
404
|
+
message=str(res.message),
|
|
405
|
+
predicted=pred,
|
|
406
|
+
)
|
|
407
|
+
|
|
408
|
+
def fisher_information(
|
|
409
|
+
self,
|
|
410
|
+
means,
|
|
411
|
+
shapes,
|
|
412
|
+
preparations,
|
|
413
|
+
ts,
|
|
414
|
+
*,
|
|
415
|
+
backend: str = "compact",
|
|
416
|
+
probability_floor: float = 1e-12,
|
|
417
|
+
) -> np.ndarray:
|
|
418
|
+
"""Compute per-cell Fisher information matrices of shape ``(M, 2E, 2E)``.
|
|
419
|
+
|
|
420
|
+
Candidates ``M = P * T`` flatten ``(preparation, time)`` in row-major order.
|
|
421
|
+
"""
|
|
422
|
+
prep_arr = np.asarray(preparations, dtype=float)
|
|
423
|
+
if prep_arr.ndim == 1:
|
|
424
|
+
prep_arr = prep_arr[None, :]
|
|
425
|
+
probs, jac = self.jacobian(means, shapes, prep_arr, ts, backend=backend, log_space=True)
|
|
426
|
+
p_np = np.asarray(probs, dtype=float).reshape(-1, self.n_nodes)
|
|
427
|
+
j_np = np.asarray(jac, dtype=float).reshape(-1, self.n_nodes, 2 * self.n_edges)
|
|
428
|
+
p_safe = np.maximum(p_np, probability_floor)
|
|
429
|
+
p_safe = p_safe / p_safe.sum(axis=1, keepdims=True)
|
|
430
|
+
# Ensure exact zero row-sum for derivative rows under probability floor
|
|
431
|
+
j_safe = j_np - j_np.mean(axis=1, keepdims=True)
|
|
432
|
+
mats = []
|
|
433
|
+
for row_p, row_j in zip(p_safe, j_safe):
|
|
434
|
+
w = multinomial_score_design(row_p[None, :], row_j[None, :, :], sample_sizes=1.0)
|
|
435
|
+
mats.append(w.T @ w)
|
|
436
|
+
return np.stack(mats, axis=0)
|
|
437
|
+
|
|
438
|
+
def optimal_design(
|
|
439
|
+
self,
|
|
440
|
+
means,
|
|
441
|
+
shapes,
|
|
442
|
+
preparations,
|
|
443
|
+
ts,
|
|
444
|
+
budget: int,
|
|
445
|
+
*,
|
|
446
|
+
pilot_information=None,
|
|
447
|
+
pilot_ridge: float = 1e-3,
|
|
448
|
+
interest: str | Sequence[int] = "all",
|
|
449
|
+
scenarios: Sequence[tuple] | None = None,
|
|
450
|
+
backend: str = "compact",
|
|
451
|
+
**kwargs,
|
|
452
|
+
) -> dict:
|
|
453
|
+
"""Compute a scenario-robust A-optimal Fisher allocation over ``(prep, time)`` arms.
|
|
454
|
+
|
|
455
|
+
Parameters
|
|
456
|
+
----------
|
|
457
|
+
interest : {'all', 'means', 'shapes'} or sequence of int, default='all'
|
|
458
|
+
Parameter indices included in the A-optimal inverse-Fisher trace criterion.
|
|
459
|
+
scenarios : sequence of (means, shapes), optional
|
|
460
|
+
Multiple pilot parameter scenarios averaged in the convex objective.
|
|
461
|
+
"""
|
|
462
|
+
e_cnt = self.n_edges
|
|
463
|
+
scen_list = [(means, shapes)] if scenarios is None else list(scenarios)
|
|
464
|
+
info = np.stack(
|
|
465
|
+
[self.fisher_information(m, k, preparations, ts, backend=backend) for m, k in scen_list],
|
|
466
|
+
axis=0,
|
|
467
|
+
)
|
|
468
|
+
if pilot_information is None:
|
|
469
|
+
pilot = np.broadcast_to(
|
|
470
|
+
pilot_ridge * np.eye(2 * e_cnt), (len(scen_list), 2 * e_cnt, 2 * e_cnt)
|
|
471
|
+
).copy()
|
|
472
|
+
else:
|
|
473
|
+
pilot = np.asarray(pilot_information, dtype=float)
|
|
474
|
+
if pilot.ndim == 2:
|
|
475
|
+
pilot = np.broadcast_to(pilot, (len(scen_list),) + pilot.shape).copy()
|
|
476
|
+
|
|
477
|
+
if interest == "all":
|
|
478
|
+
idx = list(range(2 * e_cnt))
|
|
479
|
+
elif interest == "means":
|
|
480
|
+
idx = list(range(e_cnt))
|
|
481
|
+
elif interest == "shapes":
|
|
482
|
+
idx = list(range(e_cnt, 2 * e_cnt))
|
|
483
|
+
else:
|
|
484
|
+
idx = list(interest)
|
|
485
|
+
return optimize_fisher_allocation(info, pilot, budget, idx, **kwargs)
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
class TalbotRenewalNetwork:
|
|
489
|
+
"""Stiffness- and stage-count-independent Laplace--Schur--Talbot solver (Prop. 5).
|
|
490
|
+
|
|
491
|
+
Operates purely via ``V x V`` node-level resolvent inversions along the
|
|
492
|
+
Weideman (2006) optimal fixed-Talbot contour, supporting arbitrarily stiff
|
|
493
|
+
fast/slow Hyper-Erlang clocks and simultaneous fresh + zero-shot aged forecasts.
|
|
494
|
+
|
|
495
|
+
Parameters
|
|
496
|
+
----------
|
|
497
|
+
routing : array_like of shape (V, V)
|
|
498
|
+
Column-stochastic routing matrix with entry ``R[dst, src] = P(src -> dst)``.
|
|
499
|
+
active_mask : array_like of shape (V,), optional
|
|
500
|
+
Binary mask (``1`` for transient nodes, ``0`` for absorbing sinks).
|
|
501
|
+
Inferred automatically from positive column sums of ``routing`` if omitted.
|
|
502
|
+
n_talbot : int, default=16
|
|
503
|
+
Even number of contour quadrature nodes (``16`` gives ~1e-8 accuracy,
|
|
504
|
+
``24`` gives ~1e-10 accuracy independent of stiffness ratio).
|
|
505
|
+
"""
|
|
506
|
+
|
|
507
|
+
def __init__(
|
|
508
|
+
self,
|
|
509
|
+
routing,
|
|
510
|
+
active_mask=None,
|
|
511
|
+
*,
|
|
512
|
+
n_talbot: int = 16,
|
|
513
|
+
) -> None:
|
|
514
|
+
r_arr = np.asarray(routing, dtype=float)
|
|
515
|
+
if r_arr.ndim != 2 or r_arr.shape[0] != r_arr.shape[1] or r_arr.shape[0] < 1:
|
|
516
|
+
raise ValueError("routing must be a nonempty square (V, V) matrix")
|
|
517
|
+
self.n_nodes = int(r_arr.shape[0])
|
|
518
|
+
self.routing = jnp.asarray(r_arr)
|
|
519
|
+
if active_mask is None:
|
|
520
|
+
self.active_mask = jnp.asarray((r_arr.sum(axis=0) > 0.0).astype(float))
|
|
521
|
+
else:
|
|
522
|
+
self.active_mask = jnp.asarray(active_mask, dtype=float)
|
|
523
|
+
self.n_talbot = int(n_talbot)
|
|
524
|
+
|
|
525
|
+
def predict(
|
|
526
|
+
self,
|
|
527
|
+
fast_rates,
|
|
528
|
+
slow_rates,
|
|
529
|
+
fast_weights,
|
|
530
|
+
slow_entry,
|
|
531
|
+
horizons,
|
|
532
|
+
*,
|
|
533
|
+
eval_nodes=None,
|
|
534
|
+
age: float = 0.0,
|
|
535
|
+
return_both_fresh_and_aged: bool = False,
|
|
536
|
+
):
|
|
537
|
+
"""Evaluate exact fresh and/or zero-shot aged node occupancy matrices."""
|
|
538
|
+
return solve_renewal_talbot(
|
|
539
|
+
jnp.asarray(fast_rates),
|
|
540
|
+
jnp.asarray(slow_rates),
|
|
541
|
+
jnp.asarray(fast_weights),
|
|
542
|
+
jnp.asarray(slow_entry),
|
|
543
|
+
self.routing,
|
|
544
|
+
horizons,
|
|
545
|
+
self.active_mask,
|
|
546
|
+
eval_nodes=eval_nodes,
|
|
547
|
+
age=age,
|
|
548
|
+
n_talbot=self.n_talbot,
|
|
549
|
+
return_both_fresh_and_aged=return_both_fresh_and_aged,
|
|
550
|
+
)
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
def calibrate_clock_compressor(
|
|
554
|
+
*,
|
|
555
|
+
stages_red: int = 8,
|
|
556
|
+
stages_full: int = 16,
|
|
557
|
+
k_min: float = 1.4,
|
|
558
|
+
k_max: float = 7.8,
|
|
559
|
+
maxiter: int = 250,
|
|
560
|
+
) -> ClockCompressor:
|
|
561
|
+
"""Calibrate a certified universal positive Coxian clock compressor (``Pos-Sens``)."""
|
|
562
|
+
psi, cert = calibrate_universal_pos_clock(
|
|
563
|
+
stages_red=stages_red,
|
|
564
|
+
stages_full=stages_full,
|
|
565
|
+
k_min=k_min,
|
|
566
|
+
k_max=k_max,
|
|
567
|
+
maxiter=maxiter,
|
|
568
|
+
)
|
|
569
|
+
return ClockCompressor(
|
|
570
|
+
psi=np.asarray(psi, dtype=float),
|
|
571
|
+
stages_red=int(cert["stages_red"]),
|
|
572
|
+
stages_full=int(cert["stages_full"]),
|
|
573
|
+
cone_min_shape=float(cert["cone_min_shape"]),
|
|
574
|
+
cone_max_shape=float(cert["cone_max_shape"]),
|
|
575
|
+
sup_survival_abs_error=float(cert["sup_survival_abs_error"]),
|
|
576
|
+
sup_shape_sens_abs_error=float(cert["sup_shape_sens_abs_error"]),
|
|
577
|
+
calibration_seconds=float(cert["calibration_seconds"]),
|
|
578
|
+
)
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
def sensitivity_separation_demo(
|
|
582
|
+
*,
|
|
583
|
+
n_nodes: int = 3,
|
|
584
|
+
stages: int = 16,
|
|
585
|
+
mean: float = 2.0,
|
|
586
|
+
ts: np.ndarray | None = None,
|
|
587
|
+
) -> SensitivitySeparationReport:
|
|
588
|
+
"""Reproduce the exact prediction-vs-learning separation on a symmetric Erlang cycle.
|
|
589
|
+
|
|
590
|
+
On a symmetric ``V``-node directed cycle with ``K``-stage Erlang clocks of equal
|
|
591
|
+
mean ``m`` (rate ``lambda = K / m``), ``K - 1`` common-mode poles cancel identically
|
|
592
|
+
from the occupation transfer (Theorems 1--2), yielding an exact minimal predictive
|
|
593
|
+
realization of dimension ``(V - 1) * K + 1`` (``33`` for ``V=3, K=16``). Yet a local
|
|
594
|
+
clock-rate perturbation restores every canceled pole (Theorem 3), forcing the
|
|
595
|
+
minimal sensitivity realization back to all ``V * K`` physical states (``48``).
|
|
596
|
+
"""
|
|
597
|
+
if n_nodes < 2 or stages < 2 or mean <= 0.0:
|
|
598
|
+
raise ValueError("Require n_nodes >= 2, stages >= 2, and mean > 0")
|
|
599
|
+
dim_full = n_nodes * stages
|
|
600
|
+
rate = float(stages) / float(mean)
|
|
601
|
+
a_full = -rate * np.eye(dim_full)
|
|
602
|
+
for col in range(dim_full):
|
|
603
|
+
a_full[(col + 1) % dim_full, col] += rate
|
|
604
|
+
da_full = a_full.copy()
|
|
605
|
+
da_full[:, stages:] = 0.0 # local log-rate perturbation on node 0
|
|
606
|
+
|
|
607
|
+
b_full = np.eye(dim_full)[:, [i * stages for i in range(n_nodes)]]
|
|
608
|
+
c_full = np.kron(np.eye(n_nodes), np.ones((1, stages)))
|
|
609
|
+
|
|
610
|
+
contrasts = np.kron(helmert(n_nodes, full=False).T, np.eye(stages))
|
|
611
|
+
w_mat = np.vstack([contrasts.T, np.ones(dim_full)])
|
|
612
|
+
v_mat = np.column_stack([contrasts, np.ones(dim_full) / float(dim_full)])
|
|
613
|
+
c_red = np.column_stack([c_full @ contrasts, np.ones(n_nodes) / float(n_nodes)])
|
|
614
|
+
a_red = w_mat @ a_full @ v_mat
|
|
615
|
+
da_red = w_mat @ da_full @ v_mat
|
|
616
|
+
b_red = w_mat @ b_full
|
|
617
|
+
|
|
618
|
+
t_grid = np.linspace(0.0, 7.0, 141) if ts is None else np.asarray(ts, dtype=float)
|
|
619
|
+
pi_unif = np.ones(n_nodes) / float(n_nodes)
|
|
620
|
+
|
|
621
|
+
full_occ, red_occ, full_sens, red_sens = [], [], [], []
|
|
622
|
+
max_occ_err = 0.0
|
|
623
|
+
max_sens_err = 0.0
|
|
624
|
+
for t_val in t_grid:
|
|
625
|
+
ef, df = expm_frechet(t_val * a_full, t_val * da_full)
|
|
626
|
+
er, dr = expm_frechet(t_val * a_red, t_val * da_red)
|
|
627
|
+
pf = c_full @ ef @ b_full
|
|
628
|
+
pr = c_red @ er @ b_red
|
|
629
|
+
max_occ_err = max(max_occ_err, float(np.max(np.abs(pf - pr))))
|
|
630
|
+
sf = c_full @ df @ b_full @ pi_unif
|
|
631
|
+
sr = c_red @ dr @ b_red @ pi_unif
|
|
632
|
+
max_sens_err = max(max_sens_err, float(np.max(np.abs(sf - sr))))
|
|
633
|
+
full_occ.append(pf[0, 0])
|
|
634
|
+
red_occ.append(pr[0, 0])
|
|
635
|
+
full_sens.append(sf[0])
|
|
636
|
+
red_sens.append(sr[0])
|
|
637
|
+
|
|
638
|
+
return SensitivitySeparationReport(
|
|
639
|
+
n_nodes=n_nodes,
|
|
640
|
+
stages=stages,
|
|
641
|
+
mean=float(mean),
|
|
642
|
+
full_states=dim_full,
|
|
643
|
+
reduced_states=a_red.shape[0],
|
|
644
|
+
canceled_modes=stages - 1,
|
|
645
|
+
max_occupation_error=max_occ_err,
|
|
646
|
+
max_rate_sensitivity_defect=max_sens_err,
|
|
647
|
+
ts=t_grid,
|
|
648
|
+
full_occ=np.asarray(full_occ),
|
|
649
|
+
reduced_occ=np.asarray(red_occ),
|
|
650
|
+
full_sens=np.asarray(full_sens),
|
|
651
|
+
reduced_sens=np.asarray(red_sens),
|
|
652
|
+
full_poles=np.linalg.eigvals(a_full),
|
|
653
|
+
reduced_poles=np.linalg.eigvals(a_red),
|
|
654
|
+
)
|