Coverage for biobb_ml/clustering/spectral_clustering.py: 83%

90 statements  

« prev     ^ index     » next       coverage.py v7.5.1, created at 2024-05-07 09:39 +0000

1#!/usr/bin/env python3 

2 

3"""Module containing the SpecClustering class and the command line interface.""" 

4import argparse 

5import pandas as pd 

6from biobb_common.generic.biobb_object import BiobbObject 

7from sklearn.preprocessing import StandardScaler 

8from sklearn.cluster import SpectralClustering 

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, plotCluster 

13 

14 

15class SpecClustering(BiobbObject): 

16 """ 

17 | biobb_ml SpecClustering 

18 | Wrapper of the scikit-learn SpectralClustering method. 

19 | Clusters a given dataset. Visit the `SpectralClustering documentation page <https://scikit-learn.org/stable/modules/generated/sklearn.cluster.SpectralClustering.html>`_ in the sklearn official website for further information. 

20 

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_clustering.csv>`_. Accepted formats: csv (edam:format_3752). 

23 output_results_path (str): Path to the clustered dataset. File type: output. `Sample file <https://github.com/bioexcel/biobb_ml/raw/master/biobb_ml/test/reference/clustering/ref_output_results_spectral_clustering.csv>`_. Accepted formats: csv (edam:format_3752). 

24 output_plot_path (str) (Optional): Path to the clustering plot. File type: output. `Sample file <https://github.com/bioexcel/biobb_ml/raw/master/biobb_ml/test/reference/clustering/ref_output_plot_spectral_clustering.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 * **clusters** (*int*) - (3) [1~100|1] The number of clusters to form as well as the number of centroids to generate. 

28 * **affinity** (*string*) - ("rbf") How to construct the affinity matrix. Values: nearest_neighbors (construct the affinity matrix by computing a graph of nearest neighbors), rbf (construct the affinity matrix using a radial basis function -RBF- kernel), precomputed (interpret X as a precomputed affinity matrix), precomputed_nearest_neighbors (interpret X as a sparse graph of precomputed nearest neighbors and constructs the affinity matrix by selecting the n_neighbors nearest neighbors). 

29 * **plots** (*list*) - (None) List of dictionaries with all plots you want to generate. Only 2D or 3D plots accepted. Format: [ { 'title': 'Plot 1', 'features': ['feat1', 'feat2'] } ]. 

30 * **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. 

31 * **scale** (*bool*) - (False) Whether or not to scale the input dataset. 

32 * **remove_tmp** (*bool*) - (True) [WF property] Remove temporal files. 

33 * **restart** (*bool*) - (False) [WF property] Do not execute if output files exist. 

34 

35 Examples: 

36 This is a use example of how to use the building block from Python:: 

37 

38 from biobb_ml.clustering.spectral_clustering import spectral_clustering 

39 prop = { 

40 'predictors': { 

41 'columns': [ 'column1', 'column2', 'column3' ] 

42 }, 

43 'clusters': 3, 

44 'affinity': 'rbf', 

45 'plots': [ 

46 { 

47 'title': 'Plot 1', 

48 'features': ['feat1', 'feat2'] 

49 } 

50 ] 

51 } 

52 spectral_clustering(input_dataset_path='/path/to/myDataset.csv', 

53 output_results_path='/path/to/newTable.csv', 

54 output_plot_path='/path/to/newPlot.png', 

55 properties=prop) 

56 

57 Info: 

58 * wrapped_software: 

59 * name: scikit-learn SpectralClustering 

60 * version: >=0.24.2 

61 * license: BSD 3-Clause 

62 * ontology: 

63 * name: EDAM 

64 * schema: http://edamontology.org/EDAM.owl 

65 

66 """ 

67 

68 def __init__(self, input_dataset_path, output_results_path, 

69 output_plot_path=None, properties=None, **kwargs) -> None: 

70 properties = properties or {} 

71 

72 # Call parent class constructor 

73 super().__init__(properties) 

74 self.locals_var_dict = locals().copy() 

75 

76 # Input/Output files 

77 self.io_dict = { 

78 "in": {"input_dataset_path": input_dataset_path}, 

79 "out": {"output_results_path": output_results_path, "output_plot_path": output_plot_path} 

80 } 

81 

82 # Properties specific for BB 

83 self.predictors = properties.get('predictors', {}) 

84 self.clusters = properties.get('clusters', 3) 

85 self.affinity = properties.get('affinity', 'rbf') 

86 self.plots = properties.get('plots', []) 

87 self.random_state_method = properties.get('random_state_method', 5) 

88 self.scale = properties.get('scale', False) 

89 self.properties = properties 

90 

91 # Check the properties 

92 self.check_properties(properties) 

93 self.check_arguments() 

94 

95 def check_data_params(self, out_log, err_log): 

96 """ Checks all the input/output paths and parameters """ 

97 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__) 

98 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__) 

99 if self.io_dict["out"]["output_plot_path"]: 

100 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__) 

101 

102 @launchlogger 

103 def launch(self) -> int: 

104 """Execute the :class:`SpecClustering <clustering.spectral_clustering.SpecClustering>` clustering.spectral_clustering.SpecClustering object.""" 

105 

106 # check input/output paths and parameters 

107 self.check_data_params(self.out_log, self.err_log) 

108 

109 # Setup Biobb 

110 if self.check_restart(): 

111 return 0 

112 self.stage_files() 

113 

114 # load dataset 

115 fu.log('Getting dataset from %s' % self.io_dict["in"]["input_dataset_path"], self.out_log, self.global_log) 

116 if 'columns' in self.predictors: 

117 labels = getHeader(self.io_dict["in"]["input_dataset_path"]) 

118 skiprows = 1 

119 else: 

120 labels = None 

121 skiprows = None 

122 data = pd.read_csv(self.io_dict["in"]["input_dataset_path"], header=None, sep="\\s+|;|:|,|\t", engine="python", skiprows=skiprows, names=labels) 

123 

124 # the features are the predictors 

125 predictors = getIndependentVars(self.predictors, data, self.out_log, self.__class__.__name__) 

126 fu.log('Predictors: [%s]' % (getIndependentVarsList(self.predictors)), self.out_log, self.global_log) 

127 

128 # Hopkins test 

129 H = hopkins(predictors) 

130 fu.log('Performing Hopkins test over dataset. H = %f' % H, self.out_log, self.global_log) 

131 

132 # scale dataset 

133 if self.scale: 

134 fu.log('Scaling dataset', self.out_log, self.global_log) 

135 scaler = StandardScaler() 

136 predictors = scaler.fit_transform(predictors) 

137 

138 # create a spectral clustering object with self.clusters clusters 

139 model = SpectralClustering(n_clusters=self.clusters, affinity=self.affinity, random_state=self.random_state_method) 

140 # fit the data 

141 model.fit(predictors) 

142 

143 # create a copy of data, so we can see the clusters next to the original data 

144 clusters = data.copy() 

145 # predict the cluster for each observation 

146 clusters['cluster'] = model.fit_predict(predictors) 

147 

148 fu.log('Calculating results\n\nCLUSTERING TABLE\n\n%s\n' % clusters, self.out_log, self.global_log) 

149 

150 # save results 

151 fu.log('Saving results to %s' % self.io_dict["out"]["output_results_path"], self.out_log, self.global_log) 

152 clusters.to_csv(self.io_dict["out"]["output_results_path"], index=False, header=True, float_format='%.3f') 

153 

154 if self.io_dict["out"]["output_plot_path"] and self.plots: 

155 new_plots = [] 

156 i = 0 

157 for plot in self.plots: 

158 if len(plot['features']) == 2 or len(plot['features']) == 3: 

159 new_plots.append(plot) 

160 i += 1 

161 if i == 6: 

162 break 

163 

164 plot = plotCluster(new_plots, clusters) 

165 fu.log('Saving output plot to %s' % self.io_dict["out"]["output_plot_path"], self.out_log, self.global_log) 

166 plot.savefig(self.io_dict["out"]["output_plot_path"], dpi=150) 

167 

168 # Copy files to host 

169 self.copy_to_host() 

170 

171 self.tmp_files.extend([ 

172 self.stage_io_dict.get("unique_dir") 

173 ]) 

174 self.remove_tmp_files() 

175 

176 self.check_arguments(output_files_created=True, raise_exception=False) 

177 

178 return 0 

179 

180 

181def spectral_clustering(input_dataset_path: str, output_results_path: str, output_plot_path: str = None, properties: dict = None, **kwargs) -> int: 

182 """Execute the :class:`SpecClustering <clustering.spectral_clustering.SpecClustering>` class and 

183 execute the :meth:`launch() <clustering.spectral_clustering.SpecClustering.launch>` method.""" 

184 

185 return SpecClustering(input_dataset_path=input_dataset_path, 

186 output_results_path=output_results_path, 

187 output_plot_path=output_plot_path, 

188 properties=properties, **kwargs).launch() 

189 

190 

191def main(): 

192 """Command line execution of this building block. Please check the command line documentation.""" 

193 parser = argparse.ArgumentParser(description="Wrapper of the scikit-learn SpectralClustering method.", formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999)) 

194 parser.add_argument('--config', required=False, help='Configuration file') 

195 

196 # Specific args of each building block 

197 required_args = parser.add_argument_group('required arguments') 

198 required_args.add_argument('--input_dataset_path', required=True, help='Path to the input dataset. Accepted formats: csv.') 

199 required_args.add_argument('--output_results_path', required=True, help='Path to the clustered dataset. Accepted formats: csv.') 

200 parser.add_argument('--output_plot_path', required=False, help='Path to the clustering plot. Accepted formats: png.') 

201 

202 args = parser.parse_args() 

203 args.config = args.config or "{}" 

204 properties = settings.ConfReader(config=args.config).get_prop_dic() 

205 

206 # Specific call of each building block 

207 spectral_clustering(input_dataset_path=args.input_dataset_path, 

208 output_results_path=args.output_results_path, 

209 output_plot_path=args.output_plot_path, 

210 properties=properties) 

211 

212 

213if __name__ == '__main__': 

214 main()