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,1087 @@
1
+ """Forest-partitioned copula (kind ``"forest_copula"``) over latent standard-normal scores.
2
+
3
+ An adversarial random forest (ARF; Watson, Blesch, Kapar & Wright, AISTATS 2023) is grown in
4
+ the latent space of the mixed-type encoder and its leaves are turned into a density, as in the
5
+ paper's FORDE step. Everything is numpy; nothing is pickled.
6
+
7
+ * **Coordinates.** The forest works on whitened scores ``w = A^-1 z`` with ``A = R^(1/2)``, the
8
+ symmetric square root of the latent sample correlation, and its draws are mapped back as
9
+ ``z = M w``. ``M = A`` by default; when the encoder's rank moments are passed (``hermite`` /
10
+ ``attenuation``, as for the Gaussian copula) ``M = R*^(1/2)`` with ``R*`` the Gaussian
11
+ copula's rank-moment (polychoric-type) correlation, which undoes the dilution that jittering
12
+ inside category intervals causes. Axis-aligned leaves with independent columns cannot hold
13
+ a strong linear chain (credit's monthly bills, at latent correlation 0.87, came out at 0.70);
14
+ in whitened coordinates the chain is carried by ``M`` and the forest models what is left.
15
+ ``whiten=False`` is plain ARF on ``z``.
16
+ * **Bins.** Every coordinate is cut at the same ``n_bins - 1`` edges ``Phi^-1(k / n_bins)``.
17
+ They are constants of the model, not statistics of the data, and every split threshold is
18
+ one of them (stored as a bin index).
19
+ * **Trees.** Histogram Gini classification trees grown level by level: a bootstrap sample of
20
+ the real + synthetic rows, ``floor(sqrt(d))`` candidate coordinates per split (or
21
+ ``max_features``), at least ``min_samples_leaf`` bootstrap rows per leaf (``2 * leaf_min``:
22
+ about half of a leaf is real), depth at most ``max_depth``.
23
+ * **Adversarial loop.** The first synthetic table permutes each coordinate independently (the
24
+ product of the marginals); a forest learns to tell it from the real rows. While the
25
+ out-of-bag accuracy exceeds ``0.5 + delta`` (at most ``max_iters`` rounds; ``early_stop``
26
+ ends the loop when the accuracy stops falling) the next synthetic table is drawn from the
27
+ current forest's leaf model -- pruned and fitted exactly as the stored model, so the
28
+ discriminator sees the leaves' truncated-normal smoothing -- and a new forest is trained
29
+ against it. The leaf model whose table the next discriminator found hardest to tell from
30
+ the real rows is kept.
31
+ * **Disclosure.** ``leaf_min = max(policy.min_category_support, 5)``. The kept forest is pruned
32
+ on all real fit rows: a leaf holding 1 to ``leaf_min - 1`` of them is removed by replacing
33
+ its parent with its sibling, until every leaf describes at least ``leaf_min`` real rows or
34
+ none. A leaf without real rows describes nobody: it stays in the tree as an empty region
35
+ with zero weight (a suppressed zero cell), so the forest can exclude regions the data never
36
+ visits. Coverages, leaf parameters and ``M`` are coarsened to the policy's significant
37
+ digits; leaf locations are further rounded to multiples of ``LOC_QUANTUM`` and scales and
38
+ coverages to ``STORE_BITS`` significant bits (coarser than any profile; it also lets the
39
+ float32 arrays compress about 2:1). No row-level value is stored.
40
+ * **Leaves (FORDE).** A leaf stores its *coverage* (its share of the real rows) and, per
41
+ coordinate, a truncated normal on the leaf's box (the splits on its path, intersected with
42
+ ``[-Z_LIMIT, Z_LIMIT]``) fitted to its real rows by maximum likelihood, which for a
43
+ truncated normal matches their mean and variance (Newton in the natural parameters).
44
+ * **Sampling.** Pick a leaf with probability ``coverage / n_trees`` (a tree uniformly, then a
45
+ leaf in proportion to its coverage), draw each coordinate independently from its truncated
46
+ normal by inverse CDF (in log space), map back with ``M``, and **re-standardise** every
47
+ column to exactly N(0, 1) through the model's own marginal: ``z = Phi^-1(F_j(x))`` with
48
+ ``F_j`` a quantile grid computed at fit time from ``GRID_SAMPLE`` seeded draws of the model
49
+ (model-derived, not data) and linear interpolation in it. The output is the copula of the
50
+ forest density, as for the mixture copula.
51
+
52
+ Spec: ``params`` hold the columns, the hyper-parameters, the iteration count and out-of-bag
53
+ accuracies; ``arrays`` hold ``bin_edges``, ``leaf_coverage``, ``leaf_loc``, ``leaf_scale``,
54
+ ``mixing`` (``M``) and ``marginal_quantiles`` (float32), ``nodes`` (int32 ``(nodes, 4)``:
55
+ coordinate, threshold bin, left, right; a leaf has coordinate ``-1`` and its row in the leaf
56
+ arrays in ``left``, ``-1`` when empty; the trees are concatenated with node ids local to each
57
+ tree) and ``tree_offsets`` (int32).
58
+ """
59
+
60
+ from __future__ import annotations
61
+
62
+ import math
63
+ from typing import Any, NamedTuple
64
+
65
+ import numpy as np
66
+ from scipy import special
67
+
68
+ from ectype.fingerprint.core import ArrayStore
69
+ from ectype.fingerprint.schema import DisclosurePolicySpec, ModelSpec
70
+ from ectype.models.base import JOINTS, JointModel
71
+ from ectype.models.copulas import _check_z, nearest_correlation, sample_correlation
72
+
73
+ DEFAULT_TREES = 10
74
+ DEFAULT_BINS = 64
75
+ DEFAULT_MAX_DEPTH = 48
76
+ DEFAULT_DELTA = 0.01
77
+ DEFAULT_MAX_ITERS = 10
78
+ #: fit rows above this are subsampled (fit time and leaf count grow with the row count)
79
+ MAX_FIT_ROWS = 50_000
80
+ #: smallest leaf the disclosure rule allows, whatever the policy says
81
+ MIN_LEAF_FLOOR = 5
82
+ #: latent scores are clipped to about +-6.1 by the encoder; boxes are cut at this bound
83
+ Z_LIMIT = 8.5
84
+ #: the marginal quantile grid: ``GRID_POINTS`` normal scores evenly spaced on
85
+ #: ``[-GRID_Z, GRID_Z]``, estimated from ``GRID_SAMPLE`` seeded model draws
86
+ GRID_POINTS = 151
87
+ GRID_Z = 3.75
88
+ GRID_SAMPLE = 1 << 17
89
+ #: grid steps used for the slope of the linear extrapolation beyond the grid
90
+ _EXTRAP_STEPS = 10
91
+ #: smallest stored truncated-normal scale (latent units)
92
+ MIN_SCALE = 1e-3
93
+ #: truncated-normal fit: data-standardised bounds beyond this do not bind
94
+ _FREE = 5.0
95
+ #: ... the quadrature domain is cut at this many data standard deviations
96
+ _SPAN = 8.0
97
+ #: ... and the parent scale / location are kept within these (data standard deviations)
98
+ _MAX_PARENT_SCALE = 8.0
99
+ _MAX_PARENT_SHIFT = 30.0
100
+ _GL_X, _GL_W = np.polynomial.legendre.leggauss(32)
101
+ #: whitening: eigenvalues of the latent correlation are floored here before the square root
102
+ MIN_WHITEN_EIGENVALUE = 1e-3
103
+ #: a latent column whose rank variance ``12 * sum(coef^2)`` (encoder moments) is below this is
104
+ #: jittered (ties, categories, indicators, imputed missing scores)
105
+ CONTINUOUS_RANK_VARIANCE = 0.95
106
+ #: stored leaf locations are multiples of ``LOC_QUANTUM``; scales and coverages keep
107
+ #: ``STORE_BITS`` significant bits (coarser than any profile's significant digits, and the
108
+ #: zeroed low mantissa bits make the float32 arrays compress about 2:1)
109
+ LOC_QUANTUM = 2.0 ** -10
110
+ STORE_BITS = 10
111
+
112
+
113
+ class _Tree(NamedTuple):
114
+ feature: np.ndarray # int64 (m,), -1 for a leaf
115
+ threshold: np.ndarray # int64 (m,), go left iff bin <= threshold
116
+ left: np.ndarray # int64 (m,)
117
+ right: np.ndarray # int64 (m,)
118
+ value: np.ndarray # float64 (m,), share of real rows (training only)
119
+
120
+
121
+ def leaf_min_for(policy: DisclosurePolicySpec) -> int:
122
+ """The smallest number of real rows a stored leaf may describe."""
123
+ return max(int(policy.min_category_support), MIN_LEAF_FLOOR)
124
+
125
+
126
+ def _coarsen(a: np.ndarray, policy: DisclosurePolicySpec) -> np.ndarray:
127
+ """Vectorised ``disclosure.coarsen``: round to the policy's significant digits."""
128
+ a = np.asarray(a, dtype=np.float64)
129
+ out = a.copy()
130
+ ok = np.isfinite(a) & (a != 0)
131
+ if ok.any():
132
+ e = np.floor(np.log10(np.abs(a[ok])))
133
+ scale = 10.0 ** (int(policy.significant_digits) - 1 - e)
134
+ out[ok] = np.round(a[ok] * scale) / scale
135
+ return out
136
+
137
+
138
+ def _f32(a: np.ndarray) -> np.ndarray:
139
+ """The float64 values a float32 array stores (fit and load see identical numbers)."""
140
+ return np.asarray(a, dtype=np.float32).astype(np.float64)
141
+
142
+
143
+ def bin_edges(n_bins: int) -> np.ndarray:
144
+ """Interior bin edges ``Phi^-1(k / n_bins)``, ``k = 1..n_bins-1`` (float32 values). They are
145
+ constants of the model, not statistics of the data, so the policy has nothing to coarsen."""
146
+ k = np.arange(1, n_bins, dtype=np.float64)
147
+ return _f32(special.ndtri(k / n_bins))
148
+
149
+
150
+ def _binize(z: np.ndarray, edges: np.ndarray) -> np.ndarray:
151
+ out = np.empty(z.shape, dtype=np.uint8)
152
+ for j in range(z.shape[1]):
153
+ out[:, j] = np.searchsorted(edges, z[:, j], side="right")
154
+ return out
155
+
156
+
157
+ # ---------------------------------------------------------------------------------------------
158
+ # Trees: histogram-based Gini classification trees, grown level by level
159
+ # ---------------------------------------------------------------------------------------------
160
+
161
+ def _grow(xb: np.ndarray, y: np.ndarray, weight: np.ndarray, rng: np.random.Generator, *,
162
+ m_try: int, min_leaf: int, max_depth: int, n_bins: int) -> _Tree:
163
+ """One classification tree on the rows with bootstrap count ``weight > 0``.
164
+
165
+ Splits go left when ``bin <= threshold``. A node is split by the best Gini decrease among
166
+ ``m_try`` random columns (fresh per node) and every threshold that leaves at least
167
+ ``min_leaf`` (weighted) bootstrap rows on both sides; pure nodes, nodes with fewer than
168
+ ``2 * min_leaf`` rows and nodes at ``max_depth`` are leaves.
169
+ """
170
+ d = xb.shape[1]
171
+ nb = int(n_bins)
172
+ rows = np.flatnonzero(weight > 0)
173
+ r_w = weight[rows].astype(np.float64)
174
+ r_w1 = r_w * y[rows]
175
+ r_pos = np.zeros(rows.size, dtype=np.int64) # position of the row's node in level
176
+ n_level = 1
177
+ first_id = 0
178
+ feats_out: list[np.ndarray] = []
179
+ thr_out: list[np.ndarray] = []
180
+ left_out: list[np.ndarray] = []
181
+ right_out: list[np.ndarray] = []
182
+ value_out: list[np.ndarray] = []
183
+ slots = np.arange(m_try, dtype=np.int64)
184
+ depth = 0
185
+ while n_level:
186
+ tw = np.bincount(r_pos, weights=r_w, minlength=n_level)
187
+ t1 = np.bincount(r_pos, weights=r_w1, minlength=n_level)
188
+ feature = np.full(n_level, -1, dtype=np.int64)
189
+ threshold = np.full(n_level, -1, dtype=np.int64)
190
+ left = np.full(n_level, -1, dtype=np.int64)
191
+ right = np.full(n_level, -1, dtype=np.int64)
192
+ value = np.divide(t1, tw, out=np.zeros(n_level), where=tw > 0)
193
+ can = (tw >= 2 * min_leaf) & (t1 > 1e-9) & (tw - t1 > 1e-9)
194
+ if depth >= max_depth:
195
+ can[:] = False
196
+ sub = np.flatnonzero(can)
197
+ split = np.zeros(n_level, dtype=bool)
198
+ n_next = 0
199
+ if sub.size:
200
+ s = sub.size
201
+ where = np.full(n_level, -1, dtype=np.int64)
202
+ where[sub] = np.arange(s)
203
+ sel = np.flatnonzero(can[r_pos])
204
+ sp = where[r_pos[sel]]
205
+ feats = np.argpartition(rng.random((s, d)), m_try - 1, axis=1)[:, :m_try] \
206
+ if m_try < d else np.tile(np.arange(d), (s, 1))
207
+ vals = xb[rows[sel][:, None], feats[sp]]
208
+ key = ((sp[:, None] * m_try + slots[None, :]) * nb + vals).ravel()
209
+ size = s * m_try * nb
210
+ hw = np.bincount(key, weights=np.repeat(r_w[sel], m_try), minlength=size)
211
+ h1 = np.bincount(key, weights=np.repeat(r_w1[sel], m_try), minlength=size)
212
+ cw = np.cumsum(hw.reshape(s, m_try, nb), axis=2)[:, :, :-1]
213
+ c1 = np.cumsum(h1.reshape(s, m_try, nb), axis=2)[:, :, :-1]
214
+ tot_w = tw[sub][:, None, None]
215
+ tot_1 = t1[sub][:, None, None]
216
+ rw = tot_w - cw
217
+ r1 = tot_1 - c1
218
+ valid = (cw >= min_leaf) & (rw >= min_leaf)
219
+ with np.errstate(divide="ignore", invalid="ignore"):
220
+ score = (c1 * c1 + (cw - c1) ** 2) / cw + (r1 * r1 + (rw - r1) ** 2) / rw
221
+ score = np.where(valid, score, -np.inf).reshape(s, -1)
222
+ best = np.argmax(score, axis=1)
223
+ best_score = score[np.arange(s), best]
224
+ t0 = tw[sub] - t1[sub]
225
+ parent = (t1[sub] ** 2 + t0 ** 2) / tw[sub]
226
+ ok = np.isfinite(best_score) & (best_score - parent > 1e-9 * tw[sub])
227
+ if ok.any():
228
+ k = np.flatnonzero(ok)
229
+ nodes = sub[k]
230
+ slot, thr = np.divmod(best[k], nb - 1)
231
+ feature[nodes] = feats[k, slot]
232
+ threshold[nodes] = thr
233
+ split[nodes] = True
234
+ n_split = nodes.size
235
+ base = first_id + n_level
236
+ left[nodes] = base + 2 * np.arange(n_split)
237
+ right[nodes] = left[nodes] + 1
238
+ n_next = 2 * n_split
239
+ feats_out.append(feature)
240
+ thr_out.append(threshold)
241
+ left_out.append(left)
242
+ right_out.append(right)
243
+ value_out.append(value)
244
+ if not n_next:
245
+ break
246
+ # route the rows of split nodes to the children (positions in the next level)
247
+ keep = split[r_pos]
248
+ rows, r_w, r_w1, r_pos = rows[keep], r_w[keep], r_w1[keep], r_pos[keep]
249
+ f = feature[r_pos]
250
+ go_right = xb[rows, f] > threshold[r_pos]
251
+ rank = np.cumsum(split) - 1 # index of the split among the level's
252
+ r_pos = 2 * rank[r_pos] + go_right
253
+ first_id += n_level
254
+ n_level = n_next
255
+ depth += 1
256
+ return _Tree(np.concatenate(feats_out), np.concatenate(thr_out),
257
+ np.concatenate(left_out), np.concatenate(right_out),
258
+ np.concatenate(value_out))
259
+
260
+
261
+ def _route(tree: _Tree | tuple[np.ndarray, ...], xb: np.ndarray,
262
+ rows: np.ndarray | None = None) -> np.ndarray:
263
+ """Node id of the leaf each row (of ``xb``, or of ``xb[rows]``) falls into."""
264
+ feature, threshold, left, right = tree[0], tree[1], tree[2], tree[3]
265
+ n = xb.shape[0] if rows is None else rows.size
266
+ node = np.zeros(n, dtype=np.int64)
267
+ idx = np.arange(n)
268
+ while idx.size:
269
+ nd = node[idx]
270
+ f = feature[nd]
271
+ inner = f >= 0
272
+ if not inner.all():
273
+ idx, nd, f = idx[inner], nd[inner], f[inner]
274
+ if not idx.size:
275
+ break
276
+ r = idx if rows is None else rows[idx]
277
+ node[idx] = np.where(xb[r, f] <= threshold[nd], left[nd], right[nd])
278
+ return node
279
+
280
+
281
+ def _train(xb_real: np.ndarray, xb_syn: np.ndarray, rng: np.random.Generator, *,
282
+ n_trees: int, m_try: int, min_leaf: int, max_depth: int,
283
+ n_bins: int) -> tuple[list[_Tree], float]:
284
+ """Train the discriminator forest; returns ``(trees, out-of-bag accuracy)``."""
285
+ xb = np.vstack([xb_real, xb_syn])
286
+ y = np.concatenate([np.ones(len(xb_real)), np.zeros(len(xb_syn))])
287
+ n = len(y)
288
+ trees: list[_Tree] = []
289
+ vote = np.zeros(n)
290
+ count = np.zeros(n)
291
+ for _ in range(n_trees):
292
+ w = np.bincount(rng.integers(0, n, n), minlength=n)
293
+ tree = _grow(xb, y, w, rng, m_try=m_try, min_leaf=min_leaf, max_depth=max_depth,
294
+ n_bins=n_bins)
295
+ oob = np.flatnonzero(w == 0)
296
+ vote[oob] += tree.value[_route(tree, xb, oob)]
297
+ count[oob] += 1.0
298
+ trees.append(tree)
299
+ seen = count > 0
300
+ if not seen.any():
301
+ return trees, 1.0
302
+ p = vote[seen] / count[seen]
303
+ real = y[seen] == 1
304
+ correct = np.where(p > 0.5, real, np.where(p < 0.5, ~real, 0.5)).astype(np.float64)
305
+ return trees, float(correct.mean())
306
+
307
+
308
+ # ---------------------------------------------------------------------------------------------
309
+ # Pruning (disclosure), leaf boxes and the leaf model (FORDE)
310
+ # ---------------------------------------------------------------------------------------------
311
+
312
+ def _reachable(feature: np.ndarray, left: np.ndarray, right: np.ndarray
313
+ ) -> tuple[np.ndarray, np.ndarray]:
314
+ """Breadth-first node order from the root and each listed node's depth."""
315
+ order = [np.zeros(1, dtype=np.int64)]
316
+ depth = [np.zeros(1, dtype=np.int64)]
317
+ frontier = order[0]
318
+ level = 0
319
+ while frontier.size:
320
+ inner = frontier[feature[frontier] >= 0]
321
+ level += 1
322
+ frontier = np.column_stack([left[inner], right[inner]]).ravel()
323
+ if frontier.size:
324
+ order.append(frontier)
325
+ depth.append(np.full(frontier.size, level, dtype=np.int64))
326
+ return np.concatenate(order), np.concatenate(depth)
327
+
328
+
329
+ def _prune(tree: _Tree, xb_real: np.ndarray, leaf_min: int) -> _Tree:
330
+ """Remove every leaf holding between 1 and ``leaf_min - 1`` real rows by replacing its
331
+ parent with its sibling (its rows then fall into the sibling's subtree), then renumber the
332
+ surviving nodes breadth-first. Leaves without real rows stay: they describe nobody and
333
+ become empty regions of the tree (zero weight), like a suppressed zero cell."""
334
+ feature, threshold = tree.feature.copy(), tree.threshold.copy()
335
+ left, right = tree.left.copy(), tree.right.copy()
336
+ m = feature.size
337
+ parent = np.full(m, -1, dtype=np.int64)
338
+ inner = np.flatnonzero(feature >= 0)
339
+ parent[left[inner]] = inner
340
+ parent[right[inner]] = inner
341
+ while True:
342
+ cur = (feature, threshold, left, right)
343
+ counts = np.bincount(_route(cur, xb_real), minlength=m)
344
+ nodes, depth = _reachable(feature, left, right)
345
+ is_leaf = feature[nodes] < 0
346
+ c = counts[nodes]
347
+ small = is_leaf & (c > 0) & (c < leaf_min) & (parent[nodes] >= 0)
348
+ if not small.any():
349
+ break
350
+ cand = nodes[small][np.argsort(-depth[small], kind="stable")]
351
+ touched = np.zeros(m, dtype=bool)
352
+ for s in cand:
353
+ p = parent[s]
354
+ if touched[s] or touched[p]:
355
+ continue
356
+ sib = left[p] if right[p] == s else right[p]
357
+ feature[p], threshold[p] = feature[sib], threshold[sib]
358
+ left[p], right[p] = left[sib], right[sib]
359
+ if feature[sib] >= 0:
360
+ parent[left[sib]] = p
361
+ parent[right[sib]] = p
362
+ touched[[p, s, sib]] = True
363
+ nodes, _ = _reachable(feature, left, right)
364
+ new_id = np.full(m, -1, dtype=np.int64)
365
+ new_id[nodes] = np.arange(nodes.size)
366
+ f = feature[nodes]
367
+ inner_new = f >= 0
368
+ lft = np.where(inner_new, new_id[np.where(inner_new, left[nodes], 0)], -1)
369
+ rgt = np.where(inner_new, new_id[np.where(inner_new, right[nodes], 0)], -1)
370
+ return _Tree(f, np.where(inner_new, threshold[nodes], -1), lft, rgt,
371
+ np.zeros(nodes.size))
372
+
373
+
374
+ def _leaf_boxes(tree: _Tree | tuple[np.ndarray, ...], d: int, n_bins: int
375
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
376
+ """Leaf node ids (breadth-first) and their boxes as bin ranges ``[lo, hi)`` per column."""
377
+ feature, threshold, left, right = tree[0], tree[1], tree[2], tree[3]
378
+ m = feature.size
379
+ lo = np.zeros((m, d), dtype=np.int64)
380
+ hi = np.full((m, d), n_bins, dtype=np.int64)
381
+ nodes, _ = _reachable(feature, left, right)
382
+ for k in nodes: # parents precede children
383
+ f = feature[k]
384
+ if f < 0:
385
+ continue
386
+ lo[left[k]], hi[left[k]] = lo[k], hi[k]
387
+ lo[right[k]], hi[right[k]] = lo[k], hi[k]
388
+ hi[left[k], f] = threshold[k] + 1
389
+ lo[right[k], f] = threshold[k] + 1
390
+ leaves = nodes[feature[nodes] < 0]
391
+ return leaves, lo[leaves], hi[leaves]
392
+
393
+
394
+ class _Forde(NamedTuple):
395
+ """The leaf model of a pruned forest (FORDE)."""
396
+
397
+ trees: list[_Tree] # a leaf's ``left`` is its row in the arrays below, -1 if empty
398
+ tree_of: np.ndarray # (L,) tree of each leaf
399
+ support: np.ndarray # (L,) real rows per leaf (>= leaf_min)
400
+ lo: np.ndarray # (L, d) leaf box in whitened units
401
+ hi: np.ndarray
402
+ loc: np.ndarray # (L, d) truncated-normal parent location and scale
403
+ scale: np.ndarray
404
+
405
+ def weights(self) -> np.ndarray:
406
+ """Mixture weight of every leaf: a tree uniformly, then its coverage."""
407
+ tot = np.bincount(self.tree_of, weights=self.support, minlength=len(self.trees))
408
+ return self.support / tot[self.tree_of] / len(self.trees)
409
+
410
+ def sample(self, n: int, rng: np.random.Generator) -> np.ndarray:
411
+ cum = np.cumsum(self.weights())
412
+ leaf = np.minimum(np.searchsorted(cum / cum[-1], rng.random(n), side="right"),
413
+ cum.size - 1)
414
+ u = rng.random((n, self.lo.shape[1]))
415
+ return _tn_sample(self.lo[leaf], self.hi[leaf], self.loc[leaf], self.scale[leaf], u)
416
+
417
+
418
+ def _forde_fit(forest: list[_Tree], w: np.ndarray, xb: np.ndarray, leaf_min: int,
419
+ ext: np.ndarray) -> _Forde:
420
+ """Prune every tree on the real rows, then fit each non-empty leaf's coverage and its
421
+ per-column truncated normals (moments of the leaf's real rows, box from the splits)."""
422
+ n, d = w.shape
423
+ n_bins = ext.size - 1
424
+ trees: list[_Tree] = []
425
+ tree_of, cnt_l, lo_l, hi_l, mean_l, var_l = [], [], [], [], [], []
426
+ n_leaf = 0
427
+ for t, tree in enumerate(forest):
428
+ pruned = _prune(tree, xb, leaf_min)
429
+ leaves, lo_b, hi_b = _leaf_boxes(pruned, d, n_bins)
430
+ node_leaf = np.full(pruned.feature.size, -1, dtype=np.int64)
431
+ node_leaf[leaves] = np.arange(leaves.size)
432
+ row_leaf = node_leaf[_route(pruned, xb)]
433
+ cnt = np.bincount(row_leaf, minlength=leaves.size).astype(np.float64)
434
+ s1 = np.empty((leaves.size, d))
435
+ s2 = np.empty((leaves.size, d))
436
+ for j in range(d):
437
+ s1[:, j] = np.bincount(row_leaf, weights=w[:, j], minlength=leaves.size)
438
+ s2[:, j] = np.bincount(row_leaf, weights=w[:, j] ** 2, minlength=leaves.size)
439
+ keep = cnt > 0
440
+ k = int(keep.sum())
441
+ mean = s1[keep] / cnt[keep, None]
442
+ index = np.full(leaves.size, -1, dtype=np.int64)
443
+ index[keep] = n_leaf + np.arange(k)
444
+ left = pruned.left.copy()
445
+ left[leaves] = index
446
+ trees.append(pruned._replace(left=left))
447
+ tree_of.append(np.full(k, t, dtype=np.int64))
448
+ cnt_l.append(cnt[keep])
449
+ lo_l.append(ext[lo_b[keep]])
450
+ hi_l.append(ext[hi_b[keep]])
451
+ mean_l.append(mean)
452
+ var_l.append(np.maximum(s2[keep] / cnt[keep, None] - mean ** 2, 0.0))
453
+ n_leaf += k
454
+ lo, hi = np.vstack(lo_l), np.vstack(hi_l)
455
+ loc, scale = fit_truncnorm(lo.ravel(), hi.ravel(), np.vstack(mean_l).ravel(),
456
+ np.vstack(var_l).ravel())
457
+ return _Forde(trees, np.concatenate(tree_of), np.concatenate(cnt_l), lo, hi,
458
+ loc.reshape(n_leaf, d), np.maximum(scale, MIN_SCALE).reshape(n_leaf, d))
459
+
460
+
461
+ # ---------------------------------------------------------------------------------------------
462
+ # Truncated normals
463
+ # ---------------------------------------------------------------------------------------------
464
+
465
+ def _log_partition(eta1: np.ndarray, eta2: np.ndarray, x: np.ndarray, x2: np.ndarray,
466
+ wq: np.ndarray) -> np.ndarray:
467
+ e = eta1[:, None] * x + eta2[:, None] * x2
468
+ top = e.max(axis=1)
469
+ return np.log((wq * np.exp(e - top[:, None])).sum(axis=1)) + top
470
+
471
+
472
+ def _max_step(eta1: np.ndarray, eta2: np.ndarray, s1: np.ndarray, s2: np.ndarray,
473
+ eta2_max: float) -> np.ndarray:
474
+ """Largest step along ``(s1, s2)`` that keeps ``eta2 <= eta2_max`` and
475
+ ``|eta1| <= -2 * _MAX_PARENT_SHIFT * eta2`` (parent scale and shift bounds)."""
476
+ c = 2.0 * _MAX_PARENT_SHIFT
477
+ tau = np.ones_like(eta1)
478
+ for slack, rate in ((eta2_max - eta2, s2), (-c * eta2 - eta1, s1 + c * s2),
479
+ (-c * eta2 + eta1, -s1 + c * s2)):
480
+ hit = rate > 0
481
+ tau = np.where(hit, np.minimum(tau, np.maximum(slack, 0.0) / np.where(hit, rate, 1.0)),
482
+ tau)
483
+ return tau
484
+
485
+
486
+ def fit_truncnorm(lo: np.ndarray, hi: np.ndarray, mean: np.ndarray, var: np.ndarray, *,
487
+ iters: int = 30) -> tuple[np.ndarray, np.ndarray]:
488
+ """Parent ``(loc, scale)`` of the normal whose truncation to ``[lo, hi]`` has the given
489
+ mean and variance: the maximum-likelihood truncated normal of rows with those moments.
490
+
491
+ The truncated normal is an exponential family in ``(x, x^2)``, so the log-likelihood is
492
+ concave in the natural parameters ``(mu / s^2, -1 / (2 s^2))``: vectorised Newton steps
493
+ with an Armijo backtracking line search, the moments by 32-point Gauss-Legendre
494
+ quadrature in units of the data's standard deviation (domain cut at ``_SPAN``). The parent
495
+ is kept within ``_MAX_PARENT_SCALE`` and ``_MAX_PARENT_SHIFT`` data standard deviations.
496
+ Bounds more than ``_FREE`` standard deviations away do not bind (``loc = mean``,
497
+ ``scale = sd``). Moments that no truncated normal reaches (rows piled at both edges, or
498
+ more steeply than exponentially against one) end at the nearest allowed parent.
499
+ """
500
+ lo, hi, mean = (np.asarray(v, dtype=np.float64) for v in (lo, hi, mean))
501
+ sd = np.sqrt(np.maximum(np.asarray(var, dtype=np.float64), MIN_SCALE ** 2))
502
+ loc, scale = mean.copy(), sd.copy()
503
+ with np.errstate(invalid="ignore"):
504
+ a = (lo - mean) / sd
505
+ b = (hi - mean) / sd
506
+ bind = (a > -_FREE) | (b < _FREE)
507
+ if not bind.any():
508
+ return loc, scale
509
+ a = np.clip(a[bind], -_SPAN, 0.0)
510
+ b = np.clip(b[bind], 0.0, _SPAN)
511
+ half, mid = 0.5 * (b - a), 0.5 * (b + a)
512
+ x = mid[:, None] + half[:, None] * _GL_X[None, :]
513
+ wq = half[:, None] * _GL_W[None, :]
514
+ x2 = x * x
515
+ k = a.size
516
+ eta1, eta2 = np.zeros(k), np.full(k, -0.5)
517
+ eta2_max = -0.5 / _MAX_PARENT_SCALE ** 2
518
+ active = np.ones(k, dtype=bool)
519
+ for _ in range(iters):
520
+ idx = np.flatnonzero(active)
521
+ if not idx.size:
522
+ break
523
+ xi, xi2, wi = x[idx], x2[idx], wq[idx]
524
+ e1, e2 = eta1[idx], eta2[idx]
525
+ e = e1[:, None] * xi + e2[:, None] * xi2
526
+ top = e.max(axis=1)
527
+ p = wi * np.exp(e - top[:, None])
528
+ zsum = p.sum(axis=1)
529
+ p /= zsum[:, None]
530
+ log_z = np.log(zsum) + top
531
+ px = p * xi
532
+ px2 = px * xi
533
+ m1, m2 = px.sum(axis=1), px2.sum(axis=1)
534
+ m3, m4 = (px2 * xi).sum(axis=1), (px2 * xi2).sum(axis=1)
535
+ g1, g2 = -m1, 1.0 - m2 # gradient of the log-likelihood
536
+ done = (np.abs(g1) < 1e-9) & (np.abs(g2) < 1e-9)
537
+ c11, c12, c22 = m2 - m1 * m1, m3 - m1 * m2, m4 - m2 * m2
538
+ det = c11 * c22 - c12 * c12
539
+ safe = (det > 1e-300) & ~done
540
+ s1 = np.where(safe, (c22 * g1 - c12 * g2) / np.where(safe, det, 1.0), 0.0)
541
+ s2 = np.where(safe, (c11 * g2 - c12 * g1) / np.where(safe, det, 1.0), 0.0)
542
+ ll = e2 - log_z # loglik per row at t = (0, 1)
543
+ slope = g1 * s1 + g2 * s2 # >= 0 (positive-definite Hessian)
544
+ # stay strictly inside the bounds: an iterate on the boundary whose Newton direction
545
+ # points outwards could not move again, even when the optimum is interior
546
+ tau = _max_step(e1, e2, s1, s2, eta2_max)
547
+ tau = np.where(tau < 1.0, 0.5 * tau, 1.0)
548
+ accept = np.zeros(idx.size, dtype=bool)
549
+ new1, new2 = e1.copy(), e2.copy()
550
+ for _ in range(12):
551
+ todo = np.flatnonzero(safe & ~accept & (tau > 1e-9))
552
+ if not todo.size:
553
+ break
554
+ t1 = e1[todo] + tau[todo] * s1[todo]
555
+ t2 = np.minimum(e2[todo] + tau[todo] * s2[todo], eta2_max)
556
+ ll_new = t2 - _log_partition(t1, t2, xi[todo], xi2[todo], wi[todo])
557
+ ok = ll_new >= ll[todo] + 1e-4 * tau[todo] * slope[todo] - 1e-12
558
+ hit = todo[ok]
559
+ new1[hit], new2[hit] = t1[ok], t2[ok]
560
+ accept[hit] = True
561
+ tau[todo[~ok]] *= 0.25
562
+ eta1[idx], eta2[idx] = new1, new2
563
+ active[idx[~safe | ~accept]] = False
564
+ sig2 = -0.5 / eta2
565
+ loc[bind] = mean[bind] + sd[bind] * eta1 * sig2
566
+ scale[bind] = sd[bind] * np.sqrt(sig2)
567
+ return loc, scale
568
+ a = np.clip(a[bind], -_SPAN, 0.0)
569
+ b = np.clip(b[bind], 0.0, _SPAN)
570
+ half, mid = 0.5 * (b - a), 0.5 * (b + a)
571
+ x = mid[:, None] + half[:, None] * _GL_X[None, :]
572
+ wq = half[:, None] * _GL_W[None, :]
573
+ x2 = x * x
574
+ k = a.size
575
+ eta1, eta2 = np.zeros(k), np.full(k, -0.5)
576
+ eta2_max = -0.5 / _MAX_PARENT_SCALE ** 2
577
+ active = np.ones(k, dtype=bool)
578
+ for _ in range(iters):
579
+ idx = np.flatnonzero(active)
580
+ if not idx.size:
581
+ break
582
+ xi, xi2, wi = x[idx], x2[idx], wq[idx]
583
+ e1, e2 = eta1[idx], eta2[idx]
584
+ e = e1[:, None] * xi + e2[:, None] * xi2
585
+ top = e.max(axis=1)
586
+ p = wi * np.exp(e - top[:, None])
587
+ zsum = p.sum(axis=1)
588
+ p /= zsum[:, None]
589
+ log_z = np.log(zsum) + top
590
+ m1 = (p * xi).sum(axis=1)
591
+ m2 = (p * xi2).sum(axis=1)
592
+ m3 = (p * xi2 * xi).sum(axis=1)
593
+ m4 = (p * xi2 * xi2).sum(axis=1)
594
+ g1, g2 = -m1, 1.0 - m2 # gradient of the log-likelihood
595
+ c11, c12, c22 = m2 - m1 * m1, m3 - m1 * m2, m4 - m2 * m2
596
+ det = c11 * c22 - c12 * c12
597
+ safe = det > 1e-300
598
+ s1 = np.where(safe, (c22 * g1 - c12 * g2) / np.where(safe, det, 1.0), 0.0)
599
+ s2 = np.where(safe, (c11 * g2 - c12 * g1) / np.where(safe, det, 1.0), 0.0)
600
+ ll = e2 - log_z # loglik per row at t = (0, 1)
601
+ slope = g1 * s1 + g2 * s2 # >= 0 (positive-definite Hessian)
602
+ # stay strictly inside the bounds: an iterate on the boundary whose Newton direction
603
+ # points outwards could not move again, even when the optimum is interior
604
+ tau = _max_step(e1, e2, s1, s2, eta2_max)
605
+ tau = np.where(tau < 1.0, 0.5 * tau, 1.0)
606
+ accept = np.zeros(idx.size, dtype=bool)
607
+ new1, new2 = e1.copy(), e2.copy()
608
+ for _ in range(30):
609
+ todo = np.flatnonzero(~accept & (tau > 1e-12))
610
+ if not todo.size:
611
+ break
612
+ t1 = e1[todo] + tau[todo] * s1[todo]
613
+ t2 = np.minimum(e2[todo] + tau[todo] * s2[todo], eta2_max)
614
+ ll_new = t2 - _log_partition(t1, t2, xi[todo], xi2[todo], wi[todo])
615
+ ok = ll_new >= ll[todo] + 1e-4 * tau[todo] * slope[todo] - 1e-13
616
+ hit = todo[ok]
617
+ new1[hit], new2[hit] = t1[ok], t2[ok]
618
+ accept[hit] = True
619
+ tau[todo[~ok]] *= 0.5
620
+ moved = np.abs(new1 - e1) + np.abs(new2 - e2)
621
+ eta1[idx], eta2[idx] = new1, new2
622
+ converged = (np.abs(g1) < 1e-10) & (np.abs(g2) < 1e-10)
623
+ active[idx[converged | ~safe | ~accept | (moved < 1e-14)]] = False
624
+ sig2 = -0.5 / eta2
625
+ loc[bind] = mean[bind] + sd[bind] * eta1 * sig2
626
+ scale[bind] = sd[bind] * np.sqrt(sig2)
627
+ return loc, scale
628
+
629
+
630
+ def _tn_sample(lo: np.ndarray, hi: np.ndarray, loc: np.ndarray, scale: np.ndarray,
631
+ u: np.ndarray) -> np.ndarray:
632
+ """Inverse-CDF draws from ``N(loc, scale^2)`` truncated to ``[lo, hi]`` (vectorised). The
633
+ box is mirrored into the lower half and the CDF handled in log space
634
+ (``log_ndtr`` / ``ndtri_exp``), so boxes deep in a tail neither cancel nor underflow."""
635
+ a = (lo - loc) / scale
636
+ b = (hi - loc) / scale
637
+ flip = (a + b) > 0.0
638
+ a2 = np.where(flip, -b, a)
639
+ b2 = np.where(flip, -a, b)
640
+ la, lb = special.log_ndtr(a2), special.log_ndtr(b2)
641
+ with np.errstate(divide="ignore"):
642
+ lp = lb + np.log(u + (1.0 - u) * np.exp(np.minimum(la - lb, 0.0)))
643
+ t = special.ndtri_exp(np.minimum(lp, 0.0))
644
+ t = np.where(flip, -t, t)
645
+ return np.clip(loc + scale * t, lo, hi)
646
+
647
+
648
+ def _tn_logpdf(x: np.ndarray, lo: np.ndarray, hi: np.ndarray, loc: np.ndarray,
649
+ scale: np.ndarray) -> np.ndarray:
650
+ a = (lo - loc) / scale
651
+ b = (hi - loc) / scale
652
+ flip = (a + b) > 0.0
653
+ a2 = np.where(flip, -b, a)
654
+ b2 = np.where(flip, -a, b)
655
+ la, lb = special.log_ndtr(a2), special.log_ndtr(b2)
656
+ with np.errstate(divide="ignore"):
657
+ log_z = lb + np.log1p(-np.exp(np.minimum(la - lb, 0.0)))
658
+ t = (x - loc) / scale
659
+ out = -0.5 * t * t - 0.5 * math.log(2.0 * math.pi) - np.log(scale) - log_z
660
+ return np.where((x >= lo) & (x <= hi), out, -np.inf)
661
+
662
+
663
+ def _interp(x: np.ndarray, xp: np.ndarray, fp: np.ndarray) -> np.ndarray:
664
+ """Piecewise-linear map through ``(xp, fp)`` with linear extrapolation beyond the ends
665
+ (slope over the last ``_EXTRAP_STEPS`` grid steps)."""
666
+ y = np.interp(x, xp, fp)
667
+ k = min(_EXTRAP_STEPS, xp.size - 1)
668
+ below, above = x < xp[0], x > xp[-1]
669
+ if below.any():
670
+ s = (fp[k] - fp[0]) / max(xp[k] - xp[0], 1e-12)
671
+ y[below] = fp[0] + (x[below] - xp[0]) * s
672
+ if above.any():
673
+ s = (fp[-1] - fp[-1 - k]) / max(xp[-1] - xp[-1 - k], 1e-12)
674
+ y[above] = fp[-1] + (x[above] - xp[-1]) * s
675
+ return y
676
+
677
+
678
+ def _strictly_increasing_f32(q: np.ndarray) -> np.ndarray:
679
+ """Cast a sorted grid to float32 and nudge ties up by one float32 step."""
680
+ out = np.asarray(q, dtype=np.float32).copy()
681
+ for row in out.reshape(-1, out.shape[-1]):
682
+ for i in range(1, row.size):
683
+ if row[i] <= row[i - 1]:
684
+ row[i] = np.nextafter(row[i - 1], np.float32(np.inf))
685
+ return out
686
+
687
+
688
+ # ---------------------------------------------------------------------------------------------
689
+ # Storage quantisation and whitening
690
+ # ---------------------------------------------------------------------------------------------
691
+
692
+ def _round_abs(a: np.ndarray, quantum: float) -> np.ndarray:
693
+ return np.round(np.asarray(a, dtype=np.float64) / quantum) * quantum
694
+
695
+
696
+ def _round_rel(a: np.ndarray, bits: int) -> np.ndarray:
697
+ """Round to ``bits`` significant binary digits (exact in float32, compresses well)."""
698
+ m, e = np.frexp(np.asarray(a, dtype=np.float64))
699
+ return np.ldexp(np.round(m * 2.0 ** bits) / 2.0 ** bits, e)
700
+
701
+
702
+ def _sqrt_correlation(r: np.ndarray, policy: DisclosurePolicySpec) -> np.ndarray:
703
+ """Symmetric square root of a correlation matrix (policy-coarsened, eigenvalues floored at
704
+ ``MIN_WHITEN_EIGENVALUE``), as float32 values."""
705
+ r = _coarsen(0.5 * (r + r.T), policy)
706
+ np.fill_diagonal(r, 1.0)
707
+ ev, vec = np.linalg.eigh(r)
708
+ a = (vec * np.sqrt(np.maximum(ev, MIN_WHITEN_EIGENVALUE))) @ vec.T
709
+ return _f32(_coarsen(0.5 * (a + a.T), policy))
710
+
711
+
712
+ def whitening_matrix(z: np.ndarray, policy: DisclosurePolicySpec) -> np.ndarray:
713
+ """``A = R^(1/2)`` of the latent sample correlation ``R``: ``w = A^-1 z`` has uncorrelated
714
+ columns (see ``_sqrt_correlation``)."""
715
+ return _sqrt_correlation(nearest_correlation(sample_correlation(z)), policy)
716
+
717
+
718
+ def rank_mixing_matrix(z: np.ndarray, columns: list[str], policy: DisclosurePolicySpec,
719
+ moments: Any) -> np.ndarray:
720
+ """Square root of the latent correlation with the jitter dilution undone.
721
+
722
+ Jittering inside a value's interval (ties, categories, missingness indicators, imputed
723
+ missing scores) makes a column's latent sample correlations weaker than its association.
724
+ For every pair involving such a column the correlation is the Gaussian copula's
725
+ rank-moment estimate ``R*`` (tie-aware Spearman / polychoric-type inversion, see
726
+ ``GaussianCopula.fit``); pairs of continuous columns keep the sample correlation, since
727
+ ``R*`` assumes Gaussian dependence and would bend the structure the forest models. A
728
+ column counts as jittered when its rank variance ``12 * sum(coef^2)`` (1 for a continuous,
729
+ fully observed column) is below ``CONTINUOUS_RANK_VARIANCE``.
730
+ """
731
+ from ectype.models.copulas import GaussianCopula
732
+
733
+ star = np.asarray(GaussianCopula.fit(z, columns, policy=policy, hermite=moments).corr,
734
+ dtype=np.float64)
735
+ jit = 12.0 * np.sum(np.asarray(moments.coef, dtype=np.float64) ** 2, axis=1) \
736
+ < CONTINUOUS_RANK_VARIANCE
737
+ r = np.where(jit[:, None] | jit[None, :], star, sample_correlation(z))
738
+ return _sqrt_correlation(nearest_correlation(r), policy)
739
+
740
+
741
+ # ---------------------------------------------------------------------------------------------
742
+ # The joint model
743
+ # ---------------------------------------------------------------------------------------------
744
+
745
+ @JOINTS.register()
746
+ class ForestCopula(JointModel):
747
+ kind = "forest_copula"
748
+
749
+ def __init__(self, columns: list[str], *, edges: np.ndarray, nodes: np.ndarray,
750
+ tree_offsets: np.ndarray, coverage: np.ndarray, loc: np.ndarray,
751
+ scale: np.ndarray, mixing: np.ndarray | None = None,
752
+ quantiles: np.ndarray | None = None, grid_z: float = GRID_Z,
753
+ info: dict[str, Any] | None = None) -> None:
754
+ self.columns = list(columns)
755
+ d = len(self.columns)
756
+ self.edges = _f32(np.asarray(edges, dtype=np.float64).ravel())
757
+ self.n_bins = self.edges.size + 1
758
+ self.nodes = np.asarray(nodes, dtype=np.int64).reshape(-1, 4)
759
+ self.tree_offsets = np.asarray(tree_offsets, dtype=np.int64).ravel()
760
+ self.coverage = _f32(np.asarray(coverage, dtype=np.float64).ravel())
761
+ n_leaves = self.coverage.size
762
+ self.loc = _f32(np.asarray(loc, dtype=np.float64).reshape(n_leaves, d))
763
+ self.scale = _f32(np.asarray(scale, dtype=np.float64).reshape(n_leaves, d))
764
+ self.mixing = np.eye(d) if mixing is None else _f32(
765
+ np.asarray(mixing, dtype=np.float64).reshape(d, d))
766
+ self.grid_z = float(grid_z)
767
+ self.info = dict(info or {})
768
+ self._validate()
769
+ self.grid_levels = np.linspace(-self.grid_z, self.grid_z, GRID_POINTS)
770
+ if quantiles is None:
771
+ self.quantiles = np.tile(self.grid_levels, (d, 1))
772
+ else:
773
+ self.quantiles = _f32(np.asarray(quantiles, dtype=np.float64).reshape(d, -1))
774
+ if self.quantiles.shape[1] != GRID_POINTS or not np.all(
775
+ np.diff(self.quantiles, axis=1) > 0):
776
+ raise ValueError("forest marginal grid must be strictly increasing with "
777
+ f"{GRID_POINTS} points per column")
778
+ # boxes in whitened units, and the leaf mixture weights (tree uniform x coverage)
779
+ ext = np.concatenate([[-Z_LIMIT], np.clip(self.edges, -Z_LIMIT, Z_LIMIT), [Z_LIMIT]])
780
+ self._lo = np.empty((n_leaves, d))
781
+ self._hi = np.empty((n_leaves, d))
782
+ weights = np.zeros(n_leaves)
783
+ n_trees = self.tree_offsets.size - 1
784
+ for t in range(n_trees):
785
+ tree = self._tree(t)
786
+ leaves, lo_b, hi_b = _leaf_boxes(tree, d, self.n_bins)
787
+ ids = tree[2][leaves]
788
+ full = ids >= 0 # empty leaves carry no weight
789
+ ids = ids[full]
790
+ self._lo[ids], self._hi[ids] = ext[lo_b[full]], ext[hi_b[full]]
791
+ cov = self.coverage[ids]
792
+ weights[ids] = cov / max(float(cov.sum()), 1e-300) / n_trees
793
+ self._weights = weights
794
+ self._cum = np.cumsum(weights)
795
+ self._cum /= self._cum[-1]
796
+
797
+ # -- structure ----------------------------------------------------------------------------
798
+ def _tree(self, t: int) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
799
+ nd = self.nodes[self.tree_offsets[t]:self.tree_offsets[t + 1]]
800
+ return nd[:, 0], nd[:, 1], nd[:, 2], nd[:, 3]
801
+
802
+ def _validate(self) -> None:
803
+ d = len(self.columns)
804
+ nodes, off = self.nodes, self.tree_offsets
805
+ n_leaves = self.coverage.size
806
+ if off.size < 2 or off[0] != 0 or off[-1] != len(nodes) or np.any(np.diff(off) < 1):
807
+ raise ValueError("invalid forest tree offsets")
808
+ if not np.all(np.diff(self.edges) > 0):
809
+ raise ValueError("forest bin edges must be strictly increasing")
810
+ if self.n_bins > 256:
811
+ raise ValueError("forest supports at most 256 bins")
812
+ seen = np.zeros(n_leaves, dtype=np.int64)
813
+ for t in range(off.size - 1):
814
+ f, thr, lft, rgt = (np.asarray(c) for c in self._tree(t))
815
+ m = f.size
816
+ inner = f >= 0
817
+ ids = np.arange(m)
818
+ if np.any(f >= d) or np.any(f < -1):
819
+ raise ValueError("forest split refers to an unknown column")
820
+ if np.any(inner & ((thr < 0) | (thr >= self.n_bins - 1))):
821
+ raise ValueError("forest split threshold outside the bins")
822
+ if np.any(inner & ((lft <= ids) | (rgt <= ids) | (lft >= m) | (rgt >= m))):
823
+ raise ValueError("forest children must follow their parent within the tree")
824
+ kids = np.concatenate([lft[inner], rgt[inner]])
825
+ if kids.size != np.unique(kids).size or kids.size != m - 1:
826
+ raise ValueError("forest tree is not a binary tree")
827
+ leaf_ids = lft[~inner] # -1: an empty leaf (no real rows)
828
+ if np.any((leaf_ids < -1) | (leaf_ids >= n_leaves)) or not np.any(leaf_ids >= 0):
829
+ raise ValueError("forest leaf index out of range")
830
+ np.add.at(seen, leaf_ids[leaf_ids >= 0], 1)
831
+ if np.any(seen != 1):
832
+ raise ValueError("every forest leaf must belong to exactly one tree")
833
+ if np.any(self.coverage <= 0) or not np.all(np.isfinite(self.coverage)):
834
+ raise ValueError("forest leaf coverage must be positive")
835
+ if not (np.all(np.isfinite(self.loc)) and np.all(np.isfinite(self.scale))
836
+ and np.all(self.scale > 0)):
837
+ raise ValueError("forest leaf parameters must be finite with positive scale")
838
+ if not np.all(np.isfinite(self.mixing)) or (
839
+ d and np.linalg.matrix_rank(self.mixing) < d):
840
+ raise ValueError("forest mixing matrix must be finite and invertible")
841
+
842
+ @property
843
+ def n_trees(self) -> int:
844
+ return int(self.tree_offsets.size - 1)
845
+
846
+ @property
847
+ def n_leaves(self) -> int:
848
+ return int(self.coverage.size)
849
+
850
+ @property
851
+ def n_parameters(self) -> int:
852
+ d = len(self.columns)
853
+ n_inner = int(np.sum(self.nodes[:, 0] >= 0))
854
+ return (2 * n_inner + self.n_leaves * (1 + 2 * d) + d * GRID_POINTS
855
+ + d * (d - 1) // 2)
856
+
857
+ def split_counts(self) -> dict[str, int]:
858
+ """Number of splits on each (whitened) latent coordinate, by column name."""
859
+ f = self.nodes[:, 0]
860
+ counts = np.bincount(f[f >= 0], minlength=len(self.columns))
861
+ return {c: int(k) for c, k in zip(self.columns, counts)}
862
+
863
+ # -- fitting ------------------------------------------------------------------------------
864
+ @classmethod
865
+ def fit(cls, z: np.ndarray, columns: list[str], *, policy: DisclosurePolicySpec,
866
+ rng: np.random.Generator | None = None, n_trees: int = DEFAULT_TREES,
867
+ n_bins: int = DEFAULT_BINS, max_depth: int = DEFAULT_MAX_DEPTH,
868
+ min_samples_leaf: int | None = None, delta: float = DEFAULT_DELTA,
869
+ max_iters: int = DEFAULT_MAX_ITERS, early_stop: bool = True,
870
+ whiten: bool = True, max_features: int | None = None,
871
+ max_rows: int = MAX_FIT_ROWS, attenuation: np.ndarray | None = None,
872
+ hermite: Any = None, **kwargs: Any) -> ForestCopula:
873
+ """Fit an adversarial random forest to latent normal scores (see the module doc).
874
+
875
+ ``min_samples_leaf`` (bootstrap rows per training leaf) defaults to
876
+ ``2 * leaf_min``: about half of a training leaf's rows are real. ``max_features``
877
+ (candidate columns per split) defaults to ``floor(sqrt(d))``. ``whiten=False`` grows
878
+ the forest on the latent scores themselves (plain ARF). When the encoder's rank moments
879
+ are given -- ``hermite`` (a ``LatentMoments``) or ``attenuation`` carrying
880
+ ``.moments``, the keywords ``GaussianCopula.fit`` takes -- draws are mixed back with
881
+ the square root of the rank-moment correlation instead of the sample one.
882
+ """
883
+ z = _check_z(z, columns)
884
+ rng = rng if rng is not None else np.random.default_rng(0)
885
+ n_trees, n_bins, max_depth = int(n_trees), int(n_bins), int(max_depth)
886
+ if n_trees < 1 or not 2 <= n_bins <= 256 or max_depth < 0:
887
+ raise ValueError("forest needs n_trees >= 1, 2 <= n_bins <= 256, max_depth >= 0")
888
+ n, d = z.shape
889
+ leaf_min = leaf_min_for(policy)
890
+ msl = int(min_samples_leaf) if min_samples_leaf is not None else 2 * leaf_min
891
+ if msl < 1:
892
+ raise ValueError("min_samples_leaf must be >= 1")
893
+ if n > max_rows:
894
+ z = z[np.sort(rng.choice(n, int(max_rows), replace=False))]
895
+ n = z.shape[0]
896
+ edges = bin_edges(n_bins)
897
+ info: dict[str, Any] = {"n_trees": n_trees, "n_bins": n_bins, "max_depth": max_depth,
898
+ "leaf_min": leaf_min, "min_samples_leaf": msl,
899
+ "delta": float(delta), "max_iters": int(max_iters),
900
+ "early_stop": bool(early_stop), "whiten": bool(whiten),
901
+ "fit_rows": int(n), "iterations": 0, "oob_accuracy": [],
902
+ "converged": True}
903
+ if d == 0 or n < max(leaf_min, 2):
904
+ return cls._trivial(columns, edges, info)
905
+ mixing = np.eye(d)
906
+ w = np.clip(z, -Z_LIMIT, Z_LIMIT)
907
+ if whiten:
908
+ unmix = whitening_matrix(z, policy)
909
+ w = np.clip(z @ np.linalg.inv(unmix).T, -Z_LIMIT, Z_LIMIT)
910
+ moments = hermite if hermite is not None else getattr(attenuation, "moments", None)
911
+ mixing = (unmix if moments is None
912
+ else rank_mixing_matrix(z, list(columns), policy, moments))
913
+ info["mixing_source"] = "sample_correlation" if moments is None else "rank_moments"
914
+ xb = _binize(w, edges)
915
+ m_try = int(max_features) if max_features else max(1, int(math.floor(math.sqrt(d))))
916
+ m_try = min(max(m_try, 1), d)
917
+ kw = {"n_trees": n_trees, "m_try": m_try, "min_leaf": msl, "max_depth": max_depth,
918
+ "n_bins": n_bins}
919
+ ext = np.concatenate([[-Z_LIMIT], np.clip(edges, -Z_LIMIT, Z_LIMIT), [Z_LIMIT]])
920
+ # -- adversarial loop, starting from the product of the marginals --------------------
921
+ # The synthetic table of round k is drawn from forest k's leaf model (pruned, truncated
922
+ # normals: exactly what the fitted model samples) and judged by forest k+1. The leaf
923
+ # model whose table was hardest to tell from the real rows is kept.
924
+ syn = np.column_stack([xb[rng.permutation(n), j] for j in range(d)])
925
+ forest, acc = _train(xb, syn, rng, **kw)
926
+ accs = [acc]
927
+ best: _Forde | None = None
928
+ best_acc = math.inf
929
+ converged = acc <= 0.5 + delta
930
+ rounds = 0
931
+ while not converged and rounds < max_iters:
932
+ leaves = _forde_fit(forest, w, xb, leaf_min, ext)
933
+ syn = _binize(leaves.sample(n, rng), edges)
934
+ forest, acc = _train(xb, syn, rng, **kw)
935
+ accs.append(acc)
936
+ rounds += 1
937
+ if acc < best_acc:
938
+ best, best_acc = leaves, acc
939
+ converged = acc <= 0.5 + delta
940
+ if converged or (early_stop and acc >= accs[-2]):
941
+ break
942
+ if best is None:
943
+ best = _forde_fit(forest, w, xb, leaf_min, ext)
944
+ info.update(iterations=rounds, converged=bool(converged),
945
+ oob_accuracy=[float(v) for v in _coarsen(np.array(accs), policy)])
946
+ return cls._build(columns, best, n, edges, mixing, policy, rng, info)
947
+
948
+ @classmethod
949
+ def _trivial(cls, columns: list[str], edges: np.ndarray,
950
+ info: dict[str, Any]) -> ForestCopula:
951
+ """One leaf of N(0, 1) columns: the independence copula (no data stored)."""
952
+ d = len(columns)
953
+ model = cls(columns, edges=edges, nodes=np.array([[-1, -1, 0, -1]]),
954
+ tree_offsets=np.array([0, 1]), coverage=np.ones(1), loc=np.zeros((1, d)),
955
+ scale=np.ones((1, d)), info={**info, "n_trees": 1, "whiten": False,
956
+ "n_leaves": 1})
957
+ model.quantiles = _f32(_strictly_increasing_f32(model.quantiles))
958
+ return model
959
+
960
+ @classmethod
961
+ def _build(cls, columns: list[str], leaves: _Forde, n: int, edges: np.ndarray,
962
+ mixing: np.ndarray, policy: DisclosurePolicySpec, rng: np.random.Generator,
963
+ info: dict[str, Any]) -> ForestCopula:
964
+ """Coarsen and quantise a fitted leaf model, then estimate the marginal grid from a
965
+ seeded sample of the stored model."""
966
+ loc = _round_abs(_coarsen(leaves.loc, policy), LOC_QUANTUM)
967
+ scale = _round_rel(_coarsen(leaves.scale, policy), STORE_BITS)
968
+ coverage = _round_rel(_coarsen(leaves.support / n, policy), STORE_BITS)
969
+ node_rows = [np.column_stack([t.feature, t.threshold, t.left, t.right])
970
+ for t in leaves.trees]
971
+ offsets = np.concatenate([[0], np.cumsum([len(r) for r in node_rows])])
972
+ model = cls(columns, edges=edges, nodes=np.vstack(node_rows), tree_offsets=offsets,
973
+ coverage=coverage, loc=loc, scale=scale, mixing=mixing,
974
+ info={**info, "n_leaves": int(coverage.size)})
975
+ model.quantiles = cls._grid(model, policy, rng)
976
+ return model
977
+
978
+ @staticmethod
979
+ def _grid(model: ForestCopula, policy: DisclosurePolicySpec,
980
+ rng: np.random.Generator) -> np.ndarray:
981
+ """Quantiles of every raw model column at ``Phi(grid_levels)`` from ``GRID_SAMPLE``
982
+ seeded model draws (model-derived, not data)."""
983
+ raw = model.sample_raw(GRID_SAMPLE, rng)
984
+ raw.sort(axis=0)
985
+ pos = special.ndtr(model.grid_levels) * (GRID_SAMPLE - 1)
986
+ i0 = np.floor(pos).astype(np.int64)
987
+ i1 = np.minimum(i0 + 1, GRID_SAMPLE - 1)
988
+ frac = (pos - i0)[:, None]
989
+ q = (raw[i0] * (1.0 - frac) + raw[i1] * frac).T # (d, G)
990
+ return _f32(_strictly_increasing_f32(q))
991
+
992
+ # -- sampling / density -------------------------------------------------------------------
993
+ def sample_forest(self, n: int, rng: np.random.Generator) -> np.ndarray:
994
+ """Draws of the forest density in whitened coordinates."""
995
+ d = len(self.columns)
996
+ leaf = np.minimum(np.searchsorted(self._cum, rng.random(n), side="right"),
997
+ self.n_leaves - 1)
998
+ u = rng.random((n, d))
999
+ return _tn_sample(self._lo[leaf], self._hi[leaf], self.loc[leaf], self.scale[leaf], u)
1000
+
1001
+ def sample_raw(self, n: int, rng: np.random.Generator) -> np.ndarray:
1002
+ """Draws in latent coordinates before re-standardisation (``z = A w``)."""
1003
+ return self.sample_forest(n, rng) @ self.mixing.T
1004
+
1005
+ def _to_normal(self, x: np.ndarray) -> np.ndarray:
1006
+ out = np.empty_like(x)
1007
+ for j in range(x.shape[1]):
1008
+ out[:, j] = _interp(x[:, j], self.quantiles[j], self.grid_levels)
1009
+ return np.clip(out, -Z_LIMIT, Z_LIMIT)
1010
+
1011
+ def _from_normal(self, z: np.ndarray) -> np.ndarray:
1012
+ out = np.empty_like(z)
1013
+ for j in range(z.shape[1]):
1014
+ out[:, j] = _interp(z[:, j], self.grid_levels, self.quantiles[j])
1015
+ return out
1016
+
1017
+ def sample(self, n: int, rng: np.random.Generator) -> np.ndarray:
1018
+ if not self.columns:
1019
+ return np.zeros((n, 0))
1020
+ return self._to_normal(self.sample_raw(n, rng))
1021
+
1022
+ def logpdf(self, z: np.ndarray) -> np.ndarray:
1023
+ """Log density of latent scores ``z`` under the sampled distribution: the forest
1024
+ density of ``w = A^-1 x``, with ``x`` the inverse of the piecewise-linear
1025
+ re-standardisation, times both Jacobians. The leaves of one tree partition the space,
1026
+ so each tree contributes the one leaf whose box holds ``w``."""
1027
+ z = np.asarray(z, dtype=np.float64)
1028
+ n, d = z.shape
1029
+ x = self._from_normal(z)
1030
+ log_jac = np.zeros(n)
1031
+ for j in range(d):
1032
+ q = self.quantiles[j]
1033
+ idx = np.clip(np.searchsorted(self.grid_levels, z[:, j]) - 1, 0, q.size - 2)
1034
+ log_jac += np.log(q[idx + 1] - q[idx]) - np.log(
1035
+ self.grid_levels[idx + 1] - self.grid_levels[idx])
1036
+ log_jac -= float(np.linalg.slogdet(self.mixing)[1])
1037
+ w = x @ np.linalg.inv(self.mixing).T
1038
+ xb = _binize(np.clip(w, -Z_LIMIT, Z_LIMIT), self.edges)
1039
+ terms = np.empty((self.n_trees, n))
1040
+ for t in range(self.n_trees):
1041
+ tree = self._tree(t)
1042
+ leaf = tree[2][_route(tree, xb)]
1043
+ full = leaf >= 0 # an empty leaf has no density
1044
+ safe = np.where(full, leaf, 0)
1045
+ with np.errstate(divide="ignore"):
1046
+ dens = np.log(self._weights[safe]) + _tn_logpdf(
1047
+ w, self._lo[safe], self._hi[safe], self.loc[safe],
1048
+ self.scale[safe]).sum(axis=1)
1049
+ terms[t] = np.where(full, dens, -np.inf)
1050
+ return np.asarray(special.logsumexp(terms, axis=0)) + log_jac
1051
+
1052
+ # -- serialisation ------------------------------------------------------------------------
1053
+ def to_spec(self, store: ArrayStore, prefix: str) -> ModelSpec:
1054
+ def put(name: str, a: np.ndarray, dtype: type) -> str:
1055
+ return store.put(f"{prefix}{name}", np.ascontiguousarray(a, dtype=dtype))
1056
+
1057
+ arrays = {
1058
+ "bin_edges": put("bin_edges", self.edges, np.float32),
1059
+ "nodes": put("nodes", self.nodes, np.int32),
1060
+ "tree_offsets": put("tree_offsets", self.tree_offsets, np.int32),
1061
+ "leaf_coverage": put("leaf_coverage", self.coverage, np.float32),
1062
+ "leaf_loc": put("leaf_loc", self.loc, np.float32),
1063
+ "leaf_scale": put("leaf_scale", self.scale, np.float32),
1064
+ "mixing": put("mixing", self.mixing, np.float32),
1065
+ "marginal_quantiles": put("marginal_quantiles", self.quantiles, np.float32),
1066
+ }
1067
+ params: dict[str, Any] = {"columns": list(self.columns), "grid_z": self.grid_z,
1068
+ "grid_points": GRID_POINTS, **self.info}
1069
+ return ModelSpec(kind=self.kind, params=params, arrays=arrays)
1070
+
1071
+ @classmethod
1072
+ def from_spec(cls, spec: ModelSpec, store: ArrayStore) -> ForestCopula:
1073
+ p = spec.params
1074
+ cols = [str(c) for c in p.get("columns", [])] # type: ignore[union-attr]
1075
+ if int(p.get("grid_points", GRID_POINTS)) != GRID_POINTS: # type: ignore[arg-type]
1076
+ raise ValueError("unsupported forest marginal grid size")
1077
+
1078
+ def arr(name: str) -> np.ndarray:
1079
+ return np.asarray(store.get(spec.arrays[name]))
1080
+
1081
+ info = {k: v for k, v in p.items() if k not in ("columns", "grid_z", "grid_points")}
1082
+ return cls(cols, edges=arr("bin_edges"), nodes=arr("nodes"),
1083
+ tree_offsets=arr("tree_offsets"), coverage=arr("leaf_coverage"),
1084
+ loc=arr("leaf_loc"), scale=arr("leaf_scale"), mixing=arr("mixing"),
1085
+ quantiles=arr("marginal_quantiles"),
1086
+ grid_z=float(p.get("grid_z", GRID_Z)), # type: ignore[arg-type]
1087
+ info=info)