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,256 @@
1
+ """Differentiable Mean-Field Renewal Networks (McKean-Vlasov semi-Markov ODEs).
2
+
3
+ Extends linear phase-type renewal networks to interacting populations where
4
+ transition rates or routing probabilities depend smoothly on the instantaneous
5
+ macroscopic node occupancy bar_p(t) = C x(t) in Delta^{V-1}:
6
+
7
+ dx/dt = (T(bar_p(t), t) + B(bar_p(t), t) J(bar_p(t), t)) x(t),
8
+
9
+ preserving exact non-negativity (x(t) >= 0), simplex mass conservation
10
+ (1^T x(t) = 1), and internal residence-age phase memory across nonlinear
11
+ feedback such as epidemic contagion or queueing congestion.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import diffrax
17
+ import jax
18
+ import jax.numpy as jnp
19
+ import numpy as np
20
+
21
+ from .phase_type import mixed_erlang_components, smooth_erlang_logits
22
+
23
+
24
+ def solve_mean_field_renewal(
25
+ x0: jax.Array,
26
+ ts: jax.Array,
27
+ vector_field_fn,
28
+ readout_fn,
29
+ *,
30
+ dt0: float = 0.05,
31
+ rtol: float = 1e-7,
32
+ atol: float = 1e-9,
33
+ max_steps: int = 8192,
34
+ ):
35
+ """Integrate a nonlinear mean-field semi-Markov ODE via Diffrax Tsit5."""
36
+ x0_arr = jnp.asarray(x0, dtype=jnp.float64)
37
+ ts_arr = jnp.asarray(ts, dtype=jnp.float64)
38
+
39
+ def rhs(t, x, args):
40
+ x_pos = jnp.maximum(x, 0.0)
41
+ p_bar = readout_fn(x_pos)
42
+ return vector_field_fn(t, x_pos, p_bar)
43
+
44
+ term = diffrax.ODETerm(rhs)
45
+ solver = diffrax.Tsit5()
46
+ stepsize = diffrax.PIDController(rtol=rtol, atol=atol)
47
+ saveat = diffrax.SaveAt(ts=ts_arr)
48
+ sol = diffrax.diffeqsolve(
49
+ term,
50
+ solver,
51
+ t0=0.0,
52
+ t1=ts_arr[-1],
53
+ dt0=dt0,
54
+ y0=x0_arr,
55
+ saveat=saveat,
56
+ stepsize_controller=stepsize,
57
+ max_steps=max_steps,
58
+ )
59
+ return jax.vmap(readout_fn)(sol.ys), sol.ys
60
+
61
+
62
+ def seicr_mean_field_predict(
63
+ beta: jax.Array,
64
+ m_e: jax.Array,
65
+ k_e: jax.Array,
66
+ m_i: jax.Array,
67
+ k_i: jax.Array,
68
+ m_c: jax.Array,
69
+ k_c: jax.Array,
70
+ i0: jax.Array,
71
+ e0: jax.Array,
72
+ ts: jax.Array,
73
+ *,
74
+ stages: int = 8,
75
+ infectious_in_exposed: float = 0.0,
76
+ ):
77
+ """Differentiable Mean-Field SEICR Renewal Network (S -> E -> I_bed -> C_conv -> R).
78
+
79
+ State vector layout (length 3 * stages + 2):
80
+ - index 0: Susceptible S(t)
81
+ - indices [1 : 1 + K]: Exposed E phases (smooth mixed-Erlang(m_e, k_e))
82
+ - indices [1 + K : 1 + 2K]: Bed-confined / Infectious I phases (m_i, k_i)
83
+ - indices [1 + 2K : 1 + 3K]: Convalescent C phases (m_c, k_c)
84
+ - index [1 + 3K]: Recovered R(t)
85
+
86
+ Endogenous McKean-Vlasov contagion drives S -> E at rate beta * (I(t) + eps * E(t)),
87
+ entering E with exact mixed-Erlang entry vector b_E. All phase blocks are Metzler
88
+ and column-sum zero, guaranteeing x(t) >= 0 and sum(x(t)) == 1 for all t >= 0.
89
+ """
90
+ k_st = int(stages)
91
+ r_e, b_e = mixed_erlang_components(m_e, smooth_erlang_logits(k_e, stages=k_st))
92
+ r_i, b_i = mixed_erlang_components(m_i, smooth_erlang_logits(k_i, stages=k_st))
93
+ r_c, b_c = mixed_erlang_components(m_c, smooth_erlang_logits(k_c, stages=k_st))
94
+
95
+ s0 = jnp.maximum(1.0 - i0 - e0, 1e-12)
96
+ x0 = jnp.concatenate(
97
+ [
98
+ jnp.array([s0]),
99
+ e0 * b_e,
100
+ i0 * b_i,
101
+ jnp.zeros(k_st),
102
+ jnp.array([0.0]),
103
+ ]
104
+ )
105
+
106
+ def readout(x):
107
+ s_val = x[0]
108
+ e_val = jnp.sum(x[1 : 1 + k_st])
109
+ i_val = jnp.sum(x[1 + k_st : 1 + 2 * k_st])
110
+ c_val = jnp.sum(x[1 + 2 * k_st : 1 + 3 * k_st])
111
+ r_val = x[1 + 3 * k_st]
112
+ return jnp.stack([s_val, e_val, i_val, c_val, r_val])
113
+
114
+ def chain_dx(seg, rate, inflow, entry_vec):
115
+ # Forward suffix chain: phase 0 -> 1 -> ... -> K-1 -> exit
116
+ dx = -rate * seg + inflow * entry_vec
117
+ dx = dx.at[1:].add(rate * seg[:-1])
118
+ exit_flux = rate * seg[-1]
119
+ return dx, exit_flux
120
+
121
+ def vector_field(_t, x, p_bar):
122
+ s_val = x[0]
123
+ e_seg = x[1 : 1 + k_st]
124
+ i_seg = x[1 + k_st : 1 + 2 * k_st]
125
+ c_seg = x[1 + 2 * k_st : 1 + 3 * k_st]
126
+
127
+ inf_pressure = p_bar[2] + infectious_in_exposed * p_bar[1]
128
+ inc_flux = beta * s_val * inf_pressure
129
+
130
+ de, flux_e_to_i = chain_dx(e_seg, r_e, inc_flux, b_e)
131
+ di, flux_i_to_c = chain_dx(i_seg, r_i, flux_e_to_i, b_i)
132
+ dc, flux_c_to_r = chain_dx(c_seg, r_c, flux_i_to_c, b_c)
133
+
134
+ ds = jnp.array([-inc_flux])
135
+ dr = jnp.array([flux_c_to_r])
136
+ return jnp.concatenate([ds, de, di, dc, dr])
137
+
138
+ p_traj, x_traj = solve_mean_field_renewal(x0, ts, vector_field, readout)
139
+ return p_traj, x_traj
140
+
141
+
142
+ def simulate_interacting_seicr_gillespie(
143
+ beta: float,
144
+ m_e: float,
145
+ k_e: float,
146
+ m_i: float,
147
+ k_i: float,
148
+ m_c: float,
149
+ k_c: float,
150
+ i0: float,
151
+ e0: float,
152
+ ts: np.ndarray,
153
+ n_agents: int,
154
+ *,
155
+ stages: int = 8,
156
+ seed: int = 0,
157
+ ) -> np.ndarray:
158
+ """Exact interacting phase-lifted Gillespie simulation of M finite agents.
159
+
160
+ Used to verify Kurtz's O(M^{-1/2}) propagation-of-chaos convergence of the
161
+ finite interacting semi-Markov population to `seicr_mean_field_predict`.
162
+ """
163
+ rng = np.random.default_rng(seed)
164
+ k_st = int(stages)
165
+ r_e, b_e = map(np.asarray, mixed_erlang_components(jnp.array(m_e), smooth_erlang_logits(jnp.array(k_e), stages=k_st)))
166
+ r_i, b_i = map(np.asarray, mixed_erlang_components(jnp.array(m_i), smooth_erlang_logits(jnp.array(k_i), stages=k_st)))
167
+ r_c, b_c = map(np.asarray, mixed_erlang_components(jnp.array(m_c), smooth_erlang_logits(jnp.array(k_c), stages=k_st)))
168
+ r_e, r_i, r_c = float(r_e), float(r_i), float(r_c)
169
+ b_e = np.maximum(b_e, 0.0)
170
+ b_e /= b_e.sum()
171
+ b_i = np.maximum(b_i, 0.0)
172
+ b_i /= b_i.sum()
173
+ b_c = np.maximum(b_c, 0.0)
174
+ b_c /= b_c.sum()
175
+
176
+ n_i0 = max(1, int(round(i0 * n_agents)))
177
+ n_e0 = int(round(e0 * n_agents))
178
+ n_s0 = n_agents - n_i0 - n_e0
179
+
180
+ # Counts per phase
181
+ s_cnt = int(n_s0)
182
+ e_cnt = rng.multinomial(n_e0, b_e)
183
+ i_cnt = rng.multinomial(n_i0, b_i)
184
+ c_cnt = np.zeros(k_st, dtype=np.int64)
185
+ r_cnt = 0
186
+
187
+ ts_arr = np.asarray(ts, dtype=float)
188
+ out = np.zeros((len(ts_arr), 5), dtype=float)
189
+ t_now = 0.0
190
+ out_idx = 0
191
+
192
+ def record():
193
+ out[out_idx, 0] = s_cnt / n_agents
194
+ out[out_idx, 1] = e_cnt.sum() / n_agents
195
+ out[out_idx, 2] = i_cnt.sum() / n_agents
196
+ out[out_idx, 3] = c_cnt.sum() / n_agents
197
+ out[out_idx, 4] = r_cnt / n_agents
198
+
199
+ while out_idx < len(ts_arr) and ts_arr[out_idx] <= t_now:
200
+ record()
201
+ out_idx += 1
202
+
203
+ t_end = float(ts_arr[-1])
204
+ while out_idx < len(ts_arr):
205
+ i_tot = int(i_cnt.sum())
206
+ e_tot = int(e_cnt.sum())
207
+ c_tot = int(c_cnt.sum())
208
+ rate_inf = beta * s_cnt * (i_tot / n_agents)
209
+ rate_e = r_e * e_tot
210
+ rate_i = r_i * i_tot
211
+ rate_c = r_c * c_tot
212
+ tot = rate_inf + rate_e + rate_i + rate_c
213
+ if tot <= 1e-15:
214
+ while out_idx < len(ts_arr):
215
+ record()
216
+ out_idx += 1
217
+ break
218
+ dt = rng.exponential(1.0 / tot)
219
+ t_next = t_now + dt
220
+ while out_idx < len(ts_arr) and ts_arr[out_idx] < t_next:
221
+ record()
222
+ out_idx += 1
223
+ if t_next > t_end and out_idx >= len(ts_arr):
224
+ break
225
+ t_now = t_next
226
+
227
+ u = rng.uniform(0.0, tot)
228
+ if u < rate_inf:
229
+ s_cnt -= 1
230
+ ph = int(rng.choice(k_st, p=b_e))
231
+ e_cnt[ph] += 1
232
+ elif u < rate_inf + rate_e:
233
+ ph = int(rng.choice(k_st, p=e_cnt / e_tot))
234
+ e_cnt[ph] -= 1
235
+ if ph < k_st - 1:
236
+ e_cnt[ph + 1] += 1
237
+ else:
238
+ ph_i = int(rng.choice(k_st, p=b_i))
239
+ i_cnt[ph_i] += 1
240
+ elif u < rate_inf + rate_e + rate_i:
241
+ ph = int(rng.choice(k_st, p=i_cnt / i_tot))
242
+ i_cnt[ph] -= 1
243
+ if ph < k_st - 1:
244
+ i_cnt[ph + 1] += 1
245
+ else:
246
+ ph_c = int(rng.choice(k_st, p=b_c))
247
+ c_cnt[ph_c] += 1
248
+ else:
249
+ ph = int(rng.choice(k_st, p=c_cnt / c_tot))
250
+ c_cnt[ph] -= 1
251
+ if ph < k_st - 1:
252
+ c_cnt[ph + 1] += 1
253
+ else:
254
+ r_cnt += 1
255
+
256
+ return out
diff_renewal/memory.py ADDED
@@ -0,0 +1,154 @@
1
+ """Auxiliary-state exponential memory solver and static-preserving fast-mode cutoffs."""
2
+
3
+ from collections.abc import Callable
4
+ from dataclasses import dataclass
5
+
6
+ import diffrax
7
+ import jax.numpy as jnp
8
+ import numpy as np
9
+ from scipy.optimize import nnls
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class MemoryCutoff:
14
+ rates: np.ndarray
15
+ weights: np.ndarray
16
+ direct: float
17
+ cutoff: float
18
+ removed_mass: float
19
+
20
+ def screen_bound(self, radius: float) -> float:
21
+ if not 0 <= radius < self.cutoff:
22
+ raise ValueError("require 0 <= radius < cutoff")
23
+ return radius / (self.cutoff - radius) * self.removed_mass
24
+
25
+ def log_rate_derivative_bound(self, radius: float) -> float:
26
+ self.screen_bound(radius)
27
+ return (
28
+ self.removed_mass
29
+ * radius
30
+ * (2.0 * self.cutoff + radius)
31
+ / (self.cutoff - radius) ** 2
32
+ )
33
+
34
+
35
+ def fixed_partition_cutoff(
36
+ rates, weights, retained_indices: tuple[int, ...], *, direct: float = 0.0
37
+ ):
38
+ """Differentiable static-preserving mode elimination with frozen index partition."""
39
+ rates, weights = jnp.asarray(rates), jnp.asarray(weights)
40
+ if rates.ndim != 1 or rates.shape != weights.shape:
41
+ raise ValueError("rates and weights must be equal-length 1D arrays")
42
+ if (
43
+ not isinstance(retained_indices, tuple)
44
+ or any(
45
+ isinstance(i, bool) or not isinstance(i, int) or i < 0 or i >= rates.size
46
+ for i in retained_indices
47
+ )
48
+ or len(set(retained_indices)) != len(retained_indices)
49
+ ):
50
+ raise ValueError("retained_indices must be a static tuple of distinct valid indices")
51
+ dropped = tuple(i for i in range(rates.size) if i not in retained_indices)
52
+ keep, drop = jnp.array(retained_indices, dtype=int), jnp.array(dropped, dtype=int)
53
+ return rates[keep], weights[keep], direct + jnp.sum(weights[drop] / rates[drop])
54
+
55
+
56
+ def static_preserving_cutoff(rates, weights, cutoff: float, *, direct: float = 0.0):
57
+ rates, weights = np.asarray(rates, dtype=float), np.asarray(weights, dtype=float)
58
+ if rates.ndim != 1 or rates.shape != weights.shape:
59
+ raise ValueError("rates and weights must be equal-length 1D arrays")
60
+ if (
61
+ not np.all(np.isfinite(rates))
62
+ or not np.all(np.isfinite(weights))
63
+ or not np.isfinite(cutoff)
64
+ or not np.isfinite(direct)
65
+ or np.any(rates <= 0)
66
+ or np.any(weights < 0)
67
+ or cutoff <= 0
68
+ ):
69
+ raise ValueError("require finite positive rates/cutoff and nonnegative weights")
70
+ keep = rates <= cutoff
71
+ mass = float(np.sum(weights[~keep] / rates[~keep]))
72
+ return MemoryCutoff(rates[keep], weights[keep], direct + mass, cutoff, mass)
73
+
74
+
75
+ def fit_positive_soe(times, values, rates, *, relative_floor: float = 1e-3):
76
+ """Nonnegative weighted least-squares sum-of-exponentials fit on a fixed rate grid."""
77
+ times, values, rates = map(
78
+ lambda x: np.asarray(x, dtype=float), (times, values, rates)
79
+ )
80
+ if (
81
+ times.ndim != 1
82
+ or values.shape != times.shape
83
+ or rates.ndim != 1
84
+ or times.size == 0
85
+ or rates.size == 0
86
+ or not all(np.all(np.isfinite(v)) for v in (times, values, rates))
87
+ or np.any(times < 0)
88
+ or np.any(values < 0)
89
+ or np.any(rates <= 0)
90
+ or not np.isfinite(relative_floor)
91
+ or relative_floor <= 0
92
+ ):
93
+ raise ValueError("require finite nonnegative samples, positive rates and floor")
94
+ scale = np.maximum(np.abs(values), relative_floor)
95
+ design = np.exp(-times[:, None] * rates[None, :])
96
+ weights, _ = nnls(design / scale[:, None], values / scale, maxiter=50 * rates.size)
97
+ return weights
98
+
99
+
100
+ def solve_memory(
101
+ rhs: Callable,
102
+ source: Callable,
103
+ y0,
104
+ ts,
105
+ rates,
106
+ weights,
107
+ args=None,
108
+ *,
109
+ z0=None,
110
+ direct: float = 0.0,
111
+ clock: Callable | None = None,
112
+ killing: Callable | None = None,
113
+ solver=None,
114
+ rtol: float = 1e-7,
115
+ atol: float = 1e-9,
116
+ max_steps: int = 100_000,
117
+ ):
118
+ """Solve y' = rhs(t, y, memory, args) with augmented exponential memory states."""
119
+ ts, rates, weights = map(jnp.asarray, (ts, rates, weights))
120
+ y0 = jnp.asarray(y0)
121
+ y0 = y0.astype(jnp.result_type(y0, rates, weights, 1.0))
122
+ if rates.ndim != 1 or weights.shape != rates.shape:
123
+ raise ValueError("rates and weights must be equal-length 1D arrays")
124
+ if ts.ndim != 1 or ts.shape[0] < 2:
125
+ raise ValueError("ts must be a strictly increasing 1D grid of length >= 2")
126
+ zshape = (rates.size,) + y0.shape
127
+ z0 = jnp.zeros(zshape, dtype=y0.dtype) if z0 is None else jnp.asarray(z0, dtype=y0.dtype)
128
+ if z0.shape != zshape:
129
+ raise ValueError(f"z0 must have shape {zshape}")
130
+
131
+ def field(t, state, packed):
132
+ y, z = state
133
+ lam, w, local, params = packed
134
+ u = jnp.asarray(source(t, y, params))
135
+ c = 1.0 if clock is None else clock(t, y, params)
136
+ q = 0.0 if killing is None else killing(t, y, params)
137
+ # In the fast-mode quasi-steady-state limit (lam_k -> inf), z_k -> u / (c * lam_k)
138
+ memory = jnp.tensordot(w, z, axes=1) + (local / c) * u
139
+ decay = (c * lam + q).reshape((lam.size,) + (1,) * y.ndim)
140
+ return rhs(t, y, memory, params), u[None, ...] - decay * z
141
+
142
+ return diffrax.diffeqsolve(
143
+ diffrax.ODETerm(field),
144
+ diffrax.Tsit5() if solver is None else solver,
145
+ t0=ts[0],
146
+ t1=ts[-1],
147
+ dt0=None,
148
+ y0=(y0, z0),
149
+ args=(rates, weights, direct, args),
150
+ saveat=diffrax.SaveAt(ts=ts, fn=lambda t, state, args: state[0]),
151
+ stepsize_controller=diffrax.PIDController(rtol=rtol, atol=atol),
152
+ adjoint=diffrax.RecursiveCheckpointAdjoint(),
153
+ max_steps=max_steps,
154
+ )
@@ -0,0 +1,107 @@
1
+ """Independent-particle renewal networks with competing, freshly reset clocks."""
2
+
3
+ import diffrax
4
+ import jax
5
+ import jax.numpy as jnp
6
+
7
+ from .phase_type import mixed_erlang_components
8
+
9
+
10
+ def network_layout(edges, n_nodes: int):
11
+ """Validate static topology and return outgoing edge indices per node."""
12
+ if not isinstance(n_nodes, int) or isinstance(n_nodes, bool) or n_nodes < 1:
13
+ raise ValueError("n_nodes must be a positive integer")
14
+ edges = tuple(tuple(edge) for edge in edges)
15
+ for edge in edges:
16
+ if len(edge) != 2 or any(
17
+ not isinstance(i, int) or isinstance(i, bool) or i < 0 or i >= n_nodes
18
+ for i in edge
19
+ ):
20
+ raise ValueError("edges must contain valid integer node pairs")
21
+ return edges, tuple(
22
+ tuple(e for e, (source, _) in enumerate(edges) if source == i)
23
+ for i in range(n_nodes)
24
+ )
25
+
26
+
27
+ def network_state_size(edges, n_nodes: int, stages: int) -> int:
28
+ """Number of joint tensor phase states: sum_i K**outdegree(i), including sinks."""
29
+ if not isinstance(stages, int) or isinstance(stages, bool) or stages < 1:
30
+ raise ValueError("stages must be a positive integer")
31
+ _, outgoing = network_layout(edges, n_nodes)
32
+ return sum(stages ** len(group) for group in outgoing)
33
+
34
+
35
+ def solve_renewal_network(
36
+ means,
37
+ logits,
38
+ edges,
39
+ initial,
40
+ ts,
41
+ *,
42
+ rtol: float = 1e-8,
43
+ atol: float = 1e-10,
44
+ ):
45
+ """Differentiate mean occupancies of a finite renewal network via K**d tensors."""
46
+ means, logits = jnp.asarray(means), jnp.asarray(logits)
47
+ initial, ts = jnp.asarray(initial), jnp.asarray(ts)
48
+ if initial.ndim != 1 or initial.size < 1:
49
+ raise ValueError("initial must be a nonempty 1D array")
50
+ edges, outgoing = network_layout(edges, initial.size)
51
+ if (
52
+ not edges
53
+ or means.shape != (len(edges),)
54
+ or logits.ndim != 2
55
+ or logits.shape[0] != len(edges)
56
+ or logits.shape[1] < 1
57
+ ):
58
+ raise ValueError("require E edges, means (E,), and logits (E,K), E,K >= 1")
59
+ if ts.ndim != 1 or ts.size < 1:
60
+ raise ValueError("ts must be a nonempty 1D array")
61
+ rates, alpha = jax.vmap(mixed_erlang_components)(means, logits)
62
+ entries = []
63
+ for group in outgoing:
64
+ entry = jnp.array(1.0, dtype=alpha.dtype)
65
+ for e in group:
66
+ entry = jnp.tensordot(entry, alpha[e], axes=0)
67
+ entries.append(entry)
68
+ entries = tuple(entries)
69
+ y0 = tuple(initial[i] * entry for i, entry in enumerate(entries))
70
+
71
+ def field(t, state, args):
72
+ rates_arg, entries_arg = args
73
+ incoming = [jnp.array(0.0, dtype=rates_arg.dtype) for _ in outgoing]
74
+ derivatives = []
75
+ for occupancy, group in zip(state, outgoing):
76
+ derivative = jnp.zeros_like(occupancy)
77
+ for axis, e in enumerate(group):
78
+ flux = rates_arg[e] * occupancy
79
+ shifted = jnp.roll(flux, 1, axis=axis)
80
+ first = [slice(None)] * occupancy.ndim
81
+ first[axis] = 0
82
+ shifted = shifted.at[tuple(first)].set(0.0)
83
+ derivative = derivative + shifted - flux
84
+ exit_flux = jnp.sum(jnp.take(flux, -1, axis=axis))
85
+ destination = edges[e][1]
86
+ incoming[destination] = incoming[destination] + exit_flux
87
+ derivatives.append(derivative)
88
+ return tuple(
89
+ dp + arrival * entry
90
+ for dp, arrival, entry in zip(derivatives, incoming, entries_arg)
91
+ )
92
+
93
+ return diffrax.diffeqsolve(
94
+ diffrax.ODETerm(field),
95
+ diffrax.Tsit5(),
96
+ t0=0.0,
97
+ t1=ts[-1],
98
+ dt0=None,
99
+ y0=y0,
100
+ args=(rates, entries),
101
+ saveat=diffrax.SaveAt(
102
+ ts=ts, fn=lambda t, y, args: jnp.stack([jnp.sum(p) for p in y])
103
+ ),
104
+ stepsize_controller=diffrax.PIDController(rtol=rtol, atol=atol),
105
+ adjoint=diffrax.RecursiveCheckpointAdjoint(),
106
+ max_steps=100_000,
107
+ )
@@ -0,0 +1,52 @@
1
+ """Conditional mixed-Erlang neural clock with exact age-conditioned survival."""
2
+
3
+ from typing import NamedTuple
4
+
5
+ import jax
6
+ import jax.numpy as jnp
7
+ from jax.scipy.special import gammaln
8
+
9
+
10
+ class ClockNetwork(NamedTuple):
11
+ hidden_weight: jax.Array
12
+ hidden_bias: jax.Array
13
+ output_weight: jax.Array
14
+ output_bias: jax.Array
15
+
16
+
17
+ def init_clock_network(key, features: int, *, stages: int = 16, width: int = 8):
18
+ """Initialize near a broad stage-count distribution and a phase rate of four."""
19
+ if min(features, stages, width) < 1:
20
+ raise ValueError("features, stages and width must be positive")
21
+ k1, k2 = jax.random.split(key)
22
+ counts = jnp.arange(stages, 0, -1)
23
+ bias = jnp.r_[
24
+ jnp.zeros(1), -0.5 * ((counts - (stages + 1) / 2.0) / (stages / 4.0)) ** 2
25
+ ]
26
+ return ClockNetwork(
27
+ jax.random.normal(k1, (features, width)) / jnp.sqrt(features),
28
+ jnp.zeros(width),
29
+ 0.08 * jax.random.normal(k2, (width, stages + 1)),
30
+ bias,
31
+ )
32
+
33
+
34
+ def neural_clock(network: ClockNetwork, features):
35
+ """Return positive phase rate and normalized entry probabilities."""
36
+ hidden = jnp.tanh(jnp.asarray(features) @ network.hidden_weight + network.hidden_bias)
37
+ raw = hidden @ network.output_weight + network.output_bias
38
+ rate = 4.0 * jnp.exp(1.2 * jnp.tanh(raw[..., 0]))
39
+ return rate, jax.nn.softmax(raw[..., 1:], axis=-1)
40
+
41
+
42
+ def survivor_phases(rate, entry, age):
43
+ """Unnormalized phase masses conditional on no exit up to elapsed age."""
44
+ rate, entry, age = map(jnp.asarray, (rate, entry, age))
45
+ stages = entry.shape[-1]
46
+ shifts = jnp.arange(stages)[:, None] - jnp.arange(stages)[None, :]
47
+ order = jnp.maximum(shifts, 0)
48
+ elapsed = (rate * age)[..., None, None]
49
+ scale = jnp.maximum(elapsed, 1.0)
50
+ powers = jnp.where(order == 0, 1.0, (elapsed / scale) ** jnp.maximum(order, 1))
51
+ poisson = powers * jnp.exp(-elapsed + order * jnp.log(scale) - gammaln(order + 1.0))
52
+ return jnp.einsum("...ij,...j->...i", jnp.where(shifts >= 0, poisson, 0.0), entry)
@@ -0,0 +1,15 @@
1
+ """Differentiable count-weighted multinomial losses for snapshot observations."""
2
+
3
+ import jax.numpy as jnp
4
+
5
+
6
+ def multinomial_nll(probabilities, counts, *, probability_floor: float = 1e-12):
7
+ """Constant-free multinomial negative log likelihood per observed cell."""
8
+ p, n = jnp.asarray(probabilities), jnp.asarray(counts)
9
+ if p.ndim < 1 or p.shape != n.shape or p.shape[-1] < 1:
10
+ raise ValueError("Probabilities and counts must have matching category arrays")
11
+ if not 0 < probability_floor < 1:
12
+ raise ValueError("probability_floor must be between zero and one")
13
+ p = jnp.maximum(p, probability_floor)
14
+ p = p / jnp.sum(p, axis=-1, keepdims=True)
15
+ return -jnp.sum(n * jnp.log(p)) / jnp.sum(n)
@@ -0,0 +1,79 @@
1
+ """Positive phase-type states for refractory renewal dwell times.
2
+
3
+ Q is a transient CTMC generator in row convention; occupancy is a column.
4
+ This gives exact linear population means for the specified independent-particle
5
+ phase process.
6
+ """
7
+
8
+ import jax.nn as jnn
9
+ import jax.numpy as jnp
10
+
11
+
12
+ def erlang_generator(stages: int, mean):
13
+ """Return (Q, alpha) for an Erlang dwell time of fixed integer shape."""
14
+ if not isinstance(stages, int) or isinstance(stages, bool) or stages < 1:
15
+ raise ValueError("stages must be a positive integer")
16
+ rate = stages / jnp.asarray(mean)
17
+ q = rate * (-jnp.eye(stages) + jnp.eye(stages, k=1))
18
+ return q, jnp.eye(stages)[0]
19
+
20
+
21
+ def phase_type_dynamics(q, alpha, occupancy, inflow, clock=1.0):
22
+ """Return (occupancy derivative, nonnegative absorption flux).
23
+
24
+ Requires Metzler Q with nonpositive row sums, alpha >= 0 with sum 1,
25
+ and nonnegative operational-time clock multiplier.
26
+ """
27
+ exit_rates = -jnp.sum(q, axis=1)
28
+ return alpha * inflow + clock * (q.T @ occupancy), clock * (exit_rates @ occupancy)
29
+
30
+
31
+ def mixed_erlang_components(mean, logits):
32
+ """Common-rate Erlang mixture represented as a single shared suffix chain.
33
+
34
+ logits[n-1] controls the probability of n remaining exponential stages.
35
+ Rate = E[N] / mean matches the target mean exactly while keeping stage
36
+ dimension fixed at K.
37
+ """
38
+ logits = jnp.asarray(logits)
39
+ if logits.ndim != 1 or logits.size < 1:
40
+ raise ValueError("logits must be a nonempty 1D array")
41
+ weights = jnn.softmax(logits)
42
+ counts = jnp.arange(1, logits.size + 1, dtype=weights.dtype)
43
+ return jnp.dot(counts, weights) / mean, weights[::-1]
44
+
45
+
46
+ def smooth_erlang_logits(center, *, stages: int = 64, width: float = 0.5):
47
+ """Smooth Gaussian logits over integer stage counts 1..stages."""
48
+ if not isinstance(stages, int) or isinstance(stages, bool) or stages < 1:
49
+ raise ValueError("stages must be a positive integer")
50
+ if width <= 0:
51
+ raise ValueError("width must be positive")
52
+ counts = jnp.arange(1, stages + 1)
53
+ return -0.5 * ((counts - center) / width) ** 2
54
+
55
+
56
+ def mixed_erlang_moments(rate, alpha):
57
+ """Return (mean, variance, equivalent Gamma shape E[T]^2 / Var[T])."""
58
+ alpha = jnp.asarray(alpha)
59
+ counts = jnp.arange(alpha.size, 0, -1, dtype=alpha.dtype)
60
+ count_mean = jnp.dot(alpha, counts)
61
+ count_variance = jnp.dot(alpha, (counts - count_mean) ** 2)
62
+ mean = count_mean / rate
63
+ variance = (count_mean + count_variance) / rate**2
64
+ return mean, variance, mean**2 / variance
65
+
66
+
67
+ def coxian_generator(log_rates, continuation_logits):
68
+ """Unconstrained trainable Coxian generator with fixed phase budget K."""
69
+ log_rates = jnp.asarray(log_rates)
70
+ continuation_logits = jnp.asarray(continuation_logits)
71
+ if (
72
+ log_rates.ndim != 1
73
+ or log_rates.size < 1
74
+ or continuation_logits.shape != (log_rates.size - 1,)
75
+ ):
76
+ raise ValueError("require K log rates and K-1 continuation logits")
77
+ rates = jnp.exp(log_rates)
78
+ q = -jnp.diag(rates) + jnp.diag(rates[:-1] * jnn.sigmoid(continuation_logits), 1)
79
+ return q, jnp.eye(rates.size, dtype=rates.dtype)[0]
diff_renewal/py.typed ADDED
File without changes