File size: 6,113 Bytes
1fa45cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
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)/2<ref.chr.map(cent),'p','q')
ref=ref[ref.groupby('gene').arm.transform('nunique').eq(1)].drop_duplicates('gene').set_index('gene')
programs={'tumor':'INSM1 CHGA SYP NCAM1 ASCL1 NEUROD1 POU2F3 DLL3',
'alveolar':'ABCA3 AGER AQP5 HOPX PDPN SFTPC SFTPA1','ciliated':'FOXJ1 TPPP3 DNAH5',
'club':'SCGB1A1 SCGB3A1 CYP2F1','basal':'TP63 KRT5 KRT15',
'immune':'PTPRC CD3D CD3E LST1 TYROBP MS4A1 CD79A',
'fibroblast':'DCN COL1A1 COL1A2 LUM','endothelial':'PECAM1 VWF CLDN5 KDR EMCN',
'cycle':'MKI67 TOP2A UBE2C CDK1 CENPF BIRC5'}
exclude=set(' '.join(programs.values()).split())|{'CIP2A','KIAA1524'}

rows=[]
for path in sorted(a.counts.glob('ru*counts.csv.gz')):
    sample=path.name.split('_')[0]
    data=pd.read_csv(path,index_col=0,dtype={'feature_name':str})
    if not data.index.is_unique:
        data=data.groupby(level=0,sort=False).sum()
    depth=data.sum().to_numpy()
    calls={k:(data.reindex(v.split(),fill_value=0)>0).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)