"""Reproduce the constructed stability 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.
"""
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-stability-question-and-ich-q1',2:'2-accelerated-and-long-term',3:'3-forced-degradation-by-design',4:'4-quench-and-prepare-the-sample',5:'5-prove-stability-indicating-specificity',6:'6-mass-balance-and-missing-peaks',7:'7-samples-for-the-stability-program'}
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/3-stability-indicating-methods'
NAVY='#15334e';TEAL='#007f91';ORANGE='#cc652b'
plt.rcParams.update({'font.family':'DejaVu Sans','font.size':13,'axes.spines.top':False,'axes.spines.right':False})
def write(b,name,rows):
    rows=list(rows)
    with (b/'data'/name).open('w',newline='') as f:
        w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)
def read(b,name):
    with (b/'data'/name).open() as f:return list(csv.DictReader(f))
def 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 • constructed teaching example • not experimental data or an approved stability protocol',fontsize=11,color='#526879')
    return f
def box(ax,x,y,w,h,text):
    ax.add_patch(FancyBboxPatch((x,y),w,h,boxstyle='round,pad=0.015',facecolor='#edf5f6',edgecolor=TEAL,lw=1.8))
    ax.text(x+w/2,y+h/2,text,ha='center',va='center',fontsize=13,color=NAVY)
def arrow(ax,a,c):ax.annotate('',xy=c,xytext=a,arrowprops=dict(arrowstyle='->',color=TEAL,lw=2))
def save(f,b,name):
    p=b/'images'/name;p.parent.mkdir(parents=True,exist_ok=True)
    f.canvas.draw();r=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(r)
            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):
    rows=[dict(evidence='ATP',question='Can the result support the quality decision?',sample='defined matrix and analytes',cannot_establish='shelf life by itself'),dict(evidence='forced degradation',question='Can the method see plausible degradation?',sample='separate controlled stress samples',cannot_establish='actual storage rate'),dict(evidence='accelerated stability',question='What changes under elevated storage conditions?',sample='representative product in proposed pack',cannot_establish='universal time equivalence'),dict(evidence='long_term_stability',question='What happens during labeled storage?',sample='scheduled pulls in proposed pack',cannot_establish='every future sample is automatically covered')]
    write(b,'evidence-map.csv',rows)
    f=figure('START WITH THE STABILITY QUESTION','Method challenge and shelf-life evidence answer connected, different questions.')
    ax=f.add_axes([.06,.13,.88,.66]);ax.set(xlim=(0,1),ylim=(0,1));ax.axis('off')
    for x,y,w,h,t in [(.03,.69,.94,.19,'QUALITY QUESTION\nCan this product, in this package, meet its requirements during storage?'),(.03,.35,.28,.20,'FORCED DEGRADATION\nChallenge chemistry and detection'),(.36,.35,.28,.20,'ACCELERATED STUDY\nChallenge elevated storage'),(.69,.35,.28,.20,'LONG-TERM STUDY\nObserve intended storage'),(.03,.02,.94,.18,'REPORTABLE RESULTS\nAssay + individual impurities + relevant physical and product-performance attributes')]:box(ax,x,y,w,h,t)
    for x in [.17,.50,.83]:arrow(ax,(.5,.69),(x,.55));arrow(ax,(x,.35),(.5,.20))
    save(f,b,'q1/stability-evidence-map.png')
def r2(b):
    rows=[]
    for batch,shift in [('X01',-.15),('X02',0),('X03',.15)]:
        for arm,times,slope,dslope in [('long_term_25C_60RH',[0,3,6,9,12,18,24],.12,.006),('accelerated_40C_75RH',[0,3,6],.7,.03)]:
            for m in times:
                rows.append(dict(batch=batch,study=arm,month=m,constructed_assay_percent_label=100+shift-slope*m,constructed_Deg2_percent_nominal_API=.04+dslope*m))
    write(b,'stability-trends.csv',rows)
    arr=[dict(activation_energy_kJ_mol=Ea,reference_C=25,target_C=40,acceleration_factor=math.exp(Ea*1000/8.314462618*(1/298.15-1/313.15))) for Ea in [40,60,80]]
    write(b,'arrhenius-sensitivity.csv',arr)
    f=figure('ACCELERATED IS NOT A UNIVERSAL CLOCK','Constructed storage trends and temperature-model sensitivity must not be confused with shelf-life proof.')
    data=read(b,'stability-trends.csv')
    for i,(key,label) in enumerate([('constructed_assay_percent_label','Assay (% label claim)'),('constructed_Deg2_percent_nominal_API','Deg-2 (% nominal API)')]):
        ax=f.add_axes([.08+.47*i,.25,.36,.51])
        for arm,color in [('long_term_25C_60RH',TEAL),('accelerated_40C_75RH',ORANGE)]:
            q=[r for r in data if r['batch']=='X02' and r['study']==arm]
            ax.plot([float(r['month']) for r in q],[float(r[key]) for r in q],marker='o',color=color,label='25 °C / 60% RH' if color==TEAL else '40 °C / 75% RH')
        ax.set(xlabel='Months at the stated condition',ylabel=label,xticks=[0,6,12,18,24]);ax.legend(fontsize=10)
    af=[float(r['acceleration_factor']) for r in read(b,'arrhenius-sensitivity.csv')]
    f.text(.08,.14,'At assumed Ea = 40, 60 or 80 kJ/mol, the 40 °C / 25 °C rate ratio is '+', '.join(f'{x:.2f}' for x in af)+'.',fontsize=14,color=NAVY)
    f.text(.08,.085,'Same mechanism and model validity are assumptions. No universal “hot weeks = shelf-life years” conversion is implied.',fontsize=12,color='#526879')
    save(f,b,'storage/accelerated-versus-long-term.png')
def r3(b):
    rows=[]
    for name,k in [('unstressed_control',.0005),('acid_teaching',.005),('base_teaching',.012),('oxidation_teaching',.025)]:
        for t in np.linspace(0,8,33):rows.append(dict(stress=name,time_hours=float(t),assumed_first_order_rate_per_hour=k,API_remaining_percent=100*math.exp(-k*t),API_loss_percent=100*(1-math.exp(-k*t))))
    write(b,'stress-time-course.csv',rows)
    designs=[('acid','0.01 M HCl final','25 C','0,0.5,2,8 h','verify neutralization and final pH'),('base','0.01 M NaOH final','25 C','0,0.5,2,8 h','verify neutralization and precipitation risk'),('oxidation','0.1% w/v H2O2 final','25 C','0,0.5,2,8 h','verify reaction stopping without destroying Deg-1'),('dry_heat','dry solid; no solution reagent','60 C','0,1,3,7 days','compare matrix and unstressed storage'),('humidity','open exposure; no solution reagent','40 C / 75% RH','0,1,3,7 days','record mass, moisture and physical state'),('light','qualified visible and near-UV exposure','controlled specimen temperature','dose-based pulls','protected control and dose verification')]
    write(b,'stress-design.csv',[dict(stress=a,proposed_start=c,condition=d,proposed_pulls=e,key_control=f) for a,c,d,e,f in designs])
    write(b,'light-dose-calculation.csv',[dict(visible_target_lux_h=1200000,measured_visible_lux=10000,visible_hours=120,near_UV_target_Wh_m2=200,measured_near_UV_W_m2=2,near_UV_hours=100,minimum_hours_if_both_constant_and_simultaneous=120)])
    f=figure('USE STRESS TO CHALLENGE THE METHOD','Time courses are constructed illustrations, not predictions for the proposed reagent concentrations.')
    ax=f.add_axes([.09,.23,.82,.57])
    for name,color in [('unstressed_control','#6d7b84'),('acid_teaching',TEAL),('base_teaching','#4567a7'),('oxidation_teaching',ORANGE)]:
        q=[r for r in read(b,'stress-time-course.csv') if r['stress']==name]
        ax.plot([float(r['time_hours']) for r in q],[float(r['API_loss_percent']) for r in q],lw=2.5,label=name.replace('_',' '),color=color)
    ax.set(xlabel='Hours (constructed solution-stress model)',ylabel='API loss (%)');ax.legend(fontsize=11)
    f.text(.09,.12,'Escalate only when needed; avoid secondary degradation and preserve diagnostically useful samples.',fontsize=14,color=NAVY)
    save(f,b,'stress/stress-time-course.png')
def r4(b):
    rows=[]
    for t in np.linspace(0,8,33):
        for case,v in [('effective_stop',.1),('continued_reaction',.1+.015*t),('unverified_reductant_artifact',.1*math.exp(-.25*t))]:rows.append(dict(preparation=case,hours_after_sampling=float(t),constructed_degradant_percent_nominal_API=v))
    write(b,'post-sampling-artifacts.csv',rows)
    write(b,'neutralization-and-dilution.csv',[dict(stress_aliquot_mL=1,acid_mol_L=.01,acid_amount_umol=10,base_mol_L=.01,stoichiometric_base_mL=1,final_volume_mL=10,total_dilution_factor=10,starting_API_mg_mL=1,final_API_mg_mL=.1,reporting_threshold_percent=.05,threshold_impurity_ug_mL=.05)])
    f=figure('SAMPLING IS NOT THE SAME AS STOPPING REACTION','A valid stress sample must preserve its chemistry through quench, dilution, filtration and the queue.')
    ax=f.add_axes([.09,.24,.82,.55])
    for case,color in [('effective_stop',TEAL),('continued_reaction',ORANGE),('unverified_reductant_artifact','#775391')]:
        q=[r for r in read(b,'post-sampling-artifacts.csv') if r['preparation']==case]
        ax.plot([float(r['hours_after_sampling']) for r in q],[float(r['constructed_degradant_percent_nominal_API']) for r in q],lw=3,color=color,label=case.replace('_',' '))
    ax.axhline(.05,ls=':',color='#536b7d',label='Case reporting threshold 0.05%')
    ax.set(xlabel='Hours after sampling',ylabel='Degradant (% nominal API)');ax.legend(fontsize=11)
    f.text(.09,.12,'The curves demonstrate possible artifacts; no quench reagent or hold time is validated by this figure.',fontsize=13,color=NAVY)
    save(f,b,'sample/quench-and-hold-artifacts.png')
def r5(b):
    rows=[]
    def gauss(t,mu,sigma,area):return area/(sigma*math.sqrt(2*math.pi))*math.exp(-.5*((t-mu)/sigma)**2)
    for t in np.linspace(4,6.5,1001):
        rows.append(dict(time_min=float(t),API_signal=gauss(t,5,.08,100),hidden_degradant_signal=gauss(t,5.03,.06,.5),original_total=gauss(t,5,.08,100)+gauss(t,5.03,.06,.5),alternate_degradant_signal=gauss(t,5.6,.06,.5),alternate_total=gauss(t,5,.08,100)+gauss(t,5.6,.06,.5)))
    write(b,'coelution-example.csv',rows)
    write(b,'resolution-and-bias.csv',[dict(API_area_units=100,degradant_area_units=.5,assumed_equal_mass_response=True,original_delta_t_min=.03,alternate_delta_t_min=.6,API_sigma_min=.08,degradant_sigma_min=.06,original_Rs=2*.03/(4*.08+4*.06),alternate_Rs=2*.6/(4*.08+4*.06),API_positive_relative_bias_percent=.5)])
    f=figure('ONE PEAK DOES NOT PROVE ONE COMPONENT','Synthetic Gaussian signals show a small coeluent that an alternate selectivity can expose.')
    data=read(b,'coelution-example.csv');t=[float(r['time_min']) for r in data]
    for i,(title,key,col) in enumerate([('Original selectivity','original_total',ORANGE),('Alternate selectivity','alternate_total',TEAL)]):
        ax=f.add_axes([.08+.47*i,.27,.36,.50]);ax.plot(t,[float(r[key]) for r in data],color=col,lw=2.5)
        ax.set(xlabel='Time (min)',ylabel='Signal (arbitrary units)',ylim=(0,5),xlim=(4.6,6.1));ax.set_title(title+' — low-signal zoom',fontsize=13)
        if i==1:ax.annotate('Separated degradant',xy=(5.6,3.32),xytext=(5.0,4.4),fontsize=11,arrowprops=dict(arrowstyle='->',color=NAVY))
    f.text(.08,.15,'API apex is deliberately clipped in this zoom. Equal-response degradant area is 0.5% of API area.',fontsize=13,color=NAVY)
    f.text(.08,.09,'Assumed identical UV spectral shape illustrates a DAD blind spot; no commercial peak-purity algorithm is simulated.',fontsize=12,color='#526879')
    save(f,b,'specificity/hidden-coeluent.png')
def r6(b):
    data=[('response_corrected',100,1,92,9,1),('weak_response_uncorrected',100,1,92,5,1),('baseline_not_subtracted',100,1,92,9,0)]
    rows=[]
    for label,A0,D0,At,Dt,sub in data:
        increase=Dt-D0 if sub else Dt
        balance=(At+increase)/A0*100
        rows.append(dict(scenario=label,initial_assay=A0,initial_degradants=D0,stressed_assay=At,stressed_degradants=Dt,subtract_initial_degradants=bool(sub),new_degradants=increase,parent_loss=A0-At,relative_parent_equivalent_balance_percent=balance,gap_percentage_points=100-balance))
    write(b,'mass-balance.csv',rows)
    write(b,'response-factor-example.csv',[dict(API_mass_concentration_ug_mL=1,API_peak_area=100,impurity_mass_concentration_ug_mL=1,impurity_peak_area=50,RRF_slope_impurity_over_API=.5,API_equivalent_reported_impurity_percent=4,corrected_impurity_percent=8)])
    f=figure('MASS BALANCE IS A DIAGNOSTIC, NOT A PURITY CERTIFICATE','All components use a common, justified parent-equivalent basis in this constructed example.')
    q=read(b,'mass-balance.csv');ax=f.add_axes([.1,.27,.8,.51]);x=np.arange(3)
    assay=[float(r['stressed_assay']) for r in q];added=[float(r['new_degradants']) for r in q]
    ax.bar(x,assay,color=TEAL,label='Remaining API');ax.bar(x,added,bottom=assay,color=ORANGE,label='Counted new degradants')
    ax.axhline(100,color=NAVY,ls='--',label='Initial API basis');ax.set_ylim(0,110)
    ax.set_xticks(x,['Response corrected','Weak response, uncorrected','Baseline misassigned as new'],fontsize=11)
    ax.set_ylabel('Parent-equivalent units per initial API = 100');ax.legend(loc='lower left',fontsize=11)
    for i,r in enumerate(q):ax.text(i,103,r['relative_parent_equivalent_balance_percent']+'%',ha='center',fontsize=13,color=NAVY)
    f.text(.1,.13,'A good numerical total can coexist with coelution, offsetting errors or a missing non-UV species.',fontsize=14,color=NAVY)
    save(f,b,'balance/mass-balance-diagnostic.png')
def r7(b):
    schedule=[]
    for batch in ['X01','X02','X03']:
        for study,months,cond in [('long_term',[0,3,6,9,12,18,24,36],'25 C / 60% RH'),('accelerated',[0,3,6],'40 C / 75% RH'),('intermediate_conditional',[0,6,9,12],'30 C / 65% RH')]:
            for m in months:schedule.append(dict(batch=batch,study=study,scheduled_month=m,condition=cond,analytical_units=12,retained_units=6,total_units_allocated=18,container_system='proposed marketing pack; dedicated units',status='conditional reserve' if study.startswith('intermediate') else 'planned'))
    write(b,'stability-pull-plan.csv',schedule)
    inventory=[]
    for study in ['long_term','accelerated','intermediate_conditional']:
        q=[r for r in schedule if r['study']==study]
        inventory.append(dict(study=study,scheduled_batch_pulls=len(q),analytical_units=sum(r['analytical_units'] for r in q),retained_units=sum(r['retained_units'] for r in q),total_units=sum(r['total_units_allocated'] for r in q)))
    write(b,'sample-inventory.csv',inventory)
    seq=[('diluent blank','check contamination'),('suitability mixture','critical separation and response'),('calibration standards','qualified reference basis'),('qualified retained comparator if available','support profile comparison; recorded initial results remain the baseline'),('stability sample X01','independent preparation'),('post-sample blank','carryover check'),('stability sample X02','independent preparation'),('bracketing reference','check drift'),('stability sample X03','independent preparation'),('closing reference and blank','complete suitability evidence')]
    write(b,'analytical-handoff-sequence.csv',[dict(order=i+1,injection_role=a,purpose=c,criterion_source='approved method and protocol; not assigned by this teaching schedule') for i,(a,c) in enumerate(seq)])
    f=figure('DESIGN THE SAMPLE HANDOFF BEFORE THE FIRST PULL','Identity, packaging, timing and method capability travel with every stability sample.')
    ax=f.add_axes([.06,.15,.88,.66]);ax.set(xlim=(0,1),ylim=(0,1));ax.axis('off')
    nodes=[(.02,.64,'PROTOCOL\nBatch • pack • condition'),(.36,.64,'CHAMBER\nLocation • monitoring'),(.70,.64,'PULL\nTime • identity • handling'),(.70,.15,'PREPARE & ANALYZE\nControls • suitability • hold'),(.36,.15,'REVIEW & TREND\nResults • profiles • deviations'),(.02,.15,'ACT ON EVIDENCE\nInvestigate • revise • retain')]
    for x,y,t in nodes:box(ax,x,y,.26,.22,t)
    for a,c in [((.28,.75),(.36,.75)),((.62,.75),(.70,.75)),((.83,.64),(.83,.37)),((.70,.26),(.62,.26)),((.36,.26),(.28,.26))]:arrow(ax,a,c)
    save(f,b,'handoff/stability-sample-handoff.png')
if __name__=='__main__':
    for n in ([ONLY] if ONLY else range(1,8)):
        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('matplotlib==3.11.2\nnumpy==2.5.1\n')
        print('Generated',SLUGS[n])
