"""Reproduce the constructed flow-cytometry 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 CAR-T drug-product lot, CT-01: CD3 on FITC, the CAR detection reagent on PE.
"""
from pathlib import Path
import csv, math, shutil
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
SLUGS={1:'1-from-cell-to-number',2:'2-controls-and-gates',3:'3-gating-as-a-method',4:'4-counting-cells-and-the-dose'}
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/3-flow-cytometry'
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})
SPILL=np.array([[1.0,0.22],[0.02,1.0]])   # rows: fluorophore (FITC, PE); columns: detector (FITC, PE)
CAR_FRACTION=0.46
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,'CAR-T lot CT-01 • constructed teaching example • simulated events, not patient or product data',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 asinh(x,c=150.0):return np.arcsinh(np.asarray(x)/c)
def cd3_cells(n,seed,car_fraction=CAR_FRACTION,pe_reagent=True):
    """True fluorophore amounts for viable CD3+ singlets; CAR+ cells carry PE only if the reagent is in the tube."""
    rng=np.random.default_rng(seed)
    fitc=rng.lognormal(math.log(4000),0.35,n)
    car=rng.random(n)<car_fraction
    pe=np.where(car&pe_reagent,rng.lognormal(math.log(900),0.7,n),0.0)
    return fitc,pe,car,rng
def detect(fitc,pe,rng,base_sd=40.0,photon=0.9):
    """Detector signals with spillover, electronic noise and photon (spreading) noise."""
    true=np.vstack([fitc,pe]).T@SPILL
    sd=np.sqrt(base_sd**2+photon*np.clip(true,0,None))
    return true+rng.normal(0,1,true.shape)*sd
def compensate(obs,spill=SPILL):return obs@np.linalg.inv(spill)
def r1(b):
    rng=np.random.default_rng(11);n=20000
    single=rng.random(n)>0.04
    a=rng.normal(50000,6000,n)*np.where(single,1.0,2.0)
    w=np.where(single,rng.normal(1.0,0.07,n),rng.normal(1.45,0.15,n))
    h=a/w*0.9
    gate=h/a>0.9/1.2
    write(b,'pulse-events.csv',[dict(event=i+1,FSC_A=r(a[i],0),FSC_H=r(h[i],0),true_doublet='yes' if not single[i] else 'no',in_singlet_gate='yes' if gate[i] else 'no') for i in range(3000)])
    write(b,'doublet-summary.csv',[dict(events=n,true_doublets=int((~single).sum()),singlet_gate_keeps=int(gate.sum()),doublets_inside_gate=int((gate&~single).sum()),singlets_excluded=int((~gate&single).sum()))])
    fitc,pe,car,rng=cd3_cells(15000,12);obs=detect(fitc,pe,rng)
    write(b,'spillover-matrix.csv',[dict(fluorophore='FITC (CD3)',into_FITC_detector=SPILL[0,0],into_PE_detector=SPILL[0,1]),dict(fluorophore='PE (CAR reagent)',into_FITC_detector=SPILL[1,0],into_PE_detector=SPILL[1,1])])
    fmo_f,fmo_p,_,rr=cd3_cells(15000,13,pe_reagent=False);fmo=compensate(detect(fmo_f,fmo_p,rr))
    thr=float(np.percentile(fmo[:,1],99.5))
    res=[]
    for label,sp in [('none (raw detector signal)',None),('under-compensated (FITC into PE 0.20)',np.array([[1,.20],[.02,1]])),('correct (0.22)',SPILL),('over-compensated (0.30)',np.array([[1,.30],[.02,1]]))]:
        x=obs if sp is None else compensate(obs,sp)
        pos=x[:,1]>thr
        res.append(dict(compensation=label,PE_gate_from_FMO=r(thr,1),reported_percent_CAR_positive=r(100*pos.mean(),2),true_percent_CAR_positive=r(100*car.mean(),2),CAR_negative_cells_called_positive_percent=r(100*pos[~car].mean(),2),median_PE_of_CAR_negative=r(np.median(x[~car,1]),1)))
    write(b,'compensation-effect.csv',res)
    f=figure('COMPENSATION REMOVES SPILLOVER, NOT SPREAD','Simulated viable CD3+ cells: 22% of FITC light reaches the PE detector until the spillover matrix is inverted.')
    for k,(x,ttl) in enumerate([(obs,'Before compensation'),(compensate(obs),'After compensation (correct matrix)')]):
        ax=f.add_axes([.08+.46*k,.15,.38,.62])
        ax.scatter(asinh(x[~car,0]),asinh(x[~car,1]),s=1.2,color=GREY,alpha=.35,rasterized=True,label='true CAR−')
        ax.scatter(asinh(x[car,0]),asinh(x[car,1]),s=1.2,color=ORANGE,alpha=.35,rasterized=True,label='true CAR+')
        ax.axhline(asinh(thr),color=TEAL,ls='--',lw=1.6);ax.text(.2,asinh(thr)+.15,'CAR gate (from FMO)',fontsize=11,color=TEAL)
        ax.set(title=ttl,xlabel='CD3 FITC (arcsinh scale)',ylabel='CAR PE (arcsinh scale)',xlim=(0,5.5),ylim=(-2.5,5.5))
        pc=next(z['reported_percent_CAR_positive'] for z in res if z['compensation'].startswith('none' if k==0 else 'correct'))
        ax.text(.2,5.0,f'reported CAR+: {pc}%',fontsize=13,color=NAVY)
    save(f,b,'compensation/before-and-after.png')
def r2(b):
    hier=[('acquired events',None,100000),('time gate (stable flow)','acquired events',98600),('singlets (FSC-A vs FSC-H)','time gate (stable flow)',94400),('lymphocyte scatter','singlets (FSC-A vs FSC-H)',83100),('viable (viability dye negative)','lymphocyte scatter',74800),('CD3+','viable (viability dye negative)',71900),('CAR+ (FMO-set gate)','CD3+',33150)]
    rows=[]
    for name,parent,cnt in hier:
        pc=next((c for nn,_,c in hier if nn==parent),None)
        p=cnt/pc if pc else 1.0
        rows.append(dict(gate=name,parent=parent or '',events=cnt,percent_of_parent=r(100*p,2),binomial_CV_percent_of_estimate=r(100*math.sqrt((1-p)/(p*pc)),2) if pc else ''))
    write(b,'gating-hierarchy.csv',rows)
    stats=[]
    for label,frac in [('CAR+ of viable CD3+',0.46),('residual CD19+ B cells',0.01),('residual CD19+ B cells, low',0.001),('rare event at 0.0001',0.0001)]:
        for cv in [0.10,0.05]:
            need=1/cv**2
            stats.append(dict(population=label,fraction_of_parent=frac,target_CV_percent=int(cv*100),events_of_population_needed=int(round(need*(1-frac))),parent_events_needed=int(math.ceil(need*(1-frac)/frac))))
    write(b,'counting-statistics.csv',stats)
    full_f,full_p,car,rng=cd3_cells(30000,21);full=compensate(detect(full_f,full_p,rng))
    fmo_f,fmo_p,_,rr=cd3_cells(30000,22,pe_reagent=False);fmo=compensate(detect(fmo_f,fmo_p,rr))
    un=compensate(detect(np.zeros(30000),np.zeros(30000),np.random.default_rng(23)))
    rng_i=np.random.default_rng(24);iso=fmo.copy();iso[:,1]+=rng_i.lognormal(math.log(70),0.5,len(iso))
    gates=[]
    for label,ctrl in [('unstained',un),('FMO (all stains except CAR reagent)',fmo),('isotype-matched control antibody',iso)]:
        thr=float(np.percentile(ctrl[:,1],99.5));pos=full[:,1]>thr
        gates.append(dict(gate_set_from=label,gate_PE=r(thr,1),reported_percent_CAR_positive=r(100*pos.mean(),2),true_percent_CAR_positive=r(100*car.mean(),2),bias_points=r(100*(pos.mean()-car.mean()),2)))
    write(b,'gate-placement.csv',gates)
    f=figure('THE GATE BELONGS TO THE CONTROL THAT SETS IT','Simulated CAR channel for viable CD3+ cells: unstained, FMO and isotype controls place the gate in different places.')
    ax=f.add_axes([.08,.15,.84,.62]);bins=np.linspace(-2.5,5.5,160)
    ax.hist(asinh(full[:,1]),bins=bins,color=NAVY,alpha=.55,label='Full stain (lot CT-01)')
    ax.hist(asinh(fmo[:,1]),bins=bins,histtype='step',color=TEAL,lw=2,label='FMO control')
    ax.hist(asinh(un[:,1]),bins=bins,histtype='step',color=GREY,lw=2,label='Unstained')
    for g,col,y in zip(gates,[GREY,TEAL,ORANGE],[0.92,0.80,0.68]):
        x=asinh(g['gate_PE']);ax.axvline(x,color=col,ls='--',lw=1.8)
        ax.text(1.6,ax.get_ylim()[1]*y,f"{g['gate_set_from'].split(' (')[0]}: {g['reported_percent_CAR_positive']}% CAR+",fontsize=12,color=col)
    ax.set(xlabel='CAR PE, compensated (arcsinh scale)',ylabel='Events',xlim=(-2.5,5.5));ax.legend(fontsize=11,loc='upper right')
    save(f,b,'gates/gate-placement.png')
def r3(b):
    rng=np.random.default_rng(31);days=np.arange(1,31);target=52000.0
    mfi=target*(1+rng.normal(0,0.012,30));mfi[19:]*=np.linspace(0.985,0.93,11)
    mean=float(mfi[:15].mean());sd=float(mfi[:15].std(ddof=1))
    rows=[]
    for d,v in zip(days,mfi):
        z=(v-mean)/sd;rows.append(dict(day=int(d),bead_PE_MFI=r(v,0),z_score=r(z,2),beyond_2SD='yes' if abs(z)>2 else 'no',beyond_3SD='yes' if abs(z)>3 else 'no'))
    for i in range(1,len(rows)):
        if rows[i]['beyond_2SD']=='yes' and rows[i-1]['beyond_2SD']=='yes' and np.sign(rows[i]['z_score'])==np.sign(rows[i-1]['z_score']):rows[i]['rule_2_2s']='violated'
    for z in rows:z.setdefault('rule_2_2s','')
    write(b,'bead-trend.csv',rows)
    write(b,'bead-limits.csv',[dict(baseline_days='1-15',mean_MFI=r(mean,0),sd_MFI=r(sd,0),cv_percent=r(100*sd/mean,2))])
    free=[45.8,47.1,44.2,46.5,49.0];tmpl=[46.1,46.3,46.0,46.4,46.2]
    inter=[dict(analyst=f'A{i+1}',free_hand_gating_percent_CAR=a,template_gating_percent_CAR=t) for i,(a,t) in enumerate(zip(free,tmpl))]
    inter.append(dict(analyst='CV %',free_hand_gating_percent_CAR=r(100*np.std(free,ddof=1)/np.mean(free),2),template_gating_percent_CAR=r(100*np.std(tmpl,ddof=1)/np.mean(tmpl),2)))
    write(b,'inter-analyst.csv',inter)
    fitc,pe,car,rr=cd3_cells(30000,41,car_fraction=0.398);x=compensate(detect(fitc,pe,rr))
    fmo_f,fmo_p,_,r2_=cd3_cells(30000,42,pe_reagent=False);fmo=compensate(detect(fmo_f,fmo_p,r2_));base=float(np.percentile(fmo[:,1],99.5))
    sens=[]
    for pct in [98.0,99.0,99.5,99.9]:
        thr=float(np.percentile(fmo[:,1],pct));sens.append(dict(FMO_percentile_for_gate=pct,gate_PE=r(thr,1),reported_percent_CAR=r(100*(x[:,1]>thr).mean(),2),passes_spec_ge_40='yes' if 100*(x[:,1]>thr).mean()>=40 else 'no'))
    write(b,'gate-sensitivity.csv',sens)
    f=figure('TREND THE INSTRUMENT BEFORE BLAMING THE CELLS','Simulated daily bead MFI in the PE channel with limits from the first 15 days; the laser starts to fade on day 20.')
    ax=f.add_axes([.08,.15,.84,.62])
    ax.plot(days,mfi,marker='o',color=NAVY,lw=2)
    for k,col,ls in [(0,GREY,'-'),(2,GOLD,'--'),(-2,GOLD,'--'),(3,ORANGE,':'),(-3,ORANGE,':')]:ax.axhline(mean+k*sd,color=col,ls=ls,lw=1.4)
    for k,lab,col in [(3,'+3 SD',ORANGE),(2,'+2 SD',GOLD),(-2,'−2 SD',GOLD),(-3,'−3 SD',ORANGE)]:ax.text(31.0,mean+k*sd,lab,fontsize=11,color=col,va='center')
    flag=[z for z in rows if z['beyond_3SD']=='yes']
    if flag:ax.plot([z['day'] for z in flag],[z['bead_PE_MFI'] for z in flag],'o',ms=12,mfc='none',mec=ORANGE,mew=2)
    ax.axvspan(.5,15.5,color='#edf5f6',zorder=0);ax.text(1,mean+3.4*sd,'baseline for limits',fontsize=11,color=TEAL)
    ax.set(xlabel='Day',ylabel='Bead PE median fluorescence',xlim=(0.5,33.5))
    save(f,b,'qc/bead-levey-jennings.png')
# Reading 4: cell count and viability from an automated counter, combined with the flow fractions into a dose
COUNT_REPS=[14.0,14.4,14.2]      # total nucleated cells, 10^6 cells/mL, AO/DAPI counter, three counts of one sample (assumed)
VIAB_REPS=[91.2,91.6,91.4]       # counter viability, %, same three counts (assumed)
FLOW_CD3=96.1;FLOW_CAR=46.1;FLOW_VIABLE=90.0   # from reading 2's gating hierarchy, %
BAG_ML=25.0;WEIGHT_KG=72.4;TARGET=2.0          # bag volume, patient weight, target dose 10^6 viable CAR+ T cells/kg (assumed)
DOSE_RANGE=(1.0,2.5)                           # release range, 10^6 viable CAR+ T cells/kg (assumed)
def r4(b):
    tnc=float(np.mean(COUNT_REPS));via=float(np.mean(VIAB_REPS))
    vcd=tnc*via/100;cd3=vcd*FLOW_CD3/100;car=cd3*FLOW_CAR/100
    total=car*BAG_ML;dose=total/WEIGHT_KG
    chain=[dict(step='total nucleated cells',source='cell counter (AO/DAPI)',factor_percent='',cells_per_mL_1e6=r(tnc,4)),
        dict(step='viable cells',source='cell counter viability',factor_percent=r(via,2),cells_per_mL_1e6=r(vcd,4)),
        dict(step='viable CD3+ T cells',source='flow: CD3+ of viable',factor_percent=FLOW_CD3,cells_per_mL_1e6=r(cd3,4)),
        dict(step='viable CAR+ T cells',source='flow: CAR+ of viable CD3+',factor_percent=FLOW_CAR,cells_per_mL_1e6=r(car,4))]
    write(b,'dose-chain.csv',chain)
    write(b,'dose.csv',[dict(bag_volume_mL=BAG_ML,viable_CAR_T_per_mL_1e6=r(car,4),viable_CAR_T_in_bag_1e8=r(total/100,4),patient_weight_kg=WEIGHT_KG,
        dose_1e6_per_kg=r(dose,4),target_1e6_per_kg=TARGET,release_range_1e6_per_kg=f'{DOSE_RANGE[0]}-{DOSE_RANGE[1]}',
        within_range='yes' if DOSE_RANGE[0]<=dose<=DOSE_RANGE[1] else 'no')])
    budget=[('cell count (counter intermediate precision)',5.0),('counter viability',1.5),('flow CD3+ fraction',0.5),('flow CAR+ fraction: template gating',0.34),('flow CAR+ fraction: counting statistics',0.4)]
    comb=math.sqrt(sum(c**2 for _,c in budget))
    write(b,'dose-uncertainty.csv',[dict(component=n,relative_standard_uncertainty_percent=c,share_of_variance_percent=r(100*c**2/comb**2,1)) for n,c in budget]+
        [dict(component='combined (root sum of squares)',relative_standard_uncertainty_percent=r(comb,2),share_of_variance_percent=100.0)])
    write(b,'viability-comparison.csv',[dict(method='cell counter, AO/DAPI',denominator='all nucleated cells in the sample',viability_percent=r(via,1)),
        dict(method='flow, viability dye',denominator='singlet lymphocyte-scatter events',viability_percent=FLOW_VIABLE)])
    rng=np.random.default_rng(20391);dil=[]
    for frac in [0.2,0.4,0.6,0.8,1.0]:
        for rep in range(3):
            expect=tnc*frac;obs=expect*(1+rng.normal(0,0.03))
            dil.append(dict(dilution_fraction=frac,replicate=rep+1,expected_1e6_per_mL=r(expect,3),observed_1e6_per_mL=r(obs,3)))
    x=np.array([z['dilution_fraction'] for z in dil]);y=np.array([z['observed_1e6_per_mL'] for z in dil])
    slope=float(np.sum(x*y)/np.sum(x*x))
    for z in dil:z['fit_through_origin']=r(slope*z['dilution_fraction'],3);z['residual_percent']=r(100*(z['observed_1e6_per_mL']/(slope*z['dilution_fraction'])-1),2)
    write(b,'dilution-series.csv',dil)
    f=figure('A DOSE IS A COUNT TIMES THREE FRACTIONS','The counter sets how many cells there are; flow sets what fraction of them are viable CAR⁺ T cells. Constructed values for lot CT-01.')
    ax=f.add_axes([.07,.17,.42,.60]);labels=['Total\nnucleated','Viable','Viable\nCD3⁺','Viable\nCAR⁺ T'];vals=[z['cells_per_mL_1e6'] for z in chain]
    ax.bar(range(4),vals,color=[NAVY,NAVY,TEAL,TEAL],width=.48)
    for i,v in enumerate(vals):ax.text(i,v+.3,f'{v:#.3g}',ha='center',fontsize=12,color=NAVY)   # three significant figures, as the inputs
    for i,(z,src) in enumerate(zip(chain[1:],['× 91.4%\ncounter','× 96.1%\nflow','× 46.1%\nflow'])):ax.text(i+.5,vals[i+1]*0.5,src,ha='center',fontsize=11,color=GREY)
    ax.set(xticks=range(4),xticklabels=labels,ylabel='10⁶ cells per mL',ylim=(0,16.5))
    ax.set_title('Navy from the cell counter, teal from flow',fontsize=14,color=NAVY,loc='left')
    a2=f.add_axes([.58,.17,.36,.60]);xx=np.linspace(0,1.05,50)
    a2.plot(xx,slope*xx,color=GREY,lw=2,ls='--',label=f'Fit through origin, slope {slope:#.3g}')
    a2.plot(x,y,'o',color=TEAL,ms=8,label='Observed (three per dilution)')
    a2.set(xlabel='Dilution fraction (1.0 = undiluted)',ylabel='Counted, 10⁶ cells per mL',xlim=(0,1.08),ylim=(0,16.5));a2.legend(fontsize=11,loc='upper left')
    a2.set_title('Is the count proportional to dilution?',fontsize=14,color=NAVY,loc='left')
    save(f,b,'dose/dose-chain-and-dilution.png')
if __name__=='__main__':
    for n in ([ONLY] if ONLY else range(1,5)):
        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])
