Coverage for biobb_ml/clustering/clustering_predict.py: 74%

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

4import argparse 

5import pandas as pd 

6import joblib 

7from biobb_common.generic.biobb_object import BiobbObject 

8from sklearn.preprocessing import StandardScaler 

9from sklearn.cluster import KMeans 

10from biobb_common.configuration import settings 

11from biobb_common.tools import file_utils as fu 

12from biobb_common.tools.file_utils import launchlogger 

13from biobb_ml.clustering.common import check_input_path, check_output_path, getHeader, get_list_of_predictors, get_keys_of_predictors 

14 

15 

16class ClusteringPredict(BiobbObject): 

17 """ 

18 | biobb_ml ClusteringPredict 

19 | Makes predictions from an input dataset and a given clustering model. 

20 | Makes predictions from an input dataset (provided either as a file or as a dictionary property) and a given clustering model fitted with `KMeans <https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html>`_ method. 

21 

22 Args: 

23 input_model_path (str): Path to the input model. File type: input. `Sample file <https://github.com/bioexcel/biobb_ml/raw/master/biobb_ml/test/data/clustering/model_clustering_predict.pkl>`_. Accepted formats: pkl (edam:format_3653). 

24 input_dataset_path (str) (Optional): Path to the dataset to predict. File type: input. `Sample file <https://github.com/bioexcel/biobb_ml/raw/master/biobb_ml/test/data/clustering/input_clustering_predict.csv>`_. Accepted formats: csv (edam:format_3752). 

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

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

27 * **predictions** (*list*) - (None) List of dictionaries with all values you want to predict targets. It will be taken into account only in case **input_dataset_path** is not provided. Format: [{ 'var1': 1.0, 'var2': 2.0 }, { 'var1': 4.0, 'var2': 2.7 }] for datasets with headers and [[ 1.0, 2.0 ], [ 4.0, 2.7 ]] for datasets without headers. 

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

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

30 

31 Examples: 

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

33 

34 from biobb_ml.clustering.clustering_predict import clustering_predict 

35 prop = { 

36 'predictions': [ 

37 { 

38 'var1': 1.0, 

39 'var2': 2.0 

40 }, 

41 { 

42 'var1': 4.0, 

43 'var2': 2.7 

44 } 

45 ] 

46 } 

47 clustering_predict(input_model_path='/path/to/myModel.pkl', 

48 output_results_path='/path/to/newPredictedResults.csv', 

49 input_dataset_path='/path/to/myDataset.csv', 

50 properties=prop) 

51 

52 Info: 

53 * wrapped_software: 

54 * name: scikit-learn 

55 * version: >=0.24.2 

56 * license: BSD 3-Clause 

57 * ontology: 

58 * name: EDAM 

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

60 

61 """ 

62 

63 def __init__(self, input_model_path, output_results_path, 

64 input_dataset_path=None, properties=None, **kwargs) -> None: 

65 properties = properties or {} 

66 

67 # Call parent class constructor 

68 super().__init__(properties) 

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

70 

71 # Input/Output files 

72 self.io_dict = { 

73 "in": {"input_model_path": input_model_path, "input_dataset_path": input_dataset_path}, 

74 "out": {"output_results_path": output_results_path} 

75 } 

76 

77 # Properties specific for BB 

78 self.predictions = properties.get('predictions', []) 

79 self.properties = properties 

80 

81 # Check the properties 

82 self.check_properties(properties) 

83 self.check_arguments() 

84 

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_model_path"] = check_input_path(self.io_dict["in"]["input_model_path"], "input_model_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["in"]["input_dataset_path"]: 

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

91 

92 @launchlogger 

93 def launch(self) -> int: 

94 """Execute the :class:`ClusteringPredict <clustering.clustering_predict.ClusteringPredict>` clustering.clustering_predict.ClusteringPredict object.""" 

95 

96 # check input/output paths and parameters 

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

98 

99 # Setup Biobb 

100 if self.check_restart(): 

101 return 0 

102 self.stage_files() 

103 

104 fu.log('Getting model from %s' % self.io_dict["in"]["input_model_path"], self.out_log, self.global_log) 

105 

106 with open(self.io_dict["in"]["input_model_path"], "rb") as f: 

107 while True: 

108 try: 

109 m = joblib.load(f) 

110 if (isinstance(m, KMeans)): 

111 new_model = m 

112 if isinstance(m, StandardScaler): 

113 scaler = m 

114 if isinstance(m, dict): 

115 variables = m 

116 except EOFError: 

117 break 

118 

119 if self.io_dict["in"]["input_dataset_path"]: 

120 # load dataset from input_dataset_path file 

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

122 if 'columns' in variables['predictors']: 

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

124 skiprows = 1 

125 else: 

126 labels = None 

127 skiprows = None 

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

129 else: 

130 # load dataset from properties 

131 if 'columns' in variables['predictors']: 

132 # sorting self.properties in the correct order given by variables['predictors']['columns'] 

133 index_map = {v: i for i, v in enumerate(variables['predictors']['columns'])} 

134 predictions = [] 

135 for i, pred in enumerate(self.predictions): 

136 sorted_pred = sorted(pred.items(), key=lambda pair: index_map[pair[0]]) 

137 predictions.append(dict(sorted_pred)) 

138 new_data_table = pd.DataFrame(data=get_list_of_predictors(predictions), columns=get_keys_of_predictors(predictions)) 

139 else: 

140 predictions = self.predictions 

141 new_data_table = pd.DataFrame(data=predictions) 

142 

143 if variables['scale']: 

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

145 new_data = scaler.transform(new_data_table) 

146 else: 

147 new_data = new_data_table 

148 

149 p = new_model.predict(new_data) 

150 

151 new_data_table['cluster'] = p 

152 fu.log('Predicting results\n\nPREDICTION RESULTS\n\n%s\n' % new_data_table, self.out_log, self.global_log) 

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

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

155 

156 # Copy files to host 

157 self.copy_to_host() 

158 

159 self.tmp_files.extend([ 

160 self.stage_io_dict.get("unique_dir") 

161 ]) 

162 self.remove_tmp_files() 

163 

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

165 

166 return 0 

167 

168 

169def clustering_predict(input_model_path: str, output_results_path: str, input_dataset_path: str = None, properties: dict = None, **kwargs) -> int: 

170 """Execute the :class:`ClusteringPredict <clustering.clustering_predict.ClusteringPredict>` class and 

171 execute the :meth:`launch() <clustering.clustering_predict.ClusteringPredict.launch>` method.""" 

172 

173 return ClusteringPredict(input_model_path=input_model_path, 

174 output_results_path=output_results_path, 

175 input_dataset_path=input_dataset_path, 

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

177 

178 

179def main(): 

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

181 parser = argparse.ArgumentParser(description="Makes predictions from an input dataset and a given clustering model.", formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999)) 

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

183 

184 # Specific args of each building block 

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

186 required_args.add_argument('--input_model_path', required=True, help='Path to the input model. Accepted formats: pkl.') 

187 required_args.add_argument('--output_results_path', required=True, help='Path to the output results file. Accepted formats: csv.') 

188 parser.add_argument('--input_dataset_path', required=False, help='Path to the dataset to predict. Accepted formats: csv.') 

189 

190 args = parser.parse_args() 

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

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

193 

194 # Specific call of each building block 

195 clustering_predict(input_model_path=args.input_model_path, 

196 output_results_path=args.output_results_path, 

197 input_dataset_path=args.input_dataset_path, 

198 properties=properties) 

199 

200 

201if __name__ == '__main__': 

202 main()