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,199 @@
|
|
|
1
|
+
"""Incoming-edge conditioned & Hyper-Erlang semi-Markov renewal networks (EdgeMemoryHyperDRN).
|
|
2
|
+
|
|
3
|
+
Lifts node-reset renewal dynamics onto directed incoming-transition fibres (u -> v)
|
|
4
|
+
with two-scale Hyper-Erlang competing exit hazards (capturing CV > 1 bursty micro-arousals
|
|
5
|
+
alongside multi-stage refractory consolidation) while preserving:
|
|
6
|
+
1. Strict Metzler mass conservation (global probability simplex invariance for all t >= 0), and
|
|
7
|
+
2. Exact analytical survivor-age conditioning P(X(a+t) | T_0 > a) for zero-shot cohort transfer.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import jax
|
|
11
|
+
import jax.numpy as jnp
|
|
12
|
+
import jax.scipy.linalg as jl
|
|
13
|
+
import numpy as np
|
|
14
|
+
|
|
15
|
+
from .race import mixed_erlang_race
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def init_edge_memory_params(
|
|
19
|
+
n_nodes: int,
|
|
20
|
+
n_edges: int,
|
|
21
|
+
*,
|
|
22
|
+
stages: int = 6,
|
|
23
|
+
rank: int = 3,
|
|
24
|
+
base_mean: float = 1.0,
|
|
25
|
+
emb_scale: float = 0.08,
|
|
26
|
+
seed: int = 0,
|
|
27
|
+
) -> np.ndarray:
|
|
28
|
+
"""Symmetry-breaking initializer for EdgeMemoryHyperDRN.
|
|
29
|
+
|
|
30
|
+
Avoids the exact bilinear saddle point at ``f_emb = 0, e_emb = 0`` where
|
|
31
|
+
``route_bias = f_emb @ e_emb`` produces identically zero gradients for all
|
|
32
|
+
incoming-edge embedding parameters.
|
|
33
|
+
"""
|
|
34
|
+
n_fibres = n_nodes + n_edges
|
|
35
|
+
rng = np.random.default_rng(seed)
|
|
36
|
+
base_log_means = np.full(n_edges, np.log(max(float(base_mean), 1e-6)), dtype=float)
|
|
37
|
+
base_logits = np.zeros(n_edges * stages, dtype=float)
|
|
38
|
+
fibre_mod = np.zeros(3 * n_fibres, dtype=float)
|
|
39
|
+
f_emb = rng.normal(0.0, emb_scale, size=n_fibres * rank)
|
|
40
|
+
e_emb = rng.normal(0.0, emb_scale, size=rank * n_edges)
|
|
41
|
+
return np.concatenate([base_log_means, base_logits, fibre_mod, f_emb, e_emb])
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def build_edge_memory_hyper_generator(
|
|
45
|
+
params,
|
|
46
|
+
edges: tuple[tuple[int, int], ...],
|
|
47
|
+
n_nodes: int,
|
|
48
|
+
*,
|
|
49
|
+
stages: int = 6,
|
|
50
|
+
rank: int = 3,
|
|
51
|
+
aged_horizon: float = 0.5,
|
|
52
|
+
):
|
|
53
|
+
"""Construct incoming-edge lifted two-scale Hyper-Erlang network generator.
|
|
54
|
+
|
|
55
|
+
State space consists of:
|
|
56
|
+
- V fresh-preparation root fibres (for initial cohort entry into node v at t=0), and
|
|
57
|
+
- E directed transition fibres e_in = (u -> v) (entered whenever transition u -> v fires!).
|
|
58
|
+
Wait: to keep compiled state count ultra-compact, each node v has:
|
|
59
|
+
* 1 fast exponential micro-exit branch (rate lambda_fast[f], routing softmax), and
|
|
60
|
+
* 1 compiled mixed-Erlang refractory race (K=stages per outgoing edge via Proposition 1),
|
|
61
|
+
mixed at arrival into fibre f by learned fast-vs-consolidated probability p_fast[f] = sigmoid(g_f),
|
|
62
|
+
with outgoing edge means/logits modulated by incoming-edge context embedding!
|
|
63
|
+
|
|
64
|
+
Returns:
|
|
65
|
+
gen: (M_tot, M_tot) strictly Metzler column-conserving generator.
|
|
66
|
+
fresh_mat: (M_tot, V) non-negative fresh cohort initializations.
|
|
67
|
+
aged_mat: (M_tot, V) exact analytical >= aged_horizon survivor initializations.
|
|
68
|
+
read_mat: (V, M_tot) node-occupancy readout matrix.
|
|
69
|
+
"""
|
|
70
|
+
n_edges = len(edges)
|
|
71
|
+
expected_size = edge_memory_param_size(n_nodes, n_edges, stages=stages, rank=rank)
|
|
72
|
+
params = jnp.asarray(params)
|
|
73
|
+
if params.size != expected_size:
|
|
74
|
+
raise ValueError(
|
|
75
|
+
f"Expected {expected_size} parameters for n_nodes={n_nodes}, "
|
|
76
|
+
f"n_edges={n_edges}, stages={stages}, rank={rank}; got {params.size}"
|
|
77
|
+
)
|
|
78
|
+
outgoing = [tuple(e for e, (u, _) in enumerate(edges) if u == i) for i in range(n_nodes)]
|
|
79
|
+
# Total fibres: 0..V-1 are initial root preparations at node v;
|
|
80
|
+
# V..V+E-1 are post-transition fibres after traversing edge e_in = (u -> v).
|
|
81
|
+
fibre_nodes = list(range(n_nodes)) + [dst for _, dst in edges]
|
|
82
|
+
n_fibres = len(fibre_nodes)
|
|
83
|
+
|
|
84
|
+
# Unpack parameter vector cleanly
|
|
85
|
+
# Base per-edge means & stage logits: n_edges * (1 + stages)
|
|
86
|
+
idx = 0
|
|
87
|
+
base_log_means = params[idx : idx + n_edges]
|
|
88
|
+
idx += n_edges
|
|
89
|
+
base_logits = params[idx : idx + n_edges * stages].reshape(n_edges, stages)
|
|
90
|
+
idx += n_edges * stages
|
|
91
|
+
|
|
92
|
+
# Incoming-fibre modulation of clock speed & fast-burst weight:
|
|
93
|
+
# per fibre f in 0..n_fibres-1: (speed_shift_f, fast_mix_logit_f, fast_log_rate_f) -> 3 * n_fibres
|
|
94
|
+
fibre_mod = params[idx : idx + 3 * n_fibres].reshape(n_fibres, 3)
|
|
95
|
+
idx += 3 * n_fibres
|
|
96
|
+
|
|
97
|
+
# Incoming-fibre routing bias on outgoing edges: (n_fibres, rank) @ (rank, n_edges)
|
|
98
|
+
f_emb = params[idx : idx + n_fibres * rank].reshape(n_fibres, rank)
|
|
99
|
+
idx += n_fibres * rank
|
|
100
|
+
e_emb = params[idx : idx + rank * n_edges].reshape(rank, n_edges)
|
|
101
|
+
idx += rank * n_edges
|
|
102
|
+
route_bias = f_emb @ e_emb # (n_fibres, n_edges)
|
|
103
|
+
|
|
104
|
+
# Group fibres by node out-degree so mixed_erlang_race & expm are batched via jax.vmap!
|
|
105
|
+
by_deg: dict[int, list[int]] = {}
|
|
106
|
+
for f_id, v_node in enumerate(fibre_nodes):
|
|
107
|
+
by_deg.setdefault(len(outgoing[v_node]), []).append(f_id)
|
|
108
|
+
|
|
109
|
+
fibre_blk: dict[int, jnp.ndarray] = {}
|
|
110
|
+
fibre_ent: dict[int, jnp.ndarray] = {}
|
|
111
|
+
fibre_surv: dict[int, jnp.ndarray] = {}
|
|
112
|
+
fibre_fluxes: dict[int, tuple[tuple[int, jnp.ndarray], ...]] = {}
|
|
113
|
+
|
|
114
|
+
for d_v, f_ids in by_deg.items():
|
|
115
|
+
if d_v == 0:
|
|
116
|
+
for fi in f_ids:
|
|
117
|
+
fibre_blk[fi] = jnp.zeros((1, 1), dtype=params.dtype)
|
|
118
|
+
fibre_ent[fi] = jnp.ones((1,), dtype=params.dtype)
|
|
119
|
+
fibre_surv[fi] = jnp.ones((1,), dtype=params.dtype)
|
|
120
|
+
fibre_fluxes[fi] = ()
|
|
121
|
+
continue
|
|
122
|
+
f_arr = jnp.array(f_ids, dtype=jnp.int32)
|
|
123
|
+
grp_mat = jnp.array([outgoing[fibre_nodes[fi]] for fi in f_ids], dtype=jnp.int32)
|
|
124
|
+
|
|
125
|
+
def _compile_fibre(fi, grp_idx):
|
|
126
|
+
sp_sc = jnp.exp(0.8 * jnp.tanh(fibre_mod[fi, 0]))
|
|
127
|
+
pf = jax.nn.sigmoid(fibre_mod[fi, 1] - 1.0)
|
|
128
|
+
rf = jnp.exp(0.5 + 1.8 * jnp.tanh(fibre_mod[fi, 2]))
|
|
129
|
+
b_g = 0.6 * jnp.tanh(route_bias[fi, grp_idx])
|
|
130
|
+
m_f = jnp.exp(base_log_means[grp_idx] - b_g) / sp_sc
|
|
131
|
+
l_f = base_logits[grp_idx]
|
|
132
|
+
rs, cs, causes_s = mixed_erlang_race(m_f, l_f)
|
|
133
|
+
dim_s = causes_s.shape[1]
|
|
134
|
+
dim_tot = 1 + dim_s
|
|
135
|
+
blk_s = -rs * jnp.eye(dim_s) + jnp.diag(rs * cs, k=1).T
|
|
136
|
+
blk_tot = jl.block_diag(jnp.array([[-rf]]), blk_s)
|
|
137
|
+
ent_tot = jnp.zeros(dim_tot, dtype=params.dtype).at[0].set(pf).at[1].set(1.0 - pf)
|
|
138
|
+
# Shift by min exit rate to prevent expm underflow at arbitrarily large aged_horizon
|
|
139
|
+
min_r = jnp.minimum(rf, rs)
|
|
140
|
+
blk_shifted = blk_tot + min_r * jnp.eye(dim_tot, dtype=params.dtype)
|
|
141
|
+
surv_tot = jl.expm(aged_horizon * blk_shifted) @ ent_tot
|
|
142
|
+
surv_tot = jnp.maximum(surv_tot, 0.0)
|
|
143
|
+
surv_tot = surv_tot / jnp.maximum(jnp.sum(surv_tot), 1e-300)
|
|
144
|
+
fast_p = jax.nn.softmax(route_bias[fi, grp_idx])
|
|
145
|
+
flx = jnp.concatenate([(rf * fast_p)[:, None], rs * causes_s], axis=1)
|
|
146
|
+
return blk_tot, ent_tot, surv_tot, flx
|
|
147
|
+
|
|
148
|
+
blks_d, ents_d, survs_d, flxs_d = jax.vmap(_compile_fibre)(f_arr, grp_mat)
|
|
149
|
+
for loc_i, fi in enumerate(f_ids):
|
|
150
|
+
fibre_blk[fi] = blks_d[loc_i]
|
|
151
|
+
fibre_ent[fi] = ents_d[loc_i]
|
|
152
|
+
fibre_surv[fi] = survs_d[loc_i]
|
|
153
|
+
grp = outgoing[fibre_nodes[fi]]
|
|
154
|
+
fibre_fluxes[fi] = tuple((grp[j], flxs_d[loc_i, j]) for j in range(d_v))
|
|
155
|
+
|
|
156
|
+
blocks = []
|
|
157
|
+
offsets = []
|
|
158
|
+
exit_cols_by_edge = []
|
|
159
|
+
fresh_fibre_entries = []
|
|
160
|
+
aged_fibre_entries = []
|
|
161
|
+
cur = 0
|
|
162
|
+
for f_id in range(n_fibres):
|
|
163
|
+
blk_f = fibre_blk[f_id]
|
|
164
|
+
dim_f = blk_f.shape[0]
|
|
165
|
+
offsets.append((cur, cur + dim_f))
|
|
166
|
+
blocks.append(blk_f)
|
|
167
|
+
fresh_fibre_entries.append(fibre_ent[f_id])
|
|
168
|
+
aged_fibre_entries.append(fibre_surv[f_id])
|
|
169
|
+
for e_out, flux_row in fibre_fluxes[f_id]:
|
|
170
|
+
exit_cols_by_edge.append((cur, cur + dim_f, e_out, flux_row))
|
|
171
|
+
cur += dim_f
|
|
172
|
+
|
|
173
|
+
total_states = cur
|
|
174
|
+
gen = jl.block_diag(*blocks)
|
|
175
|
+
# Route exit via edge e_out into post-transition fibre (n_nodes + e_out)!
|
|
176
|
+
for c0, c1, e_out, flux_row in exit_cols_by_edge:
|
|
177
|
+
dst_fibre = n_nodes + e_out
|
|
178
|
+
d0, d1 = offsets[dst_fibre]
|
|
179
|
+
gen = gen.at[d0:d1, c0:c1].add(fresh_fibre_entries[dst_fibre][:, None] * flux_row[None, :])
|
|
180
|
+
|
|
181
|
+
# Initial preparations at t=0 enter root fibres 0..V-1 (or stationary incoming mixture)
|
|
182
|
+
fresh_mat = jnp.zeros((total_states, n_nodes), dtype=params.dtype)
|
|
183
|
+
aged_mat = jnp.zeros((total_states, n_nodes), dtype=params.dtype)
|
|
184
|
+
read_mat = jnp.zeros((n_nodes, total_states), dtype=params.dtype)
|
|
185
|
+
|
|
186
|
+
for f_id, v_node in enumerate(fibre_nodes):
|
|
187
|
+
s0, s1 = offsets[f_id]
|
|
188
|
+
read_mat = read_mat.at[v_node, s0:s1].set(1.0)
|
|
189
|
+
if f_id < n_nodes:
|
|
190
|
+
fresh_mat = fresh_mat.at[s0:s1, v_node].set(fresh_fibre_entries[f_id])
|
|
191
|
+
aged_mat = aged_mat.at[s0:s1, v_node].set(aged_fibre_entries[f_id])
|
|
192
|
+
|
|
193
|
+
return gen, fresh_mat, aged_mat, read_mat
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def edge_memory_param_size(n_nodes: int, n_edges: int, *, stages: int = 6, rank: int = 3) -> int:
|
|
197
|
+
"""Return total parameter count of EdgeMemoryHyperDRN."""
|
|
198
|
+
n_fibres = n_nodes + n_edges
|
|
199
|
+
return n_edges * (1 + stages) + 3 * n_fibres + rank * (n_fibres + n_edges)
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"""Matrix-free O(V + K*E) sparse block-operator solver for large renewal networks.
|
|
2
|
+
|
|
3
|
+
Compiles arbitrary renewal graphs using Proposition 1 (mixed-Erlang marked-race
|
|
4
|
+
compilation) into flat 1D phase arrays and integrates dx/dt = A x via Diffrax
|
|
5
|
+
without ever materializing a dense N x N generator matrix. Supports exact
|
|
6
|
+
reverse-mode automatic differentiation up to V = 512..1024 nodes (>15,000 states).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import diffrax
|
|
12
|
+
import jax
|
|
13
|
+
import jax.numpy as jnp
|
|
14
|
+
import numpy as np
|
|
15
|
+
|
|
16
|
+
from .race import mixed_erlang_race
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def compile_sparse_regular_network(
|
|
20
|
+
means: jax.Array,
|
|
21
|
+
logits: jax.Array,
|
|
22
|
+
dst_indices: np.ndarray,
|
|
23
|
+
num_nodes: int,
|
|
24
|
+
):
|
|
25
|
+
"""Vectorized matrix-free compiler for d-regular renewal graphs in O(V * d * K).
|
|
26
|
+
|
|
27
|
+
Parameters
|
|
28
|
+
----------
|
|
29
|
+
means : array of shape (V, d)
|
|
30
|
+
Mean waiting times of the d competing outgoing clocks at each node.
|
|
31
|
+
logits : array of shape (V, d, K)
|
|
32
|
+
Stage-count logits for each competing outgoing clock.
|
|
33
|
+
dst_indices : int ndarray of shape (V, d)
|
|
34
|
+
Destination node index for each outgoing edge from node v.
|
|
35
|
+
num_nodes : int
|
|
36
|
+
Number of graph nodes V.
|
|
37
|
+
|
|
38
|
+
Returns
|
|
39
|
+
-------
|
|
40
|
+
tuple of compact 1D/2D JAX arrays describing the matrix-free generator A:
|
|
41
|
+
(rates, cont_rates, exit_rates, dst_entry_idx, entry_idx, block_len)
|
|
42
|
+
where total state size is L_tot = V * (1 + d * (K - 1)).
|
|
43
|
+
"""
|
|
44
|
+
v_cnt = int(num_nodes)
|
|
45
|
+
deg = int(means.shape[1])
|
|
46
|
+
k_st = int(logits.shape[2])
|
|
47
|
+
block_len = 1 + deg * (k_st - 1)
|
|
48
|
+
|
|
49
|
+
# Vectorized Proposition 1 marked-race compilation across all V nodes at once!
|
|
50
|
+
rates_v, cont_v, causes_v = jax.vmap(mixed_erlang_race)(means, logits)
|
|
51
|
+
# rates_v: (V,), cont_v: (V, L-1), causes_v: (V, d, L)
|
|
52
|
+
# Reshape to flat 1D state arrays of length V * L:
|
|
53
|
+
rates_flat = jnp.repeat(rates_v[:, None], block_len, axis=1).reshape(-1)
|
|
54
|
+
# Continuation from stage j to j+1 inside each node block (0 at last stage of each block)
|
|
55
|
+
cont_padded = jnp.concatenate(
|
|
56
|
+
[cont_v, jnp.zeros((v_cnt, 1), dtype=cont_v.dtype)], axis=1
|
|
57
|
+
)
|
|
58
|
+
cont_rates_flat = (rates_v[:, None] * cont_padded).reshape(-1)
|
|
59
|
+
|
|
60
|
+
# Exit rate from each phase (v, j) to each of the d outgoing neighbors: shape (V * L, d)
|
|
61
|
+
# causes_v is (V, d, L) -> transpose to (V, L, d)
|
|
62
|
+
exit_rates = (rates_v[:, None, None] * jnp.swapaxes(causes_v, 1, 2)).reshape(
|
|
63
|
+
v_cnt * block_len, deg
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
# Static integer index arrays (computed on host once)
|
|
67
|
+
entry_idx = np.arange(v_cnt, dtype=np.int32) * block_len
|
|
68
|
+
dst_entry_node = entry_idx[np.asarray(dst_indices, dtype=np.int32)] # (V, d)
|
|
69
|
+
dst_entry_idx = np.repeat(dst_entry_node[:, None, :], block_len, axis=1).reshape(
|
|
70
|
+
v_cnt * block_len, deg
|
|
71
|
+
)
|
|
72
|
+
return (
|
|
73
|
+
rates_flat,
|
|
74
|
+
cont_rates_flat,
|
|
75
|
+
exit_rates,
|
|
76
|
+
jnp.asarray(dst_entry_idx),
|
|
77
|
+
jnp.asarray(entry_idx),
|
|
78
|
+
block_len,
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def apply_sparse_generator(
|
|
83
|
+
x: jax.Array,
|
|
84
|
+
rates_flat: jax.Array,
|
|
85
|
+
cont_rates_flat: jax.Array,
|
|
86
|
+
exit_rates: jax.Array,
|
|
87
|
+
dst_entry_idx: jax.Array,
|
|
88
|
+
) -> jax.Array:
|
|
89
|
+
"""Apply generator A x in O(L_tot * d) memory and FLOPs with zero dense matrices."""
|
|
90
|
+
# 1. Diagonal decay: -Lambda_v * x_{v, j}
|
|
91
|
+
dx = -rates_flat * x
|
|
92
|
+
# 2. Sub-diagonal sequential continuation: phase j -> j + 1 (last phase has cont_rate == 0)
|
|
93
|
+
dx = dx.at[1:].add(cont_rates_flat[:-1] * x[:-1])
|
|
94
|
+
# 3. Routed exits from every phase (v, j) into destination node entry phase 0
|
|
95
|
+
fluxes = exit_rates * x[:, None] # (L_tot, d)
|
|
96
|
+
dx = dx.at[dst_entry_idx.reshape(-1)].add(fluxes.reshape(-1))
|
|
97
|
+
return dx
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def solve_sparse_renewal_network(
|
|
101
|
+
means: jax.Array,
|
|
102
|
+
logits: jax.Array,
|
|
103
|
+
dst_indices: np.ndarray,
|
|
104
|
+
init_nodes: jax.Array,
|
|
105
|
+
ts: jax.Array,
|
|
106
|
+
*,
|
|
107
|
+
dt0: float = 0.05,
|
|
108
|
+
rtol: float = 1e-6,
|
|
109
|
+
atol: float = 1e-8,
|
|
110
|
+
max_steps: int = 4096,
|
|
111
|
+
use_checkpoint_adjoint: bool = True,
|
|
112
|
+
) -> jax.Array:
|
|
113
|
+
"""Solve large d-regular renewal network P(t) = C x(t) matrix-free via Diffrax.
|
|
114
|
+
|
|
115
|
+
Parameters
|
|
116
|
+
----------
|
|
117
|
+
means : (V, d)
|
|
118
|
+
logits : (V, d, K)
|
|
119
|
+
dst_indices : (V, d) int
|
|
120
|
+
init_nodes : (V,) initial probability distribution over nodes (fresh entry)
|
|
121
|
+
ts : (T,) evaluation timestamps
|
|
122
|
+
|
|
123
|
+
Returns
|
|
124
|
+
-------
|
|
125
|
+
probs : (T, V) node occupation probabilities across timestamps `ts`.
|
|
126
|
+
"""
|
|
127
|
+
v_cnt = int(init_nodes.shape[0])
|
|
128
|
+
rates_flat, cont_rates_flat, exit_rates, dst_entry_idx, entry_idx, block_len = (
|
|
129
|
+
compile_sparse_regular_network(means, logits, dst_indices, v_cnt)
|
|
130
|
+
)
|
|
131
|
+
l_tot = v_cnt * block_len
|
|
132
|
+
x0 = jnp.zeros(l_tot, dtype=means.dtype).at[entry_idx].set(init_nodes)
|
|
133
|
+
|
|
134
|
+
def rhs(_t, x, args):
|
|
135
|
+
r_f, c_f, e_r = args
|
|
136
|
+
return apply_sparse_generator(x, r_f, c_f, e_r, dst_entry_idx)
|
|
137
|
+
|
|
138
|
+
term = diffrax.ODETerm(rhs)
|
|
139
|
+
solver = diffrax.Tsit5()
|
|
140
|
+
stepsize = diffrax.PIDController(rtol=rtol, atol=atol)
|
|
141
|
+
saveat = diffrax.SaveAt(ts=jnp.asarray(ts, dtype=means.dtype))
|
|
142
|
+
adjoint = (
|
|
143
|
+
diffrax.RecursiveCheckpointAdjoint()
|
|
144
|
+
if use_checkpoint_adjoint
|
|
145
|
+
else diffrax.DirectAdjoint()
|
|
146
|
+
)
|
|
147
|
+
sol = diffrax.diffeqsolve(
|
|
148
|
+
term,
|
|
149
|
+
solver,
|
|
150
|
+
t0=0.0,
|
|
151
|
+
t1=ts[-1],
|
|
152
|
+
dt0=dt0,
|
|
153
|
+
y0=x0,
|
|
154
|
+
args=(rates_flat, cont_rates_flat, exit_rates),
|
|
155
|
+
saveat=saveat,
|
|
156
|
+
stepsize_controller=stepsize,
|
|
157
|
+
adjoint=adjoint,
|
|
158
|
+
max_steps=max_steps,
|
|
159
|
+
)
|
|
160
|
+
# Sum phases inside each node block: (T, V, L) -> (T, V)
|
|
161
|
+
return sol.ys.reshape(-1, v_cnt, block_len).sum(axis=-1)
|
diff_renewal/traits.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""Observed, time-invariant individual traits in renewal networks."""
|
|
2
|
+
|
|
3
|
+
from functools import partial
|
|
4
|
+
|
|
5
|
+
import jax
|
|
6
|
+
import jax.numpy as jnp
|
|
7
|
+
|
|
8
|
+
from .phase_type import smooth_erlang_logits
|
|
9
|
+
from .race import solve_compact_renewal_network
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def trait_mean_shape(coefficients, traits):
|
|
13
|
+
"""Log-linear positive mean and shape functions of observed features."""
|
|
14
|
+
coefficients, traits = jnp.asarray(coefficients), jnp.asarray(traits)
|
|
15
|
+
if traits.ndim != 2 or coefficients.ndim != 3 or coefficients.shape[0] != 2:
|
|
16
|
+
raise ValueError("Require coefficients (2,E,D+1) and traits (G,D)")
|
|
17
|
+
if coefficients.shape[-1] != traits.shape[-1] + 1:
|
|
18
|
+
raise ValueError("Trait and coefficient dimensions disagree")
|
|
19
|
+
basis = jnp.concatenate((jnp.ones((traits.shape[0], 1)), traits), axis=-1)
|
|
20
|
+
values = jnp.exp(jnp.einsum("ged,xd->gxe", coefficients, basis))
|
|
21
|
+
return values[0], values[1]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def endpoint_coefficients(log_endpoints):
|
|
25
|
+
"""Map endpoint values at scalar traits -1, +1 to intercept and slope."""
|
|
26
|
+
x = jnp.asarray(log_endpoints)
|
|
27
|
+
if x.ndim != 3 or x.shape[0] != 2 or x.shape[-1] != 2:
|
|
28
|
+
raise ValueError("Require endpoint array (2,E,2)")
|
|
29
|
+
return jnp.stack(
|
|
30
|
+
((x[..., 0] + x[..., 1]) / 2.0, (x[..., 1] - x[..., 0]) / 2.0), axis=-1
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _center_shape(center, stages: int, width: float):
|
|
35
|
+
weights = jax.nn.softmax(
|
|
36
|
+
smooth_erlang_logits(center, stages=stages, width=width)
|
|
37
|
+
)
|
|
38
|
+
counts = jnp.arange(1, stages + 1)
|
|
39
|
+
mean = weights @ counts
|
|
40
|
+
variance = weights @ (counts - mean) ** 2
|
|
41
|
+
return mean**2 / (mean + variance)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@partial(jax.custom_jvp, nondiff_argnums=(1, 2))
|
|
45
|
+
def _shape_center(shape, stages: int, width: float):
|
|
46
|
+
def step(_, interval):
|
|
47
|
+
lo, hi = interval
|
|
48
|
+
mid = (lo + hi) / 2.0
|
|
49
|
+
below = _center_shape(mid, stages, width) < shape
|
|
50
|
+
return jnp.where(below, mid, lo), jnp.where(below, hi, mid)
|
|
51
|
+
|
|
52
|
+
lo_init = jnp.ones_like(shape)
|
|
53
|
+
# Allow center to reach stages + 1.5 so shape smoothly approaches stages (e.g., 10.5 for K=11)
|
|
54
|
+
hi_init = jnp.full_like(shape, float(stages) + 1.5)
|
|
55
|
+
lo, hi = jax.lax.fori_loop(0, 64, step, (lo_init, hi_init))
|
|
56
|
+
return (lo + hi) / 2.0
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@_shape_center.defjvp
|
|
60
|
+
def _shape_center_jvp(stages: int, width: float, primals, tangents):
|
|
61
|
+
(shape,), (dshape,) = primals, tangents
|
|
62
|
+
lo_val = jnp.ones_like(shape)
|
|
63
|
+
hi_val = jnp.full_like(shape, float(stages) + 1.5)
|
|
64
|
+
s_lo = _center_shape(lo_val, stages, width)
|
|
65
|
+
s_hi = _center_shape(hi_val, stages, width)
|
|
66
|
+
center = _shape_center(shape, stages, width)
|
|
67
|
+
derivative = jax.grad(_center_shape, argnums=0)(center, stages, width)
|
|
68
|
+
in_bounds = (shape > s_lo) & (shape < s_hi)
|
|
69
|
+
safe_deriv = jnp.where(in_bounds, jnp.maximum(derivative, 1e-12), 1.0)
|
|
70
|
+
return center, jnp.where(in_bounds, dshape / safe_deriv, 0.0)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def moment_matched_logits(shapes, *, stages: int = 16, width: float = 0.5):
|
|
74
|
+
"""Differentiable moment matching for a K-stage smooth mixed-Erlang clock family.
|
|
75
|
+
|
|
76
|
+
Defaults to the validated ``stages=16, width=0.5`` family from the manuscript
|
|
77
|
+
(accurate moment matching on ``[3, 12]``), while supporting arbitrary ``stages >= 2``.
|
|
78
|
+
"""
|
|
79
|
+
if not isinstance(stages, int) or isinstance(stages, bool) or stages < 2:
|
|
80
|
+
raise ValueError("stages must be an integer >= 2")
|
|
81
|
+
shapes = jnp.asarray(shapes)
|
|
82
|
+
centers = jax.vmap(lambda k: _shape_center(k, stages, width))(shapes.reshape(-1))
|
|
83
|
+
logits = jax.vmap(lambda c: smooth_erlang_logits(c, stages=stages, width=width))(centers)
|
|
84
|
+
return logits.reshape(shapes.shape + (stages,))
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def trait_network_probabilities(
|
|
88
|
+
coefficients, traits, edges, initials, times, *, adjoint=None
|
|
89
|
+
):
|
|
90
|
+
"""Conditional node probabilities (trait, preparation, time, species)."""
|
|
91
|
+
means, shapes = trait_mean_shape(coefficients, traits)
|
|
92
|
+
logits = moment_matched_logits(shapes)
|
|
93
|
+
|
|
94
|
+
def conditional(mean, logit):
|
|
95
|
+
return jax.vmap(
|
|
96
|
+
lambda initial: solve_compact_renewal_network(
|
|
97
|
+
mean, logit, edges, initial, times, adjoint=adjoint
|
|
98
|
+
).ys
|
|
99
|
+
)(jnp.asarray(initials))
|
|
100
|
+
|
|
101
|
+
return jax.vmap(conditional)(means, logits)
|