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
ectype/models/vines.py ADDED
@@ -0,0 +1,608 @@
1
+ """Regular-vine copula (kind ``"vine_copula"``) over latent standard-normal scores.
2
+
3
+ The model works on pseudo-observations ``u = Phi(z)`` and returns ``z = Phi^-1(u)``, so the
4
+ output marginals are exactly N(0, 1).
5
+
6
+ * **Structure (Dissmann et al. 2013).** Tree 1 is the maximum spanning tree on ``|tau|``
7
+ (Kendall) between variables. Tree ``t`` connects edges of tree ``t-1`` that share a node
8
+ (proximity condition) and is again a maximum spanning tree on ``|tau|`` of the conditional
9
+ pseudo-observations. Trees beyond ``trunc_level`` (default 3) are independence: they are not
10
+ stored at all (a *truncated* R-vine).
11
+ * **Pair families.** Independence, Gaussian, Student-t, Frank, and Clayton and Gumbel with
12
+ rotations 0/90/180/270, chosen per edge by AIC. A Kendall-tau independence pre-test
13
+ (``indep_level``) assigns independence to clearly unrelated pairs.
14
+ * **h-functions.** ``h(u|v) = dC(u, v)/dv`` and their inverses are implemented in numpy /
15
+ ``scipy.special`` (closed forms, except Gumbel's inverse: vectorised bisection on the normal
16
+ scale).
17
+ * **Sampling.** Inverse Rosenblatt: variables are peeled off as leaves of the (truncated) vine,
18
+ then drawn in reverse order, each by inverting its chain of h-functions given the
19
+ conditional pseudo-observations of the already-drawn variables.
20
+
21
+ The spec stores the structure (edges as ``[a, b, conditioning]`` column indices), families and
22
+ rotations in ``params`` and the pair parameters (coarsened) as an ``(E, 2)`` array.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import heapq
28
+ import math
29
+ from dataclasses import dataclass
30
+ from typing import Any
31
+
32
+ import numpy as np
33
+ from scipy import integrate, optimize, special, stats
34
+
35
+ from ectype.fingerprint.core import ArrayStore
36
+ from ectype.fingerprint.disclosure import coarsen
37
+ from ectype.fingerprint.schema import DisclosurePolicySpec, ModelSpec
38
+ from ectype.models.base import JOINTS, JointModel
39
+ from ectype.models.copulas import _check_z
40
+
41
+ EPS = 1e-12
42
+ FAMILIES = ("independence", "gaussian", "student_t", "clayton", "gumbel", "frank")
43
+ DEFAULT_FAMILIES = ("gaussian", "student_t", "clayton", "gumbel", "frank")
44
+ ROTATED = ("clayton", "gumbel")
45
+ N_PARAMS = {"independence": 0, "gaussian": 1, "student_t": 2, "clayton": 1, "gumbel": 1,
46
+ "frank": 1}
47
+ MAX_FIT_ROWS = 10_000
48
+ _TRANSPOSE = {0: 0, 90: 270, 180: 180, 270: 90}
49
+
50
+
51
+ def _clip(u: np.ndarray) -> np.ndarray:
52
+ return np.clip(np.asarray(u, dtype=np.float64), EPS, 1.0 - EPS)
53
+
54
+
55
+ # ---------------------------------------------------------------------------------------------
56
+ # Base (unrotated, exchangeable) families: h(u|v) = dC/dv, its inverse, and log density
57
+ # ---------------------------------------------------------------------------------------------
58
+
59
+ def _t_scale(y: np.ndarray, rho: float, nu: float) -> np.ndarray:
60
+ return np.sqrt((nu + y * y) * (1.0 - rho * rho) / (nu + 1.0))
61
+
62
+
63
+ def _gumbel_log_h(u: np.ndarray, v: np.ndarray, th: float) -> np.ndarray:
64
+ x, y = -np.log(u), -np.log(v)
65
+ ls = np.logaddexp(th * np.log(x), th * np.log(y))
66
+ a = np.exp(ls / th)
67
+ return -a + (1.0 / th - 1.0) * ls + (th - 1.0) * np.log(y) + y
68
+
69
+
70
+ def _log_abs_expm1(x: np.ndarray) -> np.ndarray:
71
+ """``log|e^x - 1|`` without overflow for large positive ``x``."""
72
+ x = np.asarray(x, dtype=np.float64)
73
+ pos = x > 0
74
+ with np.errstate(divide="ignore"):
75
+ return np.where(pos, x + np.log(-np.expm1(-np.abs(x))), np.log(-np.expm1(-np.abs(x))))
76
+
77
+
78
+ def _base_h(fam: str, u: np.ndarray, v: np.ndarray, p1: float, p2: float) -> np.ndarray:
79
+ u, v = _clip(u), _clip(v)
80
+ if fam == "independence":
81
+ return u
82
+ if fam == "gaussian":
83
+ return special.ndtr((special.ndtri(u) - p1 * special.ndtri(v)) / math.sqrt(1 - p1 * p1))
84
+ if fam == "student_t":
85
+ x, y = special.stdtrit(p2, u), special.stdtrit(p2, v)
86
+ return special.stdtr(p2 + 1.0, (x - p1 * y) / _t_scale(y, p1, p2))
87
+ if fam == "clayton":
88
+ lu, lv = np.log(u), np.log(v)
89
+ s = np.logaddexp(-p1 * lu, -p1 * lv)
90
+ big_l = s + np.log1p(-np.exp(-s))
91
+ return np.exp((-p1 - 1.0) * lv + (-1.0 - 1.0 / p1) * big_l)
92
+ if fam == "gumbel":
93
+ return np.exp(_gumbel_log_h(u, v, p1))
94
+ if fam == "frank":
95
+ # h = 1 / (1 + r) with r = -e^{tv} expm1(t(u-1)) / expm1(tu) >= 0 for either sign of t;
96
+ # in log space this has no cancellation at large |theta| (the textbook
97
+ # (b+1) a / (expm1(-t) + a b) form loses digits when the denominator nearly cancels)
98
+ log_r = (p1 * v + _log_abs_expm1(p1 * (u - 1.0)) - _log_abs_expm1(p1 * u))
99
+ return special.expit(-log_r)
100
+ raise ValueError(f"unknown pair-copula family {fam!r}")
101
+
102
+
103
+ def _base_hinv(fam: str, p: np.ndarray, v: np.ndarray, p1: float, p2: float) -> np.ndarray:
104
+ p, v = _clip(p), _clip(v)
105
+ if fam == "independence":
106
+ return p
107
+ if fam == "gaussian":
108
+ return special.ndtr(special.ndtri(p) * math.sqrt(1 - p1 * p1) + p1 * special.ndtri(v))
109
+ if fam == "student_t":
110
+ y = special.stdtrit(p2, v)
111
+ return special.stdtr(p2, special.stdtrit(p2 + 1.0, p) * _t_scale(y, p1, p2) + p1 * y)
112
+ if fam == "clayton":
113
+ lp, lv = np.log(p), np.log(v)
114
+ t = (-p1 / (1.0 + p1)) * (lp + (p1 + 1.0) * lv)
115
+ log_w = t + np.log1p(np.exp(-t) - np.exp((p1 / (1.0 + p1)) * lp))
116
+ return np.exp(-log_w / p1)
117
+ if fam == "frank":
118
+ # u = -log(1 + a) / theta with a = p (e^-t - 1) / (1 + (1 - p)(e^-tv - 1)). In closed
119
+ # form 1 + a = ((1-p) e^-tv + p e^-t) / ((1-p) e^-tv + p); evaluating both sums in log
120
+ # space avoids the cancellation in 1 + a near 0 at large |theta|.
121
+ lp, lq = np.log(p), np.log1p(-p)
122
+ log_num = np.logaddexp(lq - p1 * v, lp - p1)
123
+ log_den = np.logaddexp(lq - p1 * v, lp)
124
+ return -(log_num - log_den) / p1
125
+ if fam == "gumbel":
126
+ lo = np.full(p.shape, -9.0)
127
+ hi = np.full(p.shape, 9.0)
128
+ lp = np.log(p)
129
+ for _ in range(56):
130
+ mid = 0.5 * (lo + hi)
131
+ up = _gumbel_log_h(_clip(special.ndtr(mid)), v, p1) < lp
132
+ lo = np.where(up, mid, lo)
133
+ hi = np.where(up, hi, mid)
134
+ return special.ndtr(0.5 * (lo + hi))
135
+ raise ValueError(f"unknown pair-copula family {fam!r}")
136
+
137
+
138
+ def _base_logc(fam: str, u: np.ndarray, v: np.ndarray, p1: float, p2: float) -> np.ndarray:
139
+ u, v = _clip(u), _clip(v)
140
+ if fam == "independence":
141
+ return np.zeros(np.broadcast(u, v).shape)
142
+ if fam == "gaussian":
143
+ x, y = special.ndtri(u), special.ndtri(v)
144
+ r2 = 1.0 - p1 * p1
145
+ return -0.5 * math.log(r2) - (p1 * p1 * (x * x + y * y) - 2 * p1 * x * y) / (2 * r2)
146
+ if fam == "student_t":
147
+ nu, rho = p2, p1
148
+ x, y = special.stdtrit(nu, u), special.stdtrit(nu, v)
149
+ r2 = 1.0 - rho * rho
150
+ log2 = (special.gammaln((nu + 2) / 2) - special.gammaln(nu / 2) - math.log(nu * math.pi)
151
+ - 0.5 * math.log(r2)
152
+ - (nu + 2) / 2 * np.log1p((x * x - 2 * rho * x * y + y * y) / (nu * r2)))
153
+ c1 = special.gammaln((nu + 1) / 2) - special.gammaln(nu / 2) - 0.5 * math.log(nu * math.pi)
154
+ log1 = 2 * c1 - (nu + 1) / 2 * (np.log1p(x * x / nu) + np.log1p(y * y / nu))
155
+ return log2 - log1
156
+ if fam == "clayton":
157
+ lu, lv = np.log(u), np.log(v)
158
+ s = np.logaddexp(-p1 * lu, -p1 * lv)
159
+ big_l = s + np.log1p(-np.exp(-s))
160
+ return math.log1p(p1) + (-p1 - 1.0) * (lu + lv) + (-2.0 - 1.0 / p1) * big_l
161
+ if fam == "gumbel":
162
+ x, y = -np.log(u), -np.log(v)
163
+ lx, ly = np.log(x), np.log(y)
164
+ ls = np.logaddexp(p1 * lx, p1 * ly)
165
+ a = np.exp(ls / p1)
166
+ return (-a + x + y + (p1 - 1.0) * (lx + ly) + (1.0 / p1 - 2.0) * ls
167
+ + np.log(a + p1 - 1.0))
168
+ if fam == "frank":
169
+ cm = -np.expm1(-p1)
170
+ den = cm - np.expm1(-p1 * u) * np.expm1(-p1 * v)
171
+ return math.log(p1 * cm) - p1 * (u + v) - 2.0 * np.log(np.abs(den))
172
+ raise ValueError(f"unknown pair-copula family {fam!r}")
173
+
174
+
175
+ # ---------------------------------------------------------------------------------------------
176
+ # Rotations
177
+ # ---------------------------------------------------------------------------------------------
178
+
179
+ def pair_h(fam: str, rot: int, u: np.ndarray, v: np.ndarray, p1: float, p2: float
180
+ ) -> np.ndarray:
181
+ """``h(u|v) = dC_rot(u, v)/dv`` (the conditional CDF of the first argument)."""
182
+ u, v = _clip(u), _clip(v)
183
+ if rot == 0:
184
+ return _base_h(fam, u, v, p1, p2)
185
+ if rot == 90:
186
+ return 1.0 - _base_h(fam, 1.0 - u, v, p1, p2)
187
+ if rot == 180:
188
+ return 1.0 - _base_h(fam, 1.0 - u, 1.0 - v, p1, p2)
189
+ if rot == 270:
190
+ return _base_h(fam, u, 1.0 - v, p1, p2)
191
+ raise ValueError(f"invalid rotation {rot}")
192
+
193
+
194
+ def pair_hinv(fam: str, rot: int, p: np.ndarray, v: np.ndarray, p1: float, p2: float
195
+ ) -> np.ndarray:
196
+ """Inverse of :func:`pair_h` in its first argument."""
197
+ p, v = _clip(p), _clip(v)
198
+ if rot == 0:
199
+ return _base_hinv(fam, p, v, p1, p2)
200
+ if rot == 90:
201
+ return 1.0 - _base_hinv(fam, 1.0 - p, v, p1, p2)
202
+ if rot == 180:
203
+ return 1.0 - _base_hinv(fam, 1.0 - p, 1.0 - v, p1, p2)
204
+ if rot == 270:
205
+ return _base_hinv(fam, p, 1.0 - v, p1, p2)
206
+ raise ValueError(f"invalid rotation {rot}")
207
+
208
+
209
+ def pair_logc(fam: str, rot: int, u: np.ndarray, v: np.ndarray, p1: float, p2: float
210
+ ) -> np.ndarray:
211
+ u, v = _clip(u), _clip(v)
212
+ if rot == 0:
213
+ return _base_logc(fam, u, v, p1, p2)
214
+ if rot == 90:
215
+ return _base_logc(fam, 1.0 - u, v, p1, p2)
216
+ if rot == 180:
217
+ return _base_logc(fam, 1.0 - u, 1.0 - v, p1, p2)
218
+ if rot == 270:
219
+ return _base_logc(fam, u, 1.0 - v, p1, p2)
220
+ raise ValueError(f"invalid rotation {rot}")
221
+
222
+
223
+ def _debye1(x: float) -> float:
224
+ if abs(x) < 1e-8:
225
+ return 1.0
226
+ val, _ = integrate.quad(lambda t: t / math.expm1(t) if t != 0 else 1.0, 0.0, x)
227
+ return val / x
228
+
229
+
230
+ def pair_tau(fam: str, rot: int, p1: float, p2: float = 0.0) -> float:
231
+ """Kendall's tau implied by a (rotated) pair copula."""
232
+ if fam == "independence":
233
+ tau = 0.0
234
+ elif fam in ("gaussian", "student_t"):
235
+ tau = 2.0 / math.pi * math.asin(p1)
236
+ elif fam == "clayton":
237
+ tau = p1 / (p1 + 2.0)
238
+ elif fam == "gumbel":
239
+ tau = 1.0 - 1.0 / p1
240
+ elif fam == "frank":
241
+ tau = 1.0 - 4.0 / p1 * (1.0 - _debye1(p1))
242
+ else:
243
+ raise ValueError(f"unknown pair-copula family {fam!r}")
244
+ return -tau if rot in (90, 270) else tau
245
+
246
+
247
+ def pair_lower_tail(fam: str, rot: int, p1: float, p2: float = 0.0) -> float:
248
+ """Lower tail-dependence coefficient lambda_L of the (rotated) pair copula."""
249
+ if fam == "student_t":
250
+ return float(2.0 * special.stdtr(p2 + 1.0,
251
+ -math.sqrt((p2 + 1.0) * (1 - p1) / (1 + p1))))
252
+ if fam == "clayton" and rot == 0:
253
+ return 2.0 ** (-1.0 / p1)
254
+ if fam == "gumbel" and rot == 180:
255
+ return 2.0 - 2.0 ** (1.0 / p1)
256
+ return 0.0
257
+
258
+
259
+ # ---------------------------------------------------------------------------------------------
260
+ # Pair-copula fitting
261
+ # ---------------------------------------------------------------------------------------------
262
+
263
+ @dataclass
264
+ class PairCopula:
265
+ family: str = "independence"
266
+ rotation: int = 0
267
+ p1: float = 0.0
268
+ p2: float = 0.0
269
+ loglik: float = 0.0
270
+ aic: float = 0.0
271
+
272
+ def h1(self, u: np.ndarray, v: np.ndarray) -> np.ndarray:
273
+ """F(first | second)."""
274
+ return pair_h(self.family, self.rotation, u, v, self.p1, self.p2)
275
+
276
+ def h2(self, v: np.ndarray, u: np.ndarray) -> np.ndarray:
277
+ """F(second | first)."""
278
+ return pair_h(self.family, _TRANSPOSE[self.rotation], v, u, self.p1, self.p2)
279
+
280
+ def hinv1(self, p: np.ndarray, v: np.ndarray) -> np.ndarray:
281
+ return pair_hinv(self.family, self.rotation, p, v, self.p1, self.p2)
282
+
283
+ def hinv2(self, p: np.ndarray, u: np.ndarray) -> np.ndarray:
284
+ return pair_hinv(self.family, _TRANSPOSE[self.rotation], p, u, self.p1, self.p2)
285
+
286
+ def logc(self, u: np.ndarray, v: np.ndarray) -> np.ndarray:
287
+ return pair_logc(self.family, self.rotation, u, v, self.p1, self.p2)
288
+
289
+ @property
290
+ def tau(self) -> float:
291
+ return pair_tau(self.family, self.rotation, self.p1, self.p2)
292
+
293
+
294
+ def _nll(fam: str, rot: int, u: np.ndarray, v: np.ndarray, p1: float, p2: float) -> float:
295
+ with np.errstate(all="ignore"):
296
+ ll = pair_logc(fam, rot, u, v, p1, p2)
297
+ s = float(np.sum(ll))
298
+ return -s if math.isfinite(s) else 1e300
299
+
300
+
301
+ def _fit_one(fam: str, rot: int, u: np.ndarray, v: np.ndarray, tau: float
302
+ ) -> tuple[float, float, float]:
303
+ """MLE for one (family, rotation). Returns ``(p1, p2, loglik)``."""
304
+ opts = {"xatol": 1e-4}
305
+ if fam == "gaussian":
306
+ r = optimize.minimize_scalar(lambda x: _nll(fam, rot, u, v, x, 0.0),
307
+ bounds=(-0.995, 0.995), method="bounded", options=opts)
308
+ return float(r.x), 0.0, -float(r.fun)
309
+ if fam == "student_t":
310
+ rho = float(np.clip(math.sin(math.pi * tau / 2.0), -0.995, 0.995))
311
+ r = optimize.minimize_scalar(lambda ln: _nll(fam, rot, u, v, rho, math.exp(ln)),
312
+ bounds=(math.log(2.1), math.log(50.0)), method="bounded",
313
+ options=opts)
314
+ return rho, float(math.exp(r.x)), -float(r.fun)
315
+ if fam == "clayton":
316
+ bounds = (1e-3, 28.0)
317
+ elif fam == "gumbel":
318
+ bounds = (1.0 + 1e-4, 20.0)
319
+ elif fam == "frank":
320
+ bounds = (1e-3, 35.0) if tau >= 0 else (-35.0, -1e-3)
321
+ else:
322
+ raise ValueError(fam)
323
+ r = optimize.minimize_scalar(lambda x: _nll(fam, rot, u, v, x, 0.0), bounds=bounds,
324
+ method="bounded", options=opts)
325
+ return float(r.x), 0.0, -float(r.fun)
326
+
327
+
328
+ def _kendall_tau(u: np.ndarray, v: np.ndarray) -> float:
329
+ t = stats.kendalltau(u, v).statistic
330
+ return 0.0 if not np.isfinite(t) else float(t)
331
+
332
+
333
+ def fit_pair(u: np.ndarray, v: np.ndarray, *, families: tuple[str, ...] = DEFAULT_FAMILIES,
334
+ indep_level: float | None = 0.05, tau: float | None = None) -> PairCopula:
335
+ """Select the pair-copula family/rotation by AIC (independence has AIC 0)."""
336
+ u, v = _clip(u), _clip(v)
337
+ n = len(u)
338
+ tau = _kendall_tau(u, v) if tau is None else tau
339
+ best = PairCopula()
340
+ if n < 3:
341
+ return best
342
+ if indep_level is not None:
343
+ stat = abs(tau) * math.sqrt(9.0 * n * (n - 1) / (2.0 * (2 * n + 5)))
344
+ if 2.0 * special.ndtr(-stat) > indep_level:
345
+ return best
346
+ for fam in families:
347
+ rots = ((0, 180) if tau >= 0 else (90, 270)) if fam in ROTATED else (0,)
348
+ for rot in rots:
349
+ p1, p2, ll = _fit_one(fam, rot, u, v, tau)
350
+ aic = 2.0 * N_PARAMS[fam] - 2.0 * ll
351
+ if aic < best.aic:
352
+ best = PairCopula(fam, rot, p1, p2, ll, aic)
353
+ return best
354
+
355
+
356
+ # ---------------------------------------------------------------------------------------------
357
+ # Vine structure
358
+ # ---------------------------------------------------------------------------------------------
359
+
360
+ @dataclass
361
+ class VineEdge:
362
+ tree: int # 1-based tree level
363
+ a: int
364
+ b: int
365
+ cond: tuple[int, ...] # sorted conditioning set
366
+ pair: PairCopula
367
+
368
+ @property
369
+ def all_vars(self) -> frozenset[int]:
370
+ return frozenset((self.a, self.b, *self.cond))
371
+
372
+
373
+ def _key(var: int, cond: frozenset[int] | set[int] | tuple[int, ...]) -> tuple[int, frozenset[int]]:
374
+ return var, frozenset(cond)
375
+
376
+
377
+ def _max_spanning_tree(m: int, cands: list[tuple[float, int, int, Any]]) -> list[Any]:
378
+ """Prim's algorithm on a candidate edge list ``(weight, i, j, payload)``; returns
379
+ payloads of the chosen edges. Ties break deterministically on candidate order."""
380
+ adj: dict[int, list[tuple[float, int, int, int]]] = {i: [] for i in range(m)}
381
+ for idx, (w, i, j, _) in enumerate(cands):
382
+ adj[i].append((-w, idx, i, j))
383
+ adj[j].append((-w, idx, j, i))
384
+ seen = {0}
385
+ heap = list(adj[0])
386
+ heapq.heapify(heap)
387
+ chosen = []
388
+ while heap and len(seen) < m:
389
+ _, idx, _, j = heapq.heappop(heap)
390
+ if j in seen:
391
+ continue
392
+ seen.add(j)
393
+ chosen.append(cands[idx][3])
394
+ for item in adj[j]:
395
+ if item[3] not in seen:
396
+ heapq.heappush(heap, item)
397
+ if len(seen) < m:
398
+ raise RuntimeError("vine candidate graph is disconnected")
399
+ return chosen
400
+
401
+
402
+ def _peel_order(d: int, edges: list[VineEdge]) -> tuple[list[int], dict[int, list[VineEdge]]]:
403
+ """Leaf-peeling order and each variable's chain of edges (ascending tree)."""
404
+ remaining = list(edges)
405
+ alive = set(range(d))
406
+ order: list[int] = []
407
+ chains: dict[int, list[VineEdge]] = {}
408
+ while alive:
409
+ pick = None
410
+ for x in sorted(alive):
411
+ mine = [e for e in remaining if x in (e.a, e.b)]
412
+ if any(x in e.cond for e in remaining):
413
+ continue
414
+ levels = sorted(e.tree for e in mine)
415
+ if levels != list(range(1, len(levels) + 1)):
416
+ continue
417
+ if len(alive) > 1 and any(e.tree == 1 for e in remaining) and not levels:
418
+ continue
419
+ pick = (x, sorted(mine, key=lambda e: e.tree))
420
+ break
421
+ if pick is None:
422
+ raise RuntimeError("invalid vine structure: no leaf to peel")
423
+ x, chain = pick
424
+ order.append(x)
425
+ chains[x] = chain
426
+ ids = {id(e) for e in chain}
427
+ remaining = [e for e in remaining if id(e) not in ids]
428
+ alive.discard(x)
429
+ return order, chains
430
+
431
+
432
+ # ---------------------------------------------------------------------------------------------
433
+ # The joint model
434
+ # ---------------------------------------------------------------------------------------------
435
+
436
+ @JOINTS.register()
437
+ class VineCopula(JointModel):
438
+ kind = "vine_copula"
439
+
440
+ def __init__(self, columns: list[str], edges: list[VineEdge], trunc_level: int = 3) -> None:
441
+ self.columns = list(columns)
442
+ self.edges = sorted(edges, key=lambda e: (e.tree, e.a, e.b))
443
+ self.trunc_level = int(trunc_level)
444
+ d = len(self.columns)
445
+ for e in self.edges:
446
+ if not (0 <= e.a < d and 0 <= e.b < d) or any(not 0 <= c < d for c in e.cond):
447
+ raise ValueError("vine edge refers to an unknown column")
448
+ if e.pair.family not in FAMILIES or e.pair.rotation not in _TRANSPOSE:
449
+ raise ValueError(f"invalid pair copula {e.pair.family}/{e.pair.rotation}")
450
+ self._order, self._chains = _peel_order(d, self.edges)
451
+
452
+ # -- fitting ------------------------------------------------------------------------------
453
+ @classmethod
454
+ def fit(cls, z: np.ndarray, columns: list[str], *, policy: DisclosurePolicySpec,
455
+ rng: np.random.Generator | None = None, trunc_level: int = 3,
456
+ families: tuple[str, ...] | list[str] = DEFAULT_FAMILIES,
457
+ indep_level: float | None = 0.05, **kwargs: Any) -> VineCopula:
458
+ """Fit a truncated R-vine by Dissmann's algorithm.
459
+
460
+ Extra keywords (e.g. ``attenuation``) are accepted for interface compatibility and
461
+ ignored: pair-copula parameters are not linear in the latent correlation.
462
+ """
463
+ z = _check_z(z, columns)
464
+ rng = rng if rng is not None else np.random.default_rng(0)
465
+ n, d = z.shape
466
+ fams = tuple(f for f in families if f != "independence")
467
+ if any(f not in FAMILIES for f in fams):
468
+ raise ValueError(f"unknown families in {families}")
469
+ if n > MAX_FIT_ROWS:
470
+ z = z[np.sort(rng.choice(n, MAX_FIT_ROWS, replace=False))]
471
+ u = _clip(special.ndtr(z))
472
+ pseudo: dict[tuple[int, frozenset[int]], np.ndarray] = {
473
+ _key(j, ()): u[:, j] for j in range(d)}
474
+ edges: list[VineEdge] = []
475
+ prev: list[VineEdge] = []
476
+ for t in range(1, min(max(int(trunc_level), 0), d - 1) + 1):
477
+ cands: list[tuple[float, int, int, Any]] = []
478
+ if t == 1:
479
+ for i in range(d):
480
+ for j in range(i + 1, d):
481
+ tau = _kendall_tau(u[:, i], u[:, j])
482
+ cands.append((abs(tau), i, j, (i, j, (), tau)))
483
+ m = d
484
+ else:
485
+ m = len(prev)
486
+ for i in range(m):
487
+ for j in range(i + 1, m):
488
+ si, sj = prev[i].all_vars, prev[j].all_vars
489
+ common = si & sj
490
+ if len(common) != t - 1:
491
+ continue
492
+ (a,), (b,) = tuple(si - common), tuple(sj - common)
493
+ a, b = min(a, b), max(a, b)
494
+ cond = tuple(sorted(common))
495
+ tau = _kendall_tau(pseudo[_key(a, cond)], pseudo[_key(b, cond)])
496
+ cands.append((abs(tau), i, j, (a, b, cond, tau)))
497
+ tree: list[VineEdge] = []
498
+ for a, b, cond, tau in _max_spanning_tree(m, cands):
499
+ ua, ub = pseudo[_key(a, cond)], pseudo[_key(b, cond)]
500
+ pair = fit_pair(ua, ub, families=fams, indep_level=indep_level, tau=tau)
501
+ pair = cls._coarsen_pair(pair, policy)
502
+ edge = VineEdge(t, a, b, cond, pair)
503
+ pseudo[_key(a, (*cond, b))] = pair.h1(ua, ub)
504
+ pseudo[_key(b, (*cond, a))] = pair.h2(ub, ua)
505
+ tree.append(edge)
506
+ edges.extend(tree)
507
+ prev = tree
508
+ return cls(columns, edges, trunc_level=int(trunc_level))
509
+
510
+ @staticmethod
511
+ def _coarsen_pair(pair: PairCopula, policy: DisclosurePolicySpec) -> PairCopula:
512
+ p1 = coarsen(pair.p1, policy) if pair.p1 else 0.0
513
+ p2 = coarsen(pair.p2, policy) if pair.p2 else 0.0
514
+ if pair.family in ("gaussian", "student_t"):
515
+ p1 = float(np.clip(p1, -0.995, 0.995))
516
+ elif pair.family == "gumbel":
517
+ p1 = max(p1, 1.0 + 1e-4)
518
+ elif pair.family == "clayton":
519
+ p1 = max(p1, 1e-3)
520
+ elif pair.family == "frank" and p1 == 0.0:
521
+ return PairCopula()
522
+ return PairCopula(pair.family, pair.rotation, p1, p2, pair.loglik, pair.aic)
523
+
524
+ # -- density ------------------------------------------------------------------------------
525
+ def copula_logpdf(self, u: np.ndarray) -> np.ndarray:
526
+ """Log copula density at pseudo-observations ``u`` (n, d)."""
527
+ u = _clip(u)
528
+ pseudo = {_key(j, ()): u[:, j] for j in range(u.shape[1])}
529
+ out = np.zeros(len(u))
530
+ for e in self.edges: # sorted by tree, so inputs exist
531
+ ua, ub = pseudo[_key(e.a, e.cond)], pseudo[_key(e.b, e.cond)]
532
+ out += e.pair.logc(ua, ub)
533
+ pseudo[_key(e.a, (*e.cond, e.b))] = e.pair.h1(ua, ub)
534
+ pseudo[_key(e.b, (*e.cond, e.a))] = e.pair.h2(ub, ua)
535
+ return out
536
+
537
+ def logpdf(self, z: np.ndarray) -> np.ndarray:
538
+ """Log density of latent scores (vine copula with N(0, 1) margins)."""
539
+ z = np.asarray(z, dtype=np.float64)
540
+ return (self.copula_logpdf(special.ndtr(z))
541
+ - 0.5 * np.sum(z * z, axis=1) - 0.5 * z.shape[1] * math.log(2 * math.pi))
542
+
543
+ # -- sampling -----------------------------------------------------------------------------
544
+ def sample_u(self, n: int, rng: np.random.Generator) -> np.ndarray:
545
+ d = len(self.columns)
546
+ w = rng.random((n, d))
547
+ u = np.empty((n, d))
548
+ cpo: dict[tuple[int, frozenset[int]], np.ndarray] = {}
549
+ for x in reversed(self._order):
550
+ chain = self._chains[x]
551
+ q = _clip(w[:, x])
552
+ for e in reversed(chain):
553
+ other = e.b if e.a == x else e.a
554
+ cpo[_key(x, (*e.cond, other))] = q
555
+ v = cpo[_key(other, e.cond)]
556
+ q = e.pair.hinv1(q, v) if e.a == x else e.pair.hinv2(q, v)
557
+ cpo[_key(x, ())] = q
558
+ u[:, x] = q
559
+ for e in chain:
560
+ other = e.b if e.a == x else e.a
561
+ ux, uo = cpo[_key(x, e.cond)], cpo[_key(other, e.cond)]
562
+ cpo[_key(other, (*e.cond, x))] = (e.pair.h2(uo, ux) if e.a == x
563
+ else e.pair.h1(uo, ux))
564
+ return u
565
+
566
+ def sample(self, n: int, rng: np.random.Generator) -> np.ndarray:
567
+ return special.ndtri(_clip(self.sample_u(n, rng)))
568
+
569
+ @property
570
+ def n_parameters(self) -> int:
571
+ return sum(N_PARAMS[e.pair.family] for e in self.edges)
572
+
573
+ def summary(self) -> list[dict[str, Any]]:
574
+ """Human-readable edge list (column names, family, rotation, parameters, tau)."""
575
+ c = self.columns
576
+ return [{"tree": e.tree, "pair": [c[e.a], c[e.b]], "given": [c[k] for k in e.cond],
577
+ "family": e.pair.family, "rotation": e.pair.rotation,
578
+ "parameters": [e.pair.p1, e.pair.p2], "tau": e.pair.tau} for e in self.edges]
579
+
580
+ # -- serialisation ------------------------------------------------------------------------
581
+ def to_spec(self, store: ArrayStore, prefix: str) -> ModelSpec:
582
+ par = np.array([[e.pair.p1, e.pair.p2] for e in self.edges], dtype=np.float64
583
+ ).reshape(len(self.edges), 2)
584
+ params: dict[str, Any] = {
585
+ "columns": list(self.columns),
586
+ "trunc_level": self.trunc_level,
587
+ "edges": [[e.tree, e.a, e.b, list(e.cond)] for e in self.edges],
588
+ "families": [e.pair.family for e in self.edges],
589
+ "rotations": [e.pair.rotation for e in self.edges],
590
+ }
591
+ return ModelSpec(kind=self.kind, params=params,
592
+ arrays={"pair_parameters": store.put(f"{prefix}pair_parameters", par)})
593
+
594
+ @classmethod
595
+ def from_spec(cls, spec: ModelSpec, store: ArrayStore) -> VineCopula:
596
+ p = spec.params
597
+ cols = [str(c) for c in p.get("columns", [])] # type: ignore[union-attr]
598
+ raw_edges = list(p.get("edges", [])) # type: ignore[arg-type]
599
+ fams = [str(f) for f in p.get("families", [])] # type: ignore[union-attr]
600
+ rots = [int(r) for r in p.get("rotations", [])] # type: ignore[union-attr]
601
+ par = np.asarray(store.get(spec.arrays["pair_parameters"]), dtype=np.float64
602
+ ).reshape(-1, 2)
603
+ if not (len(raw_edges) == len(fams) == len(rots) == len(par)):
604
+ raise ValueError("inconsistent vine spec")
605
+ edges = [VineEdge(int(t), int(a), int(b), tuple(sorted(int(c) for c in cond)),
606
+ PairCopula(f, r, float(q[0]), float(q[1])))
607
+ for (t, a, b, cond), f, r, q in zip(raw_edges, fams, rots, par)]
608
+ return cls(cols, edges, trunc_level=int(p.get("trunc_level", 3))) # type: ignore[arg-type]
ectype/plugins.py ADDED
@@ -0,0 +1,40 @@
1
+ """Built-in plug-in registration.
2
+
3
+ Model kinds are registered by importing their modules. ``load_builtin_plugins`` imports every
4
+ built-in module that registers a kind, so a fingerprint produced by any feature (calibration,
5
+ scenarios, temporal, ...) can be compiled by a fresh process. Third-party plug-ins are never
6
+ loaded implicitly.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import importlib
12
+
13
+ _BUILTIN = (
14
+ "ectype.models.marginals",
15
+ "ectype.models.copulas",
16
+ "ectype.models.mixtures",
17
+ "ectype.models.vines",
18
+ "ectype.models.forest",
19
+ "ectype.models.chain",
20
+ "ectype.models.neural",
21
+ "ectype.calibration.adjustments",
22
+ "ectype.scenarios.mutate",
23
+ "ectype.scenarios.merge",
24
+ "ectype.validation.metrics",
25
+ )
26
+
27
+ _loaded = False
28
+
29
+
30
+ def load_builtin_plugins() -> None:
31
+ global _loaded
32
+ if _loaded:
33
+ return
34
+ for name in _BUILTIN:
35
+ try:
36
+ importlib.import_module(name)
37
+ except ModuleNotFoundError as e: # optional module not present in this build
38
+ if e.name != name:
39
+ raise
40
+ _loaded = True