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,188 @@
|
|
|
1
|
+
"""Fisher information geometry and adjoint sensitivity residual accounting."""
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def multinomial_score_design(probabilities, derivatives, sample_sizes=1):
|
|
7
|
+
"""Weighted score matrix W satisfying Fisher = W.T @ W."""
|
|
8
|
+
p, dp = np.asarray(probabilities, float), np.asarray(derivatives, float)
|
|
9
|
+
if p.ndim != 2 or dp.ndim != 3 or dp.shape[:2] != p.shape:
|
|
10
|
+
raise ValueError("Expected probabilities (T,C), derivatives (T,C,P)")
|
|
11
|
+
if not np.all(np.isfinite(p)) or not np.all(p > 0) or not np.all(np.isfinite(dp)):
|
|
12
|
+
raise ValueError("A finite, strictly positive, fixed probability support is required")
|
|
13
|
+
if not np.allclose(p.sum(axis=1), 1.0, atol=1e-9, rtol=0):
|
|
14
|
+
raise ValueError("Probabilities must sum to one")
|
|
15
|
+
if not np.allclose(dp.sum(axis=1), 0.0, atol=1e-8, rtol=0):
|
|
16
|
+
raise ValueError("Probability derivatives must sum to zero")
|
|
17
|
+
n = np.broadcast_to(np.asarray(sample_sizes, float), (p.shape[0],))
|
|
18
|
+
if not np.all(np.isfinite(n)) or np.any(n < 0):
|
|
19
|
+
raise ValueError("Sample sizes must be finite and nonnegative")
|
|
20
|
+
return (np.sqrt(n[:, None] / p)[..., None] * dp).reshape(-1, dp.shape[-1])
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def coarsened_fisher(probabilities, derivatives, groups, sample_sizes=1):
|
|
24
|
+
"""Exact conditional-score information lost under a fixed category partition."""
|
|
25
|
+
p, dp = np.asarray(probabilities, float), np.asarray(derivatives, float)
|
|
26
|
+
design = multinomial_score_design(p, dp, sample_sizes)
|
|
27
|
+
groups = np.asarray(groups)
|
|
28
|
+
if groups.shape != (p.shape[1],):
|
|
29
|
+
raise ValueError("Supply one group label per category")
|
|
30
|
+
labels, index = np.unique(groups, return_inverse=True)
|
|
31
|
+
q = np.stack([p[:, index == i].sum(axis=1) for i in range(len(labels))], axis=1)
|
|
32
|
+
dq = np.stack([dp[:, index == i].sum(axis=1) for i in range(len(labels))], axis=1)
|
|
33
|
+
coarse = multinomial_score_design(q, dq, sample_sizes)
|
|
34
|
+
n = np.broadcast_to(np.asarray(sample_sizes, float), (len(p),))
|
|
35
|
+
residual = np.sqrt(n[:, None] * p)[..., None] * (
|
|
36
|
+
dp / p[..., None] - (dq / q[..., None])[:, index]
|
|
37
|
+
)
|
|
38
|
+
residual = residual.reshape(-1, dp.shape[-1])
|
|
39
|
+
return dict(
|
|
40
|
+
fine=design.T @ design,
|
|
41
|
+
coarse=coarse.T @ coarse,
|
|
42
|
+
loss=residual.T @ residual,
|
|
43
|
+
residual_design=residual,
|
|
44
|
+
coarse_probabilities=q,
|
|
45
|
+
coarse_derivatives=dq,
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def efficient_fisher(design, interest, nuisance, relative_cutoff: float = 1e-10):
|
|
50
|
+
"""Project out nuisance tangent scores using an explicit SVD rank cutoff."""
|
|
51
|
+
w = np.asarray(design, float)
|
|
52
|
+
if w.ndim != 2 or not np.all(np.isfinite(w)) or not 0 <= relative_cutoff < 1:
|
|
53
|
+
raise ValueError("Expected finite 2D design and cutoff in [0,1)")
|
|
54
|
+
interest, nuisance = list(interest), list(nuisance)
|
|
55
|
+
if set(interest) & set(nuisance) or len(set(interest + nuisance)) != len(
|
|
56
|
+
interest + nuisance
|
|
57
|
+
):
|
|
58
|
+
raise ValueError("Interest and nuisance indices must be distinct")
|
|
59
|
+
if any(i < 0 or i >= w.shape[1] for i in interest + nuisance):
|
|
60
|
+
raise ValueError("Parameter index out of bounds")
|
|
61
|
+
retained = w[:, interest]
|
|
62
|
+
rank = 0
|
|
63
|
+
if nuisance:
|
|
64
|
+
u, s, _ = np.linalg.svd(w[:, nuisance], full_matrices=False)
|
|
65
|
+
rank = int(np.count_nonzero(s > relative_cutoff * s[0])) if len(s) and s[0] else 0
|
|
66
|
+
retained = retained - u[:, :rank] @ (u[:, :rank].T @ retained)
|
|
67
|
+
return dict(
|
|
68
|
+
information=retained.T @ retained,
|
|
69
|
+
residual_design=retained,
|
|
70
|
+
nuisance_rank=rank,
|
|
71
|
+
relative_cutoff=relative_cutoff,
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def adjoint_residual_estimate(
|
|
76
|
+
transitions,
|
|
77
|
+
approximate_states,
|
|
78
|
+
initial,
|
|
79
|
+
terminal_observable,
|
|
80
|
+
*,
|
|
81
|
+
adjoints=None,
|
|
82
|
+
adjoint_error_bounds=None,
|
|
83
|
+
):
|
|
84
|
+
"""Exact discrete suffix-adjoint terminal observable error accounting."""
|
|
85
|
+
a, x = np.asarray(transitions, float), np.asarray(approximate_states, float)
|
|
86
|
+
x0, c = np.asarray(initial, float), np.asarray(terminal_observable, float)
|
|
87
|
+
if a.ndim != 3 or a.shape[1] != a.shape[2]:
|
|
88
|
+
raise ValueError("Transitions must have shape (N,D,D)")
|
|
89
|
+
n, d, _ = a.shape
|
|
90
|
+
if x.shape != (n + 1, d) or x0.shape != (d,) or c.shape != (d,):
|
|
91
|
+
raise ValueError("State or observable shape does not match transitions")
|
|
92
|
+
if not all(np.all(np.isfinite(v)) for v in (a, x, x0, c)):
|
|
93
|
+
raise ValueError("Inputs must be finite")
|
|
94
|
+
exact = adjoints is None
|
|
95
|
+
if exact:
|
|
96
|
+
if adjoint_error_bounds is not None:
|
|
97
|
+
raise ValueError("Bounds are only used with supplied approximate adjoints")
|
|
98
|
+
z = np.empty_like(x)
|
|
99
|
+
z[-1] = c
|
|
100
|
+
for step in range(n - 1, -1, -1):
|
|
101
|
+
z[step] = a[step].T @ z[step + 1]
|
|
102
|
+
else:
|
|
103
|
+
z = np.asarray(adjoints, float)
|
|
104
|
+
if z.shape != x.shape or not np.all(np.isfinite(z)):
|
|
105
|
+
raise ValueError("Adjoints must be finite and have the state trajectory shape")
|
|
106
|
+
defects = np.vstack([x0 - x[0], np.einsum("nij,nj->ni", a, x[:-1]) - x[1:]])
|
|
107
|
+
terms = np.einsum("ni,ni->n", z, defects)
|
|
108
|
+
estimate = float(terms.sum())
|
|
109
|
+
radius = 0.0 if exact else None
|
|
110
|
+
if adjoint_error_bounds is not None:
|
|
111
|
+
bounds = np.asarray(adjoint_error_bounds, float)
|
|
112
|
+
if bounds.shape != x.shape or not np.all(np.isfinite(bounds)) or np.any(bounds < 0):
|
|
113
|
+
raise ValueError("Adjoint bounds must be finite, nonnegative and match the states")
|
|
114
|
+
radius = float(np.sum(np.abs(defects) * bounds))
|
|
115
|
+
return dict(
|
|
116
|
+
signed_error=estimate,
|
|
117
|
+
correction_interval=None if radius is None else (estimate - radius, estimate + radius),
|
|
118
|
+
error_radius=radius,
|
|
119
|
+
absolute_pairing_bound=float(np.abs(terms).sum()),
|
|
120
|
+
norm_pairing_bound=float(
|
|
121
|
+
np.sum(np.sum(np.abs(defects), axis=1) * np.max(np.abs(z), axis=1))
|
|
122
|
+
),
|
|
123
|
+
terms=terms,
|
|
124
|
+
defects=defects,
|
|
125
|
+
adjoints=z,
|
|
126
|
+
exact_adjoint=exact,
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def adjoint_sensitivity_residual(
|
|
131
|
+
transitions,
|
|
132
|
+
approximate_states,
|
|
133
|
+
initial,
|
|
134
|
+
terminal_observable,
|
|
135
|
+
transition_derivatives,
|
|
136
|
+
state_derivatives,
|
|
137
|
+
initial_derivatives,
|
|
138
|
+
observable_derivatives,
|
|
139
|
+
):
|
|
140
|
+
"""Exact discrete suffix-adjoint gradient-error decomposition."""
|
|
141
|
+
result = adjoint_residual_estimate(
|
|
142
|
+
transitions, approximate_states, initial, terminal_observable
|
|
143
|
+
)
|
|
144
|
+
a, x = np.asarray(transitions, float), np.asarray(approximate_states, float)
|
|
145
|
+
da, dx, di, dc = [
|
|
146
|
+
np.asarray(v, float)
|
|
147
|
+
for v in (
|
|
148
|
+
transition_derivatives,
|
|
149
|
+
state_derivatives,
|
|
150
|
+
initial_derivatives,
|
|
151
|
+
observable_derivatives,
|
|
152
|
+
)
|
|
153
|
+
]
|
|
154
|
+
if dc.ndim != 2:
|
|
155
|
+
raise ValueError("Derivative inputs must append a parameter axis")
|
|
156
|
+
k = dc.shape[-1]
|
|
157
|
+
if (
|
|
158
|
+
da.shape != a.shape + (k,)
|
|
159
|
+
or dx.shape != x.shape + (k,)
|
|
160
|
+
or di.shape != (a.shape[-1], k)
|
|
161
|
+
or dc.shape != di.shape
|
|
162
|
+
):
|
|
163
|
+
raise ValueError("Derivative shapes do not match their inputs")
|
|
164
|
+
if not all(np.all(np.isfinite(v)) for v in (da, dx, di, dc)):
|
|
165
|
+
raise ValueError("Derivatives must be finite")
|
|
166
|
+
z, defects = result["adjoints"], result["defects"]
|
|
167
|
+
dz = np.empty_like(dx)
|
|
168
|
+
dz[-1] = dc
|
|
169
|
+
for n in range(len(a) - 1, -1, -1):
|
|
170
|
+
dz[n] = np.einsum("ijk,i->jk", da[n], z[n + 1]) + a[n].T @ dz[n + 1]
|
|
171
|
+
dr = np.concatenate(
|
|
172
|
+
[
|
|
173
|
+
(di - dx[0])[None],
|
|
174
|
+
np.einsum("nijk,nj->nik", da, x[:-1])
|
|
175
|
+
+ np.einsum("nij,njk->nik", a, dx[:-1])
|
|
176
|
+
- dx[1:],
|
|
177
|
+
],
|
|
178
|
+
axis=0,
|
|
179
|
+
)
|
|
180
|
+
terms = np.einsum("nik,ni->nk", dz, defects) + np.einsum("ni,nik->nk", z, dr)
|
|
181
|
+
return dict(
|
|
182
|
+
signed_gradient_error=terms.sum(axis=0),
|
|
183
|
+
terms=terms,
|
|
184
|
+
adjoint_derivatives=dz,
|
|
185
|
+
defect_derivatives=dr,
|
|
186
|
+
sum_absolute_gradient_pairings=np.abs(terms).sum(axis=0),
|
|
187
|
+
output_error=result["signed_error"],
|
|
188
|
+
)
|
|
@@ -0,0 +1,420 @@
|
|
|
1
|
+
"""Stiffness- and stage-count-independent Laplace-Schur renewal solvers.
|
|
2
|
+
|
|
3
|
+
Exploits the exact renewal resolvent identity from Theorem 3,
|
|
4
|
+
P(s) = diag(S_i(s)) * (I_V - R * diag(phi_i(s)))^{-1},
|
|
5
|
+
to collapse a D_st = sum_i n_i phase-type network (arbitrary stage count K and
|
|
6
|
+
arbitrary fast/slow rate stiffness ratio lambda_f / lambda_s) into V x V node-level
|
|
7
|
+
solves:
|
|
8
|
+
1. `solve_renewal_talbot`: Weideman (2006) optimal fixed-Talbot contour quadrature
|
|
9
|
+
computing exact fresh AND aged occupancies simultaneously from a single shared
|
|
10
|
+
resolvent inverse Z(s) = (I_V - R * diag(phi(s)))^{-1}.
|
|
11
|
+
2. `solve_frailty_renewal_talbot`: G-component persistent latent-speed Frailty-DRN
|
|
12
|
+
operationalizing Proposition 3 with exact Bayesian frailty conditioning
|
|
13
|
+
P(g | T > a) proportional to pi_g * S_g(a) (persisting across transitions!).
|
|
14
|
+
3. `solve_coxian_hyper_talbot`: Exact Laplace-Schur-Talbot solver for arbitrary
|
|
15
|
+
non-uniform Coxian + fast exponential clocks (e.g. Universal Hyper-Pos-Sens
|
|
16
|
+
plugged zero-shot into large-V graphs).
|
|
17
|
+
4. `laplace_schur_sdirk2_solve`: Exact block-bidiagonal Schur-complement implicit
|
|
18
|
+
2-stage L-stable SDIRK2 time-stepper for (I - gamma*h*A) X = Y.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import jax
|
|
24
|
+
import jax.numpy as jnp
|
|
25
|
+
import jax.scipy.linalg as jl
|
|
26
|
+
import numpy as np
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def weideman_talbot_contour(
|
|
30
|
+
horizons: np.ndarray | jax.Array,
|
|
31
|
+
*,
|
|
32
|
+
n_nodes: int = 16,
|
|
33
|
+
) -> tuple[jax.Array, jax.Array]:
|
|
34
|
+
"""Build Weideman (2006) optimal fixed-Talbot upper-half-plane contour nodes & weights.
|
|
35
|
+
|
|
36
|
+
Uses conjugate symmetry of real-valued probability trajectories: evaluating only the
|
|
37
|
+
M = n_nodes // 2 upper-half-plane nodes and taking Re(sum(w * F(s))) recovers the
|
|
38
|
+
exact Bromwich inverse Laplace integral to ~1e-8 (n_nodes=16) or ~1e-10 (n_nodes=20).
|
|
39
|
+
"""
|
|
40
|
+
h_arr = np.asarray(horizons, dtype=np.float64)
|
|
41
|
+
if h_arr.ndim != 1 or h_arr.size == 0 or not np.all(np.isfinite(h_arr)) or np.any(h_arr <= 0.0):
|
|
42
|
+
raise ValueError("horizons must be a nonempty 1D array of finite positive times")
|
|
43
|
+
n_int = int(n_nodes)
|
|
44
|
+
if n_int < 2 or n_int % 2 != 0:
|
|
45
|
+
raise ValueError("n_nodes must be an even integer >= 2 for conjugate-symmetric Talbot quadrature")
|
|
46
|
+
m_half = n_int // 2
|
|
47
|
+
step = 2.0 * np.pi / float(n_int)
|
|
48
|
+
theta = (np.arange(m_half, dtype=np.float64) + 0.5) * step
|
|
49
|
+
cot_t = 1.0 / np.tan(0.6407 * theta)
|
|
50
|
+
csc2_t = 1.0 + cot_t**2
|
|
51
|
+
z_unit = -0.6122 + 0.5017 * theta * cot_t + 0.2645j * theta
|
|
52
|
+
dz_unit = 0.5017 * (cot_t - 0.6407 * theta * csc2_t) + 0.2645j
|
|
53
|
+
|
|
54
|
+
s_all = []
|
|
55
|
+
w_all = []
|
|
56
|
+
for t_val in h_arr:
|
|
57
|
+
scale = float(n_nodes) / float(t_val)
|
|
58
|
+
s = scale * z_unit
|
|
59
|
+
w = 2.0 * (step / (2.0j * np.pi)) * scale * dz_unit * np.exp(s * float(t_val))
|
|
60
|
+
s_all.append(s)
|
|
61
|
+
w_all.append(w)
|
|
62
|
+
return (
|
|
63
|
+
jnp.asarray(np.stack(s_all, axis=0), dtype=jnp.complex128),
|
|
64
|
+
jnp.asarray(np.stack(w_all, axis=0), dtype=jnp.complex128),
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def hyper_erlang_aged_phases_and_log_surv(
|
|
69
|
+
lam_f: jax.Array,
|
|
70
|
+
lam_s: jax.Array,
|
|
71
|
+
alpha_f: jax.Array,
|
|
72
|
+
b_slow: jax.Array,
|
|
73
|
+
age: float,
|
|
74
|
+
active_mask: jax.Array,
|
|
75
|
+
) -> tuple[jax.Array, jax.Array, jax.Array]:
|
|
76
|
+
"""Exact overflow-free aged phase weights (p_fast, p_slow) and log survival log S_v(a).
|
|
77
|
+
|
|
78
|
+
Valid for arbitrary nonnegative rates (both ``lam_f >= lam_s`` and ``lam_f < lam_s``)
|
|
79
|
+
on active nodes and ``lam_f = lam_s = 0`` on absorbing nodes (``active_mask == 0``).
|
|
80
|
+
"""
|
|
81
|
+
k_slow = int(b_slow.shape[-1])
|
|
82
|
+
if age <= 0.0:
|
|
83
|
+
p_f = alpha_f * active_mask
|
|
84
|
+
p_s = (1.0 - alpha_f)[:, None] * b_slow * active_mask[:, None]
|
|
85
|
+
log_s = jnp.zeros_like(lam_f)
|
|
86
|
+
return p_f, p_s, log_s
|
|
87
|
+
|
|
88
|
+
js = jnp.arange(k_slow, dtype=lam_f.dtype)
|
|
89
|
+
diff_idx = js[:, None] - js[None, :]
|
|
90
|
+
valid = diff_idx >= 0
|
|
91
|
+
d_safe = jnp.where(valid, diff_idx, 0.0)
|
|
92
|
+
xa = jnp.maximum(lam_s * age, 1e-30)
|
|
93
|
+
log_p = (
|
|
94
|
+
d_safe[None, :, :] * jnp.log(xa)[:, None, None]
|
|
95
|
+
- jax.scipy.special.gammaln(d_safe + 1.0)[None, :, :]
|
|
96
|
+
- (lam_s * age)[:, None, None]
|
|
97
|
+
)
|
|
98
|
+
log_fast = -lam_f * age
|
|
99
|
+
m_sh = jnp.maximum(
|
|
100
|
+
jnp.max(jnp.where(valid[None, :, :], log_p, -1e9), axis=(1, 2)),
|
|
101
|
+
log_fast,
|
|
102
|
+
)
|
|
103
|
+
p_mat = jnp.where(
|
|
104
|
+
valid[None, :, :],
|
|
105
|
+
jnp.exp(jnp.clip(log_p - m_sh[:, None, None], -700.0, 0.0)),
|
|
106
|
+
0.0,
|
|
107
|
+
)
|
|
108
|
+
# Factor out exp(m_sh) so both branches stay strictly <= 1 regardless of rate ordering:
|
|
109
|
+
slow_un = (1.0 - alpha_f)[:, None] * jnp.einsum("vji,vi->vj", p_mat, b_slow)
|
|
110
|
+
fast_un = alpha_f * jnp.exp(jnp.clip(log_fast - m_sh, -700.0, 0.0))
|
|
111
|
+
total_un = jnp.maximum(fast_un + jnp.sum(slow_un, axis=-1), 1e-300)
|
|
112
|
+
|
|
113
|
+
p_f = jnp.where(active_mask > 0.5, fast_un / total_un, 0.0)
|
|
114
|
+
p_s = jnp.where(active_mask[:, None] > 0.5, slow_un / total_un[:, None], 0.0)
|
|
115
|
+
log_surv = jnp.where(
|
|
116
|
+
active_mask > 0.5,
|
|
117
|
+
m_sh + jnp.log(total_un),
|
|
118
|
+
0.0,
|
|
119
|
+
)
|
|
120
|
+
return p_f, p_s, log_surv
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _hyper_erlang_laplace(
|
|
124
|
+
s_c: jax.Array,
|
|
125
|
+
lam_f: jax.Array,
|
|
126
|
+
lam_s: jax.Array,
|
|
127
|
+
p_f: jax.Array,
|
|
128
|
+
p_s: jax.Array,
|
|
129
|
+
active_mask: jax.Array,
|
|
130
|
+
) -> tuple[jax.Array, jax.Array]:
|
|
131
|
+
"""Exact Laplace transform phi_v(s) and survival transform S_v(s) for 2-branch Hyper-Erlang."""
|
|
132
|
+
k_slow = int(p_s.shape[-1])
|
|
133
|
+
qf = lam_f / (s_c + lam_f)
|
|
134
|
+
qs = lam_s / (s_c + lam_s)
|
|
135
|
+
# Entry at stage j (0..K-1) needs (K - j) exponential transitions to exit!
|
|
136
|
+
pows = jnp.stack([qs ** (k_slow - j) for j in range(k_slow)], axis=-1)
|
|
137
|
+
phi = (p_f * qf + jnp.sum(p_s * pows, axis=-1)) * active_mask
|
|
138
|
+
s_v = (1.0 - phi) / s_c
|
|
139
|
+
return phi, s_v
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def solve_renewal_talbot(
|
|
143
|
+
lam_f: jax.Array,
|
|
144
|
+
lam_s: jax.Array,
|
|
145
|
+
alpha_f: jax.Array,
|
|
146
|
+
b_slow: jax.Array,
|
|
147
|
+
routing_mat: jax.Array,
|
|
148
|
+
horizons: np.ndarray | jax.Array,
|
|
149
|
+
active_mask: jax.Array,
|
|
150
|
+
*,
|
|
151
|
+
eval_nodes: jax.Array | None = None,
|
|
152
|
+
age: float = 0.0,
|
|
153
|
+
n_talbot: int = 16,
|
|
154
|
+
return_both_fresh_and_aged: bool = False,
|
|
155
|
+
):
|
|
156
|
+
"""Exact stiffness- and K-independent Laplace-Schur-Talbot renewal network solver.
|
|
157
|
+
|
|
158
|
+
Computes P(t)[u, v] = P(X(t) = v | X(0) = u) for all eval_nodes u and all horizons t
|
|
159
|
+
simultaneously from a single shared V x V resolvent inverse Z(s) = (I - R diag(phi(s)))^{-1}.
|
|
160
|
+
When `return_both_fresh_and_aged=True`, returns `(P_fresh, P_aged)` at ZERO extra matrix solves!
|
|
161
|
+
"""
|
|
162
|
+
v_cnt = int(routing_mat.shape[0])
|
|
163
|
+
ev_idx = jnp.arange(v_cnt, dtype=jnp.int32) if eval_nodes is None else eval_nodes
|
|
164
|
+
s_grid, w_grid = weideman_talbot_contour(horizons, n_nodes=n_talbot)
|
|
165
|
+
|
|
166
|
+
pf_fresh = alpha_f * active_mask
|
|
167
|
+
ps_fresh = (1.0 - alpha_f)[:, None] * b_slow * active_mask[:, None]
|
|
168
|
+
need_aged = return_both_fresh_and_aged or (age > 0.0)
|
|
169
|
+
if need_aged:
|
|
170
|
+
pf_aged, ps_aged, _ = hyper_erlang_aged_phases_and_log_surv(
|
|
171
|
+
lam_f, lam_s, alpha_f, b_slow, age, active_mask
|
|
172
|
+
)
|
|
173
|
+
else:
|
|
174
|
+
pf_aged, ps_aged = pf_fresh, ps_fresh
|
|
175
|
+
|
|
176
|
+
eye_v = jnp.eye(v_cnt, dtype=jnp.complex128)
|
|
177
|
+
r_c = routing_mat.astype(jnp.complex128)
|
|
178
|
+
|
|
179
|
+
def one_s(s_c):
|
|
180
|
+
phi, s_v = _hyper_erlang_laplace(s_c, lam_f, lam_s, pf_fresh, ps_fresh, active_mask)
|
|
181
|
+
m_mat = eye_v - r_c * phi[None, :]
|
|
182
|
+
z_inv = jnp.linalg.solve(m_mat, eye_v) # (V, V), col u = start u
|
|
183
|
+
p_fr = s_v[:, None] * z_inv # (V, V) [v, u]
|
|
184
|
+
if not need_aged:
|
|
185
|
+
return p_fr, p_fr
|
|
186
|
+
phi_a, s_va = _hyper_erlang_laplace(s_c, lam_f, lam_s, pf_aged, ps_aged, active_mask)
|
|
187
|
+
# P^(a)(s) = diag(S^(a)) + diag(S) * Z * R * diag(phi^(a))
|
|
188
|
+
zr = z_inv @ r_c
|
|
189
|
+
p_ag = jnp.diag(s_va) + (s_v[:, None] * zr) * phi_a[None, :]
|
|
190
|
+
return p_fr, p_ag
|
|
191
|
+
|
|
192
|
+
def one_h(s_vec, w_vec):
|
|
193
|
+
p_frs, p_ags = jax.vmap(one_s)(s_vec) # (M, V, V)
|
|
194
|
+
fr_h = jnp.real(jnp.einsum("m,mvu->uv", w_vec, p_frs))[ev_idx]
|
|
195
|
+
fr_h = jnp.maximum(fr_h, 1e-12)
|
|
196
|
+
fr_h = fr_h / jnp.sum(fr_h, axis=-1, keepdims=True)
|
|
197
|
+
if not need_aged:
|
|
198
|
+
return fr_h, fr_h
|
|
199
|
+
ag_h = jnp.real(jnp.einsum("m,mvu->uv", w_vec, p_ags))[ev_idx]
|
|
200
|
+
ag_h = jnp.maximum(ag_h, 1e-12)
|
|
201
|
+
ag_h = ag_h / jnp.sum(ag_h, axis=-1, keepdims=True)
|
|
202
|
+
return fr_h, ag_h
|
|
203
|
+
|
|
204
|
+
fr_all, ag_all = jax.vmap(one_h)(s_grid, w_grid) # (H, B_ev, V)
|
|
205
|
+
fr_out = jnp.swapaxes(fr_all, 0, 1) # (B_ev, H, V)
|
|
206
|
+
ag_out = jnp.swapaxes(ag_all, 0, 1)
|
|
207
|
+
if return_both_fresh_and_aged:
|
|
208
|
+
return fr_out, ag_out
|
|
209
|
+
return ag_out if age > 0.0 else fr_out
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def solve_frailty_renewal_talbot(
|
|
213
|
+
lam_f: jax.Array,
|
|
214
|
+
lam_s: jax.Array,
|
|
215
|
+
alpha_f: jax.Array,
|
|
216
|
+
b_slow: jax.Array,
|
|
217
|
+
routing_mat: jax.Array,
|
|
218
|
+
frailty_multipliers: jax.Array,
|
|
219
|
+
frailty_weights: jax.Array,
|
|
220
|
+
horizons: np.ndarray | jax.Array,
|
|
221
|
+
active_mask: jax.Array,
|
|
222
|
+
*,
|
|
223
|
+
eval_nodes: jax.Array | None = None,
|
|
224
|
+
age: float = 0.0,
|
|
225
|
+
n_talbot: int = 16,
|
|
226
|
+
return_both_fresh_and_aged: bool = False,
|
|
227
|
+
):
|
|
228
|
+
"""Exact G-component persistent latent-speed Frailty-DRN (operationalizing Proposition 3).
|
|
229
|
+
|
|
230
|
+
Parameters
|
|
231
|
+
----------
|
|
232
|
+
frailty_multipliers : (G,) positive global speed multipliers gamma_g
|
|
233
|
+
frailty_weights : (V, G) simplex prior weights pi_{v, g} per starting node v
|
|
234
|
+
"""
|
|
235
|
+
v_cnt = int(routing_mat.shape[0])
|
|
236
|
+
ev_idx = jnp.arange(v_cnt, dtype=jnp.int32) if eval_nodes is None else eval_nodes
|
|
237
|
+
|
|
238
|
+
def one_class(gamma_g):
|
|
239
|
+
lf_g = lam_f * gamma_g
|
|
240
|
+
ls_g = lam_s * gamma_g
|
|
241
|
+
p_fr, p_ag = solve_renewal_talbot(
|
|
242
|
+
lf_g,
|
|
243
|
+
ls_g,
|
|
244
|
+
alpha_f,
|
|
245
|
+
b_slow,
|
|
246
|
+
routing_mat,
|
|
247
|
+
horizons,
|
|
248
|
+
active_mask,
|
|
249
|
+
eval_nodes=ev_idx,
|
|
250
|
+
age=age,
|
|
251
|
+
n_talbot=n_talbot,
|
|
252
|
+
return_both_fresh_and_aged=True,
|
|
253
|
+
)
|
|
254
|
+
_, _, log_s = hyper_erlang_aged_phases_and_log_surv(
|
|
255
|
+
lf_g, ls_g, alpha_f, b_slow, age, active_mask
|
|
256
|
+
)
|
|
257
|
+
return p_fr, p_ag, log_s[ev_idx]
|
|
258
|
+
|
|
259
|
+
# vmap across G persistent speed classes!
|
|
260
|
+
p_fr_g, p_ag_g, log_s_g = jax.vmap(one_class)(frailty_multipliers) # (G, B_ev, H, V), (G, B_ev)
|
|
261
|
+
pi_ev = frailty_weights[ev_idx] # (B_ev, G)
|
|
262
|
+
|
|
263
|
+
# Fresh mixture: sum_g pi_{u, g} * P_g(t)
|
|
264
|
+
p_fresh = jnp.einsum("bg,gbhv->bhv", pi_ev, p_fr_g)
|
|
265
|
+
p_fresh = jnp.maximum(p_fresh, 1e-12)
|
|
266
|
+
p_fresh = p_fresh / jnp.sum(p_fresh, axis=-1, keepdims=True)
|
|
267
|
+
|
|
268
|
+
# Exact Bayesian frailty posterior at age a: w_{u, g}(a) proportional to pi_{u, g} * S_{u, g}(a)!
|
|
269
|
+
# Strictly mask zero-prior classes to -inf so they can never hijack the posterior at large age.
|
|
270
|
+
log_pi = jnp.where(pi_ev > 0.0, jnp.log(jnp.maximum(pi_ev, 1e-300)), -jnp.inf)
|
|
271
|
+
log_post = log_pi + log_s_g.T # (B_ev, G)
|
|
272
|
+
post_w = jax.nn.softmax(log_post, axis=-1)
|
|
273
|
+
p_aged = jnp.einsum("bg,gbhv->bhv", post_w, p_ag_g)
|
|
274
|
+
p_aged = jnp.maximum(p_aged, 1e-12)
|
|
275
|
+
p_aged = p_aged / jnp.sum(p_aged, axis=-1, keepdims=True)
|
|
276
|
+
|
|
277
|
+
if return_both_fresh_and_aged:
|
|
278
|
+
return p_fresh, p_aged
|
|
279
|
+
return p_aged if age > 0.0 else p_fresh
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def solve_coxian_hyper_talbot(
|
|
283
|
+
lam_f: jax.Array,
|
|
284
|
+
stage_rates: jax.Array,
|
|
285
|
+
alpha_f: jax.Array,
|
|
286
|
+
b_slow: jax.Array,
|
|
287
|
+
routing_mat: jax.Array,
|
|
288
|
+
horizons: np.ndarray | jax.Array,
|
|
289
|
+
active_mask: jax.Array,
|
|
290
|
+
*,
|
|
291
|
+
eval_nodes: jax.Array | None = None,
|
|
292
|
+
age: float = 0.0,
|
|
293
|
+
n_talbot: int = 16,
|
|
294
|
+
return_both_fresh_and_aged: bool = False,
|
|
295
|
+
):
|
|
296
|
+
"""Exact Laplace-Schur-Talbot solver for arbitrary non-uniform Coxian + fast exp clocks.
|
|
297
|
+
|
|
298
|
+
Enables zero-shot plugging of Universal Hyper-Pos-Sens (K_r non-uniform Coxian stages +
|
|
299
|
+
1 fast exponential branch) into arbitrary large-V graphs without dense D_st x D_st matrices.
|
|
300
|
+
"""
|
|
301
|
+
v_cnt = int(routing_mat.shape[0])
|
|
302
|
+
k_red = int(stage_rates.shape[-1])
|
|
303
|
+
ev_idx = jnp.arange(v_cnt, dtype=jnp.int32) if eval_nodes is None else eval_nodes
|
|
304
|
+
s_grid, w_grid = weideman_talbot_contour(horizons, n_nodes=n_talbot)
|
|
305
|
+
|
|
306
|
+
pf_fresh = alpha_f * active_mask
|
|
307
|
+
ps_fresh = (1.0 - alpha_f)[:, None] * b_slow * active_mask[:, None]
|
|
308
|
+
need_aged = return_both_fresh_and_aged or (age > 0.0)
|
|
309
|
+
|
|
310
|
+
if need_aged:
|
|
311
|
+
# Exact per-node K_r x K_r matrix exponential (K_r=8 -> tiny 8x8 per node, <0.2ms!)
|
|
312
|
+
def aged_one_node(lf_i, r_i, af_i, bs_i, act_i):
|
|
313
|
+
# Shift by min_rate to prevent underflow for arbitrary age
|
|
314
|
+
min_r = jnp.minimum(lf_i, jnp.min(r_i))
|
|
315
|
+
t_blk = -jnp.diag(r_i - min_r) + jnp.diag(r_i[:-1], k=-1)
|
|
316
|
+
slow_surv = (1.0 - af_i) * (jl.expm(age * t_blk) @ bs_i)
|
|
317
|
+
fast_surv = af_i * jnp.exp(-jnp.clip((lf_i - min_r) * age, 0.0, 700.0))
|
|
318
|
+
tot = jnp.maximum(fast_surv + jnp.sum(slow_surv), 1e-300)
|
|
319
|
+
pf_a = jnp.where(act_i > 0.5, fast_surv / tot, 0.0)
|
|
320
|
+
ps_a = jnp.where(act_i > 0.5, slow_surv / tot, jnp.zeros(k_red, dtype=r_i.dtype))
|
|
321
|
+
return pf_a, ps_a
|
|
322
|
+
|
|
323
|
+
pf_aged, ps_aged = jax.vmap(aged_one_node)(
|
|
324
|
+
lam_f, stage_rates, alpha_f, b_slow, active_mask
|
|
325
|
+
)
|
|
326
|
+
else:
|
|
327
|
+
pf_aged, ps_aged = pf_fresh, ps_fresh
|
|
328
|
+
|
|
329
|
+
eye_v = jnp.eye(v_cnt, dtype=jnp.complex128)
|
|
330
|
+
r_c = routing_mat.astype(jnp.complex128)
|
|
331
|
+
|
|
332
|
+
def cox_laplace(s_c, p_f, p_s):
|
|
333
|
+
qf = lam_f / (s_c + lam_f)
|
|
334
|
+
# Suffix cumulative product of r_m / (s + r_m) from m = j .. K_r - 1
|
|
335
|
+
step_q = stage_rates / (s_c + stage_rates) # (V, K_r)
|
|
336
|
+
# Reverse cumprod along axis=-1
|
|
337
|
+
suf_q = jnp.cumprod(step_q[:, ::-1], axis=-1)[:, ::-1]
|
|
338
|
+
phi = (p_f * qf + jnp.sum(p_s * suf_q, axis=-1)) * active_mask
|
|
339
|
+
s_v = (1.0 - phi) / s_c
|
|
340
|
+
return phi, s_v
|
|
341
|
+
|
|
342
|
+
def one_s(s_c):
|
|
343
|
+
phi, s_v = cox_laplace(s_c, pf_fresh, ps_fresh)
|
|
344
|
+
m_mat = eye_v - r_c * phi[None, :]
|
|
345
|
+
z_inv = jnp.linalg.solve(m_mat, eye_v)
|
|
346
|
+
p_fr = s_v[:, None] * z_inv
|
|
347
|
+
if not need_aged:
|
|
348
|
+
return p_fr, p_fr
|
|
349
|
+
phi_a, s_va = cox_laplace(s_c, pf_aged, ps_aged)
|
|
350
|
+
zr = z_inv @ r_c
|
|
351
|
+
p_ag = jnp.diag(s_va) + (s_v[:, None] * zr) * phi_a[None, :]
|
|
352
|
+
return p_fr, p_ag
|
|
353
|
+
|
|
354
|
+
def one_h(s_vec, w_vec):
|
|
355
|
+
p_frs, p_ags = jax.vmap(one_s)(s_vec)
|
|
356
|
+
fr_h = jnp.real(jnp.einsum("m,mvu->uv", w_vec, p_frs))[ev_idx]
|
|
357
|
+
fr_h = jnp.maximum(fr_h, 1e-12)
|
|
358
|
+
fr_h = fr_h / jnp.sum(fr_h, axis=-1, keepdims=True)
|
|
359
|
+
if not need_aged:
|
|
360
|
+
return fr_h, fr_h
|
|
361
|
+
ag_h = jnp.real(jnp.einsum("m,mvu->uv", w_vec, p_ags))[ev_idx]
|
|
362
|
+
ag_h = jnp.maximum(ag_h, 1e-12)
|
|
363
|
+
ag_h = ag_h / jnp.sum(ag_h, axis=-1, keepdims=True)
|
|
364
|
+
return fr_h, ag_h
|
|
365
|
+
|
|
366
|
+
fr_all, ag_all = jax.vmap(one_h)(s_grid, w_grid)
|
|
367
|
+
fr_out = jnp.swapaxes(fr_all, 0, 1)
|
|
368
|
+
ag_out = jnp.swapaxes(ag_all, 0, 1)
|
|
369
|
+
if return_both_fresh_and_aged:
|
|
370
|
+
return fr_out, ag_out
|
|
371
|
+
return ag_out if age > 0.0 else fr_out
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def laplace_schur_implicit_solve(
|
|
375
|
+
rhs_y: jax.Array,
|
|
376
|
+
gamma_h: float,
|
|
377
|
+
lam_f: jax.Array,
|
|
378
|
+
lam_s: jax.Array,
|
|
379
|
+
alpha_f: jax.Array,
|
|
380
|
+
b_slow: jax.Array,
|
|
381
|
+
routing_mat: jax.Array,
|
|
382
|
+
) -> jax.Array:
|
|
383
|
+
"""Exact block-bidiagonal Laplace-Schur solve of (I - gamma_h * A) X = rhs_y.
|
|
384
|
+
|
|
385
|
+
Reduces the D_st = V*(K+1) linear system exactly to a V x V M-matrix system
|
|
386
|
+
(I_V - diag(phi_v(1 / gamma_h)) * R) f = f_0, sharing one LU across batch dimension B.
|
|
387
|
+
"""
|
|
388
|
+
v_cnt = int(routing_mat.shape[0])
|
|
389
|
+
k_slow = int(b_slow.shape[-1])
|
|
390
|
+
|
|
391
|
+
def _inv_local(y_arr):
|
|
392
|
+
zf = y_arr[:, :, 0] / (1.0 + gamma_h * lam_f[None, :])
|
|
393
|
+
inv_d = 1.0 / (1.0 + gamma_h * lam_s[None, :])
|
|
394
|
+
q_step = (gamma_h * lam_s[None, :]) * inv_d
|
|
395
|
+
zs = [y_arr[:, :, 1] * inv_d]
|
|
396
|
+
for j in range(1, k_slow):
|
|
397
|
+
zs.append(y_arr[:, :, 1 + j] * inv_d + q_step * zs[-1])
|
|
398
|
+
z_slow = jnp.stack(zs, axis=-1)
|
|
399
|
+
z_all = jnp.concatenate([zf[:, :, None], z_slow], axis=-1)
|
|
400
|
+
exit_flux = lam_f[None, :] * zf + lam_s[None, :] * zs[-1]
|
|
401
|
+
return z_all, exit_flux
|
|
402
|
+
|
|
403
|
+
qf = (gamma_h * lam_f) / (1.0 + gamma_h * lam_f)
|
|
404
|
+
qs = (gamma_h * lam_s) / (1.0 + gamma_h * lam_s)
|
|
405
|
+
rem_pows = jnp.stack([qs ** (k_slow - j) for j in range(k_slow)], axis=-1)
|
|
406
|
+
phi = alpha_f * qf + (1.0 - alpha_f) * jnp.sum(b_slow * rem_pows, axis=-1)
|
|
407
|
+
|
|
408
|
+
z0, f0 = _inv_local(rhs_y)
|
|
409
|
+
m_mat = jnp.eye(v_cnt, dtype=rhs_y.dtype) - phi[:, None] * routing_mat
|
|
410
|
+
f_sol = jnp.linalg.solve(m_mat, f0.T).T
|
|
411
|
+
inflow = gamma_h * (f_sol @ routing_mat.T)
|
|
412
|
+
b_in = jnp.concatenate(
|
|
413
|
+
[
|
|
414
|
+
(inflow * alpha_f[None, :])[:, :, None],
|
|
415
|
+
(inflow * (1.0 - alpha_f)[None, :])[:, :, None] * b_slow[None, :, :],
|
|
416
|
+
],
|
|
417
|
+
axis=-1,
|
|
418
|
+
)
|
|
419
|
+
z_in, _ = _inv_local(b_in)
|
|
420
|
+
return z0 + z_in
|