Coverage for biobb_ml/clustering/spectral_coefficient.py: 83%
82 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-10-03 14:57 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2024-10-03 14:57 +0000
1#!/usr/bin/env python3
3"""Module containing the SpectralCoefficient class and the command line interface."""
4import argparse
5import pandas as pd
6import numpy as np
7from biobb_common.generic.biobb_object import BiobbObject
8from sklearn.preprocessing import StandardScaler
9from biobb_common.configuration import settings
10from biobb_common.tools import file_utils as fu
11from biobb_common.tools.file_utils import launchlogger
12from biobb_ml.clustering.common import check_input_path, check_output_path, getHeader, getIndependentVars, getIndependentVarsList, hopkins, getSilhouetthe, plotAgglomerativeTrain
15class SpectralCoefficient(BiobbObject):
16 """
17 | biobb_ml SpectralCoefficient
18 | Wrapper of the scikit-learn SpectralClustering method.
19 | Clusters a given dataset and calculates best K coefficient. Visit the `SpectralClustering documentation page <https://scikit-learn.org/stable/modules/generated/sklearn.cluster.SpectralClustering.html>`_ in the sklearn official website for further information.
21 Args:
22 input_dataset_path (str): Path to the input dataset. File type: input. `Sample file <https://github.com/bioexcel/biobb_ml/raw/master/biobb_ml/test/data/clustering/dataset_spectral_coefficient.csv>`_. Accepted formats: csv (edam:format_3752).
23 output_results_path (str): Table with WCSS (elbow method), Gap and Silhouette coefficients for each cluster. File type: output. `Sample file <https://github.com/bioexcel/biobb_ml/raw/master/biobb_ml/test/reference/clustering/ref_output_results_spectral_coefficient.csv>`_. Accepted formats: csv (edam:format_3752).
24 output_plot_path (str) (Optional): Path to the elbow method and gap statistics plot. File type: output. `Sample file <https://github.com/bioexcel/biobb_ml/raw/master/biobb_ml/test/reference/clustering/ref_output_plot_spectral_coefficient.png>`_. Accepted formats: png (edam:format_3603).
25 properties (dic - Python dictionary object containing the tool parameters, not input/output files):
26 * **predictors** (*dict*) - ({}) Features or columns from your dataset you want to use for fitting. You can specify either a list of columns names from your input dataset, a list of columns indexes or a range of columns indexes. Formats: { "columns": ["column1", "column2"] } or { "indexes": [0, 2, 3, 10, 11, 17] } or { "range": [[0, 20], [50, 102]] }. In case of mulitple formats, the first one will be picked.
27 * **max_clusters** (*int*) - (6) [1~100|1] Maximum number of clusters to use by default for kmeans queries.
28 * **random_state_method** (*int*) - (5) [1~1000|1] A pseudo random number generator used for the initialization of the lobpcg eigen vectors decomposition when *eigen_solver='amg'* and by the K-Means initialization.
29 * **scale** (*bool*) - (False) Whether or not to scale the input dataset.
30 * **remove_tmp** (*bool*) - (True) [WF property] Remove temporal files.
31 * **restart** (*bool*) - (False) [WF property] Do not execute if output files exist.
32 * **sandbox_path** (*str*) - ("./") [WF property] Parent path to the sandbox directory.
34 Examples:
35 This is a use example of how to use the building block from Python::
37 from biobb_ml.clustering.spectral_coefficient import spectral_coefficient
38 prop = {
39 'predictors': {
40 'columns': [ 'column1', 'column2', 'column3' ]
41 },
42 'max_clusters': 6
43 }
44 spectral_coefficient(input_dataset_path='/path/to/myDataset.csv',
45 output_results_path='/path/to/newTable.csv',
46 output_plot_path='/path/to/newPlot.png',
47 properties=prop)
49 Info:
50 * wrapped_software:
51 * name: scikit-learn SpectralClustering
52 * version: >=0.24.2
53 * license: BSD 3-Clause
54 * ontology:
55 * name: EDAM
56 * schema: http://edamontology.org/EDAM.owl
58 """
60 def __init__(self, input_dataset_path, output_results_path,
61 output_plot_path=None, properties=None, **kwargs) -> None:
62 properties = properties or {}
64 # Call parent class constructor
65 super().__init__(properties)
66 self.locals_var_dict = locals().copy()
68 # Input/Output files
69 self.io_dict = {
70 "in": {"input_dataset_path": input_dataset_path},
71 "out": {"output_results_path": output_results_path, "output_plot_path": output_plot_path}
72 }
74 # Properties specific for BB
75 self.predictors = properties.get('predictors', {})
76 self.max_clusters = properties.get('max_clusters', 6)
77 self.random_state_method = properties.get('random_state_method', 5)
78 self.scale = properties.get('scale', False)
79 self.properties = properties
81 # Check the properties
82 self.check_properties(properties)
83 self.check_arguments()
85 def check_data_params(self, out_log, err_log):
86 """ Checks all the input/output paths and parameters """
87 self.io_dict["in"]["input_dataset_path"] = check_input_path(self.io_dict["in"]["input_dataset_path"], "input_dataset_path", out_log, self.__class__.__name__)
88 self.io_dict["out"]["output_results_path"] = check_output_path(self.io_dict["out"]["output_results_path"], "output_results_path", False, out_log, self.__class__.__name__)
89 if self.io_dict["out"]["output_plot_path"]:
90 self.io_dict["out"]["output_plot_path"] = check_output_path(self.io_dict["out"]["output_plot_path"], "output_plot_path", True, out_log, self.__class__.__name__)
92 @launchlogger
93 def launch(self) -> int:
94 """Execute the :class:`SpectralCoefficient <clustering.spectral_coefficient.SpectralCoefficient>` clustering.spectral_coefficient.SpectralCoefficient object."""
96 # check input/output paths and parameters
97 self.check_data_params(self.out_log, self.err_log)
99 # Setup Biobb
100 if self.check_restart():
101 return 0
102 self.stage_files()
104 # load dataset
105 fu.log('Getting dataset from %s' % self.io_dict["in"]["input_dataset_path"], self.out_log, self.global_log)
106 if 'columns' in self.predictors:
107 labels = getHeader(self.io_dict["in"]["input_dataset_path"])
108 skiprows = 1
109 else:
110 labels = None
111 skiprows = None
112 data = pd.read_csv(self.io_dict["in"]["input_dataset_path"], header=None, sep="\\s+|;|:|,|\t", engine="python", skiprows=skiprows, names=labels)
114 # the features are the predictors
115 predictors = getIndependentVars(self.predictors, data, self.out_log, self.__class__.__name__)
116 fu.log('Predictors: [%s]' % (getIndependentVarsList(self.predictors)), self.out_log, self.global_log)
118 # Hopkins test
119 H = hopkins(predictors)
120 fu.log('Performing Hopkins test over dataset. H = %f' % H, self.out_log, self.global_log)
122 # scale dataset
123 if self.scale:
124 fu.log('Scaling dataset', self.out_log, self.global_log)
125 scaler = StandardScaler()
126 predictors = scaler.fit_transform(predictors)
128 # calculate silhouette
129 silhouette_list, s_list = getSilhouetthe(method='spectral', X=predictors, max_clusters=self.max_clusters, random_state=self.random_state_method)
131 # silhouette table
132 silhouette_table = pd.DataFrame(data={'cluster': np.arange(1, self.max_clusters + 1), 'SILHOUETTE': silhouette_list})
133 fu.log('Calculating Silhouette for each cluster\n\nSILHOUETTE TABLE\n\n%s\n' % silhouette_table.to_string(index=False), self.out_log, self.global_log)
135 # get best cluster silhouette method
136 key = silhouette_list.index(max(silhouette_list))
137 best_s = s_list.__getitem__(key)
138 fu.log('Optimal number of clusters according to the Silhouette Method is %d' % best_s, self.out_log, self.global_log)
140 # save results table
141 results_table = pd.DataFrame(data={'method': ['silhouette'], 'coefficient': [max(silhouette_list)], 'cluster': [best_s]})
142 fu.log('Gathering results\n\nRESULTS TABLE\n\n%s\n' % results_table.to_string(index=False), self.out_log, self.global_log)
143 fu.log('Saving results to %s' % self.io_dict["out"]["output_results_path"], self.out_log, self.global_log)
144 results_table.to_csv(self.io_dict["out"]["output_results_path"], index=False, header=True, float_format='%.3f')
146 # wcss plot
147 if self.io_dict["out"]["output_plot_path"]:
148 fu.log('Saving methods plot to %s' % self.io_dict["out"]["output_plot_path"], self.out_log, self.global_log)
149 plot = plotAgglomerativeTrain(self.max_clusters, silhouette_list, best_s)
150 plot.savefig(self.io_dict["out"]["output_plot_path"], dpi=150)
152 # Copy files to host
153 self.copy_to_host()
155 self.tmp_files.extend([
156 self.stage_io_dict.get("unique_dir")
157 ])
158 self.remove_tmp_files()
160 self.check_arguments(output_files_created=True, raise_exception=False)
162 return 0
165def spectral_coefficient(input_dataset_path: str, output_results_path: str, output_plot_path: str = None, properties: dict = None, **kwargs) -> int:
166 """Execute the :class:`SpectralCoefficient <clustering.spectral_coefficient.SpectralCoefficient>` class and
167 execute the :meth:`launch() <clustering.spectral_coefficient.SpectralCoefficient.launch>` method."""
169 return SpectralCoefficient(input_dataset_path=input_dataset_path,
170 output_results_path=output_results_path,
171 output_plot_path=output_plot_path,
172 properties=properties, **kwargs).launch()
175def main():
176 """Command line execution of this building block. Please check the command line documentation."""
177 parser = argparse.ArgumentParser(description="Wrapper of the scikit-learn SpectralClustering method.", formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999))
178 parser.add_argument('--config', required=False, help='Configuration file')
180 # Specific args of each building block
181 required_args = parser.add_argument_group('required arguments')
182 required_args.add_argument('--input_dataset_path', required=True, help='Path to the input dataset. Accepted formats: csv.')
183 required_args.add_argument('--output_results_path', required=True, help='Table with WCSS (elbow method), Gap and Silhouette coefficients for each cluster. Accepted formats: csv.')
184 parser.add_argument('--output_plot_path', required=False, help='Path to the elbow and gap methods plot. Accepted formats: png.')
186 args = parser.parse_args()
187 args.config = args.config or "{}"
188 properties = settings.ConfReader(config=args.config).get_prop_dic()
190 # Specific call of each building block
191 spectral_coefficient(input_dataset_path=args.input_dataset_path,
192 output_results_path=args.output_results_path,
193 output_plot_path=args.output_plot_path,
194 properties=properties)
197if __name__ == '__main__':
198 main()