"""Reproduce the Week 11 predictive-modeling teaching CSVs and 3840x2160 PNGs.
Run from docs to regenerate all; a bundle's data/recompute.py regenerates only itself.
Requires Python 3, NumPy and Matplotlib. No values are experimental observations.

Reading 2 carries one synthetic NIR granule-moisture dataset through the development steps:
30 drying batches x 8 samples x 3 replicate scans, a Karl Fischer reference per sample,
a 6-batch held-out test set, and PLS1 (NIPALS) tuned by random-scan and batch-grouped
cross-validation. The other readings' figures reproduce the synthetic examples in the text.
"""
from pathlib import Path
import csv, math, shutil
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle

SLUGS={2:'2-from-question-to-prediction',3:'3-from-one-wavelength-to-spectrum',4:'4-where-the-measurement-lives',
       5:'5-from-prediction-to-control',6:'6-when-models-support-release',7:'7-a-model-has-a-lifecycle',
       8:'8-from-spectra-to-language',9:'9-one-disturbance-one-decision'}
HERE=Path(__file__).resolve()
ONLY=int(HERE.parent.parent.name.split('-')[0]) if HERE.parent.name=='data' else None
BASE=HERE.parent.parent.parent if ONLY else HERE.parents[2]/'content/en/2026-lecture/11-nov23'
NAVY='#15334e';TEAL='#007f91';ORANGE='#cc652b';GREY='#526879';GOLD='#b08a1e';PURPLE='#6a4c93';RED='#b23a48';LIGHT='#c9d3da'
plt.rcParams.update({'font.family':'DejaVu Sans','font.size':13,'axes.spines.top':False,'axes.spines.right':False})
SYNTH='Synthetic teaching data • not production data, a validated procedure or an acceptance criterion'

def r(x,n=4):return round(float(x),n)
def write(b,name,rows):
    rows=list(rows);(b/'data').mkdir(parents=True,exist_ok=True)
    with (b/'data'/name).open('w',newline='') as f:
        w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)
def figure(title,subtitle,footer=SYNTH):
    f=plt.figure(figsize=(16,9),dpi=240,facecolor='#fcfdfd')
    f.text(.06,.94,title,fontsize=23,fontweight='bold',color=NAVY)
    f.text(.06,.885,subtitle,fontsize=14,color=TEAL)
    f.text(.06,.035,footer,fontsize=11,color=GREY)
    return f
def in_view_ticks(f):
    """Drop automatic ticks outside the view limits; their hidden labels would trip the clip check."""
    for ax in f.axes:
        for axis,lim in [(ax.xaxis,ax.get_xlim()),(ax.yaxis,ax.get_ylim())]:
            if isinstance(axis.get_major_locator(),matplotlib.ticker.FixedLocator):continue
            lo,hi=min(lim),max(lim);axis.set_ticks([t for t in axis.get_majorticklocs() if lo<=t<=hi])
def save(f,b,name):
    p=b/'images'/name;p.parent.mkdir(parents=True,exist_ok=True)
    in_view_ticks(f);f.canvas.draw();rr=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(rr)
            if q.x0< -1 or q.y0< -1 or q.x1>3841 or q.y1>2161:raise ValueError('Clipped text: '+t.get_text())
    f.savefig(p,dpi=240);plt.close(f)

# ---------------------------------------------------------------- reading 2: one dataset through the steps
WL=np.arange(1100,2501,10)                      # nm, 141 variables
def band(c,wd):return np.exp(-0.5*((WL-c)/wd)**2)
BASE_SPEC=(0.30+0.10*(WL-1100)/1400+0.08*band(1210,40)+0.12*band(1730,45)+0.10*band(2100,60)
           +0.16*band(2310,45)+0.06*band(1590,50))  # excipient/API matrix, arbitrary absorbance units
WATER=0.022*band(1940,38)+0.008*band(1450,32)   # water bands, absorbance per % w/w at low water
W_SAT=8.0                                        # % w/w: the water response flattens as the bed gets wetter (assumed)
LOT=np.array([band(c,18) for c in np.linspace(1150,2450,14)[1:-1]])   # 12 narrow excipient-lot features
N_BATCH,N_SAMPLE,N_SCAN=30,8,3
KF_SD=0.08;MATCH_SD=0.10                         # % w/w: Karl Fischer repeatability; probe-to-sample mismatch
BATCH_BIAS_SD=0.10                               # % w/w: per-batch offset between probe zone and sampling point (assumed)
LOT_SD=0.003                                     # absorbance: lot-to-lot amplitude of the excipient features
SCAN_NOISE=0.0012
ENDPOINT=2.0                                     # % w/w, illustrative drying decision level
REQ=0.30                                         # % w/w, illustrative step-1 requirement: RMSEP below 3% w/w water
def water_spectrum(w):
    eff=W_SAT*(1-np.exp(-np.asarray(w)/W_SAT))  # saturating response: linear at low water, flatter when wet
    return np.outer(eff,WATER)
def snv(X):
    return (X-X.mean(1,keepdims=True))/X.std(1,keepdims=True)
def pls_fit(X,y,A):
    mx=X.mean(0);my=y.mean();E=X-mx;f=y-my;W=[];P=[];Q=[]
    for _ in range(A):
        w=E.T@f;w/=np.linalg.norm(w);t=E@w;tt=t@t;p=E.T@t/tt;q=f@t/tt
        E=E-np.outer(t,p);f=f-q*t;W.append(w);P.append(p);Q.append(q)
    W=np.array(W).T;P=np.array(P).T;Q=np.array(Q)
    coefs=[W[:,:a]@np.linalg.solve(P[:,:a].T@W[:,:a],Q[:a]) for a in range(1,A+1)]
    return mx,my,coefs
def pls_predict(model,X,a):
    mx,my,coefs=model;return (X-mx)@coefs[a-1]+my
def rmse(e):return float(np.sqrt(np.mean(np.square(e))))
def make_moisture_data():
    rng=np.random.default_rng(20131)          # seed: Applied Predictive Modeling, 2013
    rows=[];X=[]
    for bt in range(1,N_BATCH+1):
        w0=rng.uniform(7.5,9.0);k=rng.uniform(0.035,0.055);w_inf=rng.uniform(0.6,1.0)
        mult=rng.normal(1,0.06);off=rng.normal(0,0.03);slope=rng.normal(0,0.003)   # batch particle-size scatter
        lot=LOT.T@rng.normal(0,LOT_SD,len(LOT))                 # this batch's excipient-lot signature
        bias=rng.normal(0,BATCH_BIAS_SD)                         # this batch's probe-zone vs sampling-point offset
        times=np.sort(rng.choice(np.arange(0,70,2),N_SAMPLE,replace=False))   # samples spread over the drying curve
        for si,tm in enumerate(times,1):
            w_true=w_inf+(w0-w_inf)*math.exp(-k*tm)
            w_probe=w_true+bias+rng.normal(0,MATCH_SD)          # material the probe saw
            kf=round(w_true+rng.normal(0,KF_SD),2)               # reference reported to 0.01% w/w
            sm=mult*rng.normal(1,0.015)
            for sc in range(1,N_SCAN+1):
                spec=sm*(BASE_SPEC+lot+water_spectrum([w_probe])[0])+off+slope*(WL-1800)/700
                spec=spec+rng.normal(0,SCAN_NOISE,WL.size)+rng.normal(0,0.002)
                X.append(spec)
                rows.append(dict(batch=f'B{bt:02d}',sample=f'B{bt:02d}-S{si}',scan=sc,drying_time_min=int(tm),kf_water_pct_w_w=kf))
    return rows,np.array(X)
def r2(b):
    rows,X=make_moisture_data()
    y=np.array([z['kf_water_pct_w_w'] for z in rows]);batch=np.array([z['batch'] for z in rows]);sample=np.array([z['sample'] for z in rows])
    rng=np.random.default_rng(6)
    batches=sorted(set(batch));test_b=sorted(rng.choice(batches,6,replace=False))
    dev_b=[x for x in batches if x not in test_b];perm=rng.permutation(dev_b)
    fold_of={bb:i%4+1 for i,bb in enumerate(perm)}
    role=np.array(['test' if bb in test_b else f'development, fold {fold_of[bb]}' for bb in batch])
    dev=~np.isin(batch,test_b);Xs=snv(X)
    # spectra and reference table (the Week 12 notebook can start from these)
    (b/'data').mkdir(parents=True,exist_ok=True)
    with (b/'data'/'nir-moisture-spectra.csv').open('w',newline='') as f:
        w=csv.writer(f);w.writerow(['batch','sample','scan','drying_time_min','kf_water_pct_w_w','role']+[f'A_{x}nm' for x in WL])
        for z,ro,sp in zip(rows,role,X):w.writerow([z['batch'],z['sample'],z['scan'],z['drying_time_min'],f"{z['kf_water_pct_w_w']:.2f}",ro]+[f'{v:.5f}' for v in sp])
    # step 5: split plan
    write(b,'split-plan.csv',[dict(batch=bb,role='held-out test' if bb in test_b else 'development',grouped_cv_fold='' if bb in test_b else fold_of[bb]) for bb in batches])
    # steps 6-7: tuning curves
    A=12;Xd=Xs[dev];yd=y[dev];bd=batch[dev]
    full=pls_fit(Xd,yd,A);rmsec=[rmse(pls_predict(full,Xd,a)-yd) for a in range(1,A+1)]
    def cv(folds):
        pred=np.zeros((A,len(yd)))
        for k in sorted(set(folds)):
            tr=folds!=k;m=pls_fit(Xd[tr],yd[tr],A)
            for a in range(1,A+1):pred[a-1,~tr]=pls_predict(m,Xd[~tr],a)
        return [rmse(pred[a]-yd) for a in range(A)]
    rnd=np.random.default_rng(4).integers(1,5,len(yd))
    cv_random=cv(rnd);cv_group=cv(np.array([fold_of[x] for x in bd]))
    bench=[]
    for k in range(1,5):
        tr=np.array([fold_of[x]!=k for x in bd]);bench.append(yd[~tr]-yd[tr].mean())
    bench=rmse(np.concatenate(bench))
    best=int(np.argmin(cv_group))+1              # choice rule: minimum whole-batch RMSECV
    write(b,'tuning-curves.csv',[dict(latent_variables=a,RMSEC_pct_w_w=r(rmsec[a-1],3),RMSECV_random_scans_pct_w_w=r(cv_random[a-1],3),RMSECV_whole_batches_pct_w_w=r(cv_group[a-1],3),benchmark_predict_mean_pct_w_w=r(bench,3)) for a in range(1,A+1)])
    # steps 8-9: freeze, refit on development, test once
    model=pls_fit(Xd,yd,best);te=~dev;pt=pls_predict(model,Xs[te],best);yt=y[te]
    # one result per sample: mean of its three scans
    samp=sample[te];us=sorted(set(samp));ps=np.array([pt[samp==s].mean() for s in us]);ys=np.array([yt[samp==s][0] for s in us])
    bs=np.array([s.split('-')[0] for s in us]);err=ps-ys
    lo=ys<3.0;bmean=[float(err[bs==bb].mean()) for bb in test_b]
    stats=dict(latent_variables=best,test_batches=' '.join(test_b),test_samples=len(us),RMSEP_pct_w_w=r(rmse(err),3),bias_all_pct_w_w=r(err.mean(),3),
               RMSEP_below_3pct_pct_w_w=r(rmse(err[lo]),3),bias_below_3pct_pct_w_w=r(err[lo].mean(),3),samples_below_3pct=int(lo.sum()),
               RMSEP_3pct_and_above_pct_w_w=r(rmse(err[~lo]),3),bias_3pct_and_above_pct_w_w=r(err[~lo].mean(),3),
               RMSECV_whole_batches_at_choice=r(cv_group[best-1],3),RMSECV_random_scans_at_choice=r(cv_random[best-1],3),RMSEC_at_choice=r(rmsec[best-1],3),illustrative_requirement_RMSEP_below_3pct=REQ,batch_mean_errors=' '.join(f'{bb}:{v:+.3f}' for bb,v in zip(test_b,bmean)))
    write(b,'test-summary.csv',[stats])
    write(b,'test-predictions.csv',[dict(sample=s,batch=bb,kf_water_pct_w_w=f'{yy:.2f}',predicted_water_pct_w_w=r(pp,3),error_predicted_minus_reference=r(pp-yy,3)) for s,bb,yy,pp in zip(us,bs,ys,ps)])
    write(b,'simulation-assumptions.csv',[dict(quantity=q,value=v) for q,v in [
        ('batches x samples x scans',f'{N_BATCH} x {N_SAMPLE} x {N_SCAN}'),('wavelengths',f'{WL[0]}-{WL[-1]} nm every 10 nm'),
        ('drying curve','w = w_inf + (w0 - w_inf) exp(-k t); w0 7.5-9.0, k 0.035-0.055 /min, w_inf 0.6-1.0 % w/w'),
        ('water bands','1940 and 1450 nm; response 8(1 - exp(-w/8)) per % w/w, so it flattens as the bed gets wetter'),
        ('excipient lot','12 narrow bands, 1250-2350 nm, amplitude N(0, 0.003) per batch'),
        ('probe-zone vs sampling-point offset','N(0, 0.10) % w/w per batch'),
        ('batch scatter','multiplicative N(1, 0.06), offset N(0, 0.03), slope N(0, 0.02)'),
        ('Karl Fischer repeatability SD',f'{KF_SD} % w/w, reported to 0.01'),('probe-to-sample mismatch SD',f'{MATCH_SD} % w/w'),
        ('scan noise SD',f'{SCAN_NOISE} absorbance units'),('preprocessing','SNV per spectrum; mean-centring fitted inside each fold'),
        ('model','PLS1 (NIPALS), 1-12 latent variables; choice = minimum whole-batch RMSECV'),('illustrative endpoint',f'{ENDPOINT} % w/w'),('illustrative step-1 requirement',f'RMSEP <= {REQ} % w/w for samples below 3% w/w'),('seeds','20131 data; 6 split; 4 random-scan folds')]])

    # Figure A: steps 2-3, X and Y
    f=figure('STEPS 2–3: EVERY SPECTRUM NEEDS A MATCHED REFERENCE','Synthetic NIR spectra (X), each coloured by the Karl Fischer water (Y) of the sample it was paired with. Right: one batch, all 24 scans.')
    one=batch==batches[0];cm=matplotlib.colormaps['viridis_r'];norm=matplotlib.colors.Normalize(0.5,9)
    five=np.isin(batch,batches[:5])&(np.array([z['scan'] for z in rows])==1)
    ax=f.add_axes([.07,.17,.40,.60])
    for sp,yy in zip(X[five],y[five]):ax.plot(WL,sp,color=cm(norm(yy)),lw=1.0)
    ax.set(xlabel='Wavelength (nm)',ylabel='Absorbance (arbitrary units)',xlim=(1100,2500))
    ax.set_title('Raw, 5 batches: scatter shifts whole spectra',fontsize=14,color=NAVY,loc='left')
    a2=f.add_axes([.56,.17,.33,.60]);reg=(WL>=1840)&(WL<=2020)
    for sp,yy in zip(Xs[one],y[one]):a2.plot(WL[reg],sp[reg],color=cm(norm(yy)),lw=1.4)
    a2.axvline(1940,color=GREY,ls=':');a2.text(1944,a2.get_ylim()[1],'water band\n1940 nm',fontsize=10,color=GREY,ha='left',va='top')
    a2.set(xlabel='Wavelength (nm)',ylabel='SNV absorbance',xlim=(1840,2020))
    a2.set_title('After SNV, one batch: the water band carries Y',fontsize=14,color=NAVY,loc='left')
    cb=f.colorbar(matplotlib.cm.ScalarMappable(norm=norm,cmap=cm),cax=f.add_axes([.91,.17,.012,.60]));cb.set_label('Karl Fischer water (% w/w)')
    save(f,b,'workflow/x-and-y.png')

    # Figure B: step 5, the split
    f=figure('STEP 5: SPLIT THE WAY THE MODEL WILL BE USED','30 synthetic drying batches. Each column is a batch, each cell one of its 24 scans (8 samples x 3 replicate scans).')
    order=test_b+[x for x in sorted(dev_b,key=lambda z:fold_of[z])]
    fold_col={1:'#2f8fa0',2:'#7fb9c4',3:'#3e6f8f',4:'#9cc2d6'}
    for k,(ttl,mode) in enumerate([('Batch-grouped: whole batches held out (test set and four development folds)','group'),('Random scans: replicate scans of one sample land on both sides','random')]):
        ax=f.add_axes([.07,.57-k*.36,.86,.24]);ax.set_xlim(0,30);ax.set_ylim(0,24);ax.axis('off')
        ax.set_title(ttl,fontsize=14,color=NAVY,loc='left')
        rr=np.random.default_rng(4)
        for i,bb in enumerate(order):
            for j in range(24):
                if mode=='group':c=ORANGE if bb in test_b else fold_col[fold_of[bb]]
                else:c=fold_col[int(rr.integers(1,5))]
                ax.add_patch(Rectangle((i+.06,j+.06),.88,.88,color=c,lw=0))
            ax.text(i+.5,-.9,bb,fontsize=7.5,ha='center',va='top',color=GREY,rotation=90)
    f.text(.07,.105,'Orange: 6 held-out test batches, untouched until step 9.   Blues: assessment folds.',fontsize=12,color=NAVY)
    f.text(.07,.075,f'Same development data, two ways to cross-validate: at {best} latent variables, RMSECV = {cv_random[best-1]:.2f}% w/w with random scans and {cv_group[best-1]:.2f}% w/w with whole batches.',fontsize=12,color=NAVY)
    save(f,b,'workflow/batch-split.png')

    # Figure C: steps 6-7, tuning
    f=figure('STEPS 6–7: TUNE ON HONEST RESAMPLING','PLS on SNV spectra, mean-centring refitted inside every fold. Fit error always falls; only whole-batch cross-validation shows when to stop.')
    ax=f.add_axes([.08,.17,.58,.60]);aa=np.arange(1,A+1)
    ax.plot(aa,rmsec,marker='o',color=GREY,lw=2.2,label='RMSEC: error on the calibration data itself')
    ax.plot(aa,cv_random,marker='s',color=ORANGE,lw=2.4,label='RMSECV, random scans (leaks replicates)')
    ax.plot(aa,cv_group,marker='D',color=TEAL,lw=2.6,label='RMSECV, whole batches held out')
    ax.axvline(best,color=NAVY,ls=':');ax.text(best+.15,0.02,f'chosen: {best}',fontsize=11,color=NAVY,va='bottom')
    ax.set(xlabel='PLS latent variables',ylabel='Root-mean-square error (% w/w)',xticks=aa,ylim=(0,max(rmsec[0],cv_group[0],cv_random[0])*1.35))
    ax.legend(fontsize=11,loc='upper right')
    f.text(.72,.70,'Read the gap',fontsize=15,fontweight='bold',color=NAVY)
    f.text(.72,.40,f'Benchmark, predicting the\ntraining mean: {bench:.2f}% w/w.\n\nAt {best} latent variables:\n\nRMSEC          {rmsec[best-1]:.2f}% w/w\nrandom scans  {cv_random[best-1]:.2f}% w/w\nwhole batches {cv_group[best-1]:.2f}% w/w\n\nThe untouched test set\n(step 9) gave {stats["RMSEP_pct_w_w"]:.2f}% w/w.\nOnly the whole-batch\nestimate saw it coming.',fontsize=12,color=NAVY,family='DejaVu Sans Mono',va='bottom')
    save(f,b,'workflow/tuning-curves.png')

    # Figure D: steps 8-9, frozen test
    f=figure('STEPS 8–9: FREEZE, TEST ONCE, JUDGE WHERE THE DECISION IS',f'The {best}-latent-variable model, refitted on all 24 development batches, applied once to the 6 held-out batches (mean of 3 scans per sample).')
    ax=f.add_axes([.07,.17,.36,.60]);cols=[TEAL,ORANGE,PURPLE,GOLD,NAVY,RED]
    for c,bb in zip(cols,test_b):
        k=bs==bb;ax.scatter(ys[k],ps[k],color=c,s=46,label=bb,zorder=3)
    ax.plot([0,10],[0,10],color=GREY,lw=1.2);ax.axvline(ENDPOINT,color=NAVY,ls=':');ax.axhline(ENDPOINT,color=NAVY,ls=':')
    ax.set(xlabel='Karl Fischer water (% w/w)',ylabel='Predicted water (% w/w)',xlim=(0,9.5),ylim=(0,9.5),aspect='equal')
    ax.legend(fontsize=10,loc='upper left',title='Test batch',title_fontsize=10)
    ax.set_title(f'Overall RMSEP {stats["RMSEP_pct_w_w"]:.2f}% w/w',fontsize=14,color=NAVY,loc='left')
    a2=f.add_axes([.53,.17,.41,.60]);m=max(abs(err).max()*1.25,REQ*1.6)
    a2.axvspan(0,3,color='#f3e3d8',lw=0);a2.axhspan(-REQ,REQ,xmin=0,xmax=3/9.5,color='#e3f0f2',lw=0)
    for c,bb in zip(cols,test_b):
        k=bs==bb;a2.scatter(ys[k],err[k],color=c,s=46,zorder=3)
        a2.plot([ys[k].min(),ys[k].max()],[err[k].mean()]*2,color=c,lw=1.6,alpha=.8)
    a2.axhline(0,color=GREY,lw=1.2);a2.axvline(ENDPOINT,color=NAVY,ls=':')
    a2.text(.12,m*.93,'endpoint window\n(below 3% w/w)',fontsize=11,color=ORANGE,va='top',bbox=dict(facecolor='#f3e3d8',edgecolor='none',pad=1.5))
    ok='meets' if stats['RMSEP_below_3pct_pct_w_w']<=REQ else 'does not meet'
    ax.text(9.3,0.3,f"Below 3% w/w ({stats['samples_below_3pct']} samples):\nRMSEP {stats['RMSEP_below_3pct_pct_w_w']:.2f}, mean error {stats['bias_below_3pct_pct_w_w']:+.2f}% w/w\n{ok} the illustrative step-1 requirement\n(RMSEP ≤ {REQ:.2f}% w/w;\npale band on the right: ±{REQ:.2f})",fontsize=10.5,color=NAVY,ha='right',va='bottom')
    a2.set(xlabel='Karl Fischer water (% w/w)',ylabel='Predicted − reference (% w/w)',xlim=(0,9.5),ylim=(-m,m))
    a2.set_title('Residuals: judge them where the decision is made',fontsize=14,color=NAVY,loc='left')
    f.text(.53,.075,f"Short lines: each test batch's mean error, {min(bmean):+.2f} to {max(bmean):+.2f}% w/w.\nErrors cluster by batch, which is why step 5 splits by batch.",fontsize=11,color=NAVY)
    save(f,b,'workflow/frozen-test.png')

# ---------------------------------------------------------------- reading 3: PCA rotation
def r3(b):
    rng=np.random.default_rng(1973)             # seed: Wold and Kowalski meet
    a=rng.normal(1.9,1.0,40);bb=2.9+0.77*(a-1.9)+rng.normal(0,0.24,40)
    D=np.c_[a,bb];mu=D.mean(0);C=D-mu;U,s,Vt=np.linalg.svd(C,full_matrices=False)
    if Vt[0,0]<0:Vt[0]*=-1
    if Vt[1,1]<0:Vt[1]*=-1
    T=C@Vt.T;ev=s**2/np.sum(s**2)*100
    write(b,'synthetic-pca-data.csv',[dict(response_A=r(x,4),response_B=r(z,4),PC1_score=r(t1,4),PC2_score=r(t2,4)) for x,z,(t1,t2) in zip(a,bb,T)])
    write(b,'pca-summary.csv',[dict(observations=40,PC1_percent_variance=r(ev[0],1),PC2_percent_variance=r(ev[1],1),PC1_loading_A=r(Vt[0,0],3),PC1_loading_B=r(Vt[0,1],3),PC2_loading_A=r(Vt[1,0],3),PC2_loading_B=r(Vt[1,1],3))])
    iA=int(np.argmax(T[:,0]));iB=int(np.argmin(T[:,0]))
    f=figure('PCA CHANGES THE COORDINATES, NOT THE SAMPLES',f'40 synthetic observations, mean-centred, not variance-scaled: PC1 {ev[0]:.1f}% and PC2 {ev[1]:.1f}% of the variance. Percent variance is not predictive accuracy.')
    ax=f.add_axes([.06,.15,.40,.65]);ax.scatter(a,bb,color=TEAL,s=34,zorder=3)
    for v,c,lab in [(Vt[0],ORANGE,'PC1 direction'),(Vt[1],PURPLE,'PC2 direction')]:
        L=3.2 if c==ORANGE else 1.1;ax.plot([mu[0]-L*v[0],mu[0]+L*v[0]],[mu[1]-L*v[1],mu[1]+L*v[1]],color=c,lw=2.2,label=lab)
    for i,lab,c in [(iA,'A',ORANGE),(iB,'B',PURPLE)]:
        ax.scatter(a[i],bb[i],color=c,s=110,zorder=4);ax.text(a[i]+.12,bb[i]+.08,lab,fontsize=14,fontweight='bold',color=c)
    ax.set(xlabel='Response A (arbitrary units)',ylabel='Response B (arbitrary units)');ax.set_aspect('equal',adjustable='datalim');ax.legend(fontsize=11,loc='upper left')
    ax.set_title('Original measurement coordinates',fontsize=14,color=NAVY,loc='left')
    a2=f.add_axes([.55,.15,.40,.65]);a2.scatter(T[:,0],T[:,1],color=TEAL,s=34,zorder=3)
    a2.axhline(0,color=ORANGE,lw=2);a2.axvline(0,color=PURPLE,lw=2)
    for i,lab,c in [(iA,'A',ORANGE),(iB,'B',PURPLE)]:
        a2.scatter(T[i,0],T[i,1],color=c,s=110,zorder=4);a2.text(T[i,0]+.1,T[i,1]+.1,lab,fontsize=14,fontweight='bold',color=c)
    a2.set(xlabel=f'PC1 score ({ev[0]:.1f}% of variance)',ylabel=f'PC2 score ({ev[1]:.1f}% of variance)',xlim=(T[:,0].min()-.6,T[:,0].max()+.6));a2.set_aspect('equal',adjustable='datalim');a2.set_yticks([-2,-1,0,1,2])
    a2.set_title('Same observations in PCA coordinates',fontsize=14,color=NAVY,loc='left')
    save(f,b,'spectra/pca-rotation-example.png')

# ---------------------------------------------------------------- reading 4: delay
def r4(b):
    t=np.round(np.arange(0,45.0001,0.1),1);w=1+7*np.exp(-0.0625*t);rep=np.where(t>=6,1+7*np.exp(-0.0625*(t-6)),np.nan)
    write(b,'synthetic-delay-data.csv',[dict(time_min=x,underlying_water_pct=r(u,4),reported_water_pct_6min_delay='' if np.isnan(v) else r(v,4)) for x,u,v in zip(t,w,rep)])
    tc=math.log(7/2)/0.0625
    f=figure('AN ACCURATE RESULT CAN DESCRIBE AN EARLIER PROCESS STATE','Synthetic drying curve, water = 1 + 7·exp(−0.0625 t) % w/w, and the same values reported exactly but 6 minutes late.',
             'Synthetic teaching example • pure delay only, no noise or model error • the 3% decision level is illustrative, not an endpoint specification')
    ax=f.add_axes([.08,.15,.86,.65])
    ax.plot(t,w,color=TEAL,lw=2.8,label='Underlying process water content');ax.plot(t,rep,color=ORANGE,lw=2.8,label='Exact result, available 6 minutes later')
    ax.axhline(3,color=PURPLE,ls='--',lw=1.6,label='Illustrative decision level, 3% w/w')
    for x,c in [(tc,TEAL),(tc+6,ORANGE)]:ax.axvline(x,color=c,ls=':',lw=1.2);ax.scatter([x],[3],color=c,s=70,zorder=4)
    ax.annotate('',xy=(tc+6,4.3),xytext=(tc,4.3),arrowprops=dict(arrowstyle='<->',color=NAVY,lw=1.8))
    ax.text(tc+3,4.45,'6-minute reporting delay',ha='center',fontsize=12,color=NAVY)
    ax.text(tc-.4,1.15,f'process crosses\nat {tc:.1f} min',fontsize=11,color=TEAL,ha='right');ax.text(tc+6.4,1.15,f'report crosses\nat {tc+6:.1f} min',fontsize=11,color=ORANGE)
    ax.set(xlabel='Elapsed process time / time the result becomes available (min)',ylabel='Water content (% w/w)',xlim=(0,45),ylim=(1,8.4));ax.legend(fontsize=11,loc='upper right')
    save(f,b,'location/measurement-delay.png')

# ---------------------------------------------------------------- reading 5: RTD
def gamma_pdf(t,k=4,mean=1.0):
    th=mean/k;t=np.asarray(t,float);out=np.zeros_like(t);m=t>0
    out[m]=t[m]**(k-1)*np.exp(-t[m]/th)/(math.factorial(k-1)*th**k);return out
def gamma_cdf(t,k=4,mean=1.0):
    x=t/(mean/k);return 1-math.exp(-x)*sum(x**i/math.factorial(i) for i in range(k))
def gamma_ppf(p):
    lo,hi=0.0,20.0
    for _ in range(200):
        m=(lo+hi)/2;lo,hi=(m,hi) if gamma_cdf(m)<p else (lo,m)
    return (lo+hi)/2
def r5(b):
    dt=0.005;t=np.round(np.arange(0,8+dt/2,dt),3);u=((t>=2.0)&(t<2.5)).astype(float);E=gamma_pdf(t)
    out=np.convolve(u,E)[:len(t)]*dt
    p05,p995=gamma_ppf(0.005),gamma_ppf(0.995)
    write(b,'synthetic-rtd-response.csv',[dict(time_min=x,input_normalized_deviation=r(a,1),rtd_density_per_min=r(e,6),output_normalized_deviation=r(o,6)) for x,a,e,o in zip(t,u,E,out)])
    write(b,'rtd-summary.csv',[dict(rtd='gamma, shape 4',mean_residence_time_min=1.0,percentile_0p5_min=r(p05,3),percentile_99p5_min=r(p995,3),input_start_min=2.0,input_end_min=2.5,shaded_start_min=r(2.0+p05,2),shaded_end_min=r(2.5+p995,2),peak_output=r(out.max(),3),peak_time_min=r(t[int(np.argmax(out))],2))])
    f=figure('A SHORT DISTURBANCE BECOMES A SPREAD OF DOWNSTREAM EFFECTS','A 0.5-minute input pulse through ideal linear mixing with a gamma RTD (shape 4, mean 1.0 min). No corrective controller is simulated.',
             'Synthetic teaching example • the shading is an RTD percentile illustration, not a validated collection boundary; tails and quality-impact uncertainty remain')
    ax=f.add_axes([.08,.55,.86,.27]);ax.plot(t,u,color=ORANGE,lw=2.4);ax.set(ylabel='Input deviation\n(normalized)',xlim=(0,8),ylim=(-.05,1.2),xticklabels=[])
    ax.text(4.2,.75,'Input event: 2.0–2.5 min\nRTD mean: 1.0 min',fontsize=12,color=NAVY)
    a2=f.add_axes([.08,.15,.86,.33]);a2.axvspan(2.0+p05,2.5+p995,color='#ece4f3',lw=0,label=f'Illustrative interval: start + 0.5th percentile ({p05:.2f} min) to end + 99.5th ({p995:.2f} min)')
    a2.plot(t,out,color=TEAL,lw=2.8,label='Downstream deviation: input convolved with the RTD')
    for x in (3.0,3.5):a2.axvline(x,color=ORANGE,ls='--',lw=1.4)
    a2.text(3.55,out.max()*0.62,'dashed: event shifted\nby the mean only',fontsize=11,color=ORANGE)
    a2.set(xlabel='Time at the input / output observation point (min)',ylabel='Output deviation\n(normalized)',xlim=(0,8),ylim=(-.02,max(out)*1.45));a2.legend(fontsize=11,loc='upper right')
    save(f,b,'control/rtd-disturbance-example.png')
    r5_steps(b)

# ---------------------------------------------------------------- reading 6: same mean, different spread
SET_A=[98,99,100,101,102,101,99,102,98,100,101,99,102,98,100,101,99,102,98,100]
SET_B=[82,88,92,96,100,104,108,112,118,100,84,90,94,98,102,106,110,116,100,100]
def r6(b):
    write(b,'synthetic-unit-content.csv',[dict(unit=i,set_A_pct_nominal=a,set_B_pct_nominal=c) for i,(a,c) in enumerate(zip(SET_A,SET_B),1)])
    sa,sb=np.std(SET_A,ddof=1),np.std(SET_B,ddof=1)
    f=figure('SAME AVERAGE CONTENT. DIFFERENT DOSAGE-UNIT VARIATION.',f'Two invented sets of 20 units, both with a mean of exactly 100% of nominal; sample SDs {sa:.1f}% and {sb:.1f}%.',
             'Invented teaching data • no acceptance limits or pass/fail decisions • not a compendial uniformity calculation, sampling recommendation or product dataset')
    for k,(vals,c,ttl) in enumerate([(SET_A,TEAL,'Set A: narrower spread'),(SET_B,ORANGE,'Set B: wider spread')]):
        ax=f.add_axes([.07+k*.46,.15,.41,.65]);ax.scatter(range(1,21),vals,color=c,s=60,zorder=3);ax.axhline(100,color=PURPLE,ls='--',label='Mean = 100%')
        ax.set(xlabel='Illustrative dosage unit',ylabel='API content (% of nominal)' if k==0 else '',ylim=(78,122),xticks=[1,5,10,15,20]);ax.legend(fontsize=11,loc='upper left')
        ax.set_title(ttl,fontsize=14,color=NAVY,loc='left')
    save(f,b,'release/same-mean-different-uniformity.png')

# ---------------------------------------------------------------- reading 7: Q versus prediction error
def r7(b):
    rng=np.random.default_rng(14)                 # seed: ICH Q14
    xd=rng.normal(0,1,200);Xdev=np.c_[xd,xd+rng.normal(0,0.08,200)];mu=Xdev.mean(0)
    v=np.linalg.svd(Xdev-mu,full_matrices=False)[2][0]
    def Q(X):C=X-mu;R=C-np.outer(C@v,v);return (R**2).sum(1)
    rows=[];summ=[]
    x1=rng.normal(0,1,30);e2=rng.normal(0,0.08,30);ey=rng.normal(0,0.03,30)
    for name,dx2,dy in [('Baseline',0,0),('Input-pattern change',2.0,0),('Outcome-relationship change',0,0.8)]:
        X=np.c_[x1,x1+e2+dx2];yref=x1+ey+dy;yp=x1;q=Q(X)
        for i in range(30):rows.append(dict(scenario=name,observation=i+1,x1=r(X[i,0],4),x2=r(X[i,1],4),reference_y=r(yref[i],4),predicted_y=r(yp[i],4),Q=r(q[i],6),prediction_error=r(yp[i]-yref[i],4)))
        summ.append(dict(scenario=name,mean_Q=r(q.mean(),4),mean_prediction_error=r((yp-yref).mean(),3)))
    write(b,'synthetic-monitoring-data.csv',rows);write(b,'monitoring-summary.csv',summ)
    f=figure('MODEL DIAGNOSTICS AND PREDICTION ERROR ANSWER DIFFERENT QUESTIONS','One-component PCA diagnostic fitted to 200 development observations; a fixed prediction ŷ = x₁. Three scenarios, 30 observations each.',
             'Synthetic contrasts, not successive events in one run • short bars show means • no alert limits or acceptance criteria')
    cols=[TEAL,ORANGE,PURPLE];names=[s['scenario'] for s in summ];jit=np.random.default_rng(1).uniform(-.18,.18,30)
    for k,(key,ttl,lab,log) in enumerate([('Q','Q: variation in X outside the model','Squared reconstruction residual (arbitrary units)',True),('prediction_error','Prediction error against the reference Y','Predicted − reference (arbitrary units)',False)]):
        ax=f.add_axes([.08+k*.47,.17,.39,.60])
        for i,(nm,c) in enumerate(zip(names,cols)):
            vals=np.array([z[key] for z in rows if z['scenario']==nm]);ax.scatter(i+jit,vals,color=c,s=30,zorder=3)
            m=vals.mean();ax.plot([i-.3,i+.3],[m,m],color=NAVY,lw=2.4)
        ax.set(xticks=[0,1,2],xticklabels=['Baseline','Input-pattern\nchange','Outcome-relationship\nchange'],ylabel=lab)
        if log:ax.set_yscale('log')
        else:ax.axhline(0,color=GREY,ls='--',lw=1)
        ax.set_title(ttl,fontsize=14,color=NAVY,loc='left')
    save(f,b,'lifecycle/diagnostics-and-prediction-error.png')
    r7_steps(b)

# ---------------------------------------------------------------- reading 5: one feeder event, five functions
LINE_KG_H=30.0;API_KG_H=3.00                      # total and API feeder setpoints: 10.0% w/w API
LIMIT=(95.0,105.0);ACTION=(97.0,103.0)            # % of target concentration: illustrative quality limit; earlier action band
LEAD_S=15;ACT_DELAY_S=5;CLEAR_S=10;NIR_EVERY_S=5;NIR_LAG_S=3;NIR_SD=0.6
def gamma_kernel(t,k,mean):
    th=mean/k;out=np.zeros_like(t,dtype=float);m=t>0
    out[m]=t[m]**(k-1)*np.exp(-t[m]/th)/(math.factorial(k-1)*th**k);return out/out.sum()
def causal(x,kern):return np.convolve(x,kern)[:len(x)]
def control_event():
    rng=np.random.default_rng(13)                 # seed: ICH Q13
    t=np.arange(0,601,1.0)
    api=np.full(t.size,API_KG_H)
    ref=(t>=120)                                   # refill starts at 120 s: volumetric mode overfeeds, then recovers
    rise=np.clip((t-120)/3,0,1);hold=(t>=120)&(t<138);dec=t>=138
    api=api+np.where(hold,0.30*API_KG_H*rise,0)+np.where(dec,0.30*API_KG_H*np.exp(-(t-138)/10),0)
    api_true=api*(1+rng.normal(0,0.004,t.size))
    api_meas=api_true+rng.normal(0,0.02,t.size)    # load-cell-derived rate, kg/h
    exc=LINE_KG_H-API_KG_H
    def conc(a):return 100*(a/(a+exc))/(API_KG_H/LINE_KG_H)   # % of target concentration
    k_bl=gamma_kernel(t,4,45.0);k_nir=np.r_[np.zeros(15),k_bl[:-15]]           # blender RTD, then 15 s plug to the NIR
    k_div=causal(k_bl,gamma_kernel(t,10,60.0));k_div/=k_div.sum()              # blender, then press path to the diverter
    c_in=conc(api_true);c_nir=100+causal(c_in-100,k_nir);c_div=100+causal(c_in-100,k_div)
    p_nir=100+causal(conc(api_meas)-100,k_nir);p_div=100+causal(conc(api_meas)-100,k_div)   # model predictions from the measured feeder signal
    # NIR: 5 s average every 5 s, reported 3 s later
    nir_t=[];nir_v=[]
    for te in range(NIR_EVERY_S,601,NIR_EVERY_S):
        nir_t.append(te+NIR_LAG_S);nir_v.append(float(c_nir[te-NIR_EVERY_S:te].mean()+rng.normal(0,NIR_SD)))
    nir_t=np.array(nir_t);nir_v=np.array(nir_v)
    # 1 detect: measured feeder rate more than 10% from setpoint for 2 consecutive seconds
    dev=np.abs(api_meas/API_KG_H-1)>0.10;det=int(next(i for i in range(1,t.size) if dev[i] and dev[i-1]))
    # 2-3 infer and decide (feedforward): predicted diverter concentration leaves the action band -> command LEAD_S earlier.
    # The prediction for time t+h uses only feeder data up to t, so the earliest a command can be issued is the detection time.
    out=(p_div<ACTION[0])|(p_div>ACTION[1]);i_out=np.flatnonzero(out)
    pred_start,pred_end=int(t[i_out[0]]),int(t[i_out[-1]])
    cmd_on=max(det,pred_start-LEAD_S);pos_on=cmd_on+ACT_DELAY_S
    # 5 confirm: three consecutive NIR results inside the action band after the event, carried to the diverter
    # by the NIR-to-diverter mean delay, and the model's end plus clearance; collection resumes at the later
    ok=(nir_v>=ACTION[0])&(nir_v<=ACTION[1]);after=nir_t>pred_start-60
    run=0;nir_ok=None
    for tt,o,a in zip(nir_t,ok,after):
        if not a:continue
        run=run+1 if o else 0
        if run==3 and tt>t[int(np.argmax(np.abs(c_nir-100)))]:nir_ok=int(tt);break
    nir_to_div=float((t*k_div).sum()-(t*k_nir).sum())
    cmd_off=int(max(pred_end+CLEAR_S,nir_ok+round(nir_to_div)));pos_off=cmd_off+ACT_DELAY_S
    diverted=(t>=pos_on)&(t<pos_off)
    bad=(c_div<LIMIT[0])|(c_div>LIMIT[1])
    kg_s=LINE_KG_H/3600
    res=dict(detect_s=det,predicted_out_of_action_band_s=f'{pred_start}-{pred_end}',command_on_s=cmd_on,position_divert_s=pos_on,
             nir_three_in_band_s=nir_ok,nir_to_diverter_mean_delay_s=round(nir_to_div,1),command_off_s=cmd_off,position_collect_s=pos_off,
             diverted_s=int(diverted.sum()),diverted_kg=r(diverted.sum()*kg_s,3),
             true_out_of_limit_s=int(bad.sum()),true_out_of_limit_from_s=int(t[bad][0]) if bad.any() else '',true_out_of_limit_to_s=int(t[bad][-1]) if bad.any() else '',
             out_of_limit_collected_s=int((bad&~diverted).sum()),out_of_limit_collected_kg=r((bad&~diverted).sum()*kg_s,3),
             in_limit_diverted_kg=r((~bad&diverted).sum()*kg_s,3),peak_true_at_diverter_pct=r(c_div.max(),1),peak_true_at_nir_pct=r(c_nir.max(),1))
    series=[dict(time_s=int(x),api_feeder_measured_kg_h=r(a,3),conc_at_nir_true_pct=r(n,2),conc_at_nir_predicted_pct=r(pn,2),
                 conc_at_diverter_true_pct=r(d,2),conc_at_diverter_predicted_pct=r(pd,2),route='diverted' if v else 'collected')
            for x,a,n,pn,d,pd,v in zip(t,api_meas,c_nir,p_nir,c_div,p_div,diverted)]
    return t,api_meas,p_nir,c_div,p_div,nir_t,nir_v,diverted,bad,res,series
def r5_steps(b):
    t,api,p_nir,c_div,p_div,nir_t,nir_v,diverted,bad,res,series=control_event()
    write(b,'feeder-event-series.csv',series);write(b,'feeder-event-summary.csv',[res])
    write(b,'feeder-event-nir.csv',[dict(time_reported_s=int(a),nir_conc_pct=r(v,2)) for a,v in zip(nir_t,nir_v)])
    write(b,'feeder-event-rules.csv',[dict(step=s,rule=x) for s,x in [
        ('setpoints',f'API feeder {API_KG_H:.2f} kg/h in {LINE_KG_H:.1f} kg/h total (10.0% w/w); refill at 120 s overfeeds by up to 30%'),
        ('process paths','feeder to NIR: gamma RTD (shape 4, mean 45 s) + 15 s plug; feeder to diverter: the same blender RTD convolved with gamma (shape 10, mean 60 s)'),
        ('detect','measured API rate more than 10% from setpoint for 2 consecutive seconds'),
        ('infer','the same RTD models applied to the measured feeder signal predict concentration at the NIR and at the diverter'),
        ('decide',f'command diversion {LEAD_S} s before the predicted diverter concentration leaves {ACTION[0]:.0f}-{ACTION[1]:.0f}% of target (not before detection)'),
        ('act',f'diverter position confirmed {ACT_DELAY_S} s after each command'),
        ('confirm',f'resume when (a) the predicted diverter concentration has been back in band for {CLEAR_S} s and (b) three consecutive NIR results are in band, carried forward by the NIR-to-diverter delay; whichever is later'),
        ('NIR',f'{NIR_EVERY_S} s average every {NIR_EVERY_S} s, reported {NIR_LAG_S} s later, noise SD {NIR_SD}% of target'),
        ('quality limit',f'{LIMIT[0]:.0f}-{LIMIT[1]:.0f}% of target, illustrative')]])
    f=figure('DETECT, INFER, DECIDE, ACT, CONFIRM: ONE FEEDER REFILL',f'Synthetic continuous line, {LINE_KG_H:.1f} kg/h with API at 10.0% w/w. Each panel is one function from the table above, on one clock.',
             'Synthetic teaching example • RTDs, rules, limits and delays are illustrative, not a validated control strategy')
    X=(0,420);H=.155;tops=[.69,.505,.32,.135]
    X0,WD=.21,.73
    labs=['1  DETECT','2  INFER','3  DECIDE\n4  ACT','5  CONFIRM']
    axs=[f.add_axes([X0,y,WD,H]) for y in tops]
    for ax,l in zip(axs,labs):
        f.text(.04,ax.get_position().y0+H/2,l,fontsize=15,fontweight='bold',color=NAVY,va='center')
        ax.set_xlim(*X)
        if ax is not axs[-1]:ax.set_xticklabels([])
    a=axs[0];a.plot(t,api,color=GREY,lw=1.4,label='API feeder, measured');a.axhline(API_KG_H,color=NAVY,lw=1)
    a.axhspan(API_KG_H*0.9,API_KG_H*1.1,color='#e3f0f2',lw=0,label='±10% of setpoint')
    a.axvline(res['detect_s'],color=ORANGE,ls='--');a.text(res['detect_s']+40,3.85,f"detected at {res['detect_s']} s",color=ORANGE,fontsize=11,va='center')
    a.set(ylabel='kg/h',ylim=(2.7,4.05));a.legend(fontsize=10,loc='upper right')
    a=axs[1];a.plot(t,p_nir,color=TEAL,lw=2.2,label='Model: predicted at the NIR, from the feeder signal')
    a.scatter(nir_t,nir_v,color=PURPLE,s=16,zorder=3,label='NIR results (every 5 s)')
    a.set(ylabel='% of target',ylim=(96,115));a.legend(fontsize=10,loc='upper right')
    a=axs[2];a.plot(t,p_div,color=TEAL,lw=2.2,label='Model: predicted at the diverter')
    a.axhspan(*ACTION,color='#e3f0f2',lw=0,label=f'action band {ACTION[0]:.0f}–{ACTION[1]:.0f}%')
    a.axvspan(res['command_on_s'],res['command_off_s'],color='#f3e3d8',lw=0,label='commanded divert')
    a.axvspan(res['position_divert_s'],res['position_collect_s'],ymin=0,ymax=.12,color=ORANGE,lw=0,label='position confirmed')
    a.set(ylabel='% of target',ylim=(96,115));a.legend(fontsize=10,loc='upper right',ncol=2)
    a=axs[3]
    a.scatter(t[~diverted],c_div[~diverted],color=TEAL,s=6,label='collected');a.scatter(t[diverted],c_div[diverted],color=ORANGE,s=6,label='diverted')
    for y in LIMIT:a.axhline(y,color=RED,ls=':',lw=1.2)
    a.text(X[1]-3,LIMIT[1]+.4,f'quality limit {LIMIT[1]:.0f}%',color=RED,fontsize=10,ha='right',va='bottom')
    a.set(ylabel='% of target',xlabel='Time (s)',ylim=(96,117));a.legend(fontsize=10,loc='upper left',markerscale=3)
    collected_bad=f"{res['out_of_limit_collected_kg']:.3f} kg collected" if res['out_of_limit_collected_kg'] else 'none collected'
    a.text(X[1]-3,116.6,f"True concentration at the diverter: out of limit {res['true_out_of_limit_from_s']}–{res['true_out_of_limit_to_s']} s, {collected_bad}.\nDiverted {res['diverted_s']} s = {res['diverted_kg']:.3f} kg, of which {res['in_limit_diverted_kg']:.2f} kg was within the limit: the cost of the margin.",fontsize=10.5,color=NAVY,ha='right',va='top')
    save(f,b,'control/detect-to-confirm.png')

# ---------------------------------------------------------------- reading 7: a supplier-change investigation, step by step
DAYS=40;E2_DAY=21;REQ_LC=1.0;E3_SHIFT_NM=10.0
PLS7_A=4;N_CAL7=60;LOT7_SD=0.05
# Each supplier's excipient differs from E1 only at its 2270 nm band: centre shift (nm), width factor, and overall scatter.
# E2 is the supplier that actually arrives; E3 is a hypothetical comparison, run through the same steps, that fails step 4.
SUPPLIERS={'E1':dict(shift=0.0,broad=1.00,scatter=1.00),'E2':dict(shift=2.0,broad=1.01,scatter=1.02),'E3':dict(shift=E3_SHIFT_NM,broad=1.03,scatter=1.02)}
API_SPEC=0.9*band(1680,22)+0.6*band(2150,28)+0.35*band(1145,18)
def exc_spec(shift=0.0,broad=1.0,lot=(0.0,0.0)):
    """Excipient spectrum. lot = relative changes in the 1930 nm (moisture) and 2095 nm bands from lot to lot."""
    return (0.25+0.08*(WL-1100)/1400+0.55*band(1450,38)+0.75*(1+lot[0])*band(1930,42)
            +0.65*band(2270+shift,33)+0.35*(1+lot[1])*band(2095,48)+0.2*band(1210,30))
def blend(c,lot,supplier,rng):
    sp=SUPPLIERS[supplier];e=exc_spec(sp['shift'],sp['broad'],lot)
    m=rng.normal(sp['scatter'],0.02)
    return m*(c*API_SPEC*3.0+(1-c)*e)+rng.normal(0,0.01)+rng.normal(0,0.0008,WL.size)
def band_centre(sp,lo=2180,hi=2380):
    """Band position from readings 10 nm apart. Over 2180-2380 nm, fit one Gaussian band plus a curved (quadratic)
    baseline that absorbs the tails of neighbouring bands; search the band centre (0.25 nm, then 0.01 nm steps) and
    width (25-45 nm) by least squares. The fitted centre is not tied to the 10 nm grid, so a shift of a nanometre or two
    is measurable. Neighbouring bands offset the absolute centre slightly; the offset is the same for every lot, so
    differences between lots are accurate."""
    m=(WL>=lo)&(WL<=hi);x=WL[m].astype(float);y=sp[m];xs=(x-2270)/100
    def ss(c,w):
        M=np.c_[np.exp(-0.5*((x-c)/w)**2),np.ones_like(x),xs,xs**2];coef=np.linalg.lstsq(M,y,rcond=None)[0];return float(((M@coef-y)**2).sum())
    best=min((ss(c,w),c,w) for c in np.arange(2260,2290.001,0.25) for w in np.arange(25,46,1.0))
    _,c0,w0=best
    return float(min((ss(c,w0),c) for c in np.arange(c0-.3,c0+.3001,0.01))[1])
def r7_steps(b):
    rng=np.random.default_rng(1402)
    cal_c=rng.uniform(0.085,0.115,N_CAL7);cal_lot=rng.normal(0,LOT7_SD,(N_CAL7,2))
    Xc=np.array([blend(c,l,'E1',rng) for c,l in zip(cal_c,cal_lot)]);yc=cal_c*1000   # % of label claim (0.100 -> 100)
    Sc=snv(Xc);A=PLS7_A;model=pls_fit(Sc,yc,A)
    mu=Sc.mean(0);U,s,Vt=np.linalg.svd(Sc-mu,full_matrices=False);P=Vt[:A].T;lam=(s[:A]**2)/(len(Sc)-1)
    def diag(S):
        C=S-mu;T=C@P;R=C-T@P.T;return (T**2/lam).sum(1),(R**2).sum(1)
    vc=rng.uniform(0.085,0.115,N_CAL7);Sv=snv(np.array([blend(c,rng.normal(0,LOT7_SD,2),'E1',rng) for c in vc]))   # independent E1 validation blends
    t2v,qv=diag(Sv);T2_LIM,Q_LIM=float(np.percentile(t2v,99)),float(np.percentile(qv,99))
    # 40 production days, 24 spectra per day, 2 HPLC reference checks per day
    day_rows=[];ref_rows=[];inst_rows=[]
    for d in range(1,DAYS+1):
        sup='E2' if d>=E2_DAY else 'E1';lot=rng.normal(0,LOT7_SD,2)
        c=rng.normal(0.100,0.002,24);S=snv(np.array([blend(x,lot,sup,rng) for x in c]));t2,q=diag(S);pred=pls_predict(model,S,A)
        day_rows.append(dict(day=d,supplier=sup,spectra=24,median_Q=r(np.median(q),5),median_T2=r(np.median(t2),2),pct_over_Q_limit=r(100*np.mean(q>Q_LIM),1),pct_over_T2_limit=r(100*np.mean(t2>T2_LIM),1),mean_prediction_pct_LC=r(pred.mean(),2)))
        for i in (0,12):
            hplc=c[i]*1000+rng.normal(0,0.4);ref_rows.append(dict(day=d,supplier=sup,predicted_pct_LC=r(pred[i],2),hplc_pct_LC=r(hplc,2),error_pct_LC=r(pred[i]-hplc,2)))
        inst_rows.append(dict(day=d,polystyrene_peak_nm=r(1680.0+rng.normal(0,0.06),2),photometric_check_pct=r(100+rng.normal(0,0.25),2)))
    write(b,'supplier-daily-diagnostics.csv',day_rows);write(b,'supplier-reference-checks.csv',ref_rows);write(b,'supplier-instrument-checks.csv',inst_rows)
    # step 3: compare the material, pure excipient lots after SNV
    def lot_spec(sup,g=rng):
        sp=SUPPLIERS[sup];return exc_spec(sp['shift'],sp['broad'],g.normal(0,LOT7_SD,2))*g.normal(1,0.02)+g.normal(0,0.0008,WL.size)
    lots=[('E1',f'E1-{i+1:02d}',lot_spec('E1')) for i in range(12)]+[('E2',f'E2-{i+1:02d}',lot_spec('E2')) for i in range(3)]
    cen=[dict(supplier=sp,lot=n,band_centre_2270_nm=r(band_centre(x),2)) for sp,n,x in lots]
    write(b,'supplier-excipient-band-centres.csv',cen)
    c1=np.array([z['band_centre_2270_nm'] for z in cen if z['supplier']=='E1']);c2=np.array([z['band_centre_2270_nm'] for z in cen if z['supplier']=='E2'])
    # step 4: designed challenge across the decision range, 3 blends per level per supplier
    ch=[]
    for sup in ('E1','E2'):
        for lv in (90,95,100,105,110):
            for k in range(3):
                c=lv/1000;S=snv(blend(c,rng.normal(0,LOT7_SD,2),sup,rng)[None]);hplc=lv+rng.normal(0,0.4)
                ch.append(dict(supplier=sup,level_pct_LC=lv,replicate=k+1,predicted_pct_LC=r(pls_predict(model,S,A)[0],2),hplc_pct_LC=r(hplc,2),error_pct_LC=r(pls_predict(model,S,A)[0]-hplc,2),Q=r(diag(S)[1][0],5)))
    write(b,'supplier-challenge.csv',ch)
    lvl={(s,l):np.mean([z['error_pct_LC'] for z in ch if z['supplier']==s and z['level_pct_LC']==l]) for s in ('E1','E2') for l in (90,95,100,105,110)}
    rmsep={s:rmse([z['error_pct_LC'] for z in ch if z['supplier']==s]) for s in ('E1','E2')}
    flagged=[z for z in day_rows if z['pct_over_Q_limit']>=50]
    e2_refs=[z['error_pct_LC'] for z in ref_rows if z['supplier']=='E2'];e1_refs=[z['error_pct_LC'] for z in ref_rows if z['supplier']=='E1']
    summ=dict(model=f'SNV + PLS1, {A} latent variables, calibrated on {N_CAL7} E1 blends at 85-115% LC',T2_limit_99pct=r(T2_LIM,2),Q_limit_99pct=r(Q_LIM,5),
              E2_minus_E1_band_centre_nm=r(c2.mean()-c1.mean(),2),E1_band_centre_SD_nm=r(c1.std(ddof=1),2),first_day_majority_over_Q=flagged[0]['day'] if flagged else '',days_majority_over_Q=len(flagged),
              routine_ref_mean_error_E1=r(np.mean(e1_refs),2),routine_ref_mean_error_E2=r(np.mean(e2_refs),2),routine_ref_max_abs_error_E2=r(np.max(np.abs(e2_refs)),2),
              challenge_RMSEP_E1=r(rmsep['E1'],2),challenge_RMSEP_E2=r(rmsep['E2'],2),
              **{f'challenge_mean_error_{s}_{l}':r(lvl[(s,l)],2) for s in ('E1','E2') for l in (90,95,100,105,110)},
              illustrative_requirement=f'|mean error| <= {REQ_LC} % LC at every challenge level')
    write(b,'supplier-investigation-summary.csv',[summ])
    # figure: trigger + five steps
    f=figure('INVESTIGATE THE SIGNAL BEFORE YOU TOUCH THE MODEL',f'Synthetic NIR blend-assay model calibrated on supplier E1; supplier E2 enters on day {E2_DAY}. One panel per step of the investigation.',
             f'Synthetic teaching data • limits are 99th percentiles of an independent E1 validation set • the ±{REQ_LC:.1f}% LC requirement is illustrative')
    W,Hh=.245,.28;pos=[(.075,.53),(.40,.53),(.725,.53),(.075,.145),(.40,.145),(.725,.145)]
    ax=[f.add_axes([x,y,W,Hh]) for x,y in pos];days=[z['day'] for z in day_rows]
    def ttl(a,s):a.set_title(s,fontsize=13,color=NAVY,loc='left',fontweight='bold')
    a=ax[0];a.bar(days,[z['pct_over_Q_limit'] for z in day_rows],color=[ORANGE if z['supplier']=='E2' else TEAL for z in day_rows],width=.8)
    a.bar(days,[z['pct_over_T2_limit'] for z in day_rows],color=NAVY,width=.35)
    a.axvline(E2_DAY-.5,color=GREY,ls=':');a.text(E2_DAY,103,'E2 enters',fontsize=10,color=GREY,va='bottom')
    a.set(xlabel='Production day',ylabel='% of spectra over limit',ylim=(0,112));ttl(a,'Trigger: Q flags, T² mostly does not')
    a.text(1,92,'wide bars: Q\nnarrow bars: T²',fontsize=9.5,color=NAVY,va='top')
    a=ax[1];v=[z['polystyrene_peak_nm']-1680.0 for z in inst_rows];a.plot(days,v,marker='o',ms=3.5,color=TEAL,lw=1.2)
    a.axhspan(-.5,.5,color='#e3f0f2',lw=0);a.axvline(E2_DAY-.5,color=GREY,ls=':')
    a.set(xlabel='Production day',ylabel='Wavelength check,\nshift from 1680.0 nm (nm)',ylim=(-.7,.75));ttl(a,'1–2  Validity and the instrument')
    a.text(1.5,.72,'Same model version and preprocessing all 40 days;\nreference checks matched by sample ID',fontsize=9.5,color=NAVY,va='top')
    a=ax[2];jit=np.random.default_rng(3).uniform(-.12,.12,len(cen))
    a.axhspan(c1.mean()-3*c1.std(ddof=1),c1.mean()+3*c1.std(ddof=1),color='#e3f0f2',lw=0)
    a.scatter(np.where(np.array([z['supplier'] for z in cen])=='E1',0,1)+jit,[z['band_centre_2270_nm'] for z in cen],s=30,color=[TEAL if z['supplier']=='E1' else ORANGE for z in cen])
    a.set(xticks=[0,1],xticklabels=[f'E1 ({len(c1)} lots)',f'E2 ({len(c2)} lots)'],xlim=(-.6,1.6),ylabel='Band centre near 2270 nm (nm)')
    a.yaxis.get_major_formatter().set_useOffset(False)
    a.text(-.5,c1.mean()+3*c1.std(ddof=1),'E1 mean ± 3 SD',fontsize=9.5,color=GREY,va='bottom')
    ttl(a,'3  Compare the material')
    a=ax[3];a.axhspan(-REQ_LC,REQ_LC,color='#e3f0f2',lw=0)
    for s,c,dx in (('E1',TEAL,-.6),('E2',ORANGE,.6)):
        zz=[z for z in ch if z['supplier']==s];a.scatter([z['level_pct_LC']+dx for z in zz],[z['error_pct_LC'] for z in zz],color=c,s=22,label=f"{s}: RMSEP {rmsep[s]:.1f}% LC")
        a.plot([l+dx for l in (90,95,100,105,110)],[lvl[(s,l)] for l in (90,95,100,105,110)],color=c,lw=1.6)
    a.axhline(0,color=GREY,lw=.8);a.set(xlabel='Challenge level (% of label claim)',ylabel='Predicted − HPLC (% LC)',xticks=(90,95,100,105,110),ylim=(-1.4,1.75));a.legend(fontsize=9.5,loc='upper center',ncol=2)
    ttl(a,'4  Assess current performance')
    a=ax[4];rd=[z['day'] for z in ref_rows];a.scatter(rd,[z['error_pct_LC'] for z in ref_rows],s=14,color=[ORANGE if z['supplier']=='E2' else TEAL for z in ref_rows])
    a.axhspan(-REQ_LC,REQ_LC,color='#e3f0f2',lw=0,zorder=0);a.axvline(E2_DAY-.5,color=GREY,ls=':');a.axhline(0,color=GREY,lw=.8)
    a.set(xlabel='Production day',ylabel='Routine check error (% LC)');ttl(a,'5  Assess impact')
    a.text(E2_DAY+.5,a.get_ylim()[1]*.95,f'{DAYS-E2_DAY+1} days on E2\nneed assessment',fontsize=9.5,color=ORANGE,va='top')
    a=ax[5];a.axis('off')
    e2l=[lvl[('E2',l)] for l in (90,95,100,105,110)];e1l=[lvl[('E1',l)] for l in (90,95,100,105,110)]
    inside=max(abs(x) for x in e2l)<=REQ_LC;t2max=max(z['pct_over_T2_limit'] for z in day_rows if z['supplier']=='E2')
    qmin=min(z['pct_over_Q_limit'] for z in day_rows if z['supplier']=='E2')
    lines=['What the evidence says',
           (f"• Trigger: Q flags every E2 spectrum; T² at most\n  {t2max:.0f}% on any day. Mainly a new pattern, not an\n  extreme familiar one." if qmin==100 else f"• Trigger: Q flags at least {qmin:.0f}% of spectra on every\n  E2 day; T² at most {t2max:.0f}%. A new pattern, not an\n  extreme familiar one."),
           "• 1–2: model, preprocessing and pairing unchanged;\n  instrument checks inside limits every day.",
           f"• 3: E2's 2270 nm band sits {c2.mean()-c1.mean():.1f} nm higher than\n  E1's, outside E1's lot-to-lot range.",
           f"• 4: across 90–110% LC, E2 mean error {min(e2l):+.2f} to\n  {max(e2l):+.2f}% LC (E1 {min(e1l):+.2f} to {max(e1l):+.2f}): "+("inside" if inside else "outside")+f"\n  the illustrative ±{REQ_LC:.1f}% LC requirement.",
           f"• 5: {DAYS-E2_DAY+1} production days on E2 to assess.",
           ("Response: accuracy holds, but a diagnostic that\nflags every result has stopped working. Extend\nthe calibration with E2 under change control."
            if inside else "Response: accuracy does not hold. Contain the\nE2 output; rebuild before release use.")]
    a.text(0,1.12,lines[0],fontsize=13.5,fontweight='bold',color=NAVY,va='top')
    a.text(0,1.0,'\n'.join(lines[1:-1]),fontsize=9.8,color=NAVY,va='top',linespacing=1.2)
    a.text(0,-.08,lines[-1],fontsize=10.3,color=ORANGE,va='bottom',fontweight='bold')
    summ['outcome']='inside requirement: extend calibration under change control' if inside else 'outside requirement: contain and rebuild'
    write(b,'supplier-investigation-summary.csv',[summ])
    save(f,b,'lifecycle/supplier-investigation.png')
    # ---- pass and fail: hypothetical supplier E3, same model, same limits, same steps; separate seed so E2 is unchanged
    g3=np.random.default_rng(1403)
    e3_t2=[];e3_q=[]
    for d in range(DAYS-E2_DAY+1):
        c=g3.normal(0.100,0.002,24);S=snv(np.array([blend(x,g3.normal(0,LOT7_SD,2),'E3',g3) for x in c]));t2,q=diag(S);e3_t2+=list(t2);e3_q+=list(q)
    e2_q=[z['pct_over_Q_limit'] for z in day_rows if z['supplier']=='E2'];e2_t2=[z['pct_over_T2_limit'] for z in day_rows if z['supplier']=='E2']
    cen3=[dict(supplier='E3',lot=f'E3-{i+1:02d}',band_centre_2270_nm=r(band_centre(lot_spec('E3',g3)),2)) for i in range(3)]
    c3=np.array([z['band_centre_2270_nm'] for z in cen3])
    ch3=[]
    for lv in (90,95,100,105,110):
        for k in range(3):
            S=snv(blend(lv/1000,g3.normal(0,LOT7_SD,2),'E3',g3)[None]);hplc=lv+g3.normal(0,0.4);pr=pls_predict(model,S,A)[0]
            ch3.append(dict(supplier='E3',level_pct_LC=lv,replicate=k+1,predicted_pct_LC=r(pr,2),hplc_pct_LC=r(hplc,2),error_pct_LC=r(pr-hplc,2),Q=r(diag(S)[1][0],5)))
    write(b,'supplier-challenge-E3.csv',ch3);write(b,'supplier-excipient-band-centres-E3.csv',cen3)
    chall={'E2':[z for z in ch if z['supplier']=='E2'],'E3':ch3}
    lv3={(sp,l):float(np.mean([z['error_pct_LC'] for z in chall[sp] if z['level_pct_LC']==l])) for sp in ('E2','E3') for l in (90,95,100,105,110)}
    verdict={sp:max(abs(lv3[(sp,l)]) for l in (90,95,100,105,110))<=REQ_LC for sp in ('E2','E3')}
    flags={'E2':(float(np.mean(e2_q)),float(np.mean(e2_t2))),'E3':(100*np.mean(np.array(e3_q)>Q_LIM),100*np.mean(np.array(e3_t2)>T2_LIM))}
    pf=[dict(supplier=sp,band_shift_built_in_nm=SUPPLIERS[sp]['shift'],band_shift_measured_nm=r((c2 if sp=='E2' else c3).mean()-c1.mean(),2),
             pct_spectra_over_Q=r(np.mean(e2_q) if sp=='E2' else flags['E3'][0],1),pct_spectra_over_T2=r(np.mean(e2_t2) if sp=='E2' else flags['E3'][1],1),
             challenge_RMSEP=r(rmse([z['error_pct_LC'] for z in chall[sp]]),2),worst_level_mean_error=r(max((lv3[(sp,l)] for l in (90,95,100,105,110)),key=abs),2),
             **{f'mean_error_{l}':r(lv3[(sp,l)],2) for l in (90,95,100,105,110)},verdict='passes' if verdict[sp] else 'fails') for sp in ('E2','E3')]
    write(b,'supplier-pass-and-fail.csv',pf)
    f=figure('SAME SIGNAL, TWO OUTCOMES: STEP 4 DECIDES THE RESPONSE','The supplier that arrived (E2) and a hypothetical one (E3), through the same model, limits and steps. Both trip Q; only one keeps its accuracy.',
             f'Synthetic teaching data • E3 is hypothetical, for comparison • the ±{REQ_LC:.1f}% of label claim requirement is illustrative')
    a=f.add_axes([.07,.20,.22,.56]);allc=[(0,v) for v in c1]+[(1,v) for v in c2]+[(2,v) for v in c3]
    jit=np.random.default_rng(5).uniform(-.12,.12,len(allc))
    a.scatter([x+j for (x,_),j in zip(allc,jit)],[v for _,v in allc],s=34,color=[[TEAL,ORANGE,RED][x] for x,_ in allc],zorder=3)
    for x,cc in ((1,c2),(2,c3)):a.text(x,cc.max()+.35,f"+{cc.mean()-c1.mean():.1f} nm",ha='center',fontsize=11,color=NAVY)
    a.set(xticks=[0,1,2],xticklabels=['E1','E2','E3'],xlim=(-.6,2.6),ylabel='Band centre near 2270 nm (nm)',ylim=(c1.min()-1,c3.max()+1.3))
    a.yaxis.get_major_formatter().set_useOffset(False)
    a.set_title('Step 3: how far each band moved',fontsize=13,color=NAVY,loc='left',fontweight='bold')
    for k,(sp,col) in enumerate((('E2',ORANGE),('E3',RED))):
        a=f.add_axes([.38+k*.31,.20,.25,.56]);a.axhspan(-REQ_LC,REQ_LC,color='#e3f0f2',lw=0)
        zz=chall[sp];a.scatter([z['level_pct_LC'] for z in zz],[z['error_pct_LC'] for z in zz],s=26,color=col,zorder=3)
        a.plot((90,95,100,105,110),[lv3[(sp,l)] for l in (90,95,100,105,110)],color=col,lw=1.8)
        a.axhline(0,color=GREY,lw=.8);a.set(xlabel='Challenge level (% of label claim)',xticks=(90,95,100,105,110),ylim=(-3.2,1.8))
        if k==0:a.set_ylabel('Predicted − HPLC (% of label claim)')
        ok=verdict[sp];a.set_title(f"Step 4, {sp}: {'PASSES' if ok else 'FAILS'}",fontsize=13,color=TEAL if ok else RED,loc='left',fontweight='bold')
        qf,t2f=flags[sp]
        a.text(89.6,1.7,f"Over 20 days: Q flags {qf:.0f}% of spectra, T² {t2f:.0f}%",fontsize=10,color=NAVY,va='top')
        worst=max(((l,lv3[(sp,l)]) for l in (90,95,100,105,110)),key=lambda z:abs(z[1]))
        resp=('Accuracy holds; the diagnostic no longer\nworks. Extend the calibration with E2\nunder change control.' if ok else
              'Accuracy fails. Contain the output made\nwhile the flag was on; do not use the\nmodel for release until it is rebuilt.')
        f.text(.38+k*.31,.065,f"Worst level mean {worst[1]:+.2f}% at {worst[0]}%.\n"+resp,fontsize=10.5,color=NAVY,va='bottom')
    save(f,b,'lifecycle/pass-and-fail.png')
    return summ

# ---------------------------------------------------------------- reading 8: claims against records
def r8(b):
    rows=[('R1: F-02 delivery-rate alarm\nat 10:03.','Batch B-241 had an API feeder F-02\ndelivery-rate alarm at 10:03.','SUPPORTED','Preserves the recorded fact.','#e3f3f1',TEAL),
          ('R1: refill at 10:02; alarm at\n10:03. R4: root cause\nunconfirmed.','The refill caused the concentration\nexcursion.','UNSUPPORTED','Neither cause nor a concentration\nexcursion is established.','#fbeee4',ORANGE),
          ('R3: S1 and S2 met assay\ncriteria; no dissolution results\nsupplied. R4: disposition\nunder review.','All tests passed, so the batch can be\nreleased.','UNSUPPORTED','Two sample results establish neither\nall tests nor disposition.','#efe8f5',PURPLE)]
    write(b,'claims-and-evidence.csv',[dict(source_evidence=a.replace('\n',' '),candidate_statement=s.replace('\n',' '),assessment=v,reason=w.replace('\n',' ')) for a,s,v,w,_,_ in rows])
    f=figure('DOES THE CLAIM FOLLOW FROM THE SUPPLIED RECORD?','A citation is useful only when the cited evidence supports the statement.',
             'Fictional teaching case • candidate statements written for this exercise • no real batch, model output or measured model performance')
    ax=f.add_axes([.06,.12,.88,.70]);ax.set_xlim(0,1);ax.set_ylim(0,1);ax.axis('off')
    xs=[0,.34,.70,1];hdr=['Source evidence','Candidate statement','Assessment']
    ax.add_patch(Rectangle((0,.88),1,.12,color=NAVY,lw=0))
    for x0,h in zip(xs,hdr):ax.text(x0+.02,.94,h,color='white',fontsize=15,fontweight='bold',va='center')
    for i,(a,s,v,w,bg,c) in enumerate(rows):
        y0=.88-(i+1)*.29;ax.add_patch(Rectangle((0,y0),1,.285,color=bg,lw=0))
        ax.text(.02,y0+.14,a,fontsize=13,color=NAVY,va='center');ax.text(.36,y0+.14,s,fontsize=13,color=NAVY,va='center')
        ax.text(.72,y0+.19,v,fontsize=14,fontweight='bold',color=c,va='center');ax.text(.72,y0+.09,w,fontsize=12,color=NAVY,va='center')
    save(f,b,'language/claims-and-evidence.png')

# ---------------------------------------------------------------- reading 9: capstone timeline
EVENTS=[('Feeder disturbance (R2)','10:03:00','10:03:20',ORANGE),('Preliminary arrival screening (R5)','10:03:20','10:05:15',PURPLE),
        ('Confirmed diversion position (R4)','10:04:05','10:06:00',TEAL),('NIR applicability flag (R3)','10:02:40','10:06:20',RED)]
def secs(s):h,m,x=map(int,s.split(':'));return h*3600+m*60+x
def hhmmss(n):return f'{n//3600:02d}:{n%3600//60:02d}:{n%60:02d}'
def r9(b):
    ev_start,ev_end=secs('10:03:00'),secs('10:03:20');scr=(hhmmss(ev_start+25-5),hhmmss(ev_end+110+5))
    assert scr==('10:03:20','10:05:15')
    gap=secs('10:04:05')-secs(scr[0]);kg=60*gap/3600
    write(b,'fictional-event-times.csv',[dict(case_record=n,start_time=s,end_time=e) for n,s,e,_ in EVENTS])
    write(b,'screening-calculation.csv',[dict(event_start='10:03:00',event_end='10:03:20',offset_min_s=25,offset_max_s=110,allowance_s=5,screen_start=scr[0],screen_end=scr[1],confirmed_diversion='10:04:05',uncovered_gap_s=gap,output_rate_kg_per_h=60,screening_quantity_kg=f'{kg:.2f}')])
    f=figure('PUT THE EVENT, APPLICABILITY AND ROUTING ON ONE CLOCK',f'Fictional batch C-309. The screening interval starts {gap} s before diversion is confirmed: at 60 kg/h, a screening estimate of {kg:.2f} kg.',
             'Fictional teaching records • screening interval is not a validated collection boundary • position confirmation does not establish complete physical routing')
    ax=f.add_axes([.27,.17,.68,.58]);t0=secs('10:02:00')
    for i,(n,s,e,c) in enumerate(reversed(EVENTS)):
        a,z=secs(s)-t0,secs(e)-t0;ax.barh(i,z-a,left=a,height=.45,color=c)
        ax.text(a,i+.3,s,fontsize=10.5,color=c,va='bottom');ax.text(z,i-.3,e,fontsize=10.5,color=c,ha='right',va='top')
    ax.set(yticks=range(4),yticklabels=[e[0] for e in reversed(EVENTS)],xlim=(0,300),ylim=(-.7,4.4),xlabel='Recorded time on the case clock')
    ax.set_xticks(range(0,301,30));ax.set_xticklabels([hhmmss(t0+x) for x in range(0,301,30)],fontsize=10.5)
    g0,g1=secs(scr[0])-t0,secs('10:04:05')-t0
    for x in (g0,g1):ax.axvline(x,color=GREY,ls=':',lw=1.2)
    ax.annotate('',xy=(g1,3.95),xytext=(g0,3.95),arrowprops=dict(arrowstyle='<->',color=NAVY,lw=1.8))
    ax.text((g0+g1)/2,4.05,f'{gap} s before confirmed diversion',ha='center',fontsize=12,color=NAVY)
    save(f,b,'capstone/capstone-timeline.png')

if __name__=='__main__':
    for n in ([ONLY] if ONLY else sorted(SLUGS)):
        b=BASE/SLUGS[n];(b/'data').mkdir(parents=True,exist_ok=True)
        globals()[f'r{n}'](b)
        if not ONLY:shutil.copyfile(HERE,b/'data/recompute.py')
        (b/'data/requirements-plot.txt').write_text(f'matplotlib=={matplotlib.__version__}\nnumpy=={np.__version__}\n')
        print('Generated',SLUGS[n])
