Debian Codegraph @

pycoQC/pycoQC_report.py

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3
4 #~~~~~~~~~~~~~~IMPORTS~~~~~~~~~~~~~~#
5 # Standard library imports
6 import json
7 import datetime
8 import os
9
10 # Third party imports
11 import plotly.offline as py
12 import jinja2
13
14 # Local imports
15 from pycoQC.common import *
16 from pycoQC.pycoQC_parse import pycoQC_parse
17 from pycoQC.pycoQC_plot import pycoQC_plot
18 from pycoQC import __version__ as package_version
19 from pycoQC import __name__ as package_name
20
21 #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~MAIN CLASS~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
22 class pycoQC_report ():
23
24 #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~INIT METHOD~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
25 def __init__ (self,
26 parser:pycoQC_parse,
27 plotter:pycoQC_plot,
28 verbose:bool=False,
29 quiet:bool=False):
30 """
31 * parser
32 A pycoQC_parse object
33 * plotter
34 A pycoQC_plot object
35 * verbose
36 Increase verbosity
37 * quiet
38 Reduce verbosity
39 """
40 # Set logging level
41 self.logger = get_logger (name=__name__, verbose=verbose, quiet=quiet)
42
43 # Check that parser is a valid instance of pycoQC_parse
44 if not isinstance(parser, pycoQC_parse):
45 raise pycoQCError ("{} is not a valid pycoQC_parse object".format(parser))
46 self.parser = parser
47
48 # Check that plotter is a valid instance of pycoQC_plot
49 if not isinstance(plotter, pycoQC_plot):
50 raise pycoQCError ("{} is not a valid pycoQC_plot object".format(plotter))
51 self.plotter = plotter
52
53 def __repr__(self):
54 return "[{}]\n".format(self.__class__.__name__)
55
56 #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~PUBLIC METHODS~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
57 def html_report( self,
58 outfile:str,
59 config_file:str="",
60 template_file:str="",
61 report_title:str="PycoQC report",
62 skip_coverage_plot:bool=False):
63 """"""
64 self.logger.info("Generating HTML report")
65
66 # Parse configuration file
67 self.logger.info("\tParsing html config file")
68 config_dict = self._get_config(config_file)
69 self.logger.debug(config_dict)
70
71 # Loop over configuration file and run the pycoQC functions defined
72 plots = list()
73 titles = list()
74 for method_name, method_args in config_dict.items ():
75 if skip_coverage_plot and method_name == "alignment_coverage":
76 self.logger.info("\tSkipping method {}".format(method_name))
77 continue
78 try:
79 self.logger.info("\tRunning method {}".format(method_name))
80 self.logger.debug ("\t{} ({})".format(method_name, method_args))
81
82 # Store plot title for HTML title and remove from data passed to plotly
83 plot_title = method_args["plot_title"]
84 method_args["plot_title"]=""
85
86 # Get method and generate plot
87 method = getattr(self.plotter, method_name)
88 fig = method(**method_args)
89 plot = py.plot(
90 fig,
91 output_type='div',
92 include_plotlyjs=False,
93 image_width='',
94 image_height='',
95 show_link=False,
96 auto_open=False)
97
98 plots.append(plot)
99 titles.append(plot_title)
100
101 except AttributeError as E:
102 self.logger.info("\t\t{} is not a valid plotting method".format(method_name))
103 self.logger.info("\t\t{}".format(E))
104
105 except pycoQCError as E:
106 self.logger.info("\t\t{}".format(E))
107
108 # Load HTML template for Jinja
109 self.logger.info("\tLoading HTML template")
110 template = self._get_jinja_template(template_file)
111
112 # Set a subtitle for the HTML report
113 report_subtitle="Generated on {} with {} {}".format( datetime.datetime.now().strftime("%d/%m/%y"), package_name, package_version)
114
115 # Define source files list
116 src_files = ""
117 for files_list, name in (
118 (self.parser.summary_files_list,"summary"),
119 (self.parser.barcode_files_list,"barcode"),
120 (self.parser.bam_file_list,"bam")):
121
122 if files_list:
123 src_files += "<h4>Source {} files</h4><ul>".format(name)
124 for f in files_list:
125 f = os.path.abspath(f)
126 src_files += "<li>{}</li>".format(f)
127 src_files += "</ul>"
128
129 # Render plots
130 self.logger.info("\tRendering plots in d3js")
131 rendering = template.render(
132 plots=plots,
133 titles=titles,
134 plotlyjs=py.get_plotlyjs(),
135 report_title=report_title,
136 report_subtitle=report_subtitle,
137 src_files=src_files)
138
139 # Write to HTML file
140 self.logger.info("\tWriting to HTML file")
141 mkbasedir(outfile, exist_ok=True)
142 with open(outfile, "w") as fp:
143 fp.write(rendering)
144
145 def json_report(self,
146 outfile:str):
147 """"""
148 self.logger.info("Generating JSON report")
149 self.logger.info("\tRunning summary_stats_dict method")
150 res_dict = self.plotter.summary_stats_dict ()
151
152 self.logger.info("\tWriting to JSON file")
153 mkbasedir(outfile, exist_ok=True)
154 with open (outfile, "w") as fp:
155 json.dump(res_dict, fp, indent=2)
156
157 #~~~~~~~~~~~~~~PRIVATE FUNCTION~~~~~~~~~~~~~~#
158
159 def _get_config(self, config_file=None):
160 """"""
161 # First, try to read provided configuration file if given
162 if config_file:
163 self.logger.debug ("\tTry to read provided config file")
164 try:
165 with open(config_file, 'r') as cf:
166 return json.load(cf)
167 except (FileNotFoundError, IOError, json.JSONDecodeError):
168 self.logger.debug ("\t\tConfiguration file not found, non-readable or invalid")
169
170 # Last use the default harcoded config_dict
171 self.logger.debug ("\tRead default configuration file")
•172 config_file = "/usr/lib/python3/dist-packages/pycoQC/templates/pycoQC_config.json"
173 with open(config_file, 'r') as cf:
174 return json.load(cf)
175
176 def _get_jinja_template(self, template_file=None):
177 """"""
178 # First, try to read provided configuration file if given
179 if template_file:
180 self.logger.debug("\tTry to load provided jinja template file")
181 try:
182 with open(template_file) as fp:
183 template = jinja2.Template(fp.read())
184 return template
185 except (FileNotFoundError, IOError, jinja2.exceptions.TemplateNotFound, jinja2.exceptions.TemplateSyntaxError):
186 self.logger.debug ("\t\tFile not found, non-readable or invalid")
187
188 # Last use the default harcoded config_dict
189 self.logger.debug ("\tRead default jinja template")
190 env = jinja2.Environment (
191 loader=jinja2.PackageLoader('pycoQC', 'templates'),
192 autoescape=jinja2.select_autoescape(["html"]))
193 template = env.get_template('spectre.html.j2')
194 return template