#!/usr/bin/env python3 """Plot saved measurements only; never fabricates or reruns data.""" import os os.environ.setdefault('MPLCONFIGDIR','/tmp/mtusi-lab3-matplotlib') import json,statistics,csv from pathlib import Path import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt ROOT=Path(__file__).resolve().parents[1]; E=ROOT/'evidence' plt.rcParams.update({'font.family':'DejaVu Sans','font.size':10,'axes.spines.top':False,'axes.spines.right':False}) def read(name): return json.loads((E/name).read_text()) def grouped(rows,key,value): keys=sorted({r[key] for r in rows}) vals=[[r[value] for r in rows if r[key]==k] for k in keys] return keys,[statistics.mean(v) for v in vals],[statistics.stdev(v) if len(v)>1 else 0 for v in vals] def finish(fig,name): fig.tight_layout(); fig.savefig(E/(name+'.png'),dpi=180); fig.savefig(E/(name+'.svg')); plt.close(fig) rows=read('scaling.json') fig,axes=plt.subplots(1,2,figsize=(11,4)) for mode,label,color in [('fixed','Всего 1 CPU / 1 GiB','#2563eb'),('growing','0.5 CPU / 256 MiB на API','#ea580c')]: group=[r for r in rows if r['series']==mode] for ax,metric in zip(axes,['rps','p95_ms']): x,y,err=grouped(group,'replicas',metric); ax.errorbar(x,y,yerr=err,marker='o',capsize=4,label=label,color=color) for ax in axes: ax.set_xlabel('API-реплики'); ax.set_xticks([1,2,4]); ax.grid(alpha=.2) axes[0].set_ylabel('Успешные итерации / с'); axes[1].set_ylabel('p95, мс'); axes[0].legend(fontsize=8) fig.suptitle('Масштабирование: C=32, три повтора, ± выборочное σ') finish(fig,'scaling') rows=read('saturation.json'); fig,axes=plt.subplots(1,2,figsize=(11,4)) for ax,metric,label in zip(axes,['rps','p95_ms'],['Успешные итерации / с','p95, мс']): ax.plot([r['concurrency'] for r in rows],[r[metric] for r in rows],marker='o',color='#2563eb'); ax.set_xlabel('Concurrency'); ax.set_ylabel(label); ax.set_xscale('log',base=2); ax.set_xticks([1,4,16,64,128],labels=['1','4','16','64','128']); ax.grid(alpha=.2) fig.suptitle('Рост очередей: 4 API × 0.5 CPU / 256 MiB, PostgreSQL 1 CPU') finish(fig,'saturation') fig,axes=plt.subplots(1,2,figsize=(11,4)) for ax,name,c in zip(axes,['improvement.json','improvement-low.json'],[32,4]): rows=read(name) x,y,err=grouped(rows,'fast_membership','rps') ax.bar(['Полный Chat','Только членство'],y,yerr=err,capsize=5,color=['#94a3b8','#16a34a']) ax.set_ylabel('Успешные итерации / с'); ax.set_title(f'Concurrency {c}'); ax.grid(axis='y',alpha=.2) for i,v in enumerate(y): ax.text(i,v+max(err)+5,f'{v:.1f}',ha='center') fig.suptitle('A/B: один SELECT вместо двух, 4 API, три повтора') finish(fig,'improvement') rows=read('db-bottleneck.json'); fig,axes=plt.subplots(1,2,figsize=(11,4)) for db,color in [(.1,'#dc2626'),(1,'#16a34a')]: group=[r for r in rows if r['db_cpu']==db] for ax,metric in zip(axes,['rps','p95_ms']): x,y,err=grouped(group,'replicas',metric); ax.errorbar(x,y,yerr=err,marker='o',capsize=4,label=f'PostgreSQL: {db} CPU',color=color) for ax in axes: ax.set_xlabel('API-реплики (0.5 CPU / 256 MiB каждая)'); ax.set_xticks([1,2,4]); ax.grid(alpha=.2) axes[0].set_ylabel('Успешные итерации / с'); axes[1].set_ylabel('p95, мс'); axes[0].legend() fig.suptitle('Контролируемый предел общей БД: C=4, два повтора') finish(fig,'db-bottleneck') # Compact raw per-run table alongside the full JSON including container resource samples. with (E/'measurements.csv').open('w') as f: fields=['experiment','series','replicas','db_cpu','fast_membership','repeat','concurrency','elapsed','success','errors','rps','p50_ms','p95_ms','p99_ms'] writer=csv.DictWriter(f,fieldnames=fields,extrasaction='ignore'); writer.writeheader() for name in ['scaling','saturation','improvement','improvement-low','db-bottleneck']: for row in read(name+'.json'): writer.writerow(dict(row,experiment=name)) print('Four plots and raw per-run CSV generated from evidence JSON.')