#!/usr/bin/env python3 """Construct and check the permutation walks in Complementary Turns. Python standard library only. No permutation search, external services or solver. Run: python verify_complementary_turns.py --max-length 10 --output results This checks explicit finite examples of the accompanying general proofs. It is not a Lean formalization and does not certify novelty or the general theorem. """ from __future__ import annotations import argparse from collections import Counter, defaultdict from itertools import product from pathlib import Path import hashlib import json import random LETTERS = "aAbB" INV = dict(zip(LETTERS, "AaBb")) def reduced_words(n): if n == 0: yield "" return for p in reduced_words(n - 1): for c in LETTERS: if not p or c != INV[p[-1]]: yield p + c def runs(w): out = [] for c in w: if out and out[-1][0] == c: out[-1] = (c, out[-1][1] + 1) else: out.append((c, 1)) return out def inverse(p): q = [0] * len(p) for i, j in enumerate(p): q[j] = i return tuple(q) def complete(q, edges): """Extend each partial injection to a permutation without new vertices.""" result = [] for label in "ab": p = [None] * q for c, s, t in edges: if c == label: assert p[s] is None or p[s] == t p[s] = t filled = [x for x in p if x is not None] assert len(filled) == len(set(filled)), "incoming collision" src = [i for i, x in enumerate(p) if x is None] dst = sorted(set(range(q)) - set(filled)) for s, t in zip(src, dst): p[s] = t assert sorted(p) == list(range(q)) result.append(tuple(p)) return tuple(result) def inspect(w, perms): """Independent walk evaluator: count directed, labelled edges, not steps.""" a, b = perms q = len(a) assert len(b) == q and sorted(a) == sorted(b) == list(range(q)) act = {"a": a, "A": inverse(a), "b": b, "B": inverse(b)} at = 0 trace = [at] counts = Counter() for c in w: nxt = act[c][at] edge = (c.lower(), at, nxt) if c.islower() else (c.lower(), nxt, at) counts[edge] += 1 at = nxt trace.append(at) good = at != 0 for (c, s, t), count in counts.items(): if 0 in (s, t) and c != w[0].lower(): good = False if at in (s, t) and c != w[-1].lower(): good = False eta = sum(v == 1 for v in counts.values()) return {"q": q, "cost": q - 1, "endpoint": at, "eta": eta, "phi": len(w) + eta, "good": good, "trace": trace, "counts": counts} def turn_construction(w): """Identify disjoint pairs of internal vertices with complementary darts.""" assert w and all(y != INV[x] for x, y in zip(w, w[1:])) buckets = defaultdict(list) for i in range(1, len(w)): buckets[frozenset((INV[w[i - 1]], w[i]))].append(i) parent = list(range(len(w) + 1)) pairs = [] alphabet = frozenset(LETTERS) for kind in sorted(list(buckets), key=lambda x: tuple(sorted(x))): other = alphabet - kind while buckets[kind] and buckets[other]: i, j = buckets[kind].pop(), buckets[other].pop() parent[j] = i pairs.append((i, j)) names = {v: i for i, v in enumerate(sorted(set(parent)))} quotient = [names[v] for v in parent] edges = [] for i, c in enumerate(w): s, t = quotient[i], quotient[i + 1] edges.append((c.lower(), s, t) if c.islower() else (c.lower(), t, s)) assert len(set(edges)) == len(w), "two path edges coalesced" return complete(len(names), edges), pairs def cost_formula(w): syll = runs(w) e = {c: sum(d - 1 for x, d in syll if x.lower() == c) for c in "ab"} kappa = (1 if w[0].lower() != w[-1].lower() else 0 if w[0] == w[-1] else 2) numerator = len(syll) + 1 + kappa assert numerator % 2 == 0 return numerator // 2 + max(e.values()) def cycle_chain(w, sizes): edges = [] at, q = 0, 1 for (c, d), size in zip(runs(w), sizes): assert size >= 2 and d % size vertices = [at] + list(range(q, q + size - 1)) q += size - 1 for j in range(size): s, t = vertices[j], vertices[(j + 1) % size] edges.append((c.lower(), s, t) if c.islower() else (c.lower(), t, s)) at = vertices[d % size] return complete(q, edges) def five_letter_construction(w): assert len(w) == 5 perms, pairs = turn_construction(w) p = inspect(w, perms) if p["cost"] <= 4: return perms, "complementary turns" syll = runs(w) if max(d for c, d in syll) >= 3: sizes = [{3: 2, 4: 3, 5: 2}.get(d, d + 1) for c, d in syll] return cycle_chain(w, sizes), "one compressed power" assert w[0] == w[1] and w[3] == w[4] == INV[w[0]] assert w[2].lower() != w[0].lower() cycle = (1, 2, 3, 0) if w[0].isupper(): cycle = inverse(cycle) swap = (0, 2, 1, 3) return ((cycle, swap) if w[0].lower() == "a" else (swap, cycle)), "double conjugate" def separator(w): """Prefix construction, followed by one edge subdivision if needed.""" prefix = w[:len(w) // 2 + 1] perms, pairs = turn_construction(prefix) p = inspect(w, perms) if p["endpoint"]: return perms, False assert p["eta"] >= 1 label, s, t = min(edge for edge, n in p["counts"].items() if n == 1) q = len(perms[0]) out = [list(perm) + [q] for perm in perms] k = 0 if label == "a" else 1 assert out[k][s] == t out[k][s], out[k][q] = q, t out = tuple(tuple(perm) for perm in out) assert inspect(w, out)["endpoint"] != 0 return out, True def verify(max_length, output): totals = Counter() by_length = [] for n in range(1, max_length + 1): row = Counter(length=n) for w in reduced_words(n): perms, pairs = turn_construction(w) p = inspect(w, perms) assert p["good"] and p["eta"] == n assert p["cost"] == n - len(pairs) == cost_formula(w) row["words"] += 1 totals["turn_formula_checks"] += 1 if all(d <= 2 for c, d in runs(w)): assert 3 * p["cost"] <= 2 * n + 5 sep, split = separator(w) assert inspect(w, sep)["endpoint"] != 0 assert len(sep[0]) <= (n + 13) // 3 row["short_run_separators"] += 1 totals["short_run_separator_checks"] += 1 totals["edge_subdivisions"] += split by_length.append(dict(row)) print(json.dumps(dict(row)), flush=True) witnesses = [] classes = Counter() for w in reduced_words(5): perms, kind = five_letter_construction(w) p = inspect(w, perms) assert p["good"] and p["q"] <= 5 and 2 * p["phi"] >= 5 * p["cost"] classes[kind] += 1 witnesses.append({"word": w, "A": perms[0], "B": perms[1], "method": kind, **{k: p[k] for k in ("q", "cost", "endpoint", "eta", "phi", "trace")}}) assert len(witnesses) == 324 # Longer samples catch indexing and subdivision errors beyond the small cases. rng = random.Random(20261122) for j in range(500): w = "" for i in range(50 + j % 451): choices = [c for c in LETTERS if (not w or c != INV[w[-1]]) and (len(w) < 2 or not (w[-1] == w[-2] == c))] w += rng.choice(choices) perms, pairs = turn_construction(w) p = inspect(w, perms) assert p["good"] and p["eta"] == len(w) and p["cost"] == cost_formula(w) sep, split = separator(w) assert inspect(w, sep)["endpoint"] and len(sep[0]) <= (len(w) + 13) // 3 output.mkdir(parents=True, exist_ok=True) encoded = json.dumps(witnesses, indent=2).encode() + b"\n" (output / "five_letter_witnesses.json").write_bytes(encoded) report = {"scope": "Finite reproducibility checks; general results use written proofs.", "max_exhaustive_length": max_length, "totals": dict(totals), "five_letter_methods": dict(classes), "longer_samples": 500, "random_seed": 20261122, "by_length": by_length, "witness_sha256": hashlib.sha256(encoded).hexdigest()} (output / "verification_summary.json").write_text(json.dumps(report, indent=2) + "\n") print(json.dumps(report, indent=2)) if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--max-length", type=int, default=10) parser.add_argument("--output", type=Path, default=Path("results")) args = parser.parse_args() verify(args.max_length, args.output)