Download scripts/extract_chan_umap.py from xuyun/CIP2A: direct link, hf CLI and curl.
- Browser
- Download file 3.8 kB
-
https://huggingface.co/datasets/xuyun/CIP2A/resolve/main/scripts/extract_chan_umap.py
- Command line
-
hf download hf://datasets/xuyun/CIP2A/scripts/extract_chan_umap.py
-
curl -L -o extract_chan_umap.py https://huggingface.co/datasets/xuyun/CIP2A/resolve/main/scripts/extract_chan_umap.py
3.8 kB
| 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')))) | |
| 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')) | |
| print('Embeddings:',list(f['obsm']),flush=True) | |
| xy=f['obsm/X_umap'][selected.index.to_numpy()] | |
| key=obs.attrs['_index'] | |
| ids=decode(obs[key])[selected.index] | |
| assert len(set(ids))==len(ids)==11744 | |
| assert xy.shape==(len(ids),2) and np.isfinite(xy).all() | |
| selected['detected']=selected.CIP2A.gt(0).astype(int) | |
| selected['UMAP1'],selected['UMAP2']=xy.T | |
| selected[['patient','group','detected','UMAP1','UMAP2']].to_csv(out/'chan_umap.csv',index=False) | |
| expected=pd.read_csv(out/'chan_confirmed_primary.csv').set_index(['patient','group']).CIP2A.sort_index() | |
| actual=selected.groupby(['patient','group']).CIP2A.sum().sort_index() | |
| pd.testing.assert_series_equal(actual,expected,check_dtype=False) | |