Coverage for biobb_ml/utils/correlation_matrix.py: 74%

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

4import argparse 

5import pandas as pd 

6import matplotlib.pyplot as plt 

7import seaborn as sns 

8from biobb_common.generic.biobb_object import BiobbObject 

9from biobb_common.configuration import settings 

10from biobb_common.tools import file_utils as fu 

11from biobb_common.tools.file_utils import launchlogger 

12from biobb_ml.utils.common import check_input_path, check_output_path, getHeader, getIndependentVars 

13 

14 

15class CorrelationMatrix(BiobbObject): 

16 """ 

17 | biobb_ml CorrelationMatrix 

18 | Generates a correlation matrix from a given dataset. 

19 

20 Args: 

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

22 output_plot_path (str): Path to the correlation matrix plot. File type: output. `Sample file <https://github.com/bioexcel/biobb_ml/raw/master/biobb_ml/test/reference/utils/ref_output_plot_correlation_matrix.png>`_. Accepted formats: png (edam:format_3603). 

23 properties (dic): 

24 * **features** (*dict*) - ({}) Independent variables or columns from your dataset you want to compare. 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. 

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

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

27 * **sandbox_path** (*str*) - ("./") [WF property] Parent path to the sandbox directory. 

28 

29 Examples: 

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

31 

32 from biobb_ml.utils.correlation_matrix import correlation_matrix 

33 prop = { 

34 'features': { 

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

36 } 

37 } 

38 correlation_matrix(input_dataset_path='/path/to/myDataset.csv', 

39 output_plot_path='/path/to/newPlot.png', 

40 properties=prop) 

41 

42 Info: 

43 * wrapped_software: 

44 * name: In house 

45 * license: Apache-2.0 

46 * ontology: 

47 * name: EDAM 

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

49 

50 """ 

51 

52 def __init__(self, input_dataset_path, output_plot_path, 

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

54 properties = properties or {} 

55 

56 # Call parent class constructor 

57 super().__init__(properties) 

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

59 

60 # Input/Output files 

61 self.io_dict = { 

62 "in": {"input_dataset_path": input_dataset_path}, 

63 "out": {"output_plot_path": output_plot_path} 

64 } 

65 

66 # Properties specific for BB 

67 self.features = properties.get('features', {}) 

68 self.properties = properties 

69 

70 # Check the properties 

71 self.check_properties(properties) 

72 self.check_arguments() 

73 

74 def check_data_params(self, out_log, err_log): 

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

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

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

78 

79 @launchlogger 

80 def launch(self) -> int: 

81 """Execute the :class:`CorrelationMatrix <utils.correlation_matrix.CorrelationMatrix>` utils.correlation_matrix.CorrelationMatrix object.""" 

82 

83 # check input/output paths and parameters 

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

85 

86 # Setup Biobb 

87 if self.check_restart(): 

88 return 0 

89 self.stage_files() 

90 

91 # load dataset 

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

93 if 'columns' in self.features: 

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

95 skiprows = 1 

96 else: 

97 labels = None 

98 skiprows = None 

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

100 

101 if self.features: 

102 data = getIndependentVars(self.features, data, self.out_log, self.__class__.__name__) 

103 

104 fu.log('Parsing dataset', self.out_log, self.global_log) 

105 if data.shape[1] < 10: 

106 s = None 

107 fs = 12 

108 elif data.shape[1] >= 10 and data.shape[1] < 20: 

109 s = (12, 12) 

110 fs = 9 

111 elif data.shape[1] >= 20: 

112 s = (16, 16) 

113 fs = 7 

114 

115 f, ax = plt.subplots(figsize=s) 

116 corr = data.corr() 

117 sns.heatmap(round(corr, 2), annot=True, ax=ax, cmap='Blues', fmt='.2f', square=True, annot_kws={"fontsize": fs}) 

118 f.subplots_adjust(top=0.93) 

119 f.suptitle('Attributes Correlation Matrix', fontsize=14) 

120 plt.tight_layout(rect=[0, 0.03, 1, 0.95]) 

121 

122 plt.savefig(self.io_dict["out"]["output_plot_path"], dpi=150) 

123 fu.log('Saving Correlation Matrix Plot to %s' % self.io_dict["out"]["output_plot_path"], self.out_log, self.global_log) 

124 

125 # Copy files to host 

126 self.copy_to_host() 

127 

128 self.tmp_files.extend([ 

129 self.stage_io_dict.get("unique_dir") 

130 ]) 

131 self.remove_tmp_files() 

132 

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

134 

135 return 0 

136 

137 

138def correlation_matrix(input_dataset_path: str, output_plot_path: str, properties: dict = None, **kwargs) -> int: 

139 """Execute the :class:`CorrelationMatrix <utils.correlation_matrix.CorrelationMatrix>` class and 

140 execute the :meth:`launch() <utils.correlation_matrix.CorrelationMatrix.launch>` method.""" 

141 

142 return CorrelationMatrix(input_dataset_path=input_dataset_path, 

143 output_plot_path=output_plot_path, 

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

145 

146 

147def main(): 

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

149 parser = argparse.ArgumentParser(description="Generates a correlation matrix from a given dataset", formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999)) 

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

151 

152 # Specific args of each building block 

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

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

155 required_args.add_argument('--output_plot_path', required=True, help='Path to the correlation matrix plot. Accepted formats: png.') 

156 

157 args = parser.parse_args() 

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

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

160 

161 # Specific call of each building block 

162 correlation_matrix(input_dataset_path=args.input_dataset_path, 

163 output_plot_path=args.output_plot_path, 

164 properties=properties) 

165 

166 

167if __name__ == '__main__': 

168 main()