ectype-data 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. ectype/__init__.py +134 -0
  2. ectype/_version.py +5 -0
  3. ectype/authoring/__init__.py +13 -0
  4. ectype/authoring/builder.py +134 -0
  5. ectype/authoring/spec.py +555 -0
  6. ectype/calibration/__init__.py +26 -0
  7. ectype/calibration/adjustments.py +539 -0
  8. ectype/calibration/calibrator.py +781 -0
  9. ectype/cli.py +1181 -0
  10. ectype/compiler/__init__.py +1 -0
  11. ectype/compiler/plan.py +678 -0
  12. ectype/errors.py +43 -0
  13. ectype/fingerprint/__init__.py +1 -0
  14. ectype/fingerprint/comparison.py +746 -0
  15. ectype/fingerprint/container.py +408 -0
  16. ectype/fingerprint/core.py +263 -0
  17. ectype/fingerprint/disclosure.py +207 -0
  18. ectype/fingerprint/expressions.py +1317 -0
  19. ectype/fingerprint/schema.py +645 -0
  20. ectype/fingerprint/targets.py +352 -0
  21. ectype/generation/__init__.py +1 -0
  22. ectype/generation/enforce.py +163 -0
  23. ectype/generation/generator.py +525 -0
  24. ectype/generation/identifiers.py +235 -0
  25. ectype/generation/manifest.py +71 -0
  26. ectype/generation/parallel.py +229 -0
  27. ectype/io/__init__.py +16 -0
  28. ectype/io/adapters.py +224 -0
  29. ectype/io/sql.py +289 -0
  30. ectype/io/values.py +269 -0
  31. ectype/llm/__init__.py +27 -0
  32. ectype/llm/authoring.py +766 -0
  33. ectype/llm/providers.py +269 -0
  34. ectype/models/__init__.py +8 -0
  35. ectype/models/base.py +120 -0
  36. ectype/models/chain.py +2426 -0
  37. ectype/models/copulas.py +254 -0
  38. ectype/models/encoding.py +1117 -0
  39. ectype/models/forest.py +1087 -0
  40. ectype/models/marginals.py +2099 -0
  41. ectype/models/mixtures.py +336 -0
  42. ectype/models/neural/__init__.py +21 -0
  43. ectype/models/neural/adapter.py +638 -0
  44. ectype/models/neural/vae.py +432 -0
  45. ectype/models/vines.py +608 -0
  46. ectype/plugins.py +40 -0
  47. ectype/privacy/__init__.py +49 -0
  48. ectype/privacy/attacks.py +599 -0
  49. ectype/privacy/dp.py +313 -0
  50. ectype/privacy/report.py +364 -0
  51. ectype/profiler.py +783 -0
  52. ectype/profiling/__init__.py +1 -0
  53. ectype/profiling/bivariate.py +130 -0
  54. ectype/profiling/calendar.py +743 -0
  55. ectype/profiling/conditional.py +263 -0
  56. ectype/profiling/constraints.py +661 -0
  57. ectype/profiling/entity.py +1143 -0
  58. ectype/profiling/functional.py +651 -0
  59. ectype/profiling/multivariate.py +492 -0
  60. ectype/profiling/personal.py +277 -0
  61. ectype/profiling/pseudonym.py +370 -0
  62. ectype/profiling/reference.py +334 -0
  63. ectype/profiling/sketches.py +653 -0
  64. ectype/profiling/structural.py +1087 -0
  65. ectype/profiling/structure.py +1733 -0
  66. ectype/profiling/sums.py +1710 -0
  67. ectype/profiling/tolerance.py +435 -0
  68. ectype/profiling/univariate.py +555 -0
  69. ectype/py.typed +0 -0
  70. ectype/registry.py +48 -0
  71. ectype/relational/__init__.py +61 -0
  72. ectype/relational/container.py +212 -0
  73. ectype/relational/fit.py +633 -0
  74. ectype/relational/generate.py +418 -0
  75. ectype/relational/schema.py +280 -0
  76. ectype/relational/validate.py +288 -0
  77. ectype/reporting/__init__.py +439 -0
  78. ectype/reporting/adapter.py +2003 -0
  79. ectype/reporting/charts.py +964 -0
  80. ectype/reporting/drift.py +902 -0
  81. ectype/reporting/findings.py +622 -0
  82. ectype/reporting/fmt.py +429 -0
  83. ectype/reporting/render.py +1705 -0
  84. ectype/reporting/select.py +84 -0
  85. ectype/reporting/style.py +272 -0
  86. ectype/reporting/view.py +593 -0
  87. ectype/rng.py +33 -0
  88. ectype/scenarios/__init__.py +30 -0
  89. ectype/scenarios/feasibility.py +411 -0
  90. ectype/scenarios/merge.py +1392 -0
  91. ectype/scenarios/mutate.py +1613 -0
  92. ectype/temporal/__init__.py +80 -0
  93. ectype/temporal/contract.py +221 -0
  94. ectype/temporal/detect.py +431 -0
  95. ectype/temporal/events.py +946 -0
  96. ectype/temporal/panel.py +937 -0
  97. ectype/temporal/pipeline.py +192 -0
  98. ectype/temporal/regular.py +674 -0
  99. ectype/types.py +46 -0
  100. ectype/validation/__init__.py +1 -0
  101. ectype/validation/metrics/__init__.py +7 -0
  102. ectype/validation/metrics/base.py +68 -0
  103. ectype/validation/metrics/bivariate.py +353 -0
  104. ectype/validation/metrics/missingness.py +54 -0
  105. ectype/validation/metrics/multivariate.py +265 -0
  106. ectype/validation/metrics/temporal.py +596 -0
  107. ectype/validation/metrics/univariate.py +514 -0
  108. ectype/validation/report.py +627 -0
  109. ectype/validation/validator.py +707 -0
  110. ectype_data-0.1.0.dist-info/METADATA +376 -0
  111. ectype_data-0.1.0.dist-info/RECORD +115 -0
  112. ectype_data-0.1.0.dist-info/WHEEL +4 -0
  113. ectype_data-0.1.0.dist-info/entry_points.txt +2 -0
  114. ectype_data-0.1.0.dist-info/licenses/LICENSE +192 -0
  115. ectype_data-0.1.0.dist-info/licenses/NOTICE +5 -0
@@ -0,0 +1,80 @@
1
+ """Temporal fingerprinting: shape detection, the generation contract and temporal models."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ import polars as pl
8
+
9
+ from ectype.errors import GenerationError, ProfilingError
10
+ from ectype.fingerprint.core import ArrayStore
11
+ from ectype.fingerprint.schema import DisclosurePolicySpec
12
+ from ectype.temporal.contract import TemporalModel, TemporalRequest, time_index
13
+ from ectype.temporal.detect import TemporalShape, detect_periods, detect_temporal_shape
14
+ from ectype.temporal.events import EventModel
15
+ from ectype.temporal.panel import PanelModel
16
+ from ectype.temporal.regular import RegularSeriesModel
17
+
18
+ #: section kind -> model class (each has ``from_section(section, store)``)
19
+ SECTION_KINDS: dict[str, Any] = {
20
+ RegularSeriesModel.kind: RegularSeriesModel,
21
+ PanelModel.kind: PanelModel,
22
+ EventModel.kind: EventModel,
23
+ }
24
+
25
+
26
+ def fit_temporal(df: pl.DataFrame, shape: TemporalShape, value_cols: list[str] | str | None,
27
+ policy: DisclosurePolicySpec | str | None = None, seed: int = 0,
28
+ **kwargs: Any) -> TemporalModel:
29
+ """Fit the temporal model matching ``shape.shape``.
30
+
31
+ * ``"series"`` -> :class:`RegularSeriesModel` (``value_cols`` are numeric series),
32
+ * ``"panel"`` -> :class:`PanelModel` (needs ``shape.entity_col``),
33
+ * ``"events"`` -> :class:`EventModel` (``value_cols`` are the marks; ``shape.entity_col``,
34
+ if any, splits the events into per-entity sequences).
35
+
36
+ Extra keyword arguments go to the model's ``fit``. ``"cross_sectional"`` raises
37
+ :class:`~ectype.errors.ProfilingError`.
38
+ """
39
+ if shape.time_col is None:
40
+ raise ProfilingError("the temporal shape has no time column")
41
+ cols = [] if value_cols is None else ([value_cols] if isinstance(value_cols, str)
42
+ else list(value_cols))
43
+ if shape.shape == "series":
44
+ return RegularSeriesModel().fit(df, shape.time_col, cols, policy, seed, **kwargs)
45
+ if shape.shape == "panel":
46
+ if shape.entity_col is None:
47
+ raise ProfilingError("a panel shape needs an entity column")
48
+ return PanelModel().fit(df, shape.time_col, shape.entity_col, cols, policy, seed,
49
+ **kwargs)
50
+ if shape.shape == "events":
51
+ return EventModel().fit(df, shape.time_col, shape.entity_col, cols, policy, seed,
52
+ **kwargs)
53
+ raise ProfilingError(f"no temporal model for shape {shape.shape!r}: dates in "
54
+ f"cross-sectional data are modeled as ordinary columns")
55
+
56
+
57
+ def temporal_model_from_section(section: dict[str, Any], store: ArrayStore) -> TemporalModel:
58
+ """Rebuild a fitted temporal model from its section, dispatching on ``section["kind"]``."""
59
+ kind = section.get("kind")
60
+ cls = SECTION_KINDS.get(str(kind))
61
+ if cls is None:
62
+ raise GenerationError(f"unknown temporal section kind {kind!r}; expected one of "
63
+ f"{sorted(SECTION_KINDS)}")
64
+ return cls.from_section(section, store) # type: ignore[no-any-return]
65
+
66
+
67
+ __all__ = [
68
+ "SECTION_KINDS",
69
+ "EventModel",
70
+ "PanelModel",
71
+ "RegularSeriesModel",
72
+ "TemporalModel",
73
+ "TemporalRequest",
74
+ "TemporalShape",
75
+ "detect_periods",
76
+ "detect_temporal_shape",
77
+ "fit_temporal",
78
+ "temporal_model_from_section",
79
+ "time_index",
80
+ ]
@@ -0,0 +1,221 @@
1
+ """The temporal generation contract (M18, design doc section 3.5).
2
+
3
+ Generating N rows does not define a temporal simulation. A :class:`TemporalRequest` states:
4
+
5
+ * ``mode``: ``"new_period"`` simulates a period of time (by default the one right after the
6
+ fitted history: trend extrapolation is then an explicit modeling assumption), and
7
+ ``"resample"`` re-simulates the historical window.
8
+ * the window: ``start`` plus ``end`` or ``periods`` (or, with a fixed count, ``n_rows``).
9
+ * ``freq``: a polars duration string; ``None`` means the fitted cadence.
10
+ * ``count_policy``: ``"fixed"`` (exactly ``periods x n_entities`` rows, or ``n_rows``) or
11
+ ``"natural"`` (event models sample the count; regular series still produce one row per
12
+ period and entity).
13
+ * ``n_entities`` and ``warmup_periods`` (extra burn-in steps simulated and discarded before the
14
+ first output step, on top of the model's own minimum). ``n_entities=None`` (the default)
15
+ means "as in the source": panel and event models with an entity column generate as many
16
+ entities as the fitted data had (:meth:`TemporalRequest.with_entities`); models without
17
+ entities generate one stream and warn if another count is requested.
18
+
19
+ Inconsistent requests raise :class:`~ectype.errors.ScenarioError`.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import datetime as dt
25
+ import warnings
26
+ from typing import Any, ClassVar, Literal, Protocol, runtime_checkable
27
+
28
+ import polars as pl
29
+ from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator
30
+
31
+ from ectype.errors import ScenarioError
32
+ from ectype.fingerprint.core import ArrayStore
33
+ from ectype.temporal.detect import is_calendar, parse_duration
34
+
35
+ TimePoint = dt.datetime | dt.date
36
+ #: polars datetime resolutions accepted by ``pl.Datetime`` / ``cast_time_unit``
37
+ TimeUnit = Literal["ns", "us", "ms"]
38
+
39
+
40
+ class TemporalRequest(BaseModel):
41
+ model_config = ConfigDict(extra="forbid")
42
+
43
+ mode: Literal["new_period", "resample"] = "new_period"
44
+ start: TimePoint | None = None
45
+ end: TimePoint | None = None # inclusive
46
+ periods: int | None = Field(default=None, ge=1)
47
+ freq: str | None = None
48
+ count_policy: Literal["fixed", "natural"] = "fixed"
49
+ n_rows: int | None = Field(default=None, ge=1)
50
+ #: ``None``: as many entities as the source (see :meth:`with_entities`)
51
+ n_entities: int | None = Field(default=None, ge=1)
52
+ warmup_periods: int = Field(default=0, ge=0)
53
+
54
+ def __init__(self, **data: Any) -> None:
55
+ try:
56
+ super().__init__(**data)
57
+ except ValidationError as e:
58
+ msgs = "; ".join(f"{'.'.join(str(p) for p in err['loc']) or 'request'}: {err['msg']}"
59
+ for err in e.errors())
60
+ raise ScenarioError(f"invalid temporal request: {msgs}") from None
61
+
62
+ @model_validator(mode="after")
63
+ def _check(self) -> TemporalRequest:
64
+ if self.freq is not None:
65
+ try:
66
+ parse_duration(self.freq)
67
+ except ValueError as e:
68
+ raise ScenarioError(f"invalid temporal request: {e}") from None
69
+ if self.start is not None and self.end is not None and _key(self.end) < _key(self.start):
70
+ raise ScenarioError(f"invalid temporal request: end {self.end} is before start "
71
+ f"{self.start}")
72
+ if self.end is not None and self.start is None and self.mode == "new_period":
73
+ raise ScenarioError("invalid temporal request: 'end' requires 'start' for "
74
+ "new_period generation")
75
+ if self.n_rows is not None and self.count_policy == "natural":
76
+ raise ScenarioError("invalid temporal request: n_rows fixes the row count, which "
77
+ "contradicts count_policy='natural'; drop n_rows or use "
78
+ "count_policy='fixed'")
79
+ # checks that involve the entity count run once it is known: here when it was given,
80
+ # else when a model resolves it from the source (``with_entities``)
81
+ ne = self.n_entities
82
+ if ne is not None and self.n_rows is not None and self.n_rows % ne:
83
+ raise ScenarioError(f"invalid temporal request: n_rows={self.n_rows} is not a "
84
+ f"multiple of n_entities={self.n_entities}")
85
+ if ne is not None and self.n_rows is not None and self.periods is not None \
86
+ and self.n_rows != self.periods * ne:
87
+ raise ScenarioError(f"invalid temporal request: fixed n_rows={self.n_rows} "
88
+ f"conflicts with periods x n_entities = {self.periods} x "
89
+ f"{ne} = {self.periods * ne}")
90
+ if self.start is not None and self.end is not None and self.freq is not None:
91
+ k = len(self.index(self.start, self.freq))
92
+ if self.periods is not None and k != self.periods:
93
+ raise ScenarioError(f"invalid temporal request: start..end at freq "
94
+ f"{self.freq!r} spans {k} periods but periods="
95
+ f"{self.periods}")
96
+ if ne is not None and self.n_rows is not None and self.n_rows != k * ne:
97
+ raise ScenarioError(f"invalid temporal request: fixed n_rows={self.n_rows} "
98
+ f"conflicts with {k} periods ({self.start}..{self.end} at "
99
+ f"{self.freq!r}) x {self.n_entities} entities")
100
+ if self.mode == "new_period" and self.periods is None and self.end is None \
101
+ and self.n_rows is None:
102
+ raise ScenarioError("invalid temporal request: new_period generation needs a "
103
+ "length: give 'periods', 'end' or a fixed 'n_rows'")
104
+ return self
105
+
106
+ # -- resolution --------------------------------------------------------------------------
107
+ def n_periods(self, default: int | None = None) -> int | None:
108
+ """Number of time steps implied by the request (``default`` if unspecified)."""
109
+ if self.periods is not None:
110
+ return self.periods
111
+ if self.n_rows is not None:
112
+ return self.n_rows // (self.n_entities or 1)
113
+ return default
114
+
115
+ def with_entities(self, source_entities: int | None, *, model: str = "this model"
116
+ ) -> TemporalRequest:
117
+ """The request with ``n_entities`` resolved.
118
+
119
+ ``source_entities`` is the fitted model's entity count, or ``None`` for a model without
120
+ entities (a single series or an aggregate event stream): it then resolves to 1, with a
121
+ warning if another count was requested. ``n_entities=None`` resolves to the source
122
+ count. The resolved request is re-validated (e.g. ``n_rows`` must be a multiple of it).
123
+ """
124
+ if source_entities is None:
125
+ if self.n_entities not in (None, 1):
126
+ warnings.warn(f"n_entities={self.n_entities} is ignored: {model} has no entity "
127
+ f"column and generates a single stream", UserWarning,
128
+ stacklevel=3)
129
+ n = 1
130
+ else:
131
+ n = int(self.n_entities) if self.n_entities is not None else max(
132
+ 1, int(source_entities))
133
+ if n == self.n_entities:
134
+ return self
135
+ data = self.model_dump()
136
+ data["n_entities"] = n
137
+ try:
138
+ return TemporalRequest(**data)
139
+ except ScenarioError as e:
140
+ if self.n_entities is None:
141
+ raise ScenarioError(f"{e} (n_entities was not given and defaults to the "
142
+ f"source's {n} entities; pass n_entities explicitly)"
143
+ ) from None
144
+ raise
145
+
146
+ def index(self, start: TimePoint, freq: str, periods: int | None = None) -> pl.Series:
147
+ """Timestamps from ``start`` at ``freq``: ``periods`` of them, or up to ``self.end``."""
148
+ return time_index(start, freq, periods=periods if periods is not None else
149
+ (None if self.end is not None else self.n_periods()),
150
+ end=self.end)
151
+
152
+
153
+ @runtime_checkable
154
+ class TemporalModel(Protocol):
155
+ """What every fitted temporal model provides (regular series, panel, events).
156
+
157
+ ``to_section`` returns a JSON-safe dict ``{"kind": ..., "format": ..., ...}`` whose arrays
158
+ live in ``store``; the class method ``from_section(section, store)`` inverts it.
159
+ """
160
+
161
+ kind: ClassVar[str]
162
+
163
+ def generate(self, request: TemporalRequest, seed: int) -> pl.DataFrame: ...
164
+
165
+ def to_section(self, store: ArrayStore, prefix: str = "temporal.") -> dict[str, Any]: ...
166
+
167
+
168
+ def _key(x: TimePoint) -> dt.datetime:
169
+ if isinstance(x, dt.datetime):
170
+ return x.replace(tzinfo=None)
171
+ return dt.datetime(x.year, x.month, x.day)
172
+
173
+
174
+ def time_index(start: TimePoint, freq: str, *, periods: int | None = None,
175
+ end: TimePoint | None = None, time_unit: TimeUnit = "us",
176
+ time_zone: str | None = None) -> pl.Series:
177
+ """``periods`` timestamps (or all up to ``end`` inclusive) from ``start`` at ``freq``.
178
+
179
+ A ``date`` start with a day-or-coarser frequency yields ``pl.Date``; otherwise
180
+ ``pl.Datetime``.
181
+ """
182
+ parts = parse_duration(freq)
183
+ sub_day = any(u in ("h", "m", "s", "ms", "us", "ns") for _, u in parts)
184
+ as_date = isinstance(start, dt.date) and not isinstance(start, dt.datetime) and not sub_day
185
+ if periods is None and end is None:
186
+ raise ValueError("time_index needs periods or end")
187
+ if periods is not None:
188
+ mult = max(periods - 1, 0)
189
+ last = "".join(f"{n * mult}{u}" for n, u in parts) if mult else None
190
+ s0 = pl.Series("t", [start])
191
+ if not as_date:
192
+ s0 = s0.cast(pl.Datetime(time_unit)) if s0.dtype == pl.Date \
193
+ else s0.dt.cast_time_unit(time_unit)
194
+ # Offset in the output time zone: across a DST transition a naive offset is off
195
+ # by the transition (spring forward would lose a period).
196
+ if time_zone is not None and getattr(s0.dtype, "time_zone", None) is None:
197
+ s0 = s0.dt.replace_time_zone(time_zone, non_existent="raise",
198
+ ambiguous="earliest")
199
+ stop = s0.dt.offset_by(last).item() if last else s0.item()
200
+ else:
201
+ stop = end
202
+ if as_date:
203
+ stop_d = stop.date() if isinstance(stop, dt.datetime) else stop
204
+ out = pl.date_range(start, stop_d, interval=freq, eager=True)
205
+ else:
206
+ st = start if isinstance(start, dt.datetime) else dt.datetime(start.year, start.month,
207
+ start.day)
208
+ sp = stop if isinstance(stop, dt.datetime) else dt.datetime(stop.year, stop.month,
209
+ stop.day)
210
+ if (time_zone is not None and st.tzinfo is None and sp.tzinfo is not None):
211
+ # stop was computed in ``time_zone``: express start in the same zone
212
+ st = pl.Series([st]).dt.cast_time_unit(time_unit).dt.replace_time_zone(
213
+ time_zone, non_existent="raise", ambiguous="earliest").item()
214
+ out = pl.datetime_range(st, sp, interval=freq, eager=True, time_unit=time_unit,
215
+ time_zone=time_zone if st.tzinfo is None else None)
216
+ if periods is not None:
217
+ out = out.head(periods)
218
+ return out.alias("t")
219
+
220
+
221
+ __all__ = ["TemporalModel", "TemporalRequest", "time_index", "is_calendar"]