4
|
1 # -*- coding: utf-8 -*-
|
|
2 """
|
|
3 Created on Mon Jun 3 19:51:00 2019
|
|
4 @author: Narger
|
|
5 """
|
|
6
|
|
7 import sys
|
|
8 import argparse
|
|
9 import os
|
|
10 import numpy as np
|
|
11 import pandas as pd
|
|
12 from sklearn.datasets import make_blobs
|
|
13 from sklearn.cluster import KMeans, DBSCAN, AgglomerativeClustering
|
|
14 from sklearn.metrics import silhouette_samples, silhouette_score, cluster
|
|
15 import matplotlib
|
|
16 matplotlib.use('agg')
|
|
17 import matplotlib.pyplot as plt
|
|
18 import scipy.cluster.hierarchy as shc
|
|
19 import matplotlib.cm as cm
|
|
20 from typing import Optional, Dict, List
|
|
21
|
|
22 ################################# process args ###############################
|
147
|
23 def process_args(args :List[str] = None) -> argparse.Namespace:
|
4
|
24 """
|
|
25 Processes command-line arguments.
|
|
26
|
|
27 Args:
|
|
28 args (list): List of command-line arguments.
|
|
29
|
|
30 Returns:
|
|
31 Namespace: An object containing parsed arguments.
|
|
32 """
|
|
33 parser = argparse.ArgumentParser(usage = '%(prog)s [options]',
|
|
34 description = 'process some value\'s' +
|
|
35 ' genes to create class.')
|
|
36
|
|
37 parser.add_argument('-ol', '--out_log',
|
|
38 help = "Output log")
|
|
39
|
|
40 parser.add_argument('-in', '--input',
|
|
41 type = str,
|
|
42 help = 'input dataset')
|
|
43
|
|
44 parser.add_argument('-cy', '--cluster_type',
|
|
45 type = str,
|
|
46 choices = ['kmeans', 'dbscan', 'hierarchy'],
|
|
47 default = 'kmeans',
|
|
48 help = 'choose clustering algorythm')
|
|
49
|
|
50 parser.add_argument('-k1', '--k_min',
|
|
51 type = int,
|
|
52 default = 2,
|
|
53 help = 'choose minimun cluster number to be generated')
|
|
54
|
|
55 parser.add_argument('-k2', '--k_max',
|
|
56 type = int,
|
|
57 default = 7,
|
|
58 help = 'choose maximum cluster number to be generated')
|
|
59
|
|
60 parser.add_argument('-el', '--elbow',
|
|
61 type = str,
|
|
62 default = 'false',
|
|
63 choices = ['true', 'false'],
|
|
64 help = 'choose if you want to generate an elbow plot for kmeans')
|
|
65
|
|
66 parser.add_argument('-si', '--silhouette',
|
|
67 type = str,
|
|
68 default = 'false',
|
|
69 choices = ['true', 'false'],
|
|
70 help = 'choose if you want silhouette plots')
|
|
71
|
|
72 parser.add_argument('-td', '--tool_dir',
|
|
73 type = str,
|
|
74 required = True,
|
|
75 help = 'your tool directory')
|
|
76
|
|
77 parser.add_argument('-ms', '--min_samples',
|
|
78 type = float,
|
|
79 help = 'min samples for dbscan (optional)')
|
|
80
|
|
81 parser.add_argument('-ep', '--eps',
|
|
82 type = float,
|
|
83 help = 'eps for dbscan (optional)')
|
|
84
|
|
85 parser.add_argument('-bc', '--best_cluster',
|
|
86 type = str,
|
|
87 help = 'output of best cluster tsv')
|
|
88
|
147
|
89 parser.add_argument(
|
|
90 '-idop', '--output_path',
|
|
91 type = str,
|
|
92 default='result',
|
|
93 help = 'output path for maps')
|
4
|
94
|
147
|
95 args = parser.parse_args(args)
|
4
|
96 return args
|
|
97
|
|
98 ########################### warning ###########################################
|
|
99 def warning(s :str) -> None:
|
|
100 """
|
|
101 Log a warning message to an output log file and print it to the console.
|
|
102
|
|
103 Args:
|
|
104 s (str): The warning message to be logged and printed.
|
|
105
|
|
106 Returns:
|
|
107 None
|
|
108 """
|
|
109 args = process_args(sys.argv)
|
|
110 with open(args.out_log, 'a') as log:
|
|
111 log.write(s + "\n\n")
|
|
112 print(s)
|
|
113
|
|
114 ########################## read dataset ######################################
|
|
115 def read_dataset(dataset :str) -> pd.DataFrame:
|
|
116 """
|
|
117 Read dataset from a CSV file and return it as a Pandas DataFrame.
|
|
118
|
|
119 Args:
|
|
120 dataset (str): the path to the dataset to convert into a DataFrame
|
|
121
|
|
122 Returns:
|
|
123 pandas.DataFrame: The dataset loaded as a Pandas DataFrame.
|
|
124
|
|
125 Raises:
|
|
126 pandas.errors.EmptyDataError: If the dataset file is empty.
|
|
127 sys.exit: If the dataset file has the wrong format (e.g., fewer than 2 columns)
|
|
128 """
|
|
129 try:
|
|
130 dataset = pd.read_csv(dataset, sep = '\t', header = 0)
|
|
131 except pd.errors.EmptyDataError:
|
|
132 sys.exit('Execution aborted: wrong format of dataset\n')
|
|
133 if len(dataset.columns) < 2:
|
|
134 sys.exit('Execution aborted: wrong format of dataset\n')
|
|
135 return dataset
|
|
136
|
|
137 ############################ rewrite_input ###################################
|
|
138 def rewrite_input(dataset :pd.DataFrame) -> Dict[str, List[Optional[float]]]:
|
|
139 """
|
|
140 Rewrite the dataset as a dictionary of lists instead of as a dictionary of dictionaries.
|
|
141
|
|
142 Args:
|
|
143 dataset (pandas.DataFrame): The dataset to be rewritten.
|
|
144
|
|
145 Returns:
|
|
146 dict: The rewritten dataset as a dictionary of lists.
|
|
147 """
|
|
148 #Riscrivo il dataset come dizionario di liste,
|
|
149 #non come dizionario di dizionari
|
|
150
|
|
151 dataset.pop('Reactions', None)
|
|
152
|
|
153 for key, val in dataset.items():
|
|
154 l = []
|
|
155 for i in val:
|
|
156 if i == 'None':
|
|
157 l.append(None)
|
|
158 else:
|
|
159 l.append(float(i))
|
|
160
|
|
161 dataset[key] = l
|
|
162
|
|
163 return dataset
|
|
164
|
|
165 ############################## write to csv ##################################
|
|
166 def write_to_csv (dataset :pd.DataFrame, labels :List[str], name :str) -> None:
|
|
167 """
|
|
168 Write dataset and predicted labels to a CSV file.
|
|
169
|
|
170 Args:
|
|
171 dataset (pandas.DataFrame): The dataset to be written.
|
|
172 labels (list): The predicted labels for each data point.
|
|
173 name (str): The name of the output CSV file.
|
|
174
|
|
175 Returns:
|
|
176 None
|
|
177 """
|
|
178 #labels = predict
|
|
179 predict = [x+1 for x in labels]
|
|
180
|
|
181 classe = (pd.DataFrame(list(zip(dataset.index, predict)))).astype(str)
|
|
182
|
|
183 dest = name
|
|
184 classe.to_csv(dest, sep = '\t', index = False,
|
|
185 header = ['Patient_ID', 'Class'])
|
|
186
|
|
187 ########################### trova il massimo in lista ########################
|
|
188 def max_index (lista :List[int]) -> int:
|
|
189 """
|
|
190 Find the index of the maximum value in a list.
|
|
191
|
|
192 Args:
|
|
193 lista (list): The list in which we search for the index of the maximum value.
|
|
194
|
|
195 Returns:
|
|
196 int: The index of the maximum value in the list.
|
|
197 """
|
|
198 best = -1
|
|
199 best_index = 0
|
|
200 for i in range(len(lista)):
|
|
201 if lista[i] > best:
|
|
202 best = lista [i]
|
|
203 best_index = i
|
|
204
|
|
205 return best_index
|
|
206
|
|
207 ################################ kmeans #####################################
|
|
208 def kmeans (k_min: int, k_max: int, dataset: pd.DataFrame, elbow: str, silhouette: str, best_cluster: str) -> None:
|
|
209 """
|
|
210 Perform k-means clustering on the given dataset, which is an algorithm used to partition a dataset into groups (clusters) based on their characteristics.
|
|
211 The goal is to divide the data into homogeneous groups, where the elements within each group are similar to each other and different from the elements in other groups.
|
|
212
|
|
213 Args:
|
|
214 k_min (int): The minimum number of clusters to consider.
|
|
215 k_max (int): The maximum number of clusters to consider.
|
|
216 dataset (pandas.DataFrame): The dataset to perform clustering on.
|
|
217 elbow (str): Whether to generate an elbow plot for kmeans ('true' or 'false').
|
|
218 silhouette (str): Whether to generate silhouette plots ('true' or 'false').
|
|
219 best_cluster (str): The file path to save the output of the best cluster.
|
|
220
|
|
221 Returns:
|
|
222 None
|
|
223 """
|
147
|
224 if not os.path.exists(args.output_path):
|
|
225 os.makedirs(args.output_path)
|
4
|
226
|
|
227
|
|
228 if elbow == 'true':
|
|
229 elbow = True
|
|
230 else:
|
|
231 elbow = False
|
|
232
|
|
233 if silhouette == 'true':
|
|
234 silhouette = True
|
|
235 else:
|
|
236 silhouette = False
|
|
237
|
|
238 range_n_clusters = [i for i in range(k_min, k_max+1)]
|
|
239 distortions = []
|
|
240 scores = []
|
|
241 all_labels = []
|
|
242
|
|
243 clusterer = KMeans(n_clusters=1, random_state=10)
|
|
244 distortions.append(clusterer.fit(dataset).inertia_)
|
|
245
|
|
246
|
|
247 for n_clusters in range_n_clusters:
|
|
248 clusterer = KMeans(n_clusters=n_clusters, random_state=10)
|
|
249 cluster_labels = clusterer.fit_predict(dataset)
|
|
250
|
|
251 all_labels.append(cluster_labels)
|
|
252 if n_clusters == 1:
|
|
253 silhouette_avg = 0
|
|
254 else:
|
|
255 silhouette_avg = silhouette_score(dataset, cluster_labels)
|
|
256 scores.append(silhouette_avg)
|
|
257 distortions.append(clusterer.fit(dataset).inertia_)
|
|
258
|
|
259 best = max_index(scores) + k_min
|
|
260
|
|
261 for i in range(len(all_labels)):
|
|
262 prefix = ''
|
|
263 if (i + k_min == best):
|
|
264 prefix = '_BEST'
|
|
265
|
147
|
266 write_to_csv(dataset, all_labels[i], f'{args.output_path}/kmeans_with_' + str(i + k_min) + prefix + '_clusters.tsv')
|
4
|
267
|
|
268
|
|
269 if (prefix == '_BEST'):
|
|
270 labels = all_labels[i]
|
|
271 predict = [x+1 for x in labels]
|
|
272 classe = (pd.DataFrame(list(zip(dataset.index, predict)))).astype(str)
|
|
273 classe.to_csv(best_cluster, sep = '\t', index = False, header = ['Patient_ID', 'Class'])
|
|
274
|
|
275
|
|
276
|
|
277
|
|
278 if silhouette:
|
147
|
279 silhouette_draw(dataset, all_labels[i], i + k_min, f'{args.output_path}/silhouette_with_' + str(i + k_min) + prefix + '_clusters.png')
|
4
|
280
|
|
281
|
|
282 if elbow:
|
|
283 elbow_plot(distortions, k_min,k_max)
|
|
284
|
|
285
|
|
286
|
|
287
|
|
288
|
|
289 ############################## elbow_plot ####################################
|
|
290 def elbow_plot (distortions: List[float], k_min: int, k_max: int) -> None:
|
|
291 """
|
|
292 Generate an elbow plot to visualize the distortion for different numbers of clusters.
|
|
293 The elbow plot is a graphical tool used in clustering analysis to help identifying the appropriate number of clusters by looking for the point where the rate of decrease
|
|
294 in distortion sharply decreases, indicating the optimal balance between model complexity and clustering quality.
|
|
295
|
|
296 Args:
|
|
297 distortions (list): List of distortion values for different numbers of clusters.
|
|
298 k_min (int): The minimum number of clusters considered.
|
|
299 k_max (int): The maximum number of clusters considered.
|
|
300
|
|
301 Returns:
|
|
302 None
|
|
303 """
|
|
304 plt.figure(0)
|
|
305 x = list(range(k_min, k_max + 1))
|
|
306 x.insert(0, 1)
|
|
307 plt.plot(x, distortions, marker = 'o')
|
|
308 plt.xlabel('Number of clusters (k)')
|
|
309 plt.ylabel('Distortion')
|
147
|
310 s = f'{args.output_path}/elbow_plot.png'
|
4
|
311 fig = plt.gcf()
|
|
312 fig.set_size_inches(18.5, 10.5, forward = True)
|
|
313 fig.savefig(s, dpi=100)
|
|
314
|
|
315
|
|
316 ############################## silhouette plot ###############################
|
|
317 def silhouette_draw(dataset: pd.DataFrame, labels: List[str], n_clusters: int, path:str) -> None:
|
|
318 """
|
|
319 Generate a silhouette plot for the clustering results.
|
|
320 The silhouette coefficient is a measure used to evaluate the quality of clusters obtained from a clustering algorithmand it quantifies how similar an object is to its own cluster compared to other clusters.
|
|
321 The silhouette coefficient ranges from -1 to 1, where:
|
|
322 - A value close to +1 indicates that the object is well matched to its own cluster and poorly matched to neighboring clusters. This implies that the object is in a dense, well-separated cluster.
|
|
323 - A value close to 0 indicates that the object is close to the decision boundary between two neighboring clusters.
|
|
324 - A value close to -1 indicates that the object may have been assigned to the wrong cluster.
|
|
325
|
|
326 Args:
|
|
327 dataset (pandas.DataFrame): The dataset used for clustering.
|
|
328 labels (list): The cluster labels assigned to each data point.
|
|
329 n_clusters (int): The number of clusters.
|
|
330 path (str): The path to save the silhouette plot image.
|
|
331
|
|
332 Returns:
|
|
333 None
|
|
334 """
|
|
335 if n_clusters == 1:
|
|
336 return None
|
|
337
|
|
338 silhouette_avg = silhouette_score(dataset, labels)
|
|
339 warning("For n_clusters = " + str(n_clusters) +
|
|
340 " The average silhouette_score is: " + str(silhouette_avg))
|
|
341
|
|
342 plt.close('all')
|
|
343 # Create a subplot with 1 row and 2 columns
|
|
344 fig, (ax1) = plt.subplots(1, 1)
|
|
345
|
|
346 fig.set_size_inches(18, 7)
|
|
347
|
|
348 # The 1st subplot is the silhouette plot
|
|
349 # The silhouette coefficient can range from -1, 1 but in this example all
|
|
350 # lie within [-0.1, 1]
|
|
351 ax1.set_xlim([-1, 1])
|
|
352 # The (n_clusters+1)*10 is for inserting blank space between silhouette
|
|
353 # plots of individual clusters, to demarcate them clearly.
|
|
354 ax1.set_ylim([0, len(dataset) + (n_clusters + 1) * 10])
|
|
355
|
|
356 # Compute the silhouette scores for each sample
|
|
357 sample_silhouette_values = silhouette_samples(dataset, labels)
|
|
358
|
|
359 y_lower = 10
|
|
360 for i in range(n_clusters):
|
|
361 # Aggregate the silhouette scores for samples belonging to
|
|
362 # cluster i, and sort them
|
|
363 ith_cluster_silhouette_values = \
|
|
364 sample_silhouette_values[labels == i]
|
|
365
|
|
366 ith_cluster_silhouette_values.sort()
|
|
367
|
|
368 size_cluster_i = ith_cluster_silhouette_values.shape[0]
|
|
369 y_upper = y_lower + size_cluster_i
|
|
370
|
|
371 color = cm.nipy_spectral(float(i) / n_clusters)
|
|
372 ax1.fill_betweenx(np.arange(y_lower, y_upper),
|
|
373 0, ith_cluster_silhouette_values,
|
|
374 facecolor=color, edgecolor=color, alpha=0.7)
|
|
375
|
|
376 # Label the silhouette plots with their cluster numbers at the middle
|
|
377 ax1.text(-0.05, y_lower + 0.5 * size_cluster_i, str(i))
|
|
378
|
|
379 # Compute the new y_lower for next plot
|
|
380 y_lower = y_upper + 10 # 10 for the 0 samples
|
|
381
|
|
382 ax1.set_title("The silhouette plot for the various clusters.")
|
|
383 ax1.set_xlabel("The silhouette coefficient values")
|
|
384 ax1.set_ylabel("Cluster label")
|
|
385
|
|
386 # The vertical line for average silhouette score of all the values
|
|
387 ax1.axvline(x=silhouette_avg, color="red", linestyle="--")
|
|
388
|
|
389 ax1.set_yticks([]) # Clear the yaxis labels / ticks
|
|
390 ax1.set_xticks([-0.1, 0, 0.2, 0.4, 0.6, 0.8, 1])
|
|
391
|
|
392
|
|
393 plt.suptitle(("Silhouette analysis for clustering on sample data "
|
|
394 "with n_clusters = " + str(n_clusters) + "\nAverage silhouette_score = " + str(silhouette_avg)), fontsize=12, fontweight='bold')
|
|
395
|
|
396
|
|
397 plt.savefig(path, bbox_inches='tight')
|
|
398
|
|
399 ######################## dbscan ##############################################
|
|
400 def dbscan(dataset: pd.DataFrame, eps: float, min_samples: float, best_cluster: str) -> None:
|
|
401 """
|
|
402 Perform DBSCAN clustering on the given dataset, which is a clustering algorithm that groups together closely packed points based on the notion of density.
|
|
403
|
|
404 Args:
|
|
405 dataset (pandas.DataFrame): The dataset to be clustered.
|
|
406 eps (float): The maximum distance between two samples for one to be considered as in the neighborhood of the other.
|
|
407 min_samples (float): The number of samples in a neighborhood for a point to be considered as a core point.
|
|
408 best_cluster (str): The file path to save the output of the best cluster.
|
|
409
|
|
410 Returns:
|
|
411 None
|
|
412 """
|
147
|
413 if not os.path.exists(args.output_path):
|
|
414 os.makedirs(args.output_path)
|
4
|
415
|
|
416 if eps is not None:
|
|
417 clusterer = DBSCAN(eps = eps, min_samples = min_samples)
|
|
418 else:
|
|
419 clusterer = DBSCAN()
|
|
420
|
|
421 clustering = clusterer.fit(dataset)
|
|
422
|
|
423 core_samples_mask = np.zeros_like(clustering.labels_, dtype=bool)
|
|
424 core_samples_mask[clustering.core_sample_indices_] = True
|
|
425 labels = clustering.labels_
|
|
426
|
|
427 # Number of clusters in labels, ignoring noise if present.
|
|
428 n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)
|
|
429
|
|
430
|
|
431 labels = labels
|
|
432 predict = [x+1 for x in labels]
|
|
433 classe = (pd.DataFrame(list(zip(dataset.index, predict)))).astype(str)
|
|
434 classe.to_csv(best_cluster, sep = '\t', index = False, header = ['Patient_ID', 'Class'])
|
|
435
|
|
436
|
|
437 ########################## hierachical #######################################
|
|
438 def hierachical_agglomerative(dataset: pd.DataFrame, k_min: int, k_max: int, best_cluster: str, silhouette: str) -> None:
|
|
439 """
|
|
440 Perform hierarchical agglomerative clustering on the given dataset.
|
|
441
|
|
442 Args:
|
|
443 dataset (pandas.DataFrame): The dataset to be clustered.
|
|
444 k_min (int): The minimum number of clusters to consider.
|
|
445 k_max (int): The maximum number of clusters to consider.
|
|
446 best_cluster (str): The file path to save the output of the best cluster.
|
|
447 silhouette (str): Whether to generate silhouette plots ('true' or 'false').
|
|
448
|
|
449 Returns:
|
|
450 None
|
|
451 """
|
147
|
452 if not os.path.exists(args.output_path):
|
|
453 os.makedirs(args.output_path)
|
4
|
454
|
|
455 plt.figure(figsize=(10, 7))
|
|
456 plt.title("Customer Dendograms")
|
|
457 shc.dendrogram(shc.linkage(dataset, method='ward'), labels=dataset.index.values.tolist())
|
|
458 fig = plt.gcf()
|
147
|
459 fig.savefig(f'{args.output_path}/dendogram.png', dpi=200)
|
4
|
460
|
|
461 range_n_clusters = [i for i in range(k_min, k_max+1)]
|
|
462
|
|
463 scores = []
|
|
464 labels = []
|
|
465
|
|
466 n_classi = dataset.shape[0]
|
|
467
|
|
468 for n_clusters in range_n_clusters:
|
|
469 cluster = AgglomerativeClustering(n_clusters=n_clusters, affinity='euclidean', linkage='ward')
|
|
470 cluster.fit_predict(dataset)
|
|
471 cluster_labels = cluster.labels_
|
|
472 labels.append(cluster_labels)
|
147
|
473 write_to_csv(dataset, cluster_labels, f'{args.output_path}/hierarchical_with_' + str(n_clusters) + '_clusters.tsv')
|
4
|
474
|
|
475 best = max_index(scores) + k_min
|
|
476
|
|
477 for i in range(len(labels)):
|
|
478 prefix = ''
|
|
479 if (i + k_min == best):
|
|
480 prefix = '_BEST'
|
|
481 if silhouette == 'true':
|
147
|
482 silhouette_draw(dataset, labels[i], i + k_min, f'{args.output_path}/silhouette_with_' + str(i + k_min) + prefix + '_clusters.png')
|
4
|
483
|
|
484 for i in range(len(labels)):
|
|
485 if (i + k_min == best):
|
|
486 labels = labels[i]
|
|
487 predict = [x+1 for x in labels]
|
|
488 classe = (pd.DataFrame(list(zip(dataset.index, predict)))).astype(str)
|
|
489 classe.to_csv(best_cluster, sep = '\t', index = False, header = ['Patient_ID', 'Class'])
|
|
490
|
|
491
|
|
492 ############################# main ###########################################
|
147
|
493 def main(args_in:List[str] = None) -> None:
|
4
|
494 """
|
|
495 Initializes everything and sets the program in motion based on the fronted input arguments.
|
|
496
|
|
497 Returns:
|
|
498 None
|
|
499 """
|
147
|
500 global args
|
|
501 args = process_args(args_in)
|
4
|
502
|
147
|
503 if not os.path.exists(args.output_path):
|
|
504 os.makedirs(args.output_path)
|
4
|
505
|
|
506 #Data read
|
|
507
|
|
508 X = read_dataset(args.input)
|
|
509 X = pd.DataFrame.to_dict(X, orient='list')
|
|
510 X = rewrite_input(X)
|
|
511 X = pd.DataFrame.from_dict(X, orient = 'index')
|
|
512
|
|
513 for i in X.columns:
|
|
514 tmp = X[i][0]
|
|
515 if tmp == None:
|
|
516 X = X.drop(columns=[i])
|
|
517
|
|
518 ## NAN TO HANLDE
|
|
519
|
|
520 if args.k_max != None:
|
|
521 numero_classi = X.shape[0]
|
|
522 while args.k_max >= numero_classi:
|
|
523 err = 'Skipping k = ' + str(args.k_max) + ' since it is >= number of classes of dataset'
|
|
524 warning(err)
|
|
525 args.k_max = args.k_max - 1
|
|
526
|
|
527
|
|
528 if args.cluster_type == 'kmeans':
|
|
529 kmeans(args.k_min, args.k_max, X, args.elbow, args.silhouette, args.best_cluster)
|
|
530
|
|
531 if args.cluster_type == 'dbscan':
|
|
532 dbscan(X, args.eps, args.min_samples, args.best_cluster)
|
|
533
|
|
534 if args.cluster_type == 'hierarchy':
|
|
535 hierachical_agglomerative(X, args.k_min, args.k_max, args.best_cluster, args.silhouette)
|
|
536
|
|
537 ##############################################################################
|
|
538 if __name__ == "__main__":
|
|
539 main()
|