import argparse from pathlib import Path import numpy as np import pandas as pd p=argparse.ArgumentParser() p.add_argument('counts',type=Path) p.add_argument('refseq',type=Path) p.add_argument('cytoband',type=Path) p.add_argument('out',type=Path) a=p.parse_args() ref=pd.read_csv(a.refseq,sep='\t',header=None,usecols=[2,4,5,12],low_memory=False) ref.columns=['chr','start','end','gene'] ref=ref[ref.chr.isin([f'chr{i}' for i in range(1,23)])] bands=pd.read_csv(a.cytoband,sep='\t',header=None,names=['chr','start','end','band','stain']) cent=bands[bands.stain.eq('acen')].groupby('chr').start.max() ref['arm']=ref.chr+np.where((ref.start+ref.end)/20).sum().to_numpy() for k,v in programs.items()} good=depth>=500 normal=np.maximum.reduce([calls[k] for k in ('alveolar','ciliated','club','basal')]) stromal=np.maximum(calls['fibroblast'],calls['endothelial']) tumour=(calls['tumor']>=2)&(normal<2)&(calls['immune']<2)&(stromal<2)&good epi=(normal>=2)&(calls['tumor']<2)&(calls['immune']<2)&(stromal<2)&good refs=[(calls['immune']>=2)&(calls['tumor']<2)&(normal<2)&(stromal<2)&good, (stromal>=2)&(calls['tumor']<2)&(normal<2)&(calls['immune']<2)&good] genes=data.index.intersection(ref.index) genes=genes[~genes.isin(exclude)&~genes.str.match(r'^(IG[HKL]|TR[ABDG]|MT-|RP[SL])')] mapped=data.loc[genes].to_numpy() keep=np.logical_and.reduce([(mapped[:,r]>0).sum(axis=1)>=5 for r in refs]) norm=np.log1p(mapped[keep]/np.maximum(depth,1)*1e4).astype('float32') arms=ref.loc[genes[keep]].arm.to_numpy() names=[arm for arm in sorted(set(arms)) if (arms==arm).sum()>=30] x=np.stack([norm[arms==arm].mean(axis=0) for arm in names],axis=1) target=data.loc[next(k for k in ('CIP2A','KIAA1524') if k in data.index)].to_numpy() bins=np.floor(np.log2(np.maximum(depth,1))*4) for seed in (281740,41,2026,1449,1334): rng=np.random.default_rng(seed) profiles=[] for refmask in refs: fit,hold=np.array_split(rng.permutation(np.flatnonzero(refmask)),2) v=x-x[fit].mean(axis=0) v-=np.median(v,axis=1)[:,None] template=np.median(v[tumour & (calls['tumor']>=3)],axis=0) profiles.append((v,template,hold)) for quantile in (.95,.975,.99): bounds=[np.quantile(np.abs(v[hold]),quantile,axis=0) for v,_,hold in profiles] t1,t2=[z[1] for z in profiles] common=(np.sign(t1)==np.sign(t2))&(np.abs(t1)>bounds[0])&(np.abs(t2)>bounds[1]) for hits in (2,3): malignant=tumour.copy() epithelial=epi.copy() for (v,t,_),b in zip(profiles,bounds): malignant &= ((v[:,common]*np.sign(t[common]))>b[common]).sum(axis=1)>=hits epithelial &= (np.abs(v)>b).sum(axis=1)<=1 for stratum,pool in [('all',good),('low_cycle',calls['cycle']<2)]: t=np.flatnonzero(malignant & pool) e=np.flatnonzero(epithelial & pool) pairs=[] for k in np.unique(bins): tb=t[bins[t]==k]; eb=e[bins[e]==k] if len(tb) and len(eb): pairs.append((tb,eb,min(len(tb),len(eb)))) match_n=sum(z[2] for z in pairs) def cpm(z): return 1e6*target[z].sum()/depth[z].sum() deltas=[] if match_n>=10: for _ in range(500): ti=np.concatenate([rng.choice(t0,n,False) for t0,_,n in pairs]) ei=np.concatenate([rng.choice(e0,n,False) for _,e0,n in pairs]) deltas.append(cpm(ti)-cpm(ei)) rows.append(dict(sample=sample,seed=seed,quantile=quantile,min_arms=hits,stratum=stratum, tumour_cells=len(t),epithelial_cells=len(e),tumour_umi=int(target[t].sum()), epithelial_umi=int(target[e].sum()),matched_cells=match_n, delta_cpm=cpm(t)-cpm(e) if len(t) and len(e) else np.nan, matched_positive=np.mean(np.array(deltas)>0) if deltas else np.nan, matched_p025=np.quantile(deltas,.025) if deltas else np.nan, matched_median=np.median(deltas) if deltas else np.nan, matched_p975=np.quantile(deltas,.975) if deltas else np.nan)) result=pd.DataFrame(rows) result.to_csv(a.out/'cip2a_stability_grid.csv',index=False) for key,d in result.groupby(['sample','stratum']): valid=d[d[['tumour_cells','epithelial_cells']].min(axis=1)>=25] m=valid[valid.matched_cells>=25] print(key,'eligible',len(valid),'positive',int(valid.delta_cpm.gt(0).sum()), 'matched eligible',len(m),'matched fraction range',m.matched_positive.min(),m.matched_positive.max(), 'delta range',valid.delta_cpm.min(),valid.delta_cpm.max(),flush=True)