# decryption_complete: false # source: archive/local/external_voynich_units/voynich_decipherment_repro_bundle/decipherment_attack_v5/unit_probe.py # stated_sha256: df29b7935eb417c27b959790e2dbb7fe4270b5d56e906b3be1898708b5fede29 # matches_stated_sha256: false # pdf_pages: 643-646 # note: The extracted slice is shorter than the stated byte length. The stated SHA-256 was not reproduced from this slice. # The PDF page extract follows the form feed. decryption_complete stays false. Voynich Complete Reproducibility Compendium - 2026-08-28 Page 2642 archive/local/external_voynich_units/voynich_decipherme nt_repro_bundle/decipherment_attack_v5/unit_probe.py SHA-256: df29b7935eb417c27b959790e2dbb7fe4270b5d56e906b3be1898708b5fede29 | 13,165 bytes | workspace supplement #!/usr/bin/env python3 """E1: BPE unit-discovery probe of the verbose-cipher hypothesis. E2: homophone-family collapse probe of the codebook hypothesis. Corpora are matched in glyph count. All entropies are plug-in, bigrams cross word boundaries within lines, spaces are not symbols (paper's convention). """ from __future__ import annotations import json, math, random, re, sys from collections import Counter, defaultdict from pathlib import Path SCRATCH = Path(__file__).resolve().parent BUNDLE = Path(__file__).resolve().parent.parent sys.path.insert(0, str(BUNDLE / "decipherment_attack")) from plant_crib_attack import LOCUS_RE, PAGE_RE, clean_tokens, collapse, lev # type: ignore rng = random.Random(20260808) # ------------------------------------------------------------- load corpora def voynich_lines() -> list[list[str]]: """Paragraph-locus lines of raw EVA tokens (no collapse).""" lines = [] for raw in (BUNDLE / "voynich_calibration_sources" / "ZL3b.txt").read_text( encoding="utf-8", errors="replace").splitlines(): lm = LOCUS_RE.match(raw) if not lm: continue page, num, marker, typ, txt = lm.groups() if typ != "P": continue toks = clean_tokens(txt) if toks: lines.append(toks) return lines def latin_words() -> list[str]: txt = "" for f in ("caesar_la.txt", "caesar_la2.txt"): t = (SCRATCH / "latin_controls" / f).read_text(encoding="utf-8", errors="replace") # strip gutenberg header/footer a = t.find("*** START") b = t.find("*** END") t = t[t.find("\n", a)+1:b if b > 0 else len(t)] txt += " " + t txt = txt.lower() txt = txt.replace("v", "u").replace("j", "i") words = re.findall(r"[a-z]+", txt) return [w for w in words if len(w) >= 1] def to_lines(words: list[str], per_line: int = 9) -> list[list[str]]: return [words[i:i+per_line] for i in range(0, len(words), per_line)] # ----------------------------------------------------------------- ciphers CIPHER_ALPHABET = "abcdefghijklmnopqrst" # 20 output glyphs def make_groups(letters: list[str], lengths: dict[str, int]) -> dict[str, str]: used, out = set(), {} for ch in letters: L = lengths[ch] while True: g = "".join(rng.choice(CIPHER_ALPHABET) for _ in range(L)) if g not in used: used.add(g); out[ch] = g; break return out def cipher_corpus(lines: list[list[str]], table) -> list[list[str]]: out = [] for ln in lines: out.append(["".join(table(c) for c in w) for w in ln]) return out def build_ciphers(lat_lines): freq = Counter(c for ln in lat_lines for w in ln for c in w) letters = [c for c, _ in freq.most_common()] # verbose-2: every letter -> unique 2-glyph group v2 = make_groups(letters, {c: 2 for c in letters}) # verbose-1-3: frequency-ranked group lengths (common letters short) lens = {c: (1 if i < 7 else 2 if i < 16 else 3) for i, c in enumerate(letters)} v13 = make_groups(letters, lens) Voynich Complete Reproducibility Compendium - 2026-08-28 Page 2643 # homophonic: each letter -> one of 3 groups (len 2), weighted choice homo = {c: [make_groups([c], {c: 2})[c] for _ in range(3)] for c in letters} def t_v2(c): return v2[c] def t_v13(c): return v13[c] def t_homo(c): return rng.choices(homo[c], weights=(0.6, 0.3, 0.1))[0] return t_v2, t_v13, t_homo # ------------------------------------------------------- self-citation gen def selfcite_lines(vy_lines): inventory = Counter(c for ln in vy_lines for w in ln for c in w) glyphs, weights = zip(*inventory.items()) seed = [w for ln in vy_lines[:8] for w in ln] hist = list(seed) n_tokens = sum(len(ln) for ln in vy_lines) line_lens = [len(ln) for ln in vy_lines] out, cur = [], [] li = 0 while len(out) < len(line_lens) and li < n_tokens * 2: li += 1 w = list(rng.choice(hist[-200:])) for _ in range(rng.choices((0, 1, 2), weights=(0.25, 0.5, 0.25))[0]): op = rng.choice(("sub", "ins", "del")) i = rng.randrange(len(w)) if w else 0 if op == "sub" and w: w[i] = rng.choices(glyphs, weights)[0] elif op == "ins": w.insert(i, rng.choices(glyphs, weights)[0]) elif op == "del" and len(w) > 1: del w[i] token = "".join(w) if not token: continue hist.append(token); cur.append(token) if len(cur) >= line_lens[len(out)]: out.append(cur); cur = [] return out # ------------------------------------------------------------------- BPE -- def truncate(lines, target_glyphs): out, n = [], 0 for ln in lines: out.append(ln) n += sum(len(w) for w in ln) if n >= target_glyphs: break return out def bpe_checkpoints(lines, checkpoints, max_merges): """Run BPE on word types; yield (k, segmented word map) at checkpoints.""" wfreq = Counter(w for ln in lines for w in ln) segs = {w: tuple(w) for w in wfreq} results = {} if 0 in checkpoints: results[0] = dict(segs) pair_count: Counter = Counter() where: dict[tuple, set] = defaultdict(set) for w, seg in segs.items(): for a, b in zip(seg, seg[1:]): pair_count[(a, b)] += wfreq[w] where[(a, b)].add(w) for k in range(1, max_merges + 1): if not pair_count: break (a, b), cnt = max(pair_count.items(), key=lambda x: (x[1], x[0])) if cnt < 2: break new = a + b for w in list(where[(a, b)]): seg = segs[w] f = wfreq[w] # remove old pair counts for this word for x, y in zip(seg, seg[1:]): pair_count[(x, y)] -= f if pair_count[(x, y)] <= 0: del pair_count[(x, y)] where[(x, y)].discard(w) # apply merge out = [] i = 0 while i < len(seg): if i < len(seg) - 1 and seg[i] == a and seg[i+1] == b: out.append(new); i += 2 else: out.append(seg[i]); i += 1 seg = tuple(out) segs[w] = seg for x, y in zip(seg, seg[1:]): pair_count[(x, y)] += f where[(x, y)].add(w) if k in checkpoints: results[k] = dict(segs) return results Voynich Complete Reproducibility Compendium - 2026-08-28 Page 2644 def stream_stats(lines, segmap): uni, bi = Counter(), Counter() glyphs = 0 for ln in lines: units = [] for w in ln: units.extend(segmap[w]) glyphs += len(w) uni.update(units) bi.update(zip(units, units[1:])) n = sum(uni.values()) H1 = -sum(c/n * math.log2(c/n) for c in uni.values()) nb = sum(bi.values()) H12 = -sum(c/nb * math.log2(c/nb) for c in bi.values()) # H(next|prev) = H(pair) - H(prev-marginal over bigram table) prev = Counter() for (x, _), c in bi.items(): prev[x] += c Hprev = -sum(c/nb * math.log2(c/nb) for c in prev.values()) H2 = H12 - Hprev return dict(types=len(uni), units=n, glyphs=glyphs, mean_len=glyphs/n, H1=H1, H2=H2, bits_per_glyph=H2*n/glyphs, gap=H1-H2) # ----------------------------------------------------------------- E1 run -- def run_e1(): vy = voynich_lines() lat_all = to_lines(latin_words()) n_vy = sum(len(w) for ln in vy for w in ln) print(f"voynich: {len(vy)} lines, {n_vy} glyphs", flush=True) t_v2, t_v13, t_homo = build_ciphers(lat_all) corpora = { "voynich": vy, "latin": lat_all, "latin_verbose2": cipher_corpus(lat_all, t_v2), "latin_verbose13": cipher_corpus(lat_all, t_v13), "latin_homophonic": cipher_corpus(lat_all, t_homo), "selfcitation": selfcite_lines(vy), } target = min(n_vy, *(sum(len(w) for ln in c for w in ln) for c in corpora.values())) print("target glyphs:", target, flush=True) checkpoints = [0, 4, 8, 16, 32, 64, 128, 256, 512, 1024] out = {} merged_first = {} for name, lines in corpora.items(): lines = truncate(lines, target) res = bpe_checkpoints(lines, set(checkpoints), max(checkpoints)) out[name] = {} for k, segmap in sorted(res.items()): st = stream_stats(lines, segmap) out[name][k] = st print(f"{name:18s} k={k:5d} types={st['types']:5d} len={st['mean_len']:.2f} " f"H1={st['H1']:.3f} H2={st['H2']:.3f} b/g={st['bits_per_glyph']:.3f} " f"gap={st['gap']:.3f}", flush=True) # record the first 25 discovered units (longest-first among merged) if 32 in res: units = Counter() for ln in lines: for w in ln: units.update(u for u in res[32][w] if len(u) > 1) merged_first[name] = [u for u, _ in units.most_common(25)] (SCRATCH / "output" / "e1_results.json").write_text(json.dumps( dict(stats=out, early_units=merged_first), indent=2)) # ----------------------------------------------------------------- E2 run -- def one_edit_components(vocab): parent = {w: w for w in vocab} def find(x): while parent[x] != x: parent[x] = parent[parent[x]]; x = parent[x] return x def union(a, b): ra, rb = find(a), find(b) if ra != rb: parent[ra] = rb dels = defaultdict(list) for w in vocab: for i in range(len(w)): dels[w[:i] + w[i+1:]].append(w) for key, words in dels.items(): if len(words) > 250: bylen = defaultdict(list) for w in words: bylen[len(w)].append(w) groups = list(bylen.values()) else: groups = [words] for group in groups: for i, a in enumerate(group): for b in group[i+1:]: if abs(len(a)-len(b)) <= 1 and lev(a, b) <= 1: union(a, b) Voynich Complete Reproducibility Compendium - 2026-08-28 Page 2645 if key in vocab: for w in words: if lev(key, w) <= 1: union(key, w) comp = defaultdict(list) for w in vocab: comp[find(w)].append(w) return comp def order_info(lines, mapping, cap=2000, n_shuffles=60): """Excess adjacent MI over within-line shuffle, as share of H1.""" freq = Counter(mapping.get(w, w) for ln in lines for w in ln) keep = {t for t, _ in freq.most_common(cap)} def sym(w): t = mapping.get(w, w) return t if t in keep else "" sls = [[sym(w) for w in ln] for ln in lines if len(ln) >= 2] def mi(ls): uni, bi = Counter(), Counter() for ln in ls: uni.update(ln); bi.update(zip(ln, ln[1:])) n, nb = sum(uni.values()), sum(bi.values()) H1 = -sum(c/n*math.log2(c/n) for c in uni.values()) Hp = Counter(); Hn = Counter() for (x, y), c in bi.items(): Hp[x] += c; Hn[y] += c h = lambda cnt: -sum(c/nb*math.log2(c/nb) for c in cnt.values()) H12 = -sum(c/nb*math.log2(c/nb) for c in bi.values()) return h(Hp) + h(Hn) - H12, H1 obs, H1 = mi(sls) shuf = [] r = random.Random(7) for _ in range(n_shuffles): s = [list(ln) for ln in sls] for ln in s: r.shuffle(ln) shuf.append(mi(s)[0]) excess = obs - sum(shuf)/len(shuf) return dict(mi_obs=obs, mi_shuffle=sum(shuf)/len(shuf), excess=excess, H1=H1, share=excess/H1) def run_e2(): # collapsed Voynich tokens, line structure kept vy = [[collapse(w) for w in ln] for ln in voynich_lines()] lat = to_lines(latin_words()) sc = [[collapse(w) for w in ln] for ln in selfcite_lines(voynich_lines())] results = {} for name, lines in (("voynich", vy), ("latin", lat), ("selfcitation", sc)): vocab = {w for ln in lines for w in ln if len(w) >= 4} comps = one_edit_components(vocab) sizes = sorted((len(v) for v in comps.values()), reverse=True) mapping = {} for root, members in comps.items(): fam = "F:" + min(members) for w in members: mapping[w] = fam tok = order_info(lines, {}) fam = order_info(lines, mapping) results[name] = dict( vocab4=len(vocab), n_families=len(comps), top_component_sizes=sizes[:8], giant_share=sizes[0]/len(vocab) if vocab else 0, token_level=tok, family_level=fam) print(f"{name}: vocab4={len(vocab)} families={len(comps)} " f"giant={sizes[0] if sizes else 0} " f"token share={tok['share']*100:.2f}% family share={fam['share']*100:.2f}%", flush=True) (SCRATCH / "output" / "e2_results.json").write_text(json.dumps(results, indent=2)) if __name__ == "__main__": which = sys.argv[1] if len(sys.argv) > 1 else "both" if which in ("e2", "both"): run_e2() if which in ("e1", "both"): run_e1()