1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
|
#!/usr/bin/python3
import json
import re
import sys
from collections import OrderedDict
from io import StringIO
from matplotlib import pyplot as plt
from os.path import basename, getsize, join
from pandas import DataFrame, Series, read_csv, concat
from shutil import copyfile
def get_plot_type_names():
return [x.replace(" ", "_") for x in get_store_data() if x not in get_skip_csv()]
def get_skip_csv():
return ["Adapter Content", "Overrepresented sequences"]
def get_skip():
return ["Basic Statistics", "Kmer Content", "Overrepresented sequences"]
def get_store_data():
return ['Sequence Length Distribution', 'Per sequence quality scores', 'Per sequence GC content', 'Adapter Content', 'Overrepresented sequences']
# convert result type to color (adapted to color blindness)
def get_color(value):
if (value == "pass"):
return "green"
elif (value == "fail"):
return "red"
else:
return "orange"
def combine_csv(inputcsvs, data_path):
files = dict()
for plot_type in get_plot_type_names():
files[plot_type] = open(data_path + "/" + plot_type + ".csv", "w")
for csv in inputcsvs:
f = open(csv, "r")
s = f.read()
f.close()
for plot_type in get_plot_type_names():
if plot_type in csv:
files[plot_type].write(s)
break
for plot_type in get_plot_type_names():
files[plot_type].close()
# creates CSV used for boxplotting
def createCSV(name, data, plot_type, path, trimmed, paired_end=True):
df = read_csv(StringIO("".join(data)), sep="\t")
name_groups = re.search(r"(?P<samplename>.*)_(?P<read>(R1|R2)).*", name)
# if exists(filename):
# summary = read_csv (filename, header = None, sep = ",")
# else:
# summary = DataFrame()
summary = DataFrame()
if plot_type == "Sequence Length Distribution":
try:
df["#Length"] = DataFrame(df["#Length"].str.split("-", expand=True), dtype=int).mean(axis=1)
except:
# Length is already of type int
pass
samplename = "NA"
if name_groups and paired_end:
samplename = name_groups.group("samplename")
df = concat([ Series([name_groups.group("samplename")]* len(df.index), name = "Sample") ,
Series([trimmed ]* len(df.index), name="Trimmed"),
Series([name_groups.group("read") ]* len(df.index), name="Read"),
df ],axis =1)
else:
samplename = name
df = concat([Series([name] * len(df.index), name="Sample"),
Series([trimmed] * len(df.index), name="type"),
Series([""] * len(df.index), name="read"),
df],axis=1)
if len(summary) !=0:
summary.columns = df.columns
filename = path + '/' + samplename + "_" + plot_type.replace(" ", "_") + ".csv"
summary = concat([summary, df], axis=0, ignore_index = True)
summary_path = open(filename, 'a')
summary.to_csv(summary_path, header = False, index = False)
summary_path.close()
def get_fastqc_results(parameter, fastqc_path, outdir, type, to_base64,
paired_end=True):
"""
Parses trimmomatics Sample(ID)_fastqc_data.txt files
While parsing fastqc_data records are transcribed into a csv file
Returns:
fastq_results (obj::`dict`):
Key (obj::`str`): Basename of File without "_fastqc"
Value (obj::`dict`): Statistics
Key (obj::`str`): Name of stat
Value: value
(int): number of sequences
(double): Percentage of overrepresented sequences
"""
skip = get_skip()
store_data = get_store_data()
total_seq = 0
overrepr_count = 0
adapter_content = []
fastqc_results = OrderedDict()
data = []
store = False
for fastqc in fastqc_path:
sample = OrderedDict()
name = basename(fastqc).replace("_fastqc","")
sample["img"]= OrderedDict()
if getsize(fastqc) != 0:
with open(join(fastqc, "fastqc_data.txt"), "r") as fastqc_data:
for line in iter(fastqc_data):
if line.startswith("Total Sequences"):
sample["Total Sequences"] = int(line.strip().split("\t"
)[-1])
total_seq += int(line.strip().split("\t")[-1])
elif line.startswith('>>END_MODULE'):
if len(data) > 0:
if key[0] in store_data:
if key[0] == 'Adapter Content':
ac = max(read_csv(StringIO("".join(data)),
sep="\t", index_col=0
).max().round(2))
adapter_content.append(ac)
sample["%Adapter content"] = ac
elif key[0] == "Overrepresented sequences":
ors= read_csv(StringIO("".join(data)),
sep="\t")["Count"].sum()
overrepr_count += ors
sample["%Overrepr sequences"] =int(ors)
else:
createCSV(name, data, key[0],
outdir, type,
paired_end=paired_end)
data = []
store = False
elif line.startswith('>>'):
key = line.split("\t")
key[0] = key[0].replace(">>", "")
if key[0] in store_data:
store = True
if not key[0] in skip:
img = {}
img["color"] = get_color(key[1].replace("\n",""))
try:
img["base64" ] = to_base64(
join(fastqc, "Images",
parameter["FastQC"][key[0]]))
img["path"] = join(fastqc, "Images",
parameter["FastQC"][key[0]])
sample["img"][key[0]] = img
except Exception as exp:
print(exp)
pass #img["base64"] = ""
if store and not line.startswith(">>"):
data.extend([line])
fastqc_results[name] = sample
try:
adapter = round(sum(adapter_content)/len(adapter_content) ,2)
except:
adapter = 0
if total_seq == 0:
overrepr = 0
else:
overrepr = round(100*overrepr_count / total_seq ,2)
#print(fastqc_results)
return fastqc_results, int(total_seq), overrepr , adapter
def write_sample_json(outfilename, samplename, snakeinput, cmd_input):
# Fastqc_dict is historical, omitted from output for now, but still present in call to
# maintain tuple unpacking order
fastqc_dict, total_seq ,overrepr_perc, adapter_content = (
get_fastqc_results(
(x for x in snakeinput.raw_fastqc if x[-4:] != ".txt" ),
data_path , "raw" ))
res = dict()
res["Sample"] = dict()
res["Sample"]["Name"] = samplename
res["Sample"]["TS"] = total_seq
res["Sample"]["PAC"] = adapter_content
res["Sample"]["PORS"] = overrepr_perc
res["Sample"]["POST"] = "N/A"
res["Sample"]["PACT"] = "N/A"
res["Sample"]["NRR"] = "N/A"
res["Sample"]["PRR"] = "N/A"
res["Sample"]["NAR"] = "N/A"
res["Sample"]["PAR"] = "N/A"
res["Sample"]["NC"] = "N/A"
res["Sample"]["PC"] = "N/A"
if not cmd_input["notrimming"]:
fastqc_dict, total_seq, overrepr_perc, adapter_content = (
get_fastqc_results(input.trimming_fastqc, data_path,"trimmed"))
trimmomatic_results = get_trimmomatic_result(list(snakeinput.trimming), list(snakeinput.trimming_params))
res["Sample"]["POST"] = overrepr_perc
res["Sample"]["PACT"] = adapter_content
res["Sample"]["NRR"] = trimmomatic_results["#Remaining Reads"]
res["Sample"]["PRR"] = trimmomatic_results["%Remaining Reads"]
if not cmd_input["nomapping"]:
mapping_results = get_bowtie2_result(str(snakeinput.mapping))
res["Sample"]["NAR"] = mapping_result["#AlignedReads"]
res["Sample"]["PAR"] = mapping_result["%AlignedReads"]
if not cmd_input["nokraken"]:
kraken_results = get_kraken_result(str(snakeinput.kraken), str(snakeoutput.kraken_plot))
res["Sample"]["NC"] = kraken_results["#Classified"]
res["Sample"]["PC"] = kraken_results["%Classified"]
json.dump(res, open(outfilename, "w"))
def write_summary_json_new(output, sample_json):
res = dict()
res["Headers"] = dict()
res["Headers"]["Name"] = "Sample name"
res["Headers"]["TS"] = "Total sequences"
res["Headers"]["PAC"] = "% Adapter content"
res["Headers"]["PORS"] = "% Overrepresented sequences"
res["Headers"]["POST"] = "% Overrepresented sequences (trimmed)"
res["Headers"]["PACT"] = "% Adapter content (trimmed)"
res["Headers"]["NRR"] = "# Remaining reads"
res["Headers"]["PRR"] = "% Remaining reads"
res["Headers"]["NAR"] = "# Aligned reads"
res["Headers"]["PAR"] = "% Aligned reads"
res["Headers"]["NC"] = "# Classified"
res["Headers"]["PC"] = "% Classified"
res["Samples"] = []
for sample in list(sample_json):
res["Samples"] += [json.load(open(str(sample)))["Sample"]]
json.dump(res, open(str(output.summary_json_new), "w"))
def write_summary_json(output, cmd_input, ruleinput, fastqc_csv, config, boxplots, shell, get_name, to_base64):
summary = OrderedDict()
summary["summary_img"] = {}
for infile, outfile in zip(fastqc_csv, list(output.fastqc_plots)):
shell("Rscript --vanilla {path}/Rscripts/boxplot.R" +
" {input} {output} '{title}' '{xlab}' '{ylab}'",
path = config["QCumber_path"],
input = infile,
output = outfile,
title = boxplots[get_name(infile)]["title"],
xlab = boxplots[get_name(infile)]["xlab"],
ylab = boxplots[get_name(infile)]["ylab"])
summary["summary_img"][ boxplots[get_name(infile)]["title"]] = (
to_base64(outfile))
if not cmd_input["nomapping"]:
insertsizes = []
samplenames = []
notzero = 0
for infile in ruleinput["insertsize"]:
f = open(infile, "r")
data = [int(x) for x in f.read().split(",")]
notzero += len([x for x in data if x != 0])
f.close()
insertsizes += [data]
samplenames += [get_name(infile).replace("_insertsizes", "")]
if notzero == 0:
insertsizes = [[0, 0, 0, 0, 0] for x in ruleinput["insertsize"]]
boxplt = plt.boxplot(insertsizes, 0, '', patch_artist=True)
for patch in boxplt['boxes']:
patch.set_facecolor('#E25845')
plt.xticks([x+1 for x in range(len(ruleinput["insertsize"]))], samplenames, rotation="vertical")
try:
plt.tight_layout() # This breaks when sample names are to large.
# It raises a value error: bottom cannot be
# larger than top in matplotlib 2.1.x
# Might get fixed in 2.2.x
except ValueError:
print("Warning: (%s:matplotlib) Some labels to "
"long for tight_layout plot" % __file__, file=sys.stderr)
plt.title("Fragment lengths")
plt.savefig(str(output.insertsize_plot), bbox_inches='tight')
summary["summary_img"]["Insertsize"] = to_base64(output.insertsize_plot)
plt.clf()
summary["Results"] = []
batch_plot = DataFrame()
for sample in sorted(list(ruleinput.sample_json)):
sample_dict = json.load(open(str(sample),"r"),
object_pairs_hook=OrderedDict)
summary["Results"].append(sample_dict )
df = DataFrame.from_dict(
dict((key, val) for key, val
in sample_dict.items()
if key in ["Total sequences", "#Remaining Reads",
"%Classified","%AlignedReads",
"%Adapter content",
"%Adapter content (trimmed)",
"%Overrepr sequences",
"%Overrepr sequences (trimmed)"]
),
orient="index").T
df.index=[sample_dict["Name"]]
batch_plot=batch_plot.append(df)
if not cmd_input["notrimming"]:
batch_plot["Total sequences"] = (batch_plot["Total sequences"] -
batch_plot["#Remaining Reads"])
batch_plot[["#Remaining Reads","Total sequences"]].plot.bar(
stacked=True, edgecolor='black',
title="Number of Reads", alpha=0.9)
else:
batch_plot["Total sequences"].plot.bar(
stacked=True, edgecolor='black',
title="Number of Reads", alpha=0.9)
legend = plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.savefig(str(output.n_read_plot),
bbox_extra_artists=(legend,), bbox_inches='tight')
plt.close()
summary["summary_img"]["n_read"] = to_base64(str(output.n_read_plot))
try:
if not cmd_input["notrimming"]:
batch_plot[
["%Adapter content",
"%Adapter content (trimmed)"]
].plot.bar(edgecolor='black',
title = "Adapter content [%]",alpha=0.9)
else:
batch_plot["%Adapter content"].plot.bar(
edgecolor='black',title="Adapter content [%]", alpha=0.9)
legend = plt.legend(bbox_to_anchor=(1.05, 1),
loc=2, borderaxespad=0.)
plt.savefig("QCResults/_data/adapter.png" ,
bbox_extra_artists=(legend,),bbox_inches='tight')
plt.close()
summary["summary_img"]["adapter"] = to_base64(data_path +
"/adapter.png")
except:
pass
try:
if not cmd_input["notrimming"]:
batch_plot[
["%Overrepr sequences",
"%Overrepr sequences (trimmed)"]
].plot.bar(edgecolor='black',
title="Overrepresented sequences [%]",
alpha=0.9)
else:
batch_plot["%Overrepr sequences"].plot.bar(
edgecolor='black', title="Overrepresented sequences [%]",
alpha=0.9)
legend = plt.legend(bbox_to_anchor=(1.05, 1),
loc=2, borderaxespad=0.)
plt.savefig("QCResults/_data/overrepr_seq.png",
bbox_extra_artists=(legend,), bbox_inches='tight')
plt.close()
summary["summary_img"]["overrepr_seq"] = to_base64(
data_path + "/overrepr_seq.png")
except:
pass
if not cmd_input["nomapping"]:
batch_plot["%AlignedReads"].plot.bar(
edgecolor='black', title = "Map to Reference [%]",alpha=0.9)
plt.savefig(str(output.mapping_plot), bbox_inches='tight')
summary["summary_img"]["mapping"] = to_base64(
str(output.mapping_plot))
plt.close()
if not cmd_input["nokraken"]:
summary["summary_img"]["kraken"] = to_base64(ruleinput.kraken_batch)
json.dump(summary, open(str(output.summary_json), "w"))
|