Coverage for biobb_ml/utils/map_variables.py: 78%

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

4import argparse 

5import pandas as pd 

6from biobb_common.generic.biobb_object import BiobbObject 

7from biobb_common.configuration import settings 

8from biobb_common.tools import file_utils as fu 

9from biobb_common.tools.file_utils import launchlogger 

10from biobb_ml.utils.common import check_input_path, check_output_path, getHeader, getTargetsList, getIndependentVarsList 

11 

12 

13class MapVariables(BiobbObject): 

14 """ 

15 | biobb_ml MapVariables 

16 | Maps the values of a given dataset. 

17 | Maps the values of a given dataset according to input correspondence, substituting each value in a series with another value, which may be derived from a function, a dictionary, or another series. 

18 

19 Args: 

20 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/utils/dataset_map_variables.csv>`_. Accepted formats: csv (edam:format_3752). 

21 output_dataset_path (str): Path to the output dataset. File type: output. `Sample file <https://github.com/bioexcel/biobb_ml/raw/master/biobb_ml/test/reference/utils/ref_output_dataset_map_variables.csv>`_. Accepted formats: csv (edam:format_3752). 

22 properties (dic): 

23 * **targets** (*dict*) - ({}) Independent variables or columns from your dataset you want to drop. If None given, all the columns will be taken. 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. 

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

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

26 

27 Examples: 

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

29 

30 from biobb_ml.utils.map_variables import map_variables 

31 prop = { 

32 'targets': { 

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

34 } 

35 } 

36 map_variables(input_dataset_path='/path/to/myDataset.csv', 

37 output_dataset_path='/path/to/newDataset.csv', 

38 properties=prop) 

39 

40 Info: 

41 * wrapped_software: 

42 * name: In house 

43 * license: Apache-2.0 

44 * ontology: 

45 * name: EDAM 

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

47 

48 """ 

49 

50 def __init__(self, input_dataset_path, output_dataset_path, 

51 properties=None, **kwargs) -> None: 

52 properties = properties or {} 

53 

54 # Call parent class constructor 

55 super().__init__(properties) 

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

57 

58 # Input/Output files 

59 self.io_dict = { 

60 "in": {"input_dataset_path": input_dataset_path}, 

61 "out": {"output_dataset_path": output_dataset_path} 

62 } 

63 

64 # Properties specific for BB 

65 self.targets = properties.get('targets', {}) 

66 self.properties = properties 

67 

68 # Check the properties 

69 self.check_properties(properties) 

70 self.check_arguments() 

71 

72 def check_data_params(self, out_log, err_log): 

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

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

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

76 

77 @launchlogger 

78 def launch(self) -> int: 

79 """Execute the :class:`MapVariables <utils.map_variables.MapVariables>` utils.map_variables.MapVariables object.""" 

80 

81 # check input/output paths and parameters 

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

83 

84 # Setup Biobb 

85 if self.check_restart(): 

86 return 0 

87 self.stage_files() 

88 

89 # load dataset 

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

91 if 'columns' in self.targets: 

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

93 skiprows = 1 

94 else: 

95 labels = None 

96 skiprows = None 

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

98 

99 # map variables 

100 fu.log('Mapping [%s] columns of the dataset' % getIndependentVarsList(self.targets), self.out_log, self.global_log) 

101 # if None given, map all the columns 

102 cols = getTargetsList(self.targets, 'dummy', self.out_log, self.__class__.__name__) 

103 if not cols: 

104 cols = list(data) 

105 for c in cols: 

106 lst = data[c].unique().tolist() 

107 dct = {lst[i]: i for i in range(0, len(lst))} 

108 data[c] = data[c].map(dct) 

109 

110 # save to csv 

111 fu.log('Saving results to %s\n' % self.io_dict["out"]["output_dataset_path"], self.out_log, self.global_log) 

112 data.to_csv(self.io_dict["out"]["output_dataset_path"], index=False, header=True, float_format='%.3f') 

113 

114 # Copy files to host 

115 self.copy_to_host() 

116 

117 self.tmp_files.extend([ 

118 self.stage_io_dict.get("unique_dir") 

119 ]) 

120 self.remove_tmp_files() 

121 

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

123 

124 return 0 

125 

126 

127def map_variables(input_dataset_path: str, output_dataset_path: str, properties: dict = None, **kwargs) -> int: 

128 """Execute the :class:`MapVariables <utils.map_variables.MapVariables>` class and 

129 execute the :meth:`launch() <utils.map_variables.MapVariables.launch>` method.""" 

130 

131 return MapVariables(input_dataset_path=input_dataset_path, 

132 output_dataset_path=output_dataset_path, 

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

134 

135 

136def main(): 

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

138 parser = argparse.ArgumentParser(description="Maps the values of a given dataset.", formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999)) 

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

140 

141 # Specific args of each building block 

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

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

144 required_args.add_argument('--output_dataset_path', required=True, help='Path to the output dataset. Accepted formats: csv.') 

145 

146 args = parser.parse_args() 

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

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

149 

150 # Specific call of each building block 

151 map_variables(input_dataset_path=args.input_dataset_path, 

152 output_dataset_path=args.output_dataset_path, 

153 properties=properties) 

154 

155 

156if __name__ == '__main__': 

157 main()