mapselect 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.
mapselect/__init__.py ADDED
@@ -0,0 +1,23 @@
1
+ """mapselect: uncertainty at the places a map selects.
2
+
3
+ Rank a map, select places, and calibrate each selected place only on audited places the same rule would have selected:
4
+
5
+ import mapselect as ms
6
+ sel = ms.top_k(mu[audited], mu[candidates], K=30)
7
+ q = ms.jomi(scores[audited], sel, alpha=0.1) # interval half-widths on the score scale
8
+ ms.plan.n_for_finite(m=3000, K=30) # the audit needed, before any outcome is measured
9
+
10
+ Guarantees need a random audit of one finite population, a map fitted separately, and a rule that uses covariates alone and
11
+ treats audited units symmetrically.
12
+ """
13
+ from .refsets import Selection, top_k, quota, budget, publication_mask, threshold, within_groups
14
+ from .calibrate import jomi, sc_geoccp
15
+ regioncp = sc_geoccp # RegionCP, the name used in the paper (2026-11-08); sc_geoccp is kept
16
+ from .totals import selection_aware_total, exact_lower_total, vcs_credit
17
+ from .funding import cfbh, cf_pvalues, bh
18
+ from . import planner as plan, bruteforce, rules, basis
19
+
20
+ __version__ = "0.1.0"
21
+ __all__ = ["Selection", "top_k", "quota", "budget", "publication_mask", "threshold", "within_groups", "jomi", "regioncp", "sc_geoccp",
22
+ "selection_aware_total", "exact_lower_total", "vcs_credit", "cfbh", "cf_pvalues", "bh", "plan", "bruteforce",
23
+ "rules", "basis"]
mapselect/_envelope.py ADDED
@@ -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())
mapselect/basis.py ADDED
@@ -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
mapselect/calibrate.py ADDED
@@ -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
mapselect/funding.py ADDED
@@ -0,0 +1,54 @@
1
+ """Conformal Benjamini-Hochberg on reference sets (the manuscript's Theorem 3)."""
2
+ import numpy as np
3
+
4
+
5
+ def _check_scope(psi, ps, sel):
6
+ """This API supports top-/bottom-K pools and scores without ties."""
7
+ # A mixed quota can also have one shared set when only one group has candidates.
8
+ # Check the rule created by top_k, not just the number of reference sets.
9
+ direction, separator, count = sel.name.partition("-")
10
+ is_topk = direction in ("top", "bottom") and separator == "-" and count.isdecimal()
11
+ if not is_topk or not sel.shared:
12
+ raise ValueError(
13
+ f"This cfBH API supports only a top- or bottom-K rule with one shared reference set; "
14
+ f"{sel!r} has {len(sel.sets)} shared set(s){' and unit-specific extras' if sel.extras is not None else ''}. "
15
+ "For a quota, build a top_k selection within each group from that group's audited and candidate units and run "
16
+ "cfbh on each: that controls the FDR within each group, not over all groups.")
17
+ if not len(sel):
18
+ return
19
+ v = np.r_[psi[sel.sets[0]], ps]
20
+ if len(np.unique(v)) < len(v):
21
+ raise ValueError("psi has tied values among the reference set and the selected units, which Theorem 3 excludes; "
22
+ "break the ties first, e.g. psi + 1e-9 * rng.standard_normal(len(psi)) with a fixed seed")
23
+
24
+
25
+ def cf_pvalues(psi_audit, null_audit, psi_selected, sel):
26
+ """p_j = (1 + #{i in R_j : unit i is ineligible, psi_i < psi_j}) / (|R_j| + 1).
27
+
28
+ Supports top_k selections in either direction with one shared reference set; other rules (including quotas with
29
+ only one selected group) and tied values of psi raise ValueError. An empty supported selection returns no p-values."""
30
+ psi = np.asarray(psi_audit, float); null = np.asarray(null_audit, bool); ps = np.asarray(psi_selected, float)
31
+ _check_scope(psi, ps, sel)
32
+ p = np.empty(len(sel))
33
+ for a, s in enumerate(sel.sets):
34
+ v = np.sort(psi[s][null[s]]); r = sel.set_id == a
35
+ p[r] = (1 + np.searchsorted(v, ps[r], side="left")) / (len(s) + 1)
36
+ return p
37
+
38
+
39
+ def bh(p, q):
40
+ """Benjamini-Hochberg rejections at level q."""
41
+ p = np.asarray(p, float); m = len(p)
42
+ if not m:
43
+ return np.zeros(0, bool)
44
+ o = np.argsort(p); ok = np.flatnonzero(p[o] <= q * np.arange(1, m + 1) / m)
45
+ out = np.zeros(m, bool)
46
+ if len(ok):
47
+ out[o[:ok[-1] + 1]] = True
48
+ return out
49
+
50
+
51
+ def cfbh(psi_audit, null_audit, psi_selected, sel, q=0.1):
52
+ """Units funded by cfBH at FDR level q, as a boolean array over the selected units, with their p-values."""
53
+ p = cf_pvalues(psi_audit, null_audit, psi_selected, sel)
54
+ return bh(p, q), p
mapselect/planner.py ADDED
@@ -0,0 +1,99 @@
1
+ """Audit planner: what a rule's reference sets will hold, computed before any audited outcome is measured.
2
+
3
+ For a top- or bottom-K rule with distinct keys fixed given the map, under a random split of a finite population into
4
+ n audited units and m candidates, |R| = #{audited units ranked above the (K+1)-th candidate} is negative
5
+ hypergeometric (M = n + m, successes n, r = K + 1), so with tau = 1 - alpha:
6
+
7
+ finite interval Pr(finite) = Pr(|R| >= ceil(tau / alpha))
8
+ moment E[1 / (|R| + 1)] = m (1 - eps) / {K (n + 1)}, eps = C(n + m - K, m - K - 1) / C(n + m, m - 1)
9
+ floor (Theorem 1) floor(u) = tau - l1 m (1 - eps) / {(n + 1) M_u}, M_u = E[sum over selected of f(X_j)]
10
+ (M_u = K_u, the expected selected units of region u, for a group indicator)
11
+ exact total bound Pr(N_0 >= 1) = K / l, so C_0 = 0 (no outcome bound enters) needs K / (n_R + K) <= delta
12
+
13
+ A targeted audit draws the n audited units at random from a stratum fixed given the map (for example the highest-
14
+ predicted 5% of the population). Every statement above then holds with m = the stratum's candidates, because
15
+ the stratum is itself a finite population under a random split, and a top-K rule selects inside it when it holds at
16
+ least K candidates. Formulas are checked against full enumeration in the project's tests.
17
+ """
18
+ from math import ceil, exp, lgamma
19
+ import numpy as np
20
+ from scipy.stats import nhypergeom
21
+
22
+
23
+ def _lchoose(a, b):
24
+ return lgamma(a + 1) - lgamma(b + 1) - lgamma(a - b + 1)
25
+
26
+
27
+ def _thr(alpha):
28
+ return int(ceil((1 - alpha) / alpha - 1e-12)) # JOMI is finite iff |R| >= tau / alpha
29
+
30
+
31
+ def p_finite(n, m, K, alpha=0.1):
32
+ """Pr(a top-K rule's selected units get finite (1 - alpha) intervals). Requires K < m."""
33
+ if n < _thr(alpha):
34
+ return 0.0
35
+ return float(nhypergeom(n + m, n, K + 1).sf(_thr(alpha) - 1))
36
+
37
+
38
+ def mean_refset(n, m, K):
39
+ """E|R| = n (K + 1) / (m + 1)."""
40
+ return n * (K + 1) / (m + 1)
41
+
42
+
43
+ def inv_moment(n, m, K):
44
+ """E[1 / (|R| + 1)], exact."""
45
+ if m - K - 1 < 0:
46
+ raise ValueError("needs K < m")
47
+ eps = exp(_lchoose(n + m - K, m - K - 1) - _lchoose(n + m, m - 1)) # log-gamma, so that pools of 10^6 stay fast
48
+ return m * (1 - eps) / (K * (n + 1))
49
+
50
+
51
+ def floor(n, m, K, M_u, alpha=0.1, l1=0.95):
52
+ """Theorem 1's coverage floor for a basis function f >= 0 with expected selected mass M_u; <= 0 means no guarantee."""
53
+ return 1 - alpha - l1 * inv_moment(n, m, K) * K / M_u
54
+
55
+
56
+ def n_for_finite(m, K, prob=0.9, alpha=0.1, nmax=10 ** 7):
57
+ """Smallest audit of a fixed candidate pool m with Pr(finite) >= prob (bisection; p_finite increases in n)."""
58
+ lo, hi = _thr(alpha) - 1, _thr(alpha)
59
+ while p_finite(hi, m, K, alpha) < prob:
60
+ lo, hi = hi, hi * 2
61
+ if hi > nmax:
62
+ return None
63
+ while hi - lo > 1:
64
+ mid = (lo + hi) // 2
65
+ lo, hi = (lo, mid) if p_finite(mid, m, K, alpha) >= prob else (mid, hi)
66
+ return hi
67
+
68
+
69
+ def n_for_floor(m, K, M_u, target, alpha=0.1, l1=0.95, nmax=10 ** 7):
70
+ """Smallest audit with floor(u) >= target for a fixed candidate pool m; None if unreachable below nmax."""
71
+ if target >= 1 - alpha:
72
+ return None
73
+ lo, hi = 0, 1
74
+ while floor(hi, m, K, M_u, alpha, l1) < target:
75
+ lo, hi = hi, hi * 2
76
+ if hi > nmax:
77
+ return None
78
+ while hi - lo > 1:
79
+ mid = (lo + hi) // 2
80
+ lo, hi = (lo, mid) if floor(mid, m, K, M_u, alpha, l1) >= target else (mid, hi)
81
+ return hi
82
+
83
+
84
+ def n_budget_for_finite(population, K, prob=0.9, alpha=0.1):
85
+ """Smallest audit when audited units leave the pool (m = population - n), with K kept fixed.
86
+ p_finite rises with n here too, because n rises and m falls. None if no audit leaves K + 1 candidates and reaches prob."""
87
+ hi_max = population - K - 1
88
+ if hi_max < _thr(alpha) or p_finite(hi_max, population - hi_max, K, alpha) < prob:
89
+ return None
90
+ lo, hi = _thr(alpha) - 1, hi_max
91
+ while hi - lo > 1:
92
+ mid = (lo + hi) // 2
93
+ lo, hi = (lo, mid) if p_finite(mid, population - mid, K, alpha) >= prob else (mid, hi)
94
+ return hi
95
+
96
+
97
+ def planned_se_ratio(n, m, K):
98
+ """Planned selection-aware SE of a project total over the SE of K independent errors, (1 + K / E|R|)^(1/2)."""
99
+ return float(np.sqrt(1 + K / max(mean_refset(n, m, K), 1e-12)))
mapselect/refsets.py ADDED
@@ -0,0 +1,225 @@
1
+ """Closed-form reference sets for covariate-only selection rules, in compact form.
2
+
3
+ The reference set of a selected unit j is R_j = {audited i : j is still selected after swapping i and j}. Most selected units
4
+ share most of their reference set, so a `Selection` stores shared index arrays, plus, for rules where R_j really differs by
5
+ unit (budget, mask), the few audited units that can enter it. Memory is about the size of the reference sets instead of
6
+ |selected| x n, which is what makes a rule on 10^6 candidates routine.
7
+
8
+ Keys must be distinct for the guarantees of the manuscript's Theorems; ties do not break these functions.
9
+ All functions are checked against literal swaps in tests/test_refsets.py.
10
+ """
11
+ import numpy as np
12
+
13
+
14
+ class Selection:
15
+ """Selected test units and their reference sets.
16
+
17
+ selected indices into the test arrays
18
+ sets list of int arrays of audited-unit indices, shared by the units that point to them
19
+ set_id for each selected unit, the entry of `sets` it uses
20
+ extras optional function r -> audited-unit indices in R_j beyond the shared set, for the r-th selected unit
21
+ """
22
+
23
+ def __init__(self, selected, sets, set_id, name, n_audit, extras=None):
24
+ self.selected = np.asarray(selected, int)
25
+ self.sets = [np.asarray(s, int) for s in sets]
26
+ self.set_id = np.asarray(set_id, int)
27
+ self.name = name
28
+ self.n_audit = int(n_audit)
29
+ self.extras = extras
30
+
31
+ def __len__(self):
32
+ return len(self.selected)
33
+
34
+ def __repr__(self):
35
+ return f"Selection({self.name}, {len(self)} selected, {len(self.sets)} shared reference set(s))"
36
+
37
+ def reference(self, r):
38
+ """Audited-unit indices of R_j for the r-th selected unit."""
39
+ base = self.sets[self.set_id[r]]
40
+ return np.r_[base, self.extras(r)] if self.extras is not None else base
41
+
42
+ @property
43
+ def sizes(self):
44
+ base = np.array([len(s) for s in self.sets], int)[self.set_id] if len(self) else np.zeros(0, int)
45
+ if self.extras is None:
46
+ return base
47
+ return base + np.array([len(self.extras(r)) for r in range(len(self))], int)
48
+
49
+ @property
50
+ def shared(self):
51
+ """True if all selected units have one reference set."""
52
+ return self.extras is None and len(self.sets) == 1
53
+
54
+ def dense(self):
55
+ """Boolean matrix |selected| x n_audit (for checks and small problems)."""
56
+ M = np.zeros((len(self), self.n_audit), bool)
57
+ for r in range(len(self)):
58
+ M[r, self.reference(r)] = True
59
+ return M
60
+
61
+
62
+ def _kth_largest(x, k):
63
+ """k-th largest of x (1-indexed); -inf if fewer than k values, +inf if k <= 0."""
64
+ if k <= 0:
65
+ return np.inf
66
+ if len(x) < k:
67
+ return -np.inf
68
+ return np.partition(x, len(x) - k)[len(x) - k]
69
+
70
+
71
+ def top_k(key_audit, key_test, K, largest=True):
72
+ """The K candidates with the largest (or smallest) key. R_j = {i : x_i > (K+1)-th largest candidate key} for every j."""
73
+ xc = np.asarray(key_audit, float); xt = np.asarray(key_test, float)
74
+ if not largest:
75
+ xc, xt = -xc, -xt
76
+ K = int(K)
77
+ sel = np.argpartition(-xt, K - 1)[:K] if 0 < K < len(xt) else np.arange(min(K, len(xt)))
78
+ sel = np.sort(sel)
79
+ return Selection(sel, [np.flatnonzero(xc > _kth_largest(xt, K + 1))], np.zeros(len(sel), int),
80
+ f"{'top' if largest else 'bottom'}-{K}", len(xc))
81
+
82
+
83
+ def quota(key_audit, key_test, group_audit, group_test, K_by_group, largest=True):
84
+ """The K_g candidates with the largest key in each group g.
85
+
86
+ R_j = {i : x_i > T_{g_i}}, where T_g is the (K_g+1)-th largest candidate key of g if g is j's group and the K_g-th largest
87
+ otherwise. All selected units of one group share R_j, so there is one set per group."""
88
+ xc = np.asarray(key_audit, float); xt = np.asarray(key_test, float)
89
+ if not largest:
90
+ xc, xt = -xc, -xt
91
+ gc = np.asarray(group_audit); gt = np.asarray(group_test)
92
+ ugt, inv_t = np.unique(gt, return_inverse=True)
93
+ order = np.lexsort((-xt, inv_t)); starts = np.searchsorted(inv_t[order], np.arange(len(ugt)))
94
+ ends = np.r_[starts[1:], len(xt)]
95
+ picked = []
96
+ other, own = {}, {}
97
+ for a, u in enumerate(ugt):
98
+ k = int(K_by_group.get(u if not isinstance(u, np.generic) else u.item(), 0))
99
+ members = order[starts[a]:ends[a]]
100
+ if k > 0:
101
+ picked.append(members[:k])
102
+ other[a] = xt[members[k - 1]] if 0 < k <= len(members) else (np.inf if k <= 0 else -np.inf)
103
+ own[a] = xt[members[k]] if (k > 0 and k < len(members)) else (np.inf if k <= 0 else -np.inf)
104
+ sel = np.sort(np.concatenate(picked)) if picked else np.zeros(0, int)
105
+ # audited units of a group with no candidates: K_g-th largest of nothing is -inf if K_g > 0, +inf otherwise
106
+ ca = np.searchsorted(ugt, gc); known = (ca < len(ugt)) & (ugt[np.minimum(ca, len(ugt) - 1)] == gc)
107
+ T_other = np.full(len(xc), np.inf)
108
+ for a in other:
109
+ T_other[(ca == a) & known] = other[a]
110
+ for u in np.unique(gc[~known]):
111
+ k = int(K_by_group.get(u if not isinstance(u, np.generic) else u.item(), 0))
112
+ T_other[gc == u] = -np.inf if k > 0 else np.inf
113
+ base = xc > T_other
114
+ sets, set_of = [], {}
115
+ for a in np.unique(inv_t[sel]):
116
+ in_g = (ca == a) & known
117
+ m = base.copy(); m[in_g] = xc[in_g] > own[a]
118
+ set_of[a] = len(sets); sets.append(np.flatnonzero(m))
119
+ return Selection(sel, sets, np.array([set_of[a] for a in inv_t[sel]], int), "quota", len(xc))
120
+
121
+
122
+ def budget(value_audit, cost_audit, value_test, cost_test, B):
123
+ """Greedy budget: candidates in decreasing value / cost while cumulative cost stays within B.
124
+
125
+ R_j = {i : Q_{-j}(r_i) + t_i <= B}, Q_{-j}(r) the cost of the other candidates with a ratio above r. Audited units meeting
126
+ this with j's cost left in form the shared set; the rest can enter only if removing j's cost admits them."""
127
+ vc, cc = np.asarray(value_audit, float), np.asarray(cost_audit, float)
128
+ vt, ct = np.asarray(value_test, float), np.asarray(cost_test, float)
129
+ rt, rc = vt / ct, vc / cc
130
+ o = np.argsort(-rt, kind="stable")
131
+ keep = np.cumsum(ct[o]) <= B
132
+ sel = np.sort(o[keep])
133
+ a = np.argsort(rt); rs = rt[a]; suf = np.r_[np.cumsum(ct[a][::-1])[::-1], 0.0]
134
+ load = suf[np.searchsorted(rs, rc, side="right")] + cc # Q(r_i) + t_i, with j's cost still counted if r_j > r_i
135
+ base = np.flatnonzero(load <= B)
136
+ cmax = ct[sel].max() if len(sel) else 0.0
137
+ cand = np.flatnonzero((load > B) & (load - cmax <= B))
138
+ rj, cj = rt[sel], ct[sel]
139
+
140
+ def extras(r):
141
+ return cand[(rj[r] > rc[cand]) & (load[cand] - cj[r] <= B)]
142
+ return Selection(sel, [base], np.zeros(len(sel), int), "budget", len(vc), extras=extras)
143
+
144
+
145
+ def _gauss(A, Bm, h):
146
+ D2 = np.maximum((A ** 2).sum(1)[:, None] + (Bm ** 2).sum(1)[None, :] - 2 * A @ Bm.T, 0)
147
+ return np.exp(-0.5 * D2 / h ** 2)
148
+
149
+
150
+ def _kernel_sums(pts, sc, h, tree, radius, chunk):
151
+ """Sum over audited units of K_h(pts, s_i): all of them (tree is None), or those within `radius`."""
152
+ out = np.empty(len(pts))
153
+ if tree is None:
154
+ for a in range(0, len(pts), chunk):
155
+ out[a:a + chunk] = _gauss(pts[a:a + chunk], sc, h).sum(1)
156
+ return out
157
+ for a in range(0, len(pts), chunk):
158
+ P = pts[a:a + chunk]
159
+ nb = tree.query_ball_point(P, radius, workers=1)
160
+ counts = np.fromiter((len(x) for x in nb), int, len(nb))
161
+ rows = np.repeat(np.arange(len(P)), counts)
162
+ cols = np.concatenate([np.asarray(x, int) for x in nb]) if counts.sum() else np.zeros(0, int)
163
+ d2 = ((P[rows] - sc[cols]) ** 2).sum(1)
164
+ out[a:a + chunk] = np.bincount(rows, np.exp(-0.5 * d2 / h ** 2), len(P))
165
+ return out
166
+
167
+
168
+ def publication_mask(s_audit, s_test, h, alpha, chunk=2000, method="auto", tol=1e-9):
169
+ """Publish candidate k when sum_i K_h(s_k, s_i) >= (1-alpha)/alpha over audited units, K_h Gaussian.
170
+
171
+ R_j = {i : W_i + K_h(s_i, s_j) >= (1-alpha)/alpha}, W_i = sum_{i' != i} K_h(s_i, s_i').
172
+
173
+ method="dense" visits every audited unit for every kernel sum, quadratic in the audit. method="tree" prunes with a k-d tree
174
+ at a radius where the omitted mass is below tol, then recomputes densely the few sums within tol of the threshold, so the
175
+ selected units and reference sets are the same as dense. "auto" uses the tree above 20,000 audited units."""
176
+ sc = np.asarray(s_audit, float); st = np.asarray(s_test, float)
177
+ thr = (1 - alpha) / alpha
178
+ use_tree = method == "tree" or (method == "auto" and len(sc) > 20000)
179
+ tree, radius = None, None
180
+ if use_tree:
181
+ from scipy.spatial import cKDTree
182
+ tree = cKDTree(sc); radius = h * np.sqrt(2 * np.log(max(len(sc), 2) / tol))
183
+
184
+ W = _kernel_sums(sc, sc, h, tree, radius, chunk) - 1.0 # drop K(s_i, s_i) = 1
185
+ if use_tree:
186
+ for level in (thr, thr - 1.0): # the two comparisons that define base and cand below
187
+ near = np.flatnonzero(np.abs(W - level) <= tol)
188
+ if len(near):
189
+ W[near] = _kernel_sums(sc[near], sc, h, None, None, chunk) - 1.0
190
+ mass = _kernel_sums(st, sc, h, tree, radius, chunk)
191
+ if use_tree:
192
+ near = np.flatnonzero(np.abs(mass - thr) <= tol)
193
+ if len(near):
194
+ mass[near] = _kernel_sums(st[near], sc, h, None, None, chunk)
195
+ sel = np.flatnonzero(mass >= thr)
196
+ base = np.flatnonzero(W >= thr)
197
+ cand = np.flatnonzero((W < thr) & (W + 1.0 >= thr))
198
+
199
+ def extras(r):
200
+ if not len(cand):
201
+ return cand
202
+ return cand[W[cand] + _gauss(st[sel[r]][None, :], sc[cand], h)[0] >= thr]
203
+ return Selection(sel, [base], np.zeros(len(sel), int), "publication mask", len(sc), extras=extras)
204
+
205
+
206
+ def threshold(key_audit, key_test, c, above=True):
207
+ """Candidates past a fixed cut-off c; R_j holds the audited units past it."""
208
+ xc = np.asarray(key_audit, float); xt = np.asarray(key_test, float)
209
+ sel = np.flatnonzero(xt >= c if above else xt <= c)
210
+ return Selection(sel, [np.flatnonzero(xc >= c if above else xc <= c)], np.zeros(len(sel), int), "threshold", len(xc))
211
+
212
+
213
+ def within_groups(sel, group_audit, group_test):
214
+ """R_j intersected with j's group: coverage given the group, and the sets R_g of the pool lemma under a quota."""
215
+ if sel.extras is not None:
216
+ raise ValueError("within_groups needs a rule with shared reference sets")
217
+ gc = np.asarray(group_audit); gj = np.asarray(group_test)[sel.selected]
218
+ key = {}; sets = []; ids = np.empty(len(sel), int)
219
+ for r in range(len(sel)):
220
+ k = (int(sel.set_id[r]), gj[r].item() if isinstance(gj[r], np.generic) else gj[r])
221
+ if k not in key:
222
+ base = sel.sets[sel.set_id[r]]
223
+ key[k] = len(sets); sets.append(base[gc[base] == gj[r]])
224
+ ids[r] = key[k]
225
+ return Selection(sel.selected, sets, ids, sel.name + " within group", sel.n_audit)
mapselect/rules.py ADDED
@@ -0,0 +1,72 @@
1
+ """Selection rules as functions of covariates, for literal swaps (see bruteforce.py).
2
+
3
+ cal / test are dicts of per-unit covariate arrays (never labels): 'mu' prediction, 'g' group
4
+ (state), 'v' value, 'c' cost, 's' (n, 2) coordinates. Every rule here is invariant to
5
+ permutations of the calibration units, which is JOMI's Theorem 1 assumption 1. `refsets` has
6
+ the closed forms.
7
+ """
8
+ import numpy as np
9
+
10
+
11
+ def topk(K, key="mu", largest=True):
12
+ """Select the K test units with the largest (smallest) key."""
13
+ def rule(cal, test):
14
+ x = np.asarray(test[key], float); x = x if largest else -x
15
+ out = np.zeros(len(x), bool)
16
+ if K > 0:
17
+ out[np.argsort(-x, kind="stable")[:K]] = True
18
+ return out
19
+ rule.name = f"{'top' if largest else 'bottom'}-{K}"
20
+ return rule
21
+
22
+
23
+ def quota(K_by_group, key="mu", largest=True):
24
+ """State quota: within each group g select the K_g test units with the largest key.
25
+ K_by_group is FIXED (e.g. proportional to population counts), not a function of the split."""
26
+ def rule(cal, test):
27
+ x = np.asarray(test[key], float); x = x if largest else -x
28
+ g = np.asarray(test["g"]); out = np.zeros(len(x), bool)
29
+ for u in np.unique(g):
30
+ idx = np.flatnonzero(g == u)
31
+ k = int(K_by_group.get(u, 0))
32
+ if k > 0:
33
+ out[idx[np.argsort(-x[idx], kind="stable")[:k]]] = True
34
+ return out
35
+ rule.name = "quota"
36
+ return rule
37
+
38
+
39
+ def knapsack_greedy(B, value="v", cost="c"):
40
+ """Budgeted selection: rank by value / cost and fund the longest prefix whose total cost
41
+ stays within the fixed budget B (the usual 'fund until the money runs out' rule)."""
42
+ def rule(cal, test):
43
+ v = np.asarray(test[value], float); c = np.asarray(test[cost], float)
44
+ o = np.argsort(-(v / c), kind="stable")
45
+ out = np.zeros(len(v), bool)
46
+ out[o[np.cumsum(c[o]) <= B]] = True
47
+ return out
48
+ rule.name = "knapsack"
49
+ return rule
50
+
51
+
52
+ def kernel_mask(h, alpha):
53
+ """'Publish only where GeoCP v2 is finite': the Gaussian kernel mass of the calibration
54
+ set around the test location reaches (1 - alpha) / alpha (atom K(0) = 1). Uses calibration
55
+ COORDINATES only (no labels), symmetrically in the calibration units."""
56
+ thr = (1 - alpha) / alpha
57
+
58
+ def rule(cal, test):
59
+ sc = np.asarray(cal["s"], float); st = np.asarray(test["s"], float)
60
+ D2 = ((st[:, None, :] - sc[None, :, :]) ** 2).sum(-1)
61
+ return np.exp(-0.5 * D2 / h ** 2).sum(1) >= thr
62
+ rule.name = "geocp_mask"
63
+ return rule
64
+
65
+
66
+ def threshold(c, key="sigma", below=True):
67
+ """Fixed-threshold mask, e.g. publish where the training-fold scale model sigma <= c."""
68
+ def rule(cal, test):
69
+ x = np.asarray(test[key], float)
70
+ return x <= c if below else x >= c
71
+ rule.name = "threshold"
72
+ return rule
mapselect/totals.py ADDED
@@ -0,0 +1,35 @@
1
+ """Bounds on the total of a top- or bottom-K selection (the manuscript's Lemma 1 and Theorem 2)."""
2
+ import numpy as np
3
+ from ._envelope import envelope_exact, lower_total, valid_prob_fast, violation_exact
4
+
5
+ Z = {1 / 3: 0.4307, 0.30: 0.524417}
6
+
7
+
8
+ def _pool(sel):
9
+ if not sel.shared:
10
+ raise ValueError("total bounds need one shared reference set (a top- or bottom-K rule, or a fixed quota group by group)")
11
+ return sel.sets[0]
12
+
13
+
14
+ def selection_aware_total(pred_selected, resid_audit, sel):
15
+ """Difference estimate of the selected total, sum(pred) + K mean(e_R), with its standard error s_R (K + K^2 / n_R)^(1/2).
16
+ A central-limit result: no finite-sample guarantee. Returns (estimate, standard error); +inf if |R| < 2."""
17
+ pred = np.asarray(pred_selected, float); e = np.asarray(resid_audit, float)[_pool(sel)]
18
+ K, nR = len(pred), len(e)
19
+ if nR < 2:
20
+ return float(pred.sum()), np.inf
21
+ return float(pred.sum() + K * e.mean()), float(e.std(ddof=1) * np.sqrt(K + K ** 2 / nR))
22
+
23
+
24
+ def exact_lower_total(pred_selected, resid_audit, sel, delta, y_min=0.0, iters=16):
25
+ """Lower bound L with Pr(selected total >= L) >= 1 - delta in finite samples, for outcomes known to be >= y_min."""
26
+ pred = np.asarray(pred_selected, float); e = np.asarray(resid_audit, float)[_pool(sel)]
27
+ K, nR = len(pred), len(e)
28
+ C = envelope_exact(nR + K, K, delta, iters=iters, fast=True)
29
+ return float(pred.sum() + lower_total(e, K, y_min - pred.max(), C))
30
+
31
+
32
+ def vcs_credit(estimate, se):
33
+ """Verified Carbon Standard rule: no deduction at relative uncertainty U <= 10%, none creditable above 100%, else 0.4307 SE."""
34
+ U = 1.6449 * se / estimate if estimate > 0 else np.inf
35
+ return 0.0 if U > 1 else (estimate if U <= 0.10 else estimate - 0.4307 * se)
@@ -0,0 +1,87 @@
1
+ Metadata-Version: 2.4
2
+ Name: mapselect
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
+ # mapselect
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
+ `mapselect` 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.
33
+
34
+ ```python
35
+ import numpy as np
36
+ import mapselect as ms
37
+
38
+ # mu: the map's prediction; audited / candidates: a random split of one population; y known at audited places
39
+ sel = ms.top_k(mu[audited], mu[candidates], K=30)
40
+ scores = np.abs(y[audited] - mu[audited]) / sigma[audited]
41
+ q = ms.jomi(scores, sel, alpha=0.1) # may be +inf if too few audited places lie past the cutoff
42
+ J = candidates[sel.selected]
43
+ lower, upper = mu[J] - q * sigma[J], mu[J] + q * sigma[J]
44
+
45
+ ms.plan.n_for_finite(m=3000, K=30) # audited places for a 0.9 chance of finite intervals
46
+ ms.plan.n_budget_for_finite(population=300, K=30) # the same when the audit is drawn from the map's top 300 places
47
+ ```
48
+
49
+ | Task | Function | Guarantee |
50
+ |---|---|---|
51
+ | Rules | `top_k`, `quota`, `budget`, `publication_mask`, `threshold`, `within_groups` | closed-form reference sets, checked against literal swaps |
52
+ | Intervals at selected places | `jomi` | coverage at least 1 − α among selected places, on average over audits |
53
+ | Coverage within regions (RegionCP) | `regioncp` (also `sc_geoccp`), `basis.Multiscale` | Theorem 1's floors, which may be vacuous |
54
+ | Project totals | `exact_lower_total` | finite sample |
55
+ | | `selection_aware_total`, `vcs_credit` | asymptotic; the protocol rule itself |
56
+ | Funding | `cfbh` | false discovery rate at most q, for a top- or bottom-K rule without tied scores (checked) |
57
+ | Audit size | `plan.p_finite`, `plan.n_for_finite`, `plan.n_budget_for_finite`, `plan.floor`, `plan.n_for_floor` | no outcomes used |
58
+ | Any other rule | `bruteforce.reference_matrix` | literal swaps; slow |
59
+
60
+ **What the guarantees need.** A random audit of one finite population (or of a stratum fixed by the map in advance), a map fitted
61
+ separately, and a rule that uses covariates alone and treats audited places symmetrically. Rules that look at audited outcomes,
62
+ audits that are not random, and transfer to unsampled regions fall outside them. Coverage holds on average over audits, and counts
63
+ infinite intervals as covering.
64
+
65
+ `cfbh` accepts only `top_k` selections (either direction) with one shared reference set and distinct scores. It rejects
66
+ quota selections even when only one group is selected. An empty supported selection returns empty p-values and rejections.
67
+
68
+ **Install.** `pip install .` from this folder (not yet on PyPI; `RELEASE.md` has the steps). Needs numpy and scipy; `pip install .[basis]` adds scikit-learn for `basis.Multiscale`.
69
+
70
+ **Tests.** `python -m pytest tests`.
71
+
72
+ **Status.** Version 0.1.0, not yet on PyPI. Licence: MIT. Citation: [manuscript to record].
73
+
74
+ ## Performance
75
+
76
+ One core of an Apple M6 laptop, synthetic data (`experiments/run_package_benchmark.py` in the project; `results/fia_db/RESULTS_PACKAGE_BENCHMARK.md`).
77
+
78
+ | Task | Size | Time | Memory |
79
+ |---|---|---|---|
80
+ | Top-1% rule, thresholds | 10⁸ candidates, 10⁷ audited | 1.4 s | 2.5 GB |
81
+ | Quota, 50 groups | same | 40 s | 5.7 GB |
82
+ | Budget | same | 35 s | 6.9 GB |
83
+ | Publication mask, k-d tree, selection only | 10⁶ audited | 2 min | 2.2 GB |
84
+ | RegionCP, later units (one reference set) | 10⁵ reference units, 60 basis functions | 0.036 s per unit | 0.9 GB |
85
+ | Exact total bound | 10⁴ selected | 25 s | 0.2 GB |
86
+
87
+ 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,15 @@
1
+ mapselect/__init__.py,sha256=l_qRfRYEZntiRNCOooCccLse9ae4RxTBPJKhU0jSdXs,1356
2
+ mapselect/_envelope.py,sha256=PNQAT8tyQinCy3ixSSEvqQztsFBrycXXFGCIYW73vrM,4298
3
+ mapselect/basis.py,sha256=i5zhx-liECa2ohIZfHzv_vStNl9jhEnNcgajFfARDt0,1917
4
+ mapselect/bruteforce.py,sha256=QM1TPpgWrb0iWu3auVmJDISekt9lDoVNquVToeSzRgY,1182
5
+ mapselect/calibrate.py,sha256=iuCJ7L-YN2KAlK2cmyJS00mli4fibHGoO4gCHt69T2w,8911
6
+ mapselect/funding.py,sha256=NK86U1p_SaUekOxwBPrQBQhpabjQ0UjYZ1rWr5TuzEE,2689
7
+ mapselect/planner.py,sha256=Q2F521DIKbGQGuq9zezNI0NGeN0_whDvziGRyRnv2l8,4338
8
+ mapselect/refsets.py,sha256=GN656Hg-zWr9dB80fcSwM5ENHat34EGz2E5t457qogM,10906
9
+ mapselect/rules.py,sha256=iFU6QqOXjljE5GgA9iRlVdoY-anClmbIUUxtu3NZk6Y,2862
10
+ mapselect/totals.py,sha256=_j2qr11JXgPNBJSQqBabKp4_YCHMuSRHZS50mGVhYBw,1775
11
+ mapselect-0.1.0.dist-info/licenses/LICENSE,sha256=xRW8DkyGoyJK3I0bPjvQQ1YD4orcHeBz4dbTuDLUE4k,1065
12
+ mapselect-0.1.0.dist-info/METADATA,sha256=W7u0YY2OSHa6vmppQlBO47n6itbtxhXaGZFHXetbDaw,4911
13
+ mapselect-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
14
+ mapselect-0.1.0.dist-info/top_level.txt,sha256=ySAF51Atev3jq6gUyeBxcs6w8fh1zDC68YMnqK-k49Q,10
15
+ mapselect-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -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 @@
1
+ mapselect