forked from daviddaiweizhang/istar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaggregate_imputed.py
64 lines (48 loc) · 1.69 KB
/
aggregate_imputed.py
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
import sys
import numpy as np
import pandas as pd
from utils import load_pickle, save_tsv, read_lines
def get_masks(labels):
if labels.ndim == 3:
labels, labels_dict = flatten_labels(labels)
else:
uniq = np.unique(labels)
uniq = uniq[uniq >= 0]
labels_dict = uniq[..., np.newaxis]
labels_uniq = np.unique(labels[labels >= 0])
masks = [labels == lab for lab in labels_uniq]
masks = np.array(masks)
return masks, labels_dict
def flatten_labels(labels):
isin = (labels >= 0).all(-1)
flat = np.full_like(labels[..., 0], -99)
flat[~isin] = -1
dic, indices = np.unique(
labels[isin], return_inverse=True, axis=0)
flat[isin] = indices
return flat, dic
def to_str(labels):
labels = np.char.zfill(labels.astype(str), 2)
labels = ['_'.join(e) for e in labels]
return labels
def aggregate(x, masks, labels):
groups = [x[ma] for ma in masks]
df = pd.DataFrame([[g.size, g.mean(), g.var()] for g in groups])
df.columns = ['count', 'mean', 'variance']
labels = to_str(labels)
df.index = labels
df.index.name = 'cluster'
return df
def aggregate_files(prefix, gene_names, masks, labels):
for gname in gene_names:
x = load_pickle(f'{prefix}cnts-super/{gname}.pickle')
stats = aggregate(x, masks, labels)
save_tsv(stats, f'{prefix}cnts-clustered/by-genes/{gname}.tsv')
def main():
prefix = sys.argv[1] # e.g. 'data/her2st/B1/'
clus = load_pickle(f'{prefix}clusters-gene/labels.pickle')
masks, labels = get_masks(clus)
gene_names = read_lines(prefix+'gene-names.txt')
aggregate_files(prefix, gene_names, masks, labels)
if __name__ == '__main__':
main()