#!/usr/bin/env python3 """Job #1090 (route 8 rev8): split ONLY the 17 ordinary singleton vectors into independently normalized per-star copies; keep the two anchor singletons common; keep the 36 owned joint blocks. Reuses #451's (job #1086) complete phase maps and literal D51 - no old numerical work is rerun and no map is regenerated. The model is #1086's with exactly one change: for each ordinary prime q (i.e. q in Q, q not in {101,103}) and each anchor h in {101,103}, the singleton vector lambda_q becomes its own variable lambda_q^(h), with its OWN normalization row (sum_a lambda_q^(h)(a) = 1), used by the marginal rows of the blocks owned by h. Blocks, conditioned rows, anchors and their common singletons are unchanged. Because the old system's coupling lambda_q^(101) = lambda_q^(103) is dropped and 17 extra normalization rows and columns are added, the new system is a strict RELAXATION of #1086's: feasible_new superset feasible_old. Two exact routes to the verdict are computed and both are checked in integers: (a) TRANSPORTED #1086 CERTIFICATE. #1086's integer Farkas (y, z) has, for every ordinary q, z_norm(q) - A_q - B_q <= 0, where A_q/B_q are the sums of z over the two stars' marginal rows that reference lambda_q. Splitting z_norm(q) into the two copies' normalization multipliers (z_norm(q,101) = min(z_norm(q), A_q), z_norm(q,103) = z_norm(q) - z_norm(q,101)) gives a vector with zero combined coefficient on EVERY column of the new system and the same positive RHS 288. So infeasibility persists with independent ordinary distributions. (b) IPM CERTIFICATE. One bounded HiGHS interior-point phase-I search on the new model, then the usual exact integer repair of its duals, kept only if it verifies. Everything the verdict rests on is re-checked with Python integers: E'w = f' style combined coefficients <= 0 on all columns and a strictly positive multiplier sum on the normalization RHS. stdout is the artifact (deterministic, no timing); progress and timings go to stderr. """ import argparse import array import hashlib import itertools import json import os import sys import time import warnings from pathlib import Path for key in ('OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS', 'VECLIB_MAXIMUM_THREADS', 'NUMEXPR_NUM_THREADS'): os.environ.setdefault(key, '1') import numpy as np # noqa: E402 from scipy.optimize import linprog, OptimizeWarning # noqa: E402 from scipy.sparse import coo_matrix, csr_matrix, hstack # noqa: E402 HERE = Path(__file__).parent IN = HERE / 'in451' MAPS = 'ef8a0916df05899f858e69bb67fa0f292b41416614ef87ad2ee9a869dbd424a1' # maps1086.json GLOBAL = '28007cef45a1a1fc5642b207ca4c19c3325808add1a05684626e851091a40836' # global1086.json LAYOUT = 'b71ca9427970a1187f2178e5a58669a856bbca95c45a1d7cb1da719f27a731ab' # layout1086.json T0 = time.process_time() def load(name, sha): raw = (IN / name).read_bytes() assert hashlib.sha256(raw).hexdigest() == sha, name return raw, json.loads(raw) def build(mapping): """The split model. Returns A, E, f, offsets, labels.""" D = mapping['slots'] Q = mapping['Q'] H = mapping['anchors'] ordq = [q for q in Q if q not in H] maps = mapping['phase_maps'] size = {q: len(maps[str(q)]['representatives']) for q in Q} kind = mapping['kind'] if 'kind' in mapping else None sng = {} # anchor singleton: (h, None) for h in H: sng[(h, None)] = None for q in ordq: for h in H: sng[(q, h)] = None cursor = 0 for key in sorted(sng, key=lambda k: (k[0], -1 if k[1] is None else k[1])): sng[key] = cursor cursor += size[key[0]] blocks = {} for p, q, owner in mapping['pairs']: blocks[p, q, owner] = (cursor, size[p], size[q]) cursor += size[p] * size[q] def svar(q, owner): """The singleton variable for prime q as seen by the star owned by `owner`.""" return sng[(q, None)] if q in H else sng[(q, owner)] def paircol(p, a, q, b, owner): lo, hi = sorted((p, q)) offset, nlo, nhi = blocks[lo, hi, owner] return offset + a * nhi + b if p == lo else offset + b * nhi + a er, ec, ev = array.array('i'), array.array('i'), array.array('d') eq_labels, rhs = [], [] def eq(entries, label, value=0): row = len(rhs) for col, v in entries: er.append(row) ec.append(col) ev.append(v) eq_labels.append(label) rhs.append(value) for h in H: # common anchor singletons eq([(sng[(h, None)] + a, 1) for a in range(size[h])], ['normalization', h], 1) for q in ordq: # independently normalized copies for h in H: eq([(sng[(q, h)] + a, 1) for a in range(size[q])], ['normalization_copy', q, h], 1) for p, q, owner in mapping['pairs']: sp, sq = svar(p, owner), svar(q, owner) for a in range(size[p]): eq([(paircol(p, a, q, b, owner), 1) for b in range(size[q])] + [(sp + 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])] + [(sq + b, -1)], ['marginal', p, q, owner, q, b]) ar, ac, av = array.array('i'), array.array('i'), array.array('d') cov_labels = [] 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} for h in H: # conditioned rows, unchanged from #1086 for a, hit in enumerate(maps[str(h)]['kill_indices']): for i in range(len(D)): if i in hit: continue row = len(cov_labels) cov_labels.append([h, a, i]) ar.append(row) ac.append(sng[(h, None)] + a) av.append(-1) for q in Q: if q != h: for b in killing[q][i]: ar.append(row) ac.append(paircol(h, a, q, b, h)) av.append(1) E = coo_matrix((np.frombuffer(ev, dtype='d'), (np.frombuffer(er, dtype='i'), np.frombuffer(ec, dtype='i'))), shape=(len(rhs), cursor)).tocsr() A = coo_matrix((np.frombuffer(av, dtype='d'), (np.frombuffer(ar, dtype='i'), np.frombuffer(ac, dtype='i'))), shape=(len(cov_labels), cursor)).tocsr() return A, E, np.array(rhs), sng, blocks, eq_labels, cov_labels, size, ordq, H, Q, kind def columns_of(A, E, y, z): """Exact combined coefficient of every column: y^T A[:,j] + z^T E[:,j] (Python integers).""" n = A.shape[1] coef = [0] * n Ac, Ec = A.tocsc(), E.tocsc() for j in range(n): s = 0 for k in range(Ec.indptr[j], Ec.indptr[j + 1]): r = int(Ec.indices[k]) zi = z[r] if zi: s += zi * int(Ec.data[k]) for k in range(Ac.indptr[j], Ac.indptr[j + 1]): r = int(Ac.indices[k]) yi = y[r] if yi: s += yi * int(Ac.data[k]) coef[j] = s return coef def verify(A, E, f, labels, y, z): coef = columns_of(A, E, y, z) norm_idx = [i for i, L in enumerate(labels) if L[0] in ('normalization', 'normalization_copy')] rhs_sum = sum(z[i] for i in norm_idx) return {'max_combined_coefficient': max(coef), 'negative_columns': sum(1 for c in coef if c < 0), 'zero_columns': sum(1 for c in coef if c == 0), 'columns': len(coef), 'normalization_multiplier_sum': rhs_sum, 'exact_rhs_positive': rhs_sum > 0, 'ok': max(coef) <= 0 and rhs_sum > 0} def transport(old_y, old_z, old_labels, eq_labels, size, ordq, H): """Split #1086's certificate: same y, same z on marginal rows, ordinary normalization split.""" z = [0] * len(eq_labels) old_norm = {} old_marg = {} for i, L in enumerate(old_labels): if L[0] == 'normalization': old_norm[L[1]] = old_z[i] elif L[0] == 'marginal': old_marg[tuple(L)] = old_z[i] marg_sum = {} for L, v in old_marg.items(): _, p, q, owner, endpoint, a = L if endpoint in ordq: marg_sum[(endpoint, owner)] = marg_sum.get((endpoint, owner), 0) + v split = {} for i, L in enumerate(eq_labels): if L[0] == 'normalization': z[i] = old_norm[L[1]] elif L[0] == 'marginal': z[i] = old_marg[tuple(L)] else: # ('normalization_copy', q, h) q, h = L[1], L[2] if q not in split: zn, firstH = old_norm[q], min(H) A_q = marg_sum.get((q, firstH), 0) split[q] = {firstH: min(zn, A_q)} split[q][H[1] if len(H) > 1 else None] = zn - split[q][firstH] z[i] = split[q][h] return old_y, z, {str(k): v for k, v in split.items()}, marg_sum def repair(y, z, mapping, labels, cov_labels, size, ordq, H, sng): """Exact integer repair of IPM duals, generalised to the split ordinary singletons. Row addressing is by LABEL, not by position: row_of[(p,q,owner,endpoint,a)] is the marginal row and norm_row[(q, owner)] the normalization row (owner None for the common anchor vectors). """ y = np.array(y, dtype=np.int64).copy() z = np.array(z, dtype=np.int64).copy() assert int(y.min()) >= 0 D = mapping['slots'] Q = mapping['Q'] maps = mapping['phase_maps'] kill = {q: np.array([[int(i in hit) for i in range(len(D))] for hit in maps[str(q)]['kill_indices']], dtype=np.int64) for q in Q} row_of = {} norm_row = {} for i, L in enumerate(labels): if L[0] == 'marginal': row_of[(L[1], L[2], L[3], L[4], L[5])] = i elif L[0] == 'normalization': norm_row[(L[1], None)] = i else: norm_row[(L[1], L[2])] = i Y = {h: np.zeros((size[h], len(D)), dtype=np.int64) for h in H} for weight, (h, a, i) in zip(y, cov_labels): Y[h][a, i] = weight repairs = [] for p, q, owner in mapping['pairs']: coeff = np.zeros((size[p], size[q]), dtype=np.int64) for a in range(size[p]): for b in range(size[q]): coeff[a, b] = z[row_of[(p, q, owner, p, a)]] + z[row_of[(p, q, owner, q, b)]] extra = Y[p][:, :] @ kill[q].T if owner == p else kill[p] @ Y[q][:, :] total = coeff + extra delta = int(max(0, int(total.max()))) if delta: for i, L in enumerate(labels): if L[0] == 'marginal' and L[1] == p and L[2] == q and L[3] == owner: z[i] -= delta repairs.append([p, q, owner, delta]) lrep = [] for q in Q: owners = [None] if q in H else list(H) for owner in owners: idx = norm_row[(q, owner)] coeff = np.full(size[q], z[idx], dtype=np.int64) for p, r, ow in mapping['pairs']: if q not in (p, r): continue if (q in H and ow is None) or (ow != owner and q not in H): continue for a in range(size[q]): coeff[a] -= z[row_of[(p, r, ow, q, a)]] if q in H and owner is None: coeff -= Y[q].sum(axis=1) delta = int(max(0, int(coeff.max()))) z[idx] -= delta lrep.append([q, owner, delta]) return y, z, repairs, lrep def main(): ap = argparse.ArgumentParser() ap.add_argument('--preflight', action='store_true') ap.add_argument('--method', choices=['highs-ds', 'highs-ipm'], default='highs-ipm') ap.add_argument('--solve-seconds', type=float, default=30.0) args = ap.parse_args() maps_raw, mapping = load('maps1086.json', MAPS) glob_raw, glob = load('global1086.json', GLOBAL) lay_raw, layout = load('layout1086.json', LAYOUT) assert glob['certificate']['kind'] == 'integer_farkas' A, E, f, sng, blocks, eq_labels, cov_labels, size, ordq, H, Q, kind = build(mapping) new_layout = { 'job': 1090, 'route_id': 8, 'revision': 8, 'kind': 'split_ordinary_singletons_common_anchors_layout', 'source_maps_sha256': MAPS, 'source_certificate_sha256': GLOBAL, 'anchors': list(H), 'ordinary_primes': list(ordq), 'N': len(mapping['slots']), 'slots_first': mapping['slots'][:3], 'slots_last': mapping['slots'][-1], 'Q': list(Q), 'pairs': len(mapping['pairs']), 'singleton_offsets': [[q, h, off] for (q, h), off in sorted( sng.items(), key=lambda kv: kv[1])], 'blocks': [[p, q, owner, *v] for (p, q, owner), v in blocks.items()], 'equality_labels': eq_labels, 'conditioned_labels': cov_labels, 'variables': int(A.shape[1]), 'equalities': int(E.shape[0]), 'conditioned_rows': int(A.shape[0]), 'A_nnz': int(A.nnz), 'E_nnz': int(E.nnz), 'phase_class_sizes': [[q, size[q]] for q in Q], 'anchor_singletons_common': True, 'ordinary_singletons_split': True, 'anchor_pair_joint_shared': False, } print(json.dumps({'stage': 'preflight', 'variables': int(A.shape[1]), 'equalities': int(E.shape[0]), 'conditioned_rows': int(A.shape[0]), 'nnz': int(A.nnz + E.nnz), 'ordinary_singletons_split': len(ordq), 'cpu_seconds': time.process_time() - T0}), file=sys.stderr, flush=True) if args.preflight: (HERE / 'preflight1090.json').write_text(json.dumps(new_layout, sort_keys=True), encoding='utf-8') return 0 ub = hstack([-A, csr_matrix(-np.ones((A.shape[0], 1)))], format='csr') eqm = hstack([E, csr_matrix((E.shape[0], 1))], format='csr') c = np.zeros(A.shape[1] + 1) c[-1] = 1 with warnings.catch_warnings(): warnings.filterwarnings('ignore', category=OptimizeWarning) lp = linprog(c, A_ub=ub, b_ub=np.zeros(A.shape[0]), A_eq=eqm, b_eq=f, bounds=(0, None), method=args.method, options={'threads': 1, 'time_limit': max(10.0, args.solve_seconds), 'primal_feasibility_tolerance': 1e-9, 'dual_feasibility_tolerance': 1e-9}) solve_cpu = time.process_time() - T0 print(json.dumps({'stage': 'solver', 'status': int(lp.status), 'success': bool(lp.success), 'elastic_slack': None if lp.x is None else float(lp.x[-1]), 'cpu_seconds': solve_cpu}), file=sys.stderr, flush=True) cd = glob['certificate'] old_y = cd['inequality_multipliers'] old_z = cd['equality_multipliers'] assert len(old_y) == len(layout['conditioned_labels']) assert len(old_z) == len(layout['equality_labels']) y_t, z_t, split, marg_sum = transport(old_y, old_z, layout['equality_labels'], eq_labels, size, ordq, H) ver_t = verify(A, E, f, eq_labels, y_t, z_t) cert = {'kind': 'integer_farkas_transported', 'scale': cd['scale'], 'anchors': list(H), 'ordinary_singletons_split': list(ordq), 'ordinary_split_vector': [[q, h, v] for q, h, v in sorted(((int(q), int(h), int(v)) for q, d in split.items() for h, v in d.items()))], 'inequality_multipliers': [int(v) for v in y_t], 'equality_multipliers': [int(v) for v in z_t], 'positive_rhs': int(ver_t['normalization_multiplier_sum']), 'verification': ver_t, 'per_ordinary_slack': [[q, int(marg_sum.get((q, min(H)), 0)), int(marg_sum.get((q, max(H)), 0))] for q in ordq]} verdict = 'infeasible_split_ordinary_singletons' if ver_t['ok'] else 'inconclusive' second = None if lp.success and lp.x[-1] < 1e-8: verdict = 'feasible_split_ordinary_singletons' elif lp.success: for T in (1000000, 1000000000): y0 = np.rint(np.maximum(-lp.ineqlin.marginals, 0) * T).astype(np.int64) z0 = np.rint(lp.eqlin.marginals * T).astype(np.int64) if max(int(np.max(np.abs(y0))), int(np.max(np.abs(z0)))) >= 10 ** 15: continue y2, z2, rep, lrep = repair(y0, z0, mapping, eq_labels, cov_labels, size, ordq, H, sng) v2 = verify(A, E, f, eq_labels, [int(v) for v in y2], [int(v) for v in z2]) if v2['ok']: second = {'kind': 'integer_farkas_from_ipm', 'scale': T, 'inequality_multipliers': [int(v) for v in y2], 'equality_multipliers': [int(v) for v in z2], 'positive_rhs': int(v2['normalization_multiplier_sum']), 'verification': v2, 'pair_repairs': rep, 'singleton_repairs': lrep} break art = { 'job': 1090, 'route_id': 8, 'revision': 8, 'kind': 'split_ordinary_singletons_common_anchors_evidence', 'source_maps_sha256': MAPS, 'source_certificate_sha256': GLOBAL, 'source_layout_sha256': LAYOUT, 'definition': ('ordinary singleton vectors lambda_q (q in Q \\ {101,103}) are split into' ' independent per-star copies with their own normalization rows; the anchors' ' 101/103 keep one common singleton vector each; the 36 owned joint blocks,' ' their marginal equations and all conditioned rows are #1086\'s'), 'new_variables': int(A.shape[1]), 'new_equalities': int(E.shape[0]), 'new_conditioned_rows': int(A.shape[0]), 'old_variables': layout['variables'], 'old_equalities': layout['equalities'], 'old_conditioned_rows': layout['conditioned_rows'], 'solver': {'method': args.method, 'status': int(lp.status), 'success': bool(lp.success), 'elastic_slack': None if lp.x is None else float(lp.x[-1])}, 'environment': {'python': sys.version.split()[0], 'numpy': np.__version__, 'scipy': __import__('scipy').__version__, 'platform': sys.platform, 'note': 'producer runs in a project-local venv; the checker is stdlib only'}, 'verdict': verdict, 'certificate': cert, 'second_certificate': second, } text = json.dumps(art, sort_keys=True, indent=2) + '\n' (HERE / 'split1090.json').write_text(text, encoding='utf-8', newline='\n') print(text, end='') print(json.dumps({'stage': 'complete', 'cpu_seconds': time.process_time() - T0, 'checker_estimate_seconds': 0.05}), file=sys.stderr) return 0 if __name__ == '__main__': raise SystemExit(main())