# decryption_complete: false # source: archive/local/external_voynich_units/voynich_decipherment_repro_bundle/decipherment_attack_v6/validate_synthetics.py # stated_sha256: 84c63abd3a5a35d61f404945c0606426e9c9122650928f85df471d2d4e57878a # matches_stated_sha256: false # pdf_pages: 496-498 # note: The stated SHA-256 is the digest printed in the PDF. # The PDF page extract follows the form feed. decryption_complete stays false. Voynich Complete Reproducibility Compendium - 2026-08-28 Page 3495 archive/local/external_voynich_units/voynich_decipherme nt_repro_bundle/decipherment_attack_v6/validate_synthe tics.py SHA-256: 84c63abd3a5a35d61f404945c0606426e9c9122650928f85df471d2d4e57878a | 6,978 bytes | workspace supplement #!/usr/bin/env python3 """End-to-end validation of the BPE -> Brown -> substitution attack pipeline on synthetic homophonic ciphers of Caesar (Latin), with ground truth. Configs vary homophones per letter (2/3/5), group-length mix, and the homophone-choice process (iid weighted vs deterministic rotation). The attack LM is Cicero (different Latin text); German is the wrong-language contrast. Metrics: class/letter NMI, attacked-vs-truth mapping agreement, and the language-match index. """ from __future__ import annotations import json, math, random, sys from collections import Counter, defaultdict from pathlib import Path import numpy as np HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE)) from attack_lib import (letters_of, build_lms, pipeline_classes, class_arrays, attack, heldout_bits, match_index, truncate) rng = random.Random(20260809) OUT = HERE / "output" OUT.mkdir(exist_ok=True) ALPH = "abcdefghijklmnopqrst" TARGET = 120000 def caesar_lines(per_line=9): s = letters_of("latin") # rebuild rough word structure for line-making: split every ~6 letters is # wrong; instead re-read with word boundaries import re as _re from attack_lib import LM_DIR, _strip_gutenberg, _deaccent t = "" t = _strip_gutenberg((LM_DIR / "caesar_la.txt").read_text( encoding="utf-8", errors="replace")) t = _deaccent(t.lower()).replace("v", "u").replace("j", "i") words = _re.findall(r"[a-z]+", t) return [words[i:i + per_line] for i in range(0, len(words), per_line)] def make_tables(letters, n_var, lens): used, tab = set(), {} for i, ch in enumerate(letters): L = lens(i) vs, tries = [], 0 while len(vs) < n_var: tries += 1 if tries > 2000: # length class exhausted -> widen the group L += 1 tries = 0 g = "".join(rng.choice(ALPH) for _ in range(L)) if g not in used: used.add(g) vs.append(g) tab[ch] = vs return tab def encipher(lines, tab, choice): state = defaultdict(int) out_lines, prov = [], {} for ln in lines: row = [] for w in ln: if w not in prov: prov[w] = [] # list of encodings used; store first only groups = [] for ch in w: vs = tab[ch] if choice == "rot": g = vs[state[ch] % len(vs)] state[ch] += 1 else: weights = [0.6, 0.3, 0.1, 0.06, 0.04][:len(vs)] g = rng.choices(vs, weights=weights)[0] groups.append((ch, g)) row.append("".join(g for _, g in groups)) prov[row[-1]] = [(ch, len(g)) for ch, g in groups] out_lines.append(row) return out_lines, prov Voynich Complete Reproducibility Compendium - 2026-08-28 Page 3496 def unit_truth(segmap, prov, lines): """Majority underlying letter per unit occurrence, weighted by frequency.""" wfreq = Counter(w for ln in lines for w in ln) joint = Counter() for w, f in wfreq.items(): if w not in prov or w not in segmap: continue letters = [] for ch, L in prov[w]: letters.extend([ch] * L) pos = 0 for u in segmap[w]: span = letters[pos:pos + len(u)] pos += len(u) if span: maj = Counter(span).most_common(1)[0][0] joint[(u, maj)] += f return joint def nmi_and_truth(joint, classmap): cj = Counter() for (u, ch), f in joint.items(): if u in classmap: cj[(classmap[u], ch)] += f n = sum(cj.values()) pc, pl = Counter(), Counter() for (c, ch), f in cj.items(): pc[c] += f pl[ch] += f I = sum(f / n * math.log2((f / n) / (pc[c] / n * pl[ch] / n)) for (c, ch), f in cj.items()) HL = -sum(f / n * math.log2(f / n) for f in pl.values()) gt_map = {} for c in pc: best = max(((f, ch) for (cc, ch), f in cj.items() if cc == c)) gt_map[c] = best[1] purity = sum(max(f for (cc, ch), f in cj.items() if cc == c) for c in pc) / n return I / HL, purity, gt_map, pc CONFIGS = [ ("H2", 2, lambda i: 2, "iid"), ("H3", 3, lambda i: 2, "iid"), ("H5", 5, lambda i: 2, "iid"), ("H3mix", 3, lambda i: 1 if i < 6 else 2 if i < 16 else 3, "iid"), ("H3rot", 3, lambda i: 2, "rot"), ] if __name__ == "__main__": lms = build_lms(["latin_holdout", "german"]) base = caesar_lines() letter_freq = Counter(c for ln in base for w in ln for c in w) letters = [c for c, _ in letter_freq.most_common()] results = {} # sanity row: plain Caesar letters attacked directly plain_units = [[c for w in ln for c in w] for ln in base] plain_units = truncate([[c for c in ln] for ln in plain_units], TARGET) cm = {c: i for i, c in enumerate(sorted({c for ln in plain_units for c in ln}))} row = {} for lang in ("latin_holdout", "german"): lm, anchor = lms[lang] r = match_index(plain_units, cm, len(cm), lm, anchor, restarts=6) row[lang] = dict(index=r["index"], test_bits=r["test_bits"], scrambled_bits=r["scrambled_bits"], anchor=anchor) print(f"plain {lang:12s} index={r['index']:.3f} " f"bits={r['test_bits']:.3f} scr={r['scrambled_bits']:.3f} " f"anchor={anchor:.3f}", flush=True) results["plain"] = row for name, n_var, lens, choice in CONFIGS: tab = make_tables(letters, n_var, lens) n_groups = n_var * len(letters) clines, prov = encipher(base, tab, choice) clines = truncate(clines, TARGET) k = 110 if n_groups > 80 else 64 segmap, ustream, maps = pipeline_classes(clines, k, [22]) classmap = maps[22] joint = unit_truth(segmap, prov, clines) nmi, purity, gt_map, pc = nmi_and_truth(joint, classmap) row = dict(k=k, n_groups=n_groups, nmi=nmi, purity=purity) for lang in ("latin_holdout", "german"): lm, anchor = lms[lang] r = match_index(ustream, classmap, 22, lm, anchor, restarts=8) # agreement between attacked letters and ground-truth majority agree = 0 tot = sum(pc.values()) for c, f in pc.items(): if lm.alpha[r["mapping"][c]] == gt_map.get(c): agree += f row[lang] = dict(index=r["index"], test_bits=r["test_bits"], scrambled_bits=r["scrambled_bits"], agreement=agree / tot) Voynich Complete Reproducibility Compendium - 2026-08-28 Page 3497 print(f"{name:9s} {lang:12s} NMI={nmi:.3f} pur={purity:.3f} " f"index={r['index']:.3f} agree={agree/tot:.3f}", flush=True) results[name] = row (OUT / "validation_results.json").write_text( json.dumps(results, indent=2, default=float)) print("done")