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,263 @@
1
+ """Chow-Liu trees and conditional probability tables over categorical columns (M17).
2
+
3
+ One Gaussian latent per nominal column cannot represent an arbitrary contingency table, so the
4
+ encoder (``models/encoding.py``) decodes some categorical columns *conditionally* on a parent
5
+ categorical column (a Rosenblatt-style conditional-interval decode). This module learns which
6
+ parent each column gets and the table ``P(child | parent)``:
7
+
8
+ * :func:`chow_liu_parents` -- a maximum spanning forest on pairwise mutual information (Chow &
9
+ Liu, 1968). Edges need MI above ``min_mi`` plus the plug-in bias ``(ka - 1)(kb - 1) / 2n``.
10
+ Only columns with at most ``max_parent_levels`` levels may be parents: the spanning forest is
11
+ built over those, then each higher-cardinality column is attached as a leaf to its
12
+ best-MI low-cardinality neighbour. Each tree is rooted at its highest-degree node and
13
+ oriented away from the root.
14
+ * :func:`fit_cpt` -- ``P(child | parent)`` from counts, with disclosure controls: parent levels
15
+ with fewer than ``policy.rare_cell_min`` rows back off to the child marginal entirely; inside
16
+ a parent level, cells below ``rare_cell_min`` are suppressed, and their pooled mass (rounded
17
+ up to at least ``rare_cell_min``, as in ``pool_categories``) is redistributed over the
18
+ suppressed cells in proportion to the child marginal. The row is then smoothed toward the
19
+ marginal with ``pseudo_count`` pseudo-observations and coarsened to the policy's significant
20
+ digits.
21
+
22
+ All inputs are integer codes (float arrays, NaN for null) aligned with each column's
23
+ categorical marginal labels, including the trailing ``"__other__"`` code. Pure numpy; no
24
+ randomness.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ from collections.abc import Mapping, Sequence
30
+ from dataclasses import dataclass
31
+
32
+ import numpy as np
33
+
34
+ from ectype.fingerprint.disclosure import coarsen, coarsen_array
35
+ from ectype.fingerprint.schema import DisclosurePolicySpec
36
+
37
+ KIND_CPT_TREE = "cpt_tree"
38
+ MAX_PARENT_LEVELS = 50
39
+ MIN_MI = 0.005 # nats, on top of the plug-in bias
40
+ PSEUDO_COUNT = 1.0
41
+ MI_MAX_ROWS = 200_000 # deterministic stride subsample for the MI matrix
42
+
43
+
44
+ @dataclass
45
+ class ConditionalTable:
46
+ """``probs[p, c] = P(child = c | parent = p)`` over marginal codes (rows sum to 1)."""
47
+
48
+ child: str
49
+ parent: str
50
+ probs: np.ndarray
51
+ backed_off: np.ndarray # bool per parent level: row is the child marginal
52
+ mutual_information: float
53
+ pseudo_count: float
54
+
55
+
56
+ def _complete_codes(a: np.ndarray, b: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
57
+ ok = np.isfinite(a) & np.isfinite(b)
58
+ return a[ok].astype(np.int64), b[ok].astype(np.int64)
59
+
60
+
61
+ def contingency(a: np.ndarray, b: np.ndarray, ka: int, kb: int) -> np.ndarray:
62
+ """Counts table (ka, kb) of complete pairs of codes."""
63
+ x, y = _complete_codes(np.asarray(a, float), np.asarray(b, float))
64
+ x, y = np.clip(x, 0, ka - 1), np.clip(y, 0, kb - 1)
65
+ return np.bincount(x * kb + y, minlength=ka * kb).reshape(ka, kb).astype(float)
66
+
67
+
68
+ def mutual_information(table: np.ndarray) -> float:
69
+ """Plug-in mutual information (nats) of a counts table."""
70
+ n = table.sum()
71
+ if n <= 0:
72
+ return 0.0
73
+ p = table / n
74
+ pa = p.sum(axis=1, keepdims=True)
75
+ pb = p.sum(axis=0, keepdims=True)
76
+ nz = p > 0
77
+ return float(np.sum(p[nz] * np.log(p[nz] / (pa @ pb)[nz])))
78
+
79
+
80
+ def _stride(n: int, cap: int) -> np.ndarray:
81
+ if n <= cap:
82
+ return np.arange(n)
83
+ return np.linspace(0, n - 1, cap).astype(np.int64)
84
+
85
+
86
+ def chow_liu_parents(codes: Mapping[str, np.ndarray], levels: Mapping[str, int], *,
87
+ max_parent_levels: int = MAX_PARENT_LEVELS, min_mi: float = MIN_MI,
88
+ root_priority: Mapping[str, float] | None = None,
89
+ ) -> tuple[dict[str, str], dict[str, float]]:
90
+ """Chow-Liu forest over ``codes`` (iteration order = tie-break order).
91
+
92
+ Each tree is rooted at its node with the largest ``root_priority`` (then highest degree).
93
+ The encoder passes each column's strongest numeric association (eta^2): the root keeps
94
+ its marginal latent, so its numeric relations pass through the copula unchanged.
95
+
96
+ Returns ``(parents, mi)``: ``parents[child] = parent`` for every non-root column, and the
97
+ MI of each chosen edge keyed by child.
98
+ """
99
+ names = list(codes)
100
+ if len(names) < 2:
101
+ return {}, {}
102
+ n_all = len(next(iter(codes.values())))
103
+ idx = _stride(n_all, MI_MAX_ROWS)
104
+ sub = {c: np.asarray(codes[c], float)[idx] for c in names}
105
+ edges: list[tuple[float, int, int]] = []
106
+ for i, a in enumerate(names):
107
+ for j in range(i + 1, len(names)):
108
+ b = names[j]
109
+ ka, kb = int(levels[a]), int(levels[b])
110
+ if ka < 2 or kb < 2:
111
+ continue
112
+ if ka > max_parent_levels and kb > max_parent_levels:
113
+ continue
114
+ t = contingency(sub[a], sub[b], ka, kb)
115
+ n = t.sum()
116
+ if n <= 0:
117
+ continue
118
+ mi = mutual_information(t)
119
+ if mi > min_mi + (ka - 1) * (kb - 1) / (2.0 * n):
120
+ edges.append((mi, i, j))
121
+ edges.sort(key=lambda e: (-e[0], e[1], e[2]))
122
+ low = [levels[c] <= max_parent_levels for c in names]
123
+
124
+ # Kruskal over low-cardinality nodes.
125
+ root = list(range(len(names)))
126
+
127
+ def find(x: int) -> int:
128
+ while root[x] != x:
129
+ root[x] = root[root[x]]
130
+ x = root[x]
131
+ return x
132
+
133
+ adj: dict[int, list[int]] = {i: [] for i in range(len(names))}
134
+ edge_mi: dict[frozenset[int], float] = {}
135
+ for mi, i, j in edges:
136
+ if not (low[i] and low[j]):
137
+ continue
138
+ ri, rj = find(i), find(j)
139
+ if ri != rj:
140
+ root[ri] = rj
141
+ adj[i].append(j)
142
+ adj[j].append(i)
143
+ edge_mi[frozenset((i, j))] = mi
144
+ # High-cardinality columns become leaves of their best low-cardinality neighbour.
145
+ leaf_parent: dict[int, int] = {}
146
+ for mi, i, j in edges:
147
+ if low[i] and low[j]:
148
+ continue
149
+ hi_node, lo_node = (j, i) if low[i] else (i, j)
150
+ if hi_node not in leaf_parent:
151
+ leaf_parent[hi_node] = lo_node
152
+ edge_mi[frozenset((i, j))] = mi
153
+
154
+ parents: dict[str, str] = {}
155
+ mi_out: dict[str, float] = {}
156
+ seen: set[int] = set()
157
+ for start in range(len(names)):
158
+ if start in seen or not low[start]:
159
+ continue
160
+ comp, stack = [], [start]
161
+ seen.add(start)
162
+ while stack:
163
+ x = stack.pop()
164
+ comp.append(x)
165
+ for y in adj[x]:
166
+ if y not in seen:
167
+ seen.add(y)
168
+ stack.append(y)
169
+ if len(comp) == 1:
170
+ continue
171
+ prio = root_priority or {}
172
+ r = min(comp, key=lambda x: (-round(float(prio.get(names[x], 0.0)), 3),
173
+ -len(adj[x]), x))
174
+ queue, done = [r], {r}
175
+ while queue:
176
+ x = queue.pop(0)
177
+ for y in sorted(adj[x]):
178
+ if y not in done:
179
+ done.add(y)
180
+ parents[names[y]] = names[x]
181
+ mi_out[names[y]] = edge_mi[frozenset((x, y))]
182
+ queue.append(y)
183
+ for h, p in leaf_parent.items():
184
+ parents[names[h]] = names[p]
185
+ mi_out[names[h]] = edge_mi[frozenset((h, p))]
186
+ return parents, mi_out
187
+
188
+
189
+ def fit_cpt(child: np.ndarray, parent: np.ndarray, marginal: np.ndarray, k_parent: int,
190
+ policy: DisclosurePolicySpec, *, pseudo_count: float = PSEUDO_COUNT
191
+ ) -> tuple[np.ndarray, np.ndarray]:
192
+ """``(probs, backed_off)`` for ``P(child | parent)`` (see the module docstring)."""
193
+ marginal = np.asarray(marginal, float)
194
+ marginal = marginal / marginal.sum()
195
+ kc = marginal.size
196
+ counts = contingency(parent, child, k_parent, kc)
197
+ rare = float(policy.rare_cell_min)
198
+ probs = np.tile(marginal, (k_parent, 1))
199
+ backed = np.ones(k_parent, dtype=bool)
200
+ for p in range(k_parent):
201
+ row = counts[p]
202
+ n_p = row.sum()
203
+ if n_p < max(rare, 1.0):
204
+ continue
205
+ small = row < rare
206
+ kept = np.where(small, 0.0, row)
207
+ pooled = float(row[small].sum())
208
+ if pooled > 0:
209
+ pooled = max(pooled, rare)
210
+ w = np.where(small, marginal, 0.0)
211
+ kept = kept + pooled * w / w.sum() if w.sum() > 0 else kept
212
+ total = kept.sum() + pseudo_count
213
+ probs[p] = (kept + pseudo_count * marginal) / total
214
+ backed[p] = False
215
+ probs = coarsen_array(probs, policy)
216
+ probs = np.clip(probs, 0.0, None)
217
+ sums = probs.sum(axis=1, keepdims=True)
218
+ probs = np.where(sums > 0, probs / np.where(sums > 0, sums, 1.0), marginal)
219
+ return probs, backed
220
+
221
+
222
+ def fit_cpt_tree(codes: Mapping[str, np.ndarray], marginals: Mapping[str, np.ndarray],
223
+ policy: DisclosurePolicySpec, *, max_parent_levels: int = MAX_PARENT_LEVELS,
224
+ min_mi: float = MIN_MI, pseudo_count: float = PSEUDO_COUNT,
225
+ root_priority: Mapping[str, float] | None = None,
226
+ ) -> dict[str, ConditionalTable]:
227
+ """Learn the Chow-Liu forest and a :class:`ConditionalTable` for every non-root column.
228
+
229
+ ``codes[c]`` are marginal codes (NaN for null), ``marginals[c]`` the marginal probabilities
230
+ per code. Returned dict iterates parents before children.
231
+ """
232
+ levels = {c: int(np.size(marginals[c])) for c in codes}
233
+ parents, mi = chow_liu_parents(codes, levels, max_parent_levels=max_parent_levels,
234
+ min_mi=min_mi, root_priority=root_priority)
235
+ out: dict[str, ConditionalTable] = {}
236
+ for child in tree_order(list(codes), parents):
237
+ if child not in parents:
238
+ continue
239
+ par = parents[child]
240
+ probs, backed = fit_cpt(codes[child], codes[par], marginals[child], levels[par],
241
+ policy, pseudo_count=pseudo_count)
242
+ out[child] = ConditionalTable(child=child, parent=par, probs=probs, backed_off=backed,
243
+ mutual_information=coarsen(mi[child], policy),
244
+ pseudo_count=pseudo_count)
245
+ return out
246
+
247
+
248
+ def tree_order(names: Sequence[str], parents: Mapping[str, str]) -> list[str]:
249
+ """``names`` reordered so every parent precedes its children (stable by depth)."""
250
+ def depth(c: str) -> int:
251
+ d, seen = 0, {c}
252
+ while c in parents:
253
+ c = parents[c]
254
+ if c in seen:
255
+ raise ValueError("conditional parents contain a cycle")
256
+ seen.add(c)
257
+ d += 1
258
+ return d
259
+ return sorted(names, key=depth)
260
+
261
+
262
+ __all__ = ["KIND_CPT_TREE", "ConditionalTable", "chow_liu_parents", "contingency", "fit_cpt",
263
+ "fit_cpt_tree", "mutual_information", "tree_order"]