#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Route 21 / job #1306: exact max-min one-step margin over the 47 deletion phases. Solves, in exact rational arithmetic, the LP the route's registered next_step prescribes: maximise m s.t. sum_i w_i = 1, w_i >= 0 for every phase c of 47 and every q in Q_47: m <= 1 - w(E_c) - sum_{q in Q_47} C'_q(c), C'_q(c) >= w(K_q(cc) \\ E_c) for every phase cc of q C'_q(c) is only ever pushed down to its own lower bound, so at an optimum C'_q(c) = max_cc w(K_q(cc) \\ E_c) and the constraint value is exactly #567's margin at phase c. Hence max m = max over the simplex of the WORST-CASE one-step margin. Method: cutting planes over an exact rational simplex. Each cut is a phase row instantiated with the pair cc that attains the maximum at the current w -- a row of the true LP, so the restricted problem is always a relaxation of it. Loop until the oracle (a full 47-phase margin evaluation, all pairs) agrees with the restricted optimum m*; then w* is primal feasible for the true LP at margin m* and m* is the optimum of a relaxation, so true opt = m* exactly. The final basis is independently re-verified: primal feasibility, reduced costs <= 0 (dual feasibility), strong duality. Everything stdlib; no network; no input files; deterministic. """ import hashlib import itertools import json import os import sys import time from fractions import Fraction as F sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from route21_model import (Instance, Q_NEW, Q_OLD, LEAVING, ENTERING, N_SLOTS, W, # noqa: E402 witness_575, uniform) SHIFT = 9 # m' = m + SHIFT >= 0 : margin >= 1 - w(E) - sum_q C'_q >= 1 - 1 - 9 = -9 # ------------------------------------------------------------------ exact LP (max, <=, x >= 0) def simplex_max(c, A, b, max_iter=100000): """max c.x s.t. A x <= b, x >= 0 with b >= 0. Dense exact two-phase-free primal simplex, Bland's rule (smallest entering index, smallest ratio; ties by smallest leaving index).""" n, m = len(c), len(A) T = [[F(x) for x in row] + [F(1) if i == j else F(0) for j in range(m)] + [F(b[i])] for i, row in enumerate(A)] # columns: x | slack | rhs basis = [n + j for j in range(m)] obj = [F(-c[j]) for j in range(n)] + [F(0)] * m + [F(0)] # row: (z_j - c_j) | rhs = z for it in range(max_iter): ent = next((j for j in range(n + m) if obj[j] < 0), None) if ent is None: break rows = [i for i in range(m) if T[i][ent] > 0] if not rows: raise RuntimeError("unbounded") piv = min(rows, key=lambda i: (T[i][-1] / T[i][ent], basis[i])) p = T[piv][ent] T[piv] = [v / p for v in T[piv]] for i in range(m): if i != piv and T[i][ent]: f = T[i][ent] T[i] = [a - f * bb for a, bb in zip(T[i], T[piv])] if obj[ent]: f = obj[ent] obj = [a - f * bb for a, bb in zip(obj, T[piv])] basis[piv] = ent else: raise RuntimeError("iteration limit") x = [F(0)] * (n + m) for i, j in enumerate(basis): x[j] = T[i][-1] return x[:n], obj[-1], basis, T def gauss_solve(B, rhs): """Exact solve B y = rhs (square, Fractions); returns None if singular.""" n = len(B) M = [list(B[i]) + [rhs[i]] for i in range(n)] for col in range(n): p = next((r for r in range(col, n) if M[r][col] != 0), None) if p is None: return None M[col], M[p] = M[p], M[col] pv = M[col][col] M[col] = [v / pv for v in M[col]] for r in range(n): if r != col and M[r][col]: f = M[r][col] M[r] = [a - f * bb for a, bb in zip(M[r], M[col])] return [M[i][-1] for i in range(n)] def verify_optimal(c, A, b, basis, x, obj): """Independent certificate for max c.x s.t. Ax<=b, x>=0, recomputed from the final BASIS with exact Gaussian elimination (not from the simplex tableau): solve y from B^T y = c_B, then check primal feasibility, dual feasibility (y >= 0 and every reduced cost c_j - y.A_j <= 0) and strong duality y.b = obj. If all four hold, x is an optimal solution of that LP.""" n, m = len(c), len(A) col = lambda j: [A[i][j] for i in range(m)] if j < n else [F(1) if i == j - n else F(0) for i in range(m)] if len(basis) != m or len(set(basis)) != m: return {"all_conditions": False, "note": f"basis not square: {len(basis)} != {m}"} B = [[col(basis[k])[i] for k in range(m)] for i in range(m)] # B[i][k] = (column of basis k) at row i cb = [c[j] if j < n else F(0) for j in basis] y = gauss_solve([[B[i][k] for i in range(m)] for k in range(m)], cb) # solve B^T y = c_B primal_ok = (all(x[j] >= 0 for j in range(n)) and all(sum(A[i][j] * x[j] for j in range(n)) <= b[i] for i in range(m))) if y is None: return {"all_conditions": False, "primal_feasible": primal_ok, "note": "singular basis"} rc = [c[j] - sum(y[i] * A[i][j] for i in range(m)) for j in range(n)] dual_ok = all(v >= 0 for v in y) obj_dual = sum(y[i] * b[i] for i in range(m)) return {"all_conditions": bool(primal_ok and dual_ok and all(v <= 0 for v in rc) and obj_dual == obj), "primal_feasible": primal_ok, "dual_feasible": dual_ok, "reduced_costs_le_zero": all(v <= 0 for v in rc), "strong_duality": obj_dual == obj, "dual_objective": str(obj_dual), "obj": str(obj)} # ------------------------------------------------------------------ the true LP by cutting planes def phase_row(inst, c, w, shift=SHIFT): """Row of the TRUE LP for phase c instantiated at the pairs binding at w. Returns (coefficients over w (length N), rhs) for the constraint m' + sum_i coef_i w_i <= 1 + shift.""" dead = set(inst.deleted[c]) coef = [F(0)] * inst.N for i in dead: coef[i] += 1 binds, val = {}, F(0) for q in Q_NEW: v, arg = inst.post_capacity(q, c, w) binds[q] = arg val += v for i in inst.pairs_new[q].get(arg, ()): # K_q(arg) \ E_c if i not in dead: coef[i] += 1 margin = W - (sum(w[i] for i in dead) + val) assert margin == W - sum(coef[i] * w[i] for i in range(inst.N)), "row/value mismatch" return coef, binds, margin def solve_window(window_start, max_cuts=400, verbose=False, init_w=None): """Exact max-min margin for one window, with the certificate. The starting row set only affects the path: every accumulated row is an implied row of the true LP, so the restricted problem is always a relaxation (upper bound), and the returned w has its margin evaluated by the full oracle (a feasible lower bound). The run stops when they meet.""" t0 = time.time() inst = Instance(window_start) N = inst.N rows = [] # (coef over the first N-1 free weights, rhs) of the restricted LP def build(active): """Restricted LP with the given (phase, binds) rows, w_{N-1} substituted out.""" A, b = [], [] for key, coef in active: # m' + sum_i coef_i w_i <= 1 + SHIFT ; substitute w_{N-1} = 1 - sum_{i= 0 cvec = [F(0)] * (N - 1) + [F(1)] return A, b, cvec def w_from(x): w = list(x[:N - 1]) w.append(F(1) - sum(w)) return w # start: the rows binding at the uniform weights (valid implied rows of the true LP, so the # restricted problem is always a RELAXATION of it and its optimum is an upper bound) w0 = init_w if init_w is not None else uniform(N) active, keys = [], set() def add_row(c, w): coef, binds, _ = phase_row(inst, c, w) sig = (c,) + tuple(int(v) for v in coef) if sig in keys: return False keys.add(sig) active.append((sig, coef)) return True for c in inst.phases: add_row(c, w0) best_lower, best_w, ncuts, stalled = None, None, 0, 0 for it in range(max_cuts): A, b, cvec = build(active) x, objp, basis, T = simplex_max(cvec, A, b) w = w_from(x) m = objp - SHIFT m_or, arg, prof = inst.oracle(w) if best_lower is None or m_or > best_lower: best_lower, best_w = m_or, w if verbose: print(f" it={it} rows={len(active)} m*={m} oracle_at_w*={m_or}", flush=True) if m_or == m: proof = verify_optimal(cvec, A, b, basis, x, objp) return {"window_start": window_start, "N": N, "slots": inst.xs, "span_L": inst.span + 1, "w": [str(v) for v in w], "w_denominator": str((w[0]).denominator), "max_min_margin": str(m), "oracle_min_margin": str(m_or), "argmin_phase": arg["phase"], "cuts": len(active), "iterations": it + 1, "restricted_lp_certificate": proof, "restricted_rows": len(A), "profile": [{"phase": r["phase"], "margin": str(r["margin"]), "deleted_weight": str(r["deleted_weight"]), "enter_cost": str(r["enter_cost"])} for r in prof], "max_margin": str(max(r["margin"] for r in prof)), "positive_phases": sum(1 for r in prof if r["margin"] > 0), "zero_phases": sum(1 for r in prof if r["margin"] == 0), "delta": str(inst.delta(w)[0]), "exact": True, "wall_s": round(time.time() - t0, 2)} # violated: the phase row binding at w* is an implied row of the true LP; add it. If it is # already present the relaxation is at a degenerate face, so add the rows of every phase. if not add_row(arg["phase"], w): stalled += 1 for c2 in inst.phases: add_row(c2, w) if stalled > 12: break ncuts += 1 # no exact meet: report the honest interval [best verified feasible margin, relaxation optimum] return {"window_start": window_start, "N": N, "slots": inst.xs, "span_L": inst.span + 1, "exact": False, "stalled": stalled, "cuts": len(active), "iterations": max_cuts, "upper_bound_relaxation": str(m), "lower_bound_feasible": str(best_lower), "w_upper": [str(v) for v in w], "w_lower": [str(v) for v in best_w], "best_lower_profile": [{"phase": r["phase"], "margin": str(r["margin"])} for r in inst.margin_profile(best_w)], "wall_s": round(time.time() - t0, 2)} def selftest(trials=120, seed=20260915): """Validate the simplex against exact vertex enumeration on small random rational LPs. This is the cheapest credible check on the solver itself, before any of its numbers are used.""" import random rnd = random.Random(seed) bad = [] for t in range(trials): n = rnd.randint(1, 4) m = rnd.randint(1, 5) A = [[F(rnd.randint(-4, 6)) for _ in range(n)] for _ in range(m)] b = [F(rnd.randint(0, 8)) for _ in range(m)] c = [F(rnd.randint(-3, 5)) for _ in range(n)] try: x, obj, basis, T = simplex_max(c, A, b) except RuntimeError: continue # unbounded/edge case: not compared here cert = verify_optimal(c, A, b, basis, x, obj) # brute force: enumerate n-subsets of the m + n constraints (rows, then -x_j <= 0) best = None cons = [(A[i], b[i]) for i in range(m)] + [([F(-1) if k == j else F(0) for k in range(n)], F(0)) for j in range(n)] for idx in itertools.combinations(range(m + n), n): M = [cons[i][0] for i in idx] y = gauss_solve(M, [cons[i][1] for i in idx]) if y is None: continue if all(sum(cons[i][0][j] * y[j] for j in range(n)) <= cons[i][1] + 0 for i in range(m + n)): v = sum(c[j] * y[j] for j in range(n)) if y and all(y[j] >= 0 for j in range(n)) and (best is None or v > best): best = v if best is not None and (obj != best or not cert["all_conditions"]): bad.append({"trial": t, "n": n, "m": m, "simplex": str(obj), "brute": str(best), "cert": cert["all_conditions"]}) print(json.dumps({"trials": trials, "mismatches": len(bad), "examples": bad[:3]}, indent=1)) return not bad def main(): windows = [int(a) for a in sys.argv[1:]] or [1160000, 1240000, 1280000, 1000000] out = {} for ws in windows: print(f"window {ws} ...", flush=True) out[str(ws)] = solve_window(ws, verbose=True) r = out[str(ws)] print(f" -> max-min margin {r['max_min_margin']} (argmin phase {r['argmin_phase']}), " f"delta {r['delta']}, cuts {r['cuts']}, {r['wall_s']}s, " f"certificate {r['restricted_lp_certificate'].get('all_conditions')}") body = json.dumps(out, indent=1, sort_keys=True, default=str) print(body) print("sha256(result):", hashlib.sha256(body.encode()).hexdigest()) return out if __name__ == "__main__": if len(sys.argv) > 1 and sys.argv[1] == "--selftest": sys.exit(0 if selftest() else 1) main()