-
Notifications
You must be signed in to change notification settings - Fork 0
/
ExtractPopMLSTStats
183 lines (172 loc) · 7.71 KB
/
ExtractPopMLSTStats
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
#!/usr/bin/env python3
# This is the seventh script in the PopMLST pipeline. Run it
# without arguments to get the usage. Please provide
# proper attribution if you use this code.
#
# https://github.com/marade/PopMLST
#
# author: M Radey (email: marad_at_uw.edu)
import os, sys, argparse, glob, gzip
from colorama import init as cinit
from colorama import Fore, Back, Style
# edit the paths below as necessary
version = "1.0.0"
def do_args():
desc = "Final PopMLST program to gather run stats"
parser = argparse.ArgumentParser(prog=os.path.basename(__file__),\
description=desc)
parser.add_argument("readdir", help="specifies the directory with " +\
"the raw Fastq files")
parser.add_argument("logdir", help="specifies the directory with " +\
"the Cutadapt log files")
parser.add_argument("outfile", help="specifies the output file")
return parser.parse_args()
def count_reads(fq):
n = ""
if fq.endswith('.gz'): n = gzip.open(fq)
else: n = open(fq)
lines = sum([1 for line in n])
rcount = int(lines / 4)
return rcount
def get_read_counts(rdir, ldir):
print(Fore.CYAN + "Getting read counts...")
sys.stdout.write(Style.RESET_ALL)
fqs = glob.glob(rdir + "/*_1.fastq.gz")
if len(fqs) == 0: fqs = glob.glob(indir + "/*_1.fastq")
counts = {}
for fq in fqs:
bname, ext = os.path.splitext(os.path.basename(fq))
if bname.endswith('.fastq'): bname = ".".join(bname.split('.')[:-1])
if bname.endswith('_1'): bname = "_".join(bname.split('_')[:-1])
print(Fore.BLUE + bname)
sys.stdout.write(Style.RESET_ALL)
counts[bname] = count_reads(fq)
print(Fore.CYAN + "Getting filtered read counts...")
sys.stdout.write(Style.RESET_ALL)
fqs = glob.glob(ldir + "/filtered/*.fastq.gz")
filtcounts = {}
alleles = []
for fq in fqs:
bname, ext = os.path.splitext(os.path.basename(fq))
if bname.endswith('.fastq'): bname = ".".join(bname.split('.')[:-1])
if bname.endswith('.merged'): bname = ".".join(bname.split('.')[:-1])
allele = bname.split('_')[-1]
if not allele in alleles: alleles.append(allele)
bname = "_".join(bname.split('_')[:-1])
print(Fore.BLUE + bname + " " + allele)
sys.stdout.write(Style.RESET_ALL)
if not bname in filtcounts: filtcounts[bname] = {}
filtcounts[bname][allele] = count_reads(fq)
print(Fore.CYAN + "Getting pre-merged read counts...")
sys.stdout.write(Style.RESET_ALL)
fqs = glob.glob(ldir + "/*.premerged.fastq.gz")
pcounts = {}
for fq in fqs:
bname, ext = os.path.splitext(os.path.basename(fq))
if bname.endswith('.fastq'): bname = ".".join(bname.split('.')[:-1])
if bname.endswith('.premerged'):
bname = ".".join(bname.split('.')[:-1])
allele = bname.split('_')[-1]
bname = "_".join(bname.split('_')[:-1])
print(Fore.BLUE + bname + " " + allele)
sys.stdout.write(Style.RESET_ALL)
if not bname in pcounts: pcounts[bname] = {}
pcounts[bname][allele] = count_reads(fq)
print(Fore.CYAN + "Getting merged read counts...")
sys.stdout.write(Style.RESET_ALL)
fqs = glob.glob(ldir + "/*.merged.fastq.gz")
mcounts = {}
for fq in fqs:
bname, ext = os.path.splitext(os.path.basename(fq))
if bname.endswith('.fastq'): bname = ".".join(bname.split('.')[:-1])
if bname.endswith('.merged'):
bname = ".".join(bname.split('.')[:-1])
allele = bname.split('_')[-1]
bname = "_".join(bname.split('_')[:-1])
print(Fore.BLUE + bname + " " + allele)
sys.stdout.write(Style.RESET_ALL)
if not bname in mcounts: mcounts[bname] = {}
mcounts[bname][allele] = count_reads(fq)
return counts, filtcounts, pcounts, mcounts, sorted(alleles)
def read_logs(indir):
print(Fore.CYAN + "Reading logs...")
sys.stdout.write(Style.RESET_ALL)
logs = glob.glob(indir + "/*.log")
rpro = {}
rwri = {}
for thislog in logs:
with open(thislog) as n:
name = ""
allele = ""
nreads = ""
nwrit = ""
for line in n:
if line.startswith('Command line parameters'):
name = line.rstrip('\n').split(' ')[-1].split('/')[-1]
name = name.split('.')[0]
allele = name.split('_')[-1]
name = "_".join(name.split('_')[:-1])
elif line.startswith('Total reads processed'):
nreads = line.rstrip('\n').split()[-1]
nreads = "".join(nreads.split(','))
elif line.startswith('Total written'):
nwrit = line.rstrip('\n').split()[-2]
nwrit = "".join(nreads.split(','))
if not name in rpro: rpro[name] = {}
rpro[name][allele] = nreads
if not name in rwri: rwri[name] = {}
rwri[name][allele] = nwrit
break
return rpro, rwri
def write_output(outfile, counts, filtcounts, pcounts, mcounts, rpro,\
rwri, alleles):
print(Fore.CYAN + "Writing output...")
sys.stdout.write(Style.RESET_ALL)
with open(outfile, 'w') as o:
for name in counts.keys():
o.write("\t".join([name, "raw", "all", str(counts[name])]) + "\n")
for allele in alleles:
if name in pcounts.keys():
if allele in pcounts[name].keys():
o.write("\t".join([name, "mer", allele,\
str(pcounts[name][allele])]) + "\n")
else: o.write("\t".join([name, "mer", allele, "0"]) + "\n")
else: o.write("\t".join([name, "mer", allele, "0"]) + "\n")
if name in rpro.keys():
if allele in rpro[name].keys():
o.write("\t".join([name, "pro", allele,\
rpro[name][allele]]) + "\n")
else: o.write("\t".join([name, "pro", allele, "0"]) + "\n")
else: o.write("\t".join([name, "pro", allele, "0"]) + "\n")
if name in rwri.keys():
if allele in rwri[name].keys():
o.write("\t".join([name, "wri", allele,\
rwri[name][allele]]) + "\n")
else: o.write("\t".join([name, "wri", allele, "0"]) + "\n")
else: o.write("\t".join([name, "wri", allele, "0"]) + "\n")
if name in mcounts.keys():
if allele in mcounts[name].keys():
o.write("\t".join([name, "trim", allele,\
str(mcounts[name][allele])]) + "\n")
else: o.write("\t".join([name, "trim", allele, "0"]) + "\n")
else: o.write("\t".join([name, "trim", allele, "0"]) + "\n")
if name in filtcounts.keys():
if allele in filtcounts[name].keys():
o.write("\t".join([name, "filt", allele,\
str(filtcounts[name][allele])]) + "\n")
else: o.write("\t".join([name, "filt", allele, "0"]) + "\n")
else: o.write("\t".join([name, "filt", allele, "0"]) + "\n")
def main():
# setup
args = do_args()
args.readdir = os.path.abspath(args.readdir)
args.logdir = os.path.abspath(args.logdir)
args.outfile = os.path.abspath(args.outfile)
rc, fc, pc, mc, anames = get_read_counts(args.readdir, args.logdir)
lpro, lwri = read_logs(args.logdir)
write_output(args.outfile, rc, fc, pc, mc, lpro, lwri, anames)
print(Fore.CYAN + "Done.")
sys.stdout.write(Style.RESET_ALL)
return 0
if __name__ == "__main__":
sys.exit(main())