# decryption_complete: false # source: archive/local/external_voynich_units/voynich_decipherment_repro_bundle/decipherment_attack_v6/attack_lib.py # stated_sha256: 7eb42d1c1cdf5153abb271b12c3161271339d723fd98d5b8ed831041631a51bf # matches_stated_sha256: false # pdf_pages: 647-650 # 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 2646 archive/local/external_voynich_units/voynich_decipherme nt_repro_bundle/decipherment_attack_v6/attack_lib.py SHA-256: 7eb42d1c1cdf5153abb271b12c3161271339d723fd98d5b8ed831041631a51bf | 11,769 bytes | workspace supplement #!/usr/bin/env python3 """Shared machinery for the v6 substitution attack on merged unit classes. Pipeline: lines of tokens -> BPE(k) units -> Brown-style merge to m classes -> class stream. Attack: hill-climb a (many-to-one) mapping classes -> letters of a candidate language, objective = interpolated character-trigram log-likelihood; evaluation = held-out per-symbol log-likelihood, normalised into a language-match index against a scrambled-stream lower anchor and a real-text upper anchor. """ from __future__ import annotations import math, random, re, sys, unicodedata from collections import Counter, defaultdict from pathlib import Path import numpy as np HERE = Path(__file__).resolve().parent ROOT = HERE.parent sys.path.insert(0, str(ROOT / "decipherment_attack_v5")) sys.path.insert(0, str(ROOT / "decipherment_attack")) from unit_probe import bpe_checkpoints, truncate # type: ignore from plant_crib_attack import LOCUS_RE, PAGE_RE, clean_tokens # type: ignore LM_DIR = HERE / "lm_corpora" # ------------------------------------------------------------- LM corpora -- HEBREW_FINALS = str.maketrans("\u05DA\u05DD\u05DF\u05E3\u05E5", "\u05DB\u05DE\u05E0\u05E4\u05E6") def _strip_gutenberg(t: str) -> str: a = t.find("*** START") b = t.find("*** END") if a >= 0: t = t[t.find("\n", a) + 1:] if b >= 0: t = t[:t.find("*** END")] return t def _deaccent(t: str) -> str: return "".join(c for c in unicodedata.normalize("NFD", t) if not unicodedata.combining(c)) def letters_of(lang: str) -> str: """Cleaned, spaceless letter stream for a language.""" if lang == "hebrew": t = (LM_DIR / "lm_hebrew.txt").read_text(encoding="utf-8") t = t.translate(HEBREW_FINALS) return "".join(c for c in t if "\u05D0" <= c <= "\u05EA") if lang == "latin": t = "" for f in ("caesar_la.txt", "caesar_la2.txt"): t += " " + _strip_gutenberg((LM_DIR / f).read_text( encoding="utf-8", errors="replace")) elif lang == "latin_holdout": # validation LM: Caesar books V-VIII only (cipher source is I-IV) t = _strip_gutenberg((LM_DIR / "caesar_la2.txt").read_text( encoding="utf-8", errors="replace")) else: t = _strip_gutenberg((LM_DIR / f"lm_{lang}.txt").read_text( encoding="utf-8", errors="replace")) t = _deaccent(t.lower()).replace("\u00DF", "ss") if lang.startswith("latin"): t = t.replace("v", "u").replace("j", "i") s = re.sub(r"[^a-z]+", "", t) return s def novowels(s: str) -> str: return re.sub(r"[aeiou]", "", s) # --------------------------------------------------------------------- LM -- class TrigramLM: """Interpolated 1/2/3-gram over a fixed alphabet, dense log-prob array.""" def __init__(self, stream: str, lam=(0.1, 0.3, 0.6), max_alpha=28): freq = Counter(stream) alpha = [c for c, _ in freq.most_common(max_alpha)] self.alpha = sorted(alpha) self.index = {c: i for i, c in enumerate(self.alpha)} A = len(self.alpha) ids = np.array([self.index[c] for c in stream if c in self.index], dtype=np.int32) Voynich Complete Reproducibility Compendium - 2026-08-28 Page 2647 c1 = np.bincount(ids, minlength=A).astype(float) c2 = np.zeros((A, A)) np.add.at(c2, (ids[:-1], ids[1:]), 1.0) c3 = np.zeros((A, A, A)) np.add.at(c3, (ids[:-2], ids[1:-1], ids[2:]), 1.0) p1 = (c1 + 0.5) / (c1.sum() + 0.5 * A) p2 = (c2 + 0.5) / (c2.sum(1, keepdims=True) + 0.5 * A) p3 = (c3 + 0.5) / (np.maximum(c3.sum(2, keepdims=True), 1e-9) + 0.5 * A) P = lam[0] * p1[None, None, :] + lam[1] * p2[None, :, :] + lam[2] * p3 self.logp = np.log2(P) self.unigram = p1 def anchor_bits(self, heldout: str) -> float: """Per-symbol log2-prob of real held-out text of this language.""" ids = np.array([self.index[c] for c in heldout if c in self.index], dtype=np.int32) return float(self.logp[ids[:-2], ids[1:-1], ids[2:]].mean()) def build_lms(langs) -> dict[str, tuple["TrigramLM", float]]: out = {} for lang in langs: base = lang[:-9] if lang.endswith("_novowels") else lang s = letters_of(base) if lang.endswith("_novowels"): s = novowels(s) cut = int(len(s) * 0.85) lm = TrigramLM(s[:cut]) out[lang] = (lm, lm.anchor_bits(s[cut:])) return out # ------------------------------------------------- BPE + Brown-style merge -- def unit_stream(lines, segmap): return [[u for w in ln for u in segmap[w]] for ln in lines] def pipeline_classes(lines, k: int, m_targets: list[int], seed=0): """BPE(k) then agglomerative merge; returns unit lines, and per-m classmap.""" segmap = bpe_checkpoints(lines, {k}, k)[k] ustream = unit_stream(lines, segmap) train = [ln for i, ln in enumerate(ustream) if i % 2 == 0 and len(ln) > 1] types = sorted({u for ln in train for u in ln}) idx = {u: i for i, u in enumerate(types)} V = len(types) C = np.zeros((V, V)) for ln in train: for a, b in zip(ln, ln[1:]): if a in idx and b in idx: C[idx[a], idx[b]] += 1 def mi_of(M): P = M / M.sum() ra = P.sum(1, keepdims=True) rb = P.sum(0, keepdims=True) with np.errstate(divide="ignore", invalid="ignore"): T = P * np.log2(P / (ra @ rb)) return np.nansum(T) alive = list(range(V)) members = {i: [types[i]] for i in range(V)} maps = {} while len(alive) > min(m_targets): best, bp = -1e18, None for ii, a in enumerate(alive): for b in alive[ii + 1:]: sub = C[np.ix_(alive, alive)].copy() ia, ib = alive.index(a), alive.index(b) sub[ia, :] += sub[ib, :] sub[:, ia] += sub[:, ib] sub = np.delete(np.delete(sub, ib, 0), ib, 1) v = mi_of(sub) if v > best: best, bp = v, (a, b) a, b = bp C[a, :] += C[b, :] C[:, a] += C[:, b] C[b, :] = 0 C[:, b] = 0 members[a] += members.pop(b) alive.remove(b) if len(alive) in m_targets: cm = {} for root_i, root in enumerate(sorted(alive)): for u in members[root]: cm[u] = root_i maps[len(alive)] = cm return segmap, ustream, maps # ------------------------------------------------------------------ attack -- def class_arrays(ustream, classmap, parity): """Concatenated class ids + trigram index triples (not crossing lines).""" seqs = [] for i, ln in enumerate(ustream): Voynich Complete Reproducibility Compendium - 2026-08-28 Page 2648 if i % 2 != parity or len(ln) < 3: continue cs = [classmap[u] for u in ln if u in classmap] if len(cs) >= 3: seqs.append(np.array(cs, dtype=np.int32)) flat = np.concatenate(seqs) offs, i0 = 0, [] for s in seqs: i0.extend(range(offs, offs + len(s) - 2)) offs += len(s) i0 = np.array(i0, dtype=np.int64) return flat, (i0, i0 + 1, i0 + 2) def attack(flat_tr, tri_tr, m, lm: TrigramLM, restarts=8, seed=0): """Coordinate-ascent search for a NEAR-BIJECTIVE classes->letters mapping (each letter used at most ceil(m/A) times), with reassignment and swap moves. The bijection constraint prevents the degenerate collapse onto a few high-frequency letters that a free many-to-one mapping invites. Returns best mapping and its train bits/symbol.""" rng = np.random.default_rng(seed) A = len(lm.alpha) cap = max(1, math.ceil(m / A)) d0, d1, d2 = tri_tr n = len(d0) cfreq = np.bincount(flat_tr, minlength=m) def score(M): dec = M[flat_tr] return lm.logp[dec[d0], dec[d1], dec[d2]].sum() / n order_l = np.argsort(-lm.unigram) best_M, best_s = None, -1e18 for r in range(restarts): M = np.zeros(m, dtype=np.int32) ranks = np.argsort(-cfreq) if r == 0 else rng.permutation(m) for rank, c in enumerate(ranks): M[c] = order_l[rank % A] usage = np.bincount(M, minlength=A) s = score(M) improved = True while improved: improved = False for c in np.argsort(-cfreq): cur = int(M[c]) best_v, best_move = s, None for l in range(A): if l == cur or usage[l] >= cap: continue M[c] = l v = score(M) if v > best_v: best_v, best_move = v, ("re", l) M[c] = cur for c2 in range(m): l2 = int(M[c2]) if c2 == c or l2 == cur: continue M[c], M[c2] = l2, cur v = score(M) M[c], M[c2] = cur, l2 if v > best_v: best_v, best_move = v, ("sw", c2) if best_move is not None: if best_move[0] == "re": l = best_move[1] usage[cur] -= 1 usage[l] += 1 M[c] = l else: c2 = best_move[1] M[c], M[c2] = M[c2], int(M[c]) s = best_v improved = True if s > best_s: best_s, best_M = s, M.copy() return best_M, best_s def heldout_bits(flat_te, tri_te, M, lm: TrigramLM) -> float: dec = M[flat_te] d0, d1, d2 = tri_te return float(lm.logp[dec[d0], dec[d1], dec[d2]].mean()) def scrambled(ustream, classmap, seed=0): rng = random.Random(seed) out = [] for ln in ustream: ln2 = list(ln) rng.shuffle(ln2) out.append(ln2) return out def match_index(ustream, classmap, m, lm, anchor, restarts=8, seed=0): Voynich Complete Reproducibility Compendium - 2026-08-28 Page 2649 """Attack real stream and scrambled stream; return normalised index.""" ftr, ttr = class_arrays(ustream, classmap, 0) fte, tte = class_arrays(ustream, classmap, 1) M, tr_bits = attack(ftr, ttr, m, lm, restarts=restarts, seed=seed) te = heldout_bits(fte, tte, M, lm) scr = scrambled(ustream, classmap, seed=seed + 99) sftr, sttr = class_arrays(scr, classmap, 0) sfte, stte = class_arrays(scr, classmap, 1) Ms, _ = attack(sftr, sttr, m, lm, restarts=max(4, restarts // 2), seed=seed) te_scr = heldout_bits(sfte, stte, Ms, lm) idx = (te - te_scr) / (anchor - te_scr) if anchor > te_scr else float("nan") return dict(test_bits=te, scrambled_bits=te_scr, anchor_bits=anchor, index=idx, mapping=[int(x) for x in M], train_bits=tr_bits) # ------------------------------------------------------------ voynich data -- def voynich_lines_by_language() -> dict[str, list[list[str]]]: """Paragraph-locus token lines split by Currier language ($L).""" text = (ROOT / "voynich_calibration_sources" / "ZL3b.txt").read_text( encoding="utf-8", errors="replace") attrs = {} for mm in re.finditer(r"^<([^>.]+)>\s+", text, re.M): v = dict(re.findall(r"\$([A-Z])=([^ $>]+)", mm.group(2))) attrs[mm.group(1)] = v out = defaultdict(list) for raw in text.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 not toks: continue lang = attrs.get(page, {}).get("L", "?") out[lang].append(toks) out["pooled"].append(toks) return dict(out)