| 1 |
|
| 2 |
""" |
| 3 |
This module provides a few simple math and statistics functions |
| 4 |
for other scripts processing Oxford Nanopore sequencing data |
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
# FUNCTIONS |
| 10 |
* Calculate read N50 from a set of lengths |
| 11 |
get_N50(readlenghts) |
| 12 |
* Remove extreme length outliers from a dataset |
| 13 |
remove_length_outliers(dataframe, columname) |
| 14 |
* Calculate the average Phred quality of a read |
| 15 |
ave_qual(qualscores) |
| 16 |
* Write out the statistics report after calling readstats function |
| 17 |
write_stats(dataframe, outputname) |
| 18 |
* Compute a number of statistics, return a dictionary |
| 19 |
calc_read_stats(dataframe) |
| 20 |
""" |
| 21 |
|
| 22 |
import numpy as np |
| 23 |
import sys |
| 24 |
from deprecated import deprecated |
| 25 |
from math import log |
| 26 |
|
| 27 |
|
| 28 |
class Stats(object): |
| 29 |
def __init__(self, df): |
| 30 |
if len(df) < 5: |
| 31 |
sys.stderr.write("\n\nWARNING: less than 5 reads in the dataset!\n") |
| 32 |
sys.stderr.write("WARNING: some stats might be unexpected or missing\n") |
| 33 |
sys.stderr.write("WARNING: or a crash might happen, who knows\n") |
| 34 |
sys.stderr.write( |
| 35 |
"WARNING: this code is not intended for such small datasets\n\n\n" |
| 36 |
) |
| 37 |
self.number_of_reads = len(df) |
| 38 |
self.number_of_bases = np.sum(df["lengths"]) |
| 39 |
self._with_readIDs = "readIDs" in df |
| 40 |
if "aligned_lengths" in df: |
| 41 |
self.number_of_bases_aligned = np.sum(df["aligned_lengths"]) |
| 42 |
self.fraction_bases_aligned = ( |
| 43 |
self.number_of_bases_aligned / self.number_of_bases |
| 44 |
) |
| 45 |
self.median_read_length = np.median(df["lengths"]) |
| 46 |
self.mean_read_length = np.mean(df["lengths"]) |
| 47 |
self.read_length_stdev = np.std(df["lengths"]) |
| 48 |
self.n50 = get_N50(np.sort(df["lengths"])) |
| 49 |
if "percentIdentity" in df: |
| 50 |
self.average_identity = np.mean(df["percentIdentity"]) |
| 51 |
self.median_identity = np.median(df["percentIdentity"]) |
| 52 |
if "channelIDs" in df: |
| 53 |
self.active_channels = np.unique(df["channelIDs"]).size |
| 54 |
if "quals" in df: |
| 55 |
self._qualgroups = [ |
| 56 |
10, |
| 57 |
15, |
| 58 |
20, |
| 59 |
25, |
| 60 |
30, |
| 61 |
] |
| 62 |
self.mean_qual = ave_qual(df["quals"].astype("int").to_list()) |
| 63 |
self.median_qual = np.median(df["quals"]) |
| 64 |
self._top5_lengths = get_top_5( |
| 65 |
df=df, col="lengths", values=["lengths", "quals"] |
| 66 |
) |
| 67 |
self._top5_quals = get_top_5( |
| 68 |
df=df, col="quals", values=["quals", "lengths"] |
| 69 |
) |
| 70 |
self._reads_above_qual = [reads_above_qual(df, q) for q in self._qualgroups] |
| 71 |
else: |
| 72 |
self._top5_lengths = get_top_5( |
| 73 |
df=df, col="lengths", values=["lengths"], fill="quals" |
| 74 |
) |
| 75 |
|
| 76 |
def long_features_as_string(self): |
| 77 |
"""formatting long features to a string to print for legacy stats output""" |
| 78 |
self.top5_lengths = self.long_feature_as_string_top5(self._top5_lengths) |
| 79 |
self.top5_quals = self.long_feature_as_string_top5(self._top5_quals) |
| 80 |
self.reads_above_qual = self.long_feature_as_string_above_qual( |
| 81 |
self._reads_above_qual |
| 82 |
) |
| 83 |
|
| 84 |
def long_feature_as_string_top5(self, field): |
| 85 |
"""for legacy stats output""" |
| 86 |
if self._with_readIDs: |
| 87 |
return [ |
| 88 |
str(round(i, ndigits=1)) |
| 89 |
+ " (" |
| 90 |
+ str(round(j, ndigits=1)) |
| 91 |
+ "; " |
| 92 |
+ k |
| 93 |
+ ")" |
| 94 |
for i, j, k in field |
| 95 |
] |
| 96 |
else: |
| 97 |
return [ |
| 98 |
str(round(i, ndigits=1)) + " (" + str(round(j, ndigits=1)) + ")" |
| 99 |
for i, j in field |
| 100 |
] |
| 101 |
|
| 102 |
def long_feature_as_string_above_qual(self, field): |
| 103 |
"""for legacy stats output""" |
| 104 |
return [self.format_above_qual_line(entry) for entry in field] |
| 105 |
|
| 106 |
def format_above_qual_line(self, entry): |
| 107 |
"""for legacy stats output""" |
| 108 |
numberAboveQ, megAboveQ = entry |
| 109 |
return "{} ({}%) {}Mb".format( |
| 110 |
numberAboveQ, |
| 111 |
round(100 * (numberAboveQ / self.number_of_reads), ndigits=1), |
| 112 |
round(megAboveQ, ndigits=1), |
| 113 |
) |
| 114 |
|
| 115 |
def to_dict(self): |
| 116 |
"""for tsv stats output""" |
| 117 |
statdict = self.__dict__ |
| 118 |
for key, value in statdict.items(): |
| 119 |
if not key.startswith("_"): |
| 120 |
if not isinstance(value, int): |
| 121 |
statdict[key] = "{:.1f}".format(value) |
| 122 |
self.unwind_long_features_top5( |
| 123 |
feature="_top5_lengths", name="longest_read_(with_Q)" |
| 124 |
) |
| 125 |
self.unwind_long_features_top5( |
| 126 |
feature="_top5_quals", name="highest_Q_read_(with_length)" |
| 127 |
) |
| 128 |
self.unwind_long_features_above_qual(feature="_reads_above_qual", name="Reads") |
| 129 |
return {k: v for k, v in statdict.items() if not k.startswith("_")} |
| 130 |
|
| 131 |
def unwind_long_features_top5(self, feature, name): |
| 132 |
"""for tsv stats output""" |
| 133 |
if feature not in self.__dict__: |
| 134 |
return |
| 135 |
for entry, label in zip(self.__dict__[feature], range(1, 6)): |
| 136 |
self.__dict__[name + ":" + str(label)] = "{} ({})".format( |
| 137 |
round(entry[0], ndigits=1), round(entry[1], ndigits=1) |
| 138 |
) |
| 139 |
|
| 140 |
def unwind_long_features_above_qual(self, feature, name): |
| 141 |
"""for tsv stats output""" |
| 142 |
if feature not in self.__dict__: |
| 143 |
return |
| 144 |
for entry, label in zip( |
| 145 |
self.__dict__[feature], [">Q{}:".format(q) for q in self._qualgroups] |
| 146 |
): |
| 147 |
numberAboveQ, megAboveQ = entry |
| 148 |
percentage = 100 * (numberAboveQ / float(self.number_of_reads)) |
| 149 |
self.__dict__[name + " " + label] = "{} ({}%) {}Mb".format( |
| 150 |
numberAboveQ, round(percentage, ndigits=1), round(megAboveQ, ndigits=1) |
| 151 |
) |
| 152 |
|
| 153 |
|
| 154 |
def get_N50(readlengths): |
| 155 |
"""Calculate read length N50. |
| 156 |
|
| 157 |
Based on https://github.com/PapenfussLab/Mungo/blob/master/bin/fasta_stats.py |
| 158 |
""" |
| 159 |
return readlengths[ |
| 160 |
np.where(np.cumsum(readlengths) >= 0.5 * np.sum(readlengths))[0][0] |
| 161 |
] |
| 162 |
|
| 163 |
|
| 164 |
@deprecated |
| 165 |
def remove_length_outliers(df, columnname): |
| 166 |
"""Remove records with length-outliers above 3 standard deviations from the median.""" |
| 167 |
return df[df[columnname] < (np.median(df[columnname]) + 3 * np.std(df[columnname]))] |
| 168 |
|
| 169 |
|
| 170 |
def errs_tab(n): |
| 171 |
"""Generate list of error rates for qualities less than equal than n.""" |
| 172 |
return [10 ** (q / -10) for q in range(n + 1)] |
| 173 |
|
| 174 |
|
| 175 |
def ave_qual(quals, qround=False, tab=errs_tab(128)): |
| 176 |
"""Calculate average basecall quality of a read. |
| 177 |
|
| 178 |
Receive the integer quality scores of a read and return the average quality for that read |
| 179 |
First convert Phred scores to probabilities, |
| 180 |
calculate average error probability |
| 181 |
convert average back to Phred scale |
| 182 |
""" |
| 183 |
if quals: |
| 184 |
mq = -10 * log(sum([tab[q] for q in quals]) / len(quals), 10) |
| 185 |
if qround: |
| 186 |
return round(mq) |
| 187 |
else: |
| 188 |
return mq |
| 189 |
else: |
| 190 |
return None |
| 191 |
|
| 192 |
|
| 193 |
def get_top_5(df, col, values, fill=False): |
| 194 |
if "readIDs" in df: |
| 195 |
values.append("readIDs") |
| 196 |
if fill: |
| 197 |
return ( |
| 198 |
df.sort_values(col, ascending=False) |
| 199 |
.head(5)[values] |
| 200 |
.assign(fill=[0] * 5) |
| 201 |
.reset_index(drop=True) |
| 202 |
.itertuples(index=False, name=None) |
| 203 |
) |
| 204 |
else: |
| 205 |
return ( |
| 206 |
df.sort_values(col, ascending=False) |
| 207 |
.head(5)[values] |
| 208 |
.reset_index(drop=True) |
| 209 |
.itertuples(index=False, name=None) |
| 210 |
) |
| 211 |
|
| 212 |
|
| 213 |
def reads_above_qual(df, qual): |
| 214 |
numberAboveQ = np.sum(df["quals"] > qual) |
| 215 |
megAboveQ = np.sum(df.loc[df["quals"] > qual, "lengths"]) / 1e6 |
| 216 |
return numberAboveQ, megAboveQ |
| 217 |
|
| 218 |
|
| 219 |
def write_stats(datadfs, outputfile, names=[], as_tsv=False): |
| 220 |
"""Call calculation functions and write stats file. |
| 221 |
|
| 222 |
This function takes a list of DataFrames, |
| 223 |
and will create a column for each in the tab separated output. |
| 224 |
""" |
| 225 |
if outputfile == "stdout": |
| 226 |
output = sys.stdout |
| 227 |
else: |
| 228 |
output = open(outputfile, "wt") |
| 229 |
|
| 230 |
stats = [Stats(df) for df in datadfs] |
| 231 |
|
| 232 |
if as_tsv: |
| 233 |
import pandas as pd |
| 234 |
|
| 235 |
df = pd.DataFrame([s.to_dict() for s in stats]).transpose() |
| 236 |
df.index.name = "Metrics" |
| 237 |
if names: |
| 238 |
df.columns = names |
| 239 |
else: |
| 240 |
df.columns = ["dataset"] |
| 241 |
output.write(df.to_csv(sep="\t")) |
| 242 |
return df |
| 243 |
else: |
| 244 |
write_stats_legacy(stats, names, output, datadfs) |
| 245 |
|
| 246 |
|
| 247 |
def write_stats_legacy(stats, names, output, datadfs): |
| 248 |
""" |
| 249 |
Legacy method to write out stats. |
| 250 |
Will add padding to pretty print the table, and contain section headers |
| 251 |
""" |
| 252 |
features = { |
| 253 |
"Number of reads": "number_of_reads", |
| 254 |
"Total bases": "number_of_bases", |
| 255 |
"Total bases aligned": "number_of_bases_aligned", |
| 256 |
"Fraction of bases aligned": "fraction_bases_aligned", |
| 257 |
"Median read length": "median_read_length", |
| 258 |
"Mean read length": "mean_read_length", |
| 259 |
"STDEV read length": "read_length_stdev", |
| 260 |
"Read length N50": "n50", |
| 261 |
"Average percent identity": "average_identity", |
| 262 |
"Median percent identity": "median_identity", |
| 263 |
"Active channels": "active_channels", |
| 264 |
"Mean read quality": "mean_qual", |
| 265 |
"Median read quality": "median_qual", |
| 266 |
} |
| 267 |
max_len = max([len(k) for k in features.keys()]) |
| 268 |
try: |
| 269 |
max_num = ( |
| 270 |
max( |
| 271 |
max([len(str(s.number_of_bases)) for s in stats]), |
| 272 |
max([len(str(n)) for n in names]), |
| 273 |
) |
| 274 |
+ 6 |
| 275 |
) |
| 276 |
except ValueError: |
| 277 |
max_num = max([len(str(s.number_of_bases)) for s in stats]) + 6 |
| 278 |
output.write( |
| 279 |
"{:<{}}{}\n".format( |
| 280 |
"General summary:", |
| 281 |
max_len, |
| 282 |
" ".join(["{:>{}}".format(n, max_num) for n in names]), |
| 283 |
) |
| 284 |
) |
| 285 |
for f in sorted(features.keys()): |
| 286 |
try: |
| 287 |
output.write( |
| 288 |
"{f:{pad}}{v}\n".format( |
| 289 |
f=f + ":", |
| 290 |
pad=max_len, |
| 291 |
v=feature_list(stats, features[f], padding=max_num), |
| 292 |
) |
| 293 |
) |
| 294 |
except KeyError: |
| 295 |
pass |
| 296 |
if all(["quals" in df for df in datadfs]): |
| 297 |
for s in stats: |
| 298 |
s.long_features_as_string() |
| 299 |
long_features = { |
| 300 |
"Top 5 longest reads and their mean basecall quality score": [ |
| 301 |
"top5_lengths", |
| 302 |
range(1, 6), |
| 303 |
], |
| 304 |
"Top 5 highest mean basecall quality scores and their read lengths": [ |
| 305 |
"top5_quals", |
| 306 |
range(1, 6), |
| 307 |
], |
| 308 |
"Number, percentage and megabases of reads above quality cutoffs": [ |
| 309 |
"reads_above_qual", |
| 310 |
[">Q" + str(q) for q in stats[0]._qualgroups], |
| 311 |
], |
| 312 |
} |
| 313 |
for lf in sorted(long_features.keys()): |
| 314 |
output.write(lf + "\n") |
| 315 |
for index in range(5): |
| 316 |
output.write( |
| 317 |
"{}:\t{}\n".format( |
| 318 |
long_features[lf][1][index], |
| 319 |
feature_list( |
| 320 |
stats=stats, feature=long_features[lf][0], index=index |
| 321 |
), |
| 322 |
) |
| 323 |
) |
| 324 |
|
| 325 |
|
| 326 |
def feature_list(stats, feature, index=None, padding=15): |
| 327 |
if index is None: |
| 328 |
return " ".join( |
| 329 |
["{:>{},.1f}".format(s.__dict__[feature], padding) for s in stats] |
| 330 |
) |
| 331 |
else: |
| 332 |
return "\t".join( |
| 333 |
[ |
| 334 |
str(s.__dict__[feature][index]) |
| 335 |
if len(s.__dict__[feature]) > index |
| 336 |
else "NA" |
| 337 |
for s in stats |
| 338 |
] |
| 339 |
) |