from pathlib import Path import json import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib.collections import LineCollection from recovery import joint_value ROOT=Path(__file__).resolve().parents[1] plt.rcParams.update({'font.family':'DejaVu Sans','font.size':10, 'axes.spines.top':False,'axes.spines.right':False}) C={'contract':'#167f89','conventional_joint':'#65a6aa','open_loop':'#919aa6', 'blueprint':'#5d748a','blind_reserve':'#c4a06a','sensor_only':'#9b7eaa', 'early_seal':'#bd736b','biased_reference':'#dd9b59'} def main(): out=ROOT/'figures';out.mkdir(exist_ok=True) summary=json.loads((ROOT/'results/summary.json').read_text()) fig,axs=plt.subplots(1,2,figsize=(10,4.5),layout='constrained',sharey=True) names=summary['methods'] labels=['Open loop','Blueprint repair','Blind reserve','Sensors only','Early seal', 'Response contracts','Conventional joint','Biased reference'] for ax,dim in zip(axs,[2,3]): rows=[x for x in summary['summaries'] if x['dimension']==dim] for i,row in enumerate(rows): ax.barh(i,row['functional_yield_count']/row['replicates'],color=C[row['method']]) ax.text(min(.98,row['functional_yield_count']/row['replicates']+.025),i, f"{row['functional_yield_count']}/{row['replicates']}",ha='right' if row['functional_yield_count']==32 else 'left',va='center', color='white' if row['functional_yield_count']==32 else '#26364a',fontsize=9) ax.set(xlim=(0,1.12),xlabel='Completed functional yield',title=f'{dim}-D passive network') ax.set_yticks(range(len(labels)),labels);ax.grid(axis='x',alpha=.18) axs[0].invert_yaxis() fig.savefig(out/'functional_yield.png',dpi=200);plt.close(fig) checks=json.loads((ROOT/'results/theorem_checks.json').read_text()) xy=checks['composition_examples'] fig,axs=plt.subplots(1,2,figsize=(10,4.1),layout='constrained') ax=axs[0] ax.scatter([x['largest_local_error'] for x in xy],[x['global_error'] for x in xy],s=12,c=[x['modules'] for x in xy],cmap='viridis',alpha=.6) ax.plot([0,.10],[0,.10],color='#b75850',lw=1.4,label='Proved upper envelope') ax.set(xlabel='Largest local relative error',ylabel='Global relative error',title='300 multiport composition checks',xlim=(0,.10),ylim=(0,.10));ax.legend(fontsize=8) ax=axs[1] bounds=np.array(checks['weighted_examples']);order=np.argsort(bounds[:,1]) ax.fill_between(np.arange(len(order)),bounds[order,0],bounds[order,2],color='#167f89',alpha=.2,label='Deterministic energy bounds') ax.plot(bounds[order,1],color='#203044',lw=1.3,label='Solved network response') ax.set(xlabel='Random instance, sorted by response',ylabel='Conductance / target',title='250 positive-conductance checks');ax.legend(fontsize=8) fig.savefig(out/'response_certificates.png',dpi=200);plt.close(fig) fig,axs=plt.subplots(1,3,figsize=(10,3.5),layout='constrained') for ax,meth,title in zip(axs,['open_loop','early_seal','contract'],['Open loop','Early seal','Response contracts']): d=np.load(ROOT/'results'/f'2d_{meth}.npz') x=d['coordinates'];segs=x[d['edges']] color=np.abs(d['final']/d['target']-1) lc=LineCollection(segs,array=color,cmap='magma_r',norm=plt.Normalize(0,.6),linewidths=3) ax.add_collection(lc);ax.scatter(x[:,0],x[:,1],s=8,c=np.where(d['sealed'],'#203044','#e29c3d')) ax.set(xlim=(-.4,7.4),ylim=(-.4,7.4),aspect='equal',title=title);ax.set_xticks([]);ax.set_yticks([]) fig.colorbar(lc,ax=axs,shrink=.75,label='Local relative response error') fig.savefig(out/'network_snapshots.png',dpi=200);plt.close(fig) fig,axs=plt.subplots(1,2,figsize=(10,4),layout='constrained') s=np.linspace(0,4,251);S,T=np.meshgrid(s,s) value=joint_value(S,T,12) im=axs[0].pcolormesh(S,T,value,cmap='RdBu',vmin=-4,vmax=4,shading='auto') axs[0].contour(S,T,value,levels=[0],colors=['black'],linewidths=1) axs[0].set(xlabel='Normalized diagnostic precision',ylabel='Normalized repair mobility',title='Matched service reserve (inherited EDD law)') fig.colorbar(im,ax=axs[0],label='Net reserve value') xs=np.linspace(0,1,301) for k in [0,.1,1,10]: axs[1].plot(xs,(k/(1+k))*xs,label=f'Control strength {k:g}') axs[1].set(xlabel='Fraction of error made observable',ylabel='Fraction of quadratic loss recoverable',title='Neither resource substitutes for the other');axs[1].legend(fontsize=8) fig.savefig(out/'matched_recovery.png',dpi=200);plt.close(fig) fig,axs=plt.subplots(1,2,figsize=(10,3.8),layout='constrained') L=np.logspace(-7,-2,250) for D,label in [(1e-9,'Small solute, D = 10⁻⁹ m²/s'),(1e-11,'Slow complex, D = 10⁻¹¹ m²/s')]: axs[0].loglog(L,L*L/D,label=label) axs[0].set(xlabel='Diffusion length (m)',ylabel='L² / D (s)',title='Diffusion time; no reaction included');axs[0].legend(fontsize=8) R=np.logspace(1,12,240);delta=.01 for a in [.2,.6,.9]: H=np.ceil(np.log(R/delta)/-np.log1p(-a)) axs[1].semilogx(R,H,label=f'Conditional acceptance a = {a}') axs[1].set(xlabel='Number of repairable modules',ylabel='Sufficient retry rounds',title='Logical rounds, excluding transport time');axs[1].legend(fontsize=8) for ax in axs:ax.grid(alpha=.18) fig.savefig(out/'scaling_limits.png',dpi=200);plt.close(fig) if __name__=='__main__':main()