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
ectype/models/chain.py ADDED
@@ -0,0 +1,2426 @@
1
+ """Chain copula (kind ``"chain_copula"``): sequential conditional trees over latent scores.
2
+
3
+ The joint distribution of the encoder's latent columns is factorised along a recorded order,
4
+ ``p(z) = p(z_1) p(z_2 | z_1) ... p(z_d | z_1..z_{d-1})``, and every factor is a small set of
5
+ regression trees whose leaves hold a policy-coarsened conditional distribution. It is the
6
+ latent-space, disclosure-governed counterpart of a sequential CART synthesizer: the trees are
7
+ NumPy histogram trees, nothing is pickled, and no leaf stores a real value.
8
+
9
+ * **Atoms.** A latent score that was jittered inside the interval of a tied value (a category,
10
+ a discrete value, a missingness indicator, the spike of a zero-inflated amount) carries no
11
+ information beyond *which* interval it is in. Given the encoder's interval tables
12
+ (``MixedEncoder.latent_atoms``, passed as ``atoms=``) a column is one of
13
+
14
+ - *nominal* / *ordinal*: its intervals tile ``[0, 1]`` (at most ``MAX_ATOMS``). The model
15
+ predicts the atom and draws the score uniformly inside it, so the encoder decodes exactly
16
+ the value the leaf chose. A conditionally encoded child (``LatentAtoms.parent``) uses the
17
+ interval row of its parent's sampled atom, and draws only among the atoms that value of
18
+ the parent allows (``PARENT_MIN_LIFT``: a leaf that is not pure in the parent holds atoms
19
+ of several parent values; a leaf with none of the allowed ones falls back on the parent's
20
+ own table);
21
+ - *continuous*: everything else. Its up to ``MAX_MAJOR`` widest atoms of at least
22
+ ``MAJOR_MASS`` are modelled as atoms; the rest is modelled as a density in *excised*
23
+ coordinates (the normal score of the column with those atoms cut out).
24
+
25
+ Without ``atoms`` every column is continuous.
26
+ * **Order.** ``chain_order``: a column follows its missingness indicator and its conditional
27
+ parent; among the columns that may come next, indicators go first, then low-cardinality
28
+ atomic columns, then the other atomic columns, then the continuous ones, and inside a tier
29
+ the column best predicted (linear ``R^2`` of the de-jittered scores) by those already
30
+ placed. The order is stored in the spec.
31
+ * **Predictors.** An earlier column is seen through fixed bins: one per atom, or
32
+ ``n_bins`` equal-probability bins of its excised score with every major atom a bin of its
33
+ own, plus a bin for "missing". The edges are constants of the encoder's intervals, not data.
34
+ Its *score* is the latent score with the jitter taken out (the mean of the atom's interval).
35
+ * **Ridges.** Given the marginals' quantile functions (``MixedEncoder.latent_values``, passed
36
+ as ``values=``), the rows of a continuous column that have exactly the value of an earlier
37
+ column (a payment equal to the bill) are found, and a partner that at least ``RIDGE_SHARE``
38
+ of the rows copy becomes a *ridge* of the column (at most ``MAX_RIDGES``): a cell of its
39
+ leaves, like an atom, whose score is drawn in the column's interval for the partner's value
40
+ (a sampled row whose partner is missing, or has a value outside the column's range or on
41
+ one of the column's own atoms, has nothing to copy and takes the leaf's density). The
42
+ interval tables come from the two marginals, not from rows.
43
+ * **Base of a continuous column.** A ridge regression on all earlier scores (``beta``) is used
44
+ when its residual takes fewer nats to describe (entropy at ``ENTROPY_STEP``) than both the
45
+ column itself and its residual from a trimmed line on the single most correlated score.
46
+ When that single line wins, the column mostly follows one other column: it gets no linear
47
+ base (which would smear that dependence over the other predictors) and its trees are grown
48
+ on that line's residual.
49
+ * **Trees.** For each column, ``n_trees`` trees are grown on a random ``subsample`` of the rows
50
+ where the column is observed, by multi-output variance reduction: the Gini decrease over the
51
+ classes of the target (up to ``MAX_CLASSES`` atoms or groups of atoms; for a continuous
52
+ column its atoms, its ridges and ``RESIDUAL_CLASSES`` bins of its residual) plus the
53
+ variance decrease of its score. Candidates are all bin boundaries of all earlier columns
54
+ that leave ``leaf_min`` rows on both sides; depth is at most ``max_depth``. Splits are then
55
+ pruned bottom-up by the predictive log-likelihood of the rows left out of the subsample (a
56
+ split stays when it, or a split below it, predicts those rows better), and to at most
57
+ ``max_leaves`` leaves.
58
+ * **Leaves.** Fitted on all rows that reach the leaf. A row is in one *cell*: its atom; for a
59
+ continuous column its atom, a ridge, or "continuous".
60
+
61
+ - a cell with at least ``cell_min`` of the leaf's rows is stored with its share;
62
+ - the other rows are pooled into a *rest*. A rest below ``cell_min`` is never stored as it
63
+ is: fewer than ``cell_min / 2`` rows are dropped, more are rounded up to ``cell_min``;
64
+ - the rest of a nominal or continuous column is spread over the other cells like its parent
65
+ node's distribution (recursively, ending at the marginal); the rest of an ordinal column
66
+ is spread by a density over its atoms;
67
+ - a density (an ordinal column's rest, a continuous column's "continuous" cell): the rows
68
+ are sorted and cut into ``min(rows // cell_min, MAX_BLOCKS)`` equal-count blocks, and the
69
+ density is the equal-weight mixture of normals with the blocks' means and standard
70
+ deviations (it has the rows' mean and variance, and a block of tied rows is a spike).
71
+ With fewer than ``cell_min`` such rows the moments of the whole leaf, or of its nearest
72
+ ancestor with enough of them, are used;
73
+ - a continuous leaf whose rows lie along a line in one earlier column's score (``LINE_R2``
74
+ of their variance; least trimmed squares, so the line follows the rows on a ridge) stores
75
+ that column and the slope, and its density describes what the line leaves.
76
+
77
+ Every stored number is therefore a share, a mean, a standard deviation or a slope of at
78
+ least ``cell_min`` real rows, rounded to the policy's significant digits and to
79
+ ``LOC_QUANTUM`` / ``STORE_BITS``.
80
+ * **Sampling.** In chain order: pick one of the column's trees uniformly, drop the row down it,
81
+ draw a cell and then the score from the leaf. Where the column's indicator says "missing"
82
+ the score is an independent N(0, 1) draw, as in the encoder.
83
+ * **Re-standardisation.** At fit time ``GRID_SAMPLE`` seeded rows are drawn through the chain
84
+ (model-derived, not data). Column by column, the leaf probabilities are tilted by one
85
+ factor per atom until the model's atom frequencies equal the encoder's (iterative
86
+ proportional fitting), and the density draws are mapped through a ``GRID_POINTS`` quantile
87
+ grid so that the continuous part is exactly N(0, 1), as in ``forest_copula`` (copies stay
88
+ copies: the grid sends the other draws to what N(0, 1) leaves beside them). A draw beyond
89
+ the grid's ends (``GRID_Z``, about one in 11,000 on either side) gets a score from N(0, 1)'s
90
+ own tail: a dozen seeded draws do not show how the model's draws are distributed out there.
91
+ Later columns see the corrected values.
92
+
93
+ Spec: ``params`` hold the columns, the order and the hyper-parameters; ``arrays`` are int32 /
94
+ float32. Per column: ``col_kind``, ``col_parent``, ``col_indicator``, the atom tables
95
+ (``atom_shape``, ``atom_lower`` / ``atom_upper`` as normal scores), ``beta``, ``tilt``,
96
+ ``grid`` and the ridges (``ridge_offsets``, ``ridge_col``, ``ridge_lower`` / ``ridge_upper``
97
+ as normal scores). Trees: ``nodes`` (``(n, 4)``: column, bin threshold, left, right; a leaf
98
+ has column ``-1`` and its distribution row in ``left``), ``tree_offsets``, ``col_trees``.
99
+ Distribution rows (``col_dists``): ``rest``, ``parent`` row, ``line_col`` / ``line_slope`` and
100
+ the ragged ``cell_atom`` / ``cell_prob`` (``cell_offsets``) and ``means`` / ``sds``
101
+ (``mean_offsets``).
102
+ """
103
+
104
+ from __future__ import annotations
105
+
106
+ import math
107
+ from collections.abc import Iterator, Mapping, Sequence
108
+ from typing import Any, NamedTuple
109
+
110
+ import numpy as np
111
+ from scipy import special, stats
112
+
113
+ from ectype.fingerprint.core import ArrayStore
114
+ from ectype.fingerprint.schema import DisclosurePolicySpec, ModelSpec
115
+ from ectype.models.base import JOINTS, JointModel
116
+ from ectype.models.copulas import _check_z
117
+ from ectype.models.forest import (
118
+ GRID_POINTS,
119
+ GRID_SAMPLE,
120
+ GRID_Z,
121
+ LOC_QUANTUM,
122
+ MIN_SCALE,
123
+ STORE_BITS,
124
+ Z_LIMIT,
125
+ _coarsen,
126
+ _f32,
127
+ _round_abs,
128
+ _round_rel,
129
+ _route,
130
+ _strictly_increasing_f32,
131
+ leaf_min_for,
132
+ )
133
+
134
+ DEFAULT_TREES = 1
135
+ DEFAULT_BINS = 128
136
+ #: most bins of a continuous predictor (bins are stored as uint16)
137
+ MAX_BINS = 4096
138
+ DEFAULT_MAX_DEPTH = 24
139
+ DEFAULT_MAX_LEAVES = 2048
140
+ DEFAULT_SUBSAMPLE = 0.7
141
+ DEFAULT_PRUNE = 0.0
142
+ #: fit rows above this are subsampled
143
+ MAX_FIT_ROWS = 100_000
144
+ #: The work budget of a fit (ADR-0015). Growing a column's tree makes, at every level, one
145
+ #: pass over the rows of the nodes that can still be split for every earlier column, so a
146
+ #: table costs about ``rows x columns^2 / 2`` passes per level. A fit counts the passes it
147
+ #: makes (row-predictor units, :func:`_grow`), and once the columns still to come would take
148
+ #: it over the budget their trees are limited (:func:`ChainCopula.fit`), so that nobody gets a
149
+ #: slow fit by surprise. The count is of work, not of seconds, so what is limited does not
150
+ #: depend on the machine or its load. What a pass costs in seconds, and so the budget in seconds
151
+ #: of tree growing, is measured in ADR-0015. A fit also spends 0.1 to 0.2 s per latent
152
+ #: column outside the trees.
153
+ DEFAULT_WORK_BUDGET = 1.0e9
154
+ #: what a pass over one predictor costs whatever the row count, in rows (measured: 700 to
155
+ #: 1,600, by regression of the time of 572 trees on rows and predictors)
156
+ WORK_ROW_OVERHEAD = 2000
157
+ #: levels a tree is taken to search before any tree of the fit has been grown (after that the
158
+ #: fit's own trees say: 2 to 10 on the tables of ADR-0015)
159
+ WORK_LEVELS = 6.0
160
+ #: a limited fit lets a column's trees choose among at least this many earlier columns ...
161
+ MIN_PREDICTORS = 16
162
+ #: ... and, when that is not enough, is fitted on at least this many rows
163
+ MIN_BUDGET_ROWS = 20_000
164
+ #: rows on which the predictors of a column are screened (evenly spaced among its rows), and
165
+ #: the levels of the screening tree. 1: the root only. Three levels were measured on two wide
166
+ #: tables and kept no more of the fidelity for 10 to 20 s more per fit (ADR-0015)
167
+ SCREEN_ROWS = 20_000
168
+ SCREEN_LEVELS = 1
169
+ #: what a pass of screening costs, in passes of tree growing (measured on three wide public
170
+ #: tables: 20 to 25 ns against 56 to 90 ns per row and predictor, ADR-0015)
171
+ SCREEN_PASS = 0.3
172
+ #: a column whose intervals tile [0, 1] is atomic when it has at most this many atoms
173
+ MAX_ATOMS = 255
174
+ #: atoms of a continuous column modelled as atoms: the widest ones of at least this mass
175
+ MAX_MAJOR = 64
176
+ MAJOR_MASS = 0.005
177
+ #: rows that copy an earlier column ("ridges"): at most this many partners per column, each
178
+ #: copied by at least this share of the column's rows outside its atoms; a copy is told from
179
+ #: a near miss within one step of the tabulated quantile functions
180
+ MAX_RIDGES = 3
181
+ RIDGE_SHARE = 0.01
182
+ #: fewest tabulated levels of a quantile function for it to be used
183
+ MIN_VALUE_LEVELS = 16
184
+ #: classes of the split criterion (the most frequent atoms, or groups of adjacent atoms)
185
+ MAX_CLASSES = 16
186
+ #: bins of a continuous target's residual used as classes of the split criterion
187
+ RESIDUAL_CLASSES = 8
188
+ #: most equal-count blocks a leaf stores for its rest
189
+ MAX_BLOCKS = 32
190
+ #: atomic columns with at most this many atoms come before the other atomic columns
191
+ LOW_CARDINALITY = 16
192
+ #: ridge penalty of the linear base, relative to the row count
193
+ RIDGE = 1e-3
194
+ #: rows needed per coefficient before a linear base is fitted
195
+ LINEAR_ROWS_PER_COEFFICIENT = 20
196
+ #: residuals are compared at this resolution (latent units), and a base must save this many
197
+ #: nats over no base to be used
198
+ ENTROPY_STEP = 1.0 / 64.0
199
+ BASE_GAIN = 0.02
200
+ #: a continuous target's leaves hold at least this many times ``cell_min`` rows, so that
201
+ #: their rest density has several blocks
202
+ CONTINUOUS_LEAF_BLOCKS = 1
203
+ #: a leaf gets a local line when an earlier column explains this share of its rows' variance
204
+ #: (low on purpose: inside a leaf that is narrow in that column the share is small even on a
205
+ #: ridge; 0.25 gave a detection AUC of 0.709 on Credit Default, 0.1 gives 0.679)
206
+ LINE_R2 = 0.1
207
+ #: least-trimmed-squares passes of a line fit
208
+ TRIM_PASSES = 2
209
+ #: pseudo-count of the parent distribution in the predictive class probabilities (pruning)
210
+ PRUNE_PSEUDO_COUNT = 1.0
211
+ #: tolerance (latent ``u``) when a score is assigned to an atom: above the error of the
212
+ #: float32 edges, below any atom the policy lets a marginal store
213
+ ATOM_TOL = 4e-8
214
+ #: scores are drawn this share of an atom's width away from its edges
215
+ ATOM_MARGIN = 1e-3
216
+ #: a conditionally encoded child does not draw an atom that the sampled value of its parent
217
+ #: makes more than twenty times rarer than the atom is in the whole column: a city of another
218
+ #: state, a depot of another zone (a judgement; a combination that never occurs has a lift of
219
+ #: about 1e-3 in the encoder's smoothed tables, a real dependence rarely one below 0.2)
220
+ PARENT_MIN_LIFT = 0.05
221
+ #: latent ``u`` is kept inside ``[U_EPS, 1 - U_EPS]``, as in the encoder
222
+ U_EPS = 1e-9
223
+ #: fewest seeded draws from which a re-standardisation grid is estimated
224
+ MIN_GRID_ROWS = 2000
225
+ #: iterations of the proportional fitting of the atom frequencies
226
+ TILT_ITERATIONS = 6
227
+ MAX_TILT = 1e3
228
+
229
+ KIND_CONTINUOUS, KIND_NOMINAL, KIND_ORDINAL = 0, 1, 2
230
+ MISSING_PREFIX = "__missing__"
231
+
232
+ _TINY = 1e-300
233
+
234
+
235
+ # ---------------------------------------------------------------------------------------------
236
+ # Columns: the fixed structure a latent column gets from the encoder's interval tables
237
+ # ---------------------------------------------------------------------------------------------
238
+
239
+ def _edge_z(u: np.ndarray) -> np.ndarray:
240
+ """Latent ``u`` edges as the float32 normal scores that are stored."""
241
+ with np.errstate(divide="ignore"):
242
+ z = special.ndtri(np.clip(np.asarray(u, dtype=np.float64), 0.0, 1.0))
243
+ return _f32(np.clip(z, -Z_LIMIT, Z_LIMIT))
244
+
245
+
246
+ def _edge_u(z: np.ndarray) -> np.ndarray:
247
+ z = np.asarray(z, dtype=np.float64)
248
+ return np.where(z <= -Z_LIMIT, 0.0, np.where(z >= Z_LIMIT, 1.0, special.ndtr(z)))
249
+
250
+
251
+ def _interval_mean(lo: np.ndarray, hi: np.ndarray) -> np.ndarray:
252
+ """``E[Z | Phi(Z) in [lo, hi]]`` for a standard normal ``Z`` (the de-jittered score)."""
253
+ w = hi - lo
254
+ with np.errstate(divide="ignore"):
255
+ za, zb = special.ndtri(lo), special.ndtri(hi)
256
+ dens = np.exp(-0.5 * za * za) - np.exp(-0.5 * zb * zb) # exp(-inf) = 0
257
+ mid = special.ndtri(np.clip(0.5 * (lo + hi), U_EPS, 1.0 - U_EPS))
258
+ return np.where(w > 1e-12, dens / math.sqrt(2.0 * math.pi) / np.where(w > 1e-12, w, 1.0),
259
+ mid)
260
+
261
+
262
+ def _ndtri(u: np.ndarray) -> np.ndarray:
263
+ return special.ndtri(np.clip(u, U_EPS, 1.0 - U_EPS))
264
+
265
+
266
+ class _Column:
267
+ """One latent column: its atoms, its bins as a predictor and its de-jittered score."""
268
+
269
+ def __init__(self, kind: int, lower_z: np.ndarray, upper_z: np.ndarray, parent: int,
270
+ indicator: int, n_bins: int) -> None:
271
+ self.kind = int(kind)
272
+ self.parent = int(parent)
273
+ self.indicator = int(indicator)
274
+ self.lower = _edge_u(lower_z) # (rows, atoms)
275
+ self.upper = np.maximum(_edge_u(upper_z), self.lower)
276
+ self.width = self.upper - self.lower
277
+ self.n_rows, self.n_atoms = self.lower.shape
278
+ self.mean = _interval_mean(self.lower, self.upper)
279
+ if self.kind == KIND_CONTINUOUS:
280
+ w = self.width[0] if self.n_rows else np.zeros(0)
281
+ self.below = np.concatenate([[0.0], np.cumsum(w)])
282
+ self.cont_mass = float(max(1.0 - self.below[-1], 1e-12))
283
+ lo = self.lower[0] if self.n_rows else np.zeros(0)
284
+ self.cut = np.clip((lo - self.below[:-1]) / self.cont_mass, 0.0, 1.0)
285
+ grid = np.arange(1, int(n_bins), dtype=np.float64) / int(n_bins)
286
+ self.cuts = np.unique(np.concatenate([grid, self.cut]))
287
+ self.atom_bin = (np.searchsorted(self.cuts, self.cut, side="left") + 1
288
+ + np.arange(self.n_atoms))
289
+ self.n_bins = int(self.cuts.size + 1 + self.n_atoms)
290
+ self.target = np.concatenate([w, [self.cont_mass]])
291
+ else:
292
+ self.n_bins = int(self.n_atoms)
293
+ self.target = self.width[-1].copy()
294
+ self.target = self.target / max(float(self.target.sum()), _TINY)
295
+ self.n_cells = int(self.target.size)
296
+ #: number of bin values, including the bin of a missing value
297
+ self.n_values = self.n_bins + (1 if self.indicator >= 0 else 0)
298
+
299
+ # -- training rows -> model coordinates ---------------------------------------------------
300
+ def assign(self, u: np.ndarray, prow: np.ndarray) -> np.ndarray:
301
+ """Atom of each latent ``u`` (``-1``: none, continuous columns only)."""
302
+ if self.kind == KIND_CONTINUOUS:
303
+ if not self.n_atoms:
304
+ return np.full(u.shape[0], -1, dtype=np.int64)
305
+ k = np.minimum(np.searchsorted(self.upper[0] + ATOM_TOL, u, side="left"),
306
+ self.n_atoms - 1)
307
+ inside = (u > self.lower[0][k] + ATOM_TOL) & (u <= self.upper[0][k] + ATOM_TOL)
308
+ return np.where(inside, k, -1)
309
+ if self.n_rows == 1:
310
+ out = np.searchsorted(self.upper[0] + ATOM_TOL, u, side="left")
311
+ else:
312
+ out = np.zeros(u.shape[0], dtype=np.int64)
313
+ for p in np.unique(prow):
314
+ sel = prow == p
315
+ out[sel] = np.searchsorted(self.upper[p] + ATOM_TOL, u[sel], side="left")
316
+ return np.minimum(out, self.n_atoms - 1)
317
+
318
+ def excise(self, u: np.ndarray) -> np.ndarray:
319
+ """Latent ``u`` outside the major atoms -> ``u'`` in [0, 1] with the atoms cut out."""
320
+ if not self.n_atoms:
321
+ return u
322
+ m = np.searchsorted(self.lower[0] + ATOM_TOL, u, side="left")
323
+ return np.clip((u - self.below[m]) / self.cont_mass, 0.0, 1.0)
324
+
325
+ def unexcise(self, up: np.ndarray) -> np.ndarray:
326
+ if not self.n_atoms:
327
+ return up
328
+ m = np.searchsorted(self.cut, up, side="right")
329
+ u = up * self.cont_mass + self.below[m]
330
+ floor = np.where(m > 0, self.upper[0][np.maximum(m - 1, 0)] + 2.0 * ATOM_TOL, 0.0)
331
+ return np.maximum(u, floor)
332
+
333
+ def table_rows(self, atom: np.ndarray, missing: np.ndarray) -> np.ndarray:
334
+ """Interval row of every data row: the parent's atom, the last row when it is missing."""
335
+ if self.n_rows <= 1 or self.parent < 0:
336
+ return np.zeros(atom.shape[0], dtype=np.int64)
337
+ p = atom[:, self.parent].astype(np.int64)
338
+ gone = missing[:, self.parent] | (p < 0) | (p >= self.n_rows - 1)
339
+ return np.where(gone, self.n_rows - 1, p)
340
+
341
+ # -- model coordinates of a drawn or encoded value ----------------------------------------
342
+ def within(self, prow: np.ndarray, atom: np.ndarray, v: np.ndarray) -> np.ndarray:
343
+ """A score inside the interval of ``atom`` (``v`` uniform)."""
344
+ lo, w = self.lower[prow, atom], self.width[prow, atom]
345
+ pad = np.minimum(np.maximum(ATOM_MARGIN * w, 2.0 * ATOM_TOL), 0.25 * w)
346
+ return _ndtri(lo + pad + (w - 2.0 * pad) * v)
347
+
348
+ def bin_score(self, atom: np.ndarray, z: np.ndarray, up: np.ndarray, prow: np.ndarray
349
+ ) -> tuple[np.ndarray, np.ndarray]:
350
+ """Predictor bin and de-jittered score (``up``: excised ``u`` of continuous rows)."""
351
+ if self.kind != KIND_CONTINUOUS:
352
+ return atom, self.mean[prow, atom]
353
+ cont = atom < 0
354
+ b = np.empty(atom.shape[0], dtype=np.int64)
355
+ s = np.empty(atom.shape[0], dtype=np.float64)
356
+ upc = up[cont]
357
+ b[cont] = (np.searchsorted(self.cuts, upc, side="right")
358
+ + np.searchsorted(self.cut, upc, side="right"))
359
+ s[cont] = z[cont]
360
+ if not cont.all():
361
+ a = atom[~cont]
362
+ b[~cont] = self.atom_bin[a]
363
+ s[~cont] = self.mean[0][a]
364
+ return b, s
365
+
366
+
367
+ class _State:
368
+ """Rows in model coordinates: latent score, atom, predictor bin, de-jittered score."""
369
+
370
+ def __init__(self, n: int, d: int) -> None:
371
+ self.z = np.zeros((n, d), dtype=np.float64)
372
+ self.atom = np.full((n, d), -1, dtype=np.int16)
373
+ self.bins = np.zeros((n, d), dtype=np.uint16)
374
+ self.score = np.zeros((n, d), dtype=np.float64)
375
+ self.missing = np.zeros((n, d), dtype=bool)
376
+ #: excised uniform of the rows in a continuous column's continuous part (else NaN)
377
+ self.up = np.full((n, d), np.nan, dtype=np.float64)
378
+
379
+ def put(self, j: int, col: _Column, z: np.ndarray, atom: np.ndarray, up: np.ndarray,
380
+ prow: np.ndarray, missing: np.ndarray | None) -> None:
381
+ b, s = col.bin_score(atom, z, up, prow)
382
+ if missing is not None and missing.any():
383
+ b = np.where(missing, col.n_bins, b)
384
+ s = np.where(missing, 0.0, s)
385
+ atom = np.where(missing, -1, atom)
386
+ self.missing[:, j] = missing
387
+ self.z[:, j], self.atom[:, j], self.bins[:, j], self.score[:, j] = z, atom, b, s
388
+ self.up[:, j] = up
389
+
390
+
391
+ def _encode(z: np.ndarray, cols: list[_Column], order: Sequence[int]) -> _State:
392
+ """Training rows in model coordinates (parents and indicators come first in ``order``)."""
393
+ n, d = z.shape
394
+ st = _State(n, d)
395
+ u = special.ndtr(z)
396
+ for j in order:
397
+ col = cols[j]
398
+ missing = st.atom[:, col.indicator] == 1 if col.indicator >= 0 else None
399
+ prow = col.table_rows(st.atom, st.missing)
400
+ atom = col.assign(u[:, j], prow)
401
+ up = np.full(n, np.nan)
402
+ if col.kind == KIND_CONTINUOUS:
403
+ cont = atom < 0
404
+ up[cont] = col.excise(u[cont, j])
405
+ st.put(j, col, z[:, j], atom, up, prow, missing)
406
+ return st
407
+
408
+
409
+ def _layout(columns: list[str], atoms: Mapping[str, Any] | None
410
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray, list[np.ndarray], list[np.ndarray]]:
411
+ """``(kind, parent, indicator, lower_z, upper_z)`` per column from the encoder's atoms."""
412
+ d = len(columns)
413
+ index = {c: j for j, c in enumerate(columns)}
414
+ kind = np.full(d, KIND_CONTINUOUS, dtype=np.int64)
415
+ parent = np.full(d, -1, dtype=np.int64)
416
+ indicator = np.full(d, -1, dtype=np.int64)
417
+ lower: list[np.ndarray] = [np.zeros((1, 0)) for _ in range(d)]
418
+ upper: list[np.ndarray] = [np.zeros((1, 0)) for _ in range(d)]
419
+ for j, name in enumerate(columns):
420
+ a = (atoms or {}).get(name)
421
+ if a is None:
422
+ continue
423
+ lo = np.atleast_2d(np.asarray(a.lower, dtype=np.float64))
424
+ hi = np.atleast_2d(np.asarray(a.upper, dtype=np.float64))
425
+ if lo.shape != hi.shape or lo.shape[1] == 0 or not (
426
+ np.all(np.isfinite(lo)) and np.all(np.isfinite(hi))):
427
+ raise ValueError(f"atoms of {name!r} must be finite (rows, atoms) interval tables")
428
+ lo, hi = np.clip(lo, 0.0, 1.0), np.clip(np.maximum(hi, lo), 0.0, 1.0)
429
+ par = index.get(getattr(a, "parent", None) or "", -1) if lo.shape[0] > 1 else -1
430
+ if lo.shape[0] > 1 and par < 0: # parent not modelled: marginal row
431
+ lo, hi = lo[-1:], hi[-1:]
432
+ k = lo.shape[1]
433
+ tiles = bool(np.all(np.abs((hi - lo).sum(axis=1) - 1.0) < 1e-6))
434
+ if tiles and k <= MAX_ATOMS:
435
+ kind[j] = KIND_NOMINAL if bool(getattr(a, "nominal", False)) else KIND_ORDINAL
436
+ parent[j] = par
437
+ # close the rounding gaps: the intervals of one row are consecutive
438
+ lo = np.concatenate([np.zeros((lo.shape[0], 1)), hi[:, :-1]], axis=1)
439
+ hi = hi.copy()
440
+ hi[:, -1] = 1.0
441
+ elif lo.shape[0] == 1:
442
+ w = (hi - lo)[0]
443
+ top = np.sort(np.argsort(-w, kind="stable")[:MAX_MAJOR])
444
+ top = top[w[top] >= MAJOR_MASS]
445
+ lo, hi = lo[:, top], hi[:, top]
446
+ else: # row-dependent, too many atoms
447
+ lo, hi = np.zeros((1, 0)), np.zeros((1, 0))
448
+ lower[j], upper[j] = _edge_z(lo), _edge_z(hi)
449
+ for j, name in enumerate(columns):
450
+ if not name.startswith(MISSING_PREFIX):
451
+ continue
452
+ target = index.get(name[len(MISSING_PREFIX):], -1)
453
+ if target >= 0 and kind[j] != KIND_CONTINUOUS and lower[j].shape == (1, 2):
454
+ indicator[target] = j
455
+ for j in range(d): # conditional rows need an atomic parent with matching atoms
456
+ p = parent[j]
457
+ if p >= 0 and (kind[p] == KIND_CONTINUOUS or parent[p] == j
458
+ or lower[j].shape[0] != lower[p].shape[1] + 1):
459
+ parent[j] = -1
460
+ lower[j], upper[j] = lower[j][-1:], upper[j][-1:]
461
+ return kind, parent, indicator, lower, upper
462
+
463
+
464
+ def chain_order(cols: list[_Column], score: np.ndarray) -> list[int]:
465
+ """The order in which the columns are generated (see the module doc)."""
466
+ d = len(cols)
467
+ if d == 0:
468
+ return []
469
+ x = score - score.mean(axis=0)
470
+ sd = x.std(axis=0)
471
+ x = np.where(sd > 0, x / np.where(sd > 0, sd, 1.0), 0.0)
472
+ r = x.T @ x / max(len(x), 1)
473
+ np.fill_diagonal(r, 1.0)
474
+ indicators = {c.indicator for c in cols if c.indicator >= 0}
475
+ tier = []
476
+ for j, c in enumerate(cols):
477
+ if j in indicators:
478
+ tier.append(0)
479
+ elif c.kind == KIND_CONTINUOUS:
480
+ tier.append(3)
481
+ else:
482
+ tier.append(1 if c.n_atoms <= LOW_CARDINALITY else 2)
483
+ need = [{p for p in (c.indicator, c.parent) if p >= 0} for c in cols]
484
+ placed: list[int] = []
485
+ done = np.zeros(d, dtype=bool)
486
+ while len(placed) < d:
487
+ free = [j for j in range(d) if not done[j] and all(done[p] for p in need[j])]
488
+ if not free: # cyclic prerequisites: give up on them
489
+ free = [j for j in range(d) if not done[j]]
490
+ best_tier = min(tier[j] for j in free)
491
+ cand = [j for j in free if tier[j] == best_tier]
492
+ if placed:
493
+ s = np.array(placed)
494
+ inv = np.linalg.inv(r[np.ix_(s, s)] + 1e-3 * np.eye(s.size))
495
+ gain = [float(r[j, s] @ inv @ r[s, j]) for j in cand]
496
+ else:
497
+ gain = [float(np.sum(r[j] ** 2)) for j in cand]
498
+ pick = cand[int(np.argmax(np.round(gain, 9)))]
499
+ placed.append(pick)
500
+ done[pick] = True
501
+ return placed
502
+
503
+
504
+ # ---------------------------------------------------------------------------------------------
505
+ # Trees: multi-output variance-reduction trees on binned predictors, grown level by level
506
+ # ---------------------------------------------------------------------------------------------
507
+
508
+ class _Tree(NamedTuple):
509
+ feature: np.ndarray # int64 (m,), -1 for a leaf
510
+ threshold: np.ndarray # int64 (m,), go left iff bin <= threshold
511
+ left: np.ndarray # int64 (m,); the distribution row of a fitted leaf
512
+ right: np.ndarray # int64 (m,)
513
+
514
+
515
+ class _Target(NamedTuple):
516
+ """What a column's trees predict: a class per row and, optionally, a score."""
517
+
518
+ cls: np.ndarray # int64 (n,)
519
+ n_classes: int
520
+ y: np.ndarray | None # float64 (n,), standardised
521
+ wy: np.ndarray | None # float64 (n,), 1 where the row has a score
522
+
523
+
524
+ def _grow(xb: np.ndarray, feats: Sequence[int], n_values: np.ndarray, rows: np.ndarray,
525
+ target: _Target, *, min_leaf: int, max_depth: int,
526
+ work: list[float] | None = None) -> _Tree:
527
+ """One tree on ``rows``. A node is split at the bin boundary with the largest decrease of
528
+ the classes' Gini impurity plus the score's variance (both in rows), among all predictors
529
+ and all boundaries that leave ``min_leaf`` rows on both sides; candidates are found by
530
+ sorting the node's rows on (node, bin), so the cost does not depend on the bin count."""
531
+ q = int(target.n_classes)
532
+ r = np.asarray(rows, dtype=np.int64)
533
+ pos = np.zeros(r.size, dtype=np.int64)
534
+ c_r = target.cls[r]
535
+ use_y = target.y is not None and target.wy is not None
536
+ w_r = target.wy[r] if use_y else np.zeros(0) # type: ignore[index]
537
+ y_r = target.y[r] * w_r if use_y else np.zeros(0) # type: ignore[index]
538
+ levels: list[tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]] = []
539
+ n_level, first_id, depth = 1, 0, 0
540
+ while True:
541
+ cnt = np.bincount(pos, minlength=n_level).astype(np.float64)
542
+ cc = np.bincount(pos * q + c_r, minlength=n_level * q).reshape(n_level, q).astype(
543
+ np.float64)
544
+ par = (cc * cc).sum(axis=1) / np.maximum(cnt, 1.0)
545
+ if use_y:
546
+ ny = np.bincount(pos, weights=w_r, minlength=n_level)
547
+ sy = np.bincount(pos, weights=y_r, minlength=n_level)
548
+ par = par + sy * sy / np.maximum(ny, 1.0)
549
+ feature = np.full(n_level, -1, dtype=np.int64)
550
+ threshold = np.full(n_level, -1, dtype=np.int64)
551
+ left = np.full(n_level, -1, dtype=np.int64)
552
+ right = np.full(n_level, -1, dtype=np.int64)
553
+ split = np.zeros(n_level, dtype=bool)
554
+ can = cnt >= 2 * min_leaf
555
+ if depth >= max_depth or not len(feats):
556
+ can[:] = False
557
+ sub = np.flatnonzero(can)
558
+ if sub.size:
559
+ n_sub = sub.size
560
+ where = np.full(n_level, -1, dtype=np.int64)
561
+ where[sub] = np.arange(n_sub)
562
+ sel = np.flatnonzero(can[pos])
563
+ if work is not None: # one pass per predictor at this level
564
+ work[0] += float(len(feats)) * (sel.size + WORK_ROW_OVERHEAD)
565
+ sp, rs, cs = where[pos[sel]], r[sel], c_r[sel]
566
+ cnt_s, cc_s, par_s = cnt[sub], cc[sub], par[sub]
567
+ if use_y:
568
+ ws, ys, ny_s, sy_s = w_r[sel], y_r[sel], ny[sub], sy[sub]
569
+ best_gain = np.full(n_sub, 1e-9)
570
+ best_f = np.full(n_sub, -1, dtype=np.int64)
571
+ best_t = np.full(n_sub, -1, dtype=np.int64)
572
+ node_ids = np.arange(n_sub)
573
+ for f in feats:
574
+ nb = int(n_values[f])
575
+ key = sp * nb + xb[rs, f]
576
+ o = np.argsort(key, kind="stable")
577
+ ks = key[o]
578
+ new = np.empty(ks.size, dtype=bool)
579
+ new[0] = True
580
+ np.not_equal(ks[1:], ks[:-1], out=new[1:])
581
+ run_start = np.flatnonzero(new)
582
+ n_runs = run_start.size
583
+ if n_runs <= n_sub: # one bin per node: nothing to split
584
+ continue
585
+ run_node = ks[run_start] // nb
586
+ cand = np.flatnonzero(run_node[:-1] == run_node[1:])
587
+ first_run = np.searchsorted(run_node, node_ids)
588
+ g = run_node[cand]
589
+ nl = (run_start[cand + 1] - run_start[first_run[g]]).astype(np.float64)
590
+ nr = cnt_s[g] - nl
591
+ ok = (nl >= min_leaf) & (nr >= min_leaf)
592
+ if not ok.any():
593
+ continue
594
+ cand, g, nl, nr = cand[ok], g[ok], nl[ok], nr[ok]
595
+ run_id = np.cumsum(new) - 1
596
+ cum = np.cumsum(np.bincount(run_id * q + cs[o], minlength=n_runs * q).reshape(
597
+ n_runs, q), axis=0, dtype=np.float64)
598
+ has_base = first_run > 0
599
+ base = np.zeros((n_sub, q))
600
+ base[has_base] = cum[first_run[has_base] - 1]
601
+ lc = cum[cand] - base[g]
602
+ rc = cc_s[g] - lc
603
+ score = (lc * lc).sum(axis=1) / nl + (rc * rc).sum(axis=1) / nr
604
+ if use_y:
605
+ cw = np.cumsum(np.bincount(run_id, weights=ws[o], minlength=n_runs))
606
+ cy = np.cumsum(np.bincount(run_id, weights=ys[o], minlength=n_runs))
607
+ bw, by = np.zeros(n_sub), np.zeros(n_sub)
608
+ bw[has_base] = cw[first_run[has_base] - 1]
609
+ by[has_base] = cy[first_run[has_base] - 1]
610
+ lw, ly = cw[cand] - bw[g], cy[cand] - by[g]
611
+ rw, ry = ny_s[g] - lw, sy_s[g] - ly
612
+ score = (score + np.where(lw > 0, ly * ly / np.maximum(lw, 1e-12), 0.0)
613
+ + np.where(rw > 0, ry * ry / np.maximum(rw, 1e-12), 0.0))
614
+ gain = score - par_s[g]
615
+ top = np.full(n_sub, -np.inf)
616
+ np.maximum.at(top, g, gain)
617
+ hit = np.flatnonzero(gain >= top[g])
618
+ nodes, first = np.unique(g[hit], return_index=True)
619
+ pick = hit[first]
620
+ better = gain[pick] > best_gain[nodes]
621
+ nodes, pick = nodes[better], pick[better]
622
+ best_gain[nodes] = gain[pick]
623
+ best_f[nodes] = f
624
+ best_t[nodes] = ks[run_start[cand[pick]]] % nb
625
+ done = np.flatnonzero(best_f >= 0)
626
+ if done.size:
627
+ nodes = sub[done]
628
+ feature[nodes], threshold[nodes] = best_f[done], best_t[done]
629
+ split[nodes] = True
630
+ left[nodes] = first_id + n_level + 2 * np.arange(done.size)
631
+ right[nodes] = left[nodes] + 1
632
+ levels.append((feature, threshold, left, right))
633
+ n_split = int(split.sum())
634
+ if not n_split:
635
+ break
636
+ keep = split[pos]
637
+ r, pos, c_r = r[keep], pos[keep], c_r[keep]
638
+ if use_y:
639
+ w_r, y_r = w_r[keep], y_r[keep]
640
+ go_right = xb[r, feature[pos]] > threshold[pos]
641
+ pos = 2 * (np.cumsum(split) - 1)[pos] + go_right.astype(np.int64)
642
+ first_id += n_level
643
+ n_level = 2 * n_split
644
+ depth += 1
645
+ return _Tree(*(np.concatenate([lv[i] for lv in levels]) for i in range(4)))
646
+
647
+
648
+ def _node_gains(xb: np.ndarray, feats: Sequence[int], n_values: np.ndarray, r: np.ndarray,
649
+ target: _Target, min_leaf: int) -> tuple[np.ndarray, np.ndarray]:
650
+ """For the node holding the rows ``r``: the gain of the best split on each predictor (the
651
+ criterion of :func:`_grow`: the classes' Gini decrease plus the score's variance decrease,
652
+ in rows, over every bin boundary that leaves ``min_leaf`` rows on both sides; 0 when
653
+ there is none) and its threshold."""
654
+ q = int(target.n_classes)
655
+ c_r = target.cls[r]
656
+ n = float(r.size)
657
+ cc = np.bincount(c_r, minlength=q).astype(np.float64)
658
+ par = float((cc * cc).sum() / max(n, 1.0))
659
+ use_y = target.y is not None and target.wy is not None
660
+ if use_y:
661
+ w_r = target.wy[r] # type: ignore[index]
662
+ y_r = target.y[r] * w_r # type: ignore[index]
663
+ ny, sy = float(w_r.sum()), float(y_r.sum())
664
+ par += sy * sy / max(ny, 1.0)
665
+ gains = np.zeros(len(feats))
666
+ cuts = np.full(len(feats), -1, dtype=np.int64)
667
+ for i, f in enumerate(feats):
668
+ nb = int(n_values[f])
669
+ b = xb[r, f].astype(np.int64)
670
+ lc = np.cumsum(np.bincount(b * q + c_r, minlength=nb * q).reshape(nb, q), axis=0,
671
+ dtype=np.float64)[:-1]
672
+ nl = lc.sum(axis=1)
673
+ nr = n - nl
674
+ ok = np.flatnonzero((nl >= min_leaf) & (nr >= min_leaf))
675
+ if not ok.size:
676
+ continue
677
+ lc, nl, nr = lc[ok], nl[ok], nr[ok]
678
+ rc = cc - lc
679
+ score = (lc * lc).sum(axis=1) / nl + (rc * rc).sum(axis=1) / nr
680
+ if use_y:
681
+ lw = np.cumsum(np.bincount(b, weights=w_r, minlength=nb))[:-1][ok]
682
+ ly = np.cumsum(np.bincount(b, weights=y_r, minlength=nb))[:-1][ok]
683
+ rw, ry = ny - lw, sy - ly
684
+ score = (score + np.where(lw > 0, ly * ly / np.maximum(lw, 1e-12), 0.0)
685
+ + np.where(rw > 0, ry * ry / np.maximum(rw, 1e-12), 0.0))
686
+ k = int(np.argmax(score))
687
+ gains[i], cuts[i] = max(float(score[k]) - par, 0.0), int(ok[k])
688
+ return gains, cuts
689
+
690
+
691
+ def _screen(xb: np.ndarray, feats: Sequence[int], n_values: np.ndarray, rows: np.ndarray,
692
+ target: _Target, *, min_leaf: int, keep: int) -> list[int]:
693
+ """The ``keep`` predictors among ``feats`` that the top of a tree on ``rows`` would use,
694
+ in the order of ``feats``.
695
+
696
+ A tree is grown greedily for ``SCREEN_LEVELS`` levels with every predictor allowed, and
697
+ each predictor is credited with the gain of its best split in every one of those nodes
698
+ (:func:`_node_gains`). With one level, the default, that is the root: the ``keep``
699
+ predictors whose best single split of the rows gains most. (More levels look below the
700
+ root, where a predictor that repeats what the root's split said gains nothing and the
701
+ ones that explain what is left come forward; that was measured and did not pay.) At most
702
+ ``SCREEN_ROWS`` evenly spaced rows are looked at. Ties go to the earlier predictor. Uses
703
+ no random numbers."""
704
+ feats = list(feats)
705
+ if keep <= 0 or len(feats) <= keep:
706
+ return feats
707
+ r = np.asarray(rows, dtype=np.int64)
708
+ if r.size > SCREEN_ROWS:
709
+ r = r[np.linspace(0, r.size - 1, SCREEN_ROWS).astype(np.int64)]
710
+ total = np.zeros(len(feats))
711
+ nodes = [r]
712
+ for _ in range(max(int(SCREEN_LEVELS), 1)):
713
+ below: list[np.ndarray] = []
714
+ for node in nodes:
715
+ if node.size < 2 * min_leaf:
716
+ continue
717
+ gains, cuts = _node_gains(xb, feats, n_values, node, target, min_leaf)
718
+ total += gains
719
+ best = int(np.argmax(np.round(gains, 9)))
720
+ if gains[best] <= 1e-9:
721
+ continue
722
+ left = xb[node, feats[best]] <= cuts[best]
723
+ below += [node[left], node[~left]]
724
+ nodes = below
725
+ if not nodes:
726
+ break
727
+ top = np.argsort(-np.round(total, 9), kind="stable")[:keep]
728
+ return [feats[i] for i in np.sort(top)]
729
+
730
+
731
+ def _span(a: int, b: int) -> int:
732
+ """``a + (a + 1) + ... + b`` (0 when ``a > b``)."""
733
+ return (a + b) * (b - a + 1) // 2 if b >= a else 0
734
+
735
+
736
+ def _pairs(first: int, d: int, k: int) -> int:
737
+ """Predictors searched by the columns at chain positions ``first .. d - 1`` when each may
738
+ split on at most ``k`` of its earlier columns (``k`` 0: all of them)."""
739
+ a, b = max(int(first), 0), int(d) - 1
740
+ if b < a:
741
+ return 0
742
+ if k <= 0 or k >= b:
743
+ return _span(a, b)
744
+ return _span(a, min(b, k)) + k * (b - max(a, k + 1) + 1)
745
+
746
+
747
+ def tree_work(rows: int, d: int, max_predictors: int = 0, *,
748
+ subsample: float = DEFAULT_SUBSAMPLE, n_trees: int = DEFAULT_TREES,
749
+ levels: float = WORK_LEVELS, first: int = 0) -> float:
750
+ """The tree-growing work a fit to ``rows`` rows and ``d`` latent columns is expected to
751
+ take, in passes (row-predictor units): for every column from chain position ``first``,
752
+ the earlier columns its trees may split on (all, or ``max_predictors``) times the rows a
753
+ tree is grown on (plus ``WORK_ROW_OVERHEAD``), times the ``levels`` a tree searches,
754
+ times the trees per column. Before a fit ``levels`` is a guess (``WORK_LEVELS``); during
755
+ it, what the fit's own trees took."""
756
+ per = (float(subsample) * max(int(rows), 0) + WORK_ROW_OVERHEAD) * float(levels)
757
+ return float(n_trees) * _pairs(first, d, int(max_predictors or 0)) * per
758
+
759
+
760
+ def screen_work(rows: int, d: int, max_predictors: int, *, first: int = 0) -> float:
761
+ """The work that choosing the predictors takes (:func:`_screen`), in passes of tree
762
+ growing: a column that has more than ``max_predictors`` earlier columns looks at every
763
+ one of them once, on at most ``SCREEN_ROWS`` rows, and such a look costs ``SCREEN_PASS``
764
+ of a pass. Nothing when there is no limit."""
765
+ k = int(max_predictors or 0)
766
+ if k <= 0:
767
+ return 0.0
768
+ per = (min(max(int(rows), 0), SCREEN_ROWS) + WORK_ROW_OVERHEAD) * max(int(SCREEN_LEVELS), 1)
769
+ return float(_span(max(int(first), k + 1), int(d) - 1)) * per * SCREEN_PASS
770
+
771
+
772
+ def fit_work(rows: int, d: int, max_predictors: int = 0, *,
773
+ subsample: float = DEFAULT_SUBSAMPLE, n_trees: int = DEFAULT_TREES,
774
+ levels: float = WORK_LEVELS, first: int = 0) -> float:
775
+ """:func:`tree_work` plus :func:`screen_work`: every pass a work budget pays for."""
776
+ return (tree_work(rows, d, max_predictors, subsample=subsample, n_trees=n_trees,
777
+ levels=levels, first=first)
778
+ + screen_work(rows, d, max_predictors, first=first))
779
+
780
+
781
+ def affordable_predictors(remaining: float, rows: int | Sequence[int] | np.ndarray, d: int,
782
+ first: int, *, levels: float,
783
+ subsample: float = DEFAULT_SUBSAMPLE,
784
+ n_trees: int = DEFAULT_TREES) -> int:
785
+ """The most predictors per column that the columns at chain positions ``first .. d - 1``
786
+ can be given within ``remaining`` passes, the passes of choosing them included: 0 when
787
+ they can have them all, else the largest number that fits, not below
788
+ ``MIN_PREDICTORS``. (0 too in the rare fit whose trees search so few levels that choosing
789
+ ``MIN_PREDICTORS`` predictors would cost more than searching them all.)
790
+
791
+ ``rows`` is the rows a column's trees are fitted on: one number, or one for every chain
792
+ position (a column that is mostly empty costs little, one that is not fitted nothing)."""
793
+ d, first = int(d), max(int(first), 0)
794
+ if d - first <= 0:
795
+ return 0
796
+ r = np.broadcast_to(np.asarray(rows, dtype=np.float64), (d,))[first:]
797
+ t = np.arange(first, d, dtype=np.float64)
798
+ fitted = r > 0
799
+ # per predictor: the passes of one level of the column's trees, and of choosing
800
+ unit = np.where(fitted, float(n_trees) * float(levels) * (
801
+ float(subsample) * r + WORK_ROW_OVERHEAD), 0.0)
802
+ look = np.where(fitted, (np.minimum(r, SCREEN_ROWS) + WORK_ROW_OVERHEAD)
803
+ * max(int(SCREEN_LEVELS), 1) * SCREEN_PASS, 0.0)
804
+ full = float((t * unit).sum())
805
+ if full <= remaining:
806
+ return 0
807
+ hi = d - 2
808
+ if hi < MIN_PREDICTORS:
809
+ return 0 # no column has more predictors
810
+ # need(k) for k = MIN_PREDICTORS .. d - 2: columns up to position k keep all their
811
+ # predictors, the later ones search k and look at all of theirs once
812
+ ks = np.arange(MIN_PREDICTORS, hi + 1)
813
+ below = np.concatenate([[0.0], np.cumsum(t * unit)]) # positions < first + i
814
+ units = np.concatenate([[0.0], np.cumsum(unit)])
815
+ looks = np.concatenate([[0.0], np.cumsum(t * look)])
816
+ cut = np.clip(ks + 1 - first, 0, d - first) # positions <= k
817
+ need = below[cut] + ks * (units[-1] - units[cut]) + (looks[-1] - looks[cut])
818
+ fits = np.flatnonzero(need <= remaining)
819
+ if fits.size:
820
+ return int(ks[fits[-1]])
821
+ return MIN_PREDICTORS if need[0] < full else 0
822
+
823
+
824
+ def plan_work(rows: int, d: int, budget: float | None = DEFAULT_WORK_BUDGET, *,
825
+ max_rows: int = MAX_FIT_ROWS, subsample: float = DEFAULT_SUBSAMPLE,
826
+ n_trees: int = DEFAULT_TREES) -> dict[str, Any]:
827
+ """What can be said before a fit to ``rows`` rows and ``d`` latent columns about keeping
828
+ it within ``budget`` passes (``None`` or 0: no budget), with trees taken to search
829
+ ``WORK_LEVELS`` levels.
830
+
831
+ The predictors are limited during the fit, column by column, from the passes the fit has
832
+ actually made (:func:`ChainCopula.fit`); this function decides the one thing that has to
833
+ be decided first, the rows. They are subsampled (not below ``MIN_BUDGET_ROWS``) only when
834
+ even ``MIN_PREDICTORS`` predictors per column would not fit. Returns ``fit_rows``, the
835
+ work ``expected`` in full, the ``max_predictors`` the expectation would allow (0: all;
836
+ the fit decides for itself) and whether a limit is ``expected``."""
837
+ rows, d = max(int(rows), 0), max(int(d), 0)
838
+ fit_rows = min(rows, int(max_rows))
839
+
840
+ def work(n: int, k: int = 0) -> float:
841
+ return fit_work(n, d, k, subsample=subsample, n_trees=n_trees)
842
+
843
+ plan: dict[str, Any] = {"fit_rows": fit_rows, "max_predictors": 0,
844
+ "expected": work(fit_rows), "limited": False}
845
+ if not budget or plan["expected"] <= budget:
846
+ return plan
847
+ floor = min(fit_rows, MIN_BUDGET_ROWS)
848
+ if work(fit_rows, MIN_PREDICTORS) > budget and fit_rows > floor:
849
+ lo, hi = floor, fit_rows # the most rows that fit
850
+ while lo < hi:
851
+ mid = (lo + hi + 1) // 2
852
+ if work(mid, MIN_PREDICTORS) <= budget:
853
+ lo = mid
854
+ else:
855
+ hi = mid - 1
856
+ fit_rows = lo
857
+ plan.update(fit_rows=fit_rows, limited=True, max_predictors=affordable_predictors(
858
+ float(budget), fit_rows, d, 0, levels=WORK_LEVELS, subsample=subsample,
859
+ n_trees=n_trees))
860
+ return plan
861
+
862
+
863
+ def _walk(tree: _Tree, xb: np.ndarray, rows: np.ndarray) -> Iterator[tuple[np.ndarray,
864
+ np.ndarray]]:
865
+ """``(index into rows, node)`` for every node on every row's path, one level at a time."""
866
+ idx = np.arange(rows.size)
867
+ node = np.zeros(rows.size, dtype=np.int64)
868
+ while idx.size:
869
+ nd = node[idx]
870
+ yield idx, nd
871
+ f = tree.feature[nd]
872
+ inner = f >= 0
873
+ idx, nd, f = idx[inner], nd[inner], f[inner]
874
+ if not idx.size:
875
+ break
876
+ node[idx] = np.where(xb[rows[idx], f] <= tree.threshold[nd], tree.left[nd],
877
+ tree.right[nd])
878
+
879
+
880
+ def _parents(tree: _Tree) -> np.ndarray:
881
+ parent = np.full(tree.feature.size, -1, dtype=np.int64)
882
+ inner = np.flatnonzero(tree.feature >= 0)
883
+ parent[tree.left[inner]] = inner
884
+ parent[tree.right[inner]] = inner
885
+ return parent
886
+
887
+
888
+ def _depths(tree: _Tree) -> np.ndarray:
889
+ """Depth of every node (children follow their parents in the arrays)."""
890
+ depth = np.zeros(tree.feature.size, dtype=np.int64)
891
+ frontier = np.zeros(1, dtype=np.int64)
892
+ level = 0
893
+ while frontier.size:
894
+ depth[frontier] = level
895
+ inner = frontier[tree.feature[frontier] >= 0]
896
+ frontier = np.concatenate([tree.left[inner], tree.right[inner]])
897
+ level += 1
898
+ return depth
899
+
900
+
901
+ def _collapse(tree: _Tree, keep: np.ndarray) -> _Tree:
902
+ """Make leaves of the inner nodes not in ``keep`` and renumber the rest breadth-first."""
903
+ feature = np.where(keep, tree.feature, -1)
904
+ order = [np.zeros(1, dtype=np.int64)]
905
+ frontier = order[0]
906
+ while frontier.size:
907
+ inner = frontier[feature[frontier] >= 0]
908
+ frontier = np.column_stack([tree.left[inner], tree.right[inner]]).ravel()
909
+ if frontier.size:
910
+ order.append(frontier)
911
+ nodes = np.concatenate(order)
912
+ new_id = np.full(feature.size, -1, dtype=np.int64)
913
+ new_id[nodes] = np.arange(nodes.size)
914
+ f = feature[nodes]
915
+ split = f >= 0
916
+ return _Tree(f, np.where(split, tree.threshold[nodes], -1),
917
+ np.where(split, new_id[np.where(split, tree.left[nodes], 0)], -1),
918
+ np.where(split, new_id[np.where(split, tree.right[nodes], 0)], -1))
919
+
920
+
921
+ def _t_logpdf(y: np.ndarray, mu: np.ndarray, s2: np.ndarray, nu: np.ndarray) -> np.ndarray:
922
+ return (special.gammaln(0.5 * (nu + 1.0)) - special.gammaln(0.5 * nu)
923
+ - 0.5 * np.log(nu * math.pi * s2)
924
+ - 0.5 * (nu + 1.0) * np.log1p((y - mu) ** 2 / (nu * s2)))
925
+
926
+
927
+ def _prune(tree: _Tree, xb: np.ndarray, grown: np.ndarray, held: np.ndarray, target: _Target,
928
+ *, penalty: float, max_leaves: int) -> _Tree:
929
+ """Reduced-error pruning by predictive log-likelihood.
930
+
931
+ Every node is scored as a leaf on the held-out rows that reach it: the class probabilities
932
+ are the grown rows' counts smoothed towards the parent node's, the score density is the
933
+ Student-t predictive of the grown rows' mean and variance. A split stays when the best
934
+ pruning of its two subtrees beats the node as a leaf by more than ``penalty`` (so a split
935
+ without a gain of its own survives when a split below it has one). ``penalty`` is raised
936
+ until at most ``max_leaves`` leaves are left.
937
+ """
938
+ m, q = tree.feature.size, int(target.n_classes)
939
+ use_y = target.y is not None and target.wy is not None
940
+ cnt = np.zeros(m)
941
+ cc = np.zeros((m, q))
942
+ ny, sy, syy = np.zeros(m), np.zeros(m), np.zeros(m)
943
+ for idx, nd in _walk(tree, xb, grown):
944
+ rr = grown[idx]
945
+ cnt += np.bincount(nd, minlength=m)
946
+ cc += np.bincount(nd * q + target.cls[rr], minlength=m * q).reshape(m, q)
947
+ if use_y:
948
+ w, y = target.wy[rr], target.y[rr] # type: ignore[index]
949
+ ny += np.bincount(nd, weights=w, minlength=m)
950
+ sy += np.bincount(nd, weights=w * y, minlength=m)
951
+ syy += np.bincount(nd, weights=w * y * y, minlength=m)
952
+ parent, depth = _parents(tree), _depths(tree)
953
+ prob = np.empty((m, q))
954
+ mu, s2, nu = np.zeros(m), np.ones(m), np.ones(m)
955
+ for level in range(int(depth.max()) + 1):
956
+ nodes = np.flatnonzero(depth == level)
957
+ base = prob[parent[nodes]] if level else np.full((nodes.size, q), 1.0 / q)
958
+ prob[nodes] = (cc[nodes] + PRUNE_PSEUDO_COUNT * base) / (
959
+ cnt[nodes] + PRUNE_PSEUDO_COUNT)[:, None]
960
+ if use_y:
961
+ own = ny[nodes] >= 3
962
+ k = nodes[own]
963
+ mu[k] = sy[k] / ny[k]
964
+ nu[k] = ny[k] - 1.0
965
+ s2[k] = np.maximum((syy[k] - sy[k] * mu[k]) / nu[k], 1e-6) * (1.0 + 1.0 / ny[k])
966
+ if level:
967
+ k = nodes[~own]
968
+ mu[k], s2[k], nu[k] = mu[parent[k]], s2[parent[k]], nu[parent[k]]
969
+ ll = np.zeros(m)
970
+ for idx, nd in _walk(tree, xb, held):
971
+ rr = held[idx]
972
+ v = np.log(prob[nd, target.cls[rr]])
973
+ if use_y:
974
+ v = v + target.wy[rr] * _t_logpdf(target.y[rr], mu[nd], s2[nd], nu[nd]) # type: ignore[index]
975
+ ll += np.bincount(nd, weights=v, minlength=m)
976
+ inner = np.flatnonzero(tree.feature >= 0)[::-1]
977
+ left, right = tree.left, tree.right
978
+
979
+ def solve(pen: float) -> tuple[np.ndarray, int]:
980
+ best = ll.copy()
981
+ keep = np.zeros(m, dtype=bool)
982
+ size = np.ones(m, dtype=np.int64)
983
+ for v in inner:
984
+ s = best[left[v]] + best[right[v]] - pen
985
+ if s > best[v]:
986
+ best[v], keep[v] = s, True
987
+ size[v] = size[left[v]] + size[right[v]]
988
+ return keep, int(size[0])
989
+
990
+ keep, n_leaves = solve(float(penalty))
991
+ if n_leaves > max_leaves:
992
+ lo, hi = float(penalty), max(1.0, abs(float(penalty)))
993
+ while solve(hi)[1] > max_leaves:
994
+ lo, hi = hi, 2.0 * hi + 1.0
995
+ for _ in range(30):
996
+ mid = 0.5 * (lo + hi)
997
+ if solve(mid)[1] > max_leaves:
998
+ lo = mid
999
+ else:
1000
+ hi = mid
1001
+ keep, n_leaves = solve(hi)
1002
+ return _collapse(tree, keep)
1003
+
1004
+
1005
+ # ---------------------------------------------------------------------------------------------
1006
+ # Ridges: rows of a continuous column that copy an earlier column
1007
+ # ---------------------------------------------------------------------------------------------
1008
+
1009
+ class _Ridges(NamedTuple):
1010
+ """The earlier columns a continuous column copies and where a copy sits: for each partner,
1011
+ the latent ``u`` interval of the column in which it has the partner's value, tabulated at
1012
+ evenly spaced latent levels of the partner. Derived from the two marginals' quantile
1013
+ functions (``MixedEncoder.latent_values``), not from rows."""
1014
+
1015
+ cols: np.ndarray # (R,) partner columns
1016
+ lower: np.ndarray # (R, levels) latent u of the column
1017
+ upper: np.ndarray
1018
+
1019
+ @property
1020
+ def n(self) -> int:
1021
+ return int(self.cols.size)
1022
+
1023
+ def interval(self, r: int, u: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
1024
+ """The column's interval for a copy of partner ``r`` whose latent level is ``u``."""
1025
+ n = self.lower.shape[1]
1026
+ x = np.clip(u * n - 0.5, 0.0, n - 1.0)
1027
+ i = np.minimum(x.astype(np.int64), n - 2)
1028
+ f = x - i
1029
+ lo = self.lower[r, i] * (1.0 - f) + self.lower[r, i + 1] * f
1030
+ hi = self.upper[r, i] * (1.0 - f) + self.upper[r, i + 1] * f
1031
+ return lo, np.maximum(hi, lo)
1032
+
1033
+ def outside(self, lo: np.ndarray, hi: np.ndarray) -> np.ndarray:
1034
+ """Whether an interval is the degenerate one of a partner value below the column's
1035
+ lowest or above its highest tabulated value: the column has nothing to copy there."""
1036
+ edge = 0.25 / self.lower.shape[1]
1037
+ return (hi < edge) | (lo > 1.0 - edge)
1038
+
1039
+ def which(self, u: np.ndarray, score: np.ndarray, missing: np.ndarray) -> np.ndarray:
1040
+ """The first partner each latent ``u`` of the column is a copy of (``-1``: none), given
1041
+ the rows' de-jittered scores of all columns and which of them are missing. (A partner
1042
+ is looked up inside the interval of its tied value: the encoder puts every row of a
1043
+ tied float value on the interval's edge, where the table changes to the next value.)"""
1044
+ out = np.full(u.size, -1, dtype=np.int64)
1045
+ if not self.n:
1046
+ return out
1047
+ tol = 1.0 / self.lower.shape[1]
1048
+ for r in range(self.n):
1049
+ lo, hi = self.interval(r, special.ndtr(score[:, self.cols[r]]))
1050
+ on = (~missing[:, self.cols[r]] & ~self.outside(lo, hi)
1051
+ & (u >= lo - tol) & (u <= hi + tol))
1052
+ out[on & (out < 0)] = r
1053
+ return out
1054
+
1055
+
1056
+ def _no_ridges(levels: int = 2) -> _Ridges:
1057
+ return _Ridges(np.zeros(0, dtype=np.int64), np.zeros((0, levels)), np.zeros((0, levels)))
1058
+
1059
+
1060
+ def _copy_intervals(v_partner: np.ndarray, v_target: np.ndarray
1061
+ ) -> tuple[np.ndarray, np.ndarray]:
1062
+ """For every tabulated level of the partner, the latent ``u`` interval in which the target
1063
+ has the partner's value. Both arguments are quantile functions at the same evenly spaced
1064
+ levels ``(k + 1/2) / n``; a value the target's table holds (a tied value, a lattice step)
1065
+ gets the whole run of levels with that value, any other value a point between two."""
1066
+ n = v_target.size
1067
+ lv = (np.arange(n) + 0.5) / n
1068
+ i_lo = np.searchsorted(v_target, v_partner, side="left")
1069
+ i_hi = np.searchsorted(v_target, v_partner, side="right") - 1
1070
+ held = i_hi >= i_lo
1071
+ a, b = np.clip(i_hi, 0, n - 1), np.clip(i_lo, 0, n - 1)
1072
+ span = v_target[b] - v_target[a]
1073
+ f = np.where(span > 0, (v_partner - v_target[a]) / np.where(span > 0, span, 1.0), 0.5)
1074
+ point = lv[a] + np.clip(f, 0.0, 1.0) * (lv[b] - lv[a])
1075
+ point = np.where(i_lo == 0, 0.0, np.where(i_hi == n - 1, 1.0, point))
1076
+ lo = np.where(held, lv[np.clip(i_lo, 0, n - 1)] - 0.5 / n, point)
1077
+ hi = np.where(held, lv[np.clip(i_hi, 0, n - 1)] + 0.5 / n, point)
1078
+ return np.clip(lo, 0.0, 1.0), np.clip(hi, 0.0, 1.0)
1079
+
1080
+
1081
+ def _find_ridges(j: int, preds: Sequence[int], st: _State, values: Mapping[int, np.ndarray],
1082
+ rows: np.ndarray, cell_min: int) -> _Ridges:
1083
+ """The earlier columns that the rows ``rows`` of column ``j`` (those outside its atoms)
1084
+ copy: a partner qualifies when at least ``RIDGE_SHARE`` of them (and ``5 * cell_min``) have
1085
+ exactly its value and they outnumber the near misses around them. At most ``MAX_RIDGES``,
1086
+ the most copied first."""
1087
+ vt = values.get(j)
1088
+ if vt is None or not rows.size:
1089
+ return _no_ridges()
1090
+ u = special.ndtr(st.z[rows, j])
1091
+ z, missing = st.score[rows], st.missing[rows]
1092
+ found = []
1093
+ for p in preds:
1094
+ vp = values.get(p)
1095
+ if vp is None:
1096
+ continue
1097
+ lo, hi = _copy_intervals(vp, vt)
1098
+ one = _Ridges(np.array([p], dtype=np.int64), _edge_u(_edge_z(lo))[None, :],
1099
+ _edge_u(_edge_z(hi))[None, :])
1100
+ on = one.which(u, z, missing) == 0
1101
+ n_on = int(on.sum())
1102
+ if n_on < max(RIDGE_SHARE * rows.size, 5 * cell_min):
1103
+ continue
1104
+ wide = _Ridges(one.cols, np.maximum(one.lower - 3.0 / vt.size, 0.0),
1105
+ np.minimum(one.upper + 3.0 / vt.size, 1.0))
1106
+ if int((wide.which(u, z, missing) == 0).sum()) - n_on < n_on:
1107
+ found.append((-n_on, int(p), one))
1108
+ found.sort(key=lambda t: t[:2])
1109
+ keep = [t[2] for t in found[:MAX_RIDGES]]
1110
+ if not keep:
1111
+ return _no_ridges(vt.size)
1112
+ return _Ridges(np.concatenate([k.cols for k in keep]), np.vstack([k.lower for k in keep]),
1113
+ np.vstack([k.upper for k in keep]))
1114
+
1115
+
1116
+ # ---------------------------------------------------------------------------------------------
1117
+ # Leaf distributions
1118
+ # ---------------------------------------------------------------------------------------------
1119
+
1120
+ class _Dists(NamedTuple):
1121
+ """Distribution rows of one column: cells (atom, share), the rest and how it is spread."""
1122
+
1123
+ rest: np.ndarray # (R,) share of the pooled rest
1124
+ parent: np.ndarray # (R,) row the rest of a nominal column is spread like, or -1
1125
+ line_col: np.ndarray # (R,) earlier column a continuous leaf's line runs along, or -1
1126
+ line_slope: np.ndarray # (R,) slope of that line in the column's de-jittered score
1127
+ cell_offsets: np.ndarray # (R + 1,)
1128
+ cell_atom: np.ndarray
1129
+ cell_prob: np.ndarray
1130
+ mean_offsets: np.ndarray # (R + 1,)
1131
+ means: np.ndarray # block means of the rest (ordinal / continuous columns)
1132
+ sds: np.ndarray # block standard deviations
1133
+
1134
+ @property
1135
+ def n(self) -> int:
1136
+ return int(self.rest.size)
1137
+
1138
+
1139
+ def _pool(counts: np.ndarray, total: np.ndarray, cell_min: int
1140
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
1141
+ """Shares of the cells with at least ``cell_min`` rows and of the pooled rest.
1142
+
1143
+ The rest is never stored below ``cell_min`` as it is: under half of it the rows are
1144
+ dropped, from half of it they count as ``cell_min``. Returns ``(big, share, rest)``.
1145
+ """
1146
+ big = counts >= cell_min
1147
+ kept = np.where(big, counts, 0.0)
1148
+ rest = total - kept.sum(axis=1)
1149
+ rest = np.where(rest < 0.5 * cell_min, 0.0, np.maximum(rest, float(cell_min)))
1150
+ denom = np.maximum(kept.sum(axis=1) + rest, 1.0)
1151
+ return big, kept / denom[:, None], rest / denom
1152
+
1153
+
1154
+ def _line_fit(group: np.ndarray, n_groups: int, s: np.ndarray, v: np.ndarray,
1155
+ w: np.ndarray | None = None) -> tuple[np.ndarray, ...]:
1156
+ """Per group, the least-squares line of ``v`` on ``s``: ``(rows, slope, intercept, r2)``
1157
+ (slope 0 where ``s`` does not vary)."""
1158
+ if w is None:
1159
+ w = np.ones(v.size)
1160
+ n = np.bincount(group, weights=w, minlength=n_groups)
1161
+ safe = np.maximum(n, 1.0)
1162
+ ms = np.bincount(group, weights=w * s, minlength=n_groups) / safe
1163
+ mv = np.bincount(group, weights=w * v, minlength=n_groups) / safe
1164
+ ds, dv = s - ms[group], v - mv[group]
1165
+ vs = np.bincount(group, weights=w * ds * ds, minlength=n_groups) / safe
1166
+ vv = np.bincount(group, weights=w * dv * dv, minlength=n_groups) / safe
1167
+ cov = np.bincount(group, weights=w * ds * dv, minlength=n_groups) / safe
1168
+ ok = (vs > 1e-8) & (vv > 1e-12)
1169
+ slope = np.where(ok, cov / np.where(ok, vs, 1.0), 0.0)
1170
+ r2 = np.where(ok, cov * cov / np.where(ok, vs * vv, 1.0), 0.0)
1171
+ return n, slope, mv - slope * ms, r2
1172
+
1173
+
1174
+ def _trim_lines(group: np.ndarray, n_groups: int, s: np.ndarray, v: np.ndarray,
1175
+ slope: np.ndarray, icpt: np.ndarray, min_rows: int
1176
+ ) -> tuple[np.ndarray, np.ndarray]:
1177
+ """Least-trimmed-squares refinement of per-group lines: twice, refit every line on the
1178
+ half of its group's rows nearest to it, so that a line follows the rows that lie on a
1179
+ ridge instead of being pulled off it by the others. Groups with fewer than ``min_rows``
1180
+ rows keep their line (their half would describe too few rows)."""
1181
+ size = np.bincount(group, minlength=n_groups)
1182
+ start = np.concatenate([[0], np.cumsum(size)[:-1]])
1183
+ refit = size >= min_rows
1184
+ for _ in range(TRIM_PASSES):
1185
+ r = np.abs(v - slope[group] * s - icpt[group])
1186
+ o = np.lexsort((r, group))
1187
+ rank = np.empty(v.size, dtype=np.int64)
1188
+ rank[o] = np.arange(v.size) - start[group[o]]
1189
+ near = (rank < (size[group] + 1) // 2).astype(np.float64)
1190
+ _, a, b, _ = _line_fit(group, n_groups, s, v, near)
1191
+ moved = refit & (a != 0)
1192
+ slope, icpt = np.where(moved, a, slope), np.where(moved, b, icpt)
1193
+ return slope, icpt
1194
+
1195
+
1196
+ def _local_lines(row: np.ndarray, n_rows: int, v: np.ndarray, scores: np.ndarray,
1197
+ cand: Sequence[int], cell_min: int) -> tuple[np.ndarray, np.ndarray]:
1198
+ """For every leaf, the earlier column along which its rows' values ``v`` lie closest to a
1199
+ line, and that line's slope (``-1`` / 0 when no column explains ``LINE_R2`` of their
1200
+ variance or the leaf has fewer than ``cell_min`` scored rows).
1201
+
1202
+ ``row`` is each scored row's leaf, ``scores`` the candidates' de-jittered scores. A leaf
1203
+ of rows that copy another column (a bill equal to last month's) is then drawn *relative
1204
+ to that column*, which a distribution of the value alone cannot say.
1205
+ """
1206
+ col = np.full(n_rows, -1, dtype=np.int64)
1207
+ slope, icpt = np.zeros(n_rows), np.zeros(n_rows)
1208
+ best = np.full(n_rows, LINE_R2)
1209
+ pick = np.zeros(n_rows, dtype=np.int64)
1210
+ for i in range(len(cand)):
1211
+ n, a, b, r2 = _line_fit(row, n_rows, scores[:, i], v)
1212
+ better = (r2 > best) & (n >= cell_min)
1213
+ best[better], pick[better] = r2[better], i
1214
+ slope[better], icpt[better] = a[better], b[better]
1215
+ col[better] = cand[i]
1216
+ if not (col >= 0).any():
1217
+ return col, slope
1218
+ s = scores[np.arange(v.size), pick[row]]
1219
+ slope, _ = _trim_lines(row, n_rows, s, v, slope, icpt, 2 * cell_min)
1220
+ return col, np.where(col >= 0, slope, 0.0)
1221
+
1222
+
1223
+ def _fit_dists(tree: _Tree, xb: np.ndarray, rows: np.ndarray, kind: int, n_cells: int,
1224
+ atom: np.ndarray, value: np.ndarray, policy: DisclosurePolicySpec,
1225
+ cell_min: int, scores: np.ndarray | None = None,
1226
+ cand: Sequence[int] = ()) -> tuple[_Tree, _Dists]:
1227
+ """Fit the distribution of every leaf (and of the ancestors a nominal or continuous
1228
+ column's rest is spread like) on ``rows``. ``atom`` is each row's cell: an atom of an
1229
+ atomic column; an atom, "continuous" or a ridge of a continuous one. ``value`` is the
1230
+ score a density describes (the latent score of an ordinal column, the residual of the
1231
+ rows in a continuous column's "continuous" cell; NaN where the row has none). With
1232
+ ``scores`` (rows x columns) and candidate columns ``cand`` every leaf of a continuous
1233
+ column may get a local line."""
1234
+ m, k = tree.feature.size, int(n_cells)
1235
+ a_r, v_r = atom[rows], value[rows].copy()
1236
+ counts = np.zeros((m, k))
1237
+ total = np.zeros(m)
1238
+ nv, sv1, sv2 = np.zeros(m), np.zeros(m), np.zeros(m)
1239
+ leaf = np.zeros(rows.size, dtype=np.int64)
1240
+ has_v = np.isfinite(v_r)
1241
+ v0 = np.where(has_v, v_r, 0.0)
1242
+ for idx, nd in _walk(tree, xb, rows):
1243
+ total += np.bincount(nd, minlength=m)
1244
+ if k:
1245
+ ok = a_r[idx] >= 0
1246
+ counts += np.bincount(nd[ok] * k + a_r[idx][ok], minlength=m * k).reshape(m, k)
1247
+ if kind != KIND_NOMINAL: # per-node moments, for the fallback below
1248
+ nv += np.bincount(nd, weights=has_v[idx].astype(np.float64), minlength=m)
1249
+ sv1 += np.bincount(nd, weights=v0[idx], minlength=m)
1250
+ sv2 += np.bincount(nd, weights=v0[idx] ** 2, minlength=m)
1251
+ leaf[idx] = nd
1252
+ big, share, rest = _pool(counts, total, cell_min)
1253
+ parent = _parents(tree)
1254
+ needed = tree.feature < 0
1255
+ inherits = kind != KIND_ORDINAL # the rest is spread like the parent node's
1256
+ if inherits:
1257
+ for v in range(m - 1, 0, -1):
1258
+ if needed[v] and rest[v] > 0:
1259
+ needed[parent[v]] = True
1260
+ nodes = np.flatnonzero(needed)
1261
+ is_leaf = tree.feature[nodes] < 0
1262
+ row_of = np.full(m, -1, dtype=np.int64)
1263
+ row_of[nodes] = np.arange(nodes.size)
1264
+ n_rows = nodes.size
1265
+ d_parent = np.full(n_rows, -1, dtype=np.int64)
1266
+ if inherits:
1267
+ up = (rest[nodes] > 0) & (parent[nodes] >= 0)
1268
+ d_parent[up] = row_of[parent[nodes[up]]]
1269
+ lr = row_of[leaf]
1270
+ # -- local lines (continuous columns): the density then describes what they leave ---------
1271
+ line_col = np.full(n_rows, -1, dtype=np.int64)
1272
+ line_slope = np.zeros(n_rows)
1273
+ if kind == KIND_CONTINUOUS and scores is not None and len(cand) and has_v.any():
1274
+ sv = scores[np.ix_(rows[has_v], list(cand))]
1275
+ line_col, line_slope = _local_lines(lr[has_v], n_rows, v_r[has_v], sv, cand, cell_min)
1276
+ line_slope = _f32(_round_rel(_coarsen(line_slope, policy), STORE_BITS))
1277
+ on = line_col[lr[has_v]]
1278
+ v_r[has_v] -= line_slope[lr[has_v]] * scores[rows[has_v], np.maximum(on, 0)] * (on >= 0)
1279
+ # -- the density: equal-count blocks of a leaf's scored rows (an ordinal column: those
1280
+ # outside its cells; a continuous column: those of its "continuous" cell) --------------
1281
+ means, sds = np.zeros(0), np.zeros(0)
1282
+ mean_off = np.zeros(n_rows + 1, dtype=np.int64)
1283
+ if kind != KIND_NOMINAL:
1284
+ outside = has_v.copy()
1285
+ if kind == KIND_ORDINAL:
1286
+ in_cell = a_r >= 0
1287
+ outside[in_cell] &= ~big[leaf[in_cell], a_r[in_cell]]
1288
+ lr_o, v_o = lr[outside], v_r[outside]
1289
+ o = np.lexsort((v_o, lr_o))
1290
+ lr_o, v_o = lr_o[o], v_o[o]
1291
+ n_o = np.bincount(lr_o, minlength=n_rows)
1292
+ start = np.concatenate([[0], np.cumsum(n_o)[:-1]])
1293
+ cap = max(1, min(MAX_BLOCKS, int(policy.quantile_resolution)))
1294
+ g = np.where(n_o >= cell_min, np.clip(n_o // cell_min, 1, cap), 0)
1295
+ # a leaf whose cells may send a draw to the density always has one
1296
+ fallback = (g == 0) & is_leaf & ((rest[nodes] > 0) | (kind == KIND_CONTINUOUS))
1297
+ mean_off = np.concatenate([[0], np.cumsum(np.where(fallback, 1, g))])
1298
+ means, sds = np.zeros(int(mean_off[-1])), np.ones(int(mean_off[-1]))
1299
+ use = g[lr_o] > 0
1300
+ rank = np.arange(v_o.size) - start[lr_o]
1301
+ key = mean_off[lr_o[use]] + (rank[use] * g[lr_o[use]]) // np.maximum(n_o[lr_o[use]], 1)
1302
+ size = np.bincount(key, minlength=means.size)
1303
+ filled = size > 0
1304
+ means[filled] = np.bincount(key, weights=v_o[use], minlength=means.size)[filled] \
1305
+ / size[filled]
1306
+ centred = v_o[use] - means[key]
1307
+ sds[filled] = np.sqrt(np.bincount(key, weights=centred * centred,
1308
+ minlength=means.size)[filled] / size[filled])
1309
+ fb = np.flatnonzero(fallback)
1310
+ if fb.size:
1311
+ # too few rows outside the cells for a density of their own: every scored row of
1312
+ # the leaf, or of its nearest ancestor with at least ``cell_min`` of them
1313
+ anc = nodes[fb].copy()
1314
+ for _ in range(m):
1315
+ short = (nv[anc] < cell_min) & (parent[anc] >= 0)
1316
+ if not short.any():
1317
+ break
1318
+ anc[short] = parent[anc[short]]
1319
+ okf = nv[anc] >= cell_min
1320
+ mu = np.where(okf, sv1[anc] / np.maximum(nv[anc], 1.0), 0.0)
1321
+ var = np.where(okf, sv2[anc] / np.maximum(nv[anc], 1.0) - mu * mu, 1.0)
1322
+ means[mean_off[fb]] = mu
1323
+ sds[mean_off[fb]] = np.sqrt(np.maximum(var, 0.0))
1324
+ line_col[fb], line_slope[fb] = -1, 0.0 # an ancestor's moments have no line
1325
+ # -- coarsen -------------------------------------------------------------------------------
1326
+ share_n, rest_n = share[nodes], rest[nodes]
1327
+ ci, ca = np.nonzero(share_n > 0) if k else (np.zeros(0, np.int64), np.zeros(0, np.int64))
1328
+ cell_prob = _round_rel(_coarsen(share_n[ci, ca], policy), STORE_BITS) if k else np.zeros(0)
1329
+ cell_off = np.concatenate([[0], np.cumsum(np.bincount(ci, minlength=n_rows))])
1330
+ dists = _Dists(
1331
+ rest=_f32(_round_rel(_coarsen(rest_n, policy), STORE_BITS)), parent=d_parent,
1332
+ line_col=line_col, line_slope=_f32(line_slope),
1333
+ cell_offsets=cell_off.astype(np.int64), cell_atom=ca.astype(np.int64),
1334
+ cell_prob=_f32(cell_prob), mean_offsets=mean_off.astype(np.int64),
1335
+ means=_f32(_round_abs(_coarsen(means, policy), LOC_QUANTUM)),
1336
+ sds=_f32(_round_rel(_coarsen(np.maximum(sds, MIN_SCALE), policy), STORE_BITS)))
1337
+ left = tree.left.copy()
1338
+ left[nodes[is_leaf]] = row_of[nodes[is_leaf]]
1339
+ return tree._replace(left=left), dists
1340
+
1341
+
1342
+ def _root_dists(kind: int) -> _Dists:
1343
+ """One row that says nothing about the data: all rest, spread like the marginal (N(0, 1)
1344
+ for a continuous column)."""
1345
+ blocks = 0 if kind == KIND_NOMINAL else 1
1346
+ return _Dists(rest=np.ones(1), parent=np.full(1, -1, dtype=np.int64),
1347
+ line_col=np.full(1, -1, dtype=np.int64), line_slope=np.zeros(1),
1348
+ cell_offsets=np.zeros(2, dtype=np.int64), cell_atom=np.zeros(0, np.int64),
1349
+ cell_prob=np.zeros(0), mean_offsets=np.array([0, blocks], dtype=np.int64),
1350
+ means=np.zeros(blocks), sds=np.ones(blocks))
1351
+
1352
+
1353
+ def _stump() -> _Tree:
1354
+ return _Tree(np.array([-1]), np.array([-1]), np.array([0]), np.array([-1]))
1355
+
1356
+
1357
+ def _stack(trees: list[_Tree], dists: list[_Dists]) -> tuple[np.ndarray, np.ndarray, _Dists]:
1358
+ """Concatenate a column's trees and their distribution rows (rows renumbered)."""
1359
+ node_rows, parts = [], []
1360
+ row0 = cell0 = mean0 = 0
1361
+ for t, ds in zip(trees, dists):
1362
+ leaf = t.feature < 0
1363
+ node_rows.append(np.column_stack([t.feature, t.threshold,
1364
+ np.where(leaf, t.left + row0, t.left), t.right]))
1365
+ parts.append(ds._replace(parent=np.where(ds.parent >= 0, ds.parent + row0, -1),
1366
+ cell_offsets=ds.cell_offsets[:-1] + cell0,
1367
+ mean_offsets=ds.mean_offsets[:-1] + mean0))
1368
+ row0 += ds.n
1369
+ cell0 += int(ds.cell_offsets[-1])
1370
+ mean0 += int(ds.mean_offsets[-1])
1371
+ offsets = np.concatenate([[0], np.cumsum([len(r) for r in node_rows])])
1372
+ merged = _Dists(*[np.concatenate([getattr(p, f) for p in parts]) for f in _Dists._fields])
1373
+ merged = merged._replace(cell_offsets=np.append(merged.cell_offsets, cell0),
1374
+ mean_offsets=np.append(merged.mean_offsets, mean0))
1375
+ return np.vstack(node_rows), offsets, merged
1376
+
1377
+
1378
+ # ---------------------------------------------------------------------------------------------
1379
+ # Runtime: dense leaf distributions and the draws of one column
1380
+ # ---------------------------------------------------------------------------------------------
1381
+
1382
+ def _mix_draw(ds: _Dists, rows: np.ndarray, v: np.ndarray) -> np.ndarray:
1383
+ """A draw from the rest density of each of ``rows``: one of its blocks, uniformly, then
1384
+ normal with the block's mean and standard deviation (both from the one uniform ``v``).
1385
+ The mixture has the mean and the variance of the rows it was fitted on."""
1386
+ g = np.diff(ds.mean_offsets)[rows]
1387
+ gg = np.maximum(g, 1)
1388
+ k = np.minimum((v * gg).astype(np.int64), gg - 1)
1389
+ t = special.ndtri(np.clip(v * gg - k, 1e-12, 1.0 - 1e-12))
1390
+ if not ds.means.size:
1391
+ return t
1392
+ idx = np.minimum(ds.mean_offsets[rows] + k, ds.means.size - 1)
1393
+ return np.where(g > 0, ds.means[idx] + ds.sds[idx] * t, t)
1394
+
1395
+
1396
+ def _mix_cdf(ds: _Dists, x: np.ndarray) -> np.ndarray:
1397
+ """CDF of every row's rest density at the points ``x`` (shape ``(rows, len(x))``)."""
1398
+ g = np.diff(ds.mean_offsets)
1399
+ out = np.tile(special.ndtr(x), (g.size, 1))
1400
+ for gv in np.unique(g[g > 0]):
1401
+ rows = np.flatnonzero(g == gv)
1402
+ acc = np.zeros((rows.size, x.size))
1403
+ for k in range(int(gv)):
1404
+ idx = ds.mean_offsets[rows] + k
1405
+ acc += special.ndtr((x[None, :] - ds.means[idx, None]) / ds.sds[idx, None])
1406
+ out[rows] = acc / gv
1407
+ return out
1408
+
1409
+
1410
+ class _Runtime:
1411
+ """One column of the fitted chain, ready to be sampled."""
1412
+
1413
+ def __init__(self, j: int, col: _Column, nodes: np.ndarray, tree_offsets: np.ndarray,
1414
+ ds: _Dists, beta: np.ndarray, tilt: np.ndarray, grid: np.ndarray,
1415
+ grid_levels: np.ndarray, ridges: _Ridges | None = None) -> None:
1416
+ self.j, self.col, self.ds = j, col, ds
1417
+ self.ridges = ridges if ridges is not None else _no_ridges()
1418
+ # cells: the column's own (atoms; atoms and "continuous") and one per ridge, which
1419
+ # shares the tilt factor of "continuous" and has no mass in the marginal
1420
+ self.n_cells = col.n_cells + self.ridges.n
1421
+ self.group = np.concatenate([np.arange(col.n_cells),
1422
+ np.full(self.ridges.n, col.n_cells - 1)]).astype(np.int64)
1423
+ self.target = np.concatenate([col.target, np.zeros(self.ridges.n)])
1424
+ nd = np.asarray(nodes, dtype=np.int64).reshape(-1, 4)
1425
+ self.trees = [(nd[a:b, 0], nd[a:b, 1], nd[a:b, 2], nd[a:b, 3])
1426
+ for a, b in zip(tree_offsets[:-1], tree_offsets[1:])]
1427
+ self.beta = np.asarray(beta, dtype=np.float64)
1428
+ self.preds = np.flatnonzero(self.beta != 0.0)
1429
+ self.lined = bool(np.any(ds.line_col >= 0))
1430
+ self.grid_levels = grid_levels
1431
+ self.grid = np.asarray(grid, dtype=np.float64)
1432
+ #: for a conditionally encoded child: the atoms each value of its parent allows. The
1433
+ #: encoder's conditional table gives every atom an interval in every parent row (a
1434
+ #: combination that never occurs gets a sliver), so "allowed" is: not made
1435
+ #: ``PARENT_MIN_LIFT`` times rarer by the parent than the atom is overall. A leaf that
1436
+ #: is not pure in the parent holds atoms of several parent values; a row draws among
1437
+ #: those its own parent allows
1438
+ self.feasible: np.ndarray | None = None
1439
+ if col.kind != KIND_CONTINUOUS and col.n_rows > 1 and not self.ridges.n:
1440
+ self.feasible = col.width >= PARENT_MIN_LIFT * col.width[-1][None, :]
1441
+ self.base = self._dense()
1442
+ self.set_tilt(tilt)
1443
+
1444
+ def _dense(self) -> np.ndarray:
1445
+ """Cell probabilities of every row before the tilt: all atoms of an atomic column; the
1446
+ major atoms, "continuous" and the ridges of a continuous one."""
1447
+ col, ds = self.col, self.ds
1448
+ n, k = ds.n, self.n_cells
1449
+ p = np.zeros((n, k))
1450
+ ri = np.repeat(np.arange(n), np.diff(ds.cell_offsets))
1451
+ p[ri, ds.cell_atom] = ds.cell_prob
1452
+ is_cell = np.zeros((n, k), dtype=bool)
1453
+ is_cell[ri, ds.cell_atom] = True
1454
+ rest = ds.rest.astype(np.float64)
1455
+ if col.kind == KIND_ORDINAL:
1456
+ with np.errstate(divide="ignore"):
1457
+ edges = np.clip(special.ndtri(np.concatenate([col.lower[-1], [1.0]])),
1458
+ -Z_LIMIT, Z_LIMIT)
1459
+ cdf = _mix_cdf(ds, edges)
1460
+ cdf[:, 0], cdf[:, -1] = 0.0, 1.0
1461
+ spread = np.where(is_cell, 0.0, np.maximum(np.diff(cdf, axis=1), 0.0))
1462
+ p += rest[:, None] * self._share(spread, is_cell)
1463
+ else:
1464
+ level = np.zeros(n, dtype=np.int64)
1465
+ for r in np.flatnonzero(ds.parent >= 0): # parents precede their children
1466
+ level[r] = level[ds.parent[r]] + 1
1467
+ for lv in range(int(np.max(level, initial=0)) + 1):
1468
+ rows = np.flatnonzero(level == lv)
1469
+ par = ds.parent[rows]
1470
+ like = np.where((par >= 0)[:, None], p[np.maximum(par, 0)], self.target[None, :])
1471
+ spread = np.where(is_cell[rows], 0.0, like)
1472
+ p[rows] += rest[rows, None] * self._share(spread, is_cell[rows])
1473
+ total = p.sum(axis=1, keepdims=True)
1474
+ return np.where(total > 0, p / np.where(total > 0, total, 1.0), self.target[None, :])
1475
+
1476
+ def _share(self, spread: np.ndarray, is_cell: np.ndarray) -> np.ndarray:
1477
+ """Normalise how a rest is spread over the atoms outside the row's cells (the marginal
1478
+ when the density puts nothing there)."""
1479
+ total = spread.sum(axis=1, keepdims=True)
1480
+ alt = np.where(is_cell, 0.0, self.target[None, :])
1481
+ alt_total = alt.sum(axis=1, keepdims=True)
1482
+ alt = alt / np.where(alt_total > 0, alt_total, 1.0)
1483
+ return np.where(total > 1e-12, spread / np.where(total > 1e-12, total, 1.0), alt)
1484
+
1485
+ def set_tilt(self, tilt: np.ndarray) -> None:
1486
+ self.tilt = np.asarray(tilt, dtype=np.float64)
1487
+ p = self.base * self.tilt[self.group][None, :]
1488
+ total = p.sum(axis=1, keepdims=True)
1489
+ p = np.where(total > 0, p / np.where(total > 0, total, 1.0), self.base)
1490
+ cdf = np.cumsum(p, axis=1)
1491
+ cdf[:, -1] = 1.0
1492
+ self._flat = (cdf + np.arange(cdf.shape[0])[:, None]).ravel()
1493
+ self._flat_rows: dict[int, np.ndarray] = {}
1494
+
1495
+ def _allowed(self, tilt: np.ndarray, r: int) -> np.ndarray:
1496
+ """Cell probabilities of every distribution row for a data row whose parent is at
1497
+ interval row ``r``: the tilted leaf, restricted to the atoms that parent value allows.
1498
+ A leaf with none of them falls back on the parent's own table (the widths of its
1499
+ intervals: the encoder's conditional distribution)."""
1500
+ assert self.feasible is not None
1501
+ p = self.base * tilt[self.group][None, :] * self.feasible[r][None, :]
1502
+ total = p.sum(axis=1, keepdims=True)
1503
+ width = self.col.width[r]
1504
+ table = width / max(float(width.sum()), _TINY)
1505
+ return np.where(total > 0, p / np.where(total > 0, total, 1.0), table[None, :])
1506
+
1507
+ def _row_flat(self, r: int) -> np.ndarray:
1508
+ if r not in self._flat_rows:
1509
+ p = self._allowed(self.tilt, r)
1510
+ cdf = np.cumsum(p, axis=1)
1511
+ # from its last allowed atom on, a row's cumulative share is 1: no draw lands on
1512
+ # an atom the parent does not allow
1513
+ last = p.shape[1] - 1 - np.argmax(p[:, ::-1] > 0, axis=1)
1514
+ cdf[np.arange(p.shape[1])[None, :] >= last[:, None]] = 1.0
1515
+ self._flat_rows[r] = (cdf + np.arange(cdf.shape[0])[:, None]).ravel()
1516
+ return self._flat_rows[r]
1517
+
1518
+ def fit_tilt(self, leaf: np.ndarray, prow: np.ndarray | None = None) -> np.ndarray:
1519
+ """One factor per cell that makes the cell frequencies of the rows in ``leaf`` (model
1520
+ draws; ``prow``: their parent's interval rows, for a conditionally encoded child) equal
1521
+ to the column's marginal (iterative proportional fitting)."""
1522
+ want = self.col.target
1523
+ tilt = np.ones(want.size)
1524
+ if self.feasible is not None and prow is not None:
1525
+ n_rows = self.feasible.shape[0]
1526
+ share = np.bincount(prow * self.ds.n + leaf, minlength=n_rows * self.ds.n
1527
+ ).reshape(n_rows, self.ds.n) / max(leaf.size, 1)
1528
+ used = np.flatnonzero(share.sum(axis=1) > 0)
1529
+ else:
1530
+ share = (np.bincount(leaf, minlength=self.ds.n) / max(leaf.size, 1))[None, :]
1531
+ used = np.zeros(1, dtype=np.int64)
1532
+ for _ in range(TILT_ITERATIONS):
1533
+ got = np.zeros(want.size)
1534
+ for r in used:
1535
+ if self.feasible is not None and prow is not None:
1536
+ p = self._allowed(tilt, int(r))
1537
+ else:
1538
+ p = self.base * tilt[self.group][None, :]
1539
+ p /= np.maximum(p.sum(axis=1, keepdims=True), _TINY)
1540
+ got += np.bincount(self.group, weights=share[r] @ p, minlength=want.size)
1541
+ tilt *= np.where(got > 1e-12, want / np.maximum(got, 1e-12), 1.0)
1542
+ tilt = np.clip(tilt, 1.0 / MAX_TILT, MAX_TILT)
1543
+ return tilt / max(float(np.max(tilt)), _TINY)
1544
+
1545
+ # -- draws ----------------------------------------------------------------------------------
1546
+ def leaves(self, bins: np.ndarray, v: np.ndarray) -> np.ndarray:
1547
+ """Distribution row of every row: one of the column's trees, uniformly."""
1548
+ n_trees = len(self.trees)
1549
+ if n_trees == 1:
1550
+ tree = self.trees[0]
1551
+ return tree[2][_route(tree, bins)]
1552
+ pick = np.minimum((v * n_trees).astype(np.int64), n_trees - 1)
1553
+ out = np.zeros(bins.shape[0], dtype=np.int64)
1554
+ for t, tree in enumerate(self.trees):
1555
+ rows = np.flatnonzero(pick == t)
1556
+ if rows.size:
1557
+ out[rows] = tree[2][_route(tree, bins, rows)]
1558
+ return out
1559
+
1560
+ def cells(self, leaf: np.ndarray, v: np.ndarray, prow: np.ndarray | None = None
1561
+ ) -> np.ndarray:
1562
+ """The cell each row draws from its leaf at the uniform ``v``. For a conditionally
1563
+ encoded child (``prow``: the parent's interval row of every row) only among the atoms
1564
+ its parent's value allows."""
1565
+ k = self.n_cells
1566
+ at = leaf + np.minimum(v, 1.0 - 1e-12)
1567
+ if self.feasible is None or prow is None:
1568
+ idx = np.searchsorted(self._flat, at, side="right")
1569
+ return np.clip(idx - leaf * k, 0, k - 1)
1570
+ out = np.zeros(leaf.shape[0], dtype=np.int64)
1571
+ for r in np.unique(prow):
1572
+ rows = np.flatnonzero(prow == r)
1573
+ idx = np.searchsorted(self._row_flat(int(r)), at[rows], side="right")
1574
+ out[rows] = np.clip(idx - leaf[rows] * k, 0, k - 1)
1575
+ return out
1576
+
1577
+ def base_value(self, st: _State, rows: np.ndarray, leaf: np.ndarray) -> np.ndarray:
1578
+ """What the residual of a continuous column is added to at ``rows``: the column's
1579
+ linear base plus the line of each row's leaf."""
1580
+ out = np.zeros(rows.size)
1581
+ if self.preds.size:
1582
+ out += st.score[np.ix_(rows, self.preds)] @ self.beta[self.preds]
1583
+ if self.lined:
1584
+ along = self.ds.line_col[leaf]
1585
+ on = along >= 0
1586
+ out[on] += self.ds.line_slope[leaf[on]] * st.score[rows[on], along[on]]
1587
+ return out
1588
+
1589
+ def to_normal(self, raw: np.ndarray, w: np.ndarray) -> np.ndarray:
1590
+ """``raw`` through the grid. A draw beyond the grid's ends gets a score from N(0, 1)'s
1591
+ own tail out there, at the uniform ``w``: the grid cannot tell how the model's draws
1592
+ are distributed where only a dozen of the seeded rows fell, and the conditional model
1593
+ is not to be trusted there either (a leaf of a few rows with a wide block reaches far
1594
+ beyond the scores it was fitted on). The order among those draws is not kept."""
1595
+ grid, levels = self.grid, self.grid_levels
1596
+ out = np.interp(raw, grid, levels)
1597
+ beyond = float(special.ndtr(levels[0])) # N(0, 1) mass beyond either end
1598
+ below, above = raw < grid[0], raw > grid[-1]
1599
+ if below.any():
1600
+ out[below] = special.ndtri(beyond * w[below])
1601
+ if above.any():
1602
+ out[above] = -special.ndtri(beyond * w[above])
1603
+ return np.clip(out, -Z_LIMIT, Z_LIMIT)
1604
+
1605
+
1606
+ def _draw(rt: _Runtime, st: _State, v: np.ndarray, calibrate: bool = False) -> None:
1607
+ """Draw column ``rt.j`` for every row of ``st`` from the uniforms ``v`` (4 x rows). With
1608
+ ``calibrate`` the column's tilt and grid are first estimated from these very rows (those
1609
+ where the column is not missing: the others do not keep their draw)."""
1610
+ j, col = rt.j, rt.col
1611
+ n = st.z.shape[0]
1612
+ missing = st.atom[:, col.indicator] == 1 if col.indicator >= 0 else None
1613
+ kept = np.ones(n, dtype=bool) if missing is None else ~missing
1614
+ leaf = rt.leaves(st.bins, v[0])
1615
+ prow = col.table_rows(st.atom, st.missing)
1616
+ if calibrate:
1617
+ rt.set_tilt(_f32(_round_rel(rt.fit_tilt(leaf[kept], prow[kept]), STORE_BITS)))
1618
+ cell = rt.cells(leaf, v[1], prow)
1619
+ up = np.full(n, np.nan)
1620
+ if col.kind == KIND_CONTINUOUS:
1621
+ m = col.n_atoms
1622
+ atom = np.where(cell < m, cell, -1)
1623
+ z = np.empty(n)
1624
+ other = np.flatnonzero(cell < m)
1625
+ if other.size:
1626
+ z[other] = col.within(prow[other], cell[other], v[2][other])
1627
+ dense = cell == m
1628
+ copied = np.zeros(n, dtype=bool)
1629
+ for r in range(rt.ridges.n): # copies of an earlier column
1630
+ partner = int(rt.ridges.cols[r])
1631
+ rows = np.flatnonzero(cell == m + 1 + r)
1632
+ lo, hi = rt.ridges.interval(r, special.ndtr(st.score[rows, partner]))
1633
+ u = np.clip(lo + (hi - lo) * v[2][rows], U_EPS, 1.0 - U_EPS)
1634
+ # nothing to copy: the partner is missing, has a value the column never takes, or
1635
+ # has one of the column's atoms (such rows are in the atom's cell, and a copy on
1636
+ # top of them would be mass the tilt does not see). Such a row takes the density.
1637
+ gone = (st.missing[rows, partner] | rt.ridges.outside(lo, hi)
1638
+ | (col.assign(u, prow[rows]) >= 0))
1639
+ dense[rows[gone]] = True
1640
+ rows, u = rows[~gone], u[~gone]
1641
+ z[rows] = special.ndtri(u)
1642
+ up[rows] = col.excise(u)
1643
+ copied[rows] = True
1644
+ cont = np.flatnonzero(dense)
1645
+ raw = _mix_draw(rt.ds, leaf[cont], v[2][cont]) + rt.base_value(st, cont, leaf[cont])
1646
+ if calibrate and int(kept[cont].sum()) >= MIN_GRID_ROWS:
1647
+ # the grid makes the whole continuous part N(0, 1) while the copies stay copies
1648
+ rt.grid = _quantile_grid(raw[kept[cont]], rt.grid_levels, special.ndtri(np.clip(
1649
+ up[copied & kept], 1e-12, 1.0 - 1e-12)))
1650
+ upc = np.clip(special.ndtr(rt.to_normal(raw, v[3][cont])), 1e-12, 1.0 - 1e-12)
1651
+ up[cont] = upc
1652
+ z[cont] = _ndtri(col.unexcise(upc))
1653
+ else:
1654
+ atom = cell
1655
+ z = col.within(prow, cell, v[2])
1656
+ if missing is not None and missing.any(): # the encoder's imputation: N(0, 1)
1657
+ z = np.where(missing, _ndtri(v[3]), z)
1658
+ st.put(j, col, z, atom, up, prow, missing)
1659
+
1660
+
1661
+ def _quantile_grid(raw: np.ndarray, levels: np.ndarray, fixed: np.ndarray | None = None
1662
+ ) -> np.ndarray:
1663
+ """The grid that sends ``raw`` (model draws) to N(0, 1): its quantiles at ``Phi(levels)``,
1664
+ strictly increasing float32. With ``fixed`` draws that are not mapped (copies of another
1665
+ column), ``raw`` is sent to what N(0, 1) leaves once they are taken out, so that the two
1666
+ together are N(0, 1): quantiles at ``(Phi - w F_fixed) / (1 - w)``."""
1667
+ x = np.sort(raw)
1668
+ prob = special.ndtr(levels)
1669
+ if fixed is not None and fixed.size:
1670
+ w = fixed.size / (fixed.size + raw.size)
1671
+ taken = np.searchsorted(np.sort(fixed), levels, side="right") / fixed.size
1672
+ prob = np.maximum.accumulate(np.clip((prob - w * taken) / (1.0 - w), 0.0, 1.0))
1673
+ pos = prob * (x.size - 1)
1674
+ i0 = np.floor(pos).astype(np.int64)
1675
+ i1 = np.minimum(i0 + 1, x.size - 1)
1676
+ frac = pos - i0
1677
+ return _f32(_strictly_increasing_f32(x[i0] * (1.0 - frac) + x[i1] * frac))
1678
+
1679
+
1680
+ # ---------------------------------------------------------------------------------------------
1681
+ # Fitting one column
1682
+ # ---------------------------------------------------------------------------------------------
1683
+
1684
+ def _group_classes(count: np.ndarray, nominal: bool) -> np.ndarray:
1685
+ """Class of every atom for the split criterion: the atoms themselves when few; otherwise
1686
+ the most frequent ones plus "other" (nominal) or runs of adjacent atoms of about equal
1687
+ mass, atoms of at least a class's share on their own (ordinal)."""
1688
+ k = count.size
1689
+ if k <= MAX_CLASSES:
1690
+ return np.arange(k, dtype=np.int64)
1691
+ if nominal:
1692
+ out = np.full(k, MAX_CLASSES - 1, dtype=np.int64)
1693
+ top = np.argsort(-count, kind="stable")[:MAX_CLASSES - 1]
1694
+ out[top] = np.arange(MAX_CLASSES - 1)
1695
+ return out
1696
+ share = count / max(float(count.sum()), 1.0)
1697
+ out = np.zeros(k, dtype=np.int64)
1698
+ full = 1.0 / MAX_CLASSES
1699
+ cls, acc = 0, 0.0
1700
+ for a in range(k):
1701
+ alone = share[a] >= full
1702
+ if a and (alone or acc >= full) and cls < MAX_CLASSES - 1:
1703
+ cls, acc = cls + 1, 0.0
1704
+ out[a] = cls
1705
+ acc = full if alone else acc + share[a] # an atom on its own closes its class
1706
+ return out
1707
+
1708
+
1709
+ def _entropy(e: np.ndarray) -> float:
1710
+ """Entropy (nats) of residuals at a resolution of ``ENTROPY_STEP``: how many nats it takes
1711
+ to say where a row is. A sharper residual, or one piled on a ridge, takes fewer."""
1712
+ _, count = np.unique(np.floor(e / ENTROPY_STEP).astype(np.int64), return_counts=True)
1713
+ p = count / max(int(count.sum()), 1)
1714
+ return float(-(p * np.log(p)).sum())
1715
+
1716
+
1717
+ def _line_residual(zt: np.ndarray, scores: np.ndarray) -> np.ndarray | None:
1718
+ """Residual of ``zt`` from its trimmed line on the single most correlated score column:
1719
+ what is left of a column that mostly copies one other column (``None`` without one)."""
1720
+ sc, zc = scores - scores.mean(axis=0), zt - zt.mean()
1721
+ denom = np.sqrt((sc * sc).sum(axis=0) * float(zc @ zc))
1722
+ corr = np.where(denom > 0, np.abs(sc.T @ zc) / np.where(denom > 0, denom, 1.0), 0.0)
1723
+ if not corr.size or float(corr.max()) <= 0:
1724
+ return None
1725
+ s = scores[:, int(np.argmax(corr))]
1726
+ one = np.zeros(zt.size, dtype=np.int64)
1727
+ _, a, b, _ = _line_fit(one, 1, s, zt)
1728
+ a, b = _trim_lines(one, 1, s, zt, a, b, 2)
1729
+ return zt - a[0] * s - b[0]
1730
+
1731
+
1732
+ class _Fitted(NamedTuple):
1733
+ nodes: np.ndarray
1734
+ tree_offsets: np.ndarray
1735
+ dists: _Dists
1736
+ beta: np.ndarray
1737
+ ridges: _Ridges
1738
+
1739
+
1740
+ def _fit_column(j: int, preds: list[int], st: _State, cols: list[_Column], n_values: np.ndarray,
1741
+ policy: DisclosurePolicySpec, rng: np.random.Generator, *, n_trees: int,
1742
+ leaf_min: int, cell_min: int, max_depth: int, max_leaves: int,
1743
+ subsample: float, prune: float, lines: bool, linear: bool,
1744
+ leaf_blocks: int, values: Mapping[int, np.ndarray],
1745
+ max_predictors: int = 0, work: list[float] | None = None) -> _Fitted:
1746
+ col = cols[j]
1747
+ n, d = st.z.shape
1748
+ beta = np.zeros(d)
1749
+ ridges = _no_ridges()
1750
+ rows = np.flatnonzero(~st.missing[:, j])
1751
+ atom = st.atom[:, j].astype(np.int64)
1752
+ if rows.size < leaf_min: # nothing may be stored about them
1753
+ nodes, offsets, ds = _stack([_stump()], [_root_dists(col.kind)])
1754
+ return _Fitted(nodes, offsets, ds, beta, ridges)
1755
+ cand: list[int] = []
1756
+ n_cells = col.n_atoms
1757
+ if col.kind == KIND_CONTINUOUS:
1758
+ free = np.flatnonzero((atom < 0) & ~st.missing[:, j])
1759
+ ridges = _find_ridges(j, preds, st, values, free, cell_min)
1760
+ copy = ridges.which(special.ndtr(st.z[free, j]), st.score[free], st.missing[free])
1761
+ # cells: the atoms, "continuous", then one per ridge
1762
+ atom[free] = np.where(copy >= 0, col.n_atoms + 1 + copy, col.n_atoms)
1763
+ n_cells = col.n_atoms + 1 + ridges.n
1764
+ cont = free[copy < 0]
1765
+ zt = special.ndtri(np.clip(st.up[cont, j], 1e-12, 1.0 - 1e-12))
1766
+ value = np.full(n, np.nan)
1767
+ value[cont] = zt
1768
+ grow = zt # what the trees are grown on
1769
+ if preds and cont.size >= LINEAR_ROWS_PER_COEFFICIENT * len(preds):
1770
+ # the base: a linear one over all earlier columns, unless the column is better
1771
+ # described as following a single one (then its leaves get local lines instead)
1772
+ x = st.score[np.ix_(cont, np.asarray(preds, dtype=np.int64))]
1773
+ best = _entropy(zt) - BASE_GAIN
1774
+ single = _line_residual(zt, x) if lines else None
1775
+ if single is not None and _entropy(single) < best:
1776
+ best, grow = _entropy(single), single
1777
+ if linear:
1778
+ gram = x.T @ x + RIDGE * cont.size * np.eye(len(preds))
1779
+ coef = _f32(_coarsen(np.linalg.solve(gram, x.T @ zt), policy))
1780
+ e = zt - x @ coef
1781
+ if _entropy(e) < best:
1782
+ grow, value[cont] = e, e
1783
+ beta[preds] = coef
1784
+ if lines:
1785
+ cand = list(preds)
1786
+ # classes: the atoms, bins of the residual, the ridges
1787
+ cls = np.where(atom > col.n_atoms, atom + RESIDUAL_CLASSES - 1, atom)
1788
+ y, wy = np.zeros(n), np.zeros(n)
1789
+ if cont.size:
1790
+ cuts = np.quantile(grow, np.arange(1, RESIDUAL_CLASSES) / RESIDUAL_CLASSES)
1791
+ cls[cont] = col.n_atoms + np.searchsorted(cuts, grow, side="right")
1792
+ y[cont] = special.ndtri((stats.rankdata(grow) - 0.5) / grow.size)
1793
+ wy[cont] = 1.0
1794
+ target = _Target(cls, col.n_atoms + RESIDUAL_CLASSES + ridges.n, y, wy)
1795
+ leaf_min = max(leaf_min, int(leaf_blocks) * cell_min)
1796
+ else:
1797
+ value = st.z[:, j].copy()
1798
+ value[st.missing[:, j]] = np.nan
1799
+ groups = _group_classes(np.bincount(atom[rows], minlength=col.n_atoms),
1800
+ col.kind == KIND_NOMINAL)
1801
+ cls = groups[np.maximum(atom, 0)]
1802
+ if col.kind == KIND_ORDINAL:
1803
+ s = st.score[:, j]
1804
+ sd = float(s[rows].std())
1805
+ y = (s - s[rows].mean()) / (sd if sd > 0 else 1.0)
1806
+ target = _Target(cls, int(groups.max()) + 1, y, np.ones(n))
1807
+ else:
1808
+ target = _Target(cls, int(groups.max()) + 1, None, None)
1809
+ trees: list[_Tree] = []
1810
+ dists: list[_Dists] = []
1811
+ n_grow = int(round(subsample * rows.size))
1812
+ feats: list[int] | None = None
1813
+ for _ in range(n_trees):
1814
+ tree = _stump()
1815
+ perm = rng.permutation(rows.size)
1816
+ if preds and rows.size - n_grow >= 1 and n_grow >= 2 * leaf_min:
1817
+ grown, held = rows[np.sort(perm[:n_grow])], rows[np.sort(perm[n_grow:])]
1818
+ if feats is None: # the predictors the trees may use
1819
+ feats = _screen(st.bins, preds, n_values, rows, target, min_leaf=leaf_min,
1820
+ keep=max_predictors)
1821
+ if work is not None and len(feats) < len(preds): # a pass to choose them
1822
+ work[2] += float(len(preds)) * max(int(SCREEN_LEVELS), 1) * SCREEN_PASS * (
1823
+ min(rows.size, SCREEN_ROWS) + WORK_ROW_OVERHEAD)
1824
+ if work is not None: # predictor-rows offered to a tree
1825
+ work[1] += float(len(feats)) * (grown.size + WORK_ROW_OVERHEAD)
1826
+ work[3] += float(len(preds)) * (grown.size + WORK_ROW_OVERHEAD)
1827
+ tree = _grow(st.bins, feats, n_values, grown, target, min_leaf=leaf_min,
1828
+ max_depth=max_depth, work=work)
1829
+ tree = _prune(tree, st.bins, grown, held, target, penalty=prune,
1830
+ max_leaves=max_leaves)
1831
+ fitted, ds = _fit_dists(tree, st.bins, rows, col.kind, n_cells, atom, value, policy,
1832
+ cell_min, st.score, cand)
1833
+ trees.append(fitted)
1834
+ dists.append(ds)
1835
+ nodes, offsets, merged = _stack(trees, dists)
1836
+ return _Fitted(nodes, offsets, merged, beta, ridges)
1837
+
1838
+
1839
+ # ---------------------------------------------------------------------------------------------
1840
+ # The joint model
1841
+ # ---------------------------------------------------------------------------------------------
1842
+
1843
+ _DIST_FLOAT = ("rest", "line_slope", "cell_prob", "means", "sds")
1844
+ _DIST_INT = ("parent", "line_col", "cell_atom")
1845
+
1846
+
1847
+ @JOINTS.register()
1848
+ class ChainCopula(JointModel):
1849
+ kind = "chain_copula"
1850
+
1851
+ def __init__(self, columns: list[str], *, order: np.ndarray, col_kind: np.ndarray,
1852
+ col_parent: np.ndarray, col_indicator: np.ndarray, atom_shape: np.ndarray,
1853
+ atom_lower: np.ndarray, atom_upper: np.ndarray, nodes: np.ndarray,
1854
+ tree_offsets: np.ndarray, col_trees: np.ndarray, col_dists: np.ndarray,
1855
+ rest: np.ndarray, parent: np.ndarray, line_col: np.ndarray,
1856
+ line_slope: np.ndarray, cell_offsets: np.ndarray, cell_atom: np.ndarray,
1857
+ cell_prob: np.ndarray, mean_offsets: np.ndarray, means: np.ndarray,
1858
+ sds: np.ndarray, beta: np.ndarray, tilt: np.ndarray, grid: np.ndarray,
1859
+ ridge_offsets: np.ndarray, ridge_col: np.ndarray, ridge_lower: np.ndarray,
1860
+ ridge_upper: np.ndarray, n_bins: int = DEFAULT_BINS, grid_z: float = GRID_Z,
1861
+ info: dict[str, Any] | None = None) -> None:
1862
+ self.columns = list(columns)
1863
+ d = len(self.columns)
1864
+ self.n_bins = int(n_bins)
1865
+ self.grid_z = float(grid_z)
1866
+ self.info = dict(info or {})
1867
+ i64 = np.int64
1868
+
1869
+ def ints(a: np.ndarray) -> np.ndarray:
1870
+ return np.asarray(a, dtype=i64).ravel()
1871
+
1872
+ def floats(a: np.ndarray) -> np.ndarray:
1873
+ return _f32(np.asarray(a, dtype=np.float64).ravel())
1874
+
1875
+ self.order = ints(order)
1876
+ self.col_kind = ints(col_kind)
1877
+ self.col_parent = ints(col_parent)
1878
+ self.col_indicator = ints(col_indicator)
1879
+ self.atom_shape = np.asarray(atom_shape, dtype=i64).reshape(-1, 2)
1880
+ self.atom_lower, self.atom_upper = floats(atom_lower), floats(atom_upper)
1881
+ self.nodes = np.asarray(nodes, dtype=i64).reshape(-1, 4)
1882
+ self.tree_offsets = ints(tree_offsets)
1883
+ self.col_trees, self.col_dists = ints(col_trees), ints(col_dists)
1884
+ self.dists = _Dists(rest=floats(rest), parent=ints(parent), line_col=ints(line_col),
1885
+ line_slope=floats(line_slope), cell_offsets=ints(cell_offsets),
1886
+ cell_atom=ints(cell_atom), cell_prob=floats(cell_prob),
1887
+ mean_offsets=ints(mean_offsets), means=floats(means),
1888
+ sds=floats(sds))
1889
+ self.beta = _f32(np.asarray(beta, dtype=np.float64).reshape(d, d))
1890
+ self.ridge_offsets, self.ridge_col = ints(ridge_offsets), ints(ridge_col)
1891
+ n_ridges = max(int(self.ridge_col.size), 1)
1892
+ self.ridge_lower = _f32(np.asarray(ridge_lower, dtype=np.float64).reshape(n_ridges, -1)
1893
+ )[:self.ridge_col.size]
1894
+ self.ridge_upper = _f32(np.asarray(ridge_upper, dtype=np.float64).reshape(n_ridges, -1)
1895
+ )[:self.ridge_col.size]
1896
+ self.tilt = floats(tilt)
1897
+ self.grid = _f32(np.asarray(grid, dtype=np.float64).reshape(d, GRID_POINTS))
1898
+ self.grid_levels = np.linspace(-self.grid_z, self.grid_z, GRID_POINTS)
1899
+ self._validate()
1900
+ sizes = self.atom_shape[:, 0] * self.atom_shape[:, 1]
1901
+ self._atom_off = np.concatenate([[0], np.cumsum(sizes)]).astype(i64)
1902
+ self._cols = [self._column(j) for j in range(d)]
1903
+ self._tilt_off = np.concatenate([[0], np.cumsum([c.n_cells for c in self._cols])]
1904
+ ).astype(i64)
1905
+ if self.tilt.size != self._tilt_off[-1] or np.any(self.tilt <= 0) or not np.all(
1906
+ np.isfinite(self.tilt)):
1907
+ raise ValueError("chain tilt factors must be positive, one per cell")
1908
+ self._check_trees()
1909
+ self._runtime = [self._column_runtime(j) for j in range(d)]
1910
+
1911
+ # -- structure ----------------------------------------------------------------------------
1912
+ def _column(self, j: int) -> _Column:
1913
+ shape = (int(self.atom_shape[j, 0]), int(self.atom_shape[j, 1]))
1914
+ a, b = self._atom_off[j], self._atom_off[j + 1]
1915
+ return _Column(int(self.col_kind[j]), self.atom_lower[a:b].reshape(shape),
1916
+ self.atom_upper[a:b].reshape(shape), int(self.col_parent[j]),
1917
+ int(self.col_indicator[j]), self.n_bins)
1918
+
1919
+ def _column_dists(self, j: int) -> _Dists:
1920
+ a, b = int(self.col_dists[j]), int(self.col_dists[j + 1])
1921
+ ds = self.dists
1922
+ c0, c1 = int(ds.cell_offsets[a]), int(ds.cell_offsets[b])
1923
+ m0, m1 = int(ds.mean_offsets[a]), int(ds.mean_offsets[b])
1924
+ return _Dists(rest=ds.rest[a:b],
1925
+ parent=np.where(ds.parent[a:b] >= 0, ds.parent[a:b] - a, -1),
1926
+ line_col=ds.line_col[a:b], line_slope=ds.line_slope[a:b],
1927
+ cell_offsets=ds.cell_offsets[a:b + 1] - c0, cell_atom=ds.cell_atom[c0:c1],
1928
+ cell_prob=ds.cell_prob[c0:c1], mean_offsets=ds.mean_offsets[a:b + 1] - m0,
1929
+ means=ds.means[m0:m1], sds=ds.sds[m0:m1])
1930
+
1931
+ def _column_ridges(self, j: int) -> _Ridges:
1932
+ a, b = int(self.ridge_offsets[j]), int(self.ridge_offsets[j + 1])
1933
+ return _Ridges(self.ridge_col[a:b], _edge_u(self.ridge_lower[a:b]),
1934
+ _edge_u(self.ridge_upper[a:b]))
1935
+
1936
+ def _column_runtime(self, j: int) -> _Runtime:
1937
+ t0, t1 = int(self.col_trees[j]), int(self.col_trees[j + 1])
1938
+ n0 = int(self.tree_offsets[t0])
1939
+ nodes = self.nodes[n0:int(self.tree_offsets[t1])].copy()
1940
+ leaf = nodes[:, 0] < 0
1941
+ nodes[leaf, 2] -= int(self.col_dists[j])
1942
+ return _Runtime(j, self._cols[j], nodes, self.tree_offsets[t0:t1 + 1] - n0,
1943
+ self._column_dists(j), self.beta[j],
1944
+ self.tilt[self._tilt_off[j]:self._tilt_off[j + 1]], self.grid[j],
1945
+ self.grid_levels, self._column_ridges(j))
1946
+
1947
+ def _validate(self) -> None:
1948
+ d = len(self.columns)
1949
+ ds = self.dists
1950
+ n_rows = ds.n
1951
+ if sorted(self.order.tolist()) != list(range(d)):
1952
+ raise ValueError("chain order must be a permutation of the columns")
1953
+ for name, arr in (("kind", self.col_kind), ("parent", self.col_parent),
1954
+ ("indicator", self.col_indicator)):
1955
+ if arr.size != d:
1956
+ raise ValueError(f"chain column {name} array does not match the columns")
1957
+ if name != "kind" and np.any((arr < -1) | (arr >= d)):
1958
+ raise ValueError(f"chain {name} refers to an unknown column")
1959
+ if np.any((self.col_kind < 0) | (self.col_kind > 2)):
1960
+ raise ValueError("unknown chain column kind")
1961
+ rank = np.empty(d, dtype=np.int64)
1962
+ rank[self.order] = np.arange(d)
1963
+ for before in (self.col_parent, self.col_indicator):
1964
+ has = before >= 0
1965
+ if np.any(rank[before[has]] >= rank[np.flatnonzero(has)]):
1966
+ raise ValueError("a chain column must follow its parent and its indicator")
1967
+ self._rank = rank
1968
+ if not 2 <= self.n_bins <= MAX_BINS:
1969
+ raise ValueError(f"chain supports 2 to {MAX_BINS} bins")
1970
+ shape = self.atom_shape
1971
+ if shape.shape[0] != d or np.any(shape[:, 0] < 1) or np.any(shape[:, 1] < 0) \
1972
+ or self.atom_lower.size != int((shape[:, 0] * shape[:, 1]).sum()) \
1973
+ or self.atom_upper.size != self.atom_lower.size:
1974
+ raise ValueError("chain atom tables do not match their shapes")
1975
+ if not (np.all(np.isfinite(self.atom_lower)) and np.all(np.isfinite(self.atom_upper))
1976
+ and np.all(self.atom_upper >= self.atom_lower)):
1977
+ raise ValueError("chain atom intervals must be finite and ordered")
1978
+ atomic = self.col_kind != KIND_CONTINUOUS
1979
+ if np.any(shape[atomic, 1] < 1) or np.any(shape[atomic, 1] > MAX_ATOMS) or np.any(
1980
+ shape[~atomic, 1] > MAX_MAJOR) or np.any(shape[~atomic, 0] != 1):
1981
+ raise ValueError("chain atom count outside the supported range")
1982
+ has = self.col_parent >= 0
1983
+ if np.any(~atomic[has]) or np.any(~atomic[self.col_parent[has]]) or np.any(
1984
+ shape[has, 0] != shape[self.col_parent[has], 1] + 1) or np.any(
1985
+ shape[~has, 0] != 1):
1986
+ raise ValueError("chain conditional intervals do not match the parent's atoms")
1987
+ has = self.col_indicator >= 0
1988
+ if np.any(shape[self.col_indicator[has], 1] != 2) or np.any(
1989
+ ~atomic[self.col_indicator[has]]):
1990
+ raise ValueError("a chain missingness indicator must have two atoms")
1991
+ for name, off, size in (("tree", self.col_trees, self.tree_offsets.size - 1),
1992
+ ("distribution", self.col_dists, n_rows)):
1993
+ if off.size != d + 1 or off[0] != 0 or off[-1] != size or np.any(np.diff(off) < 1):
1994
+ raise ValueError(f"invalid chain {name} offsets")
1995
+ toff = self.tree_offsets
1996
+ if toff.size < 1 or toff[0] != 0 or toff[-1] != len(self.nodes) or np.any(
1997
+ np.diff(toff) < 1):
1998
+ raise ValueError("invalid chain tree offsets")
1999
+ for name, off, size in (("cell", ds.cell_offsets, ds.cell_atom.size),
2000
+ ("mean", ds.mean_offsets, ds.means.size)):
2001
+ if off.size != n_rows + 1 or off[0] != 0 or off[-1] != size or np.any(
2002
+ np.diff(off) < 0):
2003
+ raise ValueError(f"invalid chain {name} offsets")
2004
+ if not (ds.parent.size == ds.line_col.size == ds.line_slope.size == n_rows) \
2005
+ or ds.cell_prob.size != ds.cell_atom.size or ds.sds.size != ds.means.size:
2006
+ raise ValueError("chain distribution arrays do not match")
2007
+ if not all(np.all(np.isfinite(a)) for a in (ds.rest, ds.cell_prob, ds.means, ds.sds,
2008
+ ds.line_slope, self.beta, self.grid)):
2009
+ raise ValueError("chain arrays must be finite")
2010
+ if np.any(ds.rest < 0) or np.any(ds.rest > 1.0 + 1e-6) or np.any(ds.cell_prob <= 0) \
2011
+ or np.any(ds.cell_prob > 1.0 + 1e-6) or np.any(ds.sds <= 0):
2012
+ raise ValueError("chain shares must lie in (0, 1] and scales be positive")
2013
+ if np.any(np.diff(ds.mean_offsets) > MAX_BLOCKS):
2014
+ raise ValueError("chain distribution has too many blocks")
2015
+ if np.any(self.beta[rank[:, None] <= rank[None, :]] != 0) or np.any(
2016
+ self.beta[atomic] != 0):
2017
+ raise ValueError("a continuous chain column is regressed on earlier columns only")
2018
+ roff, rcol = self.ridge_offsets, self.ridge_col
2019
+ if roff.size != d + 1 or roff[0] != 0 or roff[-1] != rcol.size or np.any(
2020
+ np.diff(roff) < 0) or np.any(np.diff(roff) > MAX_RIDGES) or np.any(
2021
+ np.diff(roff)[atomic] > 0):
2022
+ raise ValueError("invalid chain ridge offsets")
2023
+ owner = np.repeat(np.arange(d), np.diff(roff))
2024
+ if np.any((rcol < 0) | (rcol >= d)) or np.any(rank[rcol] >= rank[owner]):
2025
+ raise ValueError("a chain ridge copies an earlier column")
2026
+ if self.ridge_lower.shape != self.ridge_upper.shape or (rcol.size and (
2027
+ self.ridge_lower.shape[1] < MIN_VALUE_LEVELS
2028
+ or not np.all(np.isfinite(self.ridge_lower))
2029
+ or not np.all(np.isfinite(self.ridge_upper))
2030
+ or np.any(self.ridge_upper < self.ridge_lower))):
2031
+ raise ValueError("chain ridge intervals must be finite and ordered")
2032
+ if self.grid.shape != (d, GRID_POINTS) or (d and not np.all(
2033
+ np.diff(self.grid, axis=1) > 0)):
2034
+ raise ValueError(f"chain grid must be strictly increasing with {GRID_POINTS} points "
2035
+ f"per column")
2036
+
2037
+ def _check_trees(self) -> None:
2038
+ ds = self.dists
2039
+ d = len(self.columns)
2040
+ n_values = np.array([c.n_values for c in self._cols], dtype=np.int64)
2041
+ seen = np.zeros(ds.n, dtype=np.int64)
2042
+ for j in range(d):
2043
+ col = self._cols[j]
2044
+ a, b = int(self.col_dists[j]), int(self.col_dists[j + 1])
2045
+ cells = ds.cell_atom[int(ds.cell_offsets[a]):int(ds.cell_offsets[b])]
2046
+ n_ridges = int(self.ridge_offsets[j + 1] - self.ridge_offsets[j])
2047
+ if np.any((cells < 0) | (cells >= col.n_cells + n_ridges)):
2048
+ raise ValueError("chain cell refers to an unknown atom")
2049
+ par = ds.parent[a:b]
2050
+ if np.any((par >= 0) & ((par < a) | (par >= a + np.arange(b - a)))):
2051
+ raise ValueError("a chain distribution's parent row must precede it")
2052
+ blocks = np.diff(ds.mean_offsets[a:b + 1])
2053
+ if col.kind == KIND_NOMINAL:
2054
+ if np.any(blocks != 0):
2055
+ raise ValueError("a nominal chain column stores no densities")
2056
+ elif col.kind == KIND_ORDINAL and (
2057
+ np.any(par >= 0) or np.any((blocks == 0) & (ds.rest[a:b] > 0))):
2058
+ raise ValueError("an ordinal chain rest needs a density of its own")
2059
+ along = ds.line_col[a:b]
2060
+ lined = along >= 0
2061
+ if np.any(along < -1) or np.any(along >= d) or (
2062
+ lined.any() and (col.kind != KIND_CONTINUOUS or np.any(
2063
+ self._rank[along[lined]] >= self._rank[j]))):
2064
+ raise ValueError("a chain line runs along an earlier column of a continuous "
2065
+ "column's leaf")
2066
+ for t in range(int(self.col_trees[j]), int(self.col_trees[j + 1])):
2067
+ nd = self.nodes[self.tree_offsets[t]:self.tree_offsets[t + 1]]
2068
+ f, thr, lft, rgt = nd[:, 0], nd[:, 1], nd[:, 2], nd[:, 3]
2069
+ m = f.size
2070
+ inner = f >= 0
2071
+ ids = np.arange(m)
2072
+ if np.any(f >= d) or np.any(f < -1):
2073
+ raise ValueError("chain split refers to an unknown column")
2074
+ fi = f[inner]
2075
+ if np.any(self._rank[fi] >= self._rank[j]):
2076
+ raise ValueError("a chain tree may only split on earlier columns")
2077
+ if np.any((thr[inner] < 0) | (thr[inner] >= n_values[fi] - 1)):
2078
+ raise ValueError("chain split threshold outside the bins")
2079
+ if np.any(inner & ((lft <= ids) | (rgt <= ids) | (lft >= m) | (rgt >= m))):
2080
+ raise ValueError("chain children must follow their parent within the tree")
2081
+ kids = np.concatenate([lft[inner], rgt[inner]])
2082
+ if kids.size != np.unique(kids).size or kids.size != m - 1:
2083
+ raise ValueError("chain tree is not a binary tree")
2084
+ rows = lft[~inner]
2085
+ if np.any((rows < a) | (rows >= b)):
2086
+ raise ValueError("chain leaf refers to a distribution of another column")
2087
+ if col.kind == KIND_CONTINUOUS and np.any(blocks[rows - a] == 0):
2088
+ raise ValueError("a continuous chain leaf needs a density")
2089
+ np.add.at(seen, rows, 1)
2090
+ if np.any(seen > 1):
2091
+ raise ValueError("every chain distribution belongs to at most one leaf")
2092
+
2093
+ @property
2094
+ def n_trees(self) -> int:
2095
+ return int(self.tree_offsets.size - 1)
2096
+
2097
+ @property
2098
+ def n_leaves(self) -> int:
2099
+ return int(np.sum(self.nodes[:, 0] < 0))
2100
+
2101
+ @property
2102
+ def n_parameters(self) -> int:
2103
+ ds = self.dists
2104
+ n_inner = int(np.sum(self.nodes[:, 0] >= 0))
2105
+ return int(2 * n_inner + ds.n + 2 * ds.cell_atom.size + 2 * ds.means.size
2106
+ + 2 * int(np.sum(ds.line_col >= 0)) + np.count_nonzero(self.beta)
2107
+ + self.tilt.size + self.grid.size + self.ridge_col.size)
2108
+
2109
+ def split_counts(self) -> dict[str, int]:
2110
+ """Number of splits on each latent column, by column name."""
2111
+ f = self.nodes[:, 0]
2112
+ counts = np.bincount(f[f >= 0], minlength=len(self.columns))
2113
+ return {c: int(k) for c, k in zip(self.columns, counts)}
2114
+
2115
+ def leaf_rows(self, z: np.ndarray) -> list[tuple[np.ndarray, np.ndarray]]:
2116
+ """For every column, the distribution rows the latent scores ``z`` fall into (one array
2117
+ per tree, ``-1`` where the column is missing) and the cell of every score (an atom;
2118
+ for a continuous column the atoms, then "continuous", then its ridges; ``-1`` where
2119
+ missing): what a leaf was fitted on, for audits of the leaf and cell minimums."""
2120
+ z = _check_z(z, self.columns)
2121
+ st = _encode(z, self._cols, [int(j) for j in self.order])
2122
+ u = special.ndtr(st.z)
2123
+ out = []
2124
+ for j in range(len(self.columns)):
2125
+ rt = self._runtime[j]
2126
+ leaves = np.stack([tree[2][_route(tree, st.bins)] for tree in rt.trees])
2127
+ leaves = np.where(st.missing[:, j][None, :], -1, leaves)
2128
+ cell = st.atom[:, j].astype(np.int64)
2129
+ if rt.col.kind == KIND_CONTINUOUS:
2130
+ copy = rt.ridges.which(u[:, j], st.z, st.missing)
2131
+ cell = np.where(cell >= 0, cell, rt.col.n_atoms + 1 + copy)
2132
+ out.append((leaves, np.where(st.missing[:, j], -1, cell)))
2133
+ return out
2134
+
2135
+ # -- fitting ------------------------------------------------------------------------------
2136
+ @classmethod
2137
+ def fit(cls, z: np.ndarray, columns: list[str], *, policy: DisclosurePolicySpec,
2138
+ rng: np.random.Generator | None = None, atoms: Mapping[str, Any] | None = None,
2139
+ n_trees: int = DEFAULT_TREES, n_bins: int = DEFAULT_BINS,
2140
+ max_depth: int = DEFAULT_MAX_DEPTH, max_leaves: int = DEFAULT_MAX_LEAVES,
2141
+ min_samples_leaf: int | None = None, subsample: float = DEFAULT_SUBSAMPLE,
2142
+ prune: float = DEFAULT_PRUNE, lines: bool = True, linear: bool = True,
2143
+ leaf_blocks: int = CONTINUOUS_LEAF_BLOCKS,
2144
+ values: Mapping[str, Any] | None = None,
2145
+ order: Sequence[str] | None = None, max_rows: int = MAX_FIT_ROWS,
2146
+ max_predictors: int | None = None,
2147
+ work_budget: float | None = DEFAULT_WORK_BUDGET,
2148
+ **kwargs: Any) -> ChainCopula:
2149
+ """Fit the chain to latent normal scores (see the module doc).
2150
+
2151
+ ``atoms`` maps latent column names to their tied-value intervals
2152
+ (``MixedEncoder.latent_atoms``); columns absent from it, and every column without it,
2153
+ are continuous. ``values`` maps numeric latent column names to their quantile functions
2154
+ at evenly spaced latent levels (``MixedEncoder.latent_values``); with them, rows of a
2155
+ continuous column that copy an earlier column are modelled as copies.
2156
+ ``min_samples_leaf`` may only raise the policy's leaf minimum
2157
+ ``max(min_category_support, rare_cell_min, 5)``; a continuous column's leaves hold
2158
+ ``leaf_blocks`` times the cell minimum. ``prune`` is the log-likelihood a split must
2159
+ gain on the held-out rows (negative keeps more splits). ``lines=False`` and
2160
+ ``linear=False`` take the local lines and the linear base away from the continuous
2161
+ columns. ``order`` overrides the generation order (column names; prerequisites are
2162
+ still honoured).
2163
+
2164
+ ``work_budget`` keeps the fit of a wide or tall table from taking long by surprise.
2165
+ The fit counts the passes its tree growing makes. Before each column it works out,
2166
+ from the levels its trees have taken so far, what the columns still to come would
2167
+ cost; when that exceeds what is left of the budget, their trees split only on the
2168
+ earlier columns whose best single split gains most (:func:`_screen`), as many as fit
2169
+ and at least ``MIN_PREDICTORS`` (the linear base, the local lines and the copies
2170
+ still see every earlier column). Only when even that could not fit are fewer rows
2171
+ used (:func:`plan_work`). ``work_budget=None`` fits in full. ``max_predictors`` sets
2172
+ the number of predictors per column yourself (0: no limit) and ``max_rows`` the most
2173
+ rows the chain is fitted on; with ``max_predictors`` given the budget is not
2174
+ applied. What was done is in the spec (``params``: ``work_budget``, ``tree_work``
2175
+ and ``screen_work`` (the passes made growing trees and choosing predictors),
2176
+ ``unlimited_work`` (what the fit would have taken in full, at the levels its trees
2177
+ took), ``max_predictors`` (the fewest any column got; 0: none was limited),
2178
+ ``limited_columns``, ``fit_rows``, ``source_rows``). Other
2179
+ keywords (the Gaussian copula's ``attenuation`` / ``hermite``)
2180
+ are accepted and ignored.
2181
+ """
2182
+ z = _check_z(z, columns)
2183
+ columns = list(columns)
2184
+ rng = rng if rng is not None else np.random.default_rng(0)
2185
+ n_trees, n_bins, max_depth = int(n_trees), int(n_bins), int(max_depth)
2186
+ if n_trees < 1 or not 2 <= n_bins <= MAX_BINS or max_depth < 0 or int(max_leaves) < 1:
2187
+ raise ValueError(f"chain needs n_trees >= 1, 2 <= n_bins <= {MAX_BINS}, "
2188
+ f"max_depth >= 0 and max_leaves >= 1")
2189
+ if not 0.0 < float(subsample) < 1.0:
2190
+ raise ValueError("subsample must lie strictly between 0 and 1")
2191
+ if (max_predictors is not None and int(max_predictors) < 0) or int(max_rows) < 1 \
2192
+ or (work_budget is not None and float(work_budget) < 0):
2193
+ raise ValueError("chain needs max_predictors >= 0, max_rows >= 1 and "
2194
+ "work_budget >= 0")
2195
+ n, d = z.shape
2196
+ source_rows = int(n)
2197
+ budget = float(work_budget or 0.0) if max_predictors is None else 0.0
2198
+ if max_predictors is None:
2199
+ fixed_k = 0
2200
+ max_rows = int(plan_work(n, d, budget, max_rows=int(max_rows),
2201
+ subsample=float(subsample), n_trees=n_trees)["fit_rows"])
2202
+ else:
2203
+ fixed_k = int(max_predictors) if int(max_predictors) < d - 1 else 0
2204
+ cell_min = max(leaf_min_for(policy), int(policy.rare_cell_min))
2205
+ leaf_min = max(cell_min, int(min_samples_leaf or 0))
2206
+ if n > max_rows:
2207
+ z = z[np.sort(rng.choice(n, int(max_rows), replace=False))]
2208
+ n = z.shape[0]
2209
+ kind, parent, indicator, lower, upper = _layout(columns, atoms)
2210
+ cols = [_Column(int(kind[j]), lower[j], upper[j], int(parent[j]), int(indicator[j]),
2211
+ n_bins) for j in range(d)]
2212
+ info: dict[str, Any] = {"n_trees": n_trees, "max_depth": max_depth,
2213
+ "max_leaves": int(max_leaves), "leaf_min": leaf_min,
2214
+ "cell_min": cell_min, "subsample": float(subsample),
2215
+ "prune": float(prune), "lines": bool(lines),
2216
+ "linear": bool(linear), "leaf_blocks": int(leaf_blocks),
2217
+ "fit_rows": int(n), "source_rows": source_rows,
2218
+ "work_budget": budget}
2219
+ # indicators and parents first, so that every row can be put in model coordinates
2220
+ st = _encode(z, cols, _topological(cols))
2221
+ chain = _named_order(columns, order, cols) if order is not None else chain_order(
2222
+ cols, st.score)
2223
+ n_values = np.array([c.n_values for c in cols], dtype=np.int64)
2224
+ tables = _value_tables(columns, values)
2225
+ levels = np.linspace(-GRID_Z, GRID_Z, GRID_POINTS)
2226
+ cal = _State(GRID_SAMPLE, d)
2227
+ fitted: list[_Fitted | None] = [None] * d
2228
+ tilts: list[np.ndarray] = [np.ones(0)] * d
2229
+ grid = np.tile(_f32(levels), (d, 1))
2230
+ # the work budget: [passes made growing trees, predictor-rows offered to them, passes
2231
+ # made choosing predictors, predictor-rows a fit in full would have offered]. The
2232
+ # ratio of the first two is the levels a tree of this fit searches, and prices the
2233
+ # columns still to come, each on the rows it has
2234
+ work = [0.0, 0.0, 0.0, 0.0]
2235
+ prior = MIN_PREDICTORS * (float(subsample) * n + WORK_ROW_OVERHEAD)
2236
+ present = (~st.missing).sum(axis=0)[np.asarray(chain, dtype=np.int64)]
2237
+ grown_rows = np.round(float(subsample) * present)
2238
+ col_rows = np.where((present - grown_rows >= 1) & (grown_rows >= 2 * leaf_min),
2239
+ present, 0)
2240
+ limits: list[int] = []
2241
+ for step, j in enumerate(chain):
2242
+ k = fixed_k
2243
+ if budget:
2244
+ took = (work[0] + WORK_LEVELS * prior) / (work[1] + prior)
2245
+ k = affordable_predictors(budget - work[0] - work[2], col_rows, d, step,
2246
+ levels=took, subsample=float(subsample),
2247
+ n_trees=n_trees)
2248
+ if k and step > k:
2249
+ limits.append(k)
2250
+ fit = _fit_column(j, chain[:step], st, cols, n_values, policy, rng,
2251
+ n_trees=n_trees, leaf_min=leaf_min, cell_min=cell_min,
2252
+ max_depth=max_depth, max_leaves=int(max_leaves),
2253
+ subsample=float(subsample), prune=float(prune), lines=lines,
2254
+ linear=linear, leaf_blocks=int(leaf_blocks), values=tables,
2255
+ max_predictors=k, work=work)
2256
+ rt = _Runtime(j, cols[j], fit.nodes, fit.tree_offsets, fit.dists, fit.beta,
2257
+ np.ones(cols[j].n_cells), grid[j], levels, fit.ridges)
2258
+ _draw(rt, cal, rng.random((4, GRID_SAMPLE)), calibrate=True)
2259
+ fitted[j], tilts[j], grid[j] = fit, _f32(rt.tilt), rt.grid
2260
+ took = work[0] / work[1] if work[1] > 0 else WORK_LEVELS
2261
+ info.update({
2262
+ "tree_work": float(work[0]), "screen_work": float(work[2]),
2263
+ "unlimited_work": float(work[0] if not limits else took * work[3]),
2264
+ "max_predictors": int(min(limits)) if limits else 0,
2265
+ "limited_columns": len(limits)})
2266
+ return cls._assemble(columns, chain, cols, lower, upper, fitted, tilts, grid, n_bins,
2267
+ info)
2268
+
2269
+ @classmethod
2270
+ def _assemble(cls, columns: list[str], chain: list[int], cols: list[_Column],
2271
+ lower: list[np.ndarray], upper: list[np.ndarray],
2272
+ fitted: list[_Fitted | None], tilts: list[np.ndarray], grid: np.ndarray,
2273
+ n_bins: int, info: dict[str, Any]) -> ChainCopula:
2274
+ d = len(columns)
2275
+ nodes, tree_sizes, col_trees, col_dists = [], [], [0], [0]
2276
+ parts: list[_Dists] = []
2277
+ row0 = cell0 = mean0 = 0
2278
+ for j in range(d):
2279
+ fit = fitted[j]
2280
+ assert fit is not None
2281
+ nd = fit.nodes.copy()
2282
+ leaf = nd[:, 0] < 0
2283
+ nd[leaf, 2] += row0
2284
+ nodes.append(nd)
2285
+ tree_sizes.extend(np.diff(fit.tree_offsets).tolist())
2286
+ ds = fit.dists
2287
+ parts.append(ds._replace(parent=np.where(ds.parent >= 0, ds.parent + row0, -1),
2288
+ cell_offsets=ds.cell_offsets[:-1] + cell0,
2289
+ mean_offsets=ds.mean_offsets[:-1] + mean0))
2290
+ row0 += ds.n
2291
+ cell0 += int(ds.cell_offsets[-1])
2292
+ mean0 += int(ds.mean_offsets[-1])
2293
+ col_trees.append(len(tree_sizes))
2294
+ col_dists.append(row0)
2295
+ merged = {f: (np.concatenate([getattr(p, f) for p in parts]) if parts else np.zeros(0))
2296
+ for f in _Dists._fields}
2297
+ merged["cell_offsets"] = np.append(merged["cell_offsets"], cell0)
2298
+ merged["mean_offsets"] = np.append(merged["mean_offsets"], mean0)
2299
+ flat = [np.zeros(0)]
2300
+ ridges = [f.ridges for f in fitted if f is not None and f.ridges.n]
2301
+ ridge_off = np.concatenate([[0], np.cumsum([f.ridges.n if f is not None else 0
2302
+ for f in fitted])]).astype(np.int64)
2303
+ return cls(
2304
+ columns, order=np.array(chain, dtype=np.int64),
2305
+ col_kind=np.array([c.kind for c in cols], dtype=np.int64),
2306
+ col_parent=np.array([c.parent for c in cols], dtype=np.int64),
2307
+ col_indicator=np.array([c.indicator for c in cols], dtype=np.int64),
2308
+ atom_shape=np.array([lo.shape for lo in lower], dtype=np.int64).reshape(d, 2),
2309
+ atom_lower=np.concatenate(flat + [a.ravel() for a in lower]),
2310
+ atom_upper=np.concatenate(flat + [a.ravel() for a in upper]),
2311
+ nodes=np.vstack(nodes) if nodes else np.zeros((0, 4), dtype=np.int64),
2312
+ tree_offsets=np.concatenate([[0], np.cumsum(tree_sizes)]).astype(np.int64),
2313
+ col_trees=np.array(col_trees, dtype=np.int64),
2314
+ col_dists=np.array(col_dists, dtype=np.int64),
2315
+ beta=np.vstack([f.beta for f in fitted]) if d else np.zeros((0, 0)), # type: ignore[union-attr]
2316
+ tilt=np.concatenate(flat + tilts), grid=grid, n_bins=n_bins,
2317
+ ridge_offsets=ridge_off,
2318
+ ridge_col=np.concatenate([np.zeros(0, dtype=np.int64)] + [r.cols for r in ridges]),
2319
+ ridge_lower=_edge_z(np.vstack([r.lower for r in ridges])) if ridges else np.zeros(0),
2320
+ ridge_upper=_edge_z(np.vstack([r.upper for r in ridges])) if ridges else np.zeros(0),
2321
+ info={**info, "order": [columns[j] for j in chain],
2322
+ "n_leaves": int(sum(int(np.sum(nd[:, 0] < 0)) for nd in nodes))},
2323
+ **merged) # type: ignore[arg-type]
2324
+
2325
+ # -- sampling -----------------------------------------------------------------------------
2326
+ def sample(self, n: int, rng: np.random.Generator) -> np.ndarray:
2327
+ d = len(self.columns)
2328
+ n = int(n)
2329
+ if not d or not n:
2330
+ return np.zeros((n, d))
2331
+ st = _State(n, d)
2332
+ for j in self.order:
2333
+ _draw(self._runtime[j], st, rng.random((4, n)))
2334
+ return st.z
2335
+
2336
+ # -- serialisation ------------------------------------------------------------------------
2337
+ _INT_ARRAYS = ("order", "col_kind", "col_parent", "col_indicator", "atom_shape", "nodes",
2338
+ "tree_offsets", "col_trees", "col_dists", "ridge_offsets", "ridge_col")
2339
+ _FLOAT_ARRAYS = ("atom_lower", "atom_upper", "beta", "tilt", "grid", "ridge_lower",
2340
+ "ridge_upper")
2341
+
2342
+ def to_spec(self, store: ArrayStore, prefix: str) -> ModelSpec:
2343
+ def put(name: str, a: np.ndarray, dtype: type) -> str:
2344
+ return store.put(f"{prefix}{name}", np.ascontiguousarray(a, dtype=dtype))
2345
+
2346
+ ds = self.dists
2347
+ arrays = {name: put(name, getattr(self, name), np.int32) for name in self._INT_ARRAYS}
2348
+ arrays.update({name: put(name, getattr(self, name), np.float32)
2349
+ for name in self._FLOAT_ARRAYS})
2350
+ arrays.update({name: put(name, getattr(ds, name), np.int32)
2351
+ for name in (*_DIST_INT, "cell_offsets", "mean_offsets")})
2352
+ arrays.update({name: put(name, getattr(ds, name), np.float32) for name in _DIST_FLOAT})
2353
+ params: dict[str, Any] = {"columns": list(self.columns), "n_bins": self.n_bins,
2354
+ "grid_z": self.grid_z, "grid_points": GRID_POINTS,
2355
+ **self.info}
2356
+ return ModelSpec(kind=self.kind, params=params, arrays=arrays)
2357
+
2358
+ @classmethod
2359
+ def from_spec(cls, spec: ModelSpec, store: ArrayStore) -> ChainCopula:
2360
+ p = spec.params
2361
+ cols = [str(c) for c in p.get("columns", [])] # type: ignore[union-attr]
2362
+ if int(p.get("grid_points", GRID_POINTS)) != GRID_POINTS: # type: ignore[arg-type]
2363
+ raise ValueError("unsupported chain grid size")
2364
+ names = (*cls._INT_ARRAYS, *cls._FLOAT_ARRAYS, *_DIST_INT, *_DIST_FLOAT,
2365
+ "cell_offsets", "mean_offsets")
2366
+ arrays = {name: np.asarray(store.get(spec.arrays[name])) for name in names}
2367
+ info = {k: v for k, v in p.items()
2368
+ if k not in ("columns", "n_bins", "grid_z", "grid_points")}
2369
+ return cls(cols, n_bins=int(p.get("n_bins", DEFAULT_BINS)), # type: ignore[arg-type]
2370
+ grid_z=float(p.get("grid_z", GRID_Z)), info=info, # type: ignore[arg-type]
2371
+ **arrays) # type: ignore[arg-type]
2372
+
2373
+
2374
+ def _value_tables(columns: list[str], values: Mapping[str, Any] | None
2375
+ ) -> dict[int, np.ndarray]:
2376
+ """Usable quantile-function tables by column index: finite, non-decreasing, and all of the
2377
+ length of the first one (they are compared level by level)."""
2378
+ out: dict[int, np.ndarray] = {}
2379
+ size = 0
2380
+ for j, name in enumerate(columns):
2381
+ table = (values or {}).get(name)
2382
+ if table is None:
2383
+ continue
2384
+ v = np.asarray(table, dtype=np.float64).ravel()
2385
+ if v.size < MIN_VALUE_LEVELS or not np.all(np.isfinite(v)) or np.any(np.diff(v) < 0):
2386
+ continue
2387
+ size = size or v.size
2388
+ if v.size == size:
2389
+ out[j] = v
2390
+ return out
2391
+
2392
+
2393
+ def _topological(cols: list[_Column]) -> list[int]:
2394
+ """Columns with every indicator and parent before the column that needs it."""
2395
+ d = len(cols)
2396
+ done = np.zeros(d, dtype=bool)
2397
+ out: list[int] = []
2398
+ while len(out) < d:
2399
+ free = [j for j in range(d) if not done[j]
2400
+ and all(done[p] for p in (cols[j].indicator, cols[j].parent) if p >= 0)]
2401
+ if not free:
2402
+ free = [j for j in range(d) if not done[j]]
2403
+ for j in free:
2404
+ done[j] = True
2405
+ out.extend(free)
2406
+ return out
2407
+
2408
+
2409
+ def _named_order(columns: list[str], order: Sequence[str], cols: list[_Column]) -> list[int]:
2410
+ """A caller's order, with every column moved behind its indicator and parent."""
2411
+ index = {c: j for j, c in enumerate(columns)}
2412
+ if sorted(order) != sorted(columns):
2413
+ raise ValueError("order must list every latent column exactly once")
2414
+ out: list[int] = []
2415
+
2416
+ def place(j: int) -> None:
2417
+ if j in out:
2418
+ return
2419
+ for p in (cols[j].indicator, cols[j].parent):
2420
+ if p >= 0:
2421
+ place(p)
2422
+ out.append(j)
2423
+
2424
+ for name in order:
2425
+ place(index[name])
2426
+ return out