#!/usr/bin/env python3 """exp05_oracles -- Theorem 5.1 oracle exactness, invariants, and complexity (specs/exp05_oracles.md). No dataset (paper is fully simulated). """ import argparse import itertools import json import math import os import sys import time import zlib sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import numpy as np from core.oracles import oracle from core.parallel import run_grid from core.swf import NEG_INF, swf ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) RESULTS_PATH = os.path.join(ROOT, "results", "exp05.json") BASE_SEED = 505050 FAMILY_Q = { "wpm": [NEG_INF, -5.0, -3.0, -2.0, -1.0, -0.5, 0.0, 0.5, 1.0], "kolm": [NEG_INF, -5.0, -3.0, -2.0, -1.0, -0.5, 0.0], "gini": [None], } ALL_COMBOS = [(f, q) for f, qs in FAMILY_Q.items() for q in qs] EXP05_FAMQ = [(f, q) for f in ("wpm", "kolm") for q in FAMILY_Q[f]] + [("gini", None)] O3_WPM_Q = [-5.0, -3.0, -2.0, -1.0, -0.5, 0.5] O3_KOLM_Q = [-5.0, -3.0, -2.0, -1.0, -0.5] TOL = 1e-7 def log(msg): print(f"[exp05] {msg}", file=sys.stderr, flush=True) def sid(*parts): key = "|".join(str(p) for p in parts) return BASE_SEED + (zlib.crc32(key.encode()) % 1_000_000) def qlabel(q): if q is None: return None if isinstance(q, str): return q if q == NEG_INF: return "-inf" return float(q) def sample_w(rng, n, family): if family == "gini": return np.sort(rng.uniform(0.0, 1.0, n))[::-1] return rng.dirichlet(np.ones(n)) # ============================================================ batched SWF # Vectorized re-implementations of core/swf.py's math for PGA speed. These # evaluate/differentiate the objective M -- they do NOT reuse Algorithms 2-4 # (core/oracles.py), so they are a legitimate independent baseline component. def _onehot_argmin(V): idx = np.argmin(V, axis=0) G = np.zeros_like(V) G[idx, np.arange(V.shape[1])] = 1.0 return G def batch_wpm_val(V, W, q): if q == NEG_INF: return V.min(axis=0) if q == 0.0: safe = np.all(V > 0, axis=0) val = np.exp(np.sum(W * np.log(np.clip(V, 1e-300, None)), axis=0)) return np.where(safe, val, 0.0) Vc = np.clip(V, 1e-300, None) if q < 0.0 else V val = np.sum(W * np.power(Vc, q), axis=0) ** (1.0 / q) if q < 0.0: safe = np.all(V > 0, axis=0) val = np.where(safe, val, 0.0) return val def batch_wpm_grad_v(V, W, q, Mval): if q == NEG_INF: return _onehot_argmin(V) if q == 0.0: return Mval[None, :] * W / np.clip(V, 1e-300, None) return W * np.power(np.clip(V, 1e-300, None), q - 1.0) * np.power(np.clip(Mval, 1e-300, None), 1.0 - q) def batch_kolm_val(V, W, q): if q == NEG_INF: return V.min(axis=0) if q == 0.0: return np.sum(W * V, axis=0) terms = np.log(W) + q * V m = terms.max(axis=0) lse = m + np.log(np.sum(np.exp(terms - m[None, :]), axis=0)) return lse / q def batch_kolm_grad_v(V, W, q): if q == NEG_INF: return _onehot_argmin(V) if q == 0.0: return W.copy() terms = q * V m = terms.max(axis=0) num = W * np.exp(terms - m[None, :]) den = np.sum(num, axis=0) return num / den[None, :] def batch_gini_val(V, W): order = np.argsort(V, axis=0) Vs = np.take_along_axis(V, order, axis=0) return np.sum(W * Vs, axis=0) def batch_gini_grad_v(V, W): order = np.argsort(V, axis=0) G = np.zeros_like(V) np.put_along_axis(G, order, W, axis=0) return G def batch_objective(U, P, W, family, q): V = U * P if family == "wpm": return batch_wpm_val(V, W, q) if family == "kolm": return batch_kolm_val(V, W, q) return batch_gini_val(V, W) def batch_grad_p(U, P, W, family, q): V = U * P if family == "wpm": M = batch_wpm_val(V, W, q) GV = batch_wpm_grad_v(V, W, q, M) elif family == "kolm": GV = batch_kolm_grad_v(V, W, q) else: GV = batch_gini_grad_v(V, W) return U * GV def project_capped_simplex_batch(Y, K, iters): lo = Y.min(axis=0) - 1.0 hi = Y.max(axis=0).copy() for _ in range(iters): theta = (lo + hi) / 2.0 P = np.clip(Y - theta[None, :], 0.0, 1.0) over = P.sum(axis=0) > K lo = np.where(over, theta, lo) hi = np.where(~over, theta, hi) theta = (lo + hi) / 2.0 return np.clip(Y - theta[None, :], 0.0, 1.0) def pga_run(U, W, K, family, q, restarts, steps, bisect_iters, rng): """Projected gradient ascent, 'restarts' random Dirichlet-scaled starts, backtracking (grow-on-success / shrink-on-failure) step size, exact capped-simplex projection by bisection. Batched over (instances x restarts). """ n, m = U.shape Ub = np.repeat(U, restarts, axis=1) Wb = np.repeat(W, restarts, axis=1) Kb = np.repeat(K, restarts) batch = m * restarts dir_samples = rng.dirichlet(np.ones(n), size=batch).T Y0 = dir_samples * Kb[None, :] P = project_capped_simplex_batch(Y0, Kb, bisect_iters) Mcur = batch_objective(Ub, P, Wb, family, q) eta = np.full(batch, 0.5) for _ in range(steps): G = batch_grad_p(Ub, P, Wb, family, q) Y = P + eta[None, :] * G Pn = project_capped_simplex_batch(Y, Kb, bisect_iters) Mn = batch_objective(Ub, Pn, Wb, family, q) improved = Mn >= Mcur - 1e-12 P = np.where(improved[None, :], Pn, P) Mcur = np.where(improved, Mn, Mcur) eta = np.where(improved, np.minimum(eta * 1.05, 5.0), eta * 0.6) Pr = P.reshape(n, m, restarts) Mr = Mcur.reshape(m, restarts) best = np.argmax(Mr, axis=1) Pbest = Pr[:, np.arange(m), best] Mbest = Mr[np.arange(m), best] return Pbest, Mbest # ================================================= vertex/face enumeration # n <= 6: enumerate sign patterns (p_i in {0,1,free}); solve the remaining # low-dim problem by a few random starts refined via pairwise ternary-search # coordinate sweeps (concave-on-a-line => ternary search finds the segment # optimum). This does not call core/oracles.py. def _ternary_max(f, lo, hi, iters): for _ in range(iters): m1 = lo + (hi - lo) / 3.0 m2 = hi - (hi - lo) / 3.0 if f(m1) < f(m2): lo = m1 else: hi = m2 return (lo + hi) / 2.0 def _refine_free(u, w, q, family, free, base_p, rem, rng, rounds, ternary_iters, n_starts): d = len(free) if d == 1: val = min(max(rem, 0.0), 1.0) p = base_p.copy() p[free[0]] = val return np.array([val]), swf(u * p, family, w, q) starts = [np.full(d, rem / d)] for _ in range(n_starts): raw = rng.dirichlet(np.ones(d)) * rem starts.append(np.clip(raw, 0.0, 1.0)) best_local_M = -np.inf best_local = None idxs = np.arange(d) for s in starts: cur = s.copy() for _ in range(rounds): order = idxs.copy() rng.shuffle(order) order = order.tolist() for a, b in zip(order[:-1], order[1:]): s_ab = cur[a] + cur[b] lo = max(0.0, s_ab - 1.0) hi = min(1.0, s_ab) if hi - lo < 1e-15: continue def f(t, a=a, b=b, s_ab=s_ab): trial = cur.copy() trial[a] = t trial[b] = s_ab - t p = base_p.copy() for idx2, i in enumerate(free): p[i] = trial[idx2] return swf(u * p, family, w, q) t = _ternary_max(f, lo, hi, ternary_iters) cur[a] = t cur[b] = s_ab - t p = base_p.copy() for idx2, i in enumerate(free): p[i] = cur[idx2] Mc = swf(u * p, family, w, q) if Mc > best_local_M: best_local_M = Mc best_local = cur.copy() return best_local, best_local_M def enumerate_baseline(u, w, q, k, family, rng, rounds=3, ternary_iters=20, n_starts=2): n = len(u) best_M = -np.inf best_p = None for pattern in itertools.product((0, 1, 2), repeat=n): ones = [i for i in range(n) if pattern[i] == 1] free = [i for i in range(n) if pattern[i] == 2] rem = k - len(ones) if rem < -1e-9 or rem > len(free) + 1e-9: continue p = np.zeros(n) for i in ones: p[i] = 1.0 if not free: if abs(rem) > 1e-9: continue M = swf(u * p, family, w, q) else: p_free, M = _refine_free(u, w, q, family, free, p, rem, rng, rounds, ternary_iters, n_starts) for idx2, i in enumerate(free): p[i] = p_free[idx2] if M > best_M: best_M = M best_p = p.copy() return best_p, best_M # ============================================================== O1 (per cell) def compute_o1_cell(family, q, n_instances, enum_cap, restarts, steps, bisect_iters, seed): rng = np.random.default_rng(seed) grid = [(n, k) for n in range(3, 9) for k in range(1, n + 1)] reps = int(math.ceil(n_instances / len(grid))) nk_list = (grid * reps)[:n_instances] nk_arr = np.array(nk_list) perm = rng.permutation(len(nk_arr)) nk_arr = nk_arr[perm] instances = [] for n, k in nk_arr: n, k = int(n), int(k) u = rng.uniform(0.05, 2.0, n) w = sample_w(rng, n, family) instances.append(dict(n=n, k=k, u=u, w=w)) oracle_M = np.empty(len(instances)) for i, inst in enumerate(instances): p = oracle(inst["u"], family, inst["w"], q, inst["k"]) oracle_M[i] = swf(inst["u"] * p, family, inst["w"], q) baseline_M = np.full(len(instances), -np.inf) by_n = {} for i, inst in enumerate(instances): by_n.setdefault(inst["n"], []).append(i) for n, idxs in by_n.items(): U = np.stack([instances[i]["u"] for i in idxs], axis=1) W = np.stack([instances[i]["w"] for i in idxs], axis=1) K = np.array([instances[i]["k"] for i in idxs], dtype=float) Pbest, Mbest = pga_run(U, W, K, family, q, restarts, steps, bisect_iters, rng) for j, i in enumerate(idxs): baseline_M[i] = Mbest[j] small_idx = [i for i, inst in enumerate(instances) if inst["n"] <= 6][:enum_cap] for i in small_idx: inst = instances[i] _, M_enum = enumerate_baseline(inst["u"], inst["w"], q, inst["k"], family, rng) if M_enum > baseline_M[i]: baseline_M[i] = M_enum deficit = baseline_M - oracle_M n_viol = int(np.sum(deficit > TOL)) max_deficit = float(np.max(deficit)) rel_gap = (oracle_M - baseline_M) / np.maximum(np.abs(oracle_M), 1e-9) mean_relative_gap = float(np.mean(rel_gap)) frac_strict = float(np.mean(oracle_M > baseline_M + 1e-9)) baseline_name = "pga+enumeration(n<=6,capped)" if enum_cap > 0 else "pga" log(f"O1 {family} q={qlabel(q)} n_inst={len(instances)} viol={n_viol} " f"max_deficit={max_deficit:.3e} frac_strict={frac_strict:.3f}") return { "check": "O1", "family": family, "q": qlabel(q), "n_instances": len(instances), "n_violations": n_viol, "max_deficit": max_deficit, "mean_relative_gap": mean_relative_gap, "frac_oracle_strictly_better": frac_strict, "baseline": baseline_name, } # ==================================================================== O2 def compute_o2(n_instances, seed): rng = np.random.default_rng(seed) max_box = 0.0 max_sum = 0.0 for _ in range(n_instances): n = int(rng.integers(3, 501)) family, q = ALL_COMBOS[rng.integers(len(ALL_COMBOS))] k = int(rng.integers(1, n + 1)) u = rng.uniform(0.05, 2.0, n) w = sample_w(rng, n, family) p = oracle(u, family, w, q, k) box = max(float(np.max(np.maximum(-p, 0.0))), float(np.max(np.maximum(p - 1.0, 0.0)))) s = abs(float(np.sum(p)) - k) max_box = max(max_box, box) max_sum = max(max_sum, s) log(f"O2 n_inst={n_instances} max_box={max_box:.3e} max_sum={max_sum:.3e}") return {"check": "O2", "n_instances": n_instances, "max_box_violation": max_box, "max_sum_violation": max_sum} # ==================================================================== O3 def compute_o3(family, q, n_instances, seed): rng = np.random.default_rng(seed) max_free_residual = 0.0 n_dual_violations = 0 n_degenerate = 0 for _ in range(n_instances): n = int(rng.integers(5, 51)) k = int(rng.integers(1, n + 1)) u = rng.uniform(0.05, 2.0, n) w = sample_w(rng, n, family) p = oracle(u, family, w, q, k) v = u * p V = v[:, None] W = w[:, None] if family == "wpm": M = batch_wpm_val(V, W, q) g = (batch_wpm_grad_v(V, W, q, M) * u[:, None])[:, 0] else: g = (batch_kolm_grad_v(V, W, q) * u[:, None])[:, 0] free_mask = (p > 1e-9) & (p < 1.0 - 1e-9) if not np.any(free_mask): n_degenerate += 1 continue gamma = float(np.median(g[free_mask])) resid = float(np.max(np.abs(g[free_mask] - gamma))) max_free_residual = max(max_free_residual, resid) one_mask = p >= 1.0 - 1e-9 zero_mask = p <= 1e-9 viol_one = int(np.sum(g[one_mask] < gamma - 1e-6)) viol_zero = int(np.sum(g[zero_mask] > gamma + 1e-6)) if viol_one + viol_zero > 0: n_dual_violations += 1 log(f"O3 {family} q={qlabel(q)} n_inst={n_instances} n_degenerate={n_degenerate} " f"max_resid={max_free_residual:.3e} n_dual_viol={n_dual_violations}") return {"check": "O3", "family": family, "q": qlabel(q), "n_instances": n_instances, "n_degenerate": n_degenerate, "max_free_set_residual": max_free_residual, "n_dual_violations": n_dual_violations} # ==================================================================== O4 def compute_o4_utilitarian(n_instances, seed): rng = np.random.default_rng(seed) configs = [("wpm", 1.0), ("kolm", 0.0), ("gini", None)] n_viol = 0 max_violation = 0.0 for _ in range(n_instances): family, q = configs[int(rng.integers(3))] n = int(rng.integers(3, 51)) k = int(rng.integers(1, n + 1)) u = rng.uniform(0.05, 2.0, n) if family == "gini": w = np.full(n, 1.0 / n) priority = u else: w = rng.dirichlet(np.ones(n)) priority = w * u p = oracle(u, family, w, q, k) top = np.argsort(-priority, kind="stable")[:k] expected = np.zeros(n) expected[top] = 1.0 viol = float(np.max(np.abs(p - expected))) if viol > 1e-9: n_viol += 1 max_violation = max(max_violation, viol) log(f"O4 utilitarian n_inst={n_instances} n_viol={n_viol}") return {"check": "O4", "case": "utilitarian", "family": "mixed", "q": None, "n_instances": n_instances, "n_violations": n_viol, "max_violation": max_violation} def compute_o4_egalitarian(n_instances, seed): rng = np.random.default_rng(seed) n_viol = 0 max_violation = 0.0 for _ in range(n_instances): choice = int(rng.integers(3)) n = int(rng.integers(3, 51)) k = int(rng.integers(1, n + 1)) u = rng.uniform(0.05, 2.0, n) if choice == 0: family, q, w = "wpm", NEG_INF, rng.dirichlet(np.ones(n)) elif choice == 1: family, q, w = "kolm", NEG_INF, rng.dirichlet(np.ones(n)) else: family, q = "gini", None w = np.zeros(n) w[0] = 1.0 p = oracle(u, family, w, q, k) free_mask = (p > 1e-9) & (p < 1.0 - 1e-9) if np.any(free_mask): vals = u[free_mask] * p[free_mask] resid = float(np.max(vals) - np.min(vals)) else: resid = 0.0 ones_mask = p >= 1.0 - 1e-9 others_mask = ~ones_mask if np.any(ones_mask) and np.any(others_mask): order_viol = max(0.0, float(np.max(u[ones_mask]) - np.min(u[others_mask]))) else: order_viol = 0.0 viol = max(resid, order_viol) if viol > TOL: n_viol += 1 max_violation = max(max_violation, viol) log(f"O4 egalitarian n_inst={n_instances} n_viol={n_viol}") return {"check": "O4", "case": "egalitarian", "family": "mixed", "q": None, "n_instances": n_instances, "n_violations": n_viol, "max_violation": max_violation} def compute_o4_wpmq0(n_pairs, seed): rng = np.random.default_rng(seed) n_viol = 0 max_violation = 0.0 for _ in range(n_pairs): n = int(rng.integers(3, 51)) k = int(rng.integers(1, n + 1)) w = rng.dirichlet(np.ones(n)) u1 = rng.uniform(0.05, 2.0, n) u2 = rng.uniform(0.05, 2.0, n) p1 = oracle(u1, "wpm", w, 0.0, k) p2 = oracle(u2, "wpm", w, 0.0, k) viol = float(np.max(np.abs(p1 - p2))) if viol >= 1e-9: n_viol += 1 max_violation = max(max_violation, viol) log(f"O4 wpm_q0_invariance n_pairs={n_pairs} n_viol={n_viol}") return {"check": "O4", "case": "wpm_q0_invariance", "family": "wpm", "q": 0.0, "n_instances": n_pairs, "n_violations": n_viol, "max_violation": max_violation} def compute_o4_k_equals_n(n_instances, seed): rng = np.random.default_rng(seed) n_viol = 0 max_violation = 0.0 for _ in range(n_instances): family, q = ALL_COMBOS[rng.integers(len(ALL_COMBOS))] n = int(rng.integers(3, 51)) k = n u = rng.uniform(0.05, 2.0, n) w = sample_w(rng, n, family) p = oracle(u, family, w, q, k) viol = float(np.max(np.abs(p - 1.0))) if viol >= 1e-9: n_viol += 1 max_violation = max(max_violation, viol) log(f"O4 k_equals_n n_inst={n_instances} n_viol={n_viol}") return {"check": "O4", "case": "k_equals_n", "family": "mixed", "q": None, "n_instances": n_instances, "n_violations": n_viol, "max_violation": max_violation} # ==================================================================== O5 def compute_o5(n_instances, seed): rng = np.random.default_rng(seed) n_viol = 0 max_violation = 0.0 for _ in range(n_instances): n = int(rng.integers(3, 201)) k = int(rng.integers(1, n + 1)) u = rng.uniform(0.05, 2.0, n) w = np.sort(rng.uniform(0.0, 1.0, n))[::-1] p = oracle(u, "gini", w, None, k) order = np.argsort(u) vp = (u * p)[order] diffs = vp[1:] - vp[:-1] viol = float(max(0.0, -np.min(diffs))) if len(diffs) else 0.0 if viol > 1e-9: n_viol += 1 max_violation = max(max_violation, viol) log(f"O5 n_inst={n_instances} n_viol={n_viol}") return {"check": "O5", "n_instances": n_instances, "n_violations": n_viol, "max_violation": max_violation} # ==================================================================== O6 def timed_median(fn, reps, group=5): fn() # warm cache times = np.empty(reps) for i in range(reps): t0 = time.perf_counter() fn() times[i] = time.perf_counter() - t0 n_groups = max(1, reps // group) mins = [float(np.min(times[i * group:(i + 1) * group])) for i in range(n_groups)] return float(np.median(mins)) def fit_loglog(xs, ys): lx = np.log(np.array(xs, dtype=float)) ly = np.log(np.array(ys, dtype=float)) slope, intercept = np.polyfit(lx, ly, 1) pred = slope * lx + intercept ss_res = float(np.sum((ly - pred) ** 2)) ss_tot = float(np.sum((ly - np.mean(ly)) ** 2)) r2 = 1.0 - ss_res / ss_tot if ss_tot > 0 else 1.0 return float(slope), float(r2) def compute_timing_family_n(family, qs, n_grid, reps, seed): rng = np.random.default_rng(seed) rows = [] for q in qs: xs, secs = [], [] for n in n_grid: k = max(1, math.ceil(n / 10)) u = rng.uniform(0.05, 2.0, n) w = sample_w(rng, n, family) t = timed_median(lambda: oracle(u, family, w, q, k), reps) xs.append(int(n)) secs.append(t) rho, r2 = fit_loglog(xs, secs) log(f"O6 timing {family} q={qlabel(q)} vs n: rho={rho:.3f} r2={r2:.3f}") rows.append({"family": family, "q": qlabel(q), "variable": "n", "x": xs, "seconds": secs, "rho": rho, "r2": r2, "k_setting": "ceil(n/10)"}) return rows def compute_timing_gini_n(n_grid, reps, seed): rng = np.random.default_rng(seed) xs, secs = [], [] for n in n_grid: k = min(10, n) u = rng.uniform(0.05, 2.0, n) w = np.sort(rng.uniform(0.0, 1.0, n))[::-1] t = timed_median(lambda: oracle(u, "gini", w, None, k), reps) xs.append(int(n)) secs.append(t) rho, r2 = fit_loglog(xs, secs) log(f"O6 timing gini vs n: rho={rho:.3f} r2={r2:.3f}") return {"family": "gini", "q": None, "variable": "n", "x": xs, "seconds": secs, "rho": rho, "r2": r2, "k_setting": "10"} def compute_timing_gini_k(k_grid, n_fixed, reps, seed): rng = np.random.default_rng(seed) u = rng.uniform(0.05, 2.0, n_fixed) w = np.sort(rng.uniform(0.0, 1.0, n_fixed))[::-1] xs, secs = [], [] for k in k_grid: k = min(k, n_fixed) t = timed_median(lambda: oracle(u, "gini", w, None, k), reps) xs.append(int(k)) secs.append(t) rho, r2 = fit_loglog(xs, secs) log(f"O6 timing gini vs k: rho={rho:.3f} r2={r2:.3f}") return {"family": "gini", "q": None, "variable": "k", "x": xs, "seconds": secs, "rho": rho, "r2": r2, "k_setting": f"n={n_fixed}"} # ============================================================== parameters def build_params(toy): if toy: return dict( o1_n=10, o1_restarts=3, o1_steps=20, o1_bisect_iters=20, o1_enum_cap=3, o2_n=200, o3_n=20, o4_n=30, o4_kn=30, o5_n=30, timing_n_grid=[10, 20], timing_reps=5, timing_k_grid=[1, 2], timing_gini_k_n=20, ) return dict( o1_n=5000, o1_restarts=200, o1_steps=1500, o1_bisect_iters=30, o1_enum_cap=300, o2_n=100_000, o3_n=10_000, o4_n=10_000, o4_kn=1_000, o5_n=10_000, timing_n_grid=[50, 100, 200, 500, 1000, 2000, 5000], timing_reps=200, timing_k_grid=[1, 2, 5, 10, 20, 50, 100, 200, 500], timing_gini_k_n=2000, ) # ==================================================================== main def main(): ap = argparse.ArgumentParser() ap.add_argument("--toy", action="store_true") args = ap.parse_args() t0 = time.time() n_jobs = max(1, min(int(os.environ.get("JOB_CORES", "4")), 12)) log(f"JOB_CORES(n_jobs)={n_jobs} numpy={np.__version__} toy={args.toy}") P = build_params(args.toy) log(f"O1: running {len(EXP05_FAMQ)} (family,q) cells via joblib " f"(n_instances={P['o1_n']}, restarts={P['o1_restarts']}, steps={P['o1_steps']})") o1_tasks = list(EXP05_FAMQ) results_o1 = run_grid( lambda t: compute_o1_cell(t[0], t[1], P["o1_n"], P["o1_enum_cap"], P["o1_restarts"], P["o1_steps"], P["o1_bisect_iters"], sid("O1", t[0], t[1])), o1_tasks, n_jobs=n_jobs) log("O1 done") o3_tasks = [("wpm", q) for q in O3_WPM_Q] + [("kolm", q) for q in O3_KOLM_Q] log(f"O3: running {len(o3_tasks)} (family,q) cells via joblib (n_instances={P['o3_n']})") results_o3 = run_grid( lambda t: compute_o3(t[0], t[1], P["o3_n"], sid("O3", t[0], t[1])), o3_tasks, n_jobs=n_jobs) log("O3 done") o2 = compute_o2(P["o2_n"], sid("O2")) o4a = compute_o4_utilitarian(P["o4_n"], sid("O4u")) o4b = compute_o4_egalitarian(P["o4_n"], sid("O4e")) o4c = compute_o4_wpmq0(P["o4_n"], sid("O4w")) o4d = compute_o4_k_equals_n(P["o4_kn"], sid("O4k")) o5 = compute_o5(P["o5_n"], sid("O5")) log("O6: timing (single-threaded, pinned if possible)") os.environ["OMP_NUM_THREADS"] = "1" try: os.sched_setaffinity(0, {0}) except (AttributeError, OSError): log("sched_setaffinity unavailable on this platform; proceeding without pinning") t_wpm = compute_timing_family_n("wpm", FAMILY_Q["wpm"], P["timing_n_grid"], P["timing_reps"], sid("O6wpm")) t_kolm = compute_timing_family_n("kolm", FAMILY_Q["kolm"], P["timing_n_grid"], P["timing_reps"], sid("O6kolm")) t_gini_n = compute_timing_gini_n(P["timing_n_grid"], P["timing_reps"], sid("O6ginin")) t_gini_k = compute_timing_gini_k(P["timing_k_grid"], P["timing_gini_k_n"], P["timing_reps"], sid("O6ginik")) timing = t_wpm + t_kolm + [t_gini_n, t_gini_k] invariants = [o2, *results_o3, o4a, o4b, o4c, o4d, o5] total_exactness_violations = int(sum(e["n_violations"] for e in results_o1)) o2_viol = 1 if (o2["max_box_violation"] > 1e-6 or o2["max_sum_violation"] > 1e-6) else 0 total_invariant_violations = int( o2_viol + sum(e["n_dual_violations"] for e in results_o3) + o4a["n_violations"] + o4b["n_violations"] + o4c["n_violations"] + o4d["n_violations"] + o5["n_violations"]) wpm_rhos = [r["rho"] for r in t_wpm] kolm_rhos = [r["rho"] for r in t_kolm] rho_by_family = { "wpm": float(np.mean(wpm_rhos)), "kolm": float(np.mean(kolm_rhos)), "gini_n": float(t_gini_n["rho"]), "gini_k": float(t_gini_k["rho"]), } meta = dict( exp="exp05", n_cores_used=n_jobs, wall_time_sec=time.time() - t0, seed_base=BASE_SEED, numpy_version=np.__version__, kolm_impl="n_squared", ambiguities={ "clip_range": [0.1, 1.0], "o1_enum_cap": P["o1_enum_cap"], "o1_bisect_iters": P["o1_bisect_iters"], }, ) out = dict( meta=meta, status="ok", exactness=results_o1, invariants=invariants, timing=timing, summary=dict( n_exactness_cells=len(results_o1), total_exactness_violations=total_exactness_violations, total_invariant_violations=total_invariant_violations, rho_by_family=rho_by_family, ), ) os.makedirs(os.path.dirname(RESULTS_PATH), exist_ok=True) with open(RESULTS_PATH, "w") as fh: json.dump(out, fh, indent=2) elapsed = time.time() - t0 print(f"exp05 done in {elapsed:.1f}s (toy={args.toy}, n_jobs={n_jobs})") print(f"O1: {len(results_o1)} cells, total_exactness_violations={total_exactness_violations}") print(f"invariants: {len(invariants)} entries, total_invariant_violations={total_invariant_violations}") print(f"timing: {len(timing)} curves, rho_by_family={rho_by_family}") print(f"kolm_impl={meta['kolm_impl']}") print(f"results written to {RESULTS_PATH}") return 0 if __name__ == "__main__": sys.exit(main())