Debian Codegraph @

pytools/filter.py

raw symbols SCIP
1 #! /usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 """
5 stand alone filter script based on jgi-rqc-pipeline/filter/fastq_filter2.py v3.2.8
6
7 Command
8 $ filter.py -f FASTQ.GZ -o OUT_DIR --skip-blast -html
9
10 Outputs
11 - normal filter outputs + index.html
12
13 Created: March 15, 2018
14
15 Shijie Yao ([email protected])
16
17 Revision:
18
19 """
20
21 import os
22 import sys
23 import argparse
24 import datetime
25 import shutil
26 import glob
27 import re
28 # import numpy as np
29 # import matplotlib
30 # matplotlib.use("Agg") ## This needs to skip the DISPLAY env var checking
31 # import matplotlib.pyplot as plt
32 # import mpld3
33 from pprint import pprint
34
35 ## append the pipeline lib and tools relative path:
36 SRC_ROOT = os.path.abspath(os.path.dirname(os.path.abspath(__file__)))
37 sys.path.append(SRC_ROOT + "/lib") # common
38
39 import rqc_fastq as fastqUtil
40 from common import get_logger, get_status, checkpoint_step, set_colors, get_subsample_rate, append_rqc_file, append_rqc_stats
41 from os_utility import run_sh_command, make_dir_p
42
43 from rqc_utility import get_dict_obj, pipeline_val
44 from readqc import do_html_body as do_readqc_html_body
45 from html_utility import html_tag
46
47
48 ## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
49 ## global vars
50 VERSION = "1.0.0"
51 SCRIPT_NAME = __file__
52 logLevel = "DEBUG"
53 DEBUG = False
54 color = {}
55 color = set_colors(color, True)
56
57 READQC_DIR = 'filtered-readqc'
58
59 PYDIR = os.path.abspath(os.path.dirname(__file__))
60 BBDIR = os.path.join(PYDIR, os.path.pardir)
61
62 FILTER_READ_COUNT = "read count"
63 FILTER_READ_SAMPLED_COUNT = "read sampled count"
64
65 STATUS_LOG_FNAME = 'status.log'
66 BB_STATS_LIST_FILE_NAME = 'filterStats.txt'
67 STATS_LIST_FILE_NAME = 'filter-stats.txt'
68
69 PIPE_START = 'start'
70 RQCFILTER_START = 'start rqcfilter'
71 RQCFILTER_END = 'end rqcfilter'
72 POST_START = 'start post process'
73 POST_END = 'end post process'
74 QC_START = 'start qc'
75 QC_END = 'end qc'
76 HTML_START = 'start html generation'
77 HTML_END = 'end html generation'
78 PIPE_COMPLETE = 'complete'
79
80 STEP_ORDER = {
81 PIPE_START : 0,
82
83 RQCFILTER_START : 10,
84 # rqcfilter.sh recorded steps:
85 'clumpify start' : 11,
86 'clumpify finish' : 12,
87 'ktrim start' : 20,
88 'ktrim finish' : 21,
89 'delete temp files start' : 30,
90 'delete temp files finish' : 31,
91 'filter start' : 40,
92 'filter finish' : 41,
93 'delete temp files start' : 50,
94 'delete temp files finish' : 51,
95 'short filter start' : 60,
96 'short filter finish' : 61,
97 'delete temp files start' : 70,
98 'delete temp files finish' : 71,
99 'removeCommonMicrobes start' : 80,
100 'removeCommonMicrobes finish' : 81,
101 'delete temp files start' : 90,
102 'delete temp files finish' : 91,
103 'dehumanize start' : 100,
104 'dehumanize finish' : 101,
105 'delete temp files start' : 110,
106 'delete temp files finish' : 111,
107 'merge start' : 120,
108 'merge finish' : 121,
109 'khist start' : 130,
110 'khist finish' : 131,
111 'rqcfilter complete' : 200,
112
113
114 RQCFILTER_END : 300,
115
116 POST_START : 381,
117 POST_END : 382,
118
119 QC_START : 400,
120 QC_END : 410,
121
122 HTML_START : 420,
123 HTML_END : 430,
124
125 PIPE_COMPLETE : 999
126 }
127
128 FILTER_METHODS_TXT = {"DNA": "dna.txt",
129 "FUNGAL": "fungal.txt",
130 "METAGENOME": "metagenome.txt",
131 "VIRAL-METAGENOME": "viral-metagenome.txt",
132 "ISO": "iso.txt",
133 "SAG": "sag.txt",
134 "CELL-ENRICHMENT": "cell-enrichment.txt",
135 "PLANT-2X150": "plant-2x150.txt",
136 "PLANT-2X250": "plant-2x250.txt",
137 "RNA": "rna.txt",
138 "RNAWOHUMAN": "rnawohuman.txt",
139 "3PRIMERNA": "3primerna.txt",
140 "SMRNA": "smrna.txt",
141 "METATRANSCRIPTOME": "mtaa.txt",
142 "MTF": "mtaa.txt",
143 "LFPE": "lfpe.txt",
144 "CLRS": "clrs.txt",
145 "CLIP-PE": "clip-pe.txt",
146 "NEXTERA-LMP": "nextera-lmp.txt",
147 "NEXTERA": "nextera-lmp.txt",
148 "NEXTSEQ": "nextseq.txt",
149 "ITAG": "itag.txt",
150 "MICROTRANS": "microtrans.txt",
151 "BISULPHITE": "bisulphite.txt",
152 "CHIPSEQ": "chip-seq.txt"}
153
154 ## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
155 ## pipeline function definitions
156 def log_and_print(msg):
157 print(msg)
158 log.info(msg)
159
160
161 """
162 Run rqcfilter.sh
163
164 @param fastq: the raw fastq input file [input of filtering]
165 @param outDir: the output directory
166 @param prodType: product type
167 @param status: current status
168 @return outFastqFile, outRrnaFastqFile
169
170 """
171 def run_rqcfilter(infastq, outDir, prodType, status, enableRmoveMicrobes, enableAggressive, disableRmoveMicrobes, disableClumpify, taxList, rdb, log):
172 log_and_print("\n\n%s - RUN RQCFILTER <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<%s\n" % (color['pink'], color['']))
173
174 make_dir_p(outDir)
175 opt = None
176
177 extraOptions = ""
178 optionFile = ""
179
180 if prodType.endswith("-OLD"):
181 extraOptions = " barcodefilter=f chastityfilter=f"
182 prodType = prodType.replace("-OLD", "")
183
184 if prodType in FILTER_METHODS_TXT:
185 optionFile = os.path.join(SRC_ROOT, "filter_param/", FILTER_METHODS_TXT[prodType].replace(".txt", ".config"))
186 log_and_print("Filter option file: %s" % optionFile)
187 opt = open(optionFile, 'r').readline().rstrip()
188 else:
189 log_and_print("The product type, %s, is not supported yet." % prodType)
190 sys.exit(2)
191
192 assert (opt), "Null filter options."
193
194 if prodType in ("METATRANSCRIPTOME", "MTF"):
195 if infastq.endswith(".gz"):
196 opt += " outribo=%s " % (os.path.basename(infastq).replace(".fastq", ".rRNA.fastq"))
197 else:
198 opt += " outribo=%s " % (os.path.basename(infastq).replace(".fastq", ".rRNA.fastq.gz"))
199
200 if enableRmoveMicrobes:
201 if opt.find("removemicrobes=f") != -1:
202 opt = opt.replace("removemicrobes=f", "removemicrobes=t")
203 opt += " removemicrobes=t "
204
205 if disableRmoveMicrobes:
206 if opt.find("removemicrobes=t") != -1:
207 opt = opt.replace("removemicrobes=t", "removemicrobes=f")
208 else: opt += " removemicrobes=f "
209
210 if enableAggressive:
211 opt += " aggressive=t microbebuild=3 "
212
213 if taxList:
214 opt += " taxlist=%s " % (taxList)
215
216 ## Temp set clumpify=t for all prod types (RQC-890)
217 if not disableClumpify:
218 opt += " clumpify=t "
219 else:
220 opt += " clumpify=f "
221
222 opt += " tmpdir=null "
223 opt += extraOptions
224
225
226 cmd = os.path.join(BBDIR, "rqcfilter.sh")
227 filterLogFile = os.path.join(outDir, "filter.log")
228 cmdStr = "%s in=%s path=%s %s usejni=f rqcfilterdata=%s > %s 2>&1" % (cmd, infastq, outDir, opt, rdb, filterLogFile)
229
230 rtn = [None, status]
231 outFastqFile = None
232
233 shFileName = "%s/filter.sh" % outDir
234
235 def find_filtered_fastq(adir):
236 outFastqFile = None
237
238 searchPatt = os.path.join(adir, "*.fastq.gz")
239 outFastqFileList = glob.glob(searchPatt)
240
241 assert len(outFastqFileList) >= 1, "ERROR: cannot find *.fastq.gz output file."
242 for f in outFastqFileList:
243 f = os.path.basename(f)
244 t = f.split(".")
245
246 if t[-3] not in ("frag", "singleton", "unknown", "rRNA", "lmp"):
247 filterCode = t[-3]
248 elif t[-3] == "lmp": ## nextera
249 filterCode = t[-4]
250
251 if len(t) == 7: ## ex) 12345.1.1234.ACCCC.anqdpht.fastq.gz
252 fileNamePrefix = '.'.join(t[:4])
253 elif len(t) == 6: ## ex) 6176.5.39297.anqrpht.fastq.gz
254 fileNamePrefix = '.'.join(t[:3])
255 else:
256 log.warning("Unexpected filtered file name, %s", outFastqFileList)
257 fileNamePrefix = '.'.join(t[:-3])
258 log_and_print("Use %s as file prefix." %fileNamePrefix)
259
260 assert filterCode and fileNamePrefix, "ERROR: unexpected filter file name: %s" % (outFastqFileList)
261
262 of = os.path.join(adir, '.'.join([fileNamePrefix, filterCode, "fastq.gz"]))
263 lof = os.path.join(adir, '.'.join([fileNamePrefix, filterCode, "lmp.fastq.gz"]))
264 if os.path.isfile(of):
265 outFastqFile = of
266 elif os.path.isfile(lof):
267 outFastqFile = lof
268 else:
269 log.error("Cannot find fastq.gz file.")
270
271 # rename output file to *.filtered.fastq.gz
272 f = os.path.basename(outFastqFile)
273 t = f.split(".")
274 if t[-3] != 'filtered':
275 fto = os.path.join(adir, '.'.join(['.'.join(t[:-3]), 'filtered', "fastq.gz"]))
276 shutil.move(outFastqFile, fto)
277 outFastqFile = fto
278
279 return outFastqFile
280
281 def find_filter_number(outFastqFile):
282 filteredReadNum = fastqUtil.check_fastq_format(outFastqFile) / 4
283
284 if filteredReadNum < 0:
285 log_and_print("RUN RQCFILTER - filtered fastq format error: %s." % outFastqFile)
286 return filteredReadNum
287
288 if STEP_ORDER[status] < STEP_ORDER[RQCFILTER_END]:
289
290 create_shell(shFileName, (cmdStr,))
291
292 log_and_print("rqcfilter cmd=[%s]" % cmdStr)
293 log_and_print("sh file name=[%s]" % shFileName)
294
295 stdOut, stdErr, exitCode = run_sh_command(shFileName, True, log, True) ## stdOut of 0 is success
296
297 if exitCode != 0:
298 log.error("Failed to run : %s, stdout : %s, stderr: %s", shFileName, stdOut, stdErr)
299 return rtn
300
301 outFastqFile = find_filtered_fastq(outDir)
302
303
304 filteredReadNum = find_filter_number(outFastqFile)
305 log_and_print("Read counts after RQCFILTER step = %d" % filteredReadNum)
306
307 log_and_print("RUN RQCFILTER - completed")
308 checkpoint(RQCFILTER_END, status)
309 status = RQCFILTER_END
310
311 if filteredReadNum == 0:
312 log.warning("No reads left after filtering")
313 checkpoint(PIPE_COMPLETE, status)
314 with open(BB_STATS_LIST_FILE_NAME, 'a') as fh:
315 write_stats(fh, FILTER_READ_COUNT, 0, log)
316 write_stats(fh, FILTER_READ_BASE_COUNT, 0, log)
317 else:
318 log_and_print("No need to rerun RQCFILTER step, get filtered files and stats ... ")
319 outFastqFile = find_filtered_fastq(outDir)
320
321 rtn = [outFastqFile, status]
322 return rtn
323
324 """
325 gzip the final filtered fastq file, and generate STATS_LIST_FILE_NAME log files.
326
327 @param fastq: the raw fastq file
328 @param outDir: output dir
329 @param filteredFastq: the filtered fastq file
330 @param status: where the pipeline was at by last run
331 @param log
332
333 @return filteredFastq or None if error
334 """
335 def post_process(fastq, outDir, filteredFastq, status, log):
336 ## obtain read counts from input and filtered fastq files and save the values to STATS_LIST_FILE_NAME file;
337 ## compress the filtered fastq file
338 log_and_print("\n\n%s - RUN POST PROCESS <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<%s\n" % (color['pink'], color['']))
339 if STEP_ORDER[status] < STEP_ORDER[POST_END]:
340 checkpoint(POST_START, status)
341 rawCnt = 0
342 rawBaseCnt = 0
343 newCnt = 0
344 newBaseCnt = 0
345
346 stats = get_dict_obj(BB_STATS_LIST_FILE_NAME)
347 rawCnt = pipeline_val('inputReads', {'type': 'int', 'vtype': 'numeric'}, stats)
348 rawBaseCnt = pipeline_val('inputBases', {'type': 'int', 'vtype': 'numeric'}, stats)
349 newCnt = pipeline_val('outputReads', {'type': 'int', 'vtype': 'numeric'}, stats)
350 newBaseCnt = pipeline_val('outputBases', {'type': 'int', 'vtype': 'numeric'}, stats)
351
352 readCounts = {}
353
354 readRmPct = 100.0 * ((rawCnt - newCnt) / float(rawCnt))
355 baseRmPct = 100.0 * ((rawBaseCnt - newBaseCnt) / float(rawBaseCnt))
356 readCounts['readRmPct'] = '%.3f' % readRmPct
357 readCounts['baseRmPct'] = '%.3f' % baseRmPct
358
359 refStats = {}
360 filterLogStat = {}
361
362 cardinality = None
363 bbdukVersion = None
364 bbmapVersion = None
365
366 if os.path.isfile("filter.log"):
367
368 with open(os.path.join(outDir, "filter.log"), "r") as FLFH:
369 isContamNumChecked = False ## Contamination will be done twice for removeribo or for MTF
370 isKtrimmedTotalRemovedNumChecked = False ## for parsing "Total Removed" after ktrimming
371
372 for l in FLFH:
373 if l.startswith("Input:"):
374 toks = re.findall("(\d+.\d*)", l.rstrip())
375 assert len(toks) == 2
376 if 'adaptertriminput' not in filterLogStat:
377 filterLogStat["adaptertriminput"] = {"numreads": toks[0], "numbases": toks[1]}
378 elif 'contamtriminput' not in filterLogStat:
379 filterLogStat["contamtriminput"] = {"numreads": toks[0], "numbases": toks[1]}
380
381 elif l.startswith("FTrimmed:"):
382 toks = re.findall("(\d+.\d*)", l.rstrip())
383 assert len(toks) == 4
384 filterLogStat["ftrimmed"] = {"numreads": toks[0], "percreads": toks[1], "numbases": toks[2], "percbases": toks[3]}
385 elif l.startswith("KTrimmed:"):
386 toks = re.findall("(\d+.\d*)", l.rstrip())
387 assert len(toks) == 4
388 filterLogStat["ktrimmed"] = {"numreads": toks[0], "percreads": toks[1], "numbases": toks[2], "percbases": toks[3]}
389 isKtrimmedTotalRemovedNumChecked = True
390
391 ## RQCSUPPORT-1987
392 elif l.startswith("Total Removed:") and isKtrimmedTotalRemovedNumChecked:
393 toks = re.findall("(\d+.\d*)", l.rstrip())
394 assert len(toks) == 4
395 filterLogStat["ktrimmed_total_removed"] = {"numreads": toks[0], "percreads": toks[1], "numbases": toks[2], "percbases": toks[3]}
396 isKtrimmedTotalRemovedNumChecked = False
397
398 elif l.startswith("Trimmed by overlap:"):
399 toks = re.findall("(\d+.\d*)", l.rstrip())
400 assert len(toks) == 4
401 filterLogStat["trimmedbyoverlap"] = {"numreads": toks[0], "percreads": toks[1], "numbases": toks[2], "percbases": toks[3]}
402
403 elif l.startswith("Result:"):
404 toks = re.findall("(\d+.\d*)", l.rstrip())
405 assert len(toks) == 4
406 if 'adaptertrimresult' not in filterLogStat:
407 filterLogStat["adaptertrimresult"] = {"numreads": toks[0], "percreads": toks[1], "numbases": toks[2], "percbases": toks[3]}
408 elif 'contamtrimresult' not in filterLogStat:
409 filterLogStat["contamtrimresult"] = {"numreads": toks[0], "percreads": toks[1], "numbases": toks[2], "percbases": toks[3]}
410
411 elif l.startswith("Unique 31-mers:"):
412 toks = re.findall("(\d+.\d*)", l.rstrip())
413 assert len(toks) == 2 or len(toks) == 1
414 if 'adaptertrimunique31mers' not in filterLogStat:
415 if len(toks) == 2:
416 filterLogStat["adaptertrimunique31mers"] = {"num": toks[1]}
417 else:
418 filterLogStat["adaptertrimunique31mers"] = {"num":"0"}
419 else:
420 if len(toks) == 2:
421 filterLogStat["contamtrimunique31mers"] = {"num": toks[1]}
422 else:
423 filterLogStat["contamtrimunique31mers"] = {"num":"0"}
424
425 elif not isContamNumChecked and l.startswith("Contaminants:"):
426 toks = re.findall("(\d+.\d*)", l.rstrip())
427 assert len(toks) == 4
428 filterLogStat["contaminants"] = {"numreads": toks[0], "percreads": toks[1], "numbases": toks[2], "percbases": toks[3]}
429 isContamNumChecked = True
430
431 elif l.startswith("QTrimmed:"):
432 toks = re.findall("(\d+.\d*)", l.rstrip())
433 assert len(toks) == 4
434 filterLogStat["qtrimmed"] = {"numreads": toks[0], "percreads": toks[1], "numbases": toks[2], "percbases": toks[3]}
435
436 elif l.startswith("Short Read Discards:"):
437 toks = re.findall("(\d+.\d*)", l.rstrip())
438 assert len(toks) == 4
439 filterLogStat["shortreaddiscards"] = {"numreads": toks[0], "percreads": toks[1], "numbases": toks[2], "percbases": toks[3]}
440 elif l.startswith("Low quality discards:"):
441 toks = re.findall("(\d+.\d*)", l.rstrip())
442 assert len(toks) == 4
443 filterLogStat["lowqualitydiscards"] = {"numreads": toks[0], "percreads": toks[1], "numbases": toks[2], "percbases": toks[3]}
444
445 elif l.startswith("BBDuk version"):
446 toks = re.findall("(\d+.\d*)", l.rstrip())
447 assert len(toks) == 1
448 bbdukVersion = toks[0]
449 elif l.startswith("BBMap version"):
450 toks = re.findall("(\d+.\d*)", l.rstrip())
451 assert len(toks) == 1
452 bbmapVersion = toks[0]
453
454 ## BBDuk 36.12 06272016
455 elif l.startswith("Adapter Sequence Removed:"):
456 toks = re.findall("(\d+.\d*)", l.rstrip())
457 assert len(toks) == 4
458 filterLogStat["adaptersequenceremoved"] = {"numreads": toks[0], "percreads": toks[1], "numbases": toks[2], "percbases": toks[3]}
459 elif l.startswith("Synthetic Contam Sequence Removed:"):
460 toks = re.findall("(\d+.\d*)", l.rstrip())
461 assert len(toks) == 4
462 filterLogStat["syntheticcontamsequenceremoved"] = {"numreads": toks[0], "percreads": toks[1], "numbases": toks[2], "percbases": toks[3]}
463
464 ## 08112016
465 elif l.startswith("Short Synthetic Contam Sequence Removed:"):
466 toks = re.findall("(\d+.\d*)", l.rstrip())
467 assert len(toks) == 4
468 filterLogStat["shortsyntheticcontamsequenceremoved"] = {"numreads": toks[0], "percreads": toks[1], "numbases": toks[2], "percbases": toks[3]}
469
470 elif l.startswith("Ribosomal Sequence Removed:"):
471 toks = re.findall("(\d+.\d*)", l.rstrip())
472 assert len(toks) == 4
473 filterLogStat["ribosomalsequenceremoved"] = {"numreads": toks[0], "percreads": toks[1], "numbases": toks[2], "percbases": toks[3]}
474
475 ## BBMap 36.12 06272016
476 elif l.startswith("Human Sequence Removed:"):
477 toks = re.findall("(\d+.\d*)", l.rstrip())
478 assert len(toks) == 4
479 filterLogStat["humansequenceremoved"] = {"numreads": toks[0], "percreads": toks[1], "numbases": toks[2], "percbases": toks[3]}
480
481 ## RQC-862, RQC-880
482 elif l.startswith("Microbial Sequence Removed:"):
483 toks = re.findall("(\d+.\d*)", l.rstrip())
484 assert len(toks) == 4
485 filterLogStat["microbialremoved"] = {"numreads": toks[0], "percreads": toks[1], "numbases": toks[2], "percbases": toks[3]}
486
487
488 ##
489 ## refStats.txt format
490 ##
491 ## name %unambiguousReads unambiguousMB %ambiguousReads ambiguousMB unambiguousReads ambiguousReads
492 ## human_masked 85.24693 498.92052 0.09378 0.55290 3350692 3686
493 ## mouse_masked 0.03765 0.21670 0.10802 0.63690 1480 4246
494 ## cat_masked 0.01862 0.09568 0.02514 0.14820 732 988
495 ## dog_masked 0.00697 0.03815 0.01384 0.08160 274 544
496 ##
497 if os.path.isfile("refStats.txt"):
498 refStatsFile = os.path.join(outDir, "refStats.txt")
499 with open(refStatsFile) as RFH:
500 ## Need to report 0 if nothing matched
501 refStats['human'] = {"unambiguousReadsPerc":"0", "unambiguousMB":"0", "ambiguousReadsPerc":"0", "ambiguousMB":"0", "unambiguousReads":"0", "ambiguousReads":"0", "totalPerc":"0"}
502 refStats['cat'] = {"unambiguousReadsPerc":"0", "unambiguousMB":"0", "ambiguousReadsPerc":"0", "ambiguousMB":"0", "unambiguousReads":"0", "ambiguousReads":"0", "totalPerc":"0"}
503 refStats['dog'] = {"unambiguousReadsPerc":"0", "unambiguousMB":"0", "ambiguousReadsPerc":"0", "ambiguousMB":"0", "unambiguousReads":"0", "ambiguousReads":"0", "totalPerc":"0"}
504 refStats['mouse'] = {"unambiguousReadsPerc":"0", "unambiguousMB":"0", "ambiguousReadsPerc":"0", "ambiguousMB":"0", "unambiguousReads":"0", "ambiguousReads":"0", "totalPerc":"0"}
505
506 for l in RFH:
507 if l:
508 if l.startswith("#"):
509 continue
510
511 toks = l.rstrip().split()
512 assert len(toks) >= 7
513
514 ## the number and percent of reads that map unambiguously or ambiguously to human, cat, dog.
515 ## take the sum of the two numbers (ambiguous plus unambiguous) to use as the final percentage.
516 if l.startswith("human"):
517 refStats['human'] = {"unambiguousReadsPerc": toks[1], "unambiguousMB": toks[2], "ambiguousReadsPerc": toks[3], "ambiguousMB": toks[4], "unambiguousReads": toks[5], "ambiguousReads": toks[6], "totalPerc":float(toks[3])+float(toks[1])}
518 if l.startswith("cat"):
519 refStats['cat'] = {"unambiguousReadsPerc": toks[1], "unambiguousMB": toks[2], "ambiguousReadsPerc": toks[3], "ambiguousMB": toks[4], "unambiguousReads": toks[5], "ambiguousReads": toks[6], "totalPerc":float(toks[3])+float(toks[1])}
520 if l.startswith("dog"):
521 refStats['dog'] = {"unambiguousReadsPerc": toks[1], "unambiguousMB": toks[2], "ambiguousReadsPerc": toks[3], "ambiguousMB": toks[4], "unambiguousReads": toks[5], "ambiguousReads": toks[6], "totalPerc":float(toks[3])+float(toks[1])}
522 if l.startswith("mouse"):
523 refStats['mouse'] = {"unambiguousReadsPerc": toks[1], "unambiguousMB": toks[2], "ambiguousReadsPerc": toks[3], "ambiguousMB": toks[4], "unambiguousReads": toks[5], "ambiguousReads": toks[6], "totalPerc":float(toks[3])+float(toks[1])}
524
525 log.debug("refStats.txt: %s", str(refStats))
526
527
528
529 ###########################################################
530 log_and_print("Write to stats file %s" % STATS_LIST_FILE_NAME)
531 ###########################################################
532 if os.path.isfile(STATS_LIST_FILE_NAME):
533 os.remove(STATS_LIST_FILE_NAME)
534
535 with open(BB_STATS_LIST_FILE_NAME) as bbfh:
536 with open(STATS_LIST_FILE_NAME, 'a') as fh:
537 for line in bbfh:
538 if not line.startswith("#") and line.strip():
539 fh.write(line)
540
541 bbtoolsVersion = None
542
543 stats = get_dict_obj(STATS_LIST_FILE_NAME)
544 with open(STATS_LIST_FILE_NAME, 'a') as fh:
545 for key in readCounts:
546 if key not in stats:
547 write_stats(fh, key, readCounts[key], log)
548
549 for key in refStats:
550 for k in refStats[key]:
551 write_stats(fh, key+'_'+k, refStats[key][k], log)
552
553 write_stats(fh, "cardinality", cardinality, log)
554
555 ## Write refStats to filterStats.txt file
556 for key in filterLogStat:
557 for k in filterLogStat[key]:
558 write_stats(fh, key + '_' + k, filterLogStat[key][k], log)
559
560 bbversionCmd = os.path.join(BBDIR, 'bbversion.sh')
561 cmd = "%s" % (bbversionCmd)
562 stdOut, _, exitCode = run_sh_command(cmd, True, log)
563 assert stdOut is not None
564 bbtoolsVersion = stdOut.strip()
565
566 ## 05112017 Now bbtools version = bbmap version
567 # bbtoolsVersion = bbmapVersion if bbmapVersion else "37.xx"
568 assert bbtoolsVersion is not None
569 write_stats(fh, "filter_tool", "bbtools " + bbtoolsVersion, log)
570 write_stats(fh, "filter", VERSION, log)
571
572
573 ## Version recording
574 if bbdukVersion is None: bbdukVersion = bbtoolsVersion
575 if bbmapVersion is None: bbmapVersion = bbtoolsVersion
576 write_stats(fh, "bbduk_version", bbdukVersion, log)
577 write_stats(fh, "bbmap_version", bbmapVersion, log)
578
579 checkpoint(POST_END, status)
580 status = POST_END
581 else:
582 log_and_print('No need to do post processing.')
583
584 return filteredFastq, status
585
586
587 ##==============================================================================
588 ## Helper functions
589
590 def clean_up(fList, log):
591 log_and_print("\n\n%s - CLEAN UP <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<%s\n" % ( color['pink'], color['']))
592
593 for f in fList:
594 if os.path.isfile(f):
595 log_and_print("Removing %s ... ", f)
596 os.remove(f)
597
598 log_and_print("CLEAN UP - completed")
599
600
601 def create_shell(shName, cmdArray):
602 with open(shName, 'w') as fh:
603 fh.write("#!/bin/bash\n")
604 fh.write("set -e\n")
605 fh.write("set -o pipefail\n")
606 #fh.write("module unload blast+; module load blast+\n")
607 for item in cmdArray:
608 fh.write("%s\n" % item)
609 os.chmod(shName, 0755) #-rwxr-xr-x
610
611
612 ## checkpoint logging
613 def checkpoint(status, fromStatus=PIPE_START):
614 if status == PIPE_START or STEP_ORDER[status] > STEP_ORDER[fromStatus]:
615 checkpoint_step(STATUS_LOG_FNAME, status)
616
617 def write_stats(fh, k, v, log):
618 line = "%s=%s" % (k, v)
619 fh.write("%s\n" % line)
620
621 def read_qc(odir, fastq, status):
622 log_and_print("\n\n%s - RUN QC <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<%s\n" % (color['pink'], color['']))
623 if not os.path.isfile(fastq):
624 return False, status
625
626 qcdir = os.path.join(odir, READQC_DIR)
627
628 if STEP_ORDER[status] < STEP_ORDER[QC_END]:
629 checkpoint(QC_START, status)
630
631 qcexe = os.path.join(os.path.dirname(__file__), 'readqc.py')
632 cmd = '%s -o %s -f %s --skip-blast' % (qcexe, qcdir, fastq)
633 # print('DEBUG : %s' % cmd)
634 stdOut, stdErr, exitCode = run_sh_command(cmd, True)
635 if exitCode != 0:
636 print('ERROR : %s' % stdErr)
637 return False, qcdir, status
638
639 checkpoint(QC_END, status)
640 status = QC_END
641 else:
642 log_and_print("No need to do qc step.")
643
644 return True, qcdir, status
645
646 def do_html_body(odir, rawFastq, filteredFastq):
647
648 stats = get_dict_obj(os.path.join(odir, STATS_LIST_FILE_NAME))
649 tok_map = {
650 'inputReads' : {'token' : '[_RAW-READ-CNT_]', 'type': 'bigint'},
651 'inputBases' : {'token' : '[_RAW-BASE-CNT_]', 'type': 'bigint'},
652 'outputReads' : {'token' : '[_FILTERED-READ-CNT_]', 'type': 'bigint'},
653 'outputBases' : {'token' : '[_FILTERED-BASE-CNT_]', 'type': 'bigint'},
654 'readRmPct' : {'token' : '[_REMOVED-READ-PCT_]', 'type': 'raw'},
655 'baseRmPct' : {'token' : '[_REMOVED-BASE-PCT_]', 'type': 'raw'},
656
657 'lowqualitydiscards_numreads' : {'token' : '[_LOW-QUAL-REMOVED-READ-CNT_]', 'type': 'bigint', 'filter': 0},
658 'lowqualitydiscards_percreads' : {'token' : '[_LOW-QUAL-REMOVED-PCT_]', 'type': 'raw', 'filter': 0},
659
660 'contaminants_numreads' : {'token' : '[_ARTI-REMOVED-READ-CNT_]', 'type': 'bigint', 'filter': 0},
661 'contaminants_percreads' : {'token' : '[_ARTI-REMOVED-PCT_]', 'type': 'raw', 'filter': 0},
662 'ribosomalsequenceremoved_numreads' : {'token' : '[_RRNA-REMOVED-READ-CNT_]', 'type': 'bigint', 'filter': 0},
663 'ribosomalsequenceremoved_percreads' : {'token' : '[_RRNA-REMOVED-READ-PCT_]', 'type': 'raw', 'filter': 0},
664 'microbialremoved_numreads' : {'token' : '[_MICROBE-REMOVED-READ-CNT_]', 'type': 'bigint', 'filter': 0},
665 'microbialremoved_percreads' : {'token' : '[_MICROBE-REMOVED-READ-PCT_]', 'type': 'raw', 'filter': 0},
666 'human_unambiguousreads' : {'token' : '[_HUMAN-REMOVED-READ-CNT_]', 'type': 'bigint', 'filter': 0},
667 'human_unambiguousreadsperc' : {'token' : '[_HUMAN-REMOVED-READ-PCT_]', 'type': 'raw', 'filter': 0},
668 'dog_unambiguousreads' : {'token' : '[_DOG-REMOVED-READ-CNT_]', 'type': 'bigint', 'filter': 0},
669 'dog_unambiguousreadsperc' : {'token' : '[_DOG-REMOVED-READ-PCT_]', 'type': 'raw', 'filter': 0},
670 'cat_unambiguousreads' : {'token' : '[_CAT-REMOVED-READ-CNT_]', 'type': 'bigint', 'filter': 0},
671 'cat_unambiguousreadsperc' : {'token' : '[_CAT-REMOVED-READ-PCT_]', 'type': 'raw', 'filter': 0},
672 'mouse_unambiguousreads' : {'token' : '[_MOUSE-REMOVED-READ-CNT_]', 'type': 'bigint', 'filter': 0},
673 'mouse_unambiguousreadsperc' : {'token' : '[_MOUSE-REMOVED-READ-PCT_]', 'type': 'raw', 'filter': 0},
674 }
675
676 temp = os.path.join(PYDIR, 'template/filter_body_template.html')
677 html = ''
678 with open(temp, 'r') as fh:
679 html = fh.read()
680
681 ## do the place-holder replacement !!
682 html = html.replace('[_RAW-FILE-LOCATION_]', rawFastq)
683 html = html.replace('[_FILTERED-FILE-LOCATION_]', filteredFastq)
684 fsize = format(os.stat(rawFastq).st_size / (1024*1024), ',')
685 html = html.replace('[_RAW-FILE-SIZE_]', fsize)
686 fsize = format(os.stat(filteredFastq).st_size / (1024*1024), ',')
687 html = html.replace('[_FILTERED-FILE-SIZE_]', fsize)
688
689 for key in tok_map:
690 dat = tok_map[key]
691 html = html.replace(dat['token'], pipeline_val(key, dat, stats))
692
693 # readqc on the filter file
694 if qcdir:
695 hbody = do_readqc_html_body(qcdir, odir)
696 else:
697 hbody = ''
698 html = html.replace('[_FILTERED-READ-QC_]', hbody)
699 return html
700
701 def do_html(odir, qcdir, rawFastq, filteredFastq, status):
702 log_and_print("\n\n%s - Create HTML file <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<%s\n" % (color['pink'], color['']))
703 fname = os.path.basename(rawFastq)
704
705 stats = get_dict_obj(os.path.join(odir, STATS_LIST_FILE_NAME))
706
707 temp = os.path.join(PYDIR, 'template/template.html')
708 with open(temp, 'r') as fh:
709 html = fh.read()
710 html = html.replace('[_PAGE-TITLE_]', 'Filter Report')
711 html = html.replace('[_REPORT-TITLE_]', 'BBTools Filtering Report')
712 html = html.replace('[_INPUT-FILE-NAME_]', fname)
713 html = html.replace('[_REPORT-DATE_]', '{:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()))
714
715 hbody = do_html_body(odir, rawFastq, filteredFastq)
716 html = html.replace('[_REPORT-BODY_]', hbody)
717
718 fbasename = 'filter.log'
719 fname = os.path.join(outputPath, fbasename)
720 html = html.replace('[_FILTER-LOG_]', html_tag('a', fbasename, {'href': fbasename}))
721 fsize = '%.1f' % (float(os.stat(fname).st_size) / 2014.0)
722 html = html.replace('[_FILTER-LOG-SIZE_]', fsize)
723
724 # fbasename = 'filter.txt'
725 # fname = os.path.join(outputPath, fbasename)
726 # html = html.replace('[_FILTER-REPORT_]', html_tag('a', fbasename, {'href': fbasename}))
727 # fsize = '%.1f' % (float(os.stat(fname).st_size) / 2014.0)
728 # html = html.replace('[_FILTER-REPORT-SIZE_]', fsize)
729
730 ## write the html to file
731 idxfile = os.path.join(odir, 'index.html')
732 with open(idxfile, 'w') as fh2:
733 fh2.write(html)
734 print('HTML index file written to %s' % idxfile)
735
736 # copy the css file
737 cssdir = os.path.join(PYDIR, 'css')
738 todir = os.path.join(odir, 'css')
739 if os.path.isdir(todir):
740 shutil.rmtree(todir)
741 shutil.copytree(cssdir, todir, False, None)
742
743 # copy the image file
744 imgdir = os.path.join(PYDIR, 'images')
745 todir = os.path.join(odir, 'images')
746 if os.path.isdir(todir):
747 shutil.rmtree(todir)
748 shutil.copytree(imgdir, todir, False, None)
749
750 return status
751
752 ## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
753 ## main program
754 if __name__ == "__main__":
755 ## Parse options
756 usage = "* Filter Pipeline, version %s\n" % (VERSION)
757 origCmd = ' '.join(sys.argv)
758
759 ## command line options
760 parser = argparse.ArgumentParser(description=usage, formatter_class=argparse.ArgumentDefaultsHelpFormatter)
761
762 PROD_TYPE = [
763 'DNA',
764 'FUNGAL',
765 'METAGENOME',
766 'VIRAL-METAGENOME',
767 'SAG',
768 'ISO',
769 'SAG',
770 'CELL-ENRICHMENT',
771 'PLANT-2x150',
772 'PLANT-2x250',
773 'RNA',
774 'SMRNA',
775 'METATRANSCRIPTOME',
776 'LFPE',
777 'CLRS',
778 'CLIP-PE',
779 'NEXTERA',
780 'ITAG',
781 'MICROTRANS',
782 'BISULPHITE',
783 '3PRIMERNA',
784 'CHIPSEQ',
785 'RNAWOHUMAN'
786 ]
787
788 parser.add_argument("-f", "--fastq", dest="fastq", help="Set input fastq file (full path to fastq)", required=True)
789 parser.add_argument("-o", "--output-path", dest="outputPath", help="Set output path to write to", required=True)
790 parser.add_argument("-p", "--prod-type", dest="prodType", help="Set product type: %s" % PROD_TYPE, required=True)
791 parser.add_argument("-rdb", "--ref-databases", dest="rqcfilterdata", help="Path to RQCFilterData dir", required=True)
792
793 parser.add_argument("-t", "--taxlist", dest="taxList", help="A list of taxid(s) to exclude in CSV format", required=False)
794 parser.add_argument("-ap", "--ap", dest="apNum", help="Set AP (Analysis Project) ID. Ex) -ap 123 or -ap 123,456,789", required=False)
795 parser.add_argument("-at", "--at", dest="atNum", help="Set AT (Analysis Task) ID. Ex) -at 123 or -at 123,456,789", required=False)
796 parser.add_argument("-v", "--version", action="version", version=VERSION)
797
798 ## switches
799 parser.add_argument("-qc", "--qc", dest="doqc", action="store_true", help="also perform readqc analysis on the filtered output", default=False)
800 parser.add_argument("-a", "--aggressive", dest="enableAggressive", action="store_true", help="Enable aggressive=t and microbebuild=3", default=False)
801 parser.add_argument("-b", "--skip-blast", dest="skipBlastFlag", action="store_true", help="Skip Blast search", default=False)
802 parser.add_argument("-c", "--skip-cleanup", dest="skipCleanUp", action="store_true", help="Skip file clean up after pipeline complete", default=False)
803 parser.add_argument("-d", "--debug", dest="doDebug", action="store_true", help="Enable debug mode")
804 parser.add_argument("-l", "--disable-clumpify", dest="disableClumpify", action="store_true", help="Disable clumpify", default=False)
805 parser.add_argument("-m", "--skip-microbes-removal", dest="disableRmoveMicrobes", action="store_true", help="Skip microbes removal", default=False)
806 parser.add_argument("-r", "--contam", dest="enableRmoveMicrobes", action="store_true", help="Enable removemicrobes=t", default=False)
807 parser.add_argument("-s", "--skip-subsampleqc", dest="skipSubsampleQc", action="store_true", help="Skip the subsample and qc step", default=False)
808 parser.add_argument("-pl", "--print-log", dest="print_log", default = False, action = "store_true", help = "print log to screen")
809
810 ## produce html when processing is done
811 parser.add_argument("-html", "--html", action="store_true", help="Create html file", dest="html", default=False, required=False)
812
813 skipCleanUp = False
814 skipSubsampleQc = False
815 outputPath = None ## output path, defaults to current working directory
816 fastq = None ## full path to input fastq
817 # logLevel = "DEBUG"
818 enableRmoveMicrobes = False
819 disableRmoveMicrobes = False
820 disableClumpify = False
821 enableAggressive = False
822 skipBlastFlag = False
823 apNum = None
824 atNum = None
825
826 taxList = ""
827
828 options = parser.parse_args()
829 print_log = options.print_log
830
831 if options.outputPath:
832 outputPath = options.outputPath
833
834 if not outputPath:
835 outputPath = os.getcwd()
836
837 ## create output_directory if it doesn't exist
838 if not os.path.isdir(outputPath):
839 os.makedirs(outputPath)
840
841 outputPath = os.path.realpath(outputPath)
842 outputPath = outputPath.replace("/chos", "") if outputPath.startswith("/chos") else outputPath
843
844 ## initialize my logger
845 logFile = os.path.join(outputPath, "rqc_filter_pipeline.log")
846
847 print "Started filtering pipeline with %s, writing log to: %s" % (SCRIPT_NAME, logFile)
848
849 log = get_logger("filter", logFile, logLevel, print_log, True)
850
851 if options.doDebug:
852 DEBUG = True
853
854 if options.skipCleanUp:
855 skipCleanUp = True
856
857 if options.skipBlastFlag:
858 skipBlastFlag = True
859
860 if options.skipSubsampleQc:
861 skipSubsampleQc = True
862
863 if options.enableRmoveMicrobes:
864 if options.disableRmoveMicrobes:
865 log.error("Conflict in option parameters: cannot set skip-contam with skip-microbes-removal.")
866 sys.exit(0)
867
868 enableRmoveMicrobes = True
869
870 if options.disableRmoveMicrobes:
871 if options.enableRmoveMicrobes:
872 log.error("Conflict in option parameters: cannot set skip-contam with skip-microbes-removal.")
873 sys.exit(0)
874
875 disableRmoveMicrobes = True
876
877 if options.enableAggressive:
878 enableAggressive = True
879
880 if options.disableClumpify:
881 disableClumpify = True
882
883 if options.fastq:
884 fastq = options.fastq
885
886 if options.taxList:
887 taxList = options.taxList
888
889 if options.apNum:
890 apNum = options.apNum
891 if options.atNum:
892 atNum = options.atNum
893
894
895 log_and_print("%s" % '#' * 80)
896 log_and_print(" Filtering pipeline (version %s)" % VERSION)
897 log_and_print("%s" % '#' * 80)
898
899
900 prodType = options.prodType.upper()
901 skipSubsampleQcFlag = options.skipSubsampleQc ## run subsample and qc or not
902
903 if not os.path.isdir(outputPath):
904 log.error("Cannot work with directory: %s", outputPath)
905
906 ## check for fastq file
907 if fastq:
908 if not os.path.isfile(fastq):
909 log.error("Input fastq file, %s not found, abort!", fastq)
910 else:
911 log.error("No fastq defined, abort!")
912
913 fastq = os.path.realpath(fastq)
914 fastq = fastq.replace("/chos", "") if fastq.startswith("/chos") else fastq
915
916
917 ##--------------------------------
918 ## init log
919 log_and_print("Started pipeline, writing log to: %s" % logFile)
920 log_and_print("CMD: %s" % origCmd)
921 log_and_print("Fastq file: %s" % fastq)
922 log_and_print("Output path: %s" % outputPath)
923
924 os.chdir(outputPath)
925
926 cycle = 0
927 cycleMax = 1
928 bIsPaired = False
929
930 status = get_status(STATUS_LOG_FNAME, log)
931 log_and_print("Starting pipeline at [%s]" % status)
932
933 if status == PIPE_START:
934 checkpoint(PIPE_START)
935
936 ## main loop: retry upto cycleMax times
937 while cycle < cycleMax:
938
939 cycle += 1
940
941 log_and_print("ATTEMPT [%d]" % cycle)
942
943 filesToRemove = [] # list of intermediate files for clean up
944 lastFastq = fastq # lastFastq : fastq produced by each step, init to input
945 rRnaFilterFile = None # MTF generates this 2nd filtered output file
946 subsampledFastq = None
947 bIsPaired = None
948 filteredReadNum = -1
949 filteredReadNumRrna = -1
950 FragFile = SingletonFile = UnknownFile = None
951
952 if cycle > 1:
953 status = get_status(STATUS_LOG_FNAME, log)
954
955 if status != PIPE_COMPLETE:
956 ##
957 ## Run rqcfilter.sh
958 ##
959 lastFastq, status = run_rqcfilter(lastFastq, outputPath, prodType, status, enableRmoveMicrobes, enableAggressive, disableRmoveMicrobes, disableClumpify, taxList, options.rqcfilterdata, log) ## Only MTF type generates rRnaFilterFile
960 if filteredReadNum == 0:
961 break
962
963 ##--------------------------------
964 ## Run post processing
965 if lastFastq is not None and lastFastq != -1:
966 lastFastq, status = post_process(fastq, outputPath, lastFastq, status, log)
967 else:
968 print "Failed @ rqcfilter"
969
970
971 ##--------------------------------
972 ## Clean up
973 if lastFastq is not None and lastFastq != -1:
974
975 ## run readQC on the filtered fastq
976 if options.doqc:
977 rtn, qcdir, status = read_qc(outputPath, lastFastq, status)
978 else:
979 qcdir = None
980 rtn = True
981
982 ## create html file on the readQC results
983 if rtn:
984 status = do_html(outputPath, qcdir, fastq, lastFastq, status)
985
986 checkpoint(PIPE_COMPLETE)
987
988 if not skipCleanUp:
989 clean_up(filesToRemove, log)
990 else:
991 log_and_print("SKIP CLEANUP")
992
993 log_and_print("Pipeline Completed")
994 cycle = cycleMax + 1
995
996 else:
997 print "Failed @ postprocess"
998
999 else:
1000 cycle = cycleMax + 1
1001 log_and_print("Pipeline already completed")
1002
1003
1004 print "Done."
1005 sys.exit(0)
1006
1007
1008 ## EOF