| 1 |
import re |
| 2 |
import sys |
| 3 |
import copy |
| 4 |
import random |
| 5 |
from pyfastaq import sequences, utils, caf |
| 6 |
|
| 7 |
class Error (Exception): pass |
| 8 |
|
| 9 |
def acgtn_only(infile, outfile): |
| 10 |
'''Replace every non-acgtn (case insensitve) character with an N''' |
| 11 |
f = utils.open_file_write(outfile) |
| 12 |
for seq in sequences.file_reader(infile): |
| 13 |
seq.replace_non_acgt() |
| 14 |
print(seq, file=f) |
| 15 |
utils.close(f) |
| 16 |
|
| 17 |
|
| 18 |
def caf_to_fastq(infile, outfile, min_length=0, trim=False): |
| 19 |
'''Convert a CAF file to fastq. Reads shorter than min_length are not output. If clipping information is in the CAF file (with a line Clipping QUAL ...) and trim=True, then trim the reads''' |
| 20 |
caf_reader = caf.file_reader(infile) |
| 21 |
fout = utils.open_file_write(outfile) |
| 22 |
|
| 23 |
for c in caf_reader: |
| 24 |
if trim: |
| 25 |
if c.clip_start is not None and c.clip_end is not None: |
| 26 |
c.seq.seq = c.seq.seq[c.clip_start:c.clip_end + 1] |
| 27 |
c.seq.qual = c.seq.qual[c.clip_start:c.clip_end + 1] |
| 28 |
else: |
| 29 |
print('Warning: no clipping info for sequence', c.id, file=sys.stderr) |
| 30 |
|
| 31 |
|
| 32 |
if len(c.seq) >= min_length: |
| 33 |
print(c.seq, file=fout) |
| 34 |
|
| 35 |
utils.close(fout) |
| 36 |
|
| 37 |
|
| 38 |
def capillary_to_pairs(infile, outprefix): |
| 39 |
# hash the sequences, only taking longest where an end has been sequenced more than once |
| 40 |
seq_reader = sequences.file_reader(infile) |
| 41 |
fwd_seqs = {} |
| 42 |
rev_seqs = {} |
| 43 |
unpaired_seqs = {} |
| 44 |
|
| 45 |
for seq in seq_reader: |
| 46 |
id_info = seq.split_capillary_id() |
| 47 |
if id_info['dir'] == 'fwd': |
| 48 |
seq.id = id_info['prefix'] + '/1' |
| 49 |
h = fwd_seqs |
| 50 |
elif id_info['dir'] == 'rev': |
| 51 |
seq.id = id_info['prefix'] + '/2' |
| 52 |
h = rev_seqs |
| 53 |
else: |
| 54 |
seq.id = id_info['prefix'] |
| 55 |
h = unpaired_seqs |
| 56 |
|
| 57 |
key = id_info['prefix'] |
| 58 |
|
| 59 |
if key not in h or len(h[key]) < len(seq): |
| 60 |
h[key] = copy.copy(seq) |
| 61 |
|
| 62 |
# write the output files |
| 63 |
f_pe = utils.open_file_write(outprefix + '.paired.gz') |
| 64 |
f_up = utils.open_file_write(outprefix + '.unpaired.gz') |
| 65 |
|
| 66 |
for id in fwd_seqs: |
| 67 |
if id in rev_seqs: |
| 68 |
print(fwd_seqs[id], file=f_pe) |
| 69 |
print(rev_seqs[id], file=f_pe) |
| 70 |
del rev_seqs[id] |
| 71 |
else: |
| 72 |
print(fwd_seqs[id], file=f_up) |
| 73 |
|
| 74 |
for seq in rev_seqs.values(): |
| 75 |
print(seq, file=f_up) |
| 76 |
|
| 77 |
for seq in unpaired_seqs.values(): |
| 78 |
print(seq, file=f_up) |
| 79 |
|
| 80 |
utils.close(f_pe) |
| 81 |
utils.close(f_up) |
| 82 |
|
| 83 |
|
| 84 |
def count_sequences(infile): |
| 85 |
'''Returns the number of sequences in a file''' |
| 86 |
seq_reader = sequences.file_reader(infile) |
| 87 |
n = 0 |
| 88 |
for seq in seq_reader: |
| 89 |
n += 1 |
| 90 |
return n |
| 91 |
|
| 92 |
|
| 93 |
def deinterleave(infile, outfile_1, outfile_2, fasta_out=False): |
| 94 |
seq_reader = sequences.file_reader(infile) |
| 95 |
f_1 = utils.open_file_write(outfile_1) |
| 96 |
f_2 = utils.open_file_write(outfile_2) |
| 97 |
for seq in seq_reader: |
| 98 |
if fasta_out: |
| 99 |
print(sequences.Fasta(seq.id, seq.seq), file=f_1) |
| 100 |
else: |
| 101 |
print(seq, file=f_1) |
| 102 |
try: |
| 103 |
next(seq_reader) |
| 104 |
except StopIteration: |
| 105 |
utils.close(f_1) |
| 106 |
utils.close(f_2) |
| 107 |
raise Error('Error getting mate for sequence. Cannot continue') |
| 108 |
if fasta_out: |
| 109 |
print(sequences.Fasta(seq.id, seq.seq), file=f_2) |
| 110 |
else: |
| 111 |
print(seq, file=f_2) |
| 112 |
|
| 113 |
utils.close(f_1) |
| 114 |
utils.close(f_2) |
| 115 |
|
| 116 |
|
| 117 |
def enumerate_names(infile, outfile, start_index=1, keep_illumina_suffix=False, rename_file=None, suffix=None): |
| 118 |
seq_reader = sequences.file_reader(infile) |
| 119 |
fout_seqs = utils.open_file_write(outfile) |
| 120 |
counter = start_index |
| 121 |
|
| 122 |
if keep_illumina_suffix: |
| 123 |
sequence_suffixes = ['/1', '/2'] |
| 124 |
else: |
| 125 |
sequence_suffixes = [] |
| 126 |
|
| 127 |
|
| 128 |
if rename_file is not None: |
| 129 |
fout_rename = utils.open_file_write(rename_file) |
| 130 |
print('#old\tnew', file=fout_rename) |
| 131 |
|
| 132 |
for seq in seq_reader: |
| 133 |
old_id = seq.id |
| 134 |
seq.id = str(counter) |
| 135 |
|
| 136 |
for suff in sequence_suffixes: |
| 137 |
if old_id.endswith(suff): |
| 138 |
seq.id += suff |
| 139 |
break |
| 140 |
|
| 141 |
if rename_file is not None: |
| 142 |
print(old_id, seq.id, sep='\t', file=fout_rename) |
| 143 |
|
| 144 |
if suffix is not None: |
| 145 |
seq.id += suffix |
| 146 |
|
| 147 |
print(seq, file=fout_seqs) |
| 148 |
counter += 1 |
| 149 |
|
| 150 |
utils.close(fout_seqs) |
| 151 |
|
| 152 |
if rename_file is not None: |
| 153 |
utils.close(fout_rename) |
| 154 |
|
| 155 |
|
| 156 |
def expand_nucleotides(infile, outfile): |
| 157 |
seq_reader = sequences.file_reader(infile) |
| 158 |
fout = utils.open_file_write(outfile) |
| 159 |
|
| 160 |
for seq in seq_reader: |
| 161 |
seqs = seq.expand_nucleotides() |
| 162 |
if len(seqs) > 1: |
| 163 |
for s in seqs: |
| 164 |
print(s, file=fout) |
| 165 |
else: |
| 166 |
print(seq, file=fout) |
| 167 |
|
| 168 |
|
| 169 |
def trim_contigs(infile, outfile, trim): |
| 170 |
seq_reader = sequences.file_reader(infile) |
| 171 |
fout = utils.open_file_write(outfile) |
| 172 |
|
| 173 |
for seq in seq_reader: |
| 174 |
if len(seq) < 2 * trim: |
| 175 |
continue |
| 176 |
|
| 177 |
gaps = seq.gaps() |
| 178 |
bases = list(seq.seq) |
| 179 |
|
| 180 |
# extend the length of each gap |
| 181 |
for gap in gaps: |
| 182 |
left_start = max(gap.start - trim, 0) |
| 183 |
right_end = min(gap.end + trim + 1, len(seq)) |
| 184 |
|
| 185 |
for i in range(left_start, gap.start): |
| 186 |
bases[i] = 'N' |
| 187 |
|
| 188 |
for i in range(gap.end, right_end): |
| 189 |
bases[i] = 'N' |
| 190 |
|
| 191 |
seq.seq = ''.join(bases) |
| 192 |
|
| 193 |
# trim start/end bases and tidy up any resulting Ns at either end of the trimmed seq |
| 194 |
seq.trim(trim, trim) |
| 195 |
seq.trim_Ns() |
| 196 |
|
| 197 |
# check that there is some non-N sequence left over |
| 198 |
regex = re.compile('[^nN]') |
| 199 |
if regex.search(seq.seq) is not None: |
| 200 |
print(seq, file=fout) |
| 201 |
|
| 202 |
utils.close(fout) |
| 203 |
|
| 204 |
|
| 205 |
def fastaq_to_fake_qual(infile, outfile, q=40): |
| 206 |
seq_reader = sequences.file_reader(infile) |
| 207 |
fout = utils.open_file_write(outfile) |
| 208 |
|
| 209 |
for seq in seq_reader: |
| 210 |
print('>' + seq.id, file=fout) |
| 211 |
if sequences.Fasta.line_length == 0: |
| 212 |
print(' '.join([str(q)] * len(seq)), file=fout) |
| 213 |
else: |
| 214 |
for i in range(0, len(seq), sequences.Fasta.line_length): |
| 215 |
print(' '.join([str(q)] * min(sequences.Fasta.line_length, len(seq) - i)), file=fout) |
| 216 |
|
| 217 |
utils.close(fout) |
| 218 |
|
| 219 |
|
| 220 |
def fasta_to_fastq(fasta_in, qual_in, outfile): |
| 221 |
fa_reader = sequences.file_reader(fasta_in) |
| 222 |
qual_reader = sequences.file_reader(qual_in, read_quals=True) |
| 223 |
f_out = utils.open_file_write(outfile) |
| 224 |
|
| 225 |
for seq in fa_reader: |
| 226 |
qual = next(qual_reader) |
| 227 |
if seq.id != qual.id: |
| 228 |
utils.close(f_out) |
| 229 |
raise Error('Mismatch in names from fasta and qual file', seq.id, qual.id) |
| 230 |
|
| 231 |
qual.seq = [int(x) for x in qual.seq.split()] |
| 232 |
print(seq.to_Fastq(qual.seq), file=f_out) |
| 233 |
|
| 234 |
utils.close(f_out) |
| 235 |
|
| 236 |
|
| 237 |
def fastaq_to_mira_xml(infile, outfile): |
| 238 |
seq_reader = sequences.file_reader(infile) |
| 239 |
fout = utils.open_file_write(outfile) |
| 240 |
print('<?xml version="1.0"?>', '<trace_volume>', sep='\n', file=fout) |
| 241 |
|
| 242 |
for seq in seq_reader: |
| 243 |
print(' <trace>', |
| 244 |
' <trace_name>' + seq.id + '</trace_name>', |
| 245 |
' <clip_quality_right>' + str(len(seq)) + '</clip_quality_right>', |
| 246 |
' <clip_vector_left>1</clip_vector_left>', |
| 247 |
' </trace>', sep='\n', file=fout) |
| 248 |
|
| 249 |
|
| 250 |
print('</trace_volume>', file=fout) |
| 251 |
utils.close(fout) |
| 252 |
|
| 253 |
|
| 254 |
def fastaq_to_orfs_gff(infile, outfile, min_length=300, tool_name='fastaq'): |
| 255 |
seq_reader = sequences.file_reader(infile) |
| 256 |
fout = utils.open_file_write(outfile) |
| 257 |
for seq in seq_reader: |
| 258 |
orfs = seq.all_orfs(min_length=min_length) |
| 259 |
for coords, revcomp in orfs: |
| 260 |
if revcomp: |
| 261 |
strand = '-' |
| 262 |
else: |
| 263 |
strand = '+' |
| 264 |
|
| 265 |
print(seq.id, tool_name, 'CDS', coords.start+1, coords.end+1, '.', strand, '.', sep='\t', file=fout) |
| 266 |
|
| 267 |
utils.close(fout) |
| 268 |
|
| 269 |
|
| 270 |
def file_to_dict(infile, d): |
| 271 |
seq_reader = sequences.file_reader(infile) |
| 272 |
for seq in seq_reader: |
| 273 |
d[seq.id] = copy.copy(seq) |
| 274 |
|
| 275 |
|
| 276 |
def filter( |
| 277 |
infile, |
| 278 |
outfile, |
| 279 |
minlength=0, |
| 280 |
maxlength=float('inf'), |
| 281 |
regex=None, |
| 282 |
ids_file=None, |
| 283 |
invert=False, |
| 284 |
mate_in=None, |
| 285 |
mate_out=None, |
| 286 |
both_mates_pass=True, |
| 287 |
): |
| 288 |
|
| 289 |
ids_from_file = set() |
| 290 |
if ids_file is not None: |
| 291 |
f = utils.open_file_read(ids_file) |
| 292 |
for line in f: |
| 293 |
ids_from_file.add(line.rstrip()) |
| 294 |
utils.close(f) |
| 295 |
|
| 296 |
if mate_in: |
| 297 |
if mate_out is None: |
| 298 |
raise Error('Error in filter! mate_in provided. Must also provide mate_out') |
| 299 |
|
| 300 |
seq_reader_mate = sequences.file_reader(mate_in) |
| 301 |
f_out_mate = utils.open_file_write(mate_out) |
| 302 |
|
| 303 |
seq_reader = sequences.file_reader(infile) |
| 304 |
f_out = utils.open_file_write(outfile) |
| 305 |
if regex is not None: |
| 306 |
r = re.compile(regex) |
| 307 |
|
| 308 |
|
| 309 |
def passes(seq, name_regex): |
| 310 |
# remove trailing comments from FASTQ readname lines |
| 311 |
matches = name_regex.match(seq.id) |
| 312 |
if matches is not None: |
| 313 |
clean_seq_id = matches.group(1) |
| 314 |
else: |
| 315 |
clean_seq_id = seq.id |
| 316 |
|
| 317 |
return minlength <= len(seq) <= maxlength \ |
| 318 |
and (regex is None or r.search(clean_seq_id) is not None) \ |
| 319 |
and (ids_file is None or clean_seq_id in ids_from_file) |
| 320 |
|
| 321 |
name_regex = re.compile(r'^([^\s]+).*?$') |
| 322 |
|
| 323 |
for seq in seq_reader: |
| 324 |
seq_passes = passes(seq, name_regex) |
| 325 |
if mate_in: |
| 326 |
try: |
| 327 |
seq_mate = next(seq_reader_mate) |
| 328 |
except: |
| 329 |
utils.close(f_out) |
| 330 |
raise Error('Error getting mate for sequence', seq.id, ' ... cannot continue') |
| 331 |
|
| 332 |
mate_passes = passes(seq_mate, name_regex) |
| 333 |
want_the_pair = (seq_passes and mate_passes) \ |
| 334 |
or (( seq_passes or mate_passes) and not both_mates_pass) |
| 335 |
if want_the_pair != invert: |
| 336 |
print(seq, file=f_out) |
| 337 |
print(seq_mate, file=f_out_mate) |
| 338 |
elif seq_passes != invert: |
| 339 |
print(seq, file=f_out) |
| 340 |
utils.close(f_out) |
| 341 |
if mate_in: |
| 342 |
utils.close(f_out_mate) |
| 343 |
|
| 344 |
|
| 345 |
def get_ids(infile, outfile): |
| 346 |
seq_reader = sequences.file_reader(infile) |
| 347 |
f_out = utils.open_file_write(outfile) |
| 348 |
for seq in seq_reader: |
| 349 |
print(seq.id, file=f_out) |
| 350 |
utils.close(f_out) |
| 351 |
|
| 352 |
|
| 353 |
def get_seqs_flanking_gaps(infile, outfile, left, right): |
| 354 |
seq_reader = sequences.file_reader(infile) |
| 355 |
fout = utils.open_file_write(outfile) |
| 356 |
|
| 357 |
print('#id', 'gap_start', 'gap_end', 'left_bases', 'right_bases', sep='\t', file=fout) |
| 358 |
|
| 359 |
for seq in seq_reader: |
| 360 |
gaps = seq.gaps() |
| 361 |
|
| 362 |
for gap in gaps: |
| 363 |
left_start = max(gap.start - left, 0) |
| 364 |
right_end = min(gap.end + right + 1, len(seq)) |
| 365 |
print(seq.id, |
| 366 |
gap.start + 1, |
| 367 |
gap.end + 1, |
| 368 |
seq.seq[left_start:gap.start], |
| 369 |
seq.seq[gap.end + 1:right_end], |
| 370 |
sep='\t', file=fout) |
| 371 |
|
| 372 |
utils.close(fout) |
| 373 |
|
| 374 |
|
| 375 |
def interleave(infile_1, infile_2, outfile, suffix1=None, suffix2=None): |
| 376 |
'''Makes interleaved file from two sequence files. If used, will append suffix1 onto end |
| 377 |
of every sequence name in infile_1, unless it already ends with suffix1. Similar for sufffix2.''' |
| 378 |
seq_reader_1 = sequences.file_reader(infile_1) |
| 379 |
seq_reader_2 = sequences.file_reader(infile_2) |
| 380 |
f_out = utils.open_file_write(outfile) |
| 381 |
|
| 382 |
for seq_1 in seq_reader_1: |
| 383 |
try: |
| 384 |
seq_2 = next(seq_reader_2) |
| 385 |
except: |
| 386 |
utils.close(f_out) |
| 387 |
raise Error('Error getting mate for sequence', seq_1.id, ' ... cannot continue') |
| 388 |
|
| 389 |
if suffix1 is not None and not seq_1.id.endswith(suffix1): |
| 390 |
seq_1.id += suffix1 |
| 391 |
if suffix2 is not None and not seq_2.id.endswith(suffix2): |
| 392 |
seq_2.id += suffix2 |
| 393 |
|
| 394 |
print(seq_1, file=f_out) |
| 395 |
print(seq_2, file=f_out) |
| 396 |
|
| 397 |
try: |
| 398 |
seq_2 = next(seq_reader_2) |
| 399 |
except: |
| 400 |
seq_2 = None |
| 401 |
|
| 402 |
if seq_2 is not None: |
| 403 |
utils.close(f_out) |
| 404 |
raise Error('Error getting mate for sequence', seq_2.id, ' ... cannot continue') |
| 405 |
|
| 406 |
utils.close(f_out) |
| 407 |
|
| 408 |
|
| 409 |
def make_random_contigs(contigs, length, outfile, name_by_letters=False, prefix='', seed=None, first_number=1): |
| 410 |
'''Makes a multi fasta file of random sequences, all the same length''' |
| 411 |
random.seed(a=seed) |
| 412 |
fout = utils.open_file_write(outfile) |
| 413 |
letters = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ') |
| 414 |
letters_index = 0 |
| 415 |
|
| 416 |
for i in range(contigs): |
| 417 |
if name_by_letters: |
| 418 |
name = letters[letters_index] |
| 419 |
letters_index += 1 |
| 420 |
if letters_index == len(letters): |
| 421 |
letters_index = 0 |
| 422 |
else: |
| 423 |
name = str(i + first_number) |
| 424 |
|
| 425 |
fa = sequences.Fasta(prefix + name, ''.join([random.choice('ACGT') for x in range(length)])) |
| 426 |
print(fa, file=fout) |
| 427 |
|
| 428 |
utils.close(fout) |
| 429 |
|
| 430 |
|
| 431 |
def mean_length(infile, limit=None): |
| 432 |
'''Returns the mean length of the sequences in the input file. By default uses all sequences. To limit to the first N sequences, use limit=N''' |
| 433 |
total = 0 |
| 434 |
count = 0 |
| 435 |
seq_reader = sequences.file_reader(infile) |
| 436 |
for seq in seq_reader: |
| 437 |
total += len(seq) |
| 438 |
count += 1 |
| 439 |
if limit is not None and count >= limit: |
| 440 |
break |
| 441 |
|
| 442 |
assert count > 0 |
| 443 |
return total / count |
| 444 |
|
| 445 |
|
| 446 |
def merge_to_one_seq(infile, outfile, seqname='union'): |
| 447 |
'''Takes a multi fasta or fastq file and writes a new file that contains just one sequence, with the original sequences catted together, preserving their order''' |
| 448 |
seq_reader = sequences.file_reader(infile) |
| 449 |
seqs = [] |
| 450 |
|
| 451 |
for seq in seq_reader: |
| 452 |
seqs.append(copy.copy(seq)) |
| 453 |
|
| 454 |
new_seq = ''.join([seq.seq for seq in seqs]) |
| 455 |
|
| 456 |
if type(seqs[0]) == sequences.Fastq: |
| 457 |
new_qual = ''.join([seq.qual for seq in seqs]) |
| 458 |
seqs[:] = [] |
| 459 |
merged = sequences.Fastq(seqname, new_seq, new_qual) |
| 460 |
else: |
| 461 |
merged = sequences.Fasta(seqname, new_seq) |
| 462 |
seqs[:] = [] |
| 463 |
|
| 464 |
f = utils.open_file_write(outfile) |
| 465 |
print(merged, file=f) |
| 466 |
utils.close(f) |
| 467 |
|
| 468 |
|
| 469 |
def reverse_complement(infile, outfile): |
| 470 |
seq_reader = sequences.file_reader(infile) |
| 471 |
fout = utils.open_file_write(outfile) |
| 472 |
|
| 473 |
for seq in seq_reader: |
| 474 |
seq.revcomp() |
| 475 |
print(seq, file=fout) |
| 476 |
|
| 477 |
utils.close(fout) |
| 478 |
|
| 479 |
|
| 480 |
def scaffolds_to_contigs(infile, outfile, number_contigs=False): |
| 481 |
'''Makes a file of contigs from scaffolds by splitting at every N. |
| 482 |
Use number_contigs=True to add .1, .2, etc onto end of each |
| 483 |
contig, instead of default to append coordinates.''' |
| 484 |
seq_reader = sequences.file_reader(infile) |
| 485 |
fout = utils.open_file_write(outfile) |
| 486 |
|
| 487 |
for seq in seq_reader: |
| 488 |
contigs = seq.contig_coords() |
| 489 |
counter = 1 |
| 490 |
for contig in contigs: |
| 491 |
if number_contigs: |
| 492 |
name = seq.id + '.' + str(counter) |
| 493 |
counter += 1 |
| 494 |
else: |
| 495 |
name = '.'.join([seq.id, str(contig.start + 1), str(contig.end + 1)]) |
| 496 |
print(sequences.Fasta(name, seq[contig.start:contig.end+1]), file=fout) |
| 497 |
|
| 498 |
utils.close(fout) |
| 499 |
|
| 500 |
|
| 501 |
def search_for_seq(infile, outfile, search_string): |
| 502 |
seq_reader = sequences.file_reader(infile) |
| 503 |
fout = utils.open_file_write(outfile) |
| 504 |
|
| 505 |
for seq in seq_reader: |
| 506 |
hits = seq.search(search_string) |
| 507 |
for hit in hits: |
| 508 |
print(seq.id, hit[0]+1, hit[1], sep='\t', file=fout) |
| 509 |
|
| 510 |
utils.close(fout) |
| 511 |
|
| 512 |
|
| 513 |
def sequence_trim(infile_1, infile_2, outfile_1, outfile_2, to_trim_file, min_length=50, check_revcomp=False): |
| 514 |
to_trim_seqs = {} |
| 515 |
file_to_dict(to_trim_file, to_trim_seqs) |
| 516 |
trim_seqs = [x.seq for x in to_trim_seqs.values()] |
| 517 |
if check_revcomp: |
| 518 |
for seq in to_trim_seqs.values(): |
| 519 |
seq.revcomp() |
| 520 |
trim_seqs_revcomp = [x.seq for x in to_trim_seqs.values()] |
| 521 |
else: |
| 522 |
trim_seqs_revcomp = [] |
| 523 |
|
| 524 |
seq_reader_1 = sequences.file_reader(infile_1) |
| 525 |
seq_reader_2 = sequences.file_reader(infile_2) |
| 526 |
f_out_1 = utils.open_file_write(outfile_1) |
| 527 |
f_out_2 = utils.open_file_write(outfile_2) |
| 528 |
|
| 529 |
for seq_1 in seq_reader_1: |
| 530 |
try: |
| 531 |
seq_2 = next(seq_reader_2) |
| 532 |
except: |
| 533 |
utils.close(f_out) |
| 534 |
raise Error('Error getting mate for sequence', seq_1.id, ' ... cannot continue') |
| 535 |
|
| 536 |
for seq in seq_1, seq_2: |
| 537 |
for trim_seq in trim_seqs: |
| 538 |
if seq.seq.startswith(trim_seq): |
| 539 |
seq.trim(len(trim_seq),0) |
| 540 |
break |
| 541 |
|
| 542 |
for trim_seq in trim_seqs_revcomp: |
| 543 |
if seq.seq.endswith(trim_seq): |
| 544 |
seq.trim(0,len(trim_seq)) |
| 545 |
break |
| 546 |
|
| 547 |
if len(seq_1) >= min_length and len(seq_2) >= min_length: |
| 548 |
print(seq_1, file=f_out_1) |
| 549 |
print(seq_2, file=f_out_2) |
| 550 |
|
| 551 |
|
| 552 |
utils.close(f_out_1) |
| 553 |
utils.close(f_out_2) |
| 554 |
|
| 555 |
|
| 556 |
def sort_by_size(infile, outfile, smallest_first=False): |
| 557 |
'''Sorts input sequence file by biggest sequence first, writes sorted output file. Set smallest_first=True to have smallest first''' |
| 558 |
seqs = {} |
| 559 |
file_to_dict(infile, seqs) |
| 560 |
seqs = list(seqs.values()) |
| 561 |
seqs.sort(key=lambda x: len(x), reverse=not smallest_first) |
| 562 |
fout = utils.open_file_write(outfile) |
| 563 |
for seq in seqs: |
| 564 |
print(seq, file=fout) |
| 565 |
utils.close(fout) |
| 566 |
|
| 567 |
|
| 568 |
def sort_by_name(infile, outfile): |
| 569 |
'''Sorts input sequence file by sort -d -k1,1, writes sorted output file.''' |
| 570 |
seqs = {} |
| 571 |
file_to_dict(infile, seqs) |
| 572 |
#seqs = list(seqs.values()) |
| 573 |
#seqs.sort() |
| 574 |
fout = utils.open_file_write(outfile) |
| 575 |
for name in sorted(seqs): |
| 576 |
print(seqs[name], file=fout) |
| 577 |
utils.close(fout) |
| 578 |
|
| 579 |
|
| 580 |
def to_fastg(infile, outfile, circular=None): |
| 581 |
'''Writes a FASTG file in SPAdes format from input file. Currently only whether or not a sequence is circular is supported. Put circular=set of ids, or circular=filename to make those sequences circular in the output. Puts coverage=1 on all contigs''' |
| 582 |
if circular is None: |
| 583 |
to_circularise = set() |
| 584 |
elif type(circular) is not set: |
| 585 |
f = utils.open_file_read(circular) |
| 586 |
to_circularise = set([x.rstrip() for x in f.readlines()]) |
| 587 |
utils.close(f) |
| 588 |
else: |
| 589 |
to_circularise = circular |
| 590 |
|
| 591 |
seq_reader = sequences.file_reader(infile) |
| 592 |
fout = utils.open_file_write(outfile) |
| 593 |
nodes = 1 |
| 594 |
|
| 595 |
for seq in seq_reader: |
| 596 |
new_id = '_'.join([ |
| 597 |
'NODE', str(nodes), |
| 598 |
'length', str(len(seq)), |
| 599 |
'cov', '1', |
| 600 |
'ID', seq.id |
| 601 |
]) |
| 602 |
|
| 603 |
if seq.id in to_circularise: |
| 604 |
seq.id = new_id + ':' + new_id + ';' |
| 605 |
print(seq, file=fout) |
| 606 |
seq.revcomp() |
| 607 |
seq.id = new_id + "':" + new_id + "';" |
| 608 |
print(seq, file=fout) |
| 609 |
else: |
| 610 |
seq.id = new_id + ';' |
| 611 |
print(seq, file=fout) |
| 612 |
seq.revcomp() |
| 613 |
seq.id = new_id + "';" |
| 614 |
print(seq, file=fout) |
| 615 |
|
| 616 |
nodes += 1 |
| 617 |
|
| 618 |
utils.close(fout) |
| 619 |
|
| 620 |
|
| 621 |
def translate(infile, outfile, frame=0): |
| 622 |
seq_reader = sequences.file_reader(infile) |
| 623 |
fout = utils.open_file_write(outfile) |
| 624 |
|
| 625 |
for seq in seq_reader: |
| 626 |
print(seq.translate(frame=frame), file=fout) |
| 627 |
|
| 628 |
utils.close(fout) |
| 629 |
|
| 630 |
|
| 631 |
def trim(infile, outfile, start, end): |
| 632 |
seq_reader = sequences.file_reader(infile) |
| 633 |
fout = utils.open_file_write(outfile) |
| 634 |
|
| 635 |
for seq in seq_reader: |
| 636 |
seq.trim(start, end) |
| 637 |
if len(seq): |
| 638 |
print(seq, file=fout) |
| 639 |
|
| 640 |
utils.close(fout) |
| 641 |
|
| 642 |
|
| 643 |
def trim_Ns_at_end(infile, outfile): |
| 644 |
seq_reader = sequences.file_reader(infile) |
| 645 |
fout = utils.open_file_write(outfile) |
| 646 |
|
| 647 |
for seq in seq_reader: |
| 648 |
seq.trim_Ns() |
| 649 |
if len(seq): |
| 650 |
print(seq, file=fout) |
| 651 |
|
| 652 |
utils.close(fout) |
| 653 |
|
| 654 |
|
| 655 |
def lengths_from_fai(fai_file, d): |
| 656 |
f = utils.open_file_read(fai_file) |
| 657 |
for line in f: |
| 658 |
(id, length) = line.rstrip().split()[:2] |
| 659 |
d[id] = int(length) |
| 660 |
utils.close(f) |
| 661 |
|
| 662 |
|
| 663 |
def length_offsets_from_fai(fai_file): |
| 664 |
'''Returns a dictionary of positions of the start of each sequence, as |
| 665 |
if all the sequences were catted into one sequence. |
| 666 |
eg if file has three sequences, seq1 10bp, seq2 30bp, seq3 20bp, then |
| 667 |
the output would be: {'seq1': 0, 'seq2': 10, 'seq3': 40}''' |
| 668 |
positions = {} |
| 669 |
total_length = 0 |
| 670 |
f = utils.open_file_read(fai_file) |
| 671 |
|
| 672 |
for line in f: |
| 673 |
try: |
| 674 |
(name, length) = line.rstrip().split()[:2] |
| 675 |
length = int(length) |
| 676 |
except: |
| 677 |
raise Error('Error reading the following line of fai file ' + fai_file + '\n' + line) |
| 678 |
|
| 679 |
positions[name] = total_length |
| 680 |
total_length += length |
| 681 |
|
| 682 |
utils.close(f) |
| 683 |
return positions |
| 684 |
|
| 685 |
|
| 686 |
def split_by_base_count(infile, outfiles_prefix, max_bases, max_seqs=None): |
| 687 |
'''Splits a fasta/q file into separate files, file size determined by number of bases. |
| 688 |
|
| 689 |
Puts <= max_bases in each split file The exception is a single sequence >=max_bases |
| 690 |
is put in its own file. This does not split sequences. |
| 691 |
''' |
| 692 |
seq_reader = sequences.file_reader(infile) |
| 693 |
base_count = 0 |
| 694 |
file_count = 1 |
| 695 |
seq_count = 0 |
| 696 |
fout = None |
| 697 |
if max_seqs is None: |
| 698 |
max_seqs = float('inf') |
| 699 |
|
| 700 |
for seq in seq_reader: |
| 701 |
if base_count == 0: |
| 702 |
fout = utils.open_file_write(outfiles_prefix + '.' + str(file_count)) |
| 703 |
file_count += 1 |
| 704 |
|
| 705 |
if base_count + len(seq) > max_bases or seq_count >= max_seqs: |
| 706 |
if base_count == 0: |
| 707 |
print(seq, file=fout) |
| 708 |
utils.close(fout) |
| 709 |
else: |
| 710 |
utils.close(fout) |
| 711 |
fout = utils.open_file_write(outfiles_prefix + '.' + str(file_count)) |
| 712 |
print(seq, file=fout) |
| 713 |
base_count = len(seq) |
| 714 |
file_count += 1 |
| 715 |
seq_count = 1 |
| 716 |
else: |
| 717 |
base_count += len(seq) |
| 718 |
seq_count += 1 |
| 719 |
print(seq, file=fout) |
| 720 |
|
| 721 |
utils.close(fout) |
| 722 |
|
| 723 |
|
| 724 |
def split_by_fixed_size(infile, outfiles_prefix, chunk_size, tolerance, skip_if_all_Ns=False): |
| 725 |
'''Splits fasta/q file into separate files, with up to (chunk_size + tolerance) bases in each file''' |
| 726 |
file_count = 1 |
| 727 |
coords = [] |
| 728 |
small_sequences = [] # sequences shorter than chunk_size |
| 729 |
seq_reader = sequences.file_reader(infile) |
| 730 |
f_coords = utils.open_file_write(outfiles_prefix + '.coords') |
| 731 |
|
| 732 |
for seq in seq_reader: |
| 733 |
if skip_if_all_Ns and seq.is_all_Ns(): |
| 734 |
continue |
| 735 |
if len(seq) < chunk_size: |
| 736 |
small_sequences.append(copy.copy(seq)) |
| 737 |
elif len(seq) <= chunk_size + tolerance: |
| 738 |
f = utils.open_file_write(outfiles_prefix + '.' + str(file_count)) |
| 739 |
print(seq, file=f) |
| 740 |
utils.close(f) |
| 741 |
file_count += 1 |
| 742 |
else: |
| 743 |
# make list of chunk coords |
| 744 |
chunks = [(x,x+chunk_size) for x in range(0, len(seq), chunk_size)] |
| 745 |
if chunks[-1][1] - 1 > len(seq): |
| 746 |
chunks[-1] = (chunks[-1][0], len(seq)) |
| 747 |
if len(chunks) > 1 and (chunks[-1][1] - chunks[-1][0]) <= tolerance: |
| 748 |
chunks[-2] = (chunks[-2][0], chunks[-1][1]) |
| 749 |
chunks.pop() |
| 750 |
|
| 751 |
# write one output file per chunk |
| 752 |
offset = 0 |
| 753 |
for chunk in chunks: |
| 754 |
if not(skip_if_all_Ns and seq.is_all_Ns(start=chunk[0], end=chunk[1]-1)): |
| 755 |
f = utils.open_file_write(outfiles_prefix + '.' + str(file_count)) |
| 756 |
chunk_id = seq.id + ':' + str(chunk[0]+1) + '-' + str(chunk[1]) |
| 757 |
print(sequences.Fasta(chunk_id, seq[chunk[0]:chunk[1]]), file=f) |
| 758 |
print(chunk_id, seq.id, offset, sep='\t', file=f_coords) |
| 759 |
utils.close(f) |
| 760 |
file_count += 1 |
| 761 |
|
| 762 |
offset += chunk[1] - chunk[0] |
| 763 |
|
| 764 |
# write files of small sequences |
| 765 |
if len(small_sequences): |
| 766 |
f = utils.open_file_write(outfiles_prefix + '.' + str(file_count)) |
| 767 |
file_count += 1 |
| 768 |
base_count = 0 |
| 769 |
for seq in small_sequences: |
| 770 |
if base_count > 0 and base_count + len(seq) > chunk_size + tolerance: |
| 771 |
utils.close(f) |
| 772 |
f = utils.open_file_write(outfiles_prefix + '.' + str(file_count)) |
| 773 |
file_count += 1 |
| 774 |
base_count = 0 |
| 775 |
|
| 776 |
print(seq, file=f) |
| 777 |
base_count += len(seq) |
| 778 |
|
| 779 |
utils.close(f) |
| 780 |
|
| 781 |
|
| 782 |
def split_by_fixed_size_onefile(infile, outfile, chunk_size, tolerance, skip_if_all_Ns=False): |
| 783 |
'''Splits each sequence in infile into chunks of fixed size, last chunk can be up to |
| 784 |
(chunk_size + tolerance) in length''' |
| 785 |
seq_reader = sequences.file_reader(infile) |
| 786 |
f_out = utils.open_file_write(outfile) |
| 787 |
for seq in seq_reader: |
| 788 |
for i in range(0, len(seq), chunk_size): |
| 789 |
if i + chunk_size + tolerance >= len(seq): |
| 790 |
end = len(seq) |
| 791 |
else: |
| 792 |
end = i + chunk_size |
| 793 |
|
| 794 |
subseq = seq.subseq(i, end) |
| 795 |
if not (skip_if_all_Ns and subseq.is_all_Ns()): |
| 796 |
subseq.id += '.' + str(i+1) + '_' + str(end) |
| 797 |
print(subseq, file=f_out) |
| 798 |
|
| 799 |
if end == len(seq): |
| 800 |
break |
| 801 |
|
| 802 |
utils.close(f_out) |
| 803 |
|
| 804 |
|
| 805 |
def replace_bases(infile, outfile, old, new): |
| 806 |
seq_reader = sequences.file_reader(infile) |
| 807 |
f_out = utils.open_file_write(outfile) |
| 808 |
|
| 809 |
for seq in seq_reader: |
| 810 |
seq.replace_bases(old, new) |
| 811 |
print(seq, file=f_out) |
| 812 |
|
| 813 |
utils.close(f_out) |
| 814 |
|
| 815 |
|
| 816 |
def strip_illumina_suffix(infile, outfile): |
| 817 |
seq_reader = sequences.file_reader(infile) |
| 818 |
f_out = utils.open_file_write(outfile) |
| 819 |
|
| 820 |
for seq in seq_reader: |
| 821 |
seq.strip_illumina_suffix() |
| 822 |
print(seq, file=f_out) |
| 823 |
|
| 824 |
utils.close(f_out) |
| 825 |
|
| 826 |
|
| 827 |
def stats_from_fai(infile): |
| 828 |
'''Returns dictionary of length stats from an fai file. Keys are: longest, shortest, mean, total_length, N50, number''' |
| 829 |
f = utils.open_file_read(infile) |
| 830 |
try: |
| 831 |
lengths = sorted([int(line.split('\t')[1]) for line in f], reverse=True) |
| 832 |
except: |
| 833 |
raise Error('Error getting lengths from fai file ' + infile) |
| 834 |
utils.close(f) |
| 835 |
|
| 836 |
stats = {} |
| 837 |
if len(lengths) > 0: |
| 838 |
stats['longest'] = max(lengths) |
| 839 |
stats['shortest'] = min(lengths) |
| 840 |
stats['total_length'] = sum(lengths) |
| 841 |
stats['mean'] = stats['total_length'] / len(lengths) |
| 842 |
stats['number'] = len(lengths) |
| 843 |
|
| 844 |
cumulative_length = 0 |
| 845 |
for length in lengths: |
| 846 |
cumulative_length += length |
| 847 |
if cumulative_length >= 0.5 * stats['total_length']: |
| 848 |
stats['N50'] = length |
| 849 |
break |
| 850 |
else: |
| 851 |
stats = {x: 0 for x in ('longest', 'shortest', 'mean', 'N50', 'total_length', 'number')} |
| 852 |
|
| 853 |
return stats |
| 854 |
|
| 855 |
|
| 856 |
def to_boulderio(infile, outfile): |
| 857 |
'''Converts input sequence file into a "Boulder-IO format", as used by primer3''' |
| 858 |
seq_reader = sequences.file_reader(infile) |
| 859 |
f_out = utils.open_file_write(outfile) |
| 860 |
|
| 861 |
for sequence in seq_reader: |
| 862 |
print("SEQUENCE_ID=" + sequence.id, file=f_out) |
| 863 |
print("SEQUENCE_TEMPLATE=" + sequence.seq, file=f_out) |
| 864 |
print("=", file=f_out) |
| 865 |
|
| 866 |
utils.close(f_out) |
| 867 |
|
| 868 |
|
| 869 |
def to_fasta(infile, outfile, line_length=60, strip_after_first_whitespace=False, check_unique=False): |
| 870 |
seq_reader = sequences.file_reader(infile) |
| 871 |
f_out = utils.open_file_write(outfile) |
| 872 |
original_line_length = sequences.Fasta.line_length |
| 873 |
sequences.Fasta.line_length = line_length |
| 874 |
if check_unique: |
| 875 |
used_names = {} |
| 876 |
|
| 877 |
for seq in seq_reader: |
| 878 |
if strip_after_first_whitespace: |
| 879 |
seq.strip_after_first_whitespace() |
| 880 |
|
| 881 |
if check_unique: |
| 882 |
used_names[seq.id] = used_names.get(seq.id, 0) + 1 |
| 883 |
|
| 884 |
if type(seq) == sequences.Fastq: |
| 885 |
print(sequences.Fasta(seq.id, seq.seq), file=f_out) |
| 886 |
else: |
| 887 |
print(seq, file=f_out) |
| 888 |
|
| 889 |
utils.close(f_out) |
| 890 |
sequences.Fasta.line_length = original_line_length |
| 891 |
|
| 892 |
if check_unique: |
| 893 |
all_unique = True |
| 894 |
|
| 895 |
for name, count in used_names.items(): |
| 896 |
if count > 1: |
| 897 |
print('Sequence name "' + name + '" not unique. Found', count, 'times', file=sys.stderr) |
| 898 |
all_unique = False |
| 899 |
|
| 900 |
if not all_unique: |
| 901 |
raise Error('Not all sequence names unique. Cannot continue') |
| 902 |
|
| 903 |
|
| 904 |
|
| 905 |
def to_fasta_union(infile, outfile, seqname='union'): |
| 906 |
seq_reader = sequences.file_reader(infile) |
| 907 |
new_seq = [] |
| 908 |
|
| 909 |
for seq in seq_reader: |
| 910 |
new_seq.append(seq.seq) |
| 911 |
|
| 912 |
f_out = utils.open_file_write(outfile) |
| 913 |
print(sequences.Fasta(seqname, ''.join(new_seq)), file=f_out) |
| 914 |
utils.close(f_out) |
| 915 |
|
| 916 |
|
| 917 |
|
| 918 |
def to_unique_by_id(infile, outfile): |
| 919 |
seq_reader = sequences.file_reader(infile) |
| 920 |
seqs = {} |
| 921 |
ids_in_order = [] |
| 922 |
|
| 923 |
# has the reads, keeping the longest one when we get the same |
| 924 |
# name more than once |
| 925 |
for seq in seq_reader: |
| 926 |
if len(seq) == 0: |
| 927 |
continue |
| 928 |
if seq.id not in seqs: |
| 929 |
seqs[seq.id] = copy.copy(seq) |
| 930 |
ids_in_order.append(seq.id) |
| 931 |
elif len(seqs[seq.id]) < len(seq): |
| 932 |
seqs[seq.id] = copy.copy(seq) |
| 933 |
|
| 934 |
# write the output |
| 935 |
f_out = utils.open_file_write(outfile) |
| 936 |
for id in ids_in_order: |
| 937 |
print(seqs[id], file=f_out) |
| 938 |
utils.close(f_out) |