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,429 @@
1
+ """Words and numbers for the profile report (ADR-0016).
2
+
3
+ Pure functions of plain values: standard library only, no engine knowledge. Every function
4
+ accepts ``None`` and non-finite numbers and returns a printable string (``"–"``, an en dash,
5
+ for "no value"). Label functions return any string they have no words for unchanged, so new
6
+ vocabulary in a fingerprint is shown as found, never guessed.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import math
12
+ from collections.abc import Sequence
13
+ from datetime import datetime, timedelta
14
+
15
+ #: shown for a value that is missing, not a number or infinite
16
+ DASH = "–"
17
+ #: shown where a label is needed and the fingerprint recorded nothing
18
+ NOT_RECORDED = "not recorded"
19
+
20
+ _MONTHS = ("Jan", "Feb", "Mar", "Apr", "May", "Jun",
21
+ "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
22
+
23
+ #: seconds per epoch / duration unit
24
+ _UNIT_SECONDS: dict[str, float] = {
25
+ "d": 86400.0, "h": 3600.0, "m": 60.0, "s": 1.0,
26
+ "ms": 1e-3, "us": 1e-6, "ns": 1e-9,
27
+ }
28
+
29
+ _EPOCH = datetime(1970, 1, 1)
30
+
31
+
32
+ def _finite(x: object) -> float | None:
33
+ """``x`` as a finite float, or ``None``."""
34
+ if x is None:
35
+ return None
36
+ try:
37
+ v = float(x) # type: ignore[arg-type]
38
+ except (TypeError, ValueError, OverflowError):
39
+ return None
40
+ return v if math.isfinite(v) else None
41
+
42
+
43
+ def _no_negative_zero(text: str) -> str:
44
+ if text.startswith("-") and not any(ch in "123456789" for ch in text.split("e")[0]):
45
+ return text[1:]
46
+ return text
47
+
48
+
49
+ def _strip_zeros(text: str) -> str:
50
+ if "." in text:
51
+ text = text.rstrip("0").rstrip(".")
52
+ return text
53
+
54
+
55
+ # -- numbers ----------------------------------------------------------------------------------
56
+
57
+ _COMPACT = ((1e12, "T"), (1e9, "B"), (1e6, "M"))
58
+
59
+
60
+ def _compact(v: float, digits: int) -> str:
61
+ av = abs(v)
62
+ if av >= 1e15:
63
+ return _scientific(v, digits)
64
+ for i, (size, suffix) in enumerate(_COMPACT):
65
+ if av >= size:
66
+ scaled = float(f"{v / size:.{digits}g}")
67
+ if abs(scaled) >= 1000 and i > 0: # 999.96M rounds to 1,000M: say 1B
68
+ bigger, big_suffix = _COMPACT[i - 1]
69
+ scaled = float(f"{v / bigger:.{digits}g}")
70
+ suffix = big_suffix
71
+ elif abs(scaled) >= 1000:
72
+ return _scientific(v, digits)
73
+ return _no_negative_zero(_strip_zeros(f"{scaled:.{digits}g}")) + suffix
74
+ return _scientific(v, digits) # pragma: no cover - callers pass values >= 1e6
75
+
76
+
77
+ def _scientific(v: float, digits: int) -> str:
78
+ mant, _, exp = f"{v:.{max(digits, 1)}g}".partition("e")
79
+ if not exp: # .g chose fixed notation; force the exponent form
80
+ mant, _, exp = f"{v:.{max(digits - 1, 0)}e}".partition("e")
81
+ mant = _strip_zeros(mant)
82
+ sign = "-" if exp.startswith("-") else ""
83
+ return f"{mant}e{sign}{int(exp.lstrip('+-'))}"
84
+
85
+
86
+ def number(x: float | None, digits: int = 3) -> str:
87
+ """A number for reading: ``"1,284"``, ``"0.042"``, ``"12,900"``, ``"4.2M"``, ``"3.1e-6"``.
88
+
89
+ Whole numbers below a million are written in full with thousands separators; other values
90
+ keep at most ``digits`` significant digits. From a million up the value is compact
91
+ (``M``, ``B``, ``T``), then scientific. Values below ``1e-4`` are scientific. ``None``,
92
+ NaN and infinities give ``"–"``. Never ``"-0"``.
93
+ """
94
+ v = _finite(x)
95
+ if v is None:
96
+ return DASH
97
+ digits = max(1, int(digits))
98
+ if v == 0:
99
+ return "0"
100
+ av = abs(v)
101
+ if av >= 1e6:
102
+ return _compact(v, digits)
103
+ if v.is_integer():
104
+ return f"{int(v):,}"
105
+ if av < 1e-4:
106
+ return _no_negative_zero(_scientific(v, digits))
107
+ decimals = digits - 1 - math.floor(math.log10(av))
108
+ if decimals > 0:
109
+ text = _strip_zeros(f"{v:,.{decimals}f}")
110
+ else:
111
+ rounded = round(v, decimals)
112
+ if abs(rounded) >= 1e6:
113
+ return _compact(rounded, digits)
114
+ text = f"{int(rounded):,}"
115
+ return _no_negative_zero(text)
116
+
117
+
118
+ def count(n: int | float | None) -> str:
119
+ """A whole number with thousands separators (``"12,900"``); ``"–"`` when not known."""
120
+ v = _finite(n)
121
+ if v is None:
122
+ return DASH
123
+ if abs(v) >= 1e18:
124
+ return number(v)
125
+ text = f"{round(v):,}"
126
+ return _no_negative_zero(text)
127
+
128
+
129
+ def share(x: float | None) -> str:
130
+ """A share of a whole as a percentage: ``"0%"``, ``"<0.1%"``, ``"4.2%"``, ``"37%"``,
131
+ ``">99.9%"``, ``"100%"``. Values are clamped to ``[0, 1]``; ``None`` and NaN give ``"–"``."""
132
+ v = _finite(x)
133
+ if v is None:
134
+ return DASH
135
+ if v <= 0:
136
+ return "0%"
137
+ if v >= 1:
138
+ return "100%"
139
+ if v < 0.001:
140
+ return "<0.1%"
141
+ if v > 0.999:
142
+ return ">99.9%"
143
+ pct = 100 * v
144
+ if pct < 9.95:
145
+ return f"{pct:.1f}%"
146
+ if pct >= 99.5: # would round to 100%: keep the decimal
147
+ return f"{pct:.1f}%"
148
+ return f"{pct:.0f}%"
149
+
150
+
151
+ # -- time -------------------------------------------------------------------------------------
152
+
153
+
154
+ def _to_datetime(value: float | None, unit: str) -> datetime | None:
155
+ v = _finite(value)
156
+ factor = _UNIT_SECONDS.get(unit)
157
+ if v is None or factor is None:
158
+ return None
159
+ try:
160
+ if unit == "d":
161
+ return _EPOCH + timedelta(days=v)
162
+ whole = math.floor(v)
163
+ seconds = whole * factor
164
+ frac = (v - whole) * factor
165
+ return _EPOCH + timedelta(seconds=seconds) + timedelta(seconds=frac)
166
+ except (OverflowError, ValueError):
167
+ return None
168
+
169
+
170
+ def date(value: float | None, unit: str, *, time: bool = False) -> str:
171
+ """An epoch value (in ``unit``: ``"d"``, ``"s"``, ``"ms"``, ``"us"``, ``"ns"``, since
172
+ 1970-01-01 UTC) as ``"3 Jan 2023"`` or, with ``time``, ``"3 Jan 2023 14:05"``. Month names
173
+ are English whatever the locale. ``"–"`` for a missing, non-finite or out-of-range value;
174
+ an unknown unit gives the plain number."""
175
+ if _finite(value) is not None and unit not in _UNIT_SECONDS:
176
+ return number(value)
177
+ d = _to_datetime(value, unit)
178
+ if d is None:
179
+ return DASH
180
+ text = f"{d.day} {_MONTHS[d.month - 1]} {d.year}"
181
+ if time:
182
+ text += f" {d.hour:02d}:{d.minute:02d}"
183
+ return text
184
+
185
+
186
+ def _unit_word(n_text: str, one: str, many: str) -> str:
187
+ return f"{n_text} {one if n_text == '1' else many}"
188
+
189
+
190
+ def duration(value: float | None, unit: str) -> str:
191
+ """A length of time in ``unit`` in its one or two largest sensible units: ``"0"``,
192
+ ``"850 ms"``, ``"42 s"``, ``"4 min 12 s"``, ``"2 h 5 min"``, ``"3.2 days"`` (days up to
193
+ 730), ``"2.4 years"``. Negative values carry a minus sign. An unknown unit gives the
194
+ number followed by the unit as stored."""
195
+ v = _finite(value)
196
+ if v is None:
197
+ return DASH
198
+ factor = _UNIT_SECONDS.get(unit)
199
+ if factor is None:
200
+ text = number(v)
201
+ return f"{text} {unit}" if unit else text
202
+ secs = v * factor
203
+ if not math.isfinite(secs):
204
+ return DASH
205
+ if secs == 0:
206
+ return "0"
207
+ sign = "-" if secs < 0 else ""
208
+ s = abs(secs)
209
+ if s < 1e-6:
210
+ body = f"{number(s * 1e9)} ns"
211
+ elif s < 1e-3:
212
+ body = f"{number(s * 1e6)} µs"
213
+ elif s < 1:
214
+ body = f"{number(s * 1e3)} ms"
215
+ elif s < 59.5:
216
+ body = f"{number(s)} s"
217
+ elif s < 3600 - 0.5:
218
+ m, sec = divmod(round(s), 60)
219
+ body = f"{m} min" + (f" {sec} s" if sec else "")
220
+ elif s < 86400:
221
+ h, m = divmod(round(s / 60), 60)
222
+ if h >= 24:
223
+ body = "1 day"
224
+ else:
225
+ body = f"{h} h" + (f" {m} min" if m else "")
226
+ else:
227
+ days = s / 86400
228
+ if days < 730:
229
+ text = f"{days:.1f}" if days < 10 else f"{round(days):,}"
230
+ text = _strip_zeros(text)
231
+ body = _unit_word(text, "day", "days")
232
+ else:
233
+ years = days / 365.25
234
+ text = _strip_zeros(f"{years:.1f}") if years < 10 else number(years)
235
+ body = _unit_word(text, "year", "years")
236
+ return sign + body
237
+
238
+
239
+ def axis_value(x: float | None, axis: str, unit: str = "", *, span: float | None = None) -> str:
240
+ """A value of a histogram axis (:attr:`Histogram.axis`): numbers with :func:`number`,
241
+ dates with :func:`date` (with the time of day when ``span``, the axis length in the same
242
+ unit, is under three days), durations with :func:`duration`, shares with :func:`share`.
243
+ An unknown axis is treated as numbers."""
244
+ if axis == "date":
245
+ with_time = False
246
+ span_v = _finite(span)
247
+ factor = _UNIT_SECONDS.get(unit)
248
+ if span_v is not None and factor is not None:
249
+ with_time = abs(span_v) * factor < 3 * 86400
250
+ return date(x, unit, time=with_time)
251
+ if axis == "duration":
252
+ return duration(x, unit)
253
+ if axis == "share":
254
+ return share(x)
255
+ return _number_on_axis(x, span)
256
+
257
+
258
+ def _number_on_axis(x: float | None, span: float | None) -> str:
259
+ """A number on an axis of length ``span``: with enough digits to tell the two ends of the
260
+ axis apart. Three digits do for most columns, but a counter that runs from 230,011,000 to
261
+ 230,613,000 would read "230M to 231M"; such values are written in full, rounded to the
262
+ digits that matter."""
263
+ v, s = _finite(x), _finite(span)
264
+ if v is None:
265
+ return DASH
266
+ if s is None or s <= 0 or v == 0 or abs(v) <= s:
267
+ return number(v)
268
+ digits = min(max(3, math.ceil(math.log10(abs(v) / s)) + 3), 12)
269
+ if digits <= 4:
270
+ return number(v)
271
+ if abs(v) >= 1e6:
272
+ if abs(v) >= 1e15:
273
+ return number(v, digits)
274
+ place = digits - 1 - math.floor(math.log10(abs(v)))
275
+ return _no_negative_zero(f"{round(v, place):,.{max(place, 0)}f}")
276
+ return number(v, digits)
277
+
278
+
279
+ # -- words ------------------------------------------------------------------------------------
280
+
281
+
282
+ def plural(n: int | float, one: str, many: str | None = None) -> str:
283
+ """``"1 column"``, ``"3 columns"`` (``many`` defaults to ``one + "s"``)."""
284
+ word = one if n == 1 else (many if many is not None else one + "s")
285
+ return f"{count(n)} {word}"
286
+
287
+
288
+ def join(names: Sequence[str], limit: int = 3) -> str:
289
+ """``"A"``, ``"A and B"``, ``"A, B and C"``, ``"A, B, C and 4 more"``."""
290
+ items = [str(n) for n in names]
291
+ limit = max(1, int(limit))
292
+ if not items:
293
+ return ""
294
+ if len(items) > limit:
295
+ return ", ".join(items[:limit]) + f" and {count(len(items) - limit)} more"
296
+ if len(items) == 1:
297
+ return items[0]
298
+ return ", ".join(items[:-1]) + " and " + items[-1]
299
+
300
+
301
+ def truncate(text: str, limit: int) -> str:
302
+ """``text`` cut to at most ``limit`` characters, ending with an ellipsis when cut."""
303
+ text = "" if text is None else str(text)
304
+ if limit <= 0:
305
+ return ""
306
+ if len(text) <= limit:
307
+ return text
308
+ if limit == 1:
309
+ return "…"
310
+ return text[: limit - 1].rstrip() + "…"
311
+
312
+
313
+ def _label(table: dict[str, str], key: str | None) -> str:
314
+ if key is None or key == "":
315
+ return NOT_RECORDED
316
+ return table.get(key, key)
317
+
318
+
319
+ _TYPES = {
320
+ "continuous": "decimal number",
321
+ "discrete": "whole number",
322
+ "categorical": "category",
323
+ "boolean": "yes / no",
324
+ "datetime": "date and time",
325
+ "date": "date",
326
+ "string": "structured text",
327
+ "text": "free text",
328
+ }
329
+
330
+
331
+ def type_label(logical_type: str | None, is_date: bool = False) -> str:
332
+ """The logical type in words; ``is_date`` turns ``"datetime"`` into ``"date"``."""
333
+ if logical_type == "datetime" and is_date:
334
+ return "date"
335
+ return _label(_TYPES, logical_type)
336
+
337
+
338
+ _FAMILIES = {
339
+ "normal": "normal",
340
+ "lognormal": "log-normal",
341
+ "gamma": "gamma",
342
+ "beta": "beta",
343
+ "uniform": "uniform",
344
+ "poisson": "Poisson",
345
+ "negbinom": "negative binomial",
346
+ "exponential": "exponential",
347
+ "weibull": "Weibull",
348
+ }
349
+
350
+ _MODELS = {
351
+ **_FAMILIES,
352
+ "mixed": "point masses and a curve",
353
+ "empirical": "stored quantiles",
354
+ "discrete_empirical": "stored values",
355
+ "categorical": "stored frequencies",
356
+ "summary": "mean and spread only",
357
+ "date": "stored dates",
358
+ }
359
+
360
+
361
+ def model_label(kind: str | None, slab: str | None = None) -> str:
362
+ """The kind of a fitted column model in words. A ``"mixed"`` model whose smooth part is a
363
+ named family says so (``"point masses and a log-normal curve"``)."""
364
+ if kind == "mixed" and slab in _FAMILIES:
365
+ return f"point masses and a {_FAMILIES[slab]} curve"
366
+ return _label(_MODELS, kind)
367
+
368
+
369
+ _HANDLINGS = {
370
+ "modeled": "modeled",
371
+ "computed": "computed",
372
+ "offset": "modeled as a gap",
373
+ "share": "share of a total",
374
+ "total": "sum of its parts",
375
+ "identifier": "regenerated key",
376
+ "reference": "repeating key",
377
+ "pseudonym": "stand-in tokens",
378
+ "constant": "constant",
379
+ "excluded": "left out",
380
+ "unknown": "not described",
381
+ }
382
+
383
+
384
+ def handling_label(handling: str | None) -> str:
385
+ """How a column is produced (:attr:`ColumnView.handling`), in a few words."""
386
+ return _label(_HANDLINGS, handling)
387
+
388
+
389
+ _MEASURES = {
390
+ "spearman": "rank correlation",
391
+ "pearson": "correlation",
392
+ "kendall": "Kendall's tau",
393
+ "cramers_v": "Cramér's V",
394
+ "correlation_ratio": "correlation ratio",
395
+ "mutual_information": "mutual information",
396
+ "theils_u": "Theil's U",
397
+ }
398
+
399
+
400
+ def measure_label(measure: str | None) -> str:
401
+ """An association measure in words."""
402
+ return _label(_MEASURES, measure)
403
+
404
+
405
+ _JOINTS = {
406
+ "independent": "independent columns",
407
+ "gaussian_copula": "Gaussian copula",
408
+ "gaussian_mixture_copula": "mixture of Gaussian copulas",
409
+ "vine_copula": "vine copula",
410
+ "forest_copula": "forest copula",
411
+ "chain_copula": "chain of copulas",
412
+ }
413
+
414
+
415
+ def joint_label(kind: str | None) -> str:
416
+ """The model of how columns move together, in words."""
417
+ return _label(_JOINTS, kind)
418
+
419
+
420
+ def anchor(prefix: str, index: int) -> str:
421
+ """A stable id for links: ``anchor("col", 12) == "col-12"``."""
422
+ return f"{prefix}-{int(index)}"
423
+
424
+
425
+ __all__ = [
426
+ "DASH", "NOT_RECORDED", "anchor", "axis_value", "count", "date", "duration", "handling_label",
427
+ "join", "joint_label", "measure_label", "model_label", "number", "plural", "share",
428
+ "truncate", "type_label",
429
+ ]