| 1 |
""" |
| 2 |
This module is from Porechop by Ryan Wick. The original licensing information is as follows: |
| 3 |
|
| 4 |
Copyright 2017 Ryan Wick ([email protected]) |
| 5 |
https://github.com/rrwick/Porechop |
| 6 |
|
| 7 |
This module contains miscellaneous functions used by Porechop. |
| 8 |
|
| 9 |
This file is part of Porechop. Porechop is free software: you can redistribute it and/or modify |
| 10 |
it under the terms of the GNU General Public License as published by the Free Software Foundation, |
| 11 |
either version 3 of the License, or (at your option) any later version. Porechop is distributed in |
| 12 |
the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 13 |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more |
| 14 |
details. You should have received a copy of the GNU General Public License along with Porechop. If |
| 15 |
not, see <http://www.gnu.org/licenses/>. |
| 16 |
""" |
| 17 |
|
| 18 |
import sys |
| 19 |
import os |
| 20 |
import gzip |
| 21 |
import re |
| 22 |
import textwrap |
| 23 |
import shutil |
| 24 |
import argparse |
| 25 |
|
| 26 |
def get_compression_type(filename): |
| 27 |
""" |
| 28 |
Attempts to guess the compression (if any) on a file using the first few bytes. |
| 29 |
http://stackoverflow.com/questions/13044562 |
| 30 |
""" |
| 31 |
magic_dict = {'gz': (b'\x1f', b'\x8b', b'\x08'), |
| 32 |
'bz2': (b'\x42', b'\x5a', b'\x68'), |
| 33 |
'zip': (b'\x50', b'\x4b', b'\x03', b'\x04')} |
| 34 |
max_len = max(len(x) for x in magic_dict) |
| 35 |
|
| 36 |
unknown_file = open(filename, 'rb') |
| 37 |
file_start = unknown_file.read(max_len) |
| 38 |
unknown_file.close() |
| 39 |
compression_type = 'plain' |
| 40 |
for filetype, magic_bytes in magic_dict.items(): |
| 41 |
if file_start.startswith(magic_bytes): |
| 42 |
compression_type = filetype |
| 43 |
if compression_type == 'bz2': |
| 44 |
sys.exit('Error: cannot use bzip2 format - use gzip instead') |
| 45 |
if compression_type == 'zip': |
| 46 |
sys.exit('Error: cannot use zip format - use gzip instead') |
| 47 |
return compression_type |
| 48 |
|
| 49 |
|
| 50 |
def get_sequence_file_type(filename): |
| 51 |
""" |
| 52 |
Determines whether a file is FASTA or FASTQ. |
| 53 |
""" |
| 54 |
if not os.path.isfile(filename): |
| 55 |
sys.exit('Error: could not find ' + filename) |
| 56 |
if get_compression_type(filename) == 'gz': |
| 57 |
open_func = gzip.open |
| 58 |
else: |
| 59 |
open_func = open |
| 60 |
|
| 61 |
with open_func(filename, 'rt') as seq_file: |
| 62 |
try: |
| 63 |
first_char = seq_file.read(1) |
| 64 |
except UnicodeDecodeError: |
| 65 |
first_char = '' |
| 66 |
|
| 67 |
if first_char == '>': |
| 68 |
return 'FASTA' |
| 69 |
elif first_char == '@': |
| 70 |
return 'FASTQ' |
| 71 |
else: |
| 72 |
raise ValueError('File is neither FASTA or FASTQ') |
| 73 |
|
| 74 |
|
| 75 |
def load_fasta_or_fastq(filename): |
| 76 |
""" |
| 77 |
Returns a list of tuples (header, seq) for each record in the fasta/fastq file. |
| 78 |
""" |
| 79 |
try: |
| 80 |
file_type = get_sequence_file_type(filename) |
| 81 |
if file_type == 'FASTA': |
| 82 |
return load_fasta(filename), 'FASTA' |
| 83 |
else: |
| 84 |
return load_fastq(filename), 'FASTQ' |
| 85 |
except IndexError: |
| 86 |
sys.exit('\nError: ' + filename + ' could not be parsed - is it formatted correctly?') |
| 87 |
|
| 88 |
|
| 89 |
def load_fasta(fasta_filename): |
| 90 |
""" |
| 91 |
Returns a list of tuples (header, seq) for each record in the fasta file. |
| 92 |
""" |
| 93 |
if get_compression_type(fasta_filename) == 'gz': |
| 94 |
open_func = gzip.open |
| 95 |
else: |
| 96 |
open_func = open |
| 97 |
fasta_seqs = [] |
| 98 |
with open_func(fasta_filename, 'rt') as fasta_file: |
| 99 |
name = '' |
| 100 |
sequence = '' |
| 101 |
for line in fasta_file: |
| 102 |
line = line.strip() |
| 103 |
if not line: |
| 104 |
continue |
| 105 |
if line[0] == '>': |
| 106 |
if name: |
| 107 |
fasta_seqs.append((name.split()[0], sequence, name)) |
| 108 |
sequence = '' |
| 109 |
name = line[1:] |
| 110 |
else: |
| 111 |
sequence += line |
| 112 |
if name: |
| 113 |
fasta_seqs.append((name.split()[0], sequence, name)) |
| 114 |
return fasta_seqs |
| 115 |
|
| 116 |
|
| 117 |
def load_fastq(fastq_filename): |
| 118 |
""" |
| 119 |
Returns a list of tuples (header, seq) for each record in the fastq file. |
| 120 |
""" |
| 121 |
if get_compression_type(fastq_filename) == 'gz': |
| 122 |
open_func = gzip.open |
| 123 |
else: |
| 124 |
open_func = open |
| 125 |
reads = [] |
| 126 |
with open_func(fastq_filename, 'rt') as fastq: |
| 127 |
for line in fastq: |
| 128 |
full_name = line.strip()[1:] |
| 129 |
short_name = full_name.split()[0] |
| 130 |
sequence = next(fastq).strip() |
| 131 |
spacer = next(fastq).strip() |
| 132 |
qualities = next(fastq).strip() |
| 133 |
reads.append((short_name, sequence, spacer, qualities, full_name)) |
| 134 |
return reads |
| 135 |
|
| 136 |
|
| 137 |
def print_table(table, print_dest, alignments='', max_col_width=30, col_separation=3, indent=2, |
| 138 |
row_colour=None, sub_colour=None, row_extra_text=None, leading_newline=False, |
| 139 |
subsequent_indent='', return_str=False, header_format='underline', |
| 140 |
hide_header=False, fixed_col_widths=None, left_align_header=True, |
| 141 |
bottom_align_header=True): |
| 142 |
""" |
| 143 |
Args: |
| 144 |
table: a list of lists of strings (one row is one list, all rows should be the same length) |
| 145 |
print_dest: either sys.stdout or sys.stderr - where the table will be printed |
| 146 |
alignments: a string of L and R, indicating the alignment for each row |
| 147 |
max_col_width: values longer than this will be wrapped |
| 148 |
col_separation: the number of spaces between columns |
| 149 |
indent: the number of spaces between the table and the left side of the terminal |
| 150 |
row_colour: a dictionary of row indices and their colour names |
| 151 |
sub_colour: a dictionary of values to colour names for which the text colour will be set |
| 152 |
row_extra_text: a dictionary of row indices and extra text to display after the row |
| 153 |
leading_newline: if True, the function will print a blank line above the table |
| 154 |
subsequent_indent: this string will be added to the start of wrapped text lines |
| 155 |
return_str: if True, this function will return a string of the table instead of printing it |
| 156 |
header_format: the formatting (colour, underline, etc) of the header line |
| 157 |
hide_header: if True, the header is not printed |
| 158 |
fixed_col_widths: a list to specify exact column widths (automatic if not used) |
| 159 |
left_align_header: if False, the header will follow the column alignments |
| 160 |
bottom_align_header: if False, the header will align to the top, like other rows |
| 161 |
""" |
| 162 |
column_count = len(table[0]) |
| 163 |
table = [x[:column_count] for x in table] |
| 164 |
table = [x + [''] * (column_count - len(x)) for x in table] |
| 165 |
if row_colour is None: |
| 166 |
row_colour = {} |
| 167 |
if sub_colour is None: |
| 168 |
sub_colour = {} |
| 169 |
if row_extra_text is None: |
| 170 |
row_extra_text = {} |
| 171 |
if leading_newline: |
| 172 |
print('', file=print_dest) |
| 173 |
|
| 174 |
|
| 175 |
alignments += 'L' * (column_count - len(alignments)) |
| 176 |
alignments = alignments[:column_count] |
| 177 |
|
| 178 |
if fixed_col_widths is not None: |
| 179 |
col_widths = fixed_col_widths |
| 180 |
else: |
| 181 |
col_widths = [0] * column_count |
| 182 |
for row in table: |
| 183 |
col_widths = [min(max(col_widths[i], len_without_format(x)), max_col_width) |
| 184 |
for i, x in enumerate(row)] |
| 185 |
separator = ' ' * col_separation |
| 186 |
indenter = ' ' * indent |
| 187 |
full_table_str = '' |
| 188 |
for i, row in enumerate(table): |
| 189 |
row = [str(x) for x in row] |
| 190 |
if hide_header and i == 0: |
| 191 |
continue |
| 192 |
|
| 193 |
if fixed_col_widths is not None: |
| 194 |
wrapped_row = [] |
| 195 |
for col, fixed_width in zip(row, fixed_col_widths): |
| 196 |
wrapper = textwrap.TextWrapper(subsequent_indent=subsequent_indent, |
| 197 |
width=fixed_width) |
| 198 |
wrapped_row.append(wrapper.wrap(col)) |
| 199 |
else: |
| 200 |
wrapper = textwrap.TextWrapper(subsequent_indent=subsequent_indent, width=max_col_width) |
| 201 |
wrapped_row = [wrapper.wrap(x) for x in row] |
| 202 |
|
| 203 |
row_rows = max(len(x) for x in wrapped_row) |
| 204 |
if i == 0 and bottom_align_header: |
| 205 |
wrapped_row = [[''] * (row_rows - len(x)) + x for x in wrapped_row] |
| 206 |
|
| 207 |
for j in range(row_rows): |
| 208 |
row_line = [x[j] if j < len(x) else '' for x in wrapped_row] |
| 209 |
aligned_row = [] |
| 210 |
for value, col_width, alignment in zip(row_line, col_widths, alignments): |
| 211 |
if alignment == 'L' or (i == 0 and left_align_header): |
| 212 |
aligned_row.append(value.ljust(col_width)) |
| 213 |
elif alignment == 'C': |
| 214 |
aligned_row.append(value.center(col_width)) |
| 215 |
else: |
| 216 |
aligned_row.append(value.rjust(col_width)) |
| 217 |
row_str = separator.join(aligned_row) |
| 218 |
if i in row_extra_text: |
| 219 |
row_str += row_extra_text[i] |
| 220 |
if i == 0 and header_format: |
| 221 |
row_str = colour(row_str, header_format) |
| 222 |
if i in row_colour: |
| 223 |
row_str = colour(row_str, row_colour[i]) |
| 224 |
for text, colour_name in sub_colour.items(): |
| 225 |
row_str = row_str.replace(text, colour(text, colour_name)) |
| 226 |
if j < row_rows - 1 and UNDERLINE in row_str: |
| •227 |
row_str = re.sub(r'\033\[4m', '', row_str) |
| 228 |
if return_str: |
| 229 |
full_table_str += indenter + row_str + '\n' |
| 230 |
else: |
| 231 |
print(indenter + row_str, flush=True, file=print_dest) |
| 232 |
if return_str: |
| 233 |
return full_table_str |
| 234 |
|
| 235 |
|
| 236 |
END_FORMATTING = '\033[0m' |
| 237 |
BOLD = '\033[1m' |
| 238 |
UNDERLINE = '\033[4m' |
| 239 |
RED = '\033[31m' |
| 240 |
GREEN = '\033[32m' |
| 241 |
YELLOW = '\033[93m' |
| 242 |
DIM = '\033[2m' |
| 243 |
|
| 244 |
|
| 245 |
def colour(text, text_colour): |
| 246 |
bold_text = 'bold' in text_colour |
| 247 |
text_colour = text_colour.replace('bold', '') |
| 248 |
underline_text = 'underline' in text_colour |
| 249 |
text_colour = text_colour.replace('underline', '') |
| 250 |
text_colour = text_colour.replace('_', '') |
| 251 |
text_colour = text_colour.replace(' ', '') |
| 252 |
text_colour = text_colour.lower() |
| 253 |
if 'red' in text_colour: |
| 254 |
coloured_text = RED |
| 255 |
elif 'green' in text_colour: |
| 256 |
coloured_text = GREEN |
| 257 |
elif 'yellow' in text_colour: |
| 258 |
coloured_text = YELLOW |
| 259 |
elif 'dim' in text_colour: |
| 260 |
coloured_text = DIM |
| 261 |
else: |
| 262 |
coloured_text = '' |
| 263 |
if bold_text: |
| 264 |
coloured_text += BOLD |
| 265 |
if underline_text: |
| 266 |
coloured_text += UNDERLINE |
| 267 |
if not coloured_text: |
| 268 |
return text |
| 269 |
coloured_text += text + END_FORMATTING |
| 270 |
return coloured_text |
| 271 |
|
| 272 |
|
| 273 |
def red(text): |
| 274 |
return RED + text + END_FORMATTING |
| 275 |
|
| 276 |
|
| 277 |
def yellow(text): |
| 278 |
return YELLOW + text + END_FORMATTING |
| 279 |
|
| 280 |
|
| 281 |
def bold_underline(text): |
| 282 |
return BOLD + UNDERLINE + text + END_FORMATTING |
| 283 |
|
| 284 |
|
| 285 |
def len_without_format(text): |
| 286 |
return len(remove_formatting(text)) |
| 287 |
|
| 288 |
|
| 289 |
def remove_formatting(text): |
| 290 |
return re.sub('\033.*?m', '', text) |
| 291 |
|
| 292 |
|
| 293 |
def add_line_breaks_to_sequence(sequence, line_length): |
| 294 |
""" |
| 295 |
Wraps sequences to the defined length. All resulting sequences end in a line break. |
| 296 |
""" |
| 297 |
if not sequence: |
| 298 |
return '\n' |
| 299 |
seq_with_breaks = '' |
| 300 |
pos = 0 |
| 301 |
while pos < len(sequence): |
| 302 |
seq_with_breaks += sequence[pos:pos+line_length] + '\n' |
| 303 |
pos += line_length |
| 304 |
return seq_with_breaks |
| 305 |
|
| 306 |
|
| 307 |
class MyHelpFormatter(argparse.HelpFormatter): |
| 308 |
""" |
| 309 |
This is a custom formatter class for argparse. It allows for some custom formatting, |
| 310 |
in particular for the help texts with multiple options (like bridging mode and verbosity level). |
| 311 |
http://stackoverflow.com/questions/3853722 |
| 312 |
""" |
| 313 |
def __init__(self, prog): |
| 314 |
terminal_width = shutil.get_terminal_size().columns |
| 315 |
os.environ['COLUMNS'] = str(terminal_width) |
| 316 |
max_help_position = min(max(24, terminal_width // 3), 40) |
| 317 |
super().__init__(prog, max_help_position=max_help_position) |
| 318 |
|
| 319 |
def _get_help_string(self, action): |
| 320 |
help_text = action.help |
| 321 |
if action.default != argparse.SUPPRESS and 'default' not in help_text.lower() and \ |
| 322 |
action.default is not None: |
| 323 |
help_text += ' (default: ' + str(action.default) + ')' |
| 324 |
return help_text |
| 325 |
|
| 326 |
def int_to_str(num, max_num=0): |
| 327 |
""" |
| 328 |
Converts a number to a string. Will add left padding based on the max value to ensure numbers |
| 329 |
align well. |
| 330 |
""" |
| 331 |
if num is None: |
| 332 |
num_str = 'n/a' |
| 333 |
else: |
| 334 |
num_str = '{:,}'.format(num) |
| 335 |
max_str = '{:,}'.format(int(max_num)) |
| 336 |
return num_str.rjust(len(max_str)) |
| 337 |
|
| 338 |
def output_progress_line(completed, total, end_newline=False, step=10): |
| 339 |
if step > 1 and completed % step != 0 and completed != total: |
| 340 |
return |
| 341 |
progress_str = int_to_str(completed) + ' / ' + int_to_str(total) |
| 342 |
if total > 0: |
| 343 |
percent = 100.0 * completed / total |
| 344 |
else: |
| 345 |
percent = 0.0 |
| 346 |
progress_str += ' (' + '%.1f' % percent + '%)' |
| 347 |
|
| 348 |
end_char = '\n' if end_newline else '' |
| 349 |
print('\r' + progress_str, end=end_char, flush=True) |