Coverage for biobb_ml/neural_networks/neural_network_decode.py: 84%

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

4import argparse 

5import h5py 

6# import json 

7import numpy as np 

8import pandas as pd 

9from biobb_common.generic.biobb_object import BiobbObject 

10from tensorflow.python.keras.saving import hdf5_format 

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.neural_networks.common import check_input_path, check_output_path 

15 

16 

17class DecodingNeuralNetwork(BiobbObject): 

18 """ 

19 | biobb_ml DecodingNeuralNetwork 

20 | Wrapper of the TensorFlow Keras LSTM method for decoding. 

21 | Decodes and predicts given a dataset and a model file compiled by an Autoencoder Neural Network. Visit the `LSTM documentation page <https://www.tensorflow.org/api_docs/python/tf/keras/layers/LSTM>`_ in the TensorFlow Keras official website for further information. 

22 

23 Args: 

24 input_decode_path (str): Path to the input decode dataset. File type: input. `Sample file <https://github.com/bioexcel/biobb_ml/raw/master/biobb_ml/test/data/neural_networks/dataset_decoder.csv>`_. Accepted formats: csv (edam:format_3752). 

25 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/neural_networks/input_model_decoder.h5>`_. Accepted formats: h5 (edam:format_3590). 

26 output_decode_path (str): Path to the output decode file. File type: output. `Sample file <https://github.com/bioexcel/biobb_ml/raw/master/biobb_ml/test/reference/neural_networks/ref_output_decode_decoder.csv>`_. Accepted formats: csv (edam:format_3752). 

27 output_predict_path (str) (Optional): Path to the output predict file. File type: output. `Sample file <https://github.com/bioexcel/biobb_ml/raw/master/biobb_ml/test/reference/neural_networks/ref_output_predict_decoder.csv>`_. Accepted formats: csv (edam:format_3752). 

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

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

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

31 

32 Examples: 

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

34 

35 from biobb_ml.neural_networks.neural_network_decode import neural_network_decode 

36 prop = { } 

37 neural_network_decode(input_decode_path='/path/to/myDecodeDataset.csv', 

38 input_model_path='/path/to/newModel.h5', 

39 output_decode_path='/path/to/newDecodeDataset.csv', 

40 output_predict_path='/path/to/newPredictDataset.csv', 

41 properties=prop) 

42 

43 Info: 

44 * wrapped_software: 

45 * name: TensorFlow Keras LSTM 

46 * version: >2.1.0 

47 * license: MIT 

48 * ontology: 

49 * name: EDAM 

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

51 

52 """ 

53 

54 def __init__(self, input_decode_path, input_model_path, output_decode_path, 

55 output_predict_path=None, properties=None, **kwargs) -> None: 

56 properties = properties or {} 

57 

58 # Call parent class constructor 

59 super().__init__(properties) 

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

61 

62 # Input/Output files 

63 self.io_dict = { 

64 "in": {"input_decode_path": input_decode_path, "input_model_path": input_model_path}, 

65 "out": {"output_decode_path": output_decode_path, "output_predict_path": output_predict_path} 

66 } 

67 

68 # Properties specific for BB 

69 self.properties = properties 

70 

71 # Check the properties 

72 self.check_properties(properties) 

73 self.check_arguments() 

74 

75 def check_data_params(self, out_log, err_log): 

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

77 self.io_dict["in"]["input_decode_path"] = check_input_path(self.io_dict["in"]["input_decode_path"], "input_decode_path", False, out_log, self.__class__.__name__) 

78 self.io_dict["in"]["input_model_path"] = check_input_path(self.io_dict["in"]["input_model_path"], "input_model_path", False, out_log, self.__class__.__name__) 

79 self.io_dict["out"]["output_decode_path"] = check_output_path(self.io_dict["out"]["output_decode_path"], "output_decode_path", False, out_log, self.__class__.__name__) 

80 if self.io_dict["out"]["output_predict_path"]: 

81 self.io_dict["out"]["output_predict_path"] = check_output_path(self.io_dict["out"]["output_predict_path"], "output_predict_path", False, out_log, self.__class__.__name__) 

82 

83 @launchlogger 

84 def launch(self) -> int: 

85 """Execute the :class:`DecodingNeuralNetwork <neural_networks.neural_network_decode.DecodingNeuralNetwork>` neural_networks.neural_network_decode.DecodingNeuralNetwork object.""" 

86 

87 # check input/output paths and parameters 

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

89 

90 # Setup Biobb 

91 if self.check_restart(): 

92 return 0 

93 self.stage_files() 

94 

95 # load decode dataset 

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

97 data_dec = pd.read_csv(self.io_dict["in"]["input_decode_path"]) 

98 seq_in = np.array(data_dec) 

99 

100 # reshape input into [samples, timesteps, features] 

101 n_in = len(seq_in) 

102 seq_in = seq_in.reshape((1, n_in, 1)) 

103 

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

105 with h5py.File(self.io_dict["in"]["input_model_path"], mode='r') as f: 

106 # variables = f.attrs['variables'] 

107 new_model = hdf5_format.load_model_from_hdf5(f) 

108 

109 # get dictionary with variables 

110 # vars_obj = json.loads(variables) 

111 

112 stringlist = [] 

113 new_model.summary(print_fn=lambda x: stringlist.append(x)) 

114 model_summary = "\n".join(stringlist) 

115 fu.log('Model summary:\n\n%s\n' % model_summary, self.out_log, self.global_log) 

116 

117 # decoding / predicting 

118 fu.log('Decoding / Predicting model', self.out_log, self.global_log) 

119 yhat = new_model.predict(seq_in, verbose=1) 

120 

121 # decoding 

122 decoding_table = pd.DataFrame() 

123 decoding_table['reconstructed'] = np.squeeze(np.asarray(yhat[0][0])) 

124 

125 pd.set_option('display.float_format', lambda x: '%.5f' % x) 

126 decoding_table = decoding_table.reset_index(drop=True) 

127 fu.log('RECONSTRUCTION TABLE\n\n%s\n' % decoding_table, self.out_log, self.global_log) 

128 

129 fu.log('Saving reconstruction to %s' % self.io_dict["out"]["output_decode_path"], self.out_log, self.global_log) 

130 decoding_table.to_csv(self.io_dict["out"]["output_decode_path"], index=False, header=True, float_format='%.5f') 

131 

132 if len(yhat) == 2: 

133 # decoding 

134 prediction_table = pd.DataFrame() 

135 prediction_table['predicted'] = np.squeeze(np.asarray(yhat[1][0])) 

136 

137 pd.set_option('display.float_format', lambda x: '%.5f' % x) 

138 prediction_table = prediction_table.reset_index(drop=True) 

139 fu.log('PREDICTION TABLE\n\n%s\n' % prediction_table, self.out_log, self.global_log) 

140 

141 fu.log('Saving prediction to %s' % self.io_dict["out"]["output_predict_path"], self.out_log, self.global_log) 

142 prediction_table.to_csv(self.io_dict["out"]["output_predict_path"], index=False, header=True, float_format='%.5f') 

143 

144 # Copy files to host 

145 self.copy_to_host() 

146 

147 self.tmp_files.extend([ 

148 self.stage_io_dict.get("unique_dir") 

149 ]) 

150 self.remove_tmp_files() 

151 

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

153 

154 return 0 

155 

156 

157def neural_network_decode(input_decode_path: str, input_model_path: str, output_decode_path: str, output_predict_path: str = None, properties: dict = None, **kwargs) -> int: 

158 """Execute the :class:`DecodingNeuralNetwork <neural_networks.neural_network_decode.DecodingNeuralNetwork>` class and 

159 execute the :meth:`launch() <neural_networks.neural_network_decode.DecodingNeuralNetwork.launch>` method.""" 

160 

161 return DecodingNeuralNetwork(input_decode_path=input_decode_path, 

162 input_model_path=input_model_path, 

163 output_decode_path=output_decode_path, 

164 output_predict_path=output_predict_path, 

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

166 

167 

168def main(): 

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

170 parser = argparse.ArgumentParser(description="Wrapper of the TensorFlow Keras LSTM method for decoding.", formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999)) 

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

172 

173 # Specific args of each building block 

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

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

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

177 required_args.add_argument('--output_decode_path', required=True, help='Path to the output decode file. Accepted formats: csv.') 

178 parser.add_argument('--output_predict_path', required=False, help='Path to the output predict file. Accepted formats: csv.') 

179 

180 args = parser.parse_args() 

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

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

183 

184 # Specific call of each building block 

185 neural_network_decode(input_decode_path=args.input_decode_path, 

186 input_model_path=args.input_model_path, 

187 output_decode_path=args.output_decode_path, 

188 output_predict_path=args.output_predict_path, 

189 properties=properties) 

190 

191 

192if __name__ == '__main__': 

193 main()