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/cli.py ADDED
@@ -0,0 +1,1181 @@
1
+ """Command-line interface: ``ectype <command> ...``.
2
+
3
+ Commands: profile, inspect, constraints, generate, validate, compare, schema, report.
4
+
5
+ Exit codes: 0 ok; 1 validation failed (or drift found with ``--fail-on-drift``; or, for
6
+ ``mutate`` / ``calibrate``, the change was not achieved / calibration did not converge -- the
7
+ output file is still written; ``--allow-partial`` turns this into exit 0);
8
+ 2 usage error; 3 library error (:class:`EctypeError`).
9
+ Errors print one line to stderr; ``--debug`` re-raises with the full traceback.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import json
16
+ import math
17
+ import os
18
+ import re
19
+ import sys
20
+ import tempfile
21
+ from collections.abc import Sequence
22
+ from pathlib import Path
23
+ from typing import TYPE_CHECKING, Any
24
+
25
+ from ectype._version import FORMAT_VERSION, __version__
26
+ from ectype.errors import EctypeError
27
+
28
+ if TYPE_CHECKING:
29
+ from ectype.generation.manifest import GenerationManifest
30
+
31
+ EXIT_OK = 0
32
+ EXIT_FAILED = 1
33
+ EXIT_USAGE = 2
34
+ EXIT_ERROR = 3
35
+
36
+ PROG = "ectype"
37
+
38
+ #: output suffix -> format understood by the generator / io.write_table
39
+ _OUTPUT_FORMATS = {
40
+ ".parquet": "parquet",
41
+ ".pq": "parquet",
42
+ ".csv": "csv",
43
+ ".arrow": "ipc",
44
+ ".ipc": "ipc",
45
+ ".feather": "ipc",
46
+ }
47
+
48
+
49
+ class UsageError(Exception):
50
+ """Bad command-line usage detected after argument parsing (exit code 2)."""
51
+
52
+
53
+ #: joint models selectable with ``ectype profile --joint`` (the ones that need no optional
54
+ #: extra); the first is the default (``ectype.models.base.DEFAULT_JOINT``)
55
+ CLI_JOINTS = ("chain_copula", "gaussian_copula", "forest_copula", "gaussian_mixture_copula",
56
+ "vine_copula", "auto", "independent")
57
+
58
+
59
+ def _joint_option(text: str) -> tuple[str, Any]:
60
+ """``KEY=VALUE`` of ``--joint-option``: a number, ``none``, ``true``/``false`` or text."""
61
+ key, value = _split_assignment(text, "--joint-option")
62
+ low = value.strip().lower()
63
+ if low in ("none", "null"):
64
+ return key, None
65
+ if low in ("true", "false"):
66
+ return key, low == "true"
67
+ for cast in (int, float):
68
+ try:
69
+ return key, cast(value)
70
+ except ValueError:
71
+ pass
72
+ return key, value
73
+
74
+
75
+ def _joint_line(fp: Any) -> str:
76
+ """Which joint model a fingerprint was fitted with, why, and what was limited."""
77
+ m = fp.manifest
78
+ if m.model.joint is None:
79
+ return "joint model: none (no modeled columns)"
80
+ info = (fp.diagnostics or {}).get("joint") or {}
81
+ line = f"joint model: {m.model.joint.kind}"
82
+ if info.get("reason"):
83
+ line += f" ({info['reason']})"
84
+ note = (info.get("limits") or {}).get("note")
85
+ if note:
86
+ line += f"; {note}"
87
+ return line
88
+
89
+
90
+ def cmd_calibrate(args: argparse.Namespace) -> int:
91
+ from ectype.calibration import calibrate
92
+
93
+ fp = _load_fp(args.fingerprint)
94
+ result = calibrate(fp, budget_iterations=args.iterations, n_samples=args.samples,
95
+ seed=args.seed, tolerance_scale=args.tolerance_scale,
96
+ time_budget_s=args.time_budget)
97
+ out = result.fingerprint.save(args.output)
98
+ _out(result.summary())
99
+ if args.report:
100
+ Path(args.report).write_text(json.dumps(result.to_dict(), indent=2, default=str),
101
+ encoding="utf-8")
102
+ _out(f"wrote {out}")
103
+ if not result.converged:
104
+ return _partial(args, f"calibration did not converge ({result.stopped_reason}); the "
105
+ f"best fingerprint found was still written to {out}")
106
+ return EXIT_OK
107
+
108
+
109
+ def _partial(args: argparse.Namespace, message: str) -> int:
110
+ """Exit code for a result that was written but not fully achieved."""
111
+ if getattr(args, "allow_partial", False):
112
+ _out(f"note: {message} (--allow-partial: exit 0)")
113
+ return EXIT_OK
114
+ print(f"{PROG}: {message}; pass --allow-partial to accept it", file=sys.stderr)
115
+ return EXIT_FAILED
116
+
117
+
118
+ def _parse_kv(items: list[str] | None, cast: Any = float) -> dict[str, Any]:
119
+ out: dict[str, Any] = {}
120
+ for item in items or []:
121
+ if "=" not in item:
122
+ raise UsageError(f"expected COLUMN=VALUE, got {item!r}")
123
+ k, v = item.split("=", 1)
124
+ out[k.strip()] = cast(v)
125
+ return out
126
+
127
+
128
+ def cmd_mutate(args: argparse.Namespace) -> int:
129
+ from ectype.scenarios import mutate
130
+
131
+ fp = _load_fp(args.fingerprint)
132
+ corr = {}
133
+ for item in args.correlation or []:
134
+ pair, _, val = item.partition("=")
135
+ a, _, b = pair.partition(",")
136
+ if not (a and b and val):
137
+ raise UsageError(f"--correlation expects A,B=RHO, got {item!r}")
138
+ corr[(a.strip(), b.strip())] = float(val)
139
+ kwargs: dict[str, Any] = {k: v for k, v in {
140
+ "shift": _parse_kv(args.shift), "scale": _parse_kv(args.scale),
141
+ "mean_multiplier": _parse_kv(args.mean_multiplier),
142
+ "missing_rate": _parse_kv(args.missing_rate), "correlation": corr,
143
+ }.items() if v}
144
+ if args.spec:
145
+ kwargs.update(json.loads(Path(_existing(args.spec, "spec")).read_text(encoding="utf-8")))
146
+ if not kwargs:
147
+ raise UsageError("no changes requested")
148
+ result = mutate(fp, seed=args.seed, **kwargs)
149
+ out = result.fingerprint.save(args.output)
150
+ _out(result.summary() if hasattr(result, "summary") else str(result.achieved))
151
+ _out(f"wrote {out}")
152
+ if not getattr(result, "ok", True):
153
+ return _partial(args, f"some requested changes were not achieved; the mutated "
154
+ f"fingerprint was still written to {out}")
155
+ return EXIT_OK
156
+
157
+
158
+ def cmd_merge(args: argparse.Namespace) -> int:
159
+ from ectype.scenarios import merge
160
+
161
+ fps = [_load_fp(p) for p in args.fingerprints]
162
+ weights = [float(w) for w in args.weights.split(",")] if args.weights else None
163
+ out = merge(fps, weights, seed=args.seed).save(args.output)
164
+ _out(f"wrote {out}")
165
+ return EXIT_OK
166
+
167
+
168
+ def cmd_author(args: argparse.Namespace) -> int:
169
+ from ectype.authoring import build_from_spec
170
+
171
+ spec = json.loads(Path(_existing(args.spec, "spec")).read_text(encoding="utf-8"))
172
+ build: dict[str, Any] = {"seed": args.seed}
173
+ if args.policy:
174
+ build["policy"] = args.policy
175
+ out = build_from_spec(spec, **build).save(args.output)
176
+ _out(f"wrote {out}")
177
+ return EXIT_OK
178
+
179
+
180
+ def _tables_arg(items: list[str] | None) -> dict[str, Any]:
181
+ from ectype.io import read_table
182
+
183
+ tables: dict[str, Any] = {}
184
+ for item in items or []:
185
+ name, sep, path = item.partition("=")
186
+ if not sep:
187
+ raise UsageError(f"--table expects NAME=PATH, got {item!r}")
188
+ tables[name.strip()] = read_table(_existing(path, "table"))
189
+ if not tables:
190
+ raise UsageError("at least one --table NAME=PATH is required")
191
+ return tables
192
+
193
+
194
+ def cmd_relational(args: argparse.Namespace) -> int:
195
+ from ectype import relational as rel
196
+
197
+ if args.rel_command == "profile":
198
+ schema = json.loads(Path(_existing(args.schema, "schema")).read_text(encoding="utf-8"))
199
+ rfp = rel.RelationalProfiler(schema, policy=args.policy, seed=args.seed).fit(
200
+ _tables_arg(args.table))
201
+ _out(f"wrote {rfp.save(args.output)}")
202
+ return EXIT_OK
203
+ if args.rel_command == "generate":
204
+ from ectype.io import write_table
205
+
206
+ rfp = rel.load_relational(_existing(args.fingerprint, "relational fingerprint"))
207
+ tables = rel.RelationalGenerator(rfp).generate(n_root=args.rows, seed=args.seed)
208
+ out_dir = Path(args.output)
209
+ out_dir.mkdir(parents=True, exist_ok=True)
210
+ for name, df in tables.items():
211
+ path = write_table(df, out_dir / f"{name}.{args.format}")
212
+ _out(f"wrote {df.height} rows to {path}")
213
+ return EXIT_OK
214
+ rfp = rel.load_relational(_existing(args.fingerprint, "relational fingerprint"))
215
+ report = rel.validate_relational(rfp, _tables_arg(args.table))
216
+ _out(report.summary())
217
+ if args.json:
218
+ Path(args.json).write_text(json.dumps(report.to_dict(), indent=2, default=str),
219
+ encoding="utf-8")
220
+ return EXIT_OK if report.relational_passed else EXIT_FAILED
221
+
222
+
223
+ def cmd_timeseries(args: argparse.Namespace) -> int:
224
+ from ectype.io import write_table
225
+ from ectype.temporal.pipeline import generate_temporal
226
+
227
+ fp = _load_fp(args.fingerprint)
228
+ req: dict[str, Any] = {"count_policy": args.count_policy}
229
+ if args.entities is not None:
230
+ req["n_entities"] = args.entities
231
+ for key in ("start", "end", "periods", "freq", "rows"):
232
+ val = getattr(args, key)
233
+ if val is not None:
234
+ req["n_rows" if key == "rows" else key] = val
235
+ df = generate_temporal(fp, seed=args.seed, **req)
236
+ out = write_table(df, args.output)
237
+ _out(f"wrote {df.height} rows to {out}")
238
+ return EXIT_OK
239
+
240
+
241
+ # Small helpers
242
+ # ---------------------------------------------------------------------------------------------
243
+
244
+
245
+ def _out(text: str = "") -> None:
246
+ sys.stdout.write(text + ("" if text.endswith("\n") else "\n"))
247
+
248
+
249
+ def _existing(path: str, what: str = "file") -> Path:
250
+ p = Path(path)
251
+ if not p.exists():
252
+ raise UsageError(f"{what} not found: {path}")
253
+ return p
254
+
255
+
256
+ def _load_fp(path: str) -> Any:
257
+ from ectype.fingerprint.core import Fingerprint
258
+
259
+ return Fingerprint.load(_existing(path, "fingerprint"))
260
+
261
+
262
+ def _split_assignment(text: str, flag: str) -> tuple[str, str]:
263
+ if "=" not in text:
264
+ raise UsageError(f"{flag} expects NAME=VALUE, got {text!r}")
265
+ name, value = text.split("=", 1)
266
+ name, value = name.strip(), value.strip()
267
+ if not name or not value:
268
+ raise UsageError(f"{flag} expects NAME=VALUE, got {text!r}")
269
+ return name, value
270
+
271
+
272
+ def _parse_overrides(items: Sequence[str]) -> dict[str, dict[str, Any]]:
273
+ from ectype.types import LogicalType, Role
274
+
275
+ types = {t.value for t in LogicalType}
276
+ roles = {r.value for r in Role}
277
+ out: dict[str, dict[str, Any]] = {}
278
+ for item in items:
279
+ col, spec = _split_assignment(item, "--override")
280
+ ltype, _, role = spec.partition(":")
281
+ ltype, role = ltype.strip().lower(), role.strip().lower()
282
+ entry: dict[str, Any] = {}
283
+ if ltype:
284
+ if ltype not in types:
285
+ raise UsageError(f"--override {item!r}: unknown logical type {ltype!r} "
286
+ f"(choose from {', '.join(sorted(types))})")
287
+ entry["logical_type"] = ltype
288
+ if role:
289
+ if role not in roles:
290
+ raise UsageError(f"--override {item!r}: unknown role {role!r} "
291
+ f"(choose from {', '.join(sorted(roles))})")
292
+ entry["role"] = role
293
+ if not entry:
294
+ raise UsageError(f"--override {item!r} sets nothing")
295
+ out.setdefault(col, {}).update(entry)
296
+ return out
297
+
298
+
299
+ def _write_atomic(fp: Any, target: Path) -> Path:
300
+ """Save a fingerprint via a temp file in the same directory, then replace ``target``."""
301
+ target.parent.mkdir(parents=True, exist_ok=True)
302
+ fd, tmp = tempfile.mkstemp(prefix=f".{target.name}.", suffix=".tmp", dir=target.parent)
303
+ os.close(fd)
304
+ try:
305
+ fp.save(tmp)
306
+ os.replace(tmp, target)
307
+ finally:
308
+ if os.path.exists(tmp):
309
+ os.remove(tmp)
310
+ return target
311
+
312
+
313
+ # ---------------------------------------------------------------------------------------------
314
+ # Minimal YAML emitter (block style; JSON-compatible scalars)
315
+ # ---------------------------------------------------------------------------------------------
316
+
317
+ _PLAIN = re.compile(r"^[A-Za-z_./][A-Za-z0-9_./ +\-()]*$")
318
+ _RESERVED = {"y", "n", "yes", "no", "on", "off", "true", "false", "null", "none", "~"}
319
+
320
+
321
+ def _yaml_scalar(v: Any) -> str:
322
+ if v is None:
323
+ return "null"
324
+ if isinstance(v, bool):
325
+ return "true" if v else "false"
326
+ if isinstance(v, int):
327
+ return str(v)
328
+ if isinstance(v, float):
329
+ if math.isnan(v):
330
+ return ".nan"
331
+ if math.isinf(v):
332
+ return ".inf" if v > 0 else "-.inf"
333
+ return repr(v)
334
+ s = str(v)
335
+ if (_PLAIN.match(s) and s.lower() not in _RESERVED and not s.endswith(" ")
336
+ and ": " not in s and " #" not in s):
337
+ return s
338
+ return json.dumps(s, ensure_ascii=False)
339
+
340
+
341
+ def _yaml_key(k: Any) -> str:
342
+ return _yaml_scalar(str(k))
343
+
344
+
345
+ def _yaml_lines(obj: Any, indent: int) -> list[str]:
346
+ pad = " " * indent
347
+ lines: list[str] = []
348
+ if isinstance(obj, dict):
349
+ for k, v in obj.items():
350
+ key = _yaml_key(k)
351
+ if isinstance(v, dict) and v:
352
+ lines.append(f"{pad}{key}:")
353
+ lines.extend(_yaml_lines(v, indent + 2))
354
+ elif isinstance(v, (list, tuple)) and v:
355
+ lines.append(f"{pad}{key}:")
356
+ lines.extend(_yaml_lines(list(v), indent + 2))
357
+ else:
358
+ lines.append(f"{pad}{key}: {_yaml_inline(v)}")
359
+ elif isinstance(obj, (list, tuple)):
360
+ for v in obj:
361
+ if isinstance(v, dict) and v:
362
+ sub = _yaml_lines(v, indent + 2)
363
+ lines.append(f"{pad}- {sub[0].lstrip()}")
364
+ lines.extend(sub[1:])
365
+ elif isinstance(v, (list, tuple)) and v:
366
+ sub = _yaml_lines(list(v), indent + 2)
367
+ lines.append(f"{pad}- {sub[0].lstrip()}")
368
+ lines.extend(sub[1:])
369
+ else:
370
+ lines.append(f"{pad}- {_yaml_inline(v)}")
371
+ else:
372
+ lines.append(f"{pad}{_yaml_inline(obj)}")
373
+ return lines
374
+
375
+
376
+ def _yaml_inline(v: Any) -> str:
377
+ if isinstance(v, dict):
378
+ return "{}"
379
+ if isinstance(v, (list, tuple)):
380
+ return "[]"
381
+ return _yaml_scalar(v)
382
+
383
+
384
+ def to_yaml(obj: Any) -> str:
385
+ """Render JSON-like data as block-style YAML (no external dependency)."""
386
+ return "\n".join(_yaml_lines(obj, 0)) + "\n"
387
+
388
+
389
+ # ---------------------------------------------------------------------------------------------
390
+ # Rendering
391
+ # ---------------------------------------------------------------------------------------------
392
+
393
+
394
+ def _public_manifest(fp: Any) -> dict[str, Any]:
395
+ """The manifest as JSON data. Sealed targets are never included (counts/families only)."""
396
+ m = fp.manifest.model_dump(mode="json")
397
+ targets = m.get("targets", {})
398
+ m["targets"] = {k: v for k, v in targets.items()
399
+ if k in {"calibration_ref", "n_calibration", "n_sealed", "sealed_families",
400
+ "sealed_fraction", "seal_hash", "partition_seed"}}
401
+ return m
402
+
403
+
404
+ def _transform_model(t: Any, m: Any) -> str:
405
+ """The effective model of a column computed by a structural transform, for the summary's
406
+ column table: ``"start + delta (gamma)"`` for a difference (the hidden delta is what is
407
+ modeled, with that marginal) or ``"qty * price"`` for an identity (nothing is modeled)."""
408
+ if t.kind == "difference" and len(t.inputs) == 1:
409
+ spec = m.model.marginals.get(str(t.params.get("latent")))
410
+ op = "+" if t.params.get("sign", 1) == 1 else "-"
411
+ return f"{t.inputs[0]} {op} delta ({spec.kind if spec is not None else '?'})"
412
+ if t.kind == "identity" and len(t.inputs) == 2:
413
+ return f"{t.inputs[0]} {t.params.get('op', '?')} {t.inputs[1]}"
414
+ return f"{t.kind}({', '.join(t.inputs)})"
415
+
416
+
417
+ def _transform_rule(t: Any, m: Any) -> str:
418
+ """One line on how a structural transform computes its target."""
419
+ if t.kind == "difference" and len(t.inputs) == 1:
420
+ latent = str(t.params.get("latent"))
421
+ spec = m.model.marginals.get(latent)
422
+ op = "+" if t.params.get("sign", 1) == 1 else "-"
423
+ support = ("signed delta (the source's out-of-order rows are kept)"
424
+ if t.params.get("signed") is True else "delta >= 0")
425
+ return (f"{t.target} = {t.inputs[0]} {op} delta, {support} modeled as "
426
+ f"{spec.kind if spec is not None else '?'} (hidden column {latent})")
427
+ if t.kind == "identity" and len(t.inputs) == 2:
428
+ dec = t.params.get("decimals")
429
+ rounding = "" if dec is None else f", rounded to {dec} decimals"
430
+ return f"{t.target} = {t.inputs[0]} {t.params.get('op', '?')} {t.inputs[1]}{rounding}"
431
+ return f"{t.target} = {t.kind}({', '.join(t.inputs)}) (not understood by this engine)"
432
+
433
+
434
+ def _summary(fp: Any) -> str:
435
+ m = fp.manifest
436
+ t = m.targets
437
+ lines = [
438
+ f"Fingerprint: {m.dataset.name}",
439
+ f" format version : {m.fingerprint_version}",
440
+ f" engine version : {m.provenance.engine_version}",
441
+ f" created : {m.provenance.created_at}",
442
+ f" source : {m.dataset.source_records} rows x {m.dataset.source_columns} columns",
443
+ f" policy : {m.disclosure_policy.profile}"
444
+ + (" (SENSITIVE)" if m.disclosure_policy.sensitive else ""),
445
+ f" joint model : {m.model.joint.kind if m.model.joint else 'none'}",
446
+ f" targets : {t.n_calibration} calibration, {t.n_sealed} sealed",
447
+ ]
448
+ limits = ((getattr(fp, "diagnostics", None) or {}).get("joint") or {}).get("limits") or {}
449
+ if limits.get("note"):
450
+ lines.insert(-1, f" joint limits : {limits['note']}")
451
+ if t.sealed_families:
452
+ lines.append(f" sealed families: {', '.join(t.sealed_families)}")
453
+ lines.append(f" constraints : {len(m.constraints.confirmed)} confirmed, "
454
+ f"{len(m.constraints.suggested)} suggested")
455
+ transforms = {t.target: t for t in m.model.transforms}
456
+ if transforms:
457
+ kinds = [t.kind for t in transforms.values()]
458
+ lines.append(" transforms : " + ", ".join(
459
+ f"{kinds.count(k)} {k}" for k in dict.fromkeys(kinds)))
460
+ summed = {c: x for x in m.model.sums
461
+ for c in (x.parts if x.mode == "split" else [x.total] if x.mode == "sum" else [])}
462
+ if m.model.sums:
463
+ modes = [x.mode for x in m.model.sums]
464
+ lines.append(" sums : " + ", ".join(
465
+ f"{modes.count(k)} {k}" for k in dict.fromkeys(modes)))
466
+ lines.append("")
467
+ lines.append("Columns:")
468
+ width = max([len(c.name) for c in m.columns] + [4])
469
+ lines.append(f" {'name':<{width}} {'type':<11} {'role':<10} {'nulls':>6} model")
470
+ looked_up = {a.column: g.key for g in m.model.entities for a in g.attributes}
471
+ followed = {g.anchor.column: g.key for g in m.model.entities if g.anchor is not None}
472
+ for c in m.columns:
473
+ spec = m.model.marginals.get(c.name) or m.model.identifiers.get(c.name)
474
+ model = spec.kind if spec is not None else ("constant" if c.name in m.model.constants
475
+ else "-")
476
+ if any(d.column == c.name for d in m.model.derived):
477
+ model = "derived"
478
+ if c.name in looked_up:
479
+ model = f"{model}; attribute of {looked_up[c.name]}"
480
+ if c.name in followed:
481
+ model = f"{model}; anchor of {followed[c.name]}"
482
+ if c.name in m.model.references:
483
+ model = f"group sizes ({model}), fresh keys"
484
+ if c.name in transforms:
485
+ model = _transform_model(transforms[c.name], m)
486
+ if c.name in summed:
487
+ model = ("share of its total" if summed[c.name].mode == "split"
488
+ else "sum of its parts")
489
+ lines.append(f" {c.name:<{width}} {c.logical_type.value:<11} {c.role.value:<10} "
490
+ f"{c.null_fraction:>6.1%} {model}")
491
+ if transforms:
492
+ rows = [(t.target, t.kind, ", ".join(t.inputs), _transform_rule(t, m))
493
+ for t in m.model.transforms]
494
+ w = [max(len(r[i]) for r in [("target", "kind", "inputs"), *rows]) for i in range(3)]
495
+ lines.append("")
496
+ lines.append("Transforms:")
497
+ lines.append(f" {'target':<{w[0]}} {'kind':<{w[1]}} {'inputs':<{w[2]}} rule")
498
+ for target, kind, inputs, rule in rows:
499
+ lines.append(f" {target:<{w[0]}} {kind:<{w[1]}} {inputs:<{w[2]}} {rule}")
500
+ if m.model.orderings:
501
+ lines.append("")
502
+ lines.append("Orderings (enforced by redrawing the target from its truncated marginal):")
503
+ for o in m.model.orderings:
504
+ op = "<" if o.strict else "<="
505
+ parts = [f"{b} {op} {o.target}" for b in o.lower] \
506
+ + [f"{o.target} {op} {b}" for b in o.upper]
507
+ lines.append(f" {o.target}: {', '.join(parts)} ({o.method})")
508
+ if m.model.calendars:
509
+ lines.append("")
510
+ lines.append("Calendars (rows moved by whole days onto the column's weekly profile):")
511
+ for cal in m.model.calendars:
512
+ tied = f" tied to {', '.join(cal.anchors)}" if cal.anchors else ""
513
+ shares = " follows its anchors only"
514
+ if cal.profile:
515
+ shares = " shares by day number mod 7: " + " ".join(
516
+ f"{x:.3f}" for x in cal.profile)
517
+ lines.append(f" {cal.column}:{shares}{tied}")
518
+ if m.model.entities:
519
+ lines.append("")
520
+ lines.append("Entity groups (attributes are read from their key; the key follows "
521
+ "its anchor):")
522
+ for g in m.model.entities:
523
+ lines.append(" " + _entity_line(g))
524
+ if m.model.sums:
525
+ from ectype.profiling.sums import sum_text
526
+
527
+ lines.append("")
528
+ lines.append("Sums (computed after decoding; split: the parts from the total and "
529
+ "their modeled shares, sum: the total from its parts):")
530
+ for x in m.model.sums:
531
+ lines.append(f" {x.mode:<5} {sum_text(x)}")
532
+ if m.model.derived:
533
+ lines.append("")
534
+ lines.append("Derived:")
535
+ for d in m.model.derived:
536
+ lines.append(f" {d.column} = {d.expression}")
537
+ warnings = list(m.disclosure_diagnostics.warnings)
538
+ if warnings:
539
+ lines.append("")
540
+ lines.append("Warnings:")
541
+ lines.extend(f" - {w}" for w in warnings)
542
+ return "\n".join(lines) + "\n"
543
+
544
+
545
+ def _entity_line(group: Any) -> str:
546
+ """``key -> attributes (anchor: column)`` for one entity group."""
547
+ attrs = ", ".join(a.column for a in group.attributes) or "(no looked-up attribute)"
548
+ anchor = f" (anchor: {group.anchor.column})" if group.anchor is not None else ""
549
+ return f"{group.key} -> {attrs}{anchor}"
550
+
551
+
552
+ # ---------------------------------------------------------------------------------------------
553
+ # Commands
554
+ # ---------------------------------------------------------------------------------------------
555
+
556
+
557
+ def cmd_profile(args: argparse.Namespace) -> int:
558
+ from ectype.io import read_table
559
+ from ectype.profiler import Profiler
560
+
561
+ if not 0.0 <= args.sealed_fraction <= 1.0:
562
+ raise UsageError("--sealed-fraction must be between 0 and 1")
563
+ src = _existing(args.input, "input")
564
+ overrides = _parse_overrides(args.override)
565
+ derived = dict(_split_assignment(d, "--derived") for d in args.derived)
566
+ entities: dict[str, list[str]] = {}
567
+ for item in args.entity:
568
+ key, attrs = _split_assignment(item, "--entity")
569
+ names = [a.strip() for a in attrs.split(",") if a.strip()]
570
+ if not names:
571
+ raise UsageError(f"--entity {item!r}: no attribute columns (KEY=ATTR[,ATTR...])")
572
+ entities.setdefault(key, []).extend(names)
573
+ if entities and args.structure == "off":
574
+ raise UsageError("--entity declares an entity group, which --structure off disables")
575
+ profiler = Profiler(
576
+ policy=args.policy, sealed_fraction=args.sealed_fraction, seed=args.seed,
577
+ overrides=overrides or None, constraints=args.constraint or None,
578
+ derived=derived or None, joint=args.joint,
579
+ name=args.name or src.stem, structure=args.structure, entities=entities or None,
580
+ joint_options=dict(_joint_option(o) for o in args.joint_option) or None,
581
+ effort=args.effort,
582
+ )
583
+ fp = profiler.fit(read_table(src))
584
+ out = fp.save(args.output)
585
+ m = fp.manifest
586
+ _out(f"wrote {out}")
587
+ _out(f" {m.dataset.source_records} rows x {m.dataset.source_columns} columns, "
588
+ f"policy={m.disclosure_policy.profile}, "
589
+ f"targets={m.targets.n_calibration} calibration + {m.targets.n_sealed} sealed")
590
+ _out(f" {_joint_line(fp)}")
591
+ if m.constraints.suggested:
592
+ _out(f" {len(m.constraints.suggested)} suggested constraints "
593
+ f"(review with: {PROG} constraints {out} --list)")
594
+ pseudonyms = [c.name for c in m.columns if c.role.value == "pseudonym"]
595
+ if pseudonyms:
596
+ _out(f" pseudonymised (values replaced by stand-in tokens): {', '.join(pseudonyms)} "
597
+ f"(keep real values with --override COLUMN=:feature)")
598
+ if m.model.references:
599
+ _out(f" reference keys (repeat structure kept, fresh key values): "
600
+ f"{', '.join(m.model.references)} (model the values with --override "
601
+ f"COLUMN=:feature)")
602
+ for g in m.model.entities:
603
+ _out(f" entity group: {_entity_line(g)}")
604
+ for w in m.disclosure_diagnostics.warnings:
605
+ _out(f" warning: {w}")
606
+ return EXIT_OK
607
+
608
+
609
+ def cmd_inspect(args: argparse.Namespace) -> int:
610
+ fp = _load_fp(args.fingerprint)
611
+ if args.format == "json":
612
+ _out(json.dumps(_public_manifest(fp), indent=2, ensure_ascii=False))
613
+ elif args.format == "yaml":
614
+ _out(to_yaml(_public_manifest(fp)))
615
+ else:
616
+ _out(_summary(fp))
617
+ return EXIT_OK
618
+
619
+
620
+ def cmd_constraints(args: argparse.Namespace) -> int:
621
+ if args.confirm and not (args.output or args.in_place):
622
+ raise UsageError("--confirm needs -o/--output OUT.dfp or --in-place")
623
+ if args.output and args.in_place:
624
+ raise UsageError("use either -o/--output or --in-place, not both")
625
+ fp = _load_fp(args.fingerprint)
626
+ for cid in args.confirm:
627
+ fp = fp.confirm_constraint(cid)
628
+ if args.confirm:
629
+ target = Path(args.fingerprint) if args.in_place else Path(args.output)
630
+ _write_atomic(fp, target)
631
+ _out(f"confirmed {len(args.confirm)} constraint(s): {', '.join(args.confirm)}")
632
+ _out(f"wrote {target}")
633
+ if args.list or not args.confirm:
634
+ c = fp.manifest.constraints
635
+ _out(f"Confirmed constraints ({len(c.confirmed)}):")
636
+ if not c.confirmed:
637
+ _out(" (none)")
638
+ for x in c.confirmed:
639
+ _out(f" {x.id:<12} {x.severity.value:<5} {x.enforcement.value:<10} {x.expression}")
640
+ _out(f"Suggested constraints ({len(c.suggested)}):")
641
+ if not c.suggested:
642
+ _out(" (none)")
643
+ for s in c.suggested:
644
+ _out(f" {s.id:<12} {s.family:<10} {s.confidence_label:<6} "
645
+ f"support={s.support} violations={s.violations} {s.expression}")
646
+ return EXIT_OK
647
+
648
+
649
+ def cmd_generate(args: argparse.Namespace) -> int:
650
+ from ectype.generation.generator import Generator
651
+
652
+ if args.rows < 0:
653
+ raise UsageError("--rows must be >= 0")
654
+ if args.chunk_size is not None and args.chunk_size <= 0:
655
+ raise UsageError("--chunk-size must be > 0")
656
+ out = Path(args.output)
657
+ fmt = _OUTPUT_FORMATS.get(out.suffix.lower())
658
+ if fmt is None:
659
+ raise UsageError(f"unsupported output extension {out.suffix or '(none)'!r}; "
660
+ f"use one of {', '.join(sorted(_OUTPUT_FORMATS))}")
661
+ gen = Generator.from_fingerprint(_load_fp(args.fingerprint))
662
+ manifest: GenerationManifest | None
663
+ if fmt in ("parquet", "csv"):
664
+ manifest = gen.generate_to(out, args.rows, args.seed, chunk_size=args.chunk_size,
665
+ format=fmt)
666
+ else:
667
+ from ectype.io import write_table
668
+
669
+ df = gen.generate(args.rows, args.seed, chunk_size=args.chunk_size)
670
+ write_table(df, out, format=fmt)
671
+ manifest = gen.last_manifest
672
+ if manifest is not None:
673
+ manifest.output_path = str(out)
674
+ manifest.format = fmt
675
+ if args.manifest:
676
+ if manifest is None:
677
+ raise EctypeError("generator did not produce a run manifest")
678
+ Path(args.manifest).parent.mkdir(parents=True, exist_ok=True)
679
+ manifest.to_json(args.manifest)
680
+ _out(f"wrote {args.rows} rows to {out}")
681
+ if manifest is not None:
682
+ _out(f" seed={manifest.seed} chunk_size={manifest.chunk_size} "
683
+ f"chunks={manifest.n_chunks} acceptance={manifest.acceptance_rate:.3f} "
684
+ f"time={manifest.wall_time_s:.2f}s")
685
+ for note in manifest.notes:
686
+ _out(f" note: {note}")
687
+ if args.manifest:
688
+ _out(f" manifest: {args.manifest}")
689
+ return EXIT_OK
690
+
691
+
692
+ def _sensitivity(value: str) -> str:
693
+ from ectype.fingerprint.comparison import resolve_sensitivity
694
+
695
+ try:
696
+ resolve_sensitivity(value)
697
+ except ValueError as exc:
698
+ raise argparse.ArgumentTypeError(str(exc)) from None
699
+ return value
700
+
701
+
702
+ def _sensitivity_kwargs(args: argparse.Namespace) -> dict[str, Any]:
703
+ """``{"sensitivity": ...}`` unless the default was kept (so the call stays minimal)."""
704
+ value = getattr(args, "sensitivity", "standard")
705
+ return {} if value == "standard" else {"sensitivity": value}
706
+
707
+
708
+ def cmd_validate(args: argparse.Namespace) -> int:
709
+ from ectype.io import read_table
710
+ from ectype.validation.validator import validate
711
+
712
+ fp = _load_fp(args.fingerprint)
713
+ syn = read_table(_existing(args.synthetic, "synthetic data"))
714
+ hold = read_table(_existing(args.holdout, "holdout data")) if args.holdout else None
715
+ report = validate(fp, syn, holdout=hold, **_sensitivity_kwargs(args))
716
+ _out(report.summary())
717
+ if args.json:
718
+ report.to_json(args.json)
719
+ _out(f"wrote {args.json}")
720
+ if args.html:
721
+ report.to_html(args.html)
722
+ _out(f"wrote {args.html}")
723
+ passed = bool(report.passed)
724
+ _out("RESULT: PASSED" if passed else "RESULT: FAILED")
725
+ return EXIT_OK if passed else EXIT_FAILED
726
+
727
+
728
+ def _drift_found(report: Any) -> bool:
729
+ for attr in ("drift_detected", "drifted", "has_drift"):
730
+ v = getattr(report, attr, None)
731
+ if v is not None:
732
+ return bool(v() if callable(v) else v)
733
+ passed = getattr(report, "passed", None)
734
+ return passed is not None and not bool(passed)
735
+
736
+
737
+ def cmd_compare(args: argparse.Namespace) -> int:
738
+ from ectype.fingerprint.comparison import compare
739
+
740
+ a = _load_fp(args.a)
741
+ b = _load_fp(args.b)
742
+ report = compare(a, b, **_sensitivity_kwargs(args))
743
+ _out(report.summary())
744
+ if args.json:
745
+ report.to_json(args.json)
746
+ _out(f"wrote {args.json}")
747
+ if args.html:
748
+ report.to_html(args.html)
749
+ _out(f"wrote {args.html}")
750
+ drift = _drift_found(report)
751
+ passed = getattr(report, "passed", None)
752
+ inconclusive = not drift and passed is not None and not bool(passed)
753
+ if drift:
754
+ _out("RESULT: DRIFT")
755
+ elif inconclusive:
756
+ errors = getattr(report, "errors", None) or []
757
+ _out(f"RESULT: INCONCLUSIVE ({len(errors)} target(s) could not be compared; no drift "
758
+ f"found among the rest)")
759
+ else:
760
+ _out("RESULT: NO DRIFT")
761
+ # fail closed: an inconclusive comparison is not evidence of "no drift"
762
+ return EXIT_FAILED if ((drift or inconclusive) and args.fail_on_drift) else EXIT_OK
763
+
764
+
765
+ def cmd_schema(args: argparse.Namespace) -> int:
766
+ from ectype.fingerprint.schema import manifest_json_schema
767
+
768
+ text = json.dumps(manifest_json_schema(), indent=2, ensure_ascii=False) + "\n"
769
+ if args.output:
770
+ p = Path(args.output)
771
+ p.parent.mkdir(parents=True, exist_ok=True)
772
+ p.write_text(text, encoding="utf-8")
773
+ _out(f"wrote {p}")
774
+ else:
775
+ sys.stdout.write(text)
776
+ return EXIT_OK
777
+
778
+
779
+ def cmd_report(args: argparse.Namespace) -> int:
780
+ """``ectype report``: the one-page profile report of a fingerprint (or of a table, fitted
781
+ in memory first), or the comparison page of two fingerprints. A thin wrapper of
782
+ :func:`ectype.reporting.report` and :func:`ectype.reporting.compare_report`."""
783
+ from ectype.reporting import MIN_MAX_BYTES, compare_report, report
784
+
785
+ if len(args.input) > 2:
786
+ raise UsageError("report takes one input, or two fingerprints to compare, not "
787
+ f"{len(args.input)}")
788
+ inputs = [_existing(i, "input") for i in args.input]
789
+ src = inputs[0]
790
+ two = len(inputs) == 2
791
+ is_fp = src.suffix.lower() == ".dfp"
792
+ if two:
793
+ tables = [str(i) for i in inputs if i.suffix.lower() != ".dfp"]
794
+ if tables:
795
+ raise UsageError("a comparison takes two fingerprints (.dfp); fit "
796
+ f"{' and '.join(tables)} first with `ectype profile`")
797
+ for flag, given in (("--columns", args.columns is not None),
798
+ ("--detail", args.detail != "auto"),
799
+ ("--policy", args.policy is not None)):
800
+ if given:
801
+ raise UsageError(f"{flag} applies to the report of one input, not to a "
802
+ "comparison of two fingerprints")
803
+ else:
804
+ if args.sensitivity != "standard":
805
+ raise UsageError("--sensitivity applies to a comparison of two fingerprints")
806
+ if is_fp and args.policy is not None:
807
+ raise UsageError("--policy applies to a table, which is fitted first; a "
808
+ "fingerprint keeps the policy it was fitted under")
809
+ default = f"{src.stem}-vs-{inputs[1].stem}-report.html" if two else f"{src.stem}-report.html"
810
+ out = Path(args.output) if args.output else Path(default)
811
+ if out.suffix.lower() not in (".html", ".htm"):
812
+ raise UsageError(f"the output must end in .html or .htm: {out}")
813
+ targets = [out] + ([Path(args.json)] if args.json else [])
814
+ for t in targets:
815
+ if t.exists() and not args.force:
816
+ raise UsageError(f"output exists: {t} (pass --force to overwrite)")
817
+ if args.max_bytes is not None and args.max_bytes < MIN_MAX_BYTES:
818
+ raise UsageError(f"--max-bytes must be at least {MIN_MAX_BYTES}, not {args.max_bytes}")
819
+
820
+ def write(target: Path, text: str) -> None:
821
+ target.parent.mkdir(parents=True, exist_ok=True)
822
+ fd, tmp = tempfile.mkstemp(prefix=f".{target.name}.", suffix=".tmp", dir=target.parent)
823
+ try:
824
+ with os.fdopen(fd, "w", encoding="utf-8", newline="") as fh:
825
+ fh.write(text)
826
+ os.replace(tmp, target)
827
+ finally:
828
+ if os.path.exists(tmp):
829
+ os.remove(tmp)
830
+
831
+ def kb(size: int) -> str:
832
+ return (f"{size / 1_000_000:.1f} MB" if size >= 1_000_000
833
+ else f"{max(1, round(size / 1000))} KB")
834
+
835
+ if two:
836
+ budget = {"max_bytes": args.max_bytes} if args.max_bytes is not None else {}
837
+ cmp_ = compare_report(inputs[0], inputs[1], title=args.title, **budget,
838
+ **_sensitivity_kwargs(args))
839
+ write(out, cmp_.to_html_string())
840
+ if args.json:
841
+ write(Path(args.json), json.dumps(cmp_.to_dict(), indent=2, ensure_ascii=False,
842
+ allow_nan=False) + "\n")
843
+ _out(cmp_.summary(warnings=False))
844
+ _out(f"wrote {out} ({kb(cmp_.size_bytes)}, comparison of two fingerprints)")
845
+ if args.json:
846
+ _out(f"wrote {args.json}")
847
+ for w in cmp_.warnings:
848
+ _out(f"warning: {w}")
849
+ if args.open:
850
+ import webbrowser
851
+
852
+ webbrowser.open(out.resolve().as_uri())
853
+ return EXIT_OK
854
+
855
+ columns = None
856
+ if args.columns is not None:
857
+ columns = list(dict.fromkeys(c.strip() for c in args.columns.split(",") if c.strip()))
858
+ if not columns:
859
+ raise UsageError("--columns names no column")
860
+
861
+ source: Any = src
862
+ if not is_fp:
863
+ from ectype.io import read_table
864
+ from ectype.profiler import Profiler
865
+
866
+ policy = {"policy": args.policy} if args.policy is not None else {}
867
+ source = Profiler(**policy, name=src.stem).fit(read_table(src))
868
+ kwargs: dict[str, Any] = {"detail": args.detail, "columns": columns, "title": args.title}
869
+ if args.max_bytes is not None:
870
+ kwargs["max_bytes"] = args.max_bytes
871
+ try:
872
+ rep = report(source, **kwargs)
873
+ except ValueError as e:
874
+ if columns is not None and str(e).startswith("unknown column"):
875
+ raise UsageError(f"--columns: {e}") from None
876
+ raise
877
+
878
+ write(out, rep.to_html_string())
879
+ if args.json:
880
+ write(Path(args.json), json.dumps(rep.to_dict(), indent=2, ensure_ascii=False,
881
+ allow_nan=False) + "\n")
882
+ shown = kb(rep.size_bytes)
883
+ n = len(rep.view.columns)
884
+ _out(rep.summary(warnings=False))
885
+ _out(f"wrote {out} ({shown}, {n} column{'' if n == 1 else 's'}, {rep.detail} detail)")
886
+ if args.json:
887
+ _out(f"wrote {args.json}")
888
+ if not is_fp:
889
+ _out("fitted in memory; the fingerprint was not saved (ectype profile keeps one)")
890
+ for w in rep.warnings:
891
+ _out(f"warning: {w}")
892
+ if args.open:
893
+ import webbrowser
894
+
895
+ webbrowser.open(out.resolve().as_uri())
896
+ return EXIT_OK
897
+
898
+
899
+ # ---------------------------------------------------------------------------------------------
900
+ # Parser
901
+ # ---------------------------------------------------------------------------------------------
902
+
903
+
904
+ def build_parser() -> argparse.ArgumentParser:
905
+ common = argparse.ArgumentParser(add_help=False)
906
+ common.add_argument("--debug", action="store_true", default=argparse.SUPPRESS,
907
+ help="show full tracebacks on errors")
908
+
909
+ parser = argparse.ArgumentParser(
910
+ prog=PROG, parents=[common],
911
+ description="Statistical fingerprinting and synthetic reconstruction for tables.",
912
+ epilog="exit codes: 0 ok, 1 validation failed / drift, 2 usage error, 3 library error",
913
+ )
914
+ parser.add_argument("--version", action="version",
915
+ version=f"{PROG} {__version__} (format {FORMAT_VERSION})")
916
+ sub = parser.add_subparsers(dest="command", metavar="COMMAND")
917
+
918
+ sub.required = True
919
+
920
+ p = sub.add_parser("profile", parents=[common], help="fit a fingerprint to a table")
921
+ p.add_argument("input", help="source table (.parquet, .csv, .arrow, ...)")
922
+ p.add_argument("-o", "--output", required=True, help="output fingerprint (.dfp)")
923
+ p.add_argument("--policy", choices=["strict", "standard", "research"], default="standard")
924
+ p.add_argument("--seed", type=int, default=0)
925
+ p.add_argument("--sealed-fraction", type=float, default=0.3)
926
+ p.add_argument("--name", default=None, help="dataset name (default: input file stem)")
927
+ p.add_argument("--override", action="append", default=[], metavar="COL=TYPE[:ROLE]",
928
+ help="override a column's logical type and/or role (repeatable)")
929
+ p.add_argument("--constraint", action="append", default=[], metavar="EXPR",
930
+ help="hard constraint expression (repeatable)")
931
+ p.add_argument("--derived", action="append", default=[], metavar="COL=EXPR",
932
+ help="derived column expression (repeatable)")
933
+ p.add_argument("--entity", action="append", default=[], metavar="KEY=ATTR[,ATTR...]",
934
+ help="declare an entity group: every value of the key column has one "
935
+ "value of each attribute column, which is then looked up from the "
936
+ "key (repeatable)")
937
+ p.add_argument("--effort", choices=["fast", "balanced", "best"], default="balanced",
938
+ help="how much fitting time to spend, when you would rather not choose a "
939
+ "model: fast (the Gaussian copula: the shortest fit, the least "
940
+ "faithful), balanced (default: the chain copula, with its tree search "
941
+ "limited to a work budget on very wide or tall tables; the output "
942
+ "says when) or best (the chain copula in full, however long a wide "
943
+ "table takes)")
944
+ p.add_argument("--joint", choices=list(CLI_JOINTS), default=None,
945
+ help="name the model of how columns move together yourself (default: "
946
+ "chosen by --effort, which fits chain_copula): chain_copula "
947
+ "(sequential conditional trees, the closest to the source), "
948
+ "gaussian_copula (one correlation matrix: the fastest and smallest), "
949
+ "forest_copula, gaussian_mixture_copula, vine_copula, auto (fit them "
950
+ "all and keep the default unless another is clearly better on the "
951
+ "calibration targets; several times slower) or independent "
952
+ "(baseline: no dependence)")
953
+ p.add_argument("--joint-option", action="append", default=[], metavar="KEY=VALUE",
954
+ help="an option of the joint model's fit (repeatable), e.g. "
955
+ "max_predictors=32 or n_trees=3 for chain_copula; overrides what "
956
+ "--effort sets")
957
+ p.add_argument("--structure", choices=["auto", "confirmed", "off"], default="auto",
958
+ help="model orderings (a <= b) and identities (c == a * b) directly, so "
959
+ "they hold by construction: auto (default: confirmed constraints, and "
960
+ "suggestions that are all but certain), confirmed (confirmed "
961
+ "constraints only) or off (every column modeled separately, "
962
+ "constraints enforced by rejection)")
963
+ p.set_defaults(func=cmd_profile)
964
+
965
+ p = sub.add_parser("inspect", parents=[common], help="show a fingerprint's manifest")
966
+ p.add_argument("fingerprint")
967
+ p.add_argument("--format", choices=["yaml", "json", "summary"], default="summary")
968
+ p.set_defaults(func=cmd_inspect)
969
+
970
+ p = sub.add_parser("constraints", parents=[common],
971
+ help="list suggested/confirmed constraints; confirm suggestions")
972
+ p.add_argument("fingerprint")
973
+ p.add_argument("--list", action="store_true", help="list constraints")
974
+ p.add_argument("--confirm", action="append", default=[], metavar="ID",
975
+ help="confirm a suggested constraint (repeatable)")
976
+ p.add_argument("-o", "--output", default=None, help="write the updated fingerprint here")
977
+ p.add_argument("--in-place", action="store_true", help="overwrite the input fingerprint")
978
+ p.set_defaults(func=cmd_constraints)
979
+
980
+ p = sub.add_parser("generate", parents=[common], help="generate synthetic rows")
981
+ p.add_argument("fingerprint", help="fingerprint file (.dfp)")
982
+ p.add_argument("--rows", type=int, required=True, help="number of rows to generate")
983
+ p.add_argument("--seed", type=int, default=None,
984
+ help="random seed (default: the seed stored in the fingerprint)")
985
+ p.add_argument("--chunk-size", type=int, default=None,
986
+ help="rows per generated chunk (default: the fingerprint's setting); the "
987
+ "same seed and chunk size give the same rows")
988
+ p.add_argument("-o", "--output", required=True, help="output (.parquet, .csv or .arrow)")
989
+ p.add_argument("--manifest", default=None, help="write the run manifest JSON here")
990
+ p.set_defaults(func=cmd_generate)
991
+
992
+ p = sub.add_parser("validate", parents=[common],
993
+ help="validate synthetic data against a fingerprint")
994
+ p.add_argument("fingerprint")
995
+ p.add_argument("synthetic")
996
+ p.add_argument("--holdout", default=None, help="real holdout table")
997
+ p.add_argument("--json", default=None, help="write the JSON report here")
998
+ p.add_argument("--html", default=None, help="write the HTML report here")
999
+ p.add_argument("--sensitivity", type=_sensitivity, default="standard",
1000
+ help="false-discovery rate of the sealed verdict: strict (q=0.20), "
1001
+ "standard (q=0.05, default), lenient (q=0.01), or a number in (0, 1)")
1002
+ p.set_defaults(func=cmd_validate)
1003
+
1004
+ p = sub.add_parser("compare", parents=[common], help="drift between two fingerprints")
1005
+ p.add_argument("a")
1006
+ p.add_argument("b")
1007
+ p.add_argument("--json", default=None)
1008
+ p.add_argument("--html", default=None)
1009
+ p.add_argument("--fail-on-drift", action="store_true",
1010
+ help="exit 1 if drift is found or the comparison is inconclusive")
1011
+ p.add_argument("--sensitivity", type=_sensitivity, default="standard",
1012
+ help="false-discovery rate of the target-drift decision: strict (q=0.20), "
1013
+ "standard (q=0.05, default), lenient (q=0.01), or a number in (0, 1)")
1014
+ p.set_defaults(func=cmd_compare)
1015
+
1016
+ p = sub.add_parser("calibrate", parents=[common],
1017
+ help="correct post-processing distortion using calibration targets only")
1018
+ p.add_argument("fingerprint")
1019
+ p.add_argument("-o", "--output", required=True)
1020
+ p.add_argument("--iterations", type=int, default=10)
1021
+ p.add_argument("--samples", type=int, default=None)
1022
+ p.add_argument("--seed", type=int, default=0)
1023
+ p.add_argument("--tolerance-scale", type=float, default=1.0)
1024
+ p.add_argument("--time-budget", type=float, default=120.0)
1025
+ p.add_argument("--report", default=None, help="write the calibration report JSON here")
1026
+ p.add_argument("--allow-partial", action="store_true",
1027
+ help="exit 0 even if calibration does not converge (the output is written "
1028
+ "either way)")
1029
+ p.set_defaults(func=cmd_calibrate)
1030
+
1031
+ p = sub.add_parser("timeseries", parents=[common],
1032
+ help="generate time-ordered output from a temporal fingerprint")
1033
+ p.add_argument("fingerprint")
1034
+ p.add_argument("-o", "--output", required=True)
1035
+ p.add_argument("--start", default=None)
1036
+ p.add_argument("--end", default=None)
1037
+ p.add_argument("--periods", type=int, default=None)
1038
+ p.add_argument("--freq", default=None, help="polars duration, e.g. 1d, 1h")
1039
+ p.add_argument("--rows", type=int, default=None)
1040
+ p.add_argument("--entities", type=int, default=None,
1041
+ help="number of entities (panels / entity event streams); default: as many "
1042
+ "as in the source")
1043
+ p.add_argument("--count-policy", choices=["fixed", "natural"], default="fixed")
1044
+ p.add_argument("--seed", type=int, default=None)
1045
+ p.set_defaults(func=cmd_timeseries)
1046
+
1047
+ p = sub.add_parser("mutate", parents=[common], help="create a scenario fingerprint")
1048
+ p.add_argument("fingerprint")
1049
+ p.add_argument("-o", "--output", required=True)
1050
+ p.add_argument("--shift", action="append", metavar="COL=DELTA")
1051
+ p.add_argument("--scale", action="append", metavar="COL=FACTOR")
1052
+ p.add_argument("--mean-multiplier", action="append", metavar="COL=M")
1053
+ p.add_argument("--missing-rate", action="append", metavar="COL=RATE")
1054
+ p.add_argument("--correlation", action="append", metavar="A,B=RHO")
1055
+ p.add_argument("--spec", default=None, help="JSON file with mutate() keyword arguments")
1056
+ p.add_argument("--seed", type=int, default=0)
1057
+ p.add_argument("--allow-partial", action="store_true",
1058
+ help="exit 0 even if a requested change is not achieved (the output is "
1059
+ "written either way)")
1060
+ p.set_defaults(func=cmd_mutate)
1061
+
1062
+ p = sub.add_parser("merge", parents=[common], help="mix compatible fingerprints")
1063
+ p.add_argument("fingerprints", nargs="+")
1064
+ p.add_argument("-o", "--output", required=True)
1065
+ p.add_argument("--weights", default=None, help="comma-separated, e.g. 0.3,0.7")
1066
+ p.add_argument("--seed", type=int, default=0)
1067
+ p.set_defaults(func=cmd_merge)
1068
+
1069
+ p = sub.add_parser("author", parents=[common],
1070
+ help="build a fingerprint from a JSON spec (schema-driven mode)")
1071
+ p.add_argument("spec", help="specification file (JSON)")
1072
+ p.add_argument("-o", "--output", required=True, help="write the fingerprint here (.dfp)")
1073
+ p.add_argument("--policy", default=None,
1074
+ help="disclosure policy: strict, standard or research (default: the spec's)")
1075
+ p.add_argument("--seed", type=int, default=0, help="random seed for the build (default 0)")
1076
+ p.set_defaults(func=cmd_author)
1077
+
1078
+ p = sub.add_parser("relational", parents=[common], help="multi-table fingerprints (.dfpr)")
1079
+ rsub = p.add_subparsers(dest="rel_command", metavar="ACTION", required=True)
1080
+ rp = rsub.add_parser("profile", parents=[common], help="fit a relational fingerprint")
1081
+ rp.add_argument("--schema", required=True, help="RelationalSchema JSON")
1082
+ rp.add_argument("--table", action="append", metavar="NAME=PATH")
1083
+ rp.add_argument("-o", "--output", required=True)
1084
+ rp.add_argument("--policy", default="standard")
1085
+ rp.add_argument("--seed", type=int, default=0)
1086
+ rp.set_defaults(func=cmd_relational)
1087
+ rg = rsub.add_parser("generate", parents=[common], help="generate related tables")
1088
+ rg.add_argument("fingerprint")
1089
+ rg.add_argument("--rows", type=int, required=True, help="rows for each root table")
1090
+ rg.add_argument("-o", "--output", required=True, help="output directory")
1091
+ rg.add_argument("--format", choices=["parquet", "csv", "arrow"], default="parquet")
1092
+ rg.add_argument("--seed", type=int, default=42)
1093
+ rg.set_defaults(func=cmd_relational)
1094
+ rv = rsub.add_parser("validate", parents=[common], help="validate related tables")
1095
+ rv.add_argument("fingerprint")
1096
+ rv.add_argument("--table", action="append", metavar="NAME=PATH")
1097
+ rv.add_argument("--json", default=None)
1098
+ rv.set_defaults(func=cmd_relational)
1099
+
1100
+ p = sub.add_parser("schema", parents=[common], help="print the manifest JSON Schema")
1101
+ p.add_argument("-o", "--output", default=None)
1102
+ p.set_defaults(func=cmd_schema)
1103
+
1104
+ p = sub.add_parser(
1105
+ "report", parents=[common],
1106
+ help="one-page HTML profile of a fingerprint, or a comparison of two",
1107
+ description="Write one self-contained HTML page that describes a table: each column, "
1108
+ "how columns move together, the structure the engine found and what the "
1109
+ "disclosure policy did. The page is built from the fingerprint alone, so "
1110
+ "its size does not grow with the data and it shows nothing the fingerprint "
1111
+ "does not hold. Two fingerprints give a comparison page: what drifted "
1112
+ "between the first (the reference) and the second, side by side.")
1113
+ p.add_argument("input", nargs="+", metavar="INPUT",
1114
+ help="a fingerprint (.dfp), or a table (.csv, .parquet, .arrow, ...) to fit "
1115
+ "in memory first; or two fingerprints to compare")
1116
+ p.add_argument("-o", "--output", default=None, metavar="OUT.html",
1117
+ help="the page to write (.html); default: INPUT's name with -report.html "
1118
+ "(for a comparison, the two names joined by -vs-), in the current "
1119
+ "folder")
1120
+ p.add_argument("--force", action="store_true", help="overwrite an existing output")
1121
+ p.add_argument("--detail", choices=["auto", "full", "compact", "list"], default="auto",
1122
+ help="how each column is drawn: auto (default: full up to 200 columns, "
1123
+ "compact up to 1,000, a list beyond, and one level lower while the page "
1124
+ "is over --max-bytes), full, compact or list")
1125
+ p.add_argument("--columns", default=None, metavar="A,B,C",
1126
+ help="report on these columns only (comma-separated)")
1127
+ p.add_argument("--max-bytes", type=int, default=None, metavar="N",
1128
+ help="size budget of the page in bytes (default 5000000, at least 100000)")
1129
+ p.add_argument("--json", default=None, metavar="OUT.json",
1130
+ help="also write the report's data as JSON here")
1131
+ p.add_argument("--title", default=None, metavar="TEXT", help="heading of the page")
1132
+ p.add_argument("--policy", choices=["strict", "standard", "research"], default=None,
1133
+ help="disclosure policy of the fit, for a table input only (default: the "
1134
+ "profiler's default)")
1135
+ p.add_argument("--sensitivity", type=_sensitivity, default="standard", metavar="LEVEL",
1136
+ help="for a comparison only, the false-discovery rate of the drift "
1137
+ "decision: strict (q=0.20), standard (q=0.05, default), lenient "
1138
+ "(q=0.01), or a number in (0, 1)")
1139
+ p.add_argument("--open", action="store_true", help="open the page in a browser")
1140
+ p.set_defaults(func=cmd_report)
1141
+ return parser
1142
+
1143
+
1144
+ def _one_line(exc: BaseException) -> str:
1145
+ msg = " ".join(str(exc).split())
1146
+ return msg or type(exc).__name__
1147
+
1148
+
1149
+ def main(argv: Sequence[str] | None = None) -> int:
1150
+ parser = build_parser()
1151
+ try:
1152
+ args = parser.parse_args(list(argv) if argv is not None else None)
1153
+ except SystemExit as e: # --help / --version (0) or usage errors (2)
1154
+ code = e.code
1155
+ return code if isinstance(code, int) else (EXIT_OK if code is None else EXIT_USAGE)
1156
+ debug = bool(getattr(args, "debug", False))
1157
+ try:
1158
+ return int(args.func(args))
1159
+ except UsageError as e:
1160
+ if debug:
1161
+ raise
1162
+ print(f"{PROG}: error: {_one_line(e)}", file=sys.stderr)
1163
+ return EXIT_USAGE
1164
+ except EctypeError as e:
1165
+ if debug:
1166
+ raise
1167
+ print(f"{PROG}: error: {type(e).__name__}: {_one_line(e)}", file=sys.stderr)
1168
+ return EXIT_ERROR
1169
+ except KeyboardInterrupt:
1170
+ print(f"{PROG}: interrupted", file=sys.stderr)
1171
+ return 130
1172
+ except Exception as e: # noqa: BLE001 - one clean line, traceback only with --debug
1173
+ if debug:
1174
+ raise
1175
+ print(f"{PROG}: error: {type(e).__name__}: {_one_line(e)} (rerun with --debug "
1176
+ f"for a traceback)", file=sys.stderr)
1177
+ return EXIT_ERROR
1178
+
1179
+
1180
+ if __name__ == "__main__":
1181
+ raise SystemExit(main())