-
Notifications
You must be signed in to change notification settings - Fork 0
/
trimmomatic.py
383 lines (295 loc) · 11.1 KB
/
trimmomatic.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
#!/usr/bin/env python3
"""
Purpose
-------
This module is intended execute trimmomatic on paired-end FastQ files.
Expected input
--------------
The following variables are expected whether using NextFlow or the
:py:func:`main` executor.
- ``sample_id`` : Pair of FastQ file paths.
- e.g.: ``'SampleA'``
- ``fastq_pair`` : Pair of FastQ file paths.
- e.g.: ``'SampleA_1.fastq.gz SampleA_2.fastq.gz'``
- ``trim_range`` : Crop range detected using FastQC.
- e.g.: ``'15 151'``
- ``opts`` : List of options for trimmomatic
- e.g.: ``'["5:20", "3", "3", "55"]'``
- e.g.: ``'[trim_sliding_window, trim_leading, trim_trailing, trim_min_length]'``
- ``phred`` : List of guessed phred values for each sample
- e.g.: ``'[SampleA: 33, SampleB: 33]'``
Generated output
----------------
The generated output are output files that contain an object, usually a string.
(Values within ``${}`` are substituted by the corresponding variable.)
- ``${sample_id}_*P*``: Pair of paired FastQ files generated by Trimmomatic
- e.g.: ``'SampleA_1_P.fastq.gz SampleA_2_P.fastq.gz'``
- ``trimmomatic_status``: Stores the status of the trimmomatic run. If it was\
successfully executed, it stores 'pass'. Otherwise, it stores the \
``STDERR`` message.
- e.g.: ``'pass'``
Code documentation
------------------
"""
# TODO: More control over read trimming
# TODO: Add option to remove adapters
# TODO: What to do when there is encoding failure
__version__ = "1.0.2"
__build__ = "28032018"
__template__ = "trimmomatic-nf"
import os
import json
import fileinput
import subprocess
from subprocess import PIPE
from collections import OrderedDict
from assemblerflow_utils.assemblerflow_base import get_logger, MainWrapper
logger = get_logger(__file__)
def __get_version_trimmomatic():
try:
cli = ["java", "-jar", TRIM_PATH, "-version"]
p = subprocess.Popen(cli, stdout=PIPE, stderr=PIPE)
stdout, _ = p.communicate()
version = stdout.strip().decode("utf8")
except Exception as e:
logger.debug(e)
version = "undefined"
return {
"program": "Trimmomatic",
"version": version,
}
if __file__.endswith(".command.sh"):
SAMPLE_ID = '$sample_id'
FASTQ_PAIR = '$fastq_pair'.split()
TRIM_RANGE = '$trim_range'.split()
TRIM_OPTS = [x.strip() for x in '$opts'.strip("[]").split(",")]
PHRED = '$phred'
ADAPTERS_FILE = '$ad'
logger.debug("Running {} with parameters:".format(
os.path.basename(__file__)))
logger.debug("SAMPLE_ID: {}".format(SAMPLE_ID))
logger.debug("FASTQ_PAIR: {}".format(FASTQ_PAIR))
logger.debug("TRIM_RANGE: {}".format(TRIM_RANGE))
logger.debug("TRIM_OPTS: {}".format(TRIM_OPTS))
logger.debug("PHRED: {}".format(PHRED))
logger.debug("ADAPTERS_FILE: {}".format(ADAPTERS_FILE))
TRIM_PATH = "/NGStools/Trimmomatic-0.36/trimmomatic.jar"
ADAPTERS_PATH = "/NGStools/Trimmomatic-0.36/adapters"
def parse_log(log_file):
"""Retrieves some statistics from a single Trimmomatic log file.
This function parses Trimmomatic's log file and stores some trimming
statistics in an :py:class:`OrderedDict` object. This object contains
the following keys:
- ``clean_len``: Total length after trimming.
- ``total_trim``: Total trimmed base pairs.
- ``total_trim_perc``: Total trimmed base pairs in percentage.
- ``5trim``: Total base pairs trimmed at 5' end.
- ``3trim``: Total base pairs trimmed at 3' end.
Parameters
----------
log_file : str
Path to trimmomatic log file.
Returns
-------
x : :py:class:`OrderedDict`
Object storing the trimming statistics.
"""
template = OrderedDict([
# Total length after trimming
("clean_len", 0),
# Total trimmed base pairs
("total_trim", 0),
# Total trimmed base pairs in percentage
("total_trim_perc", 0),
# Total trimmed at 5' end
("5trim", 0),
# Total trimmed at 3' end
("3trim", 0),
# Bad reads (completely trimmed)
("bad_reads", 0)
])
with open(log_file) as fh:
for line in fh:
# This will split the log fields into:
# 0. read length after trimming
# 1. amount trimmed from the start
# 2. last surviving base
# 3. amount trimmed from the end
fields = [int(x) for x in line.strip().split()[-4:]]
if not fields[0]:
template["bad_reads"] += 1
template["5trim"] += fields[1]
template["3trim"] += fields[3]
template["total_trim"] += fields[1] + fields[3]
template["clean_len"] += fields[0]
total_len = template["clean_len"] + template["total_trim"]
if total_len:
template["total_trim_perc"] = round(
(template["total_trim"] / total_len) * 100, 2)
else:
template["total_trim_perc"] = 0
return template
def write_report(storage_dic, output_file):
""" Writes a report from multiple samples.
Parameters
----------
storage_dic : dict or :py:class:`OrderedDict`
Storage containing the trimming statistics. See :py:func:`parse_log`
for its generation.
output_file : str
Path where the output file will be generated.
"""
with open(output_file, "w") as fh, open(".report.json", "w") as json_rep:
# Write header
fh.write("Sample,Total length,Total trimmed,%,5end Trim,3end Trim,"
"bad_reads\\n")
# Write contents
for sample, vals in storage_dic.items():
fh.write("{},{}\\n".format(
sample, ",".join([str(x) for x in vals.values()])))
json_dic = {
"tableRow": [
{"header": "Trimmed (%)",
"value": vals["total_trim_perc"],
"table": "assembly",
"columnBar": True},
],
"plotData": {
"sparkline": vals["clean_len"]
},
"badReads": vals["bad_reads"]
}
json_rep.write(json.dumps(json_dic, separators=(",", ":")))
def trimmomatic_log(log_file):
log_storage = OrderedDict()
log_id = log_file.rstrip("_trimlog.txt")
log_storage[log_id] = parse_log(log_file)
os.remove(log_file)
write_report(log_storage, "trimmomatic_report.csv")
def clean_up():
"""Cleans the working directory of unwanted temporary files"""
# Find unpaired fastq files
unpaired_fastq = [f for f in os.listdir(".")
if f.endswith("_U.fastq.gz")]
# Remove unpaired fastq files, if any
for fpath in unpaired_fastq:
os.remove(fpath)
def merge_default_adapters():
"""Merges the default adapters file in the trimmomatic adapters directory
Returns
-------
str
Path with the merged adapters file.
"""
default_adapters = [os.path.join(ADAPTERS_PATH, x) for x in
os.listdir(ADAPTERS_PATH)]
filepath = os.path.join(os.getcwd(), "default_adapters.fasta")
with open(filepath, "w") as fh, \
fileinput.input(default_adapters) as in_fh:
for line in in_fh:
fh.write(line)
return filepath
@MainWrapper
def main(sample_id, fastq_pair, trim_range, trim_opts, phred, adapters_file):
""" Main executor of the trimmomatic template.
Parameters
----------
sample_id : str
Sample Identification string.
fastq_pair : list
Two element list containing the paired FastQ files.
trim_range : list
Two element list containing the trimming range.
trim_opts : list
Four element list containing several trimmomatic options:
[*SLIDINGWINDOW*; *LEADING*; *TRAILING*; *MINLEN*]
phred : int
Guessed phred score for the sample. The phred score is a generated
output from :py:class:`templates.integrity_coverage`.
adapters_file : str
Path to adapters file. If not provided, or the path is not available,
it will use the default adapters from Trimmomatic will be used
"""
logger.info("Starting trimmomatic")
# Create base CLI
cli = [
"java",
"-Xmx{}".format("$task.memory"[:-1].lower().replace(" ", "")),
"-jar",
TRIM_PATH.strip(),
"PE",
"-threads",
"$task.cpus"
]
# If the phred encoding was detected, provide it
try:
# Check if the provided PHRED can be converted to int
phred = int(phred)
phred_flag = "-phred{}".format(str(phred))
cli += [phred_flag]
# Could not detect phred encoding. Do not add explicit encoding to
# trimmomatic and let it guess
except ValueError:
pass
# Add input samples to CLI
cli += fastq_pair
# Add output file names
output_names = []
for i in range(len(fastq_pair)):
output_names.append("{}_{}_trim.fastq.gz".format(
SAMPLE_ID, str(i + 1)))
output_names.append("{}_{}_U.fastq.gz".format(
SAMPLE_ID, str(i + 1)))
cli += output_names
if trim_range != ["None"]:
cli += [
"CROP:{}".format(trim_range[1]),
"HEADCROP:{}".format(trim_range[0]),
]
if os.path.exists(adapters_file):
logger.debug("Using the provided adapters file '{}'".format(
adapters_file))
else:
logger.debug("Adapters file '{}' not provided or does not exist. Using"
" default adapters".format(adapters_file))
adapters_file = merge_default_adapters()
cli += [
"ILLUMINACLIP:{}:3:30:10:6:true".format(adapters_file)
]
# Add trimmomatic options
cli += [
"SLIDINGWINDOW:{}".format(trim_opts[0]),
"LEADING:{}".format(trim_opts[1]),
"TRAILING:{}".format(trim_opts[2]),
"MINLEN:{}".format(trim_opts[3]),
"TOPHRED33",
"-trimlog",
"{}_trimlog.txt".format(sample_id)
]
logger.debug("Running trimmomatic subprocess with command: {}".format(cli))
p = subprocess.Popen(cli, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
# Attempt to decode STDERR output from bytes. If unsuccessful, coerce to
# string
try:
stderr = stderr.decode("utf8")
except (UnicodeDecodeError, AttributeError):
stderr = str(stderr)
logger.info("Finished trimmomatic subprocess with STDOUT:\\n"
"======================================\\n{}".format(stdout))
logger.info("Fished trimmomatic subprocesswith STDERR:\\n"
"======================================\\n{}".format(stderr))
logger.info("Finished trimmomatic with return code: {}".format(
p.returncode))
trimmomatic_log("{}_trimlog.txt".format(sample_id))
clean_up()
# Check if trimmomatic ran successfully. If not, write the error message
# to the status channel and exit.
with open(".status", "w") as status_fh:
if p.returncode != 0:
status_fh.write("fail")
return
else:
status_fh.write("pass")
if __name__ == '__main__':
main(SAMPLE_ID, FASTQ_PAIR, TRIM_RANGE, TRIM_OPTS, PHRED, ADAPTERS_FILE)