evalsuite-python 2.1.0__py3-none-any.whl → 2.1.2__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.
- evalsuite/_bench_metrics.py +2 -1
- evalsuite/_evalci.py +1 -1
- evalsuite/_models.py +293 -0
- evalsuite/_spatial.py +194 -0
- evalsuite/_special.py +780 -0
- evalsuite/_stats.py +1403 -0
- evalsuite/_table.py +214 -0
- evalsuite/agreement.py +9 -5
- evalsuite/auto_report.py +20 -1
- evalsuite/bayes.py +2 -2
- evalsuite/benchmarks.py +30 -14
- evalsuite/calibration.py +1 -7
- evalsuite/cards.py +3 -1
- evalsuite/cli/main.py +22 -2
- evalsuite/clinical/report.py +1 -7
- evalsuite/comparisons.py +28 -31
- evalsuite/core/registry.py +2 -0
- evalsuite/data_quality.py +6 -8
- evalsuite/drift.py +4 -5
- evalsuite/forecasting.py +3 -4
- evalsuite/html_report.py +5 -0
- evalsuite/judging.py +1 -15
- evalsuite/llm_benchmarks.py +2 -0
- evalsuite/llm_eval.py +5 -1
- evalsuite/llmsys/robustness.py +1 -1
- evalsuite/llmsys/uncertainty.py +1 -1
- evalsuite/monitor.py +1 -1
- evalsuite/rag_report.py +1 -1
- evalsuite/recalibration.py +9 -4
- evalsuite/reclassification.py +2 -3
- evalsuite/slices.py +1 -2
- evalsuite/stats/effect.py +2 -8
- evalsuite/stats/hypothesis.py +12 -38
- evalsuite/stats/intervals.py +5 -10
- evalsuite/stats/paired.py +2 -9
- evalsuite/stats/planning.py +2 -16
- evalsuite/streaming.py +1 -1
- evalsuite/survival.py +1 -1
- evalsuite/text/judge.py +2 -8
- evalsuite/text/semantic.py +5 -22
- evalsuite/text/structured.py +2 -0
- evalsuite/version.py +1 -1
- evalsuite/vision/segmentation.py +9 -16
- evalsuite/workflow.py +7 -0
- {evalsuite_python-2.1.0.dist-info → evalsuite_python-2.1.2.dist-info}/METADATA +18 -9
- {evalsuite_python-2.1.0.dist-info → evalsuite_python-2.1.2.dist-info}/RECORD +50 -45
- {evalsuite_python-2.1.0.dist-info → evalsuite_python-2.1.2.dist-info}/WHEEL +0 -0
- {evalsuite_python-2.1.0.dist-info → evalsuite_python-2.1.2.dist-info}/entry_points.txt +0 -0
- {evalsuite_python-2.1.0.dist-info → evalsuite_python-2.1.2.dist-info}/licenses/LICENSE +0 -0
- {evalsuite_python-2.1.0.dist-info → evalsuite_python-2.1.2.dist-info}/licenses/LICENSE-APACHE +0 -0
evalsuite/_bench_metrics.py
CHANGED
|
@@ -580,7 +580,8 @@ def _statistics(c: _Cases, n: int, rng: np.random.Generator) -> None:
|
|
|
580
580
|
"statistics.shapiro_wilk_test",
|
|
581
581
|
lambda: _numeric(es.shapiro_wilk_test(xs)),
|
|
582
582
|
"SciPy",
|
|
583
|
-
|
|
583
|
+
# SciPy runs Royston's algorithm in NumPy (as EvalSuite does) only from 1.18; older SciPy differs
|
|
584
|
+
(lambda: list(stats.shapiro(xs))) if hasattr(getattr(stats, "_morestats", None), "_swilk_w") else None,
|
|
584
585
|
)
|
|
585
586
|
c.add(
|
|
586
587
|
"statistics.t_test",
|
evalsuite/_evalci.py
CHANGED
evalsuite/_models.py
ADDED
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
"""Clustered-data models written from their estimating equations, so ``clustered_comparison`` needs no statsmodels.
|
|
2
|
+
|
|
3
|
+
``gee_exchangeable`` is a port of statsmodels' ``GEE`` with an exchangeable working correlation (same starting
|
|
4
|
+
GLM fit by IRLS, same update and stopping rules, same robust sandwich covariance), so it returns statsmodels'
|
|
5
|
+
numbers. ``lmm_random_intercept`` fits a linear mixed model with one random intercept per cluster by restricted
|
|
6
|
+
maximum likelihood: σ² is profiled out and the variance ratio λ = τ²/σ² is found by a bounded one-dimensional
|
|
7
|
+
search, then β̂ = (Σ Xᵢ'Vᵢ⁻¹Xᵢ)⁻¹ Σ Xᵢ'Vᵢ⁻¹yᵢ with Vᵢ⁻¹ ∝ I − λ/(1 + λnᵢ) J.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import math
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
import numpy as np
|
|
17
|
+
from numpy.typing import NDArray
|
|
18
|
+
|
|
19
|
+
__all__ = ["FitResult", "gee_exchangeable", "lmm_random_intercept"]
|
|
20
|
+
|
|
21
|
+
_FEPS = float(np.finfo(float).eps)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class FitResult:
|
|
26
|
+
params: NDArray[np.float64]
|
|
27
|
+
bse: NDArray[np.float64]
|
|
28
|
+
pvalues: NDArray[np.float64]
|
|
29
|
+
converged: bool
|
|
30
|
+
boundary: bool = False
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _clean(p: NDArray[np.float64]) -> NDArray[np.float64]:
|
|
34
|
+
return np.clip(p, _FEPS, 1.0 - _FEPS)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class _Family:
|
|
38
|
+
def __init__(self, binomial: bool) -> None:
|
|
39
|
+
self.binomial = binomial
|
|
40
|
+
|
|
41
|
+
def link(self, mu: NDArray[np.float64]) -> NDArray[np.float64]:
|
|
42
|
+
if self.binomial:
|
|
43
|
+
p = _clean(mu)
|
|
44
|
+
return np.asarray(np.log(p / (1.0 - p)))
|
|
45
|
+
return mu
|
|
46
|
+
|
|
47
|
+
def inverse(self, z: NDArray[np.float64]) -> NDArray[np.float64]:
|
|
48
|
+
return np.asarray(1.0 / (1 + np.exp(-z))) if self.binomial else z
|
|
49
|
+
|
|
50
|
+
def inverse_deriv(self, z: NDArray[np.float64]) -> NDArray[np.float64]:
|
|
51
|
+
if self.binomial:
|
|
52
|
+
t = np.exp(z)
|
|
53
|
+
return np.asarray(t / (1 + t) ** 2)
|
|
54
|
+
return np.ones_like(z)
|
|
55
|
+
|
|
56
|
+
def deriv(self, mu: NDArray[np.float64]) -> NDArray[np.float64]:
|
|
57
|
+
if self.binomial:
|
|
58
|
+
p = _clean(mu)
|
|
59
|
+
return np.asarray(1.0 / (p * (1 - p)))
|
|
60
|
+
return np.ones_like(mu)
|
|
61
|
+
|
|
62
|
+
def variance(self, mu: NDArray[np.float64]) -> NDArray[np.float64]:
|
|
63
|
+
if self.binomial:
|
|
64
|
+
p = _clean(mu)
|
|
65
|
+
return np.asarray(p * (1 - p))
|
|
66
|
+
return np.ones_like(mu)
|
|
67
|
+
|
|
68
|
+
def starting_mu(self, y: NDArray[np.float64]) -> NDArray[np.float64]:
|
|
69
|
+
return (y + 0.5) / 2 if self.binomial else (y + y.mean()) / 2.0
|
|
70
|
+
|
|
71
|
+
def deviance(self, y: NDArray[np.float64], mu: NDArray[np.float64], scale: float) -> float:
|
|
72
|
+
if self.binomial:
|
|
73
|
+
a = _clean(y / mu)
|
|
74
|
+
b = _clean((1 - y) / (1 - mu))
|
|
75
|
+
return float(np.sum(2 * (y * np.log(a) + (1 - y) * np.log(b))))
|
|
76
|
+
return float(np.sum((y - mu) ** 2)) / scale
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _glm_start(y: NDArray[np.float64], x: NDArray[np.float64], fam: _Family) -> NDArray[np.float64]:
|
|
80
|
+
"""GLM by IRLS, as statsmodels ``GLM.fit()`` (deviance convergence, tol 1e-8; final pinv WLS solve)."""
|
|
81
|
+
n, k = x.shape
|
|
82
|
+
|
|
83
|
+
def scale_of(mu: NDArray[np.float64]) -> float:
|
|
84
|
+
if fam.binomial:
|
|
85
|
+
return 1.0
|
|
86
|
+
return float(np.sum((y - mu) ** 2 / fam.variance(mu))) / float(n - k)
|
|
87
|
+
|
|
88
|
+
mu = fam.starting_mu(y)
|
|
89
|
+
lin = fam.link(mu)
|
|
90
|
+
dev = [math.inf, fam.deviance(y, mu, scale_of(mu))]
|
|
91
|
+
w = np.ones(n)
|
|
92
|
+
z = lin
|
|
93
|
+
for it in range(100):
|
|
94
|
+
w = 1.0 / (fam.deriv(mu) ** 2 * fam.variance(mu))
|
|
95
|
+
z = lin + fam.deriv(mu) * (y - mu)
|
|
96
|
+
sw = np.sqrt(w)
|
|
97
|
+
params = np.linalg.lstsq(x * sw[:, None], z * sw, rcond=-1)[0]
|
|
98
|
+
lin = x @ params
|
|
99
|
+
mu = fam.inverse(lin)
|
|
100
|
+
dev.append(fam.deviance(y, mu, scale_of(mu)))
|
|
101
|
+
if np.allclose(dev[it + 1], dev[it + 2], atol=1e-8, rtol=0.0):
|
|
102
|
+
break
|
|
103
|
+
sw = np.sqrt(w)
|
|
104
|
+
return np.asarray(np.linalg.pinv(x * sw[:, None]) @ (z * sw), dtype=np.float64)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def gee_exchangeable(
|
|
108
|
+
y: NDArray[np.float64], x: NDArray[np.float64], groups: NDArray[Any], *, binomial: bool
|
|
109
|
+
) -> FitResult:
|
|
110
|
+
"""GEE with an exchangeable working correlation and robust (sandwich) standard errors; logit link for a
|
|
111
|
+
binary ``y`` (``binomial=True``), identity otherwise. Port of statsmodels' ``GEE.fit()`` defaults."""
|
|
112
|
+
fam = _Family(binomial)
|
|
113
|
+
n, k = x.shape
|
|
114
|
+
labels, inv = np.unique(groups, return_inverse=True)
|
|
115
|
+
idx = [np.flatnonzero(inv == g) for g in range(labels.size)]
|
|
116
|
+
ys = [y[i] for i in idx]
|
|
117
|
+
xs = [x[i] for i in idx]
|
|
118
|
+
params = _glm_start(y, x, fam)
|
|
119
|
+
dep = 0.0
|
|
120
|
+
|
|
121
|
+
def means(b: NDArray[np.float64]) -> list[tuple[NDArray[np.float64], NDArray[np.float64]]]:
|
|
122
|
+
out = []
|
|
123
|
+
for xi in xs:
|
|
124
|
+
lp = xi @ b
|
|
125
|
+
out.append((fam.inverse(lp), lp))
|
|
126
|
+
return out
|
|
127
|
+
|
|
128
|
+
def solve(expval: NDArray[np.float64], sdev: NDArray[np.float64], rhs: NDArray[np.float64]) -> Any:
|
|
129
|
+
kk = len(expval)
|
|
130
|
+
c = dep / (1.0 - dep)
|
|
131
|
+
c /= 1.0 + dep * (kk - 1)
|
|
132
|
+
if rhs.ndim == 1:
|
|
133
|
+
x1 = rhs / sdev
|
|
134
|
+
out = x1 / (1.0 - dep)
|
|
135
|
+
out -= c * sum(x1)
|
|
136
|
+
return out / sdev
|
|
137
|
+
x1 = rhs / sdev[:, None]
|
|
138
|
+
out = x1 / (1.0 - dep)
|
|
139
|
+
out -= c * x1.sum(0)
|
|
140
|
+
return out / sdev[:, None]
|
|
141
|
+
|
|
142
|
+
def pieces(cached: list[Any]) -> tuple[NDArray[np.float64], NDArray[np.float64], NDArray[np.float64]]:
|
|
143
|
+
bmat: Any = 0
|
|
144
|
+
score: Any = 0
|
|
145
|
+
cmat: Any = 0
|
|
146
|
+
for i in range(len(xs)):
|
|
147
|
+
expval, lpr = cached[i]
|
|
148
|
+
resid = ys[i] - expval
|
|
149
|
+
dmat = xs[i] * fam.inverse_deriv(lpr)[:, None]
|
|
150
|
+
sdev = np.sqrt(fam.variance(expval))
|
|
151
|
+
vd = solve(expval, sdev, dmat)
|
|
152
|
+
vr = solve(expval, sdev, resid)
|
|
153
|
+
bmat = bmat + np.dot(dmat.T, vd)
|
|
154
|
+
s_i = np.dot(dmat.T, vr)
|
|
155
|
+
score = score + s_i
|
|
156
|
+
cmat = cmat + np.outer(s_i, s_i)
|
|
157
|
+
return np.asarray(bmat), np.asarray(score), np.asarray(cmat)
|
|
158
|
+
|
|
159
|
+
cached = means(params)
|
|
160
|
+
del_params = -1.0
|
|
161
|
+
n_assoc = 0
|
|
162
|
+
for _ in range(60):
|
|
163
|
+
bmat, score, _c = pieces(cached)
|
|
164
|
+
try:
|
|
165
|
+
update = np.linalg.solve(bmat, score)
|
|
166
|
+
except np.linalg.LinAlgError: # pragma: no cover - a singular design (as statsmodels: pseudo-inverse)
|
|
167
|
+
update = np.dot(np.linalg.pinv(bmat), score)
|
|
168
|
+
params = params + update
|
|
169
|
+
cached = means(params)
|
|
170
|
+
del_params = float(np.sqrt(np.sum(score**2)))
|
|
171
|
+
if del_params < 1e-6 and n_assoc > 0:
|
|
172
|
+
break
|
|
173
|
+
# exchangeable update of the working correlation (statsmodels ``Exchangeable.update``)
|
|
174
|
+
rs_sum = 0.0
|
|
175
|
+
sc = 0.0
|
|
176
|
+
fsum1 = fsum2 = n_pairs = 0.0
|
|
177
|
+
for i in range(len(xs)):
|
|
178
|
+
expval, _ = cached[i]
|
|
179
|
+
r = (ys[i] - expval) / np.sqrt(fam.variance(expval))
|
|
180
|
+
ssr = float(np.sum(r * r))
|
|
181
|
+
sc += ssr
|
|
182
|
+
fsum1 += len(ys[i])
|
|
183
|
+
rs_sum += (float(r.sum()) ** 2 - ssr) / 2
|
|
184
|
+
npr = 0.5 * len(r) * (len(r) - 1)
|
|
185
|
+
fsum2 += npr
|
|
186
|
+
n_pairs += npr
|
|
187
|
+
sc /= fsum1 * (n - k) / float(n)
|
|
188
|
+
rs_sum /= sc
|
|
189
|
+
den = fsum2 * (n_pairs - k) / float(n_pairs) if n_pairs > 0 else 0.0
|
|
190
|
+
dep = rs_sum / den if den > 0 else 0.0 # too few within-cluster pairs: independence
|
|
191
|
+
n_assoc += 1 # noqa: SIM113 - counts association updates (the loop may stop before one)
|
|
192
|
+
bmat, _s, cmat = pieces(cached)
|
|
193
|
+
try:
|
|
194
|
+
bmati = np.linalg.inv(bmat)
|
|
195
|
+
except np.linalg.LinAlgError: # pragma: no cover - a singular design
|
|
196
|
+
bmati = np.linalg.pinv(bmat)
|
|
197
|
+
cov = bmati @ cmat @ bmati
|
|
198
|
+
bse = np.sqrt(np.diag(cov))
|
|
199
|
+
zval = params / bse
|
|
200
|
+
from ._special import ndtr
|
|
201
|
+
|
|
202
|
+
pv = 2 * np.asarray(ndtr(-np.abs(zval)), dtype=np.float64)
|
|
203
|
+
return FitResult(params, bse, pv, del_params < 1e-6)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def lmm_random_intercept(y: NDArray[np.float64], x: NDArray[np.float64], groups: NDArray[Any]) -> FitResult:
|
|
207
|
+
"""Linear mixed model y = Xβ + uᵢ + ε with one random intercept per cluster, by REML."""
|
|
208
|
+
n, k = x.shape
|
|
209
|
+
labels, inv = np.unique(groups, return_inverse=True)
|
|
210
|
+
g = labels.size
|
|
211
|
+
ni = np.bincount(inv, minlength=g).astype(np.float64)
|
|
212
|
+
# per-cluster sums let every λ be evaluated in O(k²) after one pass
|
|
213
|
+
sx = np.zeros((g, k))
|
|
214
|
+
np.add.at(sx, inv, x)
|
|
215
|
+
sy = np.bincount(inv, weights=y, minlength=g)
|
|
216
|
+
xtx = x.T @ x
|
|
217
|
+
xty = x.T @ y
|
|
218
|
+
yty = float(y @ y)
|
|
219
|
+
|
|
220
|
+
def parts(lam: float) -> tuple[float, NDArray[np.float64], NDArray[np.float64], float]:
|
|
221
|
+
c = lam / (1.0 + lam * ni) # V⁻¹ ∝ I − c J per cluster
|
|
222
|
+
a = xtx - (sx * c[:, None]).T @ sx
|
|
223
|
+
b = xty - (sx * c[:, None]).T @ sy
|
|
224
|
+
beta = np.linalg.solve(a, b)
|
|
225
|
+
q = yty - float(np.sum(c * sy * sy)) - 2 * float(beta @ b) + float(beta @ a @ beta)
|
|
226
|
+
q = max(q, 0.0)
|
|
227
|
+
logdet_v = float(np.sum(np.log1p(lam * ni)))
|
|
228
|
+
_sign, logdet_a = np.linalg.slogdet(a)
|
|
229
|
+
obj = (n - k) * math.log(q / (n - k)) + logdet_v + float(logdet_a)
|
|
230
|
+
return obj, beta, a, q
|
|
231
|
+
|
|
232
|
+
from ._special import ndtr
|
|
233
|
+
from ._stats import minimize_scalar_bounded
|
|
234
|
+
|
|
235
|
+
res = minimize_scalar_bounded(lambda t: parts(math.exp(t))[0], (-20.0, 12.0), xatol=1e-12)
|
|
236
|
+
lam = math.exp(res.x)
|
|
237
|
+
boundary = parts(0.0)[0] <= res.fun
|
|
238
|
+
if boundary:
|
|
239
|
+
lam = 0.0
|
|
240
|
+
_obj, beta, a, q = parts(lam)
|
|
241
|
+
if boundary or lam < 1e-10:
|
|
242
|
+
# the cluster variance is estimated at zero: ordinary least squares (statsmodels' Hessian is singular here)
|
|
243
|
+
cov = q / (n - k) * np.linalg.inv(a)
|
|
244
|
+
else:
|
|
245
|
+
cov = _lmm_cov(x, y, inv, ni, sx, lam, beta, n, k)
|
|
246
|
+
bse = np.sqrt(np.diag(cov))
|
|
247
|
+
pv = 2 * np.asarray(ndtr(-np.abs(beta / bse)), dtype=np.float64)
|
|
248
|
+
return FitResult(np.asarray(beta), bse, pv, True, boundary or lam < 1e-8)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _lmm_cov(
|
|
252
|
+
x: NDArray[np.float64],
|
|
253
|
+
y: NDArray[np.float64],
|
|
254
|
+
inv: NDArray[np.intp],
|
|
255
|
+
ni: NDArray[np.float64],
|
|
256
|
+
sx: NDArray[np.float64],
|
|
257
|
+
psi: float,
|
|
258
|
+
beta: NDArray[np.float64],
|
|
259
|
+
n: int,
|
|
260
|
+
k: int,
|
|
261
|
+
) -> NDArray[np.float64]:
|
|
262
|
+
"""Covariance of β̂ from the observed information of the REML log-likelihood in (β, ψ), ψ = τ²/σ² — the
|
|
263
|
+
random-intercept case of statsmodels' ``MixedLM.hessian`` (cross terms between β and ψ included)."""
|
|
264
|
+
r = y - x @ beta
|
|
265
|
+
g = ni.size
|
|
266
|
+
sr = np.bincount(inv, weights=r, minlength=g)
|
|
267
|
+
srr = np.bincount(inv, weights=r * r, minlength=g)
|
|
268
|
+
d = 1.0 + ni * psi
|
|
269
|
+
c = psi / d
|
|
270
|
+
xtvix = x.T @ x - (sx * c[:, None]).T @ sx
|
|
271
|
+
rvir = float(np.sum(srr - c * sr * sr))
|
|
272
|
+
s_ = ni / d # 1'V⁻¹1 per cluster
|
|
273
|
+
w = sx / d[:, None] # X'V⁻¹1
|
|
274
|
+
t = sr / d # 1'V⁻¹r
|
|
275
|
+
hess_fere = (w * t[:, None]).sum(axis=0)
|
|
276
|
+
xtax = w.T @ w
|
|
277
|
+
bb = float(np.sum(t * t))
|
|
278
|
+
dd = float(np.sum(2 * t * t * s_))
|
|
279
|
+
hess_re = float(np.sum(s_ * s_)) / 2
|
|
280
|
+
ff = 2 * (w * s_[:, None]).T @ w
|
|
281
|
+
fac = n - k
|
|
282
|
+
hess_fe = -fac * xtvix / rvir
|
|
283
|
+
hess_re = hess_re - 0.5 * fac * (dd / rvir - bb * bb / rvir**2)
|
|
284
|
+
hess_fere = -fac * hess_fere / rvir
|
|
285
|
+
ql = np.linalg.solve(xtvix, xtax)
|
|
286
|
+
hess_re += 0.5 * (float(np.sum(ql.T * ql)) - float(np.trace(np.linalg.solve(xtvix, ff))))
|
|
287
|
+
hess = np.zeros((k + 1, k + 1))
|
|
288
|
+
hess[:k, :k] = hess_fe
|
|
289
|
+
hess[:k, k] = hess_fere
|
|
290
|
+
hess[k, :k] = hess_fere
|
|
291
|
+
hess[k, k] = hess_re
|
|
292
|
+
cov: NDArray[np.float64] = np.linalg.inv(-hess)[:k, :k]
|
|
293
|
+
return cov
|
evalsuite/_spatial.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
"""Nearest neighbours, fixed-radius pairs, binary erosion and exact optimal transport, written from scratch.
|
|
2
|
+
|
|
3
|
+
``nearest`` and ``pairs_within`` are the reference for the compiled k-d tree (``rust/evalsuite-core/src/
|
|
4
|
+
kdtree.rs``): squared distances are summed over the axes in order and rooted at the end, ties in the nearest
|
|
5
|
+
search go to the smallest index, and pairs are ``i < j`` with distance <= r. The compiled core is used when it is
|
|
6
|
+
available; both give identical results. ``transport_cost`` solves the transportation problem exactly
|
|
7
|
+
(successive shortest paths with potentials), which is what earth mover's distance needs.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import math
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
from numpy.typing import NDArray
|
|
17
|
+
|
|
18
|
+
from ._native import array_view, core
|
|
19
|
+
|
|
20
|
+
__all__ = ["nearest", "pairs_within", "binary_erosion_full", "transport_cost"]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _sq(a: NDArray[np.float64], b: NDArray[np.float64]) -> NDArray[np.float64]:
|
|
24
|
+
"""Squared distances between rows of ``a`` (m × d) and ``b`` (n × d), summed over the axes in order."""
|
|
25
|
+
s = np.zeros((a.shape[0], b.shape[0]))
|
|
26
|
+
for k in range(a.shape[1]):
|
|
27
|
+
t = a[:, k, None] - b[None, :, k]
|
|
28
|
+
s += t * t
|
|
29
|
+
return s
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def nearest(data: Any, queries: Any) -> tuple[NDArray[np.float64], NDArray[np.int64]]:
|
|
33
|
+
"""For each row of ``queries``, the Euclidean distance to its nearest row of ``data`` and that row's index."""
|
|
34
|
+
x = np.ascontiguousarray(data, dtype=np.float64)
|
|
35
|
+
q = np.ascontiguousarray(queries, dtype=np.float64)
|
|
36
|
+
if x.ndim != 2 or q.ndim != 2 or x.shape[1] != q.shape[1] or x.shape[0] == 0:
|
|
37
|
+
raise ValueError("data and queries must be non-empty 2-D arrays with the same number of columns.")
|
|
38
|
+
if q.shape[0] == 0:
|
|
39
|
+
return np.zeros(0), np.zeros(0, dtype=np.int64)
|
|
40
|
+
c = core
|
|
41
|
+
if c is not None and x.shape[1] > 0:
|
|
42
|
+
_x, vx = array_view(x, np.float64)
|
|
43
|
+
_q, vq = array_view(q, np.float64)
|
|
44
|
+
d, i = c.kd_nearest(vx, vq, x.shape[1])
|
|
45
|
+
return np.frombuffer(d, dtype=np.float64).copy(), np.asarray(i, dtype=np.int64)
|
|
46
|
+
dist = np.empty(q.shape[0])
|
|
47
|
+
idx = np.empty(q.shape[0], dtype=np.int64)
|
|
48
|
+
step = max(1, 4_000_000 // max(x.shape[0], 1))
|
|
49
|
+
for s in range(0, q.shape[0], step):
|
|
50
|
+
d2 = _sq(q[s : s + step], x)
|
|
51
|
+
j = np.argmin(d2, axis=1) # first minimum: the smallest index among ties
|
|
52
|
+
idx[s : s + step] = j
|
|
53
|
+
dist[s : s + step] = np.sqrt(d2[np.arange(j.size), j])
|
|
54
|
+
return dist, idx
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def pairs_within(data: Any, r: float) -> list[tuple[int, int]]:
|
|
58
|
+
"""Every pair ``i < j`` of rows of ``data`` within Euclidean distance ``r``, sorted."""
|
|
59
|
+
x = np.ascontiguousarray(data, dtype=np.float64)
|
|
60
|
+
if x.ndim != 2:
|
|
61
|
+
raise ValueError("data must be a 2-D array.")
|
|
62
|
+
n = x.shape[0]
|
|
63
|
+
if n < 2:
|
|
64
|
+
return []
|
|
65
|
+
c = core
|
|
66
|
+
if c is not None and x.shape[1] > 0:
|
|
67
|
+
_x, vx = array_view(x, np.float64)
|
|
68
|
+
return [(int(a), int(b)) for a, b in c.kd_pairs(vx, x.shape[1], float(r))]
|
|
69
|
+
# sweep along axis 0: only rows whose first coordinates differ by at most r can be within r
|
|
70
|
+
order = np.argsort(x[:, 0], kind="mergesort")
|
|
71
|
+
xs = x[order, 0]
|
|
72
|
+
hi = np.searchsorted(xs, xs + r, side="right")
|
|
73
|
+
out: list[tuple[int, int]] = []
|
|
74
|
+
for a in range(n):
|
|
75
|
+
if hi[a] <= a + 1:
|
|
76
|
+
continue
|
|
77
|
+
cand = order[a + 1 : hi[a]]
|
|
78
|
+
i = int(order[a])
|
|
79
|
+
d = np.sqrt(_sq(x[i : i + 1], x[cand])[0])
|
|
80
|
+
for j in cand[d <= r].tolist():
|
|
81
|
+
out.append((i, j) if i < j else (j, i))
|
|
82
|
+
out.sort()
|
|
83
|
+
return out
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def binary_erosion_full(mask: NDArray[np.bool_], iterations: int) -> NDArray[np.bool_]:
|
|
87
|
+
"""Erosion by the full (3^ndim) neighbourhood, ``iterations`` times, with the outside as background (SciPy's
|
|
88
|
+
``binary_erosion`` with ``generate_binary_structure(ndim, ndim)`` and ``border_value=0``).
|
|
89
|
+
That is a cube of half-width ``iterations``, which is separable: one 1-D window test per axis."""
|
|
90
|
+
out: NDArray[np.bool_] = np.asarray(mask, dtype=bool)
|
|
91
|
+
w = int(iterations)
|
|
92
|
+
if w <= 0:
|
|
93
|
+
same: NDArray[np.bool_] = out.copy()
|
|
94
|
+
return same
|
|
95
|
+
for ax in range(out.ndim):
|
|
96
|
+
n = out.shape[ax]
|
|
97
|
+
if 2 * w + 1 > n: # the window never fits: everything erodes
|
|
98
|
+
return np.zeros(out.shape, dtype=bool)
|
|
99
|
+
# a pixel survives when every pixel within ``w`` along this axis is set: AND of the 2w shifted copies
|
|
100
|
+
keep = out.copy()
|
|
101
|
+
src = np.moveaxis(out, ax, 0)
|
|
102
|
+
dst = np.moveaxis(keep, ax, 0)
|
|
103
|
+
for sh in range(1, w + 1):
|
|
104
|
+
dst[: n - sh] &= src[sh:] # neighbour sh steps ahead
|
|
105
|
+
dst[sh:] &= src[: n - sh] # and behind
|
|
106
|
+
dst[:w] = False # windows that reach past the edge (outside counts as background)
|
|
107
|
+
dst[n - w :] = False
|
|
108
|
+
out = keep
|
|
109
|
+
res: NDArray[np.bool_] = np.ascontiguousarray(out)
|
|
110
|
+
return res
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def transport_cost(a: Any, b: Any, cost: Any) -> float:
|
|
114
|
+
"""Minimum total cost of moving the mass ``a`` (n) onto ``b`` (m) with per-unit costs ``cost`` (n × m), where
|
|
115
|
+
Σa = Σb: the optimal value of the transportation linear programme (earth mover's distance).
|
|
116
|
+
|
|
117
|
+
Successive shortest paths with node potentials (Dijkstra on reduced costs): each augmentation moves the most
|
|
118
|
+
mass the cheapest route allows and empties a supply or fills a demand, so at most n + m of them are needed."""
|
|
119
|
+
sup = np.array(a, dtype=np.float64)
|
|
120
|
+
dem = np.array(b, dtype=np.float64)
|
|
121
|
+
c = np.ascontiguousarray(cost, dtype=np.float64)
|
|
122
|
+
n, m = c.shape
|
|
123
|
+
if core is not None and n and m:
|
|
124
|
+
_a, va = array_view(np.ascontiguousarray(sup), np.float64)
|
|
125
|
+
_b, vb = array_view(np.ascontiguousarray(dem), np.float64)
|
|
126
|
+
_c, vc = array_view(c, np.float64)
|
|
127
|
+
return float(core.transport_cost(va, vb, vc))
|
|
128
|
+
tol = 1e-15 * max(float(np.cumsum(sup)[-1]), 1.0) # strictly sequential sums, as the compiled solver
|
|
129
|
+
flow = np.zeros((n, m))
|
|
130
|
+
pot_s = np.zeros(n) # potentials of supply nodes
|
|
131
|
+
pot_d = c.min(axis=0) # of demand nodes (reduced costs c + pot_s − pot_d >= 0)
|
|
132
|
+
for _ in range(4 * (n + m) + 10):
|
|
133
|
+
active = sup > tol
|
|
134
|
+
if not active.any():
|
|
135
|
+
break
|
|
136
|
+
# Dijkstra over the bipartite residual graph from every supply with mass left
|
|
137
|
+
dist_s = np.where(active, 0.0, math.inf)
|
|
138
|
+
dist_d = np.full(m, math.inf)
|
|
139
|
+
prev_d = np.full(m, -1) # supply node feeding each demand node on the shortest path
|
|
140
|
+
prev_s = np.full(n, -1) # demand node whose backward edge reaches each supply node
|
|
141
|
+
done_s = np.zeros(n, dtype=bool)
|
|
142
|
+
done_d = np.zeros(m, dtype=bool)
|
|
143
|
+
while True:
|
|
144
|
+
ds = np.where(done_s, math.inf, dist_s)
|
|
145
|
+
dd = np.where(done_d, math.inf, dist_d)
|
|
146
|
+
i, j = int(np.argmin(ds)), int(np.argmin(dd))
|
|
147
|
+
if ds[i] == math.inf and dd[j] == math.inf:
|
|
148
|
+
break
|
|
149
|
+
if ds[i] <= dd[j]:
|
|
150
|
+
done_s[i] = True
|
|
151
|
+
red = c[i] + pot_s[i] - pot_d
|
|
152
|
+
cand = dist_s[i] + np.maximum(red, 0.0)
|
|
153
|
+
better = (~done_d) & (cand < dist_d)
|
|
154
|
+
dist_d[better] = cand[better]
|
|
155
|
+
prev_d[better] = i
|
|
156
|
+
else:
|
|
157
|
+
done_d[j] = True
|
|
158
|
+
if dem[j] > tol:
|
|
159
|
+
continue # a sink: paths end here
|
|
160
|
+
back = flow[:, j] > tol # residual edge demand j -> supply i where flow can be undone
|
|
161
|
+
red = pot_d[j] - c[:, j] - pot_s
|
|
162
|
+
cand = dist_d[j] + np.maximum(red, 0.0)
|
|
163
|
+
better = back & (~done_s) & (cand < dist_s)
|
|
164
|
+
dist_s[better] = cand[better]
|
|
165
|
+
prev_s[better] = j
|
|
166
|
+
sinks = np.flatnonzero((dem > tol) & np.isfinite(dist_d))
|
|
167
|
+
if sinks.size == 0: # pragma: no cover - balanced problems always have a path
|
|
168
|
+
break
|
|
169
|
+
t = int(sinks[np.argmin(dist_d[sinks])])
|
|
170
|
+
fin_s = np.isfinite(dist_s)
|
|
171
|
+
fin_d = np.isfinite(dist_d)
|
|
172
|
+
# path back from t; bottleneck
|
|
173
|
+
path: list[tuple[int, int, int]] = [] # (+1 forward i->j | -1 backward j->i, i, j)
|
|
174
|
+
j = t
|
|
175
|
+
amt = dem[t]
|
|
176
|
+
while True:
|
|
177
|
+
i = int(prev_d[j])
|
|
178
|
+
path.append((1, i, j))
|
|
179
|
+
if prev_s[i] < 0:
|
|
180
|
+
amt = min(amt, sup[i])
|
|
181
|
+
break
|
|
182
|
+
j2 = int(prev_s[i])
|
|
183
|
+
path.append((-1, i, j2))
|
|
184
|
+
amt = min(amt, flow[i, j2])
|
|
185
|
+
j = j2
|
|
186
|
+
for kind, i, j in path:
|
|
187
|
+
flow[i, j] += amt if kind == 1 else -amt
|
|
188
|
+
sup[path[-1][1]] -= amt
|
|
189
|
+
dem[t] -= amt
|
|
190
|
+
# potentials: shift by shortest distances (capped at the sink's) so reduced costs stay >= 0
|
|
191
|
+
cap = dist_d[t]
|
|
192
|
+
pot_s += np.minimum(np.where(fin_s, dist_s, cap), cap)
|
|
193
|
+
pot_d += np.minimum(np.where(fin_d, dist_d, cap), cap)
|
|
194
|
+
return float(np.cumsum((flow * c).ravel())[-1]) # (Python 3.12+ sum() compensates; cumsum does not)
|