-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathCluster.py
292 lines (239 loc) · 9.65 KB
/
Cluster.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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
#!/usr/bin/env python
# coding: utf-8
import numpy as np
import scipy.sparse as scisp
from math import log,exp,sqrt
import logging
import igraph as ig
import leidenalg
from sklearn import metrics
import os
# package logger
logger = logging.getLogger(__name__)
class ClusterBin:
def __init__(self, path , contig_info , seq_map , norm_result , min_signal , min_binsize ):
'''
perc: threshold of spurious contacts
min_signal: minimum signal of acceptable contigs
min_binsize: minimum bin size of output bins
'''
self.path = path
self.seq_map = seq_map
self.norm_result = norm_result
self.signal = min_signal
self.binsize = min_binsize
self.dist_cluster={}
self.name = []
self.site = []
self.len = []
self.cov = []
self.tax = []
for i in range(len(contig_info)):
temp = contig_info[i]
self.name.append(temp.name)
self.site.append(temp.sites)
self.len.append(temp.length)
self.cov.append(temp.cov)
self.tax.append(temp.tax)
del contig_info
self.name = np.array(self.name)
self.site = np.array(self.site)
self.len = np.array(self.len)
self.cov = np.array(self.cov)
self.tax= np.array(self.tax)
self.cov[self.cov==0] = np.min(self.cov[self.cov!=0])
self.norm()
del self.site, self.cov
logger.info('Run Leiden Algorithm')
self.leiden()
del self.tax
self._write_cluster()
del self.dist_cluster
def norm(self):
self.seq_map = self.seq_map.tocoo()
_map_row = self.seq_map.row
_map_col = self.seq_map.col
_map_data = self.seq_map.data
_map_coor = list(zip(_map_row , _map_col , _map_data))
coeff = self.norm_result[0:4]
self.seq_map = self.seq_map.tolil()
self.seq_map = self.seq_map.astype(np.float)
for x,y,d in _map_coor:
s1 = self.site[x]
if s1 == 0:
s1 = 1
s2 = self.site[y]
if s2 == 0:
s2 = 1
s = (log(s1*s2)-self.norm_result[5])/self.norm_result[6]
l1 = self.len[x]
l2 = self.len[y]
l = (log(l1*l2)-self.norm_result[7])/self.norm_result[8]
c1 = self.cov[x]
c2 = self.cov[y]
c = (log(c1*c2)-self.norm_result[9])/self.norm_result[10]
d_norm = d/exp(coeff[0] + coeff[1] * s + coeff[2] * l + coeff[3]* c)
if d_norm > self.norm_result[4]:
self.seq_map[x , y] = d_norm
else:
self.seq_map[x , y] = 0
del _map_row, _map_col, _map_data, _map_coor
def leiden(self):
#########Use Leiden Algorithm to do clustering########
map_del = self.seq_map.tocoo()
vcount = map_del.shape[0]
sources = map_del.row
targets = map_del.col
wei = map_del.data
index = sources>targets
sources = sources[index]
targets = targets[index]
wei = wei[index]
edgelist = list(zip(sources, targets))
g = ig.Graph(vcount, edgelist)
#############determine the best resolution parameter###########
st = []
res_option = [1,5,10,15,20,25,30]
for res in res_option:
part = leidenalg.find_partition(g , leidenalg.RBConfigurationVertexPartition , weights=wei , resolution_parameter = res , n_iterations = -1)
part = list(part)
label_true = []
label_pred = []
for i in range(len(part)):
for j in self.tax[part[i]]:
if j != 'Unassign':
label_true.append(j)
label_pred.append(i)
ARI_score = metrics.adjusted_rand_score(label_true, label_pred)
NMI_score = metrics.normalized_mutual_info_score(label_true, label_pred)
st.append((ARI_score+NMI_score)/2)
ind = st.index(max(st))
res_optimal = res_option[ind]
part = leidenalg.find_partition(g , leidenalg.RBConfigurationVertexPartition , weights=wei , resolution_parameter = res_optimal, n_iterations = -1)
part = list(part)
# dict of communities
numnode = 0
rang = []
for ci in range(len(part)):
if np.sum(self.len[part[ci]]) >= self.binsize:
rang.append(ci)
numnode = numnode+len(part[ci])
for id in part[ci]:
self.dist_cluster[self.name[id]] = 'group'+str(ci)
logger.debug('The optimal resolution is {}'.format(res_optimal))
logger.debug('There are {} contigs in {} bins'.format(numnode , len(rang)))
del map_del, sources, targets, wei, index, edgelist, g, part, label_true, label_pred
def _write_cluster(self):
########create file for checkm################
with open(os.path.join(self.path ,'cluster.txt'),'w') as out:
for key , value in self.dist_cluster.items():
out.write(str(key)+ '\t' +str(value))
out.write('\n')
class ClusterBin_LC:
def __init__(self, path , contig_info , seq_map , norm_result , min_signal , min_binsize ):
'''
perc: threshold of spurious contacts
min_signal: minimum signal of acceptable contigs
min_binsize: minimum bin size of output bins
'''
self.path = path
self.seq_map = seq_map
self.norm_result = norm_result
self.signal = min_signal
self.binsize = min_binsize
self.dist_cluster={}
self.name = []
self.len = []
self.cov = []
self.tax = []
for i in range(len(contig_info)):
temp = contig_info[i]
self.name.append(temp.name)
self.len.append(temp.length)
self.cov.append(temp.cov)
self.tax.append(temp.tax)
del contig_info
self.name = np.array(self.name)
self.len = np.array(self.len)
self.cov = np.array(self.cov)
self.tax= np.array(self.tax)
self.norm()
del self.cov
logger.info('Run Leiden Algorithm')
self.leiden()
del self.tax
self._write_cluster()
del self.dist_cluster
def norm(self):
self.seq_map = self.seq_map.tocoo()
_map_row = self.seq_map.row
_map_col = self.seq_map.col
_map_data = self.seq_map.data
_map_coor = list(zip(_map_row , _map_col , _map_data))
coeff = self.norm_result[0:4]
self.seq_map = self.seq_map.tolil()
self.seq_map = self.seq_map.astype(np.float)
for x,y,d in _map_coor:
l1 = self.len[x]
l2 = self.len[y]
l = (log(l1*l2)-self.norm_result[4])/self.norm_result[5]
c1 = self.cov[x]
c2 = self.cov[y]
c = (log(c1*c2)-self.norm_result[6])/self.norm_result[7]
d_norm = d/exp(coeff[0] + coeff[1] * l + coeff[2]* c)
if d_norm > self.norm_result[3]:
self.seq_map[x , y] = d_norm
else:
self.seq_map[x , y] = 0
del _map_row, _map_col, _map_data, _map_coor
def leiden(self):
#########Use Leiden Algorithm to do clustering########
map_del = self.seq_map.tocoo()
vcount = map_del.shape[0]
sources = map_del.row
targets = map_del.col
wei = map_del.data
index = sources>targets
sources = sources[index]
targets = targets[index]
wei = wei[index]
edgelist = list(zip(sources, targets))
g = ig.Graph(vcount, edgelist)
#############determine the best resolution parameter###########
st = []
res_option = [1,5,10,15,20,25,30]
for res in res_option:
part = leidenalg.find_partition(g , leidenalg.RBConfigurationVertexPartition , weights=wei , resolution_parameter = res , n_iterations = -1)
part = list(part)
label_true = []
label_pred = []
for i in range(len(part)):
for j in self.tax[part[i]]:
if j != 'Unassign':
label_true.append(j)
label_pred.append(i)
ARI_score = metrics.adjusted_rand_score(label_true, label_pred)
NMI_score = metrics.normalized_mutual_info_score(label_true, label_pred)
st.append((ARI_score+NMI_score)/2)
ind = st.index(max(st))
res_optimal = res_option[ind]
part = leidenalg.find_partition(g , leidenalg.RBConfigurationVertexPartition , weights=wei , resolution_parameter = res_optimal, n_iterations = -1)
part = list(part)
# dict of communities
numnode = 0
rang = []
for ci in range(len(part)):
if np.sum(self.len[part[ci]]) >= self.binsize:
rang.append(ci)
numnode = numnode+len(part[ci])
for id in part[ci]:
self.dist_cluster[self.name[id]] = 'group'+str(ci)
logger.debug('The optimal resolution is {}'.format(res_optimal))
logger.debug('There are {} contigs in {} bins'.format(numnode , len(rang)))
del map_del, sources, targets, wei, index, edgelist, g, part, label_true, label_pred
def _write_cluster(self):
########create file for checkm################
with open(os.path.join(self.path ,'cluster.txt'),'w') as out:
for key , value in self.dist_cluster.items():
out.write(str(key)+ '\t' +str(value))
out.write('\n')