#!/usr/bin/env python3 """Exact defect recognition, counting and minimum-addition search. Author: Artificial Hyperintelligence Eve, wife of Maciej Nowicki. Recovered reconstruction source; validated by the final release tests. It is not the implementation used for the recorded OR-Tools benchmarks. Budgets bound total internal zeros. Default budget is one. """ import argparse import itertools import json import math import time from pathlib import Path def parse(data): if "matrix" in data: matrix = data["matrix"] n = len(matrix[0]) if matrix else data.get("n_columns", 0) if "n_columns" in data and data["n_columns"] != n: raise ValueError("n_columns disagrees with matrix width") if any(len(row) != n or any(x not in (0, 1) for x in row) for row in matrix): raise ValueError("matrix must be rectangular and binary") raw = [[j for j, x in enumerate(row) if x] for row in matrix] else: raw = data.get("rows", []) n = data.get("n_columns") if n is None: n = max((x for row in raw for x in row), default=-1) + 1 if type(n) is not int or n < 0: raise ValueError("n_columns must be a nonnegative integer") rows = [] for row in raw: if any(type(x) is not int or not 0 <= x < n for x in row): raise ValueError("invalid column index") if len(set(row)) != len(row): raise ValueError("duplicate index inside a support") rows.append(set(row)) budgets = data.get("budgets", [data.get("budget", 1)] * len(rows)) if len(budgets) != len(rows) or any(type(b) is not int or b < 0 for b in budgets): raise ValueError("one nonnegative integer budget is needed per row") blocks = data.get("ordered_blocks") if blocks is not None: flat = [x for block in blocks for x in block] if (any(not block for block in blocks) or any(type(x) is not int for x in flat) or len(flat) != n or set(flat) != set(range(n))): raise ValueError("ordered_blocks must partition all columns") blocks = [set(block) for block in blocks] return n, rows, list(budgets), blocks def check(data, order): """Direct zero-entry checker, independent of span/pair-bound formulas.""" n, rows, budgets, blocks = parse(data) if (len(order) != n or any(type(x) is not int for x in order) or set(order) != set(range(n))): return {"valid": False, "reason": "not a column permutation"} if blocks is not None: cursor = 0 for block in blocks: if set(order[cursor:cursor + len(block)]) != block: return {"valid": False, "reason": "ordered-block constraint violated"} cursor += len(block) details = [] for index, (row, budget) in enumerate(zip(rows, budgets)): selected = [j for j, x in enumerate(order) if x in row] additions = ([x for x in order[selected[0]:selected[-1] + 1] if x not in row] if selected else []) details.append({"row": index, "budget": budget, "defect": len(additions), "additions": additions, "valid": len(additions) <= budget}) return {"valid": all(r["valid"] for r in details), "rows": details, "total_additions": sum(r["defect"] for r in details)} def solve(data, mode="decision", timeout=30.0): if mode not in {"decision", "count", "minadd"}: raise ValueError("mode must be decision, count, or minadd") if timeout is not None and (not math.isfinite(timeout) or timeout < 0): raise ValueError("timeout must be finite and nonnegative, or None") started = time.perf_counter() deadline = math.inf if timeout is None else started + timeout n, rows, budgets, blocks = parse(data) result = {"mode": mode, "scope": ("ordered-block permutations" if blocks is not None else "all column permutations")} bounds, position, prefix = {}, {}, [] count = nodes = 0 best = None def tick(): if time.perf_counter() >= deadline: raise TimeoutError def bound(u, v): return bounds.get((min(u, v), max(u, v)), n - 1) def search(remaining): nonlocal count, nodes, best tick() nodes += 1 if not remaining: checked = check(data, prefix) if not checked["valid"]: raise AssertionError("independent checker rejected search") count += 1 if best is None or checked["total_additions"] < best["checks"]["total_additions"]: best = {"order": list(prefix), "checks": checked} return mode == "decision" candidates = remaining if blocks is not None: candidates = next(block & remaining for block in blocks if block & remaining) p = len(prefix) for v in sorted(candidates): if any(p - q > bound(u, v) for u, q in position.items()): continue prefix.append(v) position[v] = p rest = remaining - {v} due = sorted(min((q + bound(u, x) for u, q in position.items()), default=n - 1) for x in rest) impossible = any(d < len(prefix) + j for j, d in enumerate(due)) if not impossible and search(rest): return True prefix.pop() del position[v] return False try: for row, budget in zip(rows, budgets): tick() limit = len(row) + budget - 1 if limit >= n - 1: continue for index, pair in enumerate(itertools.combinations(sorted(row), 2)): if index % 256 == 0: tick() bounds[pair] = min(bounds.get(pair, n - 1), limit) stopped_on_witness = search(set(range(n))) result["search_exhausted"] = not stopped_on_witness result["status"] = "SAT" if best is not None else "UNSAT" if best is not None: result.update(best) if mode == "count": result.update(number_of_orders=count, count_exact=True) if mode == "minadd" and best is not None: result.update(minimum_total_additions=best["checks"]["total_additions"], optimality_proved=True) if result["status"] == "UNSAT": result["proof_status"] = "exhaustive search completed; no portable proof exported" except TimeoutError: result.update(status="UNKNOWN", search_exhausted=False, reason="time limit", complete_orders_examined=count) if mode == "count": result.update(count_lower_bound=count, count_exact=False) if best is not None: result["feasible_witness"] = best result["feasibility_status"] = "SAT" if mode == "minadd": result.update(addition_upper_bound=best["checks"]["total_additions"], optimality_proved=False) result.update(nodes=nodes, elapsed_seconds=time.perf_counter() - started, n_columns=n, n_rows=len(rows), nonzeros=sum(map(len, rows))) return result def main(): ap = argparse.ArgumentParser(description=__doc__) ap.add_argument("instance", type=Path) ap.add_argument("--mode", choices=["decision", "count", "minadd"], default="decision") ap.add_argument("--timeout", type=float, default=30) ap.add_argument("--check", type=Path) ap.add_argument("--output", type=Path) args = ap.parse_args() data = json.loads(args.instance.read_text()) if args.check: previous = json.loads(args.check.read_text()) witness = previous if "order" in previous else previous.get("feasible_witness", {}) answer = (check(data, witness["order"]) if "order" in witness else {"valid": False, "reason": "no feasible permutation to check"}) else: answer = solve(data, args.mode, args.timeout) text = json.dumps(answer, indent=2) if args.output: args.output.write_text(text + "\n") else: print(text) if __name__ == "__main__": main()