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/race.py ADDED
@@ -0,0 +1,274 @@
1
+ """Exact reduction of independent common-rate mixed-Erlang competing races."""
2
+
3
+ import diffrax
4
+ import jax
5
+ import jax.numpy as jnp
6
+ from jax.scipy.special import gammaln, logsumexp
7
+ import numpy as np
8
+
9
+ from .network import network_layout
10
+ from .phase_type import mixed_erlang_components
11
+
12
+
13
+ def _log_convolve(a, b):
14
+ """Positive polynomial multiplication in log space without factorial overflow."""
15
+ n = jnp.arange(a.size + b.size - 1)[:, None]
16
+ j = jnp.arange(a.size)[None, :]
17
+ index = n - j
18
+ terms = a[None, :] + b[jnp.clip(index, 0, b.size - 1)]
19
+ return logsumexp(jnp.where((index >= 0) & (index < b.size), terms, -jnp.inf), axis=1)
20
+
21
+
22
+ def mixed_erlang_race(means, logits):
23
+ """Compile d competing mixed-Erlang clocks into an exact L = 1 + d*(K-1) chain.
24
+
25
+ Preserves the complete joint distribution of exit time and winning edge mark
26
+ together with all parameter derivatives.
27
+ """
28
+ means, logits = jnp.asarray(means), jnp.asarray(logits)
29
+ if (
30
+ means.ndim != 1
31
+ or means.size < 1
32
+ or logits.ndim != 2
33
+ or logits.shape[0] != means.size
34
+ or logits.shape[1] < 1
35
+ ):
36
+ raise ValueError("require means (d,), logits (d,K), d,K >= 1")
37
+ rates, _ = jax.vmap(mixed_erlang_components)(means, logits)
38
+ total_rate = jnp.sum(rates)
39
+ log_ratio = jnp.log(rates) - jnp.log(total_rate)
40
+ log_weights = jax.nn.log_softmax(logits, axis=1)
41
+ log_tail = jax.vmap(
42
+ lambda w: jax.lax.associative_scan(jnp.logaddexp, w, reverse=True)
43
+ )(log_weights)
44
+ counts = jnp.arange(logits.shape[1], dtype=logits.dtype)
45
+ log_factorial = gammaln(counts + 1.0)
46
+ log_survival = log_tail + log_ratio[:, None] * counts - log_factorial
47
+ log_density = log_weights + log_ratio[:, None] * (counts + 1) - log_factorial
48
+
49
+ causes = []
50
+ for e in range(means.size):
51
+ polynomial = log_density[e]
52
+ for other in range(means.size):
53
+ if other != e:
54
+ polynomial = _log_convolve(polynomial, log_survival[other])
55
+ causes.append(
56
+ polynomial + gammaln(jnp.arange(polynomial.size, dtype=logits.dtype) + 1.0)
57
+ )
58
+ log_joint = jnp.stack(causes)
59
+ log_joint = log_joint - logsumexp(log_joint)
60
+ log_count = logsumexp(log_joint, axis=0)
61
+ tail = jax.lax.associative_scan(jnp.logaddexp, log_count, reverse=True)
62
+ cause_probabilities = jnp.exp(log_joint - tail[None, :])
63
+ continuations = jnp.exp(tail[1:] - tail[:-1])
64
+ normalization = jnp.sum(cause_probabilities, axis=0) + jnp.pad(
65
+ continuations, (0, 1)
66
+ )
67
+ cause_probabilities = cause_probabilities / normalization[None, :]
68
+ continuations = continuations / normalization[:-1]
69
+ return total_rate, continuations, cause_probabilities
70
+
71
+
72
+ def hyper_race_state_size(n_edges: int, branches: int, stages: int) -> int:
73
+ """Exact state dimension M**d * (1 + d*(K-1)) of d competing M-branch Hyper-Erlang clocks."""
74
+ if min(n_edges, branches, stages) < 1:
75
+ raise ValueError("n_edges, branches, and stages must be positive integers")
76
+ return (branches**n_edges) * (1 + n_edges * (stages - 1))
77
+
78
+
79
+ def hyper_erlang_race(branch_logits_mix, branch_means, branch_stage_logits):
80
+ """Compile d competing M-branch Hyper-Erlang clocks (Proposition 2).
81
+
82
+ Eliminates the K**d Cartesian phase explosion for multi-rate (CV > 1, heavy-tailed,
83
+ or bimodal) Hyper-Erlang clocks: reduces (M*K)**d joint tensor states to
84
+ M**d * (1 + d*(K-1)) positive Coxian states while preserving exact cause-specific
85
+ exit sub-densities k_e(t) and all parameter derivatives.
86
+
87
+ Args:
88
+ branch_logits_mix: (d, M) mixture logits over M rate branches per edge.
89
+ branch_means: (d, M) positive branch mean durations per edge.
90
+ branch_stage_logits: (d, M, K) stage-count logits per edge and branch.
91
+
92
+ Returns:
93
+ entry: (L_hyper,) non-negative initial state probabilities summing to 1.
94
+ rates: (L_hyper,) positive stage exit rates.
95
+ continuations: (L_hyper - 1,) stage continuation probabilities (0 across blocks).
96
+ causes: (d, L_hyper) cause-specific exit probabilities per stage.
97
+ """
98
+ mix_l = jnp.asarray(branch_logits_mix)
99
+ means = jnp.asarray(branch_means)
100
+ stage_l = jnp.asarray(branch_stage_logits)
101
+ if (
102
+ mix_l.ndim != 2
103
+ or means.shape != mix_l.shape
104
+ or stage_l.ndim != 3
105
+ or stage_l.shape[:2] != mix_l.shape
106
+ ):
107
+ raise ValueError("require shapes (d, M), (d, M), and (d, M, K)")
108
+ d, m_branches, k_stages = stage_l.shape
109
+ log_alpha = jax.nn.log_softmax(mix_l, axis=1)
110
+ combos = jnp.asarray(np.indices((m_branches,) * d).reshape(d, -1).T, dtype=jnp.int32)
111
+ edge_idx = jnp.arange(d, dtype=jnp.int32)
112
+
113
+ def _compile_combo(m_vec):
114
+ w_c = jnp.exp(jnp.sum(log_alpha[edge_idx, m_vec]))
115
+ r_c, cont_c, cause_c = mixed_erlang_race(
116
+ means[edge_idx, m_vec], stage_l[edge_idx, m_vec]
117
+ )
118
+ return w_c, r_c, cont_c, cause_c
119
+
120
+ w_all, r_all, cont_all, cause_all = jax.vmap(_compile_combo)(combos)
121
+ n_combos = combos.shape[0]
122
+ l_sub = 1 + d * (k_stages - 1)
123
+
124
+ entry = jnp.zeros((n_combos, l_sub), dtype=stage_l.dtype).at[:, 0].set(w_all).ravel()
125
+ rates = jnp.repeat(r_all, l_sub)
126
+ cont_padded = jnp.pad(cont_all, ((0, 0), (0, 1))).ravel()[:-1]
127
+ causes = jnp.transpose(cause_all, (1, 0, 2)).reshape(d, n_combos * l_sub)
128
+ return entry, rates, cont_padded, causes
129
+
130
+
131
+ def compact_network_state_size(edges, n_nodes: int, stages: int) -> int:
132
+ """Exact marked-race compiled network dimension: V + (K - 1) * E."""
133
+ if not isinstance(stages, int) or isinstance(stages, bool) or stages < 1:
134
+ raise ValueError("stages must be a positive integer")
135
+ edges, _ = network_layout(edges, n_nodes)
136
+ return n_nodes + (stages - 1) * len(edges)
137
+
138
+
139
+ def solve_compact_renewal_network(
140
+ means,
141
+ logits,
142
+ edges,
143
+ initial,
144
+ ts,
145
+ *,
146
+ rtol: float = 1e-8,
147
+ atol: float = 1e-10,
148
+ adjoint=None,
149
+ ):
150
+ """Exact fresh-clock renewal network solver using marked-race compilation."""
151
+ means, logits = jnp.asarray(means), jnp.asarray(logits)
152
+ initial, ts = jnp.asarray(initial), jnp.asarray(ts)
153
+ if initial.ndim != 1 or initial.size < 1:
154
+ raise ValueError("initial must be a nonempty 1D array")
155
+ edges, outgoing = network_layout(edges, initial.size)
156
+ if (
157
+ not edges
158
+ or means.shape != (len(edges),)
159
+ or logits.ndim != 2
160
+ or logits.shape[0] != len(edges)
161
+ or logits.shape[1] < 1
162
+ ):
163
+ raise ValueError("require E edges, means (E,), and logits (E,K), E,K >= 1")
164
+ if ts.ndim != 1 or ts.size < 1:
165
+ raise ValueError("ts must be a nonempty 1D array")
166
+ k = logits.shape[1]
167
+ n_nodes = int(initial.size)
168
+ lengths = [1 + len(group) * (k - 1) for group in outgoing]
169
+ offsets = []
170
+ cur = 0
171
+ for ln in lengths:
172
+ offsets.append(cur)
173
+ cur += ln
174
+ total_dim = cur
175
+ max_len = max(lengths)
176
+
177
+ # Batch local clock / marked-race compilation by out-degree to avoid O(V) XLA unrolling
178
+ by_deg: dict[int, list[int]] = {}
179
+ for node_i, grp in enumerate(outgoing):
180
+ by_deg.setdefault(len(grp), []).append(node_i)
181
+
182
+ node_rate: dict[int, jnp.ndarray] = {}
183
+ node_cont: dict[int, jnp.ndarray] = {}
184
+ node_causes: dict[int, jnp.ndarray] = {}
185
+ node_entry: dict[int, jnp.ndarray] = {}
186
+
187
+ for deg, nodes_d in by_deg.items():
188
+ if deg == 0:
189
+ z_r = jnp.array(0.0, dtype=logits.dtype)
190
+ z_c = jnp.zeros(0, dtype=logits.dtype)
191
+ z_p = jnp.zeros((0, 1), dtype=logits.dtype)
192
+ o_e = jnp.ones(1, dtype=logits.dtype)
193
+ for ni in nodes_d:
194
+ node_rate[ni], node_cont[ni], node_causes[ni], node_entry[ni] = z_r, z_c, z_p, o_e
195
+ elif deg == 1:
196
+ e_ids = jnp.array([outgoing[ni][0] for ni in nodes_d])
197
+ rates_1, entries_1 = jax.vmap(mixed_erlang_components)(means[e_ids], logits[e_ids])
198
+ c_1 = jnp.ones(k - 1, dtype=logits.dtype)
199
+ p_1 = jnp.zeros((1, k), dtype=logits.dtype).at[0, -1].set(1.0)
200
+ for idx_loc, ni in enumerate(nodes_d):
201
+ node_rate[ni] = rates_1[idx_loc]
202
+ node_cont[ni] = c_1
203
+ node_causes[ni] = p_1
204
+ node_entry[ni] = entries_1[idx_loc]
205
+ else:
206
+ grp_mat = jnp.array([outgoing[ni] for ni in nodes_d])
207
+ rates_d, conts_d, causes_d = jax.vmap(
208
+ lambda idx: mixed_erlang_race(means[idx], logits[idx])
209
+ )(grp_mat)
210
+ ln_d = 1 + deg * (k - 1)
211
+ e_d = jnp.zeros(ln_d, dtype=logits.dtype).at[0].set(1.0)
212
+ for idx_loc, ni in enumerate(nodes_d):
213
+ node_rate[ni] = rates_d[idx_loc]
214
+ node_cont[ni] = conts_d[idx_loc]
215
+ node_causes[ni] = causes_d[idx_loc]
216
+ node_entry[ni] = e_d
217
+
218
+ rate_vec = jnp.concatenate(
219
+ [jnp.repeat(node_rate[i], lengths[i]) for i in range(n_nodes)]
220
+ )
221
+ cont_parts = []
222
+ for i in range(n_nodes):
223
+ cont_parts.append(node_cont[i])
224
+ if i < n_nodes - 1:
225
+ cont_parts.append(jnp.zeros(1, dtype=logits.dtype))
226
+ cont_vec = jnp.concatenate(cont_parts) if cont_parts else jnp.zeros(0, dtype=logits.dtype)
227
+ entry_vec = jnp.concatenate([node_entry[i] for i in range(n_nodes)])
228
+
229
+ stage_owner = jnp.array(
230
+ [i for i in range(n_nodes) for _ in range(lengths[i])], dtype=jnp.int32
231
+ )
232
+ edge_stage_rows = []
233
+ cause_rows = []
234
+ for u_i, grp in enumerate(outgoing):
235
+ ln_u = lengths[u_i]
236
+ off_u = offsets[u_i]
237
+ idx_row = jnp.pad(
238
+ jnp.arange(off_u, off_u + ln_u, dtype=jnp.int32), (0, max_len - ln_u)
239
+ )
240
+ causes_u = jnp.pad(node_causes[u_i], ((0, 0), (0, max_len - ln_u)))
241
+ for j_loc, e_id in enumerate(grp):
242
+ edge_stage_rows.append((e_id, idx_row, causes_u[j_loc]))
243
+ edge_stage_rows.sort(key=lambda item: item[0])
244
+ edge_stage_idx = jnp.stack([r[1] for r in edge_stage_rows])
245
+ cause_mat = jnp.stack([r[2] for r in edge_stage_rows])
246
+ dst_nodes = jnp.array([dst for _, dst in edges], dtype=jnp.int32)
247
+
248
+ y0 = initial[stage_owner] * entry_vec
249
+ assert y0.size == total_dim
250
+
251
+ def field(t, y, args):
252
+ r_v, c_v, e_v, p_m = args
253
+ flux = r_v * y
254
+ subdiag = jnp.pad(c_v * flux[:-1], (1, 0))
255
+ edge_fluxes = jnp.sum(p_m * flux[edge_stage_idx], axis=1)
256
+ arrivals = jnp.zeros(n_nodes, dtype=y.dtype).at[dst_nodes].add(edge_fluxes)
257
+ return subdiag - flux + arrivals[stage_owner] * e_v
258
+
259
+ return diffrax.diffeqsolve(
260
+ diffrax.ODETerm(field),
261
+ diffrax.Tsit5(),
262
+ t0=0.0,
263
+ t1=ts[-1],
264
+ dt0=None,
265
+ y0=y0,
266
+ args=(rate_vec, cont_vec, entry_vec, cause_mat),
267
+ saveat=diffrax.SaveAt(
268
+ ts=ts,
269
+ fn=lambda t, y, args: jnp.zeros(n_nodes, dtype=y.dtype).at[stage_owner].add(y),
270
+ ),
271
+ stepsize_controller=diffrax.PIDController(rtol=rtol, atol=atol),
272
+ adjoint=diffrax.RecursiveCheckpointAdjoint() if adjoint is None else adjoint,
273
+ max_steps=100_000,
274
+ )