Coverage for biobb_ml/dimensionality_reduction/pls_regression.py: 84%

89 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-10-03 14:57 +0000

1#!/usr/bin/env python3 

2 

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

4import argparse 

5import warnings 

6import pandas as pd 

7from biobb_common.generic.biobb_object import BiobbObject 

8from sklearn.cross_decomposition import PLSRegression 

9from sklearn.model_selection import cross_val_predict 

10from sklearn.metrics import mean_squared_error, r2_score 

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, getTarget, getTargetValue, PLSRegPlot 

15 

16 

17class PLS_Regression(BiobbObject): 

18 """ 

19 | biobb_ml PLS_Regression 

20 | Wrapper of the scikit-learn PLSRegression method. 

21 | Gives results for a Partial Least Square (PLS) Regression. Visit the `PLSRegression documentation page <https://scikit-learn.org/stable/modules/generated/sklearn.cross_decomposition.PLSRegression.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_pls_regression.csv>`_. Accepted formats: csv (edam:format_3752). 

25 output_results_path (str): Table with R2 and MSE for calibration and cross-validation data. File type: output. `Sample file <https://github.com/bioexcel/biobb_ml/raw/master/biobb_ml/test/reference/dimensionality_reduction/ref_output_results_pls_regression.csv>`_. Accepted formats: csv (edam:format_3752). 

26 output_plot_path (str) (Optional): Path to the R2 cross-validation plot. File type: output. `Sample file <https://github.com/bioexcel/biobb_ml/raw/master/biobb_ml/test/reference/dimensionality_reduction/ref_output_plot_pls_regression.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** (*int*) - (5) [1~1000|1] Maximum number of components to use by default for PLS queries. 

31 * **cv** (*int*) - (10) [1~10000|1] Specify the number of folds in the cross-validation splitting strategy. Value must be betwwen 2 and number of samples in the dataset. 

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 * **sandbox_path** (*str*) - ("./") [WF property] Parent path to the sandbox directory. 

36 

37 Examples: 

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

39 

40 from biobb_ml.dimensionality_reduction.pls_regression import pls_regression 

41 prop = { 

42 'features': { 

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

44 }, 

45 'target': { 

46 'column': 'target' 

47 }, 

48 'n_components': 12, 

49 'cv': 10 

50 } 

51 pls_regression(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 PLSRegression 

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', 5) 

85 self.cv = properties.get('cv', 10) 

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 def warn(*args, **kwargs): 

101 pass 

102 

103 @launchlogger 

104 def launch(self) -> int: 

105 """Execute the :class:`PLS_Regression <dimensionality_reduction.pls_regression.PLS_Regression>` dimensionality_reduction.pls_regression.PLS_Regression object.""" 

106 

107 # trick for disable warnings in interations 

108 warnings.warn = self.warn 

109 

110 # check input/output paths and parameters 

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

112 

113 # Setup Biobb 

114 if self.check_restart(): 

115 return 0 

116 self.stage_files() 

117 

118 # load dataset 

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

120 if 'columns' in self.features: 

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

122 skiprows = 1 

123 else: 

124 labels = None 

125 skiprows = None 

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

127 

128 # declare inputs, targets and weights 

129 # the inputs are all the features 

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

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

132 # target 

133 y = getTarget(self.target, data, self.out_log, self.__class__.__name__) 

134 fu.log('Target: %s' % (getTargetValue(self.target)), self.out_log, self.global_log) 

135 

136 # get rid of baseline and linear variations calculating second derivative 

137 # fu.log('Performing second derivative on the data', self.out_log, self.global_log) 

138 # self.window_length = getWindowLength(17, features.shape[1]) 

139 # X = savgol_filter(features, window_length = self.window_length, polyorder = 2, deriv = 2) 

140 X = features 

141 

142 # define PLS object with optimal number of components 

143 model = PLSRegression(n_components=self.n_components, scale=self.scale) 

144 # fit to the entire dataset 

145 model.fit(X, y) 

146 y_c = model.predict(X) 

147 # cross-validation 

148 y_cv = cross_val_predict(model, X, y, cv=self.cv) 

149 # calculate scores for calibration and cross-validation 

150 score_c = r2_score(y, y_c) 

151 score_cv = r2_score(y, y_cv) 

152 # calculate mean squared error for calibration and cross validation 

153 mse_c = mean_squared_error(y, y_c) 

154 mse_cv = mean_squared_error(y, y_cv) 

155 # create scores table 

156 r2_table = pd.DataFrame() 

157 r2_table["feature"] = ['R2 calib', 'R2 CV', 'MSE calib', 'MSE CV'] 

158 r2_table['coefficient'] = [score_c, score_cv, mse_c, mse_cv] 

159 

160 fu.log('Generating scores table\n\nR2 & MSE TABLE\n\n%s\n' % r2_table, self.out_log, self.global_log) 

161 

162 # save results table 

163 fu.log('Saving R2 & MSE table to %s' % self.io_dict["out"]["output_results_path"], self.out_log, self.global_log) 

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

165 

166 # mse plot 

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

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

169 plot = PLSRegPlot(y, y_c, y_cv) 

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

171 

172 # Copy files to host 

173 self.copy_to_host() 

174 

175 self.tmp_files.extend([ 

176 self.stage_io_dict.get("unique_dir") 

177 ]) 

178 self.remove_tmp_files() 

179 

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

181 

182 return 0 

183 

184 

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

186 """Execute the :class:`PLS_Regression <dimensionality_reduction.pls_regression.PLS_Regression>` class and 

187 execute the :meth:`launch() <dimensionality_reduction.pls_regression.PLS_Regression.launch>` method.""" 

188 

189 return PLS_Regression(input_dataset_path=input_dataset_path, 

190 output_results_path=output_results_path, 

191 output_plot_path=output_plot_path, 

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

193 

194 

195def main(): 

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

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

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

199 

200 # Specific args of each building block 

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

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

203 required_args.add_argument('--output_results_path', required=True, help='Table with R2 and MSE for calibration and cross-validation data. Accepted formats: csv.') 

204 parser.add_argument('--output_plot_path', required=False, help='Path to the R2 cross-validation plot. Accepted formats: png.') 

205 

206 args = parser.parse_args() 

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

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

209 

210 # Specific call of each building block 

211 pls_regression(input_dataset_path=args.input_dataset_path, 

212 output_results_path=args.output_results_path, 

213 output_plot_path=args.output_plot_path, 

214 properties=properties) 

215 

216 

217if __name__ == '__main__': 

218 main()