Debian Codegraph @

pycoQC/pycoQC_report.py

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