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={'immune':(calls['immune']>=2)&(calls['tumor']<2)&(normal<2)&(stromal<2)&good, 'stromal':(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() eligible=((mapped[:,refs['immune']]>0).sum(axis=1)>=5)&((mapped[:,refs['stromal']]>0).sum(axis=1)>=5) genes=genes[eligible]; mapped=mapped[eligible] assert all(mask.sum()>=40 for mask in refs.values()) # Compare each cell with disjoint held-out reference cells after library-size normalization. profiles={}; normal_flags={} rng=np.random.default_rng(281740) for name,mask in refs.items(): ir=rng.permutation(np.flatnonzero(mask)) fit,hold=np.array_split(ir,2) norm=np.log1p(mapped/np.maximum(depth,1)*1e4).astype('float32') residual=norm-norm[:,fit].mean(axis=1)[:,None] arms=ref.loc[genes].arm.to_numpy() names=[arm for arm in sorted(set(arms)) if (arms==arm).sum()>=30] v=np.stack([residual[arms==arm].mean(axis=0) for arm in names],axis=1) v-=np.median(v,axis=1)[:,None] bounds=np.quantile(np.abs(v[hold]),.99,axis=0) template=np.median(v[tumour & (calls['tumor']>=3)],axis=0) # An arm must exceed held-out background and have a concordant cohort-level direction. abnormal=np.abs(template)>bounds profiles[name]=(names,template,bounds,v) armrows.extend(dict(sample=sample,reference=name,arm=arm,median_tumour=float(t),background_q99=float(b),flag=bool(f)) for arm,t,b,f in zip(names,template,bounds,abnormal)) normal_flags[name]=(np.abs(v)>bounds).sum(axis=1)<=1 print(sample,name,len(fit),len(hold),'arms',list(np.array(names)[abnormal]),flush=True) signatures = [{arm: np.sign(t) for arm,t,b in zip(names,template,bounds) if abs(t)>b} for names,template,bounds,_ in profiles.values()] shared = {arm for arm,sign in signatures[0].items() if signatures[1].get(arm)==sign} malignant = tumour.copy() for names,template,bounds,v in profiles.values(): include=np.isin(names,list(shared)) hits=(v[:,include]*np.sign(template[include]))>bounds[include] malignant &= hits.sum(axis=1)>=2 epithelial=epi&normal_flags['immune']&normal_flags['stromal'] label=np.select([malignant,epithelial],['CNV_supported_tumour','CNV_low_epithelial'],default='unresolved') pd.DataFrame({'barcode':data.columns,'umi':depth,'label':label,'tumour_marker':tumour,'epithelial_marker':epi, 'immune_ref':refs['immune'],'stromal_ref':refs['stromal'],'cycle_markers':calls['cycle']}).to_csv(a.out/f'{sample}_cnv_labels.csv',index=False) audit.append(dict(sample=sample,cells=len(depth),qc=int(good.sum()),tumour_marker=int(tumour.sum()),epithelial_marker=int(epi.sum()), immune_ref=int(refs['immune'].sum()),stromal_ref=int(refs['stromal'].sum()),shared_arms=len(shared),supported_tumour=int(malignant.sum()), low_cnv_epithelium=int(epithelial.sum()),unresolved=int((label=='unresolved').sum()),pass25=bool(min(malignant.sum(),epithelial.sum())>=25))) # The target is read only after annotation is finalized. y=data.loc[next(k for k in ('CIP2A','KIAA1524') if k in data.index)].to_numpy() strata=[('all',good),('low_cycle',calls['cycle']<2)] for name, pool in list(strata): matched=np.zeros(len(depth),dtype=bool) bins=np.floor(np.log2(np.maximum(depth,1))*4) for bin_id in np.unique(bins): t=np.flatnonzero(pool & malignant & (bins==bin_id)) e=np.flatnonzero(pool & epithelial & (bins==bin_id)) size=min(len(t),len(e)) if size: matched[rng.choice(t,size,replace=False)]=True matched[rng.choice(e,size,replace=False)]=True strata.append((name+'_depth_matched',matched)) for stratum,keep in strata: for group in ('CNV_supported_tumour','CNV_low_epithelial'): sel=keep&(label==group) n=sel.sum(); u=depth[sel].sum(); c=y[sel].sum() effects.append(dict(sample=sample,stratum=stratum,group=group,cells=n,umi=u,cip2a=c,cpm=c/u*1e6 if u else np.nan,detected=(y[sel]>0).sum(),detection=(y[sel]>0).mean() if n else np.nan)) for name,rows in [('audit',audit),('effects',effects),('arms',armrows)]: pd.DataFrame(rows).to_csv(a.out/f'gse281740_cnv_{name}.csv',index=False) print(pd.DataFrame(audit).to_string(index=False))