Coverage for biobb_ml/utils/pairwise_comparison.py: 79%
66 statements
« prev ^ index » next coverage.py v7.5.1, created at 2024-05-07 09:39 +0000
« prev ^ index » next coverage.py v7.5.1, created at 2024-05-07 09:39 +0000
1#!/usr/bin/env python3
3"""Module containing the PairwiseComparison 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, getIndependentVarsList, getIndependentVars
15class PairwiseComparison(BiobbObject):
16 """
17 | biobb_ml PairwiseComparison
18 | Generates a pairwise comparison from a given dataset.
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_pairwise_comparison.csv>`_. Accepted formats: csv (edam:format_3752).
22 output_plot_path (str): Path to the pairwise comparison plot. File type: output. `Sample file <https://github.com/bioexcel/biobb_ml/raw/master/biobb_ml/test/reference/utils/ref_output_plot_pairwise_comparison.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.
28 Examples:
29 This is a use example of how to use the building block from Python::
31 from biobb_ml.utils.pairwise_comparison import pairwise_comparison
32 prop = {
33 'features': {
34 'columns': [ 'column1', 'column2', 'column3' ]
35 }
36 }
37 pairwise_comparison(input_dataset_path='/path/to/myDataset.csv',
38 output_plot_path='/path/to/newPlot.png',
39 properties=prop)
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
49 """
51 def __init__(self, input_dataset_path, output_plot_path,
52 properties=None, **kwargs) -> None:
53 properties = properties or {}
55 # Call parent class constructor
56 super().__init__(properties)
57 self.locals_var_dict = locals().copy()
59 # Input/Output files
60 self.io_dict = {
61 "in": {"input_dataset_path": input_dataset_path},
62 "out": {"output_plot_path": output_plot_path}
63 }
65 # Properties specific for BB
66 self.features = properties.get('features', {})
67 self.properties = properties
69 # Check the properties
70 self.check_properties(properties)
71 self.check_arguments()
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_plot_path"] = check_output_path(self.io_dict["out"]["output_plot_path"], "output_plot_path", False, out_log, self.__class__.__name__)
78 @launchlogger
79 def launch(self) -> int:
80 """Execute the :class:`PairwiseComparison <utils.pairwise_comparison.PairwiseComparison>` utils.pairwise_comparison.PairwiseComparison object."""
82 # check input/output paths and parameters
83 self.check_data_params(self.out_log, self.err_log)
85 # Setup Biobb
86 if self.check_restart():
87 return 0
88 self.stage_files()
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.features:
93 labels = getHeader(self.io_dict["in"]["input_dataset_path"])
94 skiprows = 1
95 else:
96 labels = None
97 skiprows = None
98 data = pd.read_csv(self.io_dict["in"]["input_dataset_path"], header=None, sep="\\s+|;|:|,|\t", engine="python", skiprows=skiprows, names=labels)
100 fu.log('Parsing [%s] columns of the dataset' % getIndependentVarsList(self.features), self.out_log, self.global_log)
101 if not self.features:
102 cols = data[data.columns]
103 else:
104 cols = getIndependentVars(self.features, data, self.out_log, self.__class__.__name__)
105 pp = sns.pairplot(cols, height=1.8, aspect=1.8,
106 plot_kws=dict(edgecolor="k", linewidth=0.5),
107 diag_kind="kde", diag_kws=dict(shade=True))
108 fig = pp.fig
109 fig.subplots_adjust(top=0.93, wspace=0.3)
110 fig.suptitle('Attributes Pairwise Plots', fontsize=14)
111 plt.tight_layout(rect=[0, 0.03, 1, 0.95])
113 plt.savefig(self.io_dict["out"]["output_plot_path"], dpi=150)
114 fu.log('Saving Pairwise Plot to %s' % self.io_dict["out"]["output_plot_path"], self.out_log, self.global_log)
116 # Copy files to host
117 self.copy_to_host()
119 self.tmp_files.extend([
120 self.stage_io_dict.get("unique_dir")
121 ])
122 self.remove_tmp_files()
124 self.check_arguments(output_files_created=True, raise_exception=False)
126 return 0
129def pairwise_comparison(input_dataset_path: str, output_plot_path: str, properties: dict = None, **kwargs) -> int:
130 """Execute the :class:`PairwiseComparison <utils.pairwise_comparison.PairwiseComparison>` class and
131 execute the :meth:`launch() <utils.pairwise_comparison.PairwiseComparison.launch>` method."""
133 return PairwiseComparison(input_dataset_path=input_dataset_path,
134 output_plot_path=output_plot_path,
135 properties=properties, **kwargs).launch()
138def main():
139 """Command line execution of this building block. Please check the command line documentation."""
140 parser = argparse.ArgumentParser(description="Generates a pairwise comparison from a given dataset", formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999))
141 parser.add_argument('--config', required=False, help='Configuration file')
143 # Specific args of each building block
144 required_args = parser.add_argument_group('required arguments')
145 required_args.add_argument('--input_dataset_path', required=True, help='Path to the input dataset. Accepted formats: csv.')
146 required_args.add_argument('--output_plot_path', required=True, help='Path to the pairwise comparison plot. Accepted formats: png.')
148 args = parser.parse_args()
149 args.config = args.config or "{}"
150 properties = settings.ConfReader(config=args.config).get_prop_dic()
152 # Specific call of each building block
153 pairwise_comparison(input_dataset_path=args.input_dataset_path,
154 output_plot_path=args.output_plot_path,
155 properties=properties)
158if __name__ == '__main__':
159 main()