"""Reproduce the constructed dissolution 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.
The case is a constructed Compound X immediate-release tablet: 50 mg free-base equivalent as the HCl monohydrate.
"""
from pathlib import Path
import csv, math, runpy, shutil
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
SLUGS={1:'1-from-tablet-to-solution',2:'2-the-apparatus-is-part-of-the-method',3:'3-comparing-profiles',4:'4-discriminating-by-design',5:'5-acceptance-and-the-patient',6:'6-when-a-batch-fails'}
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/9-nov9/2-dissolution'
NAVY='#15334e';TEAL='#007f91';ORANGE='#cc652b';GREY='#526879';GOLD='#b08a1e'
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, as in Week 8
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_HYD=M_BASE+AW['H']+AW['Cl']+2*AW['H']+AW['O']
DOSE_MG=50.0;VOL_ML=900.0
PKA=8.8;S0_MG_ML=0.05;KSP=0.0036   # intrinsic free-base solubility; salt solubility product (mol/L)^2, both assumed
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 tablet, 50 mg • constructed teaching example • not experimental data or an approved method',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)
def solubility(ph,cl_extra=0.0):
    """Total solubility (mg/mL, as free base) of the HCl salt: the lower of the free-base and salt limits."""
    s0=S0_MG_ML/M_BASE                      # mol/L
    fb=s0*(1+10**(PKA-ph))
    bh=(-cl_extra+math.sqrt(cl_extra**2+4*KSP))/2   # [BH+] at salt saturation with extra chloride
    salt=bh*(1+10**(ph-PKA))
    return min(fb,salt)*M_BASE,('free base' if fb<salt else 'HCl salt')
def weibull(t,tau,beta=1.0,lag=1.0,fmax=100.0):
    t=np.asarray(t,dtype=float);x=np.clip(t-lag,0,None)
    return fmax*(1-np.exp(-(x/tau)**beta))
def f2(ref,test):
    ref=np.asarray(ref);test=np.asarray(test);return 50*math.log10(100/math.sqrt(1+np.mean((ref-test)**2)))
def f1(ref,test):
    ref=np.asarray(ref);test=np.asarray(test);return 100*np.sum(np.abs(ref-test))/np.sum(ref)
def f2_points(times,ref,test):
    """Time points up to and including the first at which both profiles reach 85%."""
    idx=[]
    for i,t in enumerate(times):
        idx.append(i)
        if ref[i]>=85 and test[i]>=85:break
    return idx
def r1(b):
    ph_rows=[]
    for ph in np.round(np.arange(1.0,10.01,0.1),2):
        s,lim=solubility(ph);ph_rows.append(dict(pH=float(ph),solubility_mg_mL_as_free_base=r(s,4),limited_by=lim))
    write(b,'ph-solubility.csv',ph_rows)
    s0m=S0_MG_ML/M_BASE;phmax=PKA+math.log10(s0m/math.sqrt(KSP))
    media=[('0.1 N HCl',1.2,0.1),('acetate pH 4.5',4.5,0.0),('phosphate pH 6.8',6.8,0.0),('water (unbuffered, salt sets pH)',None,0.0),('phosphate pH 7.5',7.5,0.0),('borate pH 9.0',9.0,0.0)]
    sink=[]
    for name,ph,cl in media:
        if ph is None:s,lim=solubility(phmax-0.5);ph_s='~'+str(round(phmax-0.5,1))
        else:s,lim=solubility(ph,cl);ph_s=ph
        cap=s*VOL_ML
        sink.append(dict(medium=name,pH=ph_s,solubility_mg_mL=r(s,3),limited_by=lim,mg_dissolvable_in_900_mL=r(cap,1),sink_ratio_vs_50_mg=r(cap/DOSE_MG,1),meets_3x_sink='yes' if cap>=3*DOSE_MG else 'no',dose_solubility_volume_mL=r(DOSE_MG/s,1)))
    write(b,'sink-conditions.csv',sink)
    write(b,'salt-constants.csv',[dict(pKa=PKA,intrinsic_free_base_solubility_mg_mL=S0_MG_ML,Ksp_mol2_L2=KSP,salt_solubility_in_water_mg_mL=r(math.sqrt(KSP)*M_BASE,2),pHmax=r(phmax,2),tablet_free_base_mg=DOSE_MG,tablet_hydrate_mg=r(DOSE_MG*M_HYD/M_BASE,2))])
    # surface (diffusion-layer) solubility: the dissolving salt holds its own surface near pHmax; the free base does not
    salt_surface=math.sqrt(KSP)*M_BASE;fb_surface=solubility(6.8)[0]
    nw=[]
    for label,cs,area,h in [('HCl monohydrate, pH 6.8, 50 rpm',salt_surface,1.0,1.0),('HCl anhydrate, pH 6.8 (assumed 1.4x the hydrate)',1.4*salt_surface,1.0,1.0),('HCl monohydrate, coarse API (half the surface)',salt_surface,0.5,1.0),('HCl monohydrate, 75 rpm (boundary layer x0.7)',salt_surface,1.0,0.7),('free base, pH 6.8',fb_surface,1.0,1.0)]:
        nw.append(dict(case=label,surface_solubility_mg_mL=r(cs,2),relative_surface_area=area,relative_boundary_layer=h,relative_initial_rate=r(cs*area/h/salt_surface,2)))
    write(b,'noyes-whitney-levers.csv',nw)
    # The figure is an SVG in the Week 8 log D card style, drawn from the CSVs above by data/solubility-svg.py.
    # No matplotlib PNG is written for this reading.
    runpy.run_path(str(b/'data'/'solubility-svg.py'),run_name='__main__')
def r2(b):
    times=[5,10,15,20,30,45];true=weibull(times,8.0);vs=10.0
    rows=[];removed=0.0
    for i,t in enumerate(times):
        vol=VOL_ML-vs*i
        conc=(true[i]/100*DOSE_MG-removed)/vol
        uncorr=conc*VOL_ML/DOSE_MG*100
        corr=(conc*vol+removed)/DOSE_MG*100
        rows.append(dict(time_min=t,true_percent_released=r(true[i],2),medium_volume_mL=vol,concentration_mg_mL=r(conc,5),reported_uncorrected_percent=r(uncorr,2),reported_volume_and_mass_corrected_percent=r(corr,2)))
        removed+=conc*vs
    write(b,'sampling-correction.csv',rows)
    filt=[]
    for name,rec in [('PTFE 0.45 um, hydrophilic',[99.6,99.9,100.0]),('nylon 0.45 um',[91.2,96.8,99.1]),('glass fibre 1 um',[99.8,100.1,99.9]),('PVDF 0.45 um',[98.9,99.6,99.8])]:
        for disc,v in zip([0,2,5],rec):filt.append(dict(filter=name,discard_volume_mL=disc,recovery_percent_vs_centrifuged=v,meets_98_to_102='yes' if 98<=v<=102 else 'no'))
    write(b,'filter-recovery.csv',filt)
    write(b,'mechanical-checks.csv',[dict(parameter=p,why_it_matters=w) for p,w in [('rotational speed','sets the boundary-layer thickness and coning'),('shaft wobble and verticality','changes local hydrodynamics vessel to vessel'),('paddle or basket height','changes the flow field over the tablet'),('vessel centring and dimensions','asymmetric flow, coning under the paddle'),('temperature 37.0 +/- 0.5 C','solubility and diffusion coefficient'),('vibration','adds uncontrolled agitation'),('dissolved gas','bubbles on the tablet or basket mesh reduce wetting')]])
    f=figure('THE ARITHMETIC IS PART OF THE APPARATUS','Constructed profile with 10 mL samples removed at each point; and filter recovery against a centrifuged reference.')
    ax=f.add_axes([.07,.17,.40,.60])
    ax.plot(times,[z['true_percent_released'] for z in rows],color=GREY,lw=2,ls=':',label='True release')
    ax.plot(times,[z['reported_uncorrected_percent'] for z in rows],marker='s',color=ORANGE,lw=2.3,label='Uncorrected for removed volume')
    ax.plot(times,[z['reported_volume_and_mass_corrected_percent'] for z in rows],marker='o',color=TEAL,lw=2.3,label='Corrected')
    ax.set(xlabel='Time (min)',ylabel='% released',ylim=(0,105));ax.legend(fontsize=11,loc='lower right')
    ax2=f.add_axes([.57,.17,.37,.60]);names=['PTFE 0.45 um, hydrophilic','nylon 0.45 um','glass fibre 1 um','PVDF 0.45 um'];x=np.arange(4)
    for k,(disc,col) in enumerate([(0,ORANGE),(2,GOLD),(5,TEAL)]):
        ax2.bar(x+(k-1)*.26,[next(z['recovery_percent_vs_centrifuged'] for z in filt if z['filter']==n and z['discard_volume_mL']==disc) for n in names],.26,color=col,label=f'discard {disc} mL')
    ax2.axhspan(98,102,color='#edf5f6',zorder=0);ax2.set(xticks=x,xticklabels=['PTFE','Nylon','Glass fibre','PVDF'],ylabel='Recovery (%)',ylim=(88,102.5));ax2.legend(fontsize=11,loc='lower right')
    save(f,b,'apparatus/sampling-and-filters.png')
TIMES=[5,10,15,20,30,45]
PROFILES={'reference (clinical batch)':dict(tau=11.0,beta=1.0,lag=1.0),'T1 site transfer':dict(tau=11.7,beta=1.0,lag=1.2),'T2 slower start':dict(tau=12.5,beta=1.6,lag=2.5),'T3 faster':dict(tau=6.0,beta=1.0,lag=0.8)}
def unit_data(name,n=12,seed=7,cv_early=0.12,cv_late=0.04):
    rng=np.random.default_rng(seed+sum(map(ord,name)))
    p=PROFILES[name];out=[]
    for u in range(n):
        tau=p['tau']*math.exp(rng.normal(0,cv_early));fm=100*(1+rng.normal(0,cv_late*0.5))
        out.append(weibull(TIMES,tau,p['beta'],p['lag'],fm))
    return np.array(out)
def r3(b):
    units={k:unit_data(k,cv_early=0.25 if k.startswith('T2') else 0.10) for k in PROFILES}
    means={k:units[k].mean(axis=0) for k in units}
    prof=[]
    for k in PROFILES:
        sd=units[k].std(axis=0,ddof=1)
        for i,t in enumerate(TIMES):prof.append(dict(product=k,time_min=t,mean_percent=r(means[k][i],2),cv_percent=r(100*sd[i]/means[k][i],1)))
    write(b,'mean-profiles.csv',prof)
    write(b,'unit-data.csv',[dict(product=k,unit=u+1,**{f't{t}':r(units[k][u][i],2) for i,t in enumerate(TIMES)}) for k in units for u in range(len(units[k]))])
    ref=means['reference (clinical batch)'];res=[]
    rng=np.random.default_rng(2026)
    for k in list(PROFILES)[1:]:
        idx=f2_points(TIMES,ref,means[k]);rr_=[ref[i] for i in idx];tt=[means[k][i] for i in idx]
        boots=[]
        for _ in range(2000):
            a=units['reference (clinical batch)'][rng.integers(0,12,12)].mean(axis=0);c=units[k][rng.integers(0,12,12)].mean(axis=0)
            boots.append(f2([a[i] for i in idx],[c[i] for i in idx]))
        cv=[100*units[k][:,i].std(ddof=1)/means[k][i] for i in idx]
        res.append(dict(test=k,time_points_used=' '.join(str(TIMES[i]) for i in idx),f1=r(f1(rr_,tt),1),f2=r(f2(rr_,tt),1),bootstrap_f2_5th_percentile=r(np.percentile(boots,5),1),max_cv_first_point_percent=r(cv[0],1),max_cv_later_points_percent=r(max(cv[1:]),1),similar_by_mean_f2='yes' if f2(rr_,tt)>=50 else 'no'))
    write(b,'f2-results.csv',res)
    f=figure('SIMILAR MEANS SIMILAR SHAPE, NOT ONE GOOD POINT','Constructed mean profiles (12 units each, pH 6.8, paddle 50 rpm) of three test batches against the clinical reference, with f2.')
    ax=f.add_axes([.08,.16,.84,.62]);tf=np.linspace(0,45,200)
    for k,col in zip(PROFILES,[NAVY,TEAL,ORANGE,GOLD]):
        lab=k if k.startswith('reference') else f"{k}: f2 = {next(z['f2'] for z in res if z['test']==k)}"
        ax.plot(TIMES,means[k],marker='o',color=col,lw=2.4,label=lab)
    ax.axhline(85,color=GREY,ls=':');ax.text(31,86.5,'85%',fontsize=11,color=GREY)
    ax.set(xlabel='Time (min)',ylabel='Mean % released',xlim=(0,46),ylim=(0,105));ax.legend(fontsize=12,loc='lower right')
    save(f,b,'f2/profile-comparison.png')
VARIANTS={'hard tablet (high compression)':(1.6,1.6,1.0,1.0),'coarse API':(1.1,1.5,1.0,1.0),'over-lubricated':(1.35,1.45,1.0,1.0),'anhydrate API':(0.85,0.85,1.0,1.0),'5% disproportionated':(1.0,1.2,1.0,0.97)}
COND={'0.1 N HCl, 50 rpm':dict(tau=8.0,medium=0),'pH 6.8, 50 rpm':dict(tau=11.0,medium=1),'0.1 N HCl, 75 rpm':dict(tau=5.6,medium=0),'pH 6.8, 75 rpm':dict(tau=7.7,medium=1)}
def r4(b):
    rows=[];mat=[]
    for c,cp in COND.items():
        fast=c.endswith('75 rpm');ref=weibull(TIMES,cp['tau'])
        for v,(fh,fp,_,fm) in VARIANTS.items():
            fac=fh if cp['medium']==0 else fp
            if fast:fac=fac**0.6
            test=weibull(TIMES,cp['tau']*fac,fmax=100*(fm if cp['medium']==1 else 1.0))
            idx=f2_points(TIMES,ref,test);val=f2([ref[i] for i in idx],[test[i] for i in idx])
            mat.append(dict(condition=c,variant=v,f2=r(val,1),discriminates='yes' if val<50 else 'no',percent_at_15_min_ref=r(ref[2],1),percent_at_15_min_variant=r(test[2],1)))
            for i,t in enumerate(TIMES):rows.append(dict(condition=c,variant=v,time_min=t,reference_percent=r(ref[i],2),variant_percent=r(test[i],2)))
    write(b,'variant-profiles.csv',rows);write(b,'discrimination-matrix.csv',mat)
    f=figure('A METHOD DISCRIMINATES WHAT ITS CONDITIONS LET IT SEE','f2 of each deliberately varied batch against the reference, in four constructed test conditions; f2 < 50 means the method tells them apart.')
    ax=f.add_axes([.25,.14,.62,.64]);vs=list(VARIANTS);cs=list(COND)
    grid=np.array([[next(z['f2'] for z in mat if z['condition']==c and z['variant']==v) for c in cs] for v in vs])
    ax.imshow(grid<50,cmap=matplotlib.colors.ListedColormap(['#edf5f6','#f3d6c4']),aspect='auto')
    for i in range(len(vs)):
        for j in range(len(cs)):ax.text(j,i,f'{grid[i,j]:.0f}',ha='center',va='center',fontsize=16,color=ORANGE if grid[i,j]<50 else NAVY,fontweight='bold' if grid[i,j]<50 else 'normal')
    ax.set_xticks(range(len(cs)));ax.set_xticklabels(cs,fontsize=12);ax.set_yticks(range(len(vs)));ax.set_yticklabels(vs,fontsize=12)
    ax.tick_params(length=0);[s.set_visible(False) for s in ax.spines.values()]
    f.text(.25,.085,'Shaded orange: f2 < 50 (profiles not similar, variant detected). Pale: f2 ≥ 50 (variant passes as similar).',fontsize=12,color=GREY)
    save(f,b,'discrimination/discrimination-matrix.png')
def usp711(units6,more6,more12,Q):
    """Return the stage at which a lot is accepted (1, 2, 3) or 0 if it fails, under the USP <711> immediate-release table."""
    if np.all(units6>=Q+5):return 1
    u12=np.concatenate([units6,more6])
    if u12.mean()>=Q and np.all(u12>=Q-15):return 2
    u24=np.concatenate([u12,more12])
    if u24.mean()>=Q and np.sum(u24<Q-15)<=2 and np.all(u24>=Q-25):return 3
    return 0
def r5(b):
    Q=80;rng=np.random.default_rng(711);N=20000;oc=[]
    for sd in [3.0,6.0,10.0]:
        for mu in np.arange(78,100.1,1.0):
            x=rng.normal(mu,sd,(N,24));st=np.array([usp711(row[:6],row[6:12],row[12:],Q) for row in x])
            oc.append(dict(unit_sd=sd,batch_mean_percent=float(mu),P_accept_S1=r(np.mean(st==1),4),P_accept_S2=r(np.mean(st==2),4),P_accept_S3=r(np.mean(st==3),4),P_fail=r(np.mean(st==0),4),P_accept_total=r(np.mean(st>0),4)))
    write(b,'operating-characteristic.csv',oc)
    write(b,'usp711-stages.csv',[dict(stage='S1',units_tested=6,acceptance=f'each unit >= Q + 5% ({Q+5}%)'),dict(stage='S2',units_tested=6,acceptance=f'average of 12 >= Q ({Q}%); no unit < Q - 15% ({Q-15}%)'),dict(stage='S3',units_tested=12,acceptance=f'average of 24 >= Q ({Q}%); not more than 2 units < Q - 15% ({Q-15}%); no unit < Q - 25% ({Q-25}%)')])
    bcs=[]
    for med,ph,cl,tau in [('pH 1.2 (0.1 N HCl)',1.2,0.1,8.0),('pH 4.5 acetate',4.5,0.0,9.0),('pH 6.8 phosphate',6.8,0.0,11.0)]:
        s=solubility(ph,cl)[0];prof=weibull([15,30],tau)
        bcs.append(dict(medium=med,solubility_mg_mL=r(s,2),dose_volume_mL=r(DOSE_MG/s,1),highly_soluble_le_250_mL='yes' if DOSE_MG/s<=250 else 'no',percent_at_15_min=r(prof[0],1),percent_at_30_min=r(prof[1],1),very_rapid_ge_85_in_15='yes' if prof[0]>=85 else 'no',rapid_ge_85_in_30='yes' if prof[1]>=85 else 'no'))
    write(b,'bcs-check.csv',bcs)
    f=figure('THE STAGES DECIDE HOW CLOSE TO THE EDGE A LOT CAN BE','Monte Carlo probability of accepting a lot under the USP ⟨711⟩ stage rules, Q = 80%, for three unit-to-unit standard deviations.')
    ax=f.add_axes([.08,.16,.84,.62])
    for sd,col in [(3.0,TEAL),(6.0,NAVY),(10.0,ORANGE)]:
        q=[z for z in oc if z['unit_sd']==sd]
        ax.plot([z['batch_mean_percent'] for z in q],[z['P_accept_total'] for z in q],color=col,lw=2.6,label=f'Unit SD {sd:.0f}%: accepted at any stage')
        ax.plot([z['batch_mean_percent'] for z in q],[z['P_accept_S1'] for z in q],color=col,lw=1.6,ls='--',label=f'Unit SD {sd:.0f}%: accepted at S1')
    ax.axvline(Q,color=GREY,ls=':');ax.text(Q+.2,.05,'Q = 80%',fontsize=11,color=GREY)
    ax.set(xlabel='True batch mean % released at the specified time',ylabel='Probability',xlim=(78,100),ylim=(0,1.02));ax.legend(fontsize=11,loc='lower right',ncol=2)
    save(f,b,'acceptance/usp711-operating-characteristic.png')
# Reading 6: a constructed stability failure traced to salt disproportionation in a moisture-permeable pack
PULLS=[0,3,6,9,12]                        # months on stability, 25 C / 60% RH, new bottle without desiccant
FB_MOLFRAC=[0.000,0.021,0.048,0.082,0.120] # free-base mole fraction of the API, assumed trajectory
KF_TABLET=[2.4,2.7,3.0,3.3,3.6]           # tablet water, % w/w, assumed
U_RATIO=0.011                             # standard uncertainty of the chloride : base ratio (XRPD reading 3)
XRPD_LOD_TABLET=2.0                       # free base, % w/w of API, assumed limit in the tablet matrix (about 3x the API-only 0.58%)
def fb_ww(x):
    """Free base as % w/w of the API solid, from its mole fraction (rest is the HCl monohydrate)."""
    return 100*x*M_BASE/(x*M_BASE+(1-x)*M_HYD)
def disprop_profile(times,x,acid):
    """Reading 4's model extended: in acid no effect; at pH 6.8 tau x(1+4x) and a slow tail of 0.6x."""
    if acid:return weibull(times,8.0)
    return weibull(times,11.0*(1+4*x),fmax=100*(1-0.6*x))
def r6(b):
    Q=80;rng=np.random.default_rng(2611);tl=[]
    for m,x,kf in zip(PULLS,FB_MOLFRAC,KF_TABLET):
        mean30=float(disprop_profile([30],x,False)[0]);units=rng.normal(mean30,3.0,24)
        st=usp711(units[:6],units[6:12],units[12:],Q)
        ww=fb_ww(x)
        tl.append(dict(month=m,free_base_mol_fraction=x,chloride_to_base_ratio=r(1-x,3),ratio_shift_in_standard_uncertainties=r(x/U_RATIO,1),
            free_base_percent_w_w_of_API=r(ww,2),xrpd_detects_in_tablet='yes' if ww>=XRPD_LOD_TABLET else 'no',tablet_water_KF_percent=kf,
            model_mean_30min_pH68=r(mean30,1),S1_mean=r(units[:6].mean(),1),S1_min=r(units[:6].min(),1),S2_mean_of_12=r(units[:12].mean(),1),S3_mean_of_24=r(units.mean(),1),
            usp711_result=('pass at S%d'%st) if st else 'fail (S3)'))
    last=units                            # the 12-month pull's 24 units
    write(b,'stability-timeline.csv',tl)
    write(b,'month12-units.csv',[dict(unit=i+1,stage='S1' if i<6 else ('S2' if i<12 else 'S3'),percent_dissolved_30min=r(v,1)) for i,v in enumerate(last)])
    prof=[]
    for t in [0]+TIMES:
        prof.append(dict(time_min=t,reference_pH68=r(disprop_profile([t],0,False)[0],1),month12_pH68=r(disprop_profile([t],FB_MOLFRAC[-1],False)[0],1),
            reference_HCl=r(disprop_profile([t],0,True)[0],1),month12_HCl=r(disprop_profile([t],FB_MOLFRAC[-1],True)[0],1)))
    write(b,'month12-profiles.csv',prof)
    write(b,'hypotheses.csv',[dict(hypothesis=h,predicts=p,observed=o,verdict=v) for h,p,o,v in [
        ('laboratory error','apparatus, medium or filter fault; one run affected','mechanical checks, medium pH and filter recovery in range; retest of retained units also fails','ruled out'),
        ('hard tablet','slow in acid and at pH 6.8; hardness up; disintegration slower','hardness 98 to 101 N; disintegration 4 min at both pulls; acid profile unchanged','ruled out'),
        ('coarse API or over-lubrication','present from release; release profile slow','release lot passed at S1 with mean 93%; same API lot in passing products','ruled out'),
        ('dehydration to the anhydrate','water down; XRPD 7.41 deg; dissolution faster','water up 2.4 to 3.6%; no 7.41 deg peak; dissolution slower','ruled out'),
        ('salt disproportionation to free base','acid normal; pH 6.8 slow with a tail; chloride ratio low; XRPD 5.93 deg; water up','all five seen','supported')]])
    f=figure('DISSOLUTION RAISED THE ALARM; THE SOLID STATE EXPLAINED IT','Constructed stability lot in a bottle without desiccant: the 12-month dissolution failure, and what the solid-state tests show at every pull.')
    ax=f.add_axes([.07,.17,.38,.60]);tt=[z['time_min'] for z in prof]
    ax.plot(tt,[z['reference_HCl'] for z in prof],color=GREY,lw=2.2,label='0.1 N HCl: release and 12 months (same)')
    ax.plot(tt,[z['reference_pH68'] for z in prof],color=TEAL,lw=2.6,marker='o',label='pH 6.8: release')
    ax.plot(tt,[z['month12_pH68'] for z in prof],color=ORANGE,lw=2.6,marker='s',label='pH 6.8: 12 months')
    ax.axhline(Q,color=NAVY,ls=':');ax.text(30.5,Q-9,'Q = 80% at 30 min',fontsize=11,color=NAVY)
    ax.set(xlabel='Time (min)',ylabel='% dissolved',xlim=(0,46),ylim=(0,105));ax.legend(fontsize=11,loc='lower right')
    ax.set_title('Only the pH 6.8 profile moves',fontsize=14,color=NAVY,loc='left')
    a1=f.add_axes([.55,.52,.39,.25]);mm=[z['month'] for z in tl]
    a1.bar(mm,[z['free_base_percent_w_w_of_API'] for z in tl],width=1.6,color=[GOLD if z['xrpd_detects_in_tablet']=='yes' else '#c9d3da' for z in tl])
    a1.axhline(XRPD_LOD_TABLET,color=GREY,ls='--');a1.text(-1.5,12.6,f'Dashed line: XRPD limit in the tablet, {XRPD_LOD_TABLET:.1f}% (assumed)',fontsize=10,color=GREY)
    for m,x in zip(PULLS,FB_MOLFRAC):
        ww=fb_ww(x);a1.text(m+0.95,(XRPD_LOD_TABLET+.5) if abs(ww-XRPD_LOD_TABLET)<.6 else max(ww,0)+.3,f"{ww:.1f}%",ha='left',fontsize=10,color=NAVY)
    a1.set(ylabel='Free base\n(% w/w of API)',xticks=mm,xticklabels=[],xlim=(-1.8,13.8),ylim=(0,14))
    a1.set_title('Solid state: free base visible by XRPD from 6 months',fontsize=14,color=NAVY,loc='left')
    a2=f.add_axes([.55,.17,.39,.27])
    a2.plot(mm,[z['S3_mean_of_24'] for z in tl],color=ORANGE,lw=2.4,marker='s')
    a2.axhline(Q,color=NAVY,ls=':');a2.axhline(Q+5,color=GREY,ls='--')
    a2.text(13.6,Q+0.3,'Q',fontsize=10,color=NAVY,ha='right',va='bottom');a2.text(13.6,Q+5.3,'Q + 5 (S1)',fontsize=10,color=GREY,ha='right',va='bottom')
    a2.set(xlabel='Months on stability',ylabel='Mean of 24 units,\n% at 30 min',xticks=mm,xlim=(-1.8,13.8),ylim=(72,98))
    a2.set_title('Dissolution: fails only at 12 months',fontsize=14,color=NAVY,loc='left')
    save(f,b,'investigation/alarm-and-diagnosis.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])
