#!/usr/bin/env python """run_full.py -- corrected ORCA Table-3 reproduction (blog / fb1 / fb2). NEW file for the corrected core; the previous pipeline stays untouched as /work/run_realdata_v30.py (its data loaders, QRF fit, MILP machinery and CSV plumbing are reused via `from run_realdata_v30 import ...`). PORTING SOURCES (cloned to /work/pcp_src and /work/chr_src): - PCP baselines: /work/pcp_src/other_baselines/{cqr.py,dcp.py,dist_split.py,utils.py} - PCP driver: /work/pcp_src/main.py (splits, StandardScaler, y_min/y_max, QRF config) - CHR: /work/chr_src/chr/{methods.py,histogram.py,grey_boxes.py} Functions are ported into THIS file (no package import). =========================== PROTOCOL (per run) ============================ seed = seed0 + run_id. ONE numpy Generator per run, consumed in fixed order: split FIRST (rng.permutation -> 500 explore / 500 calib / 1000 test / rest train), then the sample matrices (explore, calib, test). Preproc: 'raw' = y untouched. 'logz' = y <- log1p(y - min(y) + 1) on the FULL data BEFORE the split, then y is z-scored with train stats. BOTH preprocs standardize X with StandardScaler fit on train. This follows the PCP main.py protocol. It is result-neutral for tree models (monotone linear transforms of each feature) and is applied for fidelity only. QRF: quantile_forest 1.5.0, n_estimators=100, min_samples_split=50 (paper E.1 literal: "50 samples per node split"). DOCUMENTED AMBIGUITY: ORCA Table 4 says "#leaf", and the PCP repo driver (main.py: min_samples_leaf=50) uses the leaf reading; here min_samples_split=50 is used per the paper text. y_min / y_max for DCP / DistSplit / CHR / CDSplit grids: min / max of the FULL pre-split y (PCP main.py protocol `y_min=min(Y); y_max=max(Y)`). FLAGGED QUIRK of the referenced implementation: this includes TEST rows. =========================== SAMPLERS ============================ Two samplers of equal status; the `sampler` column flags each CSV row: 'iid' : one u ~ U(0,1) per (row, k); grid inversion (linear interp between adjacent grid columns, clip outside the grid ends). 'shared' : one u_k per sample index k shared across rows, same inversion. Sample matrices are drawn ONCE per run per (sampler, matrix-set: explore/calib/test) from the run's rng and SHARED by ORCA and PCP (paired comparison). =========================== m-NN PROXY (paper App. A, corrected) ============================ proxy for sample k = mean of the m=5 SMALLEST pairwise distances within the row's sample cloud INCLUDING the self-distance 0: sort the K=20 pairwise distances ascending, take the first 5, mean. DIFFERS from the official repo (sampling.py ranks by the mean of the 6 smallest values, i.e. self + 5 neighbours) -- this is the corrected reading of Appendix A, documented. =========================== METHOD CONFIGS (9 per run) ============================ ORCA (4 configs: spec x sampler): spec 'paper' (PRIMARY): Stage-2 quota tau = ceil(n1*(1-alpha)) = 450 (paper p.5 verbatim); Stage-3 threshold = smallest tau with #{S_i <= tau} >= n2*(1-alpha) - 1, i.e. the 449th of the 500 order statistics of the calib scores S_i = min_r E_ir / Q_r (paper eq (9) read literally); NO post-solve tightening; NO span clipping. The Stage-2 program is the exact paper eq (7) MILP (d=1, costs E^1, monotone z, y_i <= sum_r z_{r, lmin(i,r)}) in the compact HiGHS formulation. spec 'author' (sensitivity): quota = ceil((n1+1)*(1-alpha)) = 451; Stage-3 threshold = ceil((n2+1)*(1-alpha))-th order statistic (451st), the official repo's conformal_quantile; tighten_thresholds applied after the solve; merged-union length CLIPPED to the span of train+explore+calib y. Set: union over ranks of [ranked_sample_r - R_r, ranked_sample_r + R_r], R_r = t_alpha * Q_r; eff = merged union length; coverage = y_test in set. Zero-radius ranks: degenerate intervals, guarded as in v30 (Q_r=0 handled in the score ratio). PCP (2 configs: sampler only). Score = min_k |y - sample_k| on calib; threshold = ceil((n2+1)*(1-alpha))-th order statistic of the calib scores. App. B: Q(E_{1:n} u {inf}; alpha) -- the (1-alpha)-quantile of the augmented empirical distribution; for n=500 this is the 451st order statistic. BOTH samplers use the same App. B rule. (DOCUMENTED DIVERGENCE from the PCP repo code, which uses torch.quantile linear interpolation; the paper App. B rule is used here.) Test set = union of [sample_k - t, sample_k + t]; eff = merged length. CQR (1 config, port of pcp_src/other_baselines/cqr.py verbatim): q_lo/q_hi = QRF grid quantiles at levels alpha/2 and 1-alpha/2, read off the SAME 99-level grid predict (find_nearest on the grid: alpha=0.1 -> levels 0.05 / 0.95). Calib score E = max(q_lo - y, y - q_hi) (negatives allowed); threshold q = np.quantile(scores, min(1, (1-alpha)*(n+1)/n)) with linear interpolation (the referenced implementation's formula, QR_errfun.apply_inverse). Interval [q_lo - q, q_hi + q]. CHR (1 config, port of chr_src/chr verbatim: methods.CHR + histogram.Histogram + grey_boxes.HistogramAccumulator incl. smallestSubWithSum): bbox = our QRF (bbox.predict(X) -> the (n, 99) grid matrix; bbox.get_quantiles() -> the 99-level grid); grid_histogram = np.linspace(y_min, y_max, 1000); delta_alpha=0.001; intervals=True; randomize=False. calibrate(X_calib, Y_calib, alpha) -> scores via acc.calibrate_intervals(Y_calib); calibrated_alpha = round(1 - mquantiles(scores, prob=(1-alpha)*(1+1/n2)), 4), floored at delta_alpha exactly as the PCP repo's CHR usage does (main.py context: methods.CHR line 84-85 sets calibrated_alpha=delta_alpha when it rounds to 0). predict -> (n, 2) bands; eff = q95-q95 length (single interval). DCP-CQR (1 config, port of pcp_src/other_baselines/dcp.py + utils._estim_dist verbatim): cdf, inv_cdf = _estim_dist(quantiles_row, percentiles, y_min, y_max, smooth_tails=True, tau=0.01) per calib row from the QRF grid; scores = |clip(cdf(Y), 0, 1) - 1/2|; level_adjusted = (1-alpha)*(1+1/n2); alpha_calibrated = 0.5 - mquantiles(scores, prob=level_adjusted); interval [inv_cdf(0.5-t), inv_cdf(0.5+t)]. NOTE: _estim_dist consumes the GLOBAL np.random stream (monotonicity jitter), so np.random.seed(run_seed) is called at run start to make the port deterministic. FLAGGED: the paper names a "DCP-CQR hybrid that stabilizes DCP with CQR" (sec 4.3) but gives NO formula for the hybrid, and the referenced PCP repo contains only plain DCP; this config is the faithful plain-DCP port and collapses to the full observed y-span on the heavy-tailed count data (consistent with the paper's own instability remark). Labeled 'dcp-cqr' pending an author clarification. DistSplit (1 config, port of pcp_src/other_baselines/dist_split.py verbatim): same _estim_dist; scores = cdf(Y); alpha_adjusted = 1-(1-alpha)*(1+1/n2); t_lo = mquantiles(scores, prob=alpha_adjusted/2), t_up = mquantiles(scores, prob=1-alpha_adjusted/2); interval [inv_cdf(t_lo), inv_cdf(t_up)]. CDSplit (1 config): port of cd_split.py minus sympy; density model = the cde-1.0.1 MixtureDensityNetwork with the paper overrides, rebuilt self-contained in plain PyTorch (cde is TF1-era, uninstallable): n_centers=10, hidden (100,100) tanh with weight_norm, dropout=0.2 (paper; cde default 0.0), data_normalization=True (cde), Adam lr=1e-3, batch 256 (cde defaults), 500 epochs (paper override of cde's n_training_epochs=1000). Calibration per cd_split.py verbatim (y-grid 100 pts, t_grid 100 pts, profile-density CDE vectors, KMeans(n_clusters=max(round(n_calib/100),1)), scores = pdf(X_calib, y_calib), threshold np.quantile(scores, alpha) -- repo literal, NO finite-sample correction, documented). CRD (3 configs: ellipse / convexhull / hyperrectangle): official toolbox conformal_region_designer 0.1.2 (imported from the extracted wheel). Residuals Z = y - QRF median(0.5) prediction; calibration split cal_one=250 / cal_two=250 (toolbox two-half protocol); ConformalRegion('kde','meanshift', TEMPLATE, 0.90); fit + conformalize. Region per test point = union over fitted shapes of the shape's 1-D {z: score(z) <= 0} interval, offset by the test median prediction; endpoints read ANALYTICALLY from the adjusted shape parameters (verified against the package source). The 1-D convex hull is degenerate for scipy (CHull needs 2-D): _DegenerateHull1D implements the package's exact 1-D hull semantics, documented. R2CCP (1 config): official wheel R2CCP-0.0.8 (vendored: downloaded from the Hub at job start, extracted, sys.path). Paper: "default configuration from the author's public repository and trained for 500 epochs" -> all repo defaults, max_epochs=500, seed = run seed. The repo standardizes X and y internally, bins y into range_size=50 classes over the train range, and conformalizes interpolated class scores (threshold = plain empirical alpha quantile, repo literal). Internal train/cal split: repo default test_size=0.2 of the data passed to fit (i.e. of OUR training split), re-drawn with the same seed at inference; documented. =========================== CSV / CLI ============================ CSV rows appended: dataset, preproc, run_id, method_config, coverage, eff, seconds, status='ok' + diagnostics. method_config strings: 'orca|spec=paper|sampler=iid', 'pcp|sampler=shared', 'cqr', 'chr', 'dcp-cqr', 'distsplit', 'cdsplit', 'crd-ellipse', 'crd-convexhull', 'crd-hyperrectangle', 'r2ccp'. CLI: --dataset {blog,fb1,fb2} --runs N --preproc {raw,logz} --out CSV --seed0 0; ORCA_ARGS env override; ORCA_SKIP env (comma-separated method names whose COMPUTATION is skipped: 'cdsplit'/'r2ccp' for CPU jobs, the QRF-based names for GPU jobs). """ from __future__ import annotations import argparse import copy import math import os import sys import time import numpy as np import pandas as pd from scipy import interpolate from scipy.stats.mstats import mquantiles # the actual source import (cqr/dcp/dist_split/chr) # --- bootstrap the base-pipeline module (hf_jobs materializes only this # script; the base module is fetched from the pinned Hub commit once) --- try: import run_realdata_v30 as _base # noqa: F401 except ImportError: import urllib.request _base_url = ("https://huggingface.co/datasets/Devya27/orca-table3-repro/" "resolve/f1afb40c7ba22b5b93b3b84219c9bbfdf88e7360/" "code/run_realdata.py") print(f"[bootstrap] fetching base pipeline module {_base_url}", flush=True) _src = urllib.request.urlopen(_base_url, timeout=120).read().decode() with open("run_realdata_v30.py", "w") as _f: _f.write(_src) import run_realdata_v30 as _base # noqa: F401 from run_realdata_v30 import ( # reused base pipeline ALPHA, K, K_NEIGHBOR, MILP_TIME_LIMIT, N_CALIB, N_EXPLORE, N_TEST, Q_GRID, build_levels, conformal_quantile, coverage_count, covered_by_intervals, clip_region_size, draw_samples, fit_qrf, greedy_warm_start, load_dataset, merged_total_length, rank_samples_by_density, residual_matrix, tighten_thresholds, _proxy_objective, ) # --------------------------------------------------------------------------- # # Port: pcp_src/other_baselines/utils.py :: _estim_dist (verbatim) # --------------------------------------------------------------------------- # def _estim_dist(quantiles, percentiles, y_min, y_max, smooth_tails, tau): """ Estimate CDF from list of quantiles, with smoothing """ # VERBATIM from /work/pcp_src/other_baselines/utils.py. # NOTE (documented): consumes the GLOBAL np.random stream # (monotonicity jitter) -> np.random.seed(run_seed) at run start. noise = np.random.uniform(low=0.0, high=1e-5, size=((len(quantiles),))) noise_monotone = np.sort(noise) quantiles = quantiles + noise_monotone def interp1d(x, y, a, b): return interpolate.interp1d(x, y, bounds_error=False, fill_value=(a, b), assume_sorted=True) cdf = interp1d(quantiles, percentiles, 0.0, 1.0) inv_cdf = interp1d(percentiles, quantiles, y_min, y_max) if smooth_tails: # Uniform smoothing of tails (verbatim; quantiles_smooth aliases # quantiles, so it is defined even when both idx sets are empty). quantiles_smooth = quantiles tau_lo = tau tau_hi = 1 - tau q_lo = inv_cdf(tau_lo) q_hi = inv_cdf(tau_hi) idx_lo = np.where(percentiles < tau_lo)[0] idx_hi = np.where(percentiles > tau_hi)[0] if len(idx_lo) > 0: quantiles_smooth[idx_lo] = np.linspace( quantiles[0], q_lo, num=len(idx_lo)) if len(idx_hi) > 0: quantiles_smooth[idx_hi] = np.linspace( q_hi, quantiles[-1], num=len(idx_hi)) cdf = interp1d(quantiles_smooth, percentiles, 0.0, 1.0) inv_cdf = interp1d(percentiles, quantiles_smooth, y_min, y_max) # Standardize breaks = np.linspace(y_min, y_max, num=1000, endpoint=True) cdf_hat = cdf(breaks) f_hat = np.diff(cdf_hat) f_hat = (f_hat + 1e-6) / (np.sum(f_hat + 1e-6)) cdf_hat = np.concatenate([[0], np.cumsum(f_hat)]) cdf = interp1d(breaks, cdf_hat, 0.0, 1.0) inv_cdf = interp1d(cdf_hat, breaks, y_min, y_max) return cdf, inv_cdf # --------------------------------------------------------------------------- # # Port: chr_src/chr/histogram.py :: Histogram (verbatim, except that the # black box is our QRF: quantiles_row -> (99,) grid curve) # --------------------------------------------------------------------------- # class Histogram: def __init__(self, percentiles, breaks): self.percentiles = percentiles self.breaks = breaks def compute_histogram(self, quantiles, ymin, ymax, alpha, smooth_tails=True): """Compute pi_hat[j]: the mass between break[j-1] and break[j].""" n = quantiles.shape[0] B = len(self.breaks) - 1 pi_hat = np.zeros((n, B + 1)) percentiles = np.concatenate(([0], self.percentiles, [1])) quantiles = np.pad(quantiles, ((0, 0), (1, 1)), 'constant', constant_values=(ymin, ymax)) for i in range(n): cdf, inv_cdf = _estim_dist(quantiles[i], percentiles, y_min=ymin, y_max=ymax, smooth_tails=smooth_tails, tau=0.01) cdf_hat = cdf(self.breaks) pi_hat[i] = np.concatenate([[0], np.diff(cdf_hat)]) pi_hat[i] = (pi_hat[i] + 1e-6) / (np.sum(pi_hat[i] + 1e-6)) return pi_hat # --------------------------------------------------------------------------- # # Port: chr_src/chr/grey_boxes.py :: smallestSubWithSum + HistogramAccumulator # (verbatim; randomize branch kept but epsilon=None so it never runs) # --------------------------------------------------------------------------- # def smallestSubWithSum(arr, x, include=None): """Credit: geeksforgeeks minimum-length subarray with sum >= x.""" n = len(arr) if include is None: end_init = 0 start_max = n else: end_init = include[1] start_max = include[0] start_best = 0 end_best = n min_len = n + 1 start = 0 curr_sum = np.sum(arr[start:end_init]) for end in range(end_init, n): curr_sum += arr[end] while (curr_sum >= x) and (start <= end) and (start <= start_max): if (end - start + 1 < min_len): min_len = end - start + 1 start_best = start end_best = end curr_sum -= arr[start] start += 1 if end_best == n: print("Error in smallestSubWithSum(): no solution! This may be a bug.") quit() return start_best, end_best class HistogramAccumulator: def __init__(self, pi, breaks, alpha, delta_alpha=0.001): self.n, self.K = pi.shape self.breaks = breaks self.pi = pi self.alpha = alpha self.alpha_grid = np.round(np.arange(delta_alpha, 1.0, delta_alpha), 4) self.alpha_grid = np.unique(np.sort(np.concatenate((self.alpha_grid, [alpha])))) # only used for sets (unused: intervals=True) self.order = np.argsort(-pi, axis=1) self.ranks = np.empty_like(self.order) for i in range(self.n): self.ranks[i, self.order[i]] = np.arange(len(self.order[i])) self.pi_sort = -np.sort(-pi, axis=1) self.Z = np.round(self.pi_sort.cumsum(axis=1), 9) def compute_interval_sequence(self, epsilon=None): alpha_grid = self.alpha_grid n_grid = len(alpha_grid) k_star = np.where(alpha_grid == self.alpha)[0][0] S_grid = -np.ones((n_grid, self.n, 2)).astype(int) S_grid_random = -np.ones((n_grid, self.n, 2)).astype(int) S, S_random = self.predict_intervals_single(alpha_grid[k_star], epsilon=epsilon) S_grid[k_star] = S S_grid_random[k_star] = S_random for k in range(k_star + 1, n_grid): a = S_grid[k - 1, :, 0] b = S_grid[k - 1, :, 1] S, S_random = self.predict_intervals_single( alpha_grid[k], epsilon=epsilon, a=a, b=b) S_grid[k] = S S_grid_random[k] = S_random for k in range(0, k_star)[::-1]: alpha = alpha_grid[k] S, S_random = self.predict_intervals_single( alpha, epsilon=epsilon, include=S_grid_random[k + 1]) S_grid[k] = S S_grid_random[k] = S_random return S_grid_random def predict_intervals_single(self, alpha, a=None, b=None, include=None, epsilon=None): if a is None: a = np.zeros(self.n).astype(int) if b is None: b = (np.ones(self.n) * len(self.pi[0])).astype(int) if include is None: include = [None] * self.n start = -np.ones(self.n).astype(int) end = -np.ones(self.n).astype(int) for i in range(self.n): start_offset = a[i] end_offset = b[i] + 1 if np.sum(self.pi[i][start_offset:end_offset]) < 1.0 - alpha: print("Error: incorrect probability normalization. " "This may be a bug.") quit() start[i], end[i] = smallestSubWithSum( self.pi[i][start_offset:end_offset], 1.0 - alpha, include=include[i]) start[i] += start_offset end[i] += start_offset S = np.concatenate((start.reshape((len(start), 1)), end.reshape((len(start), 1))), 1) S_random = copy.deepcopy(S) if (epsilon is not None): for i in range(self.n): if ((S[i, -1] - S[i, 0]) <= 1): continue tot_weight = np.sum(self.pi[i][S[i, 0]:(S[i, -1] + 1)]) excess_weight = tot_weight - (1.0 - alpha) weight_left = self.pi[i][S[i, 0]] weight_right = self.pi[i][S[i, -1]] if weight_left < weight_right: pi_remove = excess_weight / (weight_left + 1e-5) if epsilon[i] <= pi_remove: S_random[i, 0] += 1 else: pi_remove = excess_weight / (weight_right + 1e-5) if epsilon[i] <= pi_remove: S_random[i, -1] -= 1 return S, S_random def predict_intervals(self, alpha, epsilon=None): bands = np.zeros((self.n, 2)) S_grid = self.compute_interval_sequence(epsilon=epsilon) j_star_idx = np.where(self.alpha_grid <= alpha)[0] if len(j_star_idx) == 0: S = np.tile(np.arange(self.K), (self.n, 1)) else: j_star = np.max(j_star_idx) S = S_grid[j_star] # clamp at 0: bin 0 is [ymin, breaks[0]], so a band including bin 0 # starts at breaks[0] = ymin; S[:,0]-1 == -1 would wrap to breaks[-1] # (the original chr code never hits this because its bin 0 always has # zero mass; the delta_alpha floor path can include it -- documented) bands[:, 0] = self.breaks[np.maximum(S[:, 0] - 1, 0)] bands[:, 1] = self.breaks[S[:, -1]] return S, bands def calibrate_intervals(self, Y, epsilon=None, verbose=False): Y = np.atleast_1d(Y) n2 = len(Y) alpha_max = np.zeros(n2, ) S_grid = self.compute_interval_sequence(epsilon=epsilon) for j in range(len(self.alpha_grid)): alpha = self.alpha_grid[j] S = S_grid[j] band_left = self.breaks[S[:, 0] - 1] band_right = self.breaks[S[:, -1]] idx_inside = np.where((Y >= band_left) * (Y <= band_right))[0] if len(idx_inside) > 0: alpha_max[idx_inside] = alpha return 1.0 - alpha_max # --------------------------------------------------------------------------- # # Fast-fail helpers # --------------------------------------------------------------------------- # def _assert_finite(x, name): arr = np.asarray(x, dtype=float) assert np.all(np.isfinite(arr)), f"{name}: non-finite values" def _assert_shapes(cond, msg): assert cond, msg # --------------------------------------------------------------------------- # # Black-box adapter: our quantile_forest QRF seen as a PCP/CHR "bbox" # --------------------------------------------------------------------------- # class QrfBbox: """Adapter so the ported CHR / DCP / DistSplit code sees a bbox with predict(X) -> (n, L) grid matrix and get_quantiles() -> the L levels. quantile-forest's batched predict with quantiles=grid does exactly this.""" def __init__(self, model, grid=None): self.model = model self.grid = np.asarray(grid if grid is not None else Q_GRID, dtype=float) def predict(self, X): q = self.model.predict(np.asarray(X, dtype=np.float64), quantiles=list(self.grid)) return np.asarray(q).reshape(len(X), len(self.grid)) def get_quantiles(self): return self.grid # --------------------------------------------------------------------------- # # ORCA (4 configs: spec x sampler) # --------------------------------------------------------------------------- # def run_orca(model, y_explore, y_calib, y_test, X_explore, X_calib, X_test, rng, sampler="iid", spec="paper", quota=None, stage3_rule="paper", apply_tighten=False, clip=False, span_clipped=None, S_exp=None, S_cal=None, S_te=None): """ORCA. sampler in {'iid','shared'}; spec in {'paper','author'}. spec paper : quota=ceil(n1*(1-alpha))=450, stage3 = paper eq (9) literal (449th of 500 order stats), no tighten, no clip. spec author : quota=ceil((n1+1)*(1-alpha))=451, stage3 = 451st order stat (repo conformal_quantile), tighten applied, clip to span(train+explore+calib y). Returns (metrics_dict, diagnostics_dict).""" t0 = time.time() assert spec in ("paper", "author") n1 = len(y_explore) if quota is None: quota = (math.ceil(n1 * (1.0 - ALPHA)) if spec == "paper" else math.ceil((n1 + 1) * (1.0 - ALPHA))) assert quota <= n1, f"quota {quota} > n1 {n1}: infeasible quota" apply_tighten = apply_tighten or spec == "author" clip = clip or spec == "author" # -- samples: SHARED per-run matrices (drawn once in one_run) -- if S_exp is None: S_exp = draw_samples(model, X_explore, K, rng, shared=(sampler == "shared")) ranked_exp = rank_samples_by_density_corrected(S_exp, K_NEIGHBOR) E_explore = residual_matrix(y_explore, ranked_exp) _assert_shapes(E_explore.shape == (n1, K), f"ORCA E_explore {E_explore.shape}") _assert_finite(E_explore, "ORCA E_explore") # -- stage 2: compact HiGHS MILP = paper eq (7) (d=1, costs E^1) -- E = np.asarray(E_explore, dtype=float) levels = build_levels(E) if spec == "paper": thresholds = solve_orca_milp_paper(E, ALPHA, quota, levels) else: thresholds = solve_orca_milp_author(E, ALPHA, quota, levels) _assert_shapes(np.all(np.isfinite(thresholds)) and np.all(thresholds >= 0), "ORCA thresholds") proxy_objective = float(_proxy_objective(thresholds, 1)) # -- stage 3: split-conformal rescale on calib residuals -- if S_cal is None: S_cal = draw_samples(model, X_calib, K, rng, shared=(sampler == "shared")) ranked_cal = rank_samples_by_density_corrected(S_cal, K_NEIGHBOR) E_calib = residual_matrix(y_calib, ranked_cal) _assert_shapes(E_calib.shape == (len(y_calib), K), "ORCA E_calib shape") Q = np.asarray(thresholds, dtype=float)[None, :] # Q_r == 0 guard (v30): such a rank covers a point only if E_ir == 0 # exactly (ratio 0); otherwise the ratio is +inf and the min skips it. with np.errstate(divide="ignore", invalid="ignore"): ratios_pos = np.where(Q > 0, E_calib / np.where(Q > 0, Q, 1.0), np.inf) ratios = np.where(Q > 0, ratios_pos, np.where(E_calib == 0, 0.0, np.inf)) scores = ratios.min(axis=1) _assert_finite(scores, "ORCA calib scores") n2 = len(y_calib) if stage3_rule == "paper": # paper eq (9) literal: smallest tau with #{S_i <= tau} >= n2*(1-alpha) - 1 k_order = n2 * (1.0 - ALPHA) - 1.0 idx = int(math.floor(k_order + 1e-9)) t_alpha = float(np.sort(scores)[idx]) else: # 'author': ceil((n2+1)*(1-alpha))-th order statistic t_alpha = conformal_quantile(scores, ALPHA) _assert_finite(t_alpha, "ORCA t_alpha") assert t_alpha >= 0, f"ORCA t_alpha negative: {t_alpha}" radii = t_alpha * np.asarray(thresholds, dtype=float) # -- test -- if S_te is None: S_te = draw_samples(model, X_test, K, rng, shared=(sampler == "shared")) ranked_te = rank_samples_by_density_corrected(S_te, K_NEIGHBOR)[:, :, 0] lo = ranked_te - radii[None, :] hi = ranked_te + radii[None, :] _assert_shapes(lo.shape == (len(y_test), K) and np.all(lo <= hi), "ORCA test intervals") eff = np.array([merged_total_length(l, h) for l, h in zip(lo, hi)]) cov = np.array([covered_by_intervals(y, l, h) for y, l, h in zip(y_test, lo, hi)]) clipped = False if clip: span = float(span_clipped) if span_clipped is not None else np.inf eff = clip_region_size(eff, span) clipped = True metrics = { "coverage": float(cov.mean()), "eff": float(eff.mean()), "seconds": time.time() - t0, } diag = { "threshold": float(t_alpha), "proxy_objective": proxy_objective, "quota": quota, "tighten": ("yes" if apply_tighten else "no"), "clip": ("yes" if clipped else "no"), "sampler": sampler, "spec": spec, "milp_status": "ok", } return metrics, diag def solve_orca_milp_paper(E, alpha, quota, levels): """Stage-2 MILP = paper eq (7) exactly (compact HiGHS formulation): binary z_{r,l} (monotone z_{r,l} >= z_{r,l+1}); y_i <= sum_r z_{r, lmin(i,r)}, lmin(i,r) = smallest l with E_(l),r >= E_{i,r}; cost = sum_r threshold_r (d=1), encoded as level increments; sum_i y_i >= quota (450). NO post-solve tightening.""" from scipy.optimize import Bounds, LinearConstraint, milp import scipy.sparse as sp E = np.asarray(E, dtype=float) n, K_ = E.shape n_levels = [len(lv) for lv in levels] z_offset = np.cumsum([0] + n_levels) nz = int(z_offset[-1]) n_var = nz + n y_offset = nz c = np.zeros(n_var) for r in range(K_): lv = levels[r] c[z_offset[r]: z_offset[r] + len(lv)] = np.diff(lv, prepend=0.0) # monotonicity z_{r,l} - z_{r,l+1} >= 0 mono_rows, mono_cols, mono_data = [], [], [] row = 0 for r in range(K_): for l in range(n_levels[r] - 1): mono_rows += [row, row] mono_cols += [z_offset[r] + l, z_offset[r] + l + 1] mono_data += [1.0, -1.0] row += 1 mono_con = LinearConstraint( sp.csr_matrix((mono_data, (mono_rows, mono_cols)), shape=(row, n_var)), lb=0.0, ub=np.inf) # coverage: y_i <= sum_r z_{r, l_min(i,r)} cov_rows, cov_cols, cov_data = [], [], [] row = 0 for i in range(n): for r in range(K_): l_min = int(np.searchsorted(levels[r], E[i, r], side="left")) cov_rows.append(row) cov_cols.append(z_offset[r] + l_min) cov_data.append(1.0) cov_rows.append(row) cov_cols.append(y_offset + i) cov_data.append(-1.0) row += 1 cov_con = LinearConstraint( sp.csr_matrix((cov_data, (cov_rows, cov_cols)), shape=(n, n_var)), lb=0.0, ub=np.inf) # quota: sum_i y_i >= target quota_con = LinearConstraint( sp.csr_matrix((np.ones(n), (np.zeros(n, dtype=int), y_offset + np.arange(n))), shape=(1, n_var)), lb=float(quota), ub=np.inf) integrality = np.zeros(n_var) integrality[:nz] = 1 res = milp(c=c, constraints=[mono_con, cov_con, quota_con], integrality=integrality, bounds=Bounds(np.zeros(n_var), np.ones(n_var)), options={"time_limit": MILP_TIME_LIMIT, "mip_rel_gap": 0.01, "presolve": True}) z_sol = np.round(np.asarray(res.x[:nz])) if res.x is not None else None if z_sol is None: # no incumbent within the budget: greedy warm start fallback (v30) thresholds = greedy_warm_start(E, alpha, 1) return np.asarray(thresholds, dtype=float) thresholds = np.empty(K_) for r in range(K_): active = np.nonzero(z_sol[z_offset[r]: z_offset[r] + n_levels[r]])[0] thresholds[r] = levels[r][active[-1]] return thresholds def solve_orca_milp_author(E, alpha, quota, levels): """Official-repo sensitivity path: same MILP with the (n1+1) quota (451), then tighten_thresholds applied after the solve.""" thr = solve_orca_milp_paper(E, alpha, quota, levels) thr = tighten_thresholds(E, alpha, thr, levels) assert coverage_count(E, thr) >= quota, "tighten lost the quota" return np.asarray(thr, dtype=float) def rank_samples_by_density_corrected(Y_hat, k_neighbor=K_NEIGHBOR): """CORRECTED m-NN proxy (paper App. A): mean of the m=5 SMALLEST pairwise distances INCLUDING the self-distance 0 (sort the K pairwise distances ascending, take the first 5, mean). DIFFERS from the official repo, which averages the 6 smallest (self + 5 neighbours). Returns (n, K, 1).""" Y_hat = np.asarray(Y_hat, dtype=float) assert Y_hat.ndim == 3 and Y_hat.shape[2] == 1, Y_hat.shape S = Y_hat[:, :, 0] pairwise = np.abs(S[:, :, None] - S[:, None, :]) proxy = np.sort(pairwise, axis=2)[:, :, :k_neighbor].mean(axis=2) idx = np.argsort(proxy, axis=1, kind="stable") ranked = np.take_along_axis(S, idx, axis=1) return ranked[:, :, None] # --------------------------------------------------------------------------- # # PCP (2 configs: sampler only) # --------------------------------------------------------------------------- # def run_pcp(model, y_calib, y_test, X_calib, X_test, rng, sampler="iid", S_cal=None, S_te=None): """Port of pcp/pcp.py cal_type='uniform', with the paper App. B threshold: Q(E_{1:n} u {inf}; alpha) = the ceil((n2+1)*(1-alpha))-th order statistic of the calib scores (451st of 500). BOTH samplers use this rule. (The PCP repo code uses torch.quantile linear interpolation -- documented divergence; the paper App. B rule is authoritative here.) Returns (metrics_dict, diagnostics_dict).""" t0 = time.time() if S_cal is None: S_cal = draw_samples(model, X_calib, K, rng, shared=(sampler == "shared")) E_calib = residual_matrix(y_calib, S_cal) # (n_cal, K) _assert_shapes(E_calib.shape == (len(y_calib), K), "PCP E_calib shape") scores = E_calib.min(axis=1) # min over k _assert_finite(scores, "PCP calib scores") n2 = len(y_calib) k = int(math.ceil((1.0 - ALPHA) * (n2 + 1))) # 451 t = float(np.sort(scores)[min(k, n2) - 1]) _assert_finite(t, "PCP threshold") if S_te is None: S_te = draw_samples(model, X_test, K, rng, shared=(sampler == "shared")) S_te = np.asarray(S_te, dtype=float) if S_te.ndim == 3: S_te = S_te[:, :, 0] lo = S_te - t hi = S_te + t assert np.all(lo <= hi), "PCP test intervals" _assert_shapes(lo.shape == (len(y_test), K), "PCP test intervals shape") eff = np.array([merged_total_length(l, h) for l, h in zip(lo, hi)]) cov = np.array([covered_by_intervals(y, l, h) for y, l, h in zip(y_test, lo, hi)]) metrics = {"coverage": float(cov.mean()), "eff": float(eff.mean()), "seconds": time.time() - t0} diag = {"threshold": t, "proxy_objective": "", "quota": "", "tighten": "", "clip": "", "sampler": sampler, "spec": "", "milp_status": ""} return metrics, diag # --------------------------------------------------------------------------- # # CQR (port of pcp_src/other_baselines/cqr.py: QR_errfun + CQR, verbatim, # with bbox = QrfBbox) # --------------------------------------------------------------------------- # def find_nearest(a, a0): """Index of element in 1-d array `a` closest to scalar a0 (verbatim).""" idx = np.abs(a - a0).argmin() return idx def qr_errfun_apply(prediction, y): """QR_errfun.apply (verbatim): E = max(q_lo - y, y - q_hi), negatives allowed.""" y_lower = prediction[:, 0] y_upper = prediction[:, -1] error_low = y_lower - y error_high = y - y_upper return np.maximum(error_high, error_low) def qr_errfun_apply_inverse(nc, alpha): """QR_errfun.apply_inverse (verbatim): np.quantile linear at min(1, (1-alpha)(n+1)/n). Returns np.vstack([q, q]).""" q = np.quantile(nc, np.minimum(1.0, (1.0 - alpha) * (nc.shape[0] + 1.0) / nc.shape[0])) return np.vstack([q, q]) def run_cqr(model, y_calib, y_test, X_calib, X_test, alpha=ALPHA): """CQR, port verbatim. bbox.predict -> (n, 99) grid; the two columns are picked by find_nearest(grid, alpha/2) and find_nearest(grid, 1-alpha/2).""" t0 = time.time() bbox = QrfBbox(model) grid = bbox.get_quantiles() idx_lower = find_nearest(grid, alpha / 2.0) idx_upper = find_nearest(grid, 1.0 - alpha / 2.0) pred_calib = bbox.predict(X_calib)[:, [idx_lower, idx_upper]] scores = qr_errfun_apply(pred_calib, np.asarray(y_calib, dtype=float)) _assert_finite(scores, "CQR scores") q_lo_c, q_hi_c = pred_calib[:, 0], pred_calib[:, 1] assert np.all(q_lo_c <= q_hi_c), "CQR: q_lo > q_hi on calib" score_correction = qr_errfun_apply_inverse(scores, alpha) q_thr = float(score_correction[0, 0]) _assert_finite(q_thr, "CQR threshold") pred_test = bbox.predict(X_test)[:, [idx_lower, idx_upper]] q_lo_t, q_hi_t = pred_test[:, 0], pred_test[:, 1] assert np.all(q_lo_t <= q_hi_t), "CQR: q_lo > q_hi on test" lo = pred_test[:, 0] - score_correction[0, 0] hi = pred_test[:, 1] + score_correction[1, 0] _assert_shapes(np.all(lo <= hi), "CQR interval sanity lo<=hi") eff = float(np.mean(hi - lo)) cov = float(np.mean((y_test >= lo) & (y_test <= hi))) metrics = {"coverage": cov, "eff": eff, "seconds": time.time() - t0} diag = {"threshold": q_thr, "proxy_objective": "", "quota": "", "tighten": "", "clip": "", "sampler": "", "spec": "", "milp_status": ""} return metrics, diag # --------------------------------------------------------------------------- # # CHR (port of chr_src/chr/methods.py CHR, verbatim, bbox = QrfBbox) # --------------------------------------------------------------------------- # def run_chr(model, y_calib, y_test, X_calib, X_test, y_min, y_max, alpha=ALPHA, y_steps=1000, delta_alpha=0.001): """CHR with intervals=True, randomize=False. grid_histogram = linspace(y_min, y_max, 1000); calibrated_alpha = round(1 - mquantiles( scores, prob=(1-alpha)*(1+1/n2)), 4), floored at delta_alpha (PCP repo's CHR usage: methods.py line 84-85 rounds and floors at 0 -> delta_alpha).""" t0 = time.time() bbox = QrfBbox(model) grid_histogram = np.linspace(y_min, y_max, num=y_steps, endpoint=True) # CHR.__init__ + init_bbox assert (np.diff(bbox.get_quantiles()) >= 0).all() hist = Histogram(bbox.get_quantiles(), grid_histogram) # --- calibrate --- q_calib = bbox.predict(X_calib) _assert_shapes(q_calib.shape == (len(y_calib), len(bbox.get_quantiles())), "CHR q_calib shape") d_calib = hist.compute_histogram(q_calib, y_min, y_max, alpha) accumulator = HistogramAccumulator(d_calib, grid_histogram, alpha, delta_alpha=delta_alpha) epsilon = None # randomize=False scores = accumulator.calibrate_intervals( np.asarray(y_calib, dtype=np.float32), epsilon=epsilon) _assert_finite(scores, "CHR scores") n2 = X_calib.shape[0] level_adjusted = (1.0 - alpha) * (1.0 + 1.0 / float(n2)) calibrated_alpha = np.round( 1.0 - mquantiles(scores, prob=level_adjusted)[0], 4) if calibrated_alpha == 0: # PCP repo CHR line 84-85 calibrated_alpha = delta_alpha # floor at delta_alpha calibrated_alpha = float(max(calibrated_alpha, delta_alpha)) # --- predict --- q_new = bbox.predict(X_test) d_new = hist.compute_histogram(q_new, y_min, y_max, alpha) acc_new = HistogramAccumulator(d_new, grid_histogram, alpha, delta_alpha=delta_alpha) _, bands = acc_new.predict_intervals(calibrated_alpha, epsilon=epsilon) lo, hi = bands[:, 0], bands[:, 1] _assert_finite(bands, "CHR bands") _assert_shapes(np.all(lo <= hi), "CHR interval sanity lo<=hi") eff = float(np.mean(hi - lo)) # single-interval length cov = float(np.mean((y_test >= lo) & (y_test <= hi))) metrics = {"coverage": cov, "eff": eff, "seconds": time.time() - t0} diag = {"threshold": calibrated_alpha, "proxy_objective": "", "quota": "", "tighten": "", "clip": "", "sampler": "", "spec": "", "milp_status": ""} return metrics, diag # --------------------------------------------------------------------------- # # DCP (port of pcp_src/other_baselines/dcp.py DCP-CQR, verbatim, bbox = QrfBbox) # --------------------------------------------------------------------------- # def run_dcp(model, y_calib, y_test, X_calib, X_test, y_min, y_max, alpha=ALPHA): """DCP-CQR: scores = |clip(cdf(Y),0,1) - 1/2|; alpha_calibrated = 0.5 - mquantiles(scores, prob=(1-alpha)*(1+1/n2)); interval [inv_cdf(0.5-t), inv_cdf(0.5+t)]. _estim_dist consumes the global np.random stream -> np.random.seed(run_seed) at run start.""" t0 = time.time() bbox = QrfBbox(model) percentiles = bbox.get_quantiles() n2 = X_calib.shape[0] quantiles = bbox.predict(X_calib) cdf_values = np.array([0.0] * n2) for i in range(n2): cdf, inv_cdf = _estim_dist(quantiles[i], percentiles, y_min=y_min, y_max=y_max, smooth_tails=True, tau=0.01) cdf_values[i] = cdf(np.float64(y_calib[i])) scores = np.abs(np.clip(cdf_values, 0, 1) - 1 / 2) _assert_finite(scores, "DCP scores") level_adjusted = (1.0 - alpha) * (1.0 + 1.0 / float(n2)) alpha_calibrated = 0.5 - mquantiles(scores, prob=level_adjusted)[0] alpha_calibrated = float(alpha_calibrated) t = 0.5 - alpha_calibrated quantiles_te = bbox.predict(X_test) pred = np.zeros((len(y_test), 2)) for i in range(len(y_test)): cdf, inv_cdf = _estim_dist(quantiles_te[i], percentiles, y_min=y_min, y_max=y_max, smooth_tails=True, tau=0.01) pred[i, 0] = inv_cdf(0.5 - t) pred[i, 1] = inv_cdf(0.5 + t) lo, hi = pred[:, 0], pred[:, 1] _assert_finite(pred, "DCP bands") _assert_shapes(np.all(lo <= hi), "DCP interval sanity lo<=hi") eff = float(np.mean(hi - lo)) cov = float(np.mean((y_test >= lo) & (y_test <= hi))) metrics = {"coverage": cov, "eff": eff, "seconds": time.time() - t0} diag = {"threshold": alpha_calibrated, "proxy_objective": "", "quota": "", "tighten": "", "clip": "", "sampler": "", "spec": "", "milp_sec": "", "milp_status": ""} return metrics, diag # --------------------------------------------------------------------------- # # DistSplit (port of pcp_src/other_baselines/dist_split.py, verbatim, # bbox = QrfBbox) # --------------------------------------------------------------------------- # def run_distsplit(model, y_calib, y_test, X_calib, X_test, y_min, y_max, alpha=ALPHA): """DistSplit: scores = cdf(Y); alpha_adjusted = 1-(1-alpha)*(1+1/n2); t_lo = mquantiles(scores, prob=alpha_adjusted/2), t_up = mquantiles(scores, prob=1-alpha_adjusted/2); interval [inv_cdf(t_lo), inv_cdf(t_up)].""" t0 = time.time() bbox = QrfBbox(model) percentiles = bbox.get_quantiles() n2 = X_calib.shape[0] quantiles = bbox.predict(X_calib) scores = np.array([0.0] * n2) for i in range(n2): cdf, inv_cdf = _estim_dist(quantiles[i], percentiles, y_min=y_min, y_max=y_max, smooth_tails=True, tau=0.01) scores[i] = cdf(np.float64(y_calib[i])) _assert_finite(scores, "DistSplit scores") alpha_adjusted = 1 - (1 - alpha) * (1.0 + 1.0 / float(n2)) t_lo = mquantiles(scores, prob=alpha_adjusted / 2)[0] t_up = mquantiles(scores, prob=1.0 - alpha_adjusted / 2)[0] t_lo, t_up = float(t_lo), float(t_up) assert t_lo <= t_up, f"DistSplit t_lo {t_lo} > t_up {t_up}" quantiles_te = bbox.predict(X_test) pred = np.zeros((len(y_test), 2)) for i in range(len(y_test)): cdf, inv_cdf = _estim_dist(quantiles_te[i], percentiles, y_min=y_min, y_max=y_max, smooth_tails=True, tau=0.01) pred[i, 0] = inv_cdf(t_lo) pred[i, 1] = inv_cdf(t_up) lo, hi = pred[:, 0], pred[:, 1] _assert_finite(pred, "DistSplit bands") _assert_shapes(np.all(lo <= hi), "DistSplit interval sanity lo<=hi") eff = float(np.mean(hi - lo)) cov = float(np.mean((y_test >= lo) & (y_test <= hi))) metrics = {"coverage": cov, "eff": eff, "seconds": time.time() - t0} diag = {"threshold": f"{t_lo},{t_up}", "proxy_objective": "", "quota": "", "tighten": "", "clip": "", "sampler": "", "spec": "", "milp_status": ""} return metrics, diag # --------------------------------------------------------------------------- # # CDSplit (port of pcp_src/other_baselines/cd_split.py minus sympy; the density # model is the cde-1.0.1 MixtureDensityNetwork with the paper overrides, # rebuilt self-contained in plain PyTorch because cde is not installable here) # --------------------------------------------------------------------------- # class MDN: """MixtureDensityNetwork matching cde 1.0.1 exactly, with the paper overrides: hidden (100,100) with weight_norm -> tanh -> Dropout(0.2) per layer, final Linear -> 2*n_centers + n_centers outputs (locs, scales, logits), Adam lr=1e-3, fixed 500 epochs, batch 256, z-score normalization of X and Y with the train stats (cde fit semantics).""" def __init__(self, ndim_x, n_centers=10, hidden_sizes=(100, 100), dropout=0.2, seed=0): import torch try: # torch>=2.x moved weight_norm to parametrizations from torch.nn.utils import weight_norm as _wn _wn(torch.nn.Linear(2, 2)) except Exception: from torch.nn.utils.parametrizations import weight_norm as _wn self.n_centers = n_centers torch.manual_seed(seed) layers, in_dim = [], ndim_x for h in hidden_sizes: layers.append(_wn(torch.nn.Linear(in_dim, h))) layers.append(torch.nn.Tanh()) layers.append(torch.nn.Dropout(dropout)) in_dim = h self.net = torch.nn.Sequential(*layers) self.head = torch.nn.Linear(in_dim, 2 * n_centers + n_centers) self.x_mean = self.x_std = self.y_mean = self.y_std = None def forward(self, x): import torch out = self.head(self.net(x)) k = self.n_centers locs = out[:, :k] scales = torch.nn.functional.softplus(out[:, k: 2 * k]) + 1e-8 logits = out[:, 2 * k:] return locs, scales, logits def fit(self, X, Y, epochs=500, batch_size=256, lr=1e-3): import math import torch from torch.utils.data import DataLoader, TensorDataset X = np.asarray(X, dtype=float) Y = np.asarray(Y, dtype=float).reshape(-1, 1) # z-score normalization with the TRAIN stats (stored for pdf()) self.x_mean, self.x_std = X.mean(axis=0), X.std(axis=0) + 1e-8 self.y_mean, self.y_std = Y.mean(axis=0), Y.std(axis=0) + 1e-8 Xn = (X - self.x_mean) / self.x_std Yn = (Y - self.y_mean) / self.y_std ds = TensorDataset(torch.as_tensor(Xn, dtype=torch.float32), torch.as_tensor(Yn, dtype=torch.float32)) dl = DataLoader(ds, batch_size=batch_size, shuffle=True) opt = torch.optim.Adam(list(self.net.parameters()) + list(self.head.parameters()), lr=lr) for ep in range(epochs): # fixed 500 epochs, no scheduler for xb, yb in dl: opt.zero_grad() locs, scales, logits = self.forward(xb) log_norm = (-0.5 * ((yb - locs) / scales) ** 2 - torch.log(scales) - 0.5 * math.log(2.0 * math.pi)) comp = torch.log_softmax(logits, dim=1) + log_norm # cde _log_mixture_density, computed on the NORMALIZED y nll = -(torch.logsumexp(comp, dim=1)).mean() nll.backward() opt.step() if (ep + 1) % 100 == 0: print(f" [mdn] epoch {ep + 1}/{epochs} " f"nll={nll.item():.4f}", flush=True) return self def pdf(self, X, y): """X (n,d) numpy, y (n,1) numpy -> (n,) density in ORIGINAL y units (de-normalization factor exp(-sum(log(y_std + 1e-8))), cde semantics).""" import torch X = np.asarray(X, dtype=float) y = np.asarray(y, dtype=float).reshape(-1, 1) Xn = (X - self.x_mean) / self.x_std yn = (y - self.y_mean) / self.y_std with torch.no_grad(): locs, scales, logits = self.forward( torch.as_tensor(Xn, dtype=torch.float32)) log_norm = (-0.5 * ((torch.as_tensor(yn, dtype=torch.float32) - locs) / scales) ** 2 - torch.log(scales) - 0.5 * math.log(2.0 * math.pi)) log_pdf = torch.logsumexp( torch.log_softmax(logits, dim=1) + log_norm, dim=1).numpy() return np.exp(log_pdf - float(np.sum(np.log(self.y_std + 1e-8)))) def _cds_profile_density(t_grid, y_grid, X, model): """cd_split.profile_density verbatim (the sympy part is not needed here).""" y_num, n_levels = len(y_grid), len(t_grid) delta_y = y_grid[2] - y_grid[1] n, n_feats = X.shape X_rep = np.tile(X, y_num).reshape(n * y_num, n_feats) y_grid_rep = np.tile(y_grid, n).reshape(n * y_num, 1) pdf_grid = model.pdf(X_rep, y_grid_rep).reshape(n, y_num) cde = [] for t in t_grid: cde_t = np.where(pdf_grid >= t, pdf_grid, 0.0).sum( axis=1, keepdims=True) * delta_y cde.append(cde_t) return np.concatenate(cde, axis=1) def _cds_union(intervals): """sympy union(...) replacement: merge overlapping/adjacent intervals.""" merged = [] for lo, hi in sorted(intervals): if merged and lo <= merged[-1][1]: merged[-1][1] = max(merged[-1][1], hi) else: merged.append([lo, hi]) return merged def run_cdsplit(model, y_train, y_calib, y_test, X_train, X_calib, X_test, y_min, y_max, seed, alpha=ALPHA): """CD_split, following cd_split.py verbatim minus sympy: MDN fit on (X_train, y_train) for 500 epochs; y-grid = linspace(y_min, y_max, 100) with y_min/y_max the jittered-full-y bounds; t_grid = linspace(0, max pdf over train, 100); profile_density CDE vectors for calib; KMeans(n_clusters=max(round(n_calib/100), 1), random_state=seed); calib scores = pdf(X_calib, y_calib); per test point: ths = np.quantile(scores of the same cluster, alpha) (repo literal: NO finite-sample correction); test set = union of y-grid points with pdf >= ths expanded by the grid step; eff = merged length.""" t0 = time.time() from sklearn.cluster import KMeans mdn = MDN(ndim_x=X_train.shape[1], n_centers=10, hidden_sizes=(100, 100), dropout=0.2, seed=seed) mdn.fit(X_train, np.asarray(y_train, dtype=float).reshape(-1, 1), epochs=500, batch_size=256, lr=1e-3) y_grid = np.linspace(y_min, y_max, 100) delta_y = y_grid[1] - y_grid[0] n_calib = X_calib.shape[0] n_clusters = max(round(n_calib / 100), 1) cde_train = mdn.pdf(X_train, np.asarray(y_train, dtype=float).reshape(-1, 1)) t_grid = np.linspace(0, max(cde_train), 100) cde_calib = _cds_profile_density(t_grid, y_grid, X_calib, mdn) kmeans = KMeans(n_clusters=n_clusters, random_state=seed).fit(cde_calib) calib_class = kmeans.predict(cde_calib) calib_scores = mdn.pdf(X_calib, np.asarray(y_calib, dtype=float).reshape(-1, 1)) cde_test = _cds_profile_density(t_grid, y_grid, X_test, mdn) test_class = kmeans.predict(cde_test) n_test = len(X_test) pdf_test_grid = mdn.pdf( np.tile(X_test, len(y_grid)).reshape(n_test * len(y_grid), -1), np.tile(y_grid, n_test).reshape(-1, 1), ).reshape(n_test, len(y_grid)) effs, covs = [], [] for i, tc in enumerate(test_class): scores = calib_scores[calib_class == tc] if len(scores) == 0: # empty cluster guard scores = calib_scores ths = np.quantile(scores, alpha) yi_mask = pdf_test_grid[i] >= ths bands = _cds_union([(m - delta_y, m + delta_y) for m in y_grid[yi_mask]]) effs.append(sum(hi - lo for lo, hi in bands)) covs.append(any(lo <= y_test[i] <= hi for lo, hi in bands)) cov = float(np.mean(covs)) eff = float(np.mean(effs)) _assert_finite(np.array([cov, eff]), "CDSplit metrics") metrics = {"coverage": cov, "eff": eff, "seconds": time.time() - t0} diag = {"threshold": alpha, "proxy_objective": "", "quota": "", "tighten": "", "clip": "", "sampler": "", "spec": "", "milp_status": ""} return metrics, diag # --------------------------------------------------------------------------- # # CRD (Conformal Region Designer toolbox, wheel extracted; IMPORTED, not # ported). Residuals Z = y - median(QRF); cal split 250/250. # --------------------------------------------------------------------------- # _CRD_PKG_PATH = os.environ.get( "CRD_PKG_PATH", "/work/pkgsrc/crd_dl/extracted") class _DegenerateHull1D: """1-D convex hull in the exact semantics of the package's ConvexHullTemplate. scipy CHull cannot consume 1-D input, so the 1-D hull of a cluster is the interval [min, max]; its halfspace score is max(z - hi, lo - z) (the package's X@hyp_a.T + hyp_b form restricted to the two 1-D halfspaces), and adjust_shape(m) (hyp_b -= m) widens the interval by m on BOTH sides. Documented as the 1-D degenerate case of the referenced implementation.""" def __init__(self): self.lo = None self.hi = None def fit_shape(self, X): X = np.asarray(X, dtype=float).reshape(-1) self.lo = float(X.min()) self.hi = float(X.max()) def score_points(self, Z): z = np.asarray(Z, dtype=float).reshape(-1) return np.maximum(z - self.hi, self.lo - z) def conformalize(self, delta, Z_cal_two): from conformal_region_designer.utils import conformalized_quantile scores = self.score_points(Z_cal_two) inflation = np.quantile(scores, conformalized_quantile(len(scores), delta)) self.lo -= inflation self.hi += inflation return self.lo, self.hi def adjust_shape(self, score_margin): self.lo -= score_margin self.hi += score_margin def volume(self): return self.hi - self.lo def _crd_import(): import sys try: from conformal_region_designer.conformity_optimizer import ( ConformalRegion,) except ImportError: # vendored install of the official toolbox (pinned 0.1.2): PyPI wheel # extracted to a temp dir (deps are numpy/scipy/scikit-learn only) import json import urllib.request import zipfile dest = os.environ.get("CRD_PKG_DIR", "/tmp/crd_pkg") if not os.path.exists(os.path.join( dest, "conformal_region_designer", "conformity_optimizer.py")): os.makedirs(dest, exist_ok=True) with urllib.request.urlopen( "https://pypi.org/pypi/conformal-region-designer/0.1.2/json", timeout=60) as r: meta = json.load(r) whl_url = next(u["url"] for u in meta["urls"] if u["filename"].endswith("py3-none-any.whl")) whl = os.path.join(dest, os.path.basename(whl_url)) print(f"[crd] downloading {whl_url}", flush=True) urllib.request.urlretrieve(whl_url, whl) with zipfile.ZipFile(whl) as zf: zf.extractall(dest) if dest not in sys.path: sys.path.insert(0, dest) from conformal_region_designer.conformity_optimizer import ( ConformalRegion,) from conformal_region_designer.shapes import hyperrectangle as _hr if not getattr(_hr, "_orca_patched", False): _orig_hr_fit = _hr.HyperrectangleTemplate.fit_shape def _hr_fit_safe(self, Z): _orig_hr_fit(self, Z) # degenerate 1-D cluster (all density points identical): # (max-min)/max(max-min) = 0/0 = NaN. Take the limit behaviour # aspect_ratio -> 1 (interval collapses to a point), documented # as a NaN guard on the referenced implementation. ar = np.asarray(self.aspect_ratio, dtype=float) if not np.all(np.isfinite(ar)): self.aspect_ratio = np.ones_like(ar) _hr.HyperrectangleTemplate.fit_shape = _hr_fit_safe _hr._orca_patched = True return ConformalRegion def run_crd(model, y_calib, y_test, X_calib, X_test, y_min, y_max, tmpl, seed, delta=0.90): """CRD via the official toolbox (conformal_region_designer 0.1.2), the paper's KDE/meanshift pipeline: residuals Z = y - QRF median(0.5) prediction; calibration split cal_one = 250 / cal_two = 250 (the toolbox's two-half protocol); ConformalRegion('kde','meanshift', TEMPLATE, 0.90); fit + conformalize. Region per test point = union over fitted shapes of the shape's 1-D {z : score(z) <= 0} interval, offset by the test median prediction. Interval endpoints are read ANALYTICALLY from the adjusted shape parameters (verified against the package source): hyperrectangle [min, max] (adjust_shape inflates both bounds); ellipse center +- sqrt(score_margin / Q) (score (z-c)^2*Q/sm - 1 <= 0); convex hull via _DegenerateHull1D (1-D degenerate case, documented). eff = merged union length (shift-invariant across test points); coverage = y_test inside.""" import math t0 = time.time() ConformalRegion = _crd_import() med_cal = np.asarray(model.predict(X_calib, quantiles=0.5), dtype=float).ravel() Z_cal = np.asarray(y_calib, dtype=float) - med_cal cal_one = Z_cal[:250].reshape(-1, 1) cal_two = Z_cal[250:].reshape(-1, 1) med_test = np.asarray(model.predict(X_test, quantiles=0.5), dtype=float).ravel() np.random.seed(seed) # ConformalRegion has no internal seed if tmpl == "convexhull": pcr = ConformalRegion("kde", "meanshift", _DegenerateHull1D, delta) else: pcr = ConformalRegion("kde", "meanshift", tmpl, delta) pcr.fit(cal_one) pcr.conformalize(cal_two) intervals = [] for shape in pcr.shapes: if tmpl == "hyperrectangle": lo = float(np.asarray(shape.min).ravel()[0]) hi = float(np.asarray(shape.max).ravel()[0]) elif tmpl == "ellipse": c = float(np.asarray(shape.center).ravel()[0]) sm = float(shape.score_margin) q00 = float(np.asarray(shape.Q).ravel()[0]) if q00 <= 0.0 or sm <= 0.0: raise ValueError( f"degenerate ellipse Q={q00} score_margin={sm}") r = math.sqrt(sm / q00) lo, hi = c - r, c + r elif tmpl == "convexhull": lo, hi = float(shape.lo), float(shape.hi) else: raise ValueError(tmpl) intervals.append((lo, hi)) merged = _cds_union(intervals) eff = float(sum(hi - lo for lo, hi in merged)) zs = np.asarray(y_test, dtype=float) - med_test cov = float(np.mean([any(lo <= z <= hi for lo, hi in merged) for z in zs])) _assert_finite(np.array([cov, eff]), f"CRD-{tmpl} metrics") metrics = {"coverage": cov, "eff": eff, "seconds": time.time() - t0} diag = {"threshold": delta, "proxy_objective": "", "quota": "", "tighten": "", "clip": "", "sampler": "", "spec": "", "milp_status": ""} return metrics, diag # --------------------------------------------------------------------------- # # R2CCP (official wheel R2CCP-0.0.8, vendored at job start: downloaded from # the Hub, extracted to a temp dir, sys.path). Paper: "default configuration # from the author's public repository and trained for 500 epochs". # --------------------------------------------------------------------------- # R2CCP_PIN = "R2CCP==0.0.8" # the official authors' wheel, pinned def _r2ccp_import(): import json import urllib.request import zipfile dest = os.environ.get("R2CCP_PKG_DIR", "/tmp/r2ccp_pkg") if not os.path.exists(os.path.join(dest, "R2CCP", "main.py")): os.makedirs(dest, exist_ok=True) # locate the official wheel on PyPI (version-pinned), download, # extract; the package imports directly from the extracted dir # (R2CCP never imports its declared pyinterval dependency at # runtime -- verified against the 0.0.8 wheel source) with urllib.request.urlopen( "https://pypi.org/pypi/R2CCP/0.0.8/json", timeout=60) as r: meta = json.load(r) whl_url = next(u["url"] for u in meta["urls"] if u["filename"].endswith("py3-none-any.whl")) whl = os.path.join(dest, os.path.basename(whl_url)) if not os.path.exists(whl): print(f"[r2ccp] downloading {whl_url} -> {whl}", flush=True) urllib.request.urlretrieve(whl_url, whl) with zipfile.ZipFile(whl) as zf: zf.extractall(dest) if dest not in sys.path: sys.path.insert(0, dest) from R2CCP.main import R2CCP return R2CCP def run_r2ccp(X_train, y_train, X_test, y_test, seed, max_epochs=500): """R2CCP with the official wheel: repo defaults, max_epochs=500 (paper), seed = run seed. The repo standardizes X and y internally, bins y into range_size=50 classes over the train range, splits its own calibration (test_size=0.2 of the data passed to fit, same seed at inference), and conformalizes interpolated class scores (threshold = plain empirical alpha quantile, repo literal). Returns per-point union lengths.""" t0 = time.time() R2CCP = _r2ccp_import() os.makedirs("/tmp/r2ccp_models", exist_ok=True) model = R2CCP({"model_path": f"/tmp/r2ccp_models/m_{seed}.pth", "max_epochs": max_epochs, "seed": seed}) model.fit(np.asarray(X_train, dtype=float), np.asarray(y_train, dtype=float)) coverages, lengths = model.get_coverage_length( np.asarray(X_test, dtype=float), np.asarray(y_test, dtype=float)) cov = float(np.mean(np.asarray(coverages, dtype=float))) eff = float(np.mean(np.asarray(lengths, dtype=float))) _assert_finite(np.array([cov, eff]), "R2CCP metrics") metrics = {"coverage": cov, "eff": eff, "seconds": time.time() - t0} diag = {"threshold": ALPHA, "proxy_objective": "", "quota": "", "tighten": "", "clip": "", "sampler": "", "spec": "", "milp_status": ""} return metrics, diag # --------------------------------------------------------------------------- # # One run # --------------------------------------------------------------------------- # QRF_DEPENDENT = ("orca", "pcp", "cqr", "chr", "dcp-cqr", "distsplit", "crd-ellipse", "crd-convexhull", "crd-hyperrectangle") def _run_config(out, name, spec, sampler, fn): """Run one method-config. A per-config failure (e.g. the CRD toolbox's degenerate-ellipse case on one seed: adjust_shape(m) with m < -1 makes score_margin negative and sqrt(sm/Q) undefined -- undefined behavior of the referenced implementation) is recorded as a status='error' row with the exception as diagnostics, instead of killing the 30-run job. Failed rows are labeled in the CSV and excluded from summaries (never counted as successful repetitions).""" try: m, d = fn() out.append((name, spec, sampler, m, d)) except Exception as exc: # noqa: BLE001 m = {"coverage": float("nan"), "eff": float("nan"), "seconds": 0.0} d = {"threshold": f"{type(exc).__name__}: {exc}"[:120], "proxy_objective": "", "quota": "", "tighten": "", "clip": "", "sampler": sampler, "spec": spec, "milp_status": "error"} out.append((name, spec, sampler, m, d)) print(f"[config-error] {name}|{spec}|{sampler}: " f"{type(exc).__name__}: {exc}", flush=True) def _orca_skip_set(): import os as _os return set(x for x in _os.environ.get("ORCA_SKIP", "").split(",") if x) def one_run(dataset, X, y_full, run_id, seed0, preproc, leaf_mode="split"): """All method-configs for one run (ORCA_SKIP controls which run). Returns a list of CSV row dicts.""" seed = seed0 + run_id _skip = _orca_skip_set() rng = np.random.default_rng(seed) np.random.seed(seed) # DCP/DistSplit/CHR _estim_dist jitter stream # -- split FIRST from the rng stream -- perm = rng.permutation(len(y_full)) i_explore = perm[:N_EXPLORE] i_calib = perm[N_EXPLORE: N_EXPLORE + N_CALIB] i_test = perm[N_EXPLORE + N_CALIB: N_EXPLORE + N_CALIB + N_TEST] i_train = perm[N_EXPLORE + N_CALIB + N_TEST:] _assert_shapes(len(np.unique(perm)) == len(y_full), "split: permutation not unique") y = y_full if preproc == "logz": # y transform on the FULL data before the split, then z-score with # train stats y = np.log1p(y - y.min() + 1.0) X_train, X_explore, X_calib, X_test = (X[i_train], X[i_explore], X[i_calib], X[i_test]) y_train, y_explore, y_calib, y_test = (y[i_train], y[i_explore], y[i_calib], y[i_test]) # -- StandardScaler fit on train (both preprocs; PCP main.py protocol) -- from sklearn.preprocessing import StandardScaler scaler = StandardScaler().fit(X_train) X_train = scaler.transform(X_train) X_explore = scaler.transform(X_explore) X_calib = scaler.transform(X_calib) X_test = scaler.transform(X_test) if preproc == "logz": mu_y, sd_y = y_train.mean(), y_train.std() y_train = (y_train - mu_y) / sd_y y_explore = (y_explore - mu_y) / sd_y y_calib = (y_calib - mu_y) / sd_y y_test = (y_test - mu_y) / sd_y # y jitter (referenced-implementation protocol, PCP main.py): seeded # jitter of the FULL y BEFORE any y_min/y_max consumer. Order for logz: # (1) raw jitter, (2) log1p, (3) train-stats z-score (split arrays above). np.random.seed(seed) y_full = y_full + 1e-6 * np.random.normal(size=y_full.shape) if preproc == "logz": y_full = np.log1p(y_full - y_full.min() + 1.0) # y_min / y_max: min/max of the JITTERED full y (PCP main.py protocol; # includes test rows -- flagged quirk), mapped to z units for logz y_min = float(np.min(y_full)) y_max = float(np.max(y_full)) if preproc == "logz": y_min = (y_min - mu_y) / sd_y y_max = (y_max - mu_y) / sd_y # -- fresh QRF every run (only if a QRF-dependent config is active) -- run_qrf = any(m not in _skip for m in QRF_DEPENDENT) model = None qrf_sec = 0.0 if run_qrf: t0 = time.time() model = fit_qrf(X_train, y_train, seed=seed, leaf_mode=leaf_mode) qrf_sec = time.time() - t0 print(f"[run {run_id}] QRF fit: {qrf_sec:.1f}s " f"(train n={len(y_train)})", flush=True) # -- span of train+explore+calib y (clip target for spec=author) -- y_no_test = np.concatenate([y_train, y_explore, y_calib]) span_clipped = float(y_no_test.max() - y_no_test.min()) # -- shared sample matrices: drawn ONCE per run per (sampler, set) -- samples = {} if run_qrf: for sampler in ("iid", "shared"): for setname, Xs in (("explore", X_explore), ("calib", X_calib), ("test", X_test)): samples[(sampler, setname)] = draw_samples( model, Xs, K, rng, shared=(sampler == "shared")) out = [] # ---- ORCA x {paper, author} x {iid, shared} ---- if "orca" not in _skip: for spec in ("paper", "author"): for sampler in ("iid", "shared"): _run_config(out, "orca", spec, sampler, lambda: run_orca(model, y_explore, y_calib, y_test, X_explore, X_calib, X_test, rng, sampler=sampler, spec=spec, S_exp=samples[(sampler, "explore")], S_cal=samples[(sampler, "calib")], S_te=samples[(sampler, "test")], span_clipped=span_clipped)) # ---- PCP x {iid, shared} ---- if "pcp" not in _skip: for sampler in ("iid", "shared"): _run_config(out, "pcp", "", sampler, lambda: run_pcp(model, y_calib, y_test, X_calib, X_test, rng, sampler=sampler, S_cal=samples[(sampler, "calib")], S_te=samples[(sampler, "test")])) # ---- CQR ---- if "cqr" not in _skip: _run_config(out, "cqr", "", "", lambda: run_cqr(model, y_calib, y_test, X_calib, X_test)) # ---- CHR ---- if "chr" not in _skip: _run_config(out, "chr", "", "", lambda: run_chr(model, y_calib, y_test, X_calib, X_test, y_min, y_max)) # ---- DCP ---- if "dcp-cqr" not in _skip: _run_config(out, "dcp-cqr", "", "", lambda: run_dcp(model, y_calib, y_test, X_calib, X_test, y_min, y_max)) # ---- DistSplit ---- if "distsplit" not in _skip: _run_config(out, "distsplit", "", "", lambda: run_distsplit(model, y_calib, y_test, X_calib, X_test, y_min, y_max)) # ---- CDSplit ---- if "cdsplit" not in _skip: _run_config(out, "cdsplit", "", "", lambda: run_cdsplit(model, y_train, y_calib, y_test, X_train, X_calib, X_test, y_min, y_max, seed)) # ---- CRD (3 shape templates) ---- for tmpl in ("ellipse", "convexhull", "hyperrectangle"): if f"crd-{tmpl}" not in _skip: _run_config(out, f"crd-{tmpl}", "", "", lambda: run_crd(model, y_calib, y_test, X_calib, X_test, y_min, y_max, tmpl, seed)) # ---- R2CCP ---- if "r2ccp" not in _skip: # max_epochs: the paper's 500; ORCA_R2CCP_EPOCHS exists ONLY for # plumbing smoke tests and must stay unset in real runs ep = int(os.environ.get("ORCA_R2CCP_EPOCHS", "500")) _run_config(out, "r2ccp", "", "", lambda: run_r2ccp(X_train, y_train, X_test, y_test, seed, max_epochs=ep)) rows = [] for method, spec, sampler, m, d in out: mc = (f"orca|spec={spec}|sampler={sampler}" if method == "orca" else f"pcp|sampler={sampler}" if method == "pcp" else method) rows.append({ "dataset": dataset, "preproc": preproc, "run_id": run_id, "method_config": mc, "coverage": m["coverage"], "eff": m["eff"], "seconds": m["seconds"], "status": ("error" if d.get("milp_status") == "error" else "ok"), "threshold": d["threshold"], "proxy_objective": d["proxy_objective"], "quota": d["quota"], "tighten": d["tighten"], "clip": d["clip"], "sampler": d["sampler"], "spec": d["spec"], "milp_status": d["milp_status"], "y_min": round(y_min, 6), "y_max": round(y_max, 6), "span_clipped": round(span_clipped, 6), "qrf_sec": round(qrf_sec, 2), "leaf_mode": leaf_mode, }) print(f"[run {run_id}] {mc}: cov={m['coverage']:.3f} " f"eff={m['eff']:.3f} thr={d['threshold']} sec={m['seconds']:.2f}", flush=True) return rows def main(): # hf_jobs uv runs the script with no argv; allow config via ORCA_ARGS if os.environ.get("ORCA_ARGS"): sys.argv += os.environ["ORCA_ARGS"].split() ap = argparse.ArgumentParser(description="ORCA Table-3 corrected core") ap.add_argument("--dataset", required=True, choices=["blog", "fb1", "fb2"]) ap.add_argument("--runs", type=int, default=1) ap.add_argument("--preproc", default="raw", choices=["raw", "logz"]) ap.add_argument("--out", required=True) ap.add_argument("--seed0", type=int, default=0) ap.add_argument("--leaf_mode", default="split", choices=["leaf", "split"], help="QRF config: 'split' = min_samples_split=50 (paper E.1 " "literal); 'leaf' = min_samples_leaf=50 (the PCP-repo " "driver's config / Table 4's '#leaf' knob)") args = ap.parse_args() X, y = load_dataset(args.dataset) print(f"[data] {args.dataset}: X{X.shape} y{y.shape}", flush=True) stage = os.environ.get("ORCA_STAGE", "cpu") header = ["dataset", "preproc", "run_id", "method_config", "coverage", "eff", "seconds", "status", "threshold", "proxy_objective", "quota", "tighten", "clip", "sampler", "spec", "milp_status", "y_min", "y_max", "span_clipped", "qrf_sec", "leaf_mode"] write_header = not os.path.exists(args.out) all_rows = [] for run_id in range(args.runs): rows = one_run(args.dataset, X, y, run_id, args.seed0, args.preproc, leaf_mode=args.leaf_mode) all_rows.extend(rows) pd.DataFrame(rows, columns=header).to_csv( args.out, mode="a", header=write_header, index=False) write_header = False # summary: mean +- SE per method_config df = pd.DataFrame(all_rows, columns=header) print("\n=== summary (mean +- SE over runs) ===", flush=True) print(f"{'method_config':30s} {'coverage':>18s} {'eff':>18s}") df_ok = df[df["status"] == "ok"] for mc, g in df_ok.groupby("method_config"): print(f"{mc:30s} {g['coverage'].mean():.4f} +- " f"{g['coverage'].sem():.4f} {g['eff'].mean():.4f} +- " f"{g['eff'].sem():.4f}") print(f"[out] rows appended to {args.out}", flush=True) if os.environ.get("ORCA_UPLOAD_REPO", "Devya27/orca-table3-repro"): try: from huggingface_hub import HfApi HfApi().upload_file( path_or_fileobj=args.out, path_in_repo=f"results/full_{stage}_{args.preproc}_{args.dataset}.csv", repo_id=os.environ.get("ORCA_UPLOAD_REPO", "Devya27/orca-table3-repro"), repo_type="dataset", ) print("[upload] ok", flush=True) except Exception as exc: # noqa: BLE001 print(f"[upload] FAILED: {exc}", flush=True) if __name__ == "__main__": main()