Coverage for biobb_ml/neural_networks/neural_network_decode.py: 84%
81 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-10-03 14:57 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2024-10-03 14:57 +0000
1#!/usr/bin/env python3
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
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.
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 * **sandbox_path** (*str*) - ("./") [WF property] Parent path to the sandbox directory.
33 Examples:
34 This is a use example of how to use the building block from Python::
36 from biobb_ml.neural_networks.neural_network_decode import neural_network_decode
37 prop = { }
38 neural_network_decode(input_decode_path='/path/to/myDecodeDataset.csv',
39 input_model_path='/path/to/newModel.h5',
40 output_decode_path='/path/to/newDecodeDataset.csv',
41 output_predict_path='/path/to/newPredictDataset.csv',
42 properties=prop)
44 Info:
45 * wrapped_software:
46 * name: TensorFlow Keras LSTM
47 * version: >2.1.0
48 * license: MIT
49 * ontology:
50 * name: EDAM
51 * schema: http://edamontology.org/EDAM.owl
53 """
55 def __init__(self, input_decode_path, input_model_path, output_decode_path,
56 output_predict_path=None, properties=None, **kwargs) -> None:
57 properties = properties or {}
59 # Call parent class constructor
60 super().__init__(properties)
61 self.locals_var_dict = locals().copy()
63 # Input/Output files
64 self.io_dict = {
65 "in": {"input_decode_path": input_decode_path, "input_model_path": input_model_path},
66 "out": {"output_decode_path": output_decode_path, "output_predict_path": output_predict_path}
67 }
69 # Properties specific for BB
70 self.properties = properties
72 # Check the properties
73 self.check_properties(properties)
74 self.check_arguments()
76 def check_data_params(self, out_log, err_log):
77 """ Checks all the input/output paths and parameters """
78 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__)
79 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__)
80 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__)
81 if self.io_dict["out"]["output_predict_path"]:
82 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__)
84 @launchlogger
85 def launch(self) -> int:
86 """Execute the :class:`DecodingNeuralNetwork <neural_networks.neural_network_decode.DecodingNeuralNetwork>` neural_networks.neural_network_decode.DecodingNeuralNetwork object."""
88 # check input/output paths and parameters
89 self.check_data_params(self.out_log, self.err_log)
91 # Setup Biobb
92 if self.check_restart():
93 return 0
94 self.stage_files()
96 # load decode dataset
97 fu.log('Getting decode dataset from %s' % self.io_dict["in"]["input_decode_path"], self.out_log, self.global_log)
98 data_dec = pd.read_csv(self.io_dict["in"]["input_decode_path"])
99 seq_in = np.array(data_dec)
101 # reshape input into [samples, timesteps, features]
102 n_in = len(seq_in)
103 seq_in = seq_in.reshape((1, n_in, 1))
105 fu.log('Getting model from %s' % self.io_dict["in"]["input_model_path"], self.out_log, self.global_log)
106 with h5py.File(self.io_dict["in"]["input_model_path"], mode='r') as f:
107 # variables = f.attrs['variables']
108 new_model = hdf5_format.load_model_from_hdf5(f)
110 # get dictionary with variables
111 # vars_obj = json.loads(variables)
113 stringlist = []
114 new_model.summary(print_fn=lambda x: stringlist.append(x))
115 model_summary = "\n".join(stringlist)
116 fu.log('Model summary:\n\n%s\n' % model_summary, self.out_log, self.global_log)
118 # decoding / predicting
119 fu.log('Decoding / Predicting model', self.out_log, self.global_log)
120 yhat = new_model.predict(seq_in, verbose=1)
122 # decoding
123 decoding_table = pd.DataFrame()
124 decoding_table['reconstructed'] = np.squeeze(np.asarray(yhat[0][0]))
126 pd.set_option('display.float_format', lambda x: '%.5f' % x)
127 decoding_table = decoding_table.reset_index(drop=True)
128 fu.log('RECONSTRUCTION TABLE\n\n%s\n' % decoding_table, self.out_log, self.global_log)
130 fu.log('Saving reconstruction to %s' % self.io_dict["out"]["output_decode_path"], self.out_log, self.global_log)
131 decoding_table.to_csv(self.io_dict["out"]["output_decode_path"], index=False, header=True, float_format='%.5f')
133 if len(yhat) == 2:
134 # decoding
135 prediction_table = pd.DataFrame()
136 prediction_table['predicted'] = np.squeeze(np.asarray(yhat[1][0]))
138 pd.set_option('display.float_format', lambda x: '%.5f' % x)
139 prediction_table = prediction_table.reset_index(drop=True)
140 fu.log('PREDICTION TABLE\n\n%s\n' % prediction_table, self.out_log, self.global_log)
142 fu.log('Saving prediction to %s' % self.io_dict["out"]["output_predict_path"], self.out_log, self.global_log)
143 prediction_table.to_csv(self.io_dict["out"]["output_predict_path"], index=False, header=True, float_format='%.5f')
145 # Copy files to host
146 self.copy_to_host()
148 self.tmp_files.extend([
149 self.stage_io_dict.get("unique_dir")
150 ])
151 self.remove_tmp_files()
153 self.check_arguments(output_files_created=True, raise_exception=False)
155 return 0
158def 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:
159 """Execute the :class:`DecodingNeuralNetwork <neural_networks.neural_network_decode.DecodingNeuralNetwork>` class and
160 execute the :meth:`launch() <neural_networks.neural_network_decode.DecodingNeuralNetwork.launch>` method."""
162 return DecodingNeuralNetwork(input_decode_path=input_decode_path,
163 input_model_path=input_model_path,
164 output_decode_path=output_decode_path,
165 output_predict_path=output_predict_path,
166 properties=properties, **kwargs).launch()
169def main():
170 """Command line execution of this building block. Please check the command line documentation."""
171 parser = argparse.ArgumentParser(description="Wrapper of the TensorFlow Keras LSTM method for decoding.", formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999))
172 parser.add_argument('--config', required=False, help='Configuration file')
174 # Specific args of each building block
175 required_args = parser.add_argument_group('required arguments')
176 required_args.add_argument('--input_decode_path', required=True, help='Path to the input decode dataset. Accepted formats: csv.')
177 required_args.add_argument('--input_model_path', required=True, help='Path to the input model. Accepted formats: h5.')
178 required_args.add_argument('--output_decode_path', required=True, help='Path to the output decode file. Accepted formats: csv.')
179 parser.add_argument('--output_predict_path', required=False, help='Path to the output predict file. Accepted formats: csv.')
181 args = parser.parse_args()
182 args.config = args.config or "{}"
183 properties = settings.ConfReader(config=args.config).get_prop_dic()
185 # Specific call of each building block
186 neural_network_decode(input_decode_path=args.input_decode_path,
187 input_model_path=args.input_model_path,
188 output_decode_path=args.output_decode_path,
189 output_predict_path=args.output_predict_path,
190 properties=properties)
193if __name__ == '__main__':
194 main()