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.
| 1 | """Refine a length-17 code by solving small deletion set-packing subproblems.""" |
| 2 | |
| 3 | import argparse |
| 4 | import json |
| 5 | import random |
| 6 | from pathlib import Path |
| 7 | |
| 8 | import numpy as np |
| 9 | from ortools.sat.python import cp_model |
| 10 | |
| 11 | |
| 12 | LENGTH = 17 |
| 13 | WORD_COUNT = 1 << LENGTH |
| 14 | DESCENDANT_COUNT = 1 << (LENGTH - 2) |
| 15 | |
| 16 | |
| 17 | def delete_bit(words, position): |
| 18 | mask = (1 << position) - 1 |
| 19 | return (words & mask) | ((words >> 1) & ~mask) |
| 20 | |
| 21 | |
| 22 | def deletion_table(): |
| 23 | words = np.arange(WORD_COUNT, dtype=np.int32) |
| 24 | table = np.empty((WORD_COUNT, LENGTH * (LENGTH - 1) // 2), dtype=np.uint16) |
| 25 | index = 0 |
| 26 | for second in range(1, LENGTH): |
| 27 | short = delete_bit(words, second) |
| 28 | for first in range(second): |
| 29 | table[:, index] = delete_bit(short, first) |
| 30 | index += 1 |
| 31 | return table |
| 32 | |
| 33 | |
| 34 | def load_code(path): |
| 35 | data = json.loads(path.read_text(encoding="utf-8")) |
| 36 | if data["n"] != LENGTH: |
| 37 | raise ValueError(f"Expected n = {LENGTH} in {path}") |
| 38 | words = data["words"] |
| 39 | if not words or any(len(word) != LENGTH or set(word) - {"0", "1"} for word in words): |
| 40 | raise ValueError(f"Invalid word in {path}") |
| 41 | code = {int(word, 2) for word in words} |
| 42 | if len(code) != len(words): |
| 43 | raise ValueError(f"Repeated word in {path}") |
| 44 | return code |
| 45 | |
| 46 | |
| 47 | def check_code(code, table): |
| 48 | occupied = np.zeros(DESCENDANT_COUNT, dtype=bool) |
| 49 | for word in code: |
| 50 | if occupied[table[word]].any(): |
| 51 | raise ValueError("Code shares a two-deletion descendant") |
| 52 | occupied[table[word]] = True |
| 53 | return occupied |
| 54 | |
| 55 | |
| 56 | def write_code(output, code): |
| 57 | words = [f"{word:0{LENGTH}b}" for word in sorted(code)] |
| 58 | pending = output.with_suffix(output.suffix + ".part") |
| 59 | pending.write_text(json.dumps({"n": LENGTH, "words": words}, indent=2) + "\n", encoding="utf-8") |
| 60 | pending.replace(output) |
| 61 | |
| 62 | |
| 63 | def removable(code, target, mode, rng): |
| 64 | words = sorted(code) |
| 65 | anchor = rng.choice(words) |
| 66 | if mode == 0: |
| 67 | # Two words with weights more than two apart cannot conflict. |
| 68 | weight = anchor.bit_count() |
| 69 | return set(sorted(words, key=lambda word: (abs(word.bit_count() - weight), rng.random()))[:target]) |
| 70 | if mode == 1: |
| 71 | return set(sorted(words, key=lambda word: ((word ^ anchor).bit_count(), rng.random()))[:target]) |
| 72 | # A random set can expose exchanges in disjoint neighborhoods at once. |
| 73 | return set(rng.sample(words, target)) |
| 74 | |
| 75 | |
| 76 | def solve_repair(table, fixed, released, effort, seed): |
| 77 | occupied = check_code(fixed, table) |
| 78 | allowed = np.flatnonzero(~occupied[table].any(axis=1)).tolist() |
| 79 | |
| 80 | model = cp_model.CpModel() |
| 81 | choices = [model.new_bool_var(f"w{word}") for word in allowed] |
| 82 | by_child = [[] for _ in range(DESCENDANT_COUNT)] |
| 83 | for choice, word in zip(choices, allowed): |
| 84 | for child in np.unique(table[word]): |
| 85 | by_child[child].append(choice) |
| 86 | model.add_hint(choice, int(word in released)) |
| 87 | for parents in by_child: |
| 88 | if len(parents) > 1: |
| 89 | model.add_at_most_one(parents) |
| 90 | model.add(sum(choices) >= len(released)) |
| 91 | model.maximize(sum(choices)) |
| 92 | |
| 93 | solver = cp_model.CpSolver() |
| 94 | solver.parameters.num_workers = 1 |
| 95 | solver.parameters.random_seed = seed |
| 96 | solver.parameters.max_deterministic_time = effort |
| 97 | status = solver.solve(model) |
| 98 | if status not in (cp_model.FEASIBLE, cp_model.OPTIMAL): |
| 99 | return None, len(allowed), solver.status_name(status) |
| 100 | selected = {word for choice, word in zip(choices, allowed) if solver.boolean_value(choice)} |
| 101 | return fixed | selected, len(allowed), solver.status_name(status) |
| 102 | |
| 103 | |
| 104 | def main(): |
| 105 | parser = argparse.ArgumentParser(description=__doc__) |
| 106 | parser.add_argument("start", type=Path) |
| 107 | parser.add_argument("output", type=Path) |
| 108 | parser.add_argument("--seed", type=int, required=True) |
| 109 | parser.add_argument("--rounds", type=int, required=True) |
| 110 | parser.add_argument("--effort", type=float, default=0.15) |
| 111 | args = parser.parse_args() |
| 112 | if args.rounds < 1 or args.effort <= 0: |
| 113 | parser.error("Round count and effort must be positive") |
| 114 | |
| 115 | rng = random.Random(args.seed) |
| 116 | table = deletion_table() |
| 117 | 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") |
| 120 | check_code(current, table) |
| 121 | write_code(args.output, best) |
| 122 | print(f"metric: code_size {len(best)}", flush=True) |
| 123 | |
| 124 | # Cycle through different neighborhood geometries and sizes. |
| 125 | widths = (44, 64, 88, 112) |
| 126 | for index in range(args.rounds): |
| 127 | mode = index % 3 |
| 128 | width = widths[index % len(widths)] |
| 129 | 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): |
| 132 | current = candidate |
| 133 | if len(current) > len(best): |
| 134 | best = current |
| 135 | check_code(best, table) |
| 136 | write_code(args.output, best) |
| 137 | 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) |
| 140 | print(f"Seed {args.seed}, {args.rounds} neighborhoods, {len(best)} codewords", flush=True) |
| 141 | |
| 142 | |
| 143 | if __name__ == "__main__": |
| 144 | main() |
