#!/usr/bin/env python3 """Job #1111 (route 8 rescue): materialise the reduced exact-reconstruction system from the served basis and measure its structure. From the captured basis (aux_basis.txt) the exact witness is the unique solution of M[C, B] x_B = b_C with C the active rows (slack at its upper bound = the column inequality is tight), B the basic structural columns, b_C = 1 on the normalisation row and 0 elsewhere. This script writes that system out (reduced_system.txt, portable column-major text), reports its size, sparsity, degree distribution and connected-component decomposition, and a sha256. The component decomposition is what decides the cost of an exact rational solve: a system that splits into small blocks is solved block by block, exactly, in seconds. stdout is the artifact (deterministic). Progress goes to stderr. """ 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'): os.environ.setdefault(_k, '1') import numpy as np # 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() def log(**kw): print(json.dumps(kw, sort_keys=True), file=sys.stderr, flush=True) def parse_basis(path): rows, cols = None, None for line in Path(path).read_text(encoding='utf-8').splitlines(): if line.startswith('row_status_rle: '): runs = line.split(': ', 1)[1].split(',') rows = [] for run in runs: code, n = run.split(':') rows += [int(code)] * int(n) elif line.startswith('col_status_raw: '): cols = [int(v) for v in line.split(': ', 1)[1].split(',')] assert rows is not None and cols is not None return rows, cols class DSU: def __init__(self, n): self.p = list(range(n)) def find(self, a): while self.p[a] != a: self.p[a] = self.p[self.p[a]] a = self.p[a] return a def union(self, a, b): ra, rb = self.find(a), self.find(b) if ra != rb: self.p[rb] = ra def main(): _, 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] row_st, col_st = parse_basis(HERE / 'aux_basis.txt') active = [r for r, s in enumerate(row_st) if s == 2] basic = [j for j, s in enumerate(col_st) if s == 1] frozen_y = [j for j in range(mY) if col_st[j] != 1] frozen_z = [j for j in range(mY, mY + mZ) if col_st[j] != 1] norm_row = n log(stage='parsed', active=len(active), basic=len(basic), frozen=len(frozen_y) + len(frozen_z)) # structural matrix of the auxiliary LP, columns [y | z], rows = original columns + 1 from scipy.sparse import csc_matrix, hstack, vstack, csr_matrix M = hstack([A.T.tocsr(), E.T.tocsr()]).tocsr() extra = csr_matrix((np.ones(int(np.count_nonzero(f))), (np.zeros(int(np.count_nonzero(f)), dtype=np.int32), np.nonzero(f)[0].astype(np.int32))), shape=(1, mZ)) Mfull = vstack([M, hstack([csr_matrix((1, mY)), extra])]).tocsr() red = Mfull[active][:, basic].tocsc() nnz = int(red.nnz) log(stage='reduced', order=len(active), nnz=nnz) deg_r = np.diff(red.tocsr().indptr) deg_c = np.diff(red.indptr) dsu = DSU(len(active) + len(basic)) rows_of_col = [[] for _ in range(len(basic))] for j in range(len(basic)): rows_of_col[j] = list(red.indices[red.indptr[j]:red.indptr[j + 1]]) for j, rows in enumerate(rows_of_col): for r in rows: dsu.union(r, len(active) + j) comps = {} for i in range(len(active) + len(basic)): comps.setdefault(dsu.find(i), [0, 0]) comps[dsu.find(i)][0 if i < len(active) else 1] += 1 sizes = sorted((v[0], v[1]) for v in comps.values()) big = sizes[-1] if sizes else (0, 0) lines = ['# job #1111 route 8: reduced exact system M[C,B] x_B = b_C', '# rows C: %d active inequalities (row index in the auxiliary LP)' % len(active), '# cols B: %d basic structural columns (column index in the auxiliary LP)' % len(basic), '# b_C: 1 on the row for the auxiliary LP row %d (f^T z <= 1), 0 elsewhere' % norm_row, '# format: c then " " lines, columns ascending', 'active_rows: ' + ','.join(str(r) for r in active), 'basic_columns: ' + ','.join(str(j) for j in basic), 'frozen_nonbasic_columns_at_zero: ' + ','.join(str(j) for j in frozen_y + frozen_z)] for j in range(len(basic)): rows = rows_of_col[j] lines.append('c %d %d' % (j, len(rows))) for r in sorted(rows): lines.append('%d %d' % (r, int(round(red[r, j])))) text = '\n'.join(lines) + '\n' (HERE / 'reduced_system.txt').write_text(text, encoding='utf-8', newline='\n') art = { 'job': 1111, 'route_id': 8, 'kind': 'reduced_exact_system_structure', 'source_maps_sha256': MAPS, 'source_basis_file_sha256': hashlib.sha256((HERE / 'aux_basis.txt').read_bytes()).hexdigest(), 'system': { 'order': len(active), 'rows_active': len(active), 'columns_basic': len(basic), 'nnz': nnz, 'max_row_degree': int(deg_r.max()), 'mean_row_degree': round(float(deg_r.mean()), 3), 'max_col_degree': int(deg_c.max()), 'mean_col_degree': round(float(deg_c.mean()), 3), 'coefficient_magnitudes': sorted({int(abs(red.data[i])) for i in range(nnz)})[:12], 'rhs_nonzero_rows': 1, 'rhs_value': 1, }, 'components': { 'count': len(sizes), 'largest_rows': big[0], 'largest_columns': big[1], 'top10_by_rows': [list(s) for s in sizes[-10:][::-1]], 'note': ('an exact rational solve decomposes over these blocks; the largest block ' 'bounds the cost'), }, 'file_sha256': hashlib.sha256((HERE / 'reduced_system.txt').read_bytes()).hexdigest(), 'file_bytes': len(text.encode('utf-8')), } print(json.dumps(art, sort_keys=True, indent=2)) log(stage='done', cpu_seconds=round(time.process_time() - T0, 2)) return 0 if __name__ == '__main__': raise SystemExit(main())