Mercurial > repos > bimib > marea
comparison Marea/marea_cluster.py @ 16:c71ac0bb12de draft
Uploaded
author | bimib |
---|---|
date | Tue, 01 Oct 2019 06:05:13 -0400 |
parents | 1a0c8c2780f2 |
children | a8825e66c3a0 |
comparison
equal
deleted
inserted
replaced
15:d0e7f14b773f | 16:c71ac0bb12de |
---|---|
1 from __future__ import division | 1 # -*- coding: utf-8 -*- |
2 """ | |
3 Created on Mon Jun 3 19:51:00 2019 | |
4 | |
5 @author: Narger | |
6 """ | |
7 | |
8 import sys | |
9 import argparse | |
2 import os | 10 import os |
3 import sys | 11 from sklearn.datasets import make_blobs |
12 from sklearn.cluster import KMeans, DBSCAN, AgglomerativeClustering | |
13 from sklearn.metrics import silhouette_samples, silhouette_score, davies_bouldin_score, cluster | |
14 import matplotlib.pyplot as plt | |
15 import scipy.cluster.hierarchy as shc | |
16 import matplotlib.cm as cm | |
17 import numpy as np | |
4 import pandas as pd | 18 import pandas as pd |
5 import collections | 19 |
6 import pickle as pk | 20 ################################# process args ############################### |
7 import argparse | |
8 from sklearn.cluster import KMeans | |
9 import matplotlib | |
10 # Force matplotlib to not use any Xwindows backend. | |
11 matplotlib.use('Agg') | |
12 import matplotlib.pyplot as plt | |
13 | |
14 ########################## argparse ########################################### | |
15 | 21 |
16 def process_args(args): | 22 def process_args(args): |
17 parser = argparse.ArgumentParser(usage = '%(prog)s [options]', | 23 parser = argparse.ArgumentParser(usage = '%(prog)s [options]', |
18 description = 'process some value\'s' + | 24 description = 'process some value\'s' + |
19 ' genes to create class.') | 25 ' genes to create class.') |
20 parser.add_argument('-rs', '--rules_selector', | 26 |
21 type = str, | 27 parser.add_argument('-ol', '--out_log', |
22 default = 'HMRcore', | 28 help = "Output log") |
23 choices = ['HMRcore', 'Recon', 'Custom'], | 29 |
24 help = 'chose which type of dataset you want use') | 30 parser.add_argument('-in', '--input', |
25 parser.add_argument('-cr', '--custom', | 31 type = str, |
26 type = str, | 32 help = 'input dataset') |
27 help='your dataset if you want custom rules') | 33 |
28 parser.add_argument('-ch', '--cond_hier', | 34 parser.add_argument('-cy', '--cluster_type', |
29 type = str, | 35 type = str, |
30 default = 'no', | 36 choices = ['kmeans', 'meanshift', 'dbscan', 'hierarchy'], |
31 choices = ['no', 'yes'], | 37 default = 'kmeans', |
32 help = 'chose if you wanna hierical dendrogram') | 38 help = 'choose clustering algorythm') |
33 parser.add_argument('-lk', '--k_min', | 39 |
40 parser.add_argument('-k1', '--k_min', | |
34 type = int, | 41 type = int, |
35 help = 'min number of cluster') | 42 default = 2, |
36 parser.add_argument('-uk', '--k_max', | 43 help = 'choose minimun cluster number to be generated') |
44 | |
45 parser.add_argument('-k2', '--k_max', | |
37 type = int, | 46 type = int, |
38 help = 'max number of cluster') | 47 default = 7, |
39 parser.add_argument('-li', '--linkage', | 48 help = 'choose maximum cluster number to be generated') |
40 type = str, | 49 |
41 choices = ['single', 'complete', 'average'], | 50 parser.add_argument('-el', '--elbow', |
42 help='linkage hierarchical cluster') | 51 type = str, |
43 parser.add_argument('-d', '--data', | 52 default = 'false', |
44 type = str, | 53 choices = ['true', 'false'], |
45 required = True, | 54 help = 'choose if you want to generate an elbow plot for kmeans') |
46 help = 'input dataset') | 55 |
47 parser.add_argument('-n', '--none', | 56 parser.add_argument('-si', '--silhouette', |
48 type = str, | 57 type = str, |
49 default = 'true', | 58 default = 'false', |
50 choices = ['true', 'false'], | 59 choices = ['true', 'false'], |
51 help = 'compute Nan values') | 60 help = 'choose if you want silhouette plots') |
61 | |
62 parser.add_argument('-db', '--davies', | |
63 type = str, | |
64 default = 'false', | |
65 choices = ['true', 'false'], | |
66 help = 'choose if you want davies bouldin scores') | |
67 | |
52 parser.add_argument('-td', '--tool_dir', | 68 parser.add_argument('-td', '--tool_dir', |
53 type = str, | 69 type = str, |
54 required = True, | 70 required = True, |
55 help = 'your tool directory') | 71 help = 'your tool directory') |
56 parser.add_argument('-na', '--name', | 72 |
57 type = str, | 73 parser.add_argument('-ms', '--min_samples', |
58 help = 'name of dataset') | 74 type = int, |
59 parser.add_argument('-de', '--dendro', | 75 help = 'min samples for dbscan (optional)') |
60 help = "Dendrogram out") | 76 |
61 parser.add_argument('-ol', '--out_log', | 77 parser.add_argument('-ep', '--eps', |
62 help = "Output log") | 78 type = int, |
63 parser.add_argument('-el', '--elbow', | 79 help = 'eps for dbscan (optional)') |
64 help = "Out elbow") | 80 |
81 | |
65 args = parser.parse_args() | 82 args = parser.parse_args() |
66 return args | 83 return args |
67 | 84 |
68 ########################### warning ########################################### | 85 ########################### warning ########################################### |
69 | 86 |
70 def warning(s): | 87 def warning(s): |
71 args = process_args(sys.argv) | 88 args = process_args(sys.argv) |
72 with open(args.out_log, 'a') as log: | 89 with open(args.out_log, 'a') as log: |
73 log.write(s) | 90 log.write(s + "\n\n") |
74 | 91 print(s) |
75 ############################ dataset input #################################### | 92 |
76 | 93 ########################## read dataset ###################################### |
77 def read_dataset(data, name): | 94 |
95 def read_dataset(dataset): | |
78 try: | 96 try: |
79 dataset = pd.read_csv(data, sep = '\t', header = 0) | 97 dataset = pd.read_csv(dataset, sep = '\t', header = 0) |
80 except pd.errors.EmptyDataError: | 98 except pd.errors.EmptyDataError: |
81 sys.exit('Execution aborted: wrong format of '+name+'\n') | 99 sys.exit('Execution aborted: wrong format of dataset\n') |
82 if len(dataset.columns) < 2: | 100 if len(dataset.columns) < 2: |
83 sys.exit('Execution aborted: wrong format of '+name+'\n') | 101 sys.exit('Execution aborted: wrong format of dataset\n') |
84 return dataset | 102 return dataset |
85 | 103 |
86 ############################ dataset name ##################################### | 104 ############################ rewrite_input ################################### |
87 | 105 |
88 def name_dataset(name_data, count): | 106 def rewrite_input(dataset): |
89 if str(name_data) == 'Dataset': | 107 #Riscrivo il dataset come dizionario di liste, |
90 return str(name_data) + '_' + str(count) | 108 #non come dizionario di dizionari |
109 | |
110 for key, val in dataset.items(): | |
111 l = [] | |
112 for i in val: | |
113 if i == 'None': | |
114 l.append(None) | |
115 else: | |
116 l.append(float(i)) | |
117 | |
118 dataset[key] = l | |
119 | |
120 return dataset | |
121 | |
122 ############################## write to csv ################################## | |
123 | |
124 def write_to_csv (dataset, labels, name): | |
125 list_labels = labels | |
126 list_values = dataset | |
127 | |
128 list_values = list_values.tolist() | |
129 d = {'Label' : list_labels, 'Value' : list_values} | |
130 | |
131 df = pd.DataFrame(d, columns=['Value','Label']) | |
132 | |
133 dest = name + '.tsv' | |
134 df.to_csv(dest, sep = '\t', index = False, | |
135 header = ['Value', 'Label']) | |
136 | |
137 ########################### trova il massimo in lista ######################## | |
138 def max_index (lista): | |
139 best = -1 | |
140 best_index = 0 | |
141 for i in range(len(lista)): | |
142 if lista[i] > best: | |
143 best = lista [i] | |
144 best_index = i | |
145 | |
146 return best_index | |
147 | |
148 ################################ kmeans ##################################### | |
149 | |
150 def kmeans (k_min, k_max, dataset, elbow, silhouette, davies): | |
151 if not os.path.exists('clustering/kmeans_output'): | |
152 os.makedirs('clustering/kmeans_output') | |
153 | |
154 | |
155 if elbow == 'true': | |
156 elbow = True | |
91 else: | 157 else: |
92 return str(name_data) | 158 elbow = False |
93 | 159 |
94 ############################ load id e rules ################################## | 160 if silhouette == 'true': |
95 | 161 silhouette = True |
96 def load_id_rules(reactions): | |
97 ids, rules = [], [] | |
98 for key, value in reactions.items(): | |
99 ids.append(key) | |
100 rules.append(value) | |
101 return (ids, rules) | |
102 | |
103 ############################ check_methods #################################### | |
104 | |
105 def gene_type(l, name): | |
106 if check_hgnc(l): | |
107 return 'hugo_id' | |
108 elif check_ensembl(l): | |
109 return 'ensembl_gene_id' | |
110 elif check_symbol(l): | |
111 return 'symbol' | |
112 elif check_entrez(l): | |
113 return 'entrez_id' | |
114 else: | 162 else: |
115 sys.exit('Execution aborted:\n' + | 163 silhouette = False |
116 'gene ID type in ' + name + ' not supported. Supported ID' + | 164 |
117 'types are: HUGO ID, Ensemble ID, HUGO symbol, Entrez ID\n') | 165 if davies == 'true': |
118 | 166 davies = True |
119 def check_hgnc(l): | |
120 if len(l) > 5: | |
121 if (l.upper()).startswith('HGNC:'): | |
122 return l[5:].isdigit() | |
123 else: | |
124 return False | |
125 else: | 167 else: |
126 return False | 168 davies = False |
127 | 169 |
128 def check_ensembl(l): | 170 |
129 if len(l) == 15: | 171 range_n_clusters = [i for i in range(k_min, k_max+1)] |
130 if (l.upper()).startswith('ENS'): | 172 distortions = [] |
131 return l[4:].isdigit() | 173 scores = [] |
132 else: | 174 all_labels = [] |
133 return False | 175 |
134 else: | 176 for n_clusters in range_n_clusters: |
135 return False | 177 clusterer = KMeans(n_clusters=n_clusters, random_state=10) |
136 | 178 cluster_labels = clusterer.fit_predict(dataset) |
137 def check_symbol(l): | 179 |
138 if len(l) > 0: | 180 all_labels.append(cluster_labels) |
139 if l[0].isalpha() and l[1:].isalnum(): | 181 silhouette_avg = silhouette_score(dataset, cluster_labels) |
140 return True | 182 scores.append(silhouette_avg) |
141 else: | 183 distortions.append(clusterer.fit(dataset).inertia_) |
142 return False | 184 |
185 best = max_index(scores) + k_min | |
186 | |
187 for i in range(len(all_labels)): | |
188 prefix = '' | |
189 if (i + k_min == best): | |
190 prefix = '_BEST' | |
191 | |
192 write_to_csv(dataset, all_labels[i], 'clustering/kmeans_output/kmeans_with_' + str(i + k_min) + prefix + '_clusters.tsv') | |
193 | |
194 if davies: | |
195 with np.errstate(divide='ignore', invalid='ignore'): | |
196 davies_bouldin = davies_bouldin_score(dataset, all_labels[i]) | |
197 warning("\nFor n_clusters = " + str(i + k_min) + | |
198 " The average davies bouldin score is: " + str(davies_bouldin)) | |
199 | |
200 | |
201 if silhouette: | |
202 silihouette_draw(dataset, all_labels[i], i + k_min, 'clustering/kmeans_output/silhouette_with_' + str(i + k_min) + prefix + '_clusters.png') | |
203 | |
204 | |
205 if elbow: | |
206 elbow_plot(distortions, k_min,k_max) | |
207 | |
208 | |
209 | |
210 | |
211 | |
212 ############################## elbow_plot #################################### | |
213 | |
214 def elbow_plot (distortions, k_min, k_max): | |
215 plt.figure(0) | |
216 plt.plot(range(k_min, k_max+1), distortions, marker = 'o') | |
217 plt.xlabel('Number of cluster') | |
218 plt.ylabel('Distortion') | |
219 s = 'clustering/kmeans_output/elbow_plot.png' | |
220 fig = plt.gcf() | |
221 fig.set_size_inches(18.5, 10.5, forward = True) | |
222 fig.savefig(s, dpi=100) | |
223 | |
224 | |
225 ############################## silhouette plot ############################### | |
226 def silihouette_draw(dataset, labels, n_clusters, path): | |
227 silhouette_avg = silhouette_score(dataset, labels) | |
228 warning("For n_clusters = " + str(n_clusters) + | |
229 " The average silhouette_score is: " + str(silhouette_avg)) | |
230 | |
231 plt.close('all') | |
232 # Create a subplot with 1 row and 2 columns | |
233 fig, (ax1) = plt.subplots(1, 1) | |
234 | |
235 fig.set_size_inches(18, 7) | |
236 | |
237 # The 1st subplot is the silhouette plot | |
238 # The silhouette coefficient can range from -1, 1 but in this example all | |
239 # lie within [-0.1, 1] | |
240 ax1.set_xlim([-1, 1]) | |
241 # The (n_clusters+1)*10 is for inserting blank space between silhouette | |
242 # plots of individual clusters, to demarcate them clearly. | |
243 ax1.set_ylim([0, len(dataset) + (n_clusters + 1) * 10]) | |
244 | |
245 # Compute the silhouette scores for each sample | |
246 sample_silhouette_values = silhouette_samples(dataset, labels) | |
247 | |
248 y_lower = 10 | |
249 for i in range(n_clusters): | |
250 # Aggregate the silhouette scores for samples belonging to | |
251 # cluster i, and sort them | |
252 ith_cluster_silhouette_values = \ | |
253 sample_silhouette_values[labels == i] | |
254 | |
255 ith_cluster_silhouette_values.sort() | |
256 | |
257 size_cluster_i = ith_cluster_silhouette_values.shape[0] | |
258 y_upper = y_lower + size_cluster_i | |
259 | |
260 color = cm.nipy_spectral(float(i) / n_clusters) | |
261 ax1.fill_betweenx(np.arange(y_lower, y_upper), | |
262 0, ith_cluster_silhouette_values, | |
263 facecolor=color, edgecolor=color, alpha=0.7) | |
264 | |
265 # Label the silhouette plots with their cluster numbers at the middle | |
266 ax1.text(-0.05, y_lower + 0.5 * size_cluster_i, str(i)) | |
267 | |
268 # Compute the new y_lower for next plot | |
269 y_lower = y_upper + 10 # 10 for the 0 samples | |
270 | |
271 ax1.set_title("The silhouette plot for the various clusters.") | |
272 ax1.set_xlabel("The silhouette coefficient values") | |
273 ax1.set_ylabel("Cluster label") | |
274 | |
275 # The vertical line for average silhouette score of all the values | |
276 ax1.axvline(x=silhouette_avg, color="red", linestyle="--") | |
277 | |
278 ax1.set_yticks([]) # Clear the yaxis labels / ticks | |
279 ax1.set_xticks([-0.1, 0, 0.2, 0.4, 0.6, 0.8, 1]) | |
280 | |
281 | |
282 plt.suptitle(("Silhouette analysis for clustering on sample data " | |
283 "with n_clusters = " + str(n_clusters) + "\nAverage silhouette_score = " + str(silhouette_avg)), fontsize=12, fontweight='bold') | |
284 | |
285 | |
286 plt.savefig(path, bbox_inches='tight') | |
287 | |
288 ######################## dbscan ############################################## | |
289 | |
290 def dbscan(dataset, eps, min_samples): | |
291 if not os.path.exists('clustering/dbscan_output'): | |
292 os.makedirs('clustering/dbscan_output') | |
293 | |
294 if eps is not None: | |
295 clusterer = DBSCAN(eps = eps, min_samples = min_samples) | |
143 else: | 296 else: |
144 return False | 297 clusterer = DBSCAN() |
145 | 298 |
146 def check_entrez(l): | 299 clustering = clusterer.fit(dataset) |
147 if len(l) > 0: | 300 |
148 return l.isdigit() | 301 core_samples_mask = np.zeros_like(clustering.labels_, dtype=bool) |
149 else: | 302 core_samples_mask[clustering.core_sample_indices_] = True |
150 return False | 303 labels = clustering.labels_ |
151 | 304 |
152 def check_bool(b): | 305 # Number of clusters in labels, ignoring noise if present. |
153 if b == 'true': | 306 n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0) |
154 return True | 307 |
155 elif b == 'false': | 308 silhouette_avg = silhouette_score(dataset, labels) |
156 return False | 309 warning("For n_clusters =" + str(n_clusters_) + |
157 | 310 "The average silhouette_score is :" + str(silhouette_avg)) |
158 ############################ make recon ####################################### | 311 |
159 | 312 ##TODO: PLOT SU DBSCAN (no centers) e HIERARCHICAL |
160 def check_and_doWord(l): | 313 |
161 tmp = [] | 314 # Black removed and is used for noise instead. |
162 tmp_genes = [] | 315 unique_labels = set(labels) |
163 count = 0 | 316 colors = [plt.cm.Spectral(each) |
164 while l: | 317 for each in np.linspace(0, 1, len(unique_labels))] |
165 if count >= 0: | 318 for k, col in zip(unique_labels, colors): |
166 if l[0] == '(': | 319 if k == -1: |
167 count += 1 | 320 # Black used for noise. |
168 tmp.append(l[0]) | 321 col = [0, 0, 0, 1] |
169 l.pop(0) | 322 |
170 elif l[0] == ')': | 323 class_member_mask = (labels == k) |
171 count -= 1 | 324 |
172 tmp.append(l[0]) | 325 xy = dataset[class_member_mask & core_samples_mask] |
173 l.pop(0) | 326 plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col), |
174 elif l[0] == ' ': | 327 markeredgecolor='k', markersize=14) |
175 l.pop(0) | 328 |
176 else: | 329 xy = dataset[class_member_mask & ~core_samples_mask] |
177 word = [] | 330 plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col), |
178 while l: | 331 markeredgecolor='k', markersize=6) |
179 if l[0] in [' ', '(', ')']: | 332 |
180 break | 333 plt.title('Estimated number of clusters: %d' % n_clusters_) |
181 else: | 334 s = 'clustering/dbscan_output/dbscan_plot.png' |
182 word.append(l[0]) | 335 fig = plt.gcf() |
183 l.pop(0) | 336 fig.set_size_inches(18.5, 10.5, forward = True) |
184 word = ''.join(word) | 337 fig.savefig(s, dpi=100) |
185 tmp.append(word) | 338 |
186 if not(word in ['or', 'and']): | 339 |
187 tmp_genes.append(word) | 340 write_to_csv(dataset, labels, 'clustering/dbscan_output/dbscan_results.tsv') |
188 else: | 341 |
189 return False | 342 ########################## hierachical ####################################### |
190 if count == 0: | 343 |
191 return (tmp, tmp_genes) | 344 def hierachical_agglomerative(dataset, k_min, k_max): |
192 else: | 345 |
193 return False | 346 if not os.path.exists('clustering/agglomerative_output'): |
194 | 347 os.makedirs('clustering/agglomerative_output') |
195 def brackets_to_list(l): | 348 |
196 tmp = [] | 349 plt.figure(figsize=(10, 7)) |
197 while l: | 350 plt.title("Customer Dendograms") |
198 if l[0] == '(': | 351 shc.dendrogram(shc.linkage(dataset, method='ward')) |
199 l.pop(0) | 352 fig = plt.gcf() |
200 tmp.append(resolve_brackets(l)) | 353 fig.savefig('clustering/agglomerative_output/dendogram.png', dpi=200) |
201 else: | 354 |
202 tmp.append(l[0]) | 355 range_n_clusters = [i for i in range(k_min, k_max+1)] |
203 l.pop(0) | 356 |
204 return tmp | 357 for n_clusters in range_n_clusters: |
205 | 358 |
206 def resolve_brackets(l): | 359 cluster = AgglomerativeClustering(n_clusters=n_clusters, affinity='euclidean', linkage='ward') |
207 tmp = [] | 360 cluster.fit_predict(dataset) |
208 while l[0] != ')': | 361 cluster_labels = cluster.labels_ |
209 if l[0] == '(': | 362 |
210 l.pop(0) | 363 silhouette_avg = silhouette_score(dataset, cluster_labels) |
211 tmp.append(resolve_brackets(l)) | 364 warning("For n_clusters =", n_clusters, |
212 else: | 365 "The average silhouette_score is :", silhouette_avg) |
213 tmp.append(l[0]) | 366 |
214 l.pop(0) | 367 plt.clf() |
215 l.pop(0) | 368 plt.figure(figsize=(10, 7)) |
216 return tmp | 369 plt.title("Agglomerative Hierarchical Clustering\nwith " + str(n_clusters) + " clusters and " + str(silhouette_avg) + " silhouette score") |
217 | 370 plt.scatter(dataset[:,0], dataset[:,1], c = cluster_labels, cmap='rainbow') |
218 def priorityAND(l): | 371 s = 'clustering/agglomerative_output/hierachical_' + str(n_clusters) + '_clusters.png' |
219 tmp = [] | 372 fig = plt.gcf() |
220 flag = True | 373 fig.set_size_inches(10, 7, forward = True) |
221 while l: | 374 fig.savefig(s, dpi=200) |
222 if len(l) == 1: | 375 |
223 if isinstance(l[0], list): | 376 write_to_csv(dataset, cluster_labels, 'clustering/agglomerative_output/agglomerative_hierarchical_with_' + str(n_clusters) + '_clusters.tsv') |
224 tmp.append(priorityAND(l[0])) | 377 |
225 else: | 378 |
226 tmp.append(l[0]) | 379 |
227 l = l[1:] | 380 |
228 elif l[0] == 'or': | 381 ############################# main ########################################### |
229 tmp.append(l[0]) | 382 |
230 flag = False | 383 |
231 l = l[1:] | 384 def main(): |
232 elif l[1] == 'or': | 385 if not os.path.exists('clustering'): |
233 if isinstance(l[0], list): | 386 os.makedirs('clustering') |
234 tmp.append(priorityAND(l[0])) | 387 |
235 else: | |
236 tmp.append(l[0]) | |
237 tmp.append(l[1]) | |
238 flag = False | |
239 l = l[2:] | |
240 elif l[1] == 'and': | |
241 tmpAnd = [] | |
242 if isinstance(l[0], list): | |
243 tmpAnd.append(priorityAND(l[0])) | |
244 else: | |
245 tmpAnd.append(l[0]) | |
246 tmpAnd.append(l[1]) | |
247 if isinstance(l[2], list): | |
248 tmpAnd.append(priorityAND(l[2])) | |
249 else: | |
250 tmpAnd.append(l[2]) | |
251 l = l[3:] | |
252 while l: | |
253 if l[0] == 'and': | |
254 tmpAnd.append(l[0]) | |
255 if isinstance(l[1], list): | |
256 tmpAnd.append(priorityAND(l[1])) | |
257 else: | |
258 tmpAnd.append(l[1]) | |
259 l = l[2:] | |
260 elif l[0] == 'or': | |
261 flag = False | |
262 break | |
263 if flag == True: #se ci sono solo AND nella lista | |
264 tmp.extend(tmpAnd) | |
265 elif flag == False: | |
266 tmp.append(tmpAnd) | |
267 return tmp | |
268 | |
269 def checkRule(l): | |
270 if len(l) == 1: | |
271 if isinstance(l[0], list): | |
272 if checkRule(l[0]) is False: | |
273 return False | |
274 elif len(l) > 2: | |
275 if checkRule2(l) is False: | |
276 return False | |
277 else: | |
278 return False | |
279 return True | |
280 | |
281 def checkRule2(l): | |
282 while l: | |
283 if len(l) == 1: | |
284 return False | |
285 elif isinstance(l[0], list) and l[1] in ['and', 'or']: | |
286 if checkRule(l[0]) is False: | |
287 return False | |
288 if isinstance(l[2], list): | |
289 if checkRule(l[2]) is False: | |
290 return False | |
291 l = l[3:] | |
292 elif l[1] in ['and', 'or']: | |
293 if isinstance(l[2], list): | |
294 if checkRule(l[2]) is False: | |
295 return False | |
296 l = l[3:] | |
297 elif l[0] in ['and', 'or']: | |
298 if isinstance(l[1], list): | |
299 if checkRule(l[1]) is False: | |
300 return False | |
301 l = l[2:] | |
302 else: | |
303 return False | |
304 return True | |
305 | |
306 def do_rules(rules): | |
307 split_rules = [] | |
308 err_rules = [] | |
309 tmp_gene_in_rule = [] | |
310 for i in range(len(rules)): | |
311 tmp = list(rules[i]) | |
312 if tmp: | |
313 tmp, tmp_genes = check_and_doWord(tmp) | |
314 tmp_gene_in_rule.extend(tmp_genes) | |
315 if tmp is False: | |
316 split_rules.append([]) | |
317 err_rules.append(rules[i]) | |
318 else: | |
319 tmp = brackets_to_list(tmp) | |
320 if checkRule(tmp): | |
321 split_rules.append(priorityAND(tmp)) | |
322 else: | |
323 split_rules.append([]) | |
324 err_rules.append(rules[i]) | |
325 else: | |
326 split_rules.append([]) | |
327 if err_rules: | |
328 warning('Warning: wrong format rule in ' + str(err_rules) + '\n') | |
329 return (split_rules, list(set(tmp_gene_in_rule))) | |
330 | |
331 def make_recon(data): | |
332 try: | |
333 import cobra as cb | |
334 import warnings | |
335 with warnings.catch_warnings(): | |
336 warnings.simplefilter('ignore') | |
337 recon = cb.io.read_sbml_model(data) | |
338 react = recon.reactions | |
339 rules = [react[i].gene_reaction_rule for i in range(len(react))] | |
340 ids = [react[i].id for i in range(len(react))] | |
341 except cb.io.sbml3.CobraSBMLError: | |
342 try: | |
343 data = (pd.read_csv(data, sep = '\t', dtype = str)).fillna('') | |
344 if len(data.columns) < 2: | |
345 sys.exit('Execution aborted: wrong format of ' + | |
346 'custom GPR rules\n') | |
347 if not len(data.columns) == 2: | |
348 warning('WARNING: more than 2 columns in custom GPR rules.\n' + | |
349 'Extra columns have been disregarded\n') | |
350 ids = list(data.iloc[:, 0]) | |
351 rules = list(data.iloc[:, 1]) | |
352 except pd.errors.EmptyDataError: | |
353 sys.exit('Execution aborted: wrong format of custom GPR rules\n') | |
354 except pd.errors.ParserError: | |
355 sys.exit('Execution aborted: wrong format of custom GPR rules\n') | |
356 split_rules, tmp_genes = do_rules(rules) | |
357 gene_in_rule = {} | |
358 for i in tmp_genes: | |
359 gene_in_rule[i] = 'ok' | |
360 return (ids, split_rules, gene_in_rule) | |
361 | |
362 ############################ resolve_methods ################################## | |
363 | |
364 def replace_gene_value(l, d): | |
365 tmp = [] | |
366 err = [] | |
367 while l: | |
368 if isinstance(l[0], list): | |
369 tmp_rules, tmp_err = replace_gene_value(l[0], d) | |
370 tmp.append(tmp_rules) | |
371 err.extend(tmp_err) | |
372 else: | |
373 value = replace_gene(l[0],d) | |
374 tmp.append(value) | |
375 if value == None: | |
376 err.append(l[0]) | |
377 l = l[1:] | |
378 return (tmp, err) | |
379 | |
380 def replace_gene(l, d): | |
381 if l =='and' or l == 'or': | |
382 return l | |
383 else: | |
384 value = d.get(l, None) | |
385 if not(value == None or isinstance(value, (int, float))): | |
386 sys.exit('Execution aborted: ' + value + ' value not valid\n') | |
387 return value | |
388 | |
389 def compute(val1, op, val2, cn): | |
390 if val1 != None and val2 != None: | |
391 if op == 'and': | |
392 return min(val1, val2) | |
393 else: | |
394 return val1 + val2 | |
395 elif op == 'and': | |
396 if cn is True: | |
397 if val1 != None: | |
398 return val1 | |
399 elif val2 != None: | |
400 return val2 | |
401 else: | |
402 return None | |
403 else: | |
404 return None | |
405 else: | |
406 if val1 != None: | |
407 return val1 | |
408 elif val2 != None: | |
409 return val2 | |
410 else: | |
411 return None | |
412 | |
413 def control(ris, l, cn): | |
414 if len(l) == 1: | |
415 if isinstance(l[0], (float, int)) or l[0] == None: | |
416 return l[0] | |
417 elif isinstance(l[0], list): | |
418 return control(None, l[0], cn) | |
419 else: | |
420 return False | |
421 elif len(l) > 2: | |
422 return control_list(ris, l, cn) | |
423 else: | |
424 return False | |
425 | |
426 def control_list(ris, l, cn): | |
427 while l: | |
428 if len(l) == 1: | |
429 return False | |
430 elif (isinstance(l[0], (float, int)) or | |
431 l[0] == None) and l[1] in ['and', 'or']: | |
432 if isinstance(l[2], (float, int)) or l[2] == None: | |
433 ris = compute(l[0], l[1], l[2], cn) | |
434 elif isinstance(l[2], list): | |
435 tmp = control(None, l[2], cn) | |
436 if tmp is False: | |
437 return False | |
438 else: | |
439 ris = compute(l[0], l[1], tmp, cn) | |
440 else: | |
441 return False | |
442 l = l[3:] | |
443 elif l[0] in ['and', 'or']: | |
444 if isinstance(l[1], (float, int)) or l[1] == None: | |
445 ris = compute(ris, l[0], l[1], cn) | |
446 elif isinstance(l[1], list): | |
447 tmp = control(None,l[1], cn) | |
448 if tmp is False: | |
449 return False | |
450 else: | |
451 ris = compute(ris, l[0], tmp, cn) | |
452 else: | |
453 return False | |
454 l = l[2:] | |
455 elif isinstance(l[0], list) and l[1] in ['and', 'or']: | |
456 if isinstance(l[2], (float, int)) or l[2] == None: | |
457 tmp = control(None, l[0], cn) | |
458 if tmp is False: | |
459 return False | |
460 else: | |
461 ris = compute(tmp, l[1], l[2], cn) | |
462 elif isinstance(l[2], list): | |
463 tmp = control(None, l[0], cn) | |
464 tmp2 = control(None, l[2], cn) | |
465 if tmp is False or tmp2 is False: | |
466 return False | |
467 else: | |
468 ris = compute(tmp, l[1], tmp2, cn) | |
469 else: | |
470 return False | |
471 l = l[3:] | |
472 else: | |
473 return False | |
474 return ris | |
475 | |
476 ############################ gene ############################################# | |
477 | |
478 def data_gene(gene, type_gene, name, gene_custom): | |
479 args = process_args(sys.argv) | 388 args = process_args(sys.argv) |
480 for i in range(len(gene)): | 389 |
481 tmp = gene.iloc[i, 0] | 390 #Data read |
482 if tmp.startswith(' ') or tmp.endswith(' '): | 391 |
483 gene.iloc[i, 0] = (tmp.lstrip()).rstrip() | 392 X = read_dataset(args.input) |
484 gene_dup = [item for item, count in | 393 X = pd.DataFrame.to_dict(X, orient='list') |
485 collections.Counter(gene[gene.columns[0]]).items() if count > 1] | 394 X = rewrite_input(X) |
486 pat_dup = [item for item, count in | 395 X = pd.DataFrame.from_dict(X, orient = 'index') |
487 collections.Counter(list(gene.columns)).items() if count > 1] | 396 |
488 if gene_dup: | 397 for i in X.columns: |
489 if gene_custom == None: | 398 tmp = X[i][0] |
490 if args.rules_selector == 'HMRcore': | |
491 gene_in_rule = pk.load(open(args.tool_dir + | |
492 '/local/HMRcore_genes.p', 'rb')) | |
493 elif args.rules_selector == 'Recon': | |
494 gene_in_rule = pk.load(open(args.tool_dir + | |
495 '/local/Recon_genes.p', 'rb')) | |
496 gene_in_rule = gene_in_rule.get(type_gene) | |
497 else: | |
498 gene_in_rule = gene_custom | |
499 tmp = [] | |
500 for i in gene_dup: | |
501 if gene_in_rule.get(i) == 'ok': | |
502 tmp.append(i) | |
503 if tmp: | |
504 sys.exit('Execution aborted because gene ID ' | |
505 + str(tmp) + ' in ' + name + ' is duplicated\n') | |
506 if pat_dup: | |
507 sys.exit('Execution aborted: duplicated label\n' | |
508 + str(pat_dup) + 'in ' + name + '\n') | |
509 return (gene.set_index(gene.columns[0])).to_dict() | |
510 | |
511 ############################ resolve ########################################## | |
512 | |
513 def resolve(genes, rules, ids, resolve_none, name): | |
514 resolve_rules = {} | |
515 not_found = [] | |
516 flag = False | |
517 for key, value in genes.items(): | |
518 tmp_resolve = [] | |
519 for i in range(len(rules)): | |
520 tmp = rules[i] | |
521 if tmp: | |
522 tmp, err = replace_gene_value(tmp, value) | |
523 if err: | |
524 not_found.extend(err) | |
525 ris = control(None, tmp, resolve_none) | |
526 if ris is False or ris == None: | |
527 tmp_resolve.append(None) | |
528 else: | |
529 tmp_resolve.append(ris) | |
530 flag = True | |
531 else: | |
532 tmp_resolve.append(None) | |
533 resolve_rules[key] = tmp_resolve | |
534 if flag is False: | |
535 sys.exit('Execution aborted: no computable score' + | |
536 ' (due to missing gene values) for class ' | |
537 + name + ', the class has been disregarded\n') | |
538 return (resolve_rules, list(set(not_found))) | |
539 | |
540 ################################# clustering ################################## | |
541 | |
542 def f_cluster(resolve_rules): | |
543 os.makedirs('cluster_out') | |
544 args = process_args(sys.argv) | |
545 k_min = args.k_min | |
546 k_max = args.k_max | |
547 if k_min > k_max: | |
548 warning('k range boundaries inverted.\n') | |
549 tmp = k_min | |
550 k_min = k_max | |
551 k_max = tmp | |
552 else: | |
553 warning('k range correct.\n') | |
554 cluster_data = pd.DataFrame.from_dict(resolve_rules, orient = 'index') | |
555 for i in cluster_data.columns: | |
556 tmp = cluster_data[i][0] | |
557 if tmp == None: | 399 if tmp == None: |
558 cluster_data = cluster_data.drop(columns=[i]) | 400 X = X.drop(columns=[i]) |
559 distorsion = [] | 401 |
560 for i in range(k_min, k_max+1): | 402 X = pd.DataFrame.to_numpy(X) |
561 tmp_kmeans = KMeans(n_clusters = i, | 403 |
562 n_init = 100, | 404 |
563 max_iter = 300, | 405 if args.cluster_type == 'kmeans': |
564 random_state = 0).fit(cluster_data) | 406 kmeans(args.k_min, args.k_max, X, args.elbow, args.silhouette, args.davies) |
565 distorsion.append(tmp_kmeans.inertia_) | 407 |
566 predict = tmp_kmeans.predict(cluster_data) | 408 if args.cluster_type == 'dbscan': |
567 predict = [x+1 for x in predict] | 409 dbscan(X, args.eps, args.min_samples) |
568 classe = (pd.DataFrame(list(zip(cluster_data.index, predict)))).astype(str) | 410 |
569 dest = 'cluster_out/K=' + str(i) + '_' + args.name+'.tsv' | 411 if args.cluster_type == 'hierarchy': |
570 classe.to_csv(dest, sep = '\t', index = False, | 412 hierachical_agglomerative(X, args.k_min, args.k_max) |
571 header = ['Patient_ID', 'Class']) | 413 |
572 plt.figure(0) | 414 ############################################################################## |
573 plt.plot(range(k_min, k_max+1), distorsion, marker = 'o') | |
574 plt.xlabel('Number of cluster') | |
575 plt.ylabel('Distorsion') | |
576 plt.savefig(args.elbow, dpi = 240, format = 'pdf') | |
577 if args.cond_hier == 'yes': | |
578 import scipy.cluster.hierarchy as hier | |
579 lin = hier.linkage(cluster_data, args.linkage) | |
580 plt.figure(1) | |
581 plt.figure(figsize=(10, 5)) | |
582 hier.dendrogram(lin, leaf_font_size = 2, labels = cluster_data.index) | |
583 plt.savefig(args.dendro, dpi = 480, format = 'pdf') | |
584 return None | |
585 | |
586 ################################# main ######################################## | |
587 | |
588 def main(): | |
589 args = process_args(sys.argv) | |
590 if args.rules_selector == 'HMRcore': | |
591 recon = pk.load(open(args.tool_dir + '/local/HMRcore_rules.p', 'rb')) | |
592 elif args.rules_selector == 'Recon': | |
593 recon = pk.load(open(args.tool_dir + '/local/Recon_rules.p', 'rb')) | |
594 elif args.rules_selector == 'Custom': | |
595 ids, rules, gene_in_rule = make_recon(args.custom) | |
596 resolve_none = check_bool(args.none) | |
597 dataset = read_dataset(args.data, args.name) | |
598 dataset.iloc[:, 0] = (dataset.iloc[:, 0]).astype(str) | |
599 type_gene = gene_type(dataset.iloc[0, 0], args.name) | |
600 if args.rules_selector != 'Custom': | |
601 genes = data_gene(dataset, type_gene, args.name, None) | |
602 ids, rules = load_id_rules(recon.get(type_gene)) | |
603 elif args.rules_selector == 'Custom': | |
604 genes = data_gene(dataset, type_gene, args.name, gene_in_rule) | |
605 resolve_rules, err = resolve(genes, rules, ids, resolve_none, args.name) | |
606 if err: | |
607 warning('WARNING: gene\n' + str(err) + '\nnot found in class ' | |
608 + args.name + ', the expression level for this gene ' + | |
609 'will be considered NaN\n') | |
610 f_cluster(resolve_rules) | |
611 warning('Execution succeeded') | |
612 return None | |
613 | |
614 ############################################################################### | |
615 | 415 |
616 if __name__ == "__main__": | 416 if __name__ == "__main__": |
617 main() | 417 main() |