PureOne's picture
Upload research package with Eve Uploader
d4bfea2 verified
Raw History Blame Contribute Delete
5.89 kB
"""Rebuild paper figures and a compact metric file from measured JSON outputs.
Requires matplotlib and numpy; the research algorithms themselves do not.
"""
from pathlib import Path
import json, statistics, hashlib
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap, BoundaryNorm
ROOT=Path(__file__).resolve().parent
main=json.loads((ROOT/'holdout_full/results.json').read_text())
bounded=json.loads((ROOT/'holdout_budget/results.json').read_text())
heap=json.loads((ROOT/'heap_holdout_full/results.json').read_text())
heap_bounded=json.loads((ROOT/'heap_holdout_budget/results.json').read_text())
def stats(xs):
return {'mean':statistics.mean(xs),'sd':statistics.stdev(xs),
'min':min(xs),'max':max(xs),'n':len(xs)}
metrics={}
for condition in ('structured','asymmetric','constant'):
records=[s for r in main['results']+heap['results'] if r['condition']==condition
for s in r['summaries']]
budget_records=[s for r in bounded['results']+heap_bounded['results']
if r['condition']==condition for s in r['summaries']]
methods={}
for name in sorted({s['method'] for s in records}):
rows=[s for s in records if s['method']==name]
bs=[s for s in budget_records if s['method']==name]
methods[name]={'work':stats([s['work'] for s in rows]),
'work_with_full_oracle':stats([s['total_with_shared_oracle'] for s in rows]),
'wall_ms':stats([s['wall_ns']/1e6 for s in rows]),
'fresh_correct':sum(s['fresh_correct'] for s in rows),
'wrong':sum(s['wrong'] for s in rows),
'budget_correct':sum(s['fresh_correct'] for s in bs),
'scalar_slots':stats([s['scalar_slots'] for s in rows])}
metrics[condition]=methods
palette={'recursive':'#146B75','fast':'#A45A32','best_first':'#617481'}
labels={'recursive':'Learned symmetry','fast':'Simple fast compiler','best_first':'Best-first heap'}
plt.rcParams.update({'font.family':'DejaVu Sans','font.size':10,
'axes.spines.top':False,'axes.spines.right':False,
'axes.labelcolor':'#283A45','text.color':'#283A45'})
fig,ax=plt.subplots(figsize=(8.2,4.0))
conditions=('structured','asymmetric','constant')
for j,name in enumerate(('recursive','fast','best_first')):
means=[metrics[c][name]['work']['mean']/1000 for c in conditions]
errs=[metrics[c][name]['work']['sd']/1000 for c in conditions]
x=np.arange(3)+(j-1)*.24
bars=ax.bar(x,means,yerr=errs,color=palette[name],label=labels[name],
width=.22,error_kw={'elinewidth':.8,'capsize':2})
for bar,val in zip(bars,means):
ax.text(bar.get_x()+bar.get_width()/2,val+27,f'{val:.1f}',
ha='center',va='bottom',fontsize=8.5)
ax.set_xticks(range(3),['Structured, nonconstant','Asymmetric control','Constant control'])
ax.set_ylabel('Charged algorithm work (thousands)')
ax.grid(axis='y',color='#DFE6E8',linewidth=.6);ax.set_axisbelow(True)
ax.set_ylim(0,1060)
ax.legend(loc='upper right',fontsize=9,frameon=False)
fig.tight_layout()
fig.savefig(ROOT/'work_comparison.pdf',bbox_inches='tight')
fig.savefig(ROOT/'work_comparison.png',dpi=160,bbox_inches='tight')
plt.close(fig)
fig,axes=plt.subplots(1,2,figsize=(8.2,3.6),gridspec_kw={'width_ratios':[1.2,1]})
arr=[]
for j in range(1,5):
K={a*(16//2**j) for a in range(2**j)}
arr.append([0 if x in K else 1 if x-16 in K else 2 for x in range(32)])
cmap=ListedColormap(['#CFE9E5','#DAA66F','#E4E8EB'])
im=axes[0].imshow(arr,cmap=cmap,norm=BoundaryNorm([-.5,.5,1.5,2.5],3),aspect='auto')
axes[0].set_yticks(range(4),['h1 (size 2)','h2 (size 4)',
'h3 (size 8)','h4 (size 16)'])
axes[0].set_xticks([0,7,16,23,31],['r0','r7','s','r7s','r15s'])
axes[0].axvline(15.5,color='white',linewidth=2)
axes[0].set_title('Distinct successor kernels',fontsize=11,fontweight='bold',pad=12)
axes[0].set_xlabel('Boundary elements of D16')
cbar=fig.colorbar(im,ax=axes[0],ticks=[0,1,2],orientation='horizontal',fraction=.12,pad=.22)
cbar.ax.set_xticklabels(['Cost 0','Cost c','Cost M'])
axes[1].plot([2,3,4],[512,256,128],marker='o',linewidth=2,color=palette['recursive'],label='Discover new symmetry')
axes[1].plot([2,3,4],[512,512,512],marker='s',linestyle='--',color=palette['fast'],label='Only inherit h1 symmetry')
axes[1].set_xticks([2,3,4],['Acquire h2','Acquire h3','Acquire h4'])
axes[1].set_ylabel('Candidate pairs (not full work)')
axes[1].set_ylim(0,600);axes[1].grid(axis='y',color='#DFE6E8',linewidth=.6)
axes[1].set_title('Future acquisition',fontsize=11,fontweight='bold',pad=12)
axes[1].legend(fontsize=8,loc='lower left')
fig.tight_layout(w_pad=2)
fig.savefig(ROOT/'recursive_ladder.pdf',bbox_inches='tight')
fig.savefig(ROOT/'recursive_ladder.png',dpi=160,bbox_inches='tight')
plt.close(fig)
metrics['_provenance']={'source_sha256':main['source_sha256'],
'heap_sha256':heap['source_sha256'],
'seeds':list(range(101,121)),
'scope':'Means and sample SDs of actual instrumented runs. Full oracle work reported separately.'}
(ROOT/'paper_metrics.json').write_text(json.dumps(metrics,indent=2))
print('Figures and paper_metrics.json built from verified measured files.')
for condition in ('structured','asymmetric','constant'):
best=min(('fast','best_first','dense','sequential'),key=lambda n:metrics[condition][n]['work']['mean'])
a=metrics[condition]['recursive']['work']['mean'];b=metrics[condition][best]['work']['mean']
print(condition,'best simple',best,'ratio baseline/proposed',b/a,
'ratio incl full oracle',metrics[condition][best]['work_with_full_oracle']['mean']/metrics[condition]['recursive']['work_with_full_oracle']['mean'])