ectype-data 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. ectype/__init__.py +134 -0
  2. ectype/_version.py +5 -0
  3. ectype/authoring/__init__.py +13 -0
  4. ectype/authoring/builder.py +134 -0
  5. ectype/authoring/spec.py +555 -0
  6. ectype/calibration/__init__.py +26 -0
  7. ectype/calibration/adjustments.py +539 -0
  8. ectype/calibration/calibrator.py +781 -0
  9. ectype/cli.py +1181 -0
  10. ectype/compiler/__init__.py +1 -0
  11. ectype/compiler/plan.py +678 -0
  12. ectype/errors.py +43 -0
  13. ectype/fingerprint/__init__.py +1 -0
  14. ectype/fingerprint/comparison.py +746 -0
  15. ectype/fingerprint/container.py +408 -0
  16. ectype/fingerprint/core.py +263 -0
  17. ectype/fingerprint/disclosure.py +207 -0
  18. ectype/fingerprint/expressions.py +1317 -0
  19. ectype/fingerprint/schema.py +645 -0
  20. ectype/fingerprint/targets.py +352 -0
  21. ectype/generation/__init__.py +1 -0
  22. ectype/generation/enforce.py +163 -0
  23. ectype/generation/generator.py +525 -0
  24. ectype/generation/identifiers.py +235 -0
  25. ectype/generation/manifest.py +71 -0
  26. ectype/generation/parallel.py +229 -0
  27. ectype/io/__init__.py +16 -0
  28. ectype/io/adapters.py +224 -0
  29. ectype/io/sql.py +289 -0
  30. ectype/io/values.py +269 -0
  31. ectype/llm/__init__.py +27 -0
  32. ectype/llm/authoring.py +766 -0
  33. ectype/llm/providers.py +269 -0
  34. ectype/models/__init__.py +8 -0
  35. ectype/models/base.py +120 -0
  36. ectype/models/chain.py +2426 -0
  37. ectype/models/copulas.py +254 -0
  38. ectype/models/encoding.py +1117 -0
  39. ectype/models/forest.py +1087 -0
  40. ectype/models/marginals.py +2099 -0
  41. ectype/models/mixtures.py +336 -0
  42. ectype/models/neural/__init__.py +21 -0
  43. ectype/models/neural/adapter.py +638 -0
  44. ectype/models/neural/vae.py +432 -0
  45. ectype/models/vines.py +608 -0
  46. ectype/plugins.py +40 -0
  47. ectype/privacy/__init__.py +49 -0
  48. ectype/privacy/attacks.py +599 -0
  49. ectype/privacy/dp.py +313 -0
  50. ectype/privacy/report.py +364 -0
  51. ectype/profiler.py +783 -0
  52. ectype/profiling/__init__.py +1 -0
  53. ectype/profiling/bivariate.py +130 -0
  54. ectype/profiling/calendar.py +743 -0
  55. ectype/profiling/conditional.py +263 -0
  56. ectype/profiling/constraints.py +661 -0
  57. ectype/profiling/entity.py +1143 -0
  58. ectype/profiling/functional.py +651 -0
  59. ectype/profiling/multivariate.py +492 -0
  60. ectype/profiling/personal.py +277 -0
  61. ectype/profiling/pseudonym.py +370 -0
  62. ectype/profiling/reference.py +334 -0
  63. ectype/profiling/sketches.py +653 -0
  64. ectype/profiling/structural.py +1087 -0
  65. ectype/profiling/structure.py +1733 -0
  66. ectype/profiling/sums.py +1710 -0
  67. ectype/profiling/tolerance.py +435 -0
  68. ectype/profiling/univariate.py +555 -0
  69. ectype/py.typed +0 -0
  70. ectype/registry.py +48 -0
  71. ectype/relational/__init__.py +61 -0
  72. ectype/relational/container.py +212 -0
  73. ectype/relational/fit.py +633 -0
  74. ectype/relational/generate.py +418 -0
  75. ectype/relational/schema.py +280 -0
  76. ectype/relational/validate.py +288 -0
  77. ectype/reporting/__init__.py +439 -0
  78. ectype/reporting/adapter.py +2003 -0
  79. ectype/reporting/charts.py +964 -0
  80. ectype/reporting/drift.py +902 -0
  81. ectype/reporting/findings.py +622 -0
  82. ectype/reporting/fmt.py +429 -0
  83. ectype/reporting/render.py +1705 -0
  84. ectype/reporting/select.py +84 -0
  85. ectype/reporting/style.py +272 -0
  86. ectype/reporting/view.py +593 -0
  87. ectype/rng.py +33 -0
  88. ectype/scenarios/__init__.py +30 -0
  89. ectype/scenarios/feasibility.py +411 -0
  90. ectype/scenarios/merge.py +1392 -0
  91. ectype/scenarios/mutate.py +1613 -0
  92. ectype/temporal/__init__.py +80 -0
  93. ectype/temporal/contract.py +221 -0
  94. ectype/temporal/detect.py +431 -0
  95. ectype/temporal/events.py +946 -0
  96. ectype/temporal/panel.py +937 -0
  97. ectype/temporal/pipeline.py +192 -0
  98. ectype/temporal/regular.py +674 -0
  99. ectype/types.py +46 -0
  100. ectype/validation/__init__.py +1 -0
  101. ectype/validation/metrics/__init__.py +7 -0
  102. ectype/validation/metrics/base.py +68 -0
  103. ectype/validation/metrics/bivariate.py +353 -0
  104. ectype/validation/metrics/missingness.py +54 -0
  105. ectype/validation/metrics/multivariate.py +265 -0
  106. ectype/validation/metrics/temporal.py +596 -0
  107. ectype/validation/metrics/univariate.py +514 -0
  108. ectype/validation/report.py +627 -0
  109. ectype/validation/validator.py +707 -0
  110. ectype_data-0.1.0.dist-info/METADATA +376 -0
  111. ectype_data-0.1.0.dist-info/RECORD +115 -0
  112. ectype_data-0.1.0.dist-info/WHEEL +4 -0
  113. ectype_data-0.1.0.dist-info/entry_points.txt +2 -0
  114. ectype_data-0.1.0.dist-info/licenses/LICENSE +192 -0
  115. ectype_data-0.1.0.dist-info/licenses/NOTICE +5 -0
@@ -0,0 +1,1710 @@
1
+ """Totals and their parts (format 0.4, ADR-0014).
2
+
3
+ Tables of counts and amounts are full of sums: a population and its age bands, residents by
4
+ sex and by payer, a subtotal and its lines, percentages that add up to 100. Modeled as
5
+ separate columns the parts do not add up, and what a joint model keeps of their dependence is
6
+ far less than the arithmetic that ties them. This module finds such sums, decides which side
7
+ of each is computed, and computes it after decoding, so the sum holds on every generated row.
8
+
9
+ A sum is recorded in ``manifest.model.sums`` as a
10
+ :class:`~ectype.fingerprint.schema.SumSpec`, in one of three modes. In the first two the total
11
+ is generated first (it is modeled, or computed by another sum) and allocated to the parts by a
12
+ *composition*, a weight per part; the weights of a row are scaled to add up to 1 and the total
13
+ is allocated in whole units by the largest-remainder rule (:func:`allocate`), so parts that are
14
+ whole numbers in the source are whole numbers that add up, and a weight of zero stays a part of
15
+ zero.
16
+
17
+ ``split``
18
+ The weight of a part is its *share* of the total, a hidden column (:func:`share_name`,
19
+ ``__share__<part>``) that is modeled in place of the part: it has the marginal, the
20
+ encoding, the missingness indicator and the slot in the joint model, so the composition
21
+ keeps its dependence on every other column (a facility's payer mix depends on its type),
22
+ and the part has none. That every part scales with the total then holds by construction,
23
+ whatever the joint model keeps. Used with the chain copula for parts whose values mostly
24
+ repeat (small counts, many zeros: :data:`MIN_REPEATED`), where it was measured to help
25
+ (:meth:`_Planner.compose`).
26
+ ``scale``
27
+ The parts stay modeled columns and their decoded values are the weights: each part keeps
28
+ the model it would have without the sum (its marginal, its place in the joint model), and
29
+ the correction is small as long as the joint model holds the dependence between the parts
30
+ and the total. Used everywhere else.
31
+ ``sum``
32
+ The total is computed from its parts (``total = sum(sign * part)``) and has no marginal.
33
+ Used where a composition does not exist (a part can be negative: an allowance stored as
34
+ a negative line) or where the parts are already computed (the second margin of a two-way
35
+ table), and only when the total keeps its distribution that way
36
+ (:func:`sum_dependence`).
37
+
38
+ Detection (:func:`plan_sums`)
39
+ -----------------------------
40
+ Candidates are the numeric feature columns. A relation ``T = P1 + ... + Pk`` is *accepted*
41
+ (:class:`_Table.measure`) when
42
+
43
+ * it is supported by at least :data:`MIN_SUPPORT` rows in which the columns are present and
44
+ not all zero, and it holds on them by the rule every relationship is held to
45
+ (:mod:`ectype.profiling.tolerance`, ADR-0015): at most :data:`MAX_VIOLATION` of those rows
46
+ break it wherever they are, or up to ``tolerance.DIRTY`` of them when the rows are
47
+ isolated (not gathered in a stretch of one of its columns, in the rows where some other
48
+ numeric column is filled, which would be a part the sum leaves out, or in a category of
49
+ another column). Whole numbers must add up exactly; decimal columns that do not are given
50
+ the rounding of each term (half a unit of its last decimal), which is how published shares
51
+ add up to 99.9;
52
+ * the total takes at least :data:`MIN_TOTAL_DISTINCT` values, and the relation fails on most
53
+ rows once the total (for a constant total: the most variable part) is shuffled across rows
54
+ (:data:`MAX_SHUFFLED_HOLD`). Columns that are merely correlated, or that agree because all
55
+ of them are almost always zero, do not pass;
56
+ * at most :data:`MAX_NULL_MISMATCH` of the rows have one of its columns missing next to
57
+ another that is present (if need be with the empty cells of a column that has no zero
58
+ counted as zeros), and every part is non-zero in at least ``min_category_support`` rows.
59
+
60
+ The search is linear algebra on a row sample (:data:`SEARCH_ROWS` rows, each scaled by its
61
+ total), then an exact count on every row. For a total ``T`` the least-squares solution of
62
+ ``T = sum(beta * candidate)`` is computed; when the candidates are independent it is the
63
+ 0/1 vector of the parts. When they are not (several partitions of one total, nested totals),
64
+ the largest candidate that leaves a non-negative remainder still in the span of the others
65
+ is taken and the remainder is searched in turn (:meth:`_Search.solve`). The number of
66
+ least-squares problems per table is capped (:data:`MAX_SOLVES`).
67
+
68
+ Not every sum that holds can be computed: a column is computed once, and nothing may depend
69
+ on itself. Columns are visited as totals from the smallest to the largest
70
+ (:meth:`_Planner.visit`):
71
+
72
+ 1. **Compositions.** Every partition of the total among the columns nothing computes yet
73
+ becomes a composition (``split`` or ``scale``): several partitions of one total stay
74
+ consistent with it, and a part that was divided earlier keeps its parts (nested totals).
75
+ 2. **Sums.** A total without such a partition is expressed over the *leaves* (columns that
76
+ are not the total of an adopted sum) and computed from them: the second margin of a
77
+ two-way table, a subtotal of a statement. When several sets of leaves add up to it, the
78
+ choice waits for the end of the pass and follows the largest tree of compositions
79
+ (:meth:`_Planner.resolve`). A difference between columns that are never negative is not
80
+ computed: it could come out negative.
81
+
82
+ Then sets of columns that add up to 100 or to 1 are searched among the columns left
83
+ (:meth:`_Planner.constants`), and every total is searched once more among all columns, so
84
+ that a sum that holds and is neither adopted nor implied by the adopted ones is reported
85
+ (:meth:`_Planner.review`, ``not_enforced``). A declared sum (a confirmed hard constraint
86
+ ``total == a + b + c``, :func:`sum_form`) is adopted before any detection, in every mode but
87
+ ``"off"``; the columns of a confirmed ordering or identity are left to the transform of that
88
+ constraint.
89
+
90
+ Fit and generation
91
+ ------------------
92
+ :func:`sums_working` replaces, in the working frame the models are fitted on, each computed
93
+ column by its share (or drops it). A share is unknown where the total is null or zero; those
94
+ rows get a value drawn from the observed shares, so the share's missingness indicator means
95
+ "the part is missing although the total is present". :func:`apply_sums` computes the columns
96
+ after decoding, transforms, orderings and calendars. A part whose weight is missing is null
97
+ and keeps its mean share of the total (a suppressed cell); a total of a composition that is
98
+ below zero is raised to zero. :func:`sum_hold` counts on any table how often a recorded sum
99
+ holds (the validator's ``sums`` check).
100
+ """
101
+
102
+ from __future__ import annotations
103
+
104
+ import math
105
+ from collections.abc import Callable, Mapping, Sequence
106
+ from dataclasses import dataclass, field
107
+ from typing import TYPE_CHECKING, Any
108
+
109
+ import numpy as np
110
+ import polars as pl
111
+
112
+ from ectype.errors import FingerprintError
113
+ from ectype.fingerprint.disclosure import coarsen, resolve_policy
114
+ from ectype.fingerprint.expressions import Binary, Call, Column, Literal, Node, Unary, parse
115
+ from ectype.fingerprint.schema import (
116
+ ColumnSchema,
117
+ ConstraintSpec,
118
+ DisclosurePolicySpec,
119
+ SumSpec,
120
+ )
121
+ from ectype.io.values import column_to_values, values_to_column
122
+ from ectype.profiling import tolerance as _tolerance
123
+ from ectype.types import Enforcement, LogicalType, Role, Severity
124
+
125
+ if TYPE_CHECKING:
126
+ from ectype.profiling.structure import WorkingFrame
127
+
128
+ __all__ = [
129
+ "CONSTANTS",
130
+ "MAX_PARTS",
131
+ "MAX_SHUFFLED_HOLD",
132
+ "MAX_SOLVES",
133
+ "MAX_VIOLATION",
134
+ "MIN_REPEATED",
135
+ "MIN_SUPPORT",
136
+ "MIN_TOTAL_DISTINCT",
137
+ "MODES",
138
+ "ROUNDINGS",
139
+ "SEARCH_ROWS",
140
+ "SHARE_JOINTS",
141
+ "SHARE_PREFIX",
142
+ "allocate",
143
+ "apply_sums",
144
+ "check_sums",
145
+ "computed_columns",
146
+ "order_sums",
147
+ "plan_sums",
148
+ "scaled_columns",
149
+ "share_name",
150
+ "share_schemas",
151
+ "sum_columns",
152
+ "sum_dependence",
153
+ "sum_form",
154
+ "sum_hold",
155
+ "sum_text",
156
+ "sums_forward",
157
+ "sums_working",
158
+ ]
159
+
160
+ #: prefix of the hidden column that models the share of a part in its total
161
+ SHARE_PREFIX = "__share__"
162
+ MODES = ("split", "scale", "sum")
163
+ ROUNDINGS = ("exact", "independent")
164
+ #: largest share of the supporting rows that may break a detected sum wherever they are (the
165
+ #: shared rule of ``profiling.tolerance``, which also allows ``tolerance.DIRTY`` of isolated
166
+ #: rows)
167
+ MAX_VIOLATION = _tolerance.STRAY
168
+ #: a sum needs this many rows in which its columns are present and not all zero
169
+ MIN_SUPPORT = 30
170
+ #: a detected total takes at least this many distinct values
171
+ MIN_TOTAL_DISTINCT = 10
172
+ #: a detected sum has at most this many parts
173
+ MAX_PARTS = 48
174
+ #: at most this many partitions of one total are searched
175
+ MAX_PARTITIONS = 8
176
+ #: rows of the sample the linear search runs on (the acceptance count uses every row)
177
+ SEARCH_ROWS = 1000
178
+ #: least-squares problems solved per table, at most
179
+ MAX_SOLVES = 4000
180
+ #: ... and per search of one total
181
+ MAX_NODES = 80
182
+ #: totals of a set of shares that are searched for (percentages, proportions)
183
+ CONSTANTS = (100.0, 1.0)
184
+ #: largest share of rows in which a column of a sum is missing while another is present
185
+ MAX_NULL_MISMATCH = 0.01
186
+ #: a detected sum may hold on at most this share of the rows once its total is shuffled
187
+ MAX_SHUFFLED_HOLD = 0.2
188
+ #: a part is added to a found sum when it repairs at least this many rows that break it (and
189
+ #: at least ``min_category_support`` rows)
190
+ MIN_PART_ROWS = 3
191
+ #: with a joint model in :data:`SHARE_JOINTS`, the parts of a composition are modeled through
192
+ #: their shares (``split``) when the values of the typical part mostly repeat: among
193
+ #: :data:`SEARCH_ROWS` sampled rows, at least this share of the values of the median part
194
+ #: occur more than once. Otherwise the parts are modeled themselves and scaled to the total
195
+ #: (``scale``)
196
+ MIN_REPEATED = 0.8
197
+ #: joint models for which shares were measured to beat scaled parts on repetitive parts
198
+ SHARE_JOINTS = ("chain_copula",)
199
+ _NUMERIC = (LogicalType.CONTINUOUS, LogicalType.DISCRETE)
200
+ _REL = 1e-9
201
+
202
+
203
+ def share_name(part: str) -> str:
204
+ """Name of the hidden column that models the share of ``part`` in its total."""
205
+ return f"{SHARE_PREFIX}{part}"
206
+
207
+
208
+ def n_latents(n_parts: int) -> int:
209
+ """Shares a ``split`` of ``n_parts`` parts models: none for a copy, one for a pair (the
210
+ second part is the remainder), one per part otherwise."""
211
+ return 0 if n_parts <= 1 else (1 if n_parts == 2 else n_parts)
212
+
213
+
214
+ def computed_columns(sums: Sequence[SumSpec]) -> list[str]:
215
+ """The columns the sums compute (parts of a ``split``, the total of a ``sum``): they have
216
+ no marginal and no slot in the joint model."""
217
+ out: list[str] = []
218
+ for s in sums:
219
+ if s.mode == "split":
220
+ out += list(s.parts)
221
+ elif s.mode == "sum" and s.total:
222
+ out.append(s.total)
223
+ return out
224
+
225
+
226
+ def scaled_columns(sums: Sequence[SumSpec]) -> list[str]:
227
+ """The parts of the ``scale`` sums: modeled columns whose decoded values are scaled to add
228
+ up to their total."""
229
+ return [p for s in sums if s.mode == "scale" for p in s.parts]
230
+
231
+
232
+ def sum_columns(sums: Sequence[SumSpec]) -> list[str]:
233
+ """Every column that takes part in a sum, computed or not."""
234
+ out: dict[str, None] = {}
235
+ for s in sums:
236
+ for c in ([s.total] if s.total else []) + list(s.parts):
237
+ out[c] = None
238
+ return list(out)
239
+
240
+
241
+ def _inputs(s: SumSpec) -> list[str]:
242
+ if s.mode in ("split", "scale"):
243
+ return [s.total] if s.total else []
244
+ return list(s.parts)
245
+
246
+
247
+ def _outputs(s: SumSpec) -> list[str]:
248
+ if s.mode in ("split", "scale"):
249
+ return list(s.parts)
250
+ return [s.total] if s.total else []
251
+
252
+
253
+ def _signs(s: SumSpec) -> list[int]:
254
+ return [int(x) for x in s.signs] if s.signs else [1] * len(s.parts)
255
+
256
+
257
+ def sum_text(s: SumSpec) -> str:
258
+ """``total = a + b - c`` (or ``100 = a + b``), for messages and reports."""
259
+ terms = ""
260
+ for sign, part in zip(_signs(s), s.parts):
261
+ terms += (" - " if sign < 0 else (" + " if terms else "")) + part
262
+ left = s.total if s.total is not None else f"{float(s.constant or 0.0):g}"
263
+ return f"{left} = {terms}"
264
+
265
+
266
+ def share_schemas(sums: Sequence[SumSpec]) -> dict[str, ColumnSchema]:
267
+ """The :class:`ColumnSchema` of every hidden share column, rebuilt from the specs alone: a
268
+ ``Float64`` feature on ``[0, 1]``."""
269
+ out: dict[str, ColumnSchema] = {}
270
+ for s in sums:
271
+ for latent, part in zip(s.latents, s.parts):
272
+ out[latent] = ColumnSchema(
273
+ name=latent, logical_type=LogicalType.CONTINUOUS, role=Role.FEATURE,
274
+ physical_dtype="Float64", min_value=0.0, max_value=1.0,
275
+ notes=[f"hidden share of {part!r} in "
276
+ f"{s.total if s.total is not None else s.constant!r}"])
277
+ return out
278
+
279
+
280
+ def order_sums(sums: Sequence[SumSpec]) -> list[SumSpec]:
281
+ """Topological order (a sum after the sums that compute its inputs), stable in the given
282
+ order. Raises :class:`FingerprintError` on a cycle."""
283
+ made_by: dict[str, int] = {}
284
+ for i, s in enumerate(sums):
285
+ for c in _outputs(s):
286
+ made_by.setdefault(c, i)
287
+ out: list[SumSpec] = []
288
+ state: dict[int, int] = {}
289
+
290
+ def visit(i: int) -> None:
291
+ if state.get(i, 0) == 2:
292
+ return
293
+ if state.get(i, 0) == 1:
294
+ raise FingerprintError(f"sums form a cycle through {sum_text(sums[i])!r}")
295
+ state[i] = 1
296
+ for c in _inputs(sums[i]):
297
+ j = made_by.get(c)
298
+ if j is not None and j != i:
299
+ visit(j)
300
+ state[i] = 2
301
+ out.append(sums[i])
302
+
303
+ for i in range(len(sums)):
304
+ visit(i)
305
+ return out
306
+
307
+
308
+ def check_sums(sums: Sequence[SumSpec], schemas: Mapping[str, ColumnSchema],
309
+ computed_elsewhere: Sequence[str] = ()) -> list[str]:
310
+ """Problems with recorded sums that make a fingerprint unusable by this engine: an unknown
311
+ mode or rounding, a missing total, the wrong number of shares, unknown or non-numeric
312
+ columns, a column computed twice (by two sums, or by a sum and a transform or derived
313
+ column in ``computed_elsewhere``), or a cycle. Empty when everything is understood."""
314
+ problems: list[str] = []
315
+ made: set[str] = set(computed_elsewhere)
316
+ latents: set[str] = set()
317
+ for s in sums:
318
+ what = f"sum {sum_text(s)!r}"
319
+ if s.mode not in MODES:
320
+ problems.append(f"{what}: unknown mode {s.mode!r} (this engine supports "
321
+ f"{list(MODES)})")
322
+ continue
323
+ if s.rounding not in ROUNDINGS:
324
+ problems.append(f"{what}: unknown rounding {s.rounding!r} (this engine supports "
325
+ f"{list(ROUNDINGS)})")
326
+ if (s.total is None) == (s.constant is None):
327
+ problems.append(f"{what}: exactly one of total and constant must be given")
328
+ if s.total is None and s.mode == "sum":
329
+ problems.append(f"{what}: a sum that computes its total needs a total column")
330
+ if not s.parts or len(set(s.parts)) != len(s.parts) or s.total in s.parts:
331
+ problems.append(f"{what}: the parts must be distinct columns other than the total")
332
+ continue
333
+ if s.signs and (len(s.signs) != len(s.parts) or any(x not in (1, -1) for x in s.signs)):
334
+ problems.append(f"{what}: signs must be 1 or -1, one per part")
335
+ if s.decimals is not None and (isinstance(s.decimals, bool) or s.decimals < 0):
336
+ problems.append(f"{what}: decimals must be null or a non-negative integer")
337
+ if not (math.isfinite(s.tolerance) and s.tolerance >= 0):
338
+ problems.append(f"{what}: tolerance must be a non-negative number")
339
+ names = ([s.total] if s.total is not None else []) + list(s.parts)
340
+ for name in names:
341
+ col = schemas.get(name)
342
+ if col is None:
343
+ problems.append(f"{what}: unknown column {name!r}")
344
+ elif col.logical_type not in _NUMERIC:
345
+ problems.append(f"{what}: column {name!r} is not numeric")
346
+ if any(c not in names for c in s.zero_as_null):
347
+ problems.append(f"{what}: zero_as_null names a column that is not in the sum")
348
+ if s.mode == "scale":
349
+ if any(x < 0 for x in _signs(s)):
350
+ problems.append(f"{what}: the parts of a scaled sum cannot be subtracted")
351
+ if s.latents:
352
+ problems.append(f"{what}: only a split has share columns")
353
+ if s.fallback and (len(s.fallback) != len(s.parts)
354
+ or any(not (math.isfinite(x) and x >= 0) for x in s.fallback)):
355
+ problems.append(f"{what}: fallback must be one non-negative weight per part")
356
+ elif s.mode == "split":
357
+ if any(x < 0 for x in _signs(s)):
358
+ problems.append(f"{what}: the parts of a split cannot be subtracted")
359
+ want = n_latents(len(s.parts))
360
+ if len(s.latents) != want:
361
+ problems.append(f"{what}: a split of {len(s.parts)} part(s) has {want} "
362
+ f"share column(s), got {len(s.latents)}")
363
+ for latent in s.latents:
364
+ if (not latent.startswith(SHARE_PREFIX) or latent in schemas
365
+ or latent in latents):
366
+ problems.append(f"{what}: share column name {latent!r} must be unique, "
367
+ f"start with {SHARE_PREFIX!r} and not name a source column")
368
+ latents.add(latent)
369
+ if s.fallback and (len(s.fallback) != len(s.parts)
370
+ or any(not (math.isfinite(x) and x >= 0) for x in s.fallback)):
371
+ problems.append(f"{what}: fallback must be one non-negative weight per part")
372
+ elif s.latents:
373
+ problems.append(f"{what}: only a split has share columns")
374
+ for c in _outputs(s):
375
+ if c in made:
376
+ problems.append(f"{what}: column {c!r} is computed more than once")
377
+ made.add(c)
378
+ if not problems:
379
+ try:
380
+ order_sums(sums)
381
+ except FingerprintError as exc:
382
+ problems.append(str(exc))
383
+ return problems
384
+
385
+
386
+ # ---------------------------------------------------------------------------------------------
387
+ # Value-space application
388
+ # ---------------------------------------------------------------------------------------------
389
+
390
+
391
+ def allocate(total: np.ndarray, weights: np.ndarray, decimals: int) -> np.ndarray:
392
+ """Split each ``total`` over the columns of ``weights`` (rows that add up to 1) in whole
393
+ units of ``10 ** -decimals``, by the largest-remainder rule: every part gets the whole
394
+ units of its exact share and the units left go to the largest fractional parts (ties to
395
+ the earlier part). The parts of a row add up to its total exactly, a weight of zero gets
396
+ nothing, and a negative total is allocated as its absolute value with the sign put back.
397
+ A row whose total is NaN is NaN."""
398
+ total = np.asarray(total, dtype=np.float64)
399
+ w = np.asarray(weights, dtype=np.float64)
400
+ out = np.full(w.shape, np.nan)
401
+ ok = np.isfinite(total)
402
+ if not ok.any():
403
+ return out
404
+ scale = 10.0 ** int(decimals)
405
+ units = np.rint(total[ok] * scale)
406
+ mag = np.abs(units)
407
+ raw = mag[:, None] * w[ok]
408
+ base = np.floor(raw + 1e-9)
409
+ left = np.clip(np.rint(mag - base.sum(axis=1)), 0, w.shape[1])
410
+ frac = raw - base
411
+ order = np.argsort(-frac, axis=1, kind="stable")
412
+ rank = np.empty_like(order)
413
+ np.put_along_axis(rank, order, np.broadcast_to(np.arange(w.shape[1]), order.shape), axis=1)
414
+ out[ok] = (base + (rank < left[:, None])) * np.sign(units)[:, None] / scale
415
+ return out
416
+
417
+
418
+ def _numbers(df: pl.DataFrame, name: str, schemas: Mapping[str, ColumnSchema]) -> np.ndarray:
419
+ col = schemas.get(name)
420
+ s = df.get_column(name)
421
+ if col is None or col.logical_type not in _NUMERIC:
422
+ return np.asarray(s.cast(pl.Float64, strict=False).fill_null(np.nan).to_numpy(),
423
+ dtype=np.float64)
424
+ return np.asarray(column_to_values(s, col), dtype=np.float64)
425
+
426
+
427
+ def _total_values(df: pl.DataFrame, s: SumSpec, schemas: Mapping[str, ColumnSchema]
428
+ ) -> np.ndarray:
429
+ if s.total is None:
430
+ return np.full(df.height, float(s.constant or 0.0))
431
+ t = _numbers(df, s.total, schemas)
432
+ if s.total in s.zero_as_null:
433
+ t = np.where(np.isnan(t), 0.0, t)
434
+ return t
435
+
436
+
437
+ def _part_values(df: pl.DataFrame, s: SumSpec, schemas: Mapping[str, ColumnSchema]
438
+ ) -> np.ndarray:
439
+ cols = []
440
+ for part in s.parts:
441
+ p = _numbers(df, part, schemas)
442
+ if part in s.zero_as_null:
443
+ p = np.where(np.isnan(p), 0.0, p)
444
+ cols.append(p)
445
+ return np.column_stack(cols) if cols else np.zeros((df.height, 0))
446
+
447
+
448
+ def _weights(df: pl.DataFrame, s: SumSpec) -> tuple[np.ndarray, np.ndarray]:
449
+ """The weights of a split's parts on each row (rows add up to 1) and the mask of the
450
+ parts that are missing (their share is null)."""
451
+ n, k = df.height, len(s.parts)
452
+ if s.mode == "scale":
453
+ shares = np.column_stack([
454
+ np.asarray(df.get_column(c).cast(pl.Float64, strict=False).fill_null(np.nan)
455
+ .to_numpy(), dtype=np.float64) for c in s.parts])
456
+ missing = np.isnan(shares)
457
+ for j, part in enumerate(s.parts):
458
+ if part in s.zero_as_null:
459
+ missing[:, j] = False
460
+ shares = np.where(np.isnan(shares) & ~missing, 0.0, shares)
461
+ elif k == 1:
462
+ return np.ones((n, 1)), np.zeros((n, 1), dtype=bool)
463
+ else:
464
+ shares = np.column_stack([
465
+ np.asarray(df.get_column(c).cast(pl.Float64).fill_null(np.nan).to_numpy(),
466
+ dtype=np.float64) for c in s.latents])
467
+ missing = np.isnan(shares)
468
+ fb = np.asarray(s.fallback if len(s.fallback) == k else np.full(k, 1.0 / k),
469
+ dtype=np.float64)
470
+ fb = fb / fb.sum() if fb.sum() > 0 else np.full(k, 1.0 / k)
471
+ if k == 2 and s.mode == "split":
472
+ first = np.clip(np.where(missing[:, 0], fb[0], shares[:, 0]), 0.0, 1.0)
473
+ return np.column_stack([first, 1.0 - first]), np.column_stack(
474
+ [missing[:, 0], np.zeros(n, dtype=bool)])
475
+ w = np.clip(np.where(missing, 0.0, shares), 0.0, None)
476
+ tot = w.sum(axis=1)
477
+ empty = tot <= 0
478
+ if empty.any():
479
+ alt = np.where(missing[empty], 0.0, fb[None, :])
480
+ flat = alt.sum(axis=1) <= 0
481
+ alt[flat] = np.where(missing[empty][flat], 0.0, 1.0)
482
+ w[empty] = alt
483
+ tot = w.sum(axis=1)
484
+ with np.errstate(invalid="ignore", divide="ignore"):
485
+ w = np.where(tot[:, None] > 0, w / tot[:, None], 0.0)
486
+ # a missing part (a suppressed cell) holds its mean share of the total: the parts that
487
+ # are present add up to the rest
488
+ hidden = np.where(missing, fb[None, :], 0.0)
489
+ held = np.minimum(hidden.sum(axis=1), 0.9)
490
+ partial = missing.any(axis=1) & ~missing.all(axis=1)
491
+ if partial.any():
492
+ scale = np.where(hidden.sum(axis=1) > 0, held / np.maximum(hidden.sum(axis=1), 1e-300),
493
+ 0.0)
494
+ w[partial] = (w[partial] * (1.0 - held[partial])[:, None]
495
+ + hidden[partial] * scale[partial][:, None])
496
+ return w, missing
497
+
498
+
499
+ def _split_values(df: pl.DataFrame, s: SumSpec, schemas: Mapping[str, ColumnSchema]
500
+ ) -> np.ndarray:
501
+ t = _total_values(df, s, schemas)
502
+ w, missing = _weights(df, s)
503
+ if s.rounding == "exact" and s.decimals is not None:
504
+ vals = allocate(t, w, int(s.decimals))
505
+ else:
506
+ vals = t[:, None] * w
507
+ vals[missing] = np.nan
508
+ # every part of a row is missing (all shares null): nothing was allocated
509
+ vals[missing.all(axis=1)] = np.nan
510
+ return vals
511
+
512
+
513
+ def _floor_total(df: pl.DataFrame, s: SumSpec, schemas: Mapping[str, ColumnSchema]
514
+ ) -> pl.DataFrame:
515
+ """The total of a composition is never negative (its parts are not): a generated total
516
+ below zero, which the target of a ``difference`` transform can be, is raised to zero."""
517
+ if s.total is None or s.total not in df.columns:
518
+ return df
519
+ t = _numbers(df, s.total, schemas)
520
+ with np.errstate(invalid="ignore"):
521
+ low = t < 0
522
+ if not low.any():
523
+ return df
524
+ return df.with_columns(values_to_column(np.where(low, 0.0, t), schemas[s.total])
525
+ .alias(s.total))
526
+
527
+
528
+ def apply_sums(df: pl.DataFrame, sums: Sequence[SumSpec],
529
+ schemas: Mapping[str, ColumnSchema]) -> pl.DataFrame:
530
+ """Compute what each sum computes, in the given (topological) order: the parts of a
531
+ ``split`` from its total and the hidden shares, the parts of a ``scale`` from its total
532
+ and their own decoded values, the total of a ``sum`` from its parts. A column that is
533
+ already in ``df`` (other than the parts of a ``scale``), or whose inputs are not, is left
534
+ alone; the hidden share columns are kept (drop them by name, as
535
+ ``StructuredEncoder.decode`` does). The total of a composition that is below zero is
536
+ raised to zero first, unless a ``sum`` computes it (it is then what its parts add up to,
537
+ and is allocated with its sign)."""
538
+ added_up = {s.total for s in sums if s.mode == "sum"}
539
+ for s in sums:
540
+ if s.mode != "sum" and s.total not in added_up:
541
+ df = _floor_total(df, s, schemas)
542
+ for s in sums:
543
+ if s.mode == "sum":
544
+ if s.total is None or s.total in df.columns or \
545
+ any(p not in df.columns for p in s.parts):
546
+ continue
547
+ vals = _part_values(df, s, schemas) @ np.asarray(_signs(s), dtype=np.float64)
548
+ if s.decimals is not None:
549
+ vals = np.round(vals, int(s.decimals))
550
+ if s.total in s.zero_as_null:
551
+ vals = np.where(vals == 0, np.nan, vals)
552
+ df = df.with_columns(values_to_column(vals, schemas[s.total]).alias(s.total))
553
+ continue
554
+ needed = list(s.latents) + ([s.total] if s.total is not None else [])
555
+ if s.mode == "scale":
556
+ # the decoded parts are the weights: scaled in place (a no-op once they add up)
557
+ if any(c not in df.columns for c in [*needed, *s.parts]):
558
+ continue
559
+ elif all(p in df.columns for p in s.parts) or any(c not in df.columns for c in needed):
560
+ continue
561
+ if s.total not in added_up:
562
+ df = _floor_total(df, s, schemas)
563
+ vals = _split_values(df, s, schemas)
564
+ new = []
565
+ for j, part in enumerate(s.parts):
566
+ if part in df.columns and s.mode != "scale":
567
+ continue
568
+ v = vals[:, j]
569
+ if part in s.zero_as_null:
570
+ v = np.where(v == 0, np.nan, v)
571
+ new.append(values_to_column(v, schemas[part]).alias(part))
572
+ df = df.with_columns(new)
573
+ return df
574
+
575
+
576
+ def sums_forward(df: pl.DataFrame, sums: Sequence[SumSpec],
577
+ schemas: Mapping[str, ColumnSchema]
578
+ ) -> tuple[pl.DataFrame, dict[str, np.ndarray]]:
579
+ """Add every hidden share ``part / total`` as a ``Float64`` column, clipped to ``[0, 1]``
580
+ and null where the part is null. Where the total is null or zero the share is unknown: it
581
+ is null too, and the returned masks (per share column) mark those rows."""
582
+ unknown: dict[str, np.ndarray] = {}
583
+ new = []
584
+ for s in sums:
585
+ if s.mode != "split" or not s.latents:
586
+ continue
587
+ have = s.total is None or s.total in df.columns
588
+ t = _total_values(df, s, schemas) if have else np.full(df.height, np.nan)
589
+ known = np.isfinite(t) & (t != 0)
590
+ for latent, part in zip(s.latents, s.parts):
591
+ if part in df.columns:
592
+ p = _numbers(df, part, schemas)
593
+ if part in s.zero_as_null:
594
+ p = np.where(np.isnan(p), 0.0, p)
595
+ else:
596
+ p = np.full(df.height, np.nan)
597
+ with np.errstate(invalid="ignore", divide="ignore"):
598
+ share = np.where(known, np.clip(p / np.where(known, t, 1.0), 0.0, 1.0), np.nan)
599
+ unknown[latent] = ~known
600
+ new.append(pl.Series(latent, share, dtype=pl.Float64).fill_nan(None))
601
+ return (df.with_columns(new) if new else df), unknown
602
+
603
+
604
+ def sums_working(working: WorkingFrame, df: pl.DataFrame, sums: Sequence[SumSpec],
605
+ schemas: Mapping[str, ColumnSchema], seed: int = 0) -> WorkingFrame:
606
+ """The working frame of ``profiling.structure.working_frame`` with the sums applied: every
607
+ computed column is replaced in place by its hidden share, or dropped when it has none. In
608
+ ``encoded`` a share that is unknown (total null or zero) gets a value drawn from the
609
+ observed shares, so that only a part that is missing next to a present total counts as a
610
+ missing share."""
611
+ from ectype.profiling.structure import WorkingFrame
612
+ from ectype.rng import stream
613
+
614
+ if not sums:
615
+ return working
616
+ made = set(computed_columns(sums))
617
+ latent_of = {part: latent for s in sums for latent, part in zip(s.latents, s.parts)}
618
+ lat = share_schemas(sums)
619
+ shares, unknown = sums_forward(df.select(sum_columns(sums)), sums, schemas)
620
+ frame = working.frame.with_columns([shares.get_column(c) for c in lat])
621
+ encoded = working.encoded
622
+ filled = []
623
+ stats: dict[str, tuple[bool, float]] = {}
624
+ for name in lat:
625
+ vals = np.asarray(shares.get_column(name).fill_null(np.nan).to_numpy(), dtype=np.float64)
626
+ obs = vals[np.isfinite(vals)]
627
+ fill = unknown[name] & ~np.isfinite(vals)
628
+ if fill.any() and obs.size:
629
+ rng = stream(seed, "sums", "fill", name)
630
+ vals = vals.copy()
631
+ vals[fill] = rng.choice(obs, size=int(fill.sum()), replace=True)
632
+ nulls = int(np.isnan(vals).sum())
633
+ stats[name] = (nulls > 0, float(nulls / max(df.height, 1)))
634
+ filled.append(pl.Series(name, vals, dtype=pl.Float64).fill_nan(None))
635
+ encoded = encoded.with_columns(filled)
636
+ columns: list[ColumnSchema] = []
637
+ for c in working.columns:
638
+ if c.name not in made:
639
+ columns.append(c)
640
+ elif c.name in latent_of:
641
+ name = latent_of[c.name]
642
+ columns.append(lat[name].model_copy(update={
643
+ "nullable": stats[name][0], "null_fraction": stats[name][1]}))
644
+ drop = [c for c in made if c in frame.columns]
645
+ return WorkingFrame(frame.drop(drop), encoded.drop([c for c in made if c in encoded.columns]),
646
+ columns, working.clamped)
647
+
648
+
649
+ def sum_hold(df: pl.DataFrame, s: SumSpec, schemas: Mapping[str, ColumnSchema]
650
+ ) -> tuple[int, int]:
651
+ """``(rows, holding)``: the rows of ``df`` in which every column of the sum is present
652
+ (an empty cell of a ``zero_as_null`` column is a zero) and not all are zero, and how many
653
+ of them satisfy ``abs(total - sum(parts)) <= tolerance``. ``(0, 0)`` when a column is not
654
+ in ``df``."""
655
+ names = ([s.total] if s.total is not None else []) + list(s.parts)
656
+ if any(c not in df.columns for c in names):
657
+ return 0, 0
658
+ t = _total_values(df, s, schemas)
659
+ parts = _part_values(df, s, schemas)
660
+ with np.errstate(invalid="ignore"):
661
+ resid = t - parts @ np.asarray(_signs(s), dtype=np.float64)
662
+ complete = np.isfinite(resid)
663
+ active = complete & ((t != 0) | (parts != 0).any(axis=1))
664
+ size = np.abs(t) + np.abs(parts).sum(axis=1)
665
+ ok = np.abs(resid) <= float(s.tolerance) + _REL * np.where(complete, size, 0.0)
666
+ return int(active.sum()), int((active & ok).sum())
667
+
668
+
669
+ def sum_dependence(parts: np.ndarray, signs: Sequence[int], total: np.ndarray,
670
+ rng: np.random.Generator | None = None) -> dict[str, float]:
671
+ """What computing ``total = sum(sign * part)`` would do to the total's distribution.
672
+
673
+ A total that is computed has no marginal: it is whatever the generated parts add up to,
674
+ and the dependence between the parts is left to the joint model. Parts that move together
675
+ add up to the right total. A total that is a small difference of large parts (a margin),
676
+ or that is empty exactly when all its parts are, comes out wrong by whatever the joint
677
+ model misses.
678
+
679
+ As :func:`~ectype.profiling.structure.gap_dependence` does for a difference, the parts are
680
+ given the dependence rank correlations can carry (a Gaussian copula fitted to their normal
681
+ scores), drawn anew with their own values, and added up; ``target_ks`` is the
682
+ Kolmogorov-Smirnov distance between those totals and the real ones, and ``limit`` the
683
+ largest distance with which the sum is computed
684
+ (:func:`~ectype.profiling.structure.target_ks_limit`). Rows with a NaN are ignored (pass
685
+ zeros for the empty cells that stand for zero)."""
686
+ from scipy import special
687
+
688
+ from ectype.profiling.structure import (
689
+ DEPENDENCE_MAX_ROWS,
690
+ _ks_distance,
691
+ _normal_scores,
692
+ target_ks_limit,
693
+ )
694
+
695
+ rng = np.random.default_rng(0) if rng is None else rng
696
+ P = np.asarray(parts, dtype=np.float64)
697
+ t = np.asarray(total, dtype=np.float64)
698
+ ok = np.isfinite(t) & np.isfinite(P).all(axis=1)
699
+ P, t = P[ok], t[ok]
700
+ if t.size > DEPENDENCE_MAX_ROWS // 2:
701
+ keep = np.sort(rng.choice(t.size, size=DEPENDENCE_MAX_ROWS // 2, replace=False))
702
+ P, t = P[keep], t[keep]
703
+ n, k = P.shape
704
+ out = {"rows": float(n), "target_ks": 0.0, "limit": target_ks_limit(n)}
705
+ if n < 3 or k < 2:
706
+ return out
707
+ Z = np.column_stack([_normal_scores(P[:, j], rng) for j in range(k)])
708
+ corr = np.nan_to_num(np.corrcoef(Z, rowvar=False), nan=0.0)
709
+ np.fill_diagonal(corr, 1.0)
710
+ values, vectors = np.linalg.eigh(corr)
711
+ root = vectors * np.sqrt(np.clip(values, 0.0, None))
712
+ ordered = np.sort(P, axis=0)
713
+ weights = np.asarray(signs, dtype=np.float64)
714
+ rebuilt = []
715
+ for _ in range(2):
716
+ u = special.ndtr(rng.standard_normal((n, k)) @ root.T)
717
+ idx = np.minimum((u * n).astype(np.int64), n - 1)
718
+ rebuilt.append(np.take_along_axis(ordered, idx, axis=0) @ weights)
719
+ out["target_ks"] = _ks_distance(t, np.concatenate(rebuilt))
720
+ return out
721
+
722
+
723
+ # ---------------------------------------------------------------------------------------------
724
+ # Declared sums
725
+ # ---------------------------------------------------------------------------------------------
726
+
727
+
728
+ def _terms(node: Node, sign: int = 1) -> list[tuple[int, str]] | None:
729
+ """The signed columns of a chain ``a + b - c``; ``None`` when ``node`` is anything else."""
730
+ if isinstance(node, Column):
731
+ return [(sign, node.name)]
732
+ if isinstance(node, Unary) and node.op == "-":
733
+ return _terms(node.operand, -sign)
734
+ if isinstance(node, Binary) and node.op in ("+", "-"):
735
+ left = _terms(node.left, sign)
736
+ right = _terms(node.right, sign if node.op == "+" else -sign)
737
+ if left is None or right is None:
738
+ return None
739
+ return left + right
740
+ return None
741
+
742
+
743
+ def _number(node: Node) -> float | None:
744
+ if isinstance(node, Literal) and node.kind in ("int", "float"):
745
+ return float(node.value) # type: ignore[arg-type]
746
+ return None
747
+
748
+
749
+ def sum_form(node: Node | str) -> tuple[str | None, float | None, list[tuple[int, str]]] | None:
750
+ """``(total, constant, [(sign, part), ...])`` when ``node`` declares a sum: a column or a
751
+ number on one side of ``==`` and a chain of added and subtracted columns on the other
752
+ (``total == a + b + c``, ``a + b + c == 100``), or the tolerance form
753
+ ``abs(total - (a + b + c)) <= tol``. Needs at least three distinct columns in all, or two
754
+ for a constant total: ``c == a + b`` between three columns is the ``identity`` transform of
755
+ ADR-0005. ``None`` otherwise."""
756
+ if isinstance(node, str):
757
+ node = parse(node)
758
+ sides: list[tuple[Node, Node]] = []
759
+ if isinstance(node, Binary) and node.op == "==":
760
+ sides = [(node.left, node.right), (node.right, node.left)]
761
+ elif isinstance(node, Binary) and node.op in ("<=", "<") and _number(node.right) is not None:
762
+ lhs = node.left
763
+ if isinstance(lhs, Call) and lhs.name == "abs" and len(lhs.args) == 1:
764
+ inner = lhs.args[0]
765
+ if isinstance(inner, Binary) and inner.op == "-":
766
+ sides = [(inner.left, inner.right), (inner.right, inner.left)]
767
+ for head, chain in sides:
768
+ terms = _terms(chain)
769
+ if terms is None or len({name for _, name in terms}) != len(terms):
770
+ continue
771
+ constant = _number(head)
772
+ if isinstance(head, Column) and head.name not in {n for _, n in terms} \
773
+ and len(terms) >= 3:
774
+ return head.name, None, terms
775
+ if constant is not None and len(terms) >= 2 and all(s > 0 for s, _ in terms):
776
+ return None, constant, terms
777
+ return None
778
+
779
+
780
+ # ---------------------------------------------------------------------------------------------
781
+ # Detection
782
+ # ---------------------------------------------------------------------------------------------
783
+
784
+
785
+ @dataclass
786
+ class _Relation:
787
+ total: int | None # column index; None for a constant total
788
+ constant: float | None
789
+ parts: list[int]
790
+ signs: list[int]
791
+ stats: dict[str, Any] = field(default_factory=dict)
792
+ mode: str = ""
793
+ source: str = "detected"
794
+ constraint: str | None = None
795
+
796
+
797
+ class _Table:
798
+ """The numeric feature columns of a table as a matrix, with what the search needs to know
799
+ about each."""
800
+
801
+ def __init__(self, df: pl.DataFrame, columns: Sequence[ColumnSchema],
802
+ exclude: Sequence[str], policy: DisclosurePolicySpec | None = None) -> None:
803
+ skip = set(exclude)
804
+ self.schemas = {c.name: c for c in columns}
805
+ self.context = _tolerance.Context(df, columns, policy)
806
+ self.names = [c.name for c in columns
807
+ if c.name in df.columns and c.name not in skip
808
+ and not c.name.startswith("__") and c.role == Role.FEATURE
809
+ and c.logical_type in _NUMERIC]
810
+ self.index = {name: j for j, name in enumerate(self.names)}
811
+ self.n = df.height
812
+ p = len(self.names)
813
+ self.V = np.empty((self.n, p), dtype=np.float64)
814
+ for j, name in enumerate(self.names):
815
+ self.V[:, j] = _numbers(df, name, self.schemas)
816
+ self.null = np.isnan(self.V)
817
+ self.X = np.where(self.null, 0.0, self.V)
818
+ present = np.maximum((~self.null).sum(axis=0), 1)
819
+ #: mean absolute value, an empty cell counted as zero: totals are visited in this order
820
+ self.size = np.abs(self.X).mean(axis=0) if self.n else np.zeros(p)
821
+ self.nonneg = (self.X < 0).sum(axis=0) <= _tolerance.STRAY * present
822
+ zeros = ((self.X == 0) & ~self.null).sum(axis=0)
823
+ #: a column with empty cells and no zero: an empty cell may stand for zero
824
+ self.blank = (self.null.sum(axis=0) > 0) & (zeros == 0)
825
+ self.distinct = np.array([np.unique(self.V[~self.null[:, j], j]).size
826
+ for j in range(p)], dtype=int)
827
+ self.integer = np.array([bool(self.schemas[c].integer_valued) for c in self.names])
828
+ self.decimals: list[int | None] = [
829
+ 0 if self.schemas[c].integer_valued else self.schemas[c].decimals
830
+ for c in self.names]
831
+
832
+ def unit(self, j: int) -> float:
833
+ d = self.decimals[j]
834
+ return 0.0 if d is None else 10.0 ** -d
835
+
836
+ def isolation(self, broken: np.ndarray, active: np.ndarray, cols: Sequence[int]
837
+ ) -> Callable[[], _tolerance.Isolation]:
838
+ """The test of where the rows that break a sum over ``cols`` are, for
839
+ ``tolerance.judge``: in a stretch of one of its own columns, in the rows where
840
+ another numeric column of the table is filled (a part the sum leaves out), in a
841
+ category or a stretch of another column of the table, or scattered."""
842
+ def test() -> _tolerance.Isolation:
843
+ own = [self.names[j] for j in cols]
844
+ others = [j for j in range(len(self.names)) if j not in set(cols)]
845
+ filled = (self.X[:, others] != 0) if others else None
846
+ return self.context.scattered(
847
+ broken, own, scope=active,
848
+ ranges={self.names[j]: self.V[:, j] for j in cols},
849
+ flags=None if filled is None else (
850
+ [f"the rows in which {self.names[j]!r} is filled" for j in others],
851
+ filled))
852
+ return test
853
+
854
+ def measure(self, total: int | None, constant: float | None, parts: Sequence[int],
855
+ signs: Sequence[int], rng: np.random.Generator | None = None
856
+ ) -> dict[str, Any]:
857
+ """How well ``total = sum(sign * part)`` holds on every row: under the convention that
858
+ an empty cell is missing, and, when too many rows are incomplete that way, under the
859
+ convention that an empty cell of a column without zeros is a zero. The first that
860
+ leaves few incomplete rows is reported. With ``rng`` (a detected sum) the rows that
861
+ break it are judged by the shared rule and the coincidence guard runs; without it (a
862
+ declared sum) they are only counted."""
863
+ cols = list(parts) + ([total] if total is not None else [])
864
+ best: dict[str, Any] = {}
865
+ for zero in (False, True):
866
+ if zero and not self.blank[cols].any():
867
+ break
868
+ blank = [j for j in cols if zero and self.blank[j]]
869
+ null = self.null[:, cols].copy()
870
+ for i, j in enumerate(cols):
871
+ if j in blank:
872
+ null[:, i] = False
873
+ scope = ~self.null[:, cols].all(axis=1)
874
+ complete = ~null.any(axis=1) & scope
875
+ incomplete = float((scope & ~complete).sum() / max(int(scope.sum()), 1))
876
+ P = self.X[:, list(parts)]
877
+ t = self.X[:, total] if total is not None else np.full(self.n, float(constant or 0))
878
+ resid = t - P @ np.asarray(signs, dtype=np.float64)
879
+ active = complete & ((t != 0) | (P != 0).any(axis=1))
880
+ support = int(active.sum())
881
+ size = np.abs(t) + np.abs(P).sum(axis=1)
882
+ exact = np.abs(resid) <= _REL * size
883
+ limit = int(math.floor(MAX_VIOLATION * support))
884
+ out: dict[str, Any] = {
885
+ "support": support, "incomplete": incomplete, "limit": limit,
886
+ "zero_as_null": blank, "rounding": "exact", "tolerance": 0.0,
887
+ "violations": int((active & ~exact).sum())}
888
+ holds = exact
889
+ whole = all(self.integer[j] for j in cols)
890
+ if out["violations"] > limit and (not whole or total is None):
891
+ tol = 0.5 * sum(self.unit(j) for j in cols)
892
+ if tol > 0:
893
+ near = np.abs(resid) <= tol * (1 + 1e-9) + _REL * size
894
+ out.update(rounding="independent", tolerance=tol,
895
+ violations=int((active & ~near).sum()))
896
+ holds = near
897
+ out["negative"] = int((active & holds & ((P < 0).any(axis=1) | (t < 0))).sum())
898
+ fits = support >= MIN_SUPPORT and incomplete <= MAX_NULL_MISMATCH
899
+ broken = active & ~holds
900
+ verdict = _tolerance.judge(
901
+ out["violations"], support,
902
+ self.isolation(broken, active, cols) if fits and rng is not None else None)
903
+ out["verdict"] = verdict
904
+ out["accepted"] = fits and verdict.holds
905
+ if out["accepted"] and rng is not None:
906
+ # the coincidence guard: shuffle the total (or the most variable part)
907
+ idx = np.flatnonzero(active)
908
+ moved = total if total is not None else int(
909
+ parts[int(np.argmax(self.X[np.ix_(idx, list(parts))].std(axis=0)))])
910
+ perm = rng.permutation(idx)
911
+ delta = self.X[perm, moved] - self.X[idx, moved]
912
+ shifted = resid[idx] + (delta if total is not None else -delta)
913
+ tol = float(out["tolerance"])
914
+ again = np.abs(shifted) <= tol * (1 + 1e-9) + _REL * size[idx]
915
+ out["shuffled_hold"] = float(again.mean()) if idx.size else 1.0
916
+ out["accepted"] = out["shuffled_hold"] <= MAX_SHUFFLED_HOLD
917
+ if out["accepted"] or not best:
918
+ best = out
919
+ if out["accepted"] or incomplete <= MAX_NULL_MISMATCH:
920
+ break
921
+ return best
922
+
923
+
924
+ class _Search:
925
+ """The linear search for the parts of one total on a row sample (rows scaled by the
926
+ total)."""
927
+
928
+ def __init__(self, table: _Table, rows: np.ndarray, target: np.ndarray, slack: float,
929
+ budget: list[int]) -> None:
930
+ scale = np.maximum(np.abs(target), 1e-300)
931
+ self.A = table.X[rows] / scale[:, None]
932
+ self.y = target / scale
933
+ #: per-row tolerance in scaled units (float error, and rounding for decimal columns)
934
+ self.tol = 1e-7 + slack / scale
935
+ self.size = np.abs(self.A).mean(axis=0)
936
+ self.budget = budget
937
+ self.nodes = MAX_NODES
938
+ self.kept: np.ndarray | None = None
939
+
940
+ def fit(self, y: np.ndarray, cand: Sequence[int]) -> np.ndarray | None:
941
+ """Least-squares coefficients of ``y`` on the candidates when ``y`` is in their span
942
+ on all but a few rows of the sample (dirty rows are trimmed twice), else ``None``."""
943
+ if not cand or self.budget[0] <= 0:
944
+ return None
945
+ M = self.A[:, list(cand)]
946
+ # columns on one scale: a candidate far larger than the total must not cost digits
947
+ width = np.maximum(np.abs(M).max(axis=0), 1e-300)
948
+ M = M / width
949
+ keep = np.ones(y.size, dtype=bool)
950
+ for attempt in range(3):
951
+ self.budget[0] -= 1
952
+ beta = np.linalg.lstsq(M[keep], y[keep], rcond=1e-10)[0]
953
+ res = np.abs(M @ beta - y)
954
+ if not (res[keep] > 3 * self.tol[keep]).any():
955
+ self.kept = keep
956
+ return np.asarray(beta / width, dtype=np.float64)
957
+ if attempt == 2 or int(keep.sum()) < 4 * max(len(cand), 10):
958
+ break
959
+ cut = np.quantile(res[keep], 0.98)
960
+ keep &= res < cut
961
+ return None
962
+
963
+ def dominated(self, y: np.ndarray, cand: Sequence[int]) -> list[int]:
964
+ """The candidates that fit inside a non-negative remainder on almost every row."""
965
+ out = []
966
+ for c in cand:
967
+ x = self.A[:, c]
968
+ if np.mean((x < -self.tol) | (x > y + self.tol)) <= 0.01:
969
+ out.append(c)
970
+ return out
971
+
972
+ def solve(self, y: np.ndarray, cand: Sequence[int]) -> list[int] | None:
973
+ """Columns among ``cand`` that add up to ``y`` (all non-negative): the least-squares
974
+ solution when it is a 0/1 vector; otherwise the largest candidate that leaves a
975
+ remainder the others can still make up, and the solution of that remainder."""
976
+ if self.nodes <= 0:
977
+ return None
978
+ self.nodes -= 1
979
+ beta = self.fit(y, cand)
980
+ if beta is None:
981
+ return None
982
+ r = np.rint(beta)
983
+ if np.all(np.abs(beta - r) <= 0.1) and np.all((r == 0) | (r == 1)) and r.sum() >= 1:
984
+ return [c for c, v in zip(cand, r) if v == 1]
985
+ if not self.reachable(y, cand):
986
+ return None
987
+ left = sorted(cand, key=lambda c: (-self.size[c], c))
988
+ for c in list(left):
989
+ rest = y - self.A[:, c]
990
+ left.remove(c)
991
+ if np.mean(rest < -self.tol) > 0.01:
992
+ continue
993
+ if np.mean(np.abs(rest) <= self.tol) >= 0.99:
994
+ return [c]
995
+ sol = self.solve(rest, self.dominated(rest, left))
996
+ if sol is not None:
997
+ return [c, *sol]
998
+ if self.nodes <= 0 or self.fit(y, left) is None:
999
+ return None
1000
+ return None
1001
+
1002
+ def integral(self, cand: Sequence[int], beta: np.ndarray) -> list[tuple[int, int]] | None:
1003
+ """``[(column, sign)]`` when ``beta`` is a vector of 0, +1 and -1."""
1004
+ r = np.rint(beta)
1005
+ if np.all(np.abs(beta - r) <= 0.1) and np.all(np.abs(r) <= 1) and np.any(r != 0):
1006
+ return [(c, int(v)) for c, v in zip(cand, r) if v != 0]
1007
+ return None
1008
+
1009
+ def signed(self, cand: Sequence[int]) -> list[tuple[int, int]] | None:
1010
+ """``[(column, sign)]`` when the least-squares solution over ``cand`` is a vector of
1011
+ 0, +1 and -1."""
1012
+ beta = self.fit(self.y, cand)
1013
+ return None if beta is None else self.integral(cand, beta)
1014
+
1015
+ def reachable(self, y: np.ndarray, cand: Sequence[int]) -> bool:
1016
+ """Whether ``y`` is a non-negative combination of the candidates on the rows the last
1017
+ fit kept (a remainder that needs a column subtracted is a dead end)."""
1018
+ from scipy.optimize import nnls
1019
+
1020
+ if not cand or self.budget[0] <= 0:
1021
+ return False
1022
+ self.budget[0] -= 1
1023
+ keep = self.kept if self.kept is not None and self.kept.size == y.size else slice(None)
1024
+ M = self.A[:, list(cand)][keep]
1025
+ width = np.maximum(np.abs(M).max(axis=0), 1e-300)
1026
+ try:
1027
+ beta, _ = nnls(M / width, y[keep], maxiter=20 * len(cand) + 50)
1028
+ except RuntimeError:
1029
+ return True
1030
+ res = np.abs((M / width) @ beta - y[keep])
1031
+ return bool(np.mean(res > 3 * self.tol[keep]) <= 0.01)
1032
+
1033
+
1034
+ class _Planner:
1035
+ def __init__(self, df: pl.DataFrame, columns: Sequence[ColumnSchema],
1036
+ policy: DisclosurePolicySpec, exclude: Sequence[str], seed: int,
1037
+ joint: str | None = None) -> None:
1038
+ from ectype.rng import stream
1039
+
1040
+ self.joint = joint
1041
+ self.table = _Table(df, columns, exclude, policy)
1042
+ self.policy = policy
1043
+ self.seed = int(seed)
1044
+ self.stream = stream
1045
+ self.budget = [MAX_SOLVES]
1046
+ self.adopted: list[_Relation] = []
1047
+ self.producer: dict[int, int] = {} # column -> index of the relation computing it
1048
+ self.deps: dict[int, set[int]] = {} # column -> the columns it is computed from
1049
+ self.totals: set[int] = set() # totals of adopted relations
1050
+ self.used: set[int] = set() # columns of adopted constant sums
1051
+ self.reserved: set[int] = set() # totals waiting for resolve()
1052
+ self.claimed: set[int] = set() # modeled by a confirmed ordering or identity
1053
+ #: (total, relation, ambiguous): sums that wait for the end of the main pass
1054
+ self.pending: list[tuple[int, _Relation, bool]] = []
1055
+ self.rejected: list[dict[str, Any]] = []
1056
+ self.not_enforced: list[dict[str, Any]] = []
1057
+ self.reported: set[tuple[int, ...]] = set() # canonical forms in not_enforced
1058
+ self.refused: set[tuple[int, ...]] = set() # canonical forms in rejected
1059
+
1060
+ # -- graph --------------------------------------------------------------------------------
1061
+ def depends_on(self, x: int, y: int) -> bool:
1062
+ stack, seen = [x], {x}
1063
+ while stack:
1064
+ for dep in self.deps.get(stack.pop(), ()):
1065
+ if dep == y:
1066
+ return True
1067
+ if dep not in seen:
1068
+ seen.add(dep)
1069
+ stack.append(dep)
1070
+ return False
1071
+
1072
+ def descendants(self, root: int) -> set[int]:
1073
+ """Columns computed (directly or not) from ``root`` by a split."""
1074
+ out: set[int] = set()
1075
+ stack = [root]
1076
+ while stack:
1077
+ node = stack.pop()
1078
+ for rel in self.adopted:
1079
+ if rel.mode == "split" and rel.total == node:
1080
+ for part in rel.parts:
1081
+ if part not in out:
1082
+ out.add(part)
1083
+ stack.append(part)
1084
+ return out
1085
+
1086
+ def implied(self, rel: _Relation) -> bool:
1087
+ """Whether ``rel`` is a linear consequence of the adopted sums."""
1088
+ rows = [self.vector(r) for r in self.adopted if r.total is not None]
1089
+ if not rows or rel.total is None:
1090
+ return False
1091
+ base = np.vstack(rows)
1092
+ return bool(np.linalg.matrix_rank(np.vstack([base, self.vector(rel)]))
1093
+ == np.linalg.matrix_rank(base))
1094
+
1095
+ def vector(self, rel: _Relation) -> np.ndarray:
1096
+ v = np.zeros(len(self.table.names))
1097
+ if rel.total is not None:
1098
+ v[rel.total] = 1.0
1099
+ for sign, part in zip(rel.signs, rel.parts):
1100
+ v[part] -= sign
1101
+ return v
1102
+
1103
+ # -- adoption -----------------------------------------------------------------------------
1104
+ def describe(self, rel: _Relation) -> str:
1105
+ names = self.table.names
1106
+ terms = ""
1107
+ for sign, part in zip(rel.signs, rel.parts):
1108
+ terms += (" - " if sign < 0 else (" + " if terms else "")) + names[part]
1109
+ left = names[rel.total] if rel.total is not None else f"{float(rel.constant or 0):g}"
1110
+ return f"{left} = {terms}"
1111
+
1112
+ def record(self, rel: _Relation) -> dict[str, Any]:
1113
+ st = rel.stats
1114
+ out: dict[str, Any] = {
1115
+ "sum": self.describe(rel), "source": rel.source, "parts": len(rel.parts),
1116
+ "support": int(st.get("support", 0)),
1117
+ "violation_rate": coarsen(st.get("violations", 0) / max(st.get("support", 0), 1),
1118
+ self.policy)}
1119
+ verdict = st.get("verdict")
1120
+ if verdict is not None and rel.source != "confirmed":
1121
+ judged = verdict.record(self.policy)
1122
+ out["tolerance"] = judged["tolerance"]
1123
+ if "isolation" in judged:
1124
+ out["isolation"] = judged["isolation"]
1125
+ if rel.constraint is not None:
1126
+ out["constraint"] = rel.constraint
1127
+ if st.get("rounding") == "independent":
1128
+ out["tolerance"] = float(st.get("tolerance", 0.0))
1129
+ if st.get("zero_as_null"):
1130
+ out["zero_as_null"] = [self.table.names[j] for j in st["zero_as_null"]]
1131
+ if "shuffled_hold" in st:
1132
+ out["shuffled_hold_rate"] = coarsen(float(st["shuffled_hold"]), self.policy)
1133
+ if "repeated" in st:
1134
+ out["repeated_values"] = coarsen(float(st["repeated"]), self.policy)
1135
+ if "target_ks" in st:
1136
+ out["target_ks"] = coarsen(float(st["target_ks"]), self.policy)
1137
+ return out
1138
+
1139
+ def can_split(self, rel: _Relation) -> str | None:
1140
+ """Why ``rel`` cannot be a split (``None`` when it can)."""
1141
+ t = self.table
1142
+ if any(s < 0 for s in rel.signs):
1143
+ return "a part is subtracted"
1144
+ cols = list(rel.parts) + ([rel.total] if rel.total is not None else [])
1145
+ if not all(t.nonneg[j] for j in cols) or \
1146
+ rel.stats.get("negative", 0) > rel.stats.get("limit", 0):
1147
+ return "a column takes negative values"
1148
+ if any(p in self.producer or p in self.used for p in rel.parts):
1149
+ return "a part is already computed"
1150
+ if any(p in self.claimed for p in rel.parts):
1151
+ return "a part is modeled by a confirmed constraint"
1152
+ if rel.total is not None and any(self.depends_on(rel.total, p) or p == rel.total
1153
+ for p in rel.parts):
1154
+ return "the total is computed from a part"
1155
+ return None
1156
+
1157
+ def can_sum(self, rel: _Relation) -> str | None:
1158
+ if rel.total is None:
1159
+ return "the total is a constant"
1160
+ if rel.total in self.producer or rel.total in self.used:
1161
+ return "the total is already computed"
1162
+ if rel.total in self.claimed:
1163
+ return "the total is modeled by a confirmed constraint"
1164
+ if any(self.depends_on(p, rel.total) or p == rel.total for p in rel.parts):
1165
+ return "a part is computed from the total"
1166
+ return None
1167
+
1168
+ def distorted(self, rel: _Relation) -> str | None:
1169
+ """Why the total of a detected sum is not computed from its parts although it could
1170
+ be: added up from parts that keep only their rank correlations it would not have its
1171
+ own distribution (:func:`sum_dependence`). ``None`` when it would."""
1172
+ if rel.total is None or rel.source == "confirmed" or len(rel.parts) < 2:
1173
+ return None
1174
+ t = self.table
1175
+ cols = [rel.total, *rel.parts]
1176
+ blank = set(rel.stats.get("zero_as_null", []))
1177
+ V = np.column_stack([t.X[:, j] if j in blank else t.V[:, j] for j in cols])
1178
+ dep = sum_dependence(V[:, 1:], rel.signs, V[:, 0],
1179
+ self.stream(self.seed, "sums", "dependence", t.names[rel.total]))
1180
+ rel.stats["target_ks"] = dep["target_ks"]
1181
+ if dep["target_ks"] <= dep["limit"]:
1182
+ return None
1183
+ return (f"added up from separately modeled parts the total would be distorted "
1184
+ f"(Kolmogorov-Smirnov distance {dep['target_ks']:.3f} to its own "
1185
+ f"distribution, limit {dep['limit']:.3f})")
1186
+
1187
+ def adopt(self, rel: _Relation, mode: str) -> None:
1188
+ rel.mode = mode
1189
+ k = len(self.adopted)
1190
+ self.adopted.append(rel)
1191
+ if rel.total is not None:
1192
+ self.totals.add(rel.total)
1193
+ if mode == "split":
1194
+ for part in rel.parts:
1195
+ self.producer[part] = k
1196
+ self.deps[part] = {rel.total} if rel.total is not None else set()
1197
+ if rel.total is None:
1198
+ self.used.update(rel.parts)
1199
+ else:
1200
+ assert rel.total is not None
1201
+ self.producer[rel.total] = k
1202
+ self.deps[rel.total] = set(rel.parts)
1203
+
1204
+ # -- search -------------------------------------------------------------------------------
1205
+ def search(self, t: int | None, constant: float | None = None) -> _Search | None:
1206
+ table = self.table
1207
+ name = table.names[t] if t is not None else f"={constant:g}"
1208
+ rng = self.stream(self.seed, "sums", "rows", name)
1209
+ if t is not None:
1210
+ rows = np.flatnonzero(~table.null[:, t] & (table.X[:, t] != 0))
1211
+ else:
1212
+ rows = np.arange(table.n)
1213
+ if rows.size < MIN_SUPPORT:
1214
+ return None
1215
+ if rows.size > SEARCH_ROWS:
1216
+ rows = np.sort(rng.choice(rows, size=SEARCH_ROWS, replace=False))
1217
+ target = table.X[rows, t] if t is not None else np.full(rows.size, float(constant or 0))
1218
+ # rounding slack: a few units of the last decimal of a total that has decimals, or
1219
+ # of the coarsest column for a constant total
1220
+ if t is None:
1221
+ slack = min(4.0 * max((table.unit(j) for j in range(len(table.names))),
1222
+ default=0.0), 0.05 * float(constant or 0.0))
1223
+ else:
1224
+ slack = 0.0 if table.integer[t] else 4.0 * table.unit(t)
1225
+ return _Search(table, rows, target, slack, self.budget)
1226
+
1227
+ def complete(self, rel: _Relation, cand: Sequence[int]) -> None:
1228
+ """Add the parts the row sample could not show: a candidate that is zero on most rows
1229
+ and repairs the rows in which the found parts fall short of the total."""
1230
+ t = self.table
1231
+ if rel.total is None or t.decimals[rel.total] is None:
1232
+ return
1233
+ total = t.X[:, rel.total]
1234
+ for _ in range(MAX_PARTS):
1235
+ resid = total - t.X[:, rel.parts] @ np.asarray(rel.signs, dtype=np.float64)
1236
+ ok = ~t.null[:, rel.total]
1237
+ short = ok & (np.abs(resid) > _REL * np.abs(total))
1238
+ if int(short.sum()) < max(MIN_PART_ROWS, self.policy.min_category_support):
1239
+ return
1240
+ best, gain = None, 0
1241
+ for c in cand:
1242
+ if c in rel.parts or c == rel.total:
1243
+ continue
1244
+ x = t.X[:, c]
1245
+ fixed = int((short & (x != 0) & (np.abs(resid - x) <= _REL * np.abs(total))
1246
+ ).sum())
1247
+ broken = int((ok & ~short & (x != 0)).sum())
1248
+ if fixed - broken > gain and fixed >= max(MIN_PART_ROWS,
1249
+ self.policy.min_category_support):
1250
+ best, gain = c, fixed - broken
1251
+ if best is None:
1252
+ return
1253
+ rel.parts.append(best)
1254
+ rel.signs.append(1)
1255
+
1256
+ def accept(self, rel: _Relation, quiet: bool = False) -> bool:
1257
+ t = self.table
1258
+ name = t.names[rel.total] if rel.total is not None else "constant"
1259
+ # a part stands for at least min_category_support rows; a rarer one is left out and
1260
+ # its rows count as rows that break the sum
1261
+ keep = [i for i, j in enumerate(rel.parts)
1262
+ if int((t.X[:, j] != 0).sum()) >= self.policy.min_category_support]
1263
+ if not keep:
1264
+ return False
1265
+ if len(keep) < len(rel.parts):
1266
+ rel.parts = [rel.parts[i] for i in keep]
1267
+ rel.signs = [rel.signs[i] for i in keep]
1268
+ rel.stats = t.measure(rel.total, rel.constant, rel.parts, rel.signs,
1269
+ self.stream(self.seed, "sums", "shuffle", name))
1270
+ if not rel.stats.get("accepted") or len(rel.parts) > MAX_PARTS:
1271
+ st = rel.stats
1272
+ verdict = st.get("verdict")
1273
+ if not quiet and st.get("support", 0) >= MIN_SUPPORT and \
1274
+ st.get("violations", 0) <= _tolerance.NEAR_MISS * st.get("support", 0):
1275
+ why = (f"holds on a shuffled total in {st['shuffled_hold']:.0%} of the rows"
1276
+ if st.get("shuffled_hold", 0) > MAX_SHUFFLED_HOLD else
1277
+ f"{st.get('incomplete', 0):.1%} of the rows have a column missing"
1278
+ if st.get("incomplete", 0) > MAX_NULL_MISMATCH else
1279
+ verdict.reason("break it") if verdict is not None
1280
+ and not verdict.holds else
1281
+ f"{len(rel.parts)} parts (at most {MAX_PARTS})")
1282
+ key = self.canonical(rel)
1283
+ if key not in self.refused: # once, from whichever column it was found
1284
+ self.refused.add(key)
1285
+ self.rejected.append({**self.record(rel), "reason": why})
1286
+ return False
1287
+ return True
1288
+
1289
+ def eligible_total(self, t: int) -> bool:
1290
+ table = self.table
1291
+ return bool(table.distinct[t] >= MIN_TOTAL_DISTINCT
1292
+ and int((~table.null[:, t]).sum()) >= MIN_SUPPORT)
1293
+
1294
+ def free(self, t: int) -> list[int]:
1295
+ """Columns a split of ``t`` may compute: nothing computes them yet, and ``t`` is not
1296
+ computed from them."""
1297
+ table = self.table
1298
+ return [c for c in range(len(table.names))
1299
+ if c != t and c not in self.producer and c not in self.used
1300
+ and c not in self.reserved and c not in self.claimed and table.nonneg[c]
1301
+ and not self.depends_on(t, c)]
1302
+
1303
+ def leaves(self, t: int) -> list[int]:
1304
+ """Columns a sum for ``t`` may add up: not the total of an adopted sum, not waiting to
1305
+ become one, and not computed from ``t``."""
1306
+ own = self.descendants(t)
1307
+ return [c for c in range(len(self.table.names))
1308
+ if c != t and c not in self.totals and c not in own and c not in self.used
1309
+ and c not in self.reserved and not self.depends_on(c, t)]
1310
+
1311
+ def root(self, c: int) -> int:
1312
+ seen = {c}
1313
+ while c in self.producer and self.adopted[self.producer[c]].mode == "split":
1314
+ parent = self.adopted[self.producer[c]].total
1315
+ if parent is None or parent in seen:
1316
+ break
1317
+ seen.add(parent)
1318
+ c = parent
1319
+ return c
1320
+
1321
+ def remainder(self, rel: _Relation) -> bool:
1322
+ """``T = A - B - ...``: the sum ``A = T + B + ...`` seen from one of its parts."""
1323
+ return sum(s > 0 for s in rel.signs) == 1 and len(rel.parts) > 1
1324
+
1325
+ def visit(self, t: int) -> None:
1326
+ """The main pass for the column ``t`` as a total (columns are visited from the
1327
+ smallest to the largest).
1328
+
1329
+ (a) Every partition of ``t`` among the columns nothing computes yet becomes a split.
1330
+ (b) Otherwise ``t`` is expressed over the leaves and computed from them: at once when
1331
+ the expression over the smaller leaves is unique; after the pass (:meth:`resolve`)
1332
+ when it is not, so that it can follow the largest tree of splits, or when it needs a
1333
+ larger column (a difference such as net income)."""
1334
+ table = self.table
1335
+ if t in self.used or not self.eligible_total(t):
1336
+ return
1337
+ search = self.search(t)
1338
+ if search is None:
1339
+ return
1340
+ if table.nonneg[t]:
1341
+ free = self.free(t)
1342
+ cand = search.dominated(search.y, [c for c in free if search.size[c] > 0])
1343
+ for _ in range(MAX_PARTITIONS):
1344
+ search.nodes = MAX_NODES
1345
+ sol = search.solve(search.y, cand)
1346
+ if sol is None:
1347
+ break
1348
+ rel = _Relation(t, None, list(sol), [1] * len(sol))
1349
+ self.complete(rel, free)
1350
+ if self.accept(rel) and self.can_split(rel) is None:
1351
+ self.adopt(rel, "split")
1352
+ cand = [c for c in cand if c not in rel.parts]
1353
+ else:
1354
+ # drop the largest part of the failed solution and look again
1355
+ cand = [c for c in cand if c != sol[0]]
1356
+ if t in self.producer or t in self.claimed:
1357
+ return
1358
+ leaves = [c for c in self.leaves(t) if search.size[c] > 0]
1359
+ small = [c for c in leaves if table.size[c] <= 1.05 * table.size[t]]
1360
+ beta = search.fit(search.y, small)
1361
+ if beta is not None:
1362
+ found = search.integral(small, beta)
1363
+ if found is None:
1364
+ # not unique. When some set of leaves does add up to t, t waits for the trees
1365
+ # of splits to be complete (resolve) and is nobody's part meanwhile
1366
+ if table.nonneg[t]:
1367
+ search.nodes = MAX_NODES
1368
+ plain = [c for c in small if table.nonneg[c]]
1369
+ sol = search.solve(search.y, search.dominated(search.y, plain))
1370
+ if sol is not None:
1371
+ rel = _Relation(t, None, list(sol), [1] * len(sol))
1372
+ if self.accept(rel, quiet=True):
1373
+ self.reserved.add(t)
1374
+ self.pending.append((t, rel, True))
1375
+ return
1376
+ rel = _Relation(t, None, [c for c, _ in found], [s for _, s in found])
1377
+ if all(s > 0 for s in rel.signs):
1378
+ self.complete(rel, [c for c in small if table.nonneg[c]])
1379
+ elif len(rel.parts) == 1:
1380
+ return
1381
+ elif table.nonneg[t]:
1382
+ # a column that is never negative, computed by a subtraction: wait, a larger
1383
+ # total may turn out to be split into it
1384
+ self.pending.append((t, rel, False))
1385
+ return
1386
+ if self.accept(rel):
1387
+ self.try_sum(rel)
1388
+ return
1389
+ found = search.signed(leaves)
1390
+ if found is not None and len(found) > 1:
1391
+ rel = _Relation(t, None, [c for c, _ in found], [s for _, s in found])
1392
+ if self.remainder(rel) or table.nonneg[t]:
1393
+ self.pending.append((t, rel, False))
1394
+ elif self.accept(rel):
1395
+ self.try_sum(rel)
1396
+
1397
+ def try_sum(self, rel: _Relation, why: str | None = None) -> None:
1398
+ """Compute the total of ``rel`` from its parts when that is possible and leaves the
1399
+ total its distribution; otherwise report the sum as not enforced, unless the adopted
1400
+ sums imply it."""
1401
+ why = why or self.can_sum(rel) or self.distorted(rel)
1402
+ if why is None:
1403
+ self.adopt(rel, "sum")
1404
+ elif not self.implied(rel):
1405
+ key = self.canonical(rel)
1406
+ if key not in self.reported:
1407
+ self.reported.add(key)
1408
+ self.not_enforced.append({**self.record(rel), "reason": why})
1409
+
1410
+ def resolve(self) -> None:
1411
+ """After the main pass: the totals whose expression over the leaves was not unique
1412
+ follow the largest tree of splits that can express them; the differences are adopted
1413
+ unless another sum already states them."""
1414
+ table = self.table
1415
+ for t, rel, ambiguous in self.pending:
1416
+ if ambiguous:
1417
+ self.reserved.discard(t)
1418
+ search = self.search(t)
1419
+ if search is None or t in self.producer:
1420
+ continue
1421
+ leaves = [c for c in self.leaves(t) if search.size[c] > 0
1422
+ and table.size[c] <= 1.05 * table.size[t]]
1423
+ roots = sorted({self.root(c) for c in leaves if c in self.producer},
1424
+ key=lambda r: (-len(self.descendants(r)), r))
1425
+ for root in roots:
1426
+ below = self.descendants(root)
1427
+ tree = [c for c in leaves if c in below]
1428
+ if len(tree) < 2 or search.fit(search.y, tree) is None:
1429
+ continue
1430
+ search.nodes = MAX_NODES
1431
+ sol = search.solve(search.y, search.dominated(
1432
+ search.y, [c for c in tree if table.nonneg[c]]))
1433
+ if sol is not None:
1434
+ inside = _Relation(t, None, list(sol), [1] * len(sol))
1435
+ if self.accept(inside, quiet=True):
1436
+ rel = inside
1437
+ break
1438
+ self.try_sum(rel)
1439
+ continue
1440
+ if t in self.producer or self.implied(rel) or not self.accept(rel):
1441
+ continue
1442
+ why = None
1443
+ if all(table.nonneg[j] for j in [t, *rel.parts]):
1444
+ why = ("a difference between columns that are never negative: computed from "
1445
+ "separately generated columns it could be negative")
1446
+ self.try_sum(rel, why)
1447
+
1448
+ def canonical(self, rel: _Relation) -> tuple[int, ...]:
1449
+ """The relation as a signed column vector, the same whichever of its columns it was
1450
+ found from."""
1451
+ v = self.vector(rel)
1452
+ first = int(np.flatnonzero(v)[0]) if np.any(v) else 0
1453
+ return tuple(int(x) for x in (v if v[first] > 0 else -v))
1454
+
1455
+ def review(self) -> None:
1456
+ """Look once more for a partition of every total among all smaller columns, computed
1457
+ or not: a sum that holds in the source and is neither adopted nor a consequence of
1458
+ the adopted sums is reported (``not_enforced``)."""
1459
+ table = self.table
1460
+ known = {(r.total, frozenset(r.parts)) for r in self.adopted}
1461
+ for t in sorted(range(len(table.names)), key=lambda j: (table.size[j], j)):
1462
+ if not table.nonneg[t] or not self.eligible_total(t) or t in self.used:
1463
+ continue
1464
+ search = self.search(t)
1465
+ if search is None:
1466
+ continue
1467
+ cand = [c for c in range(len(table.names))
1468
+ if c != t and table.nonneg[c] and search.size[c] > 0 and c not in self.used]
1469
+ search.nodes = MAX_NODES
1470
+ sol = search.solve(search.y, search.dominated(search.y, cand))
1471
+ if sol is None or (t, frozenset(sol)) in known:
1472
+ continue
1473
+ rel = _Relation(t, None, list(sol), [1] * len(sol))
1474
+ if self.accept(rel, quiet=True) and not self.implied(rel) \
1475
+ and self.canonical(rel) not in self.reported:
1476
+ self.reported.add(self.canonical(rel))
1477
+ why = self.can_split(rel) or "its columns are computed by other sums"
1478
+ self.not_enforced.append({**self.record(rel), "reason": why})
1479
+
1480
+ def constants(self) -> None:
1481
+ """Sets of columns that add up to 100 or to 1, among the columns left."""
1482
+ table = self.table
1483
+ for constant in CONSTANTS:
1484
+ free = [c for c in range(len(table.names))
1485
+ if c not in self.producer and c not in self.totals and c not in self.used
1486
+ and c not in self.claimed and table.nonneg[c] and table.distinct[c] >= 3
1487
+ and not (constant == 1.0 and table.integer[c])
1488
+ and float(np.quantile(table.X[~table.null[:, c], c], 0.995)
1489
+ if (~table.null[:, c]).any() else 0.0) <= constant * 1.005]
1490
+ if len(free) < 2:
1491
+ continue
1492
+ search = self.search(None, constant)
1493
+ if search is None:
1494
+ continue
1495
+ cand = search.dominated(search.y, [c for c in free if search.size[c] > 0])
1496
+ for _ in range(MAX_PARTITIONS):
1497
+ search.nodes = MAX_NODES
1498
+ sol = search.solve(search.y, cand) if len(cand) >= 2 else None
1499
+ if sol is None:
1500
+ break
1501
+ rel = _Relation(None, constant, list(sol), [1] * len(sol))
1502
+ if len(sol) >= 2 and self.accept(rel) and self.can_split(rel) is None:
1503
+ self.adopt(rel, "split")
1504
+ cand = [c for c in cand if c not in rel.parts]
1505
+ else:
1506
+ cand = [c for c in cand if c != sol[0]]
1507
+
1508
+ def declared(self, constraints: Sequence[ConstraintSpec]) -> list[dict[str, Any]]:
1509
+ """Adopt the sums the user declared (confirmed hard constraints)."""
1510
+ skipped: list[dict[str, Any]] = []
1511
+ table = self.table
1512
+ for spec in constraints:
1513
+ if spec.severity != Severity.HARD or spec.enforcement == Enforcement.NONE:
1514
+ continue
1515
+ try:
1516
+ form = sum_form(spec.expression)
1517
+ except Exception: # noqa: BLE001 - invalid expressions are reported elsewhere
1518
+ continue
1519
+ if form is None:
1520
+ continue
1521
+ total, constant, terms = form
1522
+ names = ([total] if total is not None else []) + [name for _, name in terms]
1523
+ rec = {"sum": spec.expression, "source": "confirmed", "constraint": spec.id}
1524
+ missing = [c for c in names if c not in table.index]
1525
+ if missing:
1526
+ skipped.append({**rec, "reason": f"column(s) {missing} cannot take part (not "
1527
+ f"numeric feature columns)"})
1528
+ continue
1529
+ rel = _Relation(table.index[total] if total is not None else None, constant,
1530
+ [table.index[name] for _, name in terms],
1531
+ [sign for sign, _ in terms], source="confirmed",
1532
+ constraint=spec.id)
1533
+ rel.stats = table.measure(rel.total, rel.constant, rel.parts, rel.signs)
1534
+ # a declared sum holds exactly: its constraint is checked on every generated row
1535
+ rel.stats.update(rounding="exact", tolerance=0.0)
1536
+ if self.can_split(rel) is None:
1537
+ self.adopt(rel, "split")
1538
+ elif self.can_sum(rel) is None:
1539
+ self.adopt(rel, "sum")
1540
+ elif self.implied(rel):
1541
+ skipped.append({**rec, "reason": "holds by construction through other sums"})
1542
+ else:
1543
+ skipped.append({**rec, "reason": f"cannot be computed ("
1544
+ f"{self.can_split(rel)}; {self.can_sum(rel)})"
1545
+ f": enforced by rejection"})
1546
+ return skipped
1547
+
1548
+ # -- output -------------------------------------------------------------------------------
1549
+ def compose(self, rel: _Relation) -> str:
1550
+ """How the parts of a composition are modeled.
1551
+
1552
+ ``"scale"`` (the parts themselves, scaled to the total) keeps for every part the model
1553
+ it would have without the sum, and is the rule. ``"split"`` (their shares of the
1554
+ total, in their place) is used where it was measured to do better: for a joint model
1555
+ in :data:`SHARE_JOINTS` (or an unknown one, ``joint=None``), when the values of the
1556
+ median part mostly repeat (:data:`MIN_REPEATED`). A copy is always a split: it needs
1557
+ no share."""
1558
+ if len(rel.parts) < 2:
1559
+ return "split"
1560
+ if self.joint is not None and self.joint not in SHARE_JOINTS:
1561
+ return "scale"
1562
+ table = self.table
1563
+ rng = self.stream(self.seed, "sums", "repeated", self.describe(rel))
1564
+ shares = []
1565
+ for j in rel.parts:
1566
+ values = table.V[~table.null[:, j], j]
1567
+ if values.size > SEARCH_ROWS:
1568
+ values = rng.choice(values, size=SEARCH_ROWS, replace=False)
1569
+ _, counts = np.unique(values, return_counts=True)
1570
+ shares.append(float(counts[counts >= 2].sum() / max(values.size, 1)))
1571
+ rel.stats["repeated"] = float(np.median(shares))
1572
+ return "split" if rel.stats["repeated"] >= MIN_REPEATED else "scale"
1573
+
1574
+ def spec(self, rel: _Relation) -> SumSpec:
1575
+ t = self.table
1576
+ names = t.names
1577
+ parts = [names[j] for j in rel.parts]
1578
+ total = names[rel.total] if rel.total is not None else None
1579
+ decs = {t.decimals[j] for j in rel.parts}
1580
+ tdec = t.decimals[rel.total] if rel.total is not None else None
1581
+ rounding = str(rel.stats.get("rounding", "exact"))
1582
+ fallback: list[float] = []
1583
+ latents: list[str] = []
1584
+ if rel.mode == "split":
1585
+ # exact allocation needs one unit for every part, no finer than the total's
1586
+ dec = next(iter(decs)) if len(decs) == 1 else None
1587
+ if dec is None or (rel.total is not None and (tdec is None or tdec > dec)) or \
1588
+ (rel.constant is not None
1589
+ and abs(rel.constant * 10 ** dec - round(rel.constant * 10 ** dec)) > 1e-9):
1590
+ dec = None
1591
+ if dec is None and rel.total is not None and len(decs) == 1 \
1592
+ and next(iter(decs)) is None and tdec is None:
1593
+ rounding = "exact" # floats: the parts are total * share
1594
+ elif dec is None and rounding == "exact" and rel.source != "confirmed":
1595
+ rounding = "independent"
1596
+ mode = self.compose(rel)
1597
+ if mode == "split":
1598
+ latents = [share_name(p) for p in parts[:n_latents(len(parts))]]
1599
+ if len(parts) >= 2:
1600
+ tot = t.X[:, rel.total] if rel.total is not None else np.full(
1601
+ t.n, float(rel.constant or 0))
1602
+ ok = np.isfinite(tot) & (tot > 0)
1603
+ with np.errstate(invalid="ignore", divide="ignore"):
1604
+ mean = (t.X[np.ix_(ok, rel.parts)] / tot[ok, None]).mean(axis=0) \
1605
+ if ok.any() else np.ones(len(parts))
1606
+ fallback = [max(coarsen(float(x), self.policy), 0.0) for x in mean]
1607
+ else:
1608
+ dec = tdec
1609
+ mode = rel.mode
1610
+ tolerance = float(rel.stats.get("tolerance", 0.0))
1611
+ if rounding == "independent" and tolerance == 0.0:
1612
+ tolerance = 0.5 * sum(t.unit(j) for j in rel.parts)
1613
+ return SumSpec(
1614
+ total=total, constant=rel.constant, parts=parts,
1615
+ signs=list(rel.signs) if any(s < 0 for s in rel.signs) else [],
1616
+ mode=mode, latents=latents, decimals=dec, rounding=rounding,
1617
+ tolerance=tolerance,
1618
+ zero_as_null=[names[j] for j in rel.stats.get("zero_as_null", [])],
1619
+ fallback=fallback, source=rel.source, constraint=rel.constraint)
1620
+
1621
+
1622
+ def _claimed(constraints: Sequence[ConstraintSpec]) -> list[str]:
1623
+ """Columns of the confirmed hard constraints that state an ordering or an identity
1624
+ (``a <= b``, ``c == a * b``, ``c == a + b``). The transform of that constraint models them
1625
+ (ADR-0005, ADR-0009), so a detected sum neither computes nor scales them; they can still
1626
+ be the total of a composition or a part of a computed total."""
1627
+ from ectype.fingerprint.expressions import referenced_columns
1628
+ from ectype.profiling.structure import identity_form, ordering_form
1629
+
1630
+ out: dict[str, None] = {}
1631
+ for spec in constraints:
1632
+ if spec.severity != Severity.HARD or spec.enforcement == Enforcement.NONE:
1633
+ continue
1634
+ try:
1635
+ node = parse(spec.expression)
1636
+ except Exception: # noqa: BLE001 - invalid expressions are reported elsewhere
1637
+ continue
1638
+ if sum_form(node) is None and (identity_form(node) is not None
1639
+ or ordering_form(node) is not None):
1640
+ for name in sorted(referenced_columns(node)):
1641
+ out[name] = None
1642
+ return list(out)
1643
+
1644
+
1645
+ def plan_sums(df: pl.DataFrame, columns: Sequence[ColumnSchema],
1646
+ policy: DisclosurePolicySpec | str | None,
1647
+ confirmed_constraints: Sequence[ConstraintSpec] = (), mode: str = "auto",
1648
+ exclude: Sequence[str] = (), seed: int = 0, joint: str | None = None
1649
+ ) -> tuple[list[SumSpec], dict[str, Any]]:
1650
+ """The sums of a source table that are computed at generation, in the order they run, and
1651
+ a JSON-safe record of what was adopted (``applied``), what was found but cannot be computed
1652
+ next to the adopted sums (``not_enforced``), and the near misses (``not_selected``).
1653
+
1654
+ ``mode`` ``"off"`` plans nothing; ``"confirmed"`` adopts the declared sums only (hard
1655
+ constraints of the form :func:`sum_form` accepts); ``"auto"`` also searches the table (see
1656
+ the module docstring). ``exclude`` names columns that take no part (user-derived and
1657
+ computed columns). The columns of a confirmed ordering or identity are modeled by the
1658
+ transform of that constraint: a detected sum neither computes nor scales them. ``seed``
1659
+ keys the row samples and the shuffles. ``joint`` is the kind of the joint model the
1660
+ columns will be given to; it decides how a composition is modeled
1661
+ (:meth:`_Planner.compose`)."""
1662
+ pol = resolve_policy(policy)
1663
+ diag: dict[str, Any] = {"mode": mode, "applied": [], "not_enforced": [], "not_selected": [],
1664
+ "skipped": []}
1665
+ if mode == "off":
1666
+ return [], diag
1667
+ planner = _Planner(df, columns, pol, exclude, seed, joint)
1668
+ diag["skipped"] = planner.declared(confirmed_constraints)
1669
+ table = planner.table
1670
+ planner.claimed = {table.index[c] for c in _claimed(confirmed_constraints)
1671
+ if c in table.index}
1672
+ if mode == "auto" and len(table.names) >= 2 and table.n >= MIN_SUPPORT:
1673
+ for t in sorted(range(len(table.names)), key=lambda j: (table.size[j], j)):
1674
+ planner.visit(t)
1675
+ planner.resolve()
1676
+ planner.constants()
1677
+ planner.review()
1678
+ diag["thresholds"] = {
1679
+ "max_violation_rate": MAX_VIOLATION, **_tolerance.thresholds(),
1680
+ "min_support": MIN_SUPPORT,
1681
+ "min_total_distinct": MIN_TOTAL_DISTINCT, "max_parts": MAX_PARTS,
1682
+ "max_shuffled_hold_rate": MAX_SHUFFLED_HOLD, "search_rows": SEARCH_ROWS,
1683
+ "max_solves": MAX_SOLVES}
1684
+ diag["searched"] = {"columns": len(table.names),
1685
+ "least_squares_problems": MAX_SOLVES - planner.budget[0],
1686
+ "budget_exhausted": planner.budget[0] <= 0}
1687
+ specs = [planner.spec(rel) for rel in planner.adopted]
1688
+ by_text = {sum_text(s): rel for s, rel in zip(specs, planner.adopted)}
1689
+ ordered = order_sums(specs)
1690
+ notes: dict[str, str] = {}
1691
+ for s in ordered:
1692
+ rel = by_text[sum_text(s)]
1693
+ rec = {**planner.record(rel), "mode": s.mode, "rounding": s.rounding}
1694
+ if s.mode == "split":
1695
+ rec["shares"] = len(s.latents)
1696
+ diag["applied"].append(rec)
1697
+ verdict = rel.stats.get("verdict")
1698
+ what = {"split": "allocated from the total by its modeled share",
1699
+ "scale": "its modeled value is scaled so that the parts add up",
1700
+ "sum": "computed from its parts"}[s.mode]
1701
+ text = f"{'declared' if rel.source == 'confirmed' else 'detected'} sum " \
1702
+ f"{sum_text(s)!r}: {what}"
1703
+ if verdict is not None and verdict.exceptions:
1704
+ text += "; " + _tolerance.note(verdict, pol, breaks="break the sum")
1705
+ for column in (*computed_columns([s]), *scaled_columns([s])):
1706
+ notes.setdefault(column, text)
1707
+ diag["notes"] = notes
1708
+ diag["not_enforced"] = planner.not_enforced
1709
+ diag["not_selected"] = planner.rejected[:50]
1710
+ return ordered, diag