"""Reproduce the constructed wet-chemistry 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.
Compound X hydrochloride monohydrate uses a constructed free-base formula, C18H23NO3.
"""
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 FancyBboxPatch
SLUGS={1:'1-what-the-chromatogram-cannot-see',2:'2-titration-counting-against-a-standard',3:'3-karl-fischer-water-specifically',4:'4-loss-on-drying-and-residue-on-ignition',5:'5-ion-chromatography-back-to-the-column',6:'6-making-the-specification-add-up'}
HERE=Path(__file__).resolve()
ONLY=int(HERE.parent.parent.name[0]) if HERE.parent.name=='data' else None
BASE=HERE.parent.parent.parent if ONLY else HERE.parents[2]/'content/en/2026-lecture/8-nov2/4-wet-chemistry-workhorses'
NAVY='#15334e';TEAL='#007f91';ORANGE='#cc652b';GREY='#526879'
plt.rcParams.update({'font.family':'DejaVu Sans','font.size':13,'axes.spines.top':False,'axes.spines.right':False})
# Constructed composition of Compound X·HCl·H2O (IUPAC 2021 standard atomic weights, rounded)
AW=dict(C=12.011,H=1.008,N=14.007,O=15.999,Cl=35.453)
M_BASE=18*AW['C']+23*AW['H']+AW['N']+3*AW['O']
M_HCL=AW['H']+AW['Cl']
M_H2O=2*AW['H']+AW['O']
M_SALT=M_BASE+M_HCL
M_HYD=M_SALT+M_H2O
FARADAY=96485.33212
def r(x,n=4):return round(float(x),n)
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 figure(title,subtitle):
    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,'Compound X·HCl·H₂O • constructed teaching example • not experimental data or an approved specification',fontsize=11,color=GREY)
    return f
def box(ax,x,y,w,h,text,face='#edf5f6',edge=TEAL,size=13):
    ax.add_patch(FancyBboxPatch((x,y),w,h,boxstyle='round,pad=0.015',facecolor=face,edgecolor=edge,lw=1.8))
    ax.text(x+w/2,y+h/2,text,ha='center',va='center',fontsize=size,color=NAVY)
def save(f,b,name):
    p=b/'images'/name;p.parent.mkdir(parents=True,exist_ok=True)
    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)
def r1(b):
    comp=[dict(component='Compound X free base (C18H23NO3)',molar_mass_g_mol=r(M_BASE,3),theoretical_percent_w_w=r(100*M_BASE/M_HYD,3),primary_test='LC assay against a qualified reference standard'),
          dict(component='chloride',molar_mass_g_mol=r(AW['Cl'],3),theoretical_percent_w_w=r(100*AW['Cl']/M_HYD,3),primary_test='ion chromatography (or argentometric titration)'),
          dict(component='proton of the hydrochloride',molar_mass_g_mol=r(AW['H'],3),theoretical_percent_w_w=r(100*AW['H']/M_HYD,3),primary_test='inferred from stoichiometry; acid-base titration counts it'),
          dict(component='water of hydration',molar_mass_g_mol=r(M_H2O,3),theoretical_percent_w_w=r(100*M_H2O/M_HYD,3),primary_test='Karl Fischer titration')]
    write(b,'theoretical-composition.csv',comp)
    spec=[('Identification','IR; chloride identity test','Is this the named salt?','purity or form by itself','LC retention match'),
          ('Assay','LC, anhydrous solvent-free basis','How much Compound X?','water or counterion content','titration as development cross-check'),
          ('Related substances','LC','Which organic impurities and how much?','inorganic or volatile content','orthogonal LC in development'),
          ('Water','Karl Fischer','Is total water consistent with the intended composition?','other volatiles or crystal form by itself','XRPD, TGA and LOD in development'),
          ('Chloride content','Ion chromatography','Is bulk chloride consistent with the intended composition?','cation identity, protonation or solid-state salt identity','argentometric titration and solid-state evidence'),
          ('Residual solvents','GC headspace','Which solvents and how much?','water','LOD minus KF as a rough check'),
          ('Residue on ignition','Gravimetric, sulfated','How much non-volatile inorganic residue?','which elements are present','Q3D risk assessment and ICP methods')]
    write(b,'specification-map.csv',[dict(attribute=a,teaching_test=t,question_answered=q,cannot_establish=c,cross_check=x) for a,t,q,c,x in spec])
    f=figure('WHICH TEST SEES WHICH PART OF THE MASS','Theoretical composition of the constructed hydrochloride monohydrate and the test that answers for each slice.')
    ax=f.add_axes([.06,.40,.88,.34]);ax.set(xlim=(0,100),ylim=(0,1));ax.axis('off')
    parts=[(100*M_BASE/M_HYD,'#cfe3e6','Free base\n%.2f%%'),(100*M_HCL/M_HYD,'#f3d6c4','HCl\n%.2f%%'),(100*M_H2O/M_HYD,'#d9e1ea','H₂O\n%.2f%%')]
    x=0
    for w,c,lab in parts:
        ax.add_patch(plt.Rectangle((x,.35),w,.45,facecolor=c,edgecolor=NAVY,lw=1.5))
        ax.text(x+w/2,.575,lab%w,ha='center',va='center',fontsize=15 if w>20 else 12,color=NAVY,fontweight='bold')
        x+=w
    for x0,x1,t in [(0,100*M_BASE/M_HYD,'LC assay and related substances  →  organic part only'),(100*M_BASE/M_HYD,100*M_SALT/M_HYD,'IC: chloride'),(100*M_SALT/M_HYD,100,'KF: water')]:
        ax.annotate('',xy=(x0,.25),xytext=(x1,.25),arrowprops=dict(arrowstyle='<->',color=TEAL,lw=2))
        ax.text((x0+x1)/2,.08,t,ha='center',fontsize=13 if x1-x0>20 else 12,color=TEAL)
    ax2=f.add_axes([.06,.10,.88,.24]);ax2.set(xlim=(0,1),ylim=(0,1));ax2.axis('off')
    for i,t in enumerate(['Water supports composition:\nverify hydrate form separately','Chloride checks composition:\nnot protonation or crystal form','ROI and LOD answer for\nwhat no slice above contains']):
        box(ax2,.01+.335*i,.12,.31,.72,t,size=13)
    save(f,b,'scope/composition-and-tests.png')
def titration_ph(v_ml,n_base_mmol,n_hcl_mmol,c_naoh,v0_ml,pka1,pka2):
    """pH from the charge balance; amine and phenol treated as independent sites, aqueous Kw."""
    vt=v0_ml+v_ml;cb=n_base_mmol/vt;cl=(n_base_mmol+n_hcl_mmol)/vt;na=c_naoh*v_ml/vt
    ka1=10**-pka1;ka2=10**-pka2 if pka2 else 0.0;kw=1e-14
    lo,hi=-14.5,0.0
    for _ in range(80):
        mid=(lo+hi)/2;h=10**mid
        g=h+na+cb*h/(h+ka1)-kw/h-cl-(cb*ka2/(h+ka2) if ka2 else 0)
        if g>0:hi=mid
        else:lo=mid
    return -(lo+hi)/2
def r2(b):
    khp_m=204.221;c_true=0.1003
    std=[]
    for i,(m,e) in enumerate([(0.4083,0.004),(0.4102,-0.006),(0.4095,0.002)]):
        v=m/khp_m/c_true*1000+e
        std.append(dict(replicate=i+1,KHP_mass_g=m,KHP_molar_mass_g_mol=khp_m,endpoint_volume_mL=r(v,3),NaOH_molarity_mol_L=r(m/khp_m/(v/1000),5)))
    cs=[x['NaOH_molarity_mol_L'] for x in std];mean=float(np.mean(cs));sd=float(np.std(cs,ddof=1))
    std.append(dict(replicate='mean',KHP_mass_g='',KHP_molar_mass_g_mol='',endpoint_volume_mL='',NaOH_molarity_mol_L=r(mean,5)))
    std.append(dict(replicate='RSD_percent',KHP_mass_g='',KHP_molar_mass_g_mol='',endpoint_volume_mL='',NaOH_molarity_mol_L=r(100*sd/mean,3)))
    write(b,'titrant-standardization.csv',std)
    m_mg=300.0;n=m_mg/M_HYD;n_hcl=0.05;c=mean;v0=50.0
    vs=np.round(np.arange(0,20.0001,0.02),3)
    curves={}
    for case,pka2 in [('amine_and_phenol',10.2),('hypothetical_amine_only',None)]:
        ph=np.array([titration_ph(v,n,n_hcl,c,v0,8.8,pka2) for v in vs])
        curves[case]=(ph,np.gradient(ph,vs))
    write(b,'titration-curve.csv',[dict(volume_mL=float(v),pH_amine_and_phenol=r(curves['amine_and_phenol'][0][i],4),dpH_dV_amine_and_phenol=r(curves['amine_and_phenol'][1][i],4),pH_hypothetical_amine_only=r(curves['hypothetical_amine_only'][0][i],4),dpH_dV_hypothetical_amine_only=r(curves['hypothetical_amine_only'][1][i],4)) for i,v in enumerate(vs)])
    v1=n_hcl/c;v2=v1+n/c;v3=v1+2*n/c
    ep=[]
    for case in curves:
        d=curves[case][1]
        for label,lo,hi,true in [('excess HCl',0.1,3,v1),('amine hydrochloride',6,12,v2),('phenol',14,19.9,v3)]:
            if case=='hypothetical_amine_only' and label=='phenol':continue
            idx=[i for i in range(1,len(vs)-1) if lo<=vs[i]<=hi and d[i]>=d[i-1] and d[i]>=d[i+1]]
            i=max(idx,key=lambda k:d[k]) if idx else None
            ep.append(dict(curve=case,endpoint=label,stoichiometric_volume_mL=r(true,3),local_maximum_found='yes' if i is not None else 'no',apparent_volume_mL=r(vs[i],3) if i is not None else '',max_dpH_dV=r(d[i],3) if i is not None else '',pH_at_stoichiometric_point=r(titration_ph(true,n,n_hcl,c,v0,8.8,10.2 if case=='amine_and_phenol' else None),3)))
    write(b,'endpoint-summary.csv',ep)
    def found(case,label):return next(e for e in ep if e['curve']==case and e['endpoint']==label)
    assay=[]
    for case,label,eq,txt in [('hypothetical_amine_only','amine hydrochloride',1,'hypothetical amine only: first to second inflection'),('amine_and_phenol','amine hydrochloride',1,'amine and phenol: first to second inflection'),('amine_and_phenol','phenol',2,'amine and phenol: first to third inflection, divided by two')]:
        e1=found(case,'excess HCl');e2=found(case,label)
        if e2['local_maximum_found']!='yes':continue
        dv=float(e2['apparent_volume_mL'])-float(e1['apparent_volume_mL'])
        assay.append(dict(approach=txt,delta_volume_mL=r(dv,3),stoichiometric_delta_mL=r(eq*n/c,3),computed_percent_of_hydrate_taken=r(dv*c/eq*M_HYD/m_mg*100,2)))
    write(b,'titration-assay.csv',assay)
    bias=[]
    for name,mm in [('basic process impurity, free base 287.4 g/mol, as HCl salt',287.4+M_HCL),('basic degradant, free base 317.4 g/mol, as HCl salt',317.4+M_HCL)]:
        # each mole of impurity is counted as a mole of Compound X·HCl·H2O
        for w in [0.1,0.5,1.0]:bias.append(dict(impurity=name,impurity_percent_w_w=w,titration_assay_bias_points=r(w*M_HYD/mm,3),LC_assay_bias_if_resolved=0))
    write(b,'specificity-bias.csv',bias)
    f=figure('A TITRATION COUNTS EVERY SITE THAT REACTS','Computed NaOH titration of 300 mg Compound X·HCl·H₂O with 0.050 mmol excess HCl; aqueous model, independent site pKa values.')
    for k,(case,lab,col) in enumerate([('amine_and_phenol','Amine (pKa 8.8) + phenol (pKa 10.2)',NAVY),('hypothetical_amine_only','Hypothetical amine only',ORANGE)]):
        ax=f.add_axes([.08,.48,.84,.33]) if k==0 else ax
        ax.plot(vs,curves[case][0],color=col,lw=2.5 if k==0 else 1.8,ls='-' if k==0 else '--',label=lab)
    ax.set(ylabel='pH',xlim=(0,20));ax.legend(fontsize=11,loc='upper left',bbox_to_anchor=(.06,1));ax.tick_params(labelbottom=False)
    for v,t in [(v1,'excess HCl'),(v2,'amine'),(v3,'phenol')]:
        ax.axvline(v,color=GREY,lw=1,ls=':');ax.text(v+.12,3.0,t,fontsize=11,color=GREY)
    ax2=f.add_axes([.08,.13,.84,.30])
    ax2.plot(vs,curves['amine_and_phenol'][1],color=NAVY,lw=2.5);ax2.plot(vs,curves['hypothetical_amine_only'][1],color=ORANGE,lw=1.8,ls='--')
    ax2.set(xlabel='0.1 M NaOH added (mL)',ylabel='dpH/dV (per mL)',xlim=(0,20),ylim=(0,3))
    for v in [v1,v2,v3]:ax2.axvline(v,color=GREY,lw=1,ls=':')
    ax2.text(1.3,2.6,'first-inflection derivative continues off scale',fontsize=11,color=GREY)
    save(f,b,'titration/two-site-titration-curve.png')
def r3(b):
    q=2*FARADAY/(M_H2O*1000)
    sel=[]
    for label,wp in [('anhydrous intermediate',0.05),('hygroscopic excipient blend',0.5),('Compound X·HCl·H2O',100*M_H2O/M_HYD)]:
        for mg in [50,100,200]:
            w=mg*wp/100
            sel.append(dict(sample=label,water_percent=r(wp,3),sample_mass_mg=mg,water_mg=r(w,4),volumetric_titrant_mL_at_5_mg_per_mL=r(w/5,4),volumetric_titrant_mL_at_1_mg_per_mL=r(w/1,4),coulometric_charge_C=r(w*q,3),coulometric_minutes_at_100_mA=r(w*q/0.1/60,2)))
    write(b,'technique-selection.csv',sel)
    titers=[5.02,4.97,4.93,4.88,4.84];v=1.010;m=100.0
    rows=[]
    for i,t in enumerate(titers):
        rows.append(dict(day=['Mon','Tue','Wed','Thu','Fri'][i],measured_titer_mg_per_mL=t,titrant_volume_mL_for_constructed_sample=r(m*100*M_H2O/M_HYD/100/t,4),water_percent_with_same_day_titer=r(100*M_H2O/M_HYD,3),water_percent_with_monday_titer=r(100*M_H2O/M_HYD*titers[0]/t,3),relative_bias_percent=r(100*(titers[0]/t-1),2)))
    write(b,'titer-drift.csv',rows)
    drift=[]
    for label,water_ug,minutes,drift_ug in [('volumetric, monohydrate, 100 mg',5062,3,10),('coulometric, anhydrous intermediate, 100 mg',50,4,5),('coulometric, anhydrous intermediate, 100 mg, poor seal',50,4,20)]:
        drift.append(dict(case=label,true_water_ug=water_ug,titration_minutes=minutes,background_drift_ug_per_min=drift_ug,uncorrected_bias_ug=drift_ug*minutes,uncorrected_relative_bias_percent=r(100*drift_ug*minutes/water_ug,2)))
    write(b,'drift-correction.csv',drift)
    write(b,'coulometric-constant.csv',[dict(electrons_per_water=2,faraday_C_mol=FARADAY,water_molar_mass_g_mol=r(M_H2O,3),coulombs_per_mg_water=r(q,4))])
    f=figure('THE TITER DECIDES THE ANSWER BEFORE THE SAMPLE DOES','Constructed daily titer checks; the same titrant volume reported with Monday’s titer drifts high all week.')
    ax=f.add_axes([.08,.18,.38,.60]);d=read(b,'titer-drift.csv')
    ax.plot(range(5),[float(x['measured_titer_mg_per_mL']) for x in d],marker='o',color=TEAL,lw=2.5)
    ax.set(xticks=range(5),xticklabels=[x['day'] for x in d],ylabel='Measured titer (mg water per mL)',ylim=(4.75,5.1))
    ax2=f.add_axes([.56,.18,.38,.60])
    ax2.plot(range(5),[float(x['water_percent_with_same_day_titer']) for x in d],marker='o',color=TEAL,lw=2.5,label='Same-day titer')
    ax2.plot(range(5),[float(x['water_percent_with_monday_titer']) for x in d],marker='s',color=ORANGE,lw=2.5,label='Monday titer reused')
    ax2.axhline(5.5,color=GREY,ls=':',lw=1.2);ax2.text(2.2,5.51,'teaching upper limit 5.5%',fontsize=11,color=GREY)
    ax2.set(xticks=range(5),xticklabels=[x['day'] for x in d],ylabel='Reported water (% w/w)',ylim=(4.9,5.6));ax2.legend(fontsize=11,loc='lower right',bbox_to_anchor=(1,.02))
    save(f,b,'kf/titer-drift-bias.png')
def r4(b):
    w_kf=5.10;eth=0.12;hcl_rate=0.08
    rows=[];m0=1.0000
    hours=[0,1,2,3,4,5]
    for h in hours:
        nominal=(w_kf+eth)*(1-math.exp(-1.6*h))
        surface=(w_kf+eth+0.30)*(1-math.exp(-1.6*h))
        hcl=nominal+hcl_rate*max(0,h-1)
        rows.append(dict(hour=h,nominal_loss_percent=r(nominal,3),surface_moisture_loss_percent=r(surface,3),HCl_loss_scenario_percent=r(hcl,3)))
    write(b,'drying-curve.csv',rows)
    cw=[]
    for key in ['nominal_loss_percent','surface_moisture_loss_percent','HCl_loss_scenario_percent']:
        for i in range(1,len(rows)):
            dmg=(float(rows[i][key])-float(rows[i-1][key]))/100*m0*1000
            cw.append(dict(scenario=key.replace('_percent',''),from_hour=rows[i-1]['hour'],to_hour=rows[i]['hour'],change_mg_per_g=r(dmg/m0,3),meets_0_50_mg_per_g='yes' if dmg/m0<=0.50 else 'no'))
    write(b,'constant-weight-check.csv',cw)
    rec=[('nominal batch',5.10,0.12,5.22,'none: LOD is water plus solvent'),
         ('surface moisture after humid storage',5.40,0.12,5.52,'KF and LOD rise together; investigate added water and form'),
         ('HCl lost during drying',5.10,0.12,5.54,'LOD exceeds KF + GC; mass is leaving that is neither'),
         ('incomplete dehydration at 105 C',5.10,0.12,3.90,'LOD below KF; investigate release, recovery and bias')]
    write(b,'lod-kf-reconciliation.csv',[dict(scenario=s,KF_water_percent=k,GC_ethanol_percent=g,LOD_percent=l,LOD_minus_KF_minus_GC=r(l-k-g,2),reading=t) for s,k,g,l,t in rec])
    roi=[]
    for m in [0.5,1.0,2.0]:
        res=m*1000*0.001;u=math.sqrt(2)*0.05
        roi.append(dict(sample_mass_g=m,residue_at_0_1_percent_limit_mg=r(res,3),balance_sd_per_weighing_mg=0.05,u_residue_mg=r(u,3),relative_u_at_limit_percent=r(100*u/res,1)))
    write(b,'roi-weighing-budget.csv',roi)
    f=figure('LOSS ON DRYING WEIGHS EVERYTHING THAT LEAVES','Constructed drying curves at 105 °C and the reconciliation each scenario requires.')
    ax=f.add_axes([.07,.17,.40,.62])
    for key,col,lab,ls in [('nominal_loss_percent',TEAL,'Nominal','-'),('surface_moisture_loss_percent',NAVY,'Surface moisture','--'),('HCl_loss_scenario_percent',ORANGE,'HCl loss','-')]:
        ax.plot(hours,[float(x[key]) for x in rows],marker='o',color=col,ls=ls,lw=2.3,label=lab)
    ax.set(xlabel='Hours at 105 °C',ylabel='Mass loss (% w/w)',ylim=(0,6.2));ax.legend(fontsize=11,loc='lower right')
    ax.text(1.4,1.3,'HCl-loss curve never reaches\nconstant weight',fontsize=11,color=ORANGE)
    ax2=f.add_axes([.56,.17,.38,.62]);rr=read(b,'lod-kf-reconciliation.csv')
    labs=['Nominal','Surface\nmoisture','HCl\nloss','Incomplete\ndehydration'];x=np.arange(4)
    ax2.bar(x-.18,[float(z['KF_water_percent']) for z in rr],.34,color='#cfe3e6',edgecolor=NAVY,label='KF water')
    ax2.bar(x-.18,[float(z['GC_ethanol_percent']) for z in rr],.34,bottom=[float(z['KF_water_percent']) for z in rr],color=TEAL,edgecolor=NAVY,label='GC ethanol')
    ax2.bar(x+.18,[float(z['LOD_percent']) for z in rr],.34,color='#f3d6c4',edgecolor=ORANGE,label='LOD')
    ax2.set(xticks=x,xticklabels=labs,ylabel='% w/w',ylim=(0,6.5));ax2.legend(fontsize=11,loc='upper left',ncol=3)
    save(f,b,'gravimetry/lod-versus-kf.png')
def r5(b):
    t0=2.40;N=6000
    peaks=[('fluoride',3.30,0.05),('chloride',5.10,2.48),('nitrite',5.95,0.05),('bromide',7.60,0.05),('nitrate',8.60,0.05),('sulfate',11.20,0.10)]
    tab=[]
    for i,(nme,tr,conc) in enumerate(peaks):
        s=tr/math.sqrt(N);wb=4*s;k=(tr-t0)/t0
        row=dict(ion=nme,retention_min=tr,k=r(k,3),wb_min=r(wb,4),constructed_concentration_ug_mL=conc)
        if i:
            p=peaks[i-1];sp=p[1]/math.sqrt(N);kp=(p[1]-t0)/t0
            row.update(alpha_vs_previous=r(k/kp,3),Rs_vs_previous=r(2*(tr-p[1])/(wb+4*sp),2))
        else:row.update(alpha_vs_previous='',Rs_vs_previous='')
        tab.append(row)
    write(b,'ic-peak-table.csv',tab)
    ts=np.round(np.arange(0,14.0001,0.005),3);sig=np.zeros_like(ts)
    for nme,tr,conc in peaks:
        s=tr/math.sqrt(N);sig+=0.20*conc/(s*math.sqrt(2*math.pi))*np.exp(-0.5*((ts-tr)/s)**2)
    sig+=-0.4*np.exp(-0.5*((ts-t0)/0.06)**2)
    write(b,'ic-chromatogram.csv',[dict(time_min=float(t),conductivity_uS=r(y,4)) for t,y in zip(ts,sig)])
    levels=[0.5,1.0,2.0,4.0,6.0];noise=[0.003,-0.004,0.002,0.005,-0.003]
    cal=[dict(level=i+1,chloride_ug_mL=c,peak_area_uS_min=r(0.200*c+e,4)) for i,(c,e) in enumerate(zip(levels,noise))]
    write(b,'ic-calibration.csv',cal)
    x=np.array(levels);y=np.array([float(c['peak_area_uS_min']) for c in cal]);sl,ic=np.polyfit(x,y,1)
    target=9.92;mass=25.00;dil=1000.0
    conc=mass*1000*target/100/dil;area=0.200*conc+0.001
    found=(area-ic)/sl;pct=found*dil/(mass*1000)*100
    write(b,'chloride-assay.csv',[dict(sample_mass_mg=mass,total_dilution_mL=dil,sample_peak_area_uS_min=r(area,4),slope=r(sl,5),intercept=r(ic,5),chloride_found_ug_mL=r(found,4),chloride_percent_w_w=r(pct,3),theoretical_percent_w_w=r(100*AW['Cl']/M_HYD,3),chloride_to_base_molar_ratio_if_base_84_30_percent=r((pct/AW['Cl'])/(84.30/M_BASE),4))])
    f=figure('CONDUCTIVITY SEES WHAT UV CANNOT','Constructed suppressed-conductivity anion chromatogram of a diluted Compound X·HCl·H₂O solution with trace anions.')
    ax=f.add_axes([.08,.16,.84,.62])
    ax.plot(ts,sig,color=NAVY,lw=1.8);ax.set(xlabel='Time (min)',ylabel='Conductivity (µS)',xlim=(0,14),ylim=(-.6,4))
    for row in tab:
        tr=float(row['retention_min']);h=sig[int(round(tr/0.005))]
        lab=row['ion']+('' if row['ion']=='chloride' else '\n(trace)')
        ax.text(tr,h+.25,lab,ha='center',fontsize=11,color=TEAL if row['ion']!='chloride' else NAVY)
    rs=next(x for x in tab if x['ion']=='nitrite')
    ax.text(6.3,2.6,f"Chloride / nitrite: k = {tab[1]['k']} and {rs['k']}, α = {rs['alpha_vs_previous']}, Rs = {rs['Rs_vs_previous']}",fontsize=13,color=ORANGE)
    ax.text(2.0,-.55,'water dip (schematic)',fontsize=10,color=GREY)
    save(f,b,'ic/anion-chromatogram.png')
def r6(b):
    comps=[('Compound X free base (LC, as-is)',84.30,0.40),('HCl (from IC chloride 9.92%)',9.92*M_HCL/AW['Cl'],0.10*M_HCL/AW['Cl']),('water (KF)',5.10,0.05),('ethanol (GC)',0.12,0.01),('organic impurities (LC, as free base)',0.25,0.03),('residue on ignition',0.03,0.02)]
    rows=[dict(component=c,percent_w_w=r(v,3),standard_uncertainty_percent=r(u,3)) for c,v,u in comps]
    tot=sum(v for _,v,_ in comps);ut=math.sqrt(sum(u*u for *_,u in comps))
    rows.append(dict(component='TOTAL',percent_w_w=r(tot,3),standard_uncertainty_percent=r(ut,3)))
    write(b,'specification-balance.csv',rows)
    nb=84.30/M_BASE
    ratios=[dict(ratio='chloride : free base',value=r((9.92/AW['Cl'])/nb,4),expected=1),dict(ratio='water : free base',value=r((5.10/M_H2O)/nb,4),expected=1)]
    write(b,'stoichiometry.csv',ratios)
    as_salt=84.30*M_SALT/M_BASE
    basis=[]
    for label,kf in [('KF as reported',5.10),('KF biased by stale titer (+3.7% relative)',5.10*1.037)]:
        basis.append(dict(water_input=label,water_percent=r(kf,3),ethanol_percent=0.12,LC_assay_as_is_as_anhydrous_HCl_salt=r(as_salt,3),assay_anhydrous_solvent_free_basis=r(as_salt/(1-(kf+0.12)/100),3)))
    write(b,'basis-correction.csv',basis)
    scen=[('nominal',84.30,9.92,5.10,0.12),('low chloride input',84.30,9.40,5.10,0.12),('low water input',84.30,9.92,4.00,0.12),('low API input',83.10,9.92,5.10,0.12)]
    sc=[]
    for s,base,cl,w,e in scen:
        t=base+cl*M_HCL/AW['Cl']+w+e+0.25+0.03;nb2=base/M_BASE
        sc.append(dict(scenario=s,total_percent=r(t,2),expanded_uncertainty_k2=r(2*ut,2),gap_outside_uncertainty='yes' if abs(t-100)>2*ut else 'no',chloride_to_base=r((cl/AW['Cl'])/nb2,3),water_to_base=r((w/M_H2O)/nb2,3)))
    write(b,'reconciliation-scenarios.csv',sc)
    ctl=[('Acid–base titration','titrant standardized against a primary standard; blank','titer drift, carbonate uptake','a reacting impurity counted as analyte'),
         ('Karl Fischer','titer or water-standard recovery; drift before each sample','reagent exhaustion, leaking cell','a side reaction that makes or consumes water'),
         ('Loss on drying','dry to constant weight; empty-vessel check','incomplete drying, balance error','what left: water, solvent or HCl'),
         ('Residue on ignition','crucible ignited to constant weight','weighing and crucible error','which elements are present'),
         ('Ion chromatography','SST: chloride/nitrite Rs, replicate %RSD, check standard','column or suppressor decline','an anion co-eluting with chloride if not in the SST mixture')]
    write(b,'routine-control.csv',[dict(test=t,running_proof=p,what_it_catches=c,what_it_cannot_catch=m) for t,p,c,m in ctl])
    f=figure('THE SPECIFICATION HAS TO ADD UP','Constructed results for one batch, summed with standard uncertainties; isolated input changes illustrate sensitivity, not physical loss.')
    ax=f.add_axes([.07,.16,.40,.62])
    cols=['#cfe3e6','#f3d6c4','#d9e1ea',TEAL,ORANGE,GREY];bottom=0
    for (c,v,u),col in zip(comps,cols):
        ax.bar(0,v,.5,bottom=bottom,color=col,edgecolor=NAVY,label=c);bottom+=v
    ax.errorbar(0,tot,yerr=2*ut,color=NAVY,capsize=10,lw=2)
    ax.axhline(100,color=GREY,ls=':');ax.set(xlim=(-.4,1.6),ylim=(80,102),xticks=[],ylabel='% w/w (stacked from 80%)')
    ax.text(-.35,101.1,f'Total {tot:.2f}% ± {2*ut:.2f}% (k = 2)',fontsize=13,color=NAVY)
    ax.legend(fontsize=11,loc='center left',bbox_to_anchor=(.36,.45),frameon=False)
    ax2=f.add_axes([.62,.16,.33,.62]);s=read(b,'reconciliation-scenarios.csv')
    y=np.arange(len(s))[::-1]
    ax2.barh(y-.12,[float(z['total_percent'])-100 for z in s],height=.4,color=[TEAL if z['gap_outside_uncertainty']=='no' else ORANGE for z in s])
    ax2.axvspan(-2*ut,2*ut,color='#edf5f6',zorder=0);ax2.axvline(0,color=GREY,lw=1)
    for yy,z in zip(y,s):ax2.text(-1.75,yy+.3,f"{float(z['total_percent'])-100:+.2f} pts • Cl:base {z['chloride_to_base']} • H₂O:base {z['water_to_base']}",fontsize=11,color=NAVY)
    ax2.text(-2*ut+.03,len(s)-.45,'±U (k = 2)',fontsize=11,color=GREY)
    ax2.set(ylim=(-.6,len(s)-.3),yticks=y,yticklabels=[z['scenario'].replace(' (','\n(') for z in s],xlabel='Total − 100 (percentage points)',xlim=(-1.8,0.6),xticks=[-1.5,-1,-.5,0,.5])
    save(f,b,'balance/specification-balance.png')
if __name__=='__main__':
    for n in ([ONLY] if ONLY else range(1,7)):
        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])
