matter-embryogenesis / baseline_v1 /src /make_figures.py
PureOne's picture
Release Matter Embryogenesis v3.0.0: theory, code, data and audit
52fc221 verified
Raw History Blame Contribute Delete
6.14 kB
from pathlib import Path
import json,math
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap,BoundaryNorm
from scipy.stats import beta
R=Path(__file__).resolve().parents[1];F=R/'figures';F.mkdir(exist_ok=True)
plt.rcParams.update({'font.size':11,'axes.titlesize':12,'axes.labelsize':11,
'figure.dpi':160,'savefig.dpi':210,'axes.spines.top':False,'axes.spines.right':False,
'font.family':'DejaVu Sans'})
blue='#186B8C';orange='#CF763C';grey='#8B929C';dark='#243344'
a=np.genfromtxt(R/'results/access_redundancy.csv',delimiter=',',names=True)
fig,axs=plt.subplots(1,2,figsize=(9,3.5))
axs[0].plot(a['b'],a['exponent'],color=orange,lw=2.4,label='Supply distance grows')
axs[0].plot(a['b'],a['channel_exponent'],color=blue,lw=2.4,label='Local supply maintained')
axs[0].set(xlabel='Redundant subcomponents b',ylabel='Reliability exponent E',title='Redundancy can starve repair',xlim=(0,1100),ylim=(0,190))
axs[0].axhline(math.log(1e6/.05),color=grey,ls='--',lw=1)
axs[0].text(570,19,'Example required exponent',fontsize=8,color=grey)
axs[0].legend(fontsize=10,loc='upper left')
axs[1].plot(a['b'],a['raw_error'],color=orange,lw=2.4,label='Conversion-inclusive error')
axs[1].axhline(.2,color=dark,ls='--',label='Assumed tolerance = 0.20')
axs[1].set(xlabel='Redundant subcomponents b',ylabel='Raw subcomponent error',title='Depletion closes the window',xlim=(0,1100),ylim=(0,.8))
axs[1].legend(fontsize=10)
fig.text(.5,.01,'Illustrative analytical model; no chemical rates or device tolerance were measured.',ha='center',fontsize=8,color=grey)
fig.tight_layout(rect=(0,.055,1,1));fig.savefig(F/'reliability_access.png');plt.close(fig)
cmap=ListedColormap(['#CA4560','#F0F1F2','#7387A2','#E2A844'])
norm=BoundaryNorm([-1.5,-.5,.5,1.5,2.5],4)
fig,axs=plt.subplots(2,3,figsize=(8.2,5.7))
for row,dim in enumerate([2,3]):
ref=np.load(R/f'results/snapshot_{dim}d_reference.npz')
no=np.load(R/f'results/snapshot_{dim}d_no_repair.npz')
vals=[ref['target'],ref['final'],no['final']]
for col,v in enumerate(vals):
if dim==3:v=v[:,:,v.shape[2]//2]
axs[row,col].imshow(v.T,origin='lower',cmap=cmap,norm=norm,interpolation='nearest')
axs[row,col].set_xticks([]);axs[row,col].set_yticks([])
if row==0:axs[row,col].set_title(['Target','Repair + delayed lock','No repair'][col])
if col==0:axs[row,col].set_ylabel('2-D device' if dim==2 else '3-D central slice')
fig.text(.5,.025,'Light: void / sacrificial role Blue: support role Gold: recruited phase',ha='center',fontsize=9)
fig.tight_layout(rect=(0,.055,1,1));fig.savefig(F/'growth_snapshots.png');plt.close(fig)
summary=json.loads((R/'results/growth_summary.json').read_text());labels=['reference','no_repair','early_lock','no_internal_supply','common_mode','conversion_damage']
short=['Reference','No repair','Early lock','Boundary\nsupply','Wrong\nreference','Conversion\ndamage']
fig,axs=plt.subplots(1,2,figsize=(8.2,4.1),gridspec_kw={'width_ratios':[1.3,1]},sharey=True)
x=np.arange(6)
short=['Reference','No repair','Early lock','Boundary supply','Wrong reference','Conversion damage']
for dim,color,offset in [(2,blue,-.18),(3,orange,.18)]:
vals=[next(r for r in summary if r['dim']==dim and r['case']==lab) for lab in labels]
axs[0].barh(x+offset,[v['material_fidelity_mean'] for v in vals],height=.34,color=color,label=f'{dim}-D',
xerr=[v['material_fidelity_sd'] for v in vals],capsize=2,error_kw={'lw':1})
axs[0].set_yticks(x,short,fontsize=10);axs[0].set_xlim(.7,1.005);axs[0].set_xlabel('Material fidelity');axs[0].set_title('Local repair improves labels');axs[0].legend(fontsize=10,loc='lower left')
vals=[next(r for r in summary if r['dim']==2 and r['case']==lab) for lab in labels]
axs[1].barh(x,[v['functional_passes'] for v in vals],color=[blue]+[grey]*5,height=.6)
axs[1].set_xlim(0,8.6);axs[1].set_xlabel('Functional passes / 8');axs[1].set_title('Function remains difficult')
axs[0].invert_yaxis()
fig.text(.5,.012,'Coarse stochastic model. Error bars: between-run SD; eight runs per condition.',ha='center',fontsize=9,color=grey)
fig.tight_layout(rect=(0,.075,1,1));fig.savefig(F/'ablation_results.png');plt.close(fig)
stress=json.loads((R/'results/transport_stress.json').read_text());fig,axs=plt.subplots(1,2,figsize=(8,3.5))
for i,spacing in enumerate([5,0]):
vals=[v for v in stress if v['config']['channel_spacing']==spacing]
for ax,key in zip(axs,['completed_fraction','material_fidelity']):
yy=np.array([v[key] for v in vals]);ax.bar(i,yy.mean(),color=[blue,orange][i],alpha=.8)
ax.scatter(i+np.linspace(-.1,.1,len(yy)),yy,color=dark,s=19,zorder=3)
for ax,title in zip(axs,['Completed fraction','Material fidelity']):
ax.set_xticks([0,1],['Internal feed planes','Boundary supply only'],fontsize=9)
ax.set_ylim(0,1.);ax.set_title(title);ax.axhline(1,color=grey,ls='--',lw=1)
fig.text(.5,.015,'Four runs each; both conditions fail to complete by the declared deadline.',ha='center',fontsize=8,color=grey)
fig.tight_layout(rect=(0,.075,1,1));fig.savefig(F/'transport_stress.png');plt.close(fig)
nums=json.loads((R/'results/numerical_summary.json').read_text());mc=nums['monte_carlo']
fig,ax=plt.subplots(figsize=(6.5,3.8));b=np.array([v['b'] for v in mc]);yy=np.array([v['empirical'] for v in mc])
lo=np.array([beta.ppf(.025,v['failures'],v['trials']-v['failures']+1) if v['failures'] else 0 for v in mc])
hi=np.array([beta.ppf(.975,v['failures']+1,v['trials']-v['failures']) if v['failures']<v['trials'] else 1 for v in mc])
ax.errorbar(b,yy,yerr=[yy-lo,hi-yy],fmt='o',color=orange,capsize=3,label='Monte Carlo, exact 95% interval')
ax.plot(b,[v['exact'] for v in mc],color=blue,label='Exact binomial tail')
ax.plot(b,[v['chernoff'] for v in mc],color=grey,ls='--',label='Chernoff upper bound')
ax.set_yscale('log');ax.set(xlabel='Redundancy b',ylabel='Module-failure probability',title='Numerical check of the restricted probability model')
ax.legend(fontsize=10);fig.tight_layout();fig.savefig(F/'binomial_check.png');plt.close(fig)
print('Saved five reproducible figures')