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

68 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-10-03 14:57 +0000

1#!/usr/bin/env python3 

2 

3"""Module containing the ScaleColumns class and the command line interface.""" 

4import argparse 

5import pandas as pd 

6from biobb_common.generic.biobb_object import BiobbObject 

7from sklearn.preprocessing import MinMaxScaler 

8from biobb_common.configuration import settings 

9from biobb_common.tools import file_utils as fu 

10from biobb_common.tools.file_utils import launchlogger 

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

12 

13 

14class ScaleColumns(BiobbObject): 

15 """ 

16 | biobb_ml ScaleColumns 

17 | Scales columns from a given dataset. 

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

22 properties (dic): 

23 * **targets** (*dict*) - ({}) Independent variables or columns from your dataset you want to scale. 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 * **sandbox_path** (*str*) - ("./") [WF property] Parent path to the sandbox directory. 

27 

28 Examples: 

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

30 

31 from biobb_ml.utils.scale_columns import scale_columns 

32 prop = { 

33 'targets': { 

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

35 } 

36 } 

37 scale_columns(input_dataset_path='/path/to/myDataset.csv', 

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

39 properties=prop) 

40 

41 Info: 

42 * wrapped_software: 

43 * name: In house 

44 * license: Apache-2.0 

45 * ontology: 

46 * name: EDAM 

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

48 

49 """ 

50 

51 def __init__(self, input_dataset_path, output_dataset_path, 

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

53 properties = properties or {} 

54 

55 # Call parent class constructor 

56 super().__init__(properties) 

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

58 

59 # Input/Output files 

60 self.io_dict = { 

61 "in": {"input_dataset_path": input_dataset_path}, 

62 "out": {"output_dataset_path": output_dataset_path} 

63 } 

64 

65 # Properties specific for BB 

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

67 self.properties = properties 

68 

69 # Check the properties 

70 self.check_properties(properties) 

71 self.check_arguments() 

72 

73 def check_data_params(self, out_log, err_log): 

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

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

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

77 

78 @launchlogger 

79 def launch(self) -> int: 

80 """Execute the :class:`ScaleColumns <utils.scale_columns.ScaleColumns>` utils.scale_columns.ScaleColumns object.""" 

81 

82 # check input/output paths and parameters 

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

84 

85 # Setup Biobb 

86 if self.check_restart(): 

87 return 0 

88 self.stage_files() 

89 

90 # load dataset 

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

92 if 'columns' in self.targets: 

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

94 skiprows = 1 

95 header = 0 

96 else: 

97 labels = None 

98 skiprows = None 

99 header = None 

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

101 

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

103 

104 fu.log('Scaling [%s] columns from dataset' % getIndependentVarsList(self.targets), self.out_log, self.global_log) 

105 if not self.targets: 

106 df_scaled = data 

107 else: 

108 df_scaled = (data[targets]) 

109 

110 scaler = MinMaxScaler() 

111 

112 df_scaled = pd.DataFrame(scaler.fit_transform(df_scaled)) 

113 

114 data[targets] = df_scaled 

115 

116 hdr = False 

117 if header == 0: 

118 hdr = True 

119 fu.log('Saving dataset to %s' % self.io_dict["out"]["output_dataset_path"], self.out_log, self.global_log) 

120 data.to_csv(self.io_dict["out"]["output_dataset_path"], index=False, header=hdr) 

121 

122 # Copy files to host 

123 self.copy_to_host() 

124 

125 self.tmp_files.extend([ 

126 self.stage_io_dict.get("unique_dir") 

127 ]) 

128 self.remove_tmp_files() 

129 

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

131 

132 return 0 

133 

134 

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

136 """Execute the :class:`ScaleColumns <utils.scale_columns.ScaleColumns>` class and 

137 execute the :meth:`launch() <utils.scale_columns.ScaleColumns.launch>` method.""" 

138 

139 return ScaleColumns(input_dataset_path=input_dataset_path, 

140 output_dataset_path=output_dataset_path, 

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

142 

143 

144def main(): 

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

146 parser = argparse.ArgumentParser(description="Scales columns from a given dataset", formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999)) 

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

148 

149 # Specific args of each building block 

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

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

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

153 

154 args = parser.parse_args() 

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

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

157 

158 # Specific call of each building block 

159 scale_columns(input_dataset_path=args.input_dataset_path, 

160 output_dataset_path=args.output_dataset_path, 

161 properties=properties) 

162 

163 

164if __name__ == '__main__': 

165 main()