ectype-data 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. ectype/__init__.py +134 -0
  2. ectype/_version.py +5 -0
  3. ectype/authoring/__init__.py +13 -0
  4. ectype/authoring/builder.py +134 -0
  5. ectype/authoring/spec.py +555 -0
  6. ectype/calibration/__init__.py +26 -0
  7. ectype/calibration/adjustments.py +539 -0
  8. ectype/calibration/calibrator.py +781 -0
  9. ectype/cli.py +1181 -0
  10. ectype/compiler/__init__.py +1 -0
  11. ectype/compiler/plan.py +678 -0
  12. ectype/errors.py +43 -0
  13. ectype/fingerprint/__init__.py +1 -0
  14. ectype/fingerprint/comparison.py +746 -0
  15. ectype/fingerprint/container.py +408 -0
  16. ectype/fingerprint/core.py +263 -0
  17. ectype/fingerprint/disclosure.py +207 -0
  18. ectype/fingerprint/expressions.py +1317 -0
  19. ectype/fingerprint/schema.py +645 -0
  20. ectype/fingerprint/targets.py +352 -0
  21. ectype/generation/__init__.py +1 -0
  22. ectype/generation/enforce.py +163 -0
  23. ectype/generation/generator.py +525 -0
  24. ectype/generation/identifiers.py +235 -0
  25. ectype/generation/manifest.py +71 -0
  26. ectype/generation/parallel.py +229 -0
  27. ectype/io/__init__.py +16 -0
  28. ectype/io/adapters.py +224 -0
  29. ectype/io/sql.py +289 -0
  30. ectype/io/values.py +269 -0
  31. ectype/llm/__init__.py +27 -0
  32. ectype/llm/authoring.py +766 -0
  33. ectype/llm/providers.py +269 -0
  34. ectype/models/__init__.py +8 -0
  35. ectype/models/base.py +120 -0
  36. ectype/models/chain.py +2426 -0
  37. ectype/models/copulas.py +254 -0
  38. ectype/models/encoding.py +1117 -0
  39. ectype/models/forest.py +1087 -0
  40. ectype/models/marginals.py +2099 -0
  41. ectype/models/mixtures.py +336 -0
  42. ectype/models/neural/__init__.py +21 -0
  43. ectype/models/neural/adapter.py +638 -0
  44. ectype/models/neural/vae.py +432 -0
  45. ectype/models/vines.py +608 -0
  46. ectype/plugins.py +40 -0
  47. ectype/privacy/__init__.py +49 -0
  48. ectype/privacy/attacks.py +599 -0
  49. ectype/privacy/dp.py +313 -0
  50. ectype/privacy/report.py +364 -0
  51. ectype/profiler.py +783 -0
  52. ectype/profiling/__init__.py +1 -0
  53. ectype/profiling/bivariate.py +130 -0
  54. ectype/profiling/calendar.py +743 -0
  55. ectype/profiling/conditional.py +263 -0
  56. ectype/profiling/constraints.py +661 -0
  57. ectype/profiling/entity.py +1143 -0
  58. ectype/profiling/functional.py +651 -0
  59. ectype/profiling/multivariate.py +492 -0
  60. ectype/profiling/personal.py +277 -0
  61. ectype/profiling/pseudonym.py +370 -0
  62. ectype/profiling/reference.py +334 -0
  63. ectype/profiling/sketches.py +653 -0
  64. ectype/profiling/structural.py +1087 -0
  65. ectype/profiling/structure.py +1733 -0
  66. ectype/profiling/sums.py +1710 -0
  67. ectype/profiling/tolerance.py +435 -0
  68. ectype/profiling/univariate.py +555 -0
  69. ectype/py.typed +0 -0
  70. ectype/registry.py +48 -0
  71. ectype/relational/__init__.py +61 -0
  72. ectype/relational/container.py +212 -0
  73. ectype/relational/fit.py +633 -0
  74. ectype/relational/generate.py +418 -0
  75. ectype/relational/schema.py +280 -0
  76. ectype/relational/validate.py +288 -0
  77. ectype/reporting/__init__.py +439 -0
  78. ectype/reporting/adapter.py +2003 -0
  79. ectype/reporting/charts.py +964 -0
  80. ectype/reporting/drift.py +902 -0
  81. ectype/reporting/findings.py +622 -0
  82. ectype/reporting/fmt.py +429 -0
  83. ectype/reporting/render.py +1705 -0
  84. ectype/reporting/select.py +84 -0
  85. ectype/reporting/style.py +272 -0
  86. ectype/reporting/view.py +593 -0
  87. ectype/rng.py +33 -0
  88. ectype/scenarios/__init__.py +30 -0
  89. ectype/scenarios/feasibility.py +411 -0
  90. ectype/scenarios/merge.py +1392 -0
  91. ectype/scenarios/mutate.py +1613 -0
  92. ectype/temporal/__init__.py +80 -0
  93. ectype/temporal/contract.py +221 -0
  94. ectype/temporal/detect.py +431 -0
  95. ectype/temporal/events.py +946 -0
  96. ectype/temporal/panel.py +937 -0
  97. ectype/temporal/pipeline.py +192 -0
  98. ectype/temporal/regular.py +674 -0
  99. ectype/types.py +46 -0
  100. ectype/validation/__init__.py +1 -0
  101. ectype/validation/metrics/__init__.py +7 -0
  102. ectype/validation/metrics/base.py +68 -0
  103. ectype/validation/metrics/bivariate.py +353 -0
  104. ectype/validation/metrics/missingness.py +54 -0
  105. ectype/validation/metrics/multivariate.py +265 -0
  106. ectype/validation/metrics/temporal.py +596 -0
  107. ectype/validation/metrics/univariate.py +514 -0
  108. ectype/validation/report.py +627 -0
  109. ectype/validation/validator.py +707 -0
  110. ectype_data-0.1.0.dist-info/METADATA +376 -0
  111. ectype_data-0.1.0.dist-info/RECORD +115 -0
  112. ectype_data-0.1.0.dist-info/WHEEL +4 -0
  113. ectype_data-0.1.0.dist-info/entry_points.txt +2 -0
  114. ectype_data-0.1.0.dist-info/licenses/LICENSE +192 -0
  115. ectype_data-0.1.0.dist-info/licenses/NOTICE +5 -0
ectype/io/values.py ADDED
@@ -0,0 +1,269 @@
1
+ """Conversions between polars columns and the engine's numeric value domain.
2
+
3
+ See docs/guide/03-concepts.md ("Value conventions"). Everything statistical works on float64 arrays with
4
+ NaN for null; this module is the single place that maps to and from source dtypes.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+
11
+ import numpy as np
12
+ import polars as pl
13
+
14
+ from ectype.fingerprint.schema import ColumnSchema
15
+ from ectype.types import LogicalType
16
+
17
+ OTHER = "__other__"
18
+
19
+ _UNIT_SCALE = {"ns": 1, "us": 1_000, "ms": 1_000_000, "s": 1_000_000_000}
20
+
21
+
22
+ def category_labels(s: pl.Series) -> pl.Series:
23
+ """Canonical string labels for a categorical column (the single labelling rule used by
24
+ marginals, metrics and the encoder). Integral floats are labelled like ints ("1", not "1.0");
25
+ booleans become "True"/"False". A float NaN is always a missing value (null label), like
26
+ everywhere else in the value domain."""
27
+ if s.dtype == pl.Boolean:
28
+ return s.cast(pl.String).str.replace("true", "True").str.replace("false", "False")
29
+ if s.dtype.is_float():
30
+ s = s.fill_nan(None)
31
+ nn = s.drop_nulls()
32
+ if nn.len() == 0 or bool((nn == nn.round(0)).all()):
33
+ return s.cast(pl.Int64, strict=False).cast(pl.String)
34
+ if isinstance(s.dtype, (pl.Categorical, pl.Enum)):
35
+ return s.cast(pl.String)
36
+ return s.cast(pl.String)
37
+
38
+
39
+ _labels = category_labels
40
+
41
+
42
+ def category_codes(s: pl.Series, categories: np.ndarray) -> np.ndarray:
43
+ """Map labels to integer codes (float64, NaN for null). Unknown labels map to the
44
+ ``__other__`` code if present, else NaN."""
45
+ cats = [str(c) for c in categories]
46
+ lookup = {c: float(i) for i, c in enumerate(cats)}
47
+ other = lookup.get(OTHER, np.nan)
48
+ raw = category_labels(s).to_list()
49
+ out = np.empty(len(raw), dtype=np.float64)
50
+ for i, v in enumerate(raw):
51
+ out[i] = np.nan if v is None else lookup.get(v, other)
52
+ return out
53
+
54
+
55
+ _TRUE = {"1", "true", "t", "yes", "y", "1.0"}
56
+ _FALSE = {"0", "false", "f", "no", "n", "0.0"}
57
+
58
+
59
+ def _truthy(label: str) -> bool:
60
+ """Case-insensitive truth of a boolean label ("Y", "yes", "True", "1", ...)."""
61
+ return label.strip().lower() in _TRUE
62
+
63
+
64
+ def _boolean_output(name: str, truth: list[bool | None], col: ColumnSchema) -> pl.Series:
65
+ """Decoded boolean values in the source representation: the source's own spellings when
66
+ ``col.bool_labels`` is known, 0/1 for integer-coded flags, else ``pl.Boolean``."""
67
+ if col.bool_labels is not None:
68
+ false_label, true_label = col.bool_labels
69
+ out = pl.Series(name, [None if t is None else (true_label if t else false_label)
70
+ for t in truth], dtype=pl.String)
71
+ if col.physical_dtype.startswith("Categorical"):
72
+ return out.cast(pl.Categorical)
73
+ return out
74
+ b = pl.Series(name, truth, dtype=pl.Boolean)
75
+ target = _target_dtype(col)
76
+ if target.is_integer():
77
+ return b.cast(target) # 0/1 coded source
78
+ return b
79
+
80
+
81
+ def as_boolean(s: pl.Series) -> pl.Series:
82
+ """Normalise a boolean-like column (Boolean, 0/1 ints, yes/no strings) to pl.Boolean."""
83
+ if s.dtype == pl.Boolean:
84
+ return s
85
+ low = s.cast(pl.String).str.to_lowercase()
86
+ return pl.Series(s.name, [None if v is None else (True if v in _TRUE else
87
+ False if v in _FALSE else None)
88
+ for v in low.to_list()], dtype=pl.Boolean)
89
+
90
+
91
+ #: ``ColumnSchema.pattern`` prefix of numbers stored as strings ("12.5", "40%"), see
92
+ #: ``profiling.structural.parse_numeric_strings``
93
+ NUMERIC_PARSE_PREFIX = "numeric_parse"
94
+
95
+
96
+ def _is_numeric_string(col: ColumnSchema) -> bool:
97
+ return col.logical_type in (LogicalType.CONTINUOUS, LogicalType.DISCRETE) and bool(col.pattern) and str(col.pattern).startswith(NUMERIC_PARSE_PREFIX)
98
+
99
+
100
+ def _numeric_strings(name: str, vals: np.ndarray, null: np.ndarray, col: ColumnSchema
101
+ ) -> pl.Series:
102
+ """Numbers written back in the source's string style: integers without a decimal point,
103
+ other values with the source's detected number of decimals (``col.decimals``; positional
104
+ notation without trailing zeros when unknown), a ``%`` suffix for the ``numeric_parse:%``
105
+ pattern, nulls as null."""
106
+ suffix = "%" if str(col.pattern).endswith(":%") else ""
107
+ out: list[str | None] = []
108
+ for x, m in zip(vals, null):
109
+ if m or not np.isfinite(x):
110
+ out.append(None)
111
+ elif col.integer_valued:
112
+ out.append(f"{int(x)}{suffix}")
113
+ elif col.decimals is not None:
114
+ out.append(f"{float(x):.{int(col.decimals)}f}{suffix}")
115
+ else:
116
+ out.append(np.format_float_positional(float(x), trim="-") + suffix)
117
+ return pl.Series(name, out, dtype=pl.String)
118
+
119
+
120
+ def column_to_values(s: pl.Series, col: ColumnSchema,
121
+ categories: np.ndarray | None = None) -> np.ndarray:
122
+ lt = col.logical_type
123
+ if lt == LogicalType.BOOLEAN:
124
+ if categories is not None and s.dtype != pl.Boolean \
125
+ and not {str(c) for c in categories} <= {"True", "False", OTHER}:
126
+ # labels recorded in source form (e.g. "0"/"1" for an integer flag): match them
127
+ # directly; normalising to True/False first would miss every label
128
+ return category_codes(s, categories)
129
+ s = as_boolean(s)
130
+ if lt in (LogicalType.CATEGORICAL, LogicalType.BOOLEAN):
131
+ if categories is None:
132
+ if lt == LogicalType.BOOLEAN and s.dtype == pl.Boolean:
133
+ return s.cast(pl.Float64).to_numpy().astype(np.float64)
134
+ raise ValueError(f"categories required to encode column {col.name!r}")
135
+ return category_codes(s, categories)
136
+ if lt == LogicalType.DATETIME:
137
+ if s.dtype == pl.Date:
138
+ return s.cast(pl.Int32).cast(pl.Float64).fill_null(np.nan).to_numpy()
139
+ if isinstance(s.dtype, pl.Datetime):
140
+ unit = s.dtype.time_unit or "us"
141
+ ints = s.dt.cast_time_unit("us") if unit != "us" else s
142
+ return ints.cast(pl.Int64).cast(pl.Float64).fill_null(np.nan).to_numpy()
143
+ if s.dtype == pl.String:
144
+ fmt = col.pattern or None
145
+ if col.is_date or col.datetime_unit == "d":
146
+ parsed = s.str.to_date(format=fmt, strict=False)
147
+ return parsed.cast(pl.Int32).cast(pl.Float64).fill_null(np.nan).to_numpy()
148
+ parsed = s.str.to_datetime(format=fmt, strict=False, time_unit="us")
149
+ if isinstance(parsed.dtype, pl.Datetime) and parsed.dtype.time_zone is not None:
150
+ parsed = parsed.dt.convert_time_zone("UTC").dt.replace_time_zone(None)
151
+ return parsed.cast(pl.Int64).cast(pl.Float64).fill_null(np.nan).to_numpy()
152
+ if _is_numeric_string(col) and s.dtype in (pl.String, pl.Categorical):
153
+ from ectype.profiling.structural import parse_numeric_strings
154
+ s = parse_numeric_strings(s, col.pattern)
155
+ if s.dtype == pl.Boolean:
156
+ s = s.cast(pl.Int8)
157
+ return s.cast(pl.Float64, strict=False).fill_null(np.nan).to_numpy().astype(np.float64)
158
+
159
+
160
+ _DT_RE = re.compile(r"time_unit='(\w+)'(?:, time_zone=(?:'([^']*)'|None))?")
161
+ _DEC_RE = re.compile(r"precision=(\d+|None), scale=(\d+)")
162
+
163
+
164
+ def _target_dtype(col: ColumnSchema) -> pl.DataType:
165
+ """Reconstruct the source polars dtype from its recorded string form."""
166
+ text = col.physical_dtype
167
+ base = text.split("(")[0]
168
+ if base == "Datetime":
169
+ m = _DT_RE.search(text)
170
+ return pl.Datetime(m.group(1) if m else "us", m.group(2) if m else None) # type: ignore[arg-type]
171
+ if base == "Decimal":
172
+ m = _DEC_RE.search(text)
173
+ if m:
174
+ prec = None if m.group(1) == "None" else int(m.group(1))
175
+ return pl.Decimal(prec, int(m.group(2)))
176
+ return pl.Float64()
177
+ if base in ("Enum", "Categorical", "Utf8"):
178
+ return pl.String()
179
+ try:
180
+ dt = getattr(pl, base)
181
+ except AttributeError:
182
+ return pl.Float64()
183
+ try:
184
+ return dt() if isinstance(dt, type) else dt
185
+ except TypeError:
186
+ return pl.Float64()
187
+
188
+
189
+ def values_to_column(v: np.ndarray, col: ColumnSchema,
190
+ categories: np.ndarray | None = None) -> pl.Series:
191
+ v = np.asarray(v, dtype=np.float64)
192
+ null = np.isnan(v)
193
+ lt = col.logical_type
194
+ name = col.name
195
+ if lt in (LogicalType.CATEGORICAL, LogicalType.BOOLEAN):
196
+ if categories is None:
197
+ if lt == LogicalType.BOOLEAN:
198
+ out = [None if m else bool(round(x)) for x, m in zip(v, null)]
199
+ if col.bool_labels is not None:
200
+ return _boolean_output(name, out, col)
201
+ return pl.Series(name, out, dtype=pl.Boolean)
202
+ raise ValueError(f"categories required to decode column {col.name!r}")
203
+ cats = np.asarray(categories).astype(str)
204
+ k = len(cats)
205
+ codes = np.clip(np.where(null, 0, np.rint(v)), 0, k - 1).astype(int)
206
+ labels = [None if m else cats[c] for c, m in zip(codes, null)]
207
+ if lt == LogicalType.BOOLEAN or col.physical_dtype == "Boolean":
208
+ return _boolean_output(name, [None if x is None else _truthy(x) for x in labels],
209
+ col)
210
+ s = pl.Series(name, labels, dtype=pl.String)
211
+ if col.physical_dtype.startswith(("String", "Enum", "Utf8")):
212
+ return s
213
+ if col.physical_dtype.startswith("Categorical"):
214
+ return s.cast(pl.Categorical)
215
+ if OTHER in labels:
216
+ # A pooled bucket cannot be represented in a numeric dtype: keep labels as strings
217
+ # rather than silently turning "__other__" into null.
218
+ return s
219
+ target = _target_dtype(col)
220
+ num = s.cast(pl.Float64, strict=False) if target.is_numeric() else s
221
+ return num.cast(target, strict=False)
222
+ if lt == LogicalType.DATETIME:
223
+ if col.is_date or col.datetime_unit == "d":
224
+ ints = np.where(null, 0, np.rint(v)).astype(np.int64)
225
+ s = pl.Series(name, ints).cast(pl.Int32).cast(pl.Date)
226
+ else:
227
+ ints = np.where(null, 0, np.rint(v)).astype(np.int64)
228
+ s = pl.Series(name, ints).cast(pl.Datetime("us"))
229
+ target = _target_dtype(col)
230
+ if isinstance(target, pl.Datetime) and target.time_unit not in (None, "us"):
231
+ s = s.dt.cast_time_unit(target.time_unit)
232
+ if col.timezone:
233
+ s = s.dt.replace_time_zone("UTC").dt.convert_time_zone(col.timezone)
234
+ if null.any():
235
+ s = s.scatter(np.flatnonzero(null), None)
236
+ if col.physical_dtype.startswith(("String", "Utf8")):
237
+ fmt = col.pattern or ("%Y-%m-%d" if (col.is_date or col.datetime_unit == "d")
238
+ else "%Y-%m-%dT%H:%M:%S%.f")
239
+ # "%#z" parses any UTC offset ("+02:00", "+0200", "Z") but cannot format one
240
+ s = s.dt.to_string(fmt.replace("%#z", "%:z"))
241
+ return s
242
+ vals = v.copy()
243
+ if col.decimals is not None and not col.integer_valued:
244
+ vals = np.round(vals, col.decimals)
245
+ if col.integer_valued:
246
+ vals = np.rint(vals)
247
+ target = _target_dtype(col)
248
+ if _is_numeric_string(col) and target == pl.String:
249
+ return _numeric_strings(name, vals, null, col)
250
+ if target.is_integer():
251
+ # saturate at the dtype's range rather than letting the cast turn the value into null
252
+ bounds = _int_bounds(target)
253
+ if bounds is not None:
254
+ vals = np.clip(vals, *bounds)
255
+ s = pl.Series(name, np.where(null, np.nan, vals)).fill_nan(None)
256
+ return s.cast(target, strict=False)
257
+
258
+
259
+ def _int_bounds(dtype: pl.DataType) -> tuple[float, float] | None:
260
+ """The integer dtype's range as floats that convert back without overflow (``None`` for
261
+ widths NumPy does not have, e.g. Int128)."""
262
+ try:
263
+ info = np.iinfo(str(dtype).lower())
264
+ except (TypeError, ValueError):
265
+ return None
266
+ lo, hi = float(info.min), float(info.max)
267
+ if hi > info.max: # 2**63 - 1 and 2**64 - 1 round up as float64
268
+ hi = float(np.nextafter(hi, -np.inf))
269
+ return lo, hi
ectype/llm/__init__.py ADDED
@@ -0,0 +1,27 @@
1
+ """LLM-assisted specification authoring (M35, design doc 8.2).
2
+
3
+ An LLM authors *specifications* (``mutate`` keyword arguments or ``build_from_spec`` dicts),
4
+ never rows. It sees only the fingerprint's schema summary, its output passes the same
5
+ validation as hand-written requests, and nothing runs until ``draft.apply(...)``.
6
+ """
7
+
8
+ from ectype.llm.authoring import (
9
+ ScenarioDraft,
10
+ draft_scenario,
11
+ manifest_summary,
12
+ validate_mutate,
13
+ validate_spec,
14
+ )
15
+ from ectype.llm.providers import (
16
+ AnthropicProvider,
17
+ PromptRequest,
18
+ Provider,
19
+ ProviderError,
20
+ RuleBasedProvider,
21
+ extract_json,
22
+ provider_from_env,
23
+ )
24
+
25
+ __all__ = ["AnthropicProvider", "PromptRequest", "Provider", "ProviderError",
26
+ "RuleBasedProvider", "ScenarioDraft", "draft_scenario", "extract_json",
27
+ "manifest_summary", "provider_from_env", "validate_mutate", "validate_spec"]