#!/usr/bin/env python3 """Job #1111 (route 8 rescue): dry run of the exact-reconstruction instrument. The route's missing object is an exactly verified Farkas witness for the frozen split-D51 system. Return #463 correctly refuses to infer it from rounding a floating-point solver optimum, and return #462 reports that uniform scaling cannot produce it. This script tests the *alternative* instrument on a small integer instance built to carry the same three features the real object has: * it is infeasible only through the equalities and conditioned rows (same shape as {w >= 0 : E w = f, A w >= 0}); * its Farkas witness has non-unit denominators, so it is not recoverable by unit rounding and uniform scaling succeeds only at the exact denominator, which is not known a priori; * it contains columns whose combined coefficient is *exactly* zero (the analogue of the 1680 exactly-tight columns recorded for the shared-singleton certificate). Instrument under test, identical in form to the prescribed split-D51 step: auxiliary LP (Gleixner/Steffy/Wolter eq. 3) -> HiGHS basis at the optimum -> freeze the nonbasic structural columns at their bounds -> solve the active rows exactly over the rationals -> re-check the witness with the project's own integer verifier. stdout is the artifact (deterministic, no timings). Progress and timings go to stderr. """ import json import os import sys import time from fractions import Fraction from pathlib import Path for _k in ('OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS'): os.environ.setdefault(_k, '1') import numpy as np # noqa: E402 from scipy.sparse import csc_matrix, csr_matrix # noqa: E402 import highspy # noqa: E402 HERE = Path(__file__).parent sys.path.insert(0, str(HERE.parent / 'job1088')) from split1090 import columns_of, verify # noqa: E402 BIG = 1e30 try: sys.stdout.reconfigure(newline='\n') # portable LF stdout sys.stderr.reconfigure(newline='\n') except Exception: pass T0 = time.process_time() def log(**kw): print(json.dumps(kw, sort_keys=True), file=sys.stderr, flush=True) def core_instance(m, copies): """`copies` independent copies of a 2-variable infeasible core, plus 2 forced-zero columns. Core i uses w[4i+0..3]: equalities w[4i]+w[4i+1] = 1 and w[4i+2]+w[4i+3] = 0, conditioned rows w[4i] - m*w[4i+1] >= 0 and -m*w[4i] + w[4i+1] >= 0. Any solution has w[4i] = w[4i+1] = 0, contradicting the first equality, so the system is infeasible; a Farkas witness is y = (1/(m+1), 1/(m+1)) on each core, z = (m-1)/(m+1) on the first equality of that core, with every column combined coefficient exactly 0. """ n = 4 * copies + 2 er, ec, ev, rhs = [], [], [], [] ar, ac, av = [], [], [] labels = [] def eq_row(entries, value): r = len(rhs) for c, v in entries: er.append(r); ec.append(c); ev.append(v) labels.append(['normalization', r]) rhs.append(value) for i in range(copies): b = 4 * i eq_row([(b, 1), (b + 1, 1)], 1) # w_b + w_b1 = 1 eq_row([(b + 2, 1), (b + 3, 1)], 0) # w_b2 + w_b3 = 0 ar += [2 * i, 2 * i, 2 * i + 1, 2 * i + 1] ac += [b, b + 1, b, b + 1] av += [1.0, -float(m), -float(m), 1.0] z0, z1 = n - 2, n - 1 # two columns forced to zero by an equality row eq_row([(z0, 1), (z1, 1)], 0) A = csr_matrix((np.array(av), (np.array(ar), np.array(ac))), shape=(2 * copies, n)) E = csr_matrix((np.array(ev), (np.array(er), np.array(ec))), shape=(len(rhs), n)) return A, E, np.array(rhs, dtype=float), labels def aux_lp(A, E, f, time_limit=300.0): """GSW eq. (3): maximise f^T z s.t. A^T y + E^T z <= 0, f^T z <= 1, y >= 0, z free.""" mY, mZ, n = A.shape[0], E.shape[0], A.shape[1] cost = np.zeros(mY + mZ) cost[mY:] = f lb = np.concatenate([np.zeros(mY), np.full(mZ, -BIG)]) ub = np.full(mY + mZ, BIG) M = np.zeros((n + 1, mY + mZ)) M[:n, :mY] = A.T.toarray() M[:n, mY:] = E.T.toarray() M[n, mY:] = f lpc = csc_matrix(M) # column-wise arrays: M must be CSC, not CSR rl = np.concatenate([np.full(n, -BIG), np.array([-BIG])]) ru = np.concatenate([np.zeros(n), np.array([1.0])]) h = highspy.Highs() h.setOptionValue('output_flag', False) h.setOptionValue('threads', 1) h.setOptionValue('time_limit', time_limit) lp = highspy.HighsLp() lp.num_col_ = int(mY + mZ) lp.num_row_ = int(n + 1) lp.col_cost_ = cost lp.col_lower_ = lb lp.col_upper_ = ub lp.row_lower_ = rl lp.row_upper_ = ru lp.sense_ = highspy.ObjSense.kMaximize lp.a_matrix_.format_ = highspy.MatrixFormat.kColwise lp.a_matrix_.start_ = lpc.indptr.astype(np.int32) lp.a_matrix_.index_ = lpc.indices.astype(np.int32) lp.a_matrix_.value_ = lpc.data assert h.passModel(lp) == highspy.HighsStatus.kOk h.run() return h, M def exact_reconstruct(M, col_st, row_st, mY, mZ, basic=None, active=None): """Solve the active rows exactly for the basic structural columns. Nonbasic structural columns are frozen at their bound value (0); every active row (slack at its upper bound, i.e. the inequality is tight) is imposed as an equality with right-hand side equal to that bound. `basic`/`active` default to the basis in `col_st`/`row_st`; passing explicit sets is the control that shows the basis, and not a support guess, is the load-bearing input.""" n_rows, n_cols = M.shape norm_row = n_rows - 1 basic = [j for j, s in enumerate(col_st) if s == 1] if basic is None else list(basic) active = [r for r, s in enumerate(row_st) if s == 2] if active is None else list(active) if len(active) != len(basic): return None, {'error': 'active rows %d != basic columns %d' % (len(active), len(basic))} k = len(basic) mat = [[Fraction(int(round(M[r, c]))) for c in basic] for r in active] rhs = [Fraction(1) if r == norm_row else Fraction(0) for r in active] # Gauss-Jordan over the rationals for i in range(k): piv = next((r for r in range(i, k) if mat[r][i] != 0), None) if piv is None: return None, {'error': 'singular reduced system at column %d' % i} if piv != i: mat[i], mat[piv] = mat[piv], mat[i] rhs[i], rhs[piv] = rhs[piv], rhs[i] inv = Fraction(1) / mat[i][i] mat[i] = [v * inv for v in mat[i]] rhs[i] *= inv for r in range(k): if r == i or mat[r][i] == 0: continue fac = mat[r][i] mat[r] = [a - fac * b for a, b in zip(mat[r], mat[i])] rhs[r] -= fac * rhs[i] return dict(zip(basic, rhs)), {'active_rows': len(active), 'order': k} def main(): m, copies = 99, 2 A, E, f, labels = core_instance(m, copies) n, mY, mZ = A.shape[1], A.shape[0], E.shape[0] log(stage='instance', columns=n, conditioned_rows=mY, equalities=mZ, m=m, copies=copies) h, M = aux_lp(A, E, f) status = str(h.getModelStatus()) obj = h.getObjectiveValue() sol = h.getSolution() yf = np.asarray(sol.col_value[:mY], dtype=float) zf = np.asarray(sol.col_value[mY:], dtype=float) basis = h.getBasis() col_st = [int(s) for s in basis.col_status] row_st = [int(s) for s in basis.row_status] log(stage='solved', status=status, objective=obj, basis_valid=bool(basis.valid)) exact, info = exact_reconstruct(M, col_st, row_st, mY, mZ) art = { 'job': 1111, 'route_id': 8, 'kind': 'exact_reconstruction_instrument_dry_run', 'instance': { 'description': ('%d independent copies of the 2-variable infeasible core with ' 'm=%d, plus 2 columns forced to zero by an equality row; every ' 'column combined coefficient of the witness is exactly 0' % (copies, m)), 'columns': int(n), 'conditioned_rows': int(mY), 'equalities': int(mZ), 'forced_zero_columns': 2, }, 'auxiliary_lp': { 'status': status, 'objective': float(obj), 'note': 'optimum is 0 exactly when the frozen system is feasible, 1 when it is not', 'float_witness_max_combined_coefficient': float( np.max(np.asarray(A.T.dot(yf) + E.T.dot(zf), dtype=float))), 'basis_valid': bool(basis.valid), }, } if exact is None: art['reconstruction'] = dict(info, outcome='failed') print(json.dumps(art, sort_keys=True, indent=2)) return 1 y = [Fraction(0)] * mY z = [Fraction(0)] * mZ for j, v in exact.items(): (y if j < mY else z)[j if j < mY else j - mY] = v yi = [int(v) for v in y] # y must be >= 0 with integer-ish values den = 1 for v in list(y) + list(z): den = den * v.denominator // np.gcd(den, v.denominator) if den else v.denominator yi = [int(v * den) for v in y] zi = [int(v * den) for v in z] chk = verify(A, E, f, labels, yi, zi) art['reconstruction'] = dict( info, outcome='exact_rational_solution_found', denominators_lcm=int(den), all_values_integral_before_scaling=all(v.denominator == 1 for v in list(y) + list(z)), nonzero_y=sum(1 for v in y if v), nonzero_z=sum(1 for v in z if v), exact_witness_verification=chk, integral_witness={'denominator': int(den), 'y': yi, 'z': zi}, ) scaling = {} for T in (1, 10, 100, 200, 1000): ys = [int(round(v * T)) for v in yf] zs = [int(round(v * T)) for v in zf] c = verify(A, E, f, labels, ys, zs) scaling['T=%d' % T] = {'max_combined_coefficient': c['max_combined_coefficient'], 'normalization_multiplier_sum': c['normalization_multiplier_sum'], 'verifies': c['ok']} art['uniform_scaling_control'] = scaling # #463's warning, as a control: a nonzero support is not a basis. Reconstructing from # (a) every row treated as active and (b) the float solution's nonzero support instead # of the basis must fail, or the basis statuses would be redundant input. all_rows = list(range(M.shape[0])) support_basic = [j for j in range(mY + mZ) if (yf[j] if j < mY else zf[j - mY]) != 0.0] without_basis = {} _ex, _info = exact_reconstruct(M, col_st, row_st, mY, mZ, active=all_rows) without_basis['all_rows_active'] = _info.get('error') or 'unexpectedly_solved' _ex, _info = exact_reconstruct(M, col_st, row_st, mY, mZ, basic=support_basic) without_basis['float_support_as_basis'] = _info.get('error') or 'unexpectedly_solved' without_basis['float_support_size'] = len(support_basic) without_basis['basic_columns'] = sum(1 for s in col_st if s == 1) art['without_basis_control'] = without_basis corrupt = list(zi) j = next(i for i, v in enumerate(zi) if v) corrupt[j] += 1 art['corruption_control'] = verify(A, E, f, labels, yi, corrupt) # a witness with one sign flipped must also fail flip = list(yi) k = next(i for i, v in enumerate(flip) if v) flip[k] = -flip[k] art['sign_flip_control'] = verify(A, E, f, labels, flip, zi) print(json.dumps(art, sort_keys=True, indent=2)) log(stage='done', cpu_seconds=round(time.process_time() - T0, 3)) return 0 if __name__ == '__main__': raise SystemExit(main())