# decryption_complete: false # source: /Voynich/Voynich_CITATION_DICTIONARY_027_MISSING_LINK_reproducibility.zip!/run_citation_dictiona # stated_sha256: b3f0974a9656dbf1a175ca749b239c5455555f415b905eb191d48a0e45724384 # matches_stated_sha256: false # pdf_pages: 363-365 # note: The stated SHA-256 is the digest printed in the PDF. # The PDF page extract follows the form feed. decryption_complete stays false. run_citation_dictionary_027.py VOYNICH RESEARCH ARCHIVE | 16 SEPTEMBER 2026 1 run_citation_dictionary_027.py Source: /Voynich/Voynich_CITATION_DICTIONARY_027_MISSING_LINK_reproducibility.zip!/run_citation_dictiona ry_027.py SHA-256: b3f0974a9656dbf1a175ca749b239c5455555f415b905eb191d48a0e45724384 !/usr/bin/env python3 """CITATION-DICTIONARY-027: can label keys predict stable prose roles?""" import csv,hashlib,json,math,re from collections import Counter,defaultdict from pathlib import Path import numpy as np,pandas as pd ROOT=Path(__file__).resolve().parent;SRC=ROOT/'crosswalk002_inputs/Voynich_Line_Local_Reproducibility_20 26-08-22/data';OUT=ROOT/'citation_dictionary_027';OUT.mkdir(exist_ok=True);SEED=20260830;REPS=1000;ALPHA =8.0 TOK=re.compile(r'[A-Z][0-9a-z]');LOC=re.compile(r'^<([^>.]+)\.([^,>]+),([^>]*)>\s*(.*)$') L={'A2':'ENTRY','C2':'ENTRY','Q2':'ENTRY','A1':'REFERENCE','A3':'REFERENCE','B2':'DOMAIN_SELECTOR','U2': 'DOMAIN_SELECTOR','D1':'CONTEXT','K1':'CONTEXT','L1':'CONTEXT','Q1':'CONTEXT'} R={'B1':'CLOSURE','B3':'CLOSURE','A1':'HANDOFF','C1':'HANDOFF','C2':'HANDOFF','F1':'HANDOFF','F3':'HANDO FF','A2':'TERMINAL','B2':'TERMINAL'} def sec(f): n=int(re.search(r'\d+',f).group());return 'Herbal' if n<=66 else 'Astro' if n<=73 else 'Bio' if 75<=n<=84 else 'Pharma' if 87<=n<=102 else 'Recipes' if 103<=n<=116 else 'Other' def fold(f):return int(hashlib.sha256(('citation-dictionary-027|'+f).encode()).hexdigest()[:8],16)%5 def parse(path,wit,clusters): blocks=[];pending=None for s in path.read_text(errors='ignore').splitlines(): m=LOC.match(s) if m: pending=m.groups() if pending[3].strip():blocks.append(pending);pending=None elif pending and s and not s.startswith(('<','#')): a,b,c,d=pending;blocks.append((a,b,c,(d+' '+s).strip()));pending=None out=[] for fol,line,loc,txt in blocks: if not re.match(r'^f\d+[rv]$',fol):continue clean=re.sub(r'<[^>]*>','',txt).replace('[','').replace(']','').replace(':','');zz=[] for w in re.split(r'[.,\s]+',clean): a=TOK.findall(w) if len(a)>=3 and a[0] in L and a[-1] in R:zz.append(a) reg='LABEL' if 'L' in loc else 'PROSE' if 'P' in loc else 'OTHER';n=len(zz) for i,a in enumerate(zz): p=' '.join(a[1:-1]);nxt=' '.join(zz[i+1][1:-1]) if i+1'+R[a[-1]],'section':sec(fol),'position':'START' if i==0 else 'EARLY' if ratio<.34 else 'MID' if ratio<.67 else 'LATE','line_len':'SHORT' if n<=5 else 'MEDIUM' if n<=10 else 'LONG','next_cluster':clusters.get(nxt)}) return pd.DataFrame(out) def dist(rows,target,classes,prior): c=rows[target].value_counts().reindex(classes,fill_value=0).to_numpy(float);return (c+ALPHA*prior)/(c.sum()+ALPHA) def evaluate(z,w,target): classes=sorted(z[z.register=='PROSE'][target].dropna().unique());ci={c:i for i,c in enumerate(classes)};foldrows=[];cache=[] for k in range(5): tr=z[z.folio.map(fold)!=k];te=z[z.folio.map(fold)==k];lc=tr[tr.register=='LABEL'].payload.value_counts ();pc=tr[tr.register=='PROSE'].payload.value_counts();eligible=set(lc[lc>=2].index)&set(pc[pc>=8].index) ;trp=tr[(tr.register=='PROSE')&tr.payload.isin(eligible)&tr[target].notna()];tep=te[(te.register=='PROSE ')&te.payload.isin(eligible)&te[target].notna()].reset_index(drop=True) globalp=trp[target].value_counts().reindex(classes,fill_value=0).to_numpy(float)+1;globalp/=globalp.su m();ctrl=['section','position','line_len'] if target!='section' else ['position','line_len'];priors={} for key,g in trp.groupby(ctrl,observed=True):priors[key if isinstance(key,tuple) else (key,)]=dist(g,target,classes,globalp) pdict={} run_citation_dictionary_027.py VOYNICH RESEARCH ARCHIVE | 16 SEPTEMBER 2026 2 for p,g in trp.groupby('payload'): # Dictionary entry is shrunk toward the aggregate control-matched prior. base=np.mean([priors.get(tuple(r[c] for c in ctrl),globalp) for _,r in g.iterrows()],axis=0);pdict[p]=dist(g,target,classes,base) # A key can be frequent yet have no observed target (for example, only # line-final occurrences for next_cluster). It is ineligible for that target. tep=tep[tep.payload.isin(pdict)].reset_index(drop=True) y=np.array([ci[v] for v in tep[target]]);bp=np.vstack([priors.get(tuple(r[c] for c in ctrl),globalp) for _,r in tep.iterrows()]);dp=np.vstack([pdict.get(p,globalp) for p in tep.payload]);lb=float(-np.log2(bp[np.arange(len(y)),y]).mean());ld=float(-np.log2(dp[np.arange(len(y)), y]).mean());gain=lb-ld;foldrows.append({'witness':w,'target':target,'fold':k,'eligible_entries':len(elig ible),'test_n':len(y),'baseline_bits':lb,'dictionary_bits':ld,'gain_bits':gain}) # Precompute loss matrix for selection-aware held-out key permutation. payloads=sorted(pdict);pi={p:i for i,p in enumerate(payloads)};M=np.empty((len(y),len(payloads))) for j,p in enumerate(payloads):M[:,j]=-np.log2(pdict[p][y]);orig=np.array([pi[p] for p in tep.payload]);keys=(tep.position.astype(str)+'|'+tep.line_len.astype(str)+(('|'+tep.section.astype(str)) if target!='section' else '')).to_numpy();groups=[np.where(keys==q)[0] for q in np.unique(keys)];cache.append((M,orig,groups,lb,len(y))) rng=np.random.default_rng(SEED+len(target)+(w=='GC')*100);obs=np.average([r['gain_bits'] for r in foldrows],weights=[r['test_n'] for r in foldrows]);null=[] for rep in range(REPS): gs=[];ns=[] for M,orig,groups,lb,n in cache: q=orig.copy() for ix in groups: if len(ix)>1:q[ix]=q[rng.permutation(ix)] gs.append(lb-float(M[np.arange(n),q].mean()));ns.append(n) null.append(np.average(gs,weights=ns)) return foldrows,{'witness':w,'target':target,'gain_bits':float(obs),'positive_folds':sum(r['gain_bits'] >0 for r in foldrows),'events':sum(r['test_n'] for r in foldrows),'permutation_p':float((1+sum(x>=obs for x in null))/(REPS+1)),'null_mean':float(np.mean(null))} def ledger(z,w): lab=z[z.register=='LABEL'].groupby('payload').agg(label_n=('payload','size'),label_folios=('folio','nun ique'));pro=z[z.register=='PROSE'];rows=[] for p,a in lab[(lab.label_n>=3)&(lab.label_folios>=2)].iterrows(): q=pro[pro.payload==p] if len(q)<20 or q.folio.nunique()<5:continue def top(c): x=q[c].dropna().value_counts();return (x.index[0],int(x.iloc[0]),float(x.iloc[0]/x.sum())) if len(x) else ('NA',0,0.) s=top('section');f=top('frame');n=top('next_cluster');rows.append({'witness':w,'payload':p,'label_n':i nt(a.label_n),'label_folios':int(a.label_folios),'prose_n':len(q),'prose_folios':q.folio.nunique(),'top_ section':s[0],'section_share':s[2],'top_frame':f[0],'frame_share':f[2],'top_next_cluster':n[0],'next_clu ster_share':n[2]}) return rows def main(): cl=pd.read_csv(ROOT/'stem_context_geometry_004/consensus_clusters.csv');clusters=dict(zip(cl.payload,cl .cluster.astype(str)));allfold=[];summ=[];led=[] for w in ('ZL','GC'): z=parse(SRC/(w+'.txt'),w,clusters);led+=ledger(z,w) for target in ('section','frame','next_cluster'): fr,s=evaluate(z,w,target);allfold+=fr;summ.append(s) l=pd.DataFrame(led);p=l.pivot(index='payload',columns='witness');shared=[] if not p.empty: for payload,r in p.dropna().iterrows():shared.append({'payload':payload,'section_agree':int(r[('top_se ction','ZL')]==r[('top_section','GC')]),'frame_agree':int(r[('top_frame','ZL')]==r[('top_frame','GC')]), 'next_cluster_agree':int(r[('top_next_cluster','ZL')]==r[('top_next_cluster','GC')]),'zl_prose_n':int(r[ ('prose_n','ZL')]),'gc_prose_n':int(r[('prose_n','GC')])}) sd=pd.DataFrame(summ);# Holm correction across three targets per witness. sd['holm_p']=np.nan for w in ('ZL','GC'): ix=sd.index[sd.witness==w].tolist();order=sorted(ix,key=lambda i:sd.loc[i,'permutation_p']);vals=[] for rank,i in enumerate(order):vals.append(min(1.,sd.loc[i,'permutation_p']*(len(order)-rank))) vals=np.maximum.accumulate(vals) run_citation_dictionary_027.py VOYNICH RESEARCH ARCHIVE | 16 SEPTEMBER 2026 3 for i,v in zip(order,vals):sd.loc[i,'holm_p']=v passed=all(r.gain_bits>0 and r.positive_folds>=4 and r.holm_p<.05 for _,r in sd.iterrows());summary={'test':'CITATION-DICTIONARY-027','results':sd.to_dict('records'),'ledger_entries ':{'ZL':int(sum(r['witness']=='ZL' for r in led)),'GC':int(sum(r['witness']=='GC' for r in led)),'shared':len(shared)},'fully_concordant_shared_entries':int(sum(r['section_agree'] and r['frame_agree'] and r['next_cluster_agree'] for r in shared)),'replicated_pass':bool(passed),'boundary' :'Anonymous citation-key roles only; no plaintext or referent gloss.'} pd.DataFrame(allfold).to_csv(OUT/'heldout_folds.csv',index=False);sd.to_csv(OUT/'target_summary.csv',in dex=False);l.to_csv(OUT/'citation_ledger.csv',index=False);pd.DataFrame(shared).to_csv(OUT/'cross_witnes s_entries.csv',index=False);(OUT/'summary.json').write_text(json.dumps(summary,indent=2)) report=['# CITATION-DICTIONARY-027','',('**PASS**' if passed else '**FAIL / NOT PROMOTED**'),'', 'Label-selected payload cores were treated as citation keys. Their training-folio prose distributions predicted section/domain, outer procedural frame, and next anonymous payload cluster on untouched folios. ZL and GC were evaluated independently; 1,000 held-out key permutations and Holm correction covered all three targets.',''] for _,r in sd.iterrows():report += [f"## {r.witness} — {r.target}",'',f"- Gain: {r.gain_bits:+.6f} bits/event",f"- Positive folds: {int(r.positive_folds)}/5",f"- Events: {int(r.events)}",f"- Permutation p: {r.permutation_p:.6f}; Holm p: {r.holm_p:.6f}",''] report += ['## Dictionary','',f"- ZL entries: {summary['ledger_entries']['ZL']}",f"- GC entries: {summary['ledger_entries']['GC']}",f"- Shared entries: {summary['ledger_entries']['shared']}",f"- Fully concordant section + frame + next-cluster entries: {summary['fully_concordant_shared_entries']}",'','## Rule audit','',('A pass jointly strengthens CORE PRESERVATION and REGISTER SHIFT without adding a seventh rule.' if passed else 'The six-rule ledger remains unchanged. Citation-key coverage alone is not enough to promote a usable role dictionary.')];(OUT/'report.md').write_text('\n'.join(report));files =sorted(q for q in OUT.iterdir() if q.is_file() and q.name!='SHA256SUMS.txt');(OUT/'SHA256SUMS.txt').wri te_text('\n'.join(f'{hashlib.sha256(q.read_bytes()).hexdigest()} {q.name}' for q in files)+'\n');print(json.dumps(summary,indent=2)) if __name__=='__main__':main()