Debian Codegraph @

pytools/lib/readqc_utils.py

raw symbols SCIP
1 #! /usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 """
5 Read qc utilities
6
7 Created: Jul 24 2013
8 sulsj
9
10 """
11
12 import os
13 import subprocess
14 import matplotlib
15 import numpy as np
16
17 from common import checkpoint_step
18 from os_utility import make_dir, change_mod, run_sh_command, rm_dir
19 from readqc_constants import RQCReadQcConfig, RQCContamDb, RQCReadQcReferenceDatabases, RQCReadQc
20 from rqc_utility import safe_basename, get_cat_cmd, localize_file, safe_dirname
21 from rqc_constants import RQCExitCodes
22
23 matplotlib.use("Agg") ## This needs to skip the DISPLAY env var checking
24 import matplotlib.pyplot as plt
25 from matplotlib.font_manager import FontProperties
26 import mpld3
27 from matplotlib.ticker import MultipleLocator, FormatStrFormatter
28
29
30 """ STEP1 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
31
32 fast_subsample_fastq_sequences
33
34 Title : fast_subsample_fastq_sequences
35
36 Function : This function subsamples the data from a specified fastq file.
37
38 Usage : fast_subsample_fastq_sequences( $seq_unit, subsampledFile, $subsamplingRate, $max_count, \$totalBaseCount, $totalReadNum, log)
39
40 Args : 1) The source fastq file.
41 2) The destination fastq file.
42 3) The percentage of read subsampling.
43 4) The maximum number of reads at which to stop subsampling.
44 5) A reference to the variable that will store the
45 basecount.
46 6) A reference to the variable that will store the
47 number of reads.
48 7) A reference to a JGI_Log object.
49
50 Returns : JGI_SUCCESS: The fastq data was successfully sampled.
51 JGI_FAILURE: The fastq data could not be sampled.
52
53 Comments : Pass as parameters both the subsample_rate and the read_count
54 in order to stop subsampling at the read_count.
55 The read_count can also be null, in which case the number
56 of reads corresponding to the percentage subsample_rate will be subsampled.
57
58 @param fastq: source fastq file (full path)
59 @param outputFileName: subsampled output file name (basename)
60 @param subsamplingRate: sample rate < 1.0
61 @param isStatGenOnly: boolean -> generate stats output or not
62 @param log
63
64 @return retCode: success or failure
65 @return subsampledFile: subsampled output file name (full path)
66 @return totalBaseCount: total #bases (to be added to readqc_stats.txt)
67 @return totalReadNum: total #reads (to be added to readqc_stats.txt)
68 @return subsampledReadNum: total #reads sampled (to be added to readqc_stats.txt)
69
70 """
71 def fast_subsample_fastq_sequences(sourceFastq, outputFileName, subsamplingRate, isStatGenOnly, log):
72 ## Tools
73 cdir = os.path.dirname(__file__)
74 bbtoolsReformatShCmd = os.path.join(cdir, '../../reformat.sh') #RQCReadQcCommands.BBTOOLS_REFORMAT_CMD
75
76 READ_OUTPUT_PATH = RQCReadQcConfig.CFG["output_path"]
77 log.info("Sampling %s at %.2f rate", sourceFastq, subsamplingRate)
78
79 retCode = None
80 totalBaseCount = 0
81 totalReadNum = 0
82 subsampledReadNum = 0
83 bIsPaired = False
84 readLength = 0
85
86 subsampleDir = "subsample"
87 subsamplePath = os.path.join(READ_OUTPUT_PATH, subsampleDir)
88 make_dir(subsamplePath)
89 change_mod(subsamplePath, "0755")
90
91 subsampledFile = os.path.join(subsamplePath, outputFileName)
92
93 fileSize = os.path.getsize(sourceFastq)
94 log.info("Source fastq file size = %s", fileSize)
95
96 ## Replaced subsampler with reformat.sh
97 ## subsample with bbtoolsReformatShCmd:
98 ## $ reformat.sh in=7348.8.68143.fastq out=subsample.fastq samplerate=0.01 qout=33
99 ## - 21G == 180.399 seconds ~ 6x faster than subsample_fastq_pl
100 ## new subampler from BBTOOLS
101 ## without qin=33 then it uses auto detect, Illumina is phread64 but we need to convert to phred33
102 ##reformat.sh in=7257.1.64419.CACATTGTGAG.s1.0.fastq out=temp.out samplerate=0.02 qin=33 qout=33 overwrite
103
104 ## 20140820
105 ## bhist=<file> Write a base composition histogram to file. ## Cycle Nucleotide Composition
106 ## gchist=<file> Write a gc content histogram to file. ## Read GC, mean, std
107 ## qhist=<file> Write a quality histogram to file. ## Average Base Position Quality
108 ## bqhist=<file> Write a quality histogram designed for box plots. ## Average Base Position Quality Boxplot
109 ## obqhist=<file> Write a base quality histogram to file. ## Base quality histogram; *.base_qual.stats
110
111 reformatPrefix = os.path.basename(subsampledFile).replace(".fastq", "")
112
113 reformatLogFile = os.path.join(subsamplePath, reformatPrefix + ".reformat.log")
114 reformatGchistFile = os.path.join(subsamplePath, reformatPrefix + ".reformat.gchist.txt") ## Read GC
115 reformatBhistFile = os.path.join(subsamplePath, reformatPrefix + ".reformat.bhist.txt") ## Cycle Nucleotide Composition
116 reformatQhistFile = os.path.join(subsamplePath, reformatPrefix + ".reformat.qhist.txt") ## Average Base Position Quality
117 reformatBqhistFile = os.path.join(subsamplePath, reformatPrefix + ".reformat.bqhist.txt") ## Average Base Position Quality Boxplot
118 reformatObqhistFile = os.path.join(subsamplePath, reformatPrefix + ".reformat.obqhist.txt") ## Base quality histogram
119
120 if not isStatGenOnly: ## if subsampling for blast, do not generate the stat files
121 subsampleCmd = "%s in=%s out=%s samplerate=%s qin=33 qout=33 ow=t > %s 2>&1 " % \
122 (bbtoolsReformatShCmd, sourceFastq, subsampledFile, subsamplingRate, reformatLogFile)
123 else:
124 subsampleCmd = "%s in=%s out=%s samplerate=%s qin=33 qout=33 ow=t gcplot=t bhist=%s qhist=%s gchist=%s gcbins=auto bqhist=%s obqhist=%s > %s 2>&1 " % \
125 (bbtoolsReformatShCmd, sourceFastq, subsampledFile, subsamplingRate, reformatBhistFile,
126 reformatQhistFile, reformatGchistFile, reformatBqhistFile, reformatObqhistFile, reformatLogFile)
127
128 _, _, exitCode = run_sh_command(subsampleCmd, True, log, True)
129
130 if exitCode == 0:
131 ##java -ea -Xmx200m -cp /usr/common/jgi/utilities/bbtools/prod-33.18/lib/BBTools.jar jgi.ReformatReads in=7257.1.64419.CACATTGTGAG.s1.0.fastq out=temp.out samplerate=0.02 qin=33 qout=33 overwrite
132 ##Executing jgi.ReformatReads [in=7257.1.64419.CACATTGTGAG.s1.0.fastq, out=temp.out, samplerate=0.02, qin=33, qout=33, overwrite]
133 ##
134 ##Unspecified format for output temp.out; defaulting to fastq.
135 ##Input is being processed as paired
136 ##Writing interleaved.
137 ##Input: 6661 reads 1671911 bases
138 ##Processed: 278 reads 69778 bases
139 ##Output: 278 reads (4.17%) 69778 bases (4.17%)
140 ##
141 ##Time: 0.181 seconds.
142 ##Reads Processed: 278 1.54k reads/sec
143 ##Bases Processed: 69778 0.39m bases/sec
144
145 ## NEW
146 if os.path.isfile(reformatLogFile):
147 with open(reformatLogFile) as STAT_FH:
148 for l in STAT_FH.readlines():
149 if l.startswith("Input:"):
150 toks = l.split()
151 totalBaseCount = int(toks[3])
152 totalReadNum = int(toks[1])
153 # elif l.startswith("Processed:") or l.startswith("Output:"):
154 elif l.startswith("Output:"):
155 toks = l.split()
156 subsampledReadNum = int(toks[1])
157 elif l.startswith("Input is being processed as"):
158 toks = l.split()
159 if toks[-1].strip() == "paired":
160 bIsPaired = True
161
162 log.info("Total base count of input fastq = %s", totalBaseCount)
163 log.info("Total num reads of input fastq = %s", totalReadNum)
164 log.info("Total num reads of sampled = %s", subsampledReadNum)
165
166 readLength = int(totalBaseCount / totalReadNum)
167
168 log.info("Read length = %d", readLength)
169 log.info("Paired = %s", bIsPaired)
170
171 if totalReadNum > 0 and subsampledReadNum > 0:
172 ##
173 ## TODO: deal with sequnits with small number of reads
174 ## How to record the status in readqc.log
175 ##
176 retCode = RQCExitCodes.JGI_SUCCESS
177 log.info("illumina_readqc_subsampling complete: output file = %s", subsampledFile)
178
179 elif totalReadNum > 0 and subsampledReadNum <= 0:
180 retCode = RQCExitCodes.JGI_FAILURE
181 log.error("illumina_readqc_subsampling failure. subsampledReadNum <= 0.")
182
183 else:
184 retCode = RQCExitCodes.JGI_FAILURE
185 log.error("illumina_readqc_subsampling failure. totalReadNum <= 0 and subsampledReadNum <= 0.")
186
187 else:
188 retCode = RQCExitCodes.JGI_FAILURE
189 log.error("illumina_readqc_subsampling failure. Can't find stat file from subsampling.")
190
191 else:
192 retCode = RQCExitCodes.JGI_FAILURE
193 log.error("illumina_readqc_subsampling failure. Failed to run bbtoolsReformatShCmd. Exit code != 0")
194 with open(reformatLogFile, 'r') as f:
195 log.error(f.read())
196 retCode = -2
197
198 return retCode, subsampledFile, totalBaseCount, totalReadNum, subsampledReadNum, bIsPaired, readLength
199
200
201 """ STEP2 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
202
203 write_unique_20_mers
204
205 Title: write_unique_k_mers (k=20 or 25)
206 Function: Given a fastq file, finds unique 20/25 mers from the start
207 of the read and along a random position of the read
208 Usage: write_unique_20_mers(\@seq_files, $log)
209 Args: 1) ref to an array containing bz2 zipped fastq file path(s)
210 2) output directory
211 3) log file object
212 Returns: exitCode, merSamplerOutFile, pngPlotFile, htmlPlotFile
213 Comments: Using bbcountunique.sh's output file named merSampler.<fastq_name>.m20.e25000
214 create a plot png file, merSampler.<fastq_name>.m20.e25000.png
215
216 bbcountunique.sh: Generates a kmer uniqueness histogram, binned by file position.
217 There are 3 columns for single reads, 6 columns for paired:
218 count number of reads or pairs processed
219 r1_first percent unique 1st kmer of read 1
220 r1_rand percent unique random kmer of read 1
221 r2_first percent unique 1st kmer of read 2
222 r2_rand percent unique random kmer of read 2
223 pair percent unique concatenated kmer from read 1 and 2
224
225 @param fastq: source fastq file (full path)
226 @param log
227
228 @return retCode: success or failure
229 @return mersampler_out_file: plot data (to be added to readqc_files.txt)
230 @return pngPlotFile: output plot (to be added to readqc_files.txt)
231 @return htmlPlotFile: output d3 interactive plot (to be added to readqc_files.txt)
232
233 """
234 def write_unique_20_mers(fastq, log):
235 ## Tools
236 cdir = os.path.dirname(__file__)
237 bbcountuniqueShCmd = os.path.join(cdir, '../../bbcountunique.sh') #RQCReadQcCommands.BBCOUNTUNIQUE_SH_CMD
238
239 READ_OUTPUT_PATH = RQCReadQcConfig.CFG["output_path"]
240 uniqMerDir = "uniqueness"
241 uniqMerPath = os.path.join(READ_OUTPUT_PATH, uniqMerDir)
242 make_dir(uniqMerPath)
243 change_mod(uniqMerPath, "0755")
244
245 ## cmd line for merSampler
246 uniqMerSize = RQCReadQc.ILLUMINA_MER_SAMPLE_MER_SIZE ## 20 ==> 25 RQC-823 08102016
247 reportFreq = RQCReadQc.ILLUMINA_MER_SAMPLE_REPORT_FRQ ## 25000
248
249 sequnitFileName, exitCode = safe_basename(fastq, log)
250 sequnitFileNamePrefix = sequnitFileName.replace(".fastq", "").replace(".gz", "")
251
252 ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
253 ## bbcountunique.sh, a new version of sampler from bbtools
254 ## bbcountunique.sh in=$FILENAME out=out.txt percent=t count=t cumulative=t
255 ## ex) bbcountunique.sh in=$SEQDIR/dna/$SEQFILE.fastq.gz out=7378.1.69281.CGATG-2.txt percent=t count=t cumulative=f int=f
256 ## ex2)
257 ## cmd: bbcountunique.sh k=20 interval=25000 in=7601.1.77813.CTTGTA.fastq.gz out=7601.1.77813.CTTGTA.merSampler.m20.e25000_2 percent=t count=t cumulative=f int=f
258
259 log.info("bbcountunique.sh started.")
260
261 merSamplerOutFile = os.path.join(uniqMerPath, sequnitFileNamePrefix + ".merSampler.m" + str(uniqMerSize) + ".e" + str(reportFreq) + "_2")
262
263 ## RQC-823
264 ## Adding shuffling before bbcountunique
265 ## 08302016 Reverted to no shuffling
266 ##
267 ## shuffle.sh in=input.fastq.gz out=stdout.fq -Xmx40g | bbcountunique.sh in=stdin.fq -Xmx40g ==> not working
268 # shuffledFastqFile = os.path.join(uniqMerPath, sequnitFileNamePrefix + ".shuffled.fq")
269 # suffleCmd = "%s in=%s out=%s" % (shuffleShCmd, fastq, shuffledFastqFile)
270 # stdOut, stdErr, exitCode = run_sh_command(suffleCmd, True, log, True)
271 # if exitCode != 0:
272 # log.error("failed to suffle fastq for unique mer analysis.")
273 # return RQCExitCodes.JGI_FAILURE, None, None, None
274
275 bbcountuniqCmd = "%s in=%s out=%s k=%s interval=%s percent=t count=t cumulative=f int=f ow=t" \
276 % (bbcountuniqueShCmd, fastq, merSamplerOutFile, uniqMerSize, reportFreq)
277
278 _, _, exitCode = run_sh_command(bbcountuniqCmd, True, log, True)
279
280 if exitCode != 0:
281 log.error("Failed to sample unique %s mers by bbcountunique.sh.", uniqMerSize)
282 return RQCExitCodes.JGI_FAILURE, None, None, None
283
284 log.info("bbcountunique.sh completed.")
285
286 ## Old plotting data
287 # nSeq nStartUniMer fracStartUniMer nRandUniMer fracRandUniMer
288 ## 0 1 2 3 4
289 ##25000 2500 0.1 9704 0.3882
290
291 ## New plotting data from bbcountunique
292 # count first rand first_cnt rand_cnt
293 # 0 1 2 3 4
294 # 25000 66.400 76.088 16600 19022
295 # 50000 52.148 59.480 13037 14870
296 # 75000 46.592 53.444 11648 13361
297 # 100000 43.072 49.184 10768 12296 ...
298
299 pngPlotFile = None
300 htmlPlotFile = None
301
302 if os.path.isfile(merSamplerOutFile):
303 ## sanity check
304
305 ## OLD
306 ## #nSeq nStartUniMer fracStartUniMer nRandUniMer fracRandUniMer
307 ## ex) 25000 16594 0.6638 18986 0.7594
308 ## 50000 29622 0.5211 33822 0.5934
309 ## 75000 41263 0.4656 47228 0.5362
310 ## 100000 52026 0.4305 59545 0.4927 ...
311 """
312 2016-09-07
313 #count first rand first_cnt rand_cnt avg_quality perfect_prob
314 25000 96.480 98.636 24120 24659 30.36 80.94
315 50000 96.204 97.996 24051 24499 30.41 81.17
316 75000 95.512 97.568 23878 24392 29.99 80.06
317 100000 95.408 97.588 23852 24397 30.24 80.78
318 125000 95.176 97.240 23794 24310 30.23 80.86
319 """
320
321 line = None
322 numData = 0
323
324 with open(merSamplerOutFile, "r") as FH:
325 lines = FH.readlines()
326 line = lines[-1] ## get the last line
327 numData = sum(1 for l in lines)
328
329 toks = line.split()
330 assert len(toks) == 7, "ERROR: merSamplerOutFile format error: %s " % (merSamplerOutFile)
331
332 if numData < 3:
333 log.error("Not enough data in merSamplerOutFile: %s", merSamplerOutFile)
334 return RQCExitCodes.JGI_SUCCESS, None, None, None
335
336
337 ## Generating plots
338 rawDataMatrix = np.loadtxt(merSamplerOutFile, delimiter='\t', comments='#')
339 # Bryce: 2016-09-07, its 7 now. Its failed 622 pipelines ...
340 # assert len(rawDataMatrix[1][:]) == 5
341
342 fig, ax = plt.subplots()
343
344 markerSize = 5.0
345 lineWidth = 1.5
346
347 ## Note: no need to show all the data points
348 ## If the number of data points > 5k, get only 5k data.
349 jump = 1
350 if len(rawDataMatrix[:, 0]) > 10000:
351 jump = int(len(rawDataMatrix[:, 0]) / 5000)
352
353 xData = rawDataMatrix[:, 0][0::jump]
354 yData = rawDataMatrix[:, 1][0::jump]
355 yData2 = rawDataMatrix[:, 2][0::jump]
356
357 totalReadNum = rawDataMatrix[-1, 0] ## sampled read num from the last line of the data file
358 assert int(totalReadNum) > 0
359 maxX = int(totalReadNum) * 3
360
361 p1 = ax.plot(xData, yData, 'g', marker='x', markersize=markerSize, linewidth=lineWidth, label="Starting %s Mer Uniqueness" % (str(uniqMerSize)), alpha=0.5)
362 p2 = ax.plot(xData, yData2, 'b', marker='x', markersize=markerSize, linewidth=lineWidth, label="Random %s Mer Uniqueness" % (str(uniqMerSize)), alpha=0.5)
363
364 ## Curve-fitting
365 from scipy.optimize import curve_fit
366
367 ## fit function: f(x)=a*log(x)+b
368 def fit_func(x, a, b):
369 return a * np.log(x) + b
370
371 fitpars, _ = curve_fit(fit_func, rawDataMatrix[:, 0], rawDataMatrix[:, 1])
372
373 fix_x = [i for i in range(25000, maxX, 25000)]
374 ax.plot(fix_x, fit_func(fix_x, *fitpars), 'r', linewidth=lineWidth, label="fit", alpha=0.5)
375
376 ax.set_xlabel("Read Sampled", fontsize=12, alpha=0.5)
377 ax.set_ylabel("Percentage Unique", fontsize=12, alpha=0.5)
378 ax.spines["top"].set_visible(False)
379 ax.spines["right"].set_visible(False)
380 ax.get_xaxis().tick_bottom()
381 ax.get_yaxis().tick_left()
382 fontProp = FontProperties()
383 fontProp.set_size("small")
384 fontProp.set_family("Bitstream Vera Sans")
385 ax.legend(loc=1, prop=fontProp)
386 ax.set_xlim([0, maxX])
387 ax.set_ylim([0, 100])
388 ax.grid(color="gray", linestyle=':')
389
390 ## Add tooltip
391 labels = ["%.2f" % i for i in rawDataMatrix[:, 1]]
392 mpld3.plugins.connect(fig, mpld3.plugins.PointLabelTooltip(p1[0], labels=labels))
393
394 labels = ["%.2f" % i for i in rawDataMatrix[:, 2]]
395 mpld3.plugins.connect(fig, mpld3.plugins.PointLabelTooltip(p2[0], labels=labels))
396
397 ## Create both dynamic and static plots
398 pngPlotFile = merSamplerOutFile + "_mer_sampler_plot.png"
399 plt.savefig(pngPlotFile, dpi=fig.dpi)
400
401 htmlPlotFile = merSamplerOutFile + "_mer_sampler_plot_d3.html"
402 mpld3.save_html(fig, htmlPlotFile)
403
404 log.info("New data file from bbcountunique: %s", merSamplerOutFile)
405 log.info("New png plot: %s", pngPlotFile)
406 log.info("New D3 plot: %s", htmlPlotFile)
407
408 else:
409 log.error("Cannot find merSamplerOutFile by bbcountunique.sh, %s", merSamplerOutFile)
410 return RQCExitCodes.JGI_FAILURE, None, None, None
411
412 ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
413
414 # if os.path.isfile(merSamplerOutFile):
415 # line = None
416 # numData = 0
417 #
418 # with open(merSamplerOutFile, "r") as FH:
419 # line = FH.readlines()[-1] ## get the last line
420 # numData = len(line)
421 #
422 # ## #nSeq nStartUniMer fracStartUniMer nRandUniMer fracRandUniMer
423 # ## ex) 25000 16594 0.6638 18986 0.7594
424 # ## 50000 29622 0.5211 33822 0.5934
425 # ## 75000 41263 0.4656 47228 0.5362
426 # ## 100000 52026 0.4305 59545 0.4927 ...
427 # """
428 # 2016-09-07
429 # #count first rand first_cnt rand_cnt avg_quality perfect_prob
430 # 25000 96.480 98.636 24120 24659 30.36 80.94
431 # 50000 96.204 97.996 24051 24499 30.41 81.17
432 # 75000 95.512 97.568 23878 24392 29.99 80.06
433 # 100000 95.408 97.588 23852 24397 30.24 80.78
434 # 125000 95.176 97.240 23794 24310 30.23 80.86
435 # """
436 #
437 # toks = line.split()
438 # assert len(toks)==7, "ERROR: merSamplerOutFile format error: %s " % (merSamplerOutFile)
439 #
440 # # totalReadNum = int(toks[0])
441 # # log.info("Total number of reads = %s." % (totalReadNum))
442 # # assert totalReadNum > 0
443 #
444 # else:
445 # log.error("cannot find mersampler_out_file, %s" % (merSamplerOutFile))
446 # return RQCExitCodes.JGI_FAILURE, None, None, None
447 #
448 # if numData < 3:
449 # log.error("not enough data in %s" % (merSamplerOutFile))
450 # return RQCExitCodes.JGI_FAILURE, None, None, None
451
452 ## verify that the mer sampler output file was created
453 # if not os.path.isfile(merSamplerOutFile):
454 # log.error("failed to find output file for %s Mer Uniqueness: %s" % (str(uniqMerSize), merSamplerOutFile))
455 # else:
456 # log.info("MerSampler output file successfully generated (%s)." % (merSamplerOutFile))
457
458 ## verify that the mer sampler plot png file was created
459 if not os.path.isfile(pngPlotFile):
460 log.warning("Failed to find output plot png file for %s Mer Uniqueness", str(uniqMerSize))
461 else:
462 log.info("MerSampler output png file successfully generated (%s)", pngPlotFile)
463
464 if not os.path.isfile(htmlPlotFile):
465 log.warning("Failed to find output d3 plot html file for %s Mer Uniqueness", str(uniqMerSize))
466 else:
467 log.info("MerSampler output png file successfully generated (%s)", htmlPlotFile)
468
469
470 return RQCExitCodes.JGI_SUCCESS, merSamplerOutFile, pngPlotFile, htmlPlotFile
471
472
473 """ STEP3 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
474
475 illumina_read_gc
476
477 Title: illumina_read_gc
478 Function: Takes path to fastq file and generates
479 read gc histograms (txt and png)
480 Usage: illumina_read_gc($fastq_path, $log)
481 Args: 1) path to subsampled fastq file
482 2) log file object
483 Returns: JGI_SUCCESS
484 JGI_FAILURE
485 Comments: None.
486
487 @param fastq: source fastq file (full path)
488 @param log
489
490 @return reformatGchistFile: hist text data (to be added to readqc_files.txt)
491 @return pngFile: output plot (to be added to readqc_files.txt)
492 @return htmlFile: output d3 interactive plot (to be added to readqc_files.txt)
493 @return meanVal: gc mean (to be added to readqc_stats.txt)
494 @return stdevVal: gc stdev (to be added to readqc_stats.txt)
495
496 """
497 def illumina_read_gc(fastq, log):
498 READ_OUTPUT_PATH = RQCReadQcConfig.CFG["output_path"]
499
500 sequnitFileName, _ = safe_basename(fastq, log)
501 sequnitFileNamePrefix = sequnitFileName.replace(".fastq", "").replace(".gz", "")
502
503 subsampleDir = "subsample"
504 subsamplePath = os.path.join(READ_OUTPUT_PATH, subsampleDir)
505
506 qualDir = "qual"
507 qualPath = os.path.join(READ_OUTPUT_PATH, qualDir)
508 make_dir(qualPath)
509 change_mod(qualPath, "0755")
510
511 reformatGchistFile = os.path.join(subsamplePath, sequnitFileNamePrefix + ".reformat.gchist.txt") ## gc hist
512
513 log.debug("gchist file: %s", reformatGchistFile)
514
515 ## Gen Average Base Position Quality plot
516 if not os.path.isfile(reformatGchistFile):
517 log.error("Gchist file not found: %s", reformatGchistFile)
518 return None, None, None, None, None, None, None
519
520 ## File format
521 ## #Mean 41.647
522 ## #Median 42.000
523 ## #Mode 42.000
524 ## #STDev 4.541
525 ## #GC Count
526 ## 0.0 0
527 ## 1.0 0
528 ## 2.0 0
529 ## 3.0 0
530 ## 4.0 0
531 meanVal = None
532 medVal = None
533 modeVal = None
534 stdevVal = None
535
536 with open(reformatGchistFile, "r") as STAT_FH:
537 for l in STAT_FH.readlines():
538 if l.startswith("#Mean"):
539 meanVal = l.strip().split('\t')[1]
540 elif l.startswith("#Median"):
541 medVal = l.strip().split('\t')[1]
542 elif l.startswith("#Mode"):
543 modeVal = l.strip().split('\t')[1]
544 elif l.startswith("#STDev"):
545 stdevVal = l.strip().split('\t')[1]
546
547 rawDataMatrix = np.loadtxt(reformatGchistFile, comments='#', usecols=(0, 1, 2)) ## only use 3 colums: GC, Count, Cumulative
548
549 ## In addition to the %GC and # reads, the cumulative read % is added.
550 assert len(rawDataMatrix[1][:]) == 3
551
552 fig, ax = plt.subplots()
553
554 markerSize = 5.0
555 lineWidth = 1.5
556
557 p1 = ax.plot(rawDataMatrix[:, 0], rawDataMatrix[:, 1], 'r', marker='o', markersize=markerSize, linewidth=lineWidth, alpha=0.5)
558
559 ax.set_xlabel("%GC", fontsize=12, alpha=0.5)
560 ax.set_ylabel("Read count", fontsize=12, alpha=0.5)
561 ax.grid(color="gray", linestyle=':')
562
563 ## Add tooltip
564 toolTipStrReadCnt = ["Read count=%d" % i for i in rawDataMatrix[:, 1]]
565 toolTipStrGcPerc = ["GC percent=%.1f" % i for i in rawDataMatrix[:, 0]]
566 toolTipStrReadPerc = ["Read percent=%.1f" % (i * 100.0) for i in rawDataMatrix[:, 2]]
567 toolTipStr = ["%s, %s, %s" % (i, j, k) for (i, j, k) in
568 zip(toolTipStrGcPerc, toolTipStrReadCnt, toolTipStrReadPerc)]
569 mpld3.plugins.connect(fig, mpld3.plugins.PointLabelTooltip(p1[0], labels=toolTipStr))
570
571 pngFile = os.path.join(qualPath, sequnitFileNamePrefix + ".gchist.png")
572 htmlFile = os.path.join(qualPath, sequnitFileNamePrefix + ".gchist.html")
573
574 ## Save D3 interactive plot in html format
575 mpld3.save_html(fig, htmlFile)
576
577 ## Save Matplotlib plot in png format
578 plt.savefig(pngFile, dpi=fig.dpi)
579
580
581 return reformatGchistFile, pngFile, htmlFile, meanVal, stdevVal, medVal, modeVal
582
583
584 """ STEP5 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
585
586 write_avg_base_quality_stats
587
588 Title: write_base_quality_stats
589 Function: Takes path to fastq file and generates
590 quality plots for each read
591 Usage: write_base_quality_stats($fastq_path, $analysis, $log)
592 Args: 1) path to subsampled fastq file
593 2) log file object
594 Returns: None.
595 Comments: None.
596
597
598 @param fastq: source fastq file (full path)
599 @param log
600
601 @return reformatObqhistFile: output data file (to be added to readqc_files.txt)
602
603 """
604 def write_avg_base_quality_stats(fastq, log):
605 READ_OUTPUT_PATH = RQCReadQcConfig.CFG["output_path"]
606
607 sequnitFileName, _ = safe_basename(fastq, log)
608 sequnitFileNamePrefix = sequnitFileName.replace(".fastq", "").replace(".gz", "")
609
610 subsampleDir = "subsample"
611 subsamplePath = os.path.join(READ_OUTPUT_PATH, subsampleDir)
612
613 qualDir = "qual"
614 qualPath = os.path.join(READ_OUTPUT_PATH, qualDir)
615 make_dir(qualPath)
616 change_mod(qualPath, "0755")
617
618 reformatObqhistFile = os.path.join(subsamplePath, sequnitFileNamePrefix + ".reformat.obqhist.txt") ## base composition histogram
619
620 log.debug("obqhist file: %s", reformatObqhistFile)
621
622 ## Gen base composition histogram
623 if not os.path.isfile(reformatObqhistFile):
624 log.error("Obqhist file not found: %s", reformatObqhistFile)
625 return None
626 else:
627 return reformatObqhistFile
628
629
630 """ STEP6 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
631
632 illumina_count_q_score
633
634 Title: count_q_score
635 Function: Given a fastq (bz2 zipped or unzipped)
636 file path, creates a histogram of
637 the quality scores in the file
638 Usage: count_q_score($fastq, $log)
639 Args: 1) path to subsampled fastq file
640 2) log file object
641 Returns: JGI_SUCCESS
642 JGI_FAILURE
643 Comments: Generates a file named <fastq_path>.qhist that has
644 the quality score histogram.
645
646 @param fastq: source fastq file (full path)
647 @param log
648
649 @return reformatObqhistFile: output data file (to be added to readqc_files.txt)
650 @return pngFile: output plot file (to be added to readqc_files.txt)
651 @return htmlFile: output d3 interactive plot file (to be added to readqc_files.txt)
652
653 """
654 def illumina_count_q_score(fastq, log):
655 READ_OUTPUT_PATH = RQCReadQcConfig.CFG["output_path"]
656
657 sequnitFileName, _ = safe_basename(fastq, log)
658 sequnitFileNamePrefix = sequnitFileName.replace(".fastq", "").replace(".gz", "")
659
660 subsampleDir = "subsample"
661 subsamplePath = os.path.join(READ_OUTPUT_PATH, subsampleDir)
662
663 qualDir = "qual"
664 qualPath = os.path.join(READ_OUTPUT_PATH, qualDir)
665 make_dir(qualPath)
666 change_mod(qualPath, "0755")
667
668 reformatObqhistFile = os.path.join(subsamplePath, sequnitFileNamePrefix + ".reformat.obqhist.txt") ## base composition histogram
669
670 log.debug("obqhist file: %s", reformatObqhistFile)
671
672 rawDataMatrix = np.loadtxt(reformatObqhistFile, delimiter='\t', comments='#')
673 assert len(rawDataMatrix[1][:]) == 3
674
675 ## Qavg nrd percent
676 ## 0 1 2
677 fig, ax = plt.subplots()
678
679 markerSize = 5.0
680 lineWidth = 1.5
681
682 p1 = ax.plot(rawDataMatrix[:, 0], rawDataMatrix[:, 2], 'r', marker='o', markersize=markerSize, linewidth=lineWidth, alpha=0.5)
683 ax.set_xlabel("Average Read Quality", fontsize=12, alpha=0.5)
684 ax.set_ylabel("Fraction of Reads", fontsize=12, alpha=0.5)
685 ax.grid(color="gray", linestyle=':')
686
687 ## Add tooltip
688 mpld3.plugins.connect(fig, mpld3.plugins.PointLabelTooltip(p1[0], labels=list(rawDataMatrix[:, 2])))
689
690 pngFile = os.path.join(qualPath, sequnitFileNamePrefix + ".avg_read_quality_histogram.png")
691 htmlFile = os.path.join(qualPath, sequnitFileNamePrefix + ".avg_read_quality_histogram.html")
692
693 ## Save D3 interactive plot in html format
694 mpld3.save_html(fig, htmlFile)
695
696 ## Save Matplotlib plot in png format
697 plt.savefig(pngFile, dpi=fig.dpi)
698
699 return reformatObqhistFile, pngFile, htmlFile
700
701
702 """ STEP7 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
703
704 illumina_calculate_average_quality
705
706 Title: illumina_calculate_average_quality
707 Function: Given a fastq (subsampled) file, calculates average quality in 21 mer windows.
708 Usage: illumina_calculate_average_quality($fastq_path, $log)
709 Args: 1) path to subsampled fastq file
710 2) log file object
711 Returns: JGI_SUCCESS
712 JGI_FAILURE
713 Comments: Several output files are generated in the directory that
714 the script is run.
715 1) Text output file with 21mer start position, number of mers read,
716 total mers, and average accuracy of the bin
717 2) A gnuplot png file named <fastq_name>.21mer.qual.png
718
719 The function assumes that the fastq file exists.
720 The 21mer qual script was writtten by mli
721
722
723 @return retCode: success or failure
724 @return stat_file: plot data (to be added to readqc_files.txt)
725 @return pngFile: output plot (to be added to readqc_files.txt)
726
727 """
728 ## Removed!
729 ##def illumina_calculate_average_quality(fastq, log):
730
731
732
733 """ STEP8 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
734
735 illumina_find_common_motifs
736
737 Title: illumina_find_common_motifs
738 Function: Given a fastq (subsampled) file, finds most common N-string motifs.
739 Usage: illumina_find_common_motifs($fastq_path, $log)
740 Args: 1) path to subsampled fastq file
741 2) log file object
742 Returns: JGI_SUCCESS
743 JGI_FAILURE
744 Comments: An output file is generated in the directory
745 1) Text output summary file most common motifs and perecent total motifs.
746
747 The function assumes that the fastq file exists.
748 The nstutter script was writtten by jel
749
750
751 @param fastq: source fastq file (full path)
752 @param log
753
754 @return retCode: success or failure
755 @return nstutterStatFile: output stutter data file (to be added to readqc_files.txt)
756
757
758 """
759 def illumina_find_common_motifs(fastq, log):
760 ## Tools
761 cdir = os.path.dirname(__file__)
762 patterNFastqPlCmd = os.path.join(cdir, '../tools/patterN_fastq.pl') #RQCReadQcCommands.PATTERN_FASTQ_PL
763
764 sequnitFileName, exitCode = safe_basename(fastq, log)
765 sequnitFileNamePrefix = sequnitFileName.replace(".fastq", "").replace(".gz", "")
766
767 READ_OUTPUT_PATH = RQCReadQcConfig.CFG["output_path"]
768 stutterDir = "stutter"
769 stutterPath = os.path.join(READ_OUTPUT_PATH, stutterDir)
770 make_dir(stutterPath)
771 change_mod(stutterPath, "0755")
772
773 nstutterStatFile = os.path.join(stutterPath, sequnitFileNamePrefix + ".nstutter.stat")
774
775 ## ex) patterN_fastq.pl -analog -PCT 0.1 -in 7601.1.77813.CTTGTA.s0.01.fastq > 7601.1.77813.CTTGTA.s0.01.nstutter.stat ; wait;
776 makeStatFileCmd = "%s -analog -PCT 0.1 -in %s > %s " % (patterNFastqPlCmd, fastq, nstutterStatFile)
777 combinedCmd = "%s; wait; " % (makeStatFileCmd)
778
779 _, _, exitCode = run_sh_command(combinedCmd, True, log, True)
780
781 if exitCode != 0:
782 log.error("failed to run patterNFastqPlCmd. Exit code != 0.")
783 return RQCExitCodes.JGI_FAILURE, None
784
785 if os.path.isfile(nstutterStatFile):
786 log.info("N stutter stat file successfully created (%s)", nstutterStatFile)
787 else:
788 log.warning("Could not locate N stutter stat file %s", nstutterStatFile)
789 nstutterStatFile = "failed to generate"
790
791 return RQCExitCodes.JGI_SUCCESS, nstutterStatFile
792
793
794 """ STEP9 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
795
796 illumina_run_bwa
797
798 Title: illumina_run_bwa
799 Function: Given a fastq (subsampled) file path, runs bwa aligner
800 Reads are aligned to each other.
801 Usage: illumina_run_bwa($fastq_file_path, $log)
802 Args: 1) path to subsampled fastq file
803 2) log file object
804 Returns: JGI_SUCCESS
805 JGI_FAILURE
806 Comments: None.
807
808
809 @param fastq: source fastq file (full path)
810 @param log
811
812 @return retCode: success or failure
813 @return summary_file: output bwa summary file (to be added to readqc_files.txt)
814
815 """
816
817 ## REMOVED!
818 ##def illumina_run_bwa(fastq, log):
819
820 def illumina_run_dedupe(fastq, log):
821 ## Tools
822 cdir = os.path.dirname(__file__)
823 bbdedupeShCmd = os.path.join(cdir, '../../bbdedupe.sh') #RQCReadQcCommands.BBDEDUPE_SH
824
825 sequnitFileName, exitCode = safe_basename(fastq, log)
826 READ_OUTPUT_PATH = RQCReadQcConfig.CFG["output_path"]
827
828 dupDir = "dupes"
829 dupPath = os.path.join(READ_OUTPUT_PATH, dupDir)
830 make_dir(dupPath)
831 change_mod(dupPath, "0755")
832
833 dedupeSummaryFile = os.path.join(dupPath, sequnitFileName + ".bwa.summary")
834
835 ## dedupe.sh in=reads.fq s=0 ftr=49 ac=f int=f
836 xmx = "-Xmx23G"
837 bbdedupeShCmd = "%s %s in=%s out=null qin=33 ow=t s=0 ftr=49 ac=f int=f> %s 2>&1 " % (bbdedupeShCmd, xmx, fastq, dedupeSummaryFile)
838
839 _, _, exitCode = run_sh_command(bbdedupeShCmd, True, log, True)
840
841 if exitCode != 0:
842 log.error("Failed to run bbdedupeShCmd.sh")
843 return RQCExitCodes.JGI_FAILURE, None
844
845 return RQCExitCodes.JGI_SUCCESS, dedupeSummaryFile
846
847
848 """ STEP10 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
849
850 illumina_run_tagdust
851
852 Title: illumina_run_tagdust
853 Function: Given a fastq (subsampled) file path, runs tag dust to
854 find common illumina artifacts.
855 Usage: illumina_run_tagdust($fastq_file_path, $log)
856 Args: 1) path to subsampled fastq file
857 2) log file object
858 Returns: JGI_SUCCESS
859 JGI_FAILURE
860 Comments: None.
861
862
863 @param fastq: source fastq file (full path)
864 @param log
865
866 @return retCode: success or failure
867 @return tagdust_out: output tagdust file (to be added to readqc_files.txt)
868
869 """
870 ## No longer needed!!
871 ##def illumina_run_tagdust(fastq, log):
872
873
874
875 """ STEP11 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
876
877 illumina_detect_read_contam
878
879 @param fastq: source fastq file (full path)
880 @param firstBp: first bp length to cut for read contam detection
881 @param log
882
883 @return retCode: success or failure
884 @return outFileList: output duk stat file list (to be added to readqc_files.txt)
885 @return ratioResultDict: output stat value dict (to be added to readqc_stats.txt)
886
887 """
888 ##def illumina_detect_read_contam(fastq, log):
889 ## REMOVED!
890
891 # # def illumina_detect_read_contam2(fastq, firstBp, log):
892 ## REMOVED! 08302016
893
894
895 """
896 Contam removal by seal.sh
897
898 """
899 def illumina_detect_read_contam3(fastq, firstBp, log):
900 ## Tools
901 cdir = os.path.dirname(__file__)
902 sealShCmd = os.path.join(cdir, '../../seal.sh') #RQCReadQcCommands.SEAL_SH_CMD
903
904 sequnitFileName, exitCode = safe_basename(fastq, log)
905 sequnitFileNamePrefix = sequnitFileName.replace(".fastq", "").replace(".gz", "")
906
907 READ_OUTPUT_PATH = RQCReadQcConfig.CFG["output_path"]
908 qualDir = "qual"
909 qualPath = os.path.join(READ_OUTPUT_PATH, qualDir)
910 make_dir(qualPath)
911 change_mod(qualPath, "0755")
912
913 numBadFiles = 0
914 ratio = 0
915 outFileDict = {}
916 ratioResultDict = {}
917 contamStatDict = {}
918
919 catCmd, exitCode = get_cat_cmd(fastq, log)
920
921 ## TODO: remove JGI Contaminants from CONTAM_DBS
922 # CONTAM_DBS['artifact'] = ARTIFACT_FILE_NO_SPIKEIN
923 # CONTAM_DBS['artifact_50bp'] = ARTIFACT_FILE_NO_SPIKEIN ## 20131203 Added for 50bp contam
924 # CONTAM_DBS['DNA_spikein'] = ARTIFACT_FILE_DNA_SPIKEIN
925 # CONTAM_DBS['RNA_spikein'] = ARTIFACT_FILE_RNA_SPIKEIN
926 # CONTAM_DBS['contaminants'] = CONTAMINANTS
927 # CONTAM_DBS['fosmid'] = FOSMID_VECTOR
928 # CONTAM_DBS['mitochondrion'] = MITOCHONDRION_NCBI_REFSEQ
929 # CONTAM_DBS['phix'] = PHIX
930 # CONTAM_DBS['plastid'] = CHLOROPLAST_NCBI_REFSEQ
931 # CONTAM_DBS['rrna'] = GENERAL_RRNA_FILE
932 # CONTAM_DBS['microbes'] = MICROBES ## non-synthetic
933 # CONTAM_DBS['synthetic'] = SYNTHETIC
934 # CONTAM_DBS['adapters'] = ADAPTERS
935 for db in RQCContamDb.CONTAM_DBS.iterkeys():
936 if db == "artifact_50bp" and int(firstBp) == 20:
937 sealStatsFile = os.path.join(qualPath, sequnitFileNamePrefix + ".artifact_20bp.seal.stats")
938 else:
939 sealStatsFile = os.path.join(qualPath, sequnitFileNamePrefix + "." + db + ".seal.stats")
940
941 ## Localization file to /scratch/rqc
942 # log.info("Contam DB localization started for %s", db)
943 # localizedDb = localize_file(RQCContamDb.CONTAM_DBS[db], log)
944
945 ## 04262017 Skip localization temporarily until /scratch can be mounted
946 ## in shifter container
947 # if os.environ['NERSC_HOST'] == "genepool":
948 # localizedDb = localize_file(RQCContamDb.CONTAM_DBS[db], log)
949 # else:
950 # localizedDb = None
951 #
952 # if localizedDb is None:
953 # localizedDb = RQCContamDb.CONTAM_DBS[db] ## use the orig location
954 # else:
955 # log.info("Use the localized file, %s", localizedDb)
956 localizedDb = RQCContamDb.CONTAM_DBS[db]
957
958 ## 09112017 Manually add -Xmx23G
959 xmx = "-Xmx23G"
960 if db == "artifact_50bp":
961 cutCmd = "cut -c 1-%s | " % (firstBp)
962 cmd = "set -e; %s %s | %s %s in=stdin.fq out=null ref=%s k=22 hdist=0 stats=%s ow=t statscolumns=3 %s " % \
963 (catCmd, fastq, cutCmd, sealShCmd, localizedDb, sealStatsFile, xmx)
964 elif db == "microbes":
965 cmd = "%s in=%s out=null ref=%s hdist=0 mm=f mkf=0.5 ambig=random minlen=120 qtrim=rl trimq=10 stats=%s ow=t statscolumns=3 %s " % \
966 (sealShCmd, fastq, localizedDb, sealStatsFile, xmx)
967 else:
968 cmd = "%s in=%s out=null ref=%s k=22 hdist=0 stats=%s ow=t statscolumns=3 %s " % \
969 (sealShCmd, fastq, localizedDb, sealStatsFile, xmx)
970
971 _, _, exitCode = run_sh_command(cmd, True, log, True)
972
973 if exitCode != 0:
974 log.error("Failed to run seal.sh cmd")
975 return RQCExitCodes.JGI_FAILURE, None, None, None
976
977 ## Parsing seal output
978 if not os.path.isfile(sealStatsFile):
979 log.warning("Cannot open contam output file %s", sealStatsFile)
980 numBadFiles += 1
981 continue ## continue to next contam db
982
983 maxStatCount = 0
984 with open(sealStatsFile, "r") as sealFH:
985 for line in sealFH:
986 line.strip()
987 if line.find("#Matched") != -1:
988 ## ex) #Matched 1123123 77.31231%
989 toks = line.split()
990 assert len(toks) == 3
991 ratio = toks[-1].replace('%', '')
992
993 ## contamintaion stat
994 if not line.startswith('#'):
995 t = line.rstrip().split('\t')
996 # contamStatDict["%s:%s" % (db, t[0])] = t[2].replace('%', '')
997 if maxStatCount < 10 and t[0].startswith("gi|"):
998 # contamStatDict["contam:%s:%s" % (db, t[0])] = t[2].replace('%', '')
999 contamStatDict["contam:%s:%s" % (db, "|".join(t[0].split('|')[:2]))] = t[2].replace('%', '') ## save only gi part (RQC-906)
1000 maxStatCount += 1
1001
1002 ## RQC-743
1003 if db == "artifact_50bp" and int(firstBp) == 20:
1004 db = "artifact_20bp"
1005
1006 outFileDict[db + ".seal.stats"] = sealStatsFile
1007 log.debug("Contam db and matched ratio: %s = %f", RQCContamDb.CONTAM_KEYS[db], float(ratio))
1008 ratioResultDict[RQCContamDb.CONTAM_KEYS[db]] = float(ratio)
1009
1010 if numBadFiles:
1011 log.info("Number of bad I/O cases = %s", numBadFiles)
1012 return RQCExitCodes.JGI_FAILURE, None, None, None
1013
1014
1015 return RQCExitCodes.JGI_SUCCESS, outFileDict, ratioResultDict, contamStatDict
1016
1017
1018 """ STEP12 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1019
1020 illumina_sciclone_analysis
1021
1022 Title: illumina_sciclone_analysis
1023 Function: Takes path to fastq file and determines
1024 if it is from a multiplexed run or not
1025 Usage: illumina_sciclone_analysis($subfastq, $log)
1026 Args: 1) fastq file
1027 2) log file object
1028 Returns: JGI_SUCCESS
1029 JGI_FAILURE
1030 Comments: None.
1031
1032
1033 @param origFastq: source fastq file (full path)
1034 @param isPairedEnd: pair- or single-ended
1035 @param log
1036
1037 @return retCode: success or failure
1038 @return ratioResultDict: output stat value dict (to be added to readqc_stats.txt)
1039 @return dnaCountFile: output sam stat file (to be added to readqc_files.txt)
1040 @return rnaCountFile: output sam stat file (to be added to readqc_files.txt)
1041
1042
1043 """
1044
1045 ## Removed!
1046 ##def illumina_sciclone_analysis(origFastq, isPairedEnd, log, libName=None, isRna=None):
1047
1048 def illumina_sciclone_analysis2(origFastq, isPairedEnd, log, libName=None, isRna=None):
1049 ## detect lib is rna or not
1050 sequnitFileName, exitCode = safe_basename(origFastq, log)
1051 sequnitFileNamePrefix = sequnitFileName.replace(".fastq", "").replace(".gz", "")
1052
1053 # if libName is None and isRna is None:
1054 # _, _, libName, isRna = get_lib_info(sequnitFileNamePrefix, log) ## seqProjectId, ncbiOrganismName not used
1055 #
1056 # if isRna == "N/A":
1057 # log.error("Failed to get lib info for %s", sequnitFileNamePrefix)
1058 # return RQCExitCodes.JGI_FAILURE, -1, -1
1059
1060 if isRna == '1':
1061 isRna = True
1062
1063 elif isRna == '0':
1064 isRna = False
1065
1066 if isRna:
1067 log.debug("The lib is RNA (%s)", libName)
1068 else:
1069 log.debug("The lib is DNA (%s)", libName)
1070
1071 if isPairedEnd:
1072 log.debug("It's pair-ended.")
1073 else:
1074 log.debug("It's single-ended.")
1075
1076 ## output dir
1077 sciclone_dir = "sciclone_analysis"
1078 READ_OUTPUT_PATH = RQCReadQcConfig.CFG["output_path"]
1079 sciclone_path = os.path.join(READ_OUTPUT_PATH, sciclone_dir)
1080
1081 ## Define the subdirectory. If it exists already, remove it
1082 if os.path.isdir(sciclone_path):
1083 rm_dir(sciclone_path)
1084
1085 make_dir(sciclone_path)
1086 change_mod(sciclone_path, "0755")
1087
1088 ## NOTE: Save count file in analysis object
1089 dnaCountFile = None
1090 rnaCountFile = None
1091
1092 if isRna:
1093 rnaCountFile = os.path.join(sciclone_path, sequnitFileNamePrefix + "_bbduk_sciclone_rna_count.txt")
1094 else:
1095 dnaCountFile = os.path.join(sciclone_path, sequnitFileNamePrefix + "_bbduk_sciclone_dna_count.txt")
1096
1097 cdir = os.path.dirname(__file__)
1098 bbdukShCmd = os.path.join(cdir, '../../bbduk.sh') #RQCReadQcCommands.BBDUK_SH_CMD
1099 bbdukRnaDb = RQCReadQcReferenceDatabases.SCICLONE_RNA2
1100 # bbdukDnaDb = RQCReadQcReferenceDatabases.SCICLONE_DNA2
1101
1102 cmd = None
1103
1104 if isRna:
1105 ## Localization file to /scratch/rqc
1106 # log.info("Sciclone RNA ref DB localization started for %s", bbdukRnaDb)
1107 # localizedDb = localize_file(bbdukRnaDb, log)
1108
1109 ## 04262017 Skip localization temporarily until /scratch can be mounted
1110 ## in shifter container
1111 # if os.environ['NERSC_HOST'] == "genepool":
1112 # localizedDb = localize_file(bbdukRnaDb, log)
1113 # else:
1114 # localizedDb = None
1115 #
1116 # if localizedDb is None:
1117 # localizedDb = bbdukRnaDb ## use the orig location
1118 # else:
1119 # log.info("Use the localized file, %s", localizedDb)
1120
1121 localizedDb = bbdukRnaDb ## use the orig location
1122
1123 ## bbduk.sh in=7365.2.69553.AGTTCC.fastq.gz ref=/global/projectb/sandbox/gaag/bbtools/data/sciclone_rna.fa out=null fbm=t k=31 mbk=0 stats=sciclone2.txt
1124 cmd = "%s in=%s ref=%s out=null fbm=t k=31 mbk=0 stats=%s statscolumns=3 " % (bbdukShCmd, origFastq, localizedDb, rnaCountFile)
1125
1126 else:
1127 ## Localization file to /scratch/rqc
1128 # log.info("Sciclone DNA ref DB localization started for %s", bbdukDnaDb)
1129 # localizedDb = localize_file(bbdukDnaDb, log)
1130
1131 ## 04262017 Skip localization temporarily until /scratch can be mounted
1132 ## in shifter container
1133 # if os.environ['NERSC_HOST'] == "genepool":
1134 # localizedDb = localize_file(bbdukRnaDb, log)
1135 # else:
1136 # localizedDb = None
1137 #
1138 # if localizedDb is None:
1139 # localizedDb = bbdukRnaDb ## use the orig location
1140 # else:
1141 # log.info("Use the localized file, %s", localizedDb)
1142
1143 localizedDb = bbdukRnaDb ## use the orig location
1144
1145 ## bbduk.sh in=7257.1.64419.CACATTGTGAG.fastq.gz ref=/global/projectb/sandbox/gaag/bbtools/data/sciclone_dna.fa out=null fbm=t k=31 mbk=0 stats=sciclone1.txt
1146 cmd = "%s in=%s ref=%s out=null fbm=t k=31 mbk=0 stats=%s statscolumns=3 " % (bbdukShCmd, origFastq, localizedDb, dnaCountFile)
1147
1148 _, _, exitCode = run_sh_command(cmd, True, log, True)
1149
1150 if exitCode != 0:
1151 log.error("Failed to run bbduk.sh cmd")
1152 return RQCExitCodes.JGI_FAILURE, None, None
1153
1154 log.debug("rnaCountFile = %s", rnaCountFile)
1155 log.debug("dnaCountFile = %s", dnaCountFile)
1156
1157
1158 return RQCExitCodes.JGI_SUCCESS, dnaCountFile, rnaCountFile
1159
1160
1161 """ STEP13 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1162
1163 illumina_read_megablast
1164
1165 Title: illumina_read_megablast
1166 Function: Takes path(s) to bz2 zipped or gzipped fastq file
1167 and runs megablast against the reads.
1168 Usage: illumina_read_megablast(\@seq_files, $subsampledFile, $read_length, $log)
1169 Args: 1) reference to an array containing bz2 zipped or gzipped fastq file path(s);
1170 the files should all be compressed the same way
1171 2) subsampled fastq file
1172 3) read length
1173 4) log file object
1174 Returns: JGI_SUCCESS
1175 JGI_FAILURE
1176 Comments: None.
1177
1178
1179 @param subsampledFile: source fastq file (full path)
1180 @param log
1181
1182 @return retCode: success or failure
1183
1184 """
1185 ## No longer needed. Removed.
1186 ##def illumina_read_megablast(subsampledFile, read_num_to_pass, log, blastDbPath=None):
1187
1188
1189
1190 """ STEP14 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1191
1192 """
1193 ##def illumina_read_blastn_refseq_microbial(subsampledFile, log, blastDbPath=None):
1194 ## 12212015 sulsj REMOVED!
1195
1196
1197
1198 """ STEP14 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1199
1200 """
1201 def illumina_read_blastn_refseq_archaea(subsampledFile, log):
1202 ## Tools
1203 cdir = os.path.dirname(__file__)
1204 bbtoolsReformatShCmd = os.path.join(cdir, '../../reformat.sh') #RQCReadQcCommands.BBTOOLS_REFORMAT_CMD
1205
1206 ## verify the fastq file
1207 if not os.path.isfile(subsampledFile):
1208 log.error("Failed to find fastq file")
1209 return RQCExitCodes.JGI_FAILURE
1210
1211 log.info("Read level contamination analysis using blastn")
1212
1213 READ_OUTPUT_PATH = RQCReadQcConfig.CFG["output_path"]
1214
1215 ## output dir
1216 megablastDir = "megablast"
1217 megablastPath = os.path.join(READ_OUTPUT_PATH, megablastDir)
1218 make_dir(megablastPath)
1219 change_mod(megablastPath, "0755")
1220
1221 ## 20140929 Replaced with reformat.sh
1222 queryFastaFileName = "reads.fa"
1223
1224 ## reformat.sh for converting fastq to fasta
1225 cmd = "%s in=%s out=%s qin=33 qout=33 ow=t " % (bbtoolsReformatShCmd, subsampledFile, os.path.join(megablastPath, queryFastaFileName))
1226
1227 _, _, exitCode = run_sh_command(cmd, True, log, True)
1228
1229 if exitCode != 0:
1230 log.error("Failed to run reformat.sh to convert fastq to fasta: %s", cmd)
1231 return RQCExitCodes.JGI_FAILURE
1232
1233 megablastOutputFile = None
1234 db = "refseq.archaea"
1235
1236 log.info("---------------------------------------------")
1237 log.info("Start blastn search against %s", db)
1238 log.info("---------------------------------------------")
1239
1240 ## final output ==> READ_OUTPUT_PATH/megablast
1241 retCode, megablastOutputFile = run_blastplus_py(os.path.join(megablastPath, queryFastaFileName), db, log)
1242
1243 if retCode != RQCExitCodes.JGI_SUCCESS:
1244 if megablastOutputFile is None:
1245 log.error("Failed to run blastn against %s. Ret = %s", db, retCode)
1246 retCode = RQCExitCodes.JGI_FAILURE
1247 elif megablastOutputFile == -143:
1248 log.warning("Blast overtime. Skip the search against %s.", db)
1249 retCode = -143 ## blast overtime
1250 else:
1251 log.info("Successfully ran blastn of reads against %s", db)
1252 retCode = RQCExitCodes.JGI_SUCCESS
1253
1254
1255 return retCode
1256
1257
1258 """ STEP15 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1259
1260 """
1261 def illumina_read_blastn_refseq_bacteria(subsampledFile, log):
1262 ## Tools
1263 cdir = os.path.dirname(__file__)
1264 bbtoolsReformatShCmd = os.path.join(cdir, '../../reformat.sh') #RQCReadQcCommands.BBTOOLS_REFORMAT_CMD
1265
1266 ## verify the fastq file
1267 if not os.path.isfile(subsampledFile):
1268 log.error("Failed to find fastq file for blastn")
1269 return RQCExitCodes.JGI_FAILURE
1270
1271 log.info("Read level contamination analysis using blastn")
1272
1273 READ_OUTPUT_PATH = RQCReadQcConfig.CFG["output_path"]
1274
1275 ## output dir
1276 megablastDir = "megablast"
1277 megablastPath = os.path.join(READ_OUTPUT_PATH, megablastDir)
1278 make_dir(megablastPath)
1279 change_mod(megablastPath, "0755")
1280
1281 ## 20140929 Replaced with reformat.sh
1282 queryFastaFileName = "reads.fa"
1283
1284 ## reformat.sh for converting fastq to fasta
1285 cmd = "%s in=%s out=%s qin=33 qout=33 ow=t " % (bbtoolsReformatShCmd, subsampledFile, os.path.join(megablastPath, queryFastaFileName))
1286
1287 _, _, exitCode = run_sh_command(cmd, True, log, True)
1288
1289 if exitCode != 0:
1290 log.error("Failed to run reformat.sh to convert fastq to fasta: %s", cmd)
1291 return RQCExitCodes.JGI_FAILURE
1292
1293 megablastOutputFile = None
1294 db = "refseq.bacteria"
1295
1296 log.info("---------------------------------------------")
1297 log.info("Start blastn search against %s", db)
1298 log.info("---------------------------------------------")
1299
1300 ## final output ==> READ_OUTPUT_PATH/megablast
1301 retCode, megablastOutputFile = run_blastplus_py(os.path.join(megablastPath, queryFastaFileName), db, log)
1302
1303 if retCode != RQCExitCodes.JGI_SUCCESS:
1304 if megablastOutputFile is None:
1305 log.error("Failed to run blastn against %s. Ret = %s", db, retCode)
1306 retCode = RQCExitCodes.JGI_FAILURE
1307 elif megablastOutputFile == -143:
1308 log.warning("Blast overtime. Skip the search against %s.", db)
1309 retCode = -143 ## blast overtime
1310 else:
1311 log.info("Successfully ran blastn of reads against %s", db)
1312 retCode = RQCExitCodes.JGI_SUCCESS
1313
1314 return retCode
1315
1316
1317 """ STEP16 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1318
1319 """
1320 def illumina_read_blastn_nt(subsampledFile, log):
1321 ## Tools
1322 cdir = os.path.dirname(__file__)
1323 bbtoolsReformatShCmd = os.path.join(cdir, '../../reformat.sh') #RQCReadQcCommands.BBTOOLS_REFORMAT_CMD
1324
1325 ## verify the fastq file
1326 if not os.path.isfile(subsampledFile):
1327 log.error("Failed to find fastq file for blastn")
1328 return RQCExitCodes.JGI_FAILURE
1329
1330 log.info("Read level contamination analysis using blastn")
1331
1332 READ_OUTPUT_PATH = RQCReadQcConfig.CFG["output_path"]
1333
1334 ## output dir
1335 megablastDir = "megablast"
1336 megablastPath = os.path.join(READ_OUTPUT_PATH, megablastDir)
1337 make_dir(megablastPath)
1338 change_mod(megablastPath, "0755")
1339
1340 ## 20140929 Replaced with reformat.sh
1341 queryFastaFileName = "reads.fa"
1342
1343 ## reformat.sh
1344 cmd = "%s in=%s out=%s qin=33 qout=33 ow=t " % (bbtoolsReformatShCmd, subsampledFile, os.path.join(megablastPath, queryFastaFileName))
1345
1346 _, _, exitCode = run_sh_command(cmd, True, log, True)
1347
1348 if exitCode != 0:
1349 log.error("Failed to run reformat.sh to convert fastq to fasta: %s", cmd)
1350 return RQCExitCodes.JGI_FAILURE
1351
1352 megablastOutputFile = None
1353 db = "nt"
1354
1355 log.info("----------------------------------")
1356 log.info("Start blastn search against %s", db)
1357 log.info("----------------------------------")
1358
1359 ## final output ==> READ_OUTPUT_PATH/megablast
1360 retCode, megablastOutputFile = run_blastplus_py(os.path.join(megablastPath, queryFastaFileName), db, log)
1361
1362 if retCode != RQCExitCodes.JGI_SUCCESS:
1363 if megablastOutputFile is None:
1364 log.error("Failed to run blastn against %s. Ret = %s", db, retCode)
1365 retCode = RQCExitCodes.JGI_FAILURE
1366 elif megablastOutputFile == -143:
1367 log.warning("Blast overtime. Skip the search against %s.", db)
1368 retCode = -143 ## blast overtime
1369 else:
1370 log.info("Successfully ran blastn of reads against %s", db)
1371 retCode = RQCExitCodes.JGI_SUCCESS
1372
1373 return retCode
1374
1375
1376 """ STEP17 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1377 illumina_generate_index_sequence_detection_plot
1378
1379 """
1380 def illumina_generate_index_sequence_detection_plot(fastq, log, isMultiplexed=None): ## TO BE REMOVED!
1381 isMultiplexed = 0
1382 if not os.path.isfile(fastq):
1383 log.error("Failed to find the input fastq file, %s", fastq)
1384 return RQCExitCodes.JGI_FAILURE, None, None, None
1385 else:
1386 log.info("fastq file for index sequence analysis: %s", fastq)
1387
1388 sequnitFileName, exitCode = safe_basename(fastq, log)
1389 sequnitFileNamePrefix = sequnitFileName.replace(".fastq", "").replace(".gz", "")
1390
1391 # if isMultiplexed is None:
1392 # isMultiplexed = get_multiplex_info(sequnitFileNamePrefix, log)
1393
1394 #retCode = None
1395
1396 demultiplexStatsFile = None
1397 demultiplexPlotDataFile = None
1398 detectionPlotPngFile = None
1399 storedDemultiplexStatsFile = None
1400
1401 if int(isMultiplexed) == 1:
1402 log.info("Multiplexed - start analyzing...")
1403
1404 READ_OUTPUT_PATH = RQCReadQcConfig.CFG["output_path"]
1405 demul_dir = "demul"
1406 demulPath = os.path.join(READ_OUTPUT_PATH, demul_dir)
1407 make_dir(demulPath)
1408 change_mod(demulPath, "0755")
1409
1410 ## This version is sorted by percent for readability of stats
1411 demultiplexStatsFile = os.path.join(demulPath, sequnitFileNamePrefix + ".demultiplex_stats")
1412
1413 ## This version has index column and sort by index for plot
1414 demultiplexPlotDataFile = os.path.join(demulPath, sequnitFileNamePrefix + ".demultiplex_stats.tmp")
1415
1416 ## This path is relative to final qual location to be stored in analysis obj.
1417 detectionPlotPngFile = os.path.join(demulPath, sequnitFileNamePrefix + ".index_sequence_detection.png")
1418
1419 storedDemultiplexStatsFile = os.path.join(demulPath, sequnitFileNamePrefix + ".demultiplex_stats")
1420
1421 if not os.path.isfile(demultiplexStatsFile):
1422 indexSeq = None
1423 line = None
1424 header = None
1425 indexSeqCounter = {}
1426
1427 catCmd, exitCode = get_cat_cmd(fastq, log)
1428
1429 if fastq.endswith(".gz"):
1430 catCmd = "zcat" ## pigz does not work with subprocess
1431
1432 seqCount = 0
1433
1434 try:
1435 proc = subprocess.Popen([catCmd, fastq], bufsize=2 ** 16, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
1436
1437 while 1:
1438 line = proc.stdout.readline()
1439 if not line:
1440 break
1441
1442 ## First line is header
1443 line.strip()
1444 header = line
1445
1446 ## Get second line of record - sequence
1447 line = proc.stdout.readline()
1448
1449 ## Get third line - junk
1450 line = proc.stdout.readline()
1451
1452 ## Get the final line (4th line) - quality
1453 line = proc.stdout.readline()
1454
1455 ## Parse the header
1456 headerFields = header.split(":")
1457
1458 ## The last index is the index
1459 indexSeq = headerFields[-1].strip()
1460 assert indexSeq
1461
1462 ## Increment the counts and store the index
1463 if indexSeq in indexSeqCounter:
1464 indexSeqCounter[indexSeq] += 1
1465 else:
1466 indexSeqCounter[indexSeq] = 1
1467
1468 seqCount += 1
1469
1470 except Exception as e:
1471 if log:
1472 log.error("Exception in file reading: %s", e)
1473 log.error("Failed to read the given fastq file [%s]", fastq)
1474 log.error("Fastq header doesn't have the index sequence: %s", header)
1475 log.error("Index sequence analysis is skipped!")
1476
1477 return RQCExitCodes.JGI_SUCCESS, None, None, None
1478
1479 ## Open the output file handles for writing
1480 log.info("demultiplexPlotDataFile = %s", demultiplexPlotDataFile)
1481 log.info("detectionPlotPngFile = %s", detectionPlotPngFile)
1482 log.info("demultiplexStatsFile = %s", demultiplexStatsFile)
1483 log.info("storedDemultiplexStatsFile = %s", storedDemultiplexStatsFile)
1484
1485 plotDataFH = open(demultiplexPlotDataFile, "w")
1486 statsFH = open(demultiplexStatsFile, "w")
1487
1488 ## Count the total number of indexes found
1489 numIndexesFound = len(indexSeqCounter)
1490
1491 ## Store the data header information for printing
1492 reportHeader = """# Demultiplexing Summary
1493 #
1494 # Seq unit name: %s
1495 # Total sequences: %s
1496 # Total indexes found: %s
1497 # 1=indexSeq 2=index_sequence_count 3=percent_of_total
1498 #
1499 """ % (sequnitFileName, seqCount, numIndexesFound)
1500
1501 statsFH.write(reportHeader)
1502
1503 ## Sort by value, descending
1504 log.debug("Sort by value of indexSeqCounter")
1505 for indexSeq in sorted(indexSeqCounter, key=indexSeqCounter.get, reverse=True):
1506 perc = float(indexSeqCounter[indexSeq]) / float(seqCount) * 100
1507 l = "%s\t%s\t%.6f\n" % (indexSeq, indexSeqCounter[indexSeq], perc)
1508 statsFH.write(l)
1509
1510 ## Sort by index and add id column for plotting
1511 log.debug("Sort by index of indexSeqCounter")
1512 i = 1
1513 for indexSeq in sorted(indexSeqCounter.iterkeys()):
1514 perc = float(indexSeqCounter[indexSeq]) / float(seqCount) * 100
1515 l = "%s\t%s\t%s\t%.6f\n" % (i, indexSeq, indexSeqCounter[indexSeq], perc)
1516 plotDataFH.write(l)
1517 i += 1
1518
1519 plotDataFH.close()
1520 statsFH.close()
1521
1522 log.debug("demultiplex plotting...")
1523 ## matplotlib plotting
1524 # data
1525 # Index_seq_id Index_seq indexSeqCounter percent
1526 # 1 AAAAAAAAAAAA 320 0.000549
1527 # 2 AAAAAAAAAAAC 16 0.000027
1528 # 3 AAAAAAAAAAAG 8 0.000014
1529 # 4 AAAAAAAAAACA 4 0.000007
1530 # 5 AAAAAAAAAACG 2 0.000003
1531 # 6 AAAAAAAAAAGA 6 0.000010
1532 # 7 AAAAAAAAAATA 6 0.000010
1533
1534 # rawDataMatrix = np.loadtxt(demultiplexPlotDataFile, delimiter='\t', comments='#')
1535 # assert len(rawDataMatrix[1][:]) == 4
1536
1537 ## For a textfile with 4000x4000 words this is about 10 times faster than loadtxt.
1538 ## http://stackoverflow.com/questions/14985233/load-text-file-as-strings-using-numpy-loadtxt
1539 def load_data_file(fname):
1540 data = []
1541
1542 with open(fname, 'r') as FH:
1543 lineCnt = 0
1544 for line in FH:
1545 if lineCnt > 10000: ## experienced out of mem with a stat file with 9860976 index sequences
1546 log.warning("Too many index sequences. Only 10000 index sequences will be used for plotting.")
1547 break
1548 data.append(line.replace('\n', '').split('\t'))
1549 lineCnt += 1
1550
1551 return data
1552
1553 def column(matrix, i, opt):
1554 if opt == "int":
1555 return [int(row[i]) for row in matrix]
1556 elif opt == "float":
1557 return [float(row[i]) for row in matrix]
1558 else:
1559 return [row[i] for row in matrix]
1560
1561 rawDataMatrix = load_data_file(demultiplexPlotDataFile)
1562
1563 fig, ax = plt.subplots()
1564
1565 markerSize = 6.0
1566 lineWidth = 1.5
1567
1568 p1 = ax.plot(column(rawDataMatrix, 0, "int"), column(rawDataMatrix, 3, "float"), 'r', marker='o', markersize=markerSize, linewidth=lineWidth, label='N', alpha=0.5)
1569
1570 ax.set_xlabel("Index Sequence ID", fontsize=12, alpha=0.5)
1571 ax.set_ylabel("Fraction", fontsize=12, alpha=0.5)
1572 ax.grid(color="gray", linestyle=':')
1573
1574 ## Add tooltip
1575 labels = ["%s" % i for i in column(rawDataMatrix, 1, "str")]
1576
1577 ## Show index_seq in the plot
1578 for i in rawDataMatrix:
1579 ax.text(i[0], float(i[3]) + .2, "%s" % i[1])
1580
1581 mpld3.plugins.connect(fig, mpld3.plugins.PointLabelTooltip(p1[0], labels=labels))
1582
1583 detectionPlotHtml = os.path.join(demulPath, sequnitFileNamePrefix + ".index_sequence_detection.html")
1584
1585 ## Save D3 interactive plot in html format
1586 mpld3.save_html(fig, detectionPlotHtml)
1587
1588 ## Save Matplotlib plot in png format
1589 plt.savefig(detectionPlotPngFile, dpi=fig.dpi)
1590
1591 if exitCode != 0:
1592 log.error("Failed to create demulplex plot")
1593 return RQCExitCodes.JGI_FAILURE, None, None, None
1594
1595 log.info("demulplex stats and plot generation completed!")
1596
1597
1598 else:
1599 log.info("Not multiplexed - skip this analysis.")
1600 return RQCExitCodes.JGI_SUCCESS, None, None, None
1601
1602 if detectionPlotPngFile is not None and storedDemultiplexStatsFile is not None and os.path.isfile(
1603 detectionPlotPngFile) and os.path.isfile(storedDemultiplexStatsFile):
1604 return RQCExitCodes.JGI_SUCCESS, demultiplexStatsFile, detectionPlotPngFile, detectionPlotHtml
1605
1606 else:
1607 return RQCExitCodes.JGI_FAILURE, None, None, None
1608
1609
1610 """ STEP18 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1611 end_of_read_illumina_adapter_check
1612
1613 usage: kmercount_pos.py [-h] [-k <int>] [-c <int>] [-t <int>] [-p <file>]
1614 fastaFile fastqFile [fastqFile ...]
1615
1616 Count occurance of database kmers in reads
1617
1618 positional arguments:
1619 fastaFile Input FASTA file(s). Text or gzip
1620 fastqFile Input FASTQ file(s). Text or gzip
1621
1622 optional arguments:
1623 -h, --help show this help message and exit
1624 -k <int> kmer length (default: 16)
1625 -c <int> minimum allowed coverage (default: 2)
1626 -t <int> target coverage (default: 30)
1627 -p <file>, --plot <file> plot data and save as png to <file> (default: None)
1628
1629 * NOTE
1630 - RQC-383 04082014: Updated to the newest version of kmercount_pos.py (readqc ver 5.0.4)
1631
1632 """
1633 def end_of_read_illumina_adapter_check(firstSubsampledFastqFile, log):
1634 cdir = os.path.dirname(__file__)
1635 kmercountPosCmd = os.path.join(cdir, 'kmercount_pos.py') #RQCReadQcCommands.KMERCOUNT_POS_CMD
1636 adapterDbName = RQCReadQcReferenceDatabases.END_OF_READ_ILLUMINA_ADAPTER_CHECK_DB
1637
1638 READ_OUTPUT_PATH = RQCReadQcConfig.CFG["output_path"]
1639
1640 sequnitFileName, exitCode = safe_basename(firstSubsampledFastqFile, log)
1641 sequnitFileNamePrefix = sequnitFileName.replace(".fastq", "").replace(".gz", "")
1642
1643 plotFile = ""
1644 dataFile = ""
1645
1646 adapterCheckDir = "adapter"
1647 adapterCheckPath = os.path.join(READ_OUTPUT_PATH, adapterCheckDir)
1648 make_dir(adapterCheckPath)
1649 change_mod(adapterCheckPath, "0755")
1650
1651 plotFile = os.path.join(adapterCheckPath, sequnitFileNamePrefix + ".end_of_read_adapter_check.png") ## ignored
1652 dataFile = os.path.join(adapterCheckPath, sequnitFileNamePrefix + ".end_of_read_adapter_check.txt")
1653
1654 ## Localization file to /scratch/rqc
1655 log.info("illumina_adapter_check DB localization started for %s", adapterDbName)
1656
1657 # if os.environ['NERSC_HOST'] == "genepool":
1658 # localizedDb = localize_file(adapterDbName, log)
1659 # else:
1660 # localizedDb = None
1661 #
1662 # if localizedDb is None:
1663 # localizedDb = adapterDbName ## use the orig location
1664 # else:
1665 # log.info("Use the localized file, %s", localizedDb)
1666
1667 localizedDb = adapterDbName ## use the orig location
1668
1669 ## ex) kmercount_pos.py --plot plot.png Artifacts.adapters_primers_only.fa subsample.fastq > counts_by_pos.txt
1670 cmd = "%s --plot %s %s %s > %s " % (kmercountPosCmd, plotFile, localizedDb, firstSubsampledFastqFile, dataFile)
1671
1672 ## Run cmd
1673 _, _, exitCode = run_sh_command(cmd, True, log, True)
1674 assert exitCode == 0
1675
1676 ## mpld3 plots gen
1677 rawDataMatrix = np.loadtxt(dataFile, delimiter='\t', comments='#', skiprows=0)
1678 assert len(rawDataMatrix[1][:]) == 3 or len(rawDataMatrix[1][:]) == 5
1679
1680 ##pos read1 read2
1681 ## 0 1 2
1682
1683 ## This output file format is changed on 2013.06.26 (RQC-442)
1684 ##
1685 ## pos read1_count read1_perc read2_count read2_perc
1686 ##
1687 fig, ax = plt.subplots()
1688
1689 markerSize = 3.5
1690 lineWidth = 1.0
1691
1692 if len(rawDataMatrix[1][:]) != 5: ## support for old file
1693 p1 = ax.plot(rawDataMatrix[:, 0], rawDataMatrix[:, 1], 'r', marker='o', markersize=markerSize, linewidth=lineWidth, label="read1", alpha=0.5)
1694 p2 = ax.plot(rawDataMatrix[:, 0], rawDataMatrix[:, 2], 'g', marker='d', markersize=markerSize, linewidth=lineWidth, label="read2", alpha=0.5)
1695 ax.set_ylabel("Read Count with Database K-mer", fontsize=12, alpha=0.5)
1696
1697 else:
1698 p1 = ax.plot(rawDataMatrix[:, 0], rawDataMatrix[:, 2], 'r', marker='o', markersize=markerSize, linewidth=lineWidth, label="read1", alpha=0.5)
1699 p2 = ax.plot(rawDataMatrix[:, 0], rawDataMatrix[:, 4], 'g', marker='d', markersize=markerSize, linewidth=lineWidth, label="read2", alpha=0.5)
1700 ax.set_ylim([0, 100])
1701 ax.set_ylabel("Percent Reads with Database K-mer", fontsize=12, alpha=0.5)
1702
1703 ax.set_xlabel("Read Position", fontsize=12, alpha=0.5)
1704 ax.yaxis.set_label_coords(-0.095, 0.75)
1705 fontProp = FontProperties()
1706 fontProp.set_size("small")
1707 fontProp.set_family("Bitstream Vera Sans")
1708 ax.legend(loc=1, prop=fontProp)
1709 ax.grid(color="gray", linestyle=':')
1710
1711 ## Add tooltip
1712 mpld3.plugins.connect(fig, mpld3.plugins.PointLabelTooltip(p1[0], labels=list(rawDataMatrix[:, 1])))
1713 mpld3.plugins.connect(fig, mpld3.plugins.PointLabelTooltip(p2[0], labels=list(rawDataMatrix[:, 2])))
1714
1715 pngFile = os.path.join(adapterCheckPath, sequnitFileNamePrefix + ".end_of_read_adapter_check.png")
1716 htmlFile = os.path.join(adapterCheckPath, sequnitFileNamePrefix + ".end_of_read_adapter_check.html")
1717
1718 ## Save D3 interactive plot in html format
1719 mpld3.save_html(fig, htmlFile)
1720
1721 ## Save Matplotlib plot in png format
1722 plt.savefig(pngFile, dpi=fig.dpi)
1723
1724 if exitCode != 0:
1725 log.error("Failed to run kmercountPosCmd")
1726 return RQCExitCodes.JGI_FAILURE, None, None, None
1727
1728 if os.path.isfile(plotFile) and os.path.isfile(dataFile):
1729 log.info("kmercount_pos completed.")
1730 return RQCExitCodes.JGI_SUCCESS, dataFile, pngFile, htmlFile
1731
1732 else:
1733 log.error("cannot find the output files from kmercount_pos. kmercount_pos failed.")
1734 return RQCExitCodes.JGI_FAILURE, None, None, None
1735
1736
1737 """ STEP19 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1738
1739 insert_size_analysis
1740
1741 Using bbmerge.sh from bbtools, create insert size histogram (static/interactive) plots using D3 and data file
1742
1743 e.q.
1744 java -ea -Xmx200m -cp /usr/common/jgi/utilities/bbtools/prod-v32.28/lib/BBTools.jar jgi.BBMerge
1745 in=/global/projectb/scratch/brycef/rqc-dev/staging/00/00/66/26/6626.2.48981.TTCTCC.fastq ihist=ihist.txt
1746 Executing jgi.BBMerge [in=/global/projectb/scratch/brycef/rqc-dev/staging/00/00/66/26/6626.2.48981.TTCTCC.fastq, ihist=ihist.txt]
1747
1748 e.g.
1749 bbmerge.sh in=[path-to-fastq] hist=hist.txt
1750 - you should use the whole fastq, not just the subsampled fastq
1751
1752 """
1753 def insert_size_analysis(fastq, log):
1754 ## Tools
1755 cdir = os.path.dirname(__file__)
1756 bbmergeShCmd = os.path.join(cdir, '../../bbmerge.sh') #RQCReadQcCommands.BBMERGE_SH_CMD
1757
1758 READ_OUTPUT_PATH = RQCReadQcConfig.CFG["output_path"]
1759
1760 sequnitFileName, exitCode = safe_basename(fastq, log)
1761 sequnitFileNamePrefix = sequnitFileName.replace(".fastq", "").replace(".gz", "")
1762
1763 plotFile = ""
1764 dataFile = ""
1765
1766 insertSizeOutDir = "insert_size_analysis"
1767 insertSizeOutPath = os.path.join(READ_OUTPUT_PATH, insertSizeOutDir)
1768 make_dir(insertSizeOutPath)
1769 change_mod(insertSizeOutPath, "0755")
1770
1771 plotFile = os.path.join(insertSizeOutPath, sequnitFileNamePrefix + ".insert_size_histo.png")
1772 htmlFile = os.path.join(insertSizeOutPath, sequnitFileNamePrefix + ".insert_size_histo.html")
1773 dataFile = os.path.join(insertSizeOutPath, sequnitFileNamePrefix + ".insert_size_histo.txt")
1774
1775 ## TODO
1776 ## if it's single ended
1777 ## 1. rqcfilter.sh for adapter trim
1778 ## 2. reformat.sh for getting lhist
1779 ## 3. analyze lhist.txt
1780
1781 ## ex) bbmerge.sh in=7601.1.77813.CTTGTA.fastq.gz hist=.../insert_size_analysis/7601.1.77813.CTTGTA.insert_size_histo.txt
1782 ## reads=1000000 --> 1M reads are enough for insert size analysis
1783 cmd = "%s in=%s hist=%s reads=1000000 " % (bbmergeShCmd, fastq, dataFile)
1784
1785 ## Run cmd
1786 _, stdErr, exitCode = run_sh_command(cmd, True, log, True)
1787
1788 if exitCode != 0:
1789 log.error("Failed to run bbmerge_sh_cmd.")
1790 return RQCExitCodes.JGI_FAILURE, None, None, None, None
1791
1792 retCode = {}
1793
1794 ## File format
1795 ## BBMerge version 5.0
1796 ## Finished reading
1797 ## Total time: 8.410 seconds.
1798 ##
1799 ## Pairs: 1000000
1800 ## Joined: 556805 55.681%
1801 ## Ambiguous: 9665 0.967%
1802 ## No Solution: 433474 43.347%
1803 ## Too Short: 56 0.006%
1804 ## Avg Insert: 234.6
1805 ## Standard Deviation: 33.9
1806 ## Mode: 250
1807 ##
1808 ## Insert range: 26 - 290
1809 ## 90th percentile: 277
1810 ## 75th percentile: 262
1811 ## 50th percentile: 238
1812 ## 25th percentile: 211
1813 ## 10th percentile: 188
1814
1815 for l in stdErr.split('\n'):
1816 toks = l.split()
1817 if l.startswith("Total time"):
1818 retCode["total_time"] = toks[2]
1819 elif l.startswith("Reads"):
1820 retCode["num_reads"] = toks[1]
1821 elif l.startswith("Pairs"):
1822 retCode["num_reads"] = toks[1]
1823 elif l.startswith("Joined"):
1824 retCode["joined_num"] = toks[1]
1825 retCode["joined_perc"] = toks[2]
1826 elif l.startswith("Ambiguous"):
1827 retCode["ambiguous_num"] = toks[1]
1828 retCode["ambiguous_perc"] = toks[2]
1829 elif l.startswith("No Solution"):
1830 retCode["no_solution_num"] = toks[2]
1831 retCode["no_solution_perc"] = toks[3]
1832 elif l.startswith("Too Short"):
1833 retCode["too_short_num"] = toks[2]
1834 retCode["too_short_perc"] = toks[3]
1835 elif l.startswith("Avg Insert"):
1836 retCode["avg_insert"] = toks[2]
1837 elif l.startswith("Standard Deviation"):
1838 retCode["std_insert"] = toks[2]
1839 elif l.startswith("Mode"):
1840 retCode["mode_insert"] = toks[1]
1841 elif l.startswith("Insert range"):
1842 retCode["insert_range_start"] = toks[2]
1843 retCode["insert_range_end"] = toks[4]
1844 elif l.startswith("90th"):
1845 retCode["perc_90th"] = toks[2]
1846 elif l.startswith("50th"):
1847 retCode["perc_50th"] = toks[2]
1848 elif l.startswith("10th"):
1849 retCode["perc_10th"] = toks[2]
1850 elif l.startswith("75th"):
1851 retCode["perc_75th"] = toks[2]
1852 elif l.startswith("25th"):
1853 retCode["perc_25th"] = toks[2]
1854
1855 log.debug("Insert size stats: %s", str(retCode))
1856
1857 ## -------------------------------------------------------------------------
1858 ## plotting
1859 rawDataMatrix = np.loadtxt(dataFile, delimiter='\t', comments='#')
1860
1861 ## File format
1862 ## loc val
1863 ## 1 11
1864 try:
1865 rawDataX = rawDataMatrix[:, 0]
1866 rawDataY = rawDataMatrix[:, 1]
1867
1868 except IndexError:
1869 log.info("No solution from bbmerge.")
1870 return RQCExitCodes.JGI_SUCCESS, dataFile, None, None, retCode
1871
1872 fig, ax = plt.subplots()
1873
1874 markerSize = 5.0
1875 lineWidth = 1.5
1876
1877 p1 = ax.plot(rawDataX, rawDataY, 'r', marker='o', markersize=markerSize, linewidth=lineWidth, alpha=0.5)
1878
1879 ax.set_xlabel("Insert Size", fontsize=12, alpha=0.5)
1880 ax.set_ylabel("Count", fontsize=12, alpha=0.5)
1881
1882 ax.grid(color="gray", linestyle=':')
1883
1884 ## Add tooltip
1885 mpld3.plugins.connect(fig, mpld3.plugins.PointLabelTooltip(p1[0], labels=list(rawDataY)))
1886
1887 ## Save D3 interactive plot in html format
1888 mpld3.save_html(fig, htmlFile)
1889
1890 ## Save Matplotlib plot in png format
1891 plt.savefig(plotFile, dpi=fig.dpi)
1892
1893 ## Checking outputs
1894 if os.path.isfile(plotFile) and os.path.isfile(dataFile) and os.path.isfile(htmlFile):
1895 log.info("insert_size_analysis completed.")
1896 return RQCExitCodes.JGI_SUCCESS, dataFile, plotFile, htmlFile, retCode
1897
1898 else:
1899 log.error("cannot find the output files. insert_size_analysis failed.")
1900 return RQCExitCodes.JGI_FAILURE, None, None, None, None
1901
1902
1903 """ STEP20 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1904 gc_divergence_analysis
1905
1906
1907 """
1908 def gc_divergence_analysis(fastq, bIsPaired, srcDir, log):
1909 ## Tools
1910 # rscriptCmd = RQCReadQcCommands.RSCRIPT_CMD
1911
1912 READ_FILES_FILE = RQCReadQcConfig.CFG["files_file"]
1913 READ_OUTPUT_PATH = RQCReadQcConfig.CFG["output_path"]
1914
1915 sequnitFileName, exitCode = safe_basename(fastq, log)
1916 sequnitFileNamePrefix = sequnitFileName.replace(".fastq", "").replace(".gz", "")
1917
1918 qualDir = "qual"
1919 qualPath = os.path.join(READ_OUTPUT_PATH, qualDir)
1920 make_dir(qualPath)
1921 change_mod(qualPath, "0755")
1922
1923 ## get the bhist.txt produced by reformat.sh
1924 reformatBhistFile = None
1925 with open(READ_FILES_FILE, "r") as FFH:
1926 for l in FFH.readlines():
1927 if l.startswith("read base count text 1"):
1928 reformatBhistFile = l.split("=")[1].strip()
1929 assert os.path.isfile(reformatBhistFile), "reformatBhistFile does not exist: %s" % (l)
1930 break
1931
1932 assert reformatBhistFile, "ERROR: reformatBhistFile cannot be found in %s." % (READ_FILES_FILE)
1933 log.debug("gc_divergence_analysis(): bhist file = %s", reformatBhistFile)
1934
1935 gcDivergenceTransformedFile = os.path.join(qualPath, sequnitFileNamePrefix + ".gc.divergence.transformed.csv") ## gc divergence transformed csv
1936 gcDivergenceTransformedPlot = os.path.join(qualPath, sequnitFileNamePrefix + ".gc.divergence.transformed.png") ## gc divergence transformed plot
1937 gcDivergenceCoefficientsFile = os.path.join(qualPath, sequnitFileNamePrefix + ".gc.divergence.coefficients.csv") ## gc divergence coefficients csv
1938
1939 ## Check base composition histogram
1940 if not os.path.isfile(reformatBhistFile):
1941 log.error("Bhist file not found: %s", reformatBhistFile)
1942 return RQCExitCodes.JGI_FAILURE, None, None, None, None
1943
1944 ##
1945 ## Need R/3.1.2 b/c of library(dplyr) and library(tidyr) are only installed for the R/3.1.2 version
1946 ##
1947
1948 ## Transform bhist output from reformat.sh to csv
1949 if bIsPaired:
1950 # transformCmd = "module unload R; module load R/3.2.4; module load jgi-fastq-signal-processing/2.x; format_signal_data --input %s --output %s --read both --type composition " %\
1951 transformCmd = "module unload R; module load R/3.2.4; module load jgi-fastq-signal-processing/2.x; format_signal_data --input %s --output %s --read both --type composition " %\
1952 (reformatBhistFile, gcDivergenceTransformedFile)
1953
1954 # cmd = " ".join(["module load R; Rscript", "--vanilla", os.path.join(SRCDIR, "tools", "jgi-fastq-signal-processing", "format_signal_data"), ])
1955 # transformCmd = "module unload R; module load R; module load R/3.3.2; Rscript --vanilla %s --input %s --output %s --read both --type composition" %\
1956 if os.environ['NERSC_HOST'] in ("denovo", "cori"):
1957 transformCmd = "Rscript --vanilla %s --input %s --output %s --read both --type composition" %\
1958 (os.path.join(srcDir, "tools/jgi-fastq-signal-processing/bin", "format_signal_data"), reformatBhistFile, gcDivergenceTransformedFile)
1959 else:
1960 # transformCmd = "module unload R; module load R/3.2.4; module load jgi-fastq-signal-processing/2.x; format_signal_data --input %s --output %s --read 1 --type composition " %\
1961 transformCmd = "module unload R; module load R/3.2.4; module load jgi-fastq-signal-processing/2.x; format_signal_data --input %s --output %s --read 1 --type composition " %\
1962 (reformatBhistFile, gcDivergenceTransformedFile)
1963
1964 # transformCmd = "module unload R; module load R; module load R/3.3.2; Rscript --vanilla %s --input %s --output %s --read 1 --type composition" %\
1965 if os.environ['NERSC_HOST'] in ("denovo", "cori"):
1966 transformCmd = "Rscript --vanilla %s --input %s --output %s --read 1 --type composition" %\
1967 (os.path.join(srcDir, "tools/jgi-fastq-signal-processing/bin", "format_signal_data"), reformatBhistFile, gcDivergenceTransformedFile)
1968
1969 log.debug("Transform cmd = %s", transformCmd)
1970
1971 _, _, exitCode = run_sh_command(transformCmd, True, log, True)
1972
1973 if exitCode != 0:
1974 log.info("Failed to run GC_DIVERGENCE_TRANSFORM.")
1975 return -1, None, None, None, None
1976
1977 ## Compute divergence value
1978 coeff = []
1979 # modelCmd = "module unload R; module load R/3.2.4; module load jgi-fastq-signal-processing/2.x; model_read_signal --input %s --output %s " %\
1980 modelCmd = "module unload R; module load R/3.2.4; module load jgi-fastq-signal-processing/2.x; model_read_signal --input %s --output %s " %\
1981 (gcDivergenceTransformedFile, gcDivergenceCoefficientsFile)
1982
1983 # modelCmd = "module unload python; module unload R; module load R/3.3.2; Rscript --vanilla %s --input %s --output %s" %\
1984 if os.environ['NERSC_HOST'] in ("denovo", "cori"):
1985 modelCmd = "Rscript --vanilla %s --input %s --output %s" %\
1986 (os.path.join(srcDir, "tools/jgi-fastq-signal-processing/bin", "model_read_signal"), gcDivergenceTransformedFile, gcDivergenceCoefficientsFile)
1987
1988 log.debug("Model cmd = %s", modelCmd)
1989
1990 _, _, exitCode = run_sh_command(modelCmd, True, log, True)
1991
1992 if exitCode != 0:
1993 log.info("Failed to run GC_DIVERGENCE_MODEL.")
1994 return -1, None, None, None, None
1995
1996 ## Parsing coefficients.csv
1997 ## ex)
1998 ## "read","variable","coefficient"
1999 ## "Read 1","AT",2
2000 ## "Read 1","AT+CG",2.6
2001 ## "Read 1","CG",0.6
2002 ## "Read 2","AT",1.7
2003 ## "Read 2","AT+CG",2.3
2004 ## "Read 2","CG",0.7
2005 assert os.path.isfile(gcDivergenceCoefficientsFile), "GC divergence coefficient file not found."
2006
2007 with open(gcDivergenceCoefficientsFile) as COEFF_FH:
2008 for l in COEFF_FH.readlines():
2009 if l.startswith("\"read\""):
2010 continue ## skip header line
2011 toks = l.strip().split(',')
2012 assert len(toks) == 3, "Unexpected GC divergence coefficient file format."
2013 coeff.append({"read": toks[0], "variable": toks[1], "coefficient": toks[2]})
2014
2015 ## Plotting
2016 # plotCmd = "module unload R; module load R/3.2.4; module load jgi-fastq-signal-processing/2.x; plot_read_signal --input %s --output %s --type composition " %\
2017 plotCmd = "module unload R; module load R/3.2.4; module load jgi-fastq-signal-processing/2.x; plot_read_signal --input %s --output %s --type composition " %\
2018 (gcDivergenceTransformedFile, gcDivergenceTransformedPlot)
2019
2020 # plotCmd = "module unload python; module unload R; module load R/3.3.2; Rscript --vanilla %s --input %s --output %s --type composition" %\
2021 if os.environ['NERSC_HOST'] in ("denovo", "cori"):
2022 plotCmd = "Rscript --vanilla %s --input %s --output %s --type composition" %\
2023 (os.path.join(srcDir, "tools/jgi-fastq-signal-processing/bin", "plot_read_signal"), gcDivergenceTransformedFile, gcDivergenceTransformedPlot)
2024
2025 log.debug("Plot cmd = %s", plotCmd)
2026
2027 _, _, exitCode = run_sh_command(plotCmd, True, log, True)
2028
2029 if exitCode != 0:
2030 log.info("Failed to run GC_DIVERGENCE_PLOT.")
2031 return -1, None, None, None, None
2032
2033
2034 return RQCExitCodes.JGI_SUCCESS, gcDivergenceTransformedFile, gcDivergenceTransformedPlot, gcDivergenceCoefficientsFile, coeff
2035
2036
2037 """ STEP22 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2038
2039 cleanup_readqc
2040
2041 Cleaning up the ReadQC analysis directory with unwanted files.
2042
2043 @param log
2044
2045 @return retCode: always return success
2046
2047 """
2048 def cleanup_readqc(log):
2049 READ_OUTPUT_PATH = RQCReadQcConfig.CFG["output_path"]
2050
2051 ## Purge FASTQs
2052 cmd = "rm -f %s/%s/*.fastq " % (READ_OUTPUT_PATH, "subsample")
2053 _, _, exitCode = run_sh_command(cmd, True, log)
2054
2055 if exitCode != 0:
2056 log.error("Failed to execute %s; may be already purged.", cmd)
2057
2058 cmd = "rm -f %s/%s/*.fastq " % (READ_OUTPUT_PATH, "qual")
2059 _, _, exitCode = run_sh_command(cmd, True, log)
2060
2061 if exitCode != 0:
2062 log.error("Failed to execute %s; may be already purged.", cmd)
2063
2064 ## Purge FASTA qual and Fasta file
2065 cmd = "rm -f %s/%s/reads.fa " % (READ_OUTPUT_PATH, "megablast")
2066 _, _, exitCode = run_sh_command(cmd, True, log)
2067
2068 if exitCode != 0:
2069 log.error("Failed to execute %s; may be already purged.", cmd)
2070
2071 cmd = "rm -f %s/%s/reads.qual " % (READ_OUTPUT_PATH, "megablast")
2072 _, _, exitCode = run_sh_command(cmd, True, log)
2073
2074 if exitCode != 0:
2075 log.error("Failed to execute %s; may be already purged.", cmd)
2076
2077 ## Delete Sciclone files
2078 cmd = "rm -f %s/%s/*.fastq " % (READ_OUTPUT_PATH, "sciclone_analysis")
2079 _, _, exitCode = run_sh_command(cmd, True, log)
2080
2081 if exitCode != 0:
2082 log.error("Failed to execute %s; may be already purged.", cmd)
2083
2084 cmd = "rm -f %s/%s/*.fq " % (READ_OUTPUT_PATH, "sciclone_analysis")
2085 _, _, exitCode = run_sh_command(cmd, True, log)
2086
2087 if exitCode != 0:
2088 log.error("Failed to execute %s; may be already purged.", cmd)
2089
2090 cmd = "rm -f %s/%s/*.sam " % (READ_OUTPUT_PATH, "sciclone_analysis")
2091 _, _, exitCode = run_sh_command(cmd, True, log)
2092
2093 if exitCode != 0:
2094 log.error("Failed to execute %s; may be already purged.", cmd)
2095
2096 cmd = "rm -f %s/%s/*.sai " % (READ_OUTPUT_PATH, "sciclone_analysis")
2097 _, _, exitCode = run_sh_command(cmd, True, log)
2098
2099 if exitCode != 0:
2100 log.error("Failed to execute %s; may be already purged.", cmd)
2101
2102 ## Purge Blast files
2103 cmd = "rm -f %s/%s/megablast*v*JFfTIT " % (READ_OUTPUT_PATH, "megablast")
2104 _, _, exitCode = run_sh_command(cmd, True, log)
2105
2106 if exitCode != 0:
2107 log.error("Failed to execute %s; may be already purged.", cmd)
2108
2109 ## purge megablast.reads.fa.v.nt.FmLD2a10p90E30JFfTITW45; megablast.reads.fa.v.refseq.microbial.FmLD2a10p90E30JFfTITW45
2110 cmd = "rm -f %s/%s/megablast*v*FfTITW45 " % (READ_OUTPUT_PATH, "megablast")
2111 _, _, exitCode = run_sh_command(cmd, True, log)
2112
2113 if exitCode != 0:
2114 log.error("Failed to execute %s; may be already purged.", cmd)
2115
2116
2117 return RQCExitCodes.JGI_SUCCESS
2118
2119
2120 ## ===========================================================================================================================
2121
2122
2123 """ For NEW STEP4
2124
2125 QC plot generation using the outputs from reformat.sh
2126
2127 """
2128 def gen_average_base_position_quality_plot(fastq, bIsPaired, log):
2129 READ_OUTPUT_PATH = RQCReadQcConfig.CFG["output_path"]
2130
2131 sequnitFileName, _ = safe_basename(fastq, log)
2132 sequnitFileNamePrefix = sequnitFileName.replace(".fastq", "").replace(".gz", "")
2133
2134 subsampleDir = "subsample"
2135 subsamplePath = os.path.join(READ_OUTPUT_PATH, subsampleDir)
2136
2137 qualDir = "qual"
2138 qualPath = os.path.join(READ_OUTPUT_PATH, qualDir)
2139 make_dir(qualPath)
2140 change_mod(qualPath, "0755")
2141
2142 reformatQhistFile = os.path.join(subsamplePath, sequnitFileNamePrefix + ".reformat.qhist.txt") ## Average Base Position Quality
2143
2144 log.debug("qhist file: %s", reformatQhistFile)
2145
2146 ## Gen Average Base Position Quality Plot
2147 if not os.path.isfile(reformatQhistFile):
2148 log.error("Qhist file not found: %s", reformatQhistFile)
2149 return None, None, None
2150
2151 ## New data format
2152 ## Load data from txt
2153 rawDataMatrix = np.loadtxt(reformatQhistFile, delimiter='\t', comments='#', skiprows=0)
2154 assert len(rawDataMatrix[1][:]) == 5 or len(rawDataMatrix[1][:]) == 3
2155
2156 ## New data (paired)
2157 # BaseNum Read1_linear Read1_log Read2_linear Read2_log
2158 # 1 33.469 30.347 32.459 29.127
2159 # 2 33.600 32.236 32.663 29.532
2160 # 3 33.377 30.759 32.768 29.719
2161
2162 fig, ax = plt.subplots()
2163
2164 markerSize = 3.5
2165 lineWidth = 1.0
2166 p1 = ax.plot(rawDataMatrix[:, 0], rawDataMatrix[:, 1], 'r', marker='o', markersize=markerSize, linewidth=lineWidth, label='read1')
2167
2168 if bIsPaired:
2169 p2 = ax.plot(rawDataMatrix[:, 0], rawDataMatrix[:, 3], 'g', marker='d', markersize=markerSize, linewidth=lineWidth, label='read2')
2170
2171 ax.set_xlabel("Read Position", fontsize=12, alpha=0.5)
2172 ax.set_ylabel("Average Quality Score", fontsize=12, alpha=0.5)
2173 ax.set_ylim([0, 45])
2174 fontProp = FontProperties()
2175 fontProp.set_size("small")
2176 fontProp.set_family("Bitstream Vera Sans")
2177 ax.legend(loc=1, prop=fontProp)
2178 ax.grid(color="gray", linestyle=':')
2179
2180 ## Add tooltip
2181 mpld3.plugins.connect(fig, mpld3.plugins.PointLabelTooltip(p1[0], labels=list(rawDataMatrix[:, 1])))
2182
2183 if bIsPaired:
2184 mpld3.plugins.connect(fig, mpld3.plugins.PointLabelTooltip(p2[0], labels=list(rawDataMatrix[:, 3])))
2185
2186 pngFile = os.path.join(qualPath, sequnitFileNamePrefix + ".r1_r2_baseposqual.png")
2187 htmlFile = os.path.join(qualPath, sequnitFileNamePrefix + ".r1_r2_baseposqual.html")
2188
2189 ## Save D3 interactive plot in html format
2190 mpld3.save_html(fig, htmlFile)
2191
2192 ## Save Matplotlib plot in png format
2193 plt.savefig(pngFile, dpi=fig.dpi)
2194
2195 return reformatQhistFile, pngFile, htmlFile
2196
2197
2198 def gen_average_base_position_quality_boxplot(fastq, log):
2199 READ_OUTPUT_PATH = RQCReadQcConfig.CFG["output_path"]
2200
2201 sequnitFileName, _ = safe_basename(fastq, log)
2202 sequnitFileNamePrefix = sequnitFileName.replace(".fastq", "").replace(".gz", "")
2203
2204 subsampleDir = "subsample"
2205 subsamplePath = os.path.join(READ_OUTPUT_PATH, subsampleDir)
2206
2207 qualDir = "qual"
2208 qualPath = os.path.join(READ_OUTPUT_PATH, qualDir)
2209 make_dir(qualPath)
2210 change_mod(qualPath, "0755")
2211
2212 reformatBqhistFile = os.path.join(subsamplePath, sequnitFileNamePrefix + ".reformat.bqhist.txt") ## Average Base Position Quality Boxplot
2213
2214 log.debug("qhist file: %s", reformatBqhistFile)
2215
2216 ## Gen Average Base Position Quality Boxplot
2217 if not os.path.isfile(reformatBqhistFile):
2218 log.error("Bqhist file not found: %s", reformatBqhistFile)
2219 return None, None, None, None, None
2220
2221 ## New data format (paired)
2222 # 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
2223 ##BaseNum count_1 min_1 max_1 mean_1 Q1_1 med_1 Q3_1 LW_1 RW_1 count_2 min_2 max_2 mean_2 Q1_2 med_2 Q3_2 LW_2 RW_2
2224 # 0 6900 0 36 33.48 33 34 34 29 36 6900 0 36 33.48 33 34 34 29 36
2225
2226 rawDataMatrix = np.loadtxt(reformatBqhistFile, delimiter='\t', comments='#', skiprows=0)
2227 assert len(rawDataMatrix[1][:]) == 19 or len(rawDataMatrix[1][:]) == 10
2228
2229 bIsPaired = True
2230
2231 if len(rawDataMatrix[1][:]) == 10:
2232 bIsPaired = False
2233
2234 ## create data for boxplot
2235 boxplot_data_r1 = []
2236 boxplot_data_r2 = []
2237
2238 for i in rawDataMatrix:
2239 idx = int(i[0]) - 1 ## read base loc
2240
2241 spread = [rawDataMatrix[idx, 5], rawDataMatrix[idx, 7]] # Q1 ~ Q3
2242 center = [rawDataMatrix[idx, 6]] # median
2243 flier_high = [rawDataMatrix[idx, 8]] # whisker lW 2%
2244 flier_low = [rawDataMatrix[idx, 9]] # whisker rW 98%
2245 boxplot_data_r1.append(np.concatenate((spread, center, flier_high, flier_low), 0))
2246
2247 if bIsPaired:
2248 spread = [rawDataMatrix[idx, 14], rawDataMatrix[idx, 16]] # Q1 ~ Q3
2249 center = [rawDataMatrix[idx, 15]] # median
2250 flier_high = [rawDataMatrix[idx, 17]] # whisker lW 2%
2251 flier_low = [rawDataMatrix[idx, 18]] # whisker rW 98%
2252 boxplot_data_r2.append(np.concatenate((spread, center, flier_high, flier_low), 0))
2253
2254 fig, ax = plt.subplots()
2255 ax.boxplot(boxplot_data_r1)
2256 plt.subplots_adjust(left=0.06, right=0.9, top=0.9, bottom=0.1)
2257
2258 F = plt.gcf()
2259
2260 ## How to get the current size?
2261 ## DPI = F.get_dpi() ## = 80
2262 ## DefaultSize = F.get_size_inches() ## = (8, 6)
2263 F.set_size_inches(18, 6) ## plot size (w, h)
2264
2265 ax.set_xlabel("Read Position", fontsize=11, alpha=0.5)
2266 ax.set_ylabel("Quality Score (Solexa Scale: 40=Highest, -15=Lowest)", fontsize=11, alpha=0.5)
2267
2268 ax.set_ylim([-20, 45])
2269 ax.yaxis.grid(True, linestyle=':', which="major")
2270
2271 majorLocator_x = MultipleLocator(5)
2272 majorFormatter = FormatStrFormatter("%d")
2273 minorLocator = MultipleLocator(1)
2274
2275 ax.xaxis.set_major_locator(majorLocator_x)
2276 ax.xaxis.set_major_formatter(majorFormatter)
2277 ax.xaxis.set_minor_locator(minorLocator)
2278
2279 majorLocator_y = MultipleLocator(5)
2280 minorLocator = MultipleLocator(1)
2281 ax.yaxis.set_major_locator(majorLocator_y)
2282 ax.yaxis.set_minor_locator(minorLocator)
2283
2284 pngFileR1 = os.path.join(qualPath, sequnitFileNamePrefix + ".r1_average_base_position_quality_boxplot.png")
2285 htmlFileR1 = os.path.join(qualPath, sequnitFileNamePrefix + ".r1_average_base_position_quality_boxplot.html")
2286
2287 ## Save D3 interactive plot in html format
2288 mpld3.save_html(fig, htmlFileR1)
2289
2290 ## Save Matplotlib plot in png format
2291 plt.savefig(pngFileR1, dpi=fig.dpi)
2292
2293 plotPngPlotFileR2 = None
2294 plotHtmlPlotFileR2 = None
2295
2296 if bIsPaired:
2297 fig, ax = plt.subplots()
2298 ax.boxplot(boxplot_data_r2)
2299 plt.subplots_adjust(left=0.06, right=0.9, top=0.9, bottom=0.1)
2300
2301 F = plt.gcf()
2302
2303 ## How to get the current size?
2304 ## DPI = F.get_dpi() ## = 80
2305 ## DefaultSize = F.get_size_inches() ## = (8, 6)
2306 F.set_size_inches(18, 6) ## plot size (w, h)
2307
2308 ax.set_xlabel("Read Position", fontsize=11, alpha=0.5)
2309 ax.set_ylabel("Quality Score (Solexa Scale: 40=Highest, -15=Lowest)", fontsize=11, alpha=0.5)
2310
2311 ax.set_ylim([-20, 45])
2312 ax.yaxis.grid(True, linestyle=':', which='major')
2313
2314 majorLocator_x = MultipleLocator(5)
2315 majorFormatter = FormatStrFormatter('%d')
2316 minorLocator = MultipleLocator(1)
2317
2318 ax.xaxis.set_major_locator(majorLocator_x)
2319 ax.xaxis.set_major_formatter(majorFormatter)
2320 ax.xaxis.set_minor_locator(minorLocator)
2321
2322 majorLocator_y = MultipleLocator(5)
2323 minorLocator = MultipleLocator(1)
2324 ax.yaxis.set_major_locator(majorLocator_y)
2325 ax.yaxis.set_minor_locator(minorLocator)
2326
2327 plotPngPlotFileR2 = os.path.join(qualPath, sequnitFileNamePrefix + ".r2_average_base_position_quality_boxplot.png")
2328 plotHtmlPlotFileR2 = os.path.join(qualPath, sequnitFileNamePrefix + ".r2_average_base_position_quality_boxplot.html")
2329
2330 ## Save D3 interactive plot in html format
2331 mpld3.save_html(fig, plotHtmlPlotFileR2)
2332
2333 ## Save Matplotlib plot in png format
2334 plt.savefig(plotPngPlotFileR2, dpi=fig.dpi)
2335
2336
2337 return reformatBqhistFile, pngFileR1, plotPngPlotFileR2, htmlFileR1, plotHtmlPlotFileR2
2338
2339
2340 def gen_cycle_nucleotide_composition_plot(fastq, readLength, isPairedEnd, log):
2341 READ_OUTPUT_PATH = RQCReadQcConfig.CFG["output_path"]
2342
2343 sequnitFileName, _ = safe_basename(fastq, log)
2344 sequnitFileNamePrefix = sequnitFileName.replace(".fastq", "").replace(".gz", "")
2345
2346 subsampleDir = "subsample"
2347 subsamplePath = os.path.join(READ_OUTPUT_PATH, subsampleDir)
2348
2349 qualDir = "qual"
2350 qualPath = os.path.join(READ_OUTPUT_PATH, qualDir)
2351 make_dir(qualPath)
2352 change_mod(qualPath, "0755")
2353
2354 reformatBhistFile = os.path.join(subsamplePath, sequnitFileNamePrefix + ".reformat.bhist.txt") ## base composition histogram
2355
2356 log.debug("gen_cycle_nucleotide_composition_plot(): bhist file = %s", reformatBhistFile)
2357
2358 ## Genbase composition histogram
2359 if not os.path.isfile(reformatBhistFile):
2360 log.error("Bhist file not found: %s", reformatBhistFile)
2361 return None, None, None, None, None
2362
2363 ## data
2364 # 0 1 2 3 4 5
2365 ##Pos A C G T N
2366 # 0 0.15111 0.26714 0.51707 0.06412 0.00056
2367 # 1 0.20822 0.20773 0.25543 0.32795 0.00068
2368
2369 rawDataMatrix = np.loadtxt(reformatBhistFile, delimiter='\t', comments='#')
2370 assert len(rawDataMatrix[1][:]) == 6
2371
2372 if isPairedEnd:
2373 rawDataR1 = rawDataMatrix[:readLength - 1][:]
2374 rawDataR2 = rawDataMatrix[readLength:][:]
2375
2376 ## r1 ------------------------------------------------------------------
2377 fig, ax = plt.subplots()
2378
2379 markerSize = 2.5
2380 lineWidth = 1.0
2381 p2 = ax.plot(rawDataR1[:, 0], rawDataR1[:, 1], 'r', marker='o', markersize=markerSize, linewidth=lineWidth, label='A', alpha=0.5)
2382 p3 = ax.plot(rawDataR1[:, 0], rawDataR1[:, 4], 'g', marker='s', markersize=markerSize, linewidth=lineWidth, label='T', alpha=0.5)
2383 p4 = ax.plot(rawDataR1[:, 0], rawDataR1[:, 3], 'b', marker='*', markersize=markerSize, linewidth=lineWidth, label='G', alpha=0.5)
2384 p5 = ax.plot(rawDataR1[:, 0], rawDataR1[:, 2], 'm', marker='d', markersize=markerSize, linewidth=lineWidth, label='C', alpha=0.5)
2385 p6 = ax.plot(rawDataR1[:, 0], rawDataR1[:, 5], 'c', marker='v', markersize=markerSize, linewidth=lineWidth, label='N', alpha=0.5)
2386
2387 ax.set_xlabel("Read Position", fontsize=12, alpha=0.5)
2388 ax.set_ylabel("Fraction", fontsize=12, alpha=0.5)
2389 fontProp = FontProperties()
2390 fontProp.set_size("small")
2391 fontProp.set_family("Bitstream Vera Sans")
2392 ax.legend(loc=1, prop=fontProp)
2393 ax.grid(color="gray", linestyle=':')
2394
2395 ## Add tooltip
2396 mpld3.plugins.connect(fig, mpld3.plugins.PointLabelTooltip(p2[0], labels=list(rawDataR1[:, 1])))
2397 mpld3.plugins.connect(fig, mpld3.plugins.PointLabelTooltip(p3[0], labels=list(rawDataR1[:, 4])))
2398 mpld3.plugins.connect(fig, mpld3.plugins.PointLabelTooltip(p4[0], labels=list(rawDataR1[:, 3])))
2399 mpld3.plugins.connect(fig, mpld3.plugins.PointLabelTooltip(p5[0], labels=list(rawDataR1[:, 2])))
2400 mpld3.plugins.connect(fig, mpld3.plugins.PointLabelTooltip(p6[0], labels=list(rawDataR1[:, 5])))
2401
2402 pngFileR1 = os.path.join(qualPath, sequnitFileNamePrefix + ".cycle_nucl_composition_r1.png")
2403 htmlFileR1 = os.path.join(qualPath, sequnitFileNamePrefix + ".cycle_nucl_composition_r1.html")
2404
2405 ## Save D3 interactive plot in html format
2406 mpld3.save_html(fig, htmlFileR1)
2407
2408 ## Save Matplotlib plot in png format
2409 plt.savefig(pngFileR1, dpi=fig.dpi)
2410
2411 ## r2 ------------------------------------------------------------------
2412 fig, ax = plt.subplots()
2413
2414 markerSize = 2.5
2415 lineWidth = 1.0
2416 p2 = ax.plot([(x - readLength) for x in rawDataR2[:, 0]], rawDataR2[:, 1], 'r', marker='o', markersize=markerSize, linewidth=lineWidth, label='A', alpha=0.5)
2417 p3 = ax.plot([(x - readLength) for x in rawDataR2[:, 0]], rawDataR2[:, 4], 'g', marker='s', markersize=markerSize, linewidth=lineWidth, label='T', alpha=0.5)
2418 p4 = ax.plot([(x - readLength) for x in rawDataR2[:, 0]], rawDataR2[:, 3], 'b', marker='*', markersize=markerSize, linewidth=lineWidth, label='G', alpha=0.5)
2419 p5 = ax.plot([(x - readLength) for x in rawDataR2[:, 0]], rawDataR2[:, 2], 'm', marker='d', markersize=markerSize, linewidth=lineWidth, label='C', alpha=0.5)
2420 p6 = ax.plot([(x - readLength) for x in rawDataR2[:, 0]], rawDataR2[:, 5], 'c', marker='v', markersize=markerSize, linewidth=lineWidth, label='N', alpha=0.5)
2421
2422 ax.set_xlabel("Read Position", fontsize=12, alpha=0.5)
2423 ax.set_ylabel("Fraction", fontsize=12, alpha=0.5)
2424 fontProp = FontProperties()
2425 fontProp.set_size("small")
2426 fontProp.set_family("Bitstream Vera Sans")
2427 ax.legend(loc=1, prop=fontProp)
2428 ax.grid(color="gray", linestyle=':')
2429
2430 ## Add tooltip
2431 mpld3.plugins.connect(fig, mpld3.plugins.PointLabelTooltip(p2[0], labels=list(rawDataR2[:, 1])))
2432 mpld3.plugins.connect(fig, mpld3.plugins.PointLabelTooltip(p3[0], labels=list(rawDataR2[:, 4])))
2433 mpld3.plugins.connect(fig, mpld3.plugins.PointLabelTooltip(p4[0], labels=list(rawDataR2[:, 3])))
2434 mpld3.plugins.connect(fig, mpld3.plugins.PointLabelTooltip(p5[0], labels=list(rawDataR2[:, 2])))
2435 mpld3.plugins.connect(fig, mpld3.plugins.PointLabelTooltip(p6[0], labels=list(rawDataR2[:, 5])))
2436
2437 plotPngPlotFileR2 = os.path.join(qualPath, sequnitFileNamePrefix + ".cycle_nucl_composition_r2.png")
2438 plotHtmlPlotFileR2 = os.path.join(qualPath, sequnitFileNamePrefix + ".cycle_nucl_composition_r2.html")
2439
2440 ## Save D3 interactive plot in html format
2441 mpld3.save_html(fig, plotHtmlPlotFileR2)
2442
2443 ## Save Matplotlib plot in png format
2444 plt.savefig(plotPngPlotFileR2, dpi=fig.dpi)
2445
2446 return reformatBhistFile, pngFileR1, htmlFileR1, plotPngPlotFileR2, plotHtmlPlotFileR2
2447
2448 else:
2449 fig, ax = plt.subplots()
2450
2451 markerSize = 2.5
2452 lineWidth = 1.0
2453 p2 = ax.plot(rawDataMatrix[:, 0], rawDataMatrix[:, 1], 'r', marker='o', markersize=markerSize, linewidth=lineWidth, label='A', alpha=0.5)
2454 p3 = ax.plot(rawDataMatrix[:, 0], rawDataMatrix[:, 4], 'g', marker='s', markersize=markerSize, linewidth=lineWidth, label='T', alpha=0.5)
2455 p4 = ax.plot(rawDataMatrix[:, 0], rawDataMatrix[:, 3], 'b', marker='*', markersize=markerSize, linewidth=lineWidth, label='G', alpha=0.5)
2456 p5 = ax.plot(rawDataMatrix[:, 0], rawDataMatrix[:, 2], 'm', marker='d', markersize=markerSize, linewidth=lineWidth, label='C', alpha=0.5)
2457 p6 = ax.plot(rawDataMatrix[:, 0], rawDataMatrix[:, 5], 'c', marker='v', markersize=markerSize, linewidth=lineWidth, label='N', alpha=0.5)
2458
2459 ax.set_xlabel("Read Position", fontsize=12, alpha=0.5)
2460 ax.set_ylabel("Fraction", fontsize=12, alpha=0.5)
2461 fontProp = FontProperties()
2462 fontProp.set_size("small")
2463 fontProp.set_family("Bitstream Vera Sans")
2464 ax.legend(loc=1, prop=fontProp)
2465 ax.grid(color="gray", linestyle=':')
2466
2467 ## Add tooltip
2468 mpld3.plugins.connect(fig, mpld3.plugins.PointLabelTooltip(p2[0], labels=list(rawDataMatrix[:, 1])))
2469 mpld3.plugins.connect(fig, mpld3.plugins.PointLabelTooltip(p3[0], labels=list(rawDataMatrix[:, 4])))
2470 mpld3.plugins.connect(fig, mpld3.plugins.PointLabelTooltip(p4[0], labels=list(rawDataMatrix[:, 3])))
2471 mpld3.plugins.connect(fig, mpld3.plugins.PointLabelTooltip(p5[0], labels=list(rawDataMatrix[:, 2])))
2472 mpld3.plugins.connect(fig, mpld3.plugins.PointLabelTooltip(p6[0], labels=list(rawDataMatrix[:, 5])))
2473
2474 pngFile = os.path.join(qualPath, sequnitFileNamePrefix + ".cycle_nucl_composition.png")
2475 htmlFile = os.path.join(qualPath, sequnitFileNamePrefix + ".cycle_nucl_composition.html")
2476
2477 ## Save D3 interactive plot in html format
2478 mpld3.save_html(fig, htmlFile)
2479
2480 ## Save Matplotlib plot in png format
2481 plt.savefig(pngFile, dpi=fig.dpi)
2482
2483 return reformatBhistFile, pngFile, htmlFile, None, None
2484
2485
2486 def gen_cycle_n_base_percent_plot(fastq, readLength, isPairedEnd, log):
2487 READ_OUTPUT_PATH = RQCReadQcConfig.CFG["output_path"]
2488
2489 sequnitFileName, _ = safe_basename(fastq, log)
2490 sequnitFileNamePrefix = sequnitFileName.replace(".fastq", "").replace(".gz", "")
2491
2492 subsampleDir = "subsample"
2493 subsamplePath = os.path.join(READ_OUTPUT_PATH, subsampleDir)
2494
2495 qualDir = "qual"
2496 qualPath = os.path.join(READ_OUTPUT_PATH, qualDir)
2497 make_dir(qualPath)
2498 change_mod(qualPath, "0755")
2499
2500 reformatBhistFile = os.path.join(subsamplePath, sequnitFileNamePrefix + ".reformat.bhist.txt") ## base composition histogram
2501
2502 log.debug("gen_cycle_n_base_percent_plot(): bhist file = %s", reformatBhistFile)
2503
2504 ## Genbase composition histogram
2505 if not os.path.isfile(reformatBhistFile):
2506 log.error("Bhist file not found: %s", reformatBhistFile)
2507 return None, None, None, None, None
2508
2509 ## data
2510 # 0 1 2 3 4 5
2511 ##Pos A C G T N
2512 # 0 0.15111 0.26714 0.51707 0.06412 0.00056
2513 # 1 0.20822 0.20773 0.25543 0.32795 0.00068
2514
2515 rawDataMatrix = np.loadtxt(reformatBhistFile, delimiter='\t', comments='#')
2516 assert len(rawDataMatrix[1][:]) == 6
2517
2518 if isPairedEnd:
2519 rawDataR1 = rawDataMatrix[:readLength - 1][:]
2520 rawDataR2 = rawDataMatrix[readLength:][:]
2521
2522 ## r1 ------------------------------------------------------------------
2523 fig, ax = plt.subplots()
2524
2525 markerSize = 5.0
2526 lineWidth = 1.5
2527 p1 = ax.plot(rawDataR1[:, 0], rawDataR1[:, 5], 'r', marker='o', markersize=markerSize, linewidth=lineWidth, label='N', alpha=0.5)
2528
2529 ax.set_xlabel("Read Position", fontsize=12, alpha=0.5)
2530 ax.set_ylabel("Fraction", fontsize=12, alpha=0.5)
2531 ax.grid(color="gray", linestyle=':')
2532 ax.set_xlim([0, readLength])
2533
2534 ## Add tooltip
2535 labels = ["%.5f" % i for i in rawDataR1[:, 5]]
2536 mpld3.plugins.connect(fig, mpld3.plugins.PointLabelTooltip(p1[0], labels=labels))
2537
2538 pngFileR1 = os.path.join(qualPath, sequnitFileNamePrefix + ".cycle_n_base_percent_r1.png")
2539 htmlFileR1 = os.path.join(qualPath, sequnitFileNamePrefix + ".cycle_n_base_percent_r1.html")
2540
2541 ## Save D3 interactive plot in html format
2542 mpld3.save_html(fig, htmlFileR1)
2543
2544 ## Save Matplotlib plot in png format
2545 plt.savefig(pngFileR1, dpi=fig.dpi)
2546
2547 ## r2 ------------------------------------------------------------------
2548 fig, ax = plt.subplots()
2549
2550 markerSize = 5.0
2551 lineWidth = 1.5
2552 p1 = ax.plot([(x - readLength) for x in rawDataR2[:, 0]], rawDataR2[:, 5], 'r', marker='o', markersize=markerSize, linewidth=lineWidth, label='N', alpha=0.5)
2553
2554 ax.set_xlabel("Read Position", fontsize=12, alpha=0.5)
2555 ax.set_ylabel("Fraction", fontsize=12, alpha=0.5)
2556 ax.grid(color="gray", linestyle=':')
2557 ax.set_xlim([0, readLength])
2558
2559 ## Add tooltip
2560 labels = ["%.5f" % i for i in rawDataR2[:, 5]]
2561 mpld3.plugins.connect(fig, mpld3.plugins.PointLabelTooltip(p1[0], labels=labels))
2562
2563 plotPngPlotFileR2 = os.path.join(qualPath, sequnitFileNamePrefix + ".cycle_n_base_percent_r2.png")
2564 plotHtmlPlotFileR2 = os.path.join(qualPath, sequnitFileNamePrefix + ".cycle_n_base_percent_r2.html")
2565
2566 ## Save D3 interactive plot in html format
2567 mpld3.save_html(fig, plotHtmlPlotFileR2)
2568
2569 ## Save Matplotlib plot in png format
2570 plt.savefig(plotPngPlotFileR2, dpi=fig.dpi)
2571
2572 return reformatBhistFile, pngFileR1, htmlFileR1, plotPngPlotFileR2, plotHtmlPlotFileR2
2573
2574 else:
2575 fig, ax = plt.subplots()
2576
2577 markerSize = 5.0
2578 lineWidth = 1.5
2579 p1 = ax.plot(rawDataMatrix[:, 0], rawDataMatrix[:, 5], 'r', marker='o', markersize=markerSize, linewidth=lineWidth, label='N', alpha=0.5)
2580
2581 ax.set_xlabel("Read Position", fontsize=12, alpha=0.5)
2582 ax.set_ylabel("Fraction", fontsize=12, alpha=0.5)
2583 ax.grid(color="gray", linestyle=':')
2584
2585 ## Add tooltip
2586 labels = ["%.5f" % i for i in rawDataMatrix[:, 5]]
2587 mpld3.plugins.connect(fig, mpld3.plugins.PointLabelTooltip(p1[0], labels=labels))
2588
2589 pngFile = os.path.join(qualPath, sequnitFileNamePrefix + ".cycle_n_base_percent.png")
2590 htmlFile = os.path.join(qualPath, sequnitFileNamePrefix + ".cycle_n_base_percent.html")
2591
2592 ## Save D3 interactive plot in html format
2593 mpld3.save_html(fig, htmlFile)
2594
2595 ## Save Matplotlib plot in png format
2596 plt.savefig(pngFile, dpi=fig.dpi)
2597
2598 return reformatBhistFile, pngFile, htmlFile, None, None
2599
2600
2601 """ For STEP12
2602 sciclone_sam2summary
2603
2604 @param sam_file: input sam file
2605 @param count_file: stat file for writing
2606
2607 @return retCode: success or failure
2608 @return count_file: output count file
2609
2610 """
2611 ## Removed!
2612 ##def sciclone_sam2summary(sam_file, log):
2613
2614
2615
2616 """ For STEP12
2617 run_rna_strandedness
2618
2619 Title: run_rna_strandedness
2620 Function: Takes sam file generated from rna data set and determines
2621 mapping to sense and antisense strand
2622 Usage: run_rna_strandedness($sam_file, $log)
2623 Args: 1) sam file
2624 2) log file object
2625 Returns: JGI_SUCCESS
2626 JGI_FAILURE
2627 Comments: None.
2628
2629 @param sam_file
2630
2631 @return retCode
2632 @return outputLogFile: log file
2633 @return outResultDict: stat value dict (to be added to readqc_stats.txt)
2634
2635 """
2636 ## Removed!
2637
2638
2639
2640 """ For STEP12
2641 separate_paired_end_fq
2642
2643 Title : separate_paired_end_fq
2644 Function : Given a fastq file, this function splits the fastq into
2645 read1 and read2 fastq file.
2646 Usage : sequence_lengths( $fastq, $read1_fq, $read2_fq, $log )
2647 Args : 1) The name of a fastq sequence file.
2648 2) The name of the read1 fastq output file
2649 3) The name of the read2 fastq output file
2650 4) A JGI_Log object.
2651 Returns : JGI_SUCCESS: The fastq file was successfully separated.
2652 JGI_FAILURE: The fastq file could not be separated.
2653 Comments : For paired end fastq files only.
2654
2655
2656 sulsj
2657
2658 - Added gzip'd fastq support
2659 ## TODO: need to write a fastq IO class
2660
2661 @param fastq
2662 @param read1_outfile
2663 @param read2_outfile
2664 @param log
2665
2666 @return retCode
2667
2668 """
2669 ## Removed!
2670
2671
2672
2673 """ For STEP12
2674
2675 NOTE: Borrowed from alignment.py and updated to get lib name and isRna
2676
2677 get_lib_info
2678
2679 Look up the seqProjectId, bio_name from the library_info table
2680 - to look up the references
2681
2682 @param sequnitFileName: name of the seq unit in the seq_units.sequnitFileName field
2683
2684 @return seqProjectId
2685 @return ncbiOrganismName
2686 @return libraryName
2687 @return isRna
2688
2689 """
2690
2691 """ For STEP14 & STEP15
2692 run_blastplus_py
2693
2694 Call jgi-rqc-pipeline/tools/run_blastplus.py
2695
2696 """
2697 def run_blastplus_py(queryFastaFile, db, log):
2698 timeoutCmd = 'timeout' #RQCReadQcCommands.TIMEOUT_CMD
2699 blastOutFileNamePrefix = None
2700 # retCode = None
2701
2702 outDir, exitCode = safe_dirname(queryFastaFile, log)
2703 queryFastaFileBaseName, exitCode = safe_basename(queryFastaFile, log)
2704 dbFileBaseName, exitCode = safe_basename(db, log)
2705
2706 # runBlastnCmd = "/global/homes/s/sulsj/work/bitbucket-repo/jgi-rqc-pipeline/tools/run_blastplus.py" ## debug
2707 # runBlastnCmd = "/global/dna/projectdirs/PI/rqc/prod/jgi-rqc-pipeline/tools/run_blastplus.py"
2708 # runBlastnCmd = "/global/homes/s/sulsj/work/bitbucket-repo/jgi-rqc-pipeline/tools/run_blastplus_taxserver.py" ## debug
2709 runBlastnCmd = "/global/dna/projectdirs/PI/rqc/prod/jgi-rqc-pipeline/tools/run_blastplus_taxserver.py"
2710
2711 blastOutFileNamePrefix = outDir + "/megablast." + queryFastaFileBaseName + ".vs." + dbFileBaseName
2712
2713 ## Should use jigsaw/2.6.0 for not checking database reference fasta file
2714 ## 07212016 Added -s to add lineage to the subject field
2715 cmd = "%s 21600s %s -d %s -o %s -q %s -s > %s.log 2>&1 " % (timeoutCmd, runBlastnCmd, db, outDir, queryFastaFile, blastOutFileNamePrefix)
2716
2717 _, _, exitCode = run_sh_command(cmd, True, log, True)
2718
2719 ## Added timeout to terminate blast run manually after 6hrs
2720 ## If exitCode == 124 or exitCode = 143, this means the process exits with timeout.
2721 ## Timeout exits with 128 plus the signal number. 143 = 128 + 15 (SGITERM)
2722 ## Ref) http://stackoverflow.com/questions/4189136/waiting-for-a-command-to-return-in-a-bash-script
2723 ## timeout man page ==> If the command times out, and --preserve-status is not set, then exit with status 124.
2724 ##
2725 if exitCode in (124, 143):
2726 ## BLAST timeout
2727 ## Exit with success so that the blast step can be skipped.
2728 log.warning("##################################")
2729 log.warning("BLAST TIMEOUT. JUST SKIP THE STEP.")
2730 log.warning("##################################")
2731 return RQCExitCodes.JGI_FAILURE, -143
2732
2733 elif exitCode != 0:
2734 log.error("Failed to run_blastplus_py. Exit code != 0")
2735 return RQCExitCodes.JGI_FAILURE, None
2736
2737 else:
2738 log.info("run_blastplus_py complete.")
2739
2740 return RQCExitCodes.JGI_SUCCESS, blastOutFileNamePrefix
2741
2742
2743 """===========================================================================
2744 checkpoint_step_wrapper
2745
2746 """
2747 def checkpoint_step_wrapper(status):
2748 assert RQCReadQcConfig.CFG["status_file"]
2749 checkpoint_step(RQCReadQcConfig.CFG["status_file"], status)
2750
2751
2752 """===========================================================================
2753 get the file content
2754 """
2755 def get_analysis_file_contents(fullPath):
2756 retCode = ""
2757
2758 if os.path.isfile(fullPath):
2759 with open(fullPath, "r") as FH:
2760 retCode = FH.readlines()
2761 return retCode
2762 else:
2763 return "file not found"
2764
2765
2766 '''===========================================================================
2767 file_name_trim
2768
2769 '''
2770 def file_name_trim(fname):
2771 return fname.replace(".gz", "").replace(".fastq", "").replace(".fasta", "")
2772
2773
2774 ## EOF