hsmmkit 0.5.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.
Files changed (192) hide show
  1. hsmmkit/__init__.py +13 -0
  2. hsmmkit/cli/__init__.py +1 -0
  3. hsmmkit/cli/app.py +513 -0
  4. hsmmkit/cli/stream.py +194 -0
  5. hsmmkit/config/__init__.py +1 -0
  6. hsmmkit/config/defaults.py +13 -0
  7. hsmmkit/config/gates.py +39 -0
  8. hsmmkit/config/migrate.py +53 -0
  9. hsmmkit/config/schema.py +996 -0
  10. hsmmkit/config/yaml_io.py +67 -0
  11. hsmmkit/data/__init__.py +1 -0
  12. hsmmkit/data/batch.py +311 -0
  13. hsmmkit/data/calendar.py +314 -0
  14. hsmmkit/data/clocks.py +165 -0
  15. hsmmkit/data/contracts.py +543 -0
  16. hsmmkit/data/labels.py +150 -0
  17. hsmmkit/data/prepare.py +706 -0
  18. hsmmkit/data/provenance.py +34 -0
  19. hsmmkit/data/quality.py +112 -0
  20. hsmmkit/data/sources/__init__.py +92 -0
  21. hsmmkit/data/sources/base.py +247 -0
  22. hsmmkit/data/sources/csv.py +36 -0
  23. hsmmkit/data/sources/numpy.py +143 -0
  24. hsmmkit/data/sources/pandas.py +33 -0
  25. hsmmkit/data/sources/parquet.py +37 -0
  26. hsmmkit/data/sources/xarray.py +62 -0
  27. hsmmkit/data/transforms.py +129 -0
  28. hsmmkit/engine/__init__.py +1 -0
  29. hsmmkit/engine/approx.py +51 -0
  30. hsmmkit/engine/augmented.py +93 -0
  31. hsmmkit/engine/base.py +134 -0
  32. hsmmkit/engine/batch.py +414 -0
  33. hsmmkit/engine/constraints.py +173 -0
  34. hsmmkit/engine/criteria.py +67 -0
  35. hsmmkit/engine/estep.py +314 -0
  36. hsmmkit/engine/estep_explicit.py +260 -0
  37. hsmmkit/engine/expanded_hmm.py +336 -0
  38. hsmmkit/engine/explicit_dd.py +114 -0
  39. hsmmkit/engine/explicit_duration.py +721 -0
  40. hsmmkit/engine/ffbs.py +229 -0
  41. hsmmkit/engine/parallel.py +98 -0
  42. hsmmkit/engine/viterbi.py +85 -0
  43. hsmmkit/estimation/__init__.py +36 -0
  44. hsmmkit/estimation/compare.py +154 -0
  45. hsmmkit/estimation/ecm.py +106 -0
  46. hsmmkit/estimation/em.py +460 -0
  47. hsmmkit/estimation/gem.py +467 -0
  48. hsmmkit/estimation/gibbs.py +136 -0
  49. hsmmkit/estimation/init.py +578 -0
  50. hsmmkit/estimation/map.py +287 -0
  51. hsmmkit/estimation/mcmc.py +370 -0
  52. hsmmkit/estimation/mstep.py +304 -0
  53. hsmmkit/estimation/newton.py +104 -0
  54. hsmmkit/estimation/objective.py +232 -0
  55. hsmmkit/estimation/optimizers.py +195 -0
  56. hsmmkit/estimation/recovery.py +748 -0
  57. hsmmkit/estimation/recovery_ext.py +557 -0
  58. hsmmkit/estimation/relabel.py +85 -0
  59. hsmmkit/estimation/report.py +167 -0
  60. hsmmkit/estimation/results.py +53 -0
  61. hsmmkit/estimation/selftest.py +154 -0
  62. hsmmkit/estimation/vb.py +508 -0
  63. hsmmkit/evaluation/__init__.py +1 -0
  64. hsmmkit/evaluation/backtest.py +616 -0
  65. hsmmkit/evaluation/compare.py +172 -0
  66. hsmmkit/evaluation/metrics/__init__.py +1 -0
  67. hsmmkit/evaluation/metrics/clustering.py +111 -0
  68. hsmmkit/evaluation/metrics/labels.py +40 -0
  69. hsmmkit/evaluation/metrics/matching.py +103 -0
  70. hsmmkit/evaluation/metrics/model.py +53 -0
  71. hsmmkit/evaluation/metrics/predictive.py +337 -0
  72. hsmmkit/evaluation/metrics/registry.py +154 -0
  73. hsmmkit/evaluation/metrics/segmentation.py +182 -0
  74. hsmmkit/evaluation/padding.py +72 -0
  75. hsmmkit/evaluation/report.py +170 -0
  76. hsmmkit/evaluation/results.py +28 -0
  77. hsmmkit/inference/__init__.py +1 -0
  78. hsmmkit/inference/covariate_forecasters.py +344 -0
  79. hsmmkit/inference/decode.py +185 -0
  80. hsmmkit/inference/forecast.py +475 -0
  81. hsmmkit/inference/results.py +97 -0
  82. hsmmkit/inference/simulate.py +342 -0
  83. hsmmkit/interop/__init__.py +1 -0
  84. hsmmkit/interop/arviz.py +114 -0
  85. hsmmkit/interop/hmmlearn.py +163 -0
  86. hsmmkit/interop/pandas.py +116 -0
  87. hsmmkit/interop/sklearn.py +505 -0
  88. hsmmkit/interop/xarray.py +296 -0
  89. hsmmkit/model/__init__.py +1 -0
  90. hsmmkit/model/build.py +404 -0
  91. hsmmkit/model/conjugate.py +260 -0
  92. hsmmkit/model/dists.py +244 -0
  93. hsmmkit/model/duration/__init__.py +23 -0
  94. hsmmkit/model/duration/base.py +215 -0
  95. hsmmkit/model/duration/explicit.py +205 -0
  96. hsmmkit/model/duration/gamma.py +53 -0
  97. hsmmkit/model/duration/geometric.py +106 -0
  98. hsmmkit/model/duration/hazard.py +23 -0
  99. hsmmkit/model/duration/lognormal.py +56 -0
  100. hsmmkit/model/duration/negbin.py +115 -0
  101. hsmmkit/model/duration/nonparametric.py +120 -0
  102. hsmmkit/model/duration/per_state.py +107 -0
  103. hsmmkit/model/duration/poisson.py +56 -0
  104. hsmmkit/model/duration/weibull.py +61 -0
  105. hsmmkit/model/emission/__init__.py +24 -0
  106. hsmmkit/model/emission/_discrete.py +104 -0
  107. hsmmkit/model/emission/base.py +105 -0
  108. hsmmkit/model/emission/bernoulli.py +131 -0
  109. hsmmkit/model/emission/categorical.py +158 -0
  110. hsmmkit/model/emission/gaussian.py +754 -0
  111. hsmmkit/model/emission/mixture.py +387 -0
  112. hsmmkit/model/emission/msar.py +545 -0
  113. hsmmkit/model/emission/poisson.py +144 -0
  114. hsmmkit/model/emission/product.py +390 -0
  115. hsmmkit/model/emission/student_t.py +454 -0
  116. hsmmkit/model/lattice.py +246 -0
  117. hsmmkit/model/params/__init__.py +45 -0
  118. hsmmkit/model/params/bijectors.py +238 -0
  119. hsmmkit/model/params/manager.py +307 -0
  120. hsmmkit/model/params/priors.py +84 -0
  121. hsmmkit/model/params/spec.py +65 -0
  122. hsmmkit/model/spec.py +43 -0
  123. hsmmkit/model/topology.py +97 -0
  124. hsmmkit/model/transition.py +419 -0
  125. hsmmkit/online/__init__.py +24 -0
  126. hsmmkit/online/alerts.py +181 -0
  127. hsmmkit/online/buffer.py +203 -0
  128. hsmmkit/online/covariates.py +162 -0
  129. hsmmkit/online/em.py +304 -0
  130. hsmmkit/online/filter.py +682 -0
  131. hsmmkit/online/session.py +364 -0
  132. hsmmkit/online/state.py +240 -0
  133. hsmmkit/persistence/__init__.py +1 -0
  134. hsmmkit/persistence/results.py +495 -0
  135. hsmmkit/persistence/store.py +394 -0
  136. hsmmkit/plot/__init__.py +13 -0
  137. hsmmkit/plot/_common.py +56 -0
  138. hsmmkit/plot/diagnostics.py +176 -0
  139. hsmmkit/plot/durations.py +74 -0
  140. hsmmkit/plot/forecast.py +55 -0
  141. hsmmkit/plot/regimes.py +146 -0
  142. hsmmkit/plugins.py +311 -0
  143. hsmmkit/presets/__init__.py +116 -0
  144. hsmmkit/presets/core/counts_poisson_hazard.yaml +61 -0
  145. hsmmkit/presets/core/msar2_hamilton.yaml +59 -0
  146. hsmmkit/presets/core/segmentation_gaussian_ltr.yaml +82 -0
  147. hsmmkit/presets/core/two_regime_gaussian.yaml +60 -0
  148. hsmmkit/presets/fixtures.py +330 -0
  149. hsmmkit/project.py +1106 -0
  150. hsmmkit/py.typed +0 -0
  151. hsmmkit/scaffold.py +80 -0
  152. hsmmkit/selection/__init__.py +30 -0
  153. hsmmkit/selection/bootstrap.py +388 -0
  154. hsmmkit/selection/cv.py +301 -0
  155. hsmmkit/selection/grid.py +412 -0
  156. hsmmkit/selection/ppc.py +199 -0
  157. hsmmkit/selection/pseudo_residuals.py +265 -0
  158. hsmmkit/selection/replicate.py +57 -0
  159. hsmmkit/selection/splitters.py +213 -0
  160. hsmmkit/statespace/__init__.py +1 -0
  161. hsmmkit/statespace/builders.py +317 -0
  162. hsmmkit/statespace/factorial.py +249 -0
  163. hsmmkit/statespace/index.py +85 -0
  164. hsmmkit/statespace/transitions.py +143 -0
  165. hsmmkit/templates/family-plugin/common/README.md.tmpl +9 -0
  166. hsmmkit/templates/family-plugin/common/pyproject.toml.tmpl +19 -0
  167. hsmmkit/templates/family-plugin/common/src/__pkg__/__init__.py.tmpl +7 -0
  168. hsmmkit/templates/family-plugin/common/src/__pkg__/tests/__init__.py.tmpl +0 -0
  169. hsmmkit/templates/family-plugin/duration/family.py.tmpl +19 -0
  170. hsmmkit/templates/family-plugin/duration/test_contract.py.tmpl +14 -0
  171. hsmmkit/templates/family-plugin/emission/family.py.tmpl +95 -0
  172. hsmmkit/templates/family-plugin/emission/test_contract.py.tmpl +48 -0
  173. hsmmkit/testing/__init__.py +6 -0
  174. hsmmkit/testing/clock_contract.py +53 -0
  175. hsmmkit/testing/duration_contract.py +218 -0
  176. hsmmkit/testing/family_contract.py +339 -0
  177. hsmmkit/testing/metric_contract.py +157 -0
  178. hsmmkit/testing/source_contract.py +196 -0
  179. hsmmkit/utils/__init__.py +1 -0
  180. hsmmkit/utils/clock.py +109 -0
  181. hsmmkit/utils/deprecation.py +125 -0
  182. hsmmkit/utils/errors.py +56 -0
  183. hsmmkit/utils/jax_setup.py +48 -0
  184. hsmmkit/utils/logging.py +30 -0
  185. hsmmkit/utils/optional.py +25 -0
  186. hsmmkit/utils/rng.py +49 -0
  187. hsmmkit/utils/typing.py +32 -0
  188. hsmmkit-0.5.0.dist-info/METADATA +84 -0
  189. hsmmkit-0.5.0.dist-info/RECORD +192 -0
  190. hsmmkit-0.5.0.dist-info/WHEEL +4 -0
  191. hsmmkit-0.5.0.dist-info/entry_points.txt +2 -0
  192. hsmmkit-0.5.0.dist-info/licenses/LICENSE +190 -0
hsmmkit/model/dists.py ADDED
@@ -0,0 +1,244 @@
1
+ """In-house distributions used by emission and duration families (ADR-0003, no TFP).
2
+
3
+ Every function is pure, vectorized, float64, and jittable. Duration pmfs are truncated at `D_max`
4
+ and renormalized to sum to 1 on the support `d = 1..D_max`; `d_max` (and, for the negative-binomial
5
+ family, `r`) are static (shape-defining, overview §4.5), not differentiated.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import math
11
+
12
+ import jax
13
+ import jax.numpy as jnp
14
+ import jax.scipy.linalg as jsp_linalg
15
+ import jax.scipy.special as jsp_special
16
+ import numpy as np
17
+
18
+ from hsmmkit.utils.typing import Array
19
+
20
+ _LOG_2PI = math.log(2.0 * math.pi)
21
+
22
+
23
+ # --- Multivariate normal and LKJ -------------------------------------------------------------
24
+
25
+
26
+ def packed_size(m: int) -> int:
27
+ """Length `M(M+1)/2` of a packed (row-major) lower triangle of an `M x M` matrix."""
28
+ return m * (m + 1) // 2
29
+
30
+
31
+ def unpack_lower(packed: Array, m: int) -> Array:
32
+ """`(..., M(M+1)/2)` packed row-major lower triangle -> `(..., M, M)` lower-triangular matrix."""
33
+ rows, cols = np.tril_indices(m)
34
+ out = jnp.zeros((*packed.shape[:-1], m, m), dtype=packed.dtype)
35
+ return out.at[..., rows, cols].set(packed)
36
+
37
+
38
+ def pack_lower(matrix: Array) -> Array:
39
+ """`(..., M, M)` -> `(..., M(M+1)/2)` row-major lower triangle (inverse of `unpack_lower`)."""
40
+ rows, cols = np.tril_indices(matrix.shape[-1])
41
+ return matrix[..., rows, cols]
42
+
43
+
44
+ def _whiten(y: Array, mean: Array, chol: Array) -> tuple[Array, Array]:
45
+ """`(|L^-1 (y - mean)|^2, sum log diag L)` with broadcasting over the leading axes."""
46
+ m = y.shape[-1]
47
+ resid = y - mean
48
+ batch = jnp.broadcast_shapes(resid.shape[:-1], chol.shape[:-2])
49
+ resid_b = jnp.broadcast_to(resid, (*batch, m))
50
+ chol_b = jnp.broadcast_to(chol, (*batch, m, m))
51
+ x = jax.vmap(lambda c, r: jsp_linalg.solve_triangular(c, r, lower=True))(
52
+ chol_b.reshape(-1, m, m), resid_b.reshape(-1, m)
53
+ ).reshape(*batch, m)
54
+ log_det = jnp.sum(jnp.log(jnp.diagonal(chol_b, axis1=-2, axis2=-1)), axis=-1)
55
+ return jnp.sum(x**2, axis=-1), log_det
56
+
57
+
58
+ def mvt_logpdf(y: Array, loc: Array, chol: Array, nu: Array) -> Array:
59
+ """Multivariate Student-t log-density with scale matrix `L L^T` and `nu` degrees of freedom.
60
+
61
+ `log f = lgamma((nu+M)/2) - lgamma(nu/2) - M/2 log(nu pi) - log|L| - (nu+M)/2 log(1 + q/nu)` with
62
+ `q = |L^-1 (y - loc)|^2`; `nu` broadcasts against the leading axes.
63
+ """
64
+ m = y.shape[-1]
65
+ q, log_det = _whiten(y, loc, chol)
66
+ return (
67
+ jsp_special.gammaln((nu + m) / 2.0)
68
+ - jsp_special.gammaln(nu / 2.0)
69
+ - 0.5 * m * jnp.log(nu * math.pi)
70
+ - log_det
71
+ - 0.5 * (nu + m) * jnp.log1p(q / nu)
72
+ )
73
+
74
+
75
+ def mvn_logpdf(y: Array, mean: Array, chol: Array) -> Array:
76
+ """Multivariate normal log-density with covariance `L L^T`.
77
+
78
+ Args:
79
+ y: `(..., M)` points.
80
+ mean: `(..., M)` means (broadcast against `y`).
81
+ chol: `(..., M, M)` lower-triangular `L` with positive diagonal (broadcast over the leading axes).
82
+
83
+ Returns:
84
+ `(...)` log-densities `-1/2 [M log 2 pi + 2 sum log diag(L) + |L^-1 (y - mean)|^2]`.
85
+ """
86
+ q, log_det = _whiten(y, mean, chol)
87
+ return -0.5 * (y.shape[-1] * _LOG_2PI + q) - log_det
88
+
89
+
90
+ def lkj_logpdf(corr_chol: Array, eta: float) -> Array:
91
+ """LKJ log-density of a correlation matrix `R = C C^T` given by its Cholesky factor `C` (`(M, M)`).
92
+
93
+ `log p(R) = (eta - 1) log det R - log c_M(eta)` with `log det R = 2 sum log diag(C)` and the
94
+ normalizing constant of Lewandowski, Kurowicka and Joe (2009, eq. 16); `eta = 1` is uniform on
95
+ correlation matrices. The density is over `R` (not over `C`).
96
+ """
97
+ m = corr_chol.shape[-1]
98
+ log_c: Array | float = 0.0
99
+ for k in range(1, m):
100
+ shape = eta + (m - k - 1) / 2.0
101
+ log_c += (2.0 * eta - 2.0 + m - k) * (m - k) * math.log(2.0)
102
+ log_c += (m - k) * (2.0 * jsp_special.gammaln(shape) - jsp_special.gammaln(2.0 * shape))
103
+ log_det_r = 2.0 * jnp.sum(jnp.log(jnp.diagonal(corr_chol, axis1=-2, axis2=-1)), axis=-1)
104
+ return (eta - 1.0) * log_det_r - log_c
105
+
106
+
107
+ # --- Continuous log-densities ---------------------------------------------------------------
108
+
109
+
110
+ def normal_logpdf(y: Array, mean: Array, sd: Array) -> Array:
111
+ """Normal log-density."""
112
+ z = (y - mean) / sd
113
+ return -0.5 * z**2 - jnp.log(sd) - 0.5 * _LOG_2PI
114
+
115
+
116
+ def student_t_logpdf(y: Array, loc: Array, scale: Array, nu: Array) -> Array:
117
+ """Student-t log-density (`nu > 2` degrees of freedom, location-scale form)."""
118
+ z = (y - loc) / scale
119
+ return (
120
+ jsp_special.gammaln((nu + 1.0) / 2.0)
121
+ - jsp_special.gammaln(nu / 2.0)
122
+ - 0.5 * jnp.log(nu * jnp.pi)
123
+ - jnp.log(scale)
124
+ - (nu + 1.0) / 2.0 * jnp.log1p(z**2 / nu)
125
+ )
126
+
127
+
128
+ # --- Duration log-pmfs (truncated at D_max, renormalized) ------------------------------------
129
+
130
+
131
+ def _poisson_logpmf(k: Array, kappa: Array) -> Array:
132
+ return jnp.where(k >= 0, k * jnp.log(kappa) - kappa - jsp_special.gammaln(k + 1.0), -jnp.inf)
133
+
134
+
135
+ def poisson_shifted_logpmf(d: Array, kappa: Array, d_max: int) -> Array:
136
+ """`d = 1 + Poisson(kappa)`, truncated at `D_max` and renormalized."""
137
+ support = jnp.arange(1, d_max + 1, dtype=jnp.float64)
138
+ log_z = jsp_special.logsumexp(_poisson_logpmf(support - 1.0, kappa))
139
+ return _poisson_logpmf(d - 1.0, kappa) - log_z
140
+
141
+
142
+ def negbin_mean(r: float, a: Array) -> Array:
143
+ """Untruncated mean of the shifted negative binomial, `r / a`."""
144
+ return r / a
145
+
146
+
147
+ def negbin_var(r: float, a: Array) -> Array:
148
+ """Untruncated variance of the shifted negative binomial, `r * (1 - a) / a**2`."""
149
+ return r * (1.0 - a) / a**2
150
+
151
+
152
+ def _negbin_shifted_logpmf_raw(d: Array, r: float, a: Array) -> Array:
153
+ return jnp.where(
154
+ d >= r,
155
+ jsp_special.gammaln(d)
156
+ - jsp_special.gammaln(r)
157
+ - jsp_special.gammaln(d - r + 1.0)
158
+ + r * jnp.log(a)
159
+ + (d - r) * jnp.log1p(-a),
160
+ -jnp.inf,
161
+ )
162
+
163
+
164
+ def negbin_shifted_logpmf(d: Array, r: float, a: Array, d_max: int) -> Array:
165
+ """`d - r ~ NegBin(r, a)` (failures before `r` successes), support `d >= r`.
166
+
167
+ Truncated at `D_max` and renormalized.
168
+ """
169
+ support = jnp.arange(1, d_max + 1, dtype=jnp.float64)
170
+ log_z = jsp_special.logsumexp(_negbin_shifted_logpmf_raw(support, r, a))
171
+ return _negbin_shifted_logpmf_raw(d, r, a) - log_z
172
+
173
+
174
+ def _gamma_cdf(x: Array | float, shape: Array, scale: Array) -> Array:
175
+ return jsp_special.gammainc(shape, x / scale)
176
+
177
+
178
+ def disc_gamma_logpmf(d: Array, shape: Array, scale: Array, dt: float, d_max: int) -> Array:
179
+ """`p(d) = [F(d*dt) - F((d-1)*dt)] / F(D_max*dt)`, `F` the Gamma cdf (in years)."""
180
+ numerator = _gamma_cdf(d * dt, shape, scale) - _gamma_cdf((d - 1.0) * dt, shape, scale)
181
+ denominator = _gamma_cdf(d_max * dt, shape, scale)
182
+ return jnp.log(numerator) - jnp.log(denominator)
183
+
184
+
185
+ def _weibull_cdf(x: Array | float, shape: Array, scale: Array) -> Array:
186
+ return -jnp.expm1(-((x / scale) ** shape))
187
+
188
+
189
+ def disc_weibull_logpmf(d: Array, shape: Array, scale: Array, dt: float, d_max: int) -> Array:
190
+ """`p(d) = [F(d*dt) - F((d-1)*dt)] / F(D_max*dt)`, `F` the Weibull cdf (closed form)."""
191
+ numerator = _weibull_cdf(d * dt, shape, scale) - _weibull_cdf((d - 1.0) * dt, shape, scale)
192
+ denominator = _weibull_cdf(d_max * dt, shape, scale)
193
+ return jnp.log(numerator) - jnp.log(denominator)
194
+
195
+
196
+ def _lognormal_cdf(x: Array | float, mu_log: Array, sd_log: Array) -> Array:
197
+ z = (jnp.log(x) - mu_log) / sd_log
198
+ # `ndtr` (not `0.5 * (1 + erf(z / sqrt(2)))`) avoids catastrophic cancellation for very
199
+ # negative z, where erf(z) -> -1 and `1 + erf(...)` loses precision.
200
+ return jsp_special.ndtr(z)
201
+
202
+
203
+ def disc_lognormal_logpmf(d: Array, mu_log: Array, sd_log: Array, dt: float, d_max: int) -> Array:
204
+ """`p(d) = [F(d*dt) - F((d-1)*dt)] / F(D_max*dt)`, `F` the log-normal cdf."""
205
+ lower = jnp.where(d > 1.0, _lognormal_cdf((d - 1.0) * dt, mu_log, sd_log), 0.0)
206
+ numerator = _lognormal_cdf(d * dt, mu_log, sd_log) - lower
207
+ denominator = _lognormal_cdf(d_max * dt, mu_log, sd_log)
208
+ return jnp.log(numerator) - jnp.log(denominator)
209
+
210
+
211
+ def nonparametric_logpmf(logits: Array, d_max: int) -> Array:
212
+ """`log softmax(logits)` over `1..D_max` (`len(logits) == d_max`)."""
213
+ del d_max
214
+ return jax.nn.log_softmax(logits)
215
+
216
+
217
+ def geometric_logpmf(d: Array, a: Array, d_max: int) -> Array:
218
+ """`(1 - a)^(d - 1) * a`, truncated at `D_max` and renormalized."""
219
+ raw = (d - 1.0) * jnp.log1p(-a) + jnp.log(a)
220
+ log_z = jnp.log1p(-jnp.exp(d_max * jnp.log1p(-a)))
221
+ return raw - log_z
222
+
223
+
224
+ # --- Samplers ---------------------------------------------------------------------------------
225
+
226
+
227
+ def sample_normal(key: Array, mean: Array, sd: Array, shape: tuple[int, ...] = ()) -> Array:
228
+ """Sample from `Normal(mean, sd)`."""
229
+ return mean + sd * jax.random.normal(key, shape=shape)
230
+
231
+
232
+ def sample_student_t(key: Array, loc: Array, scale: Array, nu: Array, shape: tuple[int, ...] = ()) -> Array:
233
+ """Sample from the location-scale Student-t distribution."""
234
+ return loc + scale * jax.random.t(key, df=nu, shape=shape)
235
+
236
+
237
+ def sample_categorical(key: Array, log_probs: Array) -> Array:
238
+ """Sample a category index from `log_probs` (unnormalized log-probabilities)."""
239
+ return jax.random.categorical(key, log_probs)
240
+
241
+
242
+ def sample_pmf(key: Array, log_pmf: Array) -> Array:
243
+ """Sample `d in {1, ..., len(log_pmf)}` from a duration log-pmf."""
244
+ return sample_categorical(key, log_pmf) + 1
@@ -0,0 +1,23 @@
1
+ """Sojourn-duration families."""
2
+
3
+ from hsmmkit.model.duration.base import DurationFamily
4
+ from hsmmkit.model.duration.gamma import GammaDuration
5
+ from hsmmkit.model.duration.geometric import GeometricDuration
6
+ from hsmmkit.model.duration.hazard import hazard
7
+ from hsmmkit.model.duration.lognormal import LogNormalDuration
8
+ from hsmmkit.model.duration.negbin import NegBinDuration
9
+ from hsmmkit.model.duration.nonparametric import NonparametricDuration
10
+ from hsmmkit.model.duration.poisson import PoissonDuration
11
+ from hsmmkit.model.duration.weibull import WeibullDuration
12
+
13
+ __all__ = [
14
+ "DurationFamily",
15
+ "GammaDuration",
16
+ "GeometricDuration",
17
+ "LogNormalDuration",
18
+ "NegBinDuration",
19
+ "NonparametricDuration",
20
+ "PoissonDuration",
21
+ "WeibullDuration",
22
+ "hazard",
23
+ ]
@@ -0,0 +1,215 @@
1
+ """`DurationFamily` protocol (E3-T03; replaces the E1-T05 signature stub) and shared helpers.
2
+
3
+ Concept refs: §4.3, §4.4 Durations, §5.5, ADR-0006. `mean_sojourn(theta, nominal_dt)` (renamed
4
+ from `mean_sojourn_years`, CLAUDE.md §3.1); `supports_explicit`/`init_from_mean_sojourn`/
5
+ `advance_prob_t` are CLAUDE.md §3.3 additions to the concept's protocol text.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import TYPE_CHECKING, Literal, Protocol
11
+
12
+ import jax
13
+ import jax.numpy as jnp
14
+ import jax.scipy.special
15
+ import numpy as np
16
+
17
+ from hsmmkit.model.params import DEFAULT_COEF_PRIOR, DirichletPrior, LogNormalPrior, NormalPrior, Prior
18
+ from hsmmkit.model.params.spec import Mode, ParamSpec
19
+ from hsmmkit.utils.errors import ConfigError
20
+ from hsmmkit.utils.typing import Array
21
+
22
+ if TYPE_CHECKING:
23
+ from hsmmkit.config.schema import ParamCfg, PriorCfg
24
+
25
+ Params = dict[str, Array]
26
+
27
+
28
+ class DurationFamily(Protocol):
29
+ """Structural type for sojourn-duration families (geometric, negbin, explicit, ...)."""
30
+
31
+ name: str
32
+ representation: Literal["phase", "explicit"]
33
+ supports_explicit: bool
34
+
35
+ def param_specs(self, n_states: int, cov_names: tuple[str, ...]) -> tuple[ParamSpec, ...]:
36
+ """The `ParamSpec`s this family contributes for a model of `n_states` regimes."""
37
+ ...
38
+
39
+ def n_phases(self, i: int) -> int:
40
+ """`r_i`: the (static) number of phases regime `i` chains through."""
41
+ ...
42
+
43
+ def advance_prob(self, theta: Params, dt: Array, z_d: Array | None) -> Array:
44
+ """`(T, N)` per-step, per-regime phase-advance probability `a_i(t)`."""
45
+ ...
46
+
47
+ def advance_prob_t(self, theta: Params, dt: Array | float, z_d_t: Array | None = None) -> Array:
48
+ """Per-step wrapper of `advance_prob` (`(N,)`), for use inside a `jax.lax.scan` body."""
49
+ ...
50
+
51
+ def log_pmf(self, theta: Params, d_max: int, nominal_dt: float, z_entry: Array | None) -> Array:
52
+ """`(N, D_max)` sojourn-length log-pmf at a constant (entry-time) covariate value."""
53
+ ...
54
+
55
+ def mean_sojourn(self, theta: Params, nominal_dt: float) -> Array:
56
+ """`(N,)` mean sojourn length in clock units (`nominal_dt`'s units: years or steps)."""
57
+ ...
58
+
59
+ def init_from_mean_sojourn(self, mean_steps: Array, nominal_dt: float) -> Params:
60
+ """`theta` reproducing `mean_steps` (per state, in steps) as this family's mean sojourn."""
61
+ ...
62
+
63
+
64
+ # --- shared numerics: advance probability, independent of phase count r ------------------------
65
+
66
+
67
+ def residual_log_pmf(log_pmf: Array) -> Array:
68
+ """Residual-life (equilibrium) pmf of a sojourn pmf over `d = 1..D_max` (E12-T04).
69
+
70
+ `p_res(d) = S(d - 1) / E[d]` with `S(d) = P(duration > d)` and `E[d] = sum_d d p(d)`; `log_pmf` is
71
+ `(..., D_max)` (rows already truncated and renormalized), the result has the same shape and each row sums
72
+ to 1 (`sum_d S(d - 1) = E[d]`). It is the pmf of the time left in a segment already running at `t = 1`.
73
+ """
74
+ log_surv = jax.lax.cumlogsumexp(log_pmf, axis=log_pmf.ndim - 1, reverse=True) # log P(duration >= d)
75
+ log_mean = jax.scipy.special.logsumexp(log_surv, axis=-1, keepdims=True) # log E[d]
76
+ return log_surv - log_mean
77
+
78
+
79
+ def advance_prob_core(rate: Array, dt: Array, c: Array | None, z_d: Array | None) -> Array:
80
+ """`(T, N)` phase-advance probability `a_i(t) = 1 - exp(-lambda_i(t) * dt_t)`.
81
+
82
+ `lambda_i(t) = rate_i * exp(c_i . z_d_t)` when both `c` and `z_d` are given, else `rate_i`.
83
+ """
84
+ t = dt.shape[0]
85
+ n = rate.shape[0]
86
+ log_rate_adj = z_d @ c.T if (c is not None and z_d is not None) else jnp.zeros((t, n))
87
+ rate_t = rate[None, :] * jnp.exp(log_rate_adj) # (T, N)
88
+ return -jnp.expm1(-rate_t * dt[:, None])
89
+
90
+
91
+ def advance_prob_entry(
92
+ rate: Array, nominal_dt: Array | float, c: Array | None, z_entry: Array | None
93
+ ) -> Array:
94
+ """`(N,)` advance probability at a fixed (entry-time) covariate value `z_entry`."""
95
+ n = rate.shape[0]
96
+ log_rate_adj = c @ z_entry if (c is not None and z_entry is not None) else jnp.zeros((n,))
97
+ rate_i = rate * jnp.exp(log_rate_adj)
98
+ return -jnp.expm1(-rate_i * nominal_dt)
99
+
100
+
101
+ # --- shared config mapping: `ParamCfg` -> `ParamSpec` (rate/c), mirrors GBMFamily (E3-T01) -----
102
+
103
+
104
+ def prior_from_cfg(cfg: PriorCfg, init: np.ndarray | None) -> Prior:
105
+ """`PriorCfg` -> a `Prior` object (same rule as `GBMFamily`: lognormal centers on `log(init)`)."""
106
+ if cfg.type == "normal":
107
+ return NormalPrior(sd=cfg.sd if cfg.sd is not None else 1.0)
108
+ if cfg.type == "lognormal":
109
+ mean_log = float(np.log(init).mean()) if init is not None else 0.0
110
+ return LogNormalPrior(mean_log=mean_log, sd=cfg.sd if cfg.sd is not None else 1.0)
111
+ if cfg.type == "dirichlet":
112
+ return DirichletPrior(alpha=cfg.alpha if cfg.alpha is not None else 1.0)
113
+ raise ConfigError(f"unknown prior type {cfg.type!r}", path="prior.type")
114
+
115
+
116
+ def broadcast_per_state(values: list[float] | float | str | None, n_states: int) -> np.ndarray | None:
117
+ """`values` (one per state) -> `(n_states,)`."""
118
+ if values is None:
119
+ return None
120
+ if isinstance(values, str): # `init: labels`: the `labels` init method fills it (E12-T06)
121
+ return None
122
+ arr = np.asarray(values, dtype=np.float64)
123
+ if arr.ndim == 0: # one value for every state
124
+ arr = np.full(n_states, float(arr))
125
+ if arr.shape != (n_states,):
126
+ raise ConfigError(f"expected {n_states} per-state values, got shape {arr.shape}", path="values")
127
+ return arr
128
+
129
+
130
+ def spec_from_paramcfg(
131
+ name: str, cfg: ParamCfg, *, n_states: int, domain: Literal["real", "positive"], default_init: float
132
+ ) -> ParamSpec:
133
+ """`ParamCfg` -> a `(n_states,)` `ParamSpec` (plain `values`/`init`; no `increasing` handling)."""
134
+ shape = (n_states,)
135
+ value = broadcast_per_state(cfg.values, n_states)
136
+ init = broadcast_per_state(cfg.init, n_states)
137
+ if init is None and cfg.mode != "fixed":
138
+ init = np.full(shape, default_init, dtype=np.float64)
139
+ prior = prior_from_cfg(cfg.prior, init) if cfg.prior is not None else None
140
+ mode: Mode | tuple[Mode, ...] = cfg.mode
141
+ return ParamSpec(
142
+ name=name,
143
+ shape=shape,
144
+ domain=domain,
145
+ mode=mode,
146
+ value=value,
147
+ init=init,
148
+ bounds=cfg.bounds,
149
+ prior=prior,
150
+ tie_group=cfg.tie,
151
+ constraint=cfg.constraint,
152
+ )
153
+
154
+
155
+ def coef_spec(name: str, n_states: int, n_coef: int) -> ParamSpec:
156
+ """Default free coefficient spec (`duration.c`), `NormalPrior(0, coef_prior_sd)`-regularized."""
157
+ shape = (n_states, n_coef)
158
+ return ParamSpec(
159
+ name=name,
160
+ shape=shape,
161
+ domain="real",
162
+ mode="free",
163
+ init=np.zeros(shape, dtype=np.float64),
164
+ prior=DEFAULT_COEF_PRIOR,
165
+ )
166
+
167
+
168
+ def cov_idx_from_names(names: list[str], cov_names: tuple[str, ...], path: str) -> tuple[int, ...]:
169
+ """Column indices of `names` within `cov_names`, or `ConfigError` for an unknown name."""
170
+ try:
171
+ return tuple(cov_names.index(c) for c in names)
172
+ except ValueError as exc:
173
+ raise ConfigError(str(exc), path=path) from exc
174
+
175
+
176
+ def rate_spec_from_cfg(
177
+ rate_cfg: ParamCfg,
178
+ n_states: int,
179
+ nominal_dt: float,
180
+ init_from_mean_sojourn: object,
181
+ ) -> ParamSpec:
182
+ """`duration.rate` spec from `ParamCfg`, handling `init_mean_sojourn_steps` via `init_from_mean_sojourn`.
183
+
184
+ `init_mean_sojourn_days` needs a clock-aware days->steps conversion that only
185
+ `model/build.py` has (CLAUDE.md §3.3: "`init_mean_sojourn_days` is converted here with
186
+ `days_to_steps`"); callers must pre-convert it to `init_mean_sojourn_steps` before this ticket's
187
+ scope. `init_from_mean_sojourn` is `DurationFamily.init_from_mean_sojourn` (typed as `object`
188
+ here to avoid a `Callable[[Array, float], Params]` import cycle with the concrete families).
189
+ """
190
+ if rate_cfg.init_mean_sojourn_steps is not None:
191
+ mean_steps = broadcast_per_state(rate_cfg.init_mean_sojourn_steps, n_states)
192
+ assert mean_steps is not None
193
+ theta0 = init_from_mean_sojourn(jnp.asarray(mean_steps), nominal_dt) # type: ignore[operator]
194
+ init = np.asarray(theta0["duration.rate"])
195
+ return ParamSpec(
196
+ name="duration.rate",
197
+ shape=(n_states,),
198
+ domain="positive",
199
+ mode=rate_cfg.mode,
200
+ init=init,
201
+ value=broadcast_per_state(rate_cfg.values, n_states),
202
+ bounds=rate_cfg.bounds,
203
+ prior=prior_from_cfg(rate_cfg.prior, init) if rate_cfg.prior is not None else None,
204
+ tie_group=rate_cfg.tie,
205
+ constraint=rate_cfg.constraint,
206
+ )
207
+ if getattr(rate_cfg, "init_mean_sojourn_days", None) is not None:
208
+ raise ConfigError(
209
+ "init_mean_sojourn_days needs a clock-aware days->steps conversion (model/build.py, "
210
+ "CLAUDE.md §3.3); pre-convert to init_mean_sojourn_steps before DurationFamily.from_config",
211
+ path="model.duration.params.rate.init_mean_sojourn_days",
212
+ )
213
+ return spec_from_paramcfg(
214
+ "duration.rate", rate_cfg, n_states=n_states, domain="positive", default_init=0.1
215
+ )
@@ -0,0 +1,205 @@
1
+ """Shared machinery for the explicit-duration families (E3-T04).
2
+
3
+ An explicit family gives the sojourn pmf `p_i(d)`, `d = 1..D_max`, on a regular grid of step `nominal_dt`
4
+ (clock units: years under a year clock, steps under `steps`, CLAUDE.md §3.1). Continuous
5
+ sojourn laws are discretized as `p(d) = [F(d dt) - F((d-1) dt)] / F(D_max dt)`. The covariate link is
6
+ entry-time: the scale-like parameter is multiplied by `exp(c_i . z_entry)`.
7
+
8
+ No phase representation exists: `n_phases`/`advance_prob`/`advance_prob_t` raise `NotImplementedError`.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import warnings
14
+ from collections.abc import Callable
15
+ from dataclasses import dataclass, replace
16
+ from typing import TYPE_CHECKING, ClassVar, Literal
17
+
18
+ import jax
19
+ import jax.numpy as jnp
20
+ import numpy as np
21
+
22
+ from hsmmkit.model.duration.base import (
23
+ Params,
24
+ broadcast_per_state,
25
+ coef_spec,
26
+ cov_idx_from_names,
27
+ spec_from_paramcfg,
28
+ )
29
+ from hsmmkit.model.params.spec import ParamSpec
30
+ from hsmmkit.utils.errors import ConfigError
31
+ from hsmmkit.utils.typing import Array
32
+
33
+ if TYPE_CHECKING:
34
+ from hsmmkit.config.schema import DurationCfg
35
+
36
+ # Floors keep `log` (and its gradient) finite when a grid cell underflows; the induced mass error is
37
+ # below 1e-300 per cell, far under the 1e-10 row-sum tolerance.
38
+ _TINY = 1e-300
39
+ D_MAX_TAIL_TOLERANCE = 1e-6
40
+ D_MAX_SOJOURN_MULTIPLIER = 2.0
41
+
42
+ ParamDef = tuple[str, Literal["real", "positive"], float] # (config key, domain, default init)
43
+
44
+
45
+ def grid_log_pmf(cdf: Callable[[Array], Array], dt: float, d_max: int) -> Array:
46
+ """`(N, D_max)` log of `[F(d dt) - F((d-1) dt)] / F(D_max dt)`; `cdf` maps `(D,)` edges to `(N, D)`."""
47
+ edges = jnp.arange(1, d_max + 1, dtype=jnp.float64) * dt
48
+ f = cdf(edges) # (N, D): F(d dt), F(0) = 0 implied
49
+ f_prev = jnp.concatenate([jnp.zeros_like(f[:, :1]), f[:, :-1]], axis=1)
50
+ numerator = jnp.maximum(f - f_prev, _TINY)
51
+ denominator = jnp.maximum(f[:, -1:], _TINY)
52
+ return jnp.log(numerator) - jnp.log(denominator)
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class ExplicitDurationBase:
57
+ """Common behaviour of explicit families; subclasses supply `_log_pmf_one`, `_tail_one` and the params."""
58
+
59
+ name: str = ""
60
+ representation: Literal["phase", "explicit"] = "explicit"
61
+ supports_explicit: bool = True
62
+ cov_idx: tuple[int, ...] = ()
63
+
64
+ param_defs: ClassVar[tuple[ParamDef, ...]] = ()
65
+ primary: ClassVar[str] = ""
66
+
67
+ # --- phase-representation API: not available --------------------------------------------
68
+
69
+ def n_phases(self, i: int) -> int:
70
+ """Not defined for an explicit family."""
71
+ raise NotImplementedError(f"{self.name}: explicit duration family has no phase representation")
72
+
73
+ def advance_prob(self, theta: Params, dt: Array, z_d: Array | None) -> Array:
74
+ """Not defined for an explicit family."""
75
+ raise NotImplementedError(f"{self.name}: explicit duration family has no phase advance probability")
76
+
77
+ def advance_prob_t(self, theta: Params, dt: Array | float, z_d_t: Array | None = None) -> Array:
78
+ """Not defined for an explicit family."""
79
+ raise NotImplementedError(f"{self.name}: explicit duration family has no phase advance probability")
80
+
81
+ # --- parameters -------------------------------------------------------------------------
82
+
83
+ def param_specs(self, n_states: int, cov_names: tuple[str, ...]) -> tuple[ParamSpec, ...]:
84
+ """Default (config-free) specs: every parameter free at its default init."""
85
+ del cov_names
86
+ return tuple(
87
+ ParamSpec(
88
+ name=f"duration.{key}",
89
+ shape=(n_states,),
90
+ domain=domain,
91
+ mode="free",
92
+ init=np.full((n_states,), default),
93
+ )
94
+ for key, domain, default in self.param_defs
95
+ )
96
+
97
+ @classmethod
98
+ def from_config(
99
+ cls, cfg: DurationCfg, n_states: int, cov_names: tuple[str, ...], nominal_dt: float
100
+ ) -> tuple[ExplicitDurationBase, tuple[ParamSpec, ...]]:
101
+ """Map `model.duration` config to a configured family and its `ParamSpec`s.
102
+
103
+ `init_mean_sojourn_steps` on the family's primary parameter initializes all parameters that have
104
+ no explicit `init` through `init_from_mean_sojourn` (CLAUDE.md §3.1, §3.3).
105
+ """
106
+ cov_idx = cov_idx_from_names(cfg.covariates, cov_names, "model.duration.covariates")
107
+ family = cls(cov_idx=cov_idx)
108
+ for key, _, _ in cls.param_defs:
109
+ if key not in cfg.params:
110
+ raise ConfigError(
111
+ f"{cls.__name__} requires params.{key}", path=f"model.duration.params.{key}"
112
+ )
113
+ primary_cfg = cfg.params[cls.primary]
114
+ if getattr(primary_cfg, "init_mean_sojourn_days", None) is not None:
115
+ raise ConfigError(
116
+ "init_mean_sojourn_days needs a clock-aware days->steps conversion (model/build.py, "
117
+ "CLAUDE.md §3.3); pre-convert to init_mean_sojourn_steps",
118
+ path=f"model.duration.params.{cls.primary}.init_mean_sojourn_days",
119
+ )
120
+ theta0: Params | None = None
121
+ if primary_cfg.init_mean_sojourn_steps is not None:
122
+ mean_steps = broadcast_per_state(primary_cfg.init_mean_sojourn_steps, n_states)
123
+ assert mean_steps is not None
124
+ theta0 = family.init_from_mean_sojourn(jnp.asarray(mean_steps), nominal_dt)
125
+ specs: list[ParamSpec] = []
126
+ for key, domain, default in cls.param_defs:
127
+ spec = spec_from_paramcfg(
128
+ f"duration.{key}", cfg.params[key], n_states=n_states, domain=domain, default_init=default
129
+ )
130
+ if theta0 is not None and cfg.params[key].init is None and spec.mode != "fixed":
131
+ spec = replace(spec, init=np.asarray(theta0[f"duration.{key}"]))
132
+ specs.append(spec)
133
+ if cov_idx:
134
+ specs.append(coef_spec("duration.c", n_states, len(cov_idx)))
135
+ return family, tuple(specs)
136
+
137
+ # --- numerics ---------------------------------------------------------------------------
138
+
139
+ def _adj(self, theta: Params, z_entry: Array | None) -> Array | None:
140
+ """Entry-time link `c_i . z_entry`: `(N,)` for one entry, `(T, N)` for `(T, K)`; `None` if unused."""
141
+ if z_entry is None or not self.cov_idx or "duration.c" not in theta:
142
+ return None
143
+ return z_entry[..., jnp.asarray(self.cov_idx)] @ theta["duration.c"].T
144
+
145
+ def _log_pmf_one(self, theta: Params, adj: Array | None, d_max: int, dt: float) -> Array:
146
+ raise NotImplementedError
147
+
148
+ def _tail_one(self, theta: Params, adj: Array | None, d_max: int, dt: float) -> Array:
149
+ raise NotImplementedError
150
+
151
+ def log_pmf(self, theta: Params, d_max: int, nominal_dt: float, z_entry: Array | None) -> Array:
152
+ """`(N, D_max)` log-pmf (`z_entry (K_d,)` or `None`), or `(T, N, D_max)` for `z_entry (T, K_d)`."""
153
+ adj = self._adj(theta, z_entry)
154
+ if adj is None or adj.ndim == 1:
155
+ return self._log_pmf_one(theta, adj, d_max, nominal_dt)
156
+ return jax.vmap(lambda a: self._log_pmf_one(theta, a, d_max, nominal_dt))(adj)
157
+
158
+ def tail_mass(self, theta: Params, d_max: int, nominal_dt: float, z_entry: Array | None = None) -> Array:
159
+ """Untruncated probability beyond `D_max`, `1 - F(D_max dt)`: `(N,)`, or `(T, N)`."""
160
+ adj = self._adj(theta, z_entry)
161
+ if adj is None or adj.ndim == 1:
162
+ return self._tail_one(theta, adj, d_max, nominal_dt)
163
+ return jax.vmap(lambda a: self._tail_one(theta, a, d_max, nominal_dt))(adj)
164
+
165
+ def mean_sojourn(self, theta: Params, nominal_dt: float) -> Array:
166
+ """`(N,)` analytic untruncated mean sojourn in clock units."""
167
+ raise NotImplementedError
168
+
169
+ def init_from_mean_sojourn(self, mean_steps: Array, nominal_dt: float) -> Params:
170
+ """`theta` whose analytic mean sojourn is `mean_steps` steps (per state)."""
171
+ raise NotImplementedError
172
+
173
+ def mean_sojourn_steps_truncated(
174
+ self, theta: Params, d_max: int, dt: float, z_entry: Array | None = None
175
+ ) -> Array:
176
+ """`(N,)` mean of the truncated, renormalized pmf, in steps: `sum_d d p(d)`."""
177
+ p = jnp.exp(self.log_pmf(theta, d_max, dt, z_entry))
178
+ d = jnp.arange(1, d_max + 1, dtype=jnp.float64)
179
+ return jnp.sum(p * d, axis=-1)
180
+
181
+
182
+ def check_d_max(
183
+ family: ExplicitDurationBase, theta: Params, d_max: int, nominal_dt: float, *, warn: bool = True
184
+ ) -> list[str]:
185
+ """`D_max` rule: flag truncated mass `> 1e-6` or `d_max < 2 x` mean sojourn (in steps).
186
+
187
+ Returns the messages and emits each as a `UserWarning` unless `warn=False`. Runs outside jit
188
+ (it concretizes values).
189
+ """
190
+ messages: list[str] = []
191
+ tail = float(jnp.max(family.tail_mass(theta, d_max, nominal_dt)))
192
+ if tail > D_MAX_TAIL_TOLERANCE:
193
+ messages.append(
194
+ f"model.d_max={d_max}: truncated duration mass {tail:.3g} exceeds {D_MAX_TAIL_TOLERANCE:g}"
195
+ )
196
+ mean_steps = float(jnp.max(family.mean_sojourn(theta, nominal_dt))) / nominal_dt
197
+ if d_max < D_MAX_SOJOURN_MULTIPLIER * mean_steps:
198
+ messages.append(
199
+ f"model.d_max={d_max} is below {D_MAX_SOJOURN_MULTIPLIER:g} x the mean sojourn "
200
+ f"({mean_steps:.1f} steps)"
201
+ )
202
+ if warn:
203
+ for message in messages:
204
+ warnings.warn(message, UserWarning, stacklevel=2)
205
+ return messages