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.
- ectype/__init__.py +134 -0
- ectype/_version.py +5 -0
- ectype/authoring/__init__.py +13 -0
- ectype/authoring/builder.py +134 -0
- ectype/authoring/spec.py +555 -0
- ectype/calibration/__init__.py +26 -0
- ectype/calibration/adjustments.py +539 -0
- ectype/calibration/calibrator.py +781 -0
- ectype/cli.py +1181 -0
- ectype/compiler/__init__.py +1 -0
- ectype/compiler/plan.py +678 -0
- ectype/errors.py +43 -0
- ectype/fingerprint/__init__.py +1 -0
- ectype/fingerprint/comparison.py +746 -0
- ectype/fingerprint/container.py +408 -0
- ectype/fingerprint/core.py +263 -0
- ectype/fingerprint/disclosure.py +207 -0
- ectype/fingerprint/expressions.py +1317 -0
- ectype/fingerprint/schema.py +645 -0
- ectype/fingerprint/targets.py +352 -0
- ectype/generation/__init__.py +1 -0
- ectype/generation/enforce.py +163 -0
- ectype/generation/generator.py +525 -0
- ectype/generation/identifiers.py +235 -0
- ectype/generation/manifest.py +71 -0
- ectype/generation/parallel.py +229 -0
- ectype/io/__init__.py +16 -0
- ectype/io/adapters.py +224 -0
- ectype/io/sql.py +289 -0
- ectype/io/values.py +269 -0
- ectype/llm/__init__.py +27 -0
- ectype/llm/authoring.py +766 -0
- ectype/llm/providers.py +269 -0
- ectype/models/__init__.py +8 -0
- ectype/models/base.py +120 -0
- ectype/models/chain.py +2426 -0
- ectype/models/copulas.py +254 -0
- ectype/models/encoding.py +1117 -0
- ectype/models/forest.py +1087 -0
- ectype/models/marginals.py +2099 -0
- ectype/models/mixtures.py +336 -0
- ectype/models/neural/__init__.py +21 -0
- ectype/models/neural/adapter.py +638 -0
- ectype/models/neural/vae.py +432 -0
- ectype/models/vines.py +608 -0
- ectype/plugins.py +40 -0
- ectype/privacy/__init__.py +49 -0
- ectype/privacy/attacks.py +599 -0
- ectype/privacy/dp.py +313 -0
- ectype/privacy/report.py +364 -0
- ectype/profiler.py +783 -0
- ectype/profiling/__init__.py +1 -0
- ectype/profiling/bivariate.py +130 -0
- ectype/profiling/calendar.py +743 -0
- ectype/profiling/conditional.py +263 -0
- ectype/profiling/constraints.py +661 -0
- ectype/profiling/entity.py +1143 -0
- ectype/profiling/functional.py +651 -0
- ectype/profiling/multivariate.py +492 -0
- ectype/profiling/personal.py +277 -0
- ectype/profiling/pseudonym.py +370 -0
- ectype/profiling/reference.py +334 -0
- ectype/profiling/sketches.py +653 -0
- ectype/profiling/structural.py +1087 -0
- ectype/profiling/structure.py +1733 -0
- ectype/profiling/sums.py +1710 -0
- ectype/profiling/tolerance.py +435 -0
- ectype/profiling/univariate.py +555 -0
- ectype/py.typed +0 -0
- ectype/registry.py +48 -0
- ectype/relational/__init__.py +61 -0
- ectype/relational/container.py +212 -0
- ectype/relational/fit.py +633 -0
- ectype/relational/generate.py +418 -0
- ectype/relational/schema.py +280 -0
- ectype/relational/validate.py +288 -0
- ectype/reporting/__init__.py +439 -0
- ectype/reporting/adapter.py +2003 -0
- ectype/reporting/charts.py +964 -0
- ectype/reporting/drift.py +902 -0
- ectype/reporting/findings.py +622 -0
- ectype/reporting/fmt.py +429 -0
- ectype/reporting/render.py +1705 -0
- ectype/reporting/select.py +84 -0
- ectype/reporting/style.py +272 -0
- ectype/reporting/view.py +593 -0
- ectype/rng.py +33 -0
- ectype/scenarios/__init__.py +30 -0
- ectype/scenarios/feasibility.py +411 -0
- ectype/scenarios/merge.py +1392 -0
- ectype/scenarios/mutate.py +1613 -0
- ectype/temporal/__init__.py +80 -0
- ectype/temporal/contract.py +221 -0
- ectype/temporal/detect.py +431 -0
- ectype/temporal/events.py +946 -0
- ectype/temporal/panel.py +937 -0
- ectype/temporal/pipeline.py +192 -0
- ectype/temporal/regular.py +674 -0
- ectype/types.py +46 -0
- ectype/validation/__init__.py +1 -0
- ectype/validation/metrics/__init__.py +7 -0
- ectype/validation/metrics/base.py +68 -0
- ectype/validation/metrics/bivariate.py +353 -0
- ectype/validation/metrics/missingness.py +54 -0
- ectype/validation/metrics/multivariate.py +265 -0
- ectype/validation/metrics/temporal.py +596 -0
- ectype/validation/metrics/univariate.py +514 -0
- ectype/validation/report.py +627 -0
- ectype/validation/validator.py +707 -0
- ectype_data-0.1.0.dist-info/METADATA +376 -0
- ectype_data-0.1.0.dist-info/RECORD +115 -0
- ectype_data-0.1.0.dist-info/WHEEL +4 -0
- ectype_data-0.1.0.dist-info/entry_points.txt +2 -0
- ectype_data-0.1.0.dist-info/licenses/LICENSE +192 -0
- ectype_data-0.1.0.dist-info/licenses/NOTICE +5 -0
ectype/llm/providers.py
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
"""LLM providers for spec authoring (M35, design doc 8.2).
|
|
2
|
+
|
|
3
|
+
A :class:`Provider` turns a :class:`PromptRequest` into a text completion that should contain
|
|
4
|
+
one JSON object. Providers never see source rows: the request carries only the manifest
|
|
5
|
+
summary built by :func:`ectype.llm.authoring.manifest_summary` (column names,
|
|
6
|
+
types, roles, stored category labels and constraint expressions).
|
|
7
|
+
|
|
8
|
+
* :class:`AnthropicProvider` calls Claude through the optional ``anthropic`` SDK
|
|
9
|
+
(``pip install 'ectype-data[llm]'``), imported lazily. The API key is read from the
|
|
10
|
+
``ANTHROPIC_API_KEY`` environment variable only and is never logged or echoed.
|
|
11
|
+
* :class:`RuleBasedProvider` is a deterministic, offline fallback that understands a few
|
|
12
|
+
simple phrasings. It is used in tests and whenever no LLM is configured.
|
|
13
|
+
|
|
14
|
+
:func:`extract_json` pulls the first JSON object out of a completion (code fences, prose
|
|
15
|
+
before/after) so providers can be lenient about formatting.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import json
|
|
21
|
+
import os
|
|
22
|
+
import re
|
|
23
|
+
from collections.abc import Mapping
|
|
24
|
+
from dataclasses import dataclass, field
|
|
25
|
+
from typing import Any, Protocol, runtime_checkable
|
|
26
|
+
|
|
27
|
+
from ectype.errors import EctypeError
|
|
28
|
+
|
|
29
|
+
DEFAULT_ANTHROPIC_MODEL = "claude-opus-5-5"
|
|
30
|
+
ANTHROPIC_INSTALL_HINT = ("the Anthropic provider needs the anthropic SDK: "
|
|
31
|
+
"pip install 'ectype-data[llm]'")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class ProviderError(EctypeError):
|
|
35
|
+
"""A provider could not produce a usable completion."""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass(frozen=True)
|
|
39
|
+
class PromptRequest:
|
|
40
|
+
"""Everything a provider may see. ``context`` is the manifest summary (no rows)."""
|
|
41
|
+
|
|
42
|
+
text: str # the user's natural-language request
|
|
43
|
+
target: str # "mutate", "spec" or "auto"
|
|
44
|
+
context: dict[str, Any] # manifest summary; never rows or targets
|
|
45
|
+
system: str # instructions incl. the output JSON schema
|
|
46
|
+
schema: dict[str, Any] = field(default_factory=dict)
|
|
47
|
+
|
|
48
|
+
def user_message(self) -> str:
|
|
49
|
+
return json.dumps({"request": self.text, "target": self.target,
|
|
50
|
+
"fingerprint": self.context}, indent=2, sort_keys=True,
|
|
51
|
+
default=str)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@runtime_checkable
|
|
55
|
+
class Provider(Protocol):
|
|
56
|
+
name: str
|
|
57
|
+
|
|
58
|
+
def complete(self, request: PromptRequest) -> str:
|
|
59
|
+
"""Return the model's reply; it should contain one JSON object."""
|
|
60
|
+
...
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
# ---------------------------------------------------------------------------------------------
|
|
64
|
+
# JSON extraction
|
|
65
|
+
# ---------------------------------------------------------------------------------------------
|
|
66
|
+
|
|
67
|
+
_FENCE = re.compile(r"```(?:json|JSON)?\s*(.*?)```", re.DOTALL)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _balanced_objects(text: str) -> list[str]:
|
|
71
|
+
out: list[str] = []
|
|
72
|
+
depth, start, in_str, esc = 0, -1, False, False
|
|
73
|
+
for i, ch in enumerate(text):
|
|
74
|
+
if in_str:
|
|
75
|
+
if esc:
|
|
76
|
+
esc = False
|
|
77
|
+
elif ch == "\\":
|
|
78
|
+
esc = True
|
|
79
|
+
elif ch == '"':
|
|
80
|
+
in_str = False
|
|
81
|
+
continue
|
|
82
|
+
if ch == '"' and depth > 0:
|
|
83
|
+
in_str = True
|
|
84
|
+
elif ch == "{":
|
|
85
|
+
if depth == 0:
|
|
86
|
+
start = i
|
|
87
|
+
depth += 1
|
|
88
|
+
elif ch == "}" and depth > 0:
|
|
89
|
+
depth -= 1
|
|
90
|
+
if depth == 0:
|
|
91
|
+
out.append(text[start:i + 1])
|
|
92
|
+
return out
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def extract_json(text: str) -> dict[str, Any]:
|
|
96
|
+
"""The first JSON object in ``text`` (tolerates code fences and surrounding prose)."""
|
|
97
|
+
if not isinstance(text, str) or not text.strip():
|
|
98
|
+
raise ProviderError("the provider returned an empty reply")
|
|
99
|
+
candidates = [text.strip(), *(m.strip() for m in _FENCE.findall(text)),
|
|
100
|
+
*_balanced_objects(text)]
|
|
101
|
+
for c in candidates:
|
|
102
|
+
try:
|
|
103
|
+
obj = json.loads(c)
|
|
104
|
+
except (json.JSONDecodeError, ValueError):
|
|
105
|
+
continue
|
|
106
|
+
if isinstance(obj, dict):
|
|
107
|
+
return obj
|
|
108
|
+
raise ProviderError("the provider's reply contains no JSON object")
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
# ---------------------------------------------------------------------------------------------
|
|
112
|
+
# Anthropic
|
|
113
|
+
# ---------------------------------------------------------------------------------------------
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class AnthropicProvider:
|
|
117
|
+
"""Claude via the ``anthropic`` SDK. The key comes from ``ANTHROPIC_API_KEY`` only."""
|
|
118
|
+
|
|
119
|
+
name = "anthropic"
|
|
120
|
+
|
|
121
|
+
def __init__(self, model: str | None = None, *, max_tokens: int = 4096,
|
|
122
|
+
timeout: float = 120.0, client: Any = None) -> None:
|
|
123
|
+
self.model = model or os.environ.get("ECTYPE_LLM_MODEL") or DEFAULT_ANTHROPIC_MODEL
|
|
124
|
+
self.max_tokens = int(max_tokens)
|
|
125
|
+
self.timeout = float(timeout)
|
|
126
|
+
self._client = client
|
|
127
|
+
|
|
128
|
+
def __repr__(self) -> str: # never include credentials
|
|
129
|
+
return f"AnthropicProvider(model={self.model!r})"
|
|
130
|
+
|
|
131
|
+
def _get_client(self) -> Any:
|
|
132
|
+
if self._client is not None:
|
|
133
|
+
return self._client
|
|
134
|
+
try:
|
|
135
|
+
import anthropic
|
|
136
|
+
except ImportError as exc:
|
|
137
|
+
raise ImportError(ANTHROPIC_INSTALL_HINT) from exc
|
|
138
|
+
key = os.environ.get("ANTHROPIC_API_KEY")
|
|
139
|
+
if not key:
|
|
140
|
+
raise ProviderError("ANTHROPIC_API_KEY is not set; the Anthropic provider reads "
|
|
141
|
+
"the key from that environment variable only")
|
|
142
|
+
self._client = anthropic.Anthropic(api_key=key, timeout=self.timeout)
|
|
143
|
+
return self._client
|
|
144
|
+
|
|
145
|
+
def complete(self, request: PromptRequest) -> str:
|
|
146
|
+
client = self._get_client()
|
|
147
|
+
try:
|
|
148
|
+
resp = client.messages.create(
|
|
149
|
+
model=self.model, max_tokens=self.max_tokens, system=request.system,
|
|
150
|
+
messages=[{"role": "user", "content": request.user_message()}])
|
|
151
|
+
except Exception as exc: # noqa: BLE001 - report the type only, never request data
|
|
152
|
+
raise ProviderError(f"Anthropic request failed ({type(exc).__name__})") from None
|
|
153
|
+
if getattr(resp, "stop_reason", None) == "refusal":
|
|
154
|
+
raise ProviderError("the model declined the request")
|
|
155
|
+
parts = [getattr(b, "text", "") for b in getattr(resp, "content", [])
|
|
156
|
+
if getattr(b, "type", None) == "text"]
|
|
157
|
+
return "".join(parts)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
# ---------------------------------------------------------------------------------------------
|
|
161
|
+
# rule-based offline fallback
|
|
162
|
+
# ---------------------------------------------------------------------------------------------
|
|
163
|
+
|
|
164
|
+
_NUM = r"([-+]?\d+(?:\.\d+)?)"
|
|
165
|
+
_COL = r"[`'\"]?([A-Za-z_][\w.\-]*)[`'\"]?"
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _pct(num: str, has_pct: bool) -> float:
|
|
169
|
+
v = float(num)
|
|
170
|
+
return v / 100.0 if has_pct else v
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
class RuleBasedProvider:
|
|
174
|
+
"""Deterministic, offline parser for simple phrasings (no network, no model).
|
|
175
|
+
|
|
176
|
+
Understood (case-insensitive; several clauses may be joined by "and", ";" or ","):
|
|
177
|
+
|
|
178
|
+
* ``increase|raise|decrease|reduce|lower <col> by <n>%`` -> ``mean_multiplier``
|
|
179
|
+
* ``increase|decrease <col> by <n>`` (no %) -> ``shift``
|
|
180
|
+
* ``shift <col> by <n>`` -> ``shift``; ``scale|widen|narrow <col> by <f>`` -> ``scale``
|
|
181
|
+
(``by 20%`` means factor 1.2 / 0.8)
|
|
182
|
+
* ``set (the) missing rate of <col> to <n>%`` / ``<col> missing rate to <n>%``
|
|
183
|
+
* ``(set) (the) correlation between <a> and <b> to <rho>``
|
|
184
|
+
* ``set (the) share|probability|proportion of <label> in <col> to <n>%``
|
|
185
|
+
|
|
186
|
+
Unrecognised text yields ``{"target": "mutate", "mutate": {}, "unparsed": [...]}``,
|
|
187
|
+
which validation rejects with a reason.
|
|
188
|
+
"""
|
|
189
|
+
|
|
190
|
+
name = "rule_based"
|
|
191
|
+
|
|
192
|
+
def complete(self, request: PromptRequest) -> str:
|
|
193
|
+
out: dict[str, dict[str, Any]] = {}
|
|
194
|
+
unparsed: list[str] = []
|
|
195
|
+
text = request.text.strip().rstrip(".")
|
|
196
|
+
corr_re = re.compile(rf"^(?:set\s+)?(?:the\s+)?correlation\s+(?:between\s+)?{_COL}\s+"
|
|
197
|
+
rf"(?:and|,|with)\s+{_COL}\s+(?:to|=|at)\s+{_NUM}$", re.I)
|
|
198
|
+
# split clauses on ";" / "," / " and " except inside "between a and b"
|
|
199
|
+
protected = re.sub(r"(between\s+\S+)\s+and\s+", r"\1 &&& ", text, flags=re.I)
|
|
200
|
+
clauses = [c.strip().replace("&&&", "and")
|
|
201
|
+
for c in re.split(r";|,(?!\d)|\band\b", protected, flags=re.I) if c.strip()]
|
|
202
|
+
for clause in clauses:
|
|
203
|
+
if not self._clause(clause, out, corr_re):
|
|
204
|
+
unparsed.append(clause)
|
|
205
|
+
payload: dict[str, Any] = {"target": "mutate", "mutate": {k: v for k, v in out.items()
|
|
206
|
+
if v}}
|
|
207
|
+
if unparsed:
|
|
208
|
+
payload["unparsed"] = unparsed
|
|
209
|
+
payload["explanation"] = "rule-based parse of the request"
|
|
210
|
+
return json.dumps(payload)
|
|
211
|
+
|
|
212
|
+
@staticmethod
|
|
213
|
+
def _clause(c: str, out: dict[str, dict[str, Any]], corr_re: re.Pattern[str]) -> bool:
|
|
214
|
+
m = corr_re.match(c)
|
|
215
|
+
if m:
|
|
216
|
+
out.setdefault("correlation", {})
|
|
217
|
+
out["correlation"] = {**out["correlation"], f"{m.group(1)},{m.group(2)}":
|
|
218
|
+
float(m.group(3))}
|
|
219
|
+
return True
|
|
220
|
+
m = re.match(rf"^(?:set\s+)?(?:the\s+)?(?:missing(?:ness)?|null)\s+rate\s+(?:of|for)\s+"
|
|
221
|
+
rf"{_COL}\s+(?:to|=|at)\s+{_NUM}\s*(%?)$", c, re.I) or \
|
|
222
|
+
re.match(rf"^(?:set\s+)?{_COL}\s+(?:missing(?:ness)?|null)\s+rate\s+(?:to|=|at)\s+"
|
|
223
|
+
rf"{_NUM}\s*(%?)$", c, re.I)
|
|
224
|
+
if m:
|
|
225
|
+
out.setdefault("missing_rate", {})[m.group(1)] = _pct(m.group(2), bool(m.group(3)))
|
|
226
|
+
return True
|
|
227
|
+
m = re.match(rf"^(?:set\s+)?(?:the\s+)?(?:share|probability|proportion|frequency)\s+of\s+"
|
|
228
|
+
rf"{_COL}\s+in\s+{_COL}\s+(?:to|=|at)\s+{_NUM}\s*(%?)$", c, re.I)
|
|
229
|
+
if m:
|
|
230
|
+
out.setdefault("category_probs", {}).setdefault(m.group(2), {})[m.group(1)] = \
|
|
231
|
+
_pct(m.group(3), bool(m.group(4)))
|
|
232
|
+
return True
|
|
233
|
+
m = re.match(rf"^(increase|raise|grow|decrease|reduce|lower|cut)\s+(?:the\s+)?"
|
|
234
|
+
rf"(?:mean\s+(?:of\s+)?)?{_COL}\s+by\s+{_NUM}\s*(%?)$", c, re.I)
|
|
235
|
+
if m:
|
|
236
|
+
sign = 1.0 if m.group(1).lower() in ("increase", "raise", "grow") else -1.0
|
|
237
|
+
col, v, pct = m.group(2), float(m.group(3)), bool(m.group(4))
|
|
238
|
+
if pct:
|
|
239
|
+
out.setdefault("mean_multiplier", {})[col] = round(1.0 + sign * v / 100.0, 12)
|
|
240
|
+
else:
|
|
241
|
+
out.setdefault("shift", {})[col] = sign * v
|
|
242
|
+
return True
|
|
243
|
+
m = re.match(rf"^shift\s+{_COL}\s+by\s+{_NUM}$", c, re.I)
|
|
244
|
+
if m:
|
|
245
|
+
out.setdefault("shift", {})[m.group(1)] = float(m.group(2))
|
|
246
|
+
return True
|
|
247
|
+
m = re.match(rf"^(scale|widen|narrow)\s+(?:the\s+)?(?:spread\s+of\s+)?{_COL}\s+by\s+"
|
|
248
|
+
rf"{_NUM}\s*(%?)$", c, re.I)
|
|
249
|
+
if m:
|
|
250
|
+
v, pct = float(m.group(3)), bool(m.group(4))
|
|
251
|
+
if pct:
|
|
252
|
+
v = 1.0 + (-1.0 if m.group(1).lower() == "narrow" else 1.0) * v / 100.0
|
|
253
|
+
out.setdefault("scale", {})[m.group(2)] = v
|
|
254
|
+
return True
|
|
255
|
+
return False
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def provider_from_env(env: Mapping[str, str] | None = None) -> Provider:
|
|
259
|
+
"""``ECTYPE_LLM_PROVIDER=anthropic`` selects :class:`AnthropicProvider` (model from
|
|
260
|
+
``ECTYPE_LLM_MODEL``); anything else gives :class:`RuleBasedProvider`."""
|
|
261
|
+
env = os.environ if env is None else env
|
|
262
|
+
if str(env.get("ECTYPE_LLM_PROVIDER", "")).strip().lower() == "anthropic":
|
|
263
|
+
return AnthropicProvider(model=env.get("ECTYPE_LLM_MODEL") or None)
|
|
264
|
+
return RuleBasedProvider()
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
__all__ = ["ANTHROPIC_INSTALL_HINT", "DEFAULT_ANTHROPIC_MODEL", "AnthropicProvider",
|
|
268
|
+
"PromptRequest", "Provider", "ProviderError", "RuleBasedProvider", "extract_json",
|
|
269
|
+
"provider_from_env"]
|
ectype/models/base.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""Plug-in protocols for statistical models.
|
|
2
|
+
|
|
3
|
+
Every model must round-trip through ``ModelSpec`` (JSON params + array refs) so fingerprints
|
|
4
|
+
stay declarative. ``from_spec`` must never execute code from the spec.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from abc import ABC, abstractmethod
|
|
10
|
+
from typing import Any, ClassVar
|
|
11
|
+
|
|
12
|
+
import numpy as np
|
|
13
|
+
|
|
14
|
+
from ectype.fingerprint.core import ArrayStore
|
|
15
|
+
from ectype.fingerprint.schema import ColumnSchema, DisclosurePolicySpec, ModelSpec
|
|
16
|
+
from ectype.registry import Registry
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class MarginalModel(ABC):
|
|
20
|
+
"""A univariate distribution over the *non-null* values of one column.
|
|
21
|
+
|
|
22
|
+
Values are float64 in the model's natural scale. Categorical/boolean columns are handled as
|
|
23
|
+
integer codes ``0..k-1`` (the category labels live in the model's arrays). Datetimes are
|
|
24
|
+
float epoch values in the column's ``datetime_unit``.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
kind: ClassVar[str]
|
|
28
|
+
discrete: bool = False # class default; wrappers may set it per instance
|
|
29
|
+
|
|
30
|
+
@classmethod
|
|
31
|
+
@abstractmethod
|
|
32
|
+
def fit(cls, x: np.ndarray, *, column: ColumnSchema, policy: DisclosurePolicySpec,
|
|
33
|
+
rng: np.random.Generator) -> MarginalModel:
|
|
34
|
+
"""Fit to a 1-D float64 array without NaNs."""
|
|
35
|
+
|
|
36
|
+
@abstractmethod
|
|
37
|
+
def cdf(self, x: np.ndarray) -> np.ndarray:
|
|
38
|
+
"""P(X <= x)."""
|
|
39
|
+
|
|
40
|
+
def cdf_left(self, x: np.ndarray) -> np.ndarray:
|
|
41
|
+
"""P(X < x). Equals ``cdf`` for continuous models; needed for randomized PIT."""
|
|
42
|
+
return self.cdf(x)
|
|
43
|
+
|
|
44
|
+
@abstractmethod
|
|
45
|
+
def ppf(self, u: np.ndarray) -> np.ndarray:
|
|
46
|
+
"""Quantile function; ``u`` in (0, 1). Must be implemented in-engine (no library
|
|
47
|
+
convenience samplers) so output is stable within an engine version."""
|
|
48
|
+
|
|
49
|
+
def sample(self, n: int, rng: np.random.Generator) -> np.ndarray:
|
|
50
|
+
return self.ppf(rng.random(n))
|
|
51
|
+
|
|
52
|
+
def logpdf(self, x: np.ndarray) -> np.ndarray | None:
|
|
53
|
+
"""Log density/mass for model selection. ``None`` if not available."""
|
|
54
|
+
return None
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def n_parameters(self) -> int:
|
|
58
|
+
"""Number of stored scalars (for size accounting on the frontier)."""
|
|
59
|
+
return 0
|
|
60
|
+
|
|
61
|
+
@abstractmethod
|
|
62
|
+
def to_spec(self, store: ArrayStore, prefix: str) -> ModelSpec:
|
|
63
|
+
"""Serialise. Arrays go into ``store`` under names starting with ``prefix``."""
|
|
64
|
+
|
|
65
|
+
@classmethod
|
|
66
|
+
@abstractmethod
|
|
67
|
+
def from_spec(cls, spec: ModelSpec, store: ArrayStore) -> MarginalModel:
|
|
68
|
+
...
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class JointModel(ABC):
|
|
72
|
+
"""A dependence model over latent standard-normal scores (n, d)."""
|
|
73
|
+
|
|
74
|
+
kind: ClassVar[str]
|
|
75
|
+
|
|
76
|
+
columns: list[str]
|
|
77
|
+
|
|
78
|
+
@classmethod
|
|
79
|
+
@abstractmethod
|
|
80
|
+
def fit(cls, z: np.ndarray, columns: list[str], *, policy: DisclosurePolicySpec,
|
|
81
|
+
rng: np.random.Generator) -> JointModel:
|
|
82
|
+
...
|
|
83
|
+
|
|
84
|
+
@abstractmethod
|
|
85
|
+
def sample(self, n: int, rng: np.random.Generator) -> np.ndarray:
|
|
86
|
+
"""Return (n, d) latent standard-normal scores with the fitted dependence."""
|
|
87
|
+
|
|
88
|
+
@property
|
|
89
|
+
def n_parameters(self) -> int:
|
|
90
|
+
return 0
|
|
91
|
+
|
|
92
|
+
@abstractmethod
|
|
93
|
+
def to_spec(self, store: ArrayStore, prefix: str) -> ModelSpec:
|
|
94
|
+
...
|
|
95
|
+
|
|
96
|
+
@classmethod
|
|
97
|
+
@abstractmethod
|
|
98
|
+
def from_spec(cls, spec: ModelSpec, store: ArrayStore) -> JointModel:
|
|
99
|
+
...
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
MARGINALS: Registry[MarginalModel] = Registry("marginal")
|
|
103
|
+
JOINTS: Registry[JointModel] = Registry("joint")
|
|
104
|
+
|
|
105
|
+
#: the joint model a profiler fits when none is named, and the one ``joint="auto"`` starts
|
|
106
|
+
#: from (ADR-0015)
|
|
107
|
+
DEFAULT_JOINT = "chain_copula"
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def marginal_from_spec(spec: ModelSpec, store: ArrayStore) -> MarginalModel:
|
|
111
|
+
return MARGINALS.get(spec.kind).from_spec(spec, store)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def joint_from_spec(spec: ModelSpec, store: ArrayStore) -> JointModel:
|
|
115
|
+
return JOINTS.get(spec.kind).from_spec(spec, store)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def json_float(x: Any) -> float:
|
|
119
|
+
"""Convert numpy scalars to plain floats for JSON params."""
|
|
120
|
+
return float(x)
|