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
|
@@ -0,0 +1,534 @@
|
|
|
1
|
+
"""Symmetry-based continuation, Baur et al. projection, and Positive Fisher-Sensitivity Reduction."""
|
|
2
|
+
|
|
3
|
+
import time
|
|
4
|
+
|
|
5
|
+
import jax
|
|
6
|
+
import jax.numpy as jnp
|
|
7
|
+
import jax.scipy.linalg as jl
|
|
8
|
+
import numpy as np
|
|
9
|
+
from scipy.linalg import helmert, solve, svd
|
|
10
|
+
from scipy.optimize import minimize
|
|
11
|
+
|
|
12
|
+
from .phase_type import mixed_erlang_components, smooth_erlang_logits
|
|
13
|
+
from .traits import _shape_center, moment_matched_logits
|
|
14
|
+
|
|
15
|
+
STAGES = 16
|
|
16
|
+
K_POS_RED = 11
|
|
17
|
+
STEP = 0.5
|
|
18
|
+
STEPS = 14
|
|
19
|
+
CONTRASTS = np.kron(helmert(3, full=False).T, np.eye(STAGES))
|
|
20
|
+
READ = np.kron(np.eye(3), np.ones((1, STAGES)))
|
|
21
|
+
W_SYM = np.vstack((CONTRASTS.T, np.ones(3 * STAGES)))
|
|
22
|
+
READ_SYM = np.column_stack((READ @ CONTRASTS, np.ones(3) / 3.0))
|
|
23
|
+
ROUTE = np.roll(np.eye(3), 1, axis=0)
|
|
24
|
+
EXIT = np.kron(np.eye(3), np.eye(1, STAGES, STAGES - 1))
|
|
25
|
+
LOCAL = np.eye(STAGES, k=-1) - np.eye(STAGES)
|
|
26
|
+
|
|
27
|
+
READ_POS33 = jnp.kron(jnp.eye(3), jnp.ones((1, K_POS_RED)))
|
|
28
|
+
ANCHORS_DEFAULT = [np.log([m] * 3 + [k] * 3) for m, k in [(1.8, 5.3), (2.3, 7.7)]]
|
|
29
|
+
SHIFTS_DEFAULT = [1.0 / 7.0, 0.5, 2.0]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def cycle_symmetry_matrices(theta, *, pure: bool = False):
|
|
33
|
+
"""Return (full_48_generator, fresh_entry_48x3, reduced_33_generator)."""
|
|
34
|
+
mean, shape = jnp.exp(jnp.asarray(theta)).reshape(2, 3)
|
|
35
|
+
if pure:
|
|
36
|
+
rates = STAGES / mean
|
|
37
|
+
entry = jnp.tile(jnp.eye(STAGES)[0], (3, 1))
|
|
38
|
+
else:
|
|
39
|
+
rates, entry = jax.vmap(mixed_erlang_components)(
|
|
40
|
+
mean, moment_matched_logits(shape)
|
|
41
|
+
)
|
|
42
|
+
fresh = jl.block_diag(*(e[:, None] for e in entry))
|
|
43
|
+
generator = jnp.kron(jnp.diag(rates), LOCAL) + fresh @ ROUTE @ (
|
|
44
|
+
rates[:, None] * EXIT
|
|
45
|
+
)
|
|
46
|
+
residence = jnp.sum(jnp.cumsum(entry, axis=1) / rates[:, None], axis=0)
|
|
47
|
+
profile = residence / residence.sum()
|
|
48
|
+
lift = jnp.column_stack((CONTRASTS, jnp.tile(profile / 3.0, 3)))
|
|
49
|
+
return generator, fresh, W_SYM @ generator @ lift
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def make_cycle_engine(reduced: bool = False, *, pure: bool = False):
|
|
53
|
+
"""Return JIT-compiled evaluator (theta -> probabilities, Jacobian) on STEP*1..STEPS."""
|
|
54
|
+
|
|
55
|
+
def auxiliary(theta):
|
|
56
|
+
generator, fresh, small = cycle_symmetry_matrices(theta, pure=pure)
|
|
57
|
+
if reduced:
|
|
58
|
+
generator, fresh, read = small, W_SYM @ fresh, READ_SYM
|
|
59
|
+
else:
|
|
60
|
+
read = READ
|
|
61
|
+
transition = jl.expm(STEP * generator)
|
|
62
|
+
|
|
63
|
+
def advance(state, _):
|
|
64
|
+
state = transition @ state
|
|
65
|
+
return state, (read @ state).T
|
|
66
|
+
|
|
67
|
+
p = jax.lax.scan(advance, fresh, None, length=STEPS)[1]
|
|
68
|
+
return p, p
|
|
69
|
+
|
|
70
|
+
compiled = jax.jit(jax.jacfwd(auxiliary, has_aux=True))
|
|
71
|
+
|
|
72
|
+
def evaluate(theta):
|
|
73
|
+
derivative, values = compiled(jnp.asarray(theta))
|
|
74
|
+
return np.asarray(values), np.asarray(derivative)
|
|
75
|
+
|
|
76
|
+
return evaluate
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def build_interpolatory_basis(
|
|
80
|
+
dimension: int = 33,
|
|
81
|
+
*,
|
|
82
|
+
anchors=None,
|
|
83
|
+
shifts=None,
|
|
84
|
+
):
|
|
85
|
+
"""Build two-sided parametric interpolation basis Q (48 x dimension) from anchor points."""
|
|
86
|
+
if dimension not in (18, 33):
|
|
87
|
+
raise ValueError("Supported predeclared basis dimensions are 18 and 33")
|
|
88
|
+
t0 = time.perf_counter()
|
|
89
|
+
anchors_list = ANCHORS_DEFAULT if anchors is None else list(anchors)
|
|
90
|
+
shifts_list = SHIFTS_DEFAULT if shifts is None else list(shifts)
|
|
91
|
+
used_anchors = anchors_list[:1] if dimension == 18 else anchors_list
|
|
92
|
+
|
|
93
|
+
mass = READ.T / np.sqrt(float(STAGES))
|
|
94
|
+
columns = []
|
|
95
|
+
for theta in used_anchors:
|
|
96
|
+
a, b, _ = map(np.asarray, cycle_symmetry_matrices(theta))
|
|
97
|
+
for shift in shifts_list:
|
|
98
|
+
resolvent = shift * np.eye(3 * STAGES) - a
|
|
99
|
+
for snapshots in (solve(resolvent, b), solve(resolvent.T, READ.T)):
|
|
100
|
+
columns.append(snapshots / np.linalg.norm(snapshots, axis=0))
|
|
101
|
+
snapshots = np.column_stack(columns)
|
|
102
|
+
residual = snapshots - mass @ (mass.T @ snapshots)
|
|
103
|
+
u, s, _ = svd(residual, full_matrices=False)
|
|
104
|
+
q = np.column_stack((mass, u[:, : dimension - 3]))
|
|
105
|
+
q = np.linalg.qr(q)[0]
|
|
106
|
+
info = dict(
|
|
107
|
+
dimension=dimension,
|
|
108
|
+
anchors=[np.asarray(x).tolist() for x in used_anchors],
|
|
109
|
+
shifts=list(shifts_list),
|
|
110
|
+
residual_singular_values=s.tolist(),
|
|
111
|
+
relative_span_residual=float(
|
|
112
|
+
np.linalg.norm(snapshots - q @ (q.T @ snapshots))
|
|
113
|
+
/ np.linalg.norm(snapshots)
|
|
114
|
+
),
|
|
115
|
+
orthogonality_error=float(np.linalg.norm(q.T @ q - np.eye(dimension))),
|
|
116
|
+
output_span_residual=float(np.linalg.norm(READ - READ @ q @ q.T)),
|
|
117
|
+
seconds=time.perf_counter() - t0,
|
|
118
|
+
)
|
|
119
|
+
return q, info
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def make_interpolatory_engine(q):
|
|
123
|
+
"""Return JIT-compiled projected forward+Jacobian evaluator for basis Q."""
|
|
124
|
+
q_jax = jnp.asarray(q)
|
|
125
|
+
read_proj = jnp.asarray(READ) @ q_jax
|
|
126
|
+
|
|
127
|
+
def auxiliary(theta):
|
|
128
|
+
a, b, _ = cycle_symmetry_matrices(theta)
|
|
129
|
+
transition = jl.expm(STEP * (q_jax.T @ a @ q_jax))
|
|
130
|
+
|
|
131
|
+
def advance(state, _):
|
|
132
|
+
state = transition @ state
|
|
133
|
+
return state, (read_proj @ state).T
|
|
134
|
+
|
|
135
|
+
p = jax.lax.scan(advance, q_jax.T @ b, None, length=STEPS)[1]
|
|
136
|
+
return p, p
|
|
137
|
+
|
|
138
|
+
compiled = jax.jit(jax.jacfwd(auxiliary, has_aux=True))
|
|
139
|
+
|
|
140
|
+
def evaluate(theta):
|
|
141
|
+
derivative, values = compiled(jnp.asarray(theta))
|
|
142
|
+
return np.asarray(values), np.asarray(derivative)
|
|
143
|
+
|
|
144
|
+
return evaluate
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def resolvent_sensitivity_diagnostic(q, theta, shift: float):
|
|
148
|
+
"""Check transfer and sensitivity interpolation accuracy in Laplace domain."""
|
|
149
|
+
a, b, _ = map(np.asarray, cycle_symmetry_matrices(theta))
|
|
150
|
+
da, db, _ = map(np.asarray, jax.jacfwd(cycle_symmetry_matrices)(jnp.asarray(theta)))
|
|
151
|
+
r = solve(shift * np.eye(3 * STAGES) - a, np.eye(3 * STAGES))
|
|
152
|
+
ar, br, cr = q.T @ a @ q, q.T @ b, READ @ q
|
|
153
|
+
rr = solve(shift * np.eye(q.shape[1]) - ar, np.eye(q.shape[1]))
|
|
154
|
+
full, small = READ @ r @ b, cr @ rr @ br
|
|
155
|
+
jf = np.stack(
|
|
156
|
+
[READ @ r @ (da[:, :, i] @ r @ b + db[:, :, i]) for i in range(6)], axis=-1
|
|
157
|
+
)
|
|
158
|
+
jr = np.stack(
|
|
159
|
+
[
|
|
160
|
+
cr @ rr @ (q.T @ da[:, :, i] @ q @ rr @ br + q.T @ db[:, :, i])
|
|
161
|
+
for i in range(6)
|
|
162
|
+
],
|
|
163
|
+
axis=-1,
|
|
164
|
+
)
|
|
165
|
+
return dict(
|
|
166
|
+
transfer_max_abs=float(np.max(np.abs(full - small))),
|
|
167
|
+
sensitivity_max_abs=float(np.max(np.abs(jf - jr))),
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _pos_node_chain(mean, shape, psi):
|
|
172
|
+
"""Map (mean, shape) to a valid K_POS_RED=11 positive Coxian chain with exact mean."""
|
|
173
|
+
s_norm = (jnp.log(shape) - jnp.log(6.0)) / 0.7
|
|
174
|
+
feats = jnp.array([1.0, s_norm, s_norm**2, s_norm**3])
|
|
175
|
+
w_logits = psi[: 4 * K_POS_RED].reshape(4, K_POS_RED)
|
|
176
|
+
w_rates = psi[4 * K_POS_RED : 8 * K_POS_RED].reshape(4, K_POS_RED)
|
|
177
|
+
entry = jax.nn.softmax(feats @ w_logits)
|
|
178
|
+
rel_rates = jnp.exp(0.6 * jnp.tanh(feats @ w_rates))
|
|
179
|
+
rem_mean_unit = jnp.cumsum((1.0 / rel_rates)[::-1])[::-1]
|
|
180
|
+
unit_mean = jnp.dot(entry, rem_mean_unit)
|
|
181
|
+
stage_rates = (unit_mean / mean) * rel_rates
|
|
182
|
+
return stage_rates, entry
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def pos33_cycle_matrices(theta, psi):
|
|
186
|
+
"""Build 33x33 strictly Metzler mass-conserving generator and non-negative entry matrix."""
|
|
187
|
+
means, shapes = jnp.exp(jnp.asarray(theta)).reshape(2, 3)
|
|
188
|
+
stage_rates, entries = jax.vmap(lambda m, k: _pos_node_chain(m, k, psi))(
|
|
189
|
+
means, shapes
|
|
190
|
+
)
|
|
191
|
+
blocks = [
|
|
192
|
+
-jnp.diag(r_vec) + jnp.diag(r_vec[:-1], k=-1) for r_vec in stage_rates
|
|
193
|
+
]
|
|
194
|
+
local_gen = jl.block_diag(*blocks)
|
|
195
|
+
fresh = jl.block_diag(*(e[:, None] for e in entries))
|
|
196
|
+
out_flux = jnp.kron(
|
|
197
|
+
jnp.diag(stage_rates[:, -1]), jnp.eye(1, K_POS_RED, K_POS_RED - 1)
|
|
198
|
+
)
|
|
199
|
+
generator = local_gen + fresh @ jnp.asarray(ROUTE) @ out_flux
|
|
200
|
+
return generator, fresh
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def calibrate_positive_33_surrogate(*, seed: int = 0, maxiter: int = 250):
|
|
204
|
+
"""Offline data-free Fisher-sensitivity calibration of the 33-state positive PH family."""
|
|
205
|
+
t0 = time.perf_counter()
|
|
206
|
+
full_eval = make_cycle_engine(reduced=False)
|
|
207
|
+
rng = np.random.default_rng(seed)
|
|
208
|
+
anchors = list(ANCHORS_DEFAULT)
|
|
209
|
+
for m_base, k_base in [(1.5, 4.0), (2.0, 6.0), (2.6, 9.0), (1.8, 10.5), (2.4, 3.6)]:
|
|
210
|
+
anchors.append(np.log([m_base] * 3 + [k_base] * 3))
|
|
211
|
+
for _ in range(12):
|
|
212
|
+
ms = np.exp(rng.uniform(np.log(1.2), np.log(3.2), size=3))
|
|
213
|
+
ks = np.exp(rng.uniform(np.log(3.3), np.log(11.2), size=3))
|
|
214
|
+
anchors.append(np.log(np.r_[ms, ks]))
|
|
215
|
+
anchor_arr = jnp.asarray(anchors)
|
|
216
|
+
pf_full = jnp.asarray([full_eval(np.asarray(th))[0] for th in anchor_arr])
|
|
217
|
+
jf_full = jnp.asarray([full_eval(np.asarray(th))[1] for th in anchor_arr])
|
|
218
|
+
|
|
219
|
+
def _eval_one(th, psi):
|
|
220
|
+
def aux(t_vec):
|
|
221
|
+
gen, fresh = pos33_cycle_matrices(t_vec, psi)
|
|
222
|
+
trans = jl.expm(STEP * gen)
|
|
223
|
+
|
|
224
|
+
def step(st, _):
|
|
225
|
+
st = trans @ st
|
|
226
|
+
return st, (READ_POS33 @ st).T
|
|
227
|
+
|
|
228
|
+
p = jax.lax.scan(step, fresh, None, length=STEPS)[1]
|
|
229
|
+
return p, p
|
|
230
|
+
|
|
231
|
+
j, p = jax.jacfwd(aux, has_aux=True)(th)
|
|
232
|
+
return p, j
|
|
233
|
+
|
|
234
|
+
@jax.jit
|
|
235
|
+
def loss_fn(psi):
|
|
236
|
+
def per_anchor(th, pf, jf):
|
|
237
|
+
pr, jr = _eval_one(th, psi)
|
|
238
|
+
w = 1.0 / jnp.maximum(pf, 1e-3)
|
|
239
|
+
return jnp.mean(w * (pr - pf) ** 2) + 0.35 * jnp.mean(
|
|
240
|
+
w[..., None] * (jr - jf) ** 2
|
|
241
|
+
)
|
|
242
|
+
|
|
243
|
+
return jnp.mean(jax.vmap(per_anchor)(anchor_arr, pf_full, jf_full)) + 1e-6 * jnp.mean(
|
|
244
|
+
psi**2
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
vg = jax.jit(jax.value_and_grad(loss_fn))
|
|
248
|
+
psi0 = np.zeros(8 * K_POS_RED)
|
|
249
|
+
|
|
250
|
+
def _obj_pos33(z):
|
|
251
|
+
v, g = vg(z)
|
|
252
|
+
return float(v), np.asarray(g, dtype=float)
|
|
253
|
+
|
|
254
|
+
fit = minimize(
|
|
255
|
+
_obj_pos33,
|
|
256
|
+
psi0,
|
|
257
|
+
jac=True,
|
|
258
|
+
method="L-BFGS-B",
|
|
259
|
+
options={"maxiter": maxiter, "ftol": 1e-12},
|
|
260
|
+
)
|
|
261
|
+
psi_star = np.asarray(fit.x, dtype=float)
|
|
262
|
+
meta = dict(
|
|
263
|
+
dimension=3 * K_POS_RED,
|
|
264
|
+
stages_per_node=K_POS_RED,
|
|
265
|
+
n_anchors=len(anchors),
|
|
266
|
+
calibration_loss=float(fit.fun),
|
|
267
|
+
iterations=int(fit.nit),
|
|
268
|
+
seconds=time.perf_counter() - t0,
|
|
269
|
+
)
|
|
270
|
+
return psi_star, meta
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def make_positive_33_engine(psi):
|
|
274
|
+
"""Return JIT-compiled evaluator (theta -> probabilities, Jacobian) for Pos-Sens 33."""
|
|
275
|
+
psi_jax = jnp.asarray(psi)
|
|
276
|
+
|
|
277
|
+
def auxiliary(theta):
|
|
278
|
+
gen, fresh = pos33_cycle_matrices(theta, psi_jax)
|
|
279
|
+
trans = jl.expm(STEP * gen)
|
|
280
|
+
|
|
281
|
+
def step(st, _):
|
|
282
|
+
st = trans @ st
|
|
283
|
+
return st, (READ_POS33 @ st).T
|
|
284
|
+
|
|
285
|
+
p = jax.lax.scan(step, fresh, None, length=STEPS)[1]
|
|
286
|
+
return p, p
|
|
287
|
+
|
|
288
|
+
compiled = jax.jit(jax.jacfwd(auxiliary, has_aux=True))
|
|
289
|
+
|
|
290
|
+
def evaluate(theta):
|
|
291
|
+
deriv, vals = compiled(jnp.asarray(theta))
|
|
292
|
+
return np.asarray(vals), np.asarray(deriv)
|
|
293
|
+
|
|
294
|
+
return evaluate
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def universal_pos_clock(mean, shape, psi_univ, *, stages_red: int = 8):
|
|
298
|
+
"""Scale-equivariant topology-agnostic positive Coxian clock compressor.
|
|
299
|
+
|
|
300
|
+
Maps any (mean, shape) pair to a K_r-stage positive Coxian chain (stage_rates, entry)
|
|
301
|
+
with exact mean and strictly Metzler mass-conserving dynamics, usable on ANY graph (V, E).
|
|
302
|
+
"""
|
|
303
|
+
s_norm = (jnp.log(shape) - jnp.log(6.0)) / 0.75
|
|
304
|
+
feats = jnp.array([1.0, s_norm, s_norm**2, s_norm**3, s_norm**4])
|
|
305
|
+
w_logits = psi_univ[: 5 * stages_red].reshape(5, stages_red)
|
|
306
|
+
w_rates = psi_univ[5 * stages_red : 10 * stages_red].reshape(5, stages_red)
|
|
307
|
+
entry = jax.nn.softmax(feats @ w_logits)
|
|
308
|
+
rel_rates = jnp.exp(0.75 * jnp.tanh(feats @ w_rates))
|
|
309
|
+
rem_mean_unit = jnp.cumsum((1.0 / rel_rates)[::-1])[::-1]
|
|
310
|
+
unit_mean = jnp.dot(entry, rem_mean_unit)
|
|
311
|
+
stage_rates = (unit_mean / mean) * rel_rates
|
|
312
|
+
return stage_rates, entry
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def calibrate_universal_pos_clock(
|
|
316
|
+
*,
|
|
317
|
+
stages_red: int = 8,
|
|
318
|
+
stages_full: int = 16,
|
|
319
|
+
maxiter: int = 250,
|
|
320
|
+
k_min: float = 3.0,
|
|
321
|
+
k_max: float | None = None,
|
|
322
|
+
):
|
|
323
|
+
"""Data-free 1D survival + shape-sensitivity calibration for arbitrary graph topologies."""
|
|
324
|
+
t0 = time.perf_counter()
|
|
325
|
+
du = 0.05
|
|
326
|
+
n_u = 64
|
|
327
|
+
k_hi = float(stages_red) if k_max is None else float(k_max)
|
|
328
|
+
k_anchors = jnp.exp(jnp.linspace(jnp.log(float(k_min)), jnp.log(k_hi), 25))
|
|
329
|
+
|
|
330
|
+
def _scan_surv(blk, ent):
|
|
331
|
+
trans = jl.expm(du * blk)
|
|
332
|
+
|
|
333
|
+
def step(st, _):
|
|
334
|
+
st = trans @ st
|
|
335
|
+
return st, jnp.sum(st)
|
|
336
|
+
|
|
337
|
+
return jax.lax.scan(step, ent, None, length=n_u)[1]
|
|
338
|
+
|
|
339
|
+
def full_surv_and_sens(k_val):
|
|
340
|
+
def surv_fn(lk):
|
|
341
|
+
if stages_full == 16:
|
|
342
|
+
logits = moment_matched_logits(jnp.atleast_1d(jnp.exp(lk)))[0]
|
|
343
|
+
else:
|
|
344
|
+
center = _shape_center(jnp.exp(lk), stages_full, 0.5)
|
|
345
|
+
logits = smooth_erlang_logits(center, stages=stages_full, width=0.5)
|
|
346
|
+
rate, entry = mixed_erlang_components(1.0, logits)
|
|
347
|
+
blk = rate * (jnp.eye(stages_full, k=-1) - jnp.eye(stages_full))
|
|
348
|
+
s_u = _scan_surv(blk, entry)
|
|
349
|
+
return s_u, s_u
|
|
350
|
+
|
|
351
|
+
ds_dlk, s_u = jax.jacfwd(surv_fn, has_aux=True)(jnp.log(k_val))
|
|
352
|
+
return s_u, ds_dlk
|
|
353
|
+
|
|
354
|
+
s_ref, ds_ref = jax.vmap(full_surv_and_sens)(k_anchors)
|
|
355
|
+
|
|
356
|
+
def red_surv_and_sens(k_val, psi):
|
|
357
|
+
def surv_fn(lk):
|
|
358
|
+
r_vec, ent = universal_pos_clock(1.0, jnp.exp(lk), psi, stages_red=stages_red)
|
|
359
|
+
blk = -jnp.diag(r_vec) + jnp.diag(r_vec[:-1], k=-1)
|
|
360
|
+
s_u = _scan_surv(blk, ent)
|
|
361
|
+
return s_u, s_u
|
|
362
|
+
|
|
363
|
+
ds_dlk, s_u = jax.jacfwd(surv_fn, has_aux=True)(jnp.log(k_val))
|
|
364
|
+
return s_u, ds_dlk
|
|
365
|
+
|
|
366
|
+
@jax.jit
|
|
367
|
+
def loss_fn(psi):
|
|
368
|
+
s_hat, ds_hat = jax.vmap(lambda kv: red_surv_and_sens(kv, psi))(k_anchors)
|
|
369
|
+
w = 1.0 / jnp.maximum(s_ref * (1.0 - s_ref), 0.02)
|
|
370
|
+
return (
|
|
371
|
+
jnp.mean(w * (s_hat - s_ref) ** 2)
|
|
372
|
+
+ 0.35 * jnp.mean(w * (ds_hat - ds_ref) ** 2)
|
|
373
|
+
+ 1e-6 * jnp.mean(psi**2)
|
|
374
|
+
)
|
|
375
|
+
|
|
376
|
+
vg = jax.jit(jax.value_and_grad(loss_fn))
|
|
377
|
+
# Break stage-symmetry saddle at psi=0: index 0 has stages_red remaining stages (narrow shape),
|
|
378
|
+
# index stages_red-1 has 1 remaining stage (broad shape).
|
|
379
|
+
w_log_init = np.zeros((5, stages_red), dtype=float)
|
|
380
|
+
w_log_init[0] = np.linspace(0.5, -0.5, stages_red)
|
|
381
|
+
w_log_init[1] = np.linspace(2.5, -2.5, stages_red)
|
|
382
|
+
w_rat_init = np.zeros((5, stages_red), dtype=float)
|
|
383
|
+
w_rat_init[0] = np.linspace(-0.15, 0.15, stages_red)
|
|
384
|
+
psi0 = np.r_[w_log_init.ravel(), w_rat_init.ravel()]
|
|
385
|
+
|
|
386
|
+
def _obj_univ(z):
|
|
387
|
+
v, g = vg(z)
|
|
388
|
+
return float(v), np.asarray(g, dtype=float)
|
|
389
|
+
|
|
390
|
+
fit = minimize(
|
|
391
|
+
_obj_univ,
|
|
392
|
+
psi0,
|
|
393
|
+
jac=True,
|
|
394
|
+
method="L-BFGS-B",
|
|
395
|
+
options={"maxiter": maxiter, "ftol": 1e-13},
|
|
396
|
+
)
|
|
397
|
+
psi_univ = np.asarray(fit.x, dtype=float)
|
|
398
|
+
|
|
399
|
+
# Compute uniform global certificate on the representable positive PH cone k in [k_min, k_cert_hi]
|
|
400
|
+
k_cert_hi = float(stages_red) - 0.5 if k_max is None else float(k_max)
|
|
401
|
+
k_dense = jnp.linspace(float(k_min), k_cert_hi, 50)
|
|
402
|
+
s_f_d, ds_f_d = jax.vmap(full_surv_and_sens)(k_dense)
|
|
403
|
+
s_r_d, ds_r_d = jax.vmap(lambda kv: red_surv_and_sens(kv, jnp.asarray(psi_univ)))(k_dense)
|
|
404
|
+
cert = dict(
|
|
405
|
+
stages_red=stages_red,
|
|
406
|
+
stages_full=stages_full,
|
|
407
|
+
cone_min_shape=float(k_min),
|
|
408
|
+
cone_max_shape=k_cert_hi,
|
|
409
|
+
sup_survival_abs_error=float(jnp.max(jnp.abs(s_r_d - s_f_d))),
|
|
410
|
+
sup_shape_sens_abs_error=float(jnp.max(jnp.abs(ds_r_d - ds_f_d))),
|
|
411
|
+
calibration_seconds=time.perf_counter() - t0,
|
|
412
|
+
)
|
|
413
|
+
return psi_univ, cert
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
def build_universal_hyper_pos_network_generator(
|
|
417
|
+
fast_means,
|
|
418
|
+
slow_means,
|
|
419
|
+
slow_shapes,
|
|
420
|
+
fast_weights,
|
|
421
|
+
routing_weights,
|
|
422
|
+
edges,
|
|
423
|
+
n_nodes: int,
|
|
424
|
+
psi_univ,
|
|
425
|
+
*,
|
|
426
|
+
stages_red: int = 8,
|
|
427
|
+
):
|
|
428
|
+
"""Two-branch Universal Hyper-Pos-Sens generator on ANY graph (V, E) with K_r + 1 states/node.
|
|
429
|
+
|
|
430
|
+
Pairs one fast exponential branch (CV >= 1 burstiness) with one scale-equivariant K_r-stage
|
|
431
|
+
universal Pos-Sens Coxian branch per active node, guaranteeing exact Metzler positivity,
|
|
432
|
+
column-sum-zero simplex invariance, analytical survivor conditioning, and arbitrary CV > 1.
|
|
433
|
+
"""
|
|
434
|
+
fast_means = jnp.asarray(fast_means)
|
|
435
|
+
slow_means = jnp.asarray(slow_means)
|
|
436
|
+
slow_shapes = jnp.asarray(slow_shapes)
|
|
437
|
+
fast_weights = jnp.asarray(fast_weights)
|
|
438
|
+
psi_jax = jnp.asarray(psi_univ)
|
|
439
|
+
# Mask inactive sink nodes before vmap so placeholder zeros cannot poison psi_univ gradients with NaN
|
|
440
|
+
active_flags = jnp.array([any(u == i for u, _ in edges) for i in range(n_nodes)])
|
|
441
|
+
safe_slow_means = jnp.where(active_flags, slow_means, 1.0)
|
|
442
|
+
safe_slow_shapes = jnp.where(active_flags, slow_shapes, 6.0)
|
|
443
|
+
stage_rates, slow_entries = jax.vmap(
|
|
444
|
+
lambda m, k: universal_pos_clock(m, k, psi_jax, stages_red=stages_red)
|
|
445
|
+
)(safe_slow_means, safe_slow_shapes)
|
|
446
|
+
|
|
447
|
+
blocks = []
|
|
448
|
+
entries_all = []
|
|
449
|
+
exit_vecs = []
|
|
450
|
+
for i in range(n_nodes):
|
|
451
|
+
has_out = any(u == i for u, _ in edges)
|
|
452
|
+
if has_out:
|
|
453
|
+
r_fast = 1.0 / fast_means[i]
|
|
454
|
+
r_v = stage_rates[i]
|
|
455
|
+
blk_slow = -jnp.diag(r_v) + jnp.diag(r_v[:-1], k=-1)
|
|
456
|
+
blk = jl.block_diag(jnp.array([[-r_fast]], dtype=slow_means.dtype), blk_slow)
|
|
457
|
+
al = fast_weights[i]
|
|
458
|
+
ent = jnp.concatenate([jnp.array([al], dtype=slow_means.dtype), (1.0 - al) * slow_entries[i]])
|
|
459
|
+
ex = jnp.zeros(stages_red + 1, dtype=slow_means.dtype).at[0].set(r_fast).at[-1].set(r_v[-1])
|
|
460
|
+
blocks.append(blk)
|
|
461
|
+
entries_all.append(ent)
|
|
462
|
+
exit_vecs.append(ex)
|
|
463
|
+
else:
|
|
464
|
+
blocks.append(jnp.zeros((1, 1), dtype=slow_means.dtype))
|
|
465
|
+
entries_all.append(jnp.ones(1, dtype=slow_means.dtype))
|
|
466
|
+
exit_vecs.append(jnp.zeros(1, dtype=slow_means.dtype))
|
|
467
|
+
|
|
468
|
+
offsets = []
|
|
469
|
+
cur = 0
|
|
470
|
+
for blk in blocks:
|
|
471
|
+
offsets.append((cur, cur + blk.shape[0]))
|
|
472
|
+
cur += blk.shape[0]
|
|
473
|
+
|
|
474
|
+
gen = jl.block_diag(*blocks)
|
|
475
|
+
rw = jnp.asarray(routing_weights)
|
|
476
|
+
for e_id, (u, v) in enumerate(edges):
|
|
477
|
+
u0, u1 = offsets[u]
|
|
478
|
+
v0, v1 = offsets[v]
|
|
479
|
+
gen = gen.at[v0:v1, u0:u1].add(rw[e_id] * jnp.outer(entries_all[v], exit_vecs[u]))
|
|
480
|
+
|
|
481
|
+
fresh = jl.block_diag(*(c[:, None] for c in entries_all))
|
|
482
|
+
read = jl.block_diag(*(jnp.ones((1, e - s), dtype=slow_means.dtype) for s, e in offsets))
|
|
483
|
+
return gen, fresh, read
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def build_universal_pos_network_generator(
|
|
487
|
+
means, shapes, routing_weights, edges, n_nodes: int, psi_univ, *, stages_red: int = 8
|
|
488
|
+
):
|
|
489
|
+
"""Assemble exact positive Metzler generator on ANY graph (V, E) using universal Pos-Sens clocks.
|
|
490
|
+
|
|
491
|
+
For nodes with multiple outgoing edges sharing node sojourn clock (or per-edge split weights
|
|
492
|
+
routing_weights[e] summing to 1 per source node), compiles V*stages_red global positive states.
|
|
493
|
+
"""
|
|
494
|
+
means = jnp.asarray(means)
|
|
495
|
+
shapes = jnp.asarray(shapes)
|
|
496
|
+
psi_jax = jnp.asarray(psi_univ)
|
|
497
|
+
# Mask inactive sink nodes before vmap so placeholder zeros cannot poison psi_univ gradients with NaN
|
|
498
|
+
active_flags = jnp.array([any(u == i for u, _ in edges) for i in range(n_nodes)])
|
|
499
|
+
safe_means = jnp.where(active_flags, means, 1.0)
|
|
500
|
+
safe_shapes = jnp.where(active_flags, shapes, 6.0)
|
|
501
|
+
stage_rates, entries = jax.vmap(
|
|
502
|
+
lambda m, k: universal_pos_clock(m, k, psi_jax, stages_red=stages_red)
|
|
503
|
+
)(safe_means, safe_shapes)
|
|
504
|
+
blocks = []
|
|
505
|
+
for i in range(n_nodes):
|
|
506
|
+
has_out = any(u == i for u, _ in edges)
|
|
507
|
+
if has_out:
|
|
508
|
+
r_v = stage_rates[i]
|
|
509
|
+
blocks.append(-jnp.diag(r_v) + jnp.diag(r_v[:-1], k=-1))
|
|
510
|
+
else:
|
|
511
|
+
blocks.append(jnp.zeros((1, 1), dtype=means.dtype))
|
|
512
|
+
|
|
513
|
+
offsets = []
|
|
514
|
+
cur = 0
|
|
515
|
+
for blk in blocks:
|
|
516
|
+
offsets.append((cur, cur + blk.shape[0]))
|
|
517
|
+
cur += blk.shape[0]
|
|
518
|
+
|
|
519
|
+
gen = jl.block_diag(*blocks)
|
|
520
|
+
rw = jnp.asarray(routing_weights)
|
|
521
|
+
for e_id, (u, v) in enumerate(edges):
|
|
522
|
+
u0, u1 = offsets[u]
|
|
523
|
+
v0, v1 = offsets[v]
|
|
524
|
+
exit_rate_u = stage_rates[u, -1] * rw[e_id]
|
|
525
|
+
ent_v = entries[v] if (v1 - v0) == stages_red else jnp.ones(1, dtype=means.dtype)
|
|
526
|
+
gen = gen.at[v0:v1, u1 - 1].add(exit_rate_u * ent_v)
|
|
527
|
+
|
|
528
|
+
fresh_cols = [
|
|
529
|
+
entries[i] if (offsets[i][1] - offsets[i][0]) == stages_red else jnp.ones(1, dtype=means.dtype)
|
|
530
|
+
for i in range(n_nodes)
|
|
531
|
+
]
|
|
532
|
+
fresh = jl.block_diag(*(c[:, None] for c in fresh_cols))
|
|
533
|
+
read = jl.block_diag(*(jnp.ones((1, e - s), dtype=means.dtype) for s, e in offsets))
|
|
534
|
+
return gen, fresh, read
|
diff_renewal/renewal.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Differentiable population means for sequential independent renewal stages."""
|
|
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 solve_erlang_chain(means, logits, ts, *, rtol: float = 1e-8, atol: float = 1e-10):
|
|
11
|
+
"""Solve a fresh cohort through C sequential mixed-Erlang compartments.
|
|
12
|
+
|
|
13
|
+
means: (C,) positive mean dwell times; logits: (C, K) mixture logits for
|
|
14
|
+
1..K exponential stages; ts: sorted times >= 0 with positive final time.
|
|
15
|
+
Returns Diffrax Solution with ys shape (len(ts), C + 1) containing the C
|
|
16
|
+
transient population fractions and final absorbing fraction.
|
|
17
|
+
"""
|
|
18
|
+
means, logits, ts = jnp.asarray(means), jnp.asarray(logits), jnp.asarray(ts)
|
|
19
|
+
if (
|
|
20
|
+
means.ndim != 1
|
|
21
|
+
or means.size < 1
|
|
22
|
+
or logits.ndim != 2
|
|
23
|
+
or logits.shape[0] != means.size
|
|
24
|
+
or logits.shape[1] < 1
|
|
25
|
+
):
|
|
26
|
+
raise ValueError("require means shape (C,) and logits shape (C,K), with C,K >= 1")
|
|
27
|
+
if ts.ndim != 1 or ts.size < 1:
|
|
28
|
+
raise ValueError("ts must be a nonempty 1D array")
|
|
29
|
+
rate, alpha = jax.vmap(mixed_erlang_components)(means, logits)
|
|
30
|
+
initial = jnp.zeros_like(alpha).at[0].set(alpha[0])
|
|
31
|
+
|
|
32
|
+
def field(t, state, args):
|
|
33
|
+
rates, entry = args
|
|
34
|
+
p, completed = state
|
|
35
|
+
stage_flux = rates[:, None] * p
|
|
36
|
+
exits = stage_flux[:, -1]
|
|
37
|
+
inflows = jnp.concatenate((jnp.zeros(1, dtype=p.dtype), exits[:-1]))
|
|
38
|
+
dp = (
|
|
39
|
+
jnp.pad(stage_flux[:, :-1], ((0, 0), (1, 0)))
|
|
40
|
+
- stage_flux
|
|
41
|
+
+ entry * inflows[:, None]
|
|
42
|
+
)
|
|
43
|
+
return dp, exits[-1]
|
|
44
|
+
|
|
45
|
+
def observe(t, state, args):
|
|
46
|
+
p, completed = state
|
|
47
|
+
return jnp.concatenate((jnp.sum(p, axis=1), jnp.atleast_1d(completed)))
|
|
48
|
+
|
|
49
|
+
return diffrax.diffeqsolve(
|
|
50
|
+
diffrax.ODETerm(field),
|
|
51
|
+
diffrax.Tsit5(),
|
|
52
|
+
t0=0.0,
|
|
53
|
+
t1=ts[-1],
|
|
54
|
+
dt0=None,
|
|
55
|
+
y0=(initial, jnp.array(0.0, dtype=initial.dtype)),
|
|
56
|
+
args=(rate, alpha),
|
|
57
|
+
saveat=diffrax.SaveAt(ts=ts, fn=observe),
|
|
58
|
+
stepsize_controller=diffrax.PIDController(rtol=rtol, atol=atol),
|
|
59
|
+
adjoint=diffrax.RecursiveCheckpointAdjoint(),
|
|
60
|
+
max_steps=100_000,
|
|
61
|
+
)
|