| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
from collections import * |
| 7 |
import warnings |
| 8 |
|
| 9 |
|
| 10 |
import numpy as np |
| 11 |
import pandas as pd |
| 12 |
import pysam as ps |
| 13 |
|
| 14 |
|
| 15 |
from pycoQC.common import * |
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
warnings.filterwarnings("ignore", category=FutureWarning) |
| 21 |
|
| 22 |
|
| 23 |
class pycoQC_parse (): |
| 24 |
|
| 25 |
|
| 26 |
def __init__ (self, |
| 27 |
summary_file:str, |
| 28 |
barcode_file:str="", |
| 29 |
bam_file:str="", |
| 30 |
runid_list:list=[], |
| 31 |
filter_calibration:bool=False, |
| 32 |
filter_duplicated:bool=False, |
| 33 |
min_barcode_percent:float=0.1, |
| 34 |
cleanup:bool=True, |
| 35 |
verbose:bool=False, |
| 36 |
quiet:bool=False): |
| 37 |
""" |
| 38 |
Parse Albacore sequencing_summary.txt file and clean-up the data |
| 39 |
* summary_file |
| 40 |
Path to the sequencing_summary generated by Albacore 1.0.0 + (read_fast5_basecaller.py) / Guppy 2.1.3+ (guppy_basecaller). |
| 41 |
One can also pass multiple space separated file paths or a UNIX style regex matching multiple files |
| 42 |
* barcode_file |
| 43 |
Path to the barcode_file generated by Guppy 2.1.3+ (guppy_barcoder) or Deepbinner 0.2.0+. This is not a required file. |
| 44 |
One can also pass multiple space separated file paths or a UNIX style regex matching multiple files |
| 45 |
* bam_file |
| 46 |
Path to a Bam file corresponding to reads in the summary_file. Preferably aligned with Minimap2 |
| 47 |
One can also pass multiple space separated file paths or a UNIX style regex matching multiple files |
| 48 |
* runid_list |
| 49 |
Select only specific runids to be analysed. Can also be used to force pycoQC to order the runids for |
| 50 |
temporal plots, if the sequencing_summary file contain several sucessive runs. By default pycoQC analyses |
| 51 |
all the runids in the file and uses the runid order as defined in the file. |
| 52 |
* filter_calibration |
| 53 |
If True read flagged as calibration strand by the software are removed |
| 54 |
* filter_duplicated |
| 55 |
If True duplicated read_ids are removed but the first occurence is kept (Guppy sometimes outputs the same read multiple times) |
| 56 |
* min_barcode_percent |
| 57 |
Minimal percent of total reads to retain barcode label. If below the barcode value is set as `unclassified`. |
| 58 |
""" |
| 59 |
|
| 60 |
|
| 61 |
self.logger = get_logger(name=__name__, verbose=verbose, quiet=quiet) |
| 62 |
|
| 63 |
|
| 64 |
self.runid_list = runid_list |
| 65 |
self.filter_calibration = filter_calibration |
| 66 |
self.filter_duplicated = filter_duplicated |
| 67 |
self.min_barcode_percent = min_barcode_percent |
| 68 |
self.cleanup = cleanup |
| 69 |
|
| 70 |
|
| 71 |
self.counter = OrderedDict() |
| 72 |
|
| 73 |
|
| 74 |
self.logger.warning ("Check input data files") |
| 75 |
|
| 76 |
|
| 77 |
self.summary_files_list = expand_file_names(summary_file) |
| 78 |
self.logger.debug ("\t\tSequencing summary files found: {}".format(" ".join(self.summary_files_list))) |
| 79 |
self.counter["Summary files found"] = len(self.summary_files_list) |
| 80 |
|
| 81 |
if barcode_file: |
| 82 |
self.barcode_files_list = expand_file_names(barcode_file) |
| 83 |
self.logger.debug ("\t\tBarcode files found: {}".format(" ".join(self.barcode_files_list))) |
| 84 |
self.counter["Barcode files found"] = len(self.barcode_files_list) |
| 85 |
else: |
| 86 |
self.barcode_files_list =[] |
| 87 |
|
| 88 |
if bam_file: |
| 89 |
self.bam_file_list = expand_file_names(bam_file, bam_check=True) |
| 90 |
self.logger.debug ("\t\tBam files found: {}".format(" ".join(self.bam_file_list))) |
| 91 |
self.counter["Bam files found"] = len(self.bam_file_list) |
| 92 |
else: |
| 93 |
self.bam_file_list =[] |
| 94 |
|
| 95 |
self.logger.warning ("Parse data files") |
| 96 |
summary_reads_df = self._parse_summary() |
| 97 |
barcode_reads_df = self._parse_barcode() |
| 98 |
bam_reads_df, self.alignments_df, self.ref_len_dict = self._parse_bam() |
| 99 |
|
| 100 |
self.logger.warning ("Merge data") |
| 101 |
self.reads_df = self._merge_reads_df(summary_reads_df, barcode_reads_df, bam_reads_df) |
| 102 |
|
| 103 |
|
| 104 |
if self.cleanup: |
| 105 |
self.logger.warning("Cleaning data") |
| 106 |
self.reads_df = self._clean_reads_df(self.reads_df) |
| 107 |
|
| 108 |
def __str__(self): |
| 109 |
return dict_to_str(self.counter) |
| 110 |
|
| 111 |
def __repr__(self): |
| 112 |
return "[{}]\n".format(self.__class__.__name__) |
| 113 |
|
| 114 |
|
| 115 |
|
| 116 |
def _parse_summary (self): |
| 117 |
"""""" |
| 118 |
self.logger.debug ("\tParse summary files") |
| 119 |
df = merge_files_to_df (self.summary_files_list) |
| 120 |
|
| 121 |
if self.cleanup: |
| 122 |
|
| 123 |
self.logger.debug ("\tRename summary sequencing columns") |
| 124 |
rename_colmanes = { |
| 125 |
"sequence_length_template":"read_len", |
| 126 |
"sequence_length_2d":"read_len", |
| 127 |
"sequence_length":"read_len", |
| 128 |
"mean_qscore_template":"mean_qscore", |
| 129 |
"mean_qscore_2d":"mean_qscore", |
| 130 |
"calibration_strand_genome_template":"calibration", |
| 131 |
"barcode_arrangement":"barcode"} |
| 132 |
df = df.rename(columns=rename_colmanes) |
| 133 |
|
| 134 |
|
| 135 |
self.logger.debug ("\tVerifying fields and discarding unused columns") |
| 136 |
df = self._select_df_columns ( |
| 137 |
df = df, |
| 138 |
required_colnames = ["read_id", "run_id", "channel", "start_time", "read_len", "mean_qscore"], |
| 139 |
optional_colnames = ["calibration", "barcode"]) |
| 140 |
|
| 141 |
|
| 142 |
n = len(df) |
| 143 |
self.logger.debug ("\t\t{:,} reads found in initial file".format(n)) |
| 144 |
self.counter["Initial reads"] = n |
| 145 |
|
| 146 |
return df |
| 147 |
|
| 148 |
def _parse_barcode (self): |
| 149 |
"""""" |
| 150 |
if not self.barcode_files_list: |
| 151 |
return pd.DataFrame() |
| 152 |
|
| 153 |
self.logger.debug ("\tParse barcode files") |
| 154 |
df = merge_files_to_df (self.barcode_files_list) |
| 155 |
|
| 156 |
|
| 157 |
if "read_id" in df and "barcode_arrangement" in df: |
| 158 |
self.logger.debug ("\t\tFound valid Guppy barcode file") |
| 159 |
df = df [["read_id", "barcode_arrangement"]] |
| 160 |
df = df.rename(columns={"barcode_arrangement":"barcode"}) |
| 161 |
|
| 162 |
elif "read_ID" in df and "barcode_call" in df: |
| 163 |
self.logger.debug ("\t\tFound valid Deepbinner barcode file") |
| 164 |
df = df [["read_ID", "barcode_call"]] |
| 165 |
df = df.rename(columns={"read_ID":"read_id", "barcode_call":"barcode"}) |
| 166 |
df['barcode'].replace("none", "unclassified", inplace=True) |
| 167 |
else: |
| 168 |
raise pycoQCError ("File {} does not contain required barcode information".format(fp)) |
| 169 |
|
| 170 |
n = len(df[df['barcode']!="unclassified"]) |
| 171 |
self.logger.debug ("\t\t{:,} reads with barcodes assigned".format(n)) |
| 172 |
self.counter["Reads with barcodes"] = n |
| 173 |
|
| 174 |
return df |
| 175 |
|
| 176 |
def _parse_bam (self): |
| 177 |
"""""" |
| 178 |
if not self.bam_file_list: |
| 179 |
return (pd.DataFrame(), pd.DataFrame(), OrderedDict()) |
| 180 |
|
| 181 |
|
| 182 |
ref_len_dict = OrderedDict() |
| 183 |
alignments_dict = Counter() |
| 184 |
read_dict = OrderedDict () |
| 185 |
|
| 186 |
for bam_fn in self.bam_file_list: |
| 187 |
with ps.AlignmentFile(bam_fn, "rb") as bam: |
| 188 |
|
| 189 |
|
| 190 |
for ref_id, ref_len in zip(bam.references, bam.lengths): |
| 191 |
if not ref_id in ref_len_dict: |
| 192 |
ref_len_dict[ref_id] = ref_len |
| 193 |
|
| 194 |
|
| 195 |
for read in bam: |
| 196 |
if read.is_unmapped: |
| 197 |
alignments_dict["Unmapped"]+=1 |
| 198 |
elif read.is_secondary: |
| 199 |
alignments_dict["Secondary"]+=1 |
| 200 |
elif read.is_supplementary: |
| 201 |
alignments_dict["Suplementary"]+=1 |
| 202 |
elif read.query_name in read_dict: |
| 203 |
alignments_dict["Duplicated"]+=1 |
| 204 |
else: |
| 205 |
alignments_dict["Primary"]+=1 |
| 206 |
read_dict[read.query_name] = self._get_read_stats(read) |
| 207 |
|
| 208 |
|
| 209 |
if alignments_dict: |
| 210 |
alignments_df = pd.DataFrame.from_dict(alignments_dict, orient="index") |
| 211 |
alignments_df.reset_index(inplace=True) |
| 212 |
alignments_df.columns=["Alignments", "Counts"] |
| 213 |
alignments_df["Percents"] = (alignments_df["Counts"]/alignments_df["Counts"].sum()*100).round(2) |
| 214 |
else: |
| 215 |
alignments_df = pd.DataFrame() |
| 216 |
|
| 217 |
|
| 218 |
if read_dict: |
| 219 |
read_df = pd.DataFrame.from_dict(read_dict, orient="index") |
| 220 |
read_df.index.name="read_id" |
| 221 |
read_df.reset_index(inplace=True) |
| 222 |
else: |
| 223 |
read_df = pd.DataFrame() |
| 224 |
|
| 225 |
return (read_df, alignments_df, ref_len_dict) |
| 226 |
|
| 227 |
def _merge_reads_df(self, summary_reads_df, barcode_reads_df, bam_reads_df): |
| 228 |
"""""" |
| 229 |
df = summary_reads_df |
| 230 |
|
| 231 |
|
| 232 |
if not barcode_reads_df.empty: |
| 233 |
df = pd.merge(df, barcode_reads_df, on="read_id", how="left") |
| 234 |
df['barcode'].fillna('unclassified', inplace=True) |
| 235 |
|
| 236 |
|
| 237 |
if not bam_reads_df.empty: |
| 238 |
df = pd.merge(df, bam_reads_df, on="read_id", how="left") |
| 239 |
|
| 240 |
return df |
| 241 |
|
| 242 |
def _clean_reads_df (self, df): |
| 243 |
"""""" |
| 244 |
|
| 245 |
self.logger.info ("\tDiscarding lines containing NA values") |
| 246 |
l = len(df) |
| 247 |
df = df.dropna(subset=["read_id", "run_id", "channel", "start_time", "read_len", "mean_qscore"]) |
| 248 |
n=l-len(df) |
| 249 |
self.logger.info ("\t\t{:,} reads discarded".format(n)) |
| 250 |
self.counter["Reads with NA values discarded"] = n |
| 251 |
if len(df) <= 1: |
| 252 |
raise pycoQCError("No valid read left after NA values filtering") |
| 253 |
|
| 254 |
|
| 255 |
self.logger.info ("\tFiltering out zero length reads") |
| 256 |
l = len(df) |
| 257 |
df = df[(df["read_len"] > 0)] |
| 258 |
n=l-len(df) |
| 259 |
self.logger.info ("\t\t{:,} reads discarded".format(n)) |
| 260 |
self.counter["Zero length reads discarded"] = n |
| 261 |
if len(df) <= 1: |
| 262 |
raise pycoQCError("No valid read left after zero_len filtering") |
| 263 |
|
| 264 |
|
| 265 |
if self.filter_duplicated: |
| 266 |
self.logger.info ("\tFiltering out duplicated reads") |
| 267 |
l = len(df) |
| 268 |
df = df[~df.duplicated(subset="read_id", keep='first')] |
| 269 |
n=l-len(df) |
| 270 |
self.logger.info ("\t\t{:,} reads discarded".format(n)) |
| 271 |
self.counter["Duplicated reads discarded"] = n |
| 272 |
if len(df) <= 1: |
| 273 |
raise pycoQCError("No valid read left after calibration strand filtering") |
| 274 |
|
| 275 |
|
| 276 |
if self.filter_calibration and "calibration" in df: |
| 277 |
self.logger.info ("\tFiltering out calibration strand reads") |
| 278 |
l = len(df) |
| 279 |
df = df[(df["calibration"].isin(["filtered_out", "no_match", "*"]))] |
| 280 |
n=l-len(df) |
| 281 |
self.logger.info ("\t\t{:,} reads discarded".format(n)) |
| 282 |
self.counter["Calibration reads discarded"] = n |
| 283 |
if len(df) <= 1: |
| 284 |
raise pycoQCError("No valid read left after calibration strand filtering") |
| 285 |
|
| 286 |
|
| 287 |
if self.runid_list: |
| 288 |
self.logger.info ("\tSelecting run_ids passed by user") |
| 289 |
l = len(df) |
| 290 |
df = df[(df["run_id"].isin(self.runid_list))] |
| 291 |
n=l-len(df) |
| 292 |
self.logger.debug ("\t\t{:,} reads discarded".format(n)) |
| 293 |
self.counter["Excluded runid reads discarded"] = n |
| 294 |
if len(df) <= 1: |
| 295 |
raise pycoQCError("No valid read left after run ID filtering") |
| 296 |
runid_list = self.runid_list |
| 297 |
|
| 298 |
|
| 299 |
else: |
| 300 |
self.logger.info ("\tSorting run IDs by decreasing throughput") |
| 301 |
d = {} |
| 302 |
for run_id, sdf in df.groupby("run_id"): |
| 303 |
d[run_id] = len(sdf)/np.ptp(sdf["start_time"]) |
| 304 |
runid_list = [i for i, j in sorted (d.items(), key=lambda t: t[1], reverse=True)] |
| 305 |
self.logger.info ("\t\tRun-id order {}".format(runid_list)) |
| 306 |
|
| 307 |
|
| 308 |
self.logger.info ("\tReordering runids") |
| 309 |
increment_time = 0 |
| 310 |
runid_start = OrderedDict() |
| 311 |
for runid in runid_list: |
| 312 |
self.logger.info ("\t\tProcessing reads with Run_ID {} / time offset: {}".format(runid, increment_time)) |
| 313 |
max_val = df['start_time'][df["run_id"] == runid].max() |
| 314 |
df.loc[df["run_id"] == runid, 'start_time'] += increment_time |
| 315 |
runid_start[runid] = increment_time |
| 316 |
increment_time += max_val+1 |
| 317 |
df = df.sort_values ("start_time") |
| 318 |
|
| 319 |
|
| 320 |
if "barcode" in df and self.min_barcode_percent: |
| 321 |
self.logger.info ("\tCleaning up low frequency barcodes") |
| 322 |
l = (df["barcode"]=="unclassified").sum() |
| 323 |
barcode_counts = df["barcode"][df["barcode"]!="unclassified"].value_counts() |
| 324 |
cutoff = int(barcode_counts.sum()*self.min_barcode_percent/100) |
| 325 |
low_barcode = barcode_counts[barcode_counts<cutoff].index |
| 326 |
df.loc[df["barcode"].isin(low_barcode), "barcode"] = "unclassified" |
| 327 |
n= int((df["barcode"]=="unclassified").sum()-l) |
| 328 |
self.logger.info ("\t\t{:,} reads with low frequency barcode unset".format(n)) |
| 329 |
self.counter["Reads with low frequency barcode unset"] = n |
| 330 |
|
| 331 |
|
| 332 |
self.logger.info ("\tCast value to appropriate type") |
| 333 |
df = df.astype({'channel':"uint16","start_time":"float32","read_len":"uint32","mean_qscore":"float32"}) |
| 334 |
|
| 335 |
|
| 336 |
self.logger.info ("\tReindexing dataframe by read_ids") |
| 337 |
df = df.reset_index (drop=True) |
| 338 |
df = df.set_index ("read_id") |
| 339 |
self.logger.info ("\t\t{:,} Final valid reads".format(len(df))) |
| 340 |
|
| 341 |
|
| 342 |
self.counter["Valid reads"] = len(df) |
| 343 |
if len(df) < 500: |
| 344 |
self.logger.warning ("WARNING: Low number of reads found. This is likely to lead to errors when trying to generate plots") |
| 345 |
|
| 346 |
return df |
| 347 |
|
| 348 |
def _get_read_stats(self, read): |
| 349 |
"""""" |
| 350 |
d = OrderedDict() |
| 351 |
|
| 352 |
|
| 353 |
d["ref_id"] = read.reference_name |
| 354 |
d["ref_start"] = read.reference_start |
| 355 |
d["ref_end"] = read.reference_end |
| 356 |
d["align_len"] = read.query_alignment_length |
| 357 |
d["mapq"] = read.mapping_quality |
| 358 |
|
| 359 |
|
| 360 |
c_stat = read.get_cigar_stats()[0] |
| 361 |
d["insertion"] = c_stat[1] |
| 362 |
d["deletion"] = c_stat[2] |
| 363 |
d["soft_clip"] = c_stat[4] |
| 364 |
|
| 365 |
|
| 366 |
if read.has_tag("NM"): |
| 367 |
edit_dist = read.get_tag("NM") |
| 368 |
d["mismatch"] = edit_dist-(d["deletion"]+d["insertion"]) |
| 369 |
try: |
| 370 |
d["identity_freq"] = (d["align_len"]-edit_dist)/d["align_len"] |
| 371 |
except ZeroDivisionError: |
| 372 |
d["identity_freq"] = 0 |
| 373 |
|
| 374 |
|
| 375 |
elif read.has_tag("MD"): |
| 376 |
md_err = 0 |
| 377 |
for i in read.get_tag("MD"): |
| 378 |
if i in ["A","T","C","G","a","t","c","g"]: |
| 379 |
md_err += 1 |
| 380 |
d["mismatch"] = md_err-d["deletion"] |
| 381 |
edit_dist = d["mismatch"]+d["insertion"]+d["deletion"] |
| 382 |
try: |
| 383 |
d["identity_freq"] = (d["align_len"]-edit_dist)/d["align_len"] |
| 384 |
except ZeroDivisionError: |
| 385 |
d["identity_freq"] = 0 |
| 386 |
|
| 387 |
return d |
| 388 |
|
| 389 |
def _select_df_columns(self, df, required_colnames, optional_colnames): |
| 390 |
"""""" |
| 391 |
col_found = [] |
| 392 |
|
| 393 |
for col in required_colnames: |
| 394 |
if col in df: |
| 395 |
col_found.append(col) |
| 396 |
else: |
| 397 |
raise pycoQCError("Column {} not found in the provided sequence_summary file".format(col)) |
| 398 |
for col in optional_colnames: |
| 399 |
if col in df: |
| 400 |
col_found.append(col) |
| 401 |
|
| 402 |
return df[col_found] |