Binary codes correcting two deletions, lengths 16 to 18
Find larger binary codes of length 16, 17 and 18 that correct two deletions; the best known have 220, 349 and 567 words.
Audit bounded exchanges and add perturb-and-repair neighborhoods
Browse files+121 −0 routes/irisbud-codex/n17-local-search/audit_exchanges.py added View file
| @@ -0,0 +1,121 @@ | ||
| 1 | +"""Find improving exchanges that remove at most six words from a length-17 code.""" | |
| 2 | + | |
| 3 | +import argparse | |
| 4 | +from collections import defaultdict | |
| 5 | +from itertools import combinations | |
| 6 | +from pathlib import Path | |
| 7 | + | |
| 8 | +import numpy as np | |
| 9 | + | |
| 10 | +from optimize import DESCENDANT_COUNT, check_code, deletion_table, load_code, write_code | |
| 11 | + | |
| 12 | + | |
| 13 | +def group_options(code, table, radius): | |
| 14 | + owner = np.full(DESCENDANT_COUNT, -1, dtype=np.int32) | |
| 15 | + for word in code: | |
| 16 | + owner[table[word]] = word | |
| 17 | + blocked = np.sort(owner[table], axis=1) | |
| 18 | + transitions = (blocked[:, 1:] >= 0) & (blocked[:, :-1] != blocked[:, 1:]) | |
| 19 | + counts = (blocked[:, 0] >= 0).astype(np.int32) + transitions.sum(axis=1) | |
| 20 | + groups = defaultdict(list) | |
| 21 | + masks = {} | |
| 22 | + for candidate in np.flatnonzero(counts <= radius).tolist(): | |
| 23 | + if candidate in code: | |
| 24 | + continue | |
| 25 | + row = blocked[candidate] | |
| 26 | + owners = tuple(int(w) for w in np.unique(row) if w >= 0) | |
| 27 | + groups[owners].append(candidate) | |
| 28 | + bits = bytearray(DESCENDANT_COUNT // 8) | |
| 29 | + for result in table[candidate].tolist(): | |
| 30 | + bits[result // 8] |= 1 << (result % 8) | |
| 31 | + masks[candidate] = int.from_bytes(bits, byteorder="little") | |
| 32 | + return groups, masks | |
| 33 | + | |
| 34 | + | |
| 35 | +def packing(candidates, masks, target): | |
| 36 | + if len(candidates) < target: | |
| 37 | + return None | |
| 38 | + if target == 1: | |
| 39 | + return (candidates[0],) | |
| 40 | + for i, a in enumerate(candidates[: 1 - target]): | |
| 41 | + compatible = [b for b in candidates[i + 1 :] if not masks[a] & masks[b]] | |
| 42 | + rest = packing(compatible, masks, target - 1) | |
| 43 | + if rest: | |
| 44 | + return (a, *rest) | |
| 45 | + return None | |
| 46 | + | |
| 47 | + | |
| 48 | +def connected_owners(groups, radius): | |
| 49 | + # At the first improving radius, the blocker hypergraph must be connected. | |
| 50 | + # Otherwise a smaller component would already provide an improvement. | |
| 51 | + subsets = [set() for _ in range(radius + 1)] | |
| 52 | + incident = defaultdict(list) | |
| 53 | + for owners in groups: | |
| 54 | + if len(owners) <= radius: | |
| 55 | + subsets[len(owners)].add(owners) | |
| 56 | + if 1 < len(owners) < radius: | |
| 57 | + edge = frozenset(owners) | |
| 58 | + for word in owners: | |
| 59 | + incident[word].append(edge) | |
| 60 | + for size in range(2, radius): | |
| 61 | + for owners in subsets[size]: | |
| 62 | + selected = frozenset(owners) | |
| 63 | + for word in owners: | |
| 64 | + for edge in incident[word]: | |
| 65 | + extra = edge - selected | |
| 66 | + if 0 < len(extra) <= radius - size: | |
| 67 | + subsets[size + len(extra)].add(tuple(sorted(selected | extra))) | |
| 68 | + return subsets | |
| 69 | + | |
| 70 | + | |
| 71 | +def find_exchange(groups, masks, radius): | |
| 72 | + for size, subsets in enumerate(connected_owners(groups, radius)): | |
| 73 | + owner_sets = sorted(subsets) | |
| 74 | + print(f"radius {size}: {len(owner_sets)} relevant subsets", flush=True) | |
| 75 | + for owners in owner_sets: | |
| 76 | + candidates = [] | |
| 77 | + for k in range(1, size + 1): | |
| 78 | + for subset in combinations(owners, k): | |
| 79 | + candidates.extend(groups.get(subset, ())) | |
| 80 | + if size == 0: | |
| 81 | + candidates = groups.get((), []) | |
| 82 | + if len(candidates) <= size: | |
| 83 | + continue | |
| 84 | + candidates.sort(key=lambda word: (masks[word].bit_count(), word)) | |
| 85 | + replacement = packing(candidates, masks, size + 1) | |
| 86 | + if replacement: | |
| 87 | + return set(owners), set(replacement) | |
| 88 | + return None | |
| 89 | + | |
| 90 | + | |
| 91 | +def main(): | |
| 92 | + parser = argparse.ArgumentParser(description=__doc__) | |
| 93 | + parser.add_argument("start", type=Path) | |
| 94 | + parser.add_argument("output", type=Path) | |
| 95 | + parser.add_argument("--radius", type=int, choices=range(1, 7), default=6) | |
| 96 | + parser.add_argument("--steps", type=int, default=10) | |
| 97 | + args = parser.parse_args() | |
| 98 | + if args.steps < 1: | |
| 99 | + parser.error("Step count must be positive") | |
| 100 | + table = deletion_table() | |
| 101 | + code = load_code(args.start) | |
| 102 | + check_code(code, table) | |
| 103 | + write_code(args.output, code) | |
| 104 | + print(f"metric: code_size {len(code)}", flush=True) | |
| 105 | + for step in range(args.steps): | |
| 106 | + groups, masks = group_options(code, table, args.radius) | |
| 107 | + move = find_exchange(groups, masks, args.radius) | |
| 108 | + if move is None: | |
| 109 | + print(f"No improving exchange at radius {args.radius} for {len(code)} words", flush=True) | |
| 110 | + break | |
| 111 | + drop, add = move | |
| 112 | + code = (code - drop) | add | |
| 113 | + check_code(code, table) | |
| 114 | + write_code(args.output, code) | |
| 115 | + print(f"Exchange: removed {len(drop)}, inserted {len(add)}", flush=True) | |
| 116 | + print(f"metric: code_size {len(code)}", flush=True) | |
| 117 | + print(f"progress: {step + 1}/{args.steps} exchanges, best {len(code)}", flush=True) | |
| 118 | + | |
| 119 | + | |
| 120 | +if __name__ == "__main__": | |
| 121 | + main() | |
+44 −10 routes/irisbud-codex/n17-local-search/optimize.py View file
| @@ -73,21 +73,49 @@ def removable(code, target, mode, rng): | ||
| 73 | 73 | return set(rng.sample(words, target)) |
| 74 | 74 | |
| 75 | 75 | |
| 76 | -def solve_repair(table, fixed, released, effort, seed): | |
| 76 | +def perturbation_word(table, allowed, released, rng): | |
| 77 | + alternatives = [word for word in allowed if word not in released] | |
| 78 | + if not alternatives: | |
| 79 | + return None | |
| 80 | + ownership = np.full(DESCENDANT_COUNT, -1, dtype=np.int32) | |
| 81 | + for word in released: | |
| 82 | + ownership[table[word]] = word | |
| 83 | + choices = rng.sample(alternatives, min(140, len(alternatives))) | |
| 84 | + | |
| 85 | + def cost(word): | |
| 86 | + children = np.unique(table[word]) | |
| 87 | + owners = np.unique(ownership[children]) | |
| 88 | + loss = sum(owner >= 0 for owner in owners) | |
| 89 | + return int(loss) * 16 + len(children) + rng.randrange(30) | |
| 90 | + | |
| 91 | + return min(choices, key=cost) | |
| 92 | + | |
| 93 | + | |
| 94 | +def solve_repair(table, fixed, released, effort, seed, force_rng=None, tolerance=0): | |
| 77 | 95 | occupied = check_code(fixed, table) |
| 78 | 96 | allowed = np.flatnonzero(~occupied[table].any(axis=1)).tolist() |
| 79 | 97 | |
| 98 | + forced = None if force_rng is None else perturbation_word(table, allowed, released, force_rng) | |
| 99 | + hint = set(released) | |
| 100 | + if forced is not None: | |
| 101 | + mask = np.zeros(DESCENDANT_COUNT, dtype=bool) | |
| 102 | + mask[table[forced]] = True | |
| 103 | + hint = {word for word in released if not mask[table[word]].any()} | |
| 104 | + hint.add(forced) | |
| 105 | + | |
| 80 | 106 | model = cp_model.CpModel() |
| 81 | 107 | choices = [model.new_bool_var(f"w{word}") for word in allowed] |
| 82 | 108 | by_child = [[] for _ in range(DESCENDANT_COUNT)] |
| 83 | 109 | for choice, word in zip(choices, allowed): |
| 84 | 110 | for child in np.unique(table[word]): |
| 85 | 111 | by_child[child].append(choice) |
| 86 | - model.add_hint(choice, int(word in released)) | |
| 112 | + model.add_hint(choice, int(word in hint)) | |
| 113 | + if word == forced: | |
| 114 | + model.add(choice == 1) | |
| 87 | 115 | for parents in by_child: |
| 88 | 116 | if len(parents) > 1: |
| 89 | 117 | model.add_at_most_one(parents) |
| 90 | - model.add(sum(choices) >= len(released)) | |
| 118 | + model.add(sum(choices) >= len(released) - tolerance) | |
| 91 | 119 | model.maximize(sum(choices)) |
| 92 | 120 | |
| 93 | 121 | solver = cp_model.CpSolver() |
| @@ -108,6 +136,7 @@ def main(): | ||
| 108 | 136 | parser.add_argument("--seed", type=int, required=True) |
| 109 | 137 | parser.add_argument("--rounds", type=int, required=True) |
| 110 | 138 | parser.add_argument("--effort", type=float, default=0.15) |
| 139 | + parser.add_argument("--escape", action="store_true", help="occasionally force a new word in a larger neighborhood") | |
| 111 | 140 | args = parser.parse_args() |
| 112 | 141 | if args.rounds < 1 or args.effort <= 0: |
| 113 | 142 | parser.error("Round count and effort must be positive") |
| @@ -115,28 +144,33 @@ def main(): | ||
| 115 | 144 | rng = random.Random(args.seed) |
| 116 | 145 | table = deletion_table() |
| 117 | 146 | current = best = load_code(args.start) |
| 118 | - if len(current) < 112: | |
| 119 | - parser.error("Initial code needs at least 112 words for the chosen neighborhoods") | |
| 147 | + widths = (96, 120, 144, 168) if args.escape else (44, 64, 88, 112) | |
| 148 | + if len(current) < max(widths) + 3: | |
| 149 | + parser.error("Initial code is too small for the chosen neighborhoods") | |
| 120 | 150 | check_code(current, table) |
| 121 | 151 | write_code(args.output, best) |
| 122 | 152 | print(f"metric: code_size {len(best)}", flush=True) |
| 123 | 153 | |
| 124 | 154 | # Cycle through different neighborhood geometries and sizes. |
| 125 | - widths = (44, 64, 88, 112) | |
| 126 | 155 | for index in range(args.rounds): |
| 156 | + if args.escape and index % 36 == 0: | |
| 157 | + current = best | |
| 127 | 158 | mode = index % 3 |
| 128 | 159 | width = widths[index % len(widths)] |
| 129 | 160 | released = removable(current, width, mode, rng) |
| 130 | - candidate, count, status = solve_repair(table, current - released, released, args.effort, rng.randrange(1 << 30)) | |
| 131 | - if candidate is not None and (len(candidate) > len(current) or rng.random() < 0.4): | |
| 161 | + force = args.escape and index % 4 in (0, 2) and mode != 2 | |
| 162 | + tolerance = max(0, len(current) - len(best) + 3) if force else 0 | |
| 163 | + candidate, count, status = solve_repair(table, current - released, released, args.effort, | |
| 164 | + rng.randrange(1 << 30), rng if force else None, tolerance) | |
| 165 | + if candidate is not None and (force or len(candidate) > len(current) or rng.random() < 0.4): | |
| 132 | 166 | current = candidate |
| 133 | 167 | if len(current) > len(best): |
| 134 | 168 | best = current |
| 135 | 169 | check_code(best, table) |
| 136 | 170 | write_code(args.output, best) |
| 137 | 171 | print(f"metric: code_size {len(best)}", flush=True) |
| 138 | - print(f"progress: {index + 1}/{args.rounds} mode {mode}, released {width}, " | |
| 139 | - f"pool {count}, {status}, best {len(best)}", flush=True) | |
| 172 | + print(f"progress: {index + 1}/{args.rounds} mode {mode}, released {width}, pool {count}, " | |
| 173 | + f"{'forced, ' if force else ''}{status}, current {len(current)}, best {len(best)}", flush=True) | |
| 140 | 174 | print(f"Seed {args.seed}, {args.rounds} neighborhoods, {len(best)} codewords", flush=True) |
| 141 | 175 | |
| 142 | 176 | |
+16 −3 routes/irisbud-codex/n17-local-search/run_seeds.py View file
| @@ -2,6 +2,7 @@ | ||
| 2 | 2 | |
| 3 | 3 | import argparse |
| 4 | 4 | import json |
| 5 | +import re | |
| 5 | 6 | import shutil |
| 6 | 7 | import subprocess |
| 7 | 8 | import sys |
| @@ -26,11 +27,14 @@ def main(): | ||
| 26 | 27 | parser.add_argument("seeds", nargs=4, type=int) |
| 27 | 28 | parser.add_argument("--optimizer-rounds", type=int, default=0) |
| 28 | 29 | parser.add_argument("--effort", type=float, default=0.7) |
| 30 | + parser.add_argument("--escape", action="store_true") | |
| 29 | 31 | args = parser.parse_args() |
| 30 | 32 | scratch, seeds = args.scratch, args.seeds |
| 31 | 33 | if len(set(seeds)) != 4: |
| 32 | 34 | parser.error("Provide four distinct seeds.") |
| 33 | - optimize = set(seeds[2:]) if args.optimizer_rounds else set() | |
| 35 | + if args.escape and args.optimizer_rounds < 1: | |
| 36 | + parser.error("Escape mode needs a positive CP-SAT round count") | |
| 37 | + optimize = set(seeds if args.escape else seeds[2:]) if args.optimizer_rounds else set() | |
| 34 | 38 | outputs = {seed: scratch / f"code-{seed}.json" for seed in seeds} |
| 35 | 39 | workers = {} |
| 36 | 40 | try: |
| @@ -38,6 +42,8 @@ def main(): | ||
| 38 | 42 | if seed in optimize: |
| 39 | 43 | command = [sys.executable, "-B", "optimize.py", str(args.start), str(outputs[seed]), |
| 40 | 44 | "--seed", str(seed), "--rounds", str(args.optimizer_rounds), "--effort", str(args.effort)] |
| 45 | + if args.escape: | |
| 46 | + command.append("--escape") | |
| 41 | 47 | else: |
| 42 | 48 | command = [args.executable, str(seed), str(args.rounds), str(args.start), str(outputs[seed])] |
| 43 | 49 | with (scratch / f"seed-{seed}.log").open("w", encoding="utf-8") as log: |
| @@ -71,10 +77,17 @@ def main(): | ||
| 71 | 77 | start_size = len(read_code(args.start)) |
| 72 | 78 | largest = sizes[seed] |
| 73 | 79 | pending = Path("n17.json.part") |
| 74 | - lines = [f"Local-search rounds per seed: {args.rounds}", f"Starting code: {start_size} words"] | |
| 80 | + lines = [f"Starting code: {start_size} words"] | |
| 81 | + if len(optimize) < len(seeds): | |
| 82 | + lines.append(f"Local-search rounds per seed: {args.rounds}") | |
| 75 | 83 | if optimize: |
| 76 | 84 | lines.append(f"CP-SAT neighborhoods per seed: {args.optimizer_rounds}; deterministic effort: {args.effort}") |
| 77 | 85 | lines.extend(f"Seed {item} ({'CP-SAT' if item in optimize else 'local search'}): {sizes[item]} words" for item in seeds) |
| 86 | + if args.escape: | |
| 87 | + for item in seeds: | |
| 88 | + log = (scratch / f"seed-{item}.log").read_text(encoding="utf-8") | |
| 89 | + current_sizes = [int(size) for size in re.findall(r"current (\d+), best", log)] | |
| 90 | + lines.append(f"Seed {item}: smallest accepted incumbent {min(current_sizes)} words") | |
| 78 | 91 | |
| 79 | 92 | result, order = best_order([read_code(outputs[item]) for item in seeds]) |
| 80 | 93 | lines.append("Pairwise recombination order: " + ", ".join(str(seeds[i]) for i in order)) |
| @@ -90,7 +103,7 @@ def main(): | ||
| 90 | 103 | shutil.copyfile(args.start, pending) |
| 91 | 104 | lines.append(f"Retained starting code: {start_size} words") |
| 92 | 105 | pending.replace("n17.json") |
| 93 | - report = "refinement-report.txt" if optimize else "search-report.txt" | |
| 106 | + report = "escape-report.txt" if args.escape else ("refinement-report.txt" if optimize else "search-report.txt") | |
| 94 | 107 | Path(report).write_text("\n".join(lines) + "\n", encoding="utf-8") |
| 95 | 108 | print(f"metric: code_size {largest}", flush=True) |
| 96 | 109 | print(lines[-1], flush=True) |
+10 −5 routes/irisbud-codex/n17-local-search/search.sbatch View file
| @@ -5,18 +5,23 @@ | ||
| 5 | 5 | #SBATCH --mem=1024M |
| 6 | 6 | set -euo pipefail |
| 7 | 7 | |
| 8 | -rounds=${1:?usage: search.sbatch ROUNDS SEED SEED SEED SEED [START_JSON [OPTIMIZER_ROUNDS]]} | |
| 8 | +rounds=${1:?usage: search.sbatch ROUNDS SEED SEED SEED SEED [START_JSON [OPTIMIZER_ROUNDS [escape]]]} | |
| 9 | 9 | shift |
| 10 | 10 | repo=${SS_INPUT:-$(git rev-parse --show-toplevel)} |
| 11 | 11 | input=${5:-$repo/constructions/n17.json} |
| 12 | -if [[ $# -lt 4 || $# -gt 6 ]]; then | |
| 13 | - echo 'Specify four seeds, optionally followed by a starting code and CP-SAT round count.' >&2 | |
| 12 | +if [[ $# -lt 4 || $# -gt 7 || ( $# -eq 7 && $7 != escape ) ]]; then | |
| 13 | + echo 'Specify four seeds, optionally followed by a starting code, CP-SAT round count, and escape mode.' >&2 | |
| 14 | 14 | exit 2 |
| 15 | 15 | fi |
| 16 | 16 | |
| 17 | 17 | scratch=$(mktemp -d) |
| 18 | 18 | trap 'rm -rf -- "$scratch"' EXIT |
| 19 | -"${CXX:-c++}" -O3 -std=c++17 search.cpp -o "$scratch/search.exe" | |
| 19 | +options=(--optimizer-rounds "${6:-0}") | |
| 20 | +if [[ ${7:-} == escape ]]; then | |
| 21 | + options+=(--escape --effort 1.1) | |
| 22 | +else | |
| 23 | + "${CXX:-c++}" -O3 -std=c++17 search.cpp -o "$scratch/search.exe" | |
| 24 | +fi | |
| 20 | 25 | "${PYTHON:-python3}" -B run_seeds.py "$scratch/search.exe" "$scratch" "$input" "$rounds" "$1" "$2" "$3" "$4" \ |
| 21 | - --optimizer-rounds "${6:-0}" | |
| 26 | + "${options[@]}" | |
| 22 | 27 | "${PYTHON:-python3}" -B "$repo/checks/judge/check.py" . |
