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,743 @@
1
+ """The weekly pattern of date columns (format 0.4, ADR-0012).
2
+
3
+ Real events happen on working days. A marginal fitted to dates is smooth over the week (its
4
+ quantile grid is far coarser than a day), and a date computed as ``base + gap`` is smooth too
5
+ unless the gap happens to be a multiple of seven: two generated dates in seven fall on a
6
+ weekend, on days the source never uses. A date's weekday is not a property of its marginal's
7
+ shape but of the lattice it lives on, so it is restored where the lattice is: on the generated
8
+ values, after decoding.
9
+
10
+ Slots
11
+ -----
12
+ The *slot* of a value is its day number modulo :data:`PERIOD` (7). The day number is the value
13
+ itself for a date (days since 1970-01-01) and for a whole-number column, and the whole UTC day
14
+ for a timestamp (:func:`day_scale`). Day 0 was a Thursday, so slots 2 and 3 are Saturday and
15
+ Sunday. Nothing here knows about weekdays: the slots that are rare are whatever the data says.
16
+
17
+ Detection (:func:`weekly_evidence`)
18
+ -----------------------------------
19
+ A column gets a calendar when its slot shares are clearly not what a locally smooth
20
+ distribution would give. Per slot, the rows observed are compared with the rows *expected* if
21
+ every row were spread evenly over the seven days centred on it (a centred seven-day average,
22
+ which follows any trend of the column, so a column that merely grows or decays over its range
23
+ shows nothing). All of the following must hold:
24
+
25
+ * at least :data:`MIN_ROWS` rows over at least :data:`MIN_WEEKS` distinct weeks;
26
+ * some slot's share differs from its expected share by at least :data:`MIN_DEVIATION`
27
+ (2 points: below that a uniform week is as good);
28
+ * the difference is significant in the even weeks alone and in the odd weeks alone
29
+ (chi-square with 6 degrees of freedom, ``p <`` :data:`MAX_PVALUE` in each half);
30
+ * the two halves show the *same* pattern: the cosine of their deviation vectors is at least
31
+ :data:`MIN_AGREEMENT`. A heap on a single value (a zero, a migration date) is in one half
32
+ only and fails this, whatever its size.
33
+
34
+ The test looks at values, not at the dtype: a whole-number column of day numbers qualifies
35
+ like a ``Date`` column. So does any other whole-number column with a consistent 7-periodic
36
+ profile (durations heaped at whole weeks); there the model usually has the pattern already and
37
+ the kernel below is close to the identity.
38
+
39
+ The model (:func:`fit_calendars`, :func:`snap`)
40
+ -----------------------------------------------
41
+ Everything upstream is unchanged: marginals, differences (in days), orderings and the joint
42
+ model are fitted and generated as before. A calendar is one more step after them. For a column
43
+ with a calendar, a generated row in slot ``j`` is moved to slot ``k`` with probability
44
+ ``kernel[j][k]``, by the shortest whole-day shift (at most 3 days).
45
+
46
+ The kernel is fitted on *model* rows, not on source rows. A seeded sample is drawn from the
47
+ fitted model and its slot shares ``q`` are compared with the source profile ``p``: slots the
48
+ model overproduces give up their surplus to the nearest slots it underproduces
49
+ (:func:`transport`, nearest first), and every other row stays where it is. Where the model
50
+ already has the pattern nothing moves.
51
+
52
+ Related dates stay related. The *anchors* of a column are the columns it is computed from or
53
+ bounded by (the base of its ``difference``, the bounds of its ordering). Columns are processed
54
+ anchors first, and a row keeps its relation to each anchor exactly:
55
+
56
+ * a value that was computed as ``base +/- gap`` first takes its base's move along
57
+ (``CalendarSpec.base``), so the gap is the one the model drew;
58
+ * a row that equals an anchor before the move takes the anchor's new value (a same-day tie
59
+ stays a tie, and takes no part in the kernel);
60
+ * a row before (after) an anchor stays strictly before (after) it. When the drawn day is on
61
+ the wrong side, the nearest allowed day in a slot the column actually uses is taken instead
62
+ (a date one day after a Friday becomes the Monday).
63
+
64
+ Ties and the order between a column and its anchors are therefore exactly what the model
65
+ generated: out-of-order rates and same-day shares do not change. The share of tied rows is
66
+ taken into account when the kernel is fitted (their slot is their anchor's), and the fit is
67
+ repeated a few times against the shares it actually achieves on the sample. A column that is
68
+ tied to a column with a calendar but has no weekly profile of its own gets a spec without a
69
+ kernel: it only follows its anchors. A column of an ``identity`` transform never moves.
70
+
71
+ Randomness: one uniform number per row and calendar, from the decode stream of the chunk
72
+ (``rng.stream(seed, "chunk", i, "decode")``), which nothing else consumes. Generation stays a
73
+ deterministic function of fingerprint, seed and chunk, and parallel generation equals
74
+ sequential generation.
75
+
76
+ Disclosure
77
+ ----------
78
+ A spec stores ``profile``, the seven slot shares of the source column, and ``kernel``. A share
79
+ that stands for fewer than ``min_category_support`` rows is stored as 0 (the rule of the
80
+ granularity target, ADR-0007), the others are coarsened to the policy's significant digits:
81
+ each stored share is a count of at least ``min_category_support`` rows out of all rows of the
82
+ column, like a category frequency. The kernel is computed from that profile and from rows
83
+ drawn from the model, never from source rows. Nothing else about the rows is kept; the rates in
84
+ the diagnostics are coarsened.
85
+
86
+ Generalisation
87
+ --------------
88
+ The mechanism is "a periodic lattice with a learned profile, restored by a transport kernel":
89
+ hour of the day for timestamps (period 24 on hours) or the last days of a month would be other
90
+ ``period`` / ``unit`` pairs of the same spec. Only the week is built; a reader rejects any
91
+ other period.
92
+ """
93
+
94
+ from __future__ import annotations
95
+
96
+ import math
97
+ from collections.abc import Mapping, Sequence
98
+ from typing import Any
99
+
100
+ import numpy as np
101
+ import polars as pl
102
+ from scipy import stats
103
+
104
+ from ectype.fingerprint.disclosure import coarsen, resolve_policy
105
+ from ectype.fingerprint.schema import (
106
+ CalendarSpec,
107
+ ColumnSchema,
108
+ DisclosurePolicySpec,
109
+ OrderingSpec,
110
+ TransformSpec,
111
+ )
112
+ from ectype.io.values import column_to_values, values_to_column
113
+ from ectype.types import LogicalType, Role
114
+
115
+ __all__ = [
116
+ "ACTIVE_SHARE",
117
+ "FIT_ROUNDS",
118
+ "FIT_TOLERANCE",
119
+ "MAX_PVALUE",
120
+ "METHODS",
121
+ "MIN_AGREEMENT",
122
+ "MIN_DEVIATION",
123
+ "MIN_ROWS",
124
+ "MIN_WEEKS",
125
+ "PERIOD",
126
+ "SIM_ROWS",
127
+ "US_PER_DAY",
128
+ "apply_calendars",
129
+ "check_calendars",
130
+ "day_scale",
131
+ "detect_calendars",
132
+ "fit_calendars",
133
+ "plan_calendars",
134
+ "slots",
135
+ "snap",
136
+ "transport",
137
+ "weekly_evidence",
138
+ ]
139
+
140
+ #: the only period this engine models: the week, in days
141
+ PERIOD = 7
142
+ #: microseconds per day (timestamps are read as whole UTC days)
143
+ US_PER_DAY = 86_400_000_000.0
144
+ #: how a calendar moves rows (``CalendarSpec.method``)
145
+ METHODS = ("transport",)
146
+ #: fewest rows and distinct weeks a weekly profile is read from
147
+ MIN_ROWS = 200
148
+ MIN_WEEKS = 26
149
+ #: smallest difference between a slot's share and its locally smooth expectation that is worth
150
+ #: modeling (2 points)
151
+ MIN_DEVIATION = 0.02
152
+ #: the profile must be significant at this level in the even weeks and in the odd weeks
153
+ MAX_PVALUE = 1e-3
154
+ #: ... and the same in both: smallest cosine between the two deviation vectors
155
+ MIN_AGREEMENT = 0.8
156
+ #: smallest expected count per slot and half for the chi-square test
157
+ MIN_EXPECTED = 5.0
158
+ #: a slot is one the column "uses" (a row that cannot go where the kernel sends it may land
159
+ #: there) when its share is at least this: half of a uniform week's
160
+ ACTIVE_SHARE = 0.5 / PERIOD
161
+ #: model rows the kernels are fitted on
162
+ SIM_ROWS = 20_000
163
+ #: the kernel is refitted against the shares it achieves at most this many times, until no
164
+ #: slot is further off than the tolerance
165
+ FIT_ROUNDS = 5
166
+ FIT_TOLERANCE = 0.002
167
+ #: decimals of a stored kernel entry
168
+ KERNEL_DECIMALS = 6
169
+ #: day offsets tried, nearest first, for a row that cannot go where the kernel sends it
170
+ _NEAREST = tuple(o for d in range(0, 11) for o in ((0,) if d == 0 else (-d, d)))
171
+
172
+
173
+ # ---------------------------------------------------------------------------------------------
174
+ # Values and slots
175
+ # ---------------------------------------------------------------------------------------------
176
+
177
+
178
+ def _domain(col: ColumnSchema) -> str | None:
179
+ """The value domain of a numeric or datetime column, as ``structure`` names it: ``"d"``
180
+ for dates, ``"us"`` for timestamps, ``"num"`` for numbers; ``None`` for any other."""
181
+ if col.logical_type == LogicalType.DATETIME:
182
+ return "d" if (col.is_date or col.datetime_unit == "d") else "us"
183
+ if col.logical_type in (LogicalType.CONTINUOUS, LogicalType.DISCRETE):
184
+ return "num"
185
+ return None
186
+
187
+
188
+ def day_scale(col: ColumnSchema) -> float | None:
189
+ """Value units per day: 1 for dates and whole-number columns, :data:`US_PER_DAY` for
190
+ timestamps (epoch microseconds, so days are UTC days). ``None`` when the column's values
191
+ are not days: any other type, and numbers that are not whole."""
192
+ domain = _domain(col)
193
+ if domain is None or (domain == "num" and not col.integer_valued):
194
+ return None
195
+ return US_PER_DAY if domain == "us" else 1.0
196
+
197
+
198
+ def _values(df: pl.DataFrame, name: str, schemas: Mapping[str, ColumnSchema]) -> np.ndarray:
199
+ return np.asarray(column_to_values(df.get_column(name), schemas[name]), dtype=np.float64)
200
+
201
+
202
+ def slots(values: np.ndarray, scale: float = 1.0) -> np.ndarray:
203
+ """Day number modulo :data:`PERIOD` of finite ``values`` (``int64``)."""
204
+ day = np.floor(np.asarray(values, dtype=np.float64) / scale).astype(np.int64)
205
+ return np.asarray(np.mod(day, PERIOD), dtype=np.int64)
206
+
207
+
208
+ def _shares(values: np.ndarray, scale: float) -> np.ndarray:
209
+ v = values[np.isfinite(values)]
210
+ if v.size == 0:
211
+ return np.zeros(PERIOD)
212
+ return np.bincount(slots(v, scale), minlength=PERIOD) / v.size
213
+
214
+
215
+ # ---------------------------------------------------------------------------------------------
216
+ # Detection
217
+ # ---------------------------------------------------------------------------------------------
218
+
219
+
220
+ def weekly_evidence(values: np.ndarray, scale: float = 1.0) -> dict[str, Any]:
221
+ """Whether the day numbers of ``values`` have a weekly profile (see the module docstring).
222
+
223
+ Returns ``detected``, the statistics (``rows``, ``weeks``, ``deviation``: the largest
224
+ difference between a slot's share and its locally smooth expectation, ``pvalues`` of the
225
+ two halves, ``agreement``) and, when not detected, the ``reason``. NaN is ignored."""
226
+ v = np.asarray(values, dtype=np.float64)
227
+ v = v[np.isfinite(v)]
228
+ out: dict[str, Any] = {"detected": False, "rows": int(v.size), "weeks": 0}
229
+ if v.size == 0:
230
+ out["reason"] = "no values"
231
+ return out
232
+ day = np.floor(v / scale).astype(np.int64)
233
+ uniq, cnt = np.unique(day, return_counts=True)
234
+ week = np.floor_divide(uniq, PERIOD)
235
+ out["weeks"] = int(np.unique(week).size)
236
+ if v.size < MIN_ROWS or out["weeks"] < MIN_WEEKS:
237
+ out["reason"] = (f"needs {MIN_ROWS} rows over {MIN_WEEKS} distinct weeks (has "
238
+ f"{v.size} rows over {out['weeks']})")
239
+ return out
240
+ # rows observed per slot, and expected when each row is spread evenly over the seven days
241
+ # centred on it; both over the days at least half a week inside the column's range, so
242
+ # that every day counted has its whole window
243
+ lo, hi = int(uniq[0]) + PERIOD // 2, int(uniq[-1]) - PERIOD // 2
244
+ slot = np.mod(uniq, PERIOD)
245
+ observed = np.zeros((2, PERIOD))
246
+ expected = np.zeros((2, PERIOD))
247
+ inside = (uniq >= lo) & (uniq <= hi)
248
+ np.add.at(observed, (np.mod(week[inside], 2), slot[inside]), cnt[inside])
249
+ for k in range(PERIOD):
250
+ at = uniq + np.mod(k - slot + PERIOD // 2, PERIOD) - PERIOD // 2
251
+ ok = (at >= lo) & (at <= hi)
252
+ np.add.at(expected, (np.mod(np.floor_divide(at[ok], PERIOD), 2),
253
+ np.full(int(ok.sum()), k)), cnt[ok] / PERIOD)
254
+ if observed.sum() <= 0 or expected.sum() <= 0:
255
+ out["reason"] = "too narrow a range"
256
+ return out
257
+ total = observed.sum(axis=0) / observed.sum() - expected.sum(axis=0) / expected.sum()
258
+ out["deviation"] = float(np.max(np.abs(total)))
259
+ pvalues: list[float] = []
260
+ halves: list[np.ndarray] = []
261
+ for h in range(2):
262
+ o, e = observed[h], expected[h]
263
+ if o.sum() <= 0 or e.sum() <= 0:
264
+ pvalues.append(1.0)
265
+ halves.append(np.zeros(PERIOD))
266
+ continue
267
+ e = e * (o.sum() / e.sum())
268
+ if float(e.min()) < MIN_EXPECTED:
269
+ pvalues.append(1.0)
270
+ else:
271
+ pvalues.append(float(stats.chi2.sf(float(np.sum((o - e) ** 2 / e)), PERIOD - 1)))
272
+ halves.append(o / o.sum() - e / e.sum())
273
+ norm = float(np.linalg.norm(halves[0]) * np.linalg.norm(halves[1]))
274
+ agreement = float(halves[0] @ halves[1]) / norm if norm > 0 else 0.0
275
+ out.update(pvalues=pvalues, agreement=agreement)
276
+ if out["deviation"] < MIN_DEVIATION:
277
+ out["reason"] = (f"no slot is {MIN_DEVIATION:.0%} off a smooth week (largest "
278
+ f"difference {out['deviation']:.3g})")
279
+ elif max(pvalues) >= MAX_PVALUE:
280
+ out["reason"] = (f"not significant in both halves of the weeks (p-values "
281
+ f"{pvalues[0]:.3g} and {pvalues[1]:.3g}, needed below {MAX_PVALUE})")
282
+ elif agreement < MIN_AGREEMENT:
283
+ out["reason"] = (f"even and odd weeks disagree (cosine {agreement:.3g} < "
284
+ f"{MIN_AGREEMENT}): heaps on single values, not a weekly pattern")
285
+ else:
286
+ out["detected"] = True
287
+ return out
288
+
289
+
290
+ def _profile(values: np.ndarray, scale: float, policy: DisclosurePolicySpec) -> np.ndarray:
291
+ """The slot shares of a source column as they may be stored: a slot held by fewer than
292
+ ``min_category_support`` rows gets 0, the others are coarsened, and the result sums to 1."""
293
+ v = values[np.isfinite(values)]
294
+ counts = np.bincount(slots(v, scale), minlength=PERIOD).astype(np.float64)
295
+ counts[counts < policy.min_category_support] = 0.0
296
+ if counts.sum() <= 0:
297
+ return np.full(PERIOD, 1.0 / PERIOD)
298
+ shares = np.array([coarsen(float(c) / float(v.size), policy) for c in counts])
299
+ return np.asarray(shares / shares.sum(), dtype=np.float64)
300
+
301
+
302
+ def detect_calendars(df: pl.DataFrame, columns: Sequence[ColumnSchema],
303
+ policy: DisclosurePolicySpec | str | None
304
+ ) -> tuple[dict[str, np.ndarray], dict[str, Any]]:
305
+ """The modeled columns of ``df`` with a weekly profile: ``{column: profile}`` (the shares
306
+ of :func:`_profile`) and a JSON-safe record of what was found and what came close.
307
+
308
+ Only feature columns whose values are days are looked at (:func:`day_scale`); internal
309
+ ``__*`` columns never are."""
310
+ pol = resolve_policy(policy)
311
+ found: dict[str, np.ndarray] = {}
312
+ diag: dict[str, Any] = {
313
+ "thresholds": {"min_rows": MIN_ROWS, "min_weeks": MIN_WEEKS,
314
+ "min_deviation": MIN_DEVIATION, "max_pvalue": MAX_PVALUE,
315
+ "min_agreement": MIN_AGREEMENT},
316
+ "applied": [], "not_selected": []}
317
+ for col in columns:
318
+ scale = day_scale(col)
319
+ if (scale is None or col.role != Role.FEATURE or col.name.startswith("__")
320
+ or col.name not in df.columns):
321
+ continue
322
+ values = _values(df, col.name, {col.name: col})
323
+ ev = weekly_evidence(values, scale)
324
+ rec: dict[str, Any] = {"column": col.name, "rows": ev["rows"],
325
+ "weeks": int(coarsen(float(ev["weeks"]), pol))}
326
+ if "deviation" in ev:
327
+ rec["deviation"] = coarsen(float(ev["deviation"]), pol)
328
+ if "agreement" in ev:
329
+ rec["agreement"] = coarsen(float(ev["agreement"]), pol)
330
+ rec["pvalues"] = [coarsen(float(p), pol) for p in ev["pvalues"]]
331
+ if ev["detected"]:
332
+ found[col.name] = _profile(values, scale, pol)
333
+ diag["applied"].append(rec)
334
+ elif ev.get("deviation", 0.0) >= MIN_DEVIATION:
335
+ diag["not_selected"].append({**rec, "reason": ev["reason"]})
336
+ return found, diag
337
+
338
+
339
+ # ---------------------------------------------------------------------------------------------
340
+ # Planning: which columns move, in which order, tied to what
341
+ # ---------------------------------------------------------------------------------------------
342
+
343
+
344
+ def plan_calendars(detected: Sequence[str], transforms: Sequence[TransformSpec],
345
+ orderings: Sequence[OrderingSpec], columns: Sequence[str]
346
+ ) -> list[tuple[str, list[str], str | None]]:
347
+ """``(column, anchors, base)`` for every column a calendar touches, in the order they run.
348
+
349
+ The anchors of a column are the columns its value was made from or bounded by: the base of
350
+ its ``difference`` transform, the bounds of its ordering. ``base`` is the first kind, when
351
+ that column moves too: the value was computed as ``base +/- gap`` before the base moved,
352
+ so it first takes the base's move along (the gap is kept). A column tied to a column that
353
+ moves must follow it, so the plan is closed under "has an anchor in the plan", whether or
354
+ not the column has a profile of its own. Columns of an ``identity`` transform never move
355
+ (the formula would no longer hold). ``columns`` gives the order of the untied columns."""
356
+ fixed = {name for t in transforms if t.kind == "identity" for name in (t.target, *t.inputs)}
357
+ parents: dict[str, list[str]] = {}
358
+ computed_from: dict[str, str] = {}
359
+ for t in transforms:
360
+ if t.kind == "difference":
361
+ parents.setdefault(t.target, []).extend(t.inputs)
362
+ computed_from[t.target] = t.inputs[0]
363
+ for o in orderings:
364
+ parents.setdefault(o.target, []).extend([*o.lower, *o.upper])
365
+ wanted = {c for c in detected if c not in fixed}
366
+ plan: list[tuple[str, list[str], str | None]] = [
367
+ (c, [], None) for c in columns if c in wanted and c not in parents]
368
+ moving = {c for c, _, _ in plan}
369
+ pending = [c for c in columns if c in parents and c not in fixed]
370
+ progress = True
371
+ while progress: # parents before children, whatever the given order
372
+ progress = False
373
+ for c in list(pending):
374
+ if any(p in pending for p in parents[c]):
375
+ continue
376
+ pending.remove(c)
377
+ progress = True
378
+ if c in wanted or any(p in moving for p in parents[c]):
379
+ base = computed_from.get(c)
380
+ plan.append((c, list(dict.fromkeys(parents[c])),
381
+ base if base in moving else None))
382
+ moving.add(c)
383
+ return plan
384
+
385
+
386
+ # ---------------------------------------------------------------------------------------------
387
+ # The kernel
388
+ # ---------------------------------------------------------------------------------------------
389
+
390
+
391
+ def transport(source: np.ndarray, target: np.ndarray) -> np.ndarray:
392
+ """A :data:`PERIOD` x :data:`PERIOD` table of probabilities that turns slot shares
393
+ ``source`` into ``target`` while moving as few rows as little as possible: every slot
394
+ keeps what the target allows, and its surplus goes to the slots that lack rows, nearest
395
+ first (one day earlier, one day later, two days earlier, ...). Row ``j`` is the
396
+ distribution of the new slot of a row in slot ``j``; a slot the source never produces
397
+ keeps its rows when the target uses it and sends them to the nearest used slot
398
+ otherwise."""
399
+ q = np.clip(np.asarray(source, dtype=np.float64), 0.0, None)
400
+ r = np.clip(np.asarray(target, dtype=np.float64), 0.0, None)
401
+ q = q / q.sum() if q.sum() > 0 else np.full(PERIOD, 1.0 / PERIOD)
402
+ r = r / r.sum() if r.sum() > 0 else q.copy()
403
+ flow = np.zeros((PERIOD, PERIOD))
404
+ surplus, need = q.copy(), r.copy()
405
+ for dist in range(PERIOD // 2 + 1):
406
+ for j in range(PERIOD):
407
+ for sign in ((0,) if dist == 0 else (-1, 1)):
408
+ k = (j + sign * dist) % PERIOD
409
+ f = min(surplus[j], need[k])
410
+ if f > 0:
411
+ flow[j, k] += f
412
+ surplus[j] -= f
413
+ need[k] -= f
414
+ kernel = np.zeros((PERIOD, PERIOD))
415
+ for j in range(PERIOD):
416
+ if flow[j].sum() > 1e-12:
417
+ kernel[j] = flow[j] / flow[j].sum()
418
+ elif r[j] > 0:
419
+ kernel[j, j] = 1.0
420
+ else:
421
+ used = [k for k in sorted(range(PERIOD), key=lambda k: (
422
+ min((k - j) % PERIOD, (j - k) % PERIOD), (k - j) % PERIOD)) if r[k] > 0]
423
+ kernel[j, used[0] if used else j] = 1.0
424
+ return kernel
425
+
426
+
427
+ def _clean_kernel(kernel: np.ndarray) -> np.ndarray:
428
+ """``kernel`` as it is stored: rounded, every row summing to 1."""
429
+ k = np.round(np.clip(kernel, 0.0, None), KERNEL_DECIMALS)
430
+ for j in range(PERIOD):
431
+ if k[j].sum() <= 0:
432
+ k[j, j] = 1.0
433
+ return np.asarray(np.round(k / k.sum(axis=1, keepdims=True), KERNEL_DECIMALS + 2),
434
+ dtype=np.float64)
435
+
436
+
437
+ def _active(profile: np.ndarray | None) -> np.ndarray:
438
+ """Slots a row may land in when it cannot go where the kernel sends it."""
439
+ if profile is None or len(profile) != PERIOD:
440
+ return np.ones(PERIOD, dtype=bool)
441
+ active = np.asarray(profile, dtype=np.float64) >= ACTIVE_SHARE
442
+ return active if active.any() else np.ones(PERIOD, dtype=bool)
443
+
444
+
445
+ # ---------------------------------------------------------------------------------------------
446
+ # Moving rows
447
+ # ---------------------------------------------------------------------------------------------
448
+
449
+
450
+ def _tied(values: np.ndarray, anchors: Sequence[tuple[np.ndarray, np.ndarray]],
451
+ carry: np.ndarray | None = None
452
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
453
+ """``(out, free, lower, upper)``: the values, shifted by ``carry`` (the move of the column
454
+ they were computed from; NaN counts as 0), with every row that equals an anchor set to the
455
+ anchor's new value (the first such anchor); the rows that are left to move; and the
456
+ exclusive bounds their relation to the anchors puts on them (``-inf`` / ``inf`` without
457
+ one). Relations are read from the values and the anchors as they were before any move."""
458
+ v = np.asarray(values, dtype=np.float64)
459
+ out = v.copy()
460
+ if carry is not None:
461
+ out = out + np.where(np.isfinite(carry), carry, 0.0)
462
+ ok = np.isfinite(v)
463
+ free = ok.copy()
464
+ lower = np.full(v.size, -np.inf)
465
+ upper = np.full(v.size, np.inf)
466
+ for before, after in anchors:
467
+ both = ok & np.isfinite(before) & np.isfinite(after)
468
+ tie = both & free & (v == before)
469
+ out[tie] = after[tie]
470
+ free &= ~tie
471
+ lower = np.where(both & (v > before), np.maximum(lower, after), lower)
472
+ upper = np.where(both & (v < before), np.minimum(upper, after), upper)
473
+ return out, free, lower, upper
474
+
475
+
476
+ def snap(values: np.ndarray, anchors: Sequence[tuple[np.ndarray, np.ndarray]],
477
+ kernel: np.ndarray | None, profile: np.ndarray | None, scale: float,
478
+ u: np.ndarray, carry: np.ndarray | None = None) -> np.ndarray:
479
+ """Move ``values`` (NaN for null) onto the column's weekly pattern.
480
+
481
+ ``anchors`` are ``(before, after)`` pairs: the values of each column this one is tied to,
482
+ before and after that column's own move. ``u`` holds one uniform number per row. ``carry``
483
+ is the move of the column the values were computed from (``after - before`` of the base of
484
+ their ``difference`` transform): every row takes it along first, so the gap to the base is
485
+ what it was.
486
+
487
+ * A row equal to an anchor (the first one it equals) takes the anchor's new value.
488
+ * Any other row in slot ``j`` draws its new slot from ``kernel[j]`` and moves there by the
489
+ shortest whole-day shift, if that keeps it strictly on the side of every anchor it was
490
+ on. Otherwise it takes the nearest day (up to 10 days away) that does and whose slot the
491
+ column uses (``profile`` at least :data:`ACTIVE_SHARE`), and failing that the smallest
492
+ whole-day shift onto the right side of the anchor it is on the wrong side of.
493
+ * Without a kernel a row only moves with its base, or when an anchor has moved past it.
494
+
495
+ Rows are independent of each other, so the result does not depend on how the rows are
496
+ chunked."""
497
+ out, free, lower, upper = _tied(values, anchors, carry)
498
+ idx = np.flatnonzero(free)
499
+ if idx.size == 0:
500
+ return out
501
+ x, lo, hi = out[idx], lower[idx], upper[idx]
502
+ j = slots(x, scale)
503
+ if kernel is None:
504
+ new = x.copy()
505
+ else:
506
+ cum = np.cumsum(np.asarray(kernel, dtype=np.float64), axis=1)
507
+ cum[:, -1] = np.inf
508
+ k = np.sum(np.asarray(u, dtype=np.float64)[idx, None] >= cum[j], axis=1)
509
+ new = x + (np.mod(k - j + PERIOD // 2, PERIOD) - PERIOD // 2) * scale
510
+ todo = ~((new > lo) & (new < hi))
511
+ if todo.any():
512
+ xt, lt, ht, jt = x[todo], lo[todo], hi[todo], j[todo]
513
+ res = np.full(xt.size, np.nan)
514
+ pending = np.ones(xt.size, dtype=bool)
515
+ active = _active(None if kernel is None else profile)
516
+ for o in _NEAREST:
517
+ cand = xt + o * scale
518
+ good = pending & (cand > lt) & (cand < ht) & active[np.mod(jt + o, PERIOD)]
519
+ res[good] = cand[good]
520
+ pending &= ~good
521
+ if not pending.any():
522
+ break
523
+ if pending.any():
524
+ xs, ls, hs = xt[pending], lt[pending], ht[pending]
525
+ with np.errstate(invalid="ignore"):
526
+ up = np.where(np.isfinite(ls), np.floor((ls - xs) / scale) + 1.0, 0.0)
527
+ down = np.where(np.isfinite(hs), np.ceil((hs - xs) / scale) - 1.0, 0.0)
528
+ shift = np.where(xs <= ls, up, np.where(xs >= hs, down, 0.0))
529
+ res[pending] = xs + shift * scale
530
+ new = new.copy()
531
+ new[todo] = res
532
+ out[idx] = new
533
+ return out
534
+
535
+
536
+ def _spec_arrays(spec: CalendarSpec) -> tuple[np.ndarray | None, np.ndarray | None]:
537
+ kernel = np.asarray(spec.kernel, dtype=np.float64) if spec.kernel else None
538
+ profile = np.asarray(spec.profile, dtype=np.float64) if spec.profile else None
539
+ return kernel, profile
540
+
541
+
542
+ def apply_calendars(df: pl.DataFrame, calendars: Sequence[CalendarSpec],
543
+ schemas: Mapping[str, ColumnSchema],
544
+ rng: np.random.Generator | None = None) -> pl.DataFrame:
545
+ """Run ``calendars`` in order on decoded columns (after transforms and orderings): each
546
+ column is moved by :func:`snap`, against its anchors' values before and after their own
547
+ move. One uniform number per row is drawn from ``rng`` for every spec, whether or not the
548
+ column is present, so the stream does not depend on the frame. A spec whose column is
549
+ missing from ``df`` is skipped, and so is an anchor that is missing."""
550
+ if not calendars:
551
+ return df
552
+ if rng is None:
553
+ from ectype.rng import stream
554
+ rng = stream(0, "calendar")
555
+ before: dict[str, np.ndarray] = {}
556
+ after: dict[str, np.ndarray] = {}
557
+
558
+ def original(name: str) -> np.ndarray:
559
+ if name not in before:
560
+ before[name] = _values(df, name, schemas)
561
+ return before[name]
562
+
563
+ present = [s for s in calendars if s.column in df.columns]
564
+ for name in sorted({n for s in present for n in (s.column, *s.anchors)
565
+ if n in df.columns}):
566
+ original(name) # every value as decoded, before anything moves
567
+ for spec in calendars:
568
+ u = rng.random(df.height)
569
+ if spec.column not in df.columns:
570
+ continue
571
+ scale = day_scale(schemas[spec.column]) or 1.0
572
+ kernel, profile = _spec_arrays(spec)
573
+ v = original(spec.column)
574
+ anchors = [(original(a), after.get(a, original(a))) for a in spec.anchors
575
+ if a in df.columns]
576
+ carry = after[spec.base] - original(spec.base) if spec.base in after else None
577
+ new = snap(v, anchors, kernel, profile, scale, u, carry)
578
+ after[spec.column] = new
579
+ changed = ~((new == v) | (np.isnan(new) & np.isnan(v)))
580
+ if changed.any():
581
+ col = values_to_column(new, schemas[spec.column]).alias(spec.column)
582
+ df = df.with_columns(col.cast(df.schema[spec.column], strict=False))
583
+ return df
584
+
585
+
586
+ # ---------------------------------------------------------------------------------------------
587
+ # Fit
588
+ # ---------------------------------------------------------------------------------------------
589
+
590
+
591
+ def fit_calendars(sim: pl.DataFrame, plan: Sequence[tuple[str, list[str], str | None]],
592
+ profiles: Mapping[str, np.ndarray], schemas: Mapping[str, ColumnSchema],
593
+ policy: DisclosurePolicySpec | str | None, rng: np.random.Generator
594
+ ) -> tuple[list[CalendarSpec], dict[str, dict[str, Any]]]:
595
+ """The calendar specs for ``plan`` (:func:`plan_calendars`), fitted on ``sim``: rows
596
+ decoded from the fitted model with transforms and orderings applied and no calendar.
597
+
598
+ For each column in turn (anchors first, so the sample already carries the moves of the
599
+ columns before it): the rows tied to an anchor are set aside, the slot shares the other
600
+ rows must end with are what the profile leaves after the tied rows, and the kernel is the
601
+ :func:`transport` from the shares those rows have to the shares they need. The kernel is
602
+ then applied, and refitted against the shares the whole column actually ends with (rows
603
+ that could not go where the kernel sent them are not where it expected), at most
604
+ :data:`FIT_ROUNDS` times. Returns the specs and, per column, the slot shares of the model
605
+ before and after and the share of rows moved (all measured on model rows)."""
606
+ pol = resolve_policy(policy)
607
+ before = {name: _values(sim, name, schemas)
608
+ for name in {n for c, a, _ in plan for n in (c, *a)} if name in sim.columns}
609
+ after: dict[str, np.ndarray] = {}
610
+ specs: list[CalendarSpec] = []
611
+ diag: dict[str, dict[str, Any]] = {}
612
+ for column, anchor_names, base in plan:
613
+ if column not in before:
614
+ continue
615
+ col = schemas[column]
616
+ scale = day_scale(col) or 1.0
617
+ v = before[column]
618
+ names = [a for a in anchor_names if a in before]
619
+ anchors = [(before[a], after.get(a, before[a])) for a in names]
620
+ base = base if base in after and base in names else None
621
+ carry = after[base] - before[base] if base is not None else None
622
+ u = rng.random(v.size)
623
+ ok = np.isfinite(v)
624
+ profile = profiles.get(column)
625
+ kernel: np.ndarray | None = None
626
+ if profile is not None and ok.any():
627
+ tied, free, _, _ = _tied(v, anchors, carry)
628
+ n_ok, n_free = int(ok.sum()), int(free.sum())
629
+ if n_free:
630
+ have = np.bincount(slots(tied[free], scale), minlength=PERIOD) / n_free
631
+ held = np.bincount(slots(tied[ok & ~free], scale),
632
+ minlength=PERIOD).astype(np.float64)
633
+ want: np.ndarray = np.clip(np.asarray(profile, dtype=np.float64) * n_ok - held,
634
+ 0.0, None)
635
+ want = want / want.sum() if want.sum() > 0 else have
636
+ best: tuple[float, np.ndarray] | None = None
637
+ for _ in range(FIT_ROUNDS):
638
+ trial = _clean_kernel(transport(have, want))
639
+ got = _shares(snap(v, anchors, trial, profile, scale, u, carry), scale)
640
+ err = profile - got
641
+ worst = float(np.max(np.abs(err)))
642
+ if best is None or worst < best[0]:
643
+ best = (worst, trial)
644
+ if worst <= FIT_TOLERANCE:
645
+ break
646
+ want = np.clip(want + err * n_ok / n_free, 0.0, None)
647
+ if want.sum() <= 0:
648
+ break
649
+ want = want / want.sum()
650
+ kernel = best[1] if best is not None else None
651
+ new = snap(v, anchors, kernel, profile, scale, u, carry)
652
+ after[column] = new
653
+ specs.append(CalendarSpec(
654
+ column=column, period=PERIOD, unit=_domain(col) or "num", method=METHODS[0],
655
+ profile=[] if kernel is None or profile is None else [float(x) for x in profile],
656
+ kernel=[] if kernel is None else [[float(x) for x in row] for row in kernel],
657
+ anchors=names, base=base))
658
+ moved = float(np.mean(new[ok] != v[ok])) if ok.any() else 0.0
659
+ rec: dict[str, Any] = {
660
+ "anchors": names, "base": base, "moved": coarsen(moved, pol),
661
+ "generated": [coarsen(float(x), pol) for x in _shares(v, scale)],
662
+ "achieved": [coarsen(float(x), pol) for x in _shares(new, scale)]}
663
+ if kernel is None:
664
+ rec["note"] = ("no weekly profile of its own: follows its anchors"
665
+ if profile is None else "every row is tied to an anchor")
666
+ diag[column] = rec
667
+ return specs, diag
668
+
669
+
670
+ # ---------------------------------------------------------------------------------------------
671
+ # Validation of recorded calendars
672
+ # ---------------------------------------------------------------------------------------------
673
+
674
+
675
+ def _is_table(rows: Any, n_rows: int) -> bool:
676
+ if not isinstance(rows, list) or len(rows) != n_rows:
677
+ return False
678
+ for row in rows:
679
+ if not isinstance(row, list) or len(row) != PERIOD:
680
+ return False
681
+ if not all(isinstance(x, (int, float)) and not isinstance(x, bool)
682
+ and math.isfinite(x) and x >= 0 for x in row):
683
+ return False
684
+ if abs(sum(row) - 1.0) > 1e-3:
685
+ return False
686
+ return True
687
+
688
+
689
+ def check_calendars(calendars: Sequence[CalendarSpec], schemas: Mapping[str, ColumnSchema],
690
+ generated: Sequence[str]) -> list[str]:
691
+ """Problems with recorded calendars (``model.calendars``) that make a fingerprint unusable
692
+ by this engine: an unknown method or period, a column that is unknown, listed twice, not
693
+ one of the ``generated`` (decoded) columns or not a column of days, a unit that does not
694
+ match the column, a profile or kernel of the wrong shape, an anchor that is unknown, not
695
+ generated, of another unit, or that has a calendar of its own later in the list. Empty
696
+ when everything is understood."""
697
+ problems: list[str] = []
698
+ made = set(generated)
699
+ seen: list[str] = []
700
+ for i, spec in enumerate(calendars):
701
+ what = f"calendar for {spec.column!r}"
702
+ if spec.method not in METHODS:
703
+ problems.append(f"{what}: unknown method {spec.method!r} (this engine supports "
704
+ f"{list(METHODS)})")
705
+ if spec.period != PERIOD:
706
+ problems.append(f"{what}: period {spec.period!r} is not understood by this engine "
707
+ f"version (it supports {PERIOD})")
708
+ continue
709
+ if spec.column in seen:
710
+ problems.append(f"{what}: the column has more than one calendar")
711
+ seen.append(spec.column)
712
+ if spec.column not in schemas or spec.column not in made:
713
+ problems.append(f"{what}: not a column the model generates by decoding")
714
+ continue
715
+ unit = _domain(schemas[spec.column])
716
+ if unit is None or unit != spec.unit:
717
+ problems.append(f"{what}: unit {spec.unit!r} does not match the column's value "
718
+ f"domain ({unit})")
719
+ if spec.kernel and day_scale(schemas[spec.column]) is None:
720
+ problems.append(f"{what}: the column's values are not whole days")
721
+ if spec.profile and not _is_table([spec.profile], 1):
722
+ problems.append(f"{what}: profile must be {PERIOD} shares that sum to 1")
723
+ if spec.kernel and not _is_table(spec.kernel, PERIOD):
724
+ problems.append(f"{what}: kernel must be a {PERIOD} x {PERIOD} table of "
725
+ f"probabilities whose rows sum to 1")
726
+ if bool(spec.kernel) != bool(spec.profile):
727
+ problems.append(f"{what}: a kernel needs its profile, and a profile its kernel")
728
+ later = {s.column for s in calendars[i + 1:]}
729
+ if len(set(spec.anchors)) != len(spec.anchors) or spec.column in spec.anchors:
730
+ problems.append(f"{what}: anchors must be distinct columns other than the column "
731
+ f"itself, got {spec.anchors}")
732
+ if spec.base is not None and spec.base not in spec.anchors:
733
+ problems.append(f"{what}: base {spec.base!r} must be one of the anchors")
734
+ for a in spec.anchors:
735
+ if a not in schemas or a not in made:
736
+ problems.append(f"{what}: anchor {a!r} is not a column the model generates "
737
+ f"by decoding")
738
+ elif _domain(schemas[a]) != unit:
739
+ problems.append(f"{what}: anchor {a!r} has another value domain")
740
+ elif a in later:
741
+ problems.append(f"{what}: anchor {a!r} has a calendar of its own that runs "
742
+ f"later (anchors must come first)")
743
+ return problems