| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
from collections import * |
| 7 |
import warnings |
| 8 |
import datetime |
| 9 |
|
| 10 |
|
| 11 |
import numpy as np |
| 12 |
import pandas as pd |
| 13 |
from scipy.ndimage import gaussian_filter, gaussian_filter1d |
| 14 |
import plotly.graph_objs as go |
| 15 |
from plotly.subplots import make_subplots |
| 16 |
|
| 17 |
|
| 18 |
from pycoQC.common import * |
| 19 |
from pycoQC.pycoQC_parse import pycoQC_parse |
| 20 |
from pycoQC import __name__ as package_name |
| 21 |
from pycoQC import __version__ as package_version |
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
SEED = 42 |
| 26 |
np.random.RandomState(seed=SEED) |
| 27 |
|
| 28 |
|
| 29 |
warnings.filterwarnings("ignore", category=FutureWarning) |
| 30 |
|
| 31 |
|
| 32 |
class pycoQC_plot (): |
| 33 |
|
| 34 |
def __init__ (self, |
| 35 |
parser:pycoQC_parse, |
| 36 |
min_pass_qual:int=7, |
| 37 |
min_pass_len:int=0, |
| 38 |
sample:int=100000, |
| 39 |
verbose:bool=False, |
| 40 |
quiet:bool=False): |
| 41 |
""" |
| 42 |
* parser |
| 43 |
A pycoQC_parse object |
| 44 |
* min_pass_qual |
| 45 |
Minimum quality to consider a read as 'pass' |
| 46 |
* min_pass_len |
| 47 |
Minimum read length to consider a read as 'pass' |
| 48 |
* sample |
| 49 |
If not None a n number of reads will be randomly selected instead of the entire dataset for plotting function (deterministic sampling) |
| 50 |
""" |
| 51 |
|
| 52 |
|
| 53 |
self.logger = get_logger (name=__name__, verbose=verbose, quiet=quiet) |
| 54 |
self.logger.warning ("Loading plotting interface") |
| 55 |
|
| 56 |
|
| 57 |
self.min_pass_qual = min_pass_qual |
| 58 |
self.sample = sample |
| 59 |
|
| 60 |
|
| 61 |
if not isinstance(parser, pycoQC_parse): |
| 62 |
raise pycoQCError ("{} is not a valid pycoQC_parse object".format(parser)) |
| 63 |
self.parser = parser |
| 64 |
|
| 65 |
|
| 66 |
self.all_df = parser.reads_df |
| 67 |
if self.has_alignment: |
| 68 |
self.ref_len_dict = parser.ref_len_dict |
| 69 |
self.alignments_df = parser.alignments_df |
| 70 |
self.logger.info ("\tFound {:,} total reads".format(len(self.all_df))) |
| 71 |
|
| 72 |
|
| 73 |
if sample and len(self.all_df)>sample: |
| 74 |
self.all_sample_df = self.all_df.sample(n=sample, random_state=SEED) |
| 75 |
self.all_scaling_factor = len(self.all_df)/sample |
| 76 |
else: |
| 77 |
self.all_sample_df = self.all_df |
| 78 |
self.all_scaling_factor = 1 |
| 79 |
|
| 80 |
self.pass_df = self.all_df.query ("mean_qscore>={} and read_len>={}".format(min_pass_qual, min_pass_len)) |
| 81 |
if sample and len(self.pass_df)>sample: |
| 82 |
self.pass_sample_df = self.pass_df.sample(n=sample, random_state=SEED) |
| 83 |
self.pass_scaling_factor = len(self.pass_df)/sample |
| 84 |
else: |
| 85 |
self.pass_sample_df = self.pass_df |
| 86 |
self.pass_scaling_factor = 1 |
| 87 |
self.logger.info ("\tFound {:,} pass reads (qual >= {} and length >= {})".format(len(self.pass_df), min_pass_qual, min_pass_len)) |
| 88 |
|
| 89 |
def __str__(self): |
| 90 |
m = "" |
| 91 |
m+= "\tBarcode: {}\n".format(self.has_barcodes) |
| 92 |
m+= "\tAlignment: {}\n".format(self.has_alignment) |
| 93 |
m+= "\tPromethion: {}\n".format(self.is_promethion) |
| 94 |
m+= "\tAll reads: {:,}\n".format(len(self.all_df)) |
| 95 |
m+= "\tAll bases: {:,}\n".format(int(self.all_df["read_len"].sum())) |
| 96 |
m+= "\tAll median read length: {:,}\n".format(np.median(self.all_df["read_len"])) |
| 97 |
m+= "\tPass reads: {:,}\n".format(len(self.pass_df)) |
| 98 |
m+= "\tPass bases: {:,}\n".format(int(self.pass_df["read_len"].sum())) |
| 99 |
m+= "\tPass median read length: {:,}\n".format(np.median(self.pass_df["read_len"])) |
| 100 |
return m |
| 101 |
|
| 102 |
def __repr__(self): |
| 103 |
return "[{}]\n".format(self.__class__.__name__) |
| 104 |
|
| 105 |
|
| 106 |
@property |
| 107 |
def has_barcodes (self): |
| 108 |
return "barcode" in self.all_df |
| 109 |
|
| 110 |
@property |
| 111 |
def has_alignment (self): |
| 112 |
return "ref_id" in self.all_df |
| 113 |
|
| 114 |
@property |
| 115 |
def has_identity_freq (self): |
| 116 |
return "identity_freq" in self.all_df |
| 117 |
|
| 118 |
@property |
| 119 |
def is_promethion (self): |
| 120 |
return self.all_df["channel"].max() > 512 |
| 121 |
|
| 122 |
@property |
| 123 |
def total_ref_len (self): |
| 124 |
if self.has_alignment: |
| 125 |
return np.sum(list(self.ref_len_dict.values())) |
| 126 |
|
| 127 |
def _run_duration(self, df): |
| 128 |
return float(np.ptp(df["start_time"])/3600) |
| 129 |
|
| 130 |
def _active_channels(self, df): |
| 131 |
return int(df["channel"].nunique()) |
| 132 |
|
| 133 |
def _runid_number(self, df): |
| 134 |
return int(df["run_id"].nunique()) |
| 135 |
|
| 136 |
def _barcodes_number(self, df): |
| 137 |
return int(df["barcode"].nunique()) if self.has_barcodes else 0 |
| 138 |
|
| 139 |
def _basecalled_reads(self, df): |
| 140 |
return len(df) |
| 141 |
|
| 142 |
def _basecalled_bases(self, df): |
| 143 |
return int(df["read_len"].sum()) |
| 144 |
|
| 145 |
def _basecall_N50(self, df): |
| 146 |
return self._compute_N50(df["read_len"]) |
| 147 |
|
| 148 |
def _basecall_median_read_len(self, df): |
| 149 |
return np.median(df["read_len"]) |
| 150 |
|
| 151 |
def _basecall_median_read_qscore(self, df): |
| 152 |
return np.median(df["mean_qscore"]) |
| 153 |
|
| 154 |
def _alignment_mean_coverage(self, df): |
| 155 |
return df["align_len"].dropna().sum()/self.total_ref_len if self.has_alignment else np.nan |
| 156 |
|
| 157 |
def _aligned_reads(self, df): |
| 158 |
return len(df["align_len"].dropna()) if self.has_alignment else np.nan |
| 159 |
|
| 160 |
def _aligned_bases(self, df): |
| 161 |
return int(df["align_len"].dropna().sum()) if self.has_alignment else np.nan |
| 162 |
|
| 163 |
def _alignment_N50(self, df): |
| 164 |
return self._compute_N50(df["align_len"]) if self.has_alignment else np.nan |
| 165 |
|
| 166 |
def _alignment_median_read_len(self, df): |
| 167 |
return np.median(df["align_len"].dropna()) if self.has_alignment else np.nan |
| 168 |
|
| 169 |
def _alignment_median_identity(self, df): |
| 170 |
return np.median(df["identity_freq"].dropna()) if self.has_identity_freq else np.nan |
| 171 |
|
| 172 |
def _alignment_insertion_rate(self, df): |
| 173 |
return df["insertion"].dropna().sum()/self._aligned_bases(df) if self.has_identity_freq else np.nan |
| 174 |
|
| 175 |
def _alignment_deletion_rate(self, df): |
| 176 |
return df["deletion"].dropna().sum()/self._aligned_bases(df) if self.has_identity_freq else np.nan |
| 177 |
|
| 178 |
def _alignment_mismatch_rate(self, df): |
| 179 |
return df["mismatch"].dropna().sum()/self._aligned_bases(df) if self.has_identity_freq else np.nan |
| 180 |
|
| 181 |
|
| 182 |
|
| 183 |
def summary_stats_dict (self): |
| 184 |
""" |
| 185 |
Return a dictionnary containing exhaustive information about the run. |
| 186 |
""" |
| 187 |
self.logger.info ("\tCompute overall summary statistics") |
| 188 |
d = OrderedDict () |
| 189 |
|
| 190 |
d["pycoqc"] = OrderedDict () |
| 191 |
d["pycoqc"]["version"] = package_version |
| 192 |
d["pycoqc"]["date"] = datetime.datetime.now().strftime("%d/%m/%y") |
| 193 |
|
| 194 |
for df, lab in ((self.all_df, "All Reads"), (self.pass_df, "Pass Reads")): |
| 195 |
d[lab] = self._compute_stats(df) |
| 196 |
return d |
| 197 |
|
| 198 |
def _compute_stats (self, df): |
| 199 |
d = OrderedDict () |
| 200 |
|
| 201 |
d["run"] = OrderedDict() |
| 202 |
d["run"]["run_duration"] = self._run_duration(df) |
| 203 |
d["run"]["active_channels"] = self._active_channels(df) |
| 204 |
d["run"]["runid_number"] = self._runid_number(df) |
| 205 |
d["run"]["barcodes_number"] = self._barcodes_number(df) |
| 206 |
d["basecall"] = OrderedDict() |
| 207 |
d["basecall"]["reads_number"] = self._basecalled_reads(df) |
| 208 |
d["basecall"]["bases_number"] = self._basecalled_bases(df) |
| 209 |
d["basecall"]["N50"] = self._basecall_N50(df) |
| 210 |
d["basecall"]["len_percentiles"] = self._compute_percentiles (df["read_len"]) |
| 211 |
d["basecall"]["qual_score_percentiles"] = self._compute_percentiles (df["mean_qscore"]) |
| 212 |
|
| 213 |
x,y = self._compute_hist(data=df["read_len"],x_scale="log",smooth_sigma=2,nbins=100) |
| 214 |
d["basecall"]["len_hist"] = OrderedDict () |
| 215 |
d["basecall"]["len_hist"]["x"] = x |
| 216 |
d["basecall"]["len_hist"]["y"] = y |
| 217 |
x,y = self._compute_hist(data=df["mean_qscore"],x_scale="linear",smooth_sigma=2,nbins=100) |
| 218 |
d["basecall"]["qual_score_hist"] = OrderedDict () |
| 219 |
d["basecall"]["qual_score_hist"]["x"] = x |
| 220 |
d["basecall"]["qual_score_hist"]["y"] = y |
| 221 |
|
| 222 |
if self.has_alignment: |
| 223 |
d["alignment"] = OrderedDict() |
| 224 |
d["alignment"]["reads_number"] = self._aligned_reads(df) |
| 225 |
d["alignment"]["bases_number"] = self._aligned_bases(df) |
| 226 |
d["alignment"]["mean_coverage"] = self._alignment_mean_coverage(df) |
| 227 |
d["alignment"]["N50"] = self._alignment_N50(df) |
| 228 |
d["alignment"]["len_percentiles"] = self._compute_percentiles (df["align_len"]) |
| 229 |
x,y = self._compute_hist(data=df["align_len"],x_scale="log",smooth_sigma=2,nbins=100) |
| 230 |
d["alignment"]["len_hist"] = OrderedDict () |
| 231 |
d["alignment"]["len_hist"]["x"] = x |
| 232 |
d["alignment"]["len_hist"]["y"] = y |
| 233 |
|
| 234 |
if self.has_identity_freq: |
| 235 |
d["alignment"]["identity_freq_percentiles"] = self._compute_percentiles (df["identity_freq"]) |
| 236 |
d["alignment"]["insertion_rate"] = self._alignment_insertion_rate(df) |
| 237 |
d["alignment"]["deletion_rate"] = self._alignment_deletion_rate(df) |
| 238 |
d["alignment"]["mismatch_rate"] = self._alignment_mismatch_rate(df) |
| 239 |
x,y = self._compute_hist(data=df["identity_freq"],x_scale="linear",smooth_sigma=2,nbins=100) |
| 240 |
d["alignment"]["identity_freq_hist"] = OrderedDict () |
| 241 |
d["alignment"]["identity_freq_hist"]["x"] = x |
| 242 |
d["alignment"]["identity_freq_hist"]["y"] = y |
| 243 |
|
| 244 |
return d |
| 245 |
|
| 246 |
|
| 247 |
|
| 248 |
def run_summary (self, |
| 249 |
width:int = None, |
| 250 |
height:int = 300, |
| 251 |
plot_title:str="General run summary"): |
| 252 |
""" |
| 253 |
Plot an interactive overall summary table |
| 254 |
* groupby |
| 255 |
Value of field to group the data in the table |
| 256 |
* width |
| 257 |
With of the plotting area in pixel |
| 258 |
* height |
| 259 |
height of the plotting area in pixel |
| 260 |
* plot_title |
| 261 |
Title to display on top of the plot |
| 262 |
""" |
| 263 |
|
| 264 |
data = [] |
| 265 |
for status, df in (("All Reads", self.all_df), ("Pass Reads", self.pass_df)): |
| 266 |
data.append([ |
| 267 |
status, |
| 268 |
self._run_duration(df), |
| 269 |
self._active_channels(df), |
| 270 |
self._runid_number(df), |
| 271 |
self._barcodes_number(df)]) |
| 272 |
|
| 273 |
fig = self.__summary_plot ( |
| 274 |
width = width, |
| 275 |
height = height, |
| 276 |
plot_title = plot_title, |
| 277 |
header=["Status", "Run Duration (h)", "Active Channels", "Number of Runids", "Number of Barcodes"], |
| 278 |
data_format=["", ".2f", "", "", ""], |
| 279 |
data=[*zip(*data)]) |
| 280 |
|
| 281 |
return fig |
| 282 |
|
| 283 |
def basecall_summary (self, |
| 284 |
width:int = None, |
| 285 |
height:int = 300, |
| 286 |
plot_title:str="Basecall summary"): |
| 287 |
""" |
| 288 |
Plot an interactive basecall summary table |
| 289 |
* groupby |
| 290 |
Value of field to group the data in the table |
| 291 |
* width |
| 292 |
With of the plotting area in pixel |
| 293 |
* height |
| 294 |
height of the plotting area in pixel |
| 295 |
* plot_title |
| 296 |
Title to display on top of the plot |
| 297 |
""" |
| 298 |
|
| 299 |
data = [] |
| 300 |
for status, df in (("All Reads", self.all_df), ("Pass Reads", self.pass_df)): |
| 301 |
data.append([ |
| 302 |
status, |
| 303 |
self._basecalled_reads(df), |
| 304 |
self._basecalled_bases(df), |
| 305 |
self._basecall_N50(df), |
| 306 |
self._basecall_median_read_len(df), |
| 307 |
self._basecall_median_read_qscore(df)]) |
| 308 |
|
| 309 |
fig = self.__summary_plot ( |
| 310 |
width = width, |
| 311 |
height = height, |
| 312 |
plot_title = plot_title, |
| 313 |
header=["Status", "Reads", "Bases", "N50", "Median Read Length", "Median PHRED score"], |
| 314 |
data_format=["", ".6e", ".6e", ".3r", ".3r", ".3f"], |
| 315 |
data=[*zip(*data)]) |
| 316 |
|
| 317 |
return fig |
| 318 |
|
| 319 |
def alignment_summary (self, |
| 320 |
width:int = None, |
| 321 |
height:int = 300, |
| 322 |
plot_title:str="Alignment summary"): |
| 323 |
""" |
| 324 |
Plot an interactive alignment summary table |
| 325 |
* groupby |
| 326 |
Value of field to group the data in the table |
| 327 |
* width |
| 328 |
With of the plotting area in pixel |
| 329 |
* height |
| 330 |
height of the plotting area in pixel |
| 331 |
* plot_title |
| 332 |
Title to display on top of the plot |
| 333 |
""" |
| 334 |
|
| 335 |
if not self.has_alignment: |
| 336 |
raise pycoQCError ("No Alignment information available") |
| 337 |
|
| 338 |
data = [] |
| 339 |
for status, df in (("All Reads", self.all_df), ("Pass Reads", self.pass_df)): |
| 340 |
data.append([ |
| 341 |
status, |
| 342 |
self._aligned_reads(df), |
| 343 |
self._aligned_bases(df), |
| 344 |
self._alignment_mean_coverage(df), |
| 345 |
self._alignment_N50(df), |
| 346 |
self._alignment_median_read_len(df), |
| 347 |
self._alignment_median_identity(df)]) |
| 348 |
|
| 349 |
fig = self.__summary_plot ( |
| 350 |
width = width, |
| 351 |
height = height, |
| 352 |
plot_title = plot_title, |
| 353 |
header=["Status", "Reads", "Bases", "Mean Coverage", "N50", "Median Read Length", "Median Identity Freq"], |
| 354 |
data_format=["", ".6e", ".6e", ".3r", ".3r", ".3r", ".3f"], |
| 355 |
data=[*zip(*data)]) |
| 356 |
|
| 357 |
return fig |
| 358 |
|
| 359 |
def __summary_plot (self, width, height, plot_title, header, data_format, data): |
| 360 |
"""Private function generating summary table plots""" |
| 361 |
self.logger.info ("\t\tComputing plot") |
| 362 |
|
| 363 |
|
| 364 |
data = [go.Table( |
| 365 |
header = { |
| 366 |
"values":header, |
| 367 |
"align":"center", "fill":{"color":"grey"}, |
| 368 |
"font":{"size":14, "color":"white"}, |
| 369 |
"height":40}, |
| 370 |
cells = { |
| 371 |
"values":data, |
| 372 |
"format": data_format, |
| 373 |
"align":"center", |
| 374 |
"fill":{"color":"whitesmoke"}, |
| 375 |
"font":{"size":12}, "height":30})] |
| 376 |
|
| 377 |
|
| 378 |
layout = go.Layout ( |
| 379 |
width = width, |
| 380 |
height = height, |
| 381 |
title = {"text":plot_title, "xref":"paper" ,"x":0.5, "xanchor":"center"}) |
| 382 |
|
| 383 |
return go.Figure (data=data, layout=layout) |
| 384 |
|
| 385 |
|
| 386 |
def read_len_1D (self, |
| 387 |
color:str="lightsteelblue", |
| 388 |
nbins:int=200, |
| 389 |
smooth_sigma:float=2, |
| 390 |
width:int=None, |
| 391 |
height:int=500, |
| 392 |
plot_title:str="Basecalled reads length"): |
| 393 |
""" |
| 394 |
Plot a distribution of read length (log scale) |
| 395 |
* color |
| 396 |
Color of the area (hex, rgb, rgba, hsl, hsv or any CSS named colors https://www.w3.org/TR/css-color-3/#svg-color |
| 397 |
* nbins |
| 398 |
Number of bins to devide the x axis in |
| 399 |
* smooth_sigma |
| 400 |
standard deviation for Gaussian kernel |
| 401 |
* width |
| 402 |
With of the plotting area in pixel |
| 403 |
* height |
| 404 |
height of the plotting area in pixel |
| 405 |
* plot_title |
| 406 |
Title to display on top of the plot |
| 407 |
""" |
| 408 |
fig = self.__1D_density_plot ( |
| 409 |
field_name = "read_len", |
| 410 |
plot_title = plot_title, |
| 411 |
x_lab = "Basecalled length", |
| 412 |
color = color, |
| 413 |
x_scale = "log", |
| 414 |
nbins=nbins, |
| 415 |
smooth_sigma=smooth_sigma, |
| 416 |
width=width, |
| 417 |
height=height) |
| 418 |
return fig |
| 419 |
|
| 420 |
def read_qual_1D (self, |
| 421 |
color:str="salmon", |
| 422 |
nbins:int=200, |
| 423 |
smooth_sigma:float=2, |
| 424 |
width:int=None, |
| 425 |
height:int=500, |
| 426 |
plot_title:str="Basecalled reads PHRED quality"): |
| 427 |
""" |
| 428 |
Plot a distribution of quality scores |
| 429 |
* color |
| 430 |
Color of the area (hex, rgb, rgba, hsl, hsv or any CSS named colors https://www.w3.org/TR/css-color-3/#svg-color |
| 431 |
* nbins |
| 432 |
Number of bins to devide the x axis in |
| 433 |
* smooth_sigma |
| 434 |
standard deviation for Gaussian kernel |
| 435 |
* width |
| 436 |
With of the plotting area in pixel |
| 437 |
* height |
| 438 |
height of the plotting area in pixel |
| 439 |
* plot_title |
| 440 |
Title to display on top of the plot |
| 441 |
""" |
| 442 |
fig = self.__1D_density_plot ( |
| 443 |
field_name = "mean_qscore", |
| 444 |
plot_title = plot_title, |
| 445 |
x_lab = "Read quality scores", |
| 446 |
color = color, |
| 447 |
x_scale = "linear", |
| 448 |
nbins=nbins, |
| 449 |
smooth_sigma=smooth_sigma, |
| 450 |
width=width, |
| 451 |
height=height) |
| 452 |
return fig |
| 453 |
|
| 454 |
def align_len_1D (self, |
| 455 |
color:str="mediumseagreen", |
| 456 |
nbins:int=200, |
| 457 |
smooth_sigma:float=2, |
| 458 |
width:int=None, |
| 459 |
height:int=500, |
| 460 |
plot_title:str="Aligned reads length"): |
| 461 |
""" |
| 462 |
Plot a distribution of read length (log scale) |
| 463 |
* color |
| 464 |
Color of the area (hex, rgb, rgba, hsl, hsv or any CSS named colors https://www.w3.org/TR/css-color-3/#svg-color |
| 465 |
* nbins |
| 466 |
Number of bins to devide the x axis in |
| 467 |
* smooth_sigma |
| 468 |
standard deviation for Gaussian kernel |
| 469 |
* width |
| 470 |
With of the plotting area in pixel |
| 471 |
* height |
| 472 |
height of the plotting area in pixel |
| 473 |
* plot_title |
| 474 |
Title to display on top of the plot |
| 475 |
""" |
| 476 |
|
| 477 |
if not self.has_alignment: |
| 478 |
raise pycoQCError ("No Alignment information available") |
| 479 |
|
| 480 |
fig = self.__1D_density_plot ( |
| 481 |
field_name = "align_len", |
| 482 |
plot_title = plot_title, |
| 483 |
x_lab = "Alignment length", |
| 484 |
color = color, |
| 485 |
x_scale = "log", |
| 486 |
nbins=nbins, |
| 487 |
smooth_sigma=smooth_sigma, |
| 488 |
width=width, |
| 489 |
height=height) |
| 490 |
return fig |
| 491 |
|
| 492 |
def identity_freq_1D (self, |
| 493 |
color:str="sandybrown", |
| 494 |
nbins:int=200, |
| 495 |
smooth_sigma:float=2, |
| 496 |
width:int=None, |
| 497 |
height:int=500, |
| 498 |
plot_title:str="Aligned reads identity"): |
| 499 |
""" |
| 500 |
Plot a distribution of alignments identity |
| 501 |
* color |
| 502 |
Color of the area (hex, rgb, rgba, hsl, hsv or any CSS named colors https://www.w3.org/TR/css-color-3/#svg-color |
| 503 |
* nbins |
| 504 |
Number of bins to devide the x axis in |
| 505 |
* smooth_sigma |
| 506 |
standard deviation for Gaussian kernel |
| 507 |
* width |
| 508 |
With of the plotting area in pixel |
| 509 |
* height |
| 510 |
height of the plotting area in pixel |
| 511 |
* plot_title |
| 512 |
Title to display on top of the plot |
| 513 |
""" |
| 514 |
|
| 515 |
if not self.has_identity_freq: |
| 516 |
raise pycoQCError ("No identity frequency information available") |
| 517 |
|
| 518 |
fig = self.__1D_density_plot ( |
| 519 |
field_name = "identity_freq", |
| 520 |
plot_title = plot_title, |
| 521 |
x_lab = "Identity frequency", |
| 522 |
color = color, |
| 523 |
x_scale = "linear", |
| 524 |
nbins=nbins, |
| 525 |
smooth_sigma=smooth_sigma, |
| 526 |
width=width, |
| 527 |
height=height) |
| 528 |
return fig |
| 529 |
|
| 530 |
def __1D_density_plot (self, field_name, plot_title, x_lab, color, x_scale, nbins, smooth_sigma, width, height): |
| 531 |
"""Private function generating density plots for all 1D distribution functions""" |
| 532 |
self.logger.info ("\t\tComputing plot") |
| 533 |
|
| 534 |
|
| 535 |
lab1, dd1, ld1 = self.__1D_density_data ("all", field_name, x_scale, nbins, smooth_sigma) |
| 536 |
lab2, dd2, ld2 = self.__1D_density_data ("pass" ,field_name, x_scale, nbins, smooth_sigma) |
| 537 |
|
| 538 |
|
| 539 |
common = { |
| 540 |
"mode": "lines+text", |
| 541 |
"hoverinfo": "skip", |
| 542 |
"textposition": 'top center', |
| 543 |
"line": {'color':'gray','width':1,'dash': 'dot'}} |
| 544 |
data = [ |
| 545 |
go.Scatter (x=dd1["x"][0], y=dd1["y"][0], name=dd1["name"][0], fill='tozeroy', fillcolor=color, mode='none', showlegend=True), |
| 546 |
go.Scatter (x=dd1["x"][1], y=dd1["y"][1], name=dd1["name"][1], text=dd1["text"][1], **common), |
| 547 |
go.Scatter (x=dd1["x"][2], y=dd1["y"][2], name=dd1["name"][2], text=dd1["text"][2], **common), |
| 548 |
go.Scatter (x=dd1["x"][3], y=dd1["y"][3], name=dd1["name"][3], text=dd1["text"][3], **common), |
| 549 |
go.Scatter (x=dd1["x"][4], y=dd1["y"][4], name=dd1["name"][4], text=dd1["text"][4], **common), |
| 550 |
go.Scatter (x=dd1["x"][5], y=dd1["y"][5], name=dd1["name"][5], text=dd1["text"][5], **common)] |
| 551 |
|
| 552 |
|
| 553 |
updatemenus = [ |
| 554 |
dict (type="buttons", active=0, x=-0.2, y=0, xanchor='left', yanchor='bottom', buttons = [ |
| 555 |
dict (label=lab1, method='update', args=[dd1, ld1]), |
| 556 |
dict (label=lab2, method='update', args=[dd2, ld2])])] |
| 557 |
|
| 558 |
|
| 559 |
layout = go.Layout ( |
| 560 |
hovermode = "closest", |
| 561 |
plot_bgcolor="whitesmoke", |
| 562 |
legend = {"x":-0.2, "y":1,"xanchor":'left',"yanchor":'top'}, |
| 563 |
updatemenus = updatemenus, |
| 564 |
width = width, |
| 565 |
height = height, |
| 566 |
title = {"text":plot_title, "xref":"paper" ,"x":0.5, "xanchor":"center"}, |
| 567 |
xaxis = {"title":x_lab, "type":x_scale, "zeroline":False, "showline":True}, |
| 568 |
yaxis = {"title":"Read density", "zeroline":False, "showline":True, "fixedrange":True, "range":ld1["yaxis.range"]}) |
| 569 |
|
| 570 |
return go.Figure (data=data, layout=layout) |
| 571 |
|
| 572 |
def __1D_density_data (self, df_level, field_name, x_scale, nbins, smooth_sigma): |
| 573 |
"""Private function preparing data for reads_1D""" |
| 574 |
|
| 575 |
self.logger.debug ("\t\tPreparing data for {} reads and {}".format(df_level, field_name)) |
| 576 |
|
| 577 |
|
| 578 |
df = self.pass_sample_df if df_level=="pass" else self.all_sample_df |
| 579 |
data = df[field_name].dropna().values |
| 580 |
|
| 581 |
|
| 582 |
min = np.nanmin(data) |
| 583 |
max = np.nanmax(data) |
| 584 |
if x_scale == "log": |
| 585 |
count_y, bins = np.histogram (a=data, bins=np.logspace (np.log10(min), np.log10(max)+0.1, nbins)) |
| 586 |
elif x_scale == "linear": |
| 587 |
count_y, bins = np.histogram (a=data, bins= np.linspace (min, max, nbins)) |
| 588 |
|
| 589 |
|
| 590 |
count_x = bins[1:] |
| 591 |
|
| 592 |
|
| 593 |
if smooth_sigma: |
| 594 |
count_y = gaussian_filter1d (count_y, sigma=smooth_sigma) |
| 595 |
|
| 596 |
|
| 597 |
stat = np.percentile (data, [10,25,50,75,90]) |
| 598 |
y_max = count_y.max() |
| 599 |
|
| 600 |
data_dict = dict ( |
| 601 |
x = [count_x, [stat[0],stat[0]], [stat[1],stat[1]], [stat[2],stat[2]], [stat[3],stat[3]], [stat[4],stat[4]]], |
| 602 |
y = [count_y, [0,y_max], [0,y_max], [0,y_max], [0,y_max], [0,y_max]], |
| 603 |
name = ["Density", "10%", "25%", "Median", "75%", "90%"], |
| 604 |
text = ["", |
| 605 |
["", "10%<br>{:,.2f}".format(stat[0])], |
| 606 |
["", "25%<br>{:,.2f}".format(stat[1])], |
| 607 |
["", "Median<br>{:,.2f}".format(stat[2])], |
| 608 |
["", "75%<br>{:,.2f}".format(stat[3])], |
| 609 |
["", "90%<br>{:,.2f}".format(stat[4])]]) |
| 610 |
|
| 611 |
|
| 612 |
layout_dict = {"yaxis.range": [0, y_max+y_max/6]} |
| 613 |
|
| 614 |
label = "{} Reads".format(df_level.capitalize()) |
| 615 |
return (label, data_dict, layout_dict) |
| 616 |
|
| 617 |
|
| 618 |
def read_len_read_qual_2D (self, |
| 619 |
colorscale = [ |
| 620 |
[0.0,'rgba(255,255,255,0)'], |
| 621 |
[0.1,'rgba(255,150,0,0)'], |
| 622 |
[0.25,'rgb(255,100,0)'], |
| 623 |
[0.5,'rgb(200,0,0)'], |
| 624 |
[0.75,'rgb(120,0,0)'], |
| 625 |
[1.0,'rgb(70,0,0)']], |
| 626 |
x_nbins:int=200, |
| 627 |
y_nbins:int=100, |
| 628 |
smooth_sigma:float=2, |
| 629 |
width:int=None, |
| 630 |
height:int=600, |
| 631 |
plot_title:str="Basecalled reads length vs reads PHRED quality"): |
| 632 |
""" |
| 633 |
Plot a 2D distribution of quality scores vs length of the reads |
| 634 |
* colorscale |
| 635 |
a valid plotly color scale https://plot.ly/python/colorscales/ (Not recommanded to change) |
| 636 |
* x_nbins |
| 637 |
Number of bins to divide the read length values in (x axis) |
| 638 |
* y_nbins |
| 639 |
Number of bins to divide the read quality values in (y axis) |
| 640 |
* smooth_sigma |
| 641 |
standard deviation for 2D Gaussian kernel |
| 642 |
* width |
| 643 |
With of the plotting area in pixel |
| 644 |
* height |
| 645 |
height of the plotting area in pixel |
| 646 |
* plot_title |
| 647 |
Title to display on top of the plot |
| 648 |
""" |
| 649 |
fig = self.__2D_density_plot ( |
| 650 |
x_field_name = "read_len", |
| 651 |
y_field_name = "mean_qscore", |
| 652 |
x_lab = "Basecalled length", |
| 653 |
y_lab = "PHRED quality scores", |
| 654 |
x_scale = "log", |
| 655 |
y_scale = "linear", |
| 656 |
x_nbins = x_nbins, |
| 657 |
y_nbins = y_nbins, |
| 658 |
colorscale = colorscale, |
| 659 |
smooth_sigma=smooth_sigma, |
| 660 |
width=width, |
| 661 |
height=height, |
| 662 |
plot_title = plot_title) |
| 663 |
return fig |
| 664 |
|
| 665 |
def read_len_align_len_2D (self, |
| 666 |
colorscale = [ |
| 667 |
[0.0,'rgba(255,255,255,0)'], |
| 668 |
[0.1,'rgba(255,150,0,0)'], |
| 669 |
[0.25,'rgb(255,100,0)'], |
| 670 |
[0.5,'rgb(200,0,0)'], |
| 671 |
[0.75,'rgb(120,0,0)'], |
| 672 |
[1.0,'rgb(70,0,0)']], |
| 673 |
x_nbins:int=200, |
| 674 |
y_nbins:int=100, |
| 675 |
smooth_sigma:float=1, |
| 676 |
width:int=None, |
| 677 |
height:int=600, |
| 678 |
plot_title:str="Basecalled reads length vs alignments length"): |
| 679 |
""" |
| 680 |
Plot a 2D distribution of length of the reads vs length of the alignments |
| 681 |
* colorscale |
| 682 |
a valid plotly color scale https://plot.ly/python/colorscales/ (Not recommanded to change) |
| 683 |
* x_nbins |
| 684 |
Number of bins to divide the read length values in (x axis) |
| 685 |
* y_nbins |
| 686 |
Number of bins to divide the read quality values in (y axis) |
| 687 |
* smooth_sigma |
| 688 |
standard deviation for 2D Gaussian kernel |
| 689 |
* width |
| 690 |
With of the plotting area in pixel |
| 691 |
* height |
| 692 |
height of the plotting area in pixel |
| 693 |
* plot_title |
| 694 |
Title to display on top of the plot |
| 695 |
""" |
| 696 |
|
| 697 |
if not self.has_alignment: |
| 698 |
raise pycoQCError ("No Alignment information available") |
| 699 |
|
| 700 |
fig = self.__2D_density_plot ( |
| 701 |
x_field_name = "read_len", |
| 702 |
y_field_name = "align_len", |
| 703 |
x_lab = "Basecalled length", |
| 704 |
y_lab = "Alignment length", |
| 705 |
x_scale = "log", |
| 706 |
y_scale = "log", |
| 707 |
x_nbins = x_nbins, |
| 708 |
y_nbins = y_nbins, |
| 709 |
colorscale = colorscale, |
| 710 |
smooth_sigma=smooth_sigma, |
| 711 |
width=width, |
| 712 |
height=height, |
| 713 |
plot_title = plot_title) |
| 714 |
return fig |
| 715 |
|
| 716 |
def align_len_identity_freq_2D (self, |
| 717 |
colorscale = [ |
| 718 |
[0.0,'rgba(255,255,255,0)'], |
| 719 |
[0.1,'rgba(255,150,0,0)'], |
| 720 |
[0.25,'rgb(255,100,0)'], |
| 721 |
[0.5,'rgb(200,0,0)'], |
| 722 |
[0.75,'rgb(120,0,0)'], [1.0,'rgb(70,0,0)']], |
| 723 |
x_nbins:int=200, |
| 724 |
y_nbins:int=100, |
| 725 |
smooth_sigma:float=2, |
| 726 |
width:int=None, |
| 727 |
height:int=600, |
| 728 |
plot_title:str="Aligned reads length vs alignments identity"): |
| 729 |
""" |
| 730 |
Plot a 2D distribution of alignments length vs alignments identity |
| 731 |
* colorscale |
| 732 |
a valid plotly color scale https://plot.ly/python/colorscales/ (Not recommanded to change) |
| 733 |
* x_nbins |
| 734 |
Number of bins to divide the read length values in (x axis) |
| 735 |
* y_nbins |
| 736 |
Number of bins to divide the read quality values in (y axis) |
| 737 |
* smooth_sigma |
| 738 |
standard deviation for 2D Gaussian kernel |
| 739 |
* width |
| 740 |
With of the plotting area in pixel |
| 741 |
* height |
| 742 |
height of the plotting area in pixel |
| 743 |
* plot_title |
| 744 |
Title to display on top of the plot |
| 745 |
""" |
| 746 |
|
| 747 |
if not self.has_identity_freq: |
| 748 |
raise pycoQCError ("No identity frequency information available") |
| 749 |
|
| 750 |
fig = self.__2D_density_plot ( |
| 751 |
x_field_name = "align_len", |
| 752 |
y_field_name = "identity_freq", |
| 753 |
x_lab = "Alignment length", |
| 754 |
y_lab = "Identity frequency", |
| 755 |
x_scale = "log", |
| 756 |
y_scale = "linear", |
| 757 |
x_nbins = x_nbins, |
| 758 |
y_nbins = y_nbins, |
| 759 |
colorscale = colorscale, |
| 760 |
smooth_sigma=smooth_sigma, |
| 761 |
width=width, |
| 762 |
height=height, |
| 763 |
plot_title = plot_title) |
| 764 |
return fig |
| 765 |
|
| 766 |
def read_qual_identity_freq_2D (self, |
| 767 |
colorscale = [ |
| 768 |
[0.0,'rgba(255,255,255,0)'], |
| 769 |
[0.1,'rgba(255,150,0,0)'], |
| 770 |
[0.25,'rgb(255,100,0)'], |
| 771 |
[0.5,'rgb(200,0,0)'], |
| 772 |
[0.75,'rgb(120,0,0)'], |
| 773 |
[1.0,'rgb(70,0,0)']], |
| 774 |
x_nbins:int=200, |
| 775 |
y_nbins:int=100, |
| 776 |
smooth_sigma:float=1, |
| 777 |
width:int=None, |
| 778 |
height:int=600, |
| 779 |
plot_title:str="Reads PHRED quality vs alignments identity"): |
| 780 |
""" |
| 781 |
Plot a 2D distribution of read quality vs alignments identity |
| 782 |
* colorscale |
| 783 |
a valid plotly color scale https://plot.ly/python/colorscales/ (Not recommanded to change) |
| 784 |
* x_nbins |
| 785 |
Number of bins to divide the read length values in (x axis) |
| 786 |
* y_nbins |
| 787 |
Number of bins to divide the read quality values in (y axis) |
| 788 |
* smooth_sigma |
| 789 |
standard deviation for 2D Gaussian kernel |
| 790 |
* width |
| 791 |
With of the plotting area in pixel |
| 792 |
* height |
| 793 |
height of the plotting area in pixel |
| 794 |
* plot_title |
| 795 |
Title to display on top of the plot |
| 796 |
""" |
| 797 |
|
| 798 |
if not self.has_identity_freq: |
| 799 |
raise pycoQCError ("No identity frequency information available") |
| 800 |
|
| 801 |
fig = self.__2D_density_plot ( |
| 802 |
x_field_name = "mean_qscore", |
| 803 |
y_field_name = "identity_freq", |
| 804 |
x_lab = "PHRED quality", |
| 805 |
y_lab = "Identity frequency", |
| 806 |
x_scale = "linear", |
| 807 |
y_scale = "linear", |
| 808 |
x_nbins = x_nbins, |
| 809 |
y_nbins = y_nbins, |
| 810 |
colorscale = colorscale, |
| 811 |
smooth_sigma=smooth_sigma, |
| 812 |
width=width, |
| 813 |
height=height, |
| 814 |
plot_title = plot_title) |
| 815 |
return fig |
| 816 |
|
| 817 |
def __2D_density_plot (self, |
| 818 |
x_field_name, y_field_name, x_lab, y_lab, x_scale, y_scale, x_nbins, y_nbins, |
| 819 |
colorscale, smooth_sigma, width, height, plot_title): |
| 820 |
"""Private function generating density plots for all 2D distribution functions""" |
| 821 |
self.logger.info ("\t\tComputing plot") |
| 822 |
|
| 823 |
|
| 824 |
lab1, dd1 = self.__2D_density_data ("all", x_field_name, y_field_name, x_nbins, y_nbins, x_scale, y_scale, smooth_sigma) |
| 825 |
lab2, dd2 = self.__2D_density_data ("pass", x_field_name, y_field_name, x_nbins, y_nbins, x_scale, y_scale, smooth_sigma) |
| 826 |
|
| 827 |
|
| 828 |
data = [ |
| 829 |
go.Contour (x=dd1["x"][0], y=dd1["y"][0], z=dd1["z"][0], contours=dd1["contours"][0], |
| 830 |
name="Density", hoverinfo="name+x+y", colorscale=colorscale, showlegend=True, connectgaps=True, line={"width":0}), |
| 831 |
go.Scatter (x=dd1["x"][1], y=dd1["y"][1], |
| 832 |
mode='markers', name='Median', hoverinfo="name+x+y", marker={"size":12,"color":'black', "symbol":"x"})] |
| 833 |
|
| 834 |
|
| 835 |
updatemenus = [ |
| 836 |
dict (type="buttons", active=0, x=-0.2, y=0, xanchor='left', yanchor='bottom', buttons = [ |
| 837 |
dict (label=lab1, method='restyle', args=[dd1]), |
| 838 |
dict (label=lab2, method='restyle', args=[dd2])])] |
| 839 |
|
| 840 |
|
| 841 |
layout = go.Layout ( |
| 842 |
hovermode = "closest", |
| 843 |
plot_bgcolor="whitesmoke", |
| 844 |
legend = {"x":-0.2, "y":1,"xanchor":'left',"yanchor":'top'}, |
| 845 |
updatemenus = updatemenus, |
| 846 |
width = width, |
| 847 |
height = height, |
| 848 |
title = {"text":plot_title, "xref":"paper" ,"x":0.5, "xanchor":"center"}, |
| 849 |
xaxis = {"title":x_lab, "showgrid":True, "zeroline":False, "showline":True, "type":x_scale}, |
| 850 |
yaxis = {"title":y_lab, "showgrid":True, "zeroline":False, "showline":True, "type":y_scale}) |
| 851 |
|
| 852 |
return go.Figure (data=data, layout=layout) |
| 853 |
|
| 854 |
def __2D_density_data (self, df_level, x_field_name, y_field_name, x_nbins, y_nbins, x_scale, y_scale, smooth_sigma): |
| 855 |
""" Private function preparing data for 2D_density_plot """ |
| 856 |
|
| 857 |
self.logger.debug ("\t\tPreparing data for {} reads".format(df_level)) |
| 858 |
|
| 859 |
|
| 860 |
df = self.pass_sample_df if df_level == "pass" else self.all_sample_df |
| 861 |
df = df[[x_field_name, y_field_name]].dropna() |
| 862 |
|
| 863 |
|
| 864 |
x_data = df[x_field_name].values |
| 865 |
x_min, x_med, x_max = np.percentile (x_data, (0, 50, 100)) |
| 866 |
if x_scale == "log": |
| 867 |
x_bins = np.logspace (start=np.log10((x_min)), stop=np.log10(x_max)+0.1, num=x_nbins, base=10) |
| 868 |
else: |
| 869 |
x_bins = np.linspace (start=x_min, stop=x_max, num=x_nbins) |
| 870 |
|
| 871 |
|
| 872 |
y_data = df[y_field_name].values |
| 873 |
y_min, y_med, y_max = np.percentile (y_data, (0, 50, 100)) |
| 874 |
if y_scale == "log": |
| 875 |
y_bins = np.logspace (start=np.log10((y_min)), stop=np.log10(y_max)+0.1, num=y_nbins, base=10) |
| 876 |
else: |
| 877 |
y_bins = np.linspace (start=y_min, stop=y_max, num=y_nbins) |
| 878 |
|
| 879 |
|
| 880 |
z, y, x = np.histogram2d (x=y_data, y=x_data, bins=[y_bins, x_bins]) |
| 881 |
if smooth_sigma: |
| 882 |
z = gaussian_filter(z, sigma=smooth_sigma) |
| 883 |
z_min, z_max = np.percentile (z, (0, 100)) |
| 884 |
|
| 885 |
|
| 886 |
data_dict = dict ( |
| 887 |
x = [x, [x_med]], y = [y, [y_med]], z = [z, None], |
| 888 |
contours = [dict(start=z_min, end=z_max, size=(z_max-z_min)/15),None]) |
| 889 |
|
| 890 |
label = "{} Reads".format(df_level.capitalize()) |
| 891 |
return (label, data_dict) |
| 892 |
|
| 893 |
|
| 894 |
def output_over_time (self, |
| 895 |
cumulative_color:str="rgb(204,226,255)", |
| 896 |
interval_color:str="rgb(102,168,255)", |
| 897 |
time_bins:int=500, |
| 898 |
width:int=None, |
| 899 |
height:int=500, |
| 900 |
plot_title:str="Output over experiment time"): |
| 901 |
""" |
| 902 |
Plot a yield over time |
| 903 |
* cumulative_color |
| 904 |
Color of cumulative yield area (hex, rgb, rgba, hsl, hsv or any CSS named colors https://www.w3.org/TR/css-color-3/#svg-color |
| 905 |
* interval_color |
| 906 |
Color of interval yield line (hex, rgb, rgba, hsl, hsv or any CSS named colors https://www.w3.org/TR/css-color-3/#svg-color |
| 907 |
* time_bins |
| 908 |
Number of bins to divide the time values in (x axis) |
| 909 |
* width |
| 910 |
With of the plotting area in pixel |
| 911 |
* height |
| 912 |
height of the plotting area in pixel |
| 913 |
* plot_title |
| 914 |
Title to display on top of the plot |
| 915 |
""" |
| 916 |
self.logger.info ("\t\tComputing plot") |
| 917 |
|
| 918 |
|
| 919 |
lab1, dd1, ld1 = self.__output_over_time_data (df_level="all", count_level="reads", time_bins=time_bins) |
| 920 |
lab2, dd2, ld2 = self.__output_over_time_data (df_level="pass", count_level="reads", time_bins=time_bins) |
| 921 |
lab3, dd3, ld3 = self.__output_over_time_data (df_level="all", count_level="bases", time_bins=time_bins) |
| 922 |
lab4, dd4, ld4 = self.__output_over_time_data (df_level="pass", count_level="bases", time_bins=time_bins) |
| 923 |
|
| 924 |
|
| 925 |
common = { |
| 926 |
"mode": "lines+text", |
| 927 |
"hoverinfo": "skip", |
| 928 |
"textposition": 'top center', |
| 929 |
"line": {'color':'gray','width':1,'dash': 'dot'}} |
| 930 |
data = [ |
| 931 |
go.Scatter (x=dd1["x"][0], y=dd1["y"][0], name=dd1["name"][0], fill='tozeroy', fillcolor=cumulative_color, mode='none'), |
| 932 |
go.Scatter (x=dd1["x"][1], y=dd1["y"][1], name=dd1["name"][1], mode='lines', line={'color':interval_color,'width':2}), |
| 933 |
go.Scatter (x=dd1["x"][2], y=dd1["y"][2], name=dd1["name"][2], text=dd1["text"][2], **common), |
| 934 |
go.Scatter (x=dd1["x"][3], y=dd1["y"][3], name=dd1["name"][3], text=dd1["text"][3], **common), |
| 935 |
go.Scatter (x=dd1["x"][4], y=dd1["y"][4], name=dd1["name"][4], text=dd1["text"][4], **common), |
| 936 |
go.Scatter (x=dd1["x"][5], y=dd1["y"][5], name=dd1["name"][5], text=dd1["text"][5], **common), |
| 937 |
go.Scatter (x=dd1["x"][6], y=dd1["y"][6], name=dd1["name"][6], text=dd1["text"][6], **common)] |
| 938 |
|
| 939 |
|
| 940 |
updatemenus = [ |
| 941 |
dict (type="buttons", active=0, x=-0.06, y=0, xanchor='right', yanchor='bottom', buttons = [ |
| 942 |
dict (label=lab1, method='update', args=[dd1, ld1]), |
| 943 |
dict (label=lab2, method='update', args=[dd2, ld2]), |
| 944 |
dict (label=lab3, method='update', args=[dd3, ld3]), |
| 945 |
dict (label=lab4, method='update', args=[dd4, ld4])])] |
| 946 |
|
| 947 |
|
| 948 |
layout = go.Layout ( |
| 949 |
plot_bgcolor="whitesmoke", |
| 950 |
width = width, |
| 951 |
height = height, |
| 952 |
updatemenus = updatemenus, |
| 953 |
legend = {"x":-0.05, "y":1,"xanchor":'right',"yanchor":'top'}, |
| 954 |
title = {"text":plot_title, "xref":"paper" ,"x":0.5, "xanchor":"center"}, |
| 955 |
xaxis = {"title":"Experiment time (h)", "zeroline":False, "showline":True}, |
| 956 |
yaxis = {"title":"Count", "zeroline":False, "showline":True, "fixedrange":True, "range":ld1["yaxis.range"]}) |
| 957 |
|
| 958 |
return go.Figure (data=data, layout=layout) |
| 959 |
|
| 960 |
def __output_over_time_data (self, df_level, count_level, time_bins=500): |
| 961 |
"""Private function preparing data for output_over_time""" |
| 962 |
self.logger.debug ("\t\tPreparing data for {} {}".format(df_level, count_level)) |
| 963 |
|
| 964 |
|
| 965 |
df = self.pass_sample_df if df_level == "pass" else self.all_sample_df |
| 966 |
sf = self.pass_scaling_factor if df_level == "pass" else self.all_scaling_factor |
| 967 |
|
| 968 |
|
| 969 |
t = (df["start_time"]/3600).values |
| 970 |
x = np.linspace (t.min(), t.max(), num=time_bins) |
| 971 |
t = np.digitize (t, bins=x, right=True) |
| 972 |
|
| 973 |
|
| 974 |
if count_level == "reads": |
| 975 |
y = np.bincount(t) |
| 976 |
elif count_level == "bases": |
| 977 |
y = np.bincount(t, weights=df["read_len"].values) |
| 978 |
|
| 979 |
|
| 980 |
y = y*sf |
| 981 |
|
| 982 |
|
| 983 |
y_cum = np.cumsum(y) |
| 984 |
y_cum_max = y_cum[-1] |
| 985 |
|
| 986 |
|
| 987 |
y = gaussian_filter1d (y, sigma=1) |
| 988 |
y = y*y_cum_max/y.max() |
| 989 |
|
| 990 |
|
| 991 |
lab_text = [] |
| 992 |
lab_name = [] |
| 993 |
lab_x = [] |
| 994 |
for lab in (50, 75, 90, 99, 100): |
| 995 |
val = y_cum_max*lab/100 |
| 996 |
idx = (np.abs(y_cum-val)).argmin() |
| 997 |
lab_text.append(["", '{}%<br>{}h<br>{:,} {}'.format(lab, round(x[idx],2), int(y_cum[idx]), count_level)]) |
| 998 |
lab_x.append ([x[idx], x[idx]]) |
| 999 |
lab_name.append ("{}%".format(lab)) |
| 1000 |
|
| 1001 |
|
| 1002 |
data_dict = dict( |
| 1003 |
x = [x, x]+lab_x, |
| 1004 |
y = [y_cum, y, [0,y_cum_max], [0,y_cum_max], [0,y_cum_max], [0,y_cum_max], [0,y_cum_max]], |
| 1005 |
name = ["Cumulative", "Interval"]+lab_name, |
| 1006 |
text = ["", ""]+lab_text) |
| 1007 |
|
| 1008 |
|
| 1009 |
layout_dict = {"yaxis.range": [0, y_cum_max+y_cum_max/6]} |
| 1010 |
|
| 1011 |
label = "{} {}".format(df_level.capitalize(), count_level.capitalize()) |
| 1012 |
return (label, data_dict, layout_dict) |
| 1013 |
|
| 1014 |
|
| 1015 |
def read_len_over_time (self, |
| 1016 |
median_color:str="rgb(102,168,255)", |
| 1017 |
quartile_color:str="rgb(153,197,255)", |
| 1018 |
extreme_color:str="rgba(153,197,255,0.5)", |
| 1019 |
smooth_sigma:float=1, |
| 1020 |
time_bins:int=500, |
| 1021 |
width:int=None, |
| 1022 |
height:int=500, |
| 1023 |
plot_title:str="Read length over experiment time"): |
| 1024 |
""" |
| 1025 |
Plot a read length over time |
| 1026 |
* median_color |
| 1027 |
Color of median line color (hex, rgb, rgba, hsl, hsv or any CSS named colors https://www.w3.org/TR/css-color-3/#svg-color |
| 1028 |
* quartile_color |
| 1029 |
Color of inter quartile area and lines (hex, rgb, rgba, hsl, hsv or any CSS named colors https://www.w3.org/TR/css-color-3/#svg-color |
| 1030 |
* extreme_color |
| 1031 |
Color of inter extreme area and lines (hex, rgb, rgba, hsl, hsv or any CSS named colors https://www.w3.org/TR/css-color-3/#svg-col |
| 1032 |
* smooth_sigma |
| 1033 |
sigma parameter for the Gaussian filter line smoothing |
| 1034 |
* time_bins |
| 1035 |
Number of bins to divide the time values in (x axis) |
| 1036 |
* width |
| 1037 |
With of the plotting area in pixel |
| 1038 |
* height |
| 1039 |
height of the plotting area in pixel |
| 1040 |
* plot_title |
| 1041 |
Title to display on top of the plot |
| 1042 |
""" |
| 1043 |
fig = self.__over_time_plot ( |
| 1044 |
field_name = "read_len", |
| 1045 |
plot_title = plot_title, |
| 1046 |
y_lab = "Alignment length", |
| 1047 |
y_scale = "log", |
| 1048 |
median_color = median_color, |
| 1049 |
quartile_color = quartile_color, |
| 1050 |
extreme_color = extreme_color, |
| 1051 |
smooth_sigma = smooth_sigma, |
| 1052 |
time_bins = time_bins, |
| 1053 |
width = width, |
| 1054 |
height = height) |
| 1055 |
return fig |
| 1056 |
|
| 1057 |
def read_qual_over_time (self, |
| 1058 |
median_color:str="rgb(250,128,114)", |
| 1059 |
quartile_color:str="rgb(250,170,160)", |
| 1060 |
extreme_color:str="rgba(250,170,160,0.5)", |
| 1061 |
smooth_sigma:float=1, |
| 1062 |
time_bins:int=500, |
| 1063 |
width:int=None, |
| 1064 |
height:int=500, |
| 1065 |
plot_title:str="Read quality over experiment time"): |
| 1066 |
""" |
| 1067 |
Plot a mean quality over time |
| 1068 |
* median_color |
| 1069 |
Color of median line color (hex, rgb, rgba, hsl, hsv or any CSS named colors https://www.w3.org/TR/css-color-3/#svg-color |
| 1070 |
* quartile_color |
| 1071 |
Color of inter quartile area and lines (hex, rgb, rgba, hsl, hsv or any CSS named colors https://www.w3.org/TR/css-color-3/#svg-color |
| 1072 |
* extreme_color |
| 1073 |
Color of inter extreme area and lines (hex, rgb, rgba, hsl, hsv or any CSS named colors https://www.w3.org/TR/css-color-3/#svg-col |
| 1074 |
* smooth_sigma |
| 1075 |
sigma parameter for the Gaussian filter line smoothing |
| 1076 |
* time_bins |
| 1077 |
Number of bins to divide the time values in (x axis) |
| 1078 |
* width |
| 1079 |
With of the plotting area in pixel |
| 1080 |
* height |
| 1081 |
height of the plotting area in pixel |
| 1082 |
* plot_title |
| 1083 |
Title to display on top of the plot |
| 1084 |
""" |
| 1085 |
|
| 1086 |
fig = self.__over_time_plot ( |
| 1087 |
field_name = "mean_qscore", |
| 1088 |
plot_title = plot_title, |
| 1089 |
y_lab = "Mean read PHRED quality", |
| 1090 |
y_scale = "linear", |
| 1091 |
median_color = median_color, |
| 1092 |
quartile_color = quartile_color, |
| 1093 |
extreme_color = extreme_color, |
| 1094 |
smooth_sigma = smooth_sigma, |
| 1095 |
time_bins = time_bins, |
| 1096 |
width = width, |
| 1097 |
height = height) |
| 1098 |
return fig |
| 1099 |
|
| 1100 |
def align_len_over_time (self, |
| 1101 |
median_color:str="rgb(102,168,255)", |
| 1102 |
quartile_color:str="rgb(153,197,255)", |
| 1103 |
extreme_color:str="rgba(153,197,255,0.5)", |
| 1104 |
smooth_sigma:float=1, |
| 1105 |
time_bins:int=500, |
| 1106 |
width:int=None, |
| 1107 |
height:int=500, |
| 1108 |
plot_title:str="Aligned reads length over experiment time"): |
| 1109 |
""" |
| 1110 |
Plot a aligned reads length over time |
| 1111 |
* median_color |
| 1112 |
Color of median line color (hex, rgb, rgba, hsl, hsv or any CSS named colors https://www.w3.org/TR/css-color-3/#svg-color |
| 1113 |
* quartile_color |
| 1114 |
Color of inter quartile area and lines (hex, rgb, rgba, hsl, hsv or any CSS named colors https://www.w3.org/TR/css-color-3/#svg-color |
| 1115 |
* extreme_color |
| 1116 |
Color of inter extreme area and lines (hex, rgb, rgba, hsl, hsv or any CSS named colors https://www.w3.org/TR/css-color-3/#svg-col |
| 1117 |
* smooth_sigma |
| 1118 |
sigma parameter for the Gaussian filter line smoothing |
| 1119 |
* time_bins |
| 1120 |
Number of bins to divide the time values in (x axis) |
| 1121 |
* width |
| 1122 |
With of the plotting area in pixel |
| 1123 |
* height |
| 1124 |
height of the plotting area in pixel |
| 1125 |
* plot_title |
| 1126 |
Title to display on top of the plot |
| 1127 |
""" |
| 1128 |
|
| 1129 |
if not self.has_alignment: |
| 1130 |
raise pycoQCError ("No Alignment information available") |
| 1131 |
|
| 1132 |
fig = self.__over_time_plot ( |
| 1133 |
field_name = "align_len", |
| 1134 |
plot_title = plot_title, |
| 1135 |
y_lab = "Aligned reads length", |
| 1136 |
y_scale = "log", |
| 1137 |
median_color = median_color, |
| 1138 |
quartile_color = quartile_color, |
| 1139 |
extreme_color = extreme_color, |
| 1140 |
smooth_sigma = smooth_sigma, |
| 1141 |
time_bins = time_bins, |
| 1142 |
width = width, |
| 1143 |
height = height) |
| 1144 |
return fig |
| 1145 |
|
| 1146 |
def identity_freq_over_time (self, |
| 1147 |
median_color:str="rgb(250,128,114)", |
| 1148 |
quartile_color:str="rgb(250,170,160)", |
| 1149 |
extreme_color:str="rgba(250,170,160,0.5)", |
| 1150 |
smooth_sigma:float=1, |
| 1151 |
time_bins:int=500, |
| 1152 |
width:int=None, |
| 1153 |
height:int=500, |
| 1154 |
plot_title:str="Aligned reads identity over experiment time"): |
| 1155 |
""" |
| 1156 |
Plot the alignment identity scores over time |
| 1157 |
* median_color |
| 1158 |
Color of median line color (hex, rgb, rgba, hsl, hsv or any CSS named colors https://www.w3.org/TR/css-color-3/#svg-color |
| 1159 |
* quartile_color |
| 1160 |
Color of inter quartile area and lines (hex, rgb, rgba, hsl, hsv or any CSS named colors https://www.w3.org/TR/css-color-3/#svg-color |
| 1161 |
* extreme_color |
| 1162 |
Color of inter extreme area and lines (hex, rgb, rgba, hsl, hsv or any CSS named colors https://www.w3.org/TR/css-color-3/#svg-col |
| 1163 |
* smooth_sigma |
| 1164 |
sigma parameter for the Gaussian filter line smoothing |
| 1165 |
* time_bins |
| 1166 |
Number of bins to divide the time values in (x axis) |
| 1167 |
* width |
| 1168 |
With of the plotting area in pixel |
| 1169 |
* height |
| 1170 |
height of the plotting area in pixel |
| 1171 |
* plot_title |
| 1172 |
Title to display on top of the plot |
| 1173 |
""" |
| 1174 |
|
| 1175 |
|
| 1176 |
if not self.has_identity_freq: |
| 1177 |
raise pycoQCError ("No identity frequency information available") |
| 1178 |
|
| 1179 |
fig = self.__over_time_plot ( |
| 1180 |
field_name = "identity_freq", |
| 1181 |
plot_title = plot_title, |
| 1182 |
y_lab = "Identity frequency", |
| 1183 |
y_scale = "linear", |
| 1184 |
median_color = median_color, |
| 1185 |
quartile_color = quartile_color, |
| 1186 |
extreme_color = extreme_color, |
| 1187 |
smooth_sigma = smooth_sigma, |
| 1188 |
time_bins = time_bins, |
| 1189 |
width = width, |
| 1190 |
height = height) |
| 1191 |
return fig |
| 1192 |
|
| 1193 |
def __over_time_plot (self, |
| 1194 |
field_name, |
| 1195 |
plot_title, |
| 1196 |
y_lab, |
| 1197 |
y_scale, |
| 1198 |
median_color, |
| 1199 |
quartile_color, |
| 1200 |
extreme_color, |
| 1201 |
smooth_sigma, |
| 1202 |
time_bins, |
| 1203 |
width, |
| 1204 |
height): |
| 1205 |
"""Private function generating density plots for all over_time functions""" |
| 1206 |
self.logger.info ("\t\tComputing plot") |
| 1207 |
|
| 1208 |
lab1, dd1 = self.__over_time_data (df_level="all", field_name=field_name, smooth_sigma=smooth_sigma, time_bins=time_bins) |
| 1209 |
lab2, dd2 = self.__over_time_data (df_level="pass", field_name=field_name, smooth_sigma=smooth_sigma, time_bins=time_bins) |
| 1210 |
|
| 1211 |
|
| 1212 |
common = { |
| 1213 |
"mode": "lines", |
| 1214 |
"connectgaps": True} |
| 1215 |
data= [ |
| 1216 |
go.Scatter(x=dd1["x"][0], y=dd1["y"][0], name=dd1["name"][0], line={"color":extreme_color}, legendgroup="Extreme", **common), |
| 1217 |
go.Scatter(x=dd1["x"][1], y=dd1["y"][1], name=dd1["name"][1], fill="tonexty", line={"color":extreme_color}, legendgroup="Extreme", **common), |
| 1218 |
go.Scatter(x=dd1["x"][2], y=dd1["y"][2], name=dd1["name"][2], line={"color":quartile_color}, legendgroup="Quartiles", **common), |
| 1219 |
go.Scatter(x=dd1["x"][3], y=dd1["y"][3], name=dd1["name"][3], fill="tonexty", line={"color":quartile_color}, legendgroup="Quartiles", **common), |
| 1220 |
go.Scatter(x=dd1["x"][4], y=dd1["y"][4], name=dd1["name"][4], line={"color":median_color}, **common)] |
| 1221 |
|
| 1222 |
|
| 1223 |
updatemenus = [ |
| 1224 |
go.layout.Updatemenu (type="buttons", active=0, x=-0.07, y=0, xanchor='right', yanchor='bottom', buttons = [ |
| 1225 |
go.layout.updatemenu.Button ( |
| 1226 |
label=lab1, method='restyle', args=[dd1]), |
| 1227 |
go.layout.updatemenu.Button ( |
| 1228 |
label=lab2, method='restyle', args=[dd2])])] |
| 1229 |
|
| 1230 |
|
| 1231 |
layout = go.Layout ( |
| 1232 |
plot_bgcolor="whitesmoke", |
| 1233 |
width = width, |
| 1234 |
height = height, |
| 1235 |
updatemenus = updatemenus, |
| 1236 |
legend = {"x":-0.07, "y":1,"xanchor":'right',"yanchor":'top'}, |
| 1237 |
title = {"text":plot_title, "xref":"paper" ,"x":0.5, "xanchor":"center"}, |
| 1238 |
yaxis = {"title":y_lab, "zeroline":False, "type":y_scale, "showline":True, "rangemode":'nonnegative', "fixedrange":True}, |
| 1239 |
xaxis = {"title":"Experiment time (h)", "zeroline":False, "showline":True, "rangemode":'nonnegative'}) |
| 1240 |
|
| 1241 |
return go.Figure (data=data, layout=layout) |
| 1242 |
|
| 1243 |
def __over_time_data (self, df_level, field_name="read_len", smooth_sigma=1.5, time_bins=500): |
| 1244 |
"""Private function preparing data for qual_over_time""" |
| 1245 |
self.logger.debug ("\t\tPreparing data for {} reads and {}".format(df_level, field_name)) |
| 1246 |
|
| 1247 |
|
| 1248 |
df = self.pass_sample_df if df_level == "pass" else self.all_sample_df |
| 1249 |
data = df[field_name].dropna().values |
| 1250 |
|
| 1251 |
|
| 1252 |
t = (df["start_time"]/3600).values |
| 1253 |
x = np.linspace (t.min(), t.max(), num=time_bins) |
| 1254 |
t = np.digitize (t, bins=x, right=True) |
| 1255 |
|
| 1256 |
|
| 1257 |
bin_dict = defaultdict (list) |
| 1258 |
for bin_idx, val in zip (t, data) : |
| 1259 |
bin = x[bin_idx] |
| 1260 |
bin_dict[bin].append(val) |
| 1261 |
|
| 1262 |
|
| 1263 |
val_name = ["Min", "Max", "25%", "75%", "Median"] |
| 1264 |
stat_dict = defaultdict(list) |
| 1265 |
for bin in x: |
| 1266 |
if bin in bin_dict: |
| 1267 |
p = np.percentile (bin_dict[bin], [0, 100, 25, 75, 50]) |
| 1268 |
else: |
| 1269 |
p = [np.nan,np.nan,np.nan,np.nan,np.nan] |
| 1270 |
for val, stat in zip (val_name, p): |
| 1271 |
stat_dict[val].append(stat) |
| 1272 |
|
| 1273 |
|
| 1274 |
if smooth_sigma: |
| 1275 |
for val in val_name: |
| 1276 |
stat_dict [val] = gaussian_filter1d (stat_dict [val], sigma=smooth_sigma) |
| 1277 |
|
| 1278 |
|
| 1279 |
data_dict = dict( |
| 1280 |
x = [x,x,x,x,x], |
| 1281 |
y = [stat_dict["Min"], stat_dict["Max"], stat_dict["25%"], stat_dict["75%"], stat_dict["Median"]], |
| 1282 |
name = val_name) |
| 1283 |
|
| 1284 |
label = "{} Reads".format(df_level.capitalize()) |
| 1285 |
return (label, data_dict) |
| 1286 |
|
| 1287 |
|
| 1288 |
def barcode_counts (self, |
| 1289 |
colors:list=["#f8bc9c", "#f6e9a1", "#f5f8f2", "#92d9f5", "#4f97ba"], |
| 1290 |
width:int= None, |
| 1291 |
height:int=500, |
| 1292 |
plot_title:str="Percentage of reads per barcode"): |
| 1293 |
""" |
| 1294 |
Plot a mean quality over time |
| 1295 |
* colors |
| 1296 |
List of colors (hex, rgb, rgba, hsl, hsv or any CSS named colors https://www.w3.org/TR/css-color-3/#svg-color |
| 1297 |
* width |
| 1298 |
With of the plotting area in pixel |
| 1299 |
* height |
| 1300 |
height of the plotting area in pixel |
| 1301 |
* plot_title |
| 1302 |
Title to display on top of the plot |
| 1303 |
""" |
| 1304 |
|
| 1305 |
if not self.has_barcodes: |
| 1306 |
raise pycoQCError ("No barcode information available") |
| 1307 |
self.logger.info ("\t\tComputing plot") |
| 1308 |
|
| 1309 |
|
| 1310 |
lab1, dd1 = self.__barcode_counts_data (df_level="all") |
| 1311 |
lab2, dd2 = self.__barcode_counts_data (df_level="pass") |
| 1312 |
|
| 1313 |
|
| 1314 |
data= [go.Pie (labels=dd1["labels"][0] , values=dd1["values"][0] , sort=False, marker=dict(colors=colors))] |
| 1315 |
|
| 1316 |
|
| 1317 |
updatemenus = [ |
| 1318 |
dict (type="buttons", active=0, x=-0.2, y=0, xanchor='left', yanchor='bottom', buttons = [ |
| 1319 |
dict (label=lab1, method='restyle', args=[dd1]), |
| 1320 |
dict (label=lab2, method='restyle', args=[dd2])])] |
| 1321 |
|
| 1322 |
|
| 1323 |
layout = go.Layout ( |
| 1324 |
plot_bgcolor="whitesmoke", |
| 1325 |
legend = {"x":-0.2, "y":1,"xanchor":'left',"yanchor":'top'}, |
| 1326 |
updatemenus = updatemenus, |
| 1327 |
width = width, |
| 1328 |
height = height, |
| 1329 |
title = {"text":plot_title, "xref":"paper" ,"x":0.5, "xanchor":"center"}) |
| 1330 |
|
| 1331 |
return go.Figure (data=data, layout=layout) |
| 1332 |
|
| 1333 |
def __barcode_counts_data (self, df_level): |
| 1334 |
"""Private function preparing data for barcode_counts""" |
| 1335 |
self.logger.debug ("\t\tPreparing data for {} reads".format(df_level)) |
| 1336 |
|
| 1337 |
|
| 1338 |
df = self.pass_df if df_level == "pass" else self.all_df |
| 1339 |
counts = df["barcode"].value_counts() |
| 1340 |
counts = counts.sort_index() |
| 1341 |
|
| 1342 |
|
| 1343 |
data_dict = dict ( |
| 1344 |
labels = [counts.index], |
| 1345 |
values = [counts.values]) |
| 1346 |
|
| 1347 |
label = "{} Reads".format(df_level.capitalize()) |
| 1348 |
return (label, data_dict) |
| 1349 |
|
| 1350 |
|
| 1351 |
def channels_activity (self, |
| 1352 |
colorscale:list = [ |
| 1353 |
[0.0,'rgba(255,255,255,0)'], |
| 1354 |
[0.01,'rgb(255,255,200)'], |
| 1355 |
[0.25,'rgb(255,200,0)'], |
| 1356 |
[0.5,'rgb(200,0,0)'], |
| 1357 |
[0.75,'rgb(120,0,0)'], |
| 1358 |
[1.0,'rgb(0,0,0)']], |
| 1359 |
smooth_sigma:float=1, |
| 1360 |
time_bins:int=100, |
| 1361 |
width:int=None, |
| 1362 |
height:int=600, |
| 1363 |
plot_title:str="Output per channel over experiment time"): |
| 1364 |
""" |
| 1365 |
Plot a yield over time |
| 1366 |
* colorscale |
| 1367 |
a valid plotly color scale https://plot.ly/python/colorscales/ (Not recommanded to change) |
| 1368 |
* smooth_sigma |
| 1369 |
sigma parameter for the Gaussian filter line smoothing |
| 1370 |
* time_bins |
| 1371 |
Number of bins to divide the time values in (y axis) |
| 1372 |
* width |
| 1373 |
With of the plotting area in pixel |
| 1374 |
* height |
| 1375 |
height of the plotting area in pixel |
| 1376 |
* plot_title |
| 1377 |
Title to display on top of the plot |
| 1378 |
""" |
| 1379 |
self.logger.info ("\t\tComputing plot") |
| 1380 |
|
| 1381 |
|
| 1382 |
n_channels = 3000 if self.is_promethion else 512 |
| 1383 |
|
| 1384 |
|
| 1385 |
lab1, dd1 = self.__channels_activity_data(df_level="all", count_level="reads", n_channels=n_channels, smooth_sigma=smooth_sigma, time_bins=time_bins) |
| 1386 |
lab2, dd2 = self.__channels_activity_data(df_level="pass", count_level="reads", n_channels=n_channels, smooth_sigma=smooth_sigma, time_bins=time_bins) |
| 1387 |
lab3, dd3 = self.__channels_activity_data(df_level="all", count_level="bases", n_channels=n_channels, smooth_sigma=smooth_sigma, time_bins=time_bins) |
| 1388 |
lab4, dd4 = self.__channels_activity_data(df_level="pass", count_level="bases", n_channels=n_channels, smooth_sigma=smooth_sigma, time_bins=time_bins) |
| 1389 |
|
| 1390 |
|
| 1391 |
data = [go.Heatmap(x=dd1["x"][0], y=dd1["y"][0], z=dd1["z"][0], xgap=0.5, colorscale=colorscale, hoverinfo="x+y+z")] |
| 1392 |
|
| 1393 |
|
| 1394 |
updatemenus = [ |
| 1395 |
dict (type="buttons", active=0, x=-0.06, y=0, xanchor='right', yanchor='bottom', buttons = [ |
| 1396 |
dict (label=lab1, method='restyle', args=[dd1]), |
| 1397 |
dict (label=lab2, method='restyle', args=[dd2]), |
| 1398 |
dict (label=lab3, method='restyle', args=[dd3]), |
| 1399 |
dict (label=lab4, method='restyle', args=[dd4])])] |
| 1400 |
|
| 1401 |
|
| 1402 |
layout = go.Layout ( |
| 1403 |
plot_bgcolor="whitesmoke", |
| 1404 |
width = width, |
| 1405 |
height = height, |
| 1406 |
updatemenus = updatemenus, |
| 1407 |
title = {"text":plot_title, "xref":"paper" ,"x":0.5, "xanchor":"center"}, |
| 1408 |
xaxis = {"title":"Channel id", "zeroline":False, "showline":False, "nticks":20, "showgrid":False}, |
| 1409 |
yaxis = {"title":"Experiment time (h)", "zeroline":False, "showline":False, "hoverformat":".2f", "fixedrange":True}) |
| 1410 |
|
| 1411 |
return go.Figure (data=data, layout=layout) |
| 1412 |
|
| 1413 |
def __channels_activity_data (self, df_level, count_level="bases", n_channels=512, smooth_sigma=2, time_bins=150): |
| 1414 |
"""Private function preparing data for channels_activity""" |
| 1415 |
self.logger.debug ("\t\tPreparing data for {} {}".format(df_level, count_level)) |
| 1416 |
|
| 1417 |
|
| 1418 |
df = self.pass_sample_df if df_level == "pass" else self.all_sample_df |
| 1419 |
sf = self.pass_scaling_factor if df_level == "pass" else self.all_scaling_factor |
| 1420 |
|
| 1421 |
|
| 1422 |
t = (df["start_time"]/3600).values |
| 1423 |
bins = np.linspace (t.min(), t.max(), num=time_bins) |
| 1424 |
t = np.digitize (t, bins=bins, right=True) |
| 1425 |
|
| 1426 |
|
| 1427 |
z = np.ones((len(bins), n_channels), dtype=np.int) |
| 1428 |
if count_level == "bases": |
| 1429 |
for t_idx, channel, n_bases in zip(t, df["channel"], df["read_len"]): |
| 1430 |
z[t_idx][channel-1]+=n_bases |
| 1431 |
elif count_level == "reads": |
| 1432 |
for t_idx, channel in zip(t, df["channel"]): |
| 1433 |
try: |
| 1434 |
z[t_idx][channel-1]+=1 |
| 1435 |
except IndexError: |
| 1436 |
print (t_idx, channel) |
| 1437 |
raise |
| 1438 |
|
| 1439 |
z=z*sf |
| 1440 |
|
| 1441 |
|
| 1442 |
if smooth_sigma: |
| 1443 |
z = gaussian_filter1d (z.astype(np.float32), sigma=smooth_sigma, axis=0) |
| 1444 |
|
| 1445 |
|
| 1446 |
x = ["c {}".format(i) for i in range(1, n_channels+1)] |
| 1447 |
y = bins[1:] |
| 1448 |
|
| 1449 |
|
| 1450 |
data_dict = dict (x=[x], y=[y], z=[z]) |
| 1451 |
|
| 1452 |
label = "{} {}".format(df_level.capitalize(), count_level.capitalize()) |
| 1453 |
return (label, data_dict) |
| 1454 |
|
| 1455 |
|
| 1456 |
def alignment_reads_status (self, |
| 1457 |
colors:list=["#f44f39","#fc8161","#fcaf94","#828282"], |
| 1458 |
width:int= None, |
| 1459 |
height:int=500, |
| 1460 |
plot_title:str="Summary of reads alignment status"): |
| 1461 |
""" |
| 1462 |
Plot a basic alignment summary |
| 1463 |
* colors |
| 1464 |
List of colors (hex, rgb, rgba, hsl, hsv or any CSS named colors https://www.w3.org/TR/css-color-3/#svg-color |
| 1465 |
* width |
| 1466 |
With of the plotting area in pixel |
| 1467 |
* height |
| 1468 |
height of the plotting area in pixel |
| 1469 |
* plot_title |
| 1470 |
Title to display on top of the plot |
| 1471 |
""" |
| 1472 |
|
| 1473 |
if not self.has_alignment: |
| 1474 |
raise pycoQCError ("No Alignment information available") |
| 1475 |
self.logger.info ("\t\tComputing plot") |
| 1476 |
|
| 1477 |
df = self.alignments_df |
| 1478 |
|
| 1479 |
fig = make_subplots(rows=1, cols=2, column_widths=[0.4, 0.6], specs=[[{"type": "table"},{"type": "pie"}]]) |
| 1480 |
|
| 1481 |
|
| 1482 |
data = go.Table( |
| 1483 |
columnwidth = [3,2,2], |
| 1484 |
header = {"values":list(df.columns), "align":"center", "fill_color":"grey", "font_size":14, "font_color":"white", "height":40}, |
| 1485 |
cells = {"values":df.values.T , "align":"center", "fill_color":"whitesmoke", "font_size":12, "height":30}) |
| 1486 |
fig.add_trace (data, row=1, col=1) |
| 1487 |
|
| 1488 |
|
| 1489 |
data = go.Pie ( |
| 1490 |
labels=df["Alignments"], |
| 1491 |
values=df["Counts"], |
| 1492 |
sort=False, |
| 1493 |
marker={"colors":colors}, |
| 1494 |
name="Pie plot", |
| 1495 |
textinfo='label+percent') |
| 1496 |
fig.add_trace (data, row=1, col=2) |
| 1497 |
|
| 1498 |
|
| 1499 |
fig.update_layout( |
| 1500 |
width = width, |
| 1501 |
height = height, |
| 1502 |
title = {"text":plot_title, "xref":"paper" ,"x":0.5, "xanchor":"center"}) |
| 1503 |
|
| 1504 |
return fig |
| 1505 |
|
| 1506 |
|
| 1507 |
def alignment_rate (self, |
| 1508 |
colors:list=["#fcaf94","#828282","#fc8161","#828282","#f44f39","#d52221","#828282","#828282","#828282","#828282"], |
| 1509 |
width:int=None, |
| 1510 |
height:int=600, |
| 1511 |
plot_title:str="Bases alignment rate"): |
| 1512 |
""" |
| 1513 |
Plot a basic alignment summary |
| 1514 |
* colors |
| 1515 |
List of colors (hex, rgb, rgba, hsl, hsv or any CSS named colors https://www.w3.org/TR/css-color-3/#svg-color |
| 1516 |
* width |
| 1517 |
With of the plotting area in pixel |
| 1518 |
* height |
| 1519 |
height of the plotting area in pixel |
| 1520 |
* plot_title |
| 1521 |
Title to display on top of the plot |
| 1522 |
""" |
| 1523 |
|
| 1524 |
|
| 1525 |
if not self.has_identity_freq: |
| 1526 |
raise pycoQCError ("No identity frequency information available") |
| 1527 |
self.logger.info ("\t\tComputing plot") |
| 1528 |
|
| 1529 |
|
| 1530 |
bc_bases = self.all_df["read_len"].sum() |
| 1531 |
s = self.all_df[[ "read_len", "align_len", "insertion", "deletion", "soft_clip", "mismatch"]].dropna().sum() |
| 1532 |
total_error = s["insertion"]+s["deletion"]+s["mismatch"] |
| 1533 |
matching = s["align_len"]-total_error |
| 1534 |
unmapped = bc_bases-s["read_len"] |
| 1535 |
ct = namedtuple("ct", ["Bases","Counts","Total_freq","Aligned_freq"]) |
| 1536 |
l = [ |
| 1537 |
ct("Basecalled", bc_bases, 1, 1), |
| 1538 |
ct("Unmapped reads", unmapped, unmapped/bc_bases, 1), |
| 1539 |
ct("Mapped reads", s["read_len"], s["read_len"]/bc_bases, 1), |
| 1540 |
ct("Softclip", s["soft_clip"], s["soft_clip"]/bc_bases, 1), |
| 1541 |
ct("Aligned", s["align_len"], s["align_len"]/bc_bases, 1), |
| 1542 |
ct("Matching", matching, matching/bc_bases, matching/s["align_len"]), |
| 1543 |
ct("Non-matching", total_error, total_error/bc_bases, total_error/s["align_len"]), |
| 1544 |
ct("Insertions", s["insertion"], s["insertion"]/bc_bases, s["insertion"]/s["align_len"]), |
| 1545 |
ct("Deletions", s["deletion"], s["deletion"]/bc_bases, s["deletion"]/s["align_len"]), |
| 1546 |
ct("Mismatches", s["mismatch"], s["mismatch"]/bc_bases, s["mismatch"]/s["align_len"])] |
| 1547 |
|
| 1548 |
|
| 1549 |
df = pd.DataFrame(l) |
| 1550 |
|
| 1551 |
|
| 1552 |
data1 = go.Table( |
| 1553 |
columnwidth = [3,2,2,2], |
| 1554 |
header = { |
| 1555 |
"values":["Bases","Bases Count","% Total","% Aligned"], |
| 1556 |
"align":"center", "fill_color":["grey"], "font_size":14, "font_color":"white", "height":40}, |
| 1557 |
cells = { |
| 1558 |
"values":df.values.T , "format":["", ".3e", ".3p", ".3p"], |
| 1559 |
"align":"center", "fill_color":"whitesmoke", "font_size":12, "height":30}) |
| 1560 |
|
| 1561 |
data2 = go.Sankey( |
| 1562 |
arrangement = "freeform", |
| 1563 |
node = go.sankey.Node( |
| 1564 |
pad = 20, |
| 1565 |
thickness = 30, |
| 1566 |
line = {"width":0}, |
| 1567 |
label = df["Bases"].values, |
| 1568 |
x = [0,0.25,0.25,0.5,0.5,1,0.75], |
| 1569 |
y = [0,1,0,0.9,0,0,0.8], |
| 1570 |
color = colors), |
| 1571 |
link = go.sankey.Link( |
| 1572 |
source = [0, 0, 2, 2, 4, 4, 6, 6, 6], |
| 1573 |
target = [1, 2, 3, 4, 5, 6, 7, 8, 9], |
| 1574 |
value = df["Counts"].values[1:], |
| 1575 |
hoverinfo = "none")) |
| 1576 |
|
| 1577 |
|
| 1578 |
fig = make_subplots(rows=1, cols=2, column_widths=[0.4, 0.6], specs=[[{"type": "table"},{"type": "sankey"}]]) |
| 1579 |
fig.add_trace (data1, row=1, col=1) |
| 1580 |
fig.add_trace (data2, row=1, col=2) |
| 1581 |
fig.update_layout( |
| 1582 |
width = width, |
| 1583 |
height = height, |
| 1584 |
title = {"text":plot_title, "xref":"paper" ,"x":0.5, "xanchor":"center"}) |
| 1585 |
|
| 1586 |
return fig |
| 1587 |
|
| 1588 |
|
| 1589 |
def alignment_coverage (self, |
| 1590 |
nbins:int=500, |
| 1591 |
color:str='rgba(70,130,180,0.70)', |
| 1592 |
smooth_sigma:int=1, |
| 1593 |
width:int= None, |
| 1594 |
height:int=500, |
| 1595 |
plot_title:str="Coverage overview"): |
| 1596 |
""" |
| 1597 |
Plot coverage over all the references |
| 1598 |
* nbins |
| 1599 |
Number of bins to divide the coverage into. |
| 1600 |
* smooth_sigma |
| 1601 |
sigma parameter for the Gaussian filter line smoothing |
| 1602 |
* width |
| 1603 |
With of the plotting area in pixel |
| 1604 |
* height |
| 1605 |
height of the plotting area in pixel |
| 1606 |
* plot_title |
| 1607 |
Title to display on top of the plot |
| 1608 |
""" |
| 1609 |
|
| 1610 |
if not self.has_alignment: |
| 1611 |
raise pycoQCError ("No Alignment information available") |
| 1612 |
self.logger.info ("\t\tComputing plot") |
| 1613 |
|
| 1614 |
ref_offset_dict = self._ref_offset(self.ref_len_dict, "left", ret_type="dict") |
| 1615 |
df = self.all_df[["ref_id", "ref_start", "ref_end", "align_len"]].dropna() |
| 1616 |
steps = self.total_ref_len//nbins |
| 1617 |
mean_cov = round(df["align_len"].sum()/self.total_ref_len, 2) |
| 1618 |
|
| 1619 |
|
| 1620 |
l = [] |
| 1621 |
for line in df.itertuples(): |
| 1622 |
l.append(int(ref_offset_dict[line.ref_id]+line.ref_start)) |
| 1623 |
l = np.array(l) |
| 1624 |
bins = np.arange(0, self.total_ref_len, steps) |
| 1625 |
l = np.digitize(l,bins) |
| 1626 |
y = np.bincount(l, weights=df["align_len"])/steps |
| 1627 |
|
| 1628 |
|
| 1629 |
if smooth_sigma: |
| 1630 |
y = gaussian_filter1d (y, sigma=smooth_sigma) |
| 1631 |
|
| 1632 |
|
| 1633 |
data1 = go.Scatter ( |
| 1634 |
x=list(range(nbins+1)), |
| 1635 |
y=y, |
| 1636 |
name="Mean coverage", |
| 1637 |
hoveron="points", |
| 1638 |
hoverinfo="y", |
| 1639 |
fill='tozeroy', |
| 1640 |
fillcolor=color, |
| 1641 |
mode='none', |
| 1642 |
showlegend=True, |
| 1643 |
connectgaps=True) |
| 1644 |
|
| 1645 |
|
| 1646 |
data2 = go.Scatter ( |
| 1647 |
x=[0,nbins], |
| 1648 |
y=[mean_cov,mean_cov], |
| 1649 |
name=f"Overall coverage<br>{mean_cov}X", |
| 1650 |
mode="lines", |
| 1651 |
hoverinfo="skip", |
| 1652 |
line= {'color':'gray','width':2,'dash':'dot'}) |
| 1653 |
|
| 1654 |
updatemenus = [ |
| 1655 |
dict (type="buttons", x=-0.2, y=0, xanchor='left', yanchor='bottom', buttons = [ |
| 1656 |
dict (label="log", method='relayout', args=[{"yaxis":{"title":"Mean Coverage", "type":"log", "zeroline":False, "fixedrange":True}}]), |
| 1657 |
dict (label="linear", method='relayout', args=[{"yaxis":{"title":"Mean Coverage", "type":"linear", "zeroline":False, "fixedrange":True}}])])] |
| 1658 |
|
| 1659 |
|
| 1660 |
x_lab_coord = np.array(self._ref_offset(self.ref_len_dict, coordinates="middle", ret_type="list"))*nbins/self.total_ref_len |
| 1661 |
x_lab = list(self.ref_len_dict.keys()) |
| 1662 |
shapes = [] |
| 1663 |
x_shape_coord = np.array(self._ref_offset(self.ref_len_dict, coordinates="left", ret_type="list")[1:])*nbins/self.total_ref_len |
| 1664 |
for i in range(0, len(self.ref_len_dict)-2, 2): |
| 1665 |
shapes.append( |
| 1666 |
go.layout.Shape( |
| 1667 |
type="rect",x0=x_shape_coord[i],x1=x_shape_coord[i+1], |
| 1668 |
y0=0,y1=1, yref="paper", opacity=0.5, layer="below", fillcolor="lightgrey", line_width=0)) |
| 1669 |
|
| 1670 |
|
| 1671 |
layout = go.Layout ( |
| 1672 |
width = width, |
| 1673 |
height = height, |
| 1674 |
plot_bgcolor="whitesmoke", |
| 1675 |
updatemenus = updatemenus, |
| 1676 |
shapes=shapes, |
| 1677 |
hovermode = "closest", |
| 1678 |
legend = {"x":-0.2, "y":1,"xanchor":'left',"yanchor":'top'}, |
| 1679 |
xaxis = {"zeroline":False, "showline":True, "ticktext":x_lab, "tickvals":x_lab_coord, "tickangle":-45, "showgrid":False}, |
| 1680 |
yaxis = {"title":"Mean Coverage", "type":"log", "zeroline":False, "fixedrange":True}, |
| 1681 |
title = {"text":plot_title, "xref":"paper" ,"x":0.5, "xanchor":"center"}) |
| 1682 |
|
| 1683 |
return go.Figure(data=[data1,data2], layout=layout) |
| 1684 |
|
| 1685 |
def _ref_offset (self, rlen, coordinates="left", ret_type="dict"): |
| 1686 |
offset = [] if ret_type=="list" else OrderedDict() |
| 1687 |
cumsum=0 |
| 1688 |
for ref, rlen in rlen.items (): |
| 1689 |
|
| 1690 |
if coordinates =="left": |
| 1691 |
v = cumsum |
| 1692 |
elif coordinates =="middle": |
| 1693 |
v = cumsum + rlen/2 |
| 1694 |
else: |
| 1695 |
v = cumsum + rlen |
| 1696 |
|
| 1697 |
if ret_type =="list": |
| 1698 |
offset.append(v) |
| 1699 |
else: |
| 1700 |
offset[ref]=v |
| 1701 |
cumsum+=rlen |
| 1702 |
return offset |
| 1703 |
|
| 1704 |
|
| 1705 |
@staticmethod |
| 1706 |
def _compute_percentiles (data): |
| 1707 |
return list(np.quantile(data.dropna(), q=np.linspace(0,1,101))) |
| 1708 |
|
| 1709 |
@staticmethod |
| 1710 |
def _compute_N50 (data): |
| 1711 |
data = data.dropna().values |
| 1712 |
data.sort() |
| 1713 |
half_sum = data.sum()/2 |
| 1714 |
cum_sum = 0 |
| 1715 |
for v in data: |
| 1716 |
cum_sum += v |
| 1717 |
if cum_sum >= half_sum: |
| 1718 |
return int(v) |
| 1719 |
|
| 1720 |
@staticmethod |
| 1721 |
def _compute_hist (data, x_scale="linear", smooth_sigma=2, nbins=200): |
| 1722 |
|
| 1723 |
|
| 1724 |
min = np.nanmin(data) |
| 1725 |
max = np.nanmax(data) |
| 1726 |
|
| 1727 |
if x_scale == "log": |
| 1728 |
count_y, bins = np.histogram (a=data, bins=np.logspace (np.log10(min), np.log10(max)+0.1, nbins)) |
| 1729 |
elif x_scale == "linear": |
| 1730 |
count_y, bins = np.histogram (a=data, bins= np.linspace (min, max, nbins)) |
| 1731 |
|
| 1732 |
|
| 1733 |
count_x = bins[1:] |
| 1734 |
|
| 1735 |
|
| 1736 |
if smooth_sigma: |
| 1737 |
count_y = gaussian_filter1d (count_y, sigma=smooth_sigma) |
| 1738 |
|
| 1739 |
|
| 1740 |
count_x = [float(i) for i in count_x] |
| 1741 |
count_y = [float(i) for i in count_y] |
| 1742 |
|
| 1743 |
return (count_x, count_y) |