#!/usr/bin/env python3 """E3: numerical fixed-oracle optimum over randomized fair-pair policies. The LP uses occupation measures, not an average of per-policy TV values. See docs/policy_lp_reduction.md for the scope and symmetry reduction. """ from __future__ import annotations import argparse from collections import defaultdict from dataclasses import dataclass from functools import lru_cache from itertools import combinations, combinations_with_replacement, product import json import math from pathlib import Path import time import numpy as np from scipy.optimize import linprog from scipy.sparse import coo_matrix, csr_matrix, hstack, vstack from scipy.special import logsumexp from scipy.stats import binom @dataclass(frozen=True) class Oracle: probabilities: tuple[float, ...] weights: tuple[float, ...] def __post_init__(self): if len(self.probabilities) != len(self.weights): raise ValueError("Component lengths differ") if not all(0 < p < 1 for p in self.probabilities): raise ValueError("Positive component probabilities are required") if not all(w > 0 for w in self.weights): raise ValueError("Positive mixture weights are required") if abs(sum(self.weights) - 1) > 1e-12: raise ValueError("Mixture weights must sum to one") @lru_cache(maxsize=None) def predictive(self, c: int, m: int) -> float: p = np.asarray(self.probabilities) logw = np.log(self.weights) + m * np.log(p) + (c - m) * np.log1p(-p) posterior = np.exp(logw - logsumexp(logw)) return float(posterior @ p) def predictive_direct(self, c: int, m: int) -> float: """Independent small-n evaluation used in recovered-policy checks.""" w = [a * p**m * (1 - p)**(c - m) for a, p in zip(self.weights, self.probabilities)] return sum(a * p for a, p in zip(w, self.probabilities)) / sum(w) def count_statistics(self, n: int, tau: float) -> dict: m = np.arange(n + 1) teacher = binom.pmf(m, n, tau) log_likelihoods = np.asarray([ np.log(a) + m * np.log(p / tau) + (n - m) * np.log((1 - p) / (1 - tau)) for a, p in zip(self.weights, self.probabilities) ]) log_ratio = logsumexp(log_likelihoods, axis=0) model = sum(a * binom.pmf(m, n, p) for a, p in zip(self.weights, self.probabilities)) return { "actual_joint_kl_P_to_R": float(-teacher @ log_ratio), "actual_joint_tv_P_R": float(np.abs(teacher - model).sum() / 2), "initial_predictive_drift": self.predictive(0, 0) - tau, } def aggregate_actions(n, state, final): c, _, o = state f = n - c - o if final: return [(o, f, 0)] return [(u, v, b) for u in range(o + 1) for v in range(f + 1) for b in range(f - v + 1)] def aggregate_transition(oracle, state, action): c, m, o = state u, v, b = action p = oracle.predictive(c, m) law = np.convolve(binom.pmf(np.arange(u + 1), u, p), binom.pmf(np.arange(v + 1), v, 0.5)) return {(c + u + v, m + j, o - u + b): float(prob) for j, prob in enumerate(law) if prob > 0} def direct_aggregate_transition(oracle, state, action): """Recompute without the cached PMF/convolution used in LP assembly.""" c, m, o = state u, v, b = action p = oracle.predictive_direct(c, m) result = defaultdict(float) for x in range(u + 1): px = math.comb(u, x) * p**x * (1 - p)**(u - x) for y in range(v + 1): py = math.comb(v, y) * 0.5**v result[(c + u + v, m + x + y, o - u + b)] += px * py return dict(result) def occupation_lp(initial, rounds, actions, transition, terminal_index, target, time_limit, action_limit): """Generic finite layered MDP LP, also used for literal-coordinate checks.""" start = time.perf_counter() layers = [{initial}] records = [] by_state = defaultdict(list) for t in range(rounds): following = set() for state in sorted(layers[t]): for action in actions(state, t == rounds - 1): kernel = transition(state, action) residual = abs(sum(kernel.values()) - 1) if residual > 2e-12 or min(kernel.values()) < 0: raise ArithmeticError(f"Invalid transition: {residual}") j = len(records) if j >= action_limit: raise RuntimeError(f"State-action guard {action_limit} exceeded") records.append((t, state, action, kernel)) by_state[(t, state)].append(j) following.update(kernel) layers.append(following) na, nt = len(records), len(target) rows = {(t, s): i for i, (t, s) in enumerate( (t, s) for t in range(rounds) for s in sorted(layers[t]))} er, ec, ev, tr, tc, tv = [], [], [], [], [], [] for j, (t, state, action, kernel) in enumerate(records): er.append(rows[(t, state)]); ec.append(j); ev.append(1.0) for dest, prob in kernel.items(): if t + 1 < rounds: er.append(rows[(t + 1, dest)]); ec.append(j); ev.append(-prob) else: tr.append(terminal_index(dest)); tc.append(j); tv.append(prob) flow = coo_matrix((ev, (er, ec)), shape=(len(rows), na)).tocsr() terminal = coo_matrix((tv, (tr, tc)), shape=(nt, na)).tocsr() aeq = hstack([flow, csr_matrix((len(rows), nt))], format="csr") beq = np.zeros(len(rows)); beq[rows[(0, initial)]] = 1.0 ident = csr_matrix(np.eye(nt)) aub = vstack([hstack([terminal, -ident]), hstack([-terminal, -ident])], format="csr") bub = np.concatenate([target, -target]) cost = np.concatenate([np.zeros(na), np.full(nt, 0.5)]) assembly_seconds = time.perf_counter() - start solution = linprog(cost, A_ub=aub, b_ub=bub, A_eq=aeq, b_eq=beq, bounds=(0, None), method="highs", options={"time_limit": float(time_limit), "threads": 1, "primal_feasibility_tolerance": 1e-9, "dual_feasibility_tolerance": 1e-9}) elapsed = time.perf_counter() - start if not solution.success: raise RuntimeError(f"LP did not reach optimum: {solution.message}") x = solution.x[:na] q = np.asarray(terminal @ x).ravel() dual_value = float(beq @ solution.eqlin.marginals + bub @ solution.ineqlin.marginals) dual_slack = cost - aeq.T @ solution.eqlin.marginals - aub.T @ solution.ineqlin.marginals diagnostics = { "solver_status": int(solution.status), "solver_message": solution.message, "state_counts_by_layer": [len(s) for s in layers], "action_occupancy_variables": na, "lp_variables": na + nt, "flow_constraints": len(rows), "assembly_seconds": assembly_seconds, "total_seconds": elapsed, "solver_objective": float(solution.fun), "objective_recomputed_from_terminal": float(np.abs(q - target).sum() / 2), "max_flow_residual": float(np.max(np.abs(aeq @ solution.x - beq))), "max_l1_constraint_violation": float(max(0, np.max(aub @ solution.x - bub))), "minimum_variable": float(np.min(solution.x)), "terminal_mass_residual": float(abs(q.sum() - 1)), "dual_objective": dual_value, "primal_dual_gap": float(solution.fun - dual_value), "max_dual_slack_violation": float(max(0, -np.min(dual_slack))), "certificate_type": "floating-point diagnostics, not a rigorous exact certificate", } return {"records": records, "by_state": by_state, "occupancies": x, "terminal": q, "diagnostics": diagnostics} def recover_and_evaluate(result, oracle, n, rounds): policies = {} serialized = [] records, occupancies = result["records"], result["occupancies"] for (t, state), indices in result["by_state"].items(): raw = np.asarray([max(0.0, occupancies[j]) for j in indices]) total = float(raw.sum()) if total > 0: weights = raw / total else: weights = np.zeros(len(indices)); weights[0] = 1.0 policy = [(records[j][2], float(a)) for j, a in zip(indices, weights) if a > 0] policies[(t, state)] = policy if total > 0: serialized.append({"round": t + 1, "state_c_m_o": list(state), "state_occupancy": total, "actions": [{"u_v_b": list(action), "probability": a} for action, a in policy]}) mass = {(0, 0, 0): 1.0} stage_mass_residuals = [] for t in range(rounds): following = defaultdict(float) for state, state_mass in mass.items(): for action, action_prob in policies[(t, state)]: for dest, transition_prob in direct_aggregate_transition(oracle, state, action).items(): following[dest] += state_mass * action_prob * transition_prob mass = dict(following) stage_mass_residuals.append(abs(sum(mass.values()) - 1)) q = np.zeros(n + 1) for (c, m, o), prob in mass.items(): if c != n or o != 0: raise AssertionError("Recovered policy leaves unassigned coordinates") q[m] += prob diagnostics = { "recovered_terminal_max_difference": float(np.max(np.abs(q - result["terminal"]))), "recovered_stage_mass_max_residual": max(stage_mass_residuals), "recovered_terminal": q.tolist(), } return serialized, diagnostics def schedule_terminal(oracle, n, cumulative_completions): # Round 1 reveals one endpoint of every pair; subsequent rounds complete # uniformly selected open pairs. Hidden pair randomization is essential. mass = {(0, 0, n): 1.0} completed = 0 for cumulative in cumulative_completions: batch = cumulative - completed following = defaultdict(float) for state, prob in mass.items(): for dest, conditional in direct_aggregate_transition(oracle, state, (batch, 0, 0)).items(): following[dest] += prob * conditional mass = dict(following) completed = cumulative q = np.zeros(n + 1) for (c, m, o), prob in mass.items(): if c != n or o != 0: raise AssertionError("Incomplete baseline schedule") q[m] += prob return q def schedule_baselines(oracle, n, rounds, tau): r = rounds - 1 teacher = binom.pmf(np.arange(n + 1), n, tau) equal = tuple(math.ceil(n * j / r) for j in range(1, r + 1)) geometric = tuple(min(n, math.floor(n ** (j / r) + 1e-12)) for j in range(1, r + 1)) def evaluate(schedule): q = schedule_terminal(oracle, n, schedule) return float(np.abs(q - teacher).sum() / 2) all_grid = [tuple(prefix) + (n,) for prefix in combinations_with_replacement(range(n + 1), r - 1)] grid_values = [(evaluate(schedule), schedule) for schedule in all_grid] best_tv, best_schedule = min(grid_values) return { "equal": {"tv": evaluate(equal), "cumulative_completions": list(equal)}, "geometric_heuristic": {"tv": evaluate(geometric), "cumulative_completions": list(geometric)}, "best_fixed_completion_grid": { "tv": best_tv, "cumulative_completions": list(best_schedule), "number_of_schedules": len(all_grid), "grid": [{"tv": tv, "cumulative_completions": list(schedule)} for tv, schedule in grid_values], }, } def literal_problem(n, rounds, oracle, tau, time_limit, action_limit): """Independent full-coordinate finite MDP; no c,m,o reduction in assembly.""" complete = list(product((0, 1), repeat=2 * n)) law = {} target = [] for z in complete: mismatch = sum(z[2 * i] != z[2 * i + 1] for i in range(n)) law[z] = 2.0**(-n) * sum(a * p**mismatch * (1 - p)**(n - mismatch) for a, p in zip(oracle.weights, oracle.probabilities)) target.append(2.0**(-n) * tau**mismatch * (1 - tau)**(n - mismatch)) output_index = {z: i for i, z in enumerate(complete)} @lru_cache(maxsize=None) def literal_heads(state): compatible = [(z, p) for z, p in law.items() if all(x == -1 or x == y for x, y in zip(state, z))] denominator = sum(p for _, p in compatible) return tuple(sum(p * z[j] for z, p in compatible) / denominator for j in range(2 * n)) def actions(state, final): hidden = tuple(j for j, x in enumerate(state) if x == -1) if final: return [hidden] return [subset for size in range(len(hidden) + 1) for subset in combinations(hidden, size)] @lru_cache(maxsize=None) def transition(state, action): heads = literal_heads(state) kernel = {} for outcomes in product((0, 1), repeat=len(action)): dest = list(state) prob = 1.0 for j, bit in zip(action, outcomes): dest[j] = bit prob *= heads[j] if bit else 1 - heads[j] kernel[tuple(dest)] = prob return kernel result = occupation_lp((-1,) * (2 * n), rounds, actions, transition, output_index.__getitem__, np.asarray(target), time_limit, action_limit) return result["diagnostics"] def solve_aggregate(n, rounds, oracle, tau, time_limit, action_limit): target = binom.pmf(np.arange(n + 1), n, tau) result = occupation_lp((0, 0, 0), rounds, lambda s, final: aggregate_actions(n, s, final), lambda s, a: aggregate_transition(oracle, s, a), lambda s: s[1], target, time_limit, action_limit) policy, check = recover_and_evaluate(result, oracle, n, rounds) result["diagnostics"].update(check) return result, policy def assert_diagnostics(d): for key in ("max_flow_residual", "max_l1_constraint_violation", "terminal_mass_residual", "max_dual_slack_violation"): if d[key] > 2e-7: raise AssertionError(f"{key}={d[key]} exceeds tolerance") if abs(d["primal_dual_gap"]) > 2e-7 or d["minimum_variable"] < -2e-8: raise AssertionError("Primal/dual or nonnegativity diagnostic failed") if d.get("recovered_terminal_max_difference", 0) > 2e-7: raise AssertionError("Recovered policy disagrees with occupation solution") def randomization_regression(time_limit, action_limit): oracle = Oracle((0.125,), (1.0,)) result, policy = solve_aggregate(1, 2, oracle, 0.25, time_limit, action_limit) literal = literal_problem(1, 2, oracle, 0.25, time_limit, action_limit) assert_diagnostics(result["diagnostics"]) assert_diagnostics(literal) serial = sum(x * action[0] for x, (_, _, action, _) in zip(result["occupancies"], result["records"])) cosample = sum(x * action[1] for x, (_, _, action, _) in zip(result["occupancies"], result["records"])) if abs(serial - 2 / 3) > 1e-7 or abs(cosample - 1 / 3) > 1e-7: raise AssertionError("Expected randomized-policy mixture was not recovered") if max(result["diagnostics"]["solver_objective"], literal["solver_objective"]) > 1e-8: raise AssertionError("Randomized marginal-TV regression failed") return {"status": "PASS", "serial_probability": serial, "cosample_probability": cosample, "aggregate": result["diagnostics"], "literal": literal, "policy": policy} def atomic_json(path, obj): temporary = path.with_suffix(path.suffix + ".tmp") temporary.write_text(json.dumps(obj, indent=2, allow_nan=False) + "\n") temporary.replace(path) def run(config, output): cfg = config["e3"] if output.suffix == ".json": output_file = output output_dir = output.parent policy_dir = output_dir / (output.stem + "_policies") else: output_dir = output output_file = output_dir / "e3_results.json" policy_dir = output_dir / "policies" output_dir.mkdir(parents=True, exist_ok=True) policy_dir.mkdir(exist_ok=True) n_values = cfg.get("n_values", [2, 4, 6, 8]) rounds_values = cfg.get("rounds", [2, 3, 4]) tau, w, delta = (float(cfg.get(k, v)) for k, v in [("tau", 0.25), ("w", 0.125), ("delta", 0.25)]) lam = float(cfg.get("ladder_lambda", 0.2)) time_limit = min(float(cfg.get("time_limit_seconds", 120)), 120) action_limit = min(int(cfg.get("state_action_limit", 250000)), 250000) literal_n = set(cfg.get("literal_n_values", [1, 2])) if min(n_values) < 1 or min(rounds_values) < 2 or max(rounds_values) > 8: raise ValueError("Require n >= 1 and 2 <= K <= 8") models = { "single": Oracle((tau, tau + delta), (1 - w, w)), "two_level": Oracle((tau, tau + delta, tau + delta * (w / 2) * lam), (1 - w, w / 2, w / 2)), } result = { "experiment": "E3 fixed-oracle randomized-policy occupation LP", "scope": "inf_policy TV for each fixed R; not a KL-ball supremum or a minimax certificate", "arithmetic": "floating-point HiGHS with independent literal-coordinate and forward checks", "config": cfg, "status": "running", "cases": [], "errors": [], "randomization_regression": randomization_regression(time_limit, action_limit), } atomic_json(output_file, result) print("E3 randomization regression: PASS", flush=True) for name, oracle in models.items(): for n in n_values: previous = None for rounds in sorted(rounds_values): case_id = f"{name}_n{n}_K{rounds}" try: solved, policy = solve_aggregate(n, rounds, oracle, tau, time_limit, action_limit) diagnostics = solved["diagnostics"] assert_diagnostics(diagnostics) baselines = schedule_baselines(oracle, n, rounds, tau) optimum = diagnostics["objective_recomputed_from_terminal"] if optimum > min(b["tv"] for b in baselines.values()) + 2e-7: raise AssertionError("LP optimum is worse than a feasible baseline") if previous is not None and optimum > previous + 2e-7: raise AssertionError("Optimal error increased when adding a round") previous = optimum literal = None if n in literal_n: literal = literal_problem(n, rounds, oracle, tau, time_limit, action_limit) assert_diagnostics(literal) difference = abs(literal["objective_recomputed_from_terminal"] - optimum) literal["aggregate_objective_difference"] = difference if difference > 2e-7: raise AssertionError("Literal and aggregate LP objectives disagree") atomic_json(policy_dir / f"{case_id}.json", { "case_id": case_id, "n": n, "rounds": rounds, "oracle_probabilities": list(oracle.probabilities), "oracle_weights": list(oracle.weights), "policy": policy, "unvisited_state_rule": "choose first lexicographic legal action", "lift": "uniform pair selection and fair orientation for fresh singleton births", }) case = {"case_id": case_id, "model": name, "n": n, "rounds": rounds, "tau": tau, "oracle_probabilities": list(oracle.probabilities), "oracle_weights": list(oracle.weights), **oracle.count_statistics(n, tau), "optimal_tv": optimum, "diagnostics": diagnostics, "baselines": baselines, "literal_coordinate_check": literal, "policy_file": f"{policy_dir.name}/{case_id}.json"} result["cases"].append(case) print(f"E3 {case_id}: TV={optimum:.8g}, " f"vars={diagnostics['action_occupancy_variables']}, " f"seconds={diagnostics['total_seconds']:.3f}", flush=True) except (RuntimeError, ArithmeticError, AssertionError) as exc: result["errors"].append({"case_id": case_id, "error": str(exc)}) print(f"E3 {case_id}: FAILED: {exc}", flush=True) atomic_json(output_file, result) result["status"] = "complete" if not result["errors"] else "completed_with_errors" atomic_json(output_file, result) return not result["errors"] if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--config", type=Path, required=True) parser.add_argument("--output", type=Path, required=True) parser.add_argument("--validate-only", action="store_true", help="Run randomization regression and both fixed oracles at n=2, K=2,3") arguments = parser.parse_args() config = json.loads(arguments.config.read_text()) if arguments.validate_only: config["e3"].update(n_values=[2], rounds=[2, 3], literal_n_values=[2]) success = run(config, arguments.output) raise SystemExit(0 if success else 1)