regioncp 0.1.0__tar.gz

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.
regioncp-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Peng Luo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,4 @@
1
+ graft src
2
+ graft tests
3
+ graft examples
4
+ global-exclude __pycache__ *.pyc
@@ -0,0 +1,94 @@
1
+ Metadata-Version: 2.4
2
+ Name: regioncp
3
+ Version: 0.1.0
4
+ Summary: Uncertainty at the places a map selects: selection-conditional conformal calibration, audit planning and project-total bounds for rank-based geographic decisions
5
+ Author: Peng Luo
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/pengtum/winners-curse-of-maps
8
+ Keywords: conformal prediction,selective inference,uncertainty quantification,geospatial,earth observation
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Scientific/Engineering :: GIS
13
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
14
+ Requires-Python: >=3.9
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: numpy>=1.22
18
+ Requires-Dist: scipy>=1.9
19
+ Provides-Extra: basis
20
+ Requires-Dist: scikit-learn>=1.0; extra == "basis"
21
+ Provides-Extra: test
22
+ Requires-Dist: pytest; extra == "test"
23
+ Dynamic: license-file
24
+
25
+ # regioncp
26
+
27
+ Uncertainty at the places a map selects.
28
+
29
+ Machine-learning maps rank places, and a rule picks some of them: the highest carbon stock, the poorest villages in each country,
30
+ the most valuable sites within a travel budget. Intervals that are valid on average are often wrong at exactly those places.
31
+ `regioncp` calibrates each selected place only on audited places that the same rule would have selected, and tells you before any
32
+ field work how large the audit has to be. The package is named after RegionCP, the method for coverage within regions; it also
33
+ holds the reference sets and JOMI thresholds, the total bounds, cfBH and the audit planner.
34
+
35
+ ```bash
36
+ pip install regioncp
37
+ ```
38
+
39
+ ```python
40
+ import numpy as np
41
+ import regioncp as rcp
42
+
43
+ # mu: the map's prediction; audited / candidates: a random split of one population; y known at audited places
44
+ sel = rcp.top_k(mu[audited], mu[candidates], K=30)
45
+ scores = np.abs(y[audited] - mu[audited]) / sigma[audited]
46
+ q = rcp.jomi(scores, sel, alpha=0.1) # may be +inf if too few audited places lie past the cutoff
47
+ J = candidates[sel.selected]
48
+ lower, upper = mu[J] - q * sigma[J], mu[J] + q * sigma[J]
49
+
50
+ rcp.plan.n_for_finite(m=3000, K=30) # audited places for a 0.9 chance of finite intervals
51
+ rcp.plan.n_budget_for_finite(population=300, K=30) # the same when the audit is drawn from the map's top 300 places
52
+ ```
53
+
54
+ | Task | Function | Guarantee |
55
+ |---|---|---|
56
+ | Rules | `top_k`, `quota`, `budget`, `publication_mask`, `threshold`, `within_groups` | closed-form reference sets, checked against literal swaps |
57
+ | Intervals at selected places | `jomi` | coverage at least 1 − α among selected places, on average over audits |
58
+ | Coverage within regions (RegionCP) | `regioncp` (also `sc_geoccp`), `basis.Multiscale` | Theorem 1's floors, which may be vacuous |
59
+ | Project totals | `exact_lower_total` | finite sample |
60
+ | | `selection_aware_total`, `vcs_credit` | asymptotic; the protocol rule itself |
61
+ | Funding | `cfbh` | false discovery rate at most q, for a top- or bottom-K rule without tied scores (checked) |
62
+ | Audit size | `plan.p_finite`, `plan.n_for_finite`, `plan.n_budget_for_finite`, `plan.floor`, `plan.n_for_floor` | no outcomes used |
63
+ | Any other rule | `bruteforce.reference_matrix` | literal swaps; slow |
64
+
65
+ **What the guarantees need.** A random audit of one finite population (or of a stratum fixed by the map in advance), a map fitted
66
+ separately, and a rule that uses covariates alone and treats audited places symmetrically. Rules that look at audited outcomes,
67
+ audits that are not random, and transfer to unsampled regions fall outside them. Coverage holds on average over audits, and counts
68
+ infinite intervals as covering.
69
+
70
+ `cfbh` accepts only `top_k` selections (either direction) with one shared reference set and distinct scores. It rejects
71
+ quota selections even when only one group is selected. An empty supported selection returns empty p-values and rejections.
72
+
73
+ **Install.** `pip install regioncp`, or `pip install .` from this folder. Needs numpy and scipy; `pip install "regioncp[basis]"` adds scikit-learn for `basis.Multiscale`.
74
+
75
+ **Tests.** `python -m pytest tests`.
76
+
77
+ **Status.** Version 0.1.0. Licence: MIT. Citation: [manuscript to record].
78
+
79
+ **Former name.** Version 0.1.0 was first released on PyPI as `mapselect`. That name now only forwards to this package: `pip install mapselect` installs `regioncp`, and `import mapselect` still works but warns.
80
+
81
+ ## Performance
82
+
83
+ One core of an Apple M6 laptop, synthetic data (`experiments/run_package_benchmark.py` in the project; `results/fia_db/RESULTS_PACKAGE_BENCHMARK.md`).
84
+
85
+ | Task | Size | Time | Memory |
86
+ |---|---|---|---|
87
+ | Top-1% rule, thresholds | 10⁸ candidates, 10⁷ audited | 1.4 s | 2.5 GB |
88
+ | Quota, 50 groups | same | 40 s | 5.7 GB |
89
+ | Budget | same | 35 s | 6.9 GB |
90
+ | Publication mask, k-d tree, selection only | 10⁶ audited | 2 min | 2.2 GB |
91
+ | RegionCP, later units (one reference set) | 10⁵ reference units, 60 basis functions | 0.036 s per unit | 0.9 GB |
92
+ | Exact total bound | 10⁴ selected | 25 s | 0.2 GB |
93
+
94
+ At small sizes these gains shrink or vanish: at 10³ reference units the active set is 1.6 times faster than the full dual, and the budget rule is no faster than a careful per-unit loop up to 10⁵ candidates.
@@ -0,0 +1,70 @@
1
+ # regioncp
2
+
3
+ Uncertainty at the places a map selects.
4
+
5
+ Machine-learning maps rank places, and a rule picks some of them: the highest carbon stock, the poorest villages in each country,
6
+ the most valuable sites within a travel budget. Intervals that are valid on average are often wrong at exactly those places.
7
+ `regioncp` calibrates each selected place only on audited places that the same rule would have selected, and tells you before any
8
+ field work how large the audit has to be. The package is named after RegionCP, the method for coverage within regions; it also
9
+ holds the reference sets and JOMI thresholds, the total bounds, cfBH and the audit planner.
10
+
11
+ ```bash
12
+ pip install regioncp
13
+ ```
14
+
15
+ ```python
16
+ import numpy as np
17
+ import regioncp as rcp
18
+
19
+ # mu: the map's prediction; audited / candidates: a random split of one population; y known at audited places
20
+ sel = rcp.top_k(mu[audited], mu[candidates], K=30)
21
+ scores = np.abs(y[audited] - mu[audited]) / sigma[audited]
22
+ q = rcp.jomi(scores, sel, alpha=0.1) # may be +inf if too few audited places lie past the cutoff
23
+ J = candidates[sel.selected]
24
+ lower, upper = mu[J] - q * sigma[J], mu[J] + q * sigma[J]
25
+
26
+ rcp.plan.n_for_finite(m=3000, K=30) # audited places for a 0.9 chance of finite intervals
27
+ rcp.plan.n_budget_for_finite(population=300, K=30) # the same when the audit is drawn from the map's top 300 places
28
+ ```
29
+
30
+ | Task | Function | Guarantee |
31
+ |---|---|---|
32
+ | Rules | `top_k`, `quota`, `budget`, `publication_mask`, `threshold`, `within_groups` | closed-form reference sets, checked against literal swaps |
33
+ | Intervals at selected places | `jomi` | coverage at least 1 − α among selected places, on average over audits |
34
+ | Coverage within regions (RegionCP) | `regioncp` (also `sc_geoccp`), `basis.Multiscale` | Theorem 1's floors, which may be vacuous |
35
+ | Project totals | `exact_lower_total` | finite sample |
36
+ | | `selection_aware_total`, `vcs_credit` | asymptotic; the protocol rule itself |
37
+ | Funding | `cfbh` | false discovery rate at most q, for a top- or bottom-K rule without tied scores (checked) |
38
+ | Audit size | `plan.p_finite`, `plan.n_for_finite`, `plan.n_budget_for_finite`, `plan.floor`, `plan.n_for_floor` | no outcomes used |
39
+ | Any other rule | `bruteforce.reference_matrix` | literal swaps; slow |
40
+
41
+ **What the guarantees need.** A random audit of one finite population (or of a stratum fixed by the map in advance), a map fitted
42
+ separately, and a rule that uses covariates alone and treats audited places symmetrically. Rules that look at audited outcomes,
43
+ audits that are not random, and transfer to unsampled regions fall outside them. Coverage holds on average over audits, and counts
44
+ infinite intervals as covering.
45
+
46
+ `cfbh` accepts only `top_k` selections (either direction) with one shared reference set and distinct scores. It rejects
47
+ quota selections even when only one group is selected. An empty supported selection returns empty p-values and rejections.
48
+
49
+ **Install.** `pip install regioncp`, or `pip install .` from this folder. Needs numpy and scipy; `pip install "regioncp[basis]"` adds scikit-learn for `basis.Multiscale`.
50
+
51
+ **Tests.** `python -m pytest tests`.
52
+
53
+ **Status.** Version 0.1.0. Licence: MIT. Citation: [manuscript to record].
54
+
55
+ **Former name.** Version 0.1.0 was first released on PyPI as `mapselect`. That name now only forwards to this package: `pip install mapselect` installs `regioncp`, and `import mapselect` still works but warns.
56
+
57
+ ## Performance
58
+
59
+ One core of an Apple M6 laptop, synthetic data (`experiments/run_package_benchmark.py` in the project; `results/fia_db/RESULTS_PACKAGE_BENCHMARK.md`).
60
+
61
+ | Task | Size | Time | Memory |
62
+ |---|---|---|---|
63
+ | Top-1% rule, thresholds | 10⁸ candidates, 10⁷ audited | 1.4 s | 2.5 GB |
64
+ | Quota, 50 groups | same | 40 s | 5.7 GB |
65
+ | Budget | same | 35 s | 6.9 GB |
66
+ | Publication mask, k-d tree, selection only | 10⁶ audited | 2 min | 2.2 GB |
67
+ | RegionCP, later units (one reference set) | 10⁵ reference units, 60 basis functions | 0.036 s per unit | 0.9 GB |
68
+ | Exact total bound | 10⁴ selected | 25 s | 0.2 GB |
69
+
70
+ At small sizes these gains shrink or vanish: at 10³ reference units the active set is 1.6 times faster than the full dual, and the budget rule is no faster than a careful per-unit loop up to 10⁵ candidates.
@@ -0,0 +1,28 @@
1
+ """regioncp in one minute: a synthetic map, a random audit, and intervals at the places a rule selects.
2
+
3
+ python examples/quickstart.py
4
+ """
5
+ import numpy as np
6
+ import regioncp as rcp
7
+
8
+ rng = np.random.default_rng(0)
9
+ N = 4000
10
+ mu = rng.normal(size=N) # the map's prediction at every place
11
+ sigma = 0.3 + 0.2 * np.abs(mu) # its modelled error spread
12
+ y = mu + (0.2 + 0.5 * np.maximum(mu, 0)) * rng.standard_normal(N) # the truth: errors grow at the top of the map
13
+
14
+ perm = rng.permutation(N)
15
+ audited, candidates = perm[:2000], perm[2000:] # a random audit; y is known only at audited places
16
+ scores = np.abs(y[audited] - mu[audited]) / sigma[audited]
17
+
18
+ sel = rcp.top_k(mu[audited], mu[candidates], K=40) # the rule: the 40 highest-predicted candidates
19
+ q = rcp.jomi(scores, sel, alpha=0.1)
20
+ J = candidates[sel.selected]
21
+
22
+ all_scores = np.abs(y[candidates] - mu[candidates]) / sigma[candidates]
23
+ q_split = np.sort(scores)[int(np.ceil(0.9 * (len(scores) + 1))) - 1]
24
+ print(f"{sel}")
25
+ print(f"reference places: {sel.sizes[0]}, half-width {q[0]:.2f} spreads (split CP: {q_split:.2f})")
26
+ print(f"coverage of split CP at all candidates: {(all_scores <= q_split).mean():.2f}")
27
+ print(f"coverage at the selected places: split CP {(all_scores[sel.selected] <= q_split).mean():.2f}, JOMI {(all_scores[sel.selected] <= q).mean():.2f}")
28
+ print(f"audit needed for a 0.9 chance of finite intervals: {rcp.plan.n_for_finite(m=2000, K=40)} places")
@@ -0,0 +1,32 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "regioncp"
7
+ version = "0.1.0"
8
+ description = "Uncertainty at the places a map selects: selection-conditional conformal calibration, audit planning and project-total bounds for rank-based geographic decisions"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ authors = [{name = "Peng Luo"}]
13
+ requires-python = ">=3.9"
14
+ dependencies = ["numpy>=1.22", "scipy>=1.9"]
15
+ keywords = ["conformal prediction", "selective inference", "uncertainty quantification", "geospatial", "earth observation"]
16
+ classifiers = [
17
+ "Development Status :: 4 - Beta",
18
+ "Intended Audience :: Science/Research",
19
+ "Programming Language :: Python :: 3",
20
+ "Topic :: Scientific/Engineering :: GIS",
21
+ "Topic :: Scientific/Engineering :: Mathematics",
22
+ ]
23
+
24
+ [project.urls]
25
+ Homepage = "https://github.com/pengtum/winners-curse-of-maps"
26
+
27
+ [project.optional-dependencies]
28
+ basis = ["scikit-learn>=1.0"]
29
+ test = ["pytest"]
30
+
31
+ [tool.setuptools.packages.find]
32
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,26 @@
1
+ """regioncp: uncertainty at the places a map selects.
2
+
3
+ Named after RegionCP, the paper's method for coverage within regions; the package also holds the reference sets and JOMI
4
+ thresholds, the total bounds, cfBH and the audit planner. Version 0.1.0 was first released under the name mapselect.
5
+
6
+ Rank a map, select places, and calibrate each selected place only on audited places the same rule would have selected:
7
+
8
+ import regioncp as rcp
9
+ sel = rcp.top_k(mu[audited], mu[candidates], K=30)
10
+ q = rcp.jomi(scores[audited], sel, alpha=0.1) # interval half-widths on the score scale
11
+ rcp.plan.n_for_finite(m=3000, K=30) # the audit needed, before any outcome is measured
12
+
13
+ Guarantees need a random audit of one finite population, a map fitted separately, and a rule that uses covariates alone and
14
+ treats audited units symmetrically.
15
+ """
16
+ from .refsets import Selection, top_k, quota, budget, publication_mask, threshold, within_groups
17
+ from .calibrate import jomi, sc_geoccp
18
+ regioncp = sc_geoccp # RegionCP, the name used in the paper (2026-11-08); sc_geoccp is kept
19
+ from .totals import selection_aware_total, exact_lower_total, vcs_credit
20
+ from .funding import cfbh, cf_pvalues, bh
21
+ from . import planner as plan, bruteforce, rules, basis
22
+
23
+ __version__ = "0.1.0"
24
+ __all__ = ["Selection", "top_k", "quota", "budget", "publication_mask", "threshold", "within_groups", "jomi", "regioncp", "sc_geoccp",
25
+ "selection_aware_total", "exact_lower_total", "vcs_credit", "cfbh", "cf_pvalues", "bh", "plan", "bruteforce",
26
+ "rules", "basis"]
@@ -0,0 +1,99 @@
1
+ """Certified totals over a top/bottom-K selected set (the manuscript's Lemma 1 and Theorem 2(a)).
2
+
3
+ Given the pool P = selected u reference set (Lemma P: the selected set is a uniform K-subset of
4
+ P), the bucket counts N_b = #{selected values below the (b+1)-th smallest reference value} have a
5
+ value-free law. `envelope_exact` returns a nondecreasing integer envelope C with
6
+ P(exists b: N_b > C_b | P) <= delta computed EXACTLY by lattice-path DP (no Monte Carlo error) and certified in
7
+ integer arithmetic before it is returned;
8
+ `lower_total` turns it into a lower bound for the selected total of v (residuals or any fixed
9
+ transform), given an explicit support floor for bucket-0 values.
10
+ """
11
+ from fractions import Fraction
12
+ from itertools import accumulate
13
+ from math import comb, lgamma
14
+ import numpy as np
15
+
16
+
17
+ def good_paths(ell, K, C):
18
+ """Integer count of the K-subsets of ell slots with N_b <= C_b for all b; len(C) = ell - K + 1. One row at a time."""
19
+ nR = ell - K
20
+ row = [1] * (K + 1) # row 0: all K marks can come before the first unmarked slot
21
+ for i in range(nR):
22
+ c = int(C[i])
23
+ row = list(accumulate(v if s <= c else 0 for s, v in enumerate(row)))
24
+ return row[K]
25
+
26
+
27
+ def valid_prob(ell, K, C):
28
+ """P(N_b <= C_b for all b) for S a uniform K-subset of ell slots; len(C) = ell - K + 1."""
29
+ return good_paths(ell, K, C) / comb(ell, K)
30
+
31
+
32
+ def violation_exact(ell, K, C):
33
+ """P(exists b: N_b > C_b) as an exact rational."""
34
+ tot = comb(ell, K)
35
+ return Fraction(tot - good_paths(ell, K, C), tot)
36
+
37
+
38
+ def valid_prob_fast(ell, K, C):
39
+ """valid_prob in floating point: row i+1 of the lattice-path counts is the cumulative sum of row i
40
+ masked to s <= C_i; rows are rescaled to avoid overflow. Agrees with valid_prob to ~1e-12."""
41
+ nR = ell - K
42
+ s = np.arange(K + 1); f = np.ones(K + 1); logc = 0.0
43
+ for i in range(nR):
44
+ f = np.cumsum(np.where(s <= C[i], f, 0.0))
45
+ if f[-1] <= 0:
46
+ return 0.0
47
+ logc += np.log(f[-1]); f /= f[-1]
48
+ return float(np.exp(logc + np.log(f[K]) - (lgamma(ell + 1) - lgamma(K + 1) - lgamma(nR + 1))))
49
+
50
+
51
+ def _moments(ell, K):
52
+ """Exact mean and sd of N_b (number of K marked slots before the (b+1)-th unmarked one)."""
53
+ nR = ell - K; b = np.arange(nR)
54
+ # N_b ~ negative-hypergeometric: E = K (b+1) / (nR+1), Var = K (b+1)(nR-b)(ell+1) / ((nR+1)^2 (nR+2))
55
+ mean = K * (b + 1) / (nR + 1)
56
+ var = K * (b + 1) * (nR - b) * (ell + 1) / ((nR + 1) ** 2 * (nR + 2))
57
+ return mean, np.sqrt(np.maximum(var, 1e-12))
58
+
59
+
60
+ def envelope_exact(ell, K, delta, iters=40, fast=False):
61
+ """Shape floor(mean + lam sd) (value-free), lam by bisection on the EXACT violation probability.
62
+ fewer iterations only make it slightly more conservative; fast=True uses valid_prob_fast (floating point, same
63
+ law). The returned envelope is certified in integer arithmetic, violation <= Fraction(repr(delta)) (the shortest
64
+ decimal of the float: exactly 1/20 and 3/10, and 0.3333333333333333 <= 1/3); if the certificate fails, the trivial
65
+ envelope C = K (violation 0) is returned."""
66
+ vp = valid_prob_fast if fast else valid_prob
67
+ nR = ell - K
68
+ if nR == 0:
69
+ return np.array([K])
70
+ mu, sd = _moments(ell, K)
71
+
72
+ def C_of(lam):
73
+ C = np.maximum.accumulate(np.minimum(K, np.floor(mu + lam * sd))).astype(int)
74
+ return list(C) + [K]
75
+ lo, hi = 0.0, 12.0
76
+ for _ in range(iters):
77
+ lam = (lo + hi) / 2
78
+ if 1 - vp(ell, K, C_of(lam)) > delta:
79
+ lo = lam
80
+ else:
81
+ hi = lam
82
+ C = C_of(hi)
83
+ if violation_exact(ell, K, C) > Fraction(repr(float(delta))):
84
+ C = [K] * (nR + 1)
85
+ return np.array(C)
86
+
87
+
88
+ def lower_total(r_obs, K, floor, C, weights=None):
89
+ """sum_S v >= sum_b (C_b - C_{b-1}) r_(b) on the envelope event (r_(0) = min(floor, r_(1)));
90
+ with weights (sigma_j > 0) the rearrangement bound for sum_S sigma_j v_j."""
91
+ r_obs = np.sort(np.asarray(r_obs, float))
92
+ if len(r_obs):
93
+ floor = min(floor, r_obs[0])
94
+ r = np.r_[floor, r_obs]
95
+ c = np.diff(np.r_[0, C]).astype(int)
96
+ vals = np.repeat(r, c)[:K]
97
+ if weights is None:
98
+ return float(vals.sum())
99
+ return float((np.sort(vals) * np.sort(np.asarray(weights, float))[::-1]).sum())
@@ -0,0 +1,39 @@
1
+ """Function class for RegionCP (SC-GeoCCP in earlier versions): intercept, Gaussian bumps at several spatial scales, indicators of decision units.
2
+ The basis must be fixed given the training fold; it may use training coordinates, never audited or candidate outcomes."""
3
+ import numpy as np
4
+
5
+
6
+ class Multiscale:
7
+ """Columns lie in [0, 1], so one L1 penalty acts on all of them on the same scale. Needs scikit-learn (k-means)."""
8
+
9
+ def __init__(self, s_train, levels=(4, 12, 36), seed=0, min_per_centre=15):
10
+ from sklearn.cluster import KMeans
11
+ from scipy.spatial import cKDTree
12
+ s_train = np.asarray(s_train, float)
13
+ self.centres, self.h, self.level = [], [], []
14
+ for lv, k in enumerate(levels):
15
+ k = int(min(k, max(2, len(s_train) // min_per_centre)))
16
+ c = KMeans(k, n_init=4, random_state=seed).fit(s_train).cluster_centers_
17
+ d = cKDTree(c).query(c, k=2)[0][:, 1]
18
+ self.centres.append(c); self.h += [np.median(d)] * k; self.level += [lv] * k
19
+ self.centres = np.vstack(self.centres); self.h = np.array(self.h); self.level = np.array(self.level)
20
+ self.units = None
21
+
22
+ def with_units(self, units):
23
+ self.units = np.unique(units)
24
+ return self
25
+
26
+ def __call__(self, s, units=None):
27
+ s = np.asarray(s, float)
28
+ D2 = ((s[:, None, :] - self.centres[None, :, :]) ** 2).sum(-1)
29
+ cols = [np.ones((len(s), 1)), np.exp(-0.5 * D2 / self.h[None, :] ** 2)]
30
+ if self.units is not None:
31
+ cols.append((np.asarray(units)[:, None] == self.units[None, :]).astype(float))
32
+ return np.hstack(cols)
33
+
34
+ @property
35
+ def penalize(self):
36
+ """Only the intercept is unpenalized, which gives exact coverage among all selected units."""
37
+ p = 1 + len(self.h) + (0 if self.units is None else len(self.units))
38
+ pen = np.ones(p, bool); pen[0] = False
39
+ return pen
@@ -0,0 +1,26 @@
1
+ """Reference sets by literal swapping (Jin & Ren 2025, Sec. 3.2): the ground truth for the closed forms, and the fallback for
2
+ any covariate-only rule. Cost: |selected| x n reruns of the rule, each at least linear in the candidates."""
3
+ import numpy as np
4
+
5
+
6
+ def _swap(audit, test, i, j):
7
+ a2, t2 = {}, {}
8
+ for k in test:
9
+ av, tv = np.array(audit[k], copy=True), np.array(test[k], copy=True)
10
+ av[i], tv[j] = test[k][j], audit[k][i]
11
+ a2[k], t2[k] = av, tv
12
+ return a2, t2
13
+
14
+
15
+ def reference_matrix(rule, audit, test, rows=None):
16
+ """Boolean matrix |selected| x n. `rule(audit, test)` returns a boolean array over test units; audit and test are dicts of
17
+ arrays with the same keys. `rows` limits the work to some selected units, for timing a sample of swaps."""
18
+ sel = np.flatnonzero(np.asarray(rule(audit, test), bool))
19
+ rows = np.arange(len(sel)) if rows is None else np.asarray(rows, int)
20
+ n = len(next(iter(audit.values())))
21
+ M = np.zeros((len(rows), n), bool)
22
+ for a, r in enumerate(rows):
23
+ for i in range(n):
24
+ a2, t2 = _swap(audit, test, i, sel[r])
25
+ M[a, i] = bool(rule(a2, t2)[sel[r]])
26
+ return sel, M
@@ -0,0 +1,169 @@
1
+ """Calibration on reference sets. An interval for a selected unit j is {y : score(x_j, y) <= q_j}; q_j may be +inf."""
2
+ import warnings
3
+ import numpy as np
4
+ from scipy import sparse
5
+ from scipy.optimize import linprog
6
+
7
+
8
+ def _rank(N, alpha):
9
+ tau = 1 - alpha
10
+ return np.ceil(tau * (N + 1) - 1e-9 * (N + 1)).astype(int) # k-th smallest; infinite when k > N
11
+
12
+
13
+ def _kth_two_sorted(a, b, k):
14
+ """k-th smallest (1-indexed) of the union of two sorted arrays, without merging them."""
15
+ lo, hi = max(0, k - len(b)), min(k, len(a))
16
+ while lo < hi:
17
+ i = (lo + hi) // 2
18
+ if a[i] < b[k - i - 1]:
19
+ lo = i + 1
20
+ else:
21
+ hi = i
22
+ x = a[lo - 1] if lo > 0 else -np.inf
23
+ y = b[k - lo - 1] if k - lo > 0 else -np.inf
24
+ return max(x, y)
25
+
26
+
27
+ def jomi(scores_audit, sel, alpha=0.1):
28
+ """Joint Mondrian conformal inference (Jin & Ren): the ceil((1-alpha)(|R_j|+1))-th smallest score in R_j, or +inf.
29
+ Coverage is at least 1 - alpha among selected units, on average over audits."""
30
+ S = np.asarray(scores_audit, float)
31
+ q = np.full(len(sel), np.inf)
32
+ sorted_sets = [np.sort(S[s]) for s in sel.sets]
33
+ if sel.extras is None:
34
+ for a, ss in enumerate(sorted_sets):
35
+ k = int(_rank(len(ss), alpha))
36
+ if k <= len(ss):
37
+ q[sel.set_id == a] = ss[k - 1]
38
+ return q
39
+ for r in range(len(sel)):
40
+ base = sorted_sets[sel.set_id[r]]
41
+ ext = np.sort(S[sel.extras(r)])
42
+ N = len(base) + len(ext); k = int(_rank(N, alpha))
43
+ if k <= N:
44
+ q[r] = _kth_two_sorted(base, ext, k)
45
+ return q
46
+
47
+
48
+ def objective(beta, S, Phi, phi_j, tau, l1, pen):
49
+ """The programme's objective at beta."""
50
+ r = S - Phi @ beta
51
+ return float(np.maximum(tau * r, (tau - 1) * r).sum() - tau * phi_j @ beta + l1 * np.abs(beta[pen]).sum())
52
+
53
+
54
+ def _primal_beta(S, Phi, phi_j, tau, l1, pen):
55
+ n, p = Phi.shape
56
+ k = int(pen.sum()) if l1 > 0 else 0
57
+ Aeq = sparse.hstack([sparse.csr_matrix(Phi), sparse.csr_matrix((n, k)), sparse.eye(n), -sparse.eye(n)], format="csc")
58
+ Aub = None; bub = None
59
+ if k:
60
+ P = sparse.csr_matrix((np.ones(k), (np.arange(k), np.flatnonzero(pen))), shape=(k, p))
61
+ Z = sparse.csr_matrix((k, 2 * n)); I = sparse.eye(k)
62
+ Aub = sparse.vstack([sparse.hstack([P, -I, Z]), sparse.hstack([-P, -I, Z])], format="csc"); bub = np.zeros(2 * k)
63
+ c = np.r_[-tau * phi_j, np.full(k, l1), np.full(n, tau), np.full(n, 1 - tau)]
64
+ bounds = [(None, None)] * p + [(0, None)] * (k + 2 * n)
65
+ r = linprog(c, A_ub=Aub, b_ub=bub, A_eq=Aeq, b_eq=S, bounds=bounds, method="highs")
66
+ return r.x[:p] if r.status == 0 else None
67
+
68
+
69
+ def _dual_beta(S, Phi, phi_j, tau, l1, pen):
70
+ """The same programme through its dual: p rows instead of n, so its size is set by the basis and not the reference set.
71
+ max sum u_i S_i, u in [tau - 1, tau]^n, sum u_i Phi_i + tau phi_j = 0 unpenalized, |.| <= l1 penalized; beta = row duals."""
72
+ n, p = Phi.shape
73
+ if n < tau / (1 - tau) - 1e-12: # Proposition 2: the primal is unbounded
74
+ return None
75
+ A = Phi.T; f = np.flatnonzero(~pen); g = np.flatnonzero(pen)
76
+ r = linprog(-S, A_ub=np.vstack([A[g], -A[g]]) if len(g) else None,
77
+ b_ub=np.r_[l1 - tau * phi_j[g], l1 + tau * phi_j[g]] if len(g) else None,
78
+ A_eq=A[f] if len(f) else None, b_eq=-tau * phi_j[f] if len(f) else None,
79
+ bounds=(tau - 1, tau), method="highs")
80
+ if r.status != 0:
81
+ warnings.warn(f"linear programme failed with HiGHS status {r.status}; returning an infinite interval")
82
+ return None
83
+ beta = np.zeros(p)
84
+ if len(f):
85
+ beta[f] = -r.eqlin.marginals # beta = -(row duals of the minimization of -S'u)
86
+ if len(g):
87
+ d = r.ineqlin.marginals
88
+ beta[g] = d[len(g):] - d[:len(g)]
89
+ return beta
90
+
91
+
92
+ def _active_beta(S, Phi, phi_j, tau, l1, pen, beta0, free=None, max_rounds=30):
93
+ """The dual solved on an active set, after Portnoy and Koenker (1997). In the dual, u_i sits at tau where the residual is
94
+ positive and at tau - 1 where it is negative, so only units near the fitted surface are free. Fix the others by the signs of
95
+ the residuals at a warm start, solve the small programme, and free any unit whose sign turns out wrong. When none is wrong
96
+ the reduced solution satisfies the optimality conditions of the full programme, up to the 1e-9 sign check on fixed units and the solver's tolerance on free ones.
97
+ Returns (beta, rounds, size of the last free set)."""
98
+ n, p = Phi.shape
99
+ if n < tau / (1 - tau) - 1e-12:
100
+ return None, 0, 0
101
+ nfree = min(n, max(200, 10 * p) if free is None else free)
102
+ r0 = S - Phi @ beta0
103
+ F = np.zeros(n, bool); F[np.argpartition(np.abs(r0), nfree - 1)[:nfree]] = True
104
+ u = np.where(r0 > 0, tau, tau - 1.0)
105
+ f = np.flatnonzero(~pen); g = np.flatnonzero(pen)
106
+ for rounds in range(1, max_rounds + 1):
107
+ fixed = Phi[~F].T @ u[~F] if (~F).any() else np.zeros(p)
108
+ A = Phi[F].T; c = tau * phi_j + fixed
109
+ r = linprog(-S[F], A_ub=np.vstack([A[g], -A[g]]) if len(g) else None,
110
+ b_ub=np.r_[l1 - c[g], l1 + c[g]] if len(g) else None,
111
+ A_eq=A[f] if len(f) else None, b_eq=-c[f] if len(f) else None, bounds=(tau - 1, tau), method="highs")
112
+ if r.status != 0: # these signs admit no feasible point: free more units
113
+ if F.all():
114
+ warnings.warn(f"linear programme failed with HiGHS status {r.status}; returning an infinite interval")
115
+ return None, rounds, int(F.sum())
116
+ k = min(n, 2 * int(F.sum()))
117
+ F[np.argpartition(np.abs(S - Phi @ beta0), k - 1)[:k]] = True
118
+ continue
119
+ beta = np.zeros(p)
120
+ if len(f):
121
+ beta[f] = -r.eqlin.marginals
122
+ if len(g):
123
+ d = r.ineqlin.marginals
124
+ beta[g] = d[len(g):] - d[:len(g)]
125
+ res = S - Phi @ beta
126
+ wrong = ~F & (((res > 1e-9) & (u < 0)) | ((res < -1e-9) & (u > 0)))
127
+ if not wrong.any():
128
+ return beta, rounds, int(F.sum())
129
+ F |= wrong; u[wrong] = np.where(res[wrong] > 0, tau, tau - 1.0)
130
+ beta0 = beta
131
+ return _dual_beta(S, Phi, phi_j, tau, l1, pen), max_rounds, n # never seen in the tests; the full dual is the fallback
132
+
133
+
134
+ def sc_geoccp(scores_audit, sel, Phi_audit, Phi_selected, alpha=0.1, l1=0.95, penalize=None, form="active"):
135
+ """RegionCP (also exported as `regioncp`; SC-GeoCCP in earlier versions): per selected unit, the augmented quantile regression of Gibbs, Cherian and Candes on R_j over a basis fixed
136
+ given the map, test score imputed at +inf, L1 penalty on the `penalize` columns (default: all but the first).
137
+
138
+ form: "active" (default; warm-started active set, exact), "dual" or "primal" (full programmes, cold). Any minimizer carries
139
+ the coverage floors of the manuscript's Theorem 1, so the forms share the guarantee; where the programme has several
140
+ minimizers they may return different ones.
141
+
142
+ Numerical safeguard: when every reference score of a selected unit is below 1e-6 (outcome and prediction both zero, so
143
+ the scores are only a tie-breaking jitter), the programme is solved on the scores divided by their maximum and the
144
+ threshold multiplied back; the programme is positively homogeneous in the scores, so the threshold is unchanged. Other
145
+ reference sets take exactly the original path. The non-default form="primal" also relies on the LP solver's absolute
146
+ tolerances for scores between 1e-6 and about 1e-4; use the default form there."""
147
+ S = np.asarray(scores_audit, float); Pa = np.asarray(Phi_audit, float); Ps = np.asarray(Phi_selected, float)
148
+ pen = np.r_[False, np.ones(Pa.shape[1] - 1, bool)] if penalize is None else np.asarray(penalize, bool)
149
+ tau = 1 - alpha; q = np.empty(len(sel)); beta0 = None
150
+ for r in range(len(sel)):
151
+ idx = sel.reference(r)
152
+ Sr = S[idx]
153
+ sc = float(Sr.max()) if Sr.size else 0.0
154
+ sc = sc if 0.0 < sc < 1e-6 else 1.0 # safeguard (see docstring); 1.0 leaves the path unchanged
155
+ Sr = Sr / sc
156
+ if form == "active":
157
+ if beta0 is None: # warm start, kept in the original units
158
+ beta0 = np.zeros(Pa.shape[1])
159
+ if len(idx):
160
+ beta0[0] = np.quantile(S[idx], tau)
161
+ b = _active_beta(Sr, Pa[idx], Ps[r], tau, l1, pen, beta0 / sc)[0]
162
+ if b is not None:
163
+ b = b * sc
164
+ beta0 = b
165
+ else:
166
+ b = {"dual": _dual_beta, "primal": _primal_beta}[form](Sr, Pa[idx], Ps[r], tau, l1, pen)
167
+ b = b * sc if b is not None else None
168
+ q[r] = Ps[r] @ b if b is not None else np.inf
169
+ return q