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,645 @@
|
|
|
1
|
+
"""Pydantic models for the fingerprint manifest (the canonical ``manifest.json``).
|
|
2
|
+
|
|
3
|
+
This module *is* the format contract. Any change here is a format change: it requires an ADR,
|
|
4
|
+
a regenerated JSON Schema (``docs/format/manifest.schema.json``) and a FORMAT_VERSION bump.
|
|
5
|
+
|
|
6
|
+
Design rules
|
|
7
|
+
------------
|
|
8
|
+
* Everything is JSON-safe. Numeric arrays live in the container's ``arrays/`` directory and are
|
|
9
|
+
referenced by relative path through ``ModelSpec.arrays`` / ``ArrayRef``.
|
|
10
|
+
* Model specs are generic (``kind`` + ``params`` + ``arrays``) so plug-ins extend the format
|
|
11
|
+
without schema changes. ``kind`` must resolve through a registry at load time.
|
|
12
|
+
* Sections for later stages (temporal, population, relational) are reserved now so that adding
|
|
13
|
+
them later is a minor, not a major, format change.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import warnings
|
|
19
|
+
from datetime import UTC, datetime
|
|
20
|
+
from typing import Any, Final, Literal, TypeVar
|
|
21
|
+
|
|
22
|
+
from pydantic import (
|
|
23
|
+
BaseModel,
|
|
24
|
+
ConfigDict,
|
|
25
|
+
Field,
|
|
26
|
+
ValidationError,
|
|
27
|
+
field_validator,
|
|
28
|
+
model_validator,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
from ectype._version import FORMAT_VERSION, __version__
|
|
32
|
+
from ectype.types import Enforcement, LogicalType, Role, Severity
|
|
33
|
+
|
|
34
|
+
JSONScalar = str | int | float | bool | None
|
|
35
|
+
JSONValue = Any # recursive JSON values; validated as JSON-serialisable on save
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class _Model(BaseModel):
|
|
39
|
+
model_config = ConfigDict(extra="forbid", populate_by_name=True, use_enum_values=False)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class _OpenModel(BaseModel):
|
|
43
|
+
"""Used for sections where unknown minor-version fields must be tolerated."""
|
|
44
|
+
|
|
45
|
+
model_config = ConfigDict(extra="allow", populate_by_name=True)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
# ---------------------------------------------------------------------------------------------
|
|
49
|
+
# Dataset and schema
|
|
50
|
+
# ---------------------------------------------------------------------------------------------
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class DatasetInfo(_Model):
|
|
54
|
+
name: str = "dataset"
|
|
55
|
+
source_records: int = Field(ge=0)
|
|
56
|
+
source_columns: int = Field(ge=0)
|
|
57
|
+
grain: str | None = None
|
|
58
|
+
description: str | None = None
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class ColumnSchema(_Model):
|
|
62
|
+
"""Inferred (or user-overridden) structural facts about one source column."""
|
|
63
|
+
|
|
64
|
+
name: str
|
|
65
|
+
logical_type: LogicalType
|
|
66
|
+
#: ``pseudonym`` (format 0.4, ADR-0010): a categorical whose stored and generated labels are
|
|
67
|
+
#: stand-in tokens; no source label of the column is in the fingerprint.
|
|
68
|
+
role: Role = Role.FEATURE
|
|
69
|
+
physical_dtype: str # polars dtype string of the source column
|
|
70
|
+
nullable: bool = False
|
|
71
|
+
null_fraction: float = Field(default=0.0, ge=0.0, le=1.0)
|
|
72
|
+
n_unique: int | None = None # may be coarsened by disclosure policy
|
|
73
|
+
decimals: int | None = None # detected rounding precision for numerics
|
|
74
|
+
min_value: float | None = None # support bounds (policy-clipped)
|
|
75
|
+
max_value: float | None = None
|
|
76
|
+
integer_valued: bool = False
|
|
77
|
+
datetime_unit: str | None = None # "us", "ms", "ns", "d" (dates)
|
|
78
|
+
timezone: str | None = None
|
|
79
|
+
is_date: bool = False # pl.Date (vs Datetime)
|
|
80
|
+
pattern: str | None = None # structured-string pattern (diagnostic in v0.1)
|
|
81
|
+
#: Source spellings of a string-coded boolean, as ``(false_label, true_label)`` (e.g.
|
|
82
|
+
#: ``("N", "Y")``), so generated values decode to the source vocabulary. ``None`` for
|
|
83
|
+
#: native booleans, numeric 0/1 flags and fingerprints written before format 0.2.
|
|
84
|
+
bool_labels: tuple[str, str] | None = None
|
|
85
|
+
confidence: float = Field(default=1.0, ge=0.0, le=1.0)
|
|
86
|
+
overridden: bool = False
|
|
87
|
+
notes: list[str] = Field(default_factory=list)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
# ---------------------------------------------------------------------------------------------
|
|
91
|
+
# Disclosure policy (mandatory)
|
|
92
|
+
# ---------------------------------------------------------------------------------------------
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class DisclosurePolicySpec(_Model):
|
|
96
|
+
profile: Literal["strict", "standard", "research", "custom"] = "standard"
|
|
97
|
+
min_category_support: int = Field(default=10, ge=1)
|
|
98
|
+
quantile_resolution: int = Field(default=100, ge=2)
|
|
99
|
+
tail_clip: tuple[float, float] = (0.005, 0.995)
|
|
100
|
+
rare_cell_min: int = Field(default=10, ge=1)
|
|
101
|
+
significant_digits: int = Field(default=6, ge=1)
|
|
102
|
+
identifiers: Literal["regenerate"] = "regenerate"
|
|
103
|
+
sensitive: bool = False # True for the research profile
|
|
104
|
+
|
|
105
|
+
@field_validator("tail_clip")
|
|
106
|
+
@classmethod
|
|
107
|
+
def _check_clip(cls, v: tuple[float, float]) -> tuple[float, float]:
|
|
108
|
+
lo, hi = v
|
|
109
|
+
if not (0.0 <= lo < hi <= 1.0):
|
|
110
|
+
raise ValueError("tail_clip must satisfy 0 <= lo < hi <= 1")
|
|
111
|
+
return v
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class DisclosureDiagnostics(_OpenModel):
|
|
115
|
+
smallest_stored_support: int | None = None
|
|
116
|
+
max_quantiles_per_row: float | None = None # stored quantiles / rows
|
|
117
|
+
pooled_categories: dict[str, int] = Field(default_factory=dict)
|
|
118
|
+
nn_distance_ratio: float | None = None # filled after a test generation
|
|
119
|
+
warnings: list[str] = Field(default_factory=list)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
# ---------------------------------------------------------------------------------------------
|
|
123
|
+
# Models
|
|
124
|
+
# ---------------------------------------------------------------------------------------------
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class ModelSpec(_Model):
|
|
128
|
+
"""Generic serialised model. ``kind`` resolves through a registry; arrays are refs."""
|
|
129
|
+
|
|
130
|
+
kind: str
|
|
131
|
+
params: dict[str, JSONValue] = Field(default_factory=dict)
|
|
132
|
+
arrays: dict[str, str] = Field(default_factory=dict) # logical name -> "arrays/<file>"
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
class DerivedSpec(_Model):
|
|
136
|
+
column: str
|
|
137
|
+
expression: str
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class TransformSpec(_Model):
|
|
141
|
+
"""A structural relationship modeled in value space (format 0.3, ADR-0005).
|
|
142
|
+
|
|
143
|
+
``kind`` is ``"difference"`` (``target = inputs[0] + sign * delta``; the hidden latent
|
|
144
|
+
``params["latent"]`` is modeled in place of the target) or ``"identity"``
|
|
145
|
+
(``target = inputs[0] op inputs[1]``, derived and rounded to ``params["decimals"]``). The
|
|
146
|
+
parameters of each kind are closed: a reader that does not understand one rejects the
|
|
147
|
+
fingerprint at compile time (``profiling.structure.check_transforms``).
|
|
148
|
+
"""
|
|
149
|
+
|
|
150
|
+
kind: str
|
|
151
|
+
target: str
|
|
152
|
+
inputs: list[str]
|
|
153
|
+
params: dict[str, JSONValue] = Field(default_factory=dict)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
class OrderingSpec(_Model):
|
|
157
|
+
"""An ordering enforced on generated rows without a transform (format 0.4, ADR-0009).
|
|
158
|
+
|
|
159
|
+
``target`` is at least every ``lower`` column and at most every ``upper`` column. The target
|
|
160
|
+
keeps its own marginal and its slot in the joint model; a generated row that breaks the
|
|
161
|
+
ordering gets a new target value from that marginal truncated to the allowed side of the
|
|
162
|
+
bound (``method``; see ``profiling.structure.redraw``). ``strict`` excludes ties.
|
|
163
|
+
``source`` and ``constraints`` are informational: where the ordering came from and the
|
|
164
|
+
confirmed constraints or suggestions that state it. A reader that does not know
|
|
165
|
+
``method`` rejects the fingerprint at compile time.
|
|
166
|
+
"""
|
|
167
|
+
|
|
168
|
+
target: str
|
|
169
|
+
lower: list[str] = Field(default_factory=list)
|
|
170
|
+
upper: list[str] = Field(default_factory=list)
|
|
171
|
+
method: str = "reflect"
|
|
172
|
+
strict: bool = False
|
|
173
|
+
source: str | None = None
|
|
174
|
+
constraints: list[str] = Field(default_factory=list)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
class CalendarSpec(_Model):
|
|
178
|
+
"""The weekly pattern of a date column, restored on generated rows (format 0.4, ADR-0012).
|
|
179
|
+
|
|
180
|
+
``column`` is a generated date, timestamp or whole-number column whose values are days
|
|
181
|
+
(``unit``: ``"d"`` for dates, ``"us"`` for timestamps, read as whole UTC days, ``"num"``
|
|
182
|
+
for day numbers). The *slot* of a value is its day number modulo ``period`` (7; day 0 is
|
|
183
|
+
1970-01-01, a Thursday). Right after decoding, transforms and orderings, a row is moved
|
|
184
|
+
by whole days to a slot drawn from row ``slot`` of ``kernel``, a ``period`` x ``period``
|
|
185
|
+
table of probabilities (``method``; see ``profiling.calendar.snap``). ``profile`` is the
|
|
186
|
+
share of rows per slot the kernel aims at. ``anchors`` are the columns the value is tied
|
|
187
|
+
to: a row that equals an anchor before the move equals it afterwards, and a row that is
|
|
188
|
+
before (after) an anchor stays before (after) it. ``base`` is the anchor the value was
|
|
189
|
+
computed from (the base of its ``difference`` transform): the value first takes that
|
|
190
|
+
column's move along, so their gap is kept. A spec without a kernel only follows its
|
|
191
|
+
anchors. Specs run in the listed order, an anchor before the columns tied to it. A reader
|
|
192
|
+
that does not know ``method`` or ``period`` rejects the fingerprint at compile time.
|
|
193
|
+
"""
|
|
194
|
+
|
|
195
|
+
column: str
|
|
196
|
+
period: int = 7
|
|
197
|
+
unit: str = "d"
|
|
198
|
+
method: str = "transport"
|
|
199
|
+
profile: list[float] = Field(default_factory=list)
|
|
200
|
+
kernel: list[list[float]] = Field(default_factory=list)
|
|
201
|
+
anchors: list[str] = Field(default_factory=list)
|
|
202
|
+
base: str | None = None
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
class EntityAttribute(_Model):
|
|
206
|
+
"""One attribute of an entity group (:class:`EntitySpec`).
|
|
207
|
+
|
|
208
|
+
``values`` and ``state`` name two arrays aligned with the group's ``keys``: for key ``i``,
|
|
209
|
+
``state[i]`` is ``1`` when the attribute is ``values[i]``, ``2`` when it is empty (null) and
|
|
210
|
+
``0`` when the table has no entry. ``missing_state`` / ``missing_value`` are the same pair
|
|
211
|
+
for a row whose key is empty.
|
|
212
|
+
|
|
213
|
+
A row without an entry keeps the value the model generated when that value is one the
|
|
214
|
+
source rows without an entry hold: a label in ``rest_levels`` (a text array), or an empty
|
|
215
|
+
cell when ``rest_null`` is positive. Any other value belongs to entities that have an
|
|
216
|
+
entry, and is replaced by a draw from ``rest_levels`` with the probabilities
|
|
217
|
+
``rest_probs`` (an aligned array; with ``rest_null`` they sum to 1). Without
|
|
218
|
+
``rest_levels`` the generated value is always kept.
|
|
219
|
+
"""
|
|
220
|
+
|
|
221
|
+
column: str
|
|
222
|
+
values: str
|
|
223
|
+
state: str
|
|
224
|
+
missing_state: int = Field(default=0, ge=0, le=2)
|
|
225
|
+
missing_value: str | None = None
|
|
226
|
+
rest_levels: str | None = None
|
|
227
|
+
rest_probs: str | None = None
|
|
228
|
+
rest_null: float = Field(default=0.0, ge=0.0, le=1.0)
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
class EntityAnchor(_Model):
|
|
232
|
+
"""The column the key of an entity group follows (:class:`EntitySpec`).
|
|
233
|
+
|
|
234
|
+
``values`` and ``state`` are the anchor's value per key, as for an attribute. The anchor
|
|
235
|
+
is not overwritten: a generated row whose key has an entry for *another* anchor value than
|
|
236
|
+
the row holds gets a key drawn among the keys of its own anchor value, by their
|
|
237
|
+
frequencies in the key's marginal (the pooled key ``"__other__"`` when no key has that
|
|
238
|
+
value). Only where the anchor says nothing is it filled in: a row whose anchor is empty
|
|
239
|
+
while its key has a value for it (and no key has an empty one) takes the key's entry, and
|
|
240
|
+
a row whose key is empty takes ``missing_value`` or an empty cell when ``missing_state``
|
|
241
|
+
says so, as an attribute does.
|
|
242
|
+
"""
|
|
243
|
+
|
|
244
|
+
column: str
|
|
245
|
+
values: str
|
|
246
|
+
state: str
|
|
247
|
+
missing_state: int = Field(default=0, ge=0, le=2)
|
|
248
|
+
missing_value: str | None = None
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
class EntitySpec(_Model):
|
|
252
|
+
"""A key column and the columns that are attributes of the entity it names (format 0.4,
|
|
253
|
+
ADR-0013): each value of ``key`` has one value of each attribute.
|
|
254
|
+
|
|
255
|
+
Every column of a group is generated by the model as it would be without the group. The
|
|
256
|
+
group is a step after decoding: the key is made to agree with the ``anchor`` (when there
|
|
257
|
+
is one), then each attribute of a row is replaced by the entry of its key in the group's
|
|
258
|
+
table (``keys`` is a text array of key labels; see :class:`EntityAttribute`), and a row
|
|
259
|
+
without an entry is kept from carrying a value of an entity that has one. Specs are
|
|
260
|
+
listed in the order they run: the key of a group may be an attribute of an earlier one.
|
|
261
|
+
``method`` is closed: a reader that does not know it rejects the fingerprint at compile
|
|
262
|
+
time.
|
|
263
|
+
"""
|
|
264
|
+
|
|
265
|
+
key: str
|
|
266
|
+
keys: str
|
|
267
|
+
attributes: list[EntityAttribute] = Field(default_factory=list)
|
|
268
|
+
anchor: EntityAnchor | None = None
|
|
269
|
+
method: str = "lookup"
|
|
270
|
+
source: str | None = None
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
class SumSpec(_Model):
|
|
274
|
+
"""A total and the parts that add up to it (format 0.4, ADR-0014).
|
|
275
|
+
|
|
276
|
+
``total`` is a column, or ``None`` when the parts add up to ``constant`` (shares that sum
|
|
277
|
+
to 1, percentages that sum to 100). ``mode`` says what is computed after decoding
|
|
278
|
+
(``profiling.sums.apply_sums``):
|
|
279
|
+
|
|
280
|
+
``"split"``
|
|
281
|
+
The parts are computed from the total and a composition. Each part with a latent
|
|
282
|
+
(``latents``, hidden columns named ``__share__<part>``) has its share of the total
|
|
283
|
+
modeled in place of itself: the latent has the marginal, the encoding and the slot in
|
|
284
|
+
the joint model, the part has none. With one part there is no latent (the part is a
|
|
285
|
+
copy of the total); with two, only the first part has one and the second is the
|
|
286
|
+
remainder; with more, every part has one and the shares are scaled to add up to 1.
|
|
287
|
+
``"scale"``
|
|
288
|
+
The parts are modeled columns (they keep their marginals), and their decoded values
|
|
289
|
+
are scaled to add up to the total: the weight of a part is its own decoded value.
|
|
290
|
+
``"sum"``
|
|
291
|
+
The total is computed as ``sum(signs[i] * parts[i])`` (``signs`` empty: all ``+1``)
|
|
292
|
+
and rounded to ``decimals``; it has no marginal of its own.
|
|
293
|
+
|
|
294
|
+
In the first two modes ``rounding`` ``"exact"`` allocates the total in units of
|
|
295
|
+
``10 ** -decimals`` by the largest-remainder rule, so the parts add up exactly;
|
|
296
|
+
``"independent"`` rounds each part on its own, as published percentages are, and the sum
|
|
297
|
+
holds within ``tolerance``. ``fallback`` holds the mean share of each part: the weights of
|
|
298
|
+
a row whose own weights are all zero, and the share of the total a missing part takes
|
|
299
|
+
with it.
|
|
300
|
+
|
|
301
|
+
``zero_as_null`` lists the columns of the sum in which an empty cell stands for zero: a
|
|
302
|
+
null input counts as 0 and a computed 0 is written as null. ``tolerance`` is the largest
|
|
303
|
+
``abs(total - sum)`` that counts as holding when the sum is checked. ``source`` and
|
|
304
|
+
``constraint`` are informational. A reader that does not know ``mode`` or ``rounding``
|
|
305
|
+
rejects the fingerprint at compile time (``profiling.sums.check_sums``).
|
|
306
|
+
"""
|
|
307
|
+
|
|
308
|
+
total: str | None = None
|
|
309
|
+
constant: float | None = None
|
|
310
|
+
parts: list[str]
|
|
311
|
+
signs: list[int] = Field(default_factory=list)
|
|
312
|
+
mode: str = "split"
|
|
313
|
+
latents: list[str] = Field(default_factory=list)
|
|
314
|
+
decimals: int | None = None
|
|
315
|
+
rounding: str = "exact"
|
|
316
|
+
tolerance: float = 0.0
|
|
317
|
+
zero_as_null: list[str] = Field(default_factory=list)
|
|
318
|
+
fallback: list[float] = Field(default_factory=list)
|
|
319
|
+
source: str = "detected"
|
|
320
|
+
constraint: str | None = None
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
class ModelSection(_Model):
|
|
324
|
+
marginals: dict[str, ModelSpec] = Field(default_factory=dict)
|
|
325
|
+
encodings: dict[str, ModelSpec] = Field(default_factory=dict)
|
|
326
|
+
joint: ModelSpec | None = None
|
|
327
|
+
conditional: dict[str, ModelSpec] = Field(default_factory=dict) # Phase 2
|
|
328
|
+
missingness: dict[str, ModelSpec] = Field(default_factory=dict)
|
|
329
|
+
identifiers: dict[str, ModelSpec] = Field(default_factory=dict)
|
|
330
|
+
constants: dict[str, JSONValue] = Field(default_factory=dict)
|
|
331
|
+
derived: list[DerivedSpec] = Field(default_factory=list)
|
|
332
|
+
#: Structural transforms, in topological order (format 0.3). Empty for older files.
|
|
333
|
+
transforms: list[TransformSpec] = Field(default_factory=list)
|
|
334
|
+
#: Orderings enforced by a truncated redraw of their target (format 0.4). Empty for older
|
|
335
|
+
#: files.
|
|
336
|
+
orderings: list[OrderingSpec] = Field(default_factory=list)
|
|
337
|
+
#: Weekly patterns of date columns, restored after decoding (format 0.4, ADR-0012), in
|
|
338
|
+
#: the order they run. Empty for older files.
|
|
339
|
+
calendars: list[CalendarSpec] = Field(default_factory=list)
|
|
340
|
+
#: Entity groups (format 0.4, ADR-0013): attribute columns looked up from a key column, in
|
|
341
|
+
#: the order they run. Empty for older files.
|
|
342
|
+
entities: list[EntitySpec] = Field(default_factory=list)
|
|
343
|
+
#: Reference keys (format 0.4, ADR-0013): how the surrogate values of each ``reference``
|
|
344
|
+
#: column are written. Empty for older files.
|
|
345
|
+
references: dict[str, ModelSpec] = Field(default_factory=dict)
|
|
346
|
+
#: Totals and their parts (format 0.4, ADR-0014), in the order they run after decoding.
|
|
347
|
+
#: Empty for older files.
|
|
348
|
+
sums: list[SumSpec] = Field(default_factory=list)
|
|
349
|
+
column_order: list[str] = Field(default_factory=list)
|
|
350
|
+
generation_order: list[str] = Field(
|
|
351
|
+
default_factory=lambda: ["joint", "transforms", "conditional", "identifiers",
|
|
352
|
+
"derived", "missingness", "constraints"]
|
|
353
|
+
)
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
# ---------------------------------------------------------------------------------------------
|
|
357
|
+
# Constraints
|
|
358
|
+
# ---------------------------------------------------------------------------------------------
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
class ConstraintSpec(_Model):
|
|
362
|
+
id: str
|
|
363
|
+
expression: str
|
|
364
|
+
severity: Severity = Severity.HARD
|
|
365
|
+
enforcement: Enforcement = Enforcement.REJECTION
|
|
366
|
+
tolerance: float = 0.0
|
|
367
|
+
source: Literal["user", "confirmed_suggestion"] = "user"
|
|
368
|
+
description: str | None = None
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
class SuggestedConstraint(_Model):
|
|
372
|
+
id: str
|
|
373
|
+
expression: str
|
|
374
|
+
family: str # "ordering", "bound", "identity", "fd", ...
|
|
375
|
+
support: int
|
|
376
|
+
violations: int = 0
|
|
377
|
+
candidates_screened: int = 1
|
|
378
|
+
confidence: float = Field(ge=0.0, le=1.0)
|
|
379
|
+
confidence_label: Literal["low", "medium", "high"] = "low"
|
|
380
|
+
evidence: dict[str, JSONValue] = Field(default_factory=dict)
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
class ConstraintsSection(_Model):
|
|
384
|
+
confirmed: list[ConstraintSpec] = Field(default_factory=list)
|
|
385
|
+
suggested: list[SuggestedConstraint] = Field(default_factory=list)
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
# ---------------------------------------------------------------------------------------------
|
|
389
|
+
# Targets (stored in targets/*.json, summarised here)
|
|
390
|
+
# ---------------------------------------------------------------------------------------------
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
class Target(_Model):
|
|
394
|
+
"""One measured property of the source, with uncertainty and tolerance."""
|
|
395
|
+
|
|
396
|
+
id: str
|
|
397
|
+
metric: str # registry key, e.g. "univariate.wasserstein"
|
|
398
|
+
columns: list[str]
|
|
399
|
+
value: JSONValue # scalar, list or dict depending on metric
|
|
400
|
+
ci: tuple[float, float] | None = None
|
|
401
|
+
tolerance: float | None = None
|
|
402
|
+
params: dict[str, JSONValue] = Field(default_factory=dict)
|
|
403
|
+
family: str = "" # partition unit, e.g. "bivariate.spearman"
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
class TargetSet(_Model):
|
|
407
|
+
kind: Literal["calibration", "sealed"]
|
|
408
|
+
targets: list[Target] = Field(default_factory=list)
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
CALIBRATION_REF: Final = "targets/calibration.json"
|
|
412
|
+
SEALED_REF: Final = "targets/sealed.json"
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
class TargetsSection(_Model):
|
|
416
|
+
# Fixed paths: a manifest cannot redirect calibration to the sealed file (or vice versa).
|
|
417
|
+
calibration_ref: Literal["targets/calibration.json"] = CALIBRATION_REF
|
|
418
|
+
sealed_ref: Literal["targets/sealed.json"] = SEALED_REF
|
|
419
|
+
seal_hash: str # sha256 of sealed.json bytes, committed at fit
|
|
420
|
+
n_calibration: int = 0
|
|
421
|
+
n_sealed: int = 0
|
|
422
|
+
sealed_families: list[str] = Field(default_factory=list)
|
|
423
|
+
sealed_fraction: float = Field(default=0.3, ge=0.0, le=1.0)
|
|
424
|
+
partition_seed: int = 0
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
# ---------------------------------------------------------------------------------------------
|
|
428
|
+
# Provenance / generation defaults / reserved sections
|
|
429
|
+
# ---------------------------------------------------------------------------------------------
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
def _utcnow() -> str:
|
|
433
|
+
return datetime.now(UTC).replace(microsecond=0).isoformat()
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
class Provenance(_OpenModel):
|
|
437
|
+
created_at: str = Field(default_factory=_utcnow)
|
|
438
|
+
engine_version: str = __version__
|
|
439
|
+
dependencies: dict[str, str] = Field(default_factory=dict)
|
|
440
|
+
config: dict[str, JSONValue] = Field(default_factory=dict)
|
|
441
|
+
config_hash: str | None = None
|
|
442
|
+
fit_seed: int | None = None
|
|
443
|
+
lineage: list[dict[str, JSONValue]] = Field(default_factory=list) # mutate/merge parents
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
class GenerationDefaults(_Model):
|
|
447
|
+
default_seed: int = 42
|
|
448
|
+
chunk_size: int = 100_000
|
|
449
|
+
max_rejection_rounds: int = 50
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
class ReservedSection(_OpenModel):
|
|
453
|
+
"""Placeholder for stage-2+ sections (temporal, population, relational)."""
|
|
454
|
+
|
|
455
|
+
enabled: bool = False
|
|
456
|
+
|
|
457
|
+
# Declared so type checkers accept the extra (``extra="allow"``) fields; pydantic's
|
|
458
|
+
# synthesized signature only lists ``enabled``.
|
|
459
|
+
def __init__(self, /, **data: Any) -> None:
|
|
460
|
+
super().__init__(**data)
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
#: first format version with ``model.transforms`` (ADR-0005)
|
|
464
|
+
TRANSFORMS_SINCE: Final = (0, 3)
|
|
465
|
+
#: first format version with ``model.orderings`` and signed ``difference`` latents (ADR-0009)
|
|
466
|
+
ORDERINGS_SINCE: Final = (0, 4)
|
|
467
|
+
#: first format version with ``model.calendars`` (ADR-0012)
|
|
468
|
+
CALENDARS_SINCE: Final = (0, 4)
|
|
469
|
+
#: first format version with the ``pseudonym`` column role (ADR-0010)
|
|
470
|
+
PSEUDONYM_SINCE: Final = (0, 4)
|
|
471
|
+
#: first format version with ``model.entities``, ``model.references`` and the ``reference``
|
|
472
|
+
#: column role (ADR-0013)
|
|
473
|
+
ENTITIES_SINCE: Final = (0, 4)
|
|
474
|
+
#: first format version with ``model.sums`` (ADR-0014)
|
|
475
|
+
SUMS_SINCE: Final = (0, 4)
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
def _version_tuple(version: str) -> tuple[int, int] | None:
|
|
479
|
+
parts = str(version).split(".")
|
|
480
|
+
if len(parts) != 3 or not all(p.isdigit() for p in parts):
|
|
481
|
+
return None
|
|
482
|
+
return int(parts[0]), int(parts[1])
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
class Manifest(_Model):
|
|
486
|
+
fingerprint_version: str = FORMAT_VERSION
|
|
487
|
+
dataset: DatasetInfo
|
|
488
|
+
columns: list[ColumnSchema]
|
|
489
|
+
disclosure_policy: DisclosurePolicySpec
|
|
490
|
+
disclosure_diagnostics: DisclosureDiagnostics = Field(default_factory=DisclosureDiagnostics)
|
|
491
|
+
model: ModelSection = Field(default_factory=ModelSection)
|
|
492
|
+
constraints: ConstraintsSection = Field(default_factory=ConstraintsSection)
|
|
493
|
+
targets: TargetsSection
|
|
494
|
+
diagnostics: dict[str, JSONValue] = Field(default_factory=dict)
|
|
495
|
+
provenance: Provenance = Field(default_factory=Provenance)
|
|
496
|
+
generation: GenerationDefaults = Field(default_factory=GenerationDefaults)
|
|
497
|
+
temporal: ReservedSection | None = None
|
|
498
|
+
population: ReservedSection | None = None
|
|
499
|
+
relational: ReservedSection | None = None
|
|
500
|
+
extensions: dict[str, JSONValue] = Field(default_factory=dict)
|
|
501
|
+
|
|
502
|
+
@model_validator(mode="after")
|
|
503
|
+
def _features_need_their_version(self) -> Manifest:
|
|
504
|
+
"""A manifest may not use a feature newer than the version it declares: a reader of
|
|
505
|
+
that version would reject it, so the file is mislabeled. (Unparsable versions are
|
|
506
|
+
reported by the container's version check.)"""
|
|
507
|
+
parsed = _version_tuple(self.fingerprint_version)
|
|
508
|
+
if parsed is None:
|
|
509
|
+
return self
|
|
510
|
+
if self.model.transforms and parsed < TRANSFORMS_SINCE:
|
|
511
|
+
raise ValueError(
|
|
512
|
+
f"model.transforms requires fingerprint_version >= "
|
|
513
|
+
f"{'.'.join(map(str, TRANSFORMS_SINCE))} (the manifest declares "
|
|
514
|
+
f"{self.fingerprint_version})")
|
|
515
|
+
if parsed < ORDERINGS_SINCE:
|
|
516
|
+
since = ".".join(map(str, ORDERINGS_SINCE))
|
|
517
|
+
if self.model.orderings:
|
|
518
|
+
raise ValueError(
|
|
519
|
+
f"model.orderings requires fingerprint_version >= {since} (the manifest "
|
|
520
|
+
f"declares {self.fingerprint_version})")
|
|
521
|
+
if any(t.params.get("signed") for t in self.model.transforms):
|
|
522
|
+
raise ValueError(
|
|
523
|
+
f"a signed difference transform requires fingerprint_version >= {since} "
|
|
524
|
+
f"(the manifest declares {self.fingerprint_version})")
|
|
525
|
+
if self.model.calendars and parsed < CALENDARS_SINCE:
|
|
526
|
+
raise ValueError(
|
|
527
|
+
f"model.calendars requires fingerprint_version >= "
|
|
528
|
+
f"{'.'.join(map(str, CALENDARS_SINCE))} (the manifest declares "
|
|
529
|
+
f"{self.fingerprint_version})")
|
|
530
|
+
if self.model.sums and parsed < SUMS_SINCE:
|
|
531
|
+
raise ValueError(
|
|
532
|
+
f"model.sums requires fingerprint_version >= "
|
|
533
|
+
f"{'.'.join(map(str, SUMS_SINCE))} (the manifest declares "
|
|
534
|
+
f"{self.fingerprint_version})")
|
|
535
|
+
pseudonyms = [c.name for c in self.columns if c.role == Role.PSEUDONYM]
|
|
536
|
+
if pseudonyms and parsed < PSEUDONYM_SINCE:
|
|
537
|
+
raise ValueError(
|
|
538
|
+
f"the 'pseudonym' column role (column(s) {pseudonyms}) requires "
|
|
539
|
+
f"fingerprint_version >= {'.'.join(map(str, PSEUDONYM_SINCE))} (the "
|
|
540
|
+
f"manifest declares {self.fingerprint_version})")
|
|
541
|
+
references = [c.name for c in self.columns if c.role == Role.REFERENCE]
|
|
542
|
+
if parsed < ENTITIES_SINCE:
|
|
543
|
+
since = ".".join(map(str, ENTITIES_SINCE))
|
|
544
|
+
if self.model.entities or self.model.references:
|
|
545
|
+
raise ValueError(
|
|
546
|
+
f"model.entities and model.references require fingerprint_version >= "
|
|
547
|
+
f"{since} (the manifest declares {self.fingerprint_version})")
|
|
548
|
+
if references:
|
|
549
|
+
raise ValueError(
|
|
550
|
+
f"the 'reference' column role (column(s) {references}) requires "
|
|
551
|
+
f"fingerprint_version >= {since} (the manifest declares "
|
|
552
|
+
f"{self.fingerprint_version})")
|
|
553
|
+
return self
|
|
554
|
+
|
|
555
|
+
@model_validator(mode="after")
|
|
556
|
+
def _references_are_counts(self) -> Manifest:
|
|
557
|
+
"""A reference column is modeled by the number of rows that share its value
|
|
558
|
+
(ADR-0013): a discrete column with a surrogate-key spec."""
|
|
559
|
+
bad = [c.name for c in self.columns if c.role == Role.REFERENCE
|
|
560
|
+
and c.logical_type != LogicalType.DISCRETE]
|
|
561
|
+
if bad:
|
|
562
|
+
raise ValueError(f"reference column(s) {bad} must have logical_type 'discrete'")
|
|
563
|
+
roles = {c.name: c.role for c in self.columns}
|
|
564
|
+
stray = sorted(c for c in self.model.references if roles.get(c) != Role.REFERENCE)
|
|
565
|
+
if stray:
|
|
566
|
+
raise ValueError(f"model.references names column(s) {stray} that do not have the "
|
|
567
|
+
f"role 'reference'")
|
|
568
|
+
return self
|
|
569
|
+
|
|
570
|
+
@model_validator(mode="after")
|
|
571
|
+
def _pseudonyms_are_categorical(self) -> Manifest:
|
|
572
|
+
"""A pseudonym is a categorical whose labels are tokens (ADR-0010)."""
|
|
573
|
+
bad = [c.name for c in self.columns if c.role == Role.PSEUDONYM
|
|
574
|
+
and c.logical_type != LogicalType.CATEGORICAL]
|
|
575
|
+
if bad:
|
|
576
|
+
raise ValueError(f"pseudonym column(s) {bad} must have logical_type "
|
|
577
|
+
f"'categorical'")
|
|
578
|
+
return self
|
|
579
|
+
|
|
580
|
+
def column(self, name: str) -> ColumnSchema:
|
|
581
|
+
for c in self.columns:
|
|
582
|
+
if c.name == name:
|
|
583
|
+
return c
|
|
584
|
+
raise KeyError(name)
|
|
585
|
+
|
|
586
|
+
@property
|
|
587
|
+
def column_names(self) -> list[str]:
|
|
588
|
+
return [c.name for c in self.columns]
|
|
589
|
+
|
|
590
|
+
|
|
591
|
+
_M = TypeVar("_M", bound=BaseModel)
|
|
592
|
+
_MAX_STRIP_ROUNDS = 32
|
|
593
|
+
|
|
594
|
+
|
|
595
|
+
def validate_lenient(model: type[_M], raw: Any, *, lenient: bool, what: str) -> _M:
|
|
596
|
+
"""Validate ``raw`` against ``model``.
|
|
597
|
+
|
|
598
|
+
Strict unless ``lenient`` (a newer *minor* format version, design section 4.4): then keys
|
|
599
|
+
the model does not know are stripped (recursively) before validation and reported with
|
|
600
|
+
``warnings.warn``. Any other validation problem raises ``FingerprintError``.
|
|
601
|
+
"""
|
|
602
|
+
from ectype.errors import FingerprintError
|
|
603
|
+
|
|
604
|
+
stripped: list[str] = []
|
|
605
|
+
for _ in range(_MAX_STRIP_ROUNDS):
|
|
606
|
+
try:
|
|
607
|
+
obj = model.model_validate(raw)
|
|
608
|
+
break
|
|
609
|
+
except ValidationError as e:
|
|
610
|
+
extra = [err["loc"] for err in e.errors() if err["type"] == "extra_forbidden"]
|
|
611
|
+
if not lenient or not extra or len(extra) != len(e.errors()):
|
|
612
|
+
raise FingerprintError(f"{what} failed schema validation:\n{e}") from None
|
|
613
|
+
for loc in extra:
|
|
614
|
+
if _drop_path(raw, loc):
|
|
615
|
+
stripped.append(".".join(str(x) for x in loc))
|
|
616
|
+
else: # pragma: no cover - pathological nesting
|
|
617
|
+
raise FingerprintError(f"{what} failed schema validation: too many unknown fields")
|
|
618
|
+
if stripped:
|
|
619
|
+
warnings.warn(
|
|
620
|
+
f"{what} was written by a newer minor format version; ignoring unknown "
|
|
621
|
+
f"field(s): {', '.join(sorted(stripped))}", UserWarning, stacklevel=3)
|
|
622
|
+
return obj
|
|
623
|
+
|
|
624
|
+
|
|
625
|
+
def _drop_path(raw: Any, loc: tuple[int | str, ...]) -> bool:
|
|
626
|
+
node = raw
|
|
627
|
+
for key in loc[:-1]:
|
|
628
|
+
if isinstance(node, dict) and key in node:
|
|
629
|
+
node = node[key]
|
|
630
|
+
elif isinstance(node, list) and isinstance(key, int) and 0 <= key < len(node):
|
|
631
|
+
node = node[key]
|
|
632
|
+
else:
|
|
633
|
+
return False
|
|
634
|
+
if isinstance(node, dict) and loc and loc[-1] in node:
|
|
635
|
+
del node[loc[-1]]
|
|
636
|
+
return True
|
|
637
|
+
return False
|
|
638
|
+
|
|
639
|
+
|
|
640
|
+
def manifest_json_schema() -> dict[str, Any]:
|
|
641
|
+
"""The published JSON Schema for ``manifest.json``."""
|
|
642
|
+
schema = Manifest.model_json_schema()
|
|
643
|
+
schema["$id"] = f"urn:ectype:manifest:{FORMAT_VERSION}"
|
|
644
|
+
schema["title"] = "ectype fingerprint manifest"
|
|
645
|
+
return schema
|