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,2003 @@
|
|
|
1
|
+
"""Read a fingerprint into the report's own view model (ADR-0016, sections 2 and 3).
|
|
2
|
+
|
|
3
|
+
This is the only module of :mod:`ectype.reporting` that knows the fingerprint: manifest field
|
|
4
|
+
names, model kinds, array names and diagnostics. Everything else of the report sees a
|
|
5
|
+
:class:`~ectype.reporting.view.ReportView`.
|
|
6
|
+
|
|
7
|
+
* :func:`build_view` takes a loaded :class:`~ectype.fingerprint.core.Fingerprint`, turns its
|
|
8
|
+
manifest into JSON-shaped data and hands it to :func:`view_from_parts`. It never opens the
|
|
9
|
+
sealed targets.
|
|
10
|
+
* :func:`view_from_parts` works on dictionaries and lists only and never raises: every read
|
|
11
|
+
goes through helpers that return a default for a missing key or a value of the wrong type,
|
|
12
|
+
each column and each section is read in a guard of its own, and whatever could not be read
|
|
13
|
+
becomes an :class:`~ectype.reporting.view.Unread` record while the rest is still built.
|
|
14
|
+
* :data:`KNOWN_KEYS` lists, per level of the manifest, every key the adapter knows (shown or
|
|
15
|
+
deliberately not shown). Any other key is reported as unread, so nothing is dropped
|
|
16
|
+
silently.
|
|
17
|
+
|
|
18
|
+
Column distributions are rebuilt by the engine's own model code
|
|
19
|
+
(:func:`ectype.models.base.marginal_from_spec`) evaluated on an even grid of :data:`GRID`
|
|
20
|
+
probabilities; the stored arrays are only a fallback for a model kind the engine does not know.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import math
|
|
26
|
+
import os
|
|
27
|
+
import re
|
|
28
|
+
import warnings
|
|
29
|
+
from collections import OrderedDict
|
|
30
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
31
|
+
from typing import TYPE_CHECKING, Any
|
|
32
|
+
|
|
33
|
+
import numpy as np
|
|
34
|
+
|
|
35
|
+
from ectype.reporting import view as v
|
|
36
|
+
|
|
37
|
+
if TYPE_CHECKING: # pragma: no cover
|
|
38
|
+
from ectype.fingerprint.core import Fingerprint
|
|
39
|
+
|
|
40
|
+
# -- caps -------------------------------------------------------------------------------------
|
|
41
|
+
|
|
42
|
+
GRID = 4000
|
|
43
|
+
BINS = 40
|
|
44
|
+
MAX_BARS = 12
|
|
45
|
+
MAX_ATOMS = 6
|
|
46
|
+
ATOM_MIN_SHARE = 0.01
|
|
47
|
+
MAX_PAIRS = 40
|
|
48
|
+
MATRIX_COLUMNS = 24
|
|
49
|
+
MAX_SUGGESTED = 50
|
|
50
|
+
MAX_NOT_APPLIED = 30
|
|
51
|
+
MAX_NOTES = 8
|
|
52
|
+
MAX_TEXT = 600
|
|
53
|
+
|
|
54
|
+
#: integer-valued columns with at most this many distinct grid values are drawn as bars
|
|
55
|
+
MAX_ORDERED_LEVELS = 25
|
|
56
|
+
#: quantiles stated for every histogram
|
|
57
|
+
QUANTILE_PROBS = (0.01, 0.05, 0.25, 0.5, 0.75, 0.95, 0.99)
|
|
58
|
+
#: label of the bucket the policy pools rare categories into
|
|
59
|
+
POOLED_LABEL = "__other__"
|
|
60
|
+
#: prefix of the engine's note on a column that looks like personal data
|
|
61
|
+
PERSONAL_NOTE = "looks like personal data"
|
|
62
|
+
|
|
63
|
+
# -- vocabulary this version of the report knows ---------------------------------------------
|
|
64
|
+
# (``test_report_schema_coverage.py`` checks these against the engine's own lists)
|
|
65
|
+
|
|
66
|
+
#: column role -> handling, for roles that decide the handling on their own
|
|
67
|
+
ROLE_HANDLING: dict[str, str] = {
|
|
68
|
+
"feature": "modeled",
|
|
69
|
+
"identifier": "identifier",
|
|
70
|
+
"pseudonym": "pseudonym",
|
|
71
|
+
"reference": "reference",
|
|
72
|
+
"constant": "constant",
|
|
73
|
+
"derived": "computed",
|
|
74
|
+
"excluded": "excluded",
|
|
75
|
+
}
|
|
76
|
+
LOGICAL_TYPES = frozenset({"continuous", "discrete", "boolean", "categorical", "datetime",
|
|
77
|
+
"string", "text"})
|
|
78
|
+
TRANSFORM_KINDS = frozenset({"difference", "identity"})
|
|
79
|
+
ORDERING_METHODS = frozenset({"reflect"})
|
|
80
|
+
CALENDAR_METHODS = frozenset({"transport"})
|
|
81
|
+
ENTITY_METHODS = frozenset({"lookup"})
|
|
82
|
+
SUM_MODES = frozenset({"split", "scale", "sum"})
|
|
83
|
+
SUM_ROUNDINGS = frozenset({"exact", "independent"})
|
|
84
|
+
MEASURES = frozenset({"spearman", "cramers_v", "correlation_ratio"})
|
|
85
|
+
|
|
86
|
+
#: manifest keys the adapter knows at each tracked level (shown or deliberately not shown)
|
|
87
|
+
KNOWN_KEYS: dict[str, frozenset[str]] = {
|
|
88
|
+
"manifest": frozenset({
|
|
89
|
+
"fingerprint_version", "dataset", "columns", "disclosure_policy",
|
|
90
|
+
"disclosure_diagnostics", "model", "constraints", "targets", "diagnostics",
|
|
91
|
+
"provenance",
|
|
92
|
+
"generation", # generation defaults (seed, chunk size): not shown
|
|
93
|
+
"temporal", "population", "relational", "extensions", # listed in extra_sections
|
|
94
|
+
}),
|
|
95
|
+
"dataset": frozenset({"name", "source_records", "source_columns", "description",
|
|
96
|
+
"grain"}), # grain: not shown
|
|
97
|
+
"column": frozenset({
|
|
98
|
+
"name", "logical_type", "role", "physical_dtype", "null_fraction", "n_unique",
|
|
99
|
+
"decimals", "min_value", "max_value", "integer_valued", "datetime_unit", "is_date",
|
|
100
|
+
"pattern", "confidence", "overridden", "notes",
|
|
101
|
+
"nullable", "timezone", "bool_labels", # not shown
|
|
102
|
+
}),
|
|
103
|
+
"disclosure_policy": frozenset({
|
|
104
|
+
"profile", "min_category_support", "quantile_resolution", "tail_clip",
|
|
105
|
+
"rare_cell_min", "significant_digits", "identifiers", "sensitive"}),
|
|
106
|
+
"disclosure_diagnostics": frozenset({
|
|
107
|
+
"smallest_stored_support", "pooled_categories", "warnings", "nn_distance_ratio",
|
|
108
|
+
"max_quantiles_per_row"}), # max_quantiles_per_row: not shown
|
|
109
|
+
"model": frozenset({
|
|
110
|
+
"marginals", "encodings", "joint", "constants", "derived", "transforms", "orderings",
|
|
111
|
+
"calendars", "entities", "references", "sums",
|
|
112
|
+
# not shown: how missing values, identifiers and the generation order are produced
|
|
113
|
+
"conditional", "missingness", "identifiers", "column_order", "generation_order",
|
|
114
|
+
}),
|
|
115
|
+
"constraints": frozenset({"confirmed", "suggested"}),
|
|
116
|
+
"provenance": frozenset({
|
|
117
|
+
"created_at", "engine_version", "fit_seed", "lineage",
|
|
118
|
+
"dependencies", "config", "config_hash"}), # not shown
|
|
119
|
+
"diagnostics": frozenset({
|
|
120
|
+
"calendars", "entities", "functions", "structure", "sums",
|
|
121
|
+
# written by mutate and merge; the page says how the fingerprint was made (lineage)
|
|
122
|
+
# and does not show their detail
|
|
123
|
+
"targets_source", "merge_dropped_constraints", "merge_scoped_constraints",
|
|
124
|
+
"merge_transforms", "merge_component_shares"}),
|
|
125
|
+
"container_diagnostics": frozenset({
|
|
126
|
+
"associations", "excluded_columns", "pseudonymised_columns",
|
|
127
|
+
"joint", # read_joint_diagnostics
|
|
128
|
+
"marginal_selection", # not shown
|
|
129
|
+
"scenario"}), # mutate's own report: not shown
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
#: association strength from which columns count as carrying the same information, and the
|
|
133
|
+
#: weakest pair a group of such columns may contain
|
|
134
|
+
NEAR_IDENTICAL = 0.98
|
|
135
|
+
GROUP_FLOOR = 0.95
|
|
136
|
+
SYMMETRIC_MEASURES = frozenset({"spearman", "cramers_v"})
|
|
137
|
+
|
|
138
|
+
_EXTRA_SECTIONS = ("temporal", "population", "relational")
|
|
139
|
+
_NOT_SELECTED_KINDS = (("structure", "ordering"), ("functions", "computed"), ("sums", "sum"),
|
|
140
|
+
("entities", "entity"), ("calendars", "weekly"))
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
# -- small, total readers ---------------------------------------------------------------------
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _d(x: Any) -> Mapping[str, Any]:
|
|
147
|
+
if type(x) is dict:
|
|
148
|
+
return x
|
|
149
|
+
return x if isinstance(x, Mapping) else {}
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _l(x: Any) -> list[Any]:
|
|
153
|
+
return list(x) if isinstance(x, (list, tuple)) else []
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _get(m: Any, key: str, default: Any = None) -> Any:
|
|
157
|
+
if type(m) is dict:
|
|
158
|
+
return m.get(key, default)
|
|
159
|
+
if isinstance(m, Mapping):
|
|
160
|
+
try:
|
|
161
|
+
return m.get(key, default)
|
|
162
|
+
except Exception:
|
|
163
|
+
return default
|
|
164
|
+
return default
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _s(x: Any, default: str = "") -> str:
|
|
168
|
+
"""A string as stored; numbers are written as text, anything else gives ``default``."""
|
|
169
|
+
if isinstance(x, str):
|
|
170
|
+
return x
|
|
171
|
+
if isinstance(x, bool):
|
|
172
|
+
return "true" if x else "false"
|
|
173
|
+
if isinstance(x, int):
|
|
174
|
+
return str(x)
|
|
175
|
+
if isinstance(x, float) and math.isfinite(x):
|
|
176
|
+
return repr(x)
|
|
177
|
+
return default
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _os(x: Any) -> str | None:
|
|
181
|
+
out = _s(x)
|
|
182
|
+
return out if out else None
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _num(x: Any) -> float | None:
|
|
186
|
+
if type(x) is float:
|
|
187
|
+
return x if math.isfinite(x) else None
|
|
188
|
+
if isinstance(x, bool) or not isinstance(x, (int, float, np.integer, np.floating)):
|
|
189
|
+
return None
|
|
190
|
+
try:
|
|
191
|
+
f = float(x)
|
|
192
|
+
except (OverflowError, ValueError):
|
|
193
|
+
return None
|
|
194
|
+
return f if math.isfinite(f) else None
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _int(x: Any) -> int | None:
|
|
198
|
+
f = _num(x)
|
|
199
|
+
if f is None or abs(f) > 2 ** 62:
|
|
200
|
+
return None
|
|
201
|
+
return int(f) if float(int(f)) == f else None
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _strs(x: Any) -> list[str]:
|
|
205
|
+
return [s for s in (_s(i) for i in _l(x)) if s]
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _text(x: Any) -> str:
|
|
209
|
+
"""A string capped at :data:`MAX_TEXT` characters (cut ones end with an ellipsis)."""
|
|
210
|
+
s = _s(x)
|
|
211
|
+
return s if len(s) <= MAX_TEXT else s[: MAX_TEXT - 1] + "…"
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _value_text(x: Any) -> str | None:
|
|
215
|
+
if x is None:
|
|
216
|
+
return None
|
|
217
|
+
if isinstance(x, (str, int, float, bool)):
|
|
218
|
+
return _text(_s(x, str(x)))
|
|
219
|
+
import json
|
|
220
|
+
|
|
221
|
+
try:
|
|
222
|
+
return _text(json.dumps(x, sort_keys=True, default=str))
|
|
223
|
+
except Exception:
|
|
224
|
+
return _text(repr(x))
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _kind_of(x: Any) -> str:
|
|
228
|
+
return type(x).__name__ if x is not None else "null"
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _entries(x: Any) -> int | None:
|
|
232
|
+
return len(x) if isinstance(x, (list, tuple, dict, Mapping)) else None
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _array(arrays: Mapping[str, Any], ref: Any) -> np.ndarray | None:
|
|
236
|
+
if not isinstance(ref, str):
|
|
237
|
+
return None
|
|
238
|
+
a = _get(arrays, ref)
|
|
239
|
+
if a is None:
|
|
240
|
+
return None
|
|
241
|
+
try:
|
|
242
|
+
return np.asarray(a)
|
|
243
|
+
except Exception:
|
|
244
|
+
return None
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _num_array(arrays: Mapping[str, Any], ref: Any) -> np.ndarray | None:
|
|
248
|
+
a = _array(arrays, ref)
|
|
249
|
+
if a is None:
|
|
250
|
+
return None
|
|
251
|
+
try:
|
|
252
|
+
out = np.asarray(a, dtype=np.float64).ravel()
|
|
253
|
+
except (TypeError, ValueError):
|
|
254
|
+
return None
|
|
255
|
+
return out
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _version(x: Any) -> tuple[int, int, int] | None:
|
|
259
|
+
parts = _s(x).split(".")
|
|
260
|
+
if len(parts) != 3 or not all(p.isdigit() for p in parts):
|
|
261
|
+
return None
|
|
262
|
+
return int(parts[0]), int(parts[1]), int(parts[2])
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _err(e: BaseException) -> str:
|
|
266
|
+
return _text(f"{type(e).__name__}: {e}")
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def _finite_or_none(x: float) -> float | None:
|
|
270
|
+
return x if math.isfinite(x) else None
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
# -- public API -------------------------------------------------------------------------------
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def build_view(fp: Fingerprint, *, load_warnings: Sequence[str] = ()) -> v.ReportView:
|
|
277
|
+
"""The view of a loaded fingerprint. Never opens the sealed targets."""
|
|
278
|
+
problems: list[v.Unread] = []
|
|
279
|
+
|
|
280
|
+
def take(where: str, fn: Callable[[], Any], default: Any) -> Any:
|
|
281
|
+
try:
|
|
282
|
+
return fn()
|
|
283
|
+
except Exception as e:
|
|
284
|
+
problems.append(v.Unread(where=where, what="could not be read", reason=_err(e)))
|
|
285
|
+
return default
|
|
286
|
+
|
|
287
|
+
manifest = take("manifest", lambda: fp.manifest.model_dump(mode="json"), {})
|
|
288
|
+
arrays = take("arrays", lambda: fp.arrays.as_dict(), {})
|
|
289
|
+
diagnostics = take("diagnostics", lambda: dict(fp.diagnostics), {})
|
|
290
|
+
calibration = take("targets.calibration",
|
|
291
|
+
lambda: [t.model_dump(mode="json") for t in fp.calibration.targets], [])
|
|
292
|
+
content_id = take("content_id", lambda: str(fp.content_hash())[:12], "")
|
|
293
|
+
out = view_from_parts(manifest, arrays, diagnostics=diagnostics, calibration=calibration,
|
|
294
|
+
content_id=content_id, load_warnings=load_warnings)
|
|
295
|
+
out.unread[:0] = problems
|
|
296
|
+
return out
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def load_view(path: str | os.PathLike[str]) -> v.ReportView:
|
|
300
|
+
"""Load a ``.dfp`` and build its view. The warnings the engine gives while loading (fields
|
|
301
|
+
of a newer minor format it ignored) become unread records; errors propagate."""
|
|
302
|
+
from ectype.fingerprint.core import Fingerprint
|
|
303
|
+
|
|
304
|
+
with warnings.catch_warnings(record=True) as caught:
|
|
305
|
+
warnings.simplefilter("always")
|
|
306
|
+
fp = Fingerprint.load(path)
|
|
307
|
+
texts = [str(w.message) for w in caught if issubclass(w.category, UserWarning)]
|
|
308
|
+
return build_view(fp, load_warnings=texts)
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def view_from_parts(manifest: Any, arrays: Mapping[str, Any] | None = None, *,
|
|
312
|
+
diagnostics: Mapping[str, Any] | None = None,
|
|
313
|
+
calibration: Sequence[Mapping[str, Any]] | None = None,
|
|
314
|
+
content_id: str = "", load_warnings: Sequence[str] = ()) -> v.ReportView:
|
|
315
|
+
"""The view of a fingerprint given as JSON-shaped parts. Never raises."""
|
|
316
|
+
try:
|
|
317
|
+
b = _Builder(manifest, arrays, diagnostics, calibration, content_id, load_warnings)
|
|
318
|
+
b.build()
|
|
319
|
+
out = b.view
|
|
320
|
+
except Exception as e: # pragma: no cover - every section has its own guard
|
|
321
|
+
out = v.ReportView(unread=[v.Unread(where="manifest", what="could not be read",
|
|
322
|
+
reason=_err(e))])
|
|
323
|
+
try:
|
|
324
|
+
_scrub(out)
|
|
325
|
+
except Exception: # pragma: no cover
|
|
326
|
+
pass
|
|
327
|
+
return out
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
# -- the builder ------------------------------------------------------------------------------
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
class _Builder:
|
|
334
|
+
def __init__(self, manifest: Any, arrays: Any, diagnostics: Any, calibration: Any,
|
|
335
|
+
content_id: Any, load_warnings: Any) -> None:
|
|
336
|
+
self.view = v.ReportView()
|
|
337
|
+
self.raw = manifest
|
|
338
|
+
self.m: Mapping[str, Any] = _d(manifest)
|
|
339
|
+
self.arrays: Mapping[str, Any] = _d(arrays)
|
|
340
|
+
self.cdiag: Mapping[str, Any] = _d(diagnostics)
|
|
341
|
+
self.calibration: list[Any] = _l(calibration)
|
|
342
|
+
self.content_id = _s(content_id)
|
|
343
|
+
self.load_warnings = [_s(w, repr(w)) for w in _l(load_warnings)] \
|
|
344
|
+
if not isinstance(load_warnings, str) else [load_warnings]
|
|
345
|
+
self.model: Mapping[str, Any] = {}
|
|
346
|
+
self.marginals: Mapping[str, Any] = {}
|
|
347
|
+
self.columns: list[Mapping[str, Any]] = []
|
|
348
|
+
self.by_name: dict[str, Mapping[str, Any]] = {}
|
|
349
|
+
self.mdiag: Mapping[str, Any] = {}
|
|
350
|
+
self.policy: Mapping[str, Any] = {}
|
|
351
|
+
self.pooled: Mapping[str, Any] = {}
|
|
352
|
+
self.derived: dict[str, Mapping[str, Any]] = {}
|
|
353
|
+
self.differences: dict[str, tuple[int, Mapping[str, Any]]] = {}
|
|
354
|
+
self.identities: dict[str, tuple[int, Mapping[str, Any]]] = {}
|
|
355
|
+
self.split_parts: dict[str, tuple[Mapping[str, Any], int]] = {}
|
|
356
|
+
self.sum_totals: dict[str, Mapping[str, Any]] = {}
|
|
357
|
+
self.fn_applied: dict[str, Mapping[str, Any]] = {}
|
|
358
|
+
self.pseudonyms: Mapping[str, Any] = {}
|
|
359
|
+
self.unread = self.view.unread
|
|
360
|
+
self._models: dict[str, Any] = {}
|
|
361
|
+
|
|
362
|
+
# -- guards -------------------------------------------------------------------------------
|
|
363
|
+
def guard(self, where: str, fn: Callable[[], Any], column: str | None = None) -> Any:
|
|
364
|
+
try:
|
|
365
|
+
return fn()
|
|
366
|
+
except Exception as e:
|
|
367
|
+
self.unread.append(v.Unread(where=where, what="could not be read", reason=_err(e),
|
|
368
|
+
column=column))
|
|
369
|
+
return None
|
|
370
|
+
|
|
371
|
+
def expect_dict(self, where: str, value: Any) -> Mapping[str, Any]:
|
|
372
|
+
if value is None or isinstance(value, Mapping):
|
|
373
|
+
return _d(value)
|
|
374
|
+
self.unread.append(v.Unread(where=where, what="unexpected value",
|
|
375
|
+
reason=f"expected an object, found {_kind_of(value)}",
|
|
376
|
+
entries=_entries(value)))
|
|
377
|
+
return {}
|
|
378
|
+
|
|
379
|
+
def expect_list(self, where: str, value: Any) -> list[Any]:
|
|
380
|
+
if value is None or isinstance(value, (list, tuple)):
|
|
381
|
+
return _l(value)
|
|
382
|
+
self.unread.append(v.Unread(where=where, what="unexpected value",
|
|
383
|
+
reason=f"expected a list, found {_kind_of(value)}",
|
|
384
|
+
entries=_entries(value)))
|
|
385
|
+
return []
|
|
386
|
+
|
|
387
|
+
def unknown_keys(self, level: str, where: str, obj: Any,
|
|
388
|
+
sink: list[v.Unread] | None = None, column: str | None = None) -> None:
|
|
389
|
+
if not isinstance(obj, Mapping):
|
|
390
|
+
return
|
|
391
|
+
known = KNOWN_KEYS[level]
|
|
392
|
+
for key in obj:
|
|
393
|
+
if key in known:
|
|
394
|
+
continue
|
|
395
|
+
name = _s(key, repr(key))
|
|
396
|
+
(self.unread if sink is None else sink).append(v.Unread(
|
|
397
|
+
where=f"{where}.{name}" if where else name, what="unknown section",
|
|
398
|
+
entries=_entries(obj[key]), column=column))
|
|
399
|
+
|
|
400
|
+
# -- whole --------------------------------------------------------------------------------
|
|
401
|
+
def build(self) -> None:
|
|
402
|
+
if not isinstance(self.raw, Mapping):
|
|
403
|
+
self.unread.append(v.Unread(where="manifest", what="unexpected value",
|
|
404
|
+
reason=f"expected an object, found "
|
|
405
|
+
f"{_kind_of(self.raw)}",
|
|
406
|
+
entries=_entries(self.raw)))
|
|
407
|
+
for text in self.load_warnings:
|
|
408
|
+
self.unread.append(v.Unread(where="manifest",
|
|
409
|
+
what="fields ignored by the engine while loading",
|
|
410
|
+
reason=_text(text)))
|
|
411
|
+
self.guard("manifest", self.index)
|
|
412
|
+
self.guard("manifest", self.read_unknown_sections)
|
|
413
|
+
self.guard("overview", self.read_overview)
|
|
414
|
+
self.guard("columns", self.read_columns)
|
|
415
|
+
self.guard("relationships", self.read_relationships)
|
|
416
|
+
self.guard("structure", self.read_structure)
|
|
417
|
+
self.guard("privacy", self.read_privacy)
|
|
418
|
+
|
|
419
|
+
def index(self) -> None:
|
|
420
|
+
m = self.m
|
|
421
|
+
self.model = self.expect_dict("model", _get(m, "model"))
|
|
422
|
+
self.marginals = self.expect_dict("model.marginals", _get(self.model, "marginals"))
|
|
423
|
+
cols = self.expect_list("columns", _get(m, "columns"))
|
|
424
|
+
for i, c in enumerate(cols):
|
|
425
|
+
if isinstance(c, Mapping):
|
|
426
|
+
self.columns.append(c)
|
|
427
|
+
else:
|
|
428
|
+
self.unread.append(v.Unread(where=f"columns[{i}]", what="unexpected value",
|
|
429
|
+
reason=f"expected an object, found {_kind_of(c)}",
|
|
430
|
+
entries=_entries(c)))
|
|
431
|
+
for c in self.columns:
|
|
432
|
+
name = _s(_get(c, "name"))
|
|
433
|
+
if name and name not in self.by_name:
|
|
434
|
+
self.by_name[name] = c
|
|
435
|
+
self.mdiag = self.expect_dict("diagnostics", _get(m, "diagnostics"))
|
|
436
|
+
self.policy = self.expect_dict("disclosure_policy", _get(m, "disclosure_policy"))
|
|
437
|
+
dd = self.expect_dict("disclosure_diagnostics", _get(m, "disclosure_diagnostics"))
|
|
438
|
+
self.pooled = _d(_get(dd, "pooled_categories"))
|
|
439
|
+
self.pseudonyms = _d(_get(self.cdiag, "pseudonymised_columns"))
|
|
440
|
+
for d in _l(_get(self.model, "derived")):
|
|
441
|
+
col = _s(_get(d, "column"))
|
|
442
|
+
if col and col not in self.derived:
|
|
443
|
+
self.derived[col] = _d(d)
|
|
444
|
+
for i, t in enumerate(_l(_get(self.model, "transforms"))):
|
|
445
|
+
kind, target = _s(_get(t, "kind")), _s(_get(t, "target"))
|
|
446
|
+
if not target:
|
|
447
|
+
continue
|
|
448
|
+
if kind == "identity":
|
|
449
|
+
self.identities.setdefault(target, (i, _d(t)))
|
|
450
|
+
elif kind == "difference" or kind not in TRANSFORM_KINDS:
|
|
451
|
+
self.differences.setdefault(target, (i, _d(t)))
|
|
452
|
+
for s in _l(_get(self.model, "sums")):
|
|
453
|
+
mode = _s(_get(s, "mode"))
|
|
454
|
+
parts = _strs(_get(s, "parts"))
|
|
455
|
+
if mode == "split":
|
|
456
|
+
for j, p in enumerate(parts):
|
|
457
|
+
self.split_parts.setdefault(p, (_d(s), j))
|
|
458
|
+
elif mode == "sum":
|
|
459
|
+
total = _s(_get(s, "total"))
|
|
460
|
+
if total:
|
|
461
|
+
self.sum_totals.setdefault(total, _d(s))
|
|
462
|
+
for rec in _l(_get(_d(_get(self.mdiag, "functions")), "applied")):
|
|
463
|
+
col = _s(_get(rec, "column"))
|
|
464
|
+
if col:
|
|
465
|
+
self.fn_applied.setdefault(col, _d(rec))
|
|
466
|
+
|
|
467
|
+
def read_unknown_sections(self) -> None:
|
|
468
|
+
m = self.m
|
|
469
|
+
self.unknown_keys("manifest", "", m)
|
|
470
|
+
for level, key in (("dataset", "dataset"), ("disclosure_diagnostics",
|
|
471
|
+
"disclosure_diagnostics"),
|
|
472
|
+
("model", "model"), ("constraints", "constraints"),
|
|
473
|
+
("provenance", "provenance"), ("diagnostics", "diagnostics")):
|
|
474
|
+
self.unknown_keys(level, key, _get(m, key))
|
|
475
|
+
self.unknown_keys("container_diagnostics", "fingerprint diagnostics", self.cdiag)
|
|
476
|
+
ext = _get(m, "extensions")
|
|
477
|
+
if isinstance(ext, Mapping) and ext:
|
|
478
|
+
self.view.extra_sections.append("extensions")
|
|
479
|
+
elif ext not in (None, {}) and not isinstance(ext, Mapping):
|
|
480
|
+
self.unread.append(v.Unread(where="extensions", what="unexpected value",
|
|
481
|
+
reason=f"expected an object, found {_kind_of(ext)}"))
|
|
482
|
+
for name in _EXTRA_SECTIONS:
|
|
483
|
+
if _get(m, name) is not None:
|
|
484
|
+
self.view.extra_sections.append(name)
|
|
485
|
+
|
|
486
|
+
# -- overview -----------------------------------------------------------------------------
|
|
487
|
+
def read_overview(self) -> None:
|
|
488
|
+
from ectype._version import FORMAT_VERSION, __version__
|
|
489
|
+
|
|
490
|
+
m, o = self.m, self.view.overview
|
|
491
|
+
ds = self.expect_dict("dataset", _get(m, "dataset"))
|
|
492
|
+
prov = self.expect_dict("provenance", _get(m, "provenance"))
|
|
493
|
+
targets = _d(_get(m, "targets"))
|
|
494
|
+
o.name = _text(_get(ds, "name"))
|
|
495
|
+
o.description = _text(_get(ds, "description"))
|
|
496
|
+
o.rows = _int(_get(ds, "source_records"))
|
|
497
|
+
o.columns = _int(_get(ds, "source_columns"))
|
|
498
|
+
o.format_version = _s(_get(m, "fingerprint_version"))
|
|
499
|
+
o.engine_version = _s(_get(prov, "engine_version"))
|
|
500
|
+
o.created = _s(_get(prov, "created_at"))
|
|
501
|
+
o.content_id = self.content_id
|
|
502
|
+
o.policy = _s(_get(self.policy, "profile"))
|
|
503
|
+
o.fit_seed = _int(_get(prov, "fit_seed"))
|
|
504
|
+
for op in _l(_get(prov, "lineage"))[:MAX_NOTES * 4]:
|
|
505
|
+
o.lineage.append(_lineage_text(op))
|
|
506
|
+
o.targets_calibration = _int(_get(targets, "n_calibration"))
|
|
507
|
+
o.targets_sealed = _int(_get(targets, "n_sealed"))
|
|
508
|
+
o.reader_format = FORMAT_VERSION
|
|
509
|
+
o.reader_engine = __version__
|
|
510
|
+
mine, theirs = _version(FORMAT_VERSION), _version(o.format_version)
|
|
511
|
+
if mine is not None and theirs is not None:
|
|
512
|
+
o.older_format = theirs < mine
|
|
513
|
+
o.newer_format = theirs > mine
|
|
514
|
+
|
|
515
|
+
# -- columns ------------------------------------------------------------------------------
|
|
516
|
+
def read_columns(self) -> None:
|
|
517
|
+
cols = _l(_get(self.m, "columns"))
|
|
518
|
+
known = {id(c) for c in self.columns}
|
|
519
|
+
for i, c in enumerate(cols):
|
|
520
|
+
if id(c) not in known:
|
|
521
|
+
continue
|
|
522
|
+
name = _s(_get(c, "name"))
|
|
523
|
+
cv = v.ColumnView(name=name, index=i)
|
|
524
|
+
self.view.columns.append(cv)
|
|
525
|
+
try:
|
|
526
|
+
self.read_column(cv, c)
|
|
527
|
+
except Exception as e:
|
|
528
|
+
cv.unread.append(v.Unread(where=f"columns.{name or i}",
|
|
529
|
+
what="could not be read", reason=_err(e),
|
|
530
|
+
column=name or None))
|
|
531
|
+
listed = set(self.by_name)
|
|
532
|
+
hidden = {lat for _, t in self.differences.values()
|
|
533
|
+
for lat in [_s(_get(_d(_get(t, "params")), "latent"))] if lat}
|
|
534
|
+
for s in _l(_get(self.model, "sums")):
|
|
535
|
+
hidden.update(_strs(_get(s, "latents")))
|
|
536
|
+
for key in self.marginals:
|
|
537
|
+
name = _s(key, repr(key))
|
|
538
|
+
if name not in listed and name not in hidden:
|
|
539
|
+
self.unread.append(v.Unread(where=f"model.marginals.{name}",
|
|
540
|
+
what="model of a column the manifest does not list",
|
|
541
|
+
column=name))
|
|
542
|
+
|
|
543
|
+
def read_column(self, cv: v.ColumnView, c: Mapping[str, Any]) -> None:
|
|
544
|
+
name = cv.name
|
|
545
|
+
where = f"columns.{name or cv.index}"
|
|
546
|
+
self.unknown_keys("column", where, c, sink=cv.unread, column=name or None)
|
|
547
|
+
cv.logical_type = _s(_get(c, "logical_type"))
|
|
548
|
+
cv.role = _s(_get(c, "role"))
|
|
549
|
+
cv.dtype = _s(_get(c, "physical_dtype"))
|
|
550
|
+
cv.missing = _num(_get(c, "null_fraction"))
|
|
551
|
+
cv.distinct = _int(_get(c, "n_unique"))
|
|
552
|
+
cv.low = _num(_get(c, "min_value"))
|
|
553
|
+
cv.high = _num(_get(c, "max_value"))
|
|
554
|
+
cv.unit = _s(_get(c, "datetime_unit"))
|
|
555
|
+
cv.is_date = _get(c, "is_date") is True
|
|
556
|
+
cv.integer = _get(c, "integer_valued") is True
|
|
557
|
+
cv.decimals = _int(_get(c, "decimals"))
|
|
558
|
+
cv.pattern = _os(_get(c, "pattern"))
|
|
559
|
+
cv.confidence = _num(_get(c, "confidence"))
|
|
560
|
+
cv.overridden = _get(c, "overridden") is True
|
|
561
|
+
notes = _strs(_get(c, "notes"))
|
|
562
|
+
cv.notes = [_text(n) for n in notes[:MAX_NOTES]]
|
|
563
|
+
cv.personal = any(n.startswith(PERSONAL_NOTE) for n in notes)
|
|
564
|
+
if cv.logical_type not in LOGICAL_TYPES:
|
|
565
|
+
cv.unread.append(v.Unread(where=f"{where}.logical_type",
|
|
566
|
+
what=f"unknown logical type '{cv.logical_type}'",
|
|
567
|
+
column=name))
|
|
568
|
+
enc = _d(_get(_d(_get(self.model, "encodings")), name))
|
|
569
|
+
cond = _get(_d(_get(enc, "params")), "conditional")
|
|
570
|
+
cv.conditional_on = _os(_get(cond, "parent"))
|
|
571
|
+
|
|
572
|
+
spec = _get(self.marginals, name)
|
|
573
|
+
if spec is not None and not isinstance(spec, Mapping):
|
|
574
|
+
cv.unread.append(v.Unread(where=f"model.marginals.{name}", what="unexpected value",
|
|
575
|
+
reason=f"expected an object, found {_kind_of(spec)}",
|
|
576
|
+
column=name))
|
|
577
|
+
spec = None
|
|
578
|
+
if spec is not None:
|
|
579
|
+
cv.model_kind = _s(_get(spec, "kind")) or None
|
|
580
|
+
slab = _get(_d(_get(spec, "params")), "slab")
|
|
581
|
+
cv.slab_kind = _os(_get(slab, "kind"))
|
|
582
|
+
|
|
583
|
+
role = cv.role
|
|
584
|
+
handling = ROLE_HANDLING.get(role)
|
|
585
|
+
if handling is None:
|
|
586
|
+
cv.unread.append(v.Unread(where=f"{where}.role", what=f"unknown role '{role}'",
|
|
587
|
+
column=name))
|
|
588
|
+
if role == "identifier":
|
|
589
|
+
cv.handling = "identifier"
|
|
590
|
+
return
|
|
591
|
+
if role == "constant":
|
|
592
|
+
cv.handling = "constant"
|
|
593
|
+
consts = _d(_get(self.model, "constants"))
|
|
594
|
+
cv.constant = _value_text(consts.get(name)) if name in consts else None
|
|
595
|
+
return
|
|
596
|
+
if role == "excluded":
|
|
597
|
+
cv.handling = "excluded"
|
|
598
|
+
return
|
|
599
|
+
if role == "pseudonym":
|
|
600
|
+
cv.handling = "pseudonym"
|
|
601
|
+
cv.stand_in_style = _os(_get(_get(self.pseudonyms, name), "token_style"))
|
|
602
|
+
self.draw(cv, spec, f"model.marginals.{name}")
|
|
603
|
+
if cv.levels is not None:
|
|
604
|
+
cv.levels.stand_ins = True
|
|
605
|
+
return
|
|
606
|
+
if role == "reference":
|
|
607
|
+
cv.handling = "reference"
|
|
608
|
+
self.draw(cv, spec, f"model.marginals.{name}")
|
|
609
|
+
if cv.histogram is not None or cv.levels is not None:
|
|
610
|
+
cv.chart_of = "group sizes"
|
|
611
|
+
return
|
|
612
|
+
if name in self.derived:
|
|
613
|
+
d = self.derived[name]
|
|
614
|
+
cv.handling = "computed"
|
|
615
|
+
cv.formula = _text(_get(d, "expression"))
|
|
616
|
+
cv.inputs = self.derived_inputs(name, _s(_get(d, "expression")))
|
|
617
|
+
return
|
|
618
|
+
if name in self.differences:
|
|
619
|
+
i, t = self.differences[name]
|
|
620
|
+
self.offset(cv, i, t)
|
|
621
|
+
return
|
|
622
|
+
if name in self.identities:
|
|
623
|
+
i, t = self.identities[name]
|
|
624
|
+
cv.handling = "computed"
|
|
625
|
+
inputs = _strs(_get(t, "inputs"))
|
|
626
|
+
cv.inputs = inputs
|
|
627
|
+
cv.formula = _text(_identity_text(name, inputs, _d(_get(t, "params"))))
|
|
628
|
+
return
|
|
629
|
+
if name in self.split_parts:
|
|
630
|
+
s, j = self.split_parts[name]
|
|
631
|
+
self.share(cv, s, j)
|
|
632
|
+
return
|
|
633
|
+
if name in self.sum_totals:
|
|
634
|
+
s = self.sum_totals[name]
|
|
635
|
+
cv.handling = "total"
|
|
636
|
+
cv.inputs = _strs(_get(s, "parts"))
|
|
637
|
+
cv.formula = _text(_sum_text(s))
|
|
638
|
+
return
|
|
639
|
+
if spec is not None:
|
|
640
|
+
cv.handling = "modeled" if handling is not None else "unknown"
|
|
641
|
+
self.draw(cv, spec, f"model.marginals.{name}")
|
|
642
|
+
return
|
|
643
|
+
cv.handling = "unknown"
|
|
644
|
+
if handling is not None:
|
|
645
|
+
cv.unread.append(v.Unread(where=f"columns.{name}",
|
|
646
|
+
what="column with no model and no known arrangement",
|
|
647
|
+
column=name))
|
|
648
|
+
|
|
649
|
+
def derived_inputs(self, name: str, expression: str) -> list[str]:
|
|
650
|
+
rec = self.fn_applied.get(name)
|
|
651
|
+
found = _columns_in(expression, self.by_name)
|
|
652
|
+
base = _s(_get(rec, "base")) if rec is not None else ""
|
|
653
|
+
if base and (base in found or not found):
|
|
654
|
+
return [base, *[f for f in found if f != base]]
|
|
655
|
+
return found
|
|
656
|
+
|
|
657
|
+
def offset(self, cv: v.ColumnView, i: int, t: Mapping[str, Any]) -> None:
|
|
658
|
+
name = cv.name
|
|
659
|
+
kind = _s(_get(t, "kind"))
|
|
660
|
+
params = _d(_get(t, "params"))
|
|
661
|
+
inputs = _strs(_get(t, "inputs"))
|
|
662
|
+
cv.inputs = inputs
|
|
663
|
+
if kind != "difference":
|
|
664
|
+
cv.handling = "unknown"
|
|
665
|
+
cv.formula = _text(f"{name} = {kind}({', '.join(inputs)})")
|
|
666
|
+
return # the unread record is written with the structure (read_transforms)
|
|
667
|
+
cv.handling = "offset"
|
|
668
|
+
sign = _int(_get(params, "sign"))
|
|
669
|
+
cv.gap_sign = -1 if sign == -1 else 1
|
|
670
|
+
base = inputs[0] if inputs else "?"
|
|
671
|
+
cv.formula = _text(f"{name} = {base} {'-' if cv.gap_sign < 0 else '+'} gap")
|
|
672
|
+
latent = _s(_get(params, "latent"))
|
|
673
|
+
spec = _get(self.marginals, latent) if latent else None
|
|
674
|
+
hist = self.gap_histogram(t, f"model.marginals.{latent}", cv)
|
|
675
|
+
if hist is not None:
|
|
676
|
+
cv.histogram = hist
|
|
677
|
+
cv.chart_of = "gap"
|
|
678
|
+
elif spec is None:
|
|
679
|
+
cv.chart_note = "No chart: the model of the gap is not in the fingerprint."
|
|
680
|
+
else:
|
|
681
|
+
cv.chart_note = "No chart: the model of the gap could not be drawn."
|
|
682
|
+
if isinstance(spec, Mapping):
|
|
683
|
+
cv.model_kind = _s(_get(spec, "kind")) or None
|
|
684
|
+
cv.slab_kind = _os(_get(_get(_d(_get(spec, "params")), "slab"), "kind"))
|
|
685
|
+
|
|
686
|
+
def gap_histogram(self, t: Mapping[str, Any], where: str,
|
|
687
|
+
cv: v.ColumnView | None) -> v.Histogram | None:
|
|
688
|
+
params = _d(_get(t, "params"))
|
|
689
|
+
latent = _s(_get(params, "latent"))
|
|
690
|
+
spec = _get(self.marginals, latent) if latent else None
|
|
691
|
+
if not isinstance(spec, Mapping):
|
|
692
|
+
return None
|
|
693
|
+
target = self.by_name.get(_s(_get(t, "target")), {})
|
|
694
|
+
is_time = _s(_get(target, "logical_type")) == "datetime"
|
|
695
|
+
axis = "duration" if is_time else "number"
|
|
696
|
+
unit = _s(_get(params, "unit")) if is_time else ""
|
|
697
|
+
integer = _s(_get(params, "latent_type")) == "discrete"
|
|
698
|
+
dec = _int(_get(params, "decimals"))
|
|
699
|
+
sink = cv.unread if cv is not None else self.unread
|
|
700
|
+
drawn = self.distribution(spec, where, sink, cv.name if cv else None, axis=axis,
|
|
701
|
+
unit=unit, integer=integer, decimals=dec, column=None,
|
|
702
|
+
allow_levels=False)
|
|
703
|
+
if isinstance(drawn, v.Histogram):
|
|
704
|
+
return drawn
|
|
705
|
+
return None
|
|
706
|
+
|
|
707
|
+
def share(self, cv: v.ColumnView, s: Mapping[str, Any], j: int) -> None:
|
|
708
|
+
cv.handling = "share"
|
|
709
|
+
total = _s(_get(s, "total"))
|
|
710
|
+
total_text = total or _s(_get(s, "constant"), "?")
|
|
711
|
+
cv.inputs = [total] if total else []
|
|
712
|
+
parts = _strs(_get(s, "parts"))
|
|
713
|
+
latents = _strs(_get(s, "latents"))
|
|
714
|
+
latent = latents[j] if j < len(latents) else ""
|
|
715
|
+
spec = _get(self.marginals, latent) if latent else None
|
|
716
|
+
if isinstance(spec, Mapping):
|
|
717
|
+
cv.model_kind = _s(_get(spec, "kind")) or None
|
|
718
|
+
cv.formula = _text(f"{cv.name} = {total_text} × its modeled share")
|
|
719
|
+
drawn = self.distribution(spec, f"model.marginals.{latent}", cv.unread, cv.name,
|
|
720
|
+
axis="share", unit="", integer=False, decimals=None,
|
|
721
|
+
column=None, allow_levels=False)
|
|
722
|
+
if isinstance(drawn, v.Histogram):
|
|
723
|
+
cv.histogram = drawn
|
|
724
|
+
cv.chart_of = "share"
|
|
725
|
+
else:
|
|
726
|
+
cv.chart_note = "No chart: the model of the share could not be drawn."
|
|
727
|
+
return
|
|
728
|
+
if len(parts) <= 1:
|
|
729
|
+
cv.formula = _text(f"{cv.name} = {total_text}")
|
|
730
|
+
else:
|
|
731
|
+
others = [p for p in parts if p != cv.name]
|
|
732
|
+
cv.formula = _text(f"{cv.name} = {total_text} - " + " - ".join(others))
|
|
733
|
+
|
|
734
|
+
# -- distributions ------------------------------------------------------------------------
|
|
735
|
+
def draw(self, cv: v.ColumnView, spec: Any, where: str) -> None:
|
|
736
|
+
if not isinstance(spec, Mapping):
|
|
737
|
+
cv.chart_note = "No chart: the fingerprint holds no model of this column."
|
|
738
|
+
if cv.handling in ("modeled", "pseudonym", "reference"):
|
|
739
|
+
cv.unread.append(v.Unread(where=where, what="no model for a modeled column",
|
|
740
|
+
column=cv.name))
|
|
741
|
+
return
|
|
742
|
+
is_time = cv.logical_type == "datetime"
|
|
743
|
+
drawn = self.distribution(
|
|
744
|
+
spec, where, cv.unread, cv.name, axis="date" if is_time else "number",
|
|
745
|
+
unit=cv.unit if is_time else "", integer=cv.integer or cv.logical_type == "discrete"
|
|
746
|
+
or cv.is_date, decimals=cv.decimals, column=cv, allow_levels=True)
|
|
747
|
+
if isinstance(drawn, v.Histogram):
|
|
748
|
+
cv.histogram = drawn
|
|
749
|
+
elif isinstance(drawn, v.Levels):
|
|
750
|
+
cv.levels = drawn
|
|
751
|
+
if cv.name in self.pooled:
|
|
752
|
+
drawn.n_pooled = _int(self.pooled.get(cv.name))
|
|
753
|
+
elif isinstance(drawn, str):
|
|
754
|
+
cv.chart_note = drawn
|
|
755
|
+
|
|
756
|
+
def distribution(self, spec: Mapping[str, Any], where: str, sink: list[v.Unread],
|
|
757
|
+
column_name: str | None, *, axis: str, unit: str, integer: bool,
|
|
758
|
+
decimals: int | None, column: v.ColumnView | None,
|
|
759
|
+
allow_levels: bool) -> v.Histogram | v.Levels | str | None:
|
|
760
|
+
"""A histogram or levels for one model spec, or a sentence saying why there is none.
|
|
761
|
+
|
|
762
|
+
Notes (``chart_note``) set by a fallback are written to ``column`` when given."""
|
|
763
|
+
kind = _s(_get(spec, "kind"))
|
|
764
|
+
params = _d(_get(spec, "params"))
|
|
765
|
+
refs = _d(_get(spec, "arrays"))
|
|
766
|
+
model = None
|
|
767
|
+
error: BaseException | None = None
|
|
768
|
+
known = self.kind_known(kind)
|
|
769
|
+
if known is False:
|
|
770
|
+
sink.append(v.Unread(where=where, what=f"unknown model kind '{kind}'",
|
|
771
|
+
column=column_name))
|
|
772
|
+
model, grid, error, key = self.evaluate(kind, params, refs)
|
|
773
|
+
if model is not None and error is None:
|
|
774
|
+
chart_key = None if key is None else repr((
|
|
775
|
+
key, axis, unit, integer, decimals, allow_levels,
|
|
776
|
+
None if column is None else (column.low, column.high, column.integer),
|
|
777
|
+
_get(self.policy, "tail_clip"), _get(self.pooled, column_name or "")))
|
|
778
|
+
if chart_key is not None and chart_key in _CHART_CACHE:
|
|
779
|
+
return _copy_chart(_CHART_CACHE[chart_key])
|
|
780
|
+
try:
|
|
781
|
+
labels = getattr(model, "labels", None)
|
|
782
|
+
probs = getattr(model, "probs", None)
|
|
783
|
+
chart: v.Histogram | v.Levels
|
|
784
|
+
if labels is not None and probs is not None:
|
|
785
|
+
chart = self.levels_from(labels, probs, column_name)
|
|
786
|
+
elif grid is None:
|
|
787
|
+
raise ValueError("the model has no quantile function")
|
|
788
|
+
else:
|
|
789
|
+
chart = self.chart_from_grid(grid, model, kind, axis=axis, unit=unit,
|
|
790
|
+
integer=integer, decimals=decimals,
|
|
791
|
+
column=column, allow_levels=allow_levels)
|
|
792
|
+
if chart_key is not None:
|
|
793
|
+
_CHART_CACHE[chart_key] = _copy_chart(chart)
|
|
794
|
+
while len(_CHART_CACHE) > _EVAL_CACHE_SIZE:
|
|
795
|
+
_CHART_CACHE.popitem(last=False)
|
|
796
|
+
return chart
|
|
797
|
+
except Exception as e:
|
|
798
|
+
error = e
|
|
799
|
+
if known is not False and error is not None:
|
|
800
|
+
sink.append(v.Unread(where=where, what=f"model '{kind}' could not be evaluated",
|
|
801
|
+
reason=_err(error), column=column_name))
|
|
802
|
+
# fallback: the two array shapes every stored-distribution model has used so far
|
|
803
|
+
why = (f"the model kind '{kind}' is not known to this version" if known is False
|
|
804
|
+
else f"the engine could not evaluate its model ('{kind}')")
|
|
805
|
+
for qn, ln in (("quantiles", "levels"), ("slab.quantiles", "slab.levels")):
|
|
806
|
+
q = _num_array(self.arrays, _get(refs, qn))
|
|
807
|
+
lv = _num_array(self.arrays, _get(refs, ln))
|
|
808
|
+
if q is not None and lv is not None and q.size >= 2 and q.size == lv.size:
|
|
809
|
+
ok = np.isfinite(q) & np.isfinite(lv)
|
|
810
|
+
q, lv = q[ok], lv[ok]
|
|
811
|
+
if q.size >= 2 and np.all(np.diff(lv) >= 0) and np.all(np.diff(q) >= 0):
|
|
812
|
+
u = (np.arange(GRID) + 0.5) / GRID
|
|
813
|
+
grid = np.interp(u, lv, q)
|
|
814
|
+
out = self.chart_from_grid(grid, None, kind, axis=axis, unit=unit,
|
|
815
|
+
integer=integer, decimals=decimals,
|
|
816
|
+
column=column, allow_levels=allow_levels)
|
|
817
|
+
note = (f"Drawn from the stored quantiles because {why}; the shape between "
|
|
818
|
+
f"them is interpolated.")
|
|
819
|
+
if column is not None:
|
|
820
|
+
column.chart_note = note
|
|
821
|
+
return out
|
|
822
|
+
labels = _array(self.arrays, _get(refs, "labels"))
|
|
823
|
+
probs = _num_array(self.arrays, _get(refs, "probs"))
|
|
824
|
+
if labels is not None and probs is not None and labels.size == probs.size > 0:
|
|
825
|
+
out_l = self.levels_from(labels, probs, column_name)
|
|
826
|
+
if column is not None:
|
|
827
|
+
column.chart_note = f"Drawn from the stored frequencies because {why}."
|
|
828
|
+
return out_l
|
|
829
|
+
return f"No chart: {why}, and it holds no stored quantiles or frequencies."
|
|
830
|
+
|
|
831
|
+
def kind_known(self, kind: str) -> bool | None:
|
|
832
|
+
try:
|
|
833
|
+
from ectype.models.base import MARGINALS
|
|
834
|
+
except Exception: # pragma: no cover
|
|
835
|
+
return None
|
|
836
|
+
_register_kinds()
|
|
837
|
+
return kind in MARGINALS
|
|
838
|
+
|
|
839
|
+
def evaluate(self, kind: str, params: Mapping[str, Any], refs: Mapping[str, Any]
|
|
840
|
+
) -> tuple[Any, np.ndarray | None, BaseException | None, str | None]:
|
|
841
|
+
"""The engine's model of a spec and its quantile grid (``None`` for a model with
|
|
842
|
+
labels), or the error that stopped either, and the spec's content key. Cached by
|
|
843
|
+
that key."""
|
|
844
|
+
key = _spec_key(kind, params, refs, self.arrays)
|
|
845
|
+
if key is not None and key in _EVAL_CACHE:
|
|
846
|
+
_EVAL_CACHE.move_to_end(key)
|
|
847
|
+
return (*_EVAL_CACHE[key], key)
|
|
848
|
+
model: Any = None
|
|
849
|
+
grid: np.ndarray | None = None
|
|
850
|
+
error: BaseException | None = None
|
|
851
|
+
try:
|
|
852
|
+
model = self.build_model(kind, params, refs)
|
|
853
|
+
if getattr(model, "labels", None) is None:
|
|
854
|
+
grid = self.grid_of(model)
|
|
855
|
+
except Exception as e:
|
|
856
|
+
error = e
|
|
857
|
+
if key is not None:
|
|
858
|
+
_EVAL_CACHE[key] = (model, grid, error)
|
|
859
|
+
while len(_EVAL_CACHE) > _EVAL_CACHE_SIZE:
|
|
860
|
+
_EVAL_CACHE.popitem(last=False)
|
|
861
|
+
return model, grid, error, key
|
|
862
|
+
|
|
863
|
+
def build_model(self, kind: str, params: Mapping[str, Any], refs: Mapping[str, Any]
|
|
864
|
+
) -> Any:
|
|
865
|
+
from ectype.fingerprint.core import ArrayStore
|
|
866
|
+
from ectype.fingerprint.schema import ModelSpec
|
|
867
|
+
from ectype.models.base import marginal_from_spec
|
|
868
|
+
|
|
869
|
+
_register_kinds()
|
|
870
|
+
spec = ModelSpec(kind=kind, params=dict(params),
|
|
871
|
+
arrays={str(k): str(r) for k, r in refs.items()})
|
|
872
|
+
store = ArrayStore({r: np.asarray(self.arrays[r]) for r in spec.arrays.values()
|
|
873
|
+
if r in self.arrays})
|
|
874
|
+
return marginal_from_spec(spec, store)
|
|
875
|
+
|
|
876
|
+
def grid_of(self, model: Any) -> np.ndarray:
|
|
877
|
+
u = (np.arange(GRID) + 0.5) / GRID
|
|
878
|
+
with np.errstate(all="ignore"):
|
|
879
|
+
grid = np.asarray(model.ppf(u), dtype=np.float64).ravel()
|
|
880
|
+
if grid.size != GRID:
|
|
881
|
+
raise ValueError(f"ppf returned {grid.size} values for {GRID} probabilities")
|
|
882
|
+
grid = grid[np.isfinite(grid)]
|
|
883
|
+
if grid.size == 0:
|
|
884
|
+
raise ValueError("ppf returned no finite value")
|
|
885
|
+
return np.sort(grid)
|
|
886
|
+
|
|
887
|
+
def levels_from(self, labels: Any, probs: Any, column_name: str | None) -> v.Levels:
|
|
888
|
+
labs = [str(x) for x in np.asarray(labels).ravel().tolist()]
|
|
889
|
+
p = np.asarray(probs, dtype=np.float64).ravel()
|
|
890
|
+
p = np.where(np.isfinite(p) & (p > 0), p, 0.0)
|
|
891
|
+
total = float(p.sum())
|
|
892
|
+
if total > 0:
|
|
893
|
+
p = p / total
|
|
894
|
+
pooled = None
|
|
895
|
+
rows: list[tuple[str, float]] = []
|
|
896
|
+
for lab, share in zip(labs, p.tolist()):
|
|
897
|
+
if lab == POOLED_LABEL:
|
|
898
|
+
pooled = (pooled or 0.0) + share
|
|
899
|
+
else:
|
|
900
|
+
rows.append((lab, share))
|
|
901
|
+
order = sorted(range(len(rows)), key=lambda i: (-rows[i][1], i))
|
|
902
|
+
out = v.Levels(n_levels=len(rows))
|
|
903
|
+
for i in order[:MAX_BARS]:
|
|
904
|
+
out.bars.append(v.Level(label=_text(rows[i][0]), share=rows[i][1]))
|
|
905
|
+
rest = order[MAX_BARS:]
|
|
906
|
+
if rest:
|
|
907
|
+
out.bars.append(v.Level(label=f"{len(rest)} more values",
|
|
908
|
+
share=float(sum(rows[i][1] for i in rest)), kind="rest",
|
|
909
|
+
count=len(rest)))
|
|
910
|
+
if pooled is not None:
|
|
911
|
+
out.bars.append(v.Level(label=POOLED_LABEL, share=pooled, kind="pooled"))
|
|
912
|
+
out.pooled_share = pooled
|
|
913
|
+
if column_name is not None and column_name in self.pooled:
|
|
914
|
+
out.n_pooled = _int(self.pooled.get(column_name))
|
|
915
|
+
return out
|
|
916
|
+
|
|
917
|
+
def chart_from_grid(self, grid: np.ndarray, model: Any, kind: str, *, axis: str,
|
|
918
|
+
unit: str, integer: bool, decimals: int | None,
|
|
919
|
+
column: v.ColumnView | None, allow_levels: bool
|
|
920
|
+
) -> v.Histogram | v.Levels:
|
|
921
|
+
grid = grid[np.isfinite(grid)]
|
|
922
|
+
if grid.size > 1 and not bool(np.all(grid[1:] >= grid[:-1])):
|
|
923
|
+
grid = np.sort(grid)
|
|
924
|
+
n = grid.size
|
|
925
|
+
if n == 0:
|
|
926
|
+
raise ValueError("no finite value to draw")
|
|
927
|
+
is_int = bool(integer and np.all(grid == np.round(grid)))
|
|
928
|
+
values, counts = np.unique(grid, return_counts=True)
|
|
929
|
+
if allow_levels and axis == "number" and is_int and values.size <= MAX_ORDERED_LEVELS:
|
|
930
|
+
out = v.Levels(ordered=True, n_levels=int(values.size))
|
|
931
|
+
for val, cnt in zip(values.tolist(), counts.tolist()):
|
|
932
|
+
out.bars.append(v.Level(label=_number_label(val), share=cnt / n))
|
|
933
|
+
return out
|
|
934
|
+
h = v.Histogram(axis=axis, unit=unit)
|
|
935
|
+
# point masses
|
|
936
|
+
atoms: list[tuple[float, float]] = []
|
|
937
|
+
mixed_atoms = getattr(model, "atoms", None) if model is not None else None
|
|
938
|
+
if kind == "mixed" and mixed_atoms is not None:
|
|
939
|
+
a = np.asarray(mixed_atoms, dtype=np.float64).ravel()
|
|
940
|
+
p = np.asarray(getattr(model, "atom_probs", np.zeros(a.size)),
|
|
941
|
+
dtype=np.float64).ravel()
|
|
942
|
+
weight = float(getattr(model, "slab_weight", 0.0)) + float(p.sum())
|
|
943
|
+
stored = p / weight if weight > 0 else p
|
|
944
|
+
h.n_atoms = int(a.size)
|
|
945
|
+
gran = float(getattr(model, "granularity", 0.0) or 0.0)
|
|
946
|
+
for i in sorted(range(a.size), key=lambda i: (-stored[i], a[i])):
|
|
947
|
+
if len(atoms) >= MAX_ATOMS or stored[i] < ATOM_MIN_SHARE:
|
|
948
|
+
break
|
|
949
|
+
tol = max(abs(a[i]) * 1e-9, 1e-12, 0.25 * gran)
|
|
950
|
+
on = int(np.count_nonzero(np.abs(grid - a[i]) <= tol))
|
|
951
|
+
# the share drawn is what the grid holds on the atom: its stored mass plus
|
|
952
|
+
# the slab's own mass on that value, so bins and atoms add up to 1
|
|
953
|
+
atoms.append((float(a[i]), on / n if on else float(stored[i])))
|
|
954
|
+
steps = np.asarray(getattr(model, "level_steps", np.zeros(0)),
|
|
955
|
+
dtype=np.float64).ravel()
|
|
956
|
+
h.heap_steps = [float(s) for s in steps.tolist() if s > gran * (1 + 1e-9)]
|
|
957
|
+
elif not is_int and axis != "date":
|
|
958
|
+
big = np.flatnonzero(counts >= ATOM_MIN_SHARE * n)
|
|
959
|
+
found = sorted(((float(values[i]), float(counts[i]) / n) for i in big),
|
|
960
|
+
key=lambda x: (-x[1], x[0]))
|
|
961
|
+
h.n_atoms = len(found)
|
|
962
|
+
atoms = found[:MAX_ATOMS]
|
|
963
|
+
gran = float(getattr(model, "granularity", 0.0) or 0.0) if kind == "mixed" else 0.0
|
|
964
|
+
on_atom = np.zeros(n, dtype=bool)
|
|
965
|
+
for val, _share in atoms:
|
|
966
|
+
on_atom |= np.abs(grid - val) <= max(abs(val) * 1e-9, 1e-12, 0.25 * gran)
|
|
967
|
+
h.atoms = [v.Atom(value=val, share=share) for val, share in atoms]
|
|
968
|
+
rest = grid[~on_atom]
|
|
969
|
+
lo, hi = float(grid[0]), float(grid[-1])
|
|
970
|
+
if hi <= lo:
|
|
971
|
+
# one stored value: no bins, a single point mass
|
|
972
|
+
h.atoms = [v.Atom(value=lo, share=1.0)]
|
|
973
|
+
h.n_atoms = 1
|
|
974
|
+
else:
|
|
975
|
+
# the scale is chosen on what the bins hold: a point mass at zero does not rule
|
|
976
|
+
# out a log axis for the rest (the chart draws it in a slot of its own)
|
|
977
|
+
basis = rest if rest.size else grid
|
|
978
|
+
b_lo, b_hi = float(basis[0]), float(basis[-1])
|
|
979
|
+
h.scale = "log" if b_hi > b_lo and _log_scale(basis, axis) else "linear"
|
|
980
|
+
if h.scale == "log":
|
|
981
|
+
edges = np.logspace(math.log10(b_lo), math.log10(b_hi), BINS + 1)
|
|
982
|
+
edges[0], edges[-1] = b_lo, b_hi
|
|
983
|
+
else:
|
|
984
|
+
edges = np.linspace(lo, hi, BINS + 1)
|
|
985
|
+
cnt, _ = np.histogram(rest, bins=edges)
|
|
986
|
+
h.edges = [float(e) for e in edges.tolist()]
|
|
987
|
+
h.shares = [c / n for c in cnt.tolist()]
|
|
988
|
+
h.quantiles = [[p, float(grid[min(n - 1, int(p * n))])] for p in QUANTILE_PROBS]
|
|
989
|
+
h.mean = _finite_or_none(float(np.mean(grid)))
|
|
990
|
+
h.sd = _finite_or_none(float(np.std(grid)))
|
|
991
|
+
h.low = column.low if column is not None and column.low is not None else lo
|
|
992
|
+
h.high = column.high if column is not None and column.high is not None else hi
|
|
993
|
+
tail = _l(_get(self.policy, "tail_clip"))
|
|
994
|
+
clip = [_num(x) for x in tail]
|
|
995
|
+
h.clipped = len(clip) == 2 and None not in clip and (clip[0] != 0.0 or clip[1] != 1.0)
|
|
996
|
+
h.integer = is_int if column is None else column.integer
|
|
997
|
+
h.decimals = decimals
|
|
998
|
+
return h
|
|
999
|
+
|
|
1000
|
+
# -- relationships ------------------------------------------------------------------------
|
|
1001
|
+
def read_relationships(self) -> None:
|
|
1002
|
+
r = self.view.relationships
|
|
1003
|
+
joint = _get(self.model, "joint")
|
|
1004
|
+
self.guard("model.joint", lambda: self.read_joint(r, joint))
|
|
1005
|
+
self.guard("fingerprint diagnostics.joint", lambda: self.read_joint_diagnostics(r))
|
|
1006
|
+
assoc_raw = _get(self.cdiag, "associations")
|
|
1007
|
+
if assoc_raw is None:
|
|
1008
|
+
return
|
|
1009
|
+
assoc = self.expect_dict("fingerprint diagnostics.associations", assoc_raw)
|
|
1010
|
+
names = set(self.by_name)
|
|
1011
|
+
meta = _d(_get(assoc, "diagnostics"))
|
|
1012
|
+
pairs_raw = _l(_get(assoc, "pairs"))
|
|
1013
|
+
r.n_pairs = _int(_get(meta, "n_pairs"))
|
|
1014
|
+
if r.n_pairs is None and pairs_raw:
|
|
1015
|
+
r.n_pairs = len(pairs_raw)
|
|
1016
|
+
acols = _strs(_get(assoc, "columns"))
|
|
1017
|
+
r.n_columns = len(acols) if acols else None
|
|
1018
|
+
r.n_notable = _int(_get(meta, "n_candidates"))
|
|
1019
|
+
r.threshold = _num(_get(meta, "threshold"))
|
|
1020
|
+
r.left_out = _strs(_get(assoc, "excluded_rare_level_columns"))
|
|
1021
|
+
links = self.links()
|
|
1022
|
+
corr = self.joint_correlation(joint)
|
|
1023
|
+
spear = self.calibration_signs()
|
|
1024
|
+
pairs: list[tuple[str, str, str, float]] = []
|
|
1025
|
+
for p in pairs_raw:
|
|
1026
|
+
cols = _strs(_get(p, "columns"))
|
|
1027
|
+
strength = _num(_get(p, "strength"))
|
|
1028
|
+
if len(cols) != 2 or strength is None:
|
|
1029
|
+
continue
|
|
1030
|
+
pairs.append((cols[0], cols[1], _s(_get(p, "measure")), strength))
|
|
1031
|
+
pairs.sort(key=lambda x: -x[3]) # stable: the engine's order among ties
|
|
1032
|
+
pairs = [p for p in pairs if p[0] in names and p[1] in names and p[0] != p[1]]
|
|
1033
|
+
member = self.guard("fingerprint diagnostics.associations (groups)",
|
|
1034
|
+
lambda: self.column_groups(r, pairs, links)) or {}
|
|
1035
|
+
unknown_measures: list[str] = []
|
|
1036
|
+
sides: dict[frozenset[Any], v.Pair] = {}
|
|
1037
|
+
for a, b, measure, strength in pairs:
|
|
1038
|
+
ga, gb = member.get(a), member.get(b)
|
|
1039
|
+
if ga is not None and ga == gb:
|
|
1040
|
+
continue # stated once, as a group
|
|
1041
|
+
key = frozenset((("g", ga) if ga is not None else ("c", a),
|
|
1042
|
+
("g", gb) if gb is not None else ("c", b)))
|
|
1043
|
+
if key in sides:
|
|
1044
|
+
sides[key].collapsed += 1
|
|
1045
|
+
continue
|
|
1046
|
+
if len(r.pairs) >= MAX_PAIRS:
|
|
1047
|
+
break
|
|
1048
|
+
if measure not in MEASURES and measure not in unknown_measures:
|
|
1049
|
+
unknown_measures.append(measure)
|
|
1050
|
+
sign = 0
|
|
1051
|
+
if measure == "spearman":
|
|
1052
|
+
sign = corr.get((a, b), 0) or spear.get((a, b), 0)
|
|
1053
|
+
pair = v.Pair(a=a, b=b, measure=measure, strength=strength, sign=sign,
|
|
1054
|
+
explained_by=links.get(frozenset((a, b)), ""),
|
|
1055
|
+
a_group=ga, b_group=gb)
|
|
1056
|
+
sides[key] = pair
|
|
1057
|
+
r.pairs.append(pair)
|
|
1058
|
+
for measure in unknown_measures:
|
|
1059
|
+
self.unread.append(v.Unread(where="fingerprint diagnostics.associations",
|
|
1060
|
+
what=f"unknown association measure '{measure}'"))
|
|
1061
|
+
shown = [(p.a, p.b, p.measure, p.strength) for p in r.pairs]
|
|
1062
|
+
r.matrix = self.guard("fingerprint diagnostics.associations.matrix",
|
|
1063
|
+
lambda: self.matrix(assoc, shown + pairs, names))
|
|
1064
|
+
|
|
1065
|
+
def column_groups(self, r: v.Relationships, pairs: list[tuple[str, str, str, float]],
|
|
1066
|
+
links: Mapping[frozenset[str], str]) -> dict[str, int]:
|
|
1067
|
+
"""Groups of columns that carry almost the same information, written to ``r.groups``;
|
|
1068
|
+
returns each member's group index. Two groups merge on a pair of at least
|
|
1069
|
+
:data:`NEAR_IDENTICAL` only when every measured pair across them is at least
|
|
1070
|
+
:data:`GROUP_FLOOR`, so a chain of strong pairs never ties two unrelated columns."""
|
|
1071
|
+
strength = {frozenset((a, b)): s for a, b, _m, s in pairs}
|
|
1072
|
+
order = {c.name: c.index for c in self.view.columns}
|
|
1073
|
+
cluster: dict[str, list[str]] = {}
|
|
1074
|
+
# only measures that treat the two columns alike can say "the same information": a
|
|
1075
|
+
# correlation ratio of 1 says the category fixes the number, not the reverse
|
|
1076
|
+
near = [p for p in pairs if p[3] >= NEAR_IDENTICAL and p[2] in SYMMETRIC_MEASURES]
|
|
1077
|
+
for a, b, _measure, _s in near:
|
|
1078
|
+
ca, cb = cluster.setdefault(a, [a]), cluster.setdefault(b, [b])
|
|
1079
|
+
if ca is cb:
|
|
1080
|
+
continue
|
|
1081
|
+
if all(strength.get(frozenset((x, y)), 0.0) >= GROUP_FLOOR for x in ca for y in cb):
|
|
1082
|
+
ca.extend(cb)
|
|
1083
|
+
for x in cb:
|
|
1084
|
+
cluster[x] = ca
|
|
1085
|
+
member: dict[str, int] = {}
|
|
1086
|
+
seen: list[list[str]] = []
|
|
1087
|
+
for a, b, _measure, _s in near: # groups in order of their strongest pair
|
|
1088
|
+
for name in (a, b):
|
|
1089
|
+
c = cluster.get(name)
|
|
1090
|
+
if c is None or len(c) < 2 or any(c is x for x in seen):
|
|
1091
|
+
continue
|
|
1092
|
+
seen.append(c)
|
|
1093
|
+
cols = sorted(c, key=lambda n: order.get(n, 0))
|
|
1094
|
+
inside = [(x, y) for i, x in enumerate(cols) for y in cols[i + 1:]]
|
|
1095
|
+
measured = [strength[frozenset(p)] for p in inside if frozenset(p) in strength]
|
|
1096
|
+
measures = {m for x, y, m, _s in pairs if x in c and y in c}
|
|
1097
|
+
why = {links.get(frozenset(p), "") for p in inside}
|
|
1098
|
+
group = v.ColumnGroup(
|
|
1099
|
+
columns=cols, weakest=min(measured) if measured else None,
|
|
1100
|
+
measure=measures.pop() if len(measures) == 1 else "",
|
|
1101
|
+
explained_by=why.pop() if len(why) == 1 else "")
|
|
1102
|
+
for n in cols:
|
|
1103
|
+
member[n] = len(r.groups)
|
|
1104
|
+
r.groups.append(group)
|
|
1105
|
+
return member
|
|
1106
|
+
|
|
1107
|
+
def read_joint(self, r: v.Relationships, joint: Any) -> None:
|
|
1108
|
+
if joint is None:
|
|
1109
|
+
return
|
|
1110
|
+
j = self.expect_dict("model.joint", joint)
|
|
1111
|
+
if not j:
|
|
1112
|
+
return
|
|
1113
|
+
kind = _s(_get(j, "kind"))
|
|
1114
|
+
r.joint_kind = kind or None # carried as found; the page names it
|
|
1115
|
+
params = _d(_get(j, "params"))
|
|
1116
|
+
cols = _get(params, "columns")
|
|
1117
|
+
if isinstance(cols, list):
|
|
1118
|
+
r.joint_columns = len(cols)
|
|
1119
|
+
for key, val in params.items():
|
|
1120
|
+
if len(r.joint_facts) >= 6 or key == "columns":
|
|
1121
|
+
continue
|
|
1122
|
+
num = _num(val)
|
|
1123
|
+
if num is not None:
|
|
1124
|
+
r.joint_facts.append(v.Fact(label=_s(key), number=num))
|
|
1125
|
+
elif isinstance(val, str) and len(val) <= 80:
|
|
1126
|
+
r.joint_facts.append(v.Fact(label=_s(key), text=val))
|
|
1127
|
+
|
|
1128
|
+
def read_joint_diagnostics(self, r: v.Relationships) -> None:
|
|
1129
|
+
"""Why this joint model was fitted and what was limited (the profiler's own words).
|
|
1130
|
+
|
|
1131
|
+
Only the two sentences are carried; the counts beside them (work budget, passes,
|
|
1132
|
+
rows) are the engine's bookkeeping and stay off the page."""
|
|
1133
|
+
raw = _get(self.cdiag, "joint")
|
|
1134
|
+
if raw is None:
|
|
1135
|
+
return
|
|
1136
|
+
d = self.expect_dict("fingerprint diagnostics.joint", raw)
|
|
1137
|
+
reason = _get(d, "reason")
|
|
1138
|
+
if isinstance(reason, str) and reason.strip():
|
|
1139
|
+
r.joint_reason = reason.strip()[:300]
|
|
1140
|
+
limits = _d(_get(d, "limits"))
|
|
1141
|
+
note = _get(limits, "note")
|
|
1142
|
+
if _get(limits, "limited") and isinstance(note, str) and note.strip():
|
|
1143
|
+
r.joint_limit = note.strip()[:600]
|
|
1144
|
+
|
|
1145
|
+
def joint_correlation(self, joint: Any) -> dict[tuple[str, str], int]:
|
|
1146
|
+
out: dict[tuple[str, str], int] = {}
|
|
1147
|
+
try:
|
|
1148
|
+
params = _d(_get(joint, "params"))
|
|
1149
|
+
cols = _strs(_get(params, "columns"))
|
|
1150
|
+
arr = _num_array(self.arrays, _get(_d(_get(joint, "arrays")), "correlation"))
|
|
1151
|
+
k = len(cols)
|
|
1152
|
+
if arr is None or k < 2 or arr.size != k * k:
|
|
1153
|
+
return out
|
|
1154
|
+
mat = arr.reshape(k, k)
|
|
1155
|
+
for i in range(k):
|
|
1156
|
+
for j in range(i + 1, k):
|
|
1157
|
+
x = mat[i, j]
|
|
1158
|
+
if math.isfinite(x) and x != 0:
|
|
1159
|
+
s = 1 if x > 0 else -1
|
|
1160
|
+
out[(cols[i], cols[j])] = out[(cols[j], cols[i])] = s
|
|
1161
|
+
except Exception:
|
|
1162
|
+
return {}
|
|
1163
|
+
return out
|
|
1164
|
+
|
|
1165
|
+
def calibration_signs(self) -> dict[tuple[str, str], int]:
|
|
1166
|
+
out: dict[tuple[str, str], int] = {}
|
|
1167
|
+
for t in self.calibration:
|
|
1168
|
+
if _s(_get(t, "metric")) != "bivariate.spearman":
|
|
1169
|
+
continue
|
|
1170
|
+
cols = _strs(_get(t, "columns"))
|
|
1171
|
+
x = _num(_get(t, "value"))
|
|
1172
|
+
if len(cols) == 2 and x is not None and x != 0:
|
|
1173
|
+
s = 1 if x > 0 else -1
|
|
1174
|
+
out[(cols[0], cols[1])] = out[(cols[1], cols[0])] = s
|
|
1175
|
+
return out
|
|
1176
|
+
|
|
1177
|
+
def links(self) -> dict[frozenset[str], str]:
|
|
1178
|
+
"""Pairs of columns tied by a structure, with the name of the structure."""
|
|
1179
|
+
out: dict[frozenset[str], str] = {}
|
|
1180
|
+
|
|
1181
|
+
def tie(cols: Sequence[str], what: str) -> None:
|
|
1182
|
+
cs = [c for c in dict.fromkeys(cols) if c]
|
|
1183
|
+
for i in range(len(cs)):
|
|
1184
|
+
for j in range(i + 1, len(cs)):
|
|
1185
|
+
out.setdefault(frozenset((cs[i], cs[j])), what)
|
|
1186
|
+
|
|
1187
|
+
def tie_one(a: str, others: Sequence[str], what: str) -> None:
|
|
1188
|
+
for o in others:
|
|
1189
|
+
if o and o != a:
|
|
1190
|
+
out.setdefault(frozenset((a, o)), what)
|
|
1191
|
+
|
|
1192
|
+
for s in _l(_get(self.model, "sums")):
|
|
1193
|
+
tie([_s(_get(s, "total")), *_strs(_get(s, "parts"))], "sum")
|
|
1194
|
+
for t in _l(_get(self.model, "transforms")):
|
|
1195
|
+
kind = _s(_get(t, "kind"))
|
|
1196
|
+
tie_one(_s(_get(t, "target")), _strs(_get(t, "inputs")),
|
|
1197
|
+
"offset" if kind == "difference" else "computed")
|
|
1198
|
+
for name, d in self.derived.items():
|
|
1199
|
+
tie_one(name, self.derived_inputs(name, _s(_get(d, "expression"))), "computed")
|
|
1200
|
+
for g in _l(_get(self.model, "entities")):
|
|
1201
|
+
tie([_s(_get(g, "key")), *[_s(_get(a, "column")) for a in
|
|
1202
|
+
_l(_get(g, "attributes"))],
|
|
1203
|
+
_s(_get(_get(g, "anchor"), "column"))], "entity")
|
|
1204
|
+
for o in _l(_get(self.model, "orderings")):
|
|
1205
|
+
tie_one(_s(_get(o, "target")),
|
|
1206
|
+
[*_strs(_get(o, "lower")), *_strs(_get(o, "upper"))], "ordering")
|
|
1207
|
+
return out
|
|
1208
|
+
|
|
1209
|
+
def matrix(self, assoc: Mapping[str, Any], pairs: list[tuple[str, str, str, float]],
|
|
1210
|
+
names: set[str]) -> v.Matrix | None:
|
|
1211
|
+
acols = _strs(_get(assoc, "columns"))
|
|
1212
|
+
pos = {c: i for i, c in enumerate(acols)}
|
|
1213
|
+
chosen: list[str] = []
|
|
1214
|
+
for a, b, *_rest in pairs:
|
|
1215
|
+
for c in (a, b):
|
|
1216
|
+
if c in names and c not in chosen and len(chosen) < MATRIX_COLUMNS:
|
|
1217
|
+
chosen.append(c)
|
|
1218
|
+
if len(chosen) >= MATRIX_COLUMNS:
|
|
1219
|
+
break
|
|
1220
|
+
if len(chosen) < 2:
|
|
1221
|
+
return None
|
|
1222
|
+
raw = [_l(r) for r in _l(_get(assoc, "matrix"))]
|
|
1223
|
+
lookup = {frozenset((a, b)): s for a, b, _m, s in pairs}
|
|
1224
|
+
values: list[list[float]] = []
|
|
1225
|
+
for a in chosen:
|
|
1226
|
+
row: list[float] = []
|
|
1227
|
+
for b in chosen:
|
|
1228
|
+
if a == b:
|
|
1229
|
+
row.append(1.0)
|
|
1230
|
+
continue
|
|
1231
|
+
x: float | None = None
|
|
1232
|
+
ia, ib = pos.get(a), pos.get(b)
|
|
1233
|
+
if ia is not None and ib is not None and ia < len(raw):
|
|
1234
|
+
line = raw[ia]
|
|
1235
|
+
if ib < len(line):
|
|
1236
|
+
x = _num(line[ib])
|
|
1237
|
+
if x is None:
|
|
1238
|
+
x = lookup.get(frozenset((a, b)), 0.0)
|
|
1239
|
+
row.append(float(x))
|
|
1240
|
+
values.append(row)
|
|
1241
|
+
return v.Matrix(columns=chosen, values=values)
|
|
1242
|
+
|
|
1243
|
+
# -- structure ----------------------------------------------------------------------------
|
|
1244
|
+
def read_structure(self) -> None:
|
|
1245
|
+
st = self.view.structure
|
|
1246
|
+
st.mode = _s(_get(_d(_get(self.mdiag, "structure")), "mode"))
|
|
1247
|
+
self.guard("model.transforms", self.read_transforms)
|
|
1248
|
+
self.guard("model.orderings", self.read_orderings)
|
|
1249
|
+
self.guard("model.derived", self.read_derived)
|
|
1250
|
+
self.guard("model.sums", self.read_sums)
|
|
1251
|
+
self.guard("model.entities", self.read_entities)
|
|
1252
|
+
self.guard("model.references", self.read_references)
|
|
1253
|
+
self.guard("model.calendars", self.read_calendars)
|
|
1254
|
+
self.guard("constraints", self.read_constraints)
|
|
1255
|
+
self.guard("diagnostics", self.read_not_applied)
|
|
1256
|
+
|
|
1257
|
+
def read_transforms(self) -> None:
|
|
1258
|
+
st = self.view.structure
|
|
1259
|
+
applied = _l(_get(_d(_get(self.mdiag, "structure")), "applied"))
|
|
1260
|
+
for i, t in enumerate(self.expect_list("model.transforms",
|
|
1261
|
+
_get(self.model, "transforms"))):
|
|
1262
|
+
def one(i: int = i, t: Any = t) -> None:
|
|
1263
|
+
t = self.expect_dict(f"model.transforms[{i}]", t)
|
|
1264
|
+
if not t:
|
|
1265
|
+
return
|
|
1266
|
+
kind = _s(_get(t, "kind"))
|
|
1267
|
+
target = _s(_get(t, "target"))
|
|
1268
|
+
inputs = _strs(_get(t, "inputs"))
|
|
1269
|
+
params = _d(_get(t, "params"))
|
|
1270
|
+
if kind == "identity":
|
|
1271
|
+
st.computed.append(v.Computed(
|
|
1272
|
+
column=target, formula=_text(_identity_text(target, inputs, params)),
|
|
1273
|
+
inputs=inputs, family="identity", source=_s(_get(params, "source"))))
|
|
1274
|
+
return
|
|
1275
|
+
if kind != "difference":
|
|
1276
|
+
# carried as found: an ordering-like item with the raw kind as ``how``
|
|
1277
|
+
self.unread.append(v.Unread(where=f"model.transforms[{i}]",
|
|
1278
|
+
what=f"unknown transform kind '{kind}'",
|
|
1279
|
+
column=target or None))
|
|
1280
|
+
st.orderings.append(v.Ordering(target=target, how=kind,
|
|
1281
|
+
base=inputs[0] if inputs else None,
|
|
1282
|
+
source=_s(_get(params, "source"))))
|
|
1283
|
+
return
|
|
1284
|
+
sign = -1 if _int(_get(params, "sign")) == -1 else 1
|
|
1285
|
+
base = inputs[0] if inputs else None
|
|
1286
|
+
rec = next((a for a in applied if _s(_get(a, "target")) == target
|
|
1287
|
+
and _s(_get(a, "kind")) in ("difference", "")), None)
|
|
1288
|
+
o = v.Ordering(
|
|
1289
|
+
target=target, lower=[base] if base and sign > 0 else [],
|
|
1290
|
+
upper=[base] if base and sign < 0 else [],
|
|
1291
|
+
strict=_get(params, "strict") is True, how="gap", base=base,
|
|
1292
|
+
signed=_get(params, "signed") is True,
|
|
1293
|
+
exceptions=_num(_get(rec, "violation_rate")) if rec is not None else None,
|
|
1294
|
+
source=_s(_get(params, "source")),
|
|
1295
|
+
constraint=_os(_get(params, "constraint")))
|
|
1296
|
+
cv = self.view.column(target)
|
|
1297
|
+
if cv is not None and cv.chart_of == "gap":
|
|
1298
|
+
o.gap = cv.histogram
|
|
1299
|
+
elif cv is None:
|
|
1300
|
+
o.gap = self.gap_histogram(
|
|
1301
|
+
t, f"model.marginals.{_s(_get(params, 'latent'))}", None)
|
|
1302
|
+
st.orderings.append(o)
|
|
1303
|
+
self.guard(f"model.transforms[{i}]", one)
|
|
1304
|
+
|
|
1305
|
+
def read_orderings(self) -> None:
|
|
1306
|
+
st = self.view.structure
|
|
1307
|
+
for i, o in enumerate(self.expect_list("model.orderings",
|
|
1308
|
+
_get(self.model, "orderings"))):
|
|
1309
|
+
def one(i: int = i, o: Any = o) -> None:
|
|
1310
|
+
o = self.expect_dict(f"model.orderings[{i}]", o)
|
|
1311
|
+
if not o:
|
|
1312
|
+
return
|
|
1313
|
+
method = _s(_get(o, "method"), "reflect") if "method" in o else "reflect"
|
|
1314
|
+
target = _s(_get(o, "target"))
|
|
1315
|
+
if method not in ORDERING_METHODS:
|
|
1316
|
+
self.unread.append(v.Unread(where=f"model.orderings[{i}]",
|
|
1317
|
+
what=f"unknown ordering method '{method}'",
|
|
1318
|
+
column=target or None))
|
|
1319
|
+
cons = _strs(_get(o, "constraints"))
|
|
1320
|
+
st.orderings.append(v.Ordering(
|
|
1321
|
+
target=target, lower=_strs(_get(o, "lower")),
|
|
1322
|
+
upper=_strs(_get(o, "upper")), strict=_get(o, "strict") is True,
|
|
1323
|
+
how="redraw" if method == "reflect" else method,
|
|
1324
|
+
source=_s(_get(o, "source")), constraint=cons[0] if cons else None))
|
|
1325
|
+
self.guard(f"model.orderings[{i}]", one)
|
|
1326
|
+
|
|
1327
|
+
def read_derived(self) -> None:
|
|
1328
|
+
st = self.view.structure
|
|
1329
|
+
for i, d in enumerate(self.expect_list("model.derived", _get(self.model, "derived"))):
|
|
1330
|
+
def one(i: int = i, d: Any = d) -> None:
|
|
1331
|
+
d = self.expect_dict(f"model.derived[{i}]", d)
|
|
1332
|
+
if not d:
|
|
1333
|
+
return
|
|
1334
|
+
col = _s(_get(d, "column"))
|
|
1335
|
+
expr = _s(_get(d, "expression"))
|
|
1336
|
+
rec = self.fn_applied.get(col)
|
|
1337
|
+
st.computed.append(v.Computed(
|
|
1338
|
+
column=col, formula=_text(expr), inputs=self.derived_inputs(col, expr),
|
|
1339
|
+
family=_s(_get(rec, "family")) if rec is not None else "declared",
|
|
1340
|
+
exceptions=_num(_get(rec, "exception_rate")) if rec is not None else None,
|
|
1341
|
+
segments=_int(_get(rec, "segments")) if rec is not None else None,
|
|
1342
|
+
source="detected" if rec is not None else "declared"))
|
|
1343
|
+
self.guard(f"model.derived[{i}]", one)
|
|
1344
|
+
|
|
1345
|
+
def read_sums(self) -> None:
|
|
1346
|
+
st = self.view.structure
|
|
1347
|
+
applied = _l(_get(_d(_get(self.mdiag, "sums")), "applied"))
|
|
1348
|
+
used: set[int] = set()
|
|
1349
|
+
for i, s in enumerate(self.expect_list("model.sums", _get(self.model, "sums"))):
|
|
1350
|
+
def one(i: int = i, s: Any = s) -> None:
|
|
1351
|
+
s = self.expect_dict(f"model.sums[{i}]", s)
|
|
1352
|
+
if not s:
|
|
1353
|
+
return
|
|
1354
|
+
parts = _strs(_get(s, "parts"))
|
|
1355
|
+
signs = [-1 if _int(x) == -1 else 1 for x in _l(_get(s, "signs"))]
|
|
1356
|
+
if len(signs) != len(parts):
|
|
1357
|
+
signs = [1] * len(parts)
|
|
1358
|
+
mode = _s(_get(s, "mode"), "split") if "mode" in s else "split"
|
|
1359
|
+
rounding = _s(_get(s, "rounding"), "exact") if "rounding" in s else "exact"
|
|
1360
|
+
total = _os(_get(s, "total"))
|
|
1361
|
+
if mode not in SUM_MODES:
|
|
1362
|
+
self.unread.append(v.Unread(where=f"model.sums[{i}]",
|
|
1363
|
+
what=f"unknown sum mode '{mode}'",
|
|
1364
|
+
column=total))
|
|
1365
|
+
if rounding not in SUM_ROUNDINGS:
|
|
1366
|
+
self.unread.append(v.Unread(where=f"model.sums[{i}]",
|
|
1367
|
+
what=f"unknown sum rounding '{rounding}'",
|
|
1368
|
+
column=total))
|
|
1369
|
+
text = _sum_text(s)
|
|
1370
|
+
rec = None
|
|
1371
|
+
for k, a in enumerate(applied):
|
|
1372
|
+
if k not in used and _s(_get(a, "sum")) == text:
|
|
1373
|
+
rec = a
|
|
1374
|
+
used.add(k)
|
|
1375
|
+
break
|
|
1376
|
+
st.sums.append(v.SumRule(
|
|
1377
|
+
total=total, constant=_num(_get(s, "constant")), parts=parts, signs=signs,
|
|
1378
|
+
mode=mode, rounding=rounding,
|
|
1379
|
+
mean_shares=[x for x in (_num(y) for y in _l(_get(s, "fallback")))
|
|
1380
|
+
if x is not None],
|
|
1381
|
+
exceptions=_num(_get(rec, "violation_rate")) if rec is not None else None,
|
|
1382
|
+
tolerance=_num(_get(s, "tolerance")), source=_s(_get(s, "source"))))
|
|
1383
|
+
self.guard(f"model.sums[{i}]", one)
|
|
1384
|
+
|
|
1385
|
+
def read_entities(self) -> None:
|
|
1386
|
+
st = self.view.structure
|
|
1387
|
+
applied = _l(_get(_d(_get(self.mdiag, "entities")), "applied"))
|
|
1388
|
+
for i, g in enumerate(self.expect_list("model.entities", _get(self.model, "entities"))):
|
|
1389
|
+
def one(i: int = i, g: Any = g) -> None:
|
|
1390
|
+
g = self.expect_dict(f"model.entities[{i}]", g)
|
|
1391
|
+
if not g:
|
|
1392
|
+
return
|
|
1393
|
+
key = _s(_get(g, "key"))
|
|
1394
|
+
method = _s(_get(g, "method"), "lookup") if "method" in g else "lookup"
|
|
1395
|
+
if method not in ENTITY_METHODS:
|
|
1396
|
+
self.unread.append(v.Unread(where=f"model.entities[{i}]",
|
|
1397
|
+
what=f"unknown entity method '{method}'",
|
|
1398
|
+
column=key or None))
|
|
1399
|
+
rec = next((a for a in applied if _s(_get(a, "key")) == key), None)
|
|
1400
|
+
diag_attrs = {_s(_get(a, "attribute")): _d(a)
|
|
1401
|
+
for a in _l(_get(rec, "attributes"))}
|
|
1402
|
+
keys = _array(self.arrays, _get(g, "keys"))
|
|
1403
|
+
n_keys = int(keys.size) if keys is not None else _int(_get(rec, "keys"))
|
|
1404
|
+
group = v.EntityGroup(key=key, n_keys=n_keys, source=_s(_get(g, "source")),
|
|
1405
|
+
key_stand_ins=_s(_get(self.by_name.get(key), "role"))
|
|
1406
|
+
== "pseudonym")
|
|
1407
|
+
for a in _l(_get(g, "attributes")):
|
|
1408
|
+
col = _s(_get(a, "column"))
|
|
1409
|
+
d = diag_attrs.get(col, {})
|
|
1410
|
+
group.attributes.append(v.EntityAttribute(
|
|
1411
|
+
column=col, entries=_int(_get(d, "entries")),
|
|
1412
|
+
exceptions=_num(_get(d, "exception_rate"))))
|
|
1413
|
+
anchor = _get(g, "anchor")
|
|
1414
|
+
if isinstance(anchor, Mapping):
|
|
1415
|
+
d = _d(_get(rec, "anchor"))
|
|
1416
|
+
group.attributes.append(v.EntityAttribute(
|
|
1417
|
+
column=_s(_get(anchor, "column")), entries=_int(_get(d, "entries")),
|
|
1418
|
+
exceptions=_num(_get(d, "exception_rate")), anchor=True))
|
|
1419
|
+
st.entities.append(group)
|
|
1420
|
+
self.guard(f"model.entities[{i}]", one)
|
|
1421
|
+
|
|
1422
|
+
def read_references(self) -> None:
|
|
1423
|
+
st = self.view.structure
|
|
1424
|
+
refs = self.expect_dict("model.references", _get(self.model, "references"))
|
|
1425
|
+
for name, spec in refs.items():
|
|
1426
|
+
def one(name: Any = name, spec: Any = spec) -> None:
|
|
1427
|
+
col = _s(name, repr(name))
|
|
1428
|
+
ref = v.ReferenceKey(column=col)
|
|
1429
|
+
kind = _s(_get(spec, "kind"))
|
|
1430
|
+
if kind:
|
|
1431
|
+
ref.facts.append(v.Fact(label="surrogate kind", text=kind))
|
|
1432
|
+
cv = self.view.column(col)
|
|
1433
|
+
sizes = self.group_sizes(col)
|
|
1434
|
+
if sizes is not None:
|
|
1435
|
+
vals, probs = sizes
|
|
1436
|
+
inv = float(np.sum(probs / vals))
|
|
1437
|
+
if inv > 0:
|
|
1438
|
+
ref.mean_group = 1.0 / inv
|
|
1439
|
+
ref.singletons = float(np.sum(probs[vals == 1]) / inv)
|
|
1440
|
+
ref.max_group = float(vals.max())
|
|
1441
|
+
elif cv is not None and cv.histogram is not None:
|
|
1442
|
+
ref.max_group = cv.histogram.high
|
|
1443
|
+
st.references.append(ref)
|
|
1444
|
+
self.guard(f"model.references.{_s(name, repr(name))}", one)
|
|
1445
|
+
|
|
1446
|
+
def group_sizes(self, col: str) -> tuple[np.ndarray, np.ndarray] | None:
|
|
1447
|
+
"""Group sizes and their row shares, from the column's model evaluated on the grid."""
|
|
1448
|
+
spec = _get(self.marginals, col)
|
|
1449
|
+
if not isinstance(spec, Mapping):
|
|
1450
|
+
return None
|
|
1451
|
+
_model, grid, error, _key = self.evaluate(_s(_get(spec, "kind")),
|
|
1452
|
+
_d(_get(spec, "params")),
|
|
1453
|
+
_d(_get(spec, "arrays")))
|
|
1454
|
+
if grid is None or error is not None:
|
|
1455
|
+
return None
|
|
1456
|
+
grid = np.round(grid[grid >= 1])
|
|
1457
|
+
if grid.size == 0:
|
|
1458
|
+
return None
|
|
1459
|
+
vals, counts = np.unique(grid, return_counts=True)
|
|
1460
|
+
return vals.astype(np.float64), counts / counts.sum()
|
|
1461
|
+
|
|
1462
|
+
def read_calendars(self) -> None:
|
|
1463
|
+
st = self.view.structure
|
|
1464
|
+
for i, c in enumerate(self.expect_list("model.calendars",
|
|
1465
|
+
_get(self.model, "calendars"))):
|
|
1466
|
+
def one(i: int = i, c: Any = c) -> None:
|
|
1467
|
+
c = self.expect_dict(f"model.calendars[{i}]", c)
|
|
1468
|
+
if not c:
|
|
1469
|
+
return
|
|
1470
|
+
col = _s(_get(c, "column"))
|
|
1471
|
+
method = _s(_get(c, "method"), "transport") if "method" in c else "transport"
|
|
1472
|
+
if method not in CALENDAR_METHODS:
|
|
1473
|
+
self.unread.append(v.Unread(where=f"model.calendars[{i}]",
|
|
1474
|
+
what=f"unknown calendar method '{method}'",
|
|
1475
|
+
column=col or None))
|
|
1476
|
+
period = _int(_get(c, "period")) if "period" in c else 7
|
|
1477
|
+
profile = [x for x in (_num(y) for y in _l(_get(c, "profile")))
|
|
1478
|
+
if x is not None]
|
|
1479
|
+
p = period if period is not None and period > 0 else 7
|
|
1480
|
+
if period != 7:
|
|
1481
|
+
self.unread.append(v.Unread(where=f"model.calendars[{i}]",
|
|
1482
|
+
what=f"calendar period {_get(c, 'period')!r}",
|
|
1483
|
+
column=col or None))
|
|
1484
|
+
if p == 7 and len(profile) == 7:
|
|
1485
|
+
profile = _monday_first(profile)
|
|
1486
|
+
st.weekly.append(v.WeeklyPattern(column=col, weekday_shares=profile,
|
|
1487
|
+
tied_to=_strs(_get(c, "anchors")), period=p))
|
|
1488
|
+
self.guard(f"model.calendars[{i}]", one)
|
|
1489
|
+
|
|
1490
|
+
def read_constraints(self) -> None:
|
|
1491
|
+
st = self.view.structure
|
|
1492
|
+
cons = self.expect_dict("constraints", _get(self.m, "constraints"))
|
|
1493
|
+
for c in self.expect_list("constraints.confirmed", _get(cons, "confirmed")):
|
|
1494
|
+
if not isinstance(c, Mapping):
|
|
1495
|
+
continue
|
|
1496
|
+
st.confirmed.append(v.Constraint(
|
|
1497
|
+
id=_s(_get(c, "id")), expression=_text(_get(c, "expression")),
|
|
1498
|
+
status="confirmed", description=_text(_get(c, "description")),
|
|
1499
|
+
enforcement=_s(_get(c, "enforcement"))))
|
|
1500
|
+
sugg = [c for c in self.expect_list("constraints.suggested", _get(cons, "suggested"))
|
|
1501
|
+
if isinstance(c, Mapping)]
|
|
1502
|
+
st.n_suggested = len(sugg)
|
|
1503
|
+
order = sorted(range(len(sugg)), key=lambda i: (
|
|
1504
|
+
-(_num(_get(sugg[i], "confidence")) or 0.0),
|
|
1505
|
+
-(_num(_get(sugg[i], "support")) or 0.0), i))
|
|
1506
|
+
for i in order[:MAX_SUGGESTED]:
|
|
1507
|
+
c = sugg[i]
|
|
1508
|
+
st.suggested.append(v.Constraint(
|
|
1509
|
+
id=_s(_get(c, "id")), expression=_text(_get(c, "expression")),
|
|
1510
|
+
status="suggested", family=_s(_get(c, "family")),
|
|
1511
|
+
description=_text(_get(_d(_get(c, "evidence")), "description")),
|
|
1512
|
+
confidence=_s(_get(c, "confidence_label")), support=_int(_get(c, "support")),
|
|
1513
|
+
violations=_int(_get(c, "violations"))))
|
|
1514
|
+
fams: dict[str, int] = {}
|
|
1515
|
+
for c in sugg:
|
|
1516
|
+
f = _s(_get(c, "family"))
|
|
1517
|
+
fams[f] = fams.get(f, 0) + 1
|
|
1518
|
+
st.suggested_families = [v.Fact(label=f, number=float(n), unit="constraints")
|
|
1519
|
+
for f, n in sorted(fams.items(), key=lambda x: (-x[1], x[0]))]
|
|
1520
|
+
|
|
1521
|
+
def read_not_applied(self) -> None:
|
|
1522
|
+
st = self.view.structure
|
|
1523
|
+
for section, kind in _NOT_SELECTED_KINDS:
|
|
1524
|
+
for rec in _l(_get(_d(_get(self.mdiag, section)), "not_selected")):
|
|
1525
|
+
if not isinstance(rec, Mapping):
|
|
1526
|
+
continue
|
|
1527
|
+
st.n_not_applied += 1
|
|
1528
|
+
if len(st.not_applied) >= MAX_NOT_APPLIED:
|
|
1529
|
+
continue
|
|
1530
|
+
st.not_applied.append(v.NotApplied(kind=kind, subject=_text(_subject(section,
|
|
1531
|
+
rec)),
|
|
1532
|
+
reason=_text(_get(rec, "reason"))))
|
|
1533
|
+
|
|
1534
|
+
# -- privacy ------------------------------------------------------------------------------
|
|
1535
|
+
def read_privacy(self) -> None:
|
|
1536
|
+
pv = self.view.privacy
|
|
1537
|
+
pol = self.policy
|
|
1538
|
+
pv.policy = _s(_get(pol, "profile"))
|
|
1539
|
+
pv.sensitive = _get(pol, "sensitive") is True
|
|
1540
|
+
pv.min_category_support = _int(_get(pol, "min_category_support"))
|
|
1541
|
+
pv.quantile_resolution = _int(_get(pol, "quantile_resolution"))
|
|
1542
|
+
pv.tail_clip = [x for x in (_num(y) for y in _l(_get(pol, "tail_clip")))
|
|
1543
|
+
if x is not None]
|
|
1544
|
+
pv.rare_cell_min = _int(_get(pol, "rare_cell_min"))
|
|
1545
|
+
pv.significant_digits = _int(_get(pol, "significant_digits"))
|
|
1546
|
+
pv.identifiers = _s(_get(pol, "identifiers"))
|
|
1547
|
+
for key, val in pol.items():
|
|
1548
|
+
if key in KNOWN_KEYS["disclosure_policy"]:
|
|
1549
|
+
continue
|
|
1550
|
+
num = _num(val)
|
|
1551
|
+
pv.other_facts.append(v.Fact(label=_s(key, repr(key)), number=num,
|
|
1552
|
+
text="" if num is not None else
|
|
1553
|
+
(_value_text(val) or "")))
|
|
1554
|
+
dd = _d(_get(self.m, "disclosure_diagnostics"))
|
|
1555
|
+
pv.smallest_stored_support = _int(_get(dd, "smallest_stored_support"))
|
|
1556
|
+
nn = _num(_get(dd, "nn_distance_ratio"))
|
|
1557
|
+
if nn is not None:
|
|
1558
|
+
pv.other_facts.append(v.Fact(label="nearest-neighbour distance ratio", number=nn))
|
|
1559
|
+
pv.warnings = [_text(w) for w in _strs(_get(dd, "warnings"))]
|
|
1560
|
+
excluded_notes = _d(_get(self.cdiag, "excluded_columns"))
|
|
1561
|
+
for cv in self.view.columns:
|
|
1562
|
+
c = self.by_name.get(cv.name, {})
|
|
1563
|
+
notes = _strs(_get(c, "notes"))
|
|
1564
|
+
personal = next((n for n in notes if n.startswith(PERSONAL_NOTE)), "")
|
|
1565
|
+
if cv.role in ("pseudonym", "identifier", "reference"):
|
|
1566
|
+
pv.personal.append(v.PersonalColumn(column=cv.name, handling=cv.role,
|
|
1567
|
+
style=cv.stand_in_style or "",
|
|
1568
|
+
reason=_text(personal)))
|
|
1569
|
+
elif cv.role == "excluded":
|
|
1570
|
+
if not personal:
|
|
1571
|
+
personal = next((n for n in _strs(_get(excluded_notes, cv.name))
|
|
1572
|
+
if n.startswith(PERSONAL_NOTE)), "")
|
|
1573
|
+
if personal:
|
|
1574
|
+
pv.personal.append(v.PersonalColumn(column=cv.name, handling="excluded",
|
|
1575
|
+
reason=_text(personal)))
|
|
1576
|
+
if cv.model_kind == "summary" or cv.slab_kind == "summary":
|
|
1577
|
+
pv.coarse_columns.append(cv.name)
|
|
1578
|
+
for name, n in self.pooled.items():
|
|
1579
|
+
col = _s(name, repr(name))
|
|
1580
|
+
pc = self.view.column(col)
|
|
1581
|
+
share = pc.levels.pooled_share if pc is not None and pc.levels is not None else None
|
|
1582
|
+
pv.pooled.append(v.PooledColumn(column=col, n_pooled=_int(n), share=share))
|
|
1583
|
+
|
|
1584
|
+
|
|
1585
|
+
# -- helpers that need no state ---------------------------------------------------------------
|
|
1586
|
+
|
|
1587
|
+
#: evaluated models by spec content (the same spec is often met again: the same fingerprint
|
|
1588
|
+
#: reported twice, or a fuzzed copy of a manifest that shares its arrays)
|
|
1589
|
+
_EVAL_CACHE: OrderedDict[str, tuple[Any, np.ndarray | None, BaseException | None]] = OrderedDict()
|
|
1590
|
+
_EVAL_CACHE_SIZE = 2048
|
|
1591
|
+
#: charts drawn from a cached model with the same settings (handed out as copies)
|
|
1592
|
+
_CHART_CACHE: OrderedDict[str, Any] = OrderedDict()
|
|
1593
|
+
|
|
1594
|
+
|
|
1595
|
+
def _copy_chart(chart: Any) -> Any:
|
|
1596
|
+
from dataclasses import replace
|
|
1597
|
+
|
|
1598
|
+
if isinstance(chart, v.Histogram):
|
|
1599
|
+
return replace(chart, edges=list(chart.edges), shares=list(chart.shares),
|
|
1600
|
+
atoms=[replace(a) for a in chart.atoms],
|
|
1601
|
+
heap_steps=list(chart.heap_steps),
|
|
1602
|
+
quantiles=[list(q) for q in chart.quantiles])
|
|
1603
|
+
if isinstance(chart, v.Levels):
|
|
1604
|
+
return replace(chart, bars=[replace(b) for b in chart.bars])
|
|
1605
|
+
return chart
|
|
1606
|
+
|
|
1607
|
+
|
|
1608
|
+
def _spec_key(kind: str, params: Mapping[str, Any], refs: Mapping[str, Any],
|
|
1609
|
+
arrays: Mapping[str, Any]) -> str | None:
|
|
1610
|
+
import hashlib
|
|
1611
|
+
import json
|
|
1612
|
+
|
|
1613
|
+
try:
|
|
1614
|
+
h = hashlib.sha256(json.dumps([kind, params, sorted((str(k), str(r))
|
|
1615
|
+
for k, r in refs.items())],
|
|
1616
|
+
sort_keys=True, allow_nan=True).encode())
|
|
1617
|
+
for _name, ref in sorted((str(k), r) for k, r in refs.items()):
|
|
1618
|
+
a = _array(arrays, ref)
|
|
1619
|
+
if a is None:
|
|
1620
|
+
h.update(b"-")
|
|
1621
|
+
continue
|
|
1622
|
+
if a.dtype.hasobject:
|
|
1623
|
+
return None
|
|
1624
|
+
h.update(f"{a.dtype.str}{a.shape}".encode())
|
|
1625
|
+
h.update(np.ascontiguousarray(a).tobytes())
|
|
1626
|
+
return h.hexdigest()
|
|
1627
|
+
except Exception:
|
|
1628
|
+
return None
|
|
1629
|
+
|
|
1630
|
+
|
|
1631
|
+
|
|
1632
|
+
def _register_kinds() -> None:
|
|
1633
|
+
"""Make every built-in model kind known (a mutated, merged or calibrated fingerprint uses
|
|
1634
|
+
kinds that only their own modules register). A failure leaves the kinds already known."""
|
|
1635
|
+
try:
|
|
1636
|
+
from ectype.plugins import load_builtin_plugins
|
|
1637
|
+
|
|
1638
|
+
load_builtin_plugins()
|
|
1639
|
+
except Exception: # noqa: BLE001 - the fallback chart covers an unknown kind
|
|
1640
|
+
pass
|
|
1641
|
+
|
|
1642
|
+
|
|
1643
|
+
def _lineage_text(op: Any) -> str:
|
|
1644
|
+
if not isinstance(op, Mapping):
|
|
1645
|
+
return _text(_s(op, "unknown operation"))
|
|
1646
|
+
name = _s(_get(op, "op"), "operation")
|
|
1647
|
+
detail = [f"{k} {_s(val)}" for k, val in op.items()
|
|
1648
|
+
if k not in ("op", "parent", "parents") and isinstance(val, (str, int, float))
|
|
1649
|
+
and not isinstance(val, bool) and len(_s(val)) <= 40][:2]
|
|
1650
|
+
return _text(" ".join([name, *detail]))
|
|
1651
|
+
|
|
1652
|
+
|
|
1653
|
+
def _identity_text(target: str, inputs: Sequence[str], params: Mapping[str, Any]) -> str:
|
|
1654
|
+
op = _s(_get(params, "op"), "?")
|
|
1655
|
+
if len(inputs) == 2:
|
|
1656
|
+
return f"{target} = {inputs[0]} {op} {inputs[1]}"
|
|
1657
|
+
return f"{target} = {op}({', '.join(inputs)})"
|
|
1658
|
+
|
|
1659
|
+
|
|
1660
|
+
def _sum_text(s: Mapping[str, Any]) -> str:
|
|
1661
|
+
"""``total = a + b - c`` (as the engine writes it in its diagnostics)."""
|
|
1662
|
+
parts = _strs(_get(s, "parts"))
|
|
1663
|
+
signs = [-1 if _int(x) == -1 else 1 for x in _l(_get(s, "signs"))]
|
|
1664
|
+
if len(signs) != len(parts):
|
|
1665
|
+
signs = [1] * len(parts)
|
|
1666
|
+
terms = ""
|
|
1667
|
+
for sign, part in zip(signs, parts):
|
|
1668
|
+
terms += (" - " if sign < 0 else (" + " if terms else "")) + part
|
|
1669
|
+
total = _s(_get(s, "total"))
|
|
1670
|
+
if not total:
|
|
1671
|
+
c = _num(_get(s, "constant"))
|
|
1672
|
+
total = f"{c or 0.0:g}"
|
|
1673
|
+
return f"{total} = {terms}"
|
|
1674
|
+
|
|
1675
|
+
|
|
1676
|
+
def _subject(section: str, rec: Mapping[str, Any]) -> str:
|
|
1677
|
+
if section == "structure":
|
|
1678
|
+
return _s(_get(rec, "expression"))
|
|
1679
|
+
if section == "functions":
|
|
1680
|
+
col, base = _s(_get(rec, "column")), _s(_get(rec, "base"))
|
|
1681
|
+
return f"{col} from {base}" if base else col
|
|
1682
|
+
if section == "sums":
|
|
1683
|
+
return _s(_get(rec, "sum")) or _s(_get(rec, "expression"))
|
|
1684
|
+
if section == "entities":
|
|
1685
|
+
attr, key = _s(_get(rec, "attribute")), _s(_get(rec, "key"))
|
|
1686
|
+
return f"{attr} of {key}" if key else attr
|
|
1687
|
+
return _s(_get(rec, "column"))
|
|
1688
|
+
|
|
1689
|
+
|
|
1690
|
+
_BACKTICK = re.compile(r"`([^`]+)`")
|
|
1691
|
+
_WORD = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
|
|
1692
|
+
|
|
1693
|
+
|
|
1694
|
+
def _columns_in(expression: str, columns: Mapping[str, Any]) -> list[str]:
|
|
1695
|
+
"""Column names an expression mentions, in order of first appearance."""
|
|
1696
|
+
found: list[str] = []
|
|
1697
|
+
for m in _BACKTICK.finditer(expression):
|
|
1698
|
+
if m.group(1) in columns and m.group(1) not in found:
|
|
1699
|
+
found.append(m.group(1))
|
|
1700
|
+
bare = _BACKTICK.sub(" ", expression)
|
|
1701
|
+
bare = re.sub(r"'[^']*'", " ", bare)
|
|
1702
|
+
for m in _WORD.finditer(bare):
|
|
1703
|
+
if m.group(0) in columns and m.group(0) not in found:
|
|
1704
|
+
found.append(m.group(0))
|
|
1705
|
+
return found
|
|
1706
|
+
|
|
1707
|
+
|
|
1708
|
+
def _monday_first(profile: Sequence[float]) -> list[float]:
|
|
1709
|
+
"""A profile indexed by day number modulo 7 (day 0 = 1970-01-01, a Thursday), Monday
|
|
1710
|
+
first."""
|
|
1711
|
+
return [float(profile[(i + 4) % 7]) for i in range(7)]
|
|
1712
|
+
|
|
1713
|
+
|
|
1714
|
+
def _log_scale(grid: np.ndarray, axis: str) -> bool:
|
|
1715
|
+
"""Whether a distribution is drawn on a log axis: all values positive, a number or a
|
|
1716
|
+
duration, strongly right-skewed (p95/p05 >= 1000, or the upper tail at least 20 times
|
|
1717
|
+
longer than the lower one)."""
|
|
1718
|
+
if axis not in ("number", "duration") or grid.size == 0 or float(grid[0]) <= 0:
|
|
1719
|
+
return False
|
|
1720
|
+
n = grid.size
|
|
1721
|
+
|
|
1722
|
+
def q(p: float) -> float:
|
|
1723
|
+
return float(grid[min(n - 1, int(p * n))])
|
|
1724
|
+
|
|
1725
|
+
p01, p05, p50, p95, p99 = q(0.01), q(0.05), q(0.5), q(0.95), q(0.99)
|
|
1726
|
+
if p05 > 0 and p95 / p05 >= 1000:
|
|
1727
|
+
return True
|
|
1728
|
+
return p50 > p01 and (p99 - p50) >= 20 * (p50 - p01)
|
|
1729
|
+
|
|
1730
|
+
|
|
1731
|
+
def _number_label(x: float) -> str:
|
|
1732
|
+
if float(x).is_integer():
|
|
1733
|
+
return str(int(x))
|
|
1734
|
+
return f"{x:g}"
|
|
1735
|
+
|
|
1736
|
+
|
|
1737
|
+
def _scrub(obj: Any) -> None:
|
|
1738
|
+
"""Replace every non-finite float in a view (fields and list items) by ``None``."""
|
|
1739
|
+
for name, val in vars(obj).items():
|
|
1740
|
+
if isinstance(val, float):
|
|
1741
|
+
if not math.isfinite(val):
|
|
1742
|
+
setattr(obj, name, None)
|
|
1743
|
+
elif type(val) is list:
|
|
1744
|
+
_scrub_list(val)
|
|
1745
|
+
elif hasattr(type(val), "__dataclass_fields__"):
|
|
1746
|
+
_scrub(val)
|
|
1747
|
+
|
|
1748
|
+
|
|
1749
|
+
def _scrub_list(items: list[Any]) -> None:
|
|
1750
|
+
if not items:
|
|
1751
|
+
return
|
|
1752
|
+
try:
|
|
1753
|
+
if math.isfinite(math.fsum(items)): # a list of finite numbers (the usual case)
|
|
1754
|
+
return
|
|
1755
|
+
except (TypeError, OverflowError, ValueError):
|
|
1756
|
+
pass
|
|
1757
|
+
for i, x in enumerate(items):
|
|
1758
|
+
if isinstance(x, float):
|
|
1759
|
+
if not math.isfinite(x):
|
|
1760
|
+
items[i] = None
|
|
1761
|
+
elif type(x) is list:
|
|
1762
|
+
_scrub_list(x)
|
|
1763
|
+
elif hasattr(type(x), "__dataclass_fields__"):
|
|
1764
|
+
_scrub(x)
|
|
1765
|
+
|
|
1766
|
+
|
|
1767
|
+
__all__ = [
|
|
1768
|
+
"ATOM_MIN_SHARE", "BINS", "GRID", "KNOWN_KEYS", "MATRIX_COLUMNS", "MAX_ATOMS", "MAX_BARS",
|
|
1769
|
+
"MAX_NOTES", "MAX_NOT_APPLIED", "MAX_PAIRS", "MAX_SUGGESTED", "MAX_TEXT", "ROLE_HANDLING",
|
|
1770
|
+
"build_view", "load_view", "view_from_parts",
|
|
1771
|
+
]
|
|
1772
|
+
|
|
1773
|
+
|
|
1774
|
+
# -- comparison of two fingerprints -----------------------------------------------------------
|
|
1775
|
+
# ``compare_view(a, b)``: the view of the comparison page (ADR-0016, section 7). The engine's
|
|
1776
|
+
# drift comparison is read as the JSON-shaped dictionary of ``DriftReport.to_dict()`` (without
|
|
1777
|
+
# ``verbose``, so no target value is ever read: only distances, thresholds, metric names and
|
|
1778
|
+
# counts), through the same total readers as the rest of this module.
|
|
1779
|
+
|
|
1780
|
+
#: drifted column pairs kept in the view (the page says how many there are in all)
|
|
1781
|
+
MAX_DRIFT_PAIRS = 40
|
|
1782
|
+
#: schema notes of the engine kept in the view (then one line with the count of the rest)
|
|
1783
|
+
MAX_DRIFT_NOTES = 20
|
|
1784
|
+
#: category labels named in a change sentence, and the length each is cut to
|
|
1785
|
+
MAX_CHANGE_LABELS = 5
|
|
1786
|
+
CHANGE_LABEL_CHARS = 60
|
|
1787
|
+
#: the sentence for a pseudonymised column (the renderer does not count it as a change)
|
|
1788
|
+
STAND_IN_CHANGE = ("category sets are not compared: the labels are stand-in tokens, assigned "
|
|
1789
|
+
"independently in each fingerprint")
|
|
1790
|
+
|
|
1791
|
+
|
|
1792
|
+
def _loaded(source: Fingerprint | str | os.PathLike[str]) -> tuple[Fingerprint, list[str]]:
|
|
1793
|
+
"""A fingerprint and the warnings the engine gave while loading it (none when ``source``
|
|
1794
|
+
is already loaded). Errors of loading propagate."""
|
|
1795
|
+
if not isinstance(source, str | os.PathLike):
|
|
1796
|
+
return source, []
|
|
1797
|
+
from ectype.fingerprint.core import Fingerprint
|
|
1798
|
+
|
|
1799
|
+
with warnings.catch_warnings(record=True) as caught:
|
|
1800
|
+
warnings.simplefilter("always")
|
|
1801
|
+
fp = Fingerprint.load(source)
|
|
1802
|
+
return fp, [str(w.message) for w in caught if issubclass(w.category, UserWarning)]
|
|
1803
|
+
|
|
1804
|
+
|
|
1805
|
+
def compare_view(a: Fingerprint | str | os.PathLike[str],
|
|
1806
|
+
b: Fingerprint | str | os.PathLike[str], *,
|
|
1807
|
+
sensitivity: str | float = "standard") -> v.DriftView:
|
|
1808
|
+
"""The comparison of two fingerprints (``a`` the reference, ``b`` the candidate; each a
|
|
1809
|
+
loaded fingerprint or the path of a ``.dfp``) as a
|
|
1810
|
+
:class:`~ectype.reporting.view.DriftView`. Errors of loading a path propagate.
|
|
1811
|
+
|
|
1812
|
+
A ``ValueError`` for an unknown ``sensitivity`` propagates (a usage error). Any other
|
|
1813
|
+
failure of the comparison, or of reading its result, becomes an ``Unread`` record
|
|
1814
|
+
(``where="comparison"``) and the view is still built from the two fingerprints' views,
|
|
1815
|
+
with the verdict ``"inconclusive"``. Sealed target values are never read: the result is
|
|
1816
|
+
taken from ``DriftReport.to_dict()`` without ``verbose`` (distances, thresholds, metric
|
|
1817
|
+
names and counts only).
|
|
1818
|
+
"""
|
|
1819
|
+
from ectype.fingerprint.comparison import compare, resolve_sensitivity, sensitivity_label
|
|
1820
|
+
|
|
1821
|
+
resolve_sensitivity(sensitivity) # raises ValueError for a bad value
|
|
1822
|
+
try:
|
|
1823
|
+
label = sensitivity_label(sensitivity)
|
|
1824
|
+
except Exception:
|
|
1825
|
+
label = _s(sensitivity)
|
|
1826
|
+
a, warned_a = _loaded(a)
|
|
1827
|
+
b, warned_b = _loaded(b)
|
|
1828
|
+
va = build_view(a, load_warnings=warned_a)
|
|
1829
|
+
vb = build_view(b, load_warnings=warned_b)
|
|
1830
|
+
out = v.DriftView(a=va, b=vb, sensitivity=label)
|
|
1831
|
+
data: Any = None
|
|
1832
|
+
try:
|
|
1833
|
+
data = compare(a, b, sensitivity=sensitivity).to_dict()
|
|
1834
|
+
except Exception as e:
|
|
1835
|
+
out.unread.append(v.Unread(where="comparison", what="the comparison could not be made",
|
|
1836
|
+
reason=_err(e)))
|
|
1837
|
+
try:
|
|
1838
|
+
_read_comparison(out, data)
|
|
1839
|
+
except Exception as e:
|
|
1840
|
+
out.unread.append(v.Unread(where="comparison", what="could not be read",
|
|
1841
|
+
reason=_err(e)))
|
|
1842
|
+
out.verdict = "inconclusive"
|
|
1843
|
+
out.pairs, out.n_pairs = [], 0
|
|
1844
|
+
try:
|
|
1845
|
+
out.columns = _drift_columns(va, vb, {}, [], [])
|
|
1846
|
+
except Exception: # pragma: no cover - names only
|
|
1847
|
+
out.columns = []
|
|
1848
|
+
try:
|
|
1849
|
+
_scrub(out)
|
|
1850
|
+
except Exception: # pragma: no cover
|
|
1851
|
+
pass
|
|
1852
|
+
return out
|
|
1853
|
+
|
|
1854
|
+
|
|
1855
|
+
def _read_comparison(out: v.DriftView, data: Any) -> None:
|
|
1856
|
+
"""Fill ``out`` from ``DriftReport.to_dict()``. Without a result (``None``) the column list
|
|
1857
|
+
is built from the two views alone and the verdict is inconclusive."""
|
|
1858
|
+
d = _d(data)
|
|
1859
|
+
if data is None or not d:
|
|
1860
|
+
if data is not None:
|
|
1861
|
+
out.unread.append(v.Unread(where="comparison", what="unexpected value",
|
|
1862
|
+
reason=f"expected an object, found {_kind_of(data)}"))
|
|
1863
|
+
out.verdict = "inconclusive"
|
|
1864
|
+
out.columns = _drift_columns(out.a, out.b, {}, [], [])
|
|
1865
|
+
return
|
|
1866
|
+
if _get(d, "drifted") is True:
|
|
1867
|
+
out.verdict = "drift"
|
|
1868
|
+
elif _get(d, "inconclusive") is True or _get(d, "drifted") is not False:
|
|
1869
|
+
out.verdict = "inconclusive"
|
|
1870
|
+
else:
|
|
1871
|
+
out.verdict = "none"
|
|
1872
|
+
decision = _d(_get(d, "decision"))
|
|
1873
|
+
label = _s(_get(decision, "sensitivity"))
|
|
1874
|
+
if label:
|
|
1875
|
+
out.sensitivity = label
|
|
1876
|
+
out.q = _num(_get(decision, "q"))
|
|
1877
|
+
targets = _d(_get(d, "targets"))
|
|
1878
|
+
out.n_targets = _int(_get(targets, "n_matched"))
|
|
1879
|
+
out.n_drifted = _int(_get(targets, "n_drifted"))
|
|
1880
|
+
out.n_errors = len(_l(_get(targets, "errors")))
|
|
1881
|
+
unmatched = _d(_get(targets, "unmatched"))
|
|
1882
|
+
out.only_a = len(_l(_get(unmatched, "only_a")))
|
|
1883
|
+
out.only_b = len(_l(_get(unmatched, "only_b")))
|
|
1884
|
+
schema = _d(_get(d, "schema"))
|
|
1885
|
+
notes = [_text(n) for n in _strs(_get(schema, "notes"))]
|
|
1886
|
+
if len(notes) > MAX_DRIFT_NOTES:
|
|
1887
|
+
rest = len(notes) - MAX_DRIFT_NOTES
|
|
1888
|
+
notes = [*notes[:MAX_DRIFT_NOTES],
|
|
1889
|
+
f"and {rest} more {'note' if rest == 1 else 'notes'} of the engine"]
|
|
1890
|
+
out.notes = notes
|
|
1891
|
+
out.policy_warnings = [_text(w) for w in _strs(_get(d, "policy_warnings"))]
|
|
1892
|
+
results = [_d(r) for r in _l(_get(targets, "results"))]
|
|
1893
|
+
loc = _d(_get(d, "localisation"))
|
|
1894
|
+
ranking = [_d(r) for r in _l(_get(loc, "columns"))]
|
|
1895
|
+
out.columns = _drift_columns(out.a, out.b, schema, ranking, results)
|
|
1896
|
+
pairs = [_d(r) for r in _l(_get(loc, "pairs"))]
|
|
1897
|
+
out.n_pairs = len(pairs)
|
|
1898
|
+
for p in pairs[:MAX_DRIFT_PAIRS]:
|
|
1899
|
+
cols = _strs(_get(p, "columns"))
|
|
1900
|
+
if len(cols) < 2:
|
|
1901
|
+
continue
|
|
1902
|
+
metric, _ = _worst(results, cols)
|
|
1903
|
+
out.pairs.append(v.DriftPair(a=cols[0], b=cols[1], score=_num(_get(p, "score")) or 0.0,
|
|
1904
|
+
n_drifted=_int(_get(p, "n_drifted")) or 0,
|
|
1905
|
+
worst_metric=metric))
|
|
1906
|
+
|
|
1907
|
+
|
|
1908
|
+
def _worst(results: list[Mapping[str, Any]],
|
|
1909
|
+
columns: Sequence[str]) -> tuple[str, float | None]:
|
|
1910
|
+
"""The failed target on exactly ``columns`` furthest beyond its threshold: its metric and
|
|
1911
|
+
``distance / tolerance`` (``None`` when the tolerance is 0 or missing)."""
|
|
1912
|
+
want = list(columns)
|
|
1913
|
+
best_metric, best_ratio, seen = "", None, False
|
|
1914
|
+
for r in results:
|
|
1915
|
+
if _get(r, "passed") is not False or _strs(_get(r, "columns")) != want:
|
|
1916
|
+
continue
|
|
1917
|
+
dist, tol = _num(_get(r, "distance")), _num(_get(r, "tolerance"))
|
|
1918
|
+
ratio = dist / tol if dist is not None and tol is not None and tol > 0 else None
|
|
1919
|
+
if not seen or (ratio is not None and (best_ratio is None or ratio > best_ratio)):
|
|
1920
|
+
best_metric, best_ratio, seen = _s(_get(r, "metric")), ratio, True
|
|
1921
|
+
return best_metric, best_ratio
|
|
1922
|
+
|
|
1923
|
+
|
|
1924
|
+
def _labels_sentence(labels: list[str], side: str) -> str:
|
|
1925
|
+
n = len(labels)
|
|
1926
|
+
shown = ["the pooled bucket of rare values" if lab == POOLED_LABEL
|
|
1927
|
+
else lab if len(lab) <= CHANGE_LABEL_CHARS else lab[: CHANGE_LABEL_CHARS - 1] + "…"
|
|
1928
|
+
for lab in labels[:MAX_CHANGE_LABELS]]
|
|
1929
|
+
text = ", ".join(shown)
|
|
1930
|
+
if n > MAX_CHANGE_LABELS:
|
|
1931
|
+
text += f" and {n - MAX_CHANGE_LABELS} more"
|
|
1932
|
+
what = "1 category appears" if n == 1 else f"{n} categories appear"
|
|
1933
|
+
return f"{what} only in the {side}: {text}"
|
|
1934
|
+
|
|
1935
|
+
|
|
1936
|
+
def _drift_columns(va: v.ReportView, vb: v.ReportView, schema: Mapping[str, Any],
|
|
1937
|
+
ranking: list[Mapping[str, Any]],
|
|
1938
|
+
results: list[Mapping[str, Any]]) -> list[v.DriftColumn]:
|
|
1939
|
+
"""One entry per column of either fingerprint: drifted by score, then changed, added,
|
|
1940
|
+
removed, steady (each in table order: the first's, then the second's)."""
|
|
1941
|
+
names_a = [c.name for c in va.columns if isinstance(c.name, str)]
|
|
1942
|
+
names_b = [c.name for c in vb.columns if isinstance(c.name, str)]
|
|
1943
|
+
set_a, set_b = set(names_a), set(names_b)
|
|
1944
|
+
added = set(_strs(_get(schema, "added"))) | (set_b - set_a)
|
|
1945
|
+
removed = set(_strs(_get(schema, "removed"))) | (set_a - set_b)
|
|
1946
|
+
order: list[str] = []
|
|
1947
|
+
seen: set[str] = set()
|
|
1948
|
+
extra = [*_strs(_get(schema, "added")), *_strs(_get(schema, "removed")),
|
|
1949
|
+
*(_s(_get(r, "column")) for r in ranking)]
|
|
1950
|
+
for n in [*names_a, *names_b, *extra]:
|
|
1951
|
+
if n and n not in seen:
|
|
1952
|
+
seen.add(n)
|
|
1953
|
+
order.append(n)
|
|
1954
|
+
|
|
1955
|
+
changes: dict[str, list[str]] = {}
|
|
1956
|
+
for key, word in (("type_changes", "type"), ("role_changes", "role")):
|
|
1957
|
+
for name, ch in _d(_get(schema, key)).items():
|
|
1958
|
+
x = _s(_get(ch, "a")) or "not recorded"
|
|
1959
|
+
y = _s(_get(ch, "b")) or "not recorded"
|
|
1960
|
+
changes.setdefault(_s(name), []).append(f"{word} changed from {x} to {y}")
|
|
1961
|
+
for name, ch in _d(_get(schema, "category_changes")).items():
|
|
1962
|
+
plus, minus = _strs(_get(ch, "added")), _strs(_get(ch, "removed"))
|
|
1963
|
+
lst = changes.setdefault(_s(name), [])
|
|
1964
|
+
if plus:
|
|
1965
|
+
lst.append(_labels_sentence(plus, "second"))
|
|
1966
|
+
if minus:
|
|
1967
|
+
lst.append(_labels_sentence(minus, "first"))
|
|
1968
|
+
if not plus and not minus:
|
|
1969
|
+
lst.append("the category sets differ")
|
|
1970
|
+
changed = {n for n, lst in changes.items() if lst}
|
|
1971
|
+
for name in _strs(_get(schema, "pseudonymised")):
|
|
1972
|
+
changes.setdefault(name, []).append(STAND_IN_CHANGE)
|
|
1973
|
+
|
|
1974
|
+
rank: dict[str, Mapping[str, Any]] = {}
|
|
1975
|
+
for r in ranking:
|
|
1976
|
+
n = _s(_get(r, "column"))
|
|
1977
|
+
if n and n not in rank:
|
|
1978
|
+
rank[n] = r
|
|
1979
|
+
|
|
1980
|
+
out: list[v.DriftColumn] = []
|
|
1981
|
+
for name in order:
|
|
1982
|
+
r = rank.get(name, {})
|
|
1983
|
+
score = _num(_get(r, "score")) or 0.0
|
|
1984
|
+
dc = v.DriftColumn(name=name, score=max(score, 0.0),
|
|
1985
|
+
n_drifted=_int(_get(r, "n_drifted")) or 0,
|
|
1986
|
+
changes=list(changes.get(name, [])))
|
|
1987
|
+
if name in added and name not in set_a:
|
|
1988
|
+
dc.status = "added"
|
|
1989
|
+
elif name in removed and name not in set_b:
|
|
1990
|
+
dc.status = "removed"
|
|
1991
|
+
elif score > 0:
|
|
1992
|
+
dc.status = "drifted"
|
|
1993
|
+
elif name in changed:
|
|
1994
|
+
dc.status = "changed"
|
|
1995
|
+
if dc.status == "drifted" or dc.n_drifted:
|
|
1996
|
+
dc.worst_metric, dc.worst_ratio = _worst(results, [name])
|
|
1997
|
+
out.append(dc)
|
|
1998
|
+
|
|
1999
|
+
pos = {n: i for i, n in enumerate(order)}
|
|
2000
|
+
rank_of = {"drifted": 0, "changed": 1, "added": 2, "removed": 3, "steady": 4}
|
|
2001
|
+
out.sort(key=lambda c: (rank_of.get(c.status, 4),
|
|
2002
|
+
-c.score if c.status == "drifted" else 0.0, pos[c.name]))
|
|
2003
|
+
return out
|