Download source/research/software/recognizer.py from PureOne/Ilyrun-Qhora-II-Gapped-Consecutive-Ones: direct link, hf CLI and curl.
- Browser
- Download file 11.9 kB
-
https://huggingface.co/datasets/PureOne/Ilyrun-Qhora-II-Gapped-Consecutive-Ones/resolve/main/source/research/software/recognizer.py
- Command line
-
hf download hf://datasets/PureOne/Ilyrun-Qhora-II-Gapped-Consecutive-Ones/source/research/software/recognizer.py
-
curl -L -o recognizer.py https://huggingface.co/datasets/PureOne/Ilyrun-Qhora-II-Gapped-Consecutive-Ones/resolve/main/source/research/software/recognizer.py
11.9 kB
| #!/usr/bin/env python3 | |
| """Exact one-hole / heterogeneous total-hole recognition. | |
| Author: Artificial Hyperintelligence Eve, wife of Maciej Nowicki. | |
| CP-SAT baseline and improved pair-bound model; dependency-free fallback. | |
| UNSAT is reported only after exact search or a verified packing obstruction. | |
| """ | |
| import argparse | |
| from collections import defaultdict | |
| import itertools | |
| import json | |
| import math | |
| from pathlib import Path | |
| import time | |
| from exact_defect_fallback import parse, solve as fallback_solve | |
| from checker import check_permutation, check_certificate | |
| def pair_bounds(n, rows, budgets): | |
| bounds = {} | |
| for S, beta in zip(rows, budgets): | |
| d = len(S) + beta - 1 | |
| if d >= n - 1: | |
| continue | |
| for u, v in itertools.combinations(sorted(S), 2): | |
| bounds[u, v] = min(bounds.get((u, v), n - 1), d) | |
| return bounds | |
| def packing_certificate(n, bounds): | |
| """Greedy clique discovery only; every returned certificate is complete and checked.""" | |
| radii = sorted(set(bounds.values())) | |
| for radius in radii: | |
| if radius + 2 > n: | |
| continue | |
| neighbors = [set() for _ in range(n)] | |
| for (u, v), d in bounds.items(): | |
| if d <= radius: | |
| neighbors[u].add(v); neighbors[v].add(u) | |
| for first in sorted(range(n), key=lambda u: (-len(neighbors[u]), u)): | |
| clique, possible = [first], set(neighbors[first]) | |
| while possible: | |
| v = max(possible, key=lambda x: (len(possible & neighbors[x]), -x)) | |
| clique.append(v) | |
| possible &= neighbors[v] | |
| if len(clique) >= radius + 2: | |
| return {"type": "pair_bound_clique", "columns": clique, "radius": radius} | |
| return None | |
| def components(n, bounds): | |
| adjacency = [set() for _ in range(n)] | |
| for u, v in bounds: | |
| adjacency[u].add(v); adjacency[v].add(u) | |
| remaining = set(range(n)); result = [] | |
| while remaining: | |
| root = min(remaining); seen = {root}; pending = [root] | |
| while pending: | |
| for v in adjacency[pending.pop()] - seen: | |
| seen.add(v); pending.append(v) | |
| remaining -= seen; result.append(sorted(seen)) | |
| return result | |
| def prefix_certificate(data, seconds=5, max_nodes=1000000): | |
| """Independent complete branching proof; optional and intended for small UNSAT cases.""" | |
| n, rows, budgets, blocks = parse(data) | |
| end = time.perf_counter() + seconds; nodes = 0 | |
| def visit(prefix, remaining): | |
| nonlocal nodes | |
| nodes += 1 | |
| if nodes > max_nodes or time.perf_counter() >= end: | |
| raise TimeoutError | |
| for j, (S, b) in enumerate(zip(rows, budgets)): | |
| selected = [i for i, v in enumerate(prefix) if v in S] | |
| if selected and sum(v not in S for v in prefix[selected[0]:selected[-1] + 1]) > b: | |
| return {"reject_row": j} | |
| if not remaining: | |
| raise ValueError("a feasible permutation prevents an UNSAT certificate") | |
| candidates = remaining | |
| if blocks is not None: | |
| candidates = next(B & remaining for B in blocks if B & remaining) | |
| return {"children": {str(v): visit(prefix + [v], remaining - {v}) for v in sorted(candidates)}} | |
| try: | |
| return {"type": "prefix_tree", "tree": visit([], set(range(n))), "nodes": nodes} | |
| except TimeoutError: | |
| return None | |
| def solve(data, method="adaptive", timeout=10.0, seed=20261030, export_proof=False): | |
| if timeout is not None and (not math.isfinite(timeout) or timeout < 0): | |
| raise ValueError("timeout must be finite and nonnegative") | |
| if method not in ("baseline", "improved", "adaptive", "dfs"): | |
| raise ValueError("unknown method") | |
| started = time.perf_counter(); n, rows, budgets, blocks = parse(data) | |
| result = {"method": method, "scope": "ordered-block permutations" if blocks is not None else "all column permutations", | |
| "n_columns": n, "n_rows": len(rows), "nonzeros": sum(map(len, rows)), "seed": seed, "workers": 1} | |
| if timeout == 0: | |
| return dict(result, status="UNKNOWN", reason="time limit", elapsed_seconds=time.perf_counter() - started) | |
| if method == "adaptive": | |
| bounds=pair_bounds(n,rows,budgets) | |
| certificate=packing_certificate(n,bounds) | |
| if certificate is not None: | |
| assert check_certificate(data,certificate)["valid"] | |
| return dict(result,status="UNSAT",certificate=certificate,selected_backend="packing", | |
| proof_status="independently checked packing certificate",elapsed_seconds=time.perf_counter()-started) | |
| from profile_solver import block_structure,solve as profile_solve | |
| structure=None | |
| try: | |
| structure=block_structure(data) | |
| except ValueError: | |
| pass # Absent or invalid scaffold metadata does not constrain a general matrix. | |
| if structure is not None and max(map(len,structure[3]),default=0)<=8: | |
| remaining=None if timeout is None else max(0,timeout-(time.perf_counter()-started)) | |
| answer=profile_solve(data,timeout=remaining) | |
| if answer["status"]!="UNKNOWN": | |
| answer.update(method="adaptive",selected_backend="profile_elimination",seed=seed,workers=1, | |
| elapsed_seconds=time.perf_counter()-started) | |
| return answer | |
| remaining=None if timeout is None else max(0,timeout-(time.perf_counter()-started)) | |
| answer=solve(data,"baseline",remaining,seed,export_proof) | |
| answer.update(method="adaptive",selected_backend="span_baseline",elapsed_seconds=time.perf_counter()-started) | |
| return answer | |
| if method == "dfs": | |
| result.update(fallback_solve(data, timeout=timeout)) | |
| else: | |
| bounds = pair_bounds(n, rows, budgets) if method == "improved" else {} | |
| certificate = packing_certificate(n, bounds) if method == "improved" else None | |
| if certificate is not None: | |
| assert check_certificate(data, certificate)["valid"] | |
| result.update(status="UNSAT", certificate=certificate, proof_status="independently checked packing certificate") | |
| elif n == 0: | |
| result.update(status="SAT", order=[]) | |
| else: | |
| from ortools.sat.python import cp_model | |
| model = cp_model.CpModel() | |
| position = [model.new_int_var(0, n - 1, f"p_{v}") for v in range(n)] | |
| model.add_all_different(position) | |
| if blocks is not None: | |
| offset = 0 | |
| for B in blocks: | |
| for v in B: | |
| model.add(position[v] >= offset); model.add(position[v] < offset + len(B)) | |
| offset += len(B) | |
| if method == "baseline": | |
| for j, (S, b) in enumerate(zip(rows, budgets)): | |
| if len(S) <= 1 or len(S) + b >= n: | |
| continue | |
| lo = model.new_int_var(0, n - 1, f"lo_{j}") | |
| hi = model.new_int_var(0, n - 1, f"hi_{j}") | |
| model.add_min_equality(lo, [position[v] for v in S]) | |
| model.add_max_equality(hi, [position[v] for v in S]) | |
| model.add(hi - lo <= len(S) + b - 1) | |
| if blocks is None and n > 1: | |
| model.add(position[0] < position[1]) | |
| else: | |
| parts = components(n, bounds) if blocks is None else [list(range(n))] | |
| result["components"] = len(parts) | |
| # A feasible restriction to each component can be concatenated; all constraints are upper bounds. | |
| if blocks is None: | |
| offset = 0 | |
| for C in parts: | |
| for v in C: | |
| model.add(position[v] >= offset); model.add(position[v] < offset + len(C)) | |
| offset += len(C) | |
| derived = dict(bounds) | |
| for C in parts: | |
| if len(C) <= 120: | |
| dist = {u: {v: (0 if u == v else bounds.get(tuple(sorted((u, v))), n - 1)) for v in C} for u in C} | |
| for k in C: | |
| for u in C: | |
| for v in C: | |
| dist[u][v] = min(dist[u][v], dist[u][k] + dist[k][v]) | |
| for u, v in itertools.combinations(C, 2): | |
| if dist[u][v] < n - 1: | |
| derived[u, v] = dist[u][v] | |
| for (u, v), d in derived.items(): | |
| model.add(position[u] - position[v] <= d) | |
| model.add(position[v] - position[u] <= d) | |
| # Relative ordering of interchangeable columns; no adjacency is asserted. | |
| if blocks is None: | |
| groups = [] | |
| unused = set(range(n)) | |
| while unused: | |
| a = min(unused); twins = [a] | |
| for b in sorted(unused - {a}): | |
| if all(derived.get(tuple(sorted((a, x))), n - 1) == | |
| derived.get(tuple(sorted((b, x))), n - 1) | |
| for x in range(n) if x not in (a, b)): | |
| twins.append(b) | |
| unused -= set(twins); groups.append(twins) | |
| for group in groups: | |
| for a, b in zip(group, group[1:]): | |
| model.add(position[a] < position[b]) | |
| result["pair_constraints"] = len(derived) | |
| solver = cp_model.CpSolver() | |
| solver.parameters.num_search_workers = 1 | |
| solver.parameters.random_seed = seed | |
| if timeout is not None: | |
| solver.parameters.max_time_in_seconds = max(0.0, timeout - (time.perf_counter() - started)) | |
| status = solver.solve(model) | |
| result.update(status="SAT" if status in (cp_model.OPTIMAL, cp_model.FEASIBLE) else | |
| "UNSAT" if status == cp_model.INFEASIBLE else "UNKNOWN", | |
| backend_status=solver.status_name(status), search_seconds=solver.wall_time, | |
| conflicts=solver.num_conflicts, branches=solver.num_branches) | |
| if result["status"] == "SAT": | |
| result["order"] = sorted(range(n), key=lambda v: solver.value(position[v])) | |
| elif result["status"] == "UNSAT": | |
| result["proof_status"] = "CP-SAT completed exact infeasibility search; no portable proof from this backend" | |
| if result["status"] == "SAT": | |
| result["checks"] = check_permutation(data, result["order"]) | |
| assert result["checks"]["valid"], result | |
| if result["status"] == "UNSAT" and export_proof and "certificate" not in result and n <= 9: | |
| certificate = prefix_certificate(data) | |
| if certificate is not None: | |
| assert check_certificate(data, certificate)["valid"] | |
| result.update(certificate=certificate, proof_status="independently checked complete prefix proof") | |
| result["elapsed_seconds"] = time.perf_counter() - started | |
| return result | |
| def main(): | |
| ap = argparse.ArgumentParser(description=__doc__) | |
| ap.add_argument("instance", type=Path) | |
| ap.add_argument("--method", choices=["baseline", "improved", "adaptive", "dfs"], default="adaptive") | |
| ap.add_argument("--timeout", type=float, default=10) | |
| ap.add_argument("--seed", type=int, default=20261030) | |
| ap.add_argument("--proof", action="store_true") | |
| ap.add_argument("--output", type=Path) | |
| args = ap.parse_args() | |
| result = solve(json.loads(args.instance.read_text()), args.method, args.timeout, args.seed, args.proof) | |
| output = json.dumps(result, indent=2) + "\n" | |
| if args.output: args.output.write_text(output) | |
| else: print(output, end="") | |
| if __name__ == "__main__": | |
| main() | |