#!/usr/bin/env python3 """Job #1090: exact verdict for the split-ordinary-singleton relaxation, via a HiGHS dual ray. Two models are built from #451's maps only: NEW = the prescribed relaxation: the 17 ordinary singleton vectors split into independently normalized per-star copies, anchors 101/103 common, blocks and conditioned rows unchanged; OLD = #1086's system (all 19 singleton vectors common, independent anchor-pair joints) - known infeasible from return #451, so it is the pipeline control. Each is posed as a pure feasibility LP (minimize 0) so that HiGHS's own infeasibility verdict and dual ray - not a small elastic optimum - decide the outcome. A dual ray is rationalized to integers and checked EXACTLY (int64 sparse products, then an independent Python-integer column sweep on the winner): every column combined coefficient <= 0 and normalization multiplier sum > 0. A ray that does not verify is reported as such, never as a certificate. stdout is the artifact; progress and timings go to stderr. """ import argparse import json import sys import time from pathlib import Path import numpy as np from scipy.sparse import csr_matrix, vstack HERE = Path(__file__).parent sys.path.insert(0, str(HERE)) from split1090 import build, verify, repair, load, MAPS, GLOBAL # noqa: E402 import highspy # noqa: E402 T0 = time.process_time() def old_model(mapping): """#1086's system: one common singleton vector per prime, everything else as in build().""" D = mapping['slots'] Q = mapping['Q'] H = mapping['anchors'] maps = mapping['phase_maps'] size = {q: len(maps[str(q)]['representatives']) for q in Q} single, cursor = {}, 0 for q in Q: single[q] = cursor cursor += size[q] blocks = {} for p, q, owner in mapping['pairs']: blocks[p, q, owner] = (cursor, size[p], size[q]) cursor += size[p] * size[q] rows, cols, vals, rhs, labels = [], [], [], [], [] def eq(entries, label, value=0): r = len(rhs) for c, v in entries: rows.append(r) cols.append(c) vals.append(v) labels.append(label) rhs.append(value) def paircol(p, a, q, b, owner): lo, hi = sorted((p, q)) off, nlo, nhi = blocks[lo, hi, owner] return off + a * nhi + b if p == lo else off + b * nhi + a for q in Q: eq([(single[q] + a, 1) for a in range(size[q])], ['normalization', q], 1) for p, q, owner in mapping['pairs']: for a in range(size[p]): eq([(paircol(p, a, q, b, owner), 1) for b in range(size[q])] + [(single[p] + a, -1)], ['marginal', p, q, owner, p, a]) for b in range(size[q]): eq([(paircol(q, b, p, a, owner), 1) for a in range(size[p])] + [(single[q] + b, -1)], ['marginal', p, q, owner, q, b]) killing = {q: [[a for a, hit in enumerate(maps[str(q)]['kill_indices']) if i in hit] for i in range(len(D))] for q in Q} ar, ac, av, cov = [], [], [], [] for h in H: for a, hit in enumerate(maps[str(h)]['kill_indices']): for i in range(len(D)): if i in hit: continue r = len(cov) cov.append([h, a, i]) ar.append(r) ac.append(single[h] + a) av.append(-1) for q in Q: if q != h: for b in killing[q][i]: ar.append(r) ac.append(paircol(h, a, q, b, h)) av.append(1) E = csr_matrix((np.array(vals, dtype=float), (np.array(rows), np.array(cols))), shape=(len(rhs), cursor)) A = csr_matrix((np.array(av, dtype=float), (np.array(ar), np.array(ac))), shape=(len(cov), cursor)) return A.tocsr(), E.tocsr(), np.array(rhs), single, blocks, labels, cov, size def feasibility_status(A, E, f, seconds): """min 0 s.t. -A w <= 0, E w = f, w >= 0 -> (status string, dual ray or None).""" n = A.shape[1] neg = A.copy() neg.data = -neg.data M = vstack([neg, E]).tocsr() rl = np.concatenate([np.full(A.shape[0], -np.inf), f.astype(float)]) ru = np.concatenate([np.zeros(A.shape[0]), f.astype(float)]) h = highspy.Highs() h.setOptionValue('output_flag', False) h.setOptionValue('threads', 1) h.setOptionValue('presolve', 'on') h.setOptionValue('solver', 'simplex') h.setOptionValue('simplex_strategy', 1) h.setOptionValue('time_limit', float(seconds)) lp = highspy.HighsLp() lp.num_col_ = n lp.num_row_ = int(M.shape[0]) lp.col_cost_ = np.zeros(n) lp.col_lower_ = np.zeros(n) lp.col_upper_ = np.full(n, np.inf) lp.row_lower_ = rl.astype(float) lp.row_upper_ = ru.astype(float) lp.a_matrix_.format_ = highspy.MatrixFormat.kColwise lp.a_matrix_.start_ = M.indptr.astype(np.int32) lp.a_matrix_.index_ = M.indices.astype(np.int32) lp.a_matrix_.value_ = M.data.astype(float) h.passModel(lp) h.run() st = str(h.getModelStatus()) ray = None if 'Infeasible' in st: ok, values = h.getDualRay() if ok: ray = np.array(values, dtype=float) return st, ray def combined(A, E, y, z): """Exact per-column combined coefficient y^T A + z^T E, in int64 (data are +-1).""" Ai = csr_matrix((A.data.astype(np.int64), A.indices, A.indptr), shape=A.shape) Ei = csr_matrix((E.data.astype(np.int64), E.indices, E.indptr), shape=E.shape) v = Ai.T.dot(np.asarray(y, dtype=np.int64)) + Ei.T.dot(np.asarray(z, dtype=np.int64)) return np.asarray(v, dtype=np.int64) def quick_ok(A, E, labels, y, z): coef = combined(A, E, y, z) norm = sum(int(z[i]) for i, L in enumerate(labels) if L[0] in ('normalization', 'normalization_copy')) return int(coef.max()) <= 0 and norm > 0, int(coef.max()), norm def main(): ap = argparse.ArgumentParser() ap.add_argument('--split-seconds', type=float, default=25.0) ap.add_argument('--control-seconds', type=float, default=25.0) ap.add_argument('--control', action='store_true') args = ap.parse_args() _, mapping = load('maps1086.json', MAPS) out = {'job': 1090, 'route_id': 8, 'revision': 8, 'source_maps_sha256': MAPS, 'source_certificate_sha256': GLOBAL, 'definition': ('ordinary singleton vectors split into independently normalized per-star' ' copies; anchors 101/103 keep one common vector each; the 36 owned joint' ' blocks, marginal equations and conditioned rows are #1086\'s'), 'models': {}, 'audit': [], 'certificate': None, 'control': None} # ---- the new (split) model: the deliverable A_s, E_s, f_s, sng, blk_s, lab_s, cov_s, size2, ordq, H, Q, kind = build(mapping) st_s, ray_s = feasibility_status(A_s, E_s, f_s, args.split_seconds) out['models']['new'] = {'status': st_s, 'variables': int(A_s.shape[1]), 'equalities': int(E_s.shape[0]), 'conditioned_rows': int(A_s.shape[0]), 'nnz': int(A_s.nnz + E_s.nnz), 'ordinary_singletons_split': len(ordq), 'anchors_common': list(H), 'ray_present': ray_s is not None} print(json.dumps({'stage': 'split model', **out['models']['new'], 'cpu_seconds': time.process_time() - T0}), file=sys.stderr, flush=True) if ray_s is not None: nA, nE = A_s.shape[0], E_s.shape[0] y_raw, z_raw = ray_s[:nA], ray_s[nA:nA + nE] for T in (1.0, 1e6, 1e9, 1e12): for sy in (1.0, -1.0): for sz in (1.0, -1.0): y = np.rint(sy * y_raw * T).astype(np.int64) z = np.rint(sz * z_raw * T).astype(np.int64) if int(np.max(np.abs(y))) >= 10 ** 15 or int(np.max(np.abs(z))) >= 10 ** 15: continue ok, mx, norm = quick_ok(A_s, E_s, lab_s, y, z) rec = {'scale': T, 'sign_y': sy, 'sign_z': sz, 'raw_ok': bool(ok), 'max_combined_coefficient': mx, 'normalization_multiplier_sum': norm, 'y_min': int(y.min())} out['audit'].append(rec) if ok and int(y.min()) >= 0: v = verify(A_s, E_s, f_s, lab_s, [int(t) for t in y], [int(t) for t in z]) assert v['ok'], v out['certificate'] = {'kind': 'integer_farkas_from_dual_ray', 'scale': T, 'sign_y': sy, 'sign_z': sz, 'inequality_multipliers': [int(t) for t in y], 'equality_multipliers': [int(t) for t in z], 'positive_rhs': int(v['normalization_multiplier_sum']), 'verification': v, 'source': 'HiGHS dual ray, as returned'} break if int(y.min()) >= 0: y2, z2, rep, lrep = repair(y, z, mapping, lab_s, cov_s, size2, ordq, H, sng) ok2, mx2, norm2 = quick_ok(A_s, E_s, lab_s, y2, z2) out['audit'].append({'scale': T, 'sign_y': sy, 'sign_z': sz, 'repaired_ok': bool(ok2), 'max_combined_coefficient': mx2, 'normalization_multiplier_sum': norm2}) if ok2: v = verify(A_s, E_s, f_s, lab_s, [int(t) for t in y2], [int(t) for t in z2]) assert v['ok'], v out['certificate'] = {'kind': 'integer_farkas_from_dual_ray_repaired', 'scale': T, 'inequality_multipliers': [int(t) for t in y2], 'equality_multipliers': [int(t) for t in z2], 'positive_rhs': int(v['normalization_multiplier_sum']), 'verification': v, 'pair_repairs': rep, 'singleton_repairs': lrep, 'source': 'HiGHS dual ray, structurally repaired'} break if out['certificate']: break if out['certificate']: break # ---- the old (control) model if args.control: A_o, E_o, f_o, sing_o, blk_o, lab_o, cov_o, size = old_model(mapping) st_o, ray_o = feasibility_status(A_o, E_o, f_o, args.control_seconds) out['control'] = {'status': st_o, 'variables': int(A_o.shape[1]), 'equalities': int(E_o.shape[0]), 'conditioned_rows': int(A_o.shape[0]), 'nnz': int(A_o.nnz + E_o.nnz), 'ray_present': ray_o is not None, 'expected': 'Infeasible (return #451 / job #1086)', 'agrees_with_451': 'Infeasible' in st_o} print(json.dumps({'stage': 'old model control', **out['control'], 'cpu_seconds': time.process_time() - T0}), file=sys.stderr, flush=True) p = HERE / 'split1090.out' if p.exists() and p.stat().st_size: ipm = json.loads(p.read_text(encoding='utf-8')) out['ipm_cross_check'] = {'method': ipm['solver']['method'], 'status': ipm['solver']['status'], 'elastic_min': ipm['solver']['elastic_slack'], 'note': ('elastic formulation of the same model; the elastic is the' ' largest conditioned violation, so a positive optimum' ' means infeasible')} out['verdict'] = ('infeasible_split_ordinary_singletons' if out['certificate'] else ('feasible_split_ordinary_singletons' if 'Optimal' in st_s and 'Infeasible' not in st_s else 'inconclusive')) text = json.dumps(out, sort_keys=True, indent=2) + '\n' (HERE / 'ray1090.json').write_text(text, encoding='utf-8', newline='\n') print(text, end='') print(json.dumps({'stage': 'complete', 'cpu_seconds': time.process_time() - T0}), file=sys.stderr) return 0 if __name__ == '__main__': raise SystemExit(main())