-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQ30singleFileShuffledFastq.py
205 lines (160 loc) · 8.14 KB
/
Q30singleFileShuffledFastq.py
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
import os, sys, re, csv, statistics
import argparse, logging, warnings
from Bio import SeqIO
from Bio.SeqIO.QualityIO import FastqGeneralIterator
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from pathlib import Path
#from tabulate import tabulate
## Script for plotting average PHRED score per read and outputting data frames of PHRED averages
## Requires Biopython, Numpy, and Matplotlib
## Required Input: Two shuffled, paired-end .fastq files with equal numbers of forward (R1) and reverse (R2) reads
## Output: Two .png files and/or two .csv files
## Function: A closure for file extension checking
def ext_check(expected_ext, openner):
def extension(filename):
if not filename.lower().endswith(expected_ext):
raise ValueError()
return openner(filename)
return extension
## Check input file for zero-length
def check_for_empty(fastq_file):
path1 = Path(fastq_file)
if(path1.stat().st_size == 0):
raise ArgumentTypeError(f'{fastq_file} cannot be empty')
def readable_dir(prospective_dir):
if not os.path.isdir(prospective_dir):
raise argparse.ArgumentTypeError("readable_dir:{0} is not a valid path".format(prospective_dir))
if os.access(prospective_dir, os.R_OK):
if( not prospective_dir.endswith("/") ):
prospective_dir = prospective_dir + "/"
return prospective_dir
else:
raise argparse.ArgumentTypeError("readable_dir:{0} is not a readable dir".format(prospective_dir))
def getIsolateStr(filePathString):
splitStr = re.split(r'/', string=filePathString)
fileNameIdx = len(splitStr) - 1
isolateString = re.split(r'\.', string=splitStr[fileNameIdx])
return(isolateString[0])
origWD = os.getcwd()
## Two shuffled, paired-end .fastq files expected as input
parser = argparse.ArgumentParser(description='Computes sequence lengths and average PHRED for shuffled paired reads in fastq', usage="Q30singleFileShuffledFastq.py filepath/filename.fastq")
parser.add_argument('filename', type=ext_check('.fastq', argparse.FileType('r')), nargs='+')
## outputType enables suppression of dataframe (.csv) output files or suppression of histogram (.png) output files
parser.add_argument('--outputType', '-o', default='F', choices=['F', 'P', 'C', 'Q'], help="--outputType F for full output (plots and .csv), P for plots only, C for csv file with no plot, and Q for Q30 STDOUT summary only.")
parser.add_argument('--paired', '-u', default='F', choices=['T', 'F'], help="--paired F to calculate a average PHRED for all reads together or --paired T for input file of forward and reverse shuffled together.")
## output folder
parser.add_argument('--outDir', '-D', type=readable_dir, required=True, action='store')
args = parser.parse_args()
outFolder = args.outDir
outFilePath = origWD + '/' + outFolder + '/'
## File names used in plot titles
myTitle1 = re.split(r'[\.\/]', args.filename[0].name)
csvRow1 = []
forwardName = []
reverseName = []
allName = []
allAvg = []
forwardLen1 = []
reverseLen1 = []
forwardAvg1 = []
reverseAvg1 = []
iter = 0
myFastq1 = open(args.filename[0].name, "r")
outputFileString = getIsolateStr(args.filename[0].name)
## Throw exception for zero-length file
check_for_empty(args.filename[0].name)
r1Q30_1 = 0
r1Len_1 = 1
r2Q30_1 = 0
r2Len_1 = 1
for record in SeqIO.parse(myFastq1, "fastq"):
if(iter % 2 == 0):
forwardName.append(record.id)
allName.append(record.id)
j = 0
r1Len_1 = r1Len_1 + len(record.seq)
while( j < len(record.seq)):
if(record.letter_annotations["phred_quality"][j] >= 30):
r1Q30_1 = r1Q30_1 + 1
j = j + 1
forwardAvg1.append(statistics.mean(record.letter_annotations["phred_quality"]))
allAvg.append(statistics.mean(record.letter_annotations["phred_quality"]))
elif(iter % 2 == 1):
reverseName.append(record.id)
allName.append(record.id)
strand = record.description.split(" ")
j = 0
r2Len_1 = r2Len_1 + len(record.seq)
while( j < len(record.seq) ):
if(record.letter_annotations["phred_quality"][j] >= 30 ):
r2Q30_1 = r2Q30_1 + 1
j = j + 1
reverseAvg1.append(statistics.mean(record.letter_annotations["phred_quality"]))
allAvg.append(statistics.mean(record.letter_annotations["phred_quality"]))
iter = iter + 1
if(args.paired == 'T'):
print("%s, Forward_Q30%%: %2.2f, Reverse_Q30%%: %2.2f" % (myTitle1[len(myTitle1) - 2], 100*r1Q30_1/r1Len_1, 100*r2Q30_1/r2Len_1))
else:
print("%s, Paired_Q30%%: %2.2f" % (myTitle1[len(myTitle1) - 2], 100*(r1Q30_1 + r2Q30_1)/(r1Len_1 + r2Len_1)))
if(args.outputType == 'Q'):
sys.exit()
if((args.outputType != 'C') and (args.paired == 'T')):
SMALL_SIZE = 20
MEDIUM_SIZE = 24
BIG_SIZE = 30
fig1, axes1 = plt.subplots(nrows=2, ncols=1, sharex=True, sharey=True, figsize=(14,20))
## Plot PHRED Quality for R1 reads as 1D histogram
axes1[0].xaxis.label.set_size(MEDIUM_SIZE)
axes1[0].yaxis.label.set_size(MEDIUM_SIZE)
axes1[0].tick_params(axis='x', labelsize=SMALL_SIZE)
axes1[0].tick_params(axis='y', labelsize=SMALL_SIZE)
axes1[0].hist(forwardAvg1, bins = 40, color='blue')
axes1[0].set_title("R1 " + myTitle1[len(myTitle1) - 2], fontsize = BIG_SIZE)
axes1[0].set(ylabel='Read Counts')
## Plot PHRED Quality for R2 reads as 1D histogram
axes1[1].xaxis.label.set_size(MEDIUM_SIZE)
axes1[1].yaxis.label.set_size(MEDIUM_SIZE)
axes1[1].tick_params(axis='x', labelsize=SMALL_SIZE)
axes1[1].tick_params(axis='y', labelsize=SMALL_SIZE)
axes1[1].hist(reverseAvg1, bins = 40, color='red')
axes1[1].set_title("R2 " + myTitle1[len(myTitle1) - 2], fontsize = BIG_SIZE)
axes1[1].set(ylabel='Read Counts')
axes1[1].set(xlabel='Average Read Quality')
fig1.savefig(outFilePath + '/' + outputFileString + '_fwd_and_rev_PHRED.png')
if((args.outputType != 'C') and (args.paired == 'F')):
SMALL_SIZE = 20
MEDIUM_SIZE = 24
BIG_SIZE = 30
fig1, axes1 = plt.subplots(nrows=1, ncols=1, sharex=True, sharey=True, figsize=(14,11))
## Plot PHRED Quality for R1 reads as 1D histogram
axes1.xaxis.label.set_size(MEDIUM_SIZE)
axes1.yaxis.label.set_size(MEDIUM_SIZE)
axes1.tick_params(axis='x', labelsize=SMALL_SIZE)
axes1.tick_params(axis='y', labelsize=SMALL_SIZE)
axes1.hist(forwardAvg1, bins = 40, color='blue')
axes1.set_title("All " + myTitle1[len(myTitle1) - 2], fontsize = BIG_SIZE)
axes1.set(ylabel='Read Counts')
axes1.set(xlabel='Average Read Quality')
fig1.savefig(outFilePath + '/' + outputFileString + '_all_PHRED.png')
if((args.outputType != 'P') and (args.paired == 'T')):
dfMiSeqPHRED = pd.DataFrame()
stringList = []
stringFwdList = []
stringRevList = []
for i in forwardAvg1:
stringFwdList.append(str(round(float(i), 2)))
for j in reverseAvg1:
stringRevList.append(str(round(float(j), 2)))
pairedMiSeqPHRED = { "R1_Read_ID" : forwardName, "R1_PHRED" : stringFwdList, "R2_PHRED" : stringRevList }
dfMiSeqPHRED = pd.DataFrame(pairedMiSeqPHRED)
dfMiSeqPHRED.to_csv(outFilePath + '/' + outputFileString + '_fwd_and_rev_PHRED.csv', index=False)
if((args.outputType != 'P') and (args.paired == 'F')):
dfMiSeqPHRED = pd.DataFrame()
stringList = []
for i in allAvg:
stringList.append(str(round(float(i), 2)))
singleMiSeqPHRED = {"Read_ID" : allName, "Read_PHRED" : stringList }
dfMiSeqPHRED = pd.DataFrame(singleMiSeqPHRED)
dfMiSeqPHRED.to_csv(outFilePath + '/' + outputFileString + '_PHRED.csv', index=False)