Spaces:
Running on Zero

VM / corpus.py
kambris's picture
Upload corpus.py
ce5afaa verified
Raw History Blame Contribute Delete
21.7 kB
"""Per-view corpus statistics for the Voynich reader.
A View is everything the UI needs for one (source, include_labels) combination.
Pages are always navigable; the label toggle only decides which tokens count
toward the statistics (spec A: D2, D7).
Collocates, robustness and concordance implement spec C
(specs/collocates-concordance.md).
"""
from __future__ import annotations
from bisect import bisect_left
from collections import defaultdict
from dataclasses import dataclass, field
from functools import lru_cache
import numpy as np
import pandas as pd
from association_measures import measures as am
from build_tokens import folio_key
SECTION_NAMES = {
"H": "Herbal", "A": "Astronomical", "C": "Cosmological", "Z": "Zodiac",
"B": "Biological", "P": "Pharmaceutical", "S": "Stars / recipes", "T": "Text only",
}
SECTION_ORDER = ["H", "A", "C", "Z", "B", "P", "S", "T"]
SOURCE_NAMES = {
"ZL": "Zandbergen-Landini (ZL)",
"IT": "Takahashi (IT)",
"RF": "Reference: ZL + Claston (RF)",
}
# Spec C, C8 thresholds.
G2_MIN = 10.83
MIN_COOC = 3
MIN_FREQ = 5
DIM_FOLIOS = 3
POSITIONS = ("initial", "medial", "final", "alone")
def view_key(source: str, include_labels: bool) -> str:
return f"{source}|{int(bool(include_labels))}"
@dataclass
class View:
source: str
include_labels: bool
page_df: pd.DataFrame # every locus type: what the page shows
df: pd.DataFrame # tokens that count toward statistics
folios: list[str]
folio_idx: dict[str, int]
folio_section: dict[str, str]
word_folios: dict[str, list[str]]
word_folio_counts: dict[str, dict[str, int]]
pos_map: dict[str, dict[str, int]]
prev_map: dict[str, dict[str, int]]
next_map: dict[str, dict[str, int]]
global_freq: dict[str, int]
freq_sorted: list[int]
all_words: list[str]
section_totals: dict[str, int]
folio_token_counts: pd.Series
corpus: dict = field(default_factory=dict)
tok: pd.DataFrame | None = None # stats tokens in manuscript order, with line structure
def word_series(self, word: str) -> list[int]:
counts = self.word_folio_counts.get(word, {})
return [counts.get(f, 0) for f in self.folios]
def percentile(self, freq: int) -> int:
if not self.freq_sorted:
return 0
return int(bisect_left(self.freq_sorted, freq) / len(self.freq_sorted) * 100)
def sections_present(self) -> list[str]:
present = set(self.folio_section.values())
return [s for s in SECTION_ORDER if s in present] + sorted(present - set(SECTION_ORDER))
def _line_maps(df: pd.DataFrame):
pos_map: dict[str, dict[str, int]] = {}
prev_map: dict[str, dict[str, int]] = defaultdict(lambda: defaultdict(int))
next_map: dict[str, dict[str, int]] = defaultdict(lambda: defaultdict(int))
ordered = df.sort_values(["Folio", "Line", "Position"])
for words in ordered.groupby(["Folio", "Line"], sort=False)["Word"].agg(list):
n = len(words)
for i, w in enumerate(words):
if n > 1:
slot = "start" if i == 0 else "end" if i == n - 1 else "mid"
pos_map.setdefault(w, {"start": 0, "mid": 0, "end": 0})[slot] += 1
if i > 0:
prev_map[w][words[i - 1]] += 1
if i < n - 1:
next_map[w][words[i + 1]] += 1
return pos_map, prev_map, next_map
def _ordered_tokens(df: pd.DataFrame, folio_idx: dict[str, int]) -> pd.DataFrame:
"""Stats tokens in manuscript order with line ids, in-line index and line-position class."""
t = df.copy()
t["_fi"] = t["Folio"].map(folio_idx)
t = t.sort_values(["_fi", "Line", "Position"], kind="stable").reset_index(drop=True)
t["LineId"] = t.groupby(["_fi", "Line"], sort=False).ngroup()
t["Idx"] = t.groupby("LineId").cumcount()
t["LineLen"] = t.groupby("LineId")["Word"].transform("size")
t["LinePos"] = np.select(
[t["LineLen"] == 1, t["Idx"] == 0, t["Idx"] == t["LineLen"] - 1],
["alone", "initial", "final"], default="medial")
t["HasAlt"] = t["Alt"].fillna("").astype(str) != ""
t["Flagged"] = t["UncertainBreak"].astype(bool) | t["HasAlt"] | t["Illegible"].astype(bool)
t["Order"] = np.arange(len(t))
return t.drop(columns="_fi")
def build_view(tokens: pd.DataFrame, source: str, include_labels: bool) -> View:
page_df = tokens[tokens["Source"] == source].reset_index(drop=True)
df = page_df if include_labels else page_df[page_df["LocusType"] == "P"]
df = df.reset_index(drop=True)
folios = sorted(page_df["Folio"].unique(), key=folio_key)
folio_idx = {f: i for i, f in enumerate(folios)}
folio_section = page_df.groupby("Folio")["Section"].first().to_dict()
wf = df.groupby(["Word", "Folio"]).size()
word_folio_counts: dict[str, dict[str, int]] = defaultdict(dict)
for (w, f), c in wf.items():
word_folio_counts[w][f] = int(c)
word_folios = {w: sorted(c, key=folio_key) for w, c in word_folio_counts.items()}
global_freq = {w: int(c) for w, c in df["Word"].value_counts().items()}
pos_map, prev_map, next_map = _line_maps(df)
n_tok = len(df)
n_types = len(global_freq)
top5 = sorted(global_freq.items(), key=lambda x: (-x[1], x[0]))[:5]
corpus = {
"tokens": n_tok,
"types": n_types,
"ttr": n_types / n_tok if n_tok else 0.0,
"hapax": sum(1 for c in global_freq.values() if c == 1),
"avg_wl": float(df["Word"].str.len().mean()) if n_tok else 0.0,
"folios": len(folios),
"top5": top5,
}
return View(
source=source,
include_labels=include_labels,
page_df=page_df,
df=df,
folios=folios,
folio_idx=folio_idx,
folio_section=folio_section,
word_folios=word_folios,
word_folio_counts=dict(word_folio_counts),
pos_map=pos_map,
prev_map=prev_map,
next_map=next_map,
global_freq=global_freq,
freq_sorted=sorted(global_freq.values()),
all_words=list(global_freq),
section_totals={s: int(c) for s, c in df["Section"].value_counts().items()},
folio_token_counts=df.groupby("Folio").size(),
corpus=corpus,
tok=_ordered_tokens(df, folio_idx),
)
# ── Spec C: scope and windows ─────────────────────────────────────────────────
def _scope(view: View, section=None, language=None) -> pd.DataFrame:
"""Section and language are page-level, so scoping keeps whole lines."""
t = view.tok
if section and section != "All":
t = t[t["Section"] == section]
if language and language != "All":
t = t[t["Language"] == language]
return t
def _offsets(window: int, exclude_adjacent: bool) -> np.ndarray:
lo = 2 if exclude_adjacent else 1
return np.array([d for d in range(-window, window + 1) if abs(d) >= lo], dtype=int)
def _hits(t: pd.DataFrame, word: str, pattern=None) -> np.ndarray:
"""Hit tokens: the exact word, or every word matching a compiled pattern (spec D, D7a)."""
if pattern is None:
return t["Word"].to_numpy() == word
from search import hit_mask
return hit_mask(t, pattern).to_numpy()
def _window_pairs(t: pd.DataFrame, word: str, window: int, exclude_adjacent: bool,
certain_only: bool, pattern=None):
"""Return (hit_rows, pos_rows, offsets) for every hit Γ— window position.
`t` is a scoped slice of view.tok (whole lines). Window positions stay on the
hit's line; with certain_only, flagged tokens are neither hits nor window
positions, but still occupy their slot (C16).
"""
line = t["LineId"].to_numpy()
idx = t["Idx"].to_numpy()
flagged = t["Flagged"].to_numpy() if certain_only else np.zeros(len(t), bool)
# Rows of a line are contiguous in t and ordered by Idx, so row + d is the token d slots away.
hits = np.flatnonzero(_hits(t, word, pattern) & ~flagged)
offs = _offsets(window, exclude_adjacent)
if len(hits) == 0 or len(offs) == 0:
e = np.array([], dtype=int)
return hits, e, e, e
j = hits[:, None] + offs[None, :]
inb = (j >= 0) & (j < len(t))
jc = np.where(inb, j, 0)
ok = inb & (line[jc] == line[hits][:, None]) & (idx[jc] - idx[hits][:, None] == offs[None, :])
ok &= ~flagged[jc]
hit_rows = np.broadcast_to(hits[:, None], j.shape)[ok]
d = np.broadcast_to(offs[None, :], j.shape)[ok]
return hits, hit_rows, j[ok], d
def collocate_table(view: View, word: str, window: int = 3, section=None, language=None,
exclude_adjacent: bool = False, certain_only: bool = False,
positional: bool = False, pattern=None) -> pd.DataFrame:
"""Every candidate collocate with its full statistics, unfiltered (C7, C9, C15)."""
t = _scope(view, section, language)
cols = ["collocate", "O11", "O12", "O21", "O22", "R1", "C1", "N", "expected", "G2", "LRC",
"left", "right", "dp_wc", "dp_cw", "folios", "sections", "lang_A", "lang_B",
"lang_other", "in_family"]
if t.empty:
return pd.DataFrame(columns=cols)
t = t.reset_index(drop=True)
flagged = t["Flagged"].to_numpy() if certain_only else np.zeros(len(t), bool)
valid = t[~flagged]
N = len(valid)
hits, hit_rows, pos_rows, d = _window_pairs(t, word, window, exclude_adjacent, certain_only,
pattern)
R1 = len(pos_rows)
if R1 == 0:
return pd.DataFrame(columns=cols)
lang = t["Language"].to_numpy()[hit_rows]
rec = pd.DataFrame({
"collocate": t["Word"].to_numpy()[pos_rows],
"is_left": d < 0,
"Folio": t["Folio"].to_numpy()[hit_rows],
"Section": t["Section"].to_numpy()[hit_rows],
"is_A": lang == "A",
"is_B": lang == "B",
"LinePos": t["LinePos"].to_numpy()[pos_rows],
})
g = rec.groupby("collocate", sort=False)
sums = g[["is_left", "is_A", "is_B"]].sum()
tab = pd.DataFrame({
"O11": g.size(),
"left": sums["is_left"].astype(int),
"folios": g["Folio"].nunique(),
"sections": g["Section"].nunique(),
"lang_A": sums["is_A"].astype(int),
"lang_B": sums["is_B"].astype(int),
})
tab["right"] = tab["O11"] - tab["left"]
tab["lang_other"] = tab["O11"] - tab["lang_A"] - tab["lang_B"]
freq = valid["Word"].value_counts()
tab["C1"] = freq.reindex(tab.index).fillna(0).astype(int)
tab["R1"] = R1
tab["N"] = N
# Overlapping windows count once per hit, so O11 can exceed C1; clamp the
# derived cells at 0 so the table stays valid (C7).
tab["O12"] = R1 - tab["O11"]
tab["O21"] = (tab["C1"] - tab["O11"]).clip(lower=0)
tab["O22"] = (N - R1 - tab["O21"]).clip(lower=0)
tab["expected"] = R1 * tab["C1"] / N
scored = am.score(tab[["O11", "O12", "O21", "O22"]].astype(float),
measures=["log_likelihood", "conservative_log_ratio"])
tab["G2"] = scored["log_likelihood"].to_numpy()
tab["LRC"] = scored["conservative_log_ratio"].to_numpy()
with np.errstate(divide="ignore", invalid="ignore"):
tab["dp_wc"] = tab["O11"] / (tab["O11"] + tab["O12"]) - \
tab["O21"] / (tab["O21"] + tab["O22"]).replace(0, np.nan)
tab["dp_cw"] = tab["O11"] / (tab["O11"] + tab["O21"]) - \
tab["O12"] / (tab["O12"] + tab["O22"]).replace(0, np.nan)
tab[["dp_wc", "dp_cw"]] = tab[["dp_wc", "dp_cw"]].fillna(0.0)
if positional:
# E_pos: Ξ£ over window positions of p(collocate | that position's line-position class).
cls_tot = valid["LinePos"].value_counts()
cls_word = valid.groupby(["LinePos", "Word"]).size()
win_cls = rec["LinePos"].value_counts()
e_pos = pd.Series(0.0, index=tab.index)
for c, n_pos in win_cls.items():
p = cls_word.get(c, pd.Series(dtype=float)).reindex(tab.index).fillna(0) / cls_tot[c]
e_pos += n_pos * p
tab["E_pos"] = e_pos
with np.errstate(divide="ignore"):
tab["log_ratio_pos"] = np.log2(tab["O11"] / tab["E_pos"])
cols = cols + ["E_pos", "log_ratio_pos"]
tab = tab.rename_axis("collocate").reset_index()
# Collocates that are themselves hits: the word itself, or members of the pattern's family.
tab["in_family"] = (tab["collocate"].map(lambda w: bool(pattern.search(w))) if pattern is not None
else tab["collocate"] == word)
return tab[cols]
def collocates(view: View, word: str, window: int = 3, section=None, language=None,
exclude_adjacent: bool = False, certain_only: bool = False,
positional: bool = False, g2_min: float = G2_MIN, min_cooc: int = MIN_COOC,
min_freq: int = MIN_FREQ, pattern=None) -> pd.DataFrame:
"""Collocates passing C8, ranked by LRC (or positional log ratio), then GΒ², then alphabet.
With `pattern`, every token whose word matches is a hit and `word` is ignored (spec D, D7a).
"""
tab = collocate_table(view, word, window, section, language, exclude_adjacent,
certain_only, positional, pattern)
if tab.empty:
tab["dim"] = []
return tab
keep = ((tab["G2"] >= g2_min) & (tab["O11"] > tab["expected"])
& (tab["O11"] >= min_cooc) & (tab["C1"] >= min_freq))
tab = tab[keep].copy()
tab["dim"] = tab["folios"] < DIM_FOLIOS
# LRC is often 0 after Bonferroni correction, so GΒ² breaks ties before the alphabet (C8).
key = "log_ratio_pos" if positional else "LRC"
tab = tab.sort_values([key, "G2", "collocate"], ascending=[False, False, True], kind="stable")
return tab.reset_index(drop=True)
def robustness(views: dict[str, View], source: str, word: str, window: int = 3,
include_labels: bool = False, sources=("ZL", "IT", "RF"), **scope) -> pd.DataFrame:
"""For each collocate of `word` in `source`, whether it also passes C8 in each
transliteration's view with the same settings (C10)."""
base = collocates(views[view_key(source, include_labels)], word, window, **scope)
out = {source: set(base["collocate"])}
for s in sources:
if s in out:
continue
v = views.get(view_key(s, include_labels))
out[s] = set(collocates(v, word, window, **scope)["collocate"]) if v is not None else set()
return pd.DataFrame({s: [c in out[s] for c in base["collocate"]] for s in sources},
index=pd.Index(base["collocate"], name="collocate"))
def parameter_line(view: View, window: int, section=None, language=None,
exclude_adjacent=False, certain_only=False, positional=False,
pattern_label: str = "") -> str:
"""Collocation Parameters Notation summary of the active settings (C11, spec D AC15)."""
stat = "log2(O/E_pos)" if positional else "LRC"
span = f"L{window}–R{window}" if not exclude_adjacent else f"L{window}–L2, R2–R{window}"
lang = {"A": "A", "B": "B"}.get(language or "All", "A+B")
sec = "all sections" if not section or section == "All" else SECTION_NAMES.get(section, section)
parts = [stat, f"GΒ² β‰₯ {G2_MIN}", span, f"C β‰₯ {MIN_FREQ}", f"NC β‰₯ {MIN_COOC}", view.source,
"labels on" if view.include_labels else "labels off", sec, lang]
if exclude_adjacent:
parts.append("adjacent excluded")
if certain_only:
parts.append("certain readings only")
if positional:
parts.append("positional baseline")
if pattern_label:
parts.insert(0, f"pattern {pattern_label}")
return ", ".join(parts)
# ── Spec C: concordance ───────────────────────────────────────────────────────
def concordance(view: View, word: str, window: int = 3, section=None, language=None,
position=None, with_word=None, certain_only: bool = False,
sort: str = "ms", pattern=None, cluster=None) -> pd.DataFrame:
"""Keyword-in-context rows for every hit in scope (C17, C19, C20).
left/right are lists of (word, uncertain) to the line ends, nearest word last
on the left and first on the right.
"""
t = _scope(view, section, language).reset_index(drop=True)
cols = ["left", "keyword", "right", "Folio", "Line", "Section", "Language", "LinePos",
"UncertainBreak", "Alt", "Illegible", "LineId", "Order"]
if t.empty:
return pd.DataFrame(columns=cols)
words = t["Word"].to_numpy()
mask = _hits(t, word, pattern)
if certain_only:
mask &= ~t["Flagged"].to_numpy()
if position:
mask &= t["LinePos"].to_numpy() == position
hits = np.flatnonzero(mask)
if with_word:
_, hit_rows, pos_rows, _ = _window_pairs(t, word, window, False, False, pattern)
has = set(hit_rows[words[pos_rows] == with_word].tolist())
hits = np.array([h for h in hits if h in has], dtype=int)
line = t["LineId"].to_numpy()
flags = t["Flagged"].to_numpy()
first_row = {lid: r for r, lid in zip(np.flatnonzero(t["Idx"].to_numpy() == 0),
line[t["Idx"].to_numpy() == 0])}
rows = []
for h in hits:
lid = line[h]
r0 = first_row[lid]
r1 = r0 + int(t.at[h, "LineLen"])
rows.append({
"left": [(words[k], bool(flags[k])) for k in range(r0, h)],
"keyword": words[h],
"right": [(words[k], bool(flags[k])) for k in range(h + 1, r1)],
"Folio": t.at[h, "Folio"], "Line": int(t.at[h, "Line"]),
"Section": t.at[h, "Section"], "Language": t.at[h, "Language"],
"LinePos": t.at[h, "LinePos"],
"UncertainBreak": bool(t.at[h, "UncertainBreak"]),
"Alt": str(t.at[h, "Alt"] or ""),
"Illegible": bool(t.at[h, "Illegible"]),
"LineId": int(lid), "Order": int(t.at[h, "Order"]),
})
out = pd.DataFrame(rows, columns=cols)
if cluster and not out.empty:
# cluster = (side, context words in reading order[, node]); the node is kept for patterns.
side, ctx = cluster[0], tuple(cluster[1])
node = cluster[2] if len(cluster) > 2 else None
n = len(ctx)
if side == "L":
part = out["left"].apply(lambda s: s[len(s) - n:] if len(s) >= n else [])
else:
part = out["right"].apply(lambda s: s[:n] if len(s) >= n else [])
keep = part.apply(lambda p: len(p) == n and tuple(w for w, _ in p) == ctx
and not (certain_only and any(f for _, f in p)))
if node:
keep &= out["keyword"] == node
out = out[keep]
if out.empty:
return out.reset_index(drop=True)
def k(seq, i):
return seq[i][0] if i < len(seq) else ""
if sort == "left":
for i in (1, 2, 3):
out[f"_k{i}"] = out["left"].apply(lambda s, i=i: k(s[::-1], i - 1))
out = out.sort_values(["_k1", "_k2", "_k3", "Order"], kind="stable")
elif sort == "right":
for i in (1, 2, 3):
out[f"_k{i}"] = out["right"].apply(lambda s, i=i: k(s, i - 1))
out = out.sort_values(["_k1", "_k2", "_k3", "Order"], kind="stable")
else:
out = out.sort_values("Order", kind="stable")
return out[cols].reset_index(drop=True)
def paginate(n_rows: int, page: int, size: int) -> tuple[int, int, str]:
"""Clamp a 0-based page to the rows that exist; return (start, end, heading) (C21)."""
if n_rows <= 0:
return 0, 0, "0 hits"
last = (n_rows - 1) // size
page = max(0, min(page, last))
start, end = page * size, min(n_rows, (page + 1) * size)
return start, end, f"{start + 1}–{end} of {n_rows} hits"
def neighbour_lines(view: View, folio: str, line: int):
"""Previous and next locus on the same page, any locus type (C18).
Returns (prev, next), each None or (LocusType, [words]).
"""
page = view.page_df[view.page_df["Folio"] == folio]
nums = sorted(page["Line"].unique())
if line not in nums:
return None, None
i = nums.index(line)
def get(n):
rows = page[page["Line"] == n].sort_values("Position")
return rows["LocusType"].iloc[0], rows["Word"].tolist()
prev = get(nums[i - 1]) if i > 0 else None
nxt = get(nums[i + 1]) if i < len(nums) - 1 else None
return prev, nxt
# ── Similar words ─────────────────────────────────────────────────────────────
def levenshtein(a: str, b: str) -> int:
if abs(len(a) - len(b)) > 4:
return 99
m, n = len(a), len(b)
dp = list(range(n + 1))
for i in range(1, m + 1):
prev, dp[0] = dp[:], i
for j in range(1, n + 1):
dp[j] = prev[j - 1] if a[i - 1] == b[j - 1] else 1 + min(prev[j], dp[j - 1], prev[j - 1])
return dp[n]
_VIEWS: dict[str, View] = {}
def register_views(views: dict[str, View]) -> None:
_VIEWS.clear()
_VIEWS.update(views)
similar_words.cache_clear()
@lru_cache(maxsize=4096)
def similar_words(key: str, word: str, k: int = 6) -> tuple[tuple[str, int], ...]:
"""Closest words by edit distance within a view, cached per (view, word) (AC13)."""
v = _VIEWS[key]
scored = [(w2, levenshtein(word, w2)) for w2 in v.all_words if w2 != word]
scored.sort(key=lambda x: (x[1], -v.global_freq.get(x[0], 0)))
return tuple(scored[:k])