"""Reproduce constructed teaching CSVs and 3840x2160 figures for readings 3–7.
Repo use: python generate-readings-3-7.py
Bundle use: python data/recompute.py (automatically selects that bundle).
Requires matplotlib and numpy. No experimental data are simulated as real measurements.
"""
from pathlib import Path
import csv, math, itertools, json, shutil
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.patches import Circle, Rectangle, FancyBboxPatch
SLUGS={3:'3-column-hardware',4:'4-surface-chemistry-and-selectivity',5:'5-column-screening-doe',6:'6-risk-optimization-modr',7:'7-control-strategy-lifecycle'}
HERE=Path(__file__).resolve()
if HERE.parent.name=='data':
    BASE=HERE.parent.parent.parent
    ONLY=int(HERE.parent.parent.name.split('-')[0])
else:
    BASE=HERE.parents[2]/'content/en/2026-lecture/8-nov2/2-method-development'
    ONLY=None
NAVY='#12314e'; TEAL='#007f91'; ORANGE='#d36725'
plt.rcParams.update({'font.family':'DejaVu Sans','font.size':14,'axes.spines.top':False,'axes.spines.right':False})
def write(b,name,rows):
    rows=list(rows)
    with (b/'data'/name).open('w',newline='') as f:
        w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)
def read(b,name):
    with (b/'data'/name).open() as f:return list(csv.DictReader(f))
def fig(title,subtitle):
    f=plt.figure(figsize=(16,9),dpi=240,facecolor='#fcfdfd')
    f.text(.055,.94,title,fontsize=24,fontweight='bold',color=NAVY)
    f.text(.055,.89,subtitle,fontsize=14,color=TEAL)
    f.text(.055,.035,'Compound X • constructed teaching example • not product data or a regulatory approval',fontsize=11,color='#526879')
    return f
def save(f,b,name):
    p=b/'images'/name;p.parent.mkdir(parents=True,exist_ok=True)
    f.canvas.draw()
    renderer=f.canvas.get_renderer()
    for t in f.findobj(matplotlib.text.Text):
        if t.get_visible() and t.get_text():
            q=t.get_window_extent(renderer)
            if q.x0 < -1 or q.y0 < -1 or q.x1 > 3841 or q.y1 > 2161:
                raise ValueError('Text outside image: '+repr(t.get_text()))
    f.savefig(p,dpi=240);plt.close(f)
def box(ax,x,y,w,h,text,color=TEAL,size=14):
    ax.add_patch(FancyBboxPatch((x,y),w,h,boxstyle='round,pad=0.012',facecolor='#eef5f7',edgecolor=color,lw=1.8))
    ax.text(x+w/2,y+h/2,text,ha='center',va='center',fontsize=size,color=NAVY)
def arrow(ax,a,b):ax.annotate('',xy=b,xytext=a,arrowprops=dict(arrowstyle='->',color=TEAL,lw=2))
def r3(b):
    rows=[]
    for label,L,d,dp,mode in [('reference',150,4.6,5,'reference'),('requested_constant_velocity',100,2.1,1.7,'constant_velocity'),('requested_reduced_velocity',100,2.1,1.7,'reduced_velocity'),('exact_constant_L_dp',51,2.1,1.7,'reduced_velocity')]:
        area=(d/4.6)**2; u=1 if mode in ['reference','constant_velocity'] else 5/dp
        F=area*u;vol=L/150*area; pressure=L/150*u*(5/dp)**2
        rows.append(dict(scenario=label,length_mm=L,internal_diameter_mm=d,particle_um=dp,L_over_dp=L*1000/dp,L_over_dp_relative=(L/dp)/(150/5),flow_mL_min=F,injection_uL=10*vol,gradient_min=20*vol/F,pressure_ratio=pressure,pressure_bar_if_reference_100=100*pressure,geometric_volume_ratio=vol))
    write(b,'scaling-example.csv',rows)
    particles=[dict(particle_um=dp,relative_N_at_equal_L_and_equal_reduced_plate_height=5/dp,relative_pressure_at_equal_L_velocity_viscosity=(5/dp)**2) for dp in [5,3.5,3,2.7,1.7]]
    write(b,'particle-comparison.csv',particles)
    rows=read(b,'scaling-example.csv'); particles=read(b,'particle-comparison.csv')
    f=fig('CHOOSE A PLATFORM THE RECEIVING LAB CAN RUN','Particle architecture, format and pressure are decisions made against the ATP.')
    ax=f.add_axes([.05,.32,.4,.5]);ax.set(xlim=(0,1),ylim=(0,1));ax.set_aspect('equal',adjustable='box');ax.axis('off')
    for x,label,core in [(.25,'Fully porous',False),(.75,'Superficially porous',True)]:
        ax.add_patch(Circle((x,.7),.17,facecolor='#a9d8df',edgecolor=NAVY,lw=2))
        if core:ax.add_patch(Circle((x,.7),.105,facecolor='#54738d',edgecolor=NAVY))
        for angle in range(0,360,30):
            q=math.radians(angle);ax.plot([x+.12*math.cos(q),x+.16*math.cos(q)],[.7+.12*math.sin(q),.7+.16*math.sin(q)],color='white',lw=2)
        ax.text(x,.43,label,ha='center',fontsize=14,color=NAVY)
    box(ax,.08,.05,.84,.21,'Porous shell shortens diffusion paths.\nArchitecture alone does not fix efficiency.\nCross-sections are schematic.',size=13)
    ax2=f.add_axes([.54,.35,.4,.45])
    pos=np.arange(len(particles));ax2.bar(pos-.17,[float(p['relative_N_at_equal_L_and_equal_reduced_plate_height']) for p in particles],width=.34,color=TEAL,label='Ideal N ratio')
    ax2.bar(pos+.17,[float(p['relative_pressure_at_equal_L_velocity_viscosity']) for p in particles],width=.34,color=ORANGE,label='Pressure ratio')
    ax2.set_xticks(pos,[p['particle_um'] for p in particles]);ax2.set_xlabel('Particle diameter (µm)');ax2.set_ylabel('Relative to 5 µm');ax2.legend(fontsize=11)
    ax2.set_title('Equal L and velocity; idealized comparison',fontsize=13)
    f.text(.07,.16,'150 × 4.6 mm, 5 µm  →  100 × 2.1 mm, 1.7 µm\nL/dp increases 1.961-fold; this is NOT constant L/dp.',fontsize=16,color=NAVY)
    f.text(.07,.085,'A true constant-L/dp comparison is 51 × 2.1 mm, 1.7 µm. See CSV for both flow-scaling conventions.',fontsize=12,color='#526879')
    save(f,b,'hardware/particle-format-pressure.png')
COLS=[('Column 1','C18 on hybrid support',1,.02,.05,.02,.1),('Column 2','Similar C18',.98,.03,.04,.025,.11),('Column 3','Phenyl-hexyl on hybrid support',.85,.22,.1,.12,.08),('Column 4','PFP on high-pH-stable support',.7,-.15,.25,.3,.2),('Column 5','Polar-embedded on high-pH-stable support',.65,.12,.4,.6,.03),('Column 6','C8',.8,.04,.06,.03,.12)]
W=np.array([12.5,100,30,143,83])
def fs(a,b):return float(np.linalg.norm(W*(np.array(a[2:])-np.array(b[2:]))))
def selected():
    candidates=list(itertools.combinations(range(6),4))
    return max(candidates,key=lambda ix:(min(fs(COLS[i],COLS[j]) for i,j in itertools.combinations(ix,2)),sum(fs(COLS[i],COLS[j]) for i,j in itertools.combinations(ix,2))))
def r4(b):
    ix=selected()
    write(b,'hsm-columns.csv',[dict(column=c[0],hypothetical_class=c[1],H=c[2],S_star=c[3],A=c[4],B=c[5],C=c[6],selected_for_screen=i in ix,high_pH_qualification='assumed for selected prototypes; verify actual specification') for i,c in enumerate(COLS)])
    matrix=np.array([[fs(a,c) for c in COLS] for a in COLS])
    write(b,'fs-matrix.csv',[dict(column=COLS[i][0],**{f'Fs_to_Column_{j+1}':matrix[i,j] for j in range(6)}) for i in range(6)])
    write(b,'subset-selection.csv',[dict(columns=';'.join(COLS[i][0] for i in comb),minimum_pairwise_Fs=min(fs(COLS[i],COLS[j]) for i,j in itertools.combinations(comb,2)),sum_pairwise_Fs=sum(fs(COLS[i],COLS[j]) for i,j in itertools.combinations(comb,2)),selected=comb==ix) for comb in itertools.combinations(range(6),4)])
    matrix=np.array([[float(row[f'Fs_to_Column_{j+1}']) for j in range(6)] for row in read(b,'fs-matrix.csv')])
    f=fig('CHOOSE COLUMNS BY THEIR INTERACTIONS','Hypothetical HSM descriptors → weighted distance → maximin screening set')
    ax=f.add_axes([.12,.24,.43,.54]);vals=np.array([[float(r[k]) for k in ['H','S_star','A','B','C']] for r in read(b,'hsm-columns.csv')])
    im=ax.imshow(vals,cmap='YlGnBu',aspect='auto',vmin=-.2,vmax=1)
    ax.set_xticks(range(5),['H\nHydrophobic','S*\nSteric','A\nH donor','B\nH acceptor','C\nCation exchange'],fontsize=11)
    ax.set_yticks(range(6),[c[0]+('  ★' if i in ix else '') for i,c in enumerate(COLS)],fontsize=12)
    for i in range(6):
        for j in range(5):ax.text(j,i,f'{vals[i,j]:.2f}',ha='center',va='center',color='white' if vals[i,j]>.55 else NAVY,fontsize=12)
    ax2=f.add_axes([.65,.24,.29,.54]);im2=ax2.imshow(matrix,cmap='magma',vmin=0,vmax=matrix.max())
    ax2.set_xticks(range(6),range(1,7));ax2.set_yticks(range(6),range(1,7));ax2.set_title('Pairwise Fs (full 5-D metric)',fontsize=13)
    for i in range(6):
        for j in range(6):ax2.text(j,i,f'{matrix[i,j]:.0f}',ha='center',va='center',fontsize=11,color='white' if matrix[i,j]<50 else 'black')
    f.text(.06,.13,'★ Selected: '+', '.join(COLS[i][0] for i in ix),fontsize=16,color=TEAL)
    f.text(.06,.08,'Classes are teaching associations, not measured product fingerprints. No 2-D projection is claimed to preserve orthogonality.',fontsize=12,color='#526879')
    save(f,b,'selectivity/selectivity-map.png')
def screen_rows():
    # Explicit invented response array, not a mechanistic prediction from HSM.
    mins={1:[.9,1.1,1.2,1.0,.6,.8],3:[1.1,1.3,2.2,1.9,1.4,1.5],4:[1.2,1.4,1.7,2.0,1.3,1.6],5:[1.0,1.2,1.6,1.8,.9,1.1]}
    rows=[]
    for ci in [i+1 for i in selected()]:
        for pi,ph in enumerate([2.7,4.8,10.]):
            for mi,mod in enumerate(['ACN','MeOH']):
                m=mins[ci][2*pi+mi];tail=round(1.15+.05*((ci+pi+mi)%5),2)
                kfirst=round(.45+.18*pi+.07*mi+.03*ci,2)
                if ci==1 and pi==2:kfirst=.3
                last=round(12+ci+pi+mi,2)
                critical=round(m+.15,2);peaks=7 if m>=1.5 else 6
                eligible=m>=1.5 and tail<=1.8 and kfirst>=.5 and peaks>=7
                score=round(100*(.7*min(m/2.5,1)+.2*(1-(tail-1)/.8)+.1*min(kfirst,1)),2) if eligible else 0
                rows.append(dict(condition_id=f'C{ci}-pH{ph:.1f}-{mod}',column=f'Column {ci}',aqueous_pH=ph,modifier=mod,temperature_C=40,gradient_min=10,cycle_min=20,peaks_detected=peaks,min_Rs=m,API_ImpB_Rs=critical,API_tailing=tail,apparent_k_first=kfirst,apparent_k_last=last,eligible=eligible,score=score))
    return rows
def r5(b):
    rows=screen_rows();write(b,'screening-results.csv',rows)
    design=[{k:r[k] for k in ['condition_id','column','aqueous_pH','modifier','temperature_C','gradient_min','cycle_min']} for r in rows]
    write(b,'screening-design.csv',design)
    seq=[];elapsed=0
    for block,(col,ph) in enumerate(itertools.product([f'Column {i+1}' for i in selected()],[2.7,4.8,10.]),1):
        for mod in (['ACN','MeOH'] if block%2 else ['MeOH','ACN']):
            cid=f'C{col.split()[-1]}-pH{ph:.1f}-{mod}'
            seq.append(dict(step=len(seq)+1,condition_id=cid,action='equilibrate and condition',duration_min=15));elapsed+=15
            for action in ['diluent blank','API plus known impurities','pooled stressed product','post-sample blank']:
                seq.append(dict(step=len(seq)+1,condition_id=cid,action=action,duration_min=20));elapsed+=20
    write(b,'screening-sequence.csv',seq)
    write(b,'screening-time-budget.csv',[dict(component='analytical_injections',count=96,minutes_each=20,total_min=1920),dict(component='condition_equilibration_minimum',count=24,minutes_each=15,total_min=360),dict(component='planned_minimum_total',count=1,minutes_each=elapsed,total_min=elapsed)])
    assert elapsed==2280
    plot_rows=[dict(column=q['column'],aqueous_pH=float(q['aqueous_pH']),modifier=q['modifier'],min_Rs=float(q['min_Rs'])) for q in read(b,'screening-results.csv')]
    f=fig('SCREEN SELECTIVITY WITH TRACEABLE PEAK IDENTITIES','24 constructed conditions • color = minimum Rs • gates applied before ranking')
    for panel,mod in enumerate(['ACN','MeOH']):
        ax=f.add_axes([.08+panel*.47,.27,.37,.49]);data=np.array([[next(r['min_Rs'] for r in plot_rows if r['column']==f'Column {i+1}' and r['aqueous_pH']==ph and r['modifier']==mod) for ph in [2.7,4.8,10.]] for i in selected()])
        im=ax.imshow(data,vmin=.5,vmax=2.5,cmap='YlGnBu',aspect='auto');ax.set_xticks(range(3),['pH 2.7','pH 4.8','pH 10.0']);ax.set_yticks(range(4),[f'Column {i+1}' for i in selected()]);ax.set_title(mod,fontsize=18,color=NAVY)
        for i,ci in enumerate(selected()):
            for j,ph in enumerate([2.7,4.8,10.]):
                txt=f'{data[i,j]:.2f}'
                if ci==2 and j==1 and mod=='ACN':txt+='\nPRIMARY'
                if ci==3 and j==1 and mod=='MeOH':txt+='\nBACK-UP*'
                ax.text(j,i,txt,ha='center',va='center',fontsize=12,color='white' if data[i,j]>1.7 else NAVY)
    f.text(.08,.16,'Primary: Column 3 / pH 4.8 / ACN. Back-up candidate: Column 4 / pH 4.8 / MeOH.',fontsize=15,color=TEAL)
    f.text(.08,.10,'*Different chemistry and modifier require bridging. Screening alone does not pre-qualify a replacement.',fontsize=12,color='#526879')
    save(f,b,'screening/screening-grid.png')
def design_matrix(x):
    x=np.asarray(x);a,c,d=x[:,0],x[:,1],x[:,2]
    return np.column_stack([np.ones(len(x)),a,c,d,a*c,a*d,c*d,a*a,c*c,d*d])
def optimization():
    design=[]
    for zero in range(3):
        other=[i for i in range(3) if i!=zero]
        for v in itertools.product([-1,1],repeat=2):
            p=[0.,0.,0.];p[other[0]]=v[0];p[other[1]]=v[1];design.append(p)
    design += [[0.,0.,0.]]*5
    x=np.array(design);beta=np.array([2.8,.12,.08,-.1,.08,-.1,.05,-.5,-.35,-.45])
    noise=np.array([.02,-.01,.01,-.02,-.02,.01,-.01,.02,.01,-.02,.02,-.01,-.04,-.02,0,.02,.04])
    y=design_matrix(x)@beta+noise
    fitted=np.linalg.lstsq(design_matrix(x),y,rcond=None)[0]
    residual=y-design_matrix(x)@fitted
    return x,y,fitted,residual
SIGMA=.12
Z95=1.6448536269514722
def mu_at(tg,T,ph,beta):return (design_matrix([[(tg-10)/2,(T-40)/10,(ph-4.8)/.2]])@beta).item()
def r6(b):
    x,y,beta,res=optimization()
    write(b,'optimization-design.csv',[dict(run=i+1,gradient_min=10+2*p[0],temperature_C=40+10*p[1],aqueous_pH=4.8+.2*p[2],x_gradient=p[0],x_temperature=p[1],x_pH=p[2],constructed_observed_Rs=y[i],fitted_Rs=y[i]-res[i],residual=res[i]) for i,p in enumerate(x)])
    terms=['intercept','x_gradient','x_temperature','x_pH','x_gradient_x_temperature','x_gradient_x_pH','x_temperature_x_pH','x_gradient_squared','x_temperature_squared','x_pH_squared']
    write(b,'model-coefficients.csv',[dict(term=t,fitted_coefficient=v) for t,v in zip(terms,beta)])
    rows=[]
    for ph in np.linspace(4.6,5,21):
        for tg in np.linspace(8,12,41):
            for T in np.linspace(30,50,41):
                mu=mu_at(tg,T,ph,beta);prob=.5*(1+math.erf((mu-2)/(SIGMA*math.sqrt(2))))
                rows.append(dict(gradient_min=round(tg,3),temperature_C=round(T,3),aqueous_pH=round(ph,3),predicted_mean_Rs=mu,assumed_total_predictive_SD=SIGMA,probability_Rs_ge_2=prob,inside_Box_Behnken_convex_hull=(abs((tg-10)/2)+abs((T-40)/10)+abs((ph-4.8)/.2)<=2+1e-9),passes_probability_0_95=(prob>=.95 and abs((tg-10)/2)+abs((T-40)/10)+abs((ph-4.8)/.2)<=2+1e-9)))
    write(b,'rs-model-grid.csv',rows)
    center=mu_at(10,40,4.8,beta)
    write(b,'model-summary.csv',[dict(design_runs=len(x),model_rank=np.linalg.matrix_rank(design_matrix(x)),residual_df=len(x)-10,residual_SD=float(np.sqrt(sum(res**2)/(len(x)-10))),assumed_total_predictive_SD=SIGMA,success_mean_threshold=2+Z95*SIGMA,setpoint_mean_Rs=center,setpoint_probability=.5*(1+math.erf((center-2)/(SIGMA*math.sqrt(2)))) )])
    rng=np.random.default_rng(20261102)
    write(b,'probability-audit.csv',[dict(location=label,predicted_mean_Rs=mean,assumed_SD=SIGMA,draws=100000,Monte_Carlo_success_fraction=float(np.mean(rng.normal(mean,SIGMA,100000)>=2))) for label,mean in [('setpoint',center),('probability_boundary',2+Z95*SIGMA)]])
    # Eight-run resolution-IV fractional factorial: D=ABC. Low/high are proposed challenges.
    robust=[]
    for i,(a,c,d) in enumerate(itertools.product([-1,1],repeat=3),1):
        e=a*c*d
        robust.append(dict(run=i,flow_mL_min=.3+.015*a,initial_B_percent=5+1*c,buffer_total_acetate_mM=10+1*d,wavelength_nm=254+2*e,A=a,B=c,C=d,D=e,generator='D=ABC; I=ABCD'))
    write(b,'robustness-design.csv',robust)
    factors=[('gradient_time',8,12,'quantitative model'),('temperature',30,50,'quantitative model'),('aqueous_pH',4.6,5,'quantitative model'),('flow',.285,.315,'fractional factorial'),('initial_B',4,6,'fractional factorial'),('buffer_total_acetate',9,11,'fractional factorial'),('wavelength',252,256,'fractional factorial')]
    write(b,'risk-register.csv',[dict(parameter=n,low=lo,high=hi,study=s,severity=5 if n in ['aqueous_pH','gradient_time'] else 4,occurrence=3,detectability=3,illustrative_RPN=(5 if n in ['aqueous_pH','gradient_time'] else 4)*9,decision='teaching priority; verify evidence, do not treat score as fact') for n,lo,hi,s in factors] + [dict(parameter=n,low='not numeric',high='not numeric',study=study,severity=5,occurrence=2,detectability=4,illustrative_RPN=40,decision='independent challenge; not hidden inside continuous response surface') for n,study in [('column_lot','three lots and relevant aging'),('sample_hold','timed fresh-versus-held recovery'),('instrument','receiving-lab bridge')]])
    # Plot fixed pH slice, directly read from computed grid.
    data=[r for r in read(b,'rs-model-grid.csv') if abs(float(r['aqueous_pH'])-4.8)<1e-8]
    z=np.array([float(r['predicted_mean_Rs']) for r in data]).reshape(41,41)
    prob=np.array([float(r['probability_Rs_ge_2']) for r in data]).reshape(41,41)
    xx,yy=np.meshgrid(np.linspace(30,50,41),np.linspace(8,12,41))
    f=fig('CHOOSE A SET POINT WITH ROOM TO VARY','Fitted teaching model at aqueous pH 4.8 • uncertainty assumption SD = 0.12 Rs')
    ax=f.add_axes([.08,.20,.68,.62]);im=ax.contourf(xx,yy,z,levels=np.linspace(1.6,3.1,16),cmap='YlGnBu',extend='both')
    ax.contour(xx,yy,z,levels=[2],colors=[ORANGE],linestyles='--',linewidths=2)
    ax.contour(xx,yy,prob,levels=[.95],colors=[NAVY],linewidths=3)
    ax.scatter([40],[10],marker='*',s=300,c='#ff9a32',edgecolor='white',zorder=5)
    ax.annotate('Set point: 10 min, 40 °C',xy=(40,10),xytext=(32,10.5),fontsize=14,color=NAVY,bbox=dict(facecolor='white',alpha=.85,edgecolor='none',pad=5),arrowprops=dict(arrowstyle='->',color=NAVY))
    ax.set(xlabel='Column temperature (°C)',ylabel='Gradient ramp time (min)',xticks=[30,35,40,45,50])
    cb=f.colorbar(im,cax=f.add_axes([.8,.20,.025,.62]));cb.set_label('Predicted critical-pair Rs')
    f.text(.08,.12,'Solid: P(Rs ≥ 2.0) = 0.95    Dashed: mean Rs = 2.0    ★ chosen set point',fontsize=13,color=NAVY)
    f.text(.08,.075,'One slice of a 3-D candidate region; other ATP responses and confirmation experiments are still required.',fontsize=12,color='#526879')
    save(f,b,'modr/rs-probability-contour.png')
EC_ROWS=[
('intended_purpose','Related substances in Compound X tablets at release and stability','candidate EC','A new purpose requires development/validation and regional dossier assessment'),
('measurement_principle','LC with UV quantitation and qualified impurity response corrections','candidate EC','Changing principle requires bridging and appropriate regulatory communication'),
('column_selectivity','Column 3 primary; Column 4 plus MeOH remains a back-up candidate','candidate EC or performance-based control if justified','Back-up not authorized by this exercise; assess approved dossier'),
('MODR','Candidate modeled region only: P(Rs>=2)>=0.95 within studied 8-12 min,30-50 C,pH4.6-5.0','proposed EC range only if justified and approved','Movement inside an approved region follows PQS; expansion requires regulatory communication'),
('gradient_setpoint','10 min ramp at 40 C and aqueous pH 4.8','supporting set point if approved region permits','Within approved region and controls: documented PQS adjustment; verify other responses'),
('flow','0.300 mL/min; proposed challenge 0.285-0.315','proposed fixed parameter pending robustness','No approved range inferred from challenge design'),
('UV_wavelength','254 nm; proposed challenge 252-256','candidate EC or supporting parameter according to justified dossier','Response factors and sensitivity must remain appropriate'),
('sample_preparation','Nominal 1.00 mg/mL API; extraction/filter/hold time not finalized','candidate EC for critical elements','No validated hold time or extraction recipe established'),
('SST','Proposed critical Rs>=2.0; tailing<=1.8; LOQ S/N>=10; threshold injection RSD<=3%','candidate EC/performance criteria','Changes assessed against approved criteria and regional reporting rules')]
def r7(b):
    write(b,'precision-budget.csv',[dict(total_RSD_percent=5,injection_RSD_percent=3,remaining_RSD_percent=math.sqrt(5**2-3**2),assumption='independent random contributions; excludes bias')])
    write(b,'established-conditions.csv',[dict(element=a,teaching_proposal=c,proposed_status=d,change_management=e) for a,c,d,e in EC_ROWS])
    sst=[('critical_pair_Rs','>=',2,'Separating threshold impurities from API; confirm bias at edge'),('API_tailing','<=',1.8,'Detect loss of peak shape; definition fixed'),('LOQ_signal_to_noise','>=',10,'Supporting diagnostic only; recovery and precision establish LOQ'),('threshold_standard_injection_RSD_percent','<=',3,'Six injections; isolates instrument component, not extraction')]
    write(b,'sst-proposal.csv',[dict(metric=a,operator=c,value=d,rationale=e) for a,c,d,e in sst])
    f=fig('THE PROCEDURE HAS A LIFE AFTER VALIDATION','The ATP stays connected to evidence, control, monitoring and change.')
    ax=f.add_axes([.05,.12,.9,.71]);ax.set(xlim=(0,1),ylim=(0,1));ax.axis('off')
    nodes=[(.05,.65,'ATP\nDefine the quality decision'),(.37,.65,'DEVELOP\nRisk • experiments • knowledge'),(.69,.65,'CONTROL & VALIDATE\nACS • SST • Q2 confirmation'),(.69,.15,'MONITOR\nTrend performance and signals'),(.37,.15,'ASSESS CHANGE\nBridge • approve • document'),(.05,.15,'REVISIT THE ATP\nNew degradant or intended use')]
    for x,y,t in nodes:box(ax,x,y,.24,.20,t,size=13)
    for a,c in [((.29,.75),(.37,.75)),((.61,.75),(.69,.75)),((.81,.65),(.81,.35)),((.69,.25),(.61,.25)),((.37,.25),(.29,.25)),((.17,.35),(.17,.65))]:arrow(ax,a,c)
    box(ax,.33,.42,.34,.13,'Knowledge management + quality system\nretain the reason for every decision',size=12)
    f.text(.06,.085,'A candidate MODR or screened back-up is not an approved operating permission.',fontsize=13,color=ORANGE)
    save(f,b,'lifecycle/method-lifecycle.png')

if __name__=='__main__':
    for n in ([ONLY] if ONLY else range(3,8)):
        b=BASE/SLUGS[n];(b/'data').mkdir(parents=True,exist_ok=True)
        globals()[f'r{n}'](b)
        if HERE.parent.name!='data':shutil.copyfile(HERE,b/'data/recompute.py')
        (b/'data/requirements-plot.txt').write_text('matplotlib==3.11.2\nnumpy==2.5.1\n')
        print('Generated',SLUGS[n])
    print('HSM selected:',[i+1 for i in selected()])
    print('Screen ranked:',[(r['condition_id'],r['score']) for r in sorted(screen_rows(),key=lambda r:r['score'],reverse=True)[:3]])
