File size: 3,948 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 | import sys
from pathlib import Path
import h5py
import numpy as np
import pandas as pd
out = Path(sys.argv[2])
if sys.argv[1] == 'remote':
from remote_h5 import Remote
source = Remote('https://datasets.cellxgene.cziscience.com/a9d92e38-9a6e-401b-8484-74bb15122341.h5ad',
1463737857, sys.argv[3])
else:
source = sys.argv[1]
def decode(node):
if isinstance(node, h5py.Group):
code = node['codes'][:]
return np.append(node['categories'].asstr()[:], '')[code]
return node.asstr()[:] if node.dtype.kind in 'OS' else node[:]
with h5py.File(source) as f:
obs = f['obs']
columns = ['HTAN_Participant_ID','HTAN_Biospecimen_ID','batch','histo','tissue','treatment',
'cell_type_med','cell_type_general','procedure']
cells = pd.DataFrame({key: decode(obs[key]) for key in columns})
cells.columns = ['patient','sample','batch','histo','tissue','treatment','label','general','procedure']
cells['group'] = np.where(cells.label.str.startswith('SCLC'), 'malignant',
np.where(cells.general.eq('Immune'),'immune',
np.where(cells.label.eq('Epithelial Stroma'),'nonmalignant_epithelial',
np.where(cells.label.isin(['Endothelial','Fibroblast']),cells.label,'other'))))
cells.groupby(list(cells.columns)).size().rename('cells').reset_index().to_csv(out/'chan_sample_inventory.csv',index=False)
keep = cells.histo.eq('SCLC') & cells.tissue.eq('lung')
selected = cells.loc[keep].copy()
print(selected.groupby(['patient','sample','batch','treatment','procedure','group']).size().to_string(),flush=True)
if '--strict-only' in sys.argv:
selected = selected[selected.patient.isin(['HTA8_2003','HTA8_2010','HTA8_2013','HTA8_2018'])]
if '--patient' in sys.argv:
selected = selected[selected.patient.eq(sys.argv[sys.argv.index('--patient')+1])]
if '--inventory' in sys.argv:
sys.exit()
var = f['raw/var']
names = decode(var['feature_name']) if 'feature_name' in var else decode(f['var/feature_name'])
target = np.flatnonzero(np.isin(names,['CIP2A','KIAA1524']))
cycle = np.flatnonzero(np.isin(names,['MKI67','TOP2A','UBE2C','CDK1','CENPF','BIRC5']))
assert len(target)==1 and len(cycle)>=4
raw = f['raw/X']
ptr = raw['indptr'][:]
values = []
for left in range(0,len(cells),256):
right = min(left+256,len(cells))
rows = selected.index[(selected.index>=left)&(selected.index<right)]
if not len(rows):
continue
low, high = ptr[rows[0]], ptr[rows[-1]+1]
idx, dat = raw['indices'][low:high],raw['data'][low:high]
assert np.all(dat>=0) and np.all(dat==np.floor(dat))
for row in rows:
a,b = ptr[row]-low,ptr[row+1]-low
ii,dd = idx[a:b],dat[a:b]
values.append((row,float(dd.sum()),float(dd[ii==target[0]].sum()),int(np.isin(ii,cycle).sum())))
selected = selected.join(pd.DataFrame(values,columns=['row','library','CIP2A','cycle_markers']).set_index('row'))
selected['detected']=selected.CIP2A.gt(0)
selected['cycling_proxy']=np.where(selected.cycle_markers.ge(2),'2+ markers','0–1 markers')
strict = ['HTA8_2003','HTA8_2010','HTA8_2013','HTA8_2018']
for tag,subset,keys in [('all',selected,['patient','group']),('cycle',selected,['patient','group','cycling_proxy']),('confirmed_primary',selected[selected.patient.isin(strict)],['patient','group'])]:
result=subset.groupby(keys).agg(cells=('library','size'),umi=('library','sum'),CIP2A=('CIP2A','sum'),detected=('detected','sum')).reset_index()
result['cpm']=result.CIP2A/result.umi*1e6
result['detection']=result.detected/result.cells
result['target_share']=result.CIP2A/result.groupby('patient').CIP2A.transform('sum')
result.to_csv(out/f'chan_{tag}.csv',index=False)
|