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,766 @@
1
+ """LLM-assisted spec authoring (M35, design doc 8.2).
2
+
3
+ An LLM may *author specifications*, never records. :class:`ScenarioDraft` turns a
4
+ natural-language request into either
5
+
6
+ * ``target="mutate"``: keyword arguments for :func:`ectype.scenarios.mutate`, or
7
+ * ``target="spec"``: a dict for :func:`ectype.authoring.build_from_spec`.
8
+
9
+ Guarantees
10
+ ----------
11
+ * **No rows reach the model.** The provider receives only :func:`manifest_summary`: column
12
+ names, logical types, roles, category labels already stored in the fingerprint, and
13
+ constraint expressions. No values, quantiles, moments, targets or sealed data.
14
+ * **Same validation path.** A mutate draft is dry-run through the scenario engine's own
15
+ request handlers (unknown columns, out-of-range values, label checks, positive-definite
16
+ projection of correlations, hard-constraint feasibility); a spec draft goes through
17
+ :func:`~ectype.authoring.normalize_spec`, per-column marginal construction,
18
+ expression type-checking and the latent positive-definiteness check. Problems are
19
+ reported as human-readable reasons in ``draft.errors``.
20
+ * **Nothing executes implicitly.** Creating a draft never mutates, builds, generates or
21
+ saves. Only an explicit ``draft.apply(fp)`` runs ``mutate`` / ``build_from_spec``.
22
+
23
+ Example::
24
+
25
+ from ectype.llm import ScenarioDraft, RuleBasedProvider
26
+
27
+ draft = ScenarioDraft.from_text("increase income by 10%", fp, provider=RuleBasedProvider())
28
+ print(draft.diff_text()) # review
29
+ if draft.valid:
30
+ result = draft.apply(fp) # explicit; returns a ScenarioResult
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import json
36
+ import math
37
+ from collections.abc import Mapping
38
+ from dataclasses import dataclass, field
39
+ from typing import TYPE_CHECKING, Any
40
+
41
+ import numpy as np
42
+
43
+ from ectype.errors import EctypeError, ScenarioError
44
+ from ectype.fingerprint.core import Fingerprint
45
+ from ectype.llm.providers import (
46
+ PromptRequest,
47
+ Provider,
48
+ ProviderError,
49
+ RuleBasedProvider,
50
+ extract_json,
51
+ )
52
+ from ectype.types import LogicalType
53
+
54
+ if TYPE_CHECKING:
55
+ from ectype.scenarios.mutate import ScenarioResult
56
+
57
+ #: mutate() keywords an authored draft may set (seed / n_sample stay under user control)
58
+ MUTATE_KEYS = ("shift", "scale", "mean_multiplier", "correlation", "category_probs",
59
+ "missing_rate", "drift", "seasonality_strength", "preserve_dependencies")
60
+ TARGETS = ("mutate", "spec")
61
+ #: upper bound on ``build.n_reference`` for authored specs (the reference sample is held in
62
+ #: memory; matches the designer's scenario ``n_sample`` cap)
63
+ MAX_N_REFERENCE = 200_000
64
+ _ROW_KEYS = {"rows", "data", "records", "values", "sample", "samples", "examples"}
65
+ _MAX_LABELS = 50
66
+
67
+ OUTPUT_SCHEMA: dict[str, Any] = {
68
+ "type": "object",
69
+ "required": ["target"],
70
+ "additionalProperties": False,
71
+ "properties": {
72
+ "target": {"enum": ["mutate", "spec"]},
73
+ "explanation": {"type": "string"},
74
+ "mutate": {
75
+ "type": "object", "additionalProperties": False,
76
+ "properties": {
77
+ "shift": {"type": "object", "additionalProperties": {"type": "number"},
78
+ "description": "column -> additive delta"},
79
+ "scale": {"type": "object", "additionalProperties": {"type": "number",
80
+ "exclusiveMinimum": 0},
81
+ "description": "column -> spread factor about the mean"},
82
+ "mean_multiplier": {"type": "object",
83
+ "additionalProperties": {"type": "number",
84
+ "exclusiveMinimum": 0},
85
+ "description": "column -> multiply every value (1.1 = +10%)"},
86
+ "correlation": {"type": "array", "items": {
87
+ "type": "array", "prefixItems": [{"type": "string"}, {"type": "string"},
88
+ {"type": "number", "exclusiveMinimum": -1,
89
+ "exclusiveMaximum": 1}]},
90
+ "description": "[[a, b, latent_rho], ...]"},
91
+ "category_probs": {"type": "object", "additionalProperties": {
92
+ "type": "object", "additionalProperties": {"type": "number", "minimum": 0,
93
+ "maximum": 1}},
94
+ "description": "column -> {existing label -> probability}"},
95
+ "missing_rate": {"type": "object", "additionalProperties": {
96
+ "type": "number", "minimum": 0, "exclusiveMaximum": 1}},
97
+ "drift": {"type": "object", "additionalProperties": {
98
+ "type": "object", "properties": {
99
+ "periods": {"type": "number"}, "mean_rate": {"type": "number"},
100
+ "shift_per_period": {"type": "number"},
101
+ "scale_rate": {"type": "number"},
102
+ "missing_rate_per_period": {"type": "number"}}}},
103
+ "seasonality_strength": {"type": "object",
104
+ "additionalProperties": {"type": "number",
105
+ "minimum": 0}},
106
+ "preserve_dependencies": {"type": "boolean"},
107
+ },
108
+ },
109
+ "spec": {
110
+ "type": "object",
111
+ "description": "a build_from_spec dict: name, columns [{name, type: numeric|"
112
+ "categorical|boolean|datetime|identifier, dist: normal|lognormal|"
113
+ "gamma|beta|uniform|poisson|negbinom + params, probs, p, start, end, "
114
+ "missing}], correlations [{columns: [a, b], rho}], constraints "
115
+ "[expr], derived {col: expr}",
116
+ },
117
+ },
118
+ }
119
+
120
+ SYSTEM_PROMPT = """\
121
+ You translate a user's natural-language scenario into a declarative specification for the \
122
+ ectype engine. You author specifications only: never produce data rows, example \
123
+ records or sample values. You are shown only the fingerprint's schema (column names, types, \
124
+ roles, stored category labels and constraint expressions), never any data.
125
+
126
+ Reply with exactly one JSON object and nothing else, matching this JSON Schema:
127
+ {schema}
128
+
129
+ Rules:
130
+ - target "mutate" changes an existing fingerprint: use only column names from the schema; \
131
+ category labels must be existing labels; probabilities are in [0, 1]; missing rates in \
132
+ [0, 1); correlations strictly inside (-1, 1) and only between modeled columns; mean_multiplier \
133
+ and scale are positive factors (+10% -> 1.1).
134
+ - target "spec" builds a new fingerprint from scratch (use it when there is no fingerprint \
135
+ or the user asks for a new dataset).
136
+ - Put a one-sentence summary of what you changed in "explanation".
137
+ - If the request cannot be expressed, return target "mutate" with an empty "mutate" object \
138
+ and say why in "explanation".
139
+ """
140
+
141
+
142
+ # ---------------------------------------------------------------------------------------------
143
+ # what the model may see
144
+ # ---------------------------------------------------------------------------------------------
145
+
146
+
147
+ def _stored_labels(fp: Fingerprint, col: str) -> list[str] | None:
148
+ spec = fp.manifest.model.marginals.get(col)
149
+ if spec is None or "labels" not in spec.arrays:
150
+ return None
151
+ try:
152
+ labels = fp.arrays.get(spec.arrays["labels"])
153
+ except KeyError:
154
+ return None
155
+ return [str(x) for x in np.asarray(labels).tolist()[:_MAX_LABELS]]
156
+
157
+
158
+ def manifest_summary(fp: Fingerprint | None) -> dict[str, Any]:
159
+ """The only fingerprint information a provider receives (no rows, stats or targets)."""
160
+ if fp is None:
161
+ return {"fingerprint": None}
162
+ m = fp.manifest
163
+ model = m.model
164
+ # a column computed as base +/- gap (a "difference" transform) is modeled through its
165
+ # hidden gap; one computed by an identity (a op b) has no model and is not "modeled"
166
+ gaps = {t.target: str(t.params.get("latent")) for t in model.transforms
167
+ if t.kind == "difference"}
168
+ cols = []
169
+ for c in m.columns:
170
+ slot = gaps.get(c.name, c.name)
171
+ entry: dict[str, Any] = {"name": c.name, "type": c.logical_type.value,
172
+ "role": c.role.value,
173
+ "modeled": slot in model.marginals
174
+ and slot in model.encodings}
175
+ if c.logical_type in (LogicalType.CATEGORICAL, LogicalType.BOOLEAN):
176
+ labels = _stored_labels(fp, c.name)
177
+ if labels is not None:
178
+ entry["labels"] = labels
179
+ cols.append(entry)
180
+ return {
181
+ "dataset": m.dataset.name,
182
+ "columns": cols,
183
+ "constraints": [c.expression for c in m.constraints.confirmed],
184
+ "suggested_constraints": [s.expression for s in m.constraints.suggested],
185
+ "derived": [d.column for d in model.derived],
186
+ "joint_model": model.joint.kind if model.joint is not None else None,
187
+ "temporal": bool(m.temporal is not None and m.temporal.enabled),
188
+ }
189
+
190
+
191
+ def build_request(text: str, fp: Fingerprint | None, target: str = "auto") -> PromptRequest:
192
+ schema_txt = json.dumps(OUTPUT_SCHEMA, indent=1, sort_keys=True)
193
+ return PromptRequest(text=str(text), target=target, context=manifest_summary(fp),
194
+ system=SYSTEM_PROMPT.format(schema=schema_txt), schema=OUTPUT_SCHEMA)
195
+
196
+
197
+ # ---------------------------------------------------------------------------------------------
198
+ # normalisation and validation
199
+ # ---------------------------------------------------------------------------------------------
200
+
201
+
202
+ def _norm_correlation(raw: Any, errors: list[str]) -> list[list[Any]]:
203
+ out: list[list[Any]] = []
204
+ items: list[Any]
205
+ if isinstance(raw, Mapping):
206
+ items = []
207
+ for k, v in raw.items():
208
+ parts = [p.strip() for p in (k.split(",") if isinstance(k, str) else list(k))]
209
+ items.append([*parts, v])
210
+ elif isinstance(raw, list):
211
+ items = raw
212
+ else:
213
+ errors.append(f"correlation must be a list of [a, b, rho], got {type(raw).__name__}")
214
+ return out
215
+ for it in items:
216
+ if isinstance(it, Mapping) and "columns" in it:
217
+ it = [*list(it["columns"]), it.get("rho")]
218
+ if not isinstance(it, (list, tuple)) or len(it) != 3:
219
+ errors.append(f"correlation entry {it!r} must be [a, b, rho]")
220
+ continue
221
+ out.append([str(it[0]), str(it[1]), it[2]])
222
+ return out
223
+
224
+
225
+ def non_finite_numbers(obj: Any, path: str) -> list[str]:
226
+ """Reasons for every NaN or infinite number inside ``obj`` (nested dicts/lists), e.g.
227
+ ``"mutate.shift['x']: NaN is not a finite number"``. JSON-ish provider output may carry
228
+ ``NaN``/``Infinity`` literals; no draft parameter accepts them."""
229
+ out: list[str] = []
230
+ if isinstance(obj, bool):
231
+ return out
232
+ if isinstance(obj, (int, float)):
233
+ try:
234
+ finite = math.isfinite(obj)
235
+ except OverflowError: # an int too large for a float
236
+ finite = False
237
+ if not finite:
238
+ shown = "NaN" if isinstance(obj, float) and math.isnan(obj) else repr(obj)
239
+ out.append(f"{path}: {shown} is not a finite number; every number in a draft "
240
+ f"must be finite")
241
+ return out
242
+ if isinstance(obj, Mapping):
243
+ for k, v in obj.items():
244
+ out.extend(non_finite_numbers(v, f"{path}[{k!r}]"))
245
+ elif isinstance(obj, (list, tuple)):
246
+ for i, v in enumerate(obj):
247
+ out.extend(non_finite_numbers(v, f"{path}[{i}]"))
248
+ return out
249
+
250
+
251
+ def normalize_mutate(payload: Mapping[str, Any]) -> tuple[dict[str, Any], list[str]]:
252
+ """JSON-safe mutate kwargs (correlation as ``[[a, b, rho], ...]``) and structural errors."""
253
+ errors: list[str] = []
254
+ if not isinstance(payload, Mapping):
255
+ return {}, [f"'mutate' must be an object, got {type(payload).__name__}"]
256
+ unknown = sorted(set(payload) - set(MUTATE_KEYS))
257
+ if unknown:
258
+ errors.append(f"unknown mutate parameter(s) {unknown}; allowed: {list(MUTATE_KEYS)}")
259
+ out: dict[str, Any] = {}
260
+ errors.extend(non_finite_numbers({k: v for k, v in payload.items() if k in MUTATE_KEYS},
261
+ "mutate"))
262
+ for k in MUTATE_KEYS:
263
+ if k not in payload or payload[k] is None:
264
+ continue
265
+ v = payload[k]
266
+ if k == "correlation":
267
+ v = _norm_correlation(v, errors)
268
+ if not v:
269
+ continue
270
+ elif k == "preserve_dependencies":
271
+ if not isinstance(v, bool):
272
+ errors.append("preserve_dependencies must be true or false")
273
+ continue
274
+ elif not isinstance(v, Mapping):
275
+ errors.append(f"{k} must be an object {{column: value}}, got {type(v).__name__}")
276
+ continue
277
+ elif not v:
278
+ continue
279
+ else:
280
+ v = {str(c): (dict(x) if isinstance(x, Mapping) else x) for c, x in v.items()}
281
+ out[k] = v
282
+ if not any(k in out for k in MUTATE_KEYS if k != "preserve_dependencies") and not errors:
283
+ errors.append("the draft requests no change")
284
+ return out, errors
285
+
286
+
287
+ def to_mutate_kwargs(payload: Mapping[str, Any]) -> dict[str, Any]:
288
+ """Python ``mutate()`` keyword arguments from the JSON-safe form."""
289
+ kw = {k: v for k, v in payload.items() if k in MUTATE_KEYS}
290
+ if "correlation" in kw:
291
+ kw["correlation"] = {(a, b): float(r) for a, b, r in kw["correlation"]}
292
+ return kw
293
+
294
+
295
+ def validate_mutate(fp: Fingerprint, payload: Mapping[str, Any]) -> tuple[list[str], list[str]]:
296
+ """Dry-run ``payload`` through mutate's own request handlers. Returns (errors, notes).
297
+
298
+ Each parameter is checked on a fresh working copy so that every problem is reported;
299
+ nothing is generated and the fingerprint is not modified.
300
+ """
301
+ import importlib
302
+
303
+ # the module, not the ``mutate`` function the package re-exports under the same name
304
+ mm = importlib.import_module("ectype.scenarios.mutate")
305
+
306
+ errors: list[str] = []
307
+ notes: list[str] = []
308
+ preserve = bool(payload.get("preserve_dependencies", True))
309
+
310
+ def run(label: str, fn: Any) -> Any:
311
+ st = mm._State(fp)
312
+ try:
313
+ fn(st)
314
+ except (ScenarioError, EctypeError, ValueError, TypeError, KeyError) as exc:
315
+ msg = str(exc).strip("'\"")
316
+ errors.append(msg if label in msg else f"{label}: {msg}")
317
+ return None
318
+ notes.extend(st.notes)
319
+ for m in st.infeasible:
320
+ notes.append(f"approximate: {m}")
321
+ return st
322
+
323
+ sh = dict(payload.get("shift") or {})
324
+ sc = dict(payload.get("scale") or {})
325
+ mul = dict(payload.get("mean_multiplier") or {})
326
+ mr = dict(payload.get("missing_rate") or {})
327
+ if payload.get("drift"):
328
+ current = mm.current_missing_rates(fp)
329
+ tmp: list[str] = []
330
+ try:
331
+ for col in payload["drift"]:
332
+ if col not in fp.manifest.column_names:
333
+ raise ScenarioError(f"drift: unknown column {col!r}")
334
+ mm._expand_drift(dict(payload["drift"]), mul, sc, sh, mr, current, tmp)
335
+ notes.extend(tmp)
336
+ except (ScenarioError, TypeError, ValueError) as exc:
337
+ errors.append(f"drift: {exc}")
338
+ # one column at a time, so every problem is reported; columns linked by a structural
339
+ # transform (end = start + gap) go together, because a request on the computed column is
340
+ # met net of what its inputs do in the same request
341
+ for group in mm.linked_groups(fp, [*mul, *sc, *sh]):
342
+ label = (f"column {group[0]!r}" if len(group) == 1
343
+ else "columns " + ", ".join(repr(c) for c in group))
344
+ run(label, lambda st, g=group: mm._apply_affine(
345
+ st, {c: sh[c] for c in g if c in sh}, {c: sc[c] for c in g if c in sc},
346
+ {c: mul[c] for c in g if c in mul}))
347
+ for col, probs in dict(payload.get("category_probs") or {}).items():
348
+ run("category_probs", lambda st, c=col, p=probs: mm._apply_category_probs(
349
+ st, {c: p}, preserve))
350
+ for group in mm.linked_groups(fp, list(mr)):
351
+ run("missing_rate", lambda st, g=group: mm._apply_missing(st, {c: mr[c] for c in g}))
352
+ corr = payload.get("correlation")
353
+ if corr:
354
+ for a, b, rho in corr: # individually, so each bad pair is named ...
355
+ run("correlation", lambda st, x=a, y=b, v=rho: mm._apply_correlation(
356
+ st, [(x, y, v)], preserve))
357
+ if len(corr) > 1 and not any(e.startswith("correlation") or "correlation" in e
358
+ for e in errors):
359
+ run("correlation", lambda st: mm._apply_correlation( # ... then jointly
360
+ st, [tuple(x) for x in corr], preserve))
361
+ if payload.get("seasonality_strength"):
362
+ run("seasonality_strength", lambda st: mm._apply_seasonality(
363
+ st, dict(payload["seasonality_strength"])))
364
+ return list(dict.fromkeys(errors)), list(dict.fromkeys(notes))
365
+
366
+
367
+ def validate_spec(spec: Mapping[str, Any]) -> tuple[dict[str, Any] | None, list[str]]:
368
+ """Validate a ``build_from_spec`` dict without building it. Returns (normalised, errors)."""
369
+ from ectype.authoring import spec as sp
370
+ from ectype.fingerprint import expressions
371
+ from ectype.scenarios.feasibility import explain_not_pd, min_eigenvalue
372
+
373
+ if not isinstance(spec, Mapping):
374
+ return None, [f"'spec' must be an object, got {type(spec).__name__}"]
375
+ non_finite = non_finite_numbers(spec, "spec")
376
+ if non_finite:
377
+ return None, non_finite
378
+ rows = sorted(_ROW_KEYS & set(spec))
379
+ if rows:
380
+ return None, [f"spec contains record-like keys {rows}: an authored spec may describe "
381
+ f"distributions only, never rows"]
382
+ try:
383
+ norm = sp.normalize_spec({k: v for k, v in spec.items() if k != "build"})
384
+ except (ScenarioError, EctypeError, ValueError, TypeError, KeyError) as exc:
385
+ return None, [f"spec: {exc}"]
386
+ errors: list[str] = []
387
+ schemas = {}
388
+ for c in norm["columns"]:
389
+ try:
390
+ cs, _model, _ident = sp._schema_and_marginal(c)
391
+ schemas[cs.name] = cs
392
+ except Exception as exc: # noqa: BLE001 - surface the reason
393
+ errors.append(f"column {c['name']!r}: {exc}")
394
+ if not errors:
395
+ from ectype.fingerprint.schema import ColumnSchema
396
+ from ectype.types import Role
397
+
398
+ for d in norm["derived"]:
399
+ try:
400
+ schemas[d["column"]] = ColumnSchema(
401
+ name=d["column"], logical_type=LogicalType(d["logical_type"]),
402
+ role=Role.DERIVED, physical_dtype=d["dtype"])
403
+ except ValueError as exc:
404
+ errors.append(f"derived column {d['column']!r}: {exc}")
405
+ for d in norm["derived"]:
406
+ try:
407
+ expressions.check(d["expression"], schemas)
408
+ except Exception as exc: # noqa: BLE001
409
+ errors.append(f"derived column {d['column']!r}: {exc}")
410
+ for c in norm["constraints"]:
411
+ try:
412
+ expressions.check(c["expression"], schemas)
413
+ except Exception as exc: # noqa: BLE001
414
+ errors.append(f"constraint {c['id']!r}: {exc}")
415
+ features = [c["name"] for c in norm["columns"] if c["type"] != "identifier"]
416
+ if norm["correlations"] and features:
417
+ r = sp._latent_matrix(features, norm["correlations"])
418
+ if min_eigenvalue(r) < 1e-8:
419
+ stated = {(c["columns"][0], c["columns"][1]): c["rho"] for c in norm["correlations"]}
420
+ errors.append("contradictory correlation spec: "
421
+ + explain_not_pd(r, features, stated))
422
+ if "build" in spec:
423
+ build = dict(spec["build"] or {})
424
+ bad = set(build) - {"policy", "n_reference", "seed", "sealed_fraction"}
425
+ if bad:
426
+ errors.append(f"unknown build options {sorted(bad)}")
427
+ n_ref = build.get("n_reference")
428
+ if n_ref is not None and (isinstance(n_ref, bool) or not isinstance(n_ref, int)
429
+ or not 1 <= n_ref <= MAX_N_REFERENCE):
430
+ errors.append(f"build.n_reference must be an integer in [1, {MAX_N_REFERENCE}], "
431
+ f"got {n_ref!r}")
432
+ return norm, errors
433
+
434
+
435
+ # ---------------------------------------------------------------------------------------------
436
+ # human-readable diff
437
+ # ---------------------------------------------------------------------------------------------
438
+
439
+
440
+ def _fmt(x: Any) -> str:
441
+ if isinstance(x, float):
442
+ if not math.isfinite(x):
443
+ return str(x)
444
+ if abs(x) >= 1e9 or (x != 0 and abs(x) < 1e-3):
445
+ return f"{x:.3e}"
446
+ return f"{x:,.0f}" if abs(x) >= 1000 else f"{x:.4g}"
447
+ return str(x)
448
+
449
+
450
+ def mutate_diff(fp: Fingerprint, payload: Mapping[str, Any]) -> list[dict[str, Any]]:
451
+ """Requested changes against the fingerprint's *model* (no data is read)."""
452
+ import importlib
453
+
454
+ from ectype.models.copulas import GaussianCopula
455
+
456
+ m = fp.manifest
457
+ out: list[dict[str, Any]] = []
458
+ # the model's own mean: of the marginal, or base +/- gap for a column a transform computes
459
+ state = importlib.import_module("ectype.scenarios.mutate")._State(fp)
460
+
461
+ def mean_of(col: str) -> float | None:
462
+ try:
463
+ mu = state.model_mean(col, new=False)
464
+ except Exception: # noqa: BLE001
465
+ return None
466
+ return None if mu is None else float(mu)
467
+
468
+ def add(kind: str, cols: list[str], before: Any, after: Any, text: str) -> None:
469
+ out.append({"kind": kind, "columns": cols, "from": before, "to": after, "text": text})
470
+
471
+ for col, k in dict(payload.get("mean_multiplier") or {}).items():
472
+ mu = mean_of(col)
473
+ try:
474
+ after = None if mu is None else mu * float(k)
475
+ except (TypeError, ValueError):
476
+ after = None
477
+ add("mean_multiplier", [col], mu, after,
478
+ f"{col}: mean {_fmt(mu)} -> {_fmt(after)} (x{_fmt(k)})")
479
+ for col, f in dict(payload.get("scale") or {}).items():
480
+ add("scale", [col], 1.0, f, f"{col}: spread x{_fmt(f)} about the mean (mean kept)")
481
+ for col, d in dict(payload.get("shift") or {}).items():
482
+ mu = mean_of(col)
483
+ try:
484
+ after = None if mu is None else mu + float(d)
485
+ except (TypeError, ValueError):
486
+ after = None
487
+ add("shift", [col], mu, after, f"{col}: shift by {_fmt(d)} (mean {_fmt(mu)} -> "
488
+ f"{_fmt(after)})")
489
+ for col, r in dict(payload.get("missing_rate") or {}).items():
490
+ before = None
491
+ try:
492
+ before = m.column(col).null_fraction
493
+ except KeyError:
494
+ pass
495
+ add("missing_rate", [col], before, r, f"{col}: missing rate {_fmt(before)} -> {_fmt(r)}")
496
+ for col, probs in dict(payload.get("category_probs") or {}).items():
497
+ cur: dict[str, float] = {}
498
+ spec = m.model.marginals.get(col)
499
+ if spec is not None and "labels" in spec.arrays and "probs" in spec.arrays:
500
+ labs = [str(x) for x in np.asarray(fp.arrays.get(spec.arrays["labels"])).tolist()]
501
+ ps = np.asarray(fp.arrays.get(spec.arrays["probs"]), dtype=float)
502
+ cur = {lab: float(p) for lab, p in zip(labs, ps / max(ps.sum(), 1e-300),
503
+ strict=False)}
504
+ for lab, p in dict(probs).items():
505
+ add("category_probs", [col], cur.get(str(lab)), p,
506
+ f"{col}: P({lab}) {_fmt(cur.get(str(lab)))} -> {_fmt(p)} (other labels "
507
+ f"rescale proportionally)")
508
+ corr = payload.get("correlation") or []
509
+ if corr:
510
+ cop = None
511
+ j = m.model.joint
512
+ if j is not None and j.kind == GaussianCopula.kind:
513
+ try:
514
+ cop = GaussianCopula.from_spec(j, fp.arrays)
515
+ except Exception: # noqa: BLE001
516
+ cop = None
517
+ for a, b, rho in corr:
518
+ before = None
519
+ if cop is not None and a in cop.columns and b in cop.columns:
520
+ before = float(cop.corr[cop.columns.index(a), cop.columns.index(b)])
521
+ add("correlation", [a, b], before, rho,
522
+ f"corr({a}, {b}) latent {_fmt(before)} -> {_fmt(rho)}")
523
+ for col, d in dict(payload.get("drift") or {}).items():
524
+ add("drift", [col], None, d, f"{col}: drift {json.dumps(d, sort_keys=True)}")
525
+ for col, f in dict(payload.get("seasonality_strength") or {}).items():
526
+ add("seasonality_strength", [col], 1.0, f, f"{col}: seasonal amplitude x{_fmt(f)}")
527
+ if payload.get("preserve_dependencies") is False:
528
+ add("preserve_dependencies", [], True, False,
529
+ "dependencies: plain nearest correlation (requested entries not held fixed)")
530
+ return out
531
+
532
+
533
+ def spec_diff(norm: Mapping[str, Any] | None, fp: Fingerprint | None = None
534
+ ) -> list[dict[str, Any]]:
535
+ if not norm:
536
+ return []
537
+ out: list[dict[str, Any]] = []
538
+ existing = set(fp.manifest.column_names) if fp is not None else set()
539
+ for c in norm.get("columns", []):
540
+ desc = c["type"] + (f" {c['dist']}" if c.get("dist") else "")
541
+ if c.get("params"):
542
+ desc += " " + ", ".join(f"{k}={_fmt(v)}" for k, v in c["params"].items())
543
+ if c.get("probs"):
544
+ desc += " " + ", ".join(f"{k}:{_fmt(v)}" for k, v in c["probs"].items())
545
+ mark = "~" if c["name"] in existing else "+"
546
+ out.append({"kind": "column", "columns": [c["name"]], "from": None, "to": desc,
547
+ "text": f"{mark} column {c['name']}: {desc}"})
548
+ for c in norm.get("correlations", []):
549
+ a, b = c["columns"]
550
+ out.append({"kind": "correlation", "columns": [a, b], "from": None, "to": c["rho"],
551
+ "text": f"+ corr({a}, {b}) = {_fmt(c['rho'])} ({c['method']})"})
552
+ for c in norm.get("constraints", []):
553
+ out.append({"kind": "constraint", "columns": [], "from": None, "to": c["expression"],
554
+ "text": f"+ constraint {c['id']}: {c['expression']}"})
555
+ for d in norm.get("derived", []):
556
+ out.append({"kind": "derived", "columns": [d["column"]], "from": None,
557
+ "to": d["expression"], "text": f"+ derived {d['column']} = "
558
+ f"{d['expression']}"})
559
+ for col in sorted(existing - {c["name"] for c in norm.get("columns", [])}):
560
+ out.append({"kind": "column", "columns": [col], "from": col, "to": None,
561
+ "text": f"- column {col} (not in the authored spec)"})
562
+ return out
563
+
564
+
565
+ def python_literal(obj: Any) -> str:
566
+ """A readable Python literal for JSON-safe values (and tuple-keyed dicts)."""
567
+ if isinstance(obj, Mapping):
568
+ return "{" + ", ".join(f"{python_literal(k)}: {python_literal(v)}"
569
+ for k, v in obj.items()) + "}"
570
+ if isinstance(obj, tuple):
571
+ return "(" + ", ".join(python_literal(x) for x in obj) + ("," if len(obj) == 1 else "") \
572
+ + ")"
573
+ if isinstance(obj, list):
574
+ return "[" + ", ".join(python_literal(x) for x in obj) + "]"
575
+ if obj is None or isinstance(obj, bool):
576
+ return repr(obj)
577
+ if isinstance(obj, float) and not math.isfinite(obj):
578
+ return f"float({repr(obj)!r})"
579
+ if isinstance(obj, (int, float, str)):
580
+ return repr(obj)
581
+ return repr(str(obj))
582
+
583
+
584
+ def mutate_snippet(payload: Mapping[str, Any], *, source: str = "fp", seed: int = 0) -> str:
585
+ kw = to_mutate_kwargs(payload)
586
+ args = "".join(f",\n {k}={python_literal(v)}" for k, v in kw.items())
587
+ return (f"from ectype.scenarios import mutate\n\n"
588
+ f"result = mutate({source}{args},\n seed={seed})\n"
589
+ f"print(result.summary())")
590
+
591
+
592
+ # ---------------------------------------------------------------------------------------------
593
+ # the draft
594
+ # ---------------------------------------------------------------------------------------------
595
+
596
+
597
+ @dataclass
598
+ class ScenarioDraft:
599
+ """A validated, *unexecuted* specification authored from natural language."""
600
+
601
+ text: str
602
+ target: str # "mutate" or "spec"
603
+ payload: dict[str, Any] # JSON-safe mutate kwargs or spec dict
604
+ errors: list[str] = field(default_factory=list)
605
+ notes: list[str] = field(default_factory=list)
606
+ diff: list[dict[str, Any]] = field(default_factory=list)
607
+ explanation: str | None = None
608
+ provider: str = ""
609
+ fingerprint_hash: str | None = None
610
+ raw: dict[str, Any] | None = None
611
+ applied: bool = False
612
+
613
+ # -- construction -------------------------------------------------------------------------
614
+ @classmethod
615
+ def from_text(cls, text: str, fp: Fingerprint | None = None, *,
616
+ provider: Provider | None = None, target: str = "auto") -> ScenarioDraft:
617
+ """Ask ``provider`` (default :class:`RuleBasedProvider`) to draft a spec for ``text``.
618
+
619
+ ``target``: ``"mutate"`` (needs ``fp``), ``"spec"`` or ``"auto"`` (mutate when a
620
+ fingerprint is given). Never executes anything.
621
+ """
622
+ if target not in ("auto", *TARGETS):
623
+ raise ValueError(f"target must be 'auto', 'mutate' or 'spec', got {target!r}")
624
+ if not str(text).strip():
625
+ raise ValueError("the request text is empty")
626
+ provider = provider or RuleBasedProvider()
627
+ request = build_request(text, fp, target)
628
+ fp_hash = fp.content_hash() if fp is not None else None
629
+ pname = str(getattr(provider, "name", type(provider).__name__))
630
+ try:
631
+ obj = extract_json(provider.complete(request))
632
+ except ProviderError as exc:
633
+ return cls(text=str(text), target="mutate" if fp is not None else "spec",
634
+ payload={}, errors=[str(exc)], provider=pname,
635
+ fingerprint_hash=fp_hash)
636
+ return cls.from_output(obj, text=str(text), fp=fp, target=target, provider=pname,
637
+ fingerprint_hash=fp_hash)
638
+
639
+ @classmethod
640
+ def from_output(cls, obj: Mapping[str, Any], *, text: str, fp: Fingerprint | None,
641
+ target: str = "auto", provider: str = "",
642
+ fingerprint_hash: str | None = None) -> ScenarioDraft:
643
+ """Validate a provider's parsed JSON output into a draft."""
644
+ errors: list[str] = []
645
+ raw = json.loads(json.dumps(obj, default=str))
646
+ chosen = str(obj.get("target") or ("mutate" if fp is not None else "spec"))
647
+ if target != "auto" and chosen != target:
648
+ errors.append(f"the provider returned target {chosen!r} but {target!r} was "
649
+ f"requested")
650
+ if chosen not in TARGETS:
651
+ errors.append(f"unknown target {chosen!r}; expected 'mutate' or 'spec'")
652
+ chosen = "mutate" if fp is not None else "spec"
653
+ rows = sorted(_ROW_KEYS & set(obj))
654
+ if rows:
655
+ errors.append(f"the output contains record-like keys {rows}; an LLM may author "
656
+ f"specifications only, never rows")
657
+ unknown = sorted(set(obj) - {"target", "explanation", "mutate", "spec", "unparsed",
658
+ *_ROW_KEYS})
659
+ if unknown:
660
+ errors.append(f"unknown output keys {unknown}")
661
+ for u in obj.get("unparsed") or []:
662
+ errors.append(f"could not interpret {str(u)!r}")
663
+ notes: list[str] = []
664
+ diff: list[dict[str, Any]] = []
665
+ payload: dict[str, Any] = {}
666
+ if chosen == "mutate":
667
+ if fp is None:
668
+ errors.append("a mutate draft needs a fingerprint to change")
669
+ payload, errs = normalize_mutate(obj.get("mutate") or {})
670
+ errors.extend(errs)
671
+ if fp is not None and payload and not errs:
672
+ e2, notes = validate_mutate(fp, payload)
673
+ errors.extend(e2)
674
+ if fp is not None and payload:
675
+ diff = mutate_diff(fp, payload)
676
+ else:
677
+ spec = obj.get("spec")
678
+ norm, errs = validate_spec(spec if spec is not None else {})
679
+ errors.extend(errs)
680
+ payload = json.loads(json.dumps(spec, default=str)) if isinstance(spec, Mapping) \
681
+ else {}
682
+ diff = spec_diff(norm, fp)
683
+ expl = obj.get("explanation")
684
+ return cls(text=text, target=chosen, payload=payload,
685
+ errors=list(dict.fromkeys(errors)), notes=notes, diff=diff,
686
+ explanation=str(expl) if expl else None, provider=provider,
687
+ fingerprint_hash=fingerprint_hash, raw=raw)
688
+
689
+ # -- inspection ---------------------------------------------------------------------------
690
+ @property
691
+ def valid(self) -> bool:
692
+ return not self.errors and bool(self.payload)
693
+
694
+ def mutate_kwargs(self) -> dict[str, Any]:
695
+ if self.target != "mutate":
696
+ raise ScenarioError("this draft is a build_from_spec spec, not a mutate request")
697
+ return to_mutate_kwargs(self.payload)
698
+
699
+ def diff_text(self) -> str:
700
+ head = f"draft ({self.target}) for: {self.text}"
701
+ lines = [head, *(" " + d["text"] for d in self.diff)]
702
+ lines += [f" note: {n}" for n in self.notes]
703
+ lines += [f" REJECTED: {e}" for e in self.errors]
704
+ lines.append(" status: " + ("valid; nothing has been executed (call apply)"
705
+ if self.valid else "invalid; cannot be applied"))
706
+ return "\n".join(lines)
707
+
708
+ def python_snippet(self, source: str = "fp", seed: int = 0) -> str:
709
+ if self.target == "mutate":
710
+ return mutate_snippet(self.payload, source=source, seed=seed)
711
+ # same seed precedence as apply(): a seed in spec["build"] wins
712
+ used = dict(self.payload.get("build") or {}).get("seed", seed)
713
+ return ("from ectype.authoring import build_from_spec\n\n"
714
+ f"spec = {python_literal(self.payload)}\n"
715
+ f"fp = build_from_spec(spec, seed={python_literal(used)})")
716
+
717
+ def to_dict(self) -> dict[str, Any]:
718
+ return {"text": self.text, "target": self.target, "payload": self.payload,
719
+ "valid": self.valid, "errors": list(self.errors), "notes": list(self.notes),
720
+ "diff": list(self.diff), "diff_text": self.diff_text(),
721
+ "explanation": self.explanation, "provider": self.provider,
722
+ "fingerprint_hash": self.fingerprint_hash, "applied": self.applied,
723
+ "python": self.python_snippet()}
724
+
725
+ # -- execution (explicit only) ------------------------------------------------------------
726
+ def apply(self, fp: Fingerprint | None = None, *, seed: int = 0,
727
+ n_sample: int | None = None, **build: Any) -> Any:
728
+ """Execute the draft. ``mutate`` drafts return a ``ScenarioResult`` (needs the same
729
+ fingerprint the draft was validated against); ``spec`` drafts return a new
730
+ ``Fingerprint`` from ``build_from_spec`` (``build`` keywords are passed through)."""
731
+ if not self.valid:
732
+ raise ScenarioError("cannot apply an invalid draft: " + "; ".join(self.errors
733
+ or ["empty"]))
734
+ result: ScenarioResult | Fingerprint
735
+ if self.target == "mutate":
736
+ from ectype.scenarios import mutate
737
+
738
+ if fp is None:
739
+ raise ScenarioError("apply(fp): a mutate draft needs the fingerprint")
740
+ if self.fingerprint_hash is not None and fp.content_hash() != self.fingerprint_hash:
741
+ raise ScenarioError("apply(fp): this is not the fingerprint the draft was "
742
+ "validated against; draft it again")
743
+ kw: dict[str, Any] = {"seed": seed}
744
+ if n_sample is not None:
745
+ kw["n_sample"] = int(n_sample)
746
+ result = mutate(fp, **self.mutate_kwargs(), **kw)
747
+ else:
748
+ from ectype.authoring import build_from_spec
749
+
750
+ if "seed" not in build and "seed" not in dict(self.payload.get("build") or {}):
751
+ build["seed"] = seed
752
+ result = build_from_spec(self.payload, **build)
753
+ self.applied = True
754
+ return result
755
+
756
+
757
+ def draft_scenario(text: str, fp: Fingerprint | None = None, *,
758
+ provider: Provider | None = None, target: str = "auto") -> ScenarioDraft:
759
+ """Shorthand for :meth:`ScenarioDraft.from_text`."""
760
+ return ScenarioDraft.from_text(text, fp, provider=provider, target=target)
761
+
762
+
763
+ __all__ = ["MAX_N_REFERENCE", "MUTATE_KEYS", "OUTPUT_SCHEMA", "SYSTEM_PROMPT", "ScenarioDraft", "build_request",
764
+ "draft_scenario", "manifest_summary", "mutate_diff", "mutate_snippet",
765
+ "normalize_mutate", "python_literal", "spec_diff", "to_mutate_kwargs",
766
+ "validate_mutate", "validate_spec"]