-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathica.py
142 lines (123 loc) · 4.84 KB
/
ica.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
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
import numpy as np
import pandas as pd
import h5py
import hdbscan
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.decomposition import FastICA
from sklearn.metrics import pairwise_distances
from sklearn.manifold import MDS
from sklearn.manifold import TSNE
from scipy import stats
def multi_ica(data,
whiten=True,
n_components=None,
n_repeats=100,
seed=None):
if seed:
np.random.seed(seed)
run_seeds = np.random.randint(low=0, high=10000, size=n_repeats)
else:
run_seeds = [None] * n_repeats
if not n_components:
n_components = data.shape[1]
comps = [i for i in range(n_components)]
repeats = [i for i in range(n_repeats)]
i_repeats = [item for item in repeats for i in range(n_components)]
i_comps = comps * n_repeats
s_list = []
a_list = []
for i in range(n_repeats):
np.random.seed(run_seeds[i])
w_init = np.random.rand(n_components, n_components)
ica_transformer = FastICA(n_components=n_components,
w_init=w_init,
whiten=whiten,
max_iter=1000)
s = ica_transformer.fit_transform(data) # shape: n_genes, n_components
a = ica_transformer.mixing_ # shape: n_samples, n_components
s_list.append(s)
a_list.append(a)
return s_list, a_list, i_repeats, i_comps
def align_tail(s_list, a_list, cutoff=3):
ics = np.hstack(tuple(s_list)).T # ics shape: n_components*n_repeats, n_genes
mixs = np.hstack(tuple(a_list)).T # mixs shape: n_components*n_repeats, n_samples
for i in range(ics.shape[0]):
ic = ics[i, :]
sd = ic.std()
ic = ic/sd # normalize the std of compoments as 1
w = mixs[i, :]
w = w*sd
if sum(ic < (-cutoff)) > sum(ic > cutoff):
ics[i, :] = -ic
mixs[i, :] = -w
return ics, mixs
def dis_cal(ics, metric='cosine', name='ics', save_dis=True, out_dir='.'):
dis = pairwise_distances(ics, metric=metric, n_jobs=-1)
if save_dis:
hf = h5py.File(out_dir + '/' + name + '_dis.h5', 'w')
hf.create_dataset('dis', data=dis)
hf.close()
return dis
def ic_cluster(dis,
name='ics',
min_cluster_size=5,
min_samples=5,
show_plt=False,
save_plt=True,
figsize=5,
out_dir='.'):
clusterer = hdbscan.HDBSCAN(min_cluster_size=min_cluster_size, min_samples=min_samples, metric='precomputed')
clusterer.fit(dis)
ics_cls = clusterer.labels_.reshape((clusterer.labels_.shape[0], 1))
tsne_embedding = TSNE(n_components=2, metric='precomputed') # tSNE
ics_tsne = tsne_embedding.fit_transform(dis)
mds_embedding = MDS(dissimilarity='precomputed') # MDS
ics_mds = mds_embedding.fit_transform(dis)
ics_pts = np.hstack((ics_tsne, ics_mds, ics_cls))
plt.figure(figsize=(figsize, figsize))
color_palette = sns.color_palette('Paired', 1000)
cluster_colors = [color_palette[x] if x >= 0
else (0.5, 0.5, 0.5)
for x in clusterer.labels_]
cluster_member_colors = [sns.desaturate(x, p) for x, p in
zip(cluster_colors, clusterer.probabilities_)]
plt.scatter(ics_pts[:, 0], ics_pts[:, 1], s=50, linewidth=0, c=cluster_member_colors, alpha=0.25)
if show_plt:
plt.show()
if save_plt:
plt.savefig(fname=out_dir + '/' + name + '.png')
return ics_pts
def find_cor(mix, clinical):
"""
Find p_value of linear regression between mixing scores and clinical variables.
return a raw p value table.
"""
mix_dat = mix[clinical.index.values]
pval = []
coef = []
for i in range(mix_dat.shape[0]):
row_pval = []
row_coef = []
reg_x = mix_dat.iloc[i, :]
for variable in clinical.columns.values:
reg_y = clinical[variable]
dat = pd.concat([reg_x, reg_y], axis=1, join='inner').dropna()
x = np.array(dat.iloc[:, 0]).astype(float)
y = np.array(dat.iloc[:, 1]).astype(float)
slope, _, _, p_value, _ = stats.linregress(x=x, y=y)
row_coef.append(slope)
row_pval.append(p_value)
pval.append(row_pval)
coef.append(row_coef)
pval = np.array(pval)
coef = np.array(coef)
pval = pd.DataFrame(pval, columns=clinical.columns.values, index=mix.index.values)
pval = pd.concat([mix[['i_repeats', 'i_comps', 'cluster']], pval], axis=1)
coef = pd.DataFrame(coef, columns=clinical.columns.values, index=mix.index.values)
coef = pd.concat([mix[['i_repeats', 'i_comps', 'cluster']], coef], axis=1)
return pval, coef
def spearman_distance(x, y):
rho, _ = stats.spearmanr(x, y)
sp_dis = (1 - rho)/2
return sp_dis