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

60 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 DummyVariables 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 DummyVariables(BiobbObject): 

14 """ 

15 | biobb_ml DummyVariables 

16 | Converts categorical variables into dummy/indicator variables (binaries). 

17 

18 Args: 

19 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_dummy_variables.csv>`_. Accepted formats: csv (edam:format_3752). 

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

21 properties (dic): 

22 * **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. 

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

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

25 

26 Examples: 

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

28 

29 from biobb_ml.utils.dummy_variables import dummy_variables 

30 prop = { 

31 'targets': { 

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

33 } 

34 } 

35 dummy_variables(input_dataset_path='/path/to/myDataset.csv', 

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

37 properties=prop) 

38 

39 Info: 

40 * wrapped_software: 

41 * name: In house 

42 * license: Apache-2.0 

43 * ontology: 

44 * name: EDAM 

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

46 

47 """ 

48 

49 def __init__(self, input_dataset_path, output_dataset_path, 

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

51 properties = properties or {} 

52 

53 # Call parent class constructor 

54 super().__init__(properties) 

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

56 

57 # Input/Output files 

58 self.io_dict = { 

59 "in": {"input_dataset_path": input_dataset_path}, 

60 "out": {"output_dataset_path": output_dataset_path} 

61 } 

62 

63 # Properties specific for BB 

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

65 self.properties = properties 

66 

67 # Check the properties 

68 self.check_properties(properties) 

69 self.check_arguments() 

70 

71 def check_data_params(self, out_log, err_log): 

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

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

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

75 

76 @launchlogger 

77 def launch(self) -> int: 

78 """Execute the :class:`DummyVariables <utils.dummy_variables.DummyVariables>` utils.dummy_variables.DummyVariables object.""" 

79 

80 # check input/output paths and parameters 

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

82 

83 # Setup Biobb 

84 if self.check_restart(): 

85 return 0 

86 self.stage_files() 

87 

88 # load dataset 

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

90 if 'columns' in self.targets: 

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

92 skiprows = 1 

93 else: 

94 labels = None 

95 skiprows = None 

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

97 

98 # map dummy variables 

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

100 cols = None 

101 if self.targets is not None: 

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

103 

104 data = pd.get_dummies(data, drop_first=True, columns=cols) 

105 

106 # save to csv 

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

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

109 

110 # Copy files to host 

111 self.copy_to_host() 

112 

113 self.tmp_files.extend([ 

114 self.stage_io_dict.get("unique_dir") 

115 ]) 

116 self.remove_tmp_files() 

117 

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

119 

120 return 0 

121 

122 

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

124 """Execute the :class:`DummyVariables <utils.dummy_variables.DummyVariables>` class and 

125 execute the :meth:`launch() <utils.dummy_variables.DummyVariables.launch>` method.""" 

126 

127 return DummyVariables(input_dataset_path=input_dataset_path, 

128 output_dataset_path=output_dataset_path, 

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

130 

131 

132def main(): 

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

134 parser = argparse.ArgumentParser(description="Maps dummy variables from a given dataset.", formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999)) 

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

136 

137 # Specific args of each building block 

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

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

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

141 

142 args = parser.parse_args() 

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

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

145 

146 # Specific call of each building block 

147 dummy_variables(input_dataset_path=args.input_dataset_path, 

148 output_dataset_path=args.output_dataset_path, 

149 properties=properties) 

150 

151 

152if __name__ == '__main__': 

153 main()