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.
- ectype/__init__.py +134 -0
- ectype/_version.py +5 -0
- ectype/authoring/__init__.py +13 -0
- ectype/authoring/builder.py +134 -0
- ectype/authoring/spec.py +555 -0
- ectype/calibration/__init__.py +26 -0
- ectype/calibration/adjustments.py +539 -0
- ectype/calibration/calibrator.py +781 -0
- ectype/cli.py +1181 -0
- ectype/compiler/__init__.py +1 -0
- ectype/compiler/plan.py +678 -0
- ectype/errors.py +43 -0
- ectype/fingerprint/__init__.py +1 -0
- ectype/fingerprint/comparison.py +746 -0
- ectype/fingerprint/container.py +408 -0
- ectype/fingerprint/core.py +263 -0
- ectype/fingerprint/disclosure.py +207 -0
- ectype/fingerprint/expressions.py +1317 -0
- ectype/fingerprint/schema.py +645 -0
- ectype/fingerprint/targets.py +352 -0
- ectype/generation/__init__.py +1 -0
- ectype/generation/enforce.py +163 -0
- ectype/generation/generator.py +525 -0
- ectype/generation/identifiers.py +235 -0
- ectype/generation/manifest.py +71 -0
- ectype/generation/parallel.py +229 -0
- ectype/io/__init__.py +16 -0
- ectype/io/adapters.py +224 -0
- ectype/io/sql.py +289 -0
- ectype/io/values.py +269 -0
- ectype/llm/__init__.py +27 -0
- ectype/llm/authoring.py +766 -0
- ectype/llm/providers.py +269 -0
- ectype/models/__init__.py +8 -0
- ectype/models/base.py +120 -0
- ectype/models/chain.py +2426 -0
- ectype/models/copulas.py +254 -0
- ectype/models/encoding.py +1117 -0
- ectype/models/forest.py +1087 -0
- ectype/models/marginals.py +2099 -0
- ectype/models/mixtures.py +336 -0
- ectype/models/neural/__init__.py +21 -0
- ectype/models/neural/adapter.py +638 -0
- ectype/models/neural/vae.py +432 -0
- ectype/models/vines.py +608 -0
- ectype/plugins.py +40 -0
- ectype/privacy/__init__.py +49 -0
- ectype/privacy/attacks.py +599 -0
- ectype/privacy/dp.py +313 -0
- ectype/privacy/report.py +364 -0
- ectype/profiler.py +783 -0
- ectype/profiling/__init__.py +1 -0
- ectype/profiling/bivariate.py +130 -0
- ectype/profiling/calendar.py +743 -0
- ectype/profiling/conditional.py +263 -0
- ectype/profiling/constraints.py +661 -0
- ectype/profiling/entity.py +1143 -0
- ectype/profiling/functional.py +651 -0
- ectype/profiling/multivariate.py +492 -0
- ectype/profiling/personal.py +277 -0
- ectype/profiling/pseudonym.py +370 -0
- ectype/profiling/reference.py +334 -0
- ectype/profiling/sketches.py +653 -0
- ectype/profiling/structural.py +1087 -0
- ectype/profiling/structure.py +1733 -0
- ectype/profiling/sums.py +1710 -0
- ectype/profiling/tolerance.py +435 -0
- ectype/profiling/univariate.py +555 -0
- ectype/py.typed +0 -0
- ectype/registry.py +48 -0
- ectype/relational/__init__.py +61 -0
- ectype/relational/container.py +212 -0
- ectype/relational/fit.py +633 -0
- ectype/relational/generate.py +418 -0
- ectype/relational/schema.py +280 -0
- ectype/relational/validate.py +288 -0
- ectype/reporting/__init__.py +439 -0
- ectype/reporting/adapter.py +2003 -0
- ectype/reporting/charts.py +964 -0
- ectype/reporting/drift.py +902 -0
- ectype/reporting/findings.py +622 -0
- ectype/reporting/fmt.py +429 -0
- ectype/reporting/render.py +1705 -0
- ectype/reporting/select.py +84 -0
- ectype/reporting/style.py +272 -0
- ectype/reporting/view.py +593 -0
- ectype/rng.py +33 -0
- ectype/scenarios/__init__.py +30 -0
- ectype/scenarios/feasibility.py +411 -0
- ectype/scenarios/merge.py +1392 -0
- ectype/scenarios/mutate.py +1613 -0
- ectype/temporal/__init__.py +80 -0
- ectype/temporal/contract.py +221 -0
- ectype/temporal/detect.py +431 -0
- ectype/temporal/events.py +946 -0
- ectype/temporal/panel.py +937 -0
- ectype/temporal/pipeline.py +192 -0
- ectype/temporal/regular.py +674 -0
- ectype/types.py +46 -0
- ectype/validation/__init__.py +1 -0
- ectype/validation/metrics/__init__.py +7 -0
- ectype/validation/metrics/base.py +68 -0
- ectype/validation/metrics/bivariate.py +353 -0
- ectype/validation/metrics/missingness.py +54 -0
- ectype/validation/metrics/multivariate.py +265 -0
- ectype/validation/metrics/temporal.py +596 -0
- ectype/validation/metrics/univariate.py +514 -0
- ectype/validation/report.py +627 -0
- ectype/validation/validator.py +707 -0
- ectype_data-0.1.0.dist-info/METADATA +376 -0
- ectype_data-0.1.0.dist-info/RECORD +115 -0
- ectype_data-0.1.0.dist-info/WHEEL +4 -0
- ectype_data-0.1.0.dist-info/entry_points.txt +2 -0
- ectype_data-0.1.0.dist-info/licenses/LICENSE +192 -0
- ectype_data-0.1.0.dist-info/licenses/NOTICE +5 -0
|
@@ -0,0 +1,1117 @@
|
|
|
1
|
+
"""Mixed-type encoding between table columns and a latent standard-normal space (§3.9).
|
|
2
|
+
|
|
3
|
+
``MixedEncoder`` maps every modelled column to one latent normal score and adds one latent
|
|
4
|
+
missingness indicator per column with nulls:
|
|
5
|
+
|
|
6
|
+
* **continuous / datetime** -- ``u = F(x)`` (clipped to ``[eps, 1 - eps]``), ``z = Phi^-1(u)``;
|
|
7
|
+
spec kind ``"pit"``.
|
|
8
|
+
* **discrete** -- randomized PIT ``u ~ Uniform(F(x-), F(x))``; spec kind ``"randomized_pit"``.
|
|
9
|
+
Decoding is ``ppf(Phi(z))``.
|
|
10
|
+
* **categorical / boolean** -- frequency-interval encoding, i.e. a randomized PIT over the
|
|
11
|
+
category codes laid out in a recorded order (``category_order``). Each category owns an
|
|
12
|
+
interval of ``[0, 1]`` proportional to its marginal probability; ``u`` is uniform within it.
|
|
13
|
+
Decoding is interval lookup. Spec kind ``"frequency_interval"``. The order is data-informed
|
|
14
|
+
by default (see :func:`order_categories_by`); the categorical marginal itself is not changed,
|
|
15
|
+
the encoder keeps its own interval table built from the marginal's labels and probabilities.
|
|
16
|
+
* **conditional categoricals (M17, default)** -- a single latent per nominal column cannot
|
|
17
|
+
carry an arbitrary contingency table, so :meth:`MixedEncoder.fit` (``conditional=True``)
|
|
18
|
+
learns a Chow-Liu forest over the categorical/boolean columns
|
|
19
|
+
(:mod:`ectype.profiling.conditional`) and stores ``P(child | parent)`` for every
|
|
20
|
+
non-root column. A child is then encoded by a randomized PIT within the *conditional*
|
|
21
|
+
interval of its value given the observed parent value (same data-informed category order as
|
|
22
|
+
the marginal intervals; rows with a null parent use the marginal intervals). The copula is
|
|
23
|
+
fitted on these conditional scores, so it carries only the residual dependence (mostly with
|
|
24
|
+
numerics). Decoding runs in tree order (parents first) and maps ``Phi(z_child)`` through the
|
|
25
|
+
conditional intervals of the *decoded* parent value (marginal intervals when it is null).
|
|
26
|
+
This is a Rosenblatt-style conditional decode. Roots and columns outside the forest keep
|
|
27
|
+
marginal intervals. The table lives in the child's own ``"frequency_interval"`` spec:
|
|
28
|
+
``params["conditional"] = {"kind": "cpt_tree", "parent": ..., ...}`` and
|
|
29
|
+
``arrays = {"cpt", "cpt_parent_labels", "cpt_child_labels"}`` (see :meth:`to_specs`), so the
|
|
30
|
+
tree is the union of the children's parent links and travels with the encodings.
|
|
31
|
+
* **missingness** -- for each column with ``null_fraction > 0`` (or nulls seen at fit time) a
|
|
32
|
+
latent ``"__missing__<col>"`` column holds a Bernoulli(rate) indicator, encoded by randomized
|
|
33
|
+
PIT with "observed" on ``[0, 1 - rate)`` and "missing" on ``[1 - rate, 1)``. Decoding sets the
|
|
34
|
+
value to null where ``z_ind > Phi^-1(1 - rate)``. Spec kind ``"bernoulli_indicator"`` with the
|
|
35
|
+
policy-coarsened ``rate``.
|
|
36
|
+
|
|
37
|
+
**Imputation note:** when a value is missing its own latent score carries no information, so
|
|
38
|
+
``encode`` imputes it with an independent ``N(0, 1)`` draw. This keeps the latent matrix
|
|
39
|
+
complete for the joint fit but slightly attenuates the correlations that involve columns
|
|
40
|
+
with missing values (by roughly the observed fraction). The value itself is modelled on
|
|
41
|
+
observed rows only, per the marginal contract.
|
|
42
|
+
|
|
43
|
+
**Attenuation.** Jittering inside a CDF jump (and imputing missing scores) makes the latent
|
|
44
|
+
score ``z'`` noisier than the underlying Gaussian score ``z``. Under joint normality,
|
|
45
|
+
``corr(w, z') = rho * a`` with ``a = (1 - missing_rate) * Var(E[z | value])``, where
|
|
46
|
+
``E[z | value]`` is the truncated-normal mean over the value's interval (``a = 1`` for
|
|
47
|
+
continuous columns). :attr:`MixedEncoder.latent_attenuation` gives ``a`` per latent column;
|
|
48
|
+
``GaussianCopula.fit(..., attenuation=...)`` divides pairwise correlations by ``a_i * a_j``
|
|
49
|
+
(a polyserial-style correction), so decoded associations match the source instead of being
|
|
50
|
+
attenuated. The factors are stored (coarsened) in the specs. For a conditionally encoded
|
|
51
|
+
child ``a`` is recomputed from the conditional intervals actually used for each observed row,
|
|
52
|
+
``a = mean(E[z | interval]^2)``. This treats the conditional score as the Gaussian score of a
|
|
53
|
+
latent variable that is (approximately) independent of the parent -- the Rosenblatt
|
|
54
|
+
assumption -- and is an approximation when the residual dependence is non-Gaussian.
|
|
55
|
+
|
|
56
|
+
Latent column order: the encoded data columns in ``columns`` order, then the indicators in the
|
|
57
|
+
same order.
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
from __future__ import annotations
|
|
61
|
+
|
|
62
|
+
from typing import Any, NamedTuple
|
|
63
|
+
|
|
64
|
+
import numpy as np
|
|
65
|
+
import polars as pl
|
|
66
|
+
from scipy import special, stats
|
|
67
|
+
|
|
68
|
+
from ectype.fingerprint.core import ArrayStore
|
|
69
|
+
from ectype.fingerprint.disclosure import coarsen
|
|
70
|
+
from ectype.fingerprint.schema import ColumnSchema, DisclosurePolicySpec, ModelSpec
|
|
71
|
+
from ectype.io.values import category_codes, column_to_values, values_to_column
|
|
72
|
+
from ectype.models.base import MarginalModel
|
|
73
|
+
from ectype.profiling.conditional import (
|
|
74
|
+
KIND_CPT_TREE,
|
|
75
|
+
MAX_PARENT_LEVELS,
|
|
76
|
+
MIN_MI,
|
|
77
|
+
PSEUDO_COUNT,
|
|
78
|
+
fit_cpt_tree,
|
|
79
|
+
tree_order,
|
|
80
|
+
)
|
|
81
|
+
from ectype.types import LogicalType
|
|
82
|
+
|
|
83
|
+
MISSING_PREFIX = "__missing__"
|
|
84
|
+
EPS = 1e-9 # clip for u before Phi^-1 (|z| <= ~6)
|
|
85
|
+
_INNER = 1e-9 # relative inner margin when jittering inside an interval
|
|
86
|
+
HERMITE_TERMS = 30 # Mehler-series terms for the latent-correlation inversion
|
|
87
|
+
MAX_TREE_ORDINAL_LEVELS = 15 # tied ordinals that may join the CPT tree ...
|
|
88
|
+
MIN_TREE_ORDINAL_TOP_SHARE = 0.2 # ... when their modal value has at least this share
|
|
89
|
+
|
|
90
|
+
KIND_PIT = "pit"
|
|
91
|
+
KIND_RANDOMIZED = "randomized_pit"
|
|
92
|
+
KIND_FREQUENCY = "frequency_interval"
|
|
93
|
+
KIND_MISSING = "bernoulli_indicator"
|
|
94
|
+
|
|
95
|
+
_CONTINUOUS = (LogicalType.CONTINUOUS, LogicalType.DATETIME)
|
|
96
|
+
_CATEGORY = (LogicalType.CATEGORICAL, LogicalType.BOOLEAN)
|
|
97
|
+
_NUMERIC = (LogicalType.CONTINUOUS, LogicalType.DISCRETE, LogicalType.DATETIME)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def missing_name(column: str) -> str:
|
|
101
|
+
return f"{MISSING_PREFIX}{column}"
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _ndtri(u: np.ndarray) -> np.ndarray:
|
|
105
|
+
return special.ndtri(np.clip(u, EPS, 1.0 - EPS))
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _ndtr(z: np.ndarray) -> np.ndarray:
|
|
109
|
+
return np.clip(special.ndtr(z), EPS, 1.0 - EPS)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _truncated_mean(lo: np.ndarray, hi: np.ndarray) -> np.ndarray:
|
|
113
|
+
"""E[Z | Phi(Z) in [lo, hi]] for a standard normal Z (point masses -> Phi^-1(lo))."""
|
|
114
|
+
lo = np.asarray(lo, dtype=float)
|
|
115
|
+
hi = np.asarray(hi, dtype=float)
|
|
116
|
+
w = hi - lo
|
|
117
|
+
dens = stats.norm.pdf(special.ndtri(lo)) - stats.norm.pdf(special.ndtri(hi))
|
|
118
|
+
wide = w > 1e-12
|
|
119
|
+
out = np.asarray(special.ndtri(np.clip(0.5 * (lo + hi), EPS, 1 - EPS)), dtype=float)
|
|
120
|
+
out[wide] = dens[wide] / w[wide]
|
|
121
|
+
return out
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _interval_factor(lo: np.ndarray, hi: np.ndarray) -> float:
|
|
125
|
+
"""Var(E[Z | interval]) for a partition of [0, 1] into intervals [lo, hi]."""
|
|
126
|
+
m = _truncated_mean(lo, hi)
|
|
127
|
+
p = np.asarray(hi, dtype=float) - np.asarray(lo, dtype=float)
|
|
128
|
+
total = p.sum()
|
|
129
|
+
if total <= 0:
|
|
130
|
+
return 1.0
|
|
131
|
+
return float(np.clip(np.sum(p * m * m) / total, 1e-6, 1.0))
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _hermite_integrals(lo: np.ndarray, hi: np.ndarray, terms: int) -> np.ndarray:
|
|
135
|
+
"""``I[:, j] = integral of h_j(z) phi(z) dz`` over ``[Phi^-1(lo), Phi^-1(hi)]``, ``j = 0..terms``
|
|
136
|
+
(normalised Hermite ``h_j = He_j / sqrt(j!)``; ``I_j = -(h_{j-1} phi)|_a^b / sqrt(j)``)."""
|
|
137
|
+
za = np.clip(special.ndtri(lo), -37.0, 37.0)
|
|
138
|
+
zb = np.clip(special.ndtri(hi), -37.0, 37.0)
|
|
139
|
+
pa, pb = stats.norm.pdf(za), stats.norm.pdf(zb)
|
|
140
|
+
out = np.empty((lo.size, terms + 1))
|
|
141
|
+
out[:, 0] = hi - lo
|
|
142
|
+
ha_prev, ha = np.zeros_like(za), np.ones_like(za)
|
|
143
|
+
hb_prev, hb = np.zeros_like(zb), np.ones_like(zb)
|
|
144
|
+
for j in range(1, terms + 1):
|
|
145
|
+
out[:, j] = (ha * pa - hb * pb) / np.sqrt(j)
|
|
146
|
+
ha_prev, ha = ha, (za * ha - np.sqrt(j - 1) * ha_prev) / np.sqrt(j)
|
|
147
|
+
hb_prev, hb = hb, (zb * hb - np.sqrt(j - 1) * hb_prev) / np.sqrt(j)
|
|
148
|
+
return out
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
_GRID_Z = np.linspace(-8.5, 8.5, 17001)
|
|
152
|
+
_GRID_CACHE: dict[int, np.ndarray] = {}
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _grid_hermite(terms: int) -> np.ndarray:
|
|
156
|
+
"""``h_k(z) phi(z) dz`` trapezoid weights on ``_GRID_Z``, ``k = 1..terms`` (cached)."""
|
|
157
|
+
if terms not in _GRID_CACHE:
|
|
158
|
+
z = _GRID_Z
|
|
159
|
+
w = stats.norm.pdf(z) * np.gradient(z)
|
|
160
|
+
w[0] *= 0.5
|
|
161
|
+
w[-1] *= 0.5
|
|
162
|
+
out = np.empty((terms, z.size))
|
|
163
|
+
prev, cur = np.ones_like(z), z.copy()
|
|
164
|
+
for k in range(1, terms + 1):
|
|
165
|
+
out[k - 1] = cur * w
|
|
166
|
+
prev, cur = cur, (z * cur - np.sqrt(k) * prev) / np.sqrt(k + 1)
|
|
167
|
+
_GRID_CACHE[terms] = out
|
|
168
|
+
return _GRID_CACHE[terms]
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def rank_moments(lo: np.ndarray, hi: np.ndarray, terms: int = HERMITE_TERMS, *,
|
|
172
|
+
partition: bool = True) -> np.ndarray:
|
|
173
|
+
"""Hermite coefficients ``gamma_k = E[g(Z) h_k(Z)]``, ``k = 1..terms``, of the mid-rank
|
|
174
|
+
step function ``g(z) = (lo + hi) / 2`` of the latent interval containing ``Phi(z)``
|
|
175
|
+
(``g(z) = Phi(z)`` outside every interval), where ``h_k = He_k / sqrt(k!)`` are the
|
|
176
|
+
normalised probabilists' Hermite polynomials and ``[lo, hi]`` are the observed rows'
|
|
177
|
+
latent intervals on the ``u`` scale. ``g`` is the column's mid-rank (``F(x-) + F(x)) / 2``
|
|
178
|
+
in the source data, the score Spearman's rho with ties is computed from.
|
|
179
|
+
|
|
180
|
+
``partition=True`` (an unconditional codec): the distinct non-degenerate intervals are
|
|
181
|
+
the atoms of one fixed partition (model probability = width); the coefficients are
|
|
182
|
+
integrated on a fine grid. ``partition=False`` (conditional intervals that vary by row):
|
|
183
|
+
each row's interval is weighted equally, ``gamma_k = mean(mid * E[h_k | interval])``.
|
|
184
|
+
|
|
185
|
+
By Mehler's formula, for ``(Z_i, Z_j)`` bivariate normal with correlation ``rho``,
|
|
186
|
+
``cov(g_i, g_j) = sum_k gamma_ik gamma_jk rho^k`` -- the tie-aware generalisation of
|
|
187
|
+
``rho_S = (6 / pi) arcsin(rho / 2)`` (see ``copulas.rank_invert``).
|
|
188
|
+
"""
|
|
189
|
+
lo = np.clip(np.asarray(lo, dtype=float), 0.0, 1.0)
|
|
190
|
+
hi = np.clip(np.asarray(hi, dtype=float), 0.0, 1.0)
|
|
191
|
+
wide = (hi - lo) > 1e-12
|
|
192
|
+
if not partition:
|
|
193
|
+
out = np.zeros(terms)
|
|
194
|
+
if not wide.any():
|
|
195
|
+
return out
|
|
196
|
+
lo, hi = lo[wide], hi[wide]
|
|
197
|
+
ints = _hermite_integrals(lo, hi, terms)
|
|
198
|
+
mid = 0.5 * (lo + hi)
|
|
199
|
+
out[:] = (mid[:, None] * ints[:, 1:] / (hi - lo)[:, None]).mean(axis=0) * wide.mean()
|
|
200
|
+
return out
|
|
201
|
+
u = special.ndtr(_GRID_Z)
|
|
202
|
+
g = u.copy()
|
|
203
|
+
if wide.any():
|
|
204
|
+
pairs = np.unique(np.round(np.column_stack([lo[wide], hi[wide]]), 12), axis=0)
|
|
205
|
+
alo, ahi = pairs[:, 0], pairs[:, 1]
|
|
206
|
+
j = np.searchsorted(alo, u, side="right") - 1
|
|
207
|
+
ok = j >= 0
|
|
208
|
+
inside = np.zeros_like(ok)
|
|
209
|
+
inside[ok] = u[ok] < ahi[j[ok]]
|
|
210
|
+
g[inside] = 0.5 * (alo[j[inside]] + ahi[j[inside]])
|
|
211
|
+
return _grid_hermite(terms) @ g
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def mid_ranks(lo: np.ndarray, hi: np.ndarray) -> np.ndarray:
|
|
215
|
+
"""Per-row mid-rank ``(lo + hi) / 2`` of the latent intervals."""
|
|
216
|
+
return 0.5 * (np.asarray(lo, dtype=float) + np.asarray(hi, dtype=float))
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _jitter(lo: np.ndarray, hi: np.ndarray, rng: np.random.Generator) -> np.ndarray:
|
|
220
|
+
"""Uniform draw in ``[lo, hi]`` kept a hair inside the interval (robust lookups)."""
|
|
221
|
+
w = hi - lo
|
|
222
|
+
v = rng.random(lo.shape[0])
|
|
223
|
+
return lo + w * (_INNER + (1.0 - 2.0 * _INNER) * v)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def null_mask(s: pl.Series) -> np.ndarray:
|
|
227
|
+
"""Missing entries: nulls, plus NaN in float columns (NaN-coded missingness)."""
|
|
228
|
+
m = s.is_null()
|
|
229
|
+
if s.dtype.is_float():
|
|
230
|
+
m = m | s.is_nan().fill_null(True)
|
|
231
|
+
return np.asarray(m.to_numpy(), dtype=bool)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
class LatentMoments:
|
|
235
|
+
"""Rank moments of the fit data for the copula's latent-correlation estimate.
|
|
236
|
+
|
|
237
|
+
``coef[i]`` are column ``i``'s mid-rank Hermite coefficients (:func:`rank_moments`),
|
|
238
|
+
scaled by its observed fraction; ``target[i, j]`` is the observed mean product of centred
|
|
239
|
+
mid-ranks (missing entries contribute 0). Under a Gaussian copula with latent correlation
|
|
240
|
+
``rho_ij``, ``target_ij ~= sum_k coef_ik coef_jk rho_ij^k``; inverting that per pair is a
|
|
241
|
+
tie-aware Spearman (polychoric / polyserial-type) estimate. Unlike the jittered normal
|
|
242
|
+
scores, mid-ranks carry no jitter noise, so a column whose intervals are nearly ``[0, 1]``
|
|
243
|
+
(a near-deterministic CPT child) has tiny coefficients *and* tiny covariances instead of
|
|
244
|
+
an attenuation factor near zero dividing noise.
|
|
245
|
+
"""
|
|
246
|
+
|
|
247
|
+
def __init__(self, coef: np.ndarray, target: np.ndarray) -> None:
|
|
248
|
+
self.coef = np.asarray(coef, dtype=np.float64)
|
|
249
|
+
self.target = np.asarray(target, dtype=np.float64)
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
class AttenuationFactors(np.ndarray):
|
|
253
|
+
"""``latent_attenuation`` array that also carries ``moments`` (or ``None``)."""
|
|
254
|
+
|
|
255
|
+
moments: LatentMoments | None = None
|
|
256
|
+
|
|
257
|
+
def __array_finalize__(self, obj: Any) -> None:
|
|
258
|
+
self.moments = getattr(obj, "moments", None)
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
class LatentAtoms(NamedTuple):
|
|
262
|
+
"""The tied values of one latent column as latent ``u``-intervals: a read-only view for
|
|
263
|
+
joint models that treat ties as atoms instead of jittered scores (``models.chain``).
|
|
264
|
+
|
|
265
|
+
``lower`` / ``upper`` have shape ``(rows, atoms)`` with the atoms in latent order. An
|
|
266
|
+
unconditional column has one row. A conditionally encoded child (``parent`` names its
|
|
267
|
+
parent's latent column) has one row per parent atom, in the parent's latent order, followed
|
|
268
|
+
by its marginal intervals, which apply when the parent value is missing. ``nominal`` is
|
|
269
|
+
true for categories and missingness indicators, whose latent order carries no distance.
|
|
270
|
+
"""
|
|
271
|
+
|
|
272
|
+
lower: np.ndarray
|
|
273
|
+
upper: np.ndarray
|
|
274
|
+
nominal: bool
|
|
275
|
+
parent: str | None = None
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
# ---------------------------------------------------------------------------------------------
|
|
279
|
+
# Category helpers
|
|
280
|
+
# ---------------------------------------------------------------------------------------------
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _marginal_labels(marginal: MarginalModel) -> np.ndarray | None:
|
|
284
|
+
for name in ("labels", "categories"):
|
|
285
|
+
lab = getattr(marginal, name, None)
|
|
286
|
+
if lab is not None:
|
|
287
|
+
return np.asarray(lab).astype(str)
|
|
288
|
+
return None
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _category_table(marginal: MarginalModel, col: ColumnSchema) -> tuple[np.ndarray | None,
|
|
292
|
+
np.ndarray]:
|
|
293
|
+
"""(labels or None, probabilities per code 0..k-1) of a categorical/boolean marginal."""
|
|
294
|
+
labels = _marginal_labels(marginal)
|
|
295
|
+
if labels is not None:
|
|
296
|
+
k = len(labels)
|
|
297
|
+
elif col.logical_type == LogicalType.BOOLEAN:
|
|
298
|
+
k = 2
|
|
299
|
+
else:
|
|
300
|
+
raise ValueError(f"categorical marginal for {col.name!r} exposes no labels")
|
|
301
|
+
probs = None
|
|
302
|
+
for name in ("probabilities", "probs", "p"):
|
|
303
|
+
p = getattr(marginal, name, None)
|
|
304
|
+
if p is not None and np.size(p) == k:
|
|
305
|
+
probs = np.asarray(p, dtype=float)
|
|
306
|
+
break
|
|
307
|
+
if probs is None:
|
|
308
|
+
codes = np.arange(k, dtype=float)
|
|
309
|
+
probs = np.diff(np.concatenate([[0.0], np.asarray(marginal.cdf(codes), dtype=float)]))
|
|
310
|
+
probs = np.clip(probs, 0.0, None)
|
|
311
|
+
total = probs.sum()
|
|
312
|
+
if not np.isfinite(total) or total <= 0:
|
|
313
|
+
probs = np.full(k, 1.0 / k)
|
|
314
|
+
else:
|
|
315
|
+
probs = probs / total
|
|
316
|
+
return labels, probs
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def order_categories_by(df: pl.DataFrame, cat_col: str, numeric_cols: list[str], *,
|
|
320
|
+
categories: np.ndarray | None = None,
|
|
321
|
+
return_column: bool = False, return_strength: bool = False) -> Any:
|
|
322
|
+
"""Data-informed category order for frequency-interval encoding.
|
|
323
|
+
|
|
324
|
+
Picks the numeric column most associated with ``cat_col`` (largest correlation ratio
|
|
325
|
+
eta^2 of its ranks across categories) and orders the categories by the mean rank of that
|
|
326
|
+
column, so the frequency intervals are monotone in the strongest numeric relation.
|
|
327
|
+
|
|
328
|
+
Returns ``perm``, an integer array where ``perm[j]`` is the code (index into
|
|
329
|
+
``categories``) placed at interval position ``j``. ``categories`` defaults to the sorted
|
|
330
|
+
unique non-null labels of the column. Unobserved categories get the overall mean rank; ties
|
|
331
|
+
keep code order. With ``return_column=True`` returns ``(perm, chosen_column_or_None)``;
|
|
332
|
+
``return_strength=True`` appends the chosen column's eta^2 (0 when none) to the tuple.
|
|
333
|
+
"""
|
|
334
|
+
s = df.get_column(cat_col)
|
|
335
|
+
if categories is None:
|
|
336
|
+
if s.dtype == pl.Boolean:
|
|
337
|
+
categories = np.array(["False", "True"])
|
|
338
|
+
else:
|
|
339
|
+
categories = np.array(sorted(s.drop_nulls().cast(pl.String).unique().to_list()))
|
|
340
|
+
categories = np.asarray(categories).astype(str)
|
|
341
|
+
k = len(categories)
|
|
342
|
+
identity = np.arange(k, dtype=np.int64)
|
|
343
|
+
codes = category_codes(s, categories)
|
|
344
|
+
best: tuple[float, str | None, np.ndarray | None] = (-1.0, None, None)
|
|
345
|
+
for name in numeric_cols:
|
|
346
|
+
if name == cat_col or name not in df.columns:
|
|
347
|
+
continue
|
|
348
|
+
num = df.get_column(name)
|
|
349
|
+
if num.dtype == pl.Boolean:
|
|
350
|
+
num = num.cast(pl.Int8)
|
|
351
|
+
if num.dtype.is_temporal():
|
|
352
|
+
num = num.to_physical()
|
|
353
|
+
x = num.cast(pl.Float64, strict=False).fill_null(np.nan).to_numpy().astype(float)
|
|
354
|
+
ok = np.isfinite(codes) & np.isfinite(x)
|
|
355
|
+
if ok.sum() < 3:
|
|
356
|
+
continue
|
|
357
|
+
r = stats.rankdata(x[ok])
|
|
358
|
+
c = codes[ok].astype(np.int64)
|
|
359
|
+
tot = r.var()
|
|
360
|
+
if tot <= 0:
|
|
361
|
+
continue
|
|
362
|
+
cnt = np.bincount(c, minlength=k).astype(float)
|
|
363
|
+
sums = np.bincount(c, weights=r, minlength=k)
|
|
364
|
+
means = np.where(cnt > 0, sums / np.maximum(cnt, 1.0), r.mean())
|
|
365
|
+
eta2 = float(np.sum(cnt * (means - r.mean()) ** 2) / (len(r) * tot))
|
|
366
|
+
if eta2 > best[0]:
|
|
367
|
+
best = (eta2, name, means)
|
|
368
|
+
if best[2] is None:
|
|
369
|
+
perm = identity
|
|
370
|
+
else:
|
|
371
|
+
perm = np.argsort(best[2], kind="stable").astype(np.int64)
|
|
372
|
+
out: tuple[Any, ...] = (perm,)
|
|
373
|
+
if return_column:
|
|
374
|
+
out += (best[1],)
|
|
375
|
+
if return_strength:
|
|
376
|
+
out += (max(best[0], 0.0),)
|
|
377
|
+
return out if len(out) > 1 else perm
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
# ---------------------------------------------------------------------------------------------
|
|
381
|
+
# Per-column codecs
|
|
382
|
+
# ---------------------------------------------------------------------------------------------
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
class _Codec:
|
|
386
|
+
kind: str
|
|
387
|
+
|
|
388
|
+
def __init__(self, col: ColumnSchema, marginal: MarginalModel) -> None:
|
|
389
|
+
self.col = col
|
|
390
|
+
self.marginal = marginal
|
|
391
|
+
self.factor = 1.0 # Var(E[z | value]); 1 for continuous columns
|
|
392
|
+
|
|
393
|
+
def estimate_factor(self, v: np.ndarray) -> None:
|
|
394
|
+
"""Set :attr:`factor` from observed values (no-op for continuous columns)."""
|
|
395
|
+
|
|
396
|
+
def intervals(self, v: np.ndarray, parent: np.ndarray | None = None
|
|
397
|
+
) -> tuple[np.ndarray, np.ndarray] | None:
|
|
398
|
+
"""Latent ``u``-intervals ``(lo, hi)`` of the finite entries of ``v``; ``None`` for a
|
|
399
|
+
continuous codec (every interval has zero width)."""
|
|
400
|
+
return None
|
|
401
|
+
|
|
402
|
+
def values(self, s: pl.Series) -> np.ndarray:
|
|
403
|
+
return column_to_values(s, self.col)
|
|
404
|
+
|
|
405
|
+
def encode(self, v: np.ndarray, rng: np.random.Generator) -> np.ndarray:
|
|
406
|
+
"""Normal scores for non-NaN ``v`` (NaN entries returned as NaN)."""
|
|
407
|
+
raise NotImplementedError
|
|
408
|
+
|
|
409
|
+
def decode(self, z: np.ndarray) -> np.ndarray:
|
|
410
|
+
raise NotImplementedError
|
|
411
|
+
|
|
412
|
+
def to_series(self, v: np.ndarray) -> pl.Series:
|
|
413
|
+
return values_to_column(v, self.col)
|
|
414
|
+
|
|
415
|
+
def params(self) -> dict[str, Any]:
|
|
416
|
+
return {"column": self.col.name, "logical_type": str(self.col.logical_type),
|
|
417
|
+
"eps": EPS, "attenuation": self.factor}
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
class _PitCodec(_Codec):
|
|
421
|
+
kind = KIND_PIT
|
|
422
|
+
|
|
423
|
+
def encode(self, v: np.ndarray, rng: np.random.Generator) -> np.ndarray:
|
|
424
|
+
out = np.full(v.shape[0], np.nan)
|
|
425
|
+
ok = np.isfinite(v)
|
|
426
|
+
out[ok] = _ndtri(np.asarray(self.marginal.cdf(v[ok]), dtype=float))
|
|
427
|
+
return out
|
|
428
|
+
|
|
429
|
+
def decode(self, z: np.ndarray) -> np.ndarray:
|
|
430
|
+
return np.asarray(self.marginal.ppf(_ndtr(z)), dtype=float)
|
|
431
|
+
|
|
432
|
+
def intervals(self, v: np.ndarray, parent: np.ndarray | None = None
|
|
433
|
+
) -> tuple[np.ndarray, np.ndarray] | None:
|
|
434
|
+
x = v[np.isfinite(v)]
|
|
435
|
+
hi = np.asarray(self.marginal.cdf(x), dtype=float)
|
|
436
|
+
lo = np.minimum(np.asarray(self.marginal.cdf_left(x), dtype=float), hi)
|
|
437
|
+
return lo, hi
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
class _RandomizedPitCodec(_PitCodec):
|
|
441
|
+
kind = KIND_RANDOMIZED
|
|
442
|
+
|
|
443
|
+
def encode(self, v: np.ndarray, rng: np.random.Generator) -> np.ndarray:
|
|
444
|
+
out = np.full(v.shape[0], np.nan)
|
|
445
|
+
ok = np.isfinite(v)
|
|
446
|
+
x = v[ok]
|
|
447
|
+
hi = np.asarray(self.marginal.cdf(x), dtype=float)
|
|
448
|
+
lo = np.minimum(np.asarray(self.marginal.cdf_left(x), dtype=float), hi)
|
|
449
|
+
out[ok] = _ndtri(_jitter(lo, hi, rng))
|
|
450
|
+
return out
|
|
451
|
+
|
|
452
|
+
def intervals(self, v: np.ndarray, parent: np.ndarray | None = None
|
|
453
|
+
) -> tuple[np.ndarray, np.ndarray] | None:
|
|
454
|
+
x = v[np.isfinite(v)]
|
|
455
|
+
hi = np.asarray(self.marginal.cdf(x), dtype=float)
|
|
456
|
+
lo = np.minimum(np.asarray(self.marginal.cdf_left(x), dtype=float), hi)
|
|
457
|
+
return lo, hi
|
|
458
|
+
|
|
459
|
+
def estimate_factor(self, v: np.ndarray) -> None:
|
|
460
|
+
if not np.isfinite(v).any():
|
|
461
|
+
return
|
|
462
|
+
lo, hi = self.intervals(v) # type: ignore[misc]
|
|
463
|
+
m = _truncated_mean(lo, hi)
|
|
464
|
+
self.factor = float(np.clip(np.mean(m * m), 1e-6, 1.0))
|
|
465
|
+
|
|
466
|
+
|
|
467
|
+
class _FrequencyCodec(_Codec):
|
|
468
|
+
kind = KIND_FREQUENCY
|
|
469
|
+
|
|
470
|
+
def __init__(self, col: ColumnSchema, marginal: MarginalModel,
|
|
471
|
+
order: np.ndarray | None = None, order_by: str | None = None) -> None:
|
|
472
|
+
super().__init__(col, marginal)
|
|
473
|
+
self.labels, self.probs = self._table()
|
|
474
|
+
k = len(self.probs)
|
|
475
|
+
order = np.arange(k, dtype=np.int64) if order is None else np.asarray(order, np.int64)
|
|
476
|
+
if sorted(order.tolist()) != list(range(k)):
|
|
477
|
+
raise ValueError(f"category_order for {col.name!r} is not a permutation of 0..{k - 1}")
|
|
478
|
+
self.order = order
|
|
479
|
+
self.order_by = order_by
|
|
480
|
+
self.order_strength = 0.0 # eta^2 of order_by (root priority for the Chow-Liu forest)
|
|
481
|
+
self.position = np.empty(k, dtype=np.int64)
|
|
482
|
+
self.position[order] = np.arange(k)
|
|
483
|
+
p_perm = self.probs[order]
|
|
484
|
+
self.upper = np.cumsum(p_perm)
|
|
485
|
+
self.upper[-1] = 1.0
|
|
486
|
+
self.lower = np.concatenate([[0.0], self.upper[:-1]])
|
|
487
|
+
self.factor = _interval_factor(self.lower, self.upper)
|
|
488
|
+
# conditional decode (set by set_conditional)
|
|
489
|
+
self.parent: str | None = None
|
|
490
|
+
self.cpt: np.ndarray | None = None
|
|
491
|
+
self.parent_labels: np.ndarray | None = None
|
|
492
|
+
self.cond_meta: dict[str, Any] = {}
|
|
493
|
+
|
|
494
|
+
def label_array(self) -> np.ndarray:
|
|
495
|
+
if self.labels is not None:
|
|
496
|
+
return np.asarray(self.labels).astype(str)
|
|
497
|
+
if len(self.probs) == 2:
|
|
498
|
+
return np.array(["False", "True"])
|
|
499
|
+
return np.arange(len(self.probs)).astype(str)
|
|
500
|
+
|
|
501
|
+
def set_conditional(self, parent: str, cpt: np.ndarray, parent_labels: np.ndarray,
|
|
502
|
+
meta: dict[str, Any] | None = None) -> None:
|
|
503
|
+
"""Encode/decode conditionally on ``parent``: ``cpt[p, c] = P(self = c | parent = p)``
|
|
504
|
+
over marginal codes. Conditional intervals use the same category order."""
|
|
505
|
+
cpt = np.clip(np.asarray(cpt, dtype=float), 0.0, None)
|
|
506
|
+
if cpt.ndim != 2 or cpt.shape[1] != len(self.probs):
|
|
507
|
+
raise ValueError(f"conditional table for {self.col.name!r} has shape {cpt.shape}, "
|
|
508
|
+
f"expected (k_parent, {len(self.probs)})")
|
|
509
|
+
sums = cpt.sum(axis=1, keepdims=True)
|
|
510
|
+
cpt = np.where(sums > 0, cpt / np.where(sums > 0, sums, 1.0), self.probs)
|
|
511
|
+
self.parent = parent
|
|
512
|
+
self.cpt = cpt
|
|
513
|
+
self.parent_labels = np.asarray(parent_labels).astype(str)
|
|
514
|
+
self.cond_meta = dict(meta or {})
|
|
515
|
+
upper = np.cumsum(cpt[:, self.order], axis=1)
|
|
516
|
+
upper[:, -1] = 1.0
|
|
517
|
+
self.cond_upper = upper
|
|
518
|
+
self.cond_lower = np.concatenate([np.zeros((upper.shape[0], 1)), upper[:, :-1]], axis=1)
|
|
519
|
+
|
|
520
|
+
def values(self, s: pl.Series) -> np.ndarray:
|
|
521
|
+
return column_to_values(s, self.col, self.labels)
|
|
522
|
+
|
|
523
|
+
def _parent_index(self, parent: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
|
524
|
+
pc = np.asarray(parent, dtype=float)
|
|
525
|
+
okp = np.isfinite(pc)
|
|
526
|
+
assert self.cpt is not None
|
|
527
|
+
pi = np.clip(np.rint(pc[okp]), 0, self.cpt.shape[0] - 1).astype(np.int64)
|
|
528
|
+
return okp, pi
|
|
529
|
+
|
|
530
|
+
def _bounds(self, codes: np.ndarray, parent: np.ndarray | None
|
|
531
|
+
) -> tuple[np.ndarray, np.ndarray]:
|
|
532
|
+
"""Interval ``[lo, hi]`` per row of integer ``codes`` (conditional where the parent is
|
|
533
|
+
observed, marginal otherwise)."""
|
|
534
|
+
pos = self.position[codes]
|
|
535
|
+
lo, hi = self.lower[pos].copy(), self.upper[pos].copy()
|
|
536
|
+
if self.cpt is not None and parent is not None:
|
|
537
|
+
okp, pi = self._parent_index(parent)
|
|
538
|
+
lo[okp] = self.cond_lower[pi, pos[okp]]
|
|
539
|
+
hi[okp] = self.cond_upper[pi, pos[okp]]
|
|
540
|
+
return lo, hi
|
|
541
|
+
|
|
542
|
+
def encode(self, v: np.ndarray, rng: np.random.Generator,
|
|
543
|
+
parent: np.ndarray | None = None) -> np.ndarray:
|
|
544
|
+
out = np.full(v.shape[0], np.nan)
|
|
545
|
+
ok = np.isfinite(v)
|
|
546
|
+
k = len(self.probs)
|
|
547
|
+
codes = np.clip(np.rint(v[ok]), 0, k - 1).astype(np.int64)
|
|
548
|
+
lo, hi = self._bounds(codes, None if parent is None else np.asarray(parent)[ok])
|
|
549
|
+
out[ok] = _ndtri(_jitter(lo, hi, rng))
|
|
550
|
+
return out
|
|
551
|
+
|
|
552
|
+
def intervals(self, v: np.ndarray, parent: np.ndarray | None = None
|
|
553
|
+
) -> tuple[np.ndarray, np.ndarray] | None:
|
|
554
|
+
ok = np.isfinite(v)
|
|
555
|
+
codes = np.clip(np.rint(v[ok]), 0, len(self.probs) - 1).astype(np.int64)
|
|
556
|
+
par = None if parent is None or self.cpt is None else np.asarray(parent, float)[ok]
|
|
557
|
+
return self._bounds(codes, par)
|
|
558
|
+
|
|
559
|
+
def estimate_conditional_factor(self, v: np.ndarray, parent: np.ndarray) -> None:
|
|
560
|
+
"""Attenuation ``mean(E[z | interval]^2)`` over the intervals actually used."""
|
|
561
|
+
ok = np.isfinite(v)
|
|
562
|
+
if self.cpt is None or not ok.any():
|
|
563
|
+
return
|
|
564
|
+
codes = np.clip(np.rint(v[ok]), 0, len(self.probs) - 1).astype(np.int64)
|
|
565
|
+
lo, hi = self._bounds(codes, np.asarray(parent, dtype=float)[ok])
|
|
566
|
+
m = _truncated_mean(lo, hi)
|
|
567
|
+
self.factor = float(np.clip(np.mean(m * m), 1e-6, 1.0))
|
|
568
|
+
|
|
569
|
+
def decode(self, z: np.ndarray, parent: np.ndarray | None = None) -> np.ndarray:
|
|
570
|
+
u = _ndtr(z)
|
|
571
|
+
last = len(self.order) - 1
|
|
572
|
+
pos = np.clip(np.searchsorted(self.upper, u, side="right"), 0, last)
|
|
573
|
+
if self.cpt is not None and parent is not None:
|
|
574
|
+
okp, pi = self._parent_index(parent)
|
|
575
|
+
# per-row searchsorted(side="right"): number of upper bounds <= u
|
|
576
|
+
cnt = np.sum(self.cond_upper[pi] <= u[okp, None], axis=1)
|
|
577
|
+
pos[okp] = np.clip(cnt, 0, last)
|
|
578
|
+
return self.order[pos].astype(float)
|
|
579
|
+
|
|
580
|
+
def to_series(self, v: np.ndarray) -> pl.Series:
|
|
581
|
+
return values_to_column(v, self.col, self.labels)
|
|
582
|
+
|
|
583
|
+
def params(self) -> dict[str, Any]:
|
|
584
|
+
p = super().params()
|
|
585
|
+
p["n_categories"] = len(self.order)
|
|
586
|
+
p["category_order"] = [int(i) for i in self.order]
|
|
587
|
+
if self.order_by is not None:
|
|
588
|
+
p["order_by"] = self.order_by
|
|
589
|
+
if self.parent is not None:
|
|
590
|
+
p["conditional"] = {"kind": KIND_CPT_TREE, "parent": self.parent, **self.cond_meta}
|
|
591
|
+
return p
|
|
592
|
+
|
|
593
|
+
def _table(self) -> tuple[np.ndarray | None, np.ndarray]:
|
|
594
|
+
return _category_table(self.marginal, self.col)
|
|
595
|
+
|
|
596
|
+
|
|
597
|
+
def _finite_support(marginal: MarginalModel) -> tuple[np.ndarray, np.ndarray] | None:
|
|
598
|
+
"""``(values, probabilities)`` of a finite-support marginal, else ``None``."""
|
|
599
|
+
vals = getattr(marginal, "values", None)
|
|
600
|
+
probs = getattr(marginal, "probs", None)
|
|
601
|
+
if vals is None or probs is None or np.size(vals) != np.size(probs) or np.size(vals) < 2:
|
|
602
|
+
return None
|
|
603
|
+
p = np.clip(np.asarray(probs, dtype=float), 0.0, None)
|
|
604
|
+
if not np.isfinite(p.sum()) or p.sum() <= 0:
|
|
605
|
+
return None
|
|
606
|
+
return np.asarray(vals, dtype=float), p / p.sum()
|
|
607
|
+
|
|
608
|
+
|
|
609
|
+
#: quantile levels probed for the CDF jumps of a marginal without a finite support
|
|
610
|
+
ATOM_PROBE_LEVELS = 2049
|
|
611
|
+
#: narrowest latent interval reported as an atom
|
|
612
|
+
MIN_ATOM_WIDTH = 1e-9
|
|
613
|
+
#: latent levels at which ``MixedEncoder.latent_values`` tabulates a quantile function
|
|
614
|
+
VALUE_LEVELS = 1025
|
|
615
|
+
|
|
616
|
+
|
|
617
|
+
def marginal_atoms(marginal: MarginalModel) -> tuple[np.ndarray, np.ndarray] | None:
|
|
618
|
+
"""``(lower, upper)`` latent ``u``-intervals of the values a numeric marginal ties (the
|
|
619
|
+
jumps ``[F(x-), F(x)]`` of its CDF), in increasing order; ``None`` when it has none. A
|
|
620
|
+
finite-support marginal gives every support value. Any other marginal is probed at
|
|
621
|
+
``ATOM_PROBE_LEVELS`` quantile levels, which finds every jump wider than their spacing
|
|
622
|
+
(a plateau of a quantile grid, the spike of a zero-inflated amount)."""
|
|
623
|
+
fs = _finite_support(marginal)
|
|
624
|
+
if fs is not None:
|
|
625
|
+
x = np.unique(fs[0])
|
|
626
|
+
else:
|
|
627
|
+
u = (np.arange(ATOM_PROBE_LEVELS) + 0.5) / ATOM_PROBE_LEVELS
|
|
628
|
+
x = np.unique(np.asarray(marginal.ppf(u), dtype=float))
|
|
629
|
+
x = x[np.isfinite(x)]
|
|
630
|
+
if not x.size:
|
|
631
|
+
return None
|
|
632
|
+
hi = np.clip(np.asarray(marginal.cdf(x), dtype=float), 0.0, 1.0)
|
|
633
|
+
lo = np.clip(np.minimum(np.asarray(marginal.cdf_left(x), dtype=float), hi), 0.0, 1.0)
|
|
634
|
+
lo = np.maximum(lo, np.concatenate([[0.0], np.maximum.accumulate(hi)[:-1]]))
|
|
635
|
+
keep = hi - lo > MIN_ATOM_WIDTH
|
|
636
|
+
return (lo[keep], hi[keep]) if keep.any() else None
|
|
637
|
+
|
|
638
|
+
|
|
639
|
+
def is_tree_ordinal(col: ColumnSchema, marginal: MarginalModel) -> bool:
|
|
640
|
+
"""A heavily tied low-cardinality ordinal: a discrete column with a finite-support marginal
|
|
641
|
+
of at most ``MAX_TREE_ORDINAL_LEVELS`` values whose most frequent value has at least
|
|
642
|
+
``MIN_TREE_ORDINAL_TOP_SHARE`` of the mass (e.g. repayment-status codes)."""
|
|
643
|
+
if col.logical_type != LogicalType.DISCRETE:
|
|
644
|
+
return False
|
|
645
|
+
fs = _finite_support(marginal)
|
|
646
|
+
return fs is not None and fs[0].size <= MAX_TREE_ORDINAL_LEVELS \
|
|
647
|
+
and float(fs[1].max()) >= MIN_TREE_ORDINAL_TOP_SHARE
|
|
648
|
+
|
|
649
|
+
|
|
650
|
+
class _OrdinalCodec(_FrequencyCodec):
|
|
651
|
+
"""A tied low-cardinality discrete column encoded as frequency intervals over its finite
|
|
652
|
+
support in natural (numeric) order. Unconditionally these are exactly the randomized-PIT
|
|
653
|
+
intervals ``[F(x-), F(x)]``; the point is that the column can join the Chow-Liu forest and
|
|
654
|
+
be decoded through ``P(child | parent)``, which carries the heavily tied, often
|
|
655
|
+
non-monotone contingency structure a single Gaussian latent cannot. Internally values are
|
|
656
|
+
support codes (``values``/``decode``); ``to_series`` maps them back to numbers. Spec kind
|
|
657
|
+
stays ``"randomized_pit"`` with ``params["ordinal_tree"] = True``."""
|
|
658
|
+
|
|
659
|
+
kind = KIND_RANDOMIZED
|
|
660
|
+
|
|
661
|
+
def __init__(self, col: ColumnSchema, marginal: MarginalModel) -> None:
|
|
662
|
+
fs = _finite_support(marginal)
|
|
663
|
+
if fs is None:
|
|
664
|
+
raise ValueError(f"ordinal tree encoding for {col.name!r} needs a finite-support "
|
|
665
|
+
f"marginal")
|
|
666
|
+
self.support = fs[0]
|
|
667
|
+
super().__init__(col, marginal)
|
|
668
|
+
|
|
669
|
+
def _table(self) -> tuple[np.ndarray | None, np.ndarray]:
|
|
670
|
+
fs = _finite_support(self.marginal)
|
|
671
|
+
assert fs is not None
|
|
672
|
+
labels = np.array([str(int(v)) if float(v).is_integer() else repr(float(v))
|
|
673
|
+
for v in fs[0]])
|
|
674
|
+
return labels, fs[1]
|
|
675
|
+
|
|
676
|
+
def values(self, s: pl.Series) -> np.ndarray:
|
|
677
|
+
x = column_to_values(s, self.col)
|
|
678
|
+
out = np.full(x.shape[0], np.nan)
|
|
679
|
+
ok = np.isfinite(x)
|
|
680
|
+
sup = self.support
|
|
681
|
+
j = np.clip(np.searchsorted(sup, x[ok]), 1, sup.size - 1)
|
|
682
|
+
nearer_left = np.abs(x[ok] - sup[j - 1]) <= np.abs(sup[j] - x[ok])
|
|
683
|
+
out[ok] = np.where(nearer_left, j - 1, j)
|
|
684
|
+
return out
|
|
685
|
+
|
|
686
|
+
def to_series(self, v: np.ndarray) -> pl.Series:
|
|
687
|
+
ok = np.isfinite(v)
|
|
688
|
+
x = np.full(v.shape[0], np.nan)
|
|
689
|
+
x[ok] = self.support[np.clip(np.rint(v[ok]), 0, self.support.size - 1).astype(np.int64)]
|
|
690
|
+
return values_to_column(x, self.col)
|
|
691
|
+
|
|
692
|
+
def params(self) -> dict[str, Any]:
|
|
693
|
+
p = super().params()
|
|
694
|
+
p["ordinal_tree"] = True
|
|
695
|
+
return p
|
|
696
|
+
|
|
697
|
+
|
|
698
|
+
def _codec_class(col: ColumnSchema) -> type[_Codec]:
|
|
699
|
+
lt = col.logical_type
|
|
700
|
+
if lt in _CONTINUOUS:
|
|
701
|
+
return _PitCodec
|
|
702
|
+
if lt == LogicalType.DISCRETE:
|
|
703
|
+
return _RandomizedPitCodec
|
|
704
|
+
if lt in _CATEGORY:
|
|
705
|
+
return _FrequencyCodec
|
|
706
|
+
raise ValueError(f"column {col.name!r} has logical type {lt!s}, which is not encodable")
|
|
707
|
+
|
|
708
|
+
|
|
709
|
+
# ---------------------------------------------------------------------------------------------
|
|
710
|
+
# Encoder
|
|
711
|
+
# ---------------------------------------------------------------------------------------------
|
|
712
|
+
|
|
713
|
+
|
|
714
|
+
class MixedEncoder:
|
|
715
|
+
"""Bidirectional map between a mixed-type table and latent normal scores (see module doc)."""
|
|
716
|
+
|
|
717
|
+
latent_columns: list[str]
|
|
718
|
+
|
|
719
|
+
def __init__(self, codecs: list[_Codec], missing_rates: dict[str, float]) -> None:
|
|
720
|
+
self._codecs = codecs
|
|
721
|
+
self._moments: LatentMoments | None = None
|
|
722
|
+
self.columns = [c.col.name for c in codecs]
|
|
723
|
+
self.missing_rates = dict(missing_rates)
|
|
724
|
+
self.missing_columns = [n for n in self.columns if n in self.missing_rates]
|
|
725
|
+
self.latent_columns = self.columns + [missing_name(n) for n in self.missing_columns]
|
|
726
|
+
by_name = {c.col.name: c for c in codecs}
|
|
727
|
+
for child, parent in self.conditional_parents.items():
|
|
728
|
+
if parent not in by_name:
|
|
729
|
+
raise ValueError(f"conditional parent {parent!r} of {child!r} is not an "
|
|
730
|
+
f"encoded column")
|
|
731
|
+
pos = {n: j for j, n in enumerate(self.columns)}
|
|
732
|
+
self._decode_order = [pos[n] for n in tree_order(self.columns,
|
|
733
|
+
self.conditional_parents)]
|
|
734
|
+
|
|
735
|
+
@property
|
|
736
|
+
def marginals(self) -> dict[str, MarginalModel]:
|
|
737
|
+
"""The marginal model of every encoded column."""
|
|
738
|
+
return {c.col.name: c.marginal for c in self._codecs}
|
|
739
|
+
|
|
740
|
+
@property
|
|
741
|
+
def conditional_parents(self) -> dict[str, str]:
|
|
742
|
+
"""``{child: parent}`` of the conditional (Chow-Liu) forest; empty when off."""
|
|
743
|
+
return {c.col.name: c.parent for c in self._codecs
|
|
744
|
+
if isinstance(c, _FrequencyCodec) and c.parent is not None}
|
|
745
|
+
|
|
746
|
+
@property
|
|
747
|
+
def latent_attenuation(self) -> np.ndarray:
|
|
748
|
+
"""Per-latent-column attenuation factors ``a`` (see module doc), for
|
|
749
|
+
``GaussianCopula.fit(..., attenuation=...)``. On an encoder built by :meth:`fit` the
|
|
750
|
+
returned array also carries the rank moments (``.moments``, a :class:`LatentMoments`),
|
|
751
|
+
which the copula then uses instead of the first-order product correction."""
|
|
752
|
+
out = [c.factor * (1.0 - self.missing_rates.get(c.col.name, 0.0)) for c in self._codecs]
|
|
753
|
+
for name in self.missing_columns:
|
|
754
|
+
r = self.missing_rates[name]
|
|
755
|
+
out.append(_interval_factor(np.array([0.0, 1.0 - r]), np.array([1.0 - r, 1.0])))
|
|
756
|
+
arr = np.asarray(out, dtype=float).view(AttenuationFactors)
|
|
757
|
+
arr.moments = self._moments
|
|
758
|
+
return arr
|
|
759
|
+
|
|
760
|
+
@property
|
|
761
|
+
def latent_hermite(self) -> LatentMoments | None:
|
|
762
|
+
"""The :class:`LatentMoments` of the fit data (``None`` after :meth:`from_specs`), for
|
|
763
|
+
``GaussianCopula.fit(..., hermite=...)``."""
|
|
764
|
+
return self._moments
|
|
765
|
+
|
|
766
|
+
@property
|
|
767
|
+
def latent_atoms(self) -> dict[str, LatentAtoms]:
|
|
768
|
+
"""The tied values of each latent column as latent intervals (:class:`LatentAtoms`),
|
|
769
|
+
keyed by latent column name; a column without ties is absent. Read-only: everything
|
|
770
|
+
comes from the marginals, conditional tables and missing rates the encoder already
|
|
771
|
+
holds, so it is the same after :meth:`from_specs`."""
|
|
772
|
+
out: dict[str, LatentAtoms] = {}
|
|
773
|
+
by_name = {c.col.name: c for c in self._codecs}
|
|
774
|
+
for codec in self._codecs:
|
|
775
|
+
name = codec.col.name
|
|
776
|
+
if isinstance(codec, _FrequencyCodec):
|
|
777
|
+
lower, upper = codec.lower[None, :], codec.upper[None, :]
|
|
778
|
+
parent = by_name.get(codec.parent) if codec.parent is not None else None
|
|
779
|
+
if codec.cpt is not None and isinstance(parent, _FrequencyCodec):
|
|
780
|
+
# conditional rows are stored by parent code; list them in latent order
|
|
781
|
+
lower = np.vstack([codec.cond_lower[parent.order], lower])
|
|
782
|
+
upper = np.vstack([codec.cond_upper[parent.order], upper])
|
|
783
|
+
out[name] = LatentAtoms(lower.copy(), upper.copy(),
|
|
784
|
+
not isinstance(codec, _OrdinalCodec),
|
|
785
|
+
codec.parent if lower.shape[0] > 1 else None)
|
|
786
|
+
else:
|
|
787
|
+
found = marginal_atoms(codec.marginal)
|
|
788
|
+
if found is not None:
|
|
789
|
+
out[name] = LatentAtoms(found[0][None, :], found[1][None, :], False)
|
|
790
|
+
for name in self.missing_columns:
|
|
791
|
+
r = self.missing_rates[name]
|
|
792
|
+
out[missing_name(name)] = LatentAtoms(np.array([[0.0, 1.0 - r]]),
|
|
793
|
+
np.array([[1.0 - r, 1.0]]), True)
|
|
794
|
+
return out
|
|
795
|
+
|
|
796
|
+
@property
|
|
797
|
+
def latent_values(self) -> dict[str, np.ndarray]:
|
|
798
|
+
"""The quantile function of each numeric latent column at ``VALUE_LEVELS`` evenly
|
|
799
|
+
spaced latent levels ``(k + 1/2) / n``: the data value a latent ``u`` decodes to.
|
|
800
|
+
Read-only and a function of the marginals alone. It lets a joint model relate columns
|
|
801
|
+
on their common scale (``models.chain`` finds rows where one column equals another).
|
|
802
|
+
Categories, tied ordinals in the conditional forest and indicators are absent."""
|
|
803
|
+
u = (np.arange(VALUE_LEVELS) + 0.5) / VALUE_LEVELS
|
|
804
|
+
return {c.col.name: np.asarray(c.marginal.ppf(u), dtype=float) for c in self._codecs
|
|
805
|
+
if not isinstance(c, _FrequencyCodec)}
|
|
806
|
+
|
|
807
|
+
def _fit_moments(self, df: pl.DataFrame) -> LatentMoments | None:
|
|
808
|
+
"""Mid-rank Hermite coefficients and observed mid-rank covariances (see
|
|
809
|
+
:class:`LatentMoments`). Missing rows contribute zero (centred) mid-rank, and each
|
|
810
|
+
column's coefficients are scaled by its observed fraction to match."""
|
|
811
|
+
if not self._codecs or df.height == 0 or any(c.col.name not in df.columns for c in self._codecs):
|
|
812
|
+
return None
|
|
813
|
+
n = df.height
|
|
814
|
+
coefs: list[np.ndarray] = []
|
|
815
|
+
cols: list[np.ndarray] = []
|
|
816
|
+
values = {c.col.name: c.values(df.get_column(c.col.name)) for c in self._codecs}
|
|
817
|
+
for codec in self._codecs:
|
|
818
|
+
v = values[codec.col.name]
|
|
819
|
+
parent = None
|
|
820
|
+
if isinstance(codec, _FrequencyCodec) and codec.parent is not None:
|
|
821
|
+
parent = values[codec.parent]
|
|
822
|
+
ok = np.isfinite(v)
|
|
823
|
+
g = np.zeros(n)
|
|
824
|
+
gamma = np.zeros(HERMITE_TERMS)
|
|
825
|
+
if ok.any():
|
|
826
|
+
lo, hi = codec.intervals(v, parent) # type: ignore[misc]
|
|
827
|
+
g[ok] = mid_ranks(lo, hi) - 0.5
|
|
828
|
+
gamma = rank_moments(lo, hi, partition=parent is None) * float(ok.mean())
|
|
829
|
+
coefs.append(gamma)
|
|
830
|
+
cols.append(g)
|
|
831
|
+
for name in self.missing_columns:
|
|
832
|
+
r = self.missing_rates[name]
|
|
833
|
+
miss = null_mask(df.get_column(name))
|
|
834
|
+
lo, hi = np.where(miss, 1.0 - r, 0.0), np.where(miss, 1.0, 1.0 - r)
|
|
835
|
+
coefs.append(rank_moments(lo, hi))
|
|
836
|
+
cols.append(mid_ranks(lo, hi) - 0.5)
|
|
837
|
+
g_all = np.column_stack(cols)
|
|
838
|
+
return LatentMoments(np.vstack(coefs), g_all.T @ g_all / n)
|
|
839
|
+
|
|
840
|
+
@property
|
|
841
|
+
def category_orders(self) -> dict[str, list[int]]:
|
|
842
|
+
return {c.col.name: [int(i) for i in c.order] for c in self._codecs
|
|
843
|
+
if isinstance(c, _FrequencyCodec) and not isinstance(c, _OrdinalCodec)}
|
|
844
|
+
|
|
845
|
+
# -- construction --------------------------------------------------------------------
|
|
846
|
+
@classmethod
|
|
847
|
+
def fit(cls, df: pl.DataFrame, columns: list[ColumnSchema],
|
|
848
|
+
marginals: dict[str, MarginalModel], policy: DisclosurePolicySpec,
|
|
849
|
+
rng: np.random.Generator, *, order_categories: bool = True,
|
|
850
|
+
conditional: bool = True, max_parent_levels: int = MAX_PARENT_LEVELS,
|
|
851
|
+
min_mi: float = MIN_MI, pseudo_count: float = PSEUDO_COUNT,
|
|
852
|
+
tree_ordinals: bool = False) -> MixedEncoder:
|
|
853
|
+
"""Build the encoder for the columns in ``columns`` that have a marginal.
|
|
854
|
+
|
|
855
|
+
With ``conditional=True`` (default) categorical/boolean columns get a Chow-Liu forest
|
|
856
|
+
and conditional-interval encoding (see the module doc); ``max_parent_levels``,
|
|
857
|
+
``min_mi`` (nats, above the plug-in bias) and ``pseudo_count`` tune it.
|
|
858
|
+
``tree_ordinals=True`` (opt-in) also lets heavily tied low-cardinality discrete
|
|
859
|
+
columns (:func:`is_tree_ordinal`) join that forest; those left outside it keep the
|
|
860
|
+
plain randomized PIT. On UCI credit-default it reproduces the PAY_* contingency
|
|
861
|
+
tables (mutual information) but the Rosenblatt children lose rank dependence with
|
|
862
|
+
the numeric columns, so it is off by default. ``conditional=False`` keeps the plain frequency-interval
|
|
863
|
+
encoding. ``rng`` is accepted for interface symmetry; fitting is deterministic.
|
|
864
|
+
"""
|
|
865
|
+
used = [c for c in columns if c.name in marginals]
|
|
866
|
+
numeric = [c.name for c in used if c.logical_type in _NUMERIC]
|
|
867
|
+
codecs: list[_Codec] = []
|
|
868
|
+
rates: dict[str, float] = {}
|
|
869
|
+
for col in used:
|
|
870
|
+
m = marginals[col.name]
|
|
871
|
+
klass = _codec_class(col)
|
|
872
|
+
if klass is _FrequencyCodec:
|
|
873
|
+
order, by, eta2 = None, None, 0.0
|
|
874
|
+
if order_categories and col.logical_type == LogicalType.CATEGORICAL \
|
|
875
|
+
and col.name in df.columns:
|
|
876
|
+
labels, _ = _category_table(m, col)
|
|
877
|
+
order, by, eta2 = order_categories_by(df, col.name, numeric,
|
|
878
|
+
categories=labels, return_column=True,
|
|
879
|
+
return_strength=True)
|
|
880
|
+
codecs.append(_FrequencyCodec(col, m, order, by))
|
|
881
|
+
codecs[-1].order_strength = float(eta2) # type: ignore[attr-defined]
|
|
882
|
+
elif conditional and tree_ordinals and is_tree_ordinal(col, m) and col.name in df.columns:
|
|
883
|
+
oc = _OrdinalCodec(col, m)
|
|
884
|
+
_, _, eta2 = order_categories_by(df, col.name, numeric, categories=oc.labels,
|
|
885
|
+
return_column=True, return_strength=True)
|
|
886
|
+
oc.order_strength = float(eta2)
|
|
887
|
+
codecs.append(oc)
|
|
888
|
+
else:
|
|
889
|
+
codecs.append(klass(col, m))
|
|
890
|
+
if col.name in df.columns:
|
|
891
|
+
codecs[-1].estimate_factor(codecs[-1].values(df.get_column(col.name)))
|
|
892
|
+
codecs[-1].factor = coarsen(codecs[-1].factor, policy)
|
|
893
|
+
observed = 0.0
|
|
894
|
+
if col.name in df.columns and df.height > 0:
|
|
895
|
+
observed = float(null_mask(df.get_column(col.name)).mean())
|
|
896
|
+
if col.null_fraction > 0 or observed > 0:
|
|
897
|
+
rate = observed if observed > 0 else col.null_fraction
|
|
898
|
+
rate = float(np.clip(coarsen(float(rate), policy), 1e-12, 1.0 - 1e-12))
|
|
899
|
+
rates[col.name] = rate
|
|
900
|
+
if conditional:
|
|
901
|
+
_attach_tree(codecs, df, policy, max_parent_levels=max_parent_levels,
|
|
902
|
+
min_mi=min_mi, pseudo_count=pseudo_count)
|
|
903
|
+
_untree_ordinals(codecs, df, policy)
|
|
904
|
+
enc = cls(codecs, rates)
|
|
905
|
+
enc._moments = enc._fit_moments(df)
|
|
906
|
+
return enc
|
|
907
|
+
|
|
908
|
+
# -- encode / decode -----------------------------------------------------------------
|
|
909
|
+
def encode(self, df: pl.DataFrame, rng: np.random.Generator) -> np.ndarray:
|
|
910
|
+
"""(n, d) latent normal scores in ``latent_columns`` order.
|
|
911
|
+
|
|
912
|
+
Missing values get an independent ``N(0, 1)`` latent score (see module doc).
|
|
913
|
+
"""
|
|
914
|
+
n = df.height
|
|
915
|
+
z = np.empty((n, len(self.latent_columns)), dtype=np.float64)
|
|
916
|
+
null_masks: dict[str, np.ndarray] = {}
|
|
917
|
+
values = {c.col.name: c.values(df.get_column(c.col.name)) for c in self._codecs}
|
|
918
|
+
for j, codec in enumerate(self._codecs):
|
|
919
|
+
s = df.get_column(codec.col.name)
|
|
920
|
+
v = values[codec.col.name]
|
|
921
|
+
if isinstance(codec, _FrequencyCodec) and codec.parent is not None:
|
|
922
|
+
zj = codec.encode(v, rng, parent=values[codec.parent])
|
|
923
|
+
else:
|
|
924
|
+
zj = codec.encode(v, rng)
|
|
925
|
+
bad = ~np.isfinite(zj)
|
|
926
|
+
if bad.any():
|
|
927
|
+
zj[bad] = rng.standard_normal(int(bad.sum()))
|
|
928
|
+
z[:, j] = zj
|
|
929
|
+
null_masks[codec.col.name] = null_mask(s)
|
|
930
|
+
base = len(self._codecs)
|
|
931
|
+
for i, name in enumerate(self.missing_columns):
|
|
932
|
+
rate = self.missing_rates[name]
|
|
933
|
+
miss = null_masks[name]
|
|
934
|
+
lo = np.where(miss, 1.0 - rate, 0.0)
|
|
935
|
+
hi = np.where(miss, 1.0, 1.0 - rate)
|
|
936
|
+
z[:, base + i] = _ndtri(_jitter(lo, hi, rng))
|
|
937
|
+
return z
|
|
938
|
+
|
|
939
|
+
def decode(self, z: np.ndarray, rng: np.random.Generator | None = None) -> pl.DataFrame:
|
|
940
|
+
"""Latent scores -> table in source dtypes, with nulls applied from the indicators.
|
|
941
|
+
|
|
942
|
+
``rng`` is accepted for interface symmetry; decoding is deterministic.
|
|
943
|
+
"""
|
|
944
|
+
z = np.asarray(z, dtype=np.float64)
|
|
945
|
+
if z.ndim != 2 or z.shape[1] != len(self.latent_columns):
|
|
946
|
+
raise ValueError(f"expected latent array of shape (n, {len(self.latent_columns)}), "
|
|
947
|
+
f"got {z.shape}")
|
|
948
|
+
idx = {name: j for j, name in enumerate(self.latent_columns)}
|
|
949
|
+
decoded: dict[str, np.ndarray] = {}
|
|
950
|
+
for j in self._decode_order: # parents before children
|
|
951
|
+
codec = self._codecs[j]
|
|
952
|
+
if isinstance(codec, _FrequencyCodec) and codec.parent is not None:
|
|
953
|
+
v = codec.decode(z[:, j], parent=decoded[codec.parent])
|
|
954
|
+
else:
|
|
955
|
+
v = codec.decode(z[:, j])
|
|
956
|
+
name = codec.col.name
|
|
957
|
+
if name in self.missing_rates:
|
|
958
|
+
thr = special.ndtri(1.0 - self.missing_rates[name])
|
|
959
|
+
v = np.where(z[:, idx[missing_name(name)]] > thr, np.nan, v)
|
|
960
|
+
decoded[name] = v
|
|
961
|
+
return pl.DataFrame([c.to_series(decoded[c.col.name]) for c in self._codecs])
|
|
962
|
+
|
|
963
|
+
# -- serialisation -------------------------------------------------------------------
|
|
964
|
+
def to_specs(self, store: ArrayStore) -> dict[str, ModelSpec]:
|
|
965
|
+
"""Encoding specs keyed by column name, plus missingness specs keyed by
|
|
966
|
+
``"__missing__<col>"`` (each spec's ``params["column"]`` names the source column, so
|
|
967
|
+
callers can file them under ``manifest.model.missingness[<col>]``; see
|
|
968
|
+
:func:`split_specs`).
|
|
969
|
+
|
|
970
|
+
A conditionally encoded child keeps kind ``"frequency_interval"`` and adds
|
|
971
|
+
``params["conditional"] = {"kind": "cpt_tree", "parent", "pseudo_count",
|
|
972
|
+
"mutual_information", "backed_off_levels"}`` plus three arrays written to ``store``:
|
|
973
|
+
``cpt`` (float64 ``(k_parent, k_child)``, ``P(child | parent)`` over marginal codes),
|
|
974
|
+
``cpt_parent_labels`` and ``cpt_child_labels`` (the marginal labels both axes align
|
|
975
|
+
with, including ``"__other__"``). The forest is the union of the children's parent
|
|
976
|
+
links, so it round-trips through ``manifest.model.encodings`` and the container.
|
|
977
|
+
Unconditional encodings write no arrays."""
|
|
978
|
+
specs: dict[str, ModelSpec] = {}
|
|
979
|
+
for codec in self._codecs:
|
|
980
|
+
arrays: dict[str, str] = {}
|
|
981
|
+
if isinstance(codec, _FrequencyCodec) and codec.cpt is not None:
|
|
982
|
+
base = f"encoding.{codec.col.name}"
|
|
983
|
+
arrays = {
|
|
984
|
+
"cpt": store.put(f"{base}.cpt", codec.cpt),
|
|
985
|
+
"cpt_parent_labels": store.put(f"{base}.cpt_parent_labels",
|
|
986
|
+
np.asarray(codec.parent_labels, dtype=str)),
|
|
987
|
+
"cpt_child_labels": store.put(f"{base}.cpt_child_labels",
|
|
988
|
+
codec.label_array()),
|
|
989
|
+
}
|
|
990
|
+
specs[codec.col.name] = ModelSpec(kind=codec.kind, params=codec.params(),
|
|
991
|
+
arrays=arrays)
|
|
992
|
+
for name in self.missing_columns:
|
|
993
|
+
specs[missing_name(name)] = ModelSpec(
|
|
994
|
+
kind=KIND_MISSING,
|
|
995
|
+
params={"column": name, "rate": float(self.missing_rates[name]),
|
|
996
|
+
"latent_column": missing_name(name)})
|
|
997
|
+
return specs
|
|
998
|
+
|
|
999
|
+
@classmethod
|
|
1000
|
+
def from_specs(cls, specs: dict[str, ModelSpec], marginals: dict[str, MarginalModel],
|
|
1001
|
+
columns: list[ColumnSchema], store: ArrayStore | None = None) -> MixedEncoder:
|
|
1002
|
+
"""Restore from specs. Specs are matched by ``kind`` and ``params["column"]``, so
|
|
1003
|
+
either the merged dict from :meth:`to_specs` or ``{**encodings, **missingness}`` with
|
|
1004
|
+
missingness re-keyed works; ``list(specs.values())`` order does not matter."""
|
|
1005
|
+
enc: dict[str, ModelSpec] = {}
|
|
1006
|
+
miss: dict[str, ModelSpec] = {}
|
|
1007
|
+
for key, spec in specs.items():
|
|
1008
|
+
target = str(spec.params.get("column", key))
|
|
1009
|
+
if spec.kind == KIND_MISSING:
|
|
1010
|
+
miss[target] = spec
|
|
1011
|
+
else:
|
|
1012
|
+
enc[target] = spec
|
|
1013
|
+
codecs: list[_Codec] = []
|
|
1014
|
+
for col in columns:
|
|
1015
|
+
cspec = enc.get(col.name)
|
|
1016
|
+
if cspec is None:
|
|
1017
|
+
continue
|
|
1018
|
+
if col.name not in marginals:
|
|
1019
|
+
raise ValueError(f"no marginal for encoded column {col.name!r}")
|
|
1020
|
+
m = marginals[col.name]
|
|
1021
|
+
if cspec.kind == KIND_PIT:
|
|
1022
|
+
codecs.append(_PitCodec(col, m))
|
|
1023
|
+
elif cspec.kind == KIND_RANDOMIZED and cspec.params.get("ordinal_tree"):
|
|
1024
|
+
codecs.append(_OrdinalCodec(col, m))
|
|
1025
|
+
elif cspec.kind == KIND_RANDOMIZED:
|
|
1026
|
+
codecs.append(_RandomizedPitCodec(col, m))
|
|
1027
|
+
elif cspec.kind == KIND_FREQUENCY:
|
|
1028
|
+
order = cspec.params.get("category_order")
|
|
1029
|
+
by = cspec.params.get("order_by")
|
|
1030
|
+
codecs.append(_FrequencyCodec(col, m, None if order is None else
|
|
1031
|
+
np.asarray(order, dtype=np.int64),
|
|
1032
|
+
None if by is None else str(by)))
|
|
1033
|
+
else:
|
|
1034
|
+
raise ValueError(f"unknown encoding kind {cspec.kind!r} for {col.name!r}")
|
|
1035
|
+
if "attenuation" in cspec.params:
|
|
1036
|
+
codecs[-1].factor = float(cspec.params["attenuation"]) # type: ignore[arg-type]
|
|
1037
|
+
_restore_tree(codecs, enc, store)
|
|
1038
|
+
names = {c.col.name for c in codecs}
|
|
1039
|
+
rates = {c: float(s.params["rate"]) for c, s in miss.items() if c in names}
|
|
1040
|
+
return cls(codecs, rates)
|
|
1041
|
+
|
|
1042
|
+
|
|
1043
|
+
def _attach_tree(codecs: list[_Codec], df: pl.DataFrame, policy: DisclosurePolicySpec, *,
|
|
1044
|
+
max_parent_levels: int, min_mi: float, pseudo_count: float) -> None:
|
|
1045
|
+
"""Learn the Chow-Liu forest over the categorical codecs and make children conditional."""
|
|
1046
|
+
cats = [c for c in codecs if isinstance(c, _FrequencyCodec) and c.col.name in df.columns]
|
|
1047
|
+
if len(cats) < 2 or df.height == 0:
|
|
1048
|
+
return
|
|
1049
|
+
codes = {c.col.name: c.values(df.get_column(c.col.name)) for c in cats}
|
|
1050
|
+
probs = {c.col.name: c.probs for c in cats}
|
|
1051
|
+
priority = {c.col.name: c.order_strength for c in cats}
|
|
1052
|
+
tables = fit_cpt_tree(codes, probs, policy, max_parent_levels=max_parent_levels,
|
|
1053
|
+
min_mi=min_mi, pseudo_count=pseudo_count, root_priority=priority)
|
|
1054
|
+
by_name = {c.col.name: c for c in cats}
|
|
1055
|
+
for child, t in tables.items():
|
|
1056
|
+
codec, parent = by_name[child], by_name[t.parent]
|
|
1057
|
+
codec.set_conditional(t.parent, t.probs, parent.label_array(), {
|
|
1058
|
+
"pseudo_count": float(t.pseudo_count),
|
|
1059
|
+
"mutual_information": float(t.mutual_information),
|
|
1060
|
+
"backed_off_levels": int(t.backed_off.sum())})
|
|
1061
|
+
codec.estimate_conditional_factor(codes[child], codes[t.parent])
|
|
1062
|
+
codec.factor = coarsen(codec.factor, policy)
|
|
1063
|
+
|
|
1064
|
+
|
|
1065
|
+
def _untree_ordinals(codecs: list[_Codec], df: pl.DataFrame,
|
|
1066
|
+
policy: DisclosurePolicySpec) -> None:
|
|
1067
|
+
"""Ordinal codecs that ended up outside the forest revert to the plain randomized PIT
|
|
1068
|
+
(identical intervals, unchanged spec)."""
|
|
1069
|
+
linked = {c.parent for c in codecs if isinstance(c, _FrequencyCodec) and c.parent}
|
|
1070
|
+
for i, c in enumerate(codecs):
|
|
1071
|
+
if isinstance(c, _OrdinalCodec) and c.parent is None and c.col.name not in linked:
|
|
1072
|
+
plain = _RandomizedPitCodec(c.col, c.marginal)
|
|
1073
|
+
plain.estimate_factor(plain.values(df.get_column(c.col.name)))
|
|
1074
|
+
plain.factor = coarsen(plain.factor, policy)
|
|
1075
|
+
codecs[i] = plain
|
|
1076
|
+
|
|
1077
|
+
|
|
1078
|
+
def _restore_tree(codecs: list[_Codec], enc: dict[str, ModelSpec],
|
|
1079
|
+
store: ArrayStore | None) -> None:
|
|
1080
|
+
"""Re-attach conditional tables recorded in the children's encoding specs."""
|
|
1081
|
+
by_name = {c.col.name: c for c in codecs}
|
|
1082
|
+
for codec in codecs:
|
|
1083
|
+
spec = enc[codec.col.name]
|
|
1084
|
+
cond = spec.params.get("conditional")
|
|
1085
|
+
if not isinstance(codec, _FrequencyCodec) or not isinstance(cond, dict):
|
|
1086
|
+
continue
|
|
1087
|
+
name = codec.col.name
|
|
1088
|
+
if cond.get("kind", KIND_CPT_TREE) != KIND_CPT_TREE:
|
|
1089
|
+
raise ValueError(f"unknown conditional kind {cond.get('kind')!r} for {name!r}")
|
|
1090
|
+
if store is None:
|
|
1091
|
+
raise ValueError(f"encoding for {name!r} is conditional; an ArrayStore is required")
|
|
1092
|
+
parent = str(cond["parent"])
|
|
1093
|
+
pcodec = by_name.get(parent)
|
|
1094
|
+
if not isinstance(pcodec, _FrequencyCodec):
|
|
1095
|
+
raise ValueError(f"conditional parent {parent!r} of {name!r} is not an encoded "
|
|
1096
|
+
f"categorical column")
|
|
1097
|
+
cpt = np.asarray(store.get(spec.arrays["cpt"]), dtype=float)
|
|
1098
|
+
plabels = np.asarray(store.get(spec.arrays["cpt_parent_labels"])).astype(str)
|
|
1099
|
+
clabels = np.asarray(store.get(spec.arrays["cpt_child_labels"])).astype(str)
|
|
1100
|
+
if list(plabels) != list(pcodec.label_array()) \
|
|
1101
|
+
or list(clabels) != list(codec.label_array()):
|
|
1102
|
+
raise ValueError(f"conditional table labels for {name!r} do not match the "
|
|
1103
|
+
f"marginal labels")
|
|
1104
|
+
meta = {k: v for k, v in cond.items() if k not in ("kind", "parent")}
|
|
1105
|
+
codec.set_conditional(parent, cpt, plabels, meta)
|
|
1106
|
+
|
|
1107
|
+
|
|
1108
|
+
def split_specs(specs: dict[str, ModelSpec]) -> tuple[dict[str, ModelSpec],
|
|
1109
|
+
dict[str, ModelSpec]]:
|
|
1110
|
+
"""Split :meth:`MixedEncoder.to_specs` output into ``(encodings, missingness)`` both keyed
|
|
1111
|
+
by source column name (for ``manifest.model.encodings`` / ``.missingness``)."""
|
|
1112
|
+
enc: dict[str, ModelSpec] = {}
|
|
1113
|
+
miss: dict[str, ModelSpec] = {}
|
|
1114
|
+
for key, spec in specs.items():
|
|
1115
|
+
col = str(spec.params.get("column", key))
|
|
1116
|
+
(miss if spec.kind == KIND_MISSING else enc)[col] = spec
|
|
1117
|
+
return enc, miss
|