#!/usr/bin/env python3 """Job #1111 (route 8 rescue): capture a valid original-model basis for the split-D51 auxiliary LP of Gleixner/Steffy/Wolter section 4.1 equation (3), the object return #463 names as missing and ask #7 requests. Model: reuse #451's literal maps and #453's split-model builder unchanged (no map or certificate is regenerated, no published optimum is recomputed as an end in itself). The auxiliary LP has 9030 structural variables (y on the 5091 conditioned rows, z on the 3939 equality rows) and 107572 column inequalities plus the normalisation row f^T z <= 1: maximise f^T z s.t. A^T y + E^T z <= 0 , f^T z <= 1 , y >= 0 , z free Its optimum is 0 exactly when the frozen system is feasible and 1 when it is not, so the basis at the optimum is the sparse object needed for exact rational reconstruction. stdout is the artifact JSON (deterministic: no timings). Progress and timings go to stderr. The basis itself is written to aux_basis.txt / aux_basis.highs in the same directory; their sha256 appear in the artifact. """ import argparse import hashlib import json import os import sys import time from pathlib import Path for _k in ('OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS', 'NUMEXPR_NUM_THREADS', 'VECLIB_MAXIMUM_THREADS'): os.environ.setdefault(_k, '1') import numpy as np # noqa: E402 from scipy.sparse import csr_matrix, hstack, vstack # noqa: E402 import highspy # noqa: E402 HERE = Path(__file__).parent sys.path.insert(0, str(HERE.parent / 'job1088')) from split1090 import build, load, MAPS, GLOBAL, LAYOUT # noqa: E402 try: sys.stdout.reconfigure(newline='\n') # portable LF stdout sys.stderr.reconfigure(newline='\n') except Exception: pass T0 = time.process_time() BIG = 1e30 CODES = {0: 'L', 1: 'B', 2: 'U', 3: 'Z', 4: 'N'} def log(**kw): print(json.dumps(kw, sort_keys=True), file=sys.stderr, flush=True) def sha_of(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest() def rle(vals): """Run-length encode a list of small ints into 'code:count,...' text.""" out, run, prev = [], 0, None for v in vals: if v == prev: run += 1 else: if prev is not None: out.append('%s:%d' % (prev, run)) prev, run = v, 1 if prev is not None: out.append('%s:%d' % (prev, run)) return ','.join(out) def optstr(h, name): """Option value as text, whatever shape highspy returns it in.""" try: v = h.getOptionValue(name) except Exception as exc: # pragma: no cover return 'unavailable: %s' % exc for attr in ('str_value', 'string_value'): if hasattr(v, attr): return str(getattr(v, attr)) return str(v) def main(): ap = argparse.ArgumentParser() ap.add_argument('--time-limit', type=float, default=900.0) ap.add_argument('--build-only', action='store_true') ap.add_argument('--presolve', default='on') args = ap.parse_args() _, mapping = load('maps1086.json', MAPS) A, E, f, sng, blocks, eq_labels, cov_labels, size, ordq, H, Q, kind = build(mapping) mY, mZ, n = A.shape[0], E.shape[0], A.shape[1] log(stage='built', conditioned_rows=mY, equalities=mZ, columns=n, nnz=int(A.nnz + E.nnz), cpu_seconds=round(time.process_time() - T0, 2)) if args.build_only: return 0 norm_rows = [i for i, L in enumerate(eq_labels) if L[0] in ('normalization', 'normalization_copy')] assert len(norm_rows) == len(H) + len(ordq) * len(H), (len(norm_rows), len(H), len(ordq)) # columns: 0..mY-1 are y (>=0), mY..mY+mZ-1 are z (free). Cost is 1 on the # normalisation equality rows of z: that sum is exactly f^T z. cost = np.zeros(mY + mZ) cost[[mY + i for i in norm_rows]] = 1.0 lb = np.concatenate([np.zeros(mY), np.full(mZ, -BIG)]) ub = np.concatenate([np.full(mY, BIG), np.full(mZ, BIG)]) # rows: one per original column (A^T y + E^T z <= 0), then the normalisation row. # row r of M carries the r-th original column's coefficients on (y, z); block-column # order is [y (mY columns) | z (mZ columns)]. M = hstack([A.T.tocsr(), E.T.tocsr()]).tocsr() extra = csr_matrix((np.ones(len(norm_rows)), (np.zeros(len(norm_rows), dtype=np.int32), np.array(norm_rows, dtype=np.int32))), shape=(1, mZ)) Mfull = vstack([M, hstack([csr_matrix((1, mY)), extra])]).tocsc() rl = np.concatenate([np.full(n + 1, -BIG)]) ru = np.concatenate([np.zeros(n), np.array([1.0])]) log(stage='lp', rows=Mfull.shape[0], cols=Mfull.shape[1], nnz=int(Mfull.nnz), cpu_seconds=round(time.process_time() - T0, 2)) h = highspy.Highs() h.setOptionValue('output_flag', False) h.setOptionValue('threads', 1) h.setOptionValue('time_limit', args.time_limit) h.setOptionValue('presolve', args.presolve) 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_ = Mfull.indptr.astype(np.int32) lp.a_matrix_.index_ = Mfull.indices.astype(np.int32) lp.a_matrix_.value_ = Mfull.data assert h.passModel(lp) == highspy.HighsStatus.kOk log(stage='passed-model', cpu_seconds=round(time.process_time() - T0, 2)) h.run() status = h.getModelStatus() obj = h.getObjectiveValue() cpu = time.process_time() - T0 log(stage='solved', status=str(status), objective=obj, cpu_seconds=round(cpu, 2)) sol = h.getSolution() y = np.asarray(sol.col_value[:mY], dtype=float) z = np.asarray(sol.col_value[mY:], dtype=float) coef = np.asarray(A.T.dot(y) + E.T.dot(z), dtype=float) # measured control only basis = h.getBasis() col_st = [int(s) for s in basis.col_status] row_st = [int(s) for s in basis.row_status] # the float optimum itself, published as a warm start for exact reconstruction nz_y = [(i, float(y[i])) for i in range(mY) if y[i] != 0.0] nz_z = [(i, float(z[i])) for i in range(mZ) if z[i] != 0.0] mags = [abs(v) for _, v in nz_y + nz_z if v] (HERE / 'aux_solution.txt').write_text( '# job #1111 split-D51 auxiliary LP optimum (float, 17 significant digits),' ' one-thread HiGHS %s\n' '# y_i: conditioned-row multipliers (mY=%d); z_i: equality-row multipliers (mZ=%d)\n' 'y_nonzero: %s\nz_nonzero: %s\n' % (highspy.Highs().version(), mY, mZ, ' '.join('%d %.17g' % kv for kv in nz_y), ' '.join('%d %.17g' % kv for kv in nz_z)), encoding='utf-8', newline='\n') (HERE / 'aux_basis.txt').write_text( '# job #1111 split-D51 auxiliary LP (GSW eq.3), one-thread HiGHS %s\n' '# rows %d (= %d column inequalities + 1 normalisation row), cols %d\n' '# codes: 0=L(lower) 1=B(basic) 2=U(upper) 3=Z(zero) 4=N(nonbasic)\n' 'row_status_rle: %s\n' 'col_status_raw: %s\n' % (highspy.Highs().version(), n + 1, n, mY + mZ, rle(row_st), ','.join(str(v) for v in col_st)), encoding='utf-8', newline='\n') h.writeBasis(str(HERE / 'aux_basis.highs')) basic_cols = [j for j, s in enumerate(col_st) if s == 1] basic_rows = [r for r, s in enumerate(row_st) if s == 1] nonbasic_rows = [r for r, s in enumerate(row_st) if s != 1] active_rows = [r for r, s in enumerate(row_st) if s == 2] # slack at upper = tight nonbasic_y = [j for j in range(mY) if col_st[j] != 1] nonbasic_z = [j for j in range(mY, mY + mZ) if col_st[j] != 1] scale_of = lambda v: (0 if v == 0 else int(np.floor(np.log10(abs(v))))) art = { 'job': 1111, 'route_id': 8, 'kind': 'split_d51_auxiliary_lp_basis_capture', 'definition': ('maximise f^T z s.t. A^T y + E^T z <= 0, f^T z <= 1, y >= 0, z free; ' 'positive-objective points are Farkas proofs, so the optimum is 0 ' 'exactly when the frozen system is feasible and 1 when it is not'), 'source_maps_sha256': MAPS, 'source_certificate_sha256': GLOBAL, 'source_layout_sha256': LAYOUT, 'model': {'conditioned_rows': int(mY), 'equalities': int(mZ), 'columns': int(n), 'rows': int(n + 1), 'variables': int(mY + mZ), 'normalisation_rows': len(norm_rows), 'nnz': int(Mfull.nnz)}, 'solver': {'name': 'HiGHS via highspy', 'version': highspy.Highs().version(), 'method': optstr(h, 'solver'), 'presolve': optstr(h, 'presolve'), 'threads': 1, 'time_limit_seconds': args.time_limit, 'status': str(status), 'objective': float(obj), 'cpu_seconds': round(cpu, 3)}, 'basis': { 'valid': bool(basis.valid), 'basic_columns': len(basic_cols), 'basic_rows': len(basic_rows), 'nonbasic_rows': len(nonbasic_rows), 'basic_y': sum(1 for j in basic_cols if j < mY), 'basic_z': sum(1 for j in basic_cols if j >= mY), 'structural_condition_number_note': ('basis statuses are HiGHS original-model ' 'indexing; row r< n is the inequality of ' 'original column r, row n is f^T z <= 1'), 'file_sha256': sha_of(HERE / 'aux_basis.txt'), 'highs_basis_sha256': sha_of(HERE / 'aux_basis.highs'), }, 'reduced_exact_system': { 'source': ('exact reconstruction input, per the route next_step: freeze the nonbasic ' 'structural variables at their bounds (all zero here) and solve the active ' 'rows exactly'), 'order': len(active_rows), 'unknowns_basic_y': sum(1 for j in basic_cols if j < mY), 'unknowns_basic_z': sum(1 for j in basic_cols if j >= mY), 'fixed_nonbasic_y_at_zero': len(nonbasic_y), 'fixed_nonbasic_z_at_zero': len(nonbasic_z), 'homogeneous_rows': len(active_rows) - (1 if (n in active_rows) else 0), 'normalisation_row_is_active': bool(n in active_rows), 'normalisation_row_rhs': 1.0, 'order_check': ('|active rows| == |basic structural columns| and total unknowns =' ' |active rows| + |fixed nonbasic columns| = %d' % (mY + mZ)), 'identity_holds': len(active_rows) == len(basic_cols) and len(active_rows) + len(nonbasic_y) + len(nonbasic_z) == mY + mZ, }, 'measured_control_only': { 'max_combined_coefficient_float': float(np.max(coef)), 'columns_at_most_zero': int(np.sum(coef <= 0)), 'normalisation_multiplier_sum_float': float(sum(z[i] for i in norm_rows)), 'note': ('float reading of this solve; exactness is decided only by the integer ' 're-check after reconstruction'), }, 'float_optimum': { 'nonzeros_y': len(nz_y), 'nonzeros_z': len(nz_z), 'min_nonzero_magnitude': float(min(mags, default=0.0)), 'max_nonzero_magnitude': float(max(mags, default=0.0)), 'decade_spread': (scale_of(max(mags, default=0.0)) - scale_of(min(mags, default=0.0))) if mags else 0, 'file_sha256': sha_of(HERE / 'aux_solution.txt'), }, 'environment': {'python': sys.version.split()[0], 'numpy': np.__version__, 'scipy': __import__('scipy').__version__, 'platform': sys.platform}, } text = json.dumps(art, sort_keys=True, indent=2) + '\n' (HERE / 'aux_basis.json').write_text(text, encoding='utf-8', newline='\n') print(text, end='') log(stage='done', cpu_seconds=round(time.process_time() - T0, 2)) return 0 if __name__ == '__main__': raise SystemExit(main())