#!/usr/bin/env python3 """Route 21, job #1297: prime-band boundary-margin transport of a slot-weight witness. Prescribed case, preregistered in preregistration.json (written before this ran): support = first N=20 twin-admissible starts at or after a declared window start, band p = 43 -> r = 47, sole entering owner 89. Exact rational arithmetic throughout (Fraction). Stdlib only. Deterministic: no randomness, no input files, no network. Reproduce with `python3 route21_band_margin.py`. """ from fractions import Fraction as F import json, sys, time # ---------------------------------------------------------------- parameters WINDOW_START = 1000000 N_SLOTS = 20 P_BAND = 43 R_BAND = 47 def primes_upto(n): s = [True] * (n + 1) s[0:2] = [False, False] for i in range(2, int(n ** 0.5) + 1): if s[i]: s[i * i:: i] = [False] * len(s[i * i:: i]) return [i for i, v in enumerate(s) if v] def owners(p): """Owners at band p: the primes q with p < q <= 2p. At p=43 this makes 89 the sole entering owner of the 43->47 fold, as return #567 states.""" return [q for q in primes_upto(2 * p) if p < q <= 2 * p] def build_support(start, n, p): """Admissible twin starts: x = 5 (mod 6) and x != 0, -2 (mod q) for 5<=q<=p.""" qs = [q for q in primes_upto(p) if q >= 5] out, x = [], start + ((5 - start) % 6) while len(out) < n: if all(x % q != 0 and x % q != (q - 2) % q for q in qs): out.append(x) x += 6 return out def killset_indices(slots, t, c): """K_t(c) = {x : x = c or c-2 (mod t)} intersected with the support.""" return [i for i, x in enumerate(slots) if x % t == c % t or x % t == (c - 2) % t] # ------------------------------------------------- exact two-phase simplex class Infeasible(Exception): pass def simplex(A, b, c): """max c.x s.t. A x = b, x >= 0, b >= 0. Exact Fractions, Bland's rule. Returns (value, x). Raises Infeasible. Assumes bounded (ours is).""" m, n = len(A), len(A[0]) # phase 1: artificials T = [row[:] + [F(1) if i == j else F(0) for j in range(m)] + [b[i]] for i, row in enumerate(A)] basis = list(range(n, n + m)) cost = [F(0)] * n + [F(-1)] * m def run(cost, ncols): while True: # reduced costs: z_j - c_j via current basis y = [cost[basis[i]] for i in range(m)] enter = -1 for j in range(ncols): if j in basis: continue red = cost[j] - sum(y[i] * T[i][j] for i in range(m)) if red > 0: enter = j # Bland: first improving index break if enter < 0: return ratio, leave = None, -1 for i in range(m): if T[i][enter] > 0: r = T[i][-1] / T[i][enter] if ratio is None or r < ratio or (r == ratio and basis[i] < basis[leave]): ratio, leave = r, i if leave < 0: raise RuntimeError("unbounded") piv = T[leave][enter] T[leave] = [v / piv for v in T[leave]] for i in range(m): if i != leave and T[i][enter] != 0: f = T[i][enter] T[i] = [T[i][k] - f * T[leave][k] for k in range(len(T[i]))] basis[leave] = enter run(cost, n + m) if sum(T[i][-1] for i in range(m) if basis[i] >= n) != 0: raise Infeasible() # drive any artificial out of the basis for i in range(m): if basis[i] >= n: for j in range(n): if j not in basis and T[i][j] != 0: piv = T[i][j] T[i] = [v / piv for v in T[i]] for k in range(m): if k != i and T[k][j] != 0: f = T[k][j] T[k] = [T[k][l] - f * T[i][l] for l in range(len(T[k]))] basis[i] = j break for i in range(m): T[i] = T[i][:n] + [T[i][-1]] run(c + [F(0)] * 0, n) x = [F(0)] * n for i in range(m): if basis[i] < n: x[basis[i]] = T[i][-1] return sum(c[j] * x[j] for j in range(n)), x # ------------------------------------------------------------------- model def capacities(slots, w, qs, restrict=None): """C_q and the attaining phase, on the (optionally reduced) support.""" live = set(range(len(slots))) if restrict is None else set(restrict) out = {} for q in qs: best, arg = F(0), None for cph in range(q): v = sum(w[i] for i in killset_indices(slots, q, cph) if i in live) if arg is None or v > best: best, arg = v, cph out[q] = (best, arg) return out def main(): t0 = time.time() rep = {} slots = build_support(WINDOW_START, N_SLOTS, P_BAND) L = slots[-1] - slots[0] + 1 Q43, Q47 = owners(P_BAND), owners(R_BAND) entering = [q for q in Q47 if q not in Q43] leaving = [q for q in Q43 if q not in Q47] rep["instance"] = {"window_start": WINDOW_START, "N": N_SLOTS, "slots": slots, "L": L, "Q_43": Q43, "Q_47": Q47, "entering": entering, "leaving": leaving} # ---- gate (d): distance law, before any optimisation gate = {} for t in (47, 89): law_d, obs_d, ok = [], [], True for d in range(6, L, 6): law = (d % t in (0, 2, t - 2)) if law: law_d.append(d) # observed: distances actually co-killable by some phase of t for cph in range(t): ks = killset_indices(slots, t, cph) for a in range(len(ks)): for bb in range(a + 1, len(ks)): obs_d.append(slots[ks[bb]] - slots[ks[a]]) obs_d = sorted(set(obs_d)) ok = all(d % 6 == 0 and d % t in (0, 2, t - 2) for d in obs_d) occ = max(len(killset_indices(slots, t, cph)) for cph in range(t)) bound = 2 * ((L - 1) // (6 * t) + 1) gate[t] = {"law_distances_below_L": law_d, "observed_cokill_distances": obs_d, "every_observed_obeys_law": ok, "max_occupancy": occ, "route_bound_2*(floor((L-1)/(6t))+1)": bound, "occupancy_within_bound": occ <= bound} rep["gate_distance_law"] = gate if not all(g["every_observed_obeys_law"] and g["occupancy_within_bound"] for g in gate.values()): rep["gate"] = "FAILED" print(json.dumps(rep, indent=1, default=str)) return 1 rep["gate"] = "passed" # ---- uniform baseline (the published-style diagnostic, for comparison) wu = [F(1)] * N_SLOTS cu = capacities(slots, wu, Q43) rep["uniform_baseline"] = { "W": N_SLOTS, "C_q": {str(q): str(cu[q][0]) for q in Q43}, "sum_C": str(sum(cu[q][0] for q in Q43)), "delta": str(F(N_SLOTS) - sum(cu[q][0] for q in Q43))} # ---- LP1 (c): maximise delta = sum w - sum_{Q43} C_q, sum w = 1 nq = len(Q43) nvar = N_SLOTS + nq # w_0..w_19, C_q rows, rhs, rowinfo = [], [], [] for qi, q in enumerate(Q43): seen = set() for cph in range(q): ks = tuple(killset_indices(slots, q, cph)) if not ks or ks in seen: continue seen.add(ks) r = [F(0)] * nvar for i in ks: r[i] = F(1) r[N_SLOTS + qi] = F(-1) rows.append(r); rhs.append(F(0)); rowinfo.append((q, cph)) npair = len(rows) # slacks for the pair rows, then the normalisation row total = nvar + npair A = [] for k, r in enumerate(rows): A.append(r + [F(1) if j == k else F(0) for j in range(npair)]) norm = [F(1)] * N_SLOTS + [F(0)] * nq + [F(0)] * npair A.append(norm); rhs.append(F(1)) obj = [F(1)] * N_SLOTS + [F(-1)] * nq + [F(0)] * npair val, x = simplex(A, rhs, obj) w = [x[i] for i in range(N_SLOTS)] rep["LP1"] = {"pair_rows": npair, "variables": nvar, "delta_star_exact": str(val), "delta_star_float": float(val), "w_exact": [str(v) for v in w], "note": "normalised to sum_i w_i = 1; delta is scale-invariant in sign"} cq = capacities(slots, w, Q43) rep["LP1"]["C_q_at_optimum"] = {str(q): str(cq[q][0]) for q in Q43} rep["LP1"]["sum_C"] = str(sum(cq[q][0] for q in Q43)) delta = F(1) - sum(cq[q][0] for q in Q43) rep["LP1"]["delta_recomputed"] = str(delta) if delta <= 0: rep["verdict"] = ("no weight vector holds the old band on this prescribed case: " "max delta = %s <= 0" % val) rep["seconds"] = round(time.time() - t0, 2) print(json.dumps(rep, indent=1, default=str)) return 0 # ---- the fold: all 47 deletion phases, exact prof = [] for cph in range(R_BAND): E = killset_indices(slots, R_BAND, cph) wE = sum(w[i] for i in E) live = [i for i in range(N_SLOTS) if i not in E] cprime = capacities(slots, w, Q47, restrict=live) margin = (F(1) - wE) - sum(cprime[q][0] for q in Q47) # identity check against #567 ident = (delta + cq[R_BAND][0] - wE + sum(cq[q][0] - cprime[q][0] for q in Q43 if q != R_BAND) - cprime[89][0]) prof.append({"phase": cph, "deleted_slots": len(E), "w_E": str(wE), "C_prime_89_entering_cost": str(cprime[89][0]), "margin": str(margin), "margin_float": float(margin), "identity_holds": ident == margin}) rep["fold_profile"] = prof margins = [F(p["margin"]) for p in prof] pos = [p for p in prof if F(p["margin"]) > 0] rep["fold_summary"] = { "phases": R_BAND, "identity_holds_at_every_phase": all(p["identity_holds"] for p in prof), "min_margin": str(min(margins)), "max_margin": str(max(margins)), "phases_with_positive_margin": len(pos), "best_phase": max(prof, key=lambda p: F(p["margin"]))["phase"], "entering_cost_C89_min": str(min(F(p["C_prime_89_entering_cost"]) for p in prof)), "entering_cost_C89_max": str(max(F(p["C_prime_89_entering_cost"]) for p in prof)), "C_47_returned_credit": str(cq[R_BAND][0]), } rep["verdict"] = ("delta* = %s > 0 and %d/%d phases keep a positive one-step margin" % (val, len(pos), R_BAND)) rep["seconds"] = round(time.time() - t0, 2) print(json.dumps(rep, indent=1, default=str)) return 0 if __name__ == "__main__": sys.exit(main())