"""Contemporary PCI versus CABG: source-linked, population-specific evidence synthesis.
Only original code and factual published extractions are used. No network access.
"""
import csv,json,math,pathlib,itertools
import numpy as np
from scipy import stats,optimize
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
ROOT=pathlib.Path(__file__).resolve().parents[1];OUT=ROOT/'results';OUT.mkdir(exist_ok=True)
load=lambda p:json.loads((ROOT/p).read_text())
P=load('data/analysis_parameters.json');TR=load('data/trials.json');Z=stats.norm.ppf(1-P['alpha']/2)
def readcsv(path):
 with (ROOT/path).open() as f:return list(csv.DictReader(f))
rows=readcsv('data/endpoints.csv');hr=readcsv('data/hr_effects.csv');old=readcsv('data/prior_meta_inputs.csv')
for r in rows+old:
 for k in ['events_pci','n_pci','events_cabg','n_cabg']:r[k]=int(r[k])
 if 'years' in r:r['years']=float(r['years'])
for r in hr:
 for k in ['years','hr_pci_over_cabg','ci_lower','ci_upper']:r[k]=float(r[k])
def write(name,x):
 (OUT/name).write_text(json.dumps(x,indent=2,ensure_ascii=False,allow_nan=False)+'\n')
def table(name,x):
 with (OUT/name).open('w',newline='') as f:
  w=csv.DictWriter(f,fieldnames=list(x[0]));w.writeheader();w.writerows(x)
def holm(ps):
 out=[None]*len(ps);running=0
 for rank,i in enumerate(sorted(range(len(ps)),key=lambda i:ps[i])):
  running=max(running,min(1.,ps[i]*(len(ps)-rank)));out[i]=running
 return out
def wilson(a,n):
 p=a/n;d=1+Z*Z/n;mid=(p+Z*Z/(2*n))/d;half=Z*math.sqrt(p*(1-p)/n+Z*Z/(4*n*n))/d
 return mid-half,mid+half
def rr(a,n,c,m):
 """Log-Wald RR; Newcombe-Wilson RD. Input is reported event fractions, not KM risk."""
 assert 0<=a<=n and 0<=c<=m and n>0 and m>0
 corr= any(v==0 for v in [a,c,n-a,m-c]);aa,nn,cc,mm=(a+.5,n+1,c+.5,m+1) if corr else (a,n,c,m)
 y=math.log(aa/nn)-math.log(cc/mm);v=1/aa-1/nn+1/cc-1/mm;se=math.sqrt(v);d=a/n-c/m
 l1,u1=wilson(a,n);l0,u0=wilson(c,m)
 return {'rr':math.exp(y),'lo':math.exp(y-Z*se),'hi':math.exp(y+Z*se),'log_effect':y,'variance':v,'p':float(2*stats.norm.sf(abs(y/se))),'fisher_p':float(stats.fisher_exact([[a,n-a],[c,m-c]]).pvalue),'pci_pct':100*a/n,'cabg_pct':100*c/m,'rd_pp':100*d,'rd_lo_pp':100*(d-math.sqrt((a/n-l1)**2+(u0-c/m)**2)),'rd_hi_pp':100*(d+math.sqrt((u1-a/n)**2+(c/m-l0)**2)),'continuity_correction':corr}
def meta(effects):
 """Paule-Mandel tau^2 and modified Hartung-Knapp: q is floored at 1.
 Conventional normal intervals are a sensitivity, not a replacement for few-trial uncertainty.
 """
 y=np.array([e['y'] for e in effects]);v=np.array([e['v'] for e in effects]);k=len(y)
 assert k>=1 and np.all(v>0)
 def weights(t):return 1/(v+t)
 def mean(t):return float(np.dot(weights(t),y)/sum(weights(t)))
 def Q(t):return float(np.dot(weights(t),(y-mean(t))**2))
 tau=0.
 if k>1 and Q(0)>k-1:
  hi=max(float(np.var(y)),float(max(v)),1e-6)
  while Q(hi)>k-1:hi*=2
  tau=float(optimize.brentq(lambda t:Q(t)-(k-1),0,hi,xtol=1e-14))
 mu=mean(tau);se=math.sqrt(1/sum(weights(tau)));q=Q(tau)/(k-1) if k>1 else 1.
 hkse=se*math.sqrt(max(1.,q));crit=float(stats.t.ppf(.975,k-1)) if k>1 else float(Z)
 Q0=Q(0);i2=max(0.,(Q0-k+1)/Q0) if k>1 and Q0>0 else 0.
 out={'k':k,'effect':math.exp(mu),'log_effect':mu,'se_normal':se,'tau2':tau,'Q':Q0,'I2':i2,'hk_scale':q,'hk_scale_modified':max(1.,q),'lo_normal':math.exp(mu-Z*se),'hi_normal':math.exp(mu+Z*se),'lo_mhk':math.exp(mu-crit*hkse),'hi_mhk':math.exp(mu+crit*hkse),'p_normal':float(2*stats.norm.sf(abs(mu/se))),'p_mhk':float(2*stats.t.sf(abs(mu/hkse),k-1)) if k>1 else float(2*stats.norm.sf(abs(mu/se))),'trials':[e['trial'] for e in effects]}
 out['leave_one_out']=[dict(trial_left_out=effects[j]['trial'],**meta([e for i,e in enumerate(effects) if i!=j])) for j in range(k)] if k>1 else []
 return out
# Individual published count and hazard estimates.
ests=[]
for r in rows:
 x=rr(r['events_pci'],r['n_pci'],r['events_cabg'],r['n_cabg']);ests.append(dict(r,**x))
hrs=[]
for r in hr:
 s=(math.log(r['ci_upper'])-math.log(r['ci_lower']))/(2*Z)
 hrs.append(dict(r,se=s,log_effect=math.log(r['hr_pci_over_cabg']),p_approx=float(2*stats.norm.sf(abs(math.log(r['hr_pci_over_cabg'])/s)))))
lookup=lambda trial,pop,ep:next(x for x in ests if x['trial']==trial and x['population']==pop and x['endpoint']==ep)
# Stable five-year count summaries: all outcomes that have compatible marginal counts in both studies.
# Revascularization definition differs, so its combined result is explicitly a sensitivity only.
metas={}
for ep in ['death','mi_all','stroke']:
 data=[lookup(t,'stable',ep) for t in ['FAME3','HREVS']]
 effects=[{'trial':x['trial'],'y':x['log_effect'],'v':x['variance']} for x in data]
 metas['stable_5y_'+ep]=dict(meta(effects),estimand='reported event fraction ratio; HREVS complete case; FAME3 randomized denominator',endpoint=ep)
metas['stable_5y_mi_all']['definition_note']='Procedural MI definitions differ between trials; this is a definition sensitivity, not a harmonized clinical effect.'
# Denominator and missing-outcome sensitivities for HREVS.
miss=[]
for ep in ['death','mi_all','stroke','repeat_clinical']:
 x=lookup('HREVS','stable',ep)
 for ap,ac,label in [(0,0,'none_of_lost_has_event'),(4,0,'all_lost_PCI_has_event_only'),(0,3,'all_lost_CABG_has_event_only'),(4,3,'all_lost_has_event')]:
  h=rr(x['events_pci']+ap,53,x['events_cabg']+ac,50);miss.append(dict(endpoint=ep,scenario=label,**h))
  if ep in ['death','mi_all','stroke']:
   f=lookup('FAME3','stable',ep);metas['stable_5y_'+ep+'_'+label]=dict(meta([{'trial':'FAME3','y':f['log_effect'],'v':f['variance']},{'trial':'HREVS','y':h['log_effect'],'v':h['variance']}]),estimand='reported fraction sensitivity; only HREVS missing outcomes varied; FAME3 censoring unresolved',endpoint=ep)
f=lookup('FAME3','stable','repeat_any');h=lookup('HREVS','stable','repeat_clinical');metas['stable_5y_repeat_definition_sensitivity']=dict(meta([{'trial':'FAME3','y':f['log_effect'],'v':f['variance']},{'trial':'HREVS','y':h['log_effect'],'v':h['variance']}]),estimand='definition sensitivity: any repeat versus clinically indicated repeat',endpoint='repeat')
# Compatible published HRs only, with horizon differences retained.
for ep in ['death','death_mi_stroke','repeat_any']:
 data=[x for x in hrs if x['population']=='all' and x['endpoint']==ep and x['trial'] in ['FAME3','BEST']]
 metas['mixed_horizon_all_HR_'+ep]=dict(meta([{'trial':x['trial'],'y':x['log_effect'],'v':x['se']**2} for x in data]),estimand='trial-average HRs; FAME3 five years versus BEST median 11.8 years; mixed presentations',endpoint=ep)
# Stable secondary tests on reported fractions, specified family before calculation in parameters.
family=['mi_all','mi_spontaneous','stroke','repeat_any','death_mi_stroke'];pvals=[lookup('FAME3','stable',e)['p'] for e in family];adjusted=holm(pvals)
secondary=[dict(endpoint=e,p_nominal=p,p_holm=q) for e,p,q in zip(family,pvals,adjusted)]
# Approximate interaction from disjoint presentation subgroup HRs; no IPD covariance/model recreation.
inter=[]
for ep in sorted({x['endpoint'] for x in hrs if x['trial']=='FAME3' and x['population']=='stable'}):
 a=next(x for x in hrs if x['trial']=='FAME3' and x['population']=='stable' and x['endpoint']==ep);b=next(x for x in hrs if x['trial']=='FAME3' and x['population']=='acs' and x['endpoint']==ep)
 d=a['log_effect']-b['log_effect'];se=math.hypot(a['se'],b['se']);inter.append({'endpoint':ep,'hr_ratio_stable_over_acs':math.exp(d),'lo':math.exp(d-Z*se),'hi':math.exp(d+Z*se),'p_nominal':float(2*stats.norm.sf(abs(d/se)))})
for x,q in zip(inter,holm([x['p_nominal'] for x in inter])):x['p_holm']=q
# Source-based MI-definition sensitivity; no individual-level overlap is inferred.
base=lookup('FAME3','stable','death_mi_stroke');alt=lookup('FAME3','stable','death_mi_stroke_scai')
def discordance(a,b,n):return {'min_discordant':abs(a-b),'max_discordant':min(a+b,2*n-a-b),'net_added':b-a}
definition={'primary_rr':base['rr'],'primary_rd_pp':base['rd_pp'],'alternative_rr':alt['rr'],'alternative_rd_pp':alt['rd_pp'],'rd_shift_pp':alt['rd_pp']-base['rd_pp'],'pci':discordance(base['events_pci'],alt['events_pci'],base['n_pci']),'cabg':discordance(base['events_cabg'],alt['events_cabg'],base['n_cabg']),'published_primary_HR':[1.39,.97,2.00],'published_alternative_HR':[.69,.50,.94],'figure4_non_acs_HR':[1.37,.96,1.97],'interpretation':'Reported composite comparison reverses direction under alternate procedural-MI criteria; no paired classification table, censoring-adjusted RD or mortality effect is identified by this arithmetic.'}
# Mortality thresholds are descriptive sensitivity benchmarks, not clinical NI margins.
precision=[]
for x in hrs:
 if x['endpoint']!='death':continue
 precision.append({'trial':x['trial'],'population':x['population'],'years':x['years'],'hr':x['hr_pci_over_cabg'],'lo':x['ci_lower'],'hi':x['ci_upper'],'excludes_thresholds':{str(t):x['ci_upper']<t for t in P['thresholds']}})
# Illustrative PH mapping for a specified control risk, not an estimated patient risk.
illustrations=[]
st=next(x for x in precision if x['trial']=='FAME3' and x['population']=='stable')
for b in P['baseline_mortality_illustrations']:
 risk=lambda h:1-(1-b)**h
 illustrations.append({'assumed_cabg_risk_pct':100*b,'pci_risk_point_pct':100*risk(st['hr']),'pci_risk_lo_pct':100*risk(st['lo']),'pci_risk_hi_pct':100*risk(st['hi']),'excess_point_pp':100*(risk(st['hr'])-b),'excess_lo_pp':100*(risk(st['lo'])-b),'excess_hi_pp':100*(risk(st['hi'])-b)})
# Schoenfeld event approximation for a future equal-allocation NI design under true HR=1.
stable_reported_deaths=sum(x['events_pci']+x['events_cabg'] for x in ests if x['population']=='stable' and x['endpoint']=='death')
design=[]
for margin in P['thresholds']:
 events=math.ceil(4*(stats.norm.ppf(.975)+stats.norm.ppf(P['power']))**2/math.log(margin)**2)
 design.append({'benchmark_HR_margin':margin,'events_required_approx':events,'participants_if_7pct_average_event_risk':math.ceil(events/.07),'fraction_of_events_in_stable_reports':stable_reported_deaths/events})
# Extreme bounds on stable mortality fractions using whole-trial FAME3 loss upper limits.
# Individual stable missingness is not reported; these are permissive worst-case, not a plausible imputation.
fame_missing={'pci_observed_fraction':32/456,'cabg_observed_fraction':30/454,'pci_max_fraction_if_all_33_global_losses_stable_and_dead':65/456,'cabg_max_fraction_if_all_47_global_losses_stable_and_dead':77/454,'rd_lower_pp':100*(32/456-77/454),'rd_upper_pp':100*(65/456-30/454),'RR_lower':(32/456)/(77/454),'RR_upper':(65/456)/(30/454),'note':'Only bounds from reported observed deaths and global losses; no independent-censoring assumption, no confidence interval. Not a Cox HR bound.'}
# Reproduce the published prior synthesis's Mantel-Haenszel calculations without endorsing eligibility.
def mh(rs):
 R=S=V=0.
 for x in rs:
  a,n,c,m=x['events_pci'],x['n_pci'],x['events_cabg'],x['n_cabg'];N=n+m;R+=a*m/N;S+=c*n/N;V+=(n*m*(a+c)-a*c*N)/N**2
 se=math.sqrt(V/(R*S));v=R/S
 return {'rr':v,'lo':math.exp(math.log(v)-Z*se),'hi':math.exp(math.log(v)+Z*se),'n_pci_sum':sum(x['n_pci'] for x in rs),'n_cabg_sum':sum(x['n_cabg'] for x in rs),'input_rows':len(rs)}
prior={}
for ep in sorted({x['endpoint'] for x in old}):prior[ep]={'as_plotted':mh([x for x in old if x['endpoint']==ep]),'independent_randomized_only':mh([x for x in old if x['endpoint']==ep and x['report']=='Fearon2025'])}
prior['design']={'plotted_report_rows':3,'independent_randomized_trials':1,'nested_FAME3_participants_reused':653,'observational_input_label':'DiGioia2020','known_critique':'doi:10.4330/wjc.v18.i3.115153','novelty':'Design error already identified by Tsai et al.; this computation reproduces the plotted inputs and displays a corrected trial-only comparison.'}
# Integrity checks use reported counts, and expose rather than conceal denominator/endpoint differences.
assert len(TR)==3 and sum(x['n_pci']+x['n_cabg'] for x in TR)==2483
assert sum(x['stable_n_pci']+x['stable_n_cabg'] for x in TR if x['stable_outcomes_available'])==1013
for pop in ['stable','acs','all']:
 for side in ['pci','cabg']:
  assert lookup('FAME3',pop,'mi_all')['events_'+side]==lookup('FAME3',pop,'mi_spontaneous')['events_'+side]+lookup('FAME3',pop,'mi_procedural')['events_'+side]
  assert lookup('FAME3',pop,'repeat_any')['events_'+side]==lookup('FAME3',pop,'repeat_pci')['events_'+side]+lookup('FAME3',pop,'repeat_cabg')['events_'+side]
R={'n_trials':len(TR),'n_randomized_relevant_arms':sum(t['n_pci']+t['n_cabg'] for t in TR),'n_trials_with_stable_outcomes':sum(t['stable_outcomes_available'] for t in TR),'n_stable_randomized':sum(t['stable_n_pci']+t['stable_n_cabg'] for t in TR if t['stable_outcomes_available']),'n_stable_deaths_reported':stable_reported_deaths,'n_fame_stable':910,'n_hrevs_stable':103,'n_hrevs_observed':96,'n_best_randomized':880,'stable_count_estimates':{x['trial']+'_'+x['endpoint']:x for x in ests if x['population']=='stable'},'published_HR':hrs,'meta':metas,'stable_secondary_tests':secondary,'presentation_interactions':inter,'definition_sensitivity':definition,'mortality_precision':precision,'PH_illustrations':illustrations,'future_design':design,'fame_missing_bounds':fame_missing,'prior_synthesis_reproduction':prior,'hrev_missing_sensitivity':miss,'unavailable_analyses':['Stable-only BEST endpoint meta-analysis: no endpoint-specific stable counts/HRs located in retrieved reports','Stable HR meta-analysis: HREVS supplies no endpoint-specific HR/CI','Spontaneous-MI meta-analysis restricted to stable cohorts: HREVS does not separate spontaneous from procedural MI','New death/MI/stroke composite in HREVS: participant overlap is unavailable','Patient-level ACS/CCS interaction with adjustment and competing risks: no IPD','Long-term stable-specific effect after five years: no usable stable-only report located in retrieved literature']}
write('R1.json',R);table('individual-count-estimates.csv',ests);table('published-hazard-ratios.csv',hrs);table('stable-secondary-tests.csv',secondary);table('presentation-interactions.csv',inter);table('future-design.csv',design)
# A small display object keeps every number in the paper bound to a declared result.
D={'n_trials':3,'n_total':2483,'n_stable':1013,'n_stable_observed_denominators':1006,'n_stable_deaths':71,'fame_n':910,'hrevs_n':103,'best_n':880,'death_hr':'1.03','death_hr_ci':'0.62 to 1.72','mi_hr':'2.62','mi_hr_ci':'1.41 to 4.88','repeat_hr':'2.17','repeat_hr_ci':'1.40 to 3.36','hard_hr':'1.39','hard_hr_ci':'0.97 to 2.00','scai_hr':'0.69','scai_hr_ci':'0.50 to 0.94','hrev_death_counts':'4/49 versus 5/47','hrev_loss':'4/53 versus 3/50','mi_counts':'36/456 versus 14/454','spont_counts':'30/456 versus 11/454','repeat_counts':'66/456 versus 30/454','death_counts':'32/456 versus 30/454','stroke_counts':'9/456 versus 12/454','hard_counts':'71/456 versus 52/454','scai_counts':'73/456 versus 96/454','repeat_cabg_counts':'11/456 versus 1/454','stable_pci_n':456,'stable_cabg_n':454,'prior_independent_rct':1,'prior_nested_n':653,'prior_report_rows':3,'definition_shift_pp':f'{definition["rd_shift_pp"]:.2f}','net_pci_added':2,'net_cabg_added':44,'hrevs_observed_n':96,'search_date':'2026-11-11'}
for ep in ['death','mi_all','mi_spontaneous','stroke','repeat_any','repeat_cabg','death_mi_stroke','death_mi_stroke_scai']:
 x=lookup('FAME3','stable',ep)
 D[ep]={'pci_pct':f'{x["pci_pct"]:.2f}','cabg_pct':f'{x["cabg_pct"]:.2f}','rr':f'{x["rr"]:.2f}','rr_ci':f'{x["lo"]:.2f} to {x["hi"]:.2f}','rd_pp':f'{x["rd_pp"]:+.2f}','rd_ci':f'{x["rd_lo_pp"]:+.2f} to {x["rd_hi_pp"]:+.2f}','p':f'{x["p"]:.4f}'}
for x in secondary:D[x['endpoint']]['p_holm']=f'{x["p_holm"]:.4f}'
for k in ['stable_5y_death','stable_5y_mi_all','stable_5y_stroke','mixed_horizon_all_HR_death']:
 x=metas[k];D[k]={'effect':f'{x["effect"]:.2f}','ci_normal':f'{x["lo_normal"]:.2f} to {x["hi_normal"]:.2f}','ci_mhk':f'{x["lo_mhk"]:.2f} to {x["hi_mhk"]:.2f}','tau2':f'{x["tau2"]:.3f}'}
D['required_deaths_margin_120']=design[1]['events_required_approx'];D['required_people_margin_120']=design[1]['participants_if_7pct_average_event_risk'];D['sevenpct_excess_hi_pp']=f'{illustrations[0]["excess_hi_pp"]:.2f}'
D['prior_death_as_plotted']=f'{prior["death"]["as_plotted"]["rr"]:.2f} ({prior["death"]["as_plotted"]["lo"]:.2f} to {prior["death"]["as_plotted"]["hi"]:.2f})';D['prior_death_trial_only']=f'{prior["death"]["independent_randomized_only"]["rr"]:.2f} ({prior["death"]["independent_randomized_only"]["lo"]:.2f} to {prior["death"]["independent_randomized_only"]["hi"]:.2f})'
D['interaction_mi']=next(x for x in inter if x['endpoint']=='mi_all');D['interaction_hard']=next(x for x in inter if x['endpoint']=='death_mi_stroke')
# Display values derive from the extracted data rather than a second manual transcription.
D.update(n_trials=R['n_trials'],n_total=R['n_randomized_relevant_arms'],n_stable=R['n_stable_randomized'],n_stable_deaths=stable_reported_deaths,n_stable_observed_denominators=sum(x['n_pci']+x['n_cabg'] for x in ests if x['population']=='stable' and x['endpoint']=='death'),ci_level=int(round(100*(1-P['alpha']))),years=5,threshold_pct=20)
for ep,label in [('death','death'),('mi_all','mi'),('repeat_any','repeat'),('death_mi_stroke','hard'),('death_mi_stroke_scai','scai')]:
 x=next(x for x in hrs if x['trial']=='FAME3' and x['population']=='stable' and x['endpoint']==ep)
 D[label+'_hr']=f'{x["hr_pci_over_cabg"]:.2f}';D[label+'_hr_ci']=f'{x["ci_lower"]:.2f} to {x["ci_upper"]:.2f}'
for ep,label in [('death','death'),('mi_all','mi'),('mi_spontaneous','spont'),('repeat_any','repeat'),('stroke','stroke'),('death_mi_stroke','hard'),('death_mi_stroke_scai','scai'),('repeat_cabg','repeat_cabg')]:
 x=lookup('FAME3','stable',ep);D[label+'_counts']=f'{x["events_pci"]}/{x["n_pci"]} versus {x["events_cabg"]}/{x["n_cabg"]}'
x=lookup('HREVS','stable','death');D['hrev_death_counts']=f'{x["events_pci"]}/{x["n_pci"]} versus {x["events_cabg"]}/{x["n_cabg"]}'
D['fame_total']=next(t['n_pci']+t['n_cabg'] for t in TR if t['trial']=='FAME3')
D['best_followup_years']=next(t['followup_years'] for t in TR if t['trial']=='BEST')
D['figure4_hr']='1.37 (0.96 to 1.97)'
D['stable_mi_interaction_p']=f'{D["interaction_mi"]["p_nominal"]:.3f}';D['stable_mi_interaction_p_holm']=f'{D["interaction_mi"]["p_holm"]:.3f}'
D['mortality_excludes_20pct']=st['hi']<1.20
D['primary_rd_pp']=f'{definition["primary_rd_pp"]:+.2f}';D['alternate_rd_pp']=f'{definition["alternative_rd_pp"]:+.2f}'
D['n_pubmed_ids']=load('data/searches.json')['unique_ids'];D['n_pubmed_articles']=len(readcsv('data/pubmed-screening.csv'));D['n_registry']=len(readcsv('data/registry-screening.csv'))
write('D.json',D)
plt.rcParams.update({'font.size':10,'axes.spines.top':False,'axes.spines.right':False,'figure.dpi':140,'savefig.dpi':180})
# Direct stable-presentation published HRs, not a mixed-presentation pooled forest.
fig,ax=plt.subplots(figsize=(8.8,5.2));spec=[('death','All-cause death'),('mi_all','All myocardial infarction'),('stroke','Stroke'),('repeat_any','Any repeat revascularization'),('death_mi_stroke','Death / MI / stroke (primary definition)'),('death_mi_stroke_scai','Death / MI / stroke (alternate SCAI)')]
for j,(ep,label) in enumerate(spec):
 x=next(x for x in hrs if x['trial']=='FAME3' and x['population']=='stable' and x['endpoint']==ep);h=x['hr_pci_over_cabg'];ax.errorbar(h,j,xerr=[[h-x['ci_lower']],[x['ci_upper']-h]],fmt='o',color='#164863',capsize=3);ax.text(5.4,j,f'{h:.2f} ({x["ci_lower"]:.2f}-{x["ci_upper"]:.2f})',va='center',fontsize=9)
ax.axvline(1,color='#8b8b8b',lw=1);ax.axvline(1.20,color='#a46a23',ls=':',lw=1);ax.set_xscale('log');ax.set_xlim(.25,10);ax.set_xticks([.25,.5,1,2,4]);ax.set_xticklabels(['0.25','0.5','1','2','4']);ax.set_yticks(range(len(spec)),[x[1] for x in spec]);ax.invert_yaxis();ax.set_xlabel('Published PCI / CABG hazard ratio (95% CI); >1 favors CABG');ax.set_title('Direct stable-presentation evidence: FAME 3 at five years',loc='left',fontweight='bold');fig.text(.02,.015,'Source: official appendix Table S9. CIs are marginal; alternate procedural-MI definition is a sensitivity.',fontsize=8);fig.tight_layout(rect=[0,.05,1,1]);fig.savefig(OUT/'stable-published-hr.png');plt.close(fig)
# Reported event fractions, not KM five-year cumulative incidence.
fig,ax=plt.subplots(figsize=(8.8,4.8));keys=['death','mi_spontaneous','mi_all','stroke','repeat_any'];labs=['Death','Spontaneous MI','All MI','Stroke','Any repeat procedure'];ys=np.arange(len(keys));pw=[lookup('FAME3','stable',x)['pci_pct'] for x in keys];cw=[lookup('FAME3','stable',x)['cabg_pct'] for x in keys]
ax.barh(ys-.18,pw,.34,label='PCI',color='#326e8f');ax.barh(ys+.18,cw,.34,label='CABG',color='#b1c9c0')
for j,(p,c) in enumerate(zip(pw,cw)):
 ax.text(p+.25,j-.18,f'{p:.1f}%',va='center',fontsize=9);ax.text(c+.25,j+.18,f'{c:.1f}%',va='center',fontsize=9)
ax.set_yticks(ys,labs);ax.invert_yaxis();ax.set_xlim(0,18);ax.set_xlabel('Reported participants with events / randomized participants (%)');ax.legend(frameon=False,loc='upper right');ax.set_title('Stable FAME 3 subgroup: outcomes remain distinct',loc='left',fontweight='bold');fig.text(.02,.015,'PCI n=456; CABG n=454. Crude reported fractions; censoring and competing risks are not adjusted.',fontsize=8);fig.tight_layout(rect=[0,.05,1,1]);fig.savefig(OUT/'stable-reported-fractions.png');plt.close(fig)
fig,ax=plt.subplots(figsize=(8.8,4.6));ys=np.arange(2);pc=[base['pci_pct'],alt['pci_pct']];cc=[base['cabg_pct'],alt['cabg_pct']]
ax.barh(ys-.18,pc,.34,label='PCI',color='#326e8f');ax.barh(ys+.18,cc,.34,label='CABG',color='#b1c9c0');ax.set_yticks(ys,['Primary procedural-MI criteria','Alternate SCAI procedural-MI criteria']);ax.invert_yaxis();ax.set_xlim(0,26);ax.set_xlabel('Death / MI / stroke: reported event fraction (%)');ax.legend(frameon=False,loc='upper right')
for j,(p,c) in enumerate(zip(pc,cc)):ax.text(p+.3,j-.18,f'{p:.1f}%',va='center');ax.text(c+.3,j+.18,f'{c:.1f}%',va='center')
ax.set_title('The composite direction changes with the infarction definition',loc='left',fontweight='bold');fig.text(.02,.015,'Same stable subgroup; no patient-level reclassification table is available. This is not a mortality comparison.',fontsize=8);fig.tight_layout(rect=[0,.06,1,1]);fig.savefig(OUT/'endpoint-definition-sensitivity.png');plt.close(fig)
# Compare ordinary and small-k adjusted mortality uncertainty, explicitly exploratory.
fig,ax=plt.subplots(figsize=(8.8,4.4));m=metas['stable_5y_death']
for j,(lo,hi,label,col) in enumerate([(m['lo_normal'],m['hi_normal'],'Conventional normal interval','#326e8f'),(m['lo_mhk'],m['hi_mhk'],'Modified Hartung-Knapp (two trials)','#a46a23')]):
 ax.errorbar(m['effect'],j,xerr=[[m['effect']-lo],[hi-m['effect']]],fmt='o',color=col,capsize=4);ax.text(.011,j+.17,f'{m["effect"]:.2f} ({lo:.2f}-{hi:.2f})',color=col,fontsize=9)
ax.axvline(1,color='gray',lw=1);ax.axvline(1.20,color='gray',ls=':',lw=1);ax.set_xscale('log');ax.set_xlim(.01,100);ax.set_xticks([.01,.1,1,10,100]);ax.set_xticklabels(['0.01','0.1','1','10','100']);ax.set_yticks([0,1],['Normal','Modified HK']);ax.invert_yaxis();ax.set_xlabel('PCI / CABG ratio of reported death fractions (95% CI)');ax.set_title('Mortality precision depends strongly on few-trial assumptions',loc='left',fontweight='bold');fig.text(.02,.015,'Exploratory count synthesis: FAME 3 randomized denominators; HREVS complete cases. No equivalence conclusion.',fontsize=8);fig.tight_layout(rect=[0,.08,1,1]);fig.savefig(OUT/'mortality-precision.png');plt.close(fig)
print(json.dumps({'stable_mortality':D['stable_5y_death'],'stable_mi':D['stable_5y_mi_all'],'secondary':secondary,'required_events_120':D['required_deaths_margin_120'],'prior_mortality':D['prior_death_as_plotted'],'trial_only':D['prior_death_trial_only']},indent=2))
