ectype-data 0.1.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 (115) hide show
  1. ectype/__init__.py +134 -0
  2. ectype/_version.py +5 -0
  3. ectype/authoring/__init__.py +13 -0
  4. ectype/authoring/builder.py +134 -0
  5. ectype/authoring/spec.py +555 -0
  6. ectype/calibration/__init__.py +26 -0
  7. ectype/calibration/adjustments.py +539 -0
  8. ectype/calibration/calibrator.py +781 -0
  9. ectype/cli.py +1181 -0
  10. ectype/compiler/__init__.py +1 -0
  11. ectype/compiler/plan.py +678 -0
  12. ectype/errors.py +43 -0
  13. ectype/fingerprint/__init__.py +1 -0
  14. ectype/fingerprint/comparison.py +746 -0
  15. ectype/fingerprint/container.py +408 -0
  16. ectype/fingerprint/core.py +263 -0
  17. ectype/fingerprint/disclosure.py +207 -0
  18. ectype/fingerprint/expressions.py +1317 -0
  19. ectype/fingerprint/schema.py +645 -0
  20. ectype/fingerprint/targets.py +352 -0
  21. ectype/generation/__init__.py +1 -0
  22. ectype/generation/enforce.py +163 -0
  23. ectype/generation/generator.py +525 -0
  24. ectype/generation/identifiers.py +235 -0
  25. ectype/generation/manifest.py +71 -0
  26. ectype/generation/parallel.py +229 -0
  27. ectype/io/__init__.py +16 -0
  28. ectype/io/adapters.py +224 -0
  29. ectype/io/sql.py +289 -0
  30. ectype/io/values.py +269 -0
  31. ectype/llm/__init__.py +27 -0
  32. ectype/llm/authoring.py +766 -0
  33. ectype/llm/providers.py +269 -0
  34. ectype/models/__init__.py +8 -0
  35. ectype/models/base.py +120 -0
  36. ectype/models/chain.py +2426 -0
  37. ectype/models/copulas.py +254 -0
  38. ectype/models/encoding.py +1117 -0
  39. ectype/models/forest.py +1087 -0
  40. ectype/models/marginals.py +2099 -0
  41. ectype/models/mixtures.py +336 -0
  42. ectype/models/neural/__init__.py +21 -0
  43. ectype/models/neural/adapter.py +638 -0
  44. ectype/models/neural/vae.py +432 -0
  45. ectype/models/vines.py +608 -0
  46. ectype/plugins.py +40 -0
  47. ectype/privacy/__init__.py +49 -0
  48. ectype/privacy/attacks.py +599 -0
  49. ectype/privacy/dp.py +313 -0
  50. ectype/privacy/report.py +364 -0
  51. ectype/profiler.py +783 -0
  52. ectype/profiling/__init__.py +1 -0
  53. ectype/profiling/bivariate.py +130 -0
  54. ectype/profiling/calendar.py +743 -0
  55. ectype/profiling/conditional.py +263 -0
  56. ectype/profiling/constraints.py +661 -0
  57. ectype/profiling/entity.py +1143 -0
  58. ectype/profiling/functional.py +651 -0
  59. ectype/profiling/multivariate.py +492 -0
  60. ectype/profiling/personal.py +277 -0
  61. ectype/profiling/pseudonym.py +370 -0
  62. ectype/profiling/reference.py +334 -0
  63. ectype/profiling/sketches.py +653 -0
  64. ectype/profiling/structural.py +1087 -0
  65. ectype/profiling/structure.py +1733 -0
  66. ectype/profiling/sums.py +1710 -0
  67. ectype/profiling/tolerance.py +435 -0
  68. ectype/profiling/univariate.py +555 -0
  69. ectype/py.typed +0 -0
  70. ectype/registry.py +48 -0
  71. ectype/relational/__init__.py +61 -0
  72. ectype/relational/container.py +212 -0
  73. ectype/relational/fit.py +633 -0
  74. ectype/relational/generate.py +418 -0
  75. ectype/relational/schema.py +280 -0
  76. ectype/relational/validate.py +288 -0
  77. ectype/reporting/__init__.py +439 -0
  78. ectype/reporting/adapter.py +2003 -0
  79. ectype/reporting/charts.py +964 -0
  80. ectype/reporting/drift.py +902 -0
  81. ectype/reporting/findings.py +622 -0
  82. ectype/reporting/fmt.py +429 -0
  83. ectype/reporting/render.py +1705 -0
  84. ectype/reporting/select.py +84 -0
  85. ectype/reporting/style.py +272 -0
  86. ectype/reporting/view.py +593 -0
  87. ectype/rng.py +33 -0
  88. ectype/scenarios/__init__.py +30 -0
  89. ectype/scenarios/feasibility.py +411 -0
  90. ectype/scenarios/merge.py +1392 -0
  91. ectype/scenarios/mutate.py +1613 -0
  92. ectype/temporal/__init__.py +80 -0
  93. ectype/temporal/contract.py +221 -0
  94. ectype/temporal/detect.py +431 -0
  95. ectype/temporal/events.py +946 -0
  96. ectype/temporal/panel.py +937 -0
  97. ectype/temporal/pipeline.py +192 -0
  98. ectype/temporal/regular.py +674 -0
  99. ectype/types.py +46 -0
  100. ectype/validation/__init__.py +1 -0
  101. ectype/validation/metrics/__init__.py +7 -0
  102. ectype/validation/metrics/base.py +68 -0
  103. ectype/validation/metrics/bivariate.py +353 -0
  104. ectype/validation/metrics/missingness.py +54 -0
  105. ectype/validation/metrics/multivariate.py +265 -0
  106. ectype/validation/metrics/temporal.py +596 -0
  107. ectype/validation/metrics/univariate.py +514 -0
  108. ectype/validation/report.py +627 -0
  109. ectype/validation/validator.py +707 -0
  110. ectype_data-0.1.0.dist-info/METADATA +376 -0
  111. ectype_data-0.1.0.dist-info/RECORD +115 -0
  112. ectype_data-0.1.0.dist-info/WHEEL +4 -0
  113. ectype_data-0.1.0.dist-info/entry_points.txt +2 -0
  114. ectype_data-0.1.0.dist-info/licenses/LICENSE +192 -0
  115. ectype_data-0.1.0.dist-info/licenses/NOTICE +5 -0
@@ -0,0 +1,2099 @@
1
+ """Univariate marginal models (M7).
2
+
3
+ Every model is registered in ``MARGINALS`` and round-trips through ``ModelSpec`` + ``ArrayStore``.
4
+ All stored scalars and arrays are coarsened with the disclosure policy. Quantile functions are
5
+ deterministic math (``scipy.special`` / ``scipy.stats.*.ppf``), never library samplers, so
6
+ ``sample(n, rng) == ppf(rng.random(n))`` is stable within an engine version.
7
+
8
+ Value domains follow the engine conventions: continuous/discrete/datetime models work on float64 in
9
+ the natural scale; ``categorical`` works on integer codes ``0..k-1``.
10
+
11
+ ``mixed`` (ADR-0007) is the spike-and-slab model for columns that are neither a handful of values
12
+ nor smooth: point masses ("atoms": zeros, heaped round numbers) over a policy-limited quantile
13
+ slab whose draws are rounded to the column's granularity.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import math
19
+ from collections.abc import Callable
20
+ from typing import Any, ClassVar
21
+
22
+ import numpy as np
23
+ from scipy import special, stats
24
+ from scipy.optimize import minimize_scalar
25
+
26
+ from ectype.fingerprint.core import ArrayStore
27
+ from ectype.fingerprint.disclosure import (
28
+ OTHER,
29
+ clip_bounds,
30
+ coarse_summary,
31
+ coarsen,
32
+ coarsen_array,
33
+ needs_coarse_summary,
34
+ pool_categories,
35
+ quantile_levels,
36
+ resolve_policy,
37
+ support_clip_levels,
38
+ )
39
+ from ectype.fingerprint.schema import ColumnSchema, DisclosurePolicySpec, ModelSpec
40
+ from ectype.models.base import MARGINALS, MarginalModel
41
+ from ectype.types import LogicalType
42
+
43
+ U_MIN = 1e-12
44
+ U_MAX = 1.0 - 1e-12
45
+
46
+ __all__ = [
47
+ "NormalMarginal", "LognormalMarginal", "GammaMarginal", "BetaMarginal", "UniformMarginal",
48
+ "EmpiricalMarginal", "PoissonMarginal", "NegBinomMarginal", "DiscreteEmpiricalMarginal",
49
+ "CategoricalMarginal", "SummaryMarginal", "MixedMarginal", "PARAMETRIC_KINDS",
50
+ "detect_granularity", "point_masses",
51
+ ]
52
+
53
+ #: Kinds subject to goodness-of-fit rejection during selection (the rest are fallbacks).
54
+ PARAMETRIC_KINDS = frozenset({"normal", "lognormal", "gamma", "beta", "uniform", "poisson",
55
+ "negbinom"})
56
+
57
+
58
+ # ---------------------------------------------------------------------------------------------
59
+ # helpers
60
+ # ---------------------------------------------------------------------------------------------
61
+
62
+
63
+ def _clip_u(u: np.ndarray) -> np.ndarray:
64
+ return np.clip(np.asarray(u, dtype=np.float64), U_MIN, U_MAX)
65
+
66
+
67
+ def _as_x(x: np.ndarray) -> np.ndarray:
68
+ return np.asarray(x, dtype=np.float64)
69
+
70
+
71
+ def _clean(x: np.ndarray) -> np.ndarray:
72
+ a = np.asarray(x, dtype=np.float64).ravel()
73
+ a = a[np.isfinite(a)]
74
+ if a.size == 0:
75
+ raise ValueError("cannot fit a marginal to an empty array")
76
+ return a
77
+
78
+
79
+ def _c(x: float, policy: DisclosurePolicySpec) -> float:
80
+ return float(coarsen(float(x), policy))
81
+
82
+
83
+ def _opt(x: float) -> float | None:
84
+ """JSON-safe float: infinities become None."""
85
+ return float(x) if math.isfinite(x) else None
86
+
87
+
88
+ def _from_opt(x: Any, default: float) -> float:
89
+ return default if x is None else float(x)
90
+
91
+
92
+ def _shift_grid(x: np.ndarray, policy: DisclosurePolicySpec) -> list[float]:
93
+ """Candidate location shifts for 3-parameter families.
94
+
95
+ The grid is anchored at the policy clip quantile (never at the exact data minimum, which a
96
+ fitted shift just below it would reveal); the caller rejects candidates that are not below
97
+ the minimum. On non-negative data shifts stay >= 0 so the model's support stays non-negative
98
+ (with an exact zero in the data no valid shift exists and the family is not used).
99
+ """
100
+ lo = float(x.min())
101
+ ref = float(clip_bounds(x, policy)[0])
102
+ s = float(x.std()) or max(abs(ref), 1.0)
103
+ grid = [ref - s * f for f in (0.01, 0.03, 0.1, 0.3, 1.0, 3.0, 10.0)]
104
+ if lo >= 0.0:
105
+ grid = [g for g in grid if g >= 0.0]
106
+ if lo > 0.0:
107
+ grid.append(0.0)
108
+ return grid
109
+
110
+
111
+ def natural_bounds(a: np.ndarray) -> tuple[float, float]:
112
+ """Natural support of a column's values: ``[0, inf)`` for non-negative data, ``[0, 1]`` for
113
+ data in the unit interval, otherwise unbounded. Every ``ppf`` stays within it."""
114
+ lo = 0.0 if float(a.min()) >= 0.0 else -math.inf
115
+ hi = 1.0 if lo == 0.0 and float(a.max()) <= 1.0 else math.inf
116
+ return lo, hi
117
+
118
+
119
+ class _Parametric(MarginalModel):
120
+ """Shared to_spec/from_spec for models whose state is a handful of named scalars."""
121
+
122
+ _params: ClassVar[tuple[str, ...]] = ()
123
+
124
+ def __init__(self, **params: float) -> None:
125
+ for name in self._params:
126
+ setattr(self, name, float(params[name]))
127
+
128
+ @property
129
+ def n_parameters(self) -> int:
130
+ return len(self._params)
131
+
132
+ def params(self) -> dict[str, float]:
133
+ return {k: float(getattr(self, k)) for k in self._params}
134
+
135
+ def to_spec(self, store: ArrayStore, prefix: str) -> ModelSpec:
136
+ return ModelSpec(kind=self.kind, params=self.params())
137
+
138
+ @classmethod
139
+ def from_spec(cls, spec: ModelSpec, store: ArrayStore) -> MarginalModel:
140
+ return cls(**{k: float(spec.params[k]) for k in cls._params})
141
+
142
+ def __repr__(self) -> str:
143
+ inner = ", ".join(f"{k}={v:.6g}" for k, v in self.params().items())
144
+ return f"{type(self).__name__}({inner})"
145
+
146
+
147
+ # ---------------------------------------------------------------------------------------------
148
+ # continuous parametric
149
+ # ---------------------------------------------------------------------------------------------
150
+
151
+
152
+ @MARGINALS.register()
153
+ class NormalMarginal(_Parametric):
154
+ kind = "normal"
155
+ _params = ("mu", "sigma")
156
+ mu: float
157
+ sigma: float
158
+
159
+ #: natural support (see ``natural_bounds``); the mass beyond it is placed on the bound
160
+ lower_bound: float = -math.inf
161
+ upper_bound: float = math.inf
162
+
163
+ def __init__(self, *, lower_bound: float | None = None, upper_bound: float | None = None,
164
+ **params: float) -> None:
165
+ super().__init__(**params)
166
+ self.lower_bound = -math.inf if lower_bound is None else float(lower_bound)
167
+ self.upper_bound = math.inf if upper_bound is None else float(upper_bound)
168
+
169
+ @classmethod
170
+ def fit(cls, x, *, column=None, policy=None, rng=None) -> NormalMarginal:
171
+ pol = resolve_policy(policy)
172
+ a = _clean(x)
173
+ sd = float(a.std(ddof=1)) if a.size > 1 else 0.0
174
+ sd = max(sd, 1e-12 * max(1.0, abs(float(a.mean()))))
175
+ lo, hi = natural_bounds(a)
176
+ return cls(mu=_c(a.mean(), pol), sigma=_c(sd, pol), lower_bound=_opt(lo),
177
+ upper_bound=_opt(hi))
178
+
179
+ def to_spec(self, store: ArrayStore, prefix: str) -> ModelSpec:
180
+ params: dict[str, Any] = dict(self.params())
181
+ if math.isfinite(self.lower_bound):
182
+ params["lower_bound"] = self.lower_bound
183
+ if math.isfinite(self.upper_bound):
184
+ params["upper_bound"] = self.upper_bound
185
+ return ModelSpec(kind=self.kind, params=params)
186
+
187
+ @classmethod
188
+ def from_spec(cls, spec: ModelSpec, store: ArrayStore) -> NormalMarginal:
189
+ p = spec.params
190
+ return cls(mu=float(p["mu"]), sigma=float(p["sigma"]),
191
+ lower_bound=p.get("lower_bound"), upper_bound=p.get("upper_bound"))
192
+
193
+ def cdf(self, x):
194
+ xx = _as_x(x)
195
+ out = special.ndtr((xx - self.mu) / self.sigma)
196
+ return np.where(xx < self.lower_bound, 0.0, np.where(xx >= self.upper_bound, 1.0, out))
197
+
198
+ def ppf(self, u):
199
+ return np.clip(self.mu + self.sigma * special.ndtri(_clip_u(u)),
200
+ self.lower_bound, self.upper_bound)
201
+
202
+ def logpdf(self, x):
203
+ xx = _as_x(x)
204
+ z = (xx - self.mu) / self.sigma
205
+ lp = -0.5 * z * z - math.log(self.sigma) - 0.5 * math.log(2 * math.pi)
206
+ ok = (xx >= self.lower_bound) & (xx <= self.upper_bound)
207
+ return np.where(ok, lp, -np.inf)
208
+
209
+
210
+ @MARGINALS.register()
211
+ class LognormalMarginal(_Parametric):
212
+ """``shift + exp(N(mu, sigma))``."""
213
+
214
+ kind = "lognormal"
215
+ _params = ("shift", "mu", "sigma")
216
+ shift: float
217
+ mu: float
218
+ sigma: float
219
+
220
+ @staticmethod
221
+ def _fit_at(a: np.ndarray, shift: float) -> tuple[float, float, float]:
222
+ y = np.log(a - shift)
223
+ mu, sd = float(y.mean()), max(float(y.std()), 1e-12)
224
+ ll = float(np.sum(-0.5 * ((y - mu) / sd) ** 2 - math.log(sd) - y)) - a.size * 0.5 * math.log(
225
+ 2 * math.pi)
226
+ return mu, sd, ll
227
+
228
+ @classmethod
229
+ def fit(cls, x, *, column=None, policy=None, rng=None) -> LognormalMarginal:
230
+ pol = resolve_policy(policy)
231
+ a = _clean(x)
232
+ best = None
233
+ for shift in _shift_grid(a, pol):
234
+ shift = _c(shift, pol)
235
+ if not np.all(a > shift):
236
+ continue
237
+ mu, sd, ll = cls._fit_at(a, shift)
238
+ if best is None or ll > best[3]:
239
+ best = (shift, mu, sd, ll)
240
+ if best is None:
241
+ raise ValueError("lognormal: no valid shift")
242
+ return cls(shift=best[0], mu=_c(best[1], pol), sigma=_c(best[2], pol))
243
+
244
+ def cdf(self, x):
245
+ y = _as_x(x) - self.shift
246
+ with np.errstate(divide="ignore", invalid="ignore"):
247
+ z = (np.log(np.where(y > 0, y, 1.0)) - self.mu) / self.sigma
248
+ return np.where(y > 0, special.ndtr(z), 0.0)
249
+
250
+ def ppf(self, u):
251
+ return self.shift + np.exp(self.mu + self.sigma * special.ndtri(_clip_u(u)))
252
+
253
+ def logpdf(self, x):
254
+ y = _as_x(x) - self.shift
255
+ ok = y > 0
256
+ ly = np.log(np.where(ok, y, 1.0))
257
+ z = (ly - self.mu) / self.sigma
258
+ lp = -0.5 * z * z - math.log(self.sigma) - 0.5 * math.log(2 * math.pi) - ly
259
+ return np.where(ok, lp, -np.inf)
260
+
261
+
262
+ @MARGINALS.register()
263
+ class GammaMarginal(_Parametric):
264
+ """``loc + Gamma(shape=a, scale)``."""
265
+
266
+ kind = "gamma"
267
+ _params = ("loc", "a", "scale")
268
+ loc: float
269
+ a: float
270
+ scale: float
271
+
272
+ @classmethod
273
+ def fit(cls, x, *, column=None, policy=None, rng=None) -> GammaMarginal:
274
+ pol = resolve_policy(policy)
275
+ d = _clean(x)
276
+ best = None
277
+ for loc in _shift_grid(d, pol):
278
+ loc = _c(loc, pol)
279
+ y = d - loc
280
+ if not np.all(y > 0):
281
+ continue
282
+ # closed-form-ish MLE for the shape (Minka's approximation + Newton steps)
283
+ m = float(y.mean())
284
+ s = math.log(m) - float(np.log(y).mean())
285
+ if s <= 0:
286
+ continue
287
+ k = (3 - s + math.sqrt((s - 3) ** 2 + 24 * s)) / (12 * s)
288
+ for _ in range(5):
289
+ k_new = k - (math.log(k) - special.digamma(k) - s) / (1 / k - special.polygamma(1, k))
290
+ k = k_new if k_new > 0 else k / 2
291
+ k = min(max(k, 1e-3), 1e7)
292
+ scale = m / k
293
+ ll = float(np.sum(stats.gamma.logpdf(y, k, scale=scale)))
294
+ if best is None or ll > best[3]:
295
+ best = (loc, k, scale, ll)
296
+ if best is None:
297
+ raise ValueError("gamma: no valid location")
298
+ return cls(loc=best[0], a=_c(best[1], pol), scale=_c(best[2], pol))
299
+
300
+ def cdf(self, x):
301
+ y = np.maximum((_as_x(x) - self.loc) / self.scale, 0.0)
302
+ return special.gammainc(self.a, y)
303
+
304
+ def ppf(self, u):
305
+ return self.loc + self.scale * special.gammaincinv(self.a, _clip_u(u))
306
+
307
+ def logpdf(self, x):
308
+ y = (_as_x(x) - self.loc) / self.scale
309
+ ok = y > 0
310
+ yy = np.where(ok, y, 1.0)
311
+ lp = (self.a - 1) * np.log(yy) - yy - special.gammaln(self.a) - math.log(self.scale)
312
+ return np.where(ok, lp, -np.inf)
313
+
314
+
315
+ def _beta_support(a: np.ndarray, column: ColumnSchema | None,
316
+ pol: DisclosurePolicySpec) -> tuple[float, float]:
317
+ lo_d, hi_d = float(a.min()), float(a.max())
318
+ if (column is not None and column.min_value is not None and column.max_value is not None
319
+ and column.min_value <= lo_d and hi_d <= column.max_value
320
+ and column.max_value > column.min_value):
321
+ return float(column.min_value), float(column.max_value)
322
+ if lo_d >= 0.0 and hi_d <= 1.0:
323
+ return 0.0, 1.0
324
+ pad = 0.01 * max(hi_d - lo_d, 1e-12)
325
+ lo, hi = _c(lo_d - pad, pol), _c(hi_d + pad, pol)
326
+ if lo_d >= 0.0:
327
+ lo = max(lo, 0.0) # natural support of non-negative data
328
+ return lo, hi
329
+
330
+
331
+ def is_bounded(x: np.ndarray, column: ColumnSchema | None) -> bool:
332
+ """Whether a beta (bounded-support) candidate is appropriate."""
333
+ a = np.asarray(x, dtype=float)
334
+ a = a[np.isfinite(a)]
335
+ if a.size == 0:
336
+ return False
337
+ if a.min() >= 0.0 and a.max() <= 1.0:
338
+ return True
339
+ return bool(column is not None and column.min_value is not None
340
+ and column.max_value is not None and column.max_value > column.min_value
341
+ and column.min_value <= a.min() and a.max() <= column.max_value)
342
+
343
+
344
+ @MARGINALS.register()
345
+ class BetaMarginal(_Parametric):
346
+ """``lo + (hi - lo) * Beta(a, b)``."""
347
+
348
+ kind = "beta"
349
+ _params = ("lo", "hi", "a", "b")
350
+ lo: float
351
+ hi: float
352
+ a: float
353
+ b: float
354
+
355
+ @classmethod
356
+ def fit(cls, x, *, column=None, policy=None, rng=None) -> BetaMarginal:
357
+ pol = resolve_policy(policy)
358
+ d = _clean(x)
359
+ lo, hi = _beta_support(d, column, pol)
360
+ y = np.clip((d - lo) / (hi - lo), 1e-6, 1 - 1e-6)
361
+ m, v = float(y.mean()), float(y.var())
362
+ common = m * (1 - m) / max(v, 1e-12) - 1
363
+ a0, b0 = max(m * common, 1e-2), max((1 - m) * common, 1e-2)
364
+ la, lb = np.log(y).sum(), np.log1p(-y).sum()
365
+ n = y.size
366
+
367
+ def nll(t: np.ndarray) -> float:
368
+ a, b = math.exp(t[0]), math.exp(t[1])
369
+ return -((a - 1) * la + (b - 1) * lb - n * special.betaln(a, b))
370
+
371
+ from scipy.optimize import minimize
372
+
373
+ res = minimize(nll, np.log([a0, b0]), method="Nelder-Mead",
374
+ options={"xatol": 1e-6, "fatol": 1e-8, "maxiter": 400})
375
+ a, b = float(np.exp(res.x[0])), float(np.exp(res.x[1]))
376
+ return cls(lo=_c(lo, pol), hi=_c(hi, pol), a=_c(a, pol), b=_c(b, pol))
377
+
378
+ def _y(self, x):
379
+ return (_as_x(x) - self.lo) / (self.hi - self.lo)
380
+
381
+ def cdf(self, x):
382
+ return special.betainc(self.a, self.b, np.clip(self._y(x), 0.0, 1.0))
383
+
384
+ def ppf(self, u):
385
+ return self.lo + (self.hi - self.lo) * special.betaincinv(self.a, self.b, _clip_u(u))
386
+
387
+ def logpdf(self, x):
388
+ y = self._y(x)
389
+ ok = (y > 0) & (y < 1)
390
+ yy = np.where(ok, y, 0.5)
391
+ lp = ((self.a - 1) * np.log(yy) + (self.b - 1) * np.log1p(-yy)
392
+ - special.betaln(self.a, self.b) - math.log(self.hi - self.lo))
393
+ return np.where(ok, lp, -np.inf)
394
+
395
+
396
+ @MARGINALS.register()
397
+ class UniformMarginal(_Parametric):
398
+ kind = "uniform"
399
+ _params = ("lo", "hi")
400
+ lo: float
401
+ hi: float
402
+
403
+ @classmethod
404
+ def fit(cls, x, *, column=None, policy=None, rng=None) -> UniformMarginal:
405
+ pol = resolve_policy(policy)
406
+ d = _clean(x)
407
+ plo, phi = support_clip_levels(d.size, pol)
408
+ qlo, qhi = np.quantile(d, [plo, phi])
409
+ # extrapolate the support from the policy clip quantiles (no exact extremes stored)
410
+ width = max(float(qhi - qlo) / (phi - plo), 1e-12)
411
+ lo = float(qlo) - plo * width
412
+ hi = float(qhi) + (1 - phi) * width
413
+ # pad by ~3 s.e. of the clip quantiles so held-out values rarely fall outside
414
+ n = max(d.size, 1)
415
+ pad = width * (1.0 / n + 3.0 * math.sqrt(max(plo, 1 - phi, 1.0 / n) / n))
416
+ nat_lo, nat_hi = natural_bounds(d)
417
+ return cls(lo=max(_c(lo - pad, pol), nat_lo), hi=min(_c(hi + pad, pol), nat_hi))
418
+
419
+ def cdf(self, x):
420
+ return np.clip((_as_x(x) - self.lo) / (self.hi - self.lo), 0.0, 1.0)
421
+
422
+ def ppf(self, u):
423
+ return self.lo + (self.hi - self.lo) * _clip_u(u)
424
+
425
+ def logpdf(self, x):
426
+ xx = _as_x(x)
427
+ ok = (xx >= self.lo) & (xx <= self.hi)
428
+ return np.where(ok, -math.log(self.hi - self.lo), -np.inf)
429
+
430
+
431
+ # ---------------------------------------------------------------------------------------------
432
+ # empirical (policy-limited quantile grid + exponential tails)
433
+ # ---------------------------------------------------------------------------------------------
434
+
435
+
436
+ #: datetime tails end this many exponential tail scales beyond the clip quantile (at least the
437
+ #: uniform-tail extrapolation), so synthetic dates stay near the source range
438
+ DATETIME_TAIL_SCALES = 2.0
439
+
440
+
441
+ def _datetime_tail_pads(levels: np.ndarray, q: np.ndarray) -> tuple[float, float]:
442
+ """Distances beyond the outer stored quantiles at which datetime tails are truncated. Only
443
+ stored (policy-safe) quantiles are used: the larger of the uniform-tail extrapolation
444
+ ``p0 * (qk - q0) / (pk - p0)`` and ``DATETIME_TAIL_SCALES`` exponential tail scales."""
445
+ plo, phi = float(levels[0]), float(levels[-1])
446
+ w = float(q[-1] - q[0]) / max(phi - plo, 1e-12)
447
+ lo_pad, hi_pad = plo * w, (1.0 - phi) * w
448
+ if q.size >= 2 and plo > 0 and levels[1] > plo:
449
+ lo_pad = max(lo_pad, DATETIME_TAIL_SCALES * float(q[1] - q[0])
450
+ / math.log(float(levels[1]) / plo))
451
+ if q.size >= 2 and phi < 1 and levels[-2] < phi:
452
+ hi_pad = max(hi_pad, DATETIME_TAIL_SCALES * float(q[-1] - q[-2])
453
+ / math.log((1.0 - float(levels[-2])) / (1.0 - phi)))
454
+ return lo_pad, hi_pad
455
+
456
+
457
+ @MARGINALS.register()
458
+ class EmpiricalMarginal(MarginalModel):
459
+ """Quantile grid at ``disclosure.quantile_levels`` with linear interpolation inside and
460
+ (optionally truncated) exponential tails beyond the tail-clip levels.
461
+
462
+ Lower tail (``x < q0``, level ``p0``): ``F(x) = p0 (e^{(x-q0)/b} - c) / (1 - c)`` with
463
+ ``c = e^{(L-q0)/b}`` for a known lower bound ``L`` (``c = 0`` if unbounded). The scale ``b``
464
+ is fitted from the clip quantile and the adjacent spacing: ``b = (q1-q0)/log(p1/p0)``.
465
+ The upper tail mirrors this.
466
+ """
467
+
468
+ kind = "empirical"
469
+
470
+ def __init__(self, levels: np.ndarray, quantiles: np.ndarray, lower_scale: float = 0.0,
471
+ upper_scale: float = 0.0, lower_bound: float = -math.inf,
472
+ upper_bound: float = math.inf) -> None:
473
+ self.levels = np.asarray(levels, dtype=np.float64)
474
+ self.quantiles = np.maximum.accumulate(np.asarray(quantiles, dtype=np.float64))
475
+ if self.levels.size < 2 or self.levels.size != self.quantiles.size:
476
+ raise ValueError("empirical: need >= 2 levels and matching quantiles")
477
+ self.lower_scale = float(lower_scale)
478
+ self.upper_scale = float(upper_scale)
479
+ self.lower_bound = float(min(lower_bound, self.quantiles[0]))
480
+ self.upper_bound = float(max(upper_bound, self.quantiles[-1]))
481
+
482
+ # -- fitting -----------------------------------------------------------------------------
483
+ @classmethod
484
+ def fit(cls, x, *, column=None, policy=None, rng=None) -> MarginalModel:
485
+ """Fit the grid; on a column with too few rows for a safe grid
486
+ (``disclosure.needs_coarse_summary``) return a ``SummaryMarginal`` instead."""
487
+ pol = resolve_policy(policy)
488
+ a = _clean(x)
489
+ if needs_coarse_summary(a.size, pol):
490
+ return SummaryMarginal.fit(a, column=column, policy=pol, rng=rng)
491
+ return cls._fit_grid(a, column, pol)
492
+
493
+ @classmethod
494
+ def _fit_grid(cls, a: np.ndarray, column: ColumnSchema | None, pol: DisclosurePolicySpec,
495
+ *, quantiles: Callable[[np.ndarray], np.ndarray] | None = None,
496
+ pad: float = 0.0, floor: float = -math.inf,
497
+ cap: float = math.inf) -> EmpiricalMarginal:
498
+ """The grid for the values ``a``. The keywords serve the mixed model, which fits its
499
+ slab to rows spread over their rounding cells (``_fit_slab``): ``quantiles`` replaces
500
+ the sample quantiles of ``a`` (a function of the grid levels), ``floor`` and ``cap``
501
+ are further bounds on the values, and ``pad`` moves every finite bound outwards (the
502
+ spread rows reach half a step beyond the recorded values)."""
503
+ levels = quantile_levels(a.size, pol)
504
+ raw = np.quantile(a, levels) if quantiles is None else quantiles(levels)
505
+ q = np.maximum.accumulate(coarsen_array(raw, pol))
506
+ lower, upper = -math.inf, math.inf
507
+ if column is not None:
508
+ if (column.logical_type in (LogicalType.CONTINUOUS, LogicalType.DISCRETE)
509
+ and a.min() >= 0.0):
510
+ lower = 0.0
511
+ if column.min_value is not None and a.min() >= column.min_value:
512
+ lower = max(lower, float(column.min_value))
513
+ if column.max_value is not None and a.max() <= column.max_value:
514
+ upper = float(column.max_value)
515
+ if is_bounded(a, column):
516
+ nat_lo, nat_hi = natural_bounds(a) # e.g. [0, 1] for shares
517
+ lower, upper = max(lower, nat_lo), min(upper, nat_hi)
518
+ if column.logical_type == LogicalType.DATETIME:
519
+ lo_pad, hi_pad = _datetime_tail_pads(levels, q)
520
+ lower = max(lower, _c(q[0] - lo_pad, pol))
521
+ upper = min(upper, _c(q[-1] + hi_pad, pol))
522
+ elif a.min() >= 0.0:
523
+ lower = 0.0
524
+ lower, upper = max(lower, floor), min(upper, cap)
525
+ if pad > 0:
526
+ # a draw of exactly ``bound - pad`` would round to the step below the bound
527
+ if math.isfinite(lower):
528
+ lower = float(np.nextafter(lower - pad, math.inf))
529
+ if math.isfinite(upper):
530
+ upper = upper + pad
531
+ q = np.clip(q, lower, upper) # coarsening can move a quantile past them
532
+ lower, upper = min(lower, q[0]), max(upper, q[-1])
533
+ b_lo = b_hi = 0.0
534
+ if levels[0] > 0 and q[1] > q[0] and q[0] > lower:
535
+ b_lo = (q[1] - q[0]) / math.log(levels[1] / levels[0])
536
+ if levels[-1] < 1 and q[-1] > q[-2] and q[-1] < upper:
537
+ b_hi = (q[-1] - q[-2]) / math.log((1 - levels[-2]) / (1 - levels[-1]))
538
+ return cls(levels, q, _c(b_lo, pol), _c(b_hi, pol), lower, upper)
539
+
540
+ # -- tails ------------------------------------------------------------------------------
541
+ def _edge_scales(self) -> tuple[float, float]:
542
+ """Exponential scales of the first/last grid segments. When a tail is active, these
543
+ segments are interpolated exponentially (log-linear in the tail probability) instead of
544
+ linearly: the curve passes through both segment end points and joins the tail smoothly,
545
+ which matters for heavy tails where the outer grid spacing is wide."""
546
+ lv, q = self.levels, self.quantiles
547
+ b0 = b1 = 0.0
548
+ if q.size >= 4:
549
+ if self.lower_scale > 0 and lv[0] > 0 and q[1] > q[0]:
550
+ b0 = float((q[1] - q[0]) / math.log(lv[1] / lv[0]))
551
+ if self.upper_scale > 0 and lv[-1] < 1 and q[-1] > q[-2]:
552
+ b1 = float((q[-1] - q[-2]) / math.log((1 - lv[-2]) / (1 - lv[-1])))
553
+ return b0, b1
554
+
555
+ def _lower_c(self) -> float:
556
+ b, q0 = self.lower_scale, self.quantiles[0]
557
+ return math.exp((self.lower_bound - q0) / b) if math.isfinite(self.lower_bound) else 0.0
558
+
559
+ def _upper_c(self) -> float:
560
+ b, qk = self.upper_scale, self.quantiles[-1]
561
+ return math.exp((qk - self.upper_bound) / b) if math.isfinite(self.upper_bound) else 0.0
562
+
563
+ def cdf(self, x):
564
+ x = _as_x(x)
565
+ lv, q = self.levels, self.quantiles
566
+ k = q.size - 1
567
+ i = np.clip(np.searchsorted(q, x, side="right") - 1, 0, k - 1)
568
+ dq = q[i + 1] - q[i]
569
+ with np.errstate(divide="ignore", invalid="ignore"):
570
+ frac = np.where(dq > 0, (x - q[i]) / np.where(dq > 0, dq, 1.0), 1.0)
571
+ out = lv[i] + np.clip(frac, 0.0, 1.0) * (lv[i + 1] - lv[i])
572
+ p0, pk = lv[0], lv[-1]
573
+ e0, e1 = self._edge_scales()
574
+ if e0 > 0:
575
+ seg = (x >= q[0]) & (x < q[1])
576
+ out[seg] = p0 * np.exp((x[seg] - q[0]) / e0)
577
+ if e1 > 0:
578
+ seg = (x > q[-2]) & (x <= q[-1])
579
+ out[seg] = 1 - (1 - pk) * np.exp((q[-1] - x[seg]) / e1)
580
+ below, above = x < q[0], x > q[-1]
581
+ if not (self.upper_scale > 0 and pk < 1):
582
+ # no upper tail: ppf puts the mass beyond pk at q[-1]
583
+ out[x >= q[-1]] = 1.0
584
+ if below.any():
585
+ if self.lower_scale > 0 and p0 > 0:
586
+ b, c = self.lower_scale, self._lower_c()
587
+ e = np.exp(np.minimum((x[below] - q[0]) / b, 0.0))
588
+ t = np.clip((e - c) / (1 - c), 0.0, 1.0)
589
+ out[below] = p0 * t
590
+ else:
591
+ out[below] = 0.0
592
+ if above.any():
593
+ if self.upper_scale > 0 and pk < 1:
594
+ b, c = self.upper_scale, self._upper_c()
595
+ e = np.exp(np.minimum((q[-1] - x[above]) / b, 0.0))
596
+ t = np.clip((e - c) / (1 - c), 0.0, 1.0)
597
+ out[above] = 1 - (1 - pk) * t
598
+ else:
599
+ out[above] = 1.0
600
+ return out
601
+
602
+ def cdf_left(self, x):
603
+ """``P(X < x)``: the grid CDF is continuous except where quantiles repeat (a plateau
604
+ ``q[j] = ... = q[l]`` is an atom of mass ``lv[l] - lv[j]``), at a lower bound carrying
605
+ the whole lower tail, and at ``q[-1]`` without an upper tail. Randomized PIT needs
606
+ these jumps to spread tied values (e.g. a zero-inflated integer column)."""
607
+ x = _as_x(x)
608
+ out = np.asarray(self.cdf(x), dtype=np.float64).copy()
609
+ lv, q = self.levels, self.quantiles
610
+ j = np.searchsorted(q, x, side="left")
611
+ hit = j < q.size
612
+ hit[hit] = q[j[hit]] == x[hit]
613
+ if hit.any():
614
+ jj = j[hit]
615
+ first = 0.0
616
+ if self.lower_scale > 0 and lv[0] > 0 and self._lower_c() < 1.0:
617
+ first = float(lv[0])
618
+ out[hit] = np.minimum(out[hit], np.where(jj == 0, first, lv[jj]))
619
+ return out
620
+
621
+ def ppf(self, u):
622
+ u = _clip_u(u)
623
+ lv, q = self.levels, self.quantiles
624
+ out = np.interp(u, lv, q)
625
+ p0, pk = lv[0], lv[-1]
626
+ e0, e1 = self._edge_scales()
627
+ if e0 > 0:
628
+ seg = (u >= p0) & (u < lv[1])
629
+ out[seg] = q[0] + e0 * np.log(u[seg] / p0)
630
+ if e1 > 0:
631
+ seg = (u > lv[-2]) & (u <= pk)
632
+ out[seg] = q[-1] - e1 * np.log((1 - u[seg]) / (1 - pk))
633
+ lo, hi = u < p0, u > pk
634
+ if lo.any() and self.lower_scale > 0:
635
+ c = self._lower_c()
636
+ t = u[lo] / p0
637
+ out[lo] = q[0] + self.lower_scale * np.log(c + t * (1 - c))
638
+ elif lo.any():
639
+ out[lo] = q[0]
640
+ if hi.any() and self.upper_scale > 0:
641
+ c = self._upper_c()
642
+ t = (1 - u[hi]) / (1 - pk)
643
+ out[hi] = q[-1] - self.upper_scale * np.log(c + t * (1 - c))
644
+ elif hi.any():
645
+ out[hi] = q[-1]
646
+ return np.clip(out, self.lower_bound, self.upper_bound)
647
+
648
+ def logpdf(self, x):
649
+ x = _as_x(x)
650
+ lv, q = self.levels, self.quantiles
651
+ k = q.size - 1
652
+ span = max(q[-1] - q[0], 1e-12)
653
+ i = np.clip(np.searchsorted(q, x, side="right") - 1, 0, k - 1)
654
+ dq = np.maximum(q[i + 1] - q[i], 1e-9 * span)
655
+ dens = (lv[i + 1] - lv[i]) / dq
656
+ p0, pk = lv[0], lv[-1]
657
+ e0, e1 = self._edge_scales()
658
+ if e0 > 0:
659
+ seg = (x >= q[0]) & (x < q[1])
660
+ dens[seg] = p0 / e0 * np.exp((x[seg] - q[0]) / e0)
661
+ if e1 > 0:
662
+ seg = (x > q[-2]) & (x <= q[-1])
663
+ dens[seg] = (1 - pk) / e1 * np.exp((q[-1] - x[seg]) / e1)
664
+ below, above = x < q[0], x > q[-1]
665
+ if below.any():
666
+ if self.lower_scale > 0 and p0 > 0:
667
+ b, c = self.lower_scale, self._lower_c()
668
+ ok = x[below] >= self.lower_bound
669
+ d = p0 / b * np.exp((x[below] - q[0]) / b) / (1 - c)
670
+ dens[below] = np.where(ok, d, 0.0)
671
+ else:
672
+ dens[below] = 0.0
673
+ if above.any():
674
+ if self.upper_scale > 0 and pk < 1:
675
+ b, c = self.upper_scale, self._upper_c()
676
+ ok = x[above] <= self.upper_bound
677
+ d = (1 - pk) / b * np.exp((q[-1] - x[above]) / b) / (1 - c)
678
+ dens[above] = np.where(ok, d, 0.0)
679
+ else:
680
+ dens[above] = 0.0
681
+ with np.errstate(divide="ignore"):
682
+ return np.log(dens)
683
+
684
+ @property
685
+ def n_parameters(self) -> int:
686
+ return int(self.quantiles.size + 4)
687
+
688
+ def to_spec(self, store: ArrayStore, prefix: str) -> ModelSpec:
689
+ return ModelSpec(
690
+ kind=self.kind,
691
+ params={"lower_scale": self.lower_scale, "upper_scale": self.upper_scale,
692
+ "lower_bound": _opt(self.lower_bound), "upper_bound": _opt(self.upper_bound)},
693
+ arrays={"levels": store.put(f"{prefix}levels", self.levels),
694
+ "quantiles": store.put(f"{prefix}quantiles", self.quantiles)},
695
+ )
696
+
697
+ @classmethod
698
+ def from_spec(cls, spec: ModelSpec, store: ArrayStore) -> EmpiricalMarginal:
699
+ p = spec.params
700
+ return cls(store.get(spec.arrays["levels"]), store.get(spec.arrays["quantiles"]),
701
+ float(p.get("lower_scale", 0.0)), float(p.get("upper_scale", 0.0)),
702
+ _from_opt(p.get("lower_bound"), -math.inf),
703
+ _from_opt(p.get("upper_bound"), math.inf))
704
+
705
+
706
+ # ---------------------------------------------------------------------------------------------
707
+ # small tables: coarse location/scale summary
708
+ # ---------------------------------------------------------------------------------------------
709
+
710
+
711
+ #: a positive column whose sample skewness exceeds this is summarised on the log scale
712
+ SUMMARY_LOG_SKEW = 1.0
713
+
714
+
715
+ @MARGINALS.register()
716
+ class SummaryMarginal(MarginalModel):
717
+ """Coarse location/scale summary for columns with too few rows to store a quantile grid
718
+ (``disclosure.needs_coarse_summary``): a normal with the stored mean and standard deviation
719
+ (``disclosure.coarse_summary``), on the log scale for strongly right-skewed positive data,
720
+ truncated to the column's natural support (``natural_bounds``: ``[0, inf)`` for
721
+ non-negative data, ``[0, 1]`` for shares). No quantile or extreme of the data is stored.
722
+ Discrete columns are rounded on output by their codec.
723
+ """
724
+
725
+ kind = "summary"
726
+
727
+ def __init__(self, loc: float, scale: float, log_scale: bool = False,
728
+ lower_bound: float = -math.inf, upper_bound: float = math.inf) -> None:
729
+ self.loc = float(loc)
730
+ self.scale = max(float(scale), 1e-12 * max(1.0, abs(float(loc))))
731
+ self.log_scale = bool(log_scale)
732
+ self.lower_bound = float(lower_bound)
733
+ self.upper_bound = float(upper_bound)
734
+ if self.log_scale:
735
+ self.lower_bound = max(self.lower_bound, 0.0)
736
+ z = self._z(np.array([self.lower_bound, self.upper_bound]))
737
+ self._p_lo = float(special.ndtr(z[0])) if math.isfinite(self.lower_bound) else 0.0
738
+ self._p_hi = float(special.ndtr(z[1])) if math.isfinite(self.upper_bound) else 1.0
739
+ if not self._p_hi > self._p_lo: # support far out in a tail: drop the truncation
740
+ self._p_lo, self._p_hi = 0.0, 1.0
741
+
742
+ def _z(self, x: np.ndarray) -> np.ndarray:
743
+ x = _as_x(x)
744
+ if self.log_scale:
745
+ with np.errstate(divide="ignore", invalid="ignore"):
746
+ x = np.where(x > 0, np.log(np.where(x > 0, x, 1.0)), -np.inf)
747
+ return (x - self.loc) / self.scale
748
+
749
+ @classmethod
750
+ def fit(cls, x, *, column=None, policy=None, rng=None) -> SummaryMarginal:
751
+ pol = resolve_policy(policy)
752
+ a = _clean(x)
753
+ lo, hi = natural_bounds(a)
754
+ log_scale = False
755
+ if a.size >= 3 and float(a.min()) > 0.0 and float(a.std()) > 0.0:
756
+ log_scale = bool(stats.skew(a) > SUMMARY_LOG_SKEW)
757
+ loc, scale = coarse_summary(a, pol, log_scale=log_scale)
758
+ return cls(loc, scale, log_scale, lo, hi)
759
+
760
+ def cdf(self, x):
761
+ xx = _as_x(x)
762
+ p = special.ndtr(self._z(xx))
763
+ out = (np.clip(p, self._p_lo, self._p_hi) - self._p_lo) / (self._p_hi - self._p_lo)
764
+ return np.where(xx < self.lower_bound, 0.0, np.where(xx >= self.upper_bound, 1.0, out))
765
+
766
+ def ppf(self, u):
767
+ p = self._p_lo + _clip_u(u) * (self._p_hi - self._p_lo)
768
+ y = self.loc + self.scale * special.ndtri(_clip_u(p))
769
+ if self.log_scale:
770
+ y = np.exp(y)
771
+ return np.clip(y, self.lower_bound, self.upper_bound)
772
+
773
+ def logpdf(self, x):
774
+ xx = _as_x(x)
775
+ z = self._z(xx)
776
+ with np.errstate(invalid="ignore"):
777
+ lp = (-0.5 * z * z - math.log(self.scale) - 0.5 * math.log(2 * math.pi)
778
+ - math.log(self._p_hi - self._p_lo))
779
+ ok = (xx >= self.lower_bound) & (xx <= self.upper_bound)
780
+ if self.log_scale:
781
+ ok &= xx > 0
782
+ lp = lp - np.log(np.where(xx > 0, xx, 1.0))
783
+ return np.where(ok, lp, -np.inf)
784
+
785
+ @property
786
+ def n_parameters(self) -> int:
787
+ return 2
788
+
789
+ def to_spec(self, store: ArrayStore, prefix: str) -> ModelSpec:
790
+ return ModelSpec(kind=self.kind, params={
791
+ "loc": self.loc, "scale": self.scale, "log_scale": self.log_scale,
792
+ "lower_bound": _opt(self.lower_bound), "upper_bound": _opt(self.upper_bound)})
793
+
794
+ @classmethod
795
+ def from_spec(cls, spec: ModelSpec, store: ArrayStore) -> SummaryMarginal:
796
+ p = spec.params
797
+ return cls(float(p["loc"]), float(p["scale"]), bool(p.get("log_scale", False)),
798
+ _from_opt(p.get("lower_bound"), -math.inf),
799
+ _from_opt(p.get("upper_bound"), math.inf))
800
+
801
+ def __repr__(self) -> str:
802
+ return (f"SummaryMarginal(loc={self.loc:.6g}, scale={self.scale:.6g}, "
803
+ f"log_scale={self.log_scale})")
804
+
805
+
806
+ # ---------------------------------------------------------------------------------------------
807
+ # discrete
808
+ # ---------------------------------------------------------------------------------------------
809
+
810
+
811
+ def _check_integer(a: np.ndarray, kind: str) -> None:
812
+ if not np.all(a == np.round(a)):
813
+ raise ValueError(f"{kind}: data must be integer-valued")
814
+
815
+
816
+ @MARGINALS.register()
817
+ class PoissonMarginal(_Parametric):
818
+ kind = "poisson"
819
+ discrete = True
820
+ _params = ("lam",)
821
+ lam: float
822
+
823
+ @classmethod
824
+ def fit(cls, x, *, column=None, policy=None, rng=None) -> PoissonMarginal:
825
+ pol = resolve_policy(policy)
826
+ a = _clean(x)
827
+ _check_integer(a, cls.kind)
828
+ if a.min() < 0:
829
+ raise ValueError("poisson: data must be non-negative")
830
+ return cls(lam=_c(max(float(a.mean()), 1e-9), pol))
831
+
832
+ def cdf(self, x):
833
+ k = np.floor(_as_x(x))
834
+ return np.where(k >= 0, special.pdtr(np.maximum(k, 0.0), self.lam), 0.0)
835
+
836
+ def cdf_left(self, x):
837
+ return self.cdf(np.ceil(_as_x(x)) - 1.0)
838
+
839
+ def ppf(self, u):
840
+ return np.asarray(stats.poisson.ppf(_clip_u(u), self.lam), dtype=np.float64)
841
+
842
+ def logpdf(self, x):
843
+ return stats.poisson.logpmf(_as_x(x), self.lam)
844
+
845
+
846
+ def _count_shift(a: np.ndarray, policy: DisclosurePolicySpec) -> float:
847
+ """Integer origin for shifted counts that does not reveal the exact minimum: the policy clip
848
+ quantile rounded down to a coarse power-of-ten grid (sized by the clip spread, and never
849
+ finer than the policy's significant digits), stepped further down until it is at or below
850
+ every value. Counts that start near 0 get 0."""
851
+ plo, phi = support_clip_levels(a.size, policy)
852
+ lo, hi = (float(q) for q in np.quantile(a, [plo, phi]))
853
+ amin = float(a.min())
854
+ step = 10.0 ** max(0, math.floor(math.log10(max(hi - lo, 1.0))))
855
+ if lo != 0.0:
856
+ digits = math.floor(math.log10(abs(lo))) - policy.significant_digits + 1
857
+ step = max(step, 10.0 ** max(0, digits))
858
+ shift = math.floor(lo / step) * step
859
+ if shift > amin:
860
+ shift -= math.ceil((shift - amin) / step) * step
861
+ if amin >= 0.0:
862
+ shift = max(shift, 0.0)
863
+ return float(shift)
864
+
865
+
866
+ @MARGINALS.register()
867
+ class NegBinomMarginal(_Parametric):
868
+ """``shift + NB(r, mean=mu)``: ``P(Y=k) = C(k+r-1, k) p^r (1-p)^k`` with ``p = r/(r+mu)``.
869
+
870
+ Parameterised by the mean (not ``p``) so coarsening keeps the mean accurate when ``r`` is
871
+ large (the near-Poisson limit). ``shift`` is an integer.
872
+ """
873
+
874
+ kind = "negbinom"
875
+ discrete = True
876
+ _params = ("shift", "r", "mu")
877
+ shift: float
878
+ r: float
879
+ mu: float
880
+
881
+ @property
882
+ def p(self) -> float:
883
+ return self.r / (self.r + self.mu)
884
+
885
+ @classmethod
886
+ def fit(cls, x, *, column=None, policy=None, rng=None) -> NegBinomMarginal:
887
+ pol = resolve_policy(policy)
888
+ a = _clean(x)
889
+ _check_integer(a, cls.kind)
890
+ shift = _count_shift(a, pol)
891
+ y = a - shift
892
+ m = max(float(y.mean()), 1e-9)
893
+
894
+ def nll(log_r: float) -> float:
895
+ r = math.exp(log_r)
896
+ return -float(np.sum(stats.nbinom.logpmf(y, r, r / (r + m))))
897
+
898
+ res = minimize_scalar(nll, bounds=(-6.0, 14.0), method="bounded",
899
+ options={"xatol": 1e-4})
900
+ return cls(shift=shift, r=_c(math.exp(res.x), pol), mu=_c(m, pol))
901
+
902
+ def cdf(self, x):
903
+ k = np.floor(_as_x(x) - self.shift)
904
+ return np.where(k >= 0, special.betainc(self.r, np.maximum(k, 0.0) + 1.0, self.p), 0.0)
905
+
906
+ def cdf_left(self, x):
907
+ return self.cdf(np.ceil(_as_x(x)) - 1.0)
908
+
909
+ def ppf(self, u):
910
+ return self.shift + np.asarray(stats.nbinom.ppf(_clip_u(u), self.r, self.p),
911
+ dtype=np.float64)
912
+
913
+ def logpdf(self, x):
914
+ return stats.nbinom.logpmf(_as_x(x) - self.shift, self.r, self.p)
915
+
916
+
917
+ class _FiniteSupport(MarginalModel):
918
+ """Shared math for a pmf over sorted support ``values`` with probabilities ``probs``."""
919
+
920
+ discrete = True
921
+ values: np.ndarray
922
+ probs: np.ndarray
923
+
924
+ def _setup(self, values: np.ndarray, probs: np.ndarray) -> None:
925
+ self.values = np.asarray(values, dtype=np.float64)
926
+ self.probs = np.asarray(probs, dtype=np.float64)
927
+ cum = np.cumsum(self.probs)
928
+ self._cum = cum / cum[-1]
929
+ self._cum[-1] = 1.0
930
+
931
+ def cdf(self, x):
932
+ i = np.searchsorted(self.values, _as_x(x), side="right")
933
+ return np.where(i > 0, self._cum[np.maximum(i - 1, 0)], 0.0)
934
+
935
+ def cdf_left(self, x):
936
+ i = np.searchsorted(self.values, _as_x(x), side="left")
937
+ return np.where(i > 0, self._cum[np.maximum(i - 1, 0)], 0.0)
938
+
939
+ def ppf(self, u):
940
+ j = np.searchsorted(self._cum, _clip_u(u), side="left")
941
+ return self.values[np.minimum(j, self.values.size - 1)]
942
+
943
+ def _pmf_normalized(self) -> np.ndarray:
944
+ return self.probs / self.probs.sum()
945
+
946
+
947
+ @MARGINALS.register()
948
+ class DiscreteEmpiricalMarginal(_FiniteSupport):
949
+ """Support values and probabilities. Values seen fewer than ``min_category_support`` times
950
+ are merged into the nearest kept value; the number of values is capped by
951
+ ``len(quantile_levels(n, policy))``."""
952
+
953
+ kind = "discrete_empirical"
954
+
955
+ def __init__(self, values: np.ndarray, probs: np.ndarray) -> None:
956
+ v = np.asarray(values, dtype=np.float64)
957
+ order = np.argsort(v, kind="stable")
958
+ self._setup(v[order], np.asarray(probs, dtype=np.float64)[order])
959
+
960
+ #: on a small table (``disclosure.needs_coarse_summary``) the merged support is replaced by
961
+ #: a ``SummaryMarginal`` when its standard deviation falls below this share of the data's
962
+ SUMMARY_MIN_SPREAD = 0.8
963
+
964
+ @classmethod
965
+ def fit(cls, x, *, column=None, policy=None, rng=None) -> MarginalModel:
966
+ """Fit the support; on a small table where merging rare values collapses the spread,
967
+ return a ``SummaryMarginal`` instead (rounded on output by the discrete codec)."""
968
+ pol = resolve_policy(policy)
969
+ a = _clean(x)
970
+ model = cls._fit_support(a, pol)
971
+ if needs_coarse_summary(a.size, pol) and a.size > 1:
972
+ p = model._pmf_normalized()
973
+ mean = float(np.dot(p, model.values))
974
+ sd = math.sqrt(max(float(np.dot(p, (model.values - mean) ** 2)), 0.0))
975
+ if sd < cls.SUMMARY_MIN_SPREAD * float(a.std(ddof=1)):
976
+ return SummaryMarginal.fit(a, column=column, policy=pol, rng=rng)
977
+ return model
978
+
979
+ @classmethod
980
+ def _fit_support(cls, a: np.ndarray, pol: DisclosurePolicySpec) -> DiscreteEmpiricalMarginal:
981
+ vals, counts = np.unique(a, return_counts=True)
982
+ m = pol.min_category_support
983
+ max_k = len(quantile_levels(a.size, pol))
984
+ keep = counts >= m
985
+ if keep.sum() > max_k:
986
+ order = sorted(range(vals.size), key=lambda i: (-counts[i], vals[i]))[:max_k]
987
+ keep = np.zeros(vals.size, dtype=bool)
988
+ keep[order] = True
989
+ if keep.any():
990
+ kv = vals[keep]
991
+ # nearest kept value (ties go to the lower neighbour)
992
+ j = np.clip(np.searchsorted(kv, vals), 0, kv.size - 1)
993
+ jl = np.maximum(j - 1, 0)
994
+ use_lower = np.abs(vals - kv[jl]) <= np.abs(kv[j] - vals)
995
+ target = np.where(use_lower, jl, j)
996
+ kc = np.bincount(target, weights=counts, minlength=kv.size)
997
+ out_v = kv
998
+ else:
999
+ # nothing reaches the support threshold: aggregate consecutive values into groups
1000
+ # of >= m rows, each represented by its (rounded) weighted mean
1001
+ integer = bool(np.all(vals == np.round(vals)))
1002
+ groups: list[list[int]] = [[]]
1003
+ acc = 0
1004
+ for i, c in enumerate(counts):
1005
+ groups[-1].append(i)
1006
+ acc += int(c)
1007
+ if acc >= m:
1008
+ groups.append([])
1009
+ acc = 0
1010
+ if not groups[-1]:
1011
+ groups.pop()
1012
+ if len(groups) > 1 and counts[groups[-1]].sum() < m:
1013
+ last = groups.pop()
1014
+ groups[-1].extend(last)
1015
+ reps, kc_list = [], []
1016
+ for g in groups:
1017
+ w = counts[g].astype(float)
1018
+ rep = float(np.dot(vals[g], w) / w.sum())
1019
+ reps.append(round(rep) if integer else rep)
1020
+ kc_list.append(w.sum())
1021
+ out_v, kc = np.asarray(reps, dtype=float), np.asarray(kc_list)
1022
+ out_v = coarsen_array(out_v, pol)
1023
+ # coarsening can collide values; merge duplicates
1024
+ uv, inv = np.unique(out_v, return_inverse=True)
1025
+ pc = np.bincount(inv, weights=kc, minlength=uv.size)
1026
+ probs = coarsen_array(pc / pc.sum(), pol)
1027
+ return cls(uv, probs)
1028
+
1029
+ def logpdf(self, x):
1030
+ # held-out values outside the stored support are scored at the value they merge into
1031
+ x = _as_x(x)
1032
+ v = self.values
1033
+ j = np.clip(np.searchsorted(v, x), 0, v.size - 1)
1034
+ jl = np.maximum(j - 1, 0)
1035
+ idx = np.where(np.abs(x - v[jl]) <= np.abs(v[j] - x), jl, j)
1036
+ with np.errstate(divide="ignore"):
1037
+ return np.log(self._pmf_normalized()[idx])
1038
+
1039
+ @property
1040
+ def n_parameters(self) -> int:
1041
+ return int(2 * self.values.size)
1042
+
1043
+ def to_spec(self, store: ArrayStore, prefix: str) -> ModelSpec:
1044
+ return ModelSpec(kind=self.kind, params={},
1045
+ arrays={"values": store.put(f"{prefix}values", self.values),
1046
+ "probs": store.put(f"{prefix}probs", self.probs)})
1047
+
1048
+ @classmethod
1049
+ def from_spec(cls, spec: ModelSpec, store: ArrayStore) -> DiscreteEmpiricalMarginal:
1050
+ return cls(store.get(spec.arrays["values"]), store.get(spec.arrays["probs"]))
1051
+
1052
+
1053
+ @MARGINALS.register()
1054
+ class CategoricalMarginal(_FiniteSupport):
1055
+ """Probabilities over codes ``0..k-1``; ``labels[i]`` is the label of code ``i``. A pooled
1056
+ ``"__other__"`` bucket, if present, is last."""
1057
+
1058
+ kind = "categorical"
1059
+ #: fit diagnostic (not serialised): source labels pooled into ``__other__`` (or, for
1060
+ #: booleans, rare levels whose stored support was raised to the policy minimum)
1061
+ n_pooled: int = 0
1062
+
1063
+ def __init__(self, labels: np.ndarray, probs: np.ndarray) -> None:
1064
+ self.labels = np.asarray(labels).astype(str)
1065
+ p = np.asarray(probs, dtype=np.float64)
1066
+ if self.labels.size == 0 or self.labels.size != p.size:
1067
+ raise ValueError("categorical: labels and probs must be non-empty and equal length")
1068
+ self._setup(np.arange(p.size, dtype=np.float64), p)
1069
+
1070
+ @classmethod
1071
+ def from_counts(cls, labels: np.ndarray, counts: np.ndarray,
1072
+ policy: DisclosurePolicySpec | str | None) -> CategoricalMarginal:
1073
+ pol = resolve_policy(policy)
1074
+ c = np.asarray(counts, dtype=np.float64)
1075
+ probs = coarsen_array(c / c.sum(), pol)
1076
+ if probs.sum() <= 0:
1077
+ probs = np.full(c.size, 1.0 / c.size)
1078
+ return cls(np.asarray(labels).astype(str), probs)
1079
+
1080
+ @classmethod
1081
+ def fit(cls, x, *, column=None, policy=None, rng=None) -> CategoricalMarginal:
1082
+ """Fit from integer codes when labels are not available; labels become the code
1083
+ strings and rare codes are pooled. Prefer ``profiling.univariate.fit_categorical``."""
1084
+ pol = resolve_policy(policy)
1085
+ a = _clean(x)
1086
+ vals, counts = np.unique(a, return_counts=True)
1087
+ labels = np.array([str(int(v)) if v == round(v) else str(v) for v in vals])
1088
+ labels, counts, n_pooled = pool_categories(labels, counts, pol)
1089
+ model = cls.from_counts(labels, counts, pol)
1090
+ model.n_pooled = int(n_pooled)
1091
+ return model
1092
+
1093
+ @property
1094
+ def has_other(self) -> bool:
1095
+ return bool(self.labels.size and self.labels[-1] == OTHER)
1096
+
1097
+ def logpdf(self, x):
1098
+ x = _as_x(x)
1099
+ k = self.labels.size
1100
+ idx = np.rint(x).astype(np.int64)
1101
+ ok = (idx >= 0) & (idx < k)
1102
+ pmf = self._pmf_normalized()
1103
+ with np.errstate(divide="ignore"):
1104
+ return np.where(ok, np.log(pmf[np.clip(idx, 0, k - 1)]), -np.inf)
1105
+
1106
+ @property
1107
+ def n_parameters(self) -> int:
1108
+ return int(self.labels.size)
1109
+
1110
+ def to_spec(self, store: ArrayStore, prefix: str) -> ModelSpec:
1111
+ return ModelSpec(kind=self.kind, params={},
1112
+ arrays={"labels": store.put(f"{prefix}labels", self.labels),
1113
+ "probs": store.put(f"{prefix}probs", self.probs)})
1114
+
1115
+ @classmethod
1116
+ def from_spec(cls, spec: ModelSpec, store: ArrayStore) -> CategoricalMarginal:
1117
+ return cls(store.get(spec.arrays["labels"]), store.get(spec.arrays["probs"]))
1118
+
1119
+
1120
+ # ---------------------------------------------------------------------------------------------
1121
+ # mixed spike-and-slab (ADR-0007)
1122
+ # ---------------------------------------------------------------------------------------------
1123
+
1124
+
1125
+ #: finest decimal resolution treated as a lattice; values with more decimals are continuous
1126
+ LATTICE_MAX_DECIMALS = 6
1127
+ #: largest ``|x| / step`` for which the lattice arithmetic is exact in float64
1128
+ LATTICE_MAX_INDEX = 1e11
1129
+ #: slack, in lattice steps, when a float is mapped to its lattice index
1130
+ _LATTICE_EPS = 1e-4
1131
+ _INDEX_LIMIT = 2.0 ** 62
1132
+ #: "nearly all": the granularity may ignore fewer than ``min_category_support`` rows, and no more
1133
+ #: than this share of the non-zero rows
1134
+ GRANULARITY_MAX_EXCEPTIONS = 0.01
1135
+ #: a step other than the decimal unit needs this many distinct non-zero values behind it
1136
+ GRANULARITY_MIN_DISTINCT = 10
1137
+ #: an atom needs this many rows whatever the policy (a point mass, not a chance tie)
1138
+ ATOM_MIN_COUNT = 5
1139
+ #: level of the "count clearly above the smooth remainder" test (Poisson upper tail)
1140
+ ATOM_ALPHA = 0.01
1141
+ #: lattice neighbours on each side whose median count is a value's smooth baseline ...
1142
+ ATOM_WINDOW = 3
1143
+ #: ... and the wider window whose rare values give the baseline a floor on a sparse lattice
1144
+ ATOM_WIDE_WINDOW = 100
1145
+ #: atoms kept per marginal, as a multiple of the policy's quantile resolution
1146
+ ATOM_CAP_FACTOR = 10
1147
+ #: passes of "fit the slab, drop the atoms it already explains"
1148
+ ATOM_PASSES = 6
1149
+ #: a magnitude band needs this many rows to get its own rounding-level weights
1150
+ LEVEL_BAND_MIN_ROWS = 30
1151
+ #: likelihood-ratio statistic (chi-square, 1 d.o.f., p = 0.001) a rounding level must reach
1152
+ LEVEL_CHI2 = 10.83
1153
+ #: a rounding level is not used in a band where more than this share of its cells are atoms
1154
+ LEVEL_MAX_CENSORED = 0.999
1155
+ #: magnitude bands (decades) with their own rounding-level weights
1156
+ LEVEL_MAX_BANDS = 12
1157
+ _ATOM_CHUNK = 50_000
1158
+ #: most breakpoints the quantile table of a mixed marginal may hold (more: bisection)
1159
+ _TABLE_MAX = 1_000_000
1160
+ #: a level this close above the top of a jump of the CDF still belongs to the jump, so mapping
1161
+ #: a value to its CDF and back (PIT encoding) returns the value despite float rounding (the
1162
+ #: normal CDF and its inverse are a few 1e-16 apart)
1163
+ _PPF_SLACK = 1e-14
1164
+ #: two ways of evaluating the CDF of a mixed marginal (the quantile table's closed form and the
1165
+ #: sum over levels) agree to well within this; a comparison closer than this is settled by the
1166
+ #: second, so the table and the bisection return the same quantile. Smaller than _PPF_SLACK.
1167
+ _CDF_NOISE = 4e-15
1168
+ _SLAB_KINDS = frozenset({"empirical", "summary"})
1169
+
1170
+
1171
+ class _Lattice:
1172
+ """The points ``k * step`` with ``step = g * 10^-decimals`` (``g`` a positive integer)."""
1173
+
1174
+ def __init__(self, step: float, decimals: int) -> None:
1175
+ self.decimals = int(decimals)
1176
+ self.scale = 10.0 ** self.decimals
1177
+ self.g = max(int(round(float(step) * self.scale)), 1)
1178
+ self.step = self.g / self.scale
1179
+
1180
+ def _coord(self, x: np.ndarray) -> np.ndarray:
1181
+ t = np.asarray(x, dtype=np.float64) * self.scale / self.g
1182
+ return np.clip(np.nan_to_num(t, nan=0.0, posinf=_INDEX_LIMIT, neginf=-_INDEX_LIMIT),
1183
+ -_INDEX_LIMIT, _INDEX_LIMIT)
1184
+
1185
+ def floor(self, x: np.ndarray) -> np.ndarray:
1186
+ """Index of the largest lattice point ``<= x``."""
1187
+ return np.floor(self._coord(x) + _LATTICE_EPS).astype(np.int64)
1188
+
1189
+ def ceil(self, x: np.ndarray) -> np.ndarray:
1190
+ """Index of the smallest lattice point ``>= x``."""
1191
+ return np.ceil(self._coord(x) - _LATTICE_EPS).astype(np.int64)
1192
+
1193
+ def nearest(self, x: np.ndarray) -> np.ndarray:
1194
+ return np.rint(self._coord(x)).astype(np.int64)
1195
+
1196
+ def value(self, k: np.ndarray) -> np.ndarray:
1197
+ v = np.asarray(k, dtype=np.float64) * self.g
1198
+ return v if self.decimals == 0 else np.round(v / self.scale, self.decimals)
1199
+
1200
+
1201
+ def _decimals_of(vals: np.ndarray) -> int | None:
1202
+ """Fewest decimal places ``d <= LATTICE_MAX_DECIMALS`` at which every value is a multiple of
1203
+ ``10^-d``; ``None`` when there is no such ``d`` (a continuous column)."""
1204
+ v = vals
1205
+ if v.size > 20_000:
1206
+ v = v[np.linspace(0, v.size - 1, 20_000).round().astype(np.int64)]
1207
+ for d in range(LATTICE_MAX_DECIMALS + 1):
1208
+ s = v * (10.0 ** d)
1209
+ if np.all(np.abs(s - np.rint(s)) <= 1e-6 + 1e-12 * np.abs(s)):
1210
+ return d
1211
+ return None
1212
+
1213
+
1214
+ def detect_granularity(x: np.ndarray, *, min_support: int = 1) -> tuple[float, int]:
1215
+ """Granularity of a column: ``(step, decimals)`` with ``step`` the greatest
1216
+ ``g * 10^-decimals`` such that (nearly) all values are multiples of it, e.g. ``(1.0, 0)``
1217
+ for integers, ``(100.0, 0)`` for amounts in hundreds, ``(0.01, 2)`` for prices in cents and
1218
+ ``(0.25, 2)`` for quarters. ``(0.0, 0)`` when the values are on no decimal lattice of at
1219
+ most ``LATTICE_MAX_DECIMALS`` places (or are too large for exact lattice arithmetic).
1220
+
1221
+ "Nearly all": fewer than ``min_support`` rows, and at most ``GRANULARITY_MAX_EXCEPTIONS``
1222
+ of the non-zero rows, may be off the step; those rows cannot be told apart from a rare
1223
+ category and are rounded onto it. The step is the largest that qualifies among the exact
1224
+ greatest common divisor of the values and the round numbers ``{1, 2, 5, 25} x 10^e``
1225
+ (times one or times that divisor). A step coarser than the decimal unit needs
1226
+ ``GRANULARITY_MIN_DISTINCT`` distinct non-zero values, so a handful of values that happen
1227
+ to share a divisor do not define a lattice.
1228
+ """
1229
+ a = _clean(x)
1230
+ vals, counts = np.unique(a, return_counts=True)
1231
+ d = _decimals_of(vals)
1232
+ if d is None:
1233
+ return 0.0, 0
1234
+ scale = 10.0 ** d
1235
+ if float(np.max(np.abs(vals))) * scale > LATTICE_MAX_INDEX:
1236
+ return 0.0, 0
1237
+ k = np.abs(np.rint(vals * scale).astype(np.int64))
1238
+ nz = k != 0
1239
+ if int(nz.sum()) < GRANULARITY_MIN_DISTINCT:
1240
+ return 1.0 / scale, d
1241
+ kk, cc = k[nz], counts[nz]
1242
+ allowed = min(int(min_support) - 1, int(GRANULARITY_MAX_EXCEPTIONS * int(cc.sum())))
1243
+ g0 = math.gcd(*kk.tolist())
1244
+ top = int(kk.max())
1245
+ cands = {g0}
1246
+ for base in {1, g0}:
1247
+ for mant in (1, 2, 5, 25):
1248
+ s = base * mant
1249
+ while s <= top:
1250
+ cands.add(s)
1251
+ s *= 10
1252
+ best = g0
1253
+ for s in sorted(cands):
1254
+ if s > best and int(cc[kk % s != 0].sum()) <= allowed:
1255
+ best = s
1256
+ return best / scale, d
1257
+
1258
+
1259
+ def _smooth_baseline(idx: np.ndarray, counts: np.ndarray, k_min: int) -> np.ndarray:
1260
+ """Count each well-supported lattice value would have if the column were locally smooth:
1261
+ the median count of its ``ATOM_WINDOW`` lattice neighbours on each side (lattice points the
1262
+ data never takes count 0), but at least the mean count per lattice point of the rare
1263
+ values (below ``k_min`` rows) within ``ATOM_WIDE_WINDOW`` steps, which keeps the baseline
1264
+ positive on a sparse lattice. Zero for values with fewer than ``k_min`` rows."""
1265
+ out = np.zeros(idx.size, dtype=np.float64)
1266
+ pos = np.flatnonzero(counts >= k_min)
1267
+ if pos.size == 0:
1268
+ return out
1269
+ w = ATOM_WINDOW
1270
+ offs = np.concatenate([np.arange(-w, 0), np.arange(1, w + 1)])
1271
+ rare = np.concatenate([[0], np.cumsum(np.where(counts < k_min, counts, 0))])
1272
+ for start in range(0, pos.size, _ATOM_CHUNK):
1273
+ p = pos[start:start + _ATOM_CHUNK]
1274
+ nb = p[:, None] + offs[None, :]
1275
+ nbc = np.clip(nb, 0, idx.size - 1)
1276
+ near = (nb >= 0) & (nb < idx.size) & (np.abs(idx[nbc] - idx[p][:, None]) <= w)
1277
+ med = np.median(np.where(near, counts[nbc], 0), axis=1)
1278
+ lo = np.searchsorted(idx, idx[p] - ATOM_WIDE_WINDOW, side="left")
1279
+ hi = np.searchsorted(idx, idx[p] + ATOM_WIDE_WINDOW, side="right")
1280
+ out[p] = np.maximum(med, (rare[hi] - rare[lo]) / (2.0 * ATOM_WIDE_WINDOW))
1281
+ return out
1282
+
1283
+
1284
+ def point_masses(idx: np.ndarray | None, counts: np.ndarray,
1285
+ min_support: int) -> tuple[np.ndarray, np.ndarray]:
1286
+ """``(is_point_mass, baseline)`` for the distinct values of a column, given as sorted
1287
+ lattice indices ``idx`` (``None`` for values on no lattice) held by ``counts`` rows each.
1288
+
1289
+ A point mass is a value with real mass of its own, a zero or a heaped round number: it is
1290
+ held by at least ``max(min_support, ATOM_MIN_COUNT)`` rows, by at least that many more than
1291
+ its smooth ``baseline`` (``_smooth_baseline``; 0 without a lattice, where every tie is
1292
+ mass a continuous distribution cannot have), and its count is in the upper ``ATOM_ALPHA``
1293
+ tail of a Poisson distribution with that baseline. A value of a smooth count distribution
1294
+ is not a point mass however many rows hold it.
1295
+ """
1296
+ k_min = max(int(min_support), ATOM_MIN_COUNT)
1297
+ counts = np.asarray(counts)
1298
+ base = (np.zeros(counts.size, dtype=np.float64) if idx is None
1299
+ else _smooth_baseline(np.asarray(idx), counts, k_min))
1300
+ is_mass = (counts >= k_min) & (counts - base >= k_min) \
1301
+ & (stats.poisson.sf(counts - 1, base) <= ATOM_ALPHA)
1302
+ return is_mass, base
1303
+
1304
+
1305
+ def _nice_levels(g: int, top_index: int) -> np.ndarray:
1306
+ """Rounding levels as whole multiples of the lattice step ``g`` (in decimal units): the
1307
+ step itself, then every round number ``{1, 5} x 10^e`` that is a larger whole multiple of
1308
+ it, up to ``top_index`` steps. Each level divides the next."""
1309
+ out = [1]
1310
+ s = 1
1311
+ while s <= g * max(top_index, 1):
1312
+ for mant in (1, 5):
1313
+ v = mant * s
1314
+ if v > g and v % g == 0 and v // g <= top_index:
1315
+ out.append(v // g)
1316
+ s *= 10
1317
+ return np.asarray(sorted(set(out)), dtype=np.int64)
1318
+
1319
+
1320
+ def _band_layout(band_start: float, n_bands: int) -> tuple[np.ndarray, np.ndarray]:
1321
+ """``(cuts, band_of)``: the points ``+-band_start * 10^b`` that cut the real line into
1322
+ ``2 n_bands - 1`` intervals, and the magnitude band of each interval."""
1323
+ if n_bands <= 1 or band_start <= 0:
1324
+ return np.zeros(0, dtype=np.float64), np.zeros(1, dtype=np.int64)
1325
+ pos = band_start * 10.0 ** np.arange(n_bands - 1, dtype=np.float64)
1326
+ band_of = np.concatenate([np.arange(n_bands - 1, 0, -1), [0], np.arange(1, n_bands)])
1327
+ return np.concatenate([-pos[::-1], pos]), band_of.astype(np.int64)
1328
+
1329
+
1330
+ def _atom_cell_shares(lat: _Lattice, slab: MarginalModel, atom_idx: np.ndarray,
1331
+ mults: np.ndarray, band_start: float, n_bands: int) -> np.ndarray:
1332
+ """``shares[b, j]``: share of the slab's mass in magnitude band ``b`` that lies in a
1333
+ level-``j`` rounding cell centred on an atom (``mults[j]`` lattice steps wide)."""
1334
+ out = np.zeros((n_bands, mults.size), dtype=np.float64)
1335
+ if atom_idx.size == 0:
1336
+ return out
1337
+ cuts, band_of = _band_layout(band_start, n_bands)
1338
+ s_cut = np.asarray(slab.cdf(cuts), dtype=np.float64) if cuts.size else np.zeros(0)
1339
+ s_lo, s_hi = np.concatenate([[0.0], s_cut]), np.concatenate([s_cut, [1.0]])
1340
+ mass = np.zeros(n_bands, dtype=np.float64)
1341
+ np.add.at(mass, band_of, np.clip(s_hi - s_lo, 0.0, None))
1342
+ centre = atom_idx.astype(np.float64) * lat.step
1343
+ for j, m in enumerate(mults.tolist()):
1344
+ on = centre[atom_idx % m == 0]
1345
+ if on.size == 0:
1346
+ continue
1347
+ half = 0.5 * m * lat.step
1348
+ a = np.asarray(slab.cdf(on - half), dtype=np.float64)
1349
+ b = np.asarray(slab.cdf(on + half), dtype=np.float64)
1350
+ for i in range(band_of.size): # the part of each cell in interval i
1351
+ part = np.minimum(b, s_hi[i]) - np.maximum(a, s_lo[i])
1352
+ out[band_of[i], j] += float(np.clip(part, 0.0, None).sum())
1353
+ return np.clip(np.where(mass[:, None] > 0, out / np.where(mass > 0, mass, 1.0)[:, None],
1354
+ 0.0), 0.0, 1.0)
1355
+
1356
+
1357
+ def _em_levels(idx: np.ndarray, counts: np.ndarray, mults: np.ndarray, hidden: np.ndarray,
1358
+ min_rows: int) -> np.ndarray:
1359
+ """Maximum-likelihood weights of the rounding levels ``mults`` for the lattice values
1360
+ ``idx`` (with ``counts`` rows each) of one magnitude band; the values are those that are
1361
+ not atoms.
1362
+
1363
+ Under a locally smooth slab a draw rounded at level ``m`` lands on a multiple of ``m`` with
1364
+ ``m`` times the mass of one base cell, so the likelihood of a value depends only on which
1365
+ levels divide it. ``hidden[j]`` is the share of level ``j``'s cells that are atoms: a
1366
+ coarse level spreads its draws over its other multiples only (each gets ``1 / (1 -
1367
+ hidden)`` times more), while the base level's draws on an atom are part of that atom's rows
1368
+ and so missing from ``idx`` (EM for a truncated component). Levels are removed backwards:
1369
+ first those the data attribute fewer than ``min_rows`` rows to (the support rule; this can
1370
+ remove the finest level, whose few rows are then rounded), then those whose
1371
+ likelihood-ratio statistic is below ``LEVEL_CHI2``.
1372
+ """
1373
+ weights = np.zeros(mults.size, dtype=np.float64)
1374
+ divides = idx[:, None] % mults[None, :] == 0
1375
+ pats, inv = np.unique(divides, axis=0, return_inverse=True)
1376
+ n_pat = np.bincount(np.ravel(inv), weights=counts, minlength=pats.shape[0])
1377
+ base = mults == 1
1378
+ spread = np.where(base, 1.0, 1.0 / (1.0 - np.clip(hidden, 0.0, LEVEL_MAX_CENSORED)))
1379
+ like = pats * (mults * spread)[None, :]
1380
+ censored = np.where(base, np.clip(hidden, 0.0, LEVEL_MAX_CENSORED), 0.0)
1381
+
1382
+ def run(mask: np.ndarray, start: np.ndarray | None = None
1383
+ ) -> tuple[np.ndarray, float, np.ndarray]:
1384
+ cols = np.flatnonzero(mask)
1385
+ c, q = like[:, cols], censored[cols]
1386
+ ok = c.sum(axis=1) > 0
1387
+ c, npk = c[ok], n_pat[ok]
1388
+ total = float(npk.sum())
1389
+ pi = np.full(cols.size, 1.0 / cols.size)
1390
+ if total <= 0:
1391
+ return pi, 0.0, np.zeros(cols.size)
1392
+ if start is not None and float(start[cols].sum()) > 0:
1393
+ pi = np.maximum(start[cols], 1e-9)
1394
+ pi = pi / pi.sum()
1395
+ scaled = (npk[:, None] * c).T / total
1396
+ for it in range(400):
1397
+ new = pi * (scaled @ (1.0 / (c @ pi))) * (1.0 - float(q @ pi)) + pi * q
1398
+ new = new / new.sum()
1399
+ done = it % 4 == 3 and float(np.max(np.abs(new - pi))) < 1e-9
1400
+ pi = new
1401
+ if done:
1402
+ break
1403
+ mix = c @ pi
1404
+ ll = float(npk @ np.log(mix)) - total * math.log(1.0 - float(q @ pi))
1405
+ return pi, ll, total * pi * (scaled @ (1.0 / mix))
1406
+
1407
+ def full(pi: np.ndarray, mask: np.ndarray) -> np.ndarray:
1408
+ out = np.zeros(mults.size, dtype=np.float64)
1409
+ out[np.flatnonzero(mask)] = pi
1410
+ return out
1411
+
1412
+ keep = np.ones(mults.size, dtype=bool)
1413
+ pi, ll, obs = run(keep)
1414
+ while int(keep.sum()) > 1:
1415
+ cols = np.flatnonzero(keep)
1416
+ weak = np.flatnonzero(obs < min_rows)
1417
+ if weak.size:
1418
+ drop = int(cols[weak[np.argmin(obs[weak])]])
1419
+ else:
1420
+ stat, drop = math.inf, -1
1421
+ for c in cols[1:]: # the finest kept level is never tested
1422
+ trial = keep.copy()
1423
+ trial[c] = False
1424
+ s = 2.0 * (ll - run(trial, full(pi, keep))[1])
1425
+ if s < stat:
1426
+ stat, drop = s, int(c)
1427
+ if stat >= LEVEL_CHI2:
1428
+ break
1429
+ start = full(pi, keep)
1430
+ keep[drop] = False
1431
+ pi, ll, obs = run(keep, start)
1432
+ weights[np.flatnonzero(keep)] = pi
1433
+ return weights
1434
+
1435
+
1436
+ def _fit_levels(lat: _Lattice, slab: MarginalModel, idx: np.ndarray, counts: np.ndarray,
1437
+ is_atom: np.ndarray, min_rows: int) -> tuple[np.ndarray, np.ndarray, float]:
1438
+ """Rounding levels of the slab: ``(multipliers, weights, band_start)``.
1439
+
1440
+ ``weights[b, j]`` is the probability that a slab draw in magnitude band ``b`` is rounded to
1441
+ ``multipliers[j]`` lattice steps. Band 0 is ``|x| < band_start`` and band ``b >= 1`` the
1442
+ decade ``[band_start * 10^(b-1), band_start * 10^b)``; the last stored band also covers
1443
+ everything above it. A level is eligible in a band when it is no larger than the band's
1444
+ lower edge (rounding keeps at least one significant digit, and never creates a zero), so
1445
+ band 0 always uses the lattice step, and when not all of its cells there are atoms. A band
1446
+ is fitted on its rows that are not atoms (``_em_levels``); with fewer than
1447
+ ``LEVEL_BAND_MIN_ROWS`` of those, on all its rows; with fewer than that in all it inherits
1448
+ the nearest fitted band below.
1449
+ """
1450
+ e_g = len(str(lat.g)) - 1
1451
+ band_start = 10.0 ** (e_g + 1 - lat.decimals)
1452
+ top = int(np.max(np.abs(idx))) if idx.size else 0
1453
+ mults = _nice_levels(lat.g, top)
1454
+ if mults.size == 1:
1455
+ return mults, np.ones((1, 1), dtype=np.float64), band_start
1456
+ units = np.abs(idx).astype(np.float64) * lat.g
1457
+ edges = 10.0 ** (e_g + 1 + np.arange(LEVEL_MAX_BANDS - 1, dtype=np.float64))
1458
+ band = np.searchsorted(edges, units, side="right")
1459
+ n_bands = int(np.max(band)) + 1
1460
+ hidden = _atom_cell_shares(lat, slab, idx[is_atom], mults, band_start, n_bands)
1461
+ probs = np.zeros((n_bands, mults.size), dtype=np.float64)
1462
+ probs[:, 0] = 1.0
1463
+ fitted = np.zeros(n_bands, dtype=bool)
1464
+ level_units = mults.astype(np.float64) * lat.g
1465
+ for b in range(1, n_bands):
1466
+ elig = (level_units <= edges[b - 1] * (1.0 + 1e-12)) \
1467
+ & ((mults == 1) | (hidden[b] <= LEVEL_MAX_CENSORED))
1468
+ if int(elig.sum()) < 2:
1469
+ continue
1470
+ in_b = band == b
1471
+ free = in_b & ~is_atom
1472
+ if int(counts[free].sum()) >= LEVEL_BAND_MIN_ROWS:
1473
+ rows, hid = free, hidden[b, elig]
1474
+ elif int(counts[in_b].sum()) >= LEVEL_BAND_MIN_ROWS:
1475
+ rows, hid = in_b, np.zeros(int(elig.sum()), dtype=np.float64)
1476
+ else:
1477
+ continue
1478
+ probs[b, elig] = _em_levels(idx[rows], counts[rows], mults[elig], hid, min_rows)
1479
+ probs[b, ~elig] = 0.0
1480
+ fitted[b] = True
1481
+ last = 0
1482
+ for b in range(1, n_bands):
1483
+ if fitted[b]:
1484
+ last = b
1485
+ else:
1486
+ probs[b] = probs[last]
1487
+ probs = probs[:last + 1] # bands above inherit the last fitted one
1488
+ active = probs.sum(axis=0) > 0
1489
+ mults, probs = mults[active], probs[:, active]
1490
+ if np.all(probs == probs[0]):
1491
+ probs = probs[:1]
1492
+ return mults, probs, band_start
1493
+
1494
+
1495
+ def _fit_slab(vals: np.ndarray, rows: np.ndarray, counts: np.ndarray, lat: _Lattice | None,
1496
+ column: ColumnSchema | None, pol: DisclosurePolicySpec,
1497
+ rng: np.random.Generator | None) -> MarginalModel:
1498
+ """The slab for the sorted values ``vals``, of which ``rows`` rows each are left to it
1499
+ (``counts`` rows hold each value in all).
1500
+
1501
+ On a lattice the slab is the distribution of the value *before* rounding, so its quantile
1502
+ grid is that of the rows spread evenly over their rounding cells (uniform dequantisation):
1503
+ the ``i``-th of the ``r`` rows of a value ``v`` sits at ``v + step ((i + 1/2) / r - 1/2)``.
1504
+ The slab's mass in a cell is then the share of the rows on its value wherever the grid
1505
+ resolves the cell, and the grid error is spread within a cell, not across values. Fitted
1506
+ to the recorded values themselves, a grid of 1% steps places each cell edge half-way
1507
+ between two grid levels, and so puts up to 0.5% of the rows on the wrong side of it. A
1508
+ value held by one row stays where it is, so where the values are sparse the grid is the
1509
+ one the plain quantile model would store.
1510
+
1511
+ The slab's tails then start inside a cell, so they need the bounds the recorded values
1512
+ used to give them: the smallest and the largest value bound the slab when at least
1513
+ ``max(min_category_support, ATOM_MIN_COUNT)`` rows hold them (a well-supported extreme is
1514
+ a floor or a cap, not the thin end of a tail, and may be stored like a category).
1515
+ """
1516
+ data = np.repeat(vals, rows)
1517
+ if lat is None or needs_coarse_summary(data.size, pol):
1518
+ return EmpiricalMarginal.fit(data, column=column, policy=pol, rng=rng)
1519
+ held = rows > 0
1520
+ v, r = vals[held], rows[held].astype(np.float64)
1521
+ cum = np.cumsum(r)
1522
+ step, last = lat.step, float(cum[-1]) - 1.0
1523
+ k_min = max(int(pol.min_category_support), ATOM_MIN_COUNT)
1524
+
1525
+ def point(rank: np.ndarray) -> np.ndarray:
1526
+ """The spread row of the given 0-based rank."""
1527
+ j = np.minimum(np.searchsorted(cum, rank, side="right"), v.size - 1)
1528
+ return v[j] + step * ((rank - (cum[j] - r[j]) + 0.5) / r[j] - 0.5)
1529
+
1530
+ def spread_quantiles(levels: np.ndarray) -> np.ndarray:
1531
+ """``np.quantile(spread rows, levels)`` without laying the rows out."""
1532
+ h = np.asarray(levels, dtype=np.float64) * last
1533
+ lo = np.floor(h)
1534
+ a, b = point(lo), point(np.minimum(lo + 1.0, last))
1535
+ return a + (h - lo) * (b - a)
1536
+
1537
+ return EmpiricalMarginal._fit_grid(
1538
+ data, column, pol, quantiles=spread_quantiles, pad=0.5 * step,
1539
+ floor=float(vals[0]) if counts[0] >= k_min else -math.inf,
1540
+ cap=float(vals[-1]) if counts[-1] >= k_min else math.inf)
1541
+
1542
+
1543
+ @MARGINALS.register()
1544
+ class MixedMarginal(MarginalModel):
1545
+ """Spike-and-slab marginal (ADR-0007): point masses over a rounded continuous slab.
1546
+
1547
+ With probability ``atom_probs[i]`` the value is the atom ``atoms[i]``. Otherwise a value
1548
+ ``Y`` is drawn from the continuous ``slab`` (the policy-limited ``empirical`` quantile
1549
+ model with parametric tails, or its small-table ``summary``) and, when the column has a
1550
+ ``granularity``, rounded to a multiple of one of the ``level_steps``. The level is drawn
1551
+ with the probabilities ``level_probs[b]`` of the magnitude band ``b`` that ``Y`` lies in
1552
+ (``_fit_levels``). A column whose values all share one step has a single level, the
1553
+ granularity itself; a column with mixed granularity (most amounts in thousands, some not)
1554
+ has several. A level coarser than the granularity only produces values that are not
1555
+ atoms: within its band its draws are spread over its other multiples (a draw that would
1556
+ land on an atom is redrawn), so the atoms and the coarse levels never compete for the same
1557
+ mass. Draws at the granularity itself do land on atoms: the slab runs under the spikes,
1558
+ and an atom stores only the mass above it.
1559
+
1560
+ The output is therefore discrete on the lattice of the granularity, and ``cdf`` /
1561
+ ``cdf_left`` / ``ppf`` / ``logpdf`` are exact for it. Rounding ``Y`` to a multiple of ``L``
1562
+ gives a value ``<= x`` exactly when ``Y <= (floor(x / L) + 1/2) L``, so
1563
+
1564
+ ``F(x) = sum_{a <= x} p_a + w [sum_j G_j((floor(x / L_j) + 1/2) L_j) - R(x)] / T``
1565
+
1566
+ with ``G_j(t) = int_{y <= t} q_j(band(y)) dS(y)``, ``q_j`` the level weights (those of a
1567
+ coarse level divided by the share of its cells that are not atoms), ``R(x)`` the mass of
1568
+ the coarse cells of the atoms ``<= x`` and ``T`` the total (1 up to rounding). ``ppf`` is
1569
+ the generalised inverse: between two consecutive points where an atom sits or a coarse
1570
+ level jumps only the finest level moves, which gives a closed form (``_table``); bisection
1571
+ on ``F`` is the fallback. Without a granularity (``granularity == 0``: more than
1572
+ ``LATTICE_MAX_DECIMALS`` decimals) the slab is not rounded and
1573
+ ``F(x) = sum_{a <= x} p_a + w S(x)``.
1574
+
1575
+ Disclosure: an atom is a value held by at least ``max(min_category_support,
1576
+ ATOM_MIN_COUNT)`` rows whose stored mass (its rows beyond what the slab puts there) is
1577
+ itself at least that many rows (the category rule); the slab obeys the
1578
+ quantile-resolution and tail-clip rules of ``EmpiricalMarginal`` (on a lattice its grid
1579
+ is that of the rows spread over their rounding cells, and an extreme value bounds it only
1580
+ when that many rows hold it: ``_fit_slab``); every level weight is a share of at least
1581
+ ``min_category_support`` rows of a band of at least ``LEVEL_BAND_MIN_ROWS``. Values below
1582
+ the support threshold are never stored: they are represented by the slab.
1583
+ """
1584
+
1585
+ kind = "mixed"
1586
+
1587
+ def __init__(self, slab: MarginalModel | None, slab_weight: float,
1588
+ atoms: np.ndarray | None = None, atom_probs: np.ndarray | None = None, *,
1589
+ granularity: float = 0.0, decimals: int = 0,
1590
+ level_steps: np.ndarray | None = None,
1591
+ level_probs: np.ndarray | None = None, band_start: float = 0.0) -> None:
1592
+ a = np.asarray([] if atoms is None else atoms, dtype=np.float64).ravel()
1593
+ p = np.asarray([] if atom_probs is None else atom_probs, dtype=np.float64).ravel()
1594
+ if a.size != p.size:
1595
+ raise ValueError("mixed: atoms and atom_probs must have the same length")
1596
+ order = np.argsort(a, kind="stable")
1597
+ self.atoms = a[order]
1598
+ self.atom_probs = np.clip(p[order], 0.0, None)
1599
+ self.slab = slab
1600
+ self.slab_weight = max(float(slab_weight), 0.0) if slab is not None else 0.0
1601
+ total = self.slab_weight + float(self.atom_probs.sum())
1602
+ if not (math.isfinite(total) and total > 0):
1603
+ raise ValueError("mixed: the atoms and the slab carry no mass")
1604
+ self._w = self.slab_weight / total
1605
+ self._cum = np.concatenate([[0.0], np.cumsum(self.atom_probs / total)])
1606
+ if self._w <= 0:
1607
+ self._cum[-1] = 1.0
1608
+ self.granularity = float(granularity) if granularity and granularity > 0 else 0.0
1609
+ self.decimals = int(decimals) if self.granularity > 0 else 0
1610
+ self._lat = _Lattice(self.granularity, self.decimals) if self.granularity > 0 else None
1611
+ self.discrete = self._lat is not None
1612
+ self.band_start = float(band_start)
1613
+ self._tab: tuple[np.ndarray, ...] | None = None # quantile table, built on first use
1614
+ self._tab_built = False
1615
+ if self._lat is None:
1616
+ self.level_steps = np.zeros(0, dtype=np.float64)
1617
+ self.level_probs = np.zeros((0, 0), dtype=np.float64)
1618
+ else:
1619
+ self.granularity = self._lat.step
1620
+ self._atom_idx = self._lat.nearest(self.atoms)
1621
+ self._setup_levels(level_steps, level_probs)
1622
+ if self.slab is not None and self.atoms.size:
1623
+ hi = np.asarray(self.slab.cdf(self.atoms), dtype=np.float64)
1624
+ lo = np.minimum(np.asarray(self.slab.cdf_left(self.atoms), dtype=np.float64), hi)
1625
+ self._fc_hi = np.maximum.accumulate(self._w * hi + self._cum[1:])
1626
+ self._fc_lo = self._w * lo + self._cum[:-1]
1627
+
1628
+ def _setup_levels(self, level_steps: np.ndarray | None,
1629
+ level_probs: np.ndarray | None) -> None:
1630
+ lat = self._lat
1631
+ assert lat is not None
1632
+ if level_steps is None or np.size(level_steps) == 0:
1633
+ steps = np.array([lat.step])
1634
+ probs = np.ones((1, 1), dtype=np.float64)
1635
+ else:
1636
+ steps = np.asarray(level_steps, dtype=np.float64).ravel()
1637
+ probs = np.clip(np.atleast_2d(np.asarray(level_probs, dtype=np.float64)), 0.0, None)
1638
+ if probs.shape[1] != steps.size or probs.shape[0] < 1:
1639
+ raise ValueError("mixed: level_probs must have one column per level step")
1640
+ mults = np.maximum(np.rint(steps / lat.step), 1.0).astype(np.int64)
1641
+ if np.any(np.diff(mults) <= 0):
1642
+ raise ValueError("mixed: level steps must be increasing multiples of the "
1643
+ "granularity")
1644
+ if self.band_start <= 0 or self.slab is None:
1645
+ probs = probs[:1]
1646
+ self.level_steps = mults.astype(np.float64) * lat.step
1647
+ self.level_probs = probs # as stored; rows are normalised below
1648
+ sums = probs.sum(axis=1, keepdims=True)
1649
+ first = np.zeros_like(probs)
1650
+ first[:, 0] = 1.0
1651
+ probs = np.where(sums > 0, probs / np.where(sums > 0, sums, 1.0), first)
1652
+ self._mults = mults
1653
+ self._n_bands = n_bands = probs.shape[0]
1654
+ self._removed: np.ndarray | None = None
1655
+ self._slab_total = 1.0
1656
+ if self.slab is None:
1657
+ return
1658
+ # a coarse level spreads its draws over the multiples that are not atoms
1659
+ eff = probs.copy()
1660
+ coarse = mults > 1
1661
+ if self.atoms.size and coarse.any():
1662
+ hidden = _atom_cell_shares(lat, self.slab, self._atom_idx, mults, self.band_start,
1663
+ n_bands)
1664
+ eff[:, coarse] /= 1.0 - np.minimum(hidden[:, coarse], 1.0 - 1e-6)
1665
+ self._eff = eff
1666
+ if n_bands > 1:
1667
+ cuts, band_of = _band_layout(self.band_start, n_bands)
1668
+ self._neg_edges, self._pos_edges = cuts[:n_bands - 1], cuts[n_bands - 1:]
1669
+ s_edges = np.concatenate([
1670
+ np.asarray(self.slab.cdf(self._neg_edges), dtype=np.float64),
1671
+ np.asarray(self.slab.cdf_left(self._pos_edges), dtype=np.float64)])
1672
+ s_edges = np.maximum.accumulate(np.clip(s_edges, 0.0, 1.0))
1673
+ self._s_lo = np.concatenate([[0.0], s_edges])
1674
+ self._ds = np.concatenate([s_edges, [1.0]]) - self._s_lo
1675
+ self._iprob = eff[band_of]
1676
+ below = np.cumsum(self._iprob * self._ds[:, None], axis=0)
1677
+ self._below = np.concatenate([np.zeros((1, steps.size)), below[:-1]])
1678
+ total = float(below[-1].sum())
1679
+ else:
1680
+ total = float(eff[0].sum())
1681
+ if self.atoms.size and coarse.any():
1682
+ gone = np.zeros(self.atoms.size, dtype=np.float64)
1683
+ centre = self._atom_idx.astype(np.float64) * lat.step
1684
+ for j in np.flatnonzero(coarse & (eff.sum(axis=0) > 0)).tolist():
1685
+ on = np.flatnonzero(self._atom_idx % int(mults[j]) == 0)
1686
+ if on.size:
1687
+ half = 0.5 * float(mults[j]) * lat.step
1688
+ gone[on] += np.clip(self._level_cdf(j, centre[on] + half)
1689
+ - self._level_cdf(j, centre[on] - half), 0.0, None)
1690
+ self._removed = np.concatenate([[0.0], np.cumsum(gone)])
1691
+ total -= float(gone.sum())
1692
+ self._slab_total = total if total > 0 else 1.0
1693
+
1694
+ def _level_cdf(self, j: int, y: np.ndarray) -> np.ndarray:
1695
+ """``G_j(y)``: mass of the slab draws ``<= y`` that are rounded at level ``j``."""
1696
+ slab = self.slab
1697
+ assert slab is not None
1698
+ if self._n_bands == 1:
1699
+ return self._eff[0, j] * np.asarray(slab.cdf(y), dtype=np.float64)
1700
+ i = (np.searchsorted(self._neg_edges, y, side="left")
1701
+ + np.searchsorted(self._pos_edges, y, side="right"))
1702
+ out = self._below[i, j].copy()
1703
+ w = self._iprob[i, j]
1704
+ use = w > 0
1705
+ if use.any():
1706
+ iu = i[use]
1707
+ part = np.asarray(slab.cdf(y[use]), dtype=np.float64) - self._s_lo[iu]
1708
+ out[use] += w[use] * np.clip(part, 0.0, self._ds[iu])
1709
+ return out
1710
+
1711
+ # -- fitting -----------------------------------------------------------------------------
1712
+ @classmethod
1713
+ def fit(cls, x, *, column=None, policy=None, rng=None) -> MixedMarginal:
1714
+ pol = resolve_policy(policy)
1715
+ a = _clean(x)
1716
+ n = a.size
1717
+ k_min = max(int(pol.min_category_support), ATOM_MIN_COUNT)
1718
+ step, decimals = detect_granularity(a, min_support=pol.min_category_support)
1719
+ lat = _Lattice(step, decimals) if step > 0 else None
1720
+ if lat is not None:
1721
+ idx, counts = np.unique(lat.nearest(a), return_counts=True)
1722
+ vals = lat.value(idx)
1723
+ else:
1724
+ vals, counts = np.unique(a, return_counts=True)
1725
+ idx = np.arange(vals.size, dtype=np.int64)
1726
+ # atoms: the point masses, i.e. counts clearly above the smooth baseline around them
1727
+ is_atom, expected = point_masses(idx if lat is not None else None, counts,
1728
+ pol.min_category_support)
1729
+ cap = ATOM_CAP_FACTOR * int(pol.quantile_resolution)
1730
+ if int(is_atom.sum()) > cap:
1731
+ excess = np.where(is_atom, counts - expected, -np.inf)
1732
+ order = sorted(range(vals.size), key=lambda i: (-excess[i], vals[i]))[:cap]
1733
+ is_atom = np.zeros(vals.size, dtype=bool)
1734
+ is_atom[order] = True
1735
+
1736
+ slab: MarginalModel | None = None
1737
+ levels: tuple[np.ndarray, np.ndarray, float] | None = None
1738
+ weight, probs = 1.0, np.zeros(0, dtype=np.float64)
1739
+ for attempt in range(ATOM_PASSES):
1740
+ rows = np.where(is_atom, np.minimum(np.rint(expected), counts), counts)
1741
+ rows = rows.astype(np.int64)
1742
+ if is_atom.any() and int(rows.sum()) < max(int(pol.min_category_support), 1):
1743
+ slab, levels = None, None # too few rows for a slab: nearest atom
1744
+ kv, kc = vals[is_atom], counts[is_atom].astype(np.float64)
1745
+ rest = np.flatnonzero(~is_atom)
1746
+ j = np.clip(np.searchsorted(kv, vals[rest]), 0, kv.size - 1)
1747
+ jl = np.maximum(j - 1, 0)
1748
+ near = np.where(np.abs(vals[rest] - kv[jl]) <= np.abs(kv[j] - vals[rest]),
1749
+ jl, j)
1750
+ weight = 0.0
1751
+ probs = (kc + np.bincount(near, weights=counts[rest], minlength=kv.size)) / n
1752
+ break
1753
+ slab = _fit_slab(vals, rows, counts, lat, column, pol, rng)
1754
+ levels = None if lat is None else _fit_levels(
1755
+ lat, slab, idx, counts, is_atom, int(pol.min_category_support))
1756
+ if not is_atom.any():
1757
+ weight, probs = 1.0, np.zeros(0, dtype=np.float64)
1758
+ break
1759
+ shell = cls._build(slab, 1.0, vals[is_atom], np.zeros(int(is_atom.sum())), lat,
1760
+ levels)
1761
+ own = shell._slab_mass(vals[is_atom]) # what the slab puts on each atom value
1762
+ share = counts[is_atom] / n
1763
+ weight = min(max((1.0 - float(share.sum())) / max(1.0 - float(own.sum()), 1e-9),
1764
+ 0.0), 1.0)
1765
+ probs = share - weight * own
1766
+ tail = stats.poisson.sf(counts[is_atom] - 1, n * weight * own)
1767
+ clear = (probs * n >= k_min - 1e-9) & (tail <= ATOM_ALPHA)
1768
+ if clear.all():
1769
+ break
1770
+ is_atom[np.flatnonzero(is_atom)[~clear]] = False
1771
+ if attempt == ATOM_PASSES - 1: # not settled: the slab takes their mass
1772
+ probs = probs[clear]
1773
+ weight = 1.0 - float(probs.sum())
1774
+ return cls._finalize(slab, weight, vals[is_atom], probs, lat, levels, pol)
1775
+
1776
+ @classmethod
1777
+ def _build(cls, slab: MarginalModel | None, weight: float, atoms: np.ndarray | None,
1778
+ probs: np.ndarray | None, lat: _Lattice | None,
1779
+ levels: tuple[np.ndarray, np.ndarray, float] | None) -> MixedMarginal:
1780
+ if lat is None:
1781
+ return cls(slab, weight, atoms, probs)
1782
+ if levels is None:
1783
+ return cls(slab, weight, atoms, probs, granularity=lat.step, decimals=lat.decimals)
1784
+ mults, lprobs, start = levels
1785
+ return cls(slab, weight, atoms, probs, granularity=lat.step, decimals=lat.decimals,
1786
+ level_steps=mults.astype(np.float64) * lat.step, level_probs=lprobs,
1787
+ band_start=start)
1788
+
1789
+ @classmethod
1790
+ def _finalize(cls, slab: MarginalModel | None, weight: float, atoms: np.ndarray,
1791
+ probs: np.ndarray, lat: _Lattice | None,
1792
+ levels: tuple[np.ndarray, np.ndarray, float] | None,
1793
+ pol: DisclosurePolicySpec) -> MixedMarginal:
1794
+ """Coarsen the stored masses and weights. Atom values are stored as they are: like a
1795
+ category label, an atom is a value shared by at least ``min_category_support`` rows,
1796
+ and rounding it would move the point mass off the value that defines it."""
1797
+ if atoms.size:
1798
+ probs = coarsen_array(probs, pol)
1799
+ if levels is not None:
1800
+ mults, lprobs, start = levels
1801
+ levels = (mults, coarsen_array(lprobs, pol), start)
1802
+ return cls._build(slab, _c(weight, pol) if slab is not None else 0.0, atoms, probs,
1803
+ lat, levels)
1804
+
1805
+ # -- distribution ------------------------------------------------------------------------
1806
+ @property
1807
+ def has_atoms(self) -> bool:
1808
+ """Whether the model stores point masses (its CDF then jumps even without a
1809
+ granularity)."""
1810
+ return bool(self.atoms.size)
1811
+
1812
+ def _slab_index_cdf(self, k: np.ndarray) -> np.ndarray:
1813
+ """``P(slab output <= k * granularity)`` for lattice indices ``k``."""
1814
+ lat = self._lat
1815
+ assert lat is not None
1816
+ acc = np.zeros(k.shape, dtype=np.float64)
1817
+ if self._removed is not None:
1818
+ acc -= self._removed[np.searchsorted(self._atom_idx, k, side="right")]
1819
+ for j, m in enumerate(self._mults.tolist()):
1820
+ if self._n_bands == 1 and self._eff[0, j] <= 0:
1821
+ continue
1822
+ edge = (np.floor_divide(k, m).astype(np.float64) + 0.5) * (m * lat.step)
1823
+ acc += self._level_cdf(j, edge)
1824
+ return acc / self._slab_total
1825
+
1826
+ def _index_cdf(self, k: np.ndarray) -> np.ndarray:
1827
+ out = self._cum[np.searchsorted(self._atom_idx, k, side="right")]
1828
+ if self._w > 0:
1829
+ out = out + self._w * self._slab_index_cdf(k)
1830
+ return np.clip(out, 0.0, 1.0)
1831
+
1832
+ def _slab_mass(self, values: np.ndarray) -> np.ndarray:
1833
+ """Probability the slab alone gives each of ``values``."""
1834
+ if self.slab is None:
1835
+ return np.zeros(np.shape(values), dtype=np.float64)
1836
+ if self._lat is None:
1837
+ hi = np.asarray(self.slab.cdf(values), dtype=np.float64)
1838
+ return np.clip(hi - np.asarray(self.slab.cdf_left(values), dtype=np.float64),
1839
+ 0.0, 1.0)
1840
+ k = self._lat.nearest(values)
1841
+ return np.clip(self._slab_index_cdf(k) - self._slab_index_cdf(k - 1), 0.0, 1.0)
1842
+
1843
+ @staticmethod
1844
+ def _finish(out: np.ndarray, x: np.ndarray) -> np.ndarray:
1845
+ out = np.where(np.isposinf(x), 1.0, np.where(np.isneginf(x), 0.0, out))
1846
+ return np.where(np.isnan(x), np.nan, out)
1847
+
1848
+ def cdf(self, x):
1849
+ x = _as_x(x)
1850
+ flat = np.atleast_1d(x).ravel()
1851
+ if self._lat is not None:
1852
+ out = self._index_cdf(self._lat.floor(flat))
1853
+ else:
1854
+ out = self._cum[np.searchsorted(self.atoms, flat, side="right")]
1855
+ if self._w > 0:
1856
+ out = out + self._w * np.asarray(self.slab.cdf(flat), dtype=np.float64)
1857
+ out = np.clip(out, 0.0, 1.0)
1858
+ return self._finish(out, flat).reshape(np.shape(x))
1859
+
1860
+ def cdf_left(self, x):
1861
+ x = _as_x(x)
1862
+ flat = np.atleast_1d(x).ravel()
1863
+ if self._lat is not None:
1864
+ out = self._index_cdf(self._lat.ceil(flat) - 1)
1865
+ else:
1866
+ out = self._cum[np.searchsorted(self.atoms, flat, side="left")]
1867
+ if self._w > 0:
1868
+ out = out + self._w * np.asarray(self.slab.cdf_left(flat), dtype=np.float64)
1869
+ out = np.clip(out, 0.0, 1.0)
1870
+ return self._finish(out, flat).reshape(np.shape(x))
1871
+
1872
+ def _unrounded_ppf(self, u: np.ndarray) -> np.ndarray:
1873
+ """Quantiles of the atoms plus the *unrounded* slab (exact without a granularity)."""
1874
+ n_atoms = self.atoms.size
1875
+ if self.slab is None or self._w <= 0:
1876
+ j = np.searchsorted(self._cum[1:], u, side="left")
1877
+ return self.atoms[np.minimum(j, n_atoms - 1)]
1878
+ if n_atoms == 0:
1879
+ return np.asarray(self.slab.ppf(u), dtype=np.float64)
1880
+ i = np.searchsorted(self._fc_hi, u, side="left")
1881
+ on_atom = (i < n_atoms) & (u > self._fc_lo[np.minimum(i, n_atoms - 1)])
1882
+ out = np.asarray(self.slab.ppf(_clip_u((u - self._cum[i]) / self._w)),
1883
+ dtype=np.float64)
1884
+ out[on_atom] = self.atoms[i[on_atom]]
1885
+ return out
1886
+
1887
+ def ppf(self, u):
1888
+ u = _clip_u(u)
1889
+ # the quantile of a level a hair lower (see _PPF_SLACK)
1890
+ flat = np.maximum(np.atleast_1d(u).ravel() - _PPF_SLACK, 0.5 * U_MIN)
1891
+ lat = self._lat
1892
+ if lat is None or self.slab is None or self._w <= 0:
1893
+ return self._unrounded_ppf(flat).reshape(np.shape(u))
1894
+ table = self._table()
1895
+ if table is None:
1896
+ return lat.value(self._bisect_ppf(flat)).reshape(np.shape(u))
1897
+ bp, f_lo, f_hi, f0, s0, coef = table
1898
+ pos = np.searchsorted(f_hi, flat, side="left") # first breakpoint with F >= u
1899
+ at = np.minimum(pos, bp.size - 1)
1900
+ on_bp = (pos < bp.size) & ((flat > f_lo[at]) | (coef[pos] <= 0))
1901
+ k = np.where(on_bp, bp[at], 0)
1902
+ todo = ~on_bp & ((pos >= bp.size) | (pos == 0)) # outside the table: bisection
1903
+ inside = np.flatnonzero(~on_bp & (pos > 0) & (pos < bp.size))
1904
+ if inside.size:
1905
+ # between two breakpoints only the base level moves: F(k) = F0 + coef (S(e_k) - S0)
1906
+ st = pos[inside]
1907
+ c, base, fb, target = coef[st], s0[st], f0[st], flat[inside]
1908
+ y = np.asarray(self.slab.ppf(_clip_u(base + (target - fb) / c)), dtype=np.float64)
1909
+ ki = np.clip(lat.ceil(y - 0.5 * lat.step), bp[st - 1] + 1, bp[st] - 1)
1910
+
1911
+ def stretch_cdf(kk, sel=slice(None)):
1912
+ edge = (kk.astype(np.float64) + 0.5) * lat.step
1913
+ part = np.asarray(self.slab.cdf(edge), dtype=np.float64) - base[sel]
1914
+ return fb[sel] + c[sel] * part
1915
+
1916
+ f_k = stretch_cdf(ki)
1917
+ up = f_k < target
1918
+ ki = ki + up # one step of polish each way
1919
+ f_below = stretch_cdf(ki - 1)
1920
+ down = f_below >= target
1921
+ ki = ki - down
1922
+ # k is the quantile when F(k - 1) < u <= F(k). The polish leaves one of the two
1923
+ # unchecked for a k it moved; a comparison within the float noise of F, or one
1924
+ # that fails (the closed form was more than a step off), goes to the bisection
1925
+ f_k = np.where(down, f_below, f_k)
1926
+ moved = np.flatnonzero(up & ~down)
1927
+ f_k[moved] = stretch_cdf(ki[moved], moved)
1928
+ moved = np.flatnonzero(down)
1929
+ f_below[moved] = stretch_cdf(ki[moved] - 1, moved)
1930
+ unsure = (f_k < target + _CDF_NOISE) | (f_below > target - _CDF_NOISE)
1931
+ k[inside] = ki
1932
+ todo[inside[unsure | (ki >= bp[st]) | (ki <= bp[st - 1])]] = True
1933
+ if todo.any():
1934
+ k[todo] = self._bisect_ppf(flat[todo])
1935
+ return lat.value(k).reshape(np.shape(u))
1936
+
1937
+ def _table(self) -> tuple[np.ndarray, ...] | None:
1938
+ """Breakpoints of the lattice CDF, built on first use: every lattice index where an
1939
+ atom sits or a coarse rounding level (or the band of the base level) changes. Between
1940
+ two consecutive breakpoints only the base level moves, so the quantile there has a
1941
+ closed form. Returns ``(bp, F(bp - 1), F(bp), f0, s0, coef)`` where entry ``s`` of the
1942
+ last three describes the stretch *below* breakpoint ``s``:
1943
+ ``F(k) = f0 + coef (S((k + 1/2) step) - s0)``. ``None`` (``ppf`` then bisects) when the
1944
+ table would exceed ``_TABLE_MAX`` breakpoints. Which of the two is used depends on the
1945
+ model alone, never on the batch, so a quantile is the same in any chunking."""
1946
+ if self._tab_built:
1947
+ return self._tab
1948
+ self._tab_built = True
1949
+ lat, slab = self._lat, self.slab
1950
+ assert lat is not None and slab is not None
1951
+ mults = self._mults
1952
+ top = int(np.max(mults))
1953
+ # the range that holds all but 1e-12 of the slab; its two ends are breakpoints too, so
1954
+ # everything between them is in a stretch (quantiles beyond are found by bisection)
1955
+ k_lo = int(lat.floor(np.asarray(slab.ppf(np.array([U_MIN]))))[0]) - top - 2
1956
+ k_hi = int(lat.ceil(np.asarray(slab.ppf(np.array([U_MAX]))))[0]) + top + 2
1957
+ base_j = int(np.flatnonzero(mults == 1)[0]) if (mults == 1).any() else -1
1958
+ pieces = [self._atom_idx, np.array([k_lo, k_hi], dtype=np.int64)]
1959
+ if self._n_bands == 1:
1960
+ spans = [(k_lo, k_hi, self._eff[0])]
1961
+ else:
1962
+ cuts = np.concatenate([self._neg_edges, self._pos_edges]) / lat.step
1963
+ lows = np.concatenate([[float(k_lo)], cuts])
1964
+ highs = np.concatenate([cuts, [float(k_hi)]])
1965
+ spans = [(max(int(math.floor(lows[i])), k_lo), min(int(math.ceil(highs[i])), k_hi),
1966
+ self._iprob[i]) for i in range(lows.size) if self._ds[i] > 0]
1967
+ near = np.floor(cuts - 0.5).astype(np.int64)
1968
+ pieces.append((near[:, None] + np.arange(-1, 3)[None, :]).ravel())
1969
+ ranges = [((lo - m) // m, (hi + m) // m + 1, m) for lo, hi, probs in spans
1970
+ for j, m in enumerate(mults.tolist()) if m > 1 and probs[j] > 0 and hi >= lo]
1971
+ size = int(self._atom_idx.size) + sum(last - first + 1 for first, last, _ in ranges)
1972
+ if size > _TABLE_MAX:
1973
+ return None
1974
+ pieces += [np.arange(first, last + 1, dtype=np.int64) * m for first, last, m in ranges]
1975
+ bp = np.sort(np.concatenate(pieces))
1976
+ bp = bp[np.concatenate([[True], bp[1:] != bp[:-1]])]
1977
+ f_hi = np.maximum.accumulate(self._index_cdf(bp))
1978
+ f_lo = np.minimum(self._index_cdf(bp - 1), f_hi)
1979
+ # stretch below breakpoint s starts just above breakpoint s - 1
1980
+ start = np.concatenate([[bp[0] - 1], bp]) # index the stretch starts after
1981
+ edge = (start.astype(np.float64) + 0.5) * lat.step
1982
+ s0 = np.asarray(slab.cdf(edge), dtype=np.float64)
1983
+ f0 = np.concatenate([[0.0], f_hi])
1984
+ if base_j < 0:
1985
+ coef = np.zeros(start.size, dtype=np.float64)
1986
+ elif self._n_bands == 1:
1987
+ coef = np.full(start.size, self._w * self._eff[0, base_j] / self._slab_total)
1988
+ else:
1989
+ nxt = edge + lat.step
1990
+ i = (np.searchsorted(self._neg_edges, nxt, side="left")
1991
+ + np.searchsorted(self._pos_edges, nxt, side="right"))
1992
+ coef = self._w * self._iprob[i, base_j] / self._slab_total
1993
+ self._tab = (bp, f_lo, f_hi, f0, s0, coef)
1994
+ return self._tab
1995
+
1996
+ def _bisect_ppf(self, flat: np.ndarray) -> np.ndarray:
1997
+ """Lattice index of the quantile by bisection on the exact CDF (the rounded quantile is
1998
+ within half the coarsest level of the unrounded one; the bracket is verified)."""
1999
+ lat = self._lat
2000
+ assert lat is not None
2001
+ centre = lat.floor(self._unrounded_ppf(flat))
2002
+ half = int(np.max(self._mults)) // 2 + 1
2003
+ lo, hi = centre - half - 1, centre + half + 1
2004
+ grow = np.full(flat.shape, half + 1, dtype=np.int64)
2005
+ for _ in range(64): # guarantee F(lo) < u <= F(hi)
2006
+ short = self._index_cdf(hi) < flat
2007
+ if not short.any():
2008
+ break
2009
+ lo[short] = hi[short]
2010
+ hi[short] += grow[short]
2011
+ grow[short] *= 2
2012
+ grow[:] = half + 1
2013
+ for _ in range(64):
2014
+ over = self._index_cdf(lo) >= flat
2015
+ if not over.any():
2016
+ break
2017
+ hi[over] = lo[over]
2018
+ lo[over] -= grow[over]
2019
+ grow[over] *= 2
2020
+ while True:
2021
+ act = np.flatnonzero(hi - lo > 1)
2022
+ if act.size == 0:
2023
+ break
2024
+ mid = lo[act] + (hi[act] - lo[act]) // 2
2025
+ ge = self._index_cdf(mid) >= flat[act]
2026
+ hi[act] = np.where(ge, mid, hi[act])
2027
+ lo[act] = np.where(ge, lo[act], mid)
2028
+ return hi
2029
+
2030
+ def logpdf(self, x):
2031
+ """Log probability mass on the lattice of the granularity (a value off it is scored at
2032
+ the lattice point it rounds to). Without a granularity: the log mass of an atom, and
2033
+ ``log(w) + `` the slab's log density elsewhere."""
2034
+ x = _as_x(x)
2035
+ flat = np.atleast_1d(x).ravel()
2036
+ with np.errstate(divide="ignore"):
2037
+ if self._lat is not None:
2038
+ k = self._lat.nearest(flat)
2039
+ out = np.log(np.clip(self._index_cdf(k) - self._index_cdf(k - 1), 0.0, None))
2040
+ else:
2041
+ j = np.clip(np.searchsorted(self.atoms, flat), 0, max(self.atoms.size - 1, 0))
2042
+ hit = (self.atoms[j] == flat) if self.atoms.size else np.zeros(flat.size, bool)
2043
+ out = np.full(flat.shape, -np.inf)
2044
+ if self._w > 0:
2045
+ lp = self.slab.logpdf(flat)
2046
+ if lp is None:
2047
+ return None
2048
+ out = math.log(self._w) + np.asarray(lp, dtype=np.float64)
2049
+ if hit.any():
2050
+ out[hit] = np.log(np.diff(self._cum)[j[hit]])
2051
+ return out.reshape(np.shape(x))
2052
+
2053
+ @property
2054
+ def n_parameters(self) -> int:
2055
+ slab = self.slab.n_parameters if self.slab is not None else 0
2056
+ return int(2 * self.atoms.size + slab + np.count_nonzero(self.level_probs) + 2)
2057
+
2058
+ # -- serialisation -----------------------------------------------------------------------
2059
+ def to_spec(self, store: ArrayStore, prefix: str) -> ModelSpec:
2060
+ params: dict[str, Any] = {"granularity": self.granularity, "decimals": self.decimals,
2061
+ "slab_weight": self.slab_weight,
2062
+ "band_start": self.band_start, "slab": None}
2063
+ arrays: dict[str, str] = {}
2064
+ if self.atoms.size:
2065
+ arrays["atoms"] = store.put(f"{prefix}atoms", self.atoms)
2066
+ arrays["atom_probs"] = store.put(f"{prefix}atom_probs", self.atom_probs)
2067
+ if self.level_steps.size:
2068
+ arrays["level_steps"] = store.put(f"{prefix}level_steps", self.level_steps)
2069
+ arrays["level_probs"] = store.put(f"{prefix}level_probs", self.level_probs)
2070
+ if self.slab is not None:
2071
+ inner = self.slab.to_spec(store, f"{prefix}slab.")
2072
+ params["slab"] = {"kind": inner.kind, "params": dict(inner.params)}
2073
+ arrays.update({f"slab.{k}": v for k, v in inner.arrays.items()})
2074
+ return ModelSpec(kind=self.kind, params=params, arrays=arrays)
2075
+
2076
+ @classmethod
2077
+ def from_spec(cls, spec: ModelSpec, store: ArrayStore) -> MixedMarginal:
2078
+ p = spec.params
2079
+ slab = None
2080
+ inner = p.get("slab")
2081
+ if inner is not None:
2082
+ if not isinstance(inner, dict) or str(inner.get("kind")) not in _SLAB_KINDS:
2083
+ raise ValueError("mixed: the slab must be an 'empirical' or 'summary' marginal")
2084
+ ispec = ModelSpec(kind=str(inner["kind"]), params=dict(inner.get("params") or {}),
2085
+ arrays={k[len("slab."):]: v for k, v in spec.arrays.items()
2086
+ if k.startswith("slab.")})
2087
+ slab = MARGINALS.get(ispec.kind).from_spec(ispec, store)
2088
+
2089
+ def arr(name: str) -> np.ndarray | None:
2090
+ return store.get(spec.arrays[name]) if name in spec.arrays else None
2091
+
2092
+ return cls(slab, float(p.get("slab_weight", 0.0)), arr("atoms"), arr("atom_probs"),
2093
+ granularity=float(p.get("granularity") or 0.0),
2094
+ decimals=int(p.get("decimals") or 0), level_steps=arr("level_steps"),
2095
+ level_probs=arr("level_probs"), band_start=float(p.get("band_start") or 0.0))
2096
+
2097
+ def __repr__(self) -> str:
2098
+ return (f"MixedMarginal(atoms={self.atoms.size}, slab_weight={self.slab_weight:.6g}, "
2099
+ f"granularity={self.granularity:.6g}, levels={self.level_steps.size})")