Coverage for biobb_ml/dimensionality_reduction/principal_component.py: 81%

102 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 PrincipalComponentAnalysis class and the command line interface.""" 

4import argparse 

5import pandas as pd 

6import numpy as np 

7import matplotlib.pyplot as plt 

8from biobb_common.generic.biobb_object import BiobbObject 

9from sklearn.preprocessing import StandardScaler 

10from sklearn.decomposition import PCA 

11from biobb_common.configuration import settings 

12from biobb_common.tools import file_utils as fu 

13from biobb_common.tools.file_utils import launchlogger 

14from biobb_ml.dimensionality_reduction.common import check_input_path, check_output_path, getHeader, getIndependentVars, getIndependentVarsList, getTargetValue, generate_columns_labels, PCA2CPlot, PCA3CPlot 

15 

16 

17class PrincipalComponentAnalysis(BiobbObject): 

18 """ 

19 | biobb_ml PrincipalComponentAnalysis 

20 | Wrapper of the scikit-learn PCA method. 

21 | Analyses a given dataset through Principal Component Analysis (PCA). Visit the `PCA documentation page <https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html>`_ in the sklearn official website for further information. 

22 

23 Args: 

24 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/dimensionality_reduction/dataset_principal_component.csv>`_. Accepted formats: csv (edam:format_3752). 

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

26 output_plot_path (str) (Optional): Path to the Principal Component plot, only if number of components is 2 or 3. File type: output. `Sample file <https://github.com/bioexcel/biobb_ml/raw/master/biobb_ml/test/reference/dimensionality_reduction/ref_output_plot_principal_component.png>`_. Accepted formats: png (edam:format_3603). 

27 properties (dic - Python dictionary object containing the tool parameters, not input/output files): 

28 * **features** (*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. 

29 * **target** (*dict*) - ({}) Dependent variable you want to predict from your dataset. You can specify either a column name or a column index. Formats: { "column": "column3" } or { "index": 21 }. In case of mulitple formats, the first one will be picked. 

30 * **n_components** (*dict*) - ({}) Dictionary containing the number of components to keep (int) or the minimum number of principal components such the 0 to 1 range of the variance (float) is retained. If not set ({}) all components are kept. Formats for integer values: { "value": 2 } or for float values: { "value": 0.3 } 

31 * **random_state_method** (*int*) - (5) [1~1000|1] Controls the randomness of the estimator. 

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

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

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

35 

36 Examples: 

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

38 

39 from biobb_ml.dimensionality_reduction.principal_component import principal_component 

40 prop = { 

41 'features': { 

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

43 }, 

44 'target': { 

45 'column': 'target' 

46 }, 

47 'n_components': { 

48 'int': 2 

49 } 

50 } 

51 principal_component(input_dataset_path='/path/to/myDataset.csv', 

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

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

54 properties=prop) 

55 

56 Info: 

57 * wrapped_software: 

58 * name: scikit-learn PCA 

59 * version: >=0.24.2 

60 * license: BSD 3-Clause 

61 * ontology: 

62 * name: EDAM 

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

64 

65 """ 

66 

67 def __init__(self, input_dataset_path, output_results_path, 

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

69 properties = properties or {} 

70 

71 # Call parent class constructor 

72 super().__init__(properties) 

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

74 

75 # Input/Output files 

76 self.io_dict = { 

77 "in": {"input_dataset_path": input_dataset_path}, 

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

79 } 

80 

81 # Properties specific for BB 

82 self.features = properties.get('features', {}) 

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

84 self.n_components = properties.get('n_components', {}) 

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

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

87 self.properties = properties 

88 

89 # Check the properties 

90 self.check_properties(properties) 

91 self.check_arguments() 

92 

93 def check_data_params(self, out_log, err_log): 

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

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

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

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

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

99 

100 @launchlogger 

101 def launch(self) -> int: 

102 """Execute the :class:`PrincipalComponentAnalysis <dimensionality_reduction.principal_component.PrincipalComponentAnalysis>` dimensionality_reduction.pincipal_component.PrincipalComponentAnalysis object.""" 

103 

104 # check input/output paths and parameters 

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

106 

107 # Setup Biobb 

108 if self.check_restart(): 

109 return 0 

110 self.stage_files() 

111 

112 # load dataset 

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

114 if 'columns' in self.features: 

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

116 skiprows = 1 

117 else: 

118 labels = None 

119 skiprows = None 

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

121 

122 # declare inputs, targets and weights 

123 # the inputs are all the features 

124 features = getIndependentVars(self.features, data, self.out_log, self.__class__.__name__) 

125 fu.log('Features: [%s]' % (getIndependentVarsList(self.features)), self.out_log, self.global_log) 

126 # target 

127 y_value = getTargetValue(self.target) 

128 fu.log('Target: %s' % (y_value), self.out_log, self.global_log) 

129 

130 if self.scale: 

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

132 scaler = StandardScaler() 

133 features = scaler.fit_transform(features) 

134 

135 # create a PCA object with self.n_components['value'] n_components 

136 if 'value' not in self.n_components: 

137 n_c = None 

138 else: 

139 n_c = self.n_components['value'] 

140 fu.log('Fitting dataset', self.out_log, self.global_log) 

141 model = PCA(n_components=n_c, random_state=self.random_state_method) 

142 # fit the data 

143 model.fit(features) 

144 

145 # calculate variance ratio 

146 v_ratio = model.explained_variance_ratio_ 

147 fu.log('Variance ratio for %d Principal Components: %s' % (v_ratio.shape[0], np.array2string(v_ratio, precision=3, separator=', ')), self.out_log, self.global_log) 

148 

149 # transform 

150 fu.log('Transforming dataset', self.out_log, self.global_log) 

151 pca = model.transform(features) 

152 pca = pd.DataFrame(data=pca, columns=generate_columns_labels('PC', v_ratio.shape[0])) 

153 

154 if 'columns' in self.features: 

155 d = data[[y_value]] 

156 target_plot = y_value 

157 else: 

158 d = data.loc[:, int(y_value)] 

159 target_plot = int(y_value) 

160 

161 # output results 

162 pca_table = pd.concat([pca, d], axis=1) 

163 fu.log('Calculating PCA for dataset\n\n%d COMPONENT PCA TABLE\n\n%s\n' % (v_ratio.shape[0], pca_table), self.out_log, self.global_log) 

164 

165 # save results 

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

167 pca_table.to_csv(self.io_dict["out"]["output_results_path"], index=False, header=True) 

168 

169 # create output plot 

170 if (self.io_dict["out"]["output_plot_path"]): 

171 if v_ratio.shape[0] > 3: 

172 fu.log('%d PC\'s found. Displaying only 1st, 2nd and 3rd PC' % v_ratio.shape[0], self.out_log, self.global_log) 

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

174 targets = np.unique(d) 

175 if v_ratio.shape[0] == 2: 

176 PCA2CPlot(pca_table, targets, target_plot) 

177 

178 if v_ratio.shape[0] >= 3: 

179 PCA3CPlot(pca_table, targets, target_plot) 

180 

181 plt.savefig(self.io_dict["out"]["output_plot_path"], dpi=150) 

182 

183 # Copy files to host 

184 self.copy_to_host() 

185 

186 self.tmp_files.extend([ 

187 self.stage_io_dict.get("unique_dir") 

188 ]) 

189 self.remove_tmp_files() 

190 

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

192 

193 return 0 

194 

195 

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

197 """Execute the :class:`PrincipalComponentAnalysis <dimensionality_reduction.principal_component.PrincipalComponentAnalysis>` class and 

198 execute the :meth:`launch() <dimensionality_reduction.principal_component.PrincipalComponentAnalysis.launch>` method.""" 

199 

200 return PrincipalComponentAnalysis(input_dataset_path=input_dataset_path, 

201 output_results_path=output_results_path, 

202 output_plot_path=output_plot_path, 

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

204 

205 

206def main(): 

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

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

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

210 

211 # Specific args of each building block 

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

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

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

215 parser.add_argument('--output_plot_path', required=False, help='Path to the Principal Component plot, only if number of components is 2 or 3. Accepted formats: png.') 

216 

217 args = parser.parse_args() 

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

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

220 

221 # Specific call of each building block 

222 principal_component(input_dataset_path=args.input_dataset_path, 

223 output_results_path=args.output_results_path, 

224 output_plot_path=args.output_plot_path, 

225 properties=properties) 

226 

227 

228if __name__ == '__main__': 

229 main()