"""Make standalone scientific figures from the registered analysis outputs."""
import pathlib,json,math,argparse,numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.ticker import ScalarFormatter,NullFormatter
ap=argparse.ArgumentParser();ap.add_argument('--root');a=ap.parse_args();root=pathlib.Path(a.root) if a.root else pathlib.Path(__file__).resolve().parents[1];out=root/'results';r=json.loads((out/'R.json').read_text());records=r['association_summaries'];plt.rcParams.update({'font.family':'DejaVu Sans','font.size':10,'axes.spines.top':False,'axes.spines.right':False,'axes.labelcolor':'#263746','text.color':'#263746','axes.edgecolor':'#aeb8bf','savefig.facecolor':'white','figure.facecolor':'white'})
primary=[x for x in records if x['dataset']=='IAVGC_EUR' and x['role'] in ['primary','secondary']]
fig,ax=plt.subplots(figsize=(8.6,3.7));y=np.arange(len(primary))[::-1]
for pos,x in zip(y,primary):
 if x['available']:
  lo,hi=x['or_ci95'];value=x['odds_ratio'];color='#14686d' if x['role']=='primary' else '#875b38';ax.errorbar(value,pos,xerr=[[value-lo],[hi-value]],fmt='o',color=color,capsize=3,ms=6)
  ax.text(2.02,pos,'%.3f (%.3f–%.3f)'%(value,lo,hi),va='center',fontsize=9)
 else:ax.text(.51,pos,'Unavailable in primary source',va='center',fontsize=9,color='#727e88');ax.text(2.02,pos,'—',va='center',fontsize=9)
ax.axvline(1,color='#89959d',ls='--',lw=1);ax.set_yticks(y,[x['protein']+('  primary' if x['role']=='primary' else '') for x in primary]);ax.set_xscale('log');ax.set_xlim(.5,2);ax.set_xticks([.5,.75,1,1.5,2]);ax.xaxis.set_major_formatter(ScalarFormatter());ax.xaxis.set_minor_formatter(NullFormatter());ax.set_xlabel('Clinical aortic-stenosis odds ratio per specified coding allele');ax.set_ylim(-.6,3.65);ax.set_title('European-ancestry clinical aortic stenosis',loc='left',fontweight='bold',pad=16);ax.text(2.02,3.6,'OR (95% CI)',fontsize=9,fontweight='bold');fig.subplots_adjust(left=.16,right=.70,bottom=.23,top=.83);fig.text(.16,.035,'Source: IAVGC 2025. Intervals are marginal; rare-allele tests retain the prespecified three-test family.',fontsize=8,color='#697782');fig.savefig(out/'figure1-clinical.png',dpi=200);plt.close(fig)
# Raw un-MTAG imaging only: all registered cells, including missing variants.
traits=[('Kany_valve_area','Aortic valve area'),('Kany_peak_velocity','Peak velocity'),('Kany_mean_gradient','Mean gradient')]
fig,axes=plt.subplots(1,3,figsize=(10.2,4.2),sharey=True);names=['E354Q','R190Q','E288G','R101H']
for ax,(ds,label) in zip(axes,traits):
 xs=[x for x in records if x['dataset']==ds and x['role'] in ['primary','secondary']]
 for k,name in enumerate(names):
  y=3-k;match=next((x for x in xs if x['protein']==name),None)
  if match and match['available']:
   b=match['beta'];lo,hi=match['beta_ci95'];ax.errorbar(b,y,xerr=[[b-lo],[hi-b]],fmt='o',color='#14686d',capsize=3,ms=5)
  else:ax.text(0,y,'unavailable',ha='center',va='center',color='#8b969e',fontsize=8)
 ax.axvline(0,ls='--',color='#89959d',lw=1);ax.set_yticks(range(4),names[::-1]);ax.set_title(label,fontsize=11,fontweight='bold');ax.set_xlabel('Effect per coding allele\n(inverse-normal residual SD)');ax.grid(axis='x',alpha=.12);ax.set_ylim(-.6,3.7)
 observed=[x for x in xs if x['available']]
 extent=max([.035]+[abs(v) for x in observed for v in x['beta_ci95']]);ax.set_xlim(-extent*1.25,extent*1.25)
fig.suptitle('Original quantitative valve-trait associations',x=.06,ha='left',fontweight='bold',fontsize=13);fig.subplots_adjust(left=.09,right=.97,bottom=.27,top=.80,wspace=.24);fig.text(.09,.055,'All four fixed variants × three traits form one 12-test family. Points have marginal 95% intervals.\nMRI traits are correlated; these estimates are not independent replications or effects in physical units.',fontsize=8,color='#697782');fig.savefig(out/'figure3-imaging.png',dpi=200);plt.close(fig)
# Regional context is descriptive, not an additional locus discovery exercise.
region=json.loads((out/'regional-context.json').read_text());x=np.array([v['position']/1e6 for v in region]);y=np.array([-math.log10(max(v['p_source'],1e-300)) for v in region]);fig,ax=plt.subplots(figsize=(9,3.7));ax.scatter(x,y,s=5,color='#91a5ad',alpha=.55,linewidths=0,rasterized=True)
for pos,label,col,offset in [(44.908684,'APOE','#875b38',0),(45.678134,'GIPR E354Q','#14686d',0),(45.687010,'SNRPD2','#3c4857',1)]:
 ax.axvline(pos,color=col,lw=1,alpha=.8)
 ax.text(pos,max(y)*(.91 if not offset else .72),label,rotation=90,va='top',ha='right' if not offset else 'left',color=col,fontsize=8)
ax.axhline(-math.log10(5e-8),color='#9aa5ad',ls=':',lw=.9);ax.set_xlabel('Chromosome 19 position (GRCh38, Mb)');ax.set_ylabel('−log10(source P)');ax.set_title('Regional clinical-AS association context',loc='left',fontweight='bold');ax.set_xlim(44.668207,46.683722);fig.subplots_adjust(left=.1,right=.97,bottom=.24,top=.86);fig.text(.1,.04,'Complete numeric interval from the CRC-verified European source; proximity does not assign a signal to a gene.',fontsize=8,color='#697782');fig.savefig(out/'figure2-regional.png',dpi=200);plt.close(fig)
# Common-allele source consistency; deliberately no pooled row.
order=['IAVGC_EUR','IAVGC_ALL','IAVGC_female','IAVGC_male','IAVGC_AFR','IAVGC_EAS','IAVGC_SAS','FinnGen_R13_operated'];labels=['IAVGC European (primary)','IAVGC multi-ancestry','IAVGC female','IAVGC male','IAVGC African ancestry','IAVGC East Asian ancestry','IAVGC South Asian ancestry','FinnGen operated-AS endpoint']
fig,ax=plt.subplots(figsize=(8.5,4.7))
for j,(ds,label) in enumerate(zip(order,labels)):
 q=next((v for v in records if v['dataset']==ds and v['variant']=='rs1800437'),None);pos=len(order)-1-j
 if q and q['available']:
  value=q['odds_ratio'];lo,hi=q['or_ci95'];ax.errorbar(value,pos,xerr=[[value-lo],[hi-value]],fmt='o',color='#14686d' if j==0 else '#718895',capsize=2,ms=5)
ax.set_yticks(range(len(order)),labels[::-1],fontsize=8.5);ax.axvline(1,ls='--',color='#89959d',lw=1);ax.set_xlabel('Odds ratio per Q354 allele (marginal 95% interval)');ax.set_xlim(.7,1.7);ax.set_title('Common-allele estimates across overlapping sources',loc='left',fontsize=12,fontweight='bold');fig.subplots_adjust(left=.31,right=.97,bottom=.22,top=.88);fig.text(.31,.045,'These rows overlap and are not independent replications.\nThe operated-AS endpoint also depends on intervention and access.',fontsize=8,color='#697782');fig.savefig(out/'figure4-source-consistency.png',dpi=200);plt.close(fig)
print('Wrote four figures from analysis outputs.')
