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
|
@@ -0,0 +1,411 @@
|
|
|
1
|
+
"""Feasibility analysis for scenarios and authored fingerprints (M26/M27).
|
|
2
|
+
|
|
3
|
+
Every helper here either returns a diagnostic or raises :class:`ScenarioError` with an
|
|
4
|
+
actionable explanation; nothing silently compromises a request (design doc section 4.5).
|
|
5
|
+
|
|
6
|
+
* :func:`pinned_correlation` - re-project a correlation matrix to positive definite while
|
|
7
|
+
holding requested entries fixed (alternating projections with Dykstra's correction), and
|
|
8
|
+
report the entries actually achieved.
|
|
9
|
+
* :func:`explain_not_pd` / :func:`require_pd` - name the pairs that make a requested
|
|
10
|
+
correlation matrix contradictory.
|
|
11
|
+
* :func:`marginal_mean` / :func:`marginal_std` - deterministic moments of a marginal by
|
|
12
|
+
quadrature on its quantile function (no sampling).
|
|
13
|
+
* :func:`constraint_violation_share` - the share of a (mutated) marginal's mass that violates
|
|
14
|
+
the single-column hard constraints of a fingerprint.
|
|
15
|
+
* :func:`spearman_to_latent` - the Gaussian-copula latent correlation for a target Spearman.
|
|
16
|
+
* :class:`Structure` - the structural transforms of a manifest (format 0.3, ADR-0005) as the
|
|
17
|
+
scenario operations need them: which columns are computed (``end = start + delta``,
|
|
18
|
+
``total = qty * price``) and from what, which hidden latent stands for a column in the joint
|
|
19
|
+
model, and which constraints hold by construction.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import math
|
|
25
|
+
from collections.abc import Mapping, Sequence
|
|
26
|
+
|
|
27
|
+
import numpy as np
|
|
28
|
+
import polars as pl
|
|
29
|
+
|
|
30
|
+
from ectype.errors import ExpressionError, FingerprintError, ScenarioError
|
|
31
|
+
from ectype.fingerprint.schema import ColumnSchema, ConstraintSpec, Manifest, TransformSpec
|
|
32
|
+
from ectype.models.base import MarginalModel
|
|
33
|
+
from ectype.types import Severity
|
|
34
|
+
|
|
35
|
+
MIN_EIGENVALUE = 1e-6
|
|
36
|
+
#: requested correlation entries that move more than this after projection raise
|
|
37
|
+
PIN_RAISE = 0.05
|
|
38
|
+
#: ... and more than this are reported as a compromise in ``ScenarioResult.infeasible``
|
|
39
|
+
PIN_REPORT = 1e-3
|
|
40
|
+
_GRID = 4001
|
|
41
|
+
|
|
42
|
+
Pair = tuple[str, str]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
# ---------------------------------------------------------------------------------------------
|
|
46
|
+
# correlation matrices
|
|
47
|
+
# ---------------------------------------------------------------------------------------------
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _psd_clip(r: np.ndarray, min_eig: float) -> np.ndarray:
|
|
51
|
+
w, v = np.linalg.eigh(0.5 * (r + r.T))
|
|
52
|
+
return (v * np.maximum(w, min_eig)) @ v.T
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def min_eigenvalue(r: np.ndarray) -> float:
|
|
56
|
+
r = np.asarray(r, dtype=float)
|
|
57
|
+
return float(np.linalg.eigvalsh(0.5 * (r + r.T)).min()) if r.size else 1.0
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def pinned_correlation(r: np.ndarray, pinned: Mapping[tuple[int, int], float], *,
|
|
61
|
+
preserve: bool = True, min_eig: float = MIN_EIGENVALUE,
|
|
62
|
+
max_iter: int = 2000, tol: float = 1e-10) -> np.ndarray:
|
|
63
|
+
"""Nearest correlation matrix to ``r`` with the ``pinned`` entries set.
|
|
64
|
+
|
|
65
|
+
With ``preserve=True`` the pinned entries are held fixed (Higham-style alternating
|
|
66
|
+
projections with Dykstra's correction onto {PSD} and {unit diagonal, pinned entries}), so
|
|
67
|
+
the *other* entries absorb the adjustment and move as little as possible. With
|
|
68
|
+
``preserve=False`` the pinned entries are written in and the whole matrix is clipped to the
|
|
69
|
+
nearest PD correlation (every entry, pinned or not, may move). Either way the result is
|
|
70
|
+
symmetric, unit-diagonal and has eigenvalues >= ~``min_eig``; callers compare the pinned
|
|
71
|
+
entries of the result with the request.
|
|
72
|
+
"""
|
|
73
|
+
y = np.array(r, dtype=float, copy=True)
|
|
74
|
+
y = 0.5 * (y + y.T)
|
|
75
|
+
idx = [(i, j) for (i, j) in pinned]
|
|
76
|
+
vals = [float(v) for v in pinned.values()]
|
|
77
|
+
|
|
78
|
+
def fix(m: np.ndarray) -> np.ndarray:
|
|
79
|
+
np.fill_diagonal(m, 1.0)
|
|
80
|
+
for (i, j), v in zip(idx, vals):
|
|
81
|
+
m[i, j] = m[j, i] = v
|
|
82
|
+
return m
|
|
83
|
+
|
|
84
|
+
y = fix(y)
|
|
85
|
+
if min_eigenvalue(y) >= min_eig:
|
|
86
|
+
return y
|
|
87
|
+
if preserve:
|
|
88
|
+
ds = np.zeros_like(y)
|
|
89
|
+
for _ in range(max_iter):
|
|
90
|
+
rk = y - ds
|
|
91
|
+
x = _psd_clip(rk, min_eig)
|
|
92
|
+
ds = x - rk
|
|
93
|
+
y_new = fix(x.copy())
|
|
94
|
+
if np.max(np.abs(y_new - y)) < tol:
|
|
95
|
+
y = y_new
|
|
96
|
+
break
|
|
97
|
+
y = y_new
|
|
98
|
+
if min_eigenvalue(y) >= 0.5 * min_eig:
|
|
99
|
+
return 0.5 * (y + y.T)
|
|
100
|
+
# plain nearest correlation (pinned entries may move)
|
|
101
|
+
x = _psd_clip(y, min_eig)
|
|
102
|
+
d = np.sqrt(np.clip(np.diag(x), 1e-300, None))
|
|
103
|
+
x = x / np.outer(d, d)
|
|
104
|
+
x = 0.5 * (x + x.T)
|
|
105
|
+
np.fill_diagonal(x, 1.0)
|
|
106
|
+
return x
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def explain_not_pd(r: np.ndarray, names: Sequence[str],
|
|
110
|
+
specified: Mapping[Pair, float] | None = None) -> str:
|
|
111
|
+
"""Human explanation of why ``r`` is not positive definite: the eigen-direction that fails
|
|
112
|
+
and the specified pairs among its columns, marking the pairs whose removal (set to 0)
|
|
113
|
+
alone would make the matrix valid."""
|
|
114
|
+
r = np.asarray(r, dtype=float)
|
|
115
|
+
w, v = np.linalg.eigh(0.5 * (r + r.T))
|
|
116
|
+
vec = v[:, int(np.argmin(w))]
|
|
117
|
+
big = np.abs(vec) >= 0.2 * np.abs(vec).max()
|
|
118
|
+
involved = [names[int(i)] for i in np.flatnonzero(big)]
|
|
119
|
+
pos = {n: i for i, n in enumerate(names)}
|
|
120
|
+
spec = dict(specified or {})
|
|
121
|
+
rows = []
|
|
122
|
+
for (a, b), rho in spec.items():
|
|
123
|
+
if a in involved and b in involved:
|
|
124
|
+
t = r.copy()
|
|
125
|
+
i, j = pos[a], pos[b]
|
|
126
|
+
t[i, j] = t[j, i] = 0.0
|
|
127
|
+
fixes = min_eigenvalue(t) > 0
|
|
128
|
+
rows.append(f"({a}, {b}) = {rho:+.3f}" + (" [removing it resolves the conflict]"
|
|
129
|
+
if fixes else ""))
|
|
130
|
+
if not rows:
|
|
131
|
+
rows = [f"({a}, {b}) = {r[pos[a], pos[b]]:+.3f}" for k, a in enumerate(involved)
|
|
132
|
+
for b in involved[k + 1:]]
|
|
133
|
+
return (f"the correlation matrix is not positive definite (smallest eigenvalue "
|
|
134
|
+
f"{float(w.min()):.4g}); the conflict involves columns {involved}. Conflicting "
|
|
135
|
+
f"pairs: " + "; ".join(rows) + ". Correlations must be jointly consistent (e.g. "
|
|
136
|
+
"if a~b and b~c are both strongly positive, a~c cannot be strongly negative).")
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def require_pd(r: np.ndarray, names: Sequence[str], specified: Mapping[Pair, float],
|
|
140
|
+
*, error: type[Exception] = ScenarioError, min_eig: float = 1e-8) -> None:
|
|
141
|
+
if r.size and min_eigenvalue(r) < min_eig:
|
|
142
|
+
raise error("contradictory correlation spec: " + explain_not_pd(r, names, specified))
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def spearman_to_latent(rho_s: float) -> float:
|
|
146
|
+
"""Latent (Gaussian copula) correlation giving Spearman ``rho_s`` for continuous margins:
|
|
147
|
+
``2 sin(pi rho_s / 6)``."""
|
|
148
|
+
return float(2.0 * math.sin(math.pi * float(rho_s) / 6.0))
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def latent_to_spearman(rho: float) -> float:
|
|
152
|
+
return float(6.0 / math.pi * math.asin(float(rho) / 2.0))
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def check_rho(rho: float, what: str) -> float:
|
|
156
|
+
try:
|
|
157
|
+
x = float(rho)
|
|
158
|
+
except (TypeError, ValueError):
|
|
159
|
+
raise ScenarioError(f"{what}: correlation must be a number, got {rho!r}") from None
|
|
160
|
+
if not math.isfinite(x) or not -1.0 < x < 1.0:
|
|
161
|
+
raise ScenarioError(f"{what}: correlation must lie strictly inside (-1, 1), got {x}")
|
|
162
|
+
return x
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
# ---------------------------------------------------------------------------------------------
|
|
166
|
+
# marginal moments
|
|
167
|
+
# ---------------------------------------------------------------------------------------------
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _grid_values(m: MarginalModel, n: int = _GRID) -> np.ndarray:
|
|
171
|
+
u = (np.arange(n, dtype=float) + 0.5) / n
|
|
172
|
+
return np.asarray(m.ppf(u), dtype=float)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def marginal_mean(m: MarginalModel) -> float:
|
|
176
|
+
"""Mean of a marginal by midpoint quadrature on its quantile function."""
|
|
177
|
+
return float(np.mean(_grid_values(m)))
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def marginal_std(m: MarginalModel) -> float:
|
|
181
|
+
return float(np.std(_grid_values(m)))
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
# ---------------------------------------------------------------------------------------------
|
|
185
|
+
# constraints
|
|
186
|
+
# ---------------------------------------------------------------------------------------------
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def single_column_constraints(constraints: Sequence[ConstraintSpec], column: str
|
|
190
|
+
) -> list[ConstraintSpec]:
|
|
191
|
+
"""Hard constraints whose expression references ``column`` only."""
|
|
192
|
+
from ectype.fingerprint import expressions as ex
|
|
193
|
+
|
|
194
|
+
out = []
|
|
195
|
+
for c in constraints:
|
|
196
|
+
if c.severity != Severity.HARD:
|
|
197
|
+
continue
|
|
198
|
+
try:
|
|
199
|
+
refs = ex.referenced_columns(c.expression)
|
|
200
|
+
except ExpressionError:
|
|
201
|
+
continue
|
|
202
|
+
if refs == {column}:
|
|
203
|
+
out.append(c)
|
|
204
|
+
return out
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def value_violation_share(values: np.ndarray, column: ColumnSchema,
|
|
208
|
+
constraints: Sequence[ConstraintSpec]) -> dict[str, float]:
|
|
209
|
+
"""``{constraint_id: share of values violating it}`` for the single-column hard constraints
|
|
210
|
+
on ``column``. ``values`` are in the engine's value domain; a null result counts as
|
|
211
|
+
satisfied."""
|
|
212
|
+
from ectype.fingerprint import expressions as ex
|
|
213
|
+
from ectype.io.values import values_to_column
|
|
214
|
+
|
|
215
|
+
cons = single_column_constraints(constraints, column.name)
|
|
216
|
+
if not cons or np.size(values) == 0:
|
|
217
|
+
return {}
|
|
218
|
+
df = pl.DataFrame([values_to_column(np.asarray(values, dtype=np.float64), column)])
|
|
219
|
+
out: dict[str, float] = {}
|
|
220
|
+
for c in cons:
|
|
221
|
+
try:
|
|
222
|
+
ok = df.select(ex.to_polars(c.expression, {column.name: column}).alias("ok"))["ok"]
|
|
223
|
+
except Exception: # noqa: BLE001 - a constraint we cannot evaluate is not checked here
|
|
224
|
+
continue
|
|
225
|
+
out[c.id] = float((ok == False).sum()) / df.height # noqa: E712 (null = satisfied)
|
|
226
|
+
return out
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def constraint_violation_share(marginal: MarginalModel, column: ColumnSchema,
|
|
230
|
+
constraints: Sequence[ConstraintSpec]) -> dict[str, float]:
|
|
231
|
+
"""``{constraint_id: share of the marginal's mass violating it}`` for the single-column
|
|
232
|
+
hard constraints on ``column`` (stratified quantile grid; deterministic)."""
|
|
233
|
+
if not single_column_constraints(constraints, column.name):
|
|
234
|
+
return {}
|
|
235
|
+
return value_violation_share(_grid_values(marginal, 2000), column, constraints)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
# ---------------------------------------------------------------------------------------------
|
|
239
|
+
# structural transforms
|
|
240
|
+
# ---------------------------------------------------------------------------------------------
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
class Structure:
|
|
244
|
+
"""The structural transforms of a manifest (``model.transforms``, ADR-0005) as the scenario
|
|
245
|
+
operations need them.
|
|
246
|
+
|
|
247
|
+
A *target* is a column computed by a transform. A ``difference`` target is
|
|
248
|
+
``base + sign * delta``, where the hidden latent ``delta`` is modeled in its place
|
|
249
|
+
(``delta >= 0``, unless the transform is ``signed``: it then models the source's few
|
|
250
|
+
out-of-order rows and guarantees no ordering, ADR-0009); an ``identity`` target is
|
|
251
|
+
``a op b`` and has no model at all. Every other column is *plain*, including the target of
|
|
252
|
+
an ordering enforced without a transform (``model.orderings``): it keeps its own marginal.
|
|
253
|
+
|
|
254
|
+
Nothing here validates the transforms (the compiler does). A manifest without transforms
|
|
255
|
+
gives an empty structure in which every column is plain.
|
|
256
|
+
"""
|
|
257
|
+
|
|
258
|
+
def __init__(self, manifest: Manifest | None = None,
|
|
259
|
+
transforms: Sequence[TransformSpec] | None = None) -> None:
|
|
260
|
+
raw = list(transforms if transforms is not None
|
|
261
|
+
else (manifest.model.transforms if manifest is not None else []))
|
|
262
|
+
try:
|
|
263
|
+
from ectype.profiling.structure import order_transforms
|
|
264
|
+
|
|
265
|
+
raw = order_transforms(raw)
|
|
266
|
+
except FingerprintError: # a cycle: the compiler reports it
|
|
267
|
+
pass
|
|
268
|
+
#: transforms in topological order (inputs before the targets computed from them)
|
|
269
|
+
self.transforms: list[TransformSpec] = raw
|
|
270
|
+
self.by_target: dict[str, TransformSpec] = {t.target: t for t in raw}
|
|
271
|
+
#: hidden latent column -> its ``difference`` transform
|
|
272
|
+
self.by_latent: dict[str, TransformSpec] = {
|
|
273
|
+
str(t.params["latent"]): t for t in raw
|
|
274
|
+
if t.kind == "difference" and "latent" in t.params}
|
|
275
|
+
|
|
276
|
+
def __bool__(self) -> bool:
|
|
277
|
+
return bool(self.transforms)
|
|
278
|
+
|
|
279
|
+
# -- one transform ----------------------------------------------------------------------
|
|
280
|
+
def transform(self, column: str) -> TransformSpec | None:
|
|
281
|
+
"""The transform that computes ``column`` (``None`` for a plain column)."""
|
|
282
|
+
return self.by_target.get(column)
|
|
283
|
+
|
|
284
|
+
@staticmethod
|
|
285
|
+
def latent(t: TransformSpec) -> str:
|
|
286
|
+
return str(t.params["latent"])
|
|
287
|
+
|
|
288
|
+
@staticmethod
|
|
289
|
+
def sign(t: TransformSpec) -> float:
|
|
290
|
+
return float(t.params.get("sign", 1)) # type: ignore[arg-type]
|
|
291
|
+
|
|
292
|
+
@staticmethod
|
|
293
|
+
def signed(t: TransformSpec) -> bool:
|
|
294
|
+
"""Whether the latent of a ``difference`` transform may be negative (no ordering is
|
|
295
|
+
guaranteed, so nothing has to keep it non-negative)."""
|
|
296
|
+
return t.kind == "difference" and t.params.get("signed") is True
|
|
297
|
+
|
|
298
|
+
@staticmethod
|
|
299
|
+
def formula(t: TransformSpec, *, hidden: bool = True) -> str:
|
|
300
|
+
"""``"end = start + __delta__end"`` or ``"total = qty * price"``. With
|
|
301
|
+
``hidden=False`` the latent is written ``delta``."""
|
|
302
|
+
if t.kind == "difference":
|
|
303
|
+
op = "+" if Structure.sign(t) > 0 else "-"
|
|
304
|
+
lat = str(t.params.get("latent", "delta")) if hidden else "delta"
|
|
305
|
+
return f"{t.target} = {t.inputs[0]} {op} {lat}"
|
|
306
|
+
if t.kind == "identity" and len(t.inputs) == 2:
|
|
307
|
+
return f"{t.target} = {t.inputs[0]} {t.params.get('op')} {t.inputs[1]}"
|
|
308
|
+
return f"{t.target} = {t.kind}({', '.join(t.inputs)})"
|
|
309
|
+
|
|
310
|
+
# -- the dependency graph -----------------------------------------------------------------
|
|
311
|
+
def inputs(self, column: str) -> set[str]:
|
|
312
|
+
"""Every column ``column`` is computed from, transitively (empty for a plain one)."""
|
|
313
|
+
out: set[str] = set()
|
|
314
|
+
stack = [column]
|
|
315
|
+
while stack:
|
|
316
|
+
t = self.by_target.get(stack.pop())
|
|
317
|
+
for name in (t.inputs if t is not None else ()):
|
|
318
|
+
if name not in out:
|
|
319
|
+
out.add(name)
|
|
320
|
+
stack.append(name)
|
|
321
|
+
return out
|
|
322
|
+
|
|
323
|
+
def dependents(self, column: str) -> list[str]:
|
|
324
|
+
"""The targets computed from ``column``, transitively, in topological order."""
|
|
325
|
+
return [t.target for t in self.transforms if column in self.inputs(t.target)]
|
|
326
|
+
|
|
327
|
+
def related(self, a: str, b: str) -> bool:
|
|
328
|
+
"""Whether ``a`` and ``b`` are structurally linked: one is computed from the other, or
|
|
329
|
+
both are computed from a common column."""
|
|
330
|
+
return bool(({a} | self.inputs(a)) & ({b} | self.inputs(b)))
|
|
331
|
+
|
|
332
|
+
def ordered(self, columns: Sequence[str]) -> list[str]:
|
|
333
|
+
"""``columns`` with the plain ones first (in the given order) and the targets after
|
|
334
|
+
them in topological order, so a base is always handled before what is computed from
|
|
335
|
+
it."""
|
|
336
|
+
plain = [c for c in columns if c not in self.by_target]
|
|
337
|
+
return plain + [t.target for t in self.transforms if t.target in columns]
|
|
338
|
+
|
|
339
|
+
# -- the joint model ----------------------------------------------------------------------
|
|
340
|
+
def slot(self, column: str) -> tuple[str, float] | None:
|
|
341
|
+
"""The column of the joint model that stands for ``column``, and the direction in which
|
|
342
|
+
``column`` moves with it: ``(column, 1.0)`` for a plain column, ``(latent, sign)`` for
|
|
343
|
+
a ``difference`` target, ``None`` for a target without a model (``identity``)."""
|
|
344
|
+
t = self.by_target.get(column)
|
|
345
|
+
if t is None:
|
|
346
|
+
return column, 1.0
|
|
347
|
+
if t.kind == "difference" and "latent" in t.params:
|
|
348
|
+
return self.latent(t), self.sign(t)
|
|
349
|
+
return None
|
|
350
|
+
|
|
351
|
+
def feeds(self, column: str) -> set[str]:
|
|
352
|
+
"""The joint-model columns ``column`` is computed from: its own slot and the slots of
|
|
353
|
+
everything it is computed from."""
|
|
354
|
+
out: set[str] = set()
|
|
355
|
+
for name in {column} | self.inputs(column):
|
|
356
|
+
s = self.slot(name)
|
|
357
|
+
if s is not None:
|
|
358
|
+
out.add(s[0])
|
|
359
|
+
return out
|
|
360
|
+
|
|
361
|
+
# -- constraints --------------------------------------------------------------------------
|
|
362
|
+
def implies(self, expression: str) -> bool:
|
|
363
|
+
"""Whether a constraint holds by construction: an ordering ``lo <= hi`` guaranteed by a
|
|
364
|
+
chain of ``difference`` transforms (not ``signed`` ones), or the identity an
|
|
365
|
+
``identity`` transform computes. A strict ordering holds up to ties (``delta == 0``)."""
|
|
366
|
+
from ectype.profiling.structure import identity_form, ordering_form
|
|
367
|
+
|
|
368
|
+
try:
|
|
369
|
+
order = ordering_form(expression)
|
|
370
|
+
ident = identity_form(expression) if order is None else None
|
|
371
|
+
except Exception: # noqa: BLE001 - not an expression this engine parses
|
|
372
|
+
return False
|
|
373
|
+
if order is not None:
|
|
374
|
+
lo, hi, _strict = order
|
|
375
|
+
le: dict[str, set[str]] = {}
|
|
376
|
+
for t in self.transforms:
|
|
377
|
+
if t.kind != "difference" or self.signed(t):
|
|
378
|
+
continue
|
|
379
|
+
a, b = (t.inputs[0], t.target) if self.sign(t) > 0 else (t.target, t.inputs[0])
|
|
380
|
+
le.setdefault(a, set()).add(b)
|
|
381
|
+
seen, stack = {lo}, [lo]
|
|
382
|
+
while stack:
|
|
383
|
+
for nxt in le.get(stack.pop(), ()):
|
|
384
|
+
if nxt == hi:
|
|
385
|
+
return True
|
|
386
|
+
if nxt not in seen:
|
|
387
|
+
seen.add(nxt)
|
|
388
|
+
stack.append(nxt)
|
|
389
|
+
return False
|
|
390
|
+
if ident is not None:
|
|
391
|
+
target, op, a, b = ident
|
|
392
|
+
spec = self.by_target.get(target)
|
|
393
|
+
if spec is None or spec.kind != "identity" or spec.params.get("op") != op:
|
|
394
|
+
return False
|
|
395
|
+
return list(spec.inputs) == [a, b] or (op in "+*" and list(spec.inputs) == [b, a])
|
|
396
|
+
return False
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def generated_columns(manifest: Manifest) -> set[str]:
|
|
400
|
+
"""The source columns the model itself generates: the encoded features (without the hidden
|
|
401
|
+
latents of ``difference`` transforms) plus the transform targets."""
|
|
402
|
+
structure = Structure(manifest)
|
|
403
|
+
return (set(manifest.model.encodings) - set(structure.by_latent)) | set(structure.by_target)
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
__all__ = [
|
|
407
|
+
"MIN_EIGENVALUE", "PIN_RAISE", "PIN_REPORT", "Structure", "check_rho",
|
|
408
|
+
"constraint_violation_share", "explain_not_pd", "generated_columns", "latent_to_spearman",
|
|
409
|
+
"marginal_mean", "marginal_std", "min_eigenvalue", "pinned_correlation", "require_pd",
|
|
410
|
+
"single_column_constraints", "spearman_to_latent", "value_violation_share",
|
|
411
|
+
]
|