# decryption_complete: false # source: /Voynich/Voynich_Tests_024_025_reproducibility_bundles.zip!/Voynich_MEASURE_PHARMA_024_reproduci # stated_sha256: 5cfda23e5810e2985963d869e1908e7103a0057c042933f87ed037c3df5c57a3 # matches_stated_sha256: false # pdf_pages: 756-758 # note: The stated SHA-256 is the digest printed in the PDF. # The PDF page extract follows the form feed. decryption_complete stays false. measure_pharma_024.py VOYNICH RESEARCH ARCHIVE | 16 SEPTEMBER 2026 1 measure_pharma_024.py Source: /Voynich/Voynich_Tests_024_025_reproducibility_bundles.zip!/Voynich_MEASURE_PHARMA_024_reproduci bility.zip!/measure_pharma_024.py SHA-256: 5cfda23e5810e2985963d869e1908e7103a0057c042933f87ed037c3df5c57a3 !/usr/bin/env python3 """Prospective MEASURE->PHARMA structural-series test (audited test 024).""" from pathlib import Path import hashlib, json, re import numpy as np import pandas as pd from sklearn.compose import ColumnTransformer from sklearn.impute import SimpleImputer from sklearn.linear_model import LogisticRegression from sklearn.metrics import log_loss, roc_auc_score from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler ROOT=Path(__file__).resolve().parent IN=ROOT/'outer_scaffold_coverage_001/corpus_scaffold.csv' OUT=ROOT/'measure_pharma_024'; OUT.mkdir(exist_ok=True) SEED=20260829; RNG=np.random.default_rng(SEED) def section(f): m=re.match(r'f(\d+)',str(f)); n=int(m.group(1)) if m else -1 if 1<=n<=66:return 'Herbal' if 87<=n<=102:return 'Pharma' if 103<=n<=116:return 'Recipes' return 'Other' def line_features(g): g=g.sort_values('index'); n=len(g) payload=g.payload.fillna('').astype(str).tolist() frame=(g.left_function.fillna('UNRESOLVED').astype(str)+'|'+g.right_function.fillna('UNRESOLVED').as type(str)).tolist() exact=list(zip(frame,payload)); pc=pd.Series(payload).value_counts(); fc=pd.Series(frame).value_counts(); ec=pd.Series(exact).value_counts() samef=[]; step=[]; varying=[] for fr, q in g.assign(_f=frame).groupby('_f'): ps=q.payload.fillna('').astype(str).tolist() if len(ps)>=2 and len(set(ps))>=2: varying.append(len(ps)) for i in range(len(ps)): a=ps[i].split() for j in range(i+1,len(ps)): b=ps[j].split(); samef.append(1) step.append(int(len(a)==len(b) and sum(x!=y for x,y in zip(a,b))==1)) adjf=np.mean([frame[i]==frame[i-1] for i in range(1,n)]) if n>1 else 0 adjp=np.mean([payload[i]==payload[i-1] for i in range(1,n)]) if n>1 else 0 runs=[] if n: cur=1 for i in range(1,n): if frame[i]==frame[i-1]:cur+=1 else:runs.append(cur);cur=1 runs.append(cur) return { 'n_tokens':n,'resolved_rate':float(g.both_resolved.mean()), 'payload_repeat':1-len(pc)/n,'max_payload_mult':pc.max()/n, 'frame_repeat':1-len(fc)/n,'max_frame_mult':fc.max()/n, 'exact_repeat':1-len(ec)/n,'max_exact_mult':ec.max()/n, 'adjacent_frame':adjf,'adjacent_payload':adjp,'longest_frame_run':max(runs)/n, 'variable_frame_types':len(varying)/n,'variable_frame_mass':sum(varying)/n, 'single_atom_step_rate':float(np.mean(step)) if step else 0, 'has_bounded_series':int(bool(varying)), measure_pharma_024.py VOYNICH RESEARCH ARCHIVE | 16 SEPTEMBER 2026 2 } def folds(folios,k=5): fs=sorted(folios); rng=np.random.default_rng(SEED); rng.shuffle(fs) return {f:i%k for i,f in enumerate(fs)} BASE=['n_tokens','resolved_rate'] REP=['payload_repeat','max_payload_mult','frame_repeat','max_frame_mult','exact_repeat','max_exact_mult' ,'adjacent_frame','adjacent_payload','longest_frame_run'] SER=['variable_frame_types','variable_frame_mass','single_atom_step_rate','has_bounded_series'] def fit_eval(train,test,features): pipe=Pipeline([('imp',SimpleImputer()),('scale',StandardScaler()),('lr',LogisticRegression(C=.3,max_ iter=3000,class_weight='balanced',random_state=SEED))]) pipe.fit(train[features],train.y); p=pipe.predict_proba(test[features])[:,1] return p def fitted(train,features): pipe=Pipeline([('imp',SimpleImputer()),('scale',StandardScaler()),('lr',LogisticRegression(C=.3,max_ iter=3000,class_weight='balanced',random_state=SEED))]) return pipe.fit(train[features],train.y) def analyze(d,w): d=d[(d.witness==w)&d.section.isin(['Herbal','Pharma'])].copy(); d['y']=(d.section=='Pharma').astype(int) fmap=folds(d.folio.unique()); d['fold']=d.folio.map(fmap) rows=[]; preds=[] models={'BASE':BASE,'REPETITION':BASE+REP,'SERIES':BASE+SER,'FULL':BASE+REP+SER} for fold in range(5): tr=d[d.fold!=fold]; te=d[d.fold==fold] if te.y.nunique()<2: continue for name,feats in models.items(): p=fit_eval(tr,te,feats); ll=log_loss(te.y,p,labels=[0,1])/np.log(2); auc=roc_auc_score(te.y,p) rows.append({'witness':w,'fold':fold,'model':name,'n_test':len(te),'bits_logloss':ll,'auc':auc}) for ix,pp in zip(te.index,p): preds.append({'witness':w,'fold':fold,'model':name,'index':int(ix) ,'y':int(d.loc[ix,'y']),'p':float(pp)}) r=pd.DataFrame(rows); p=pd.DataFrame(preds) wide=r.pivot(index=['witness','fold'],columns='model',values='bits_logloss').reset_index() wide['gain_series_vs_base']=wide.BASE-wide.SERIES; wide['gain_full_vs_rep']=wide.REPETITION-wide.FUL L # Conditional test: shuffle series vectors among equal coarse line-length bins in each held-out set. observed=float(wide.gain_full_vs_rep.mean()); null=[] cached=[] for fold in sorted(d.fold.unique()): tr=d[d.fold!=fold]; te=d[d.fold==fold].copy() if te.y.nunique()<2:continue prep=fitted(tr,BASE+REP).predict_proba(te[BASE+REP])[:,1] llrep=log_loss(te.y,prep,labels=[0,1])/np.log(2) full_model=fitted(tr,BASE+REP+SER) bins=pd.cut(te.n_tokens,[-np.inf,3,5,8,12,np.inf],labels=False).to_numpy() cached.append((te,llrep,full_model,bins)) for b in range(1000): gains=[] for te0,llrep,full_model,bins in cached: te=te0.copy() for col in SER: vals=te[col].to_numpy().copy() for z in np.unique(bins): ii=np.where(bins==z)[0]; vals[ii]=vals[RNG.permutation(ii)] te[col]=vals pf=full_model.predict_proba(te[BASE+REP+SER])[:,1]; llf=log_loss(te.y,pf,labels=[0,1])/np.log(2) ; gains.append(llrep-llf) null.append(np.mean(gains)) pv=(1+sum(x>=observed for x in null))/(len(null)+1) return r,wide,p,{'witness':w,'observed_full_over_repetition_bits':observed,'permutation_p':pv,'null_ mean':float(np.mean(null)),'n_lines':len(d),'n_folios':d.folio.nunique(),'pharma_lines':int(d.y.sum())} measure_pharma_024.py VOYNICH RESEARCH ARCHIVE | 16 SEPTEMBER 2026 3 def main(): x=pd.read_csv(IN); x['section']=x.folio.map(section) feats=[] for keys,g in x.groupby(['witness','folio','line','section'],sort=False): z=line_features(g); z.update(dict(zip(['witness','folio','line','section'],keys))); feats.append(z) d=pd.DataFrame(feats); d.to_csv(OUT/'line_features.csv',index=False) allr=[];allw=[];allp=[];summ=[] for w in ['ZL','GC']: r,ww,p,s=analyze(d,w);allr.append(r);allw.append(ww);allp.append(p);summ.append(s) pd.concat(allr).to_csv(OUT/'fold_models.csv',index=False); pd.concat(allw).to_csv(OUT/'contrasts.csv', index=False); pd.concat(allp).to_csv(OUT/'predictions.csv',index=False) summary={'test':'MEASURE-PHARMA-024','seed':SEED,'frozen_gate':{'series_vs_base':'positive >=4/5 folds both witnesses','full_vs_repetition':'positive mean and permutation p<.05 both witnesses'},'results':summ} summary['pass']=all(s['observed_full_over_repetition_bits']>0 and s['permutation_p']<.05 for s in summ) (OUT/'summary.json').write_text(json.dumps(summary,indent=2)) c=pd.concat(allw); lines=['# MEASURE–PHARMA–024','', '## Outcome','',('**PASS**' if summary['pass'] else '**FAIL / NOT PROMOTED**'),'', 'This prospective test asked whether quantity-like structural series distinguish Pharma from same-range Herbal text after controlling ordinary repetition and line length. It did not assign meanings to glyphs or use illustrations.','', '## Results',''] for s in summ: q=c[c.witness==s['witness']]; lines += [f"### {s['witness']}",'',f"- Full over repetition: {s['observed_full_over_repetition_bits']:+.6f} bits/token-equivalent line log loss",f"- Conditional permutation p: {s['permutation_p']:.6f}",f"- Lines / folios: {s['n_lines']} / {s['n_folios']}",'',q.to_markdown(index=False,floatfmt='.6f'),''] lines += ['## Interpretation','', 'A pass would support a measurement-like structural layer, not a translation. A failure means the Libro MEASURE→Pharma page-level analogy has not generated a manuscript-level quantity signature. Ordinary repetition remains previously established structure and is not counted as new semantic evidence.','', '## Controls','', '- Primary contrast restricted to Herbal and Pharma; no diagrams or labels used.', '- ZL and GC analyzed independently.', '- Five folio-held-out folds.', '- Baseline controls line length and resolution.', '- Incremental gate charges ordinary repetition before testing variable-frame series.', '- 1,000 conditional permutations within held-out line-length bins.', '- No seventh recovery rule is added by this test.'] (OUT/'report.md').write_text('\n'.join(lines)) files=[p for p in OUT.iterdir() if p.is_file() and p.name!='SHA256SUMS.txt']; manifest='\n'.join(f"{hashlib.sha256(p.read_bytes()).hexdigest()} {p.name}" for p in sorted(files))+'\n'; (OUT/'SHA256SUMS.txt').write_text(manifest) print(json.dumps(summary,indent=2)) if __name__=='__main__':main()