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.
@@ -0,0 +1,282 @@
1
+ """Modern continuous-time neural population baselines on renewal networks.
2
+
3
+ Implements parameter-matched, multi-start population architectures for comparison
4
+ against Conditional Neural Clocks:
5
+ 1. Tuned Population Latent ODE (Rubanova et al., 2019)
6
+ 2. Liquid Time-Constant Population ODE (LTC / CfC; Hasani et al., 2021, 2022)
7
+ 3. Diagonal Structured State-Space Population ODE (S4D; Gu et al., 2022)
8
+ 4. Time-Inhomogeneous Neural Master Equation (Neural-CME; clock-time generator A(t, x, u))
9
+ """
10
+
11
+ import jax
12
+ from jax.flatten_util import ravel_pytree
13
+ import jax.numpy as jnp
14
+ import numpy as np
15
+
16
+
17
+ def init_population_baseline(kind: str, seed: int = 17):
18
+ keys = jax.random.split(jax.random.PRNGKey(seed), 6)
19
+ if kind == "latent_ode":
20
+ width, latent = 16, 6 # 387 parameters
21
+ return (
22
+ jax.random.normal(keys[0], (6, latent)) * 0.35,
23
+ jnp.zeros(latent),
24
+ jax.random.normal(keys[1], (3 + latent + 2, width)) * 0.32,
25
+ jnp.zeros(width),
26
+ jax.random.normal(keys[2], (width, latent + 3)) * 0.16,
27
+ jnp.zeros(latent + 3),
28
+ )
29
+ if kind == "ltc_ode":
30
+ # Liquid Time-Constant ODE: state- and input-modulated time constants tau(y,x,u)
31
+ width, latent = 12, 6 # 378 parameters
32
+ return (
33
+ jax.random.normal(keys[0], (6, latent)) * 0.35,
34
+ jnp.zeros(latent),
35
+ jax.random.normal(keys[1], (3 + latent + 2, width)) * 0.30,
36
+ jnp.zeros(width),
37
+ jax.random.normal(keys[2], (width, latent)) * 0.20, # target attractor A(y,u)
38
+ jnp.zeros(latent),
39
+ jax.random.normal(keys[3], (width, latent)) * 0.20, # liquid rate gate
40
+ jnp.zeros(latent),
41
+ jax.random.normal(keys[4], (latent + 5, 3)) * 0.18, # positive cycle flux head
42
+ jnp.zeros(3),
43
+ )
44
+ if kind == "s4d_ode":
45
+ # Diagonal Structured State-Space (S4D) with multi-timescale log-spaced decay bank
46
+ latent = 12 # 429 active parameters (6 paired skew frequencies)
47
+ log_dt_rates = jnp.linspace(jnp.log(0.15), jnp.log(4.5), latent)
48
+ return (
49
+ jax.random.normal(keys[0], (6, latent)) * 0.35, # age/prep encoder
50
+ jnp.zeros(latent),
51
+ log_dt_rates, # trainable diagonal S4D log decay rates
52
+ jax.random.normal(keys[1], (latent // 2,)) * 0.25, # paired oscillatory/skew coupling
53
+ jax.random.normal(keys[2], (5, latent)) * 0.28, # input B projection (p, trait, u)
54
+ jnp.zeros(latent),
55
+ jax.random.normal(keys[3], (latent + 5, 12)) * 0.25, # nonlinear readout mixer
56
+ jnp.zeros(12),
57
+ jax.random.normal(keys[4], (12, 3)) * 0.18,
58
+ jnp.zeros(3),
59
+ )
60
+ if kind == "neural_cme":
61
+ # Time-Inhomogeneous Neural Master Equation: dp/dt = A_phi(t, trait, base, u) p(t)
62
+ # Isolates clock-time inhomogeneity A(t) from true semi-Markov residence-age memory!
63
+ width = 24 # 7*24 + 24 + 24*6 + 6 = 342 parameters
64
+ return (
65
+ jax.random.normal(keys[0], (7, width)) * 0.35,
66
+ jnp.zeros(width),
67
+ jax.random.normal(keys[1], (width, 6)) * 0.20, # 6 directed off-diagonal rates on 3-node graph
68
+ jnp.zeros(6),
69
+ )
70
+ if kind == "mamba_ode":
71
+ # Input-dependent Selective State-Space Model (Mamba; Gu & Dao 2024):
72
+ # ZOH selective scan with input-dependent step Delta(x), B(x), C(x) & SiLU gate
73
+ latent = 12 # 414 parameters (matched to S4D 429 / Latent ODE 387)
74
+ log_a = jnp.linspace(jnp.log(0.2), jnp.log(4.5), latent)
75
+ return (
76
+ jax.random.normal(keys[0], (6, latent)) * 0.35, # initial encoder
77
+ jnp.zeros(latent),
78
+ log_a, # diagonal negative decay A = -exp(log_a)
79
+ jax.random.normal(keys[1], (5, latent)) * 0.22, # W_delta (input-dep step)
80
+ jnp.full(latent, -1.2), # b_delta
81
+ jax.random.normal(keys[2], (5, latent)) * 0.25, # W_B (input-dep input proj)
82
+ jax.random.normal(keys[3], (5, latent)) * 0.25, # W_C (input-dep readout gate)
83
+ jax.random.normal(keys[4], (5, latent)) * 0.22, # W_z (SiLU residual gate)
84
+ jnp.zeros(latent),
85
+ jax.random.normal(keys[5], (latent + 5, 3)) * 0.18, # flux readout
86
+ jnp.zeros(3),
87
+ )
88
+ raise ValueError(f"Unknown baseline kind: {kind}")
89
+
90
+
91
+ def _rk4_scan(field, state, inputs, sample, read, period: float, substeps: int):
92
+ dt = period / substeps
93
+
94
+ def interval(y, u):
95
+ def substep(_, v):
96
+ k1 = field(v, u)
97
+ k2 = field(v + 0.5 * dt * k1, u)
98
+ k3 = field(v + 0.5 * dt * k2, u)
99
+ k4 = field(v + dt * k3, u)
100
+ return v + (dt / 6.0) * (k1 + 2.0 * k2 + 2.0 * k3 + k4)
101
+
102
+ y_next = jax.lax.fori_loop(0, substeps, substep, y)
103
+ return y_next, read(y_next)
104
+
105
+ obs = jax.lax.scan(interval, state, inputs)[1]
106
+ return obs[sample].transpose(1, 0, 2, 3)
107
+
108
+
109
+ def predict_population_baseline(kind: str, params, plan, *, period: float = 0.25, substeps: int = 4):
110
+ traits, base, age = map(jnp.asarray, (plan.traits, plan.baseline, plan.ages))
111
+ schedule = jnp.asarray(plan.exposure)
112
+ prep = jnp.broadcast_to(jnp.eye(3), (len(traits), 3, 3))
113
+
114
+ def bcast(v):
115
+ return jnp.broadcast_to(v[:, None, None], prep.shape[:-1] + (1,))
116
+
117
+ encoded = jnp.concatenate((prep, bcast(traits), bcast(base), bcast(age)), axis=-1)
118
+
119
+ if kind == "latent_ode":
120
+ enc, eb, w, b, out, ob = params
121
+ state = jnp.concatenate((prep, jnp.tanh(encoded @ enc + eb)), axis=-1)
122
+
123
+ def field(y, u):
124
+ p = y[..., :3]
125
+ inp = jnp.concatenate((y, bcast(traits), bcast(u)), axis=-1)
126
+ raw = jnp.tanh(inp @ w + b) @ out + ob
127
+ flux = p * (0.005 + 5.0 * jax.nn.sigmoid(raw[..., :3] - 1.8))
128
+ return jnp.concatenate((jnp.roll(flux, 1, axis=-1) - flux, jnp.tanh(raw[..., 3:])), axis=-1)
129
+
130
+ return _rk4_scan(field, state, schedule, plan.sample, lambda y: y[..., :3], period, substeps)
131
+
132
+ if kind == "ltc_ode":
133
+ enc, eb, w_h, b_h, w_a, b_a, w_t, b_t, w_f, b_f = params
134
+ z0 = jnp.tanh(encoded @ enc + eb)
135
+ state = jnp.concatenate((prep, z0), axis=-1)
136
+
137
+ def field(y, u):
138
+ p, z = y[..., :3], y[..., 3:]
139
+ inp = jnp.concatenate((p, z, bcast(traits), bcast(u)), axis=-1)
140
+ h = jnp.tanh(inp @ w_h + b_h)
141
+ target = jnp.tanh(h @ w_a + b_a)
142
+ tau_inv = 0.15 + 4.5 * jax.nn.sigmoid(h @ w_t + b_t)
143
+ dz = -tau_inv * (z - target)
144
+ f_inp = jnp.concatenate((p, z, bcast(traits), bcast(u)), axis=-1)
145
+ flux_raw = f_inp @ w_f + b_f
146
+ flux = p * (0.005 + 5.0 * jax.nn.sigmoid(flux_raw - 1.8))
147
+ dp = jnp.roll(flux, 1, axis=-1) - flux
148
+ return jnp.concatenate((dp, dz), axis=-1)
149
+
150
+ return _rk4_scan(field, state, schedule, plan.sample, lambda y: y[..., :3], period, substeps)
151
+
152
+ if kind == "s4d_ode":
153
+ enc, eb, log_rates, omega, w_b, b_b, w_m, b_m, w_o, b_o = params
154
+ z0 = jnp.tanh(encoded @ enc + eb)
155
+ state = jnp.concatenate((prep, z0), axis=-1)
156
+ # Bound decay rate strictly inside RK4 stability region (dt = period/substeps <= 0.0625 -> max ~33 < 44.5)
157
+ decay = jnp.exp(jnp.clip(log_rates, -4.0, 3.3))
158
+ # Skew-symmetric block coupling among pairs of diagonal modes
159
+ half = z0.shape[-1] // 2
160
+
161
+ def field(y, u):
162
+ p, z = y[..., :3], y[..., 3:]
163
+ drv_in = jnp.concatenate((p, bcast(traits), bcast(u)), axis=-1)
164
+ drive = drv_in @ w_b + b_b
165
+ z1, z2 = z[..., :half], z[..., half:]
166
+ w_skew = omega[:half]
167
+ rot = jnp.concatenate((-w_skew * z2, w_skew * z1), axis=-1)
168
+ dz = -decay * z + rot + drive
169
+ mix_in = jnp.concatenate((p, z, bcast(traits), bcast(u)), axis=-1)
170
+ hid = jax.nn.gelu(mix_in @ w_m + b_m)
171
+ flux_raw = hid @ w_o + b_o
172
+ flux = p * (0.005 + 5.0 * jax.nn.sigmoid(flux_raw - 1.8))
173
+ dp = jnp.roll(flux, 1, axis=-1) - flux
174
+ return jnp.concatenate((dp, dz), axis=-1)
175
+
176
+ return _rk4_scan(field, state, schedule, plan.sample, lambda y: y[..., :3], period, substeps)
177
+
178
+ if kind == "neural_cme":
179
+ w1, b1, w2, b2 = params
180
+ dt = period / substeps
181
+ t_horizon = jnp.maximum(schedule.shape[0] * period, 1e-6)
182
+
183
+ def interval(carry, step_in):
184
+ p, t_cur = carry
185
+ u = step_in
186
+
187
+ def substep(i_sub, p_st):
188
+ t_now = t_cur + (i_sub + 0.5) * dt
189
+ t_norm = t_now / t_horizon
190
+ t_feats = jnp.stack(
191
+ [
192
+ jnp.broadcast_to(t_norm, traits.shape),
193
+ jnp.broadcast_to(jnp.sin(2.0 * jnp.pi * t_norm), traits.shape),
194
+ jnp.broadcast_to(jnp.cos(2.0 * jnp.pi * t_norm), traits.shape),
195
+ traits,
196
+ base,
197
+ age,
198
+ u,
199
+ ],
200
+ axis=-1,
201
+ ) # (n_plans, 7)
202
+ h = jax.nn.gelu(t_feats @ w1 + b1)
203
+ rates = 0.005 + 5.0 * jax.nn.sigmoid(h @ w2 + b2 - 1.5) # (n_plans, 6)
204
+
205
+ def eval_field(p_cur):
206
+ # 3 forward cycle edges (0->1, 1->2, 2->0) + 3 reverse/skip edges
207
+ f_fwd = p_cur * rates[:, None, :3]
208
+ f_rev = p_cur * rates[:, None, 3:]
209
+ return (
210
+ jnp.roll(f_fwd, 1, axis=-1)
211
+ - f_fwd
212
+ + jnp.roll(f_rev, -1, axis=-1)
213
+ - f_rev
214
+ )
215
+
216
+ k1 = eval_field(p_st)
217
+ k2 = eval_field(p_st + 0.5 * dt * k1)
218
+ k3 = eval_field(p_st + 0.5 * dt * k2)
219
+ k4 = eval_field(p_st + dt * k3)
220
+ return p_st + (dt / 6.0) * (k1 + 2.0 * k2 + 2.0 * k3 + k4)
221
+
222
+ p_next = jax.lax.fori_loop(0, substeps, substep, p)
223
+ return (p_next, t_cur + period), p_next
224
+
225
+ obs = jax.lax.scan(interval, (prep, jnp.array(0.0, dtype=prep.dtype)), schedule)[1]
226
+ return obs[plan.sample].transpose(1, 0, 2, 3)
227
+
228
+ if kind == "mamba_ode":
229
+ enc, eb, log_a, w_dt, b_dt, w_b, w_c, w_z, b_z, w_o, b_o = params
230
+ h0 = jnp.tanh(encoded @ enc + eb)
231
+ dt = period / substeps
232
+ neg_a = -jnp.exp(jnp.clip(log_a, -3.5, 3.0)) # negative diagonal decay
233
+
234
+ def interval(carry, u):
235
+ def substep(_, st):
236
+ p, h = st
237
+ x_in = jnp.concatenate((p, bcast(traits), bcast(u)), axis=-1)
238
+ delta = jax.nn.softplus(x_in @ w_dt + b_dt) * dt
239
+ a_bar = jnp.exp(delta * neg_a)
240
+ # Exact ZOH discretization: expm1(Delta * A) / A * B(x)
241
+ b_bar = (jnp.expm1(delta * neg_a) / neg_a) * (x_in @ w_b)
242
+ h_next = a_bar * h + b_bar
243
+ # Input-dependent selective readout C(x) * h * SiLU(z(x))
244
+ y_sel = (x_in @ w_c) * h_next * jax.nn.silu(x_in @ w_z + b_z)
245
+ f_in = jnp.concatenate((y_sel, x_in), axis=-1)
246
+ flux = p * (0.005 + 5.0 * jax.nn.sigmoid(f_in @ w_o + b_o - 1.8))
247
+ # Mass-preserving midpoint update on simplex p
248
+ dp1 = jnp.roll(flux, 1, axis=-1) - flux
249
+ p_mid = jnp.clip(p + 0.5 * dt * dp1, 1e-12, 1.0)
250
+ p_mid = p_mid / jnp.sum(p_mid, axis=-1, keepdims=True)
251
+ x_mid = jnp.concatenate((p_mid, bcast(traits), bcast(u)), axis=-1)
252
+ f_mid = p_mid * (0.005 + 5.0 * jax.nn.sigmoid(jnp.concatenate((y_sel, x_mid), axis=-1) @ w_o + b_o - 1.8))
253
+ p_next = jnp.clip(p + dt * (jnp.roll(f_mid, 1, axis=-1) - f_mid), 1e-12, 1.0)
254
+ p_next = p_next / jnp.sum(p_next, axis=-1, keepdims=True)
255
+ return (p_next, h_next)
256
+
257
+ st_next = jax.lax.fori_loop(0, substeps, substep, carry)
258
+ return st_next, st_next[0]
259
+
260
+ obs = jax.lax.scan(interval, (prep, h0), schedule)[1]
261
+ return obs[plan.sample].transpose(1, 0, 2, 3)
262
+
263
+ raise ValueError(kind)
264
+
265
+
266
+ def make_baseline_engine(kind: str, train_plan, test_plan, *, seed: int = 17, reg: float = 1e-4):
267
+ params = init_population_baseline(kind, seed)
268
+ flat, unpack = ravel_pytree(params)
269
+
270
+ def loss(w, counts):
271
+ p = predict_population_baseline(kind, unpack(w), train_plan)
272
+ p = jnp.maximum(p, 1e-12)
273
+ p = p / jnp.sum(p, axis=-1, keepdims=True)
274
+ nll = -jnp.sum(counts * jnp.log(p)) / jnp.maximum(jnp.sum(counts), 1.0)
275
+ return nll + reg * jnp.sum(w**2)
276
+
277
+ return (
278
+ np.asarray(flat),
279
+ unpack,
280
+ jax.jit(jax.value_and_grad(loss)),
281
+ jax.jit(lambda w: predict_population_baseline(kind, unpack(w), test_plan)),
282
+ )
@@ -0,0 +1,107 @@
1
+ """Rate-preserving phase capping with coupling and latent-Fisher gradient bounds."""
2
+
3
+ import jax.nn as jnn
4
+ import jax.numpy as jnp
5
+ from jax.scipy.special import logsumexp
6
+ import numpy as np
7
+
8
+
9
+ def cap_mixed_erlang(mean, logits, *, cap: int):
10
+ """Replace latent stage count N by min(N, cap) while preserving exponential rate."""
11
+ logits = jnp.asarray(logits)
12
+ if logits.ndim != 1 or logits.size < 1:
13
+ raise ValueError("logits must be a nonempty vector")
14
+ if not isinstance(cap, int) or isinstance(cap, bool) or not 1 <= cap <= logits.size:
15
+ raise ValueError("cap must be an integer between 1 and the original stage count")
16
+ log_weights = jnn.log_softmax(logits)
17
+ weights = jnp.exp(log_weights)
18
+ counts = jnp.arange(1, logits.size + 1, dtype=weights.dtype)
19
+ rate = jnp.dot(counts, weights) / mean
20
+ capped_logits = jnp.concatenate(
21
+ [log_weights[: cap - 1], logsumexp(log_weights[cap - 1 :])[None]]
22
+ )
23
+ capped_mean = jnp.dot(jnp.minimum(counts, cap), weights) / rate
24
+ tail = (
25
+ jnp.exp(logsumexp(log_weights[cap:]))
26
+ if cap < logits.size
27
+ else jnp.zeros((), dtype=weights.dtype)
28
+ )
29
+ return capped_mean, capped_logits, tail
30
+
31
+
32
+ def capped_network_tv_bound(tail_probabilities, clock_rates, edges, horizon: float):
33
+ """Conservative single-particle path-TV bound under fresh independent resets."""
34
+ tail, rates = np.asarray(tail_probabilities, float), np.asarray(clock_rates, float)
35
+ if tail.ndim != 1 or rates.shape != tail.shape or len(edges) != len(tail):
36
+ raise ValueError("One tail probability and rate are required per edge")
37
+ if not np.all(np.isfinite(tail)) or np.any(tail < 0) or np.any(tail > 1):
38
+ raise ValueError("Tail probabilities must be in [0,1]")
39
+ if (
40
+ not np.all(np.isfinite(rates))
41
+ or np.any(rates <= 0)
42
+ or not np.isfinite(horizon)
43
+ or horizon < 0
44
+ ):
45
+ raise ValueError("Rates must be positive and the horizon finite and nonnegative")
46
+ sources = [edge[0] for edge in edges]
47
+ nodes = []
48
+ for source in sorted(set(sources)):
49
+ selected = np.array([s == source for s in sources])
50
+ tails = tail[selected]
51
+ failure = (
52
+ 1.0 if np.any(tails == 1) else float(-np.expm1(np.log1p(-tails).sum()))
53
+ )
54
+ nodes.append(
55
+ dict(
56
+ source=int(source),
57
+ preparation_failure_probability=failure,
58
+ exit_rate_upper_bound=float(rates[selected].sum()),
59
+ )
60
+ )
61
+ delta = max((row["preparation_failure_probability"] for row in nodes), default=0.0)
62
+ hazard = max((row["exit_rate_upper_bound"] for row in nodes), default=0.0)
63
+ return dict(
64
+ path_tv_bound=min(1.0, delta * (1.0 + hazard * horizon)),
65
+ max_preparation_failure_probability=delta,
66
+ max_exit_rate=hazard,
67
+ expected_preparations_upper_bound=1.0 + hazard * horizon,
68
+ nodes=nodes,
69
+ )
70
+
71
+
72
+ def capped_clock_bank_gradient_bound(
73
+ weights, log_rate_derivatives, log_weight_derivatives, *, cap: int
74
+ ):
75
+ """Loewner-order bound on expectation gradient bias for a finite clock bank."""
76
+ w, dr, dw = [
77
+ np.asarray(v, float)
78
+ for v in (weights, log_rate_derivatives, log_weight_derivatives)
79
+ ]
80
+ if (
81
+ w.ndim != 2
82
+ or dr.ndim != 2
83
+ or dw.shape != w.shape + (dr.shape[-1],)
84
+ or dr.shape[0] != w.shape[0]
85
+ ):
86
+ raise ValueError("Expected weights (E,K), rate scores (E,P), weight scores (E,K,P)")
87
+ if not isinstance(cap, int) or isinstance(cap, bool) or not 1 <= cap <= w.shape[1]:
88
+ raise ValueError("cap must be an integer in [1,K]")
89
+ if not all(np.all(np.isfinite(v)) for v in (w, dr, dw)) or np.any(w <= 0):
90
+ raise ValueError("Weights must be positive and inputs finite")
91
+ if not np.allclose(w.sum(axis=1), 1.0, rtol=0, atol=1e-9):
92
+ raise ValueError("Weights must sum to one")
93
+ if not np.allclose(np.einsum("en,enp->ep", w, dw), 0.0, rtol=0, atol=1e-8):
94
+ raise ValueError("Weight scores must be centered")
95
+ tails = w[:, cap:].sum(axis=1)
96
+ delta = 1.0 if np.any(tails >= 1) else float(-np.expm1(np.log1p(-tails).sum()))
97
+ expected_counts = w @ np.arange(1, w.shape[1] + 1)
98
+ information = np.einsum("e,ei,ej->ij", expected_counts, dr, dr) + np.einsum(
99
+ "en,eni,enj->ij", w, dw, dw
100
+ )
101
+ matrix = delta * information
102
+ return dict(
103
+ cap_failure_probability=delta,
104
+ latent_fisher=information,
105
+ gradient_outer_product_upper_bound=matrix,
106
+ coordinate_absolute_bounds=np.sqrt(np.maximum(np.diag(matrix), 0.0)),
107
+ )
diff_renewal/cli.py ADDED
@@ -0,0 +1,63 @@
1
+ """Lightweight command-line diagnostic entrypoint (`drn-info`)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+
8
+ import diffrax
9
+ import jax
10
+ import numpy as np
11
+ import scipy
12
+
13
+ from . import __version__
14
+ from .api import RenewalNetwork, sensitivity_separation_demo
15
+
16
+
17
+ def main(argv: list[str] | None = None) -> int:
18
+ parser = argparse.ArgumentParser(
19
+ prog="drn-info",
20
+ description="Display diff-renewal-network installation details and run a quick self-check.",
21
+ )
22
+ parser.add_argument(
23
+ "--check",
24
+ action="store_true",
25
+ help="Run a fast (<2s) numerical self-check of marked-race compilation and 33-vs-48 separation.",
26
+ )
27
+ args = parser.parse_args(argv)
28
+
29
+ print(f"diff-renewal-network {__version__}")
30
+ print(f" python : {sys.version.split()[0]}")
31
+ print(f" jax : {jax.__version__} (x64={jax.config.jax_enable_x64}, devices={[str(d) for d in jax.devices()]})")
32
+ print(f" diffrax : {diffrax.__version__}")
33
+ print(f" numpy : {np.__version__}")
34
+ print(f" scipy : {scipy.__version__}")
35
+
36
+ if args.check:
37
+ jax.config.update("jax_enable_x64", True)
38
+ rep = sensitivity_separation_demo(n_nodes=3, stages=16, mean=2.0)
39
+ net = RenewalNetwork(4, [(0, 1), (0, 2), (1, 3), (2, 3)], stages=8)
40
+ ts = np.array([0.5, 1.5, 3.0])
41
+ init = np.array([1.0, 0.0, 0.0, 0.0])
42
+ means = np.array([1.8, 2.2, 1.5, 2.0])
43
+ shapes = np.array([4.0, 5.5, 3.5, 5.0])
44
+ p_comp = np.asarray(net.predict(means, shapes, init, ts, backend="compact"))
45
+ p_tens = np.asarray(net.predict(means, shapes, init, ts, backend="tensor"))
46
+ race_err = float(np.max(np.abs(p_comp - p_tens)))
47
+ assert rep.max_occupation_error < 1e-12
48
+ assert rep.max_rate_sensitivity_defect > 0.25
49
+ assert race_err < 1e-7
50
+ print("Self-check PASSED:")
51
+ print(
52
+ f" Erlang-16 3-cycle : {rep.full_states} -> {rep.reduced_states} states "
53
+ f"(occ err={rep.max_occupation_error:.2e}, rate sens defect={rep.max_rate_sensitivity_defect:.4f})"
54
+ )
55
+ print(
56
+ f" Diamond marked race: {net.tensor_state_size} -> {net.compact_state_size} states "
57
+ f"({net.compression_ratio:.2f}x smaller, max err={race_err:.2e})"
58
+ )
59
+ return 0
60
+
61
+
62
+ if __name__ == "__main__":
63
+ raise SystemExit(main())
diff_renewal/design.py ADDED
@@ -0,0 +1,129 @@
1
+ """Scenario-robust A-optimal Fisher experimental design for snapshot allocations."""
2
+
3
+ import numpy as np
4
+ from scipy.optimize import minimize
5
+
6
+
7
+ def largest_remainder(weights, total: int):
8
+ """Round nonnegative allocation weights to an exact integer cell budget."""
9
+ weights = np.asarray(weights, float)
10
+ if (
11
+ weights.ndim != 1
12
+ or not np.all(np.isfinite(weights))
13
+ or np.any(weights < 0)
14
+ or weights.sum() <= 0
15
+ or not isinstance(total, (int, np.integer))
16
+ or total < 0
17
+ ):
18
+ raise ValueError("Require finite nonnegative weights and a nonnegative integer budget")
19
+ target = total * weights / weights.sum()
20
+ counts = np.floor(target).astype(int)
21
+ order = np.argsort(-(target - counts), kind="stable")
22
+ counts[order[: int(total - counts.sum())]] += 1
23
+ return counts
24
+
25
+
26
+ def a_optimal_value_gradient(weights, information, pilot_information, budget: int, interest):
27
+ """Average trace of interest-block inverse Fisher information across scenarios."""
28
+ w, info, pilot = map(np.asarray, (weights, information, pilot_information))
29
+ selector = np.eye(info.shape[-1])[:, list(interest)]
30
+ full = pilot + budget * np.einsum("m,bmpq->bpq", w, info)
31
+ solved = np.linalg.solve(
32
+ full, np.broadcast_to(selector, (len(info),) + selector.shape)
33
+ )
34
+ value = np.einsum("pi,bpi->", selector, solved) / len(info)
35
+ gradient = -budget * np.einsum("bpi,bmpq,bqi->m", solved, info, solved) / len(info)
36
+ return float(value), gradient
37
+
38
+
39
+ def optimize_fisher_allocation(
40
+ information,
41
+ pilot_information,
42
+ budget: int,
43
+ interest,
44
+ *,
45
+ initial_weights=None,
46
+ maxiter: int = 800,
47
+ gap_tolerance: float = 2e-5,
48
+ ):
49
+ """Convex scenario-averaged A-optimal design over a discrete candidate grid."""
50
+ info, pilot = np.asarray(information, float), np.asarray(pilot_information, float)
51
+ if (
52
+ info.ndim != 4
53
+ or info.shape[-1] != info.shape[-2]
54
+ or pilot.shape != info.shape[:1] + info.shape[2:]
55
+ ):
56
+ raise ValueError("Expected scenario/candidate information and matching pilot information")
57
+ if not isinstance(budget, (int, np.integer)) or budget < 1:
58
+ raise ValueError("Budget must be a positive integer")
59
+ interest = list(interest)
60
+ if (
61
+ not interest
62
+ or len(set(interest)) != len(interest)
63
+ or min(interest) < 0
64
+ or max(interest) >= info.shape[-1]
65
+ ):
66
+ raise ValueError("Interest indices must be nonempty, distinct, and valid")
67
+ if not np.all(np.isfinite(info)) or not np.all(np.isfinite(pilot)):
68
+ raise ValueError("Information must be finite")
69
+ if not np.allclose(info, info.swapaxes(-1, -2), atol=1e-10) or not np.allclose(
70
+ pilot, pilot.swapaxes(-1, -2), atol=1e-10
71
+ ):
72
+ raise ValueError("Information must be symmetric")
73
+ if np.linalg.eigvalsh(info).min() < -1e-8 or np.linalg.eigvalsh(pilot).min() <= 0:
74
+ raise ValueError("Candidate information must be PSD and pilot information positive definite")
75
+
76
+ m = info.shape[1]
77
+ initial = (
78
+ np.full(m, 1.0 / m)
79
+ if initial_weights is None
80
+ else np.asarray(initial_weights, float)
81
+ )
82
+ if (
83
+ initial.shape != (m,)
84
+ or np.any(initial < 0)
85
+ or not np.all(np.isfinite(initial))
86
+ or initial.sum() <= 0
87
+ ):
88
+ raise ValueError("Invalid initial simplex weights")
89
+ initial = initial / initial.sum()
90
+ scale = a_optimal_value_gradient(initial, info, pilot, budget, interest)[0]
91
+
92
+ def objective(w):
93
+ value, gradient = a_optimal_value_gradient(w, info, pilot, budget, interest)
94
+ return value / scale, gradient / scale
95
+
96
+ fit = minimize(
97
+ objective,
98
+ initial,
99
+ jac=True,
100
+ method="SLSQP",
101
+ bounds=[(0.0, 1.0)] * m,
102
+ constraints=[
103
+ dict(type="eq", fun=lambda w: w.sum() - 1.0, jac=lambda w: np.ones(m))
104
+ ],
105
+ options=dict(maxiter=maxiter, ftol=1e-12),
106
+ )
107
+ weights = np.maximum(fit.x, 0.0)
108
+ weights /= weights.sum()
109
+ value, gradient = a_optimal_value_gradient(weights, info, pilot, budget, interest)
110
+ gap = max(float(weights @ gradient - np.min(gradient)), 0.0)
111
+ counts = largest_remainder(weights, budget)
112
+ rounded = a_optimal_value_gradient(counts / budget, info, pilot, budget, interest)[0]
113
+ if gap / value > gap_tolerance:
114
+ raise RuntimeError(
115
+ f"Allocation optimality gap {gap / value:.3g} exceeds tolerance: {fit.message}"
116
+ )
117
+ return dict(
118
+ weights=weights,
119
+ counts=counts,
120
+ criterion=value,
121
+ initial_criterion=scale,
122
+ rounded_criterion=rounded,
123
+ relative_rounding_loss=rounded / value - 1.0,
124
+ convex_gap=gap,
125
+ relative_convex_gap=gap / value,
126
+ iterations=int(fit.nit),
127
+ success=bool(fit.success),
128
+ message=str(fit.message),
129
+ )