| 1 |
import copy |
| 2 |
import re |
| 3 |
import random |
| 4 |
import itertools |
| 5 |
from collections import Counter |
| 6 |
from pyfastaq import utils, intervals, genetic_codes |
| 7 |
|
| 8 |
class Error (Exception): pass |
| 9 |
|
| 10 |
|
| 11 |
# python 3's seek is glacially slow. When we read a fasta file, we know |
| 12 |
# we've reached the end of a sequence when we get a new line starting with |
| 13 |
# '>'. Instead of using seek and tell, we just remember the previous line |
| 14 |
# of the file, for any given filehandle |
| 15 |
previous_lines = {} |
| 16 |
|
| 17 |
genetic_code = 1 |
| 18 |
|
| 19 |
redundant_nts = { |
| 20 |
'R': ('A', 'G'), |
| 21 |
'Y': ('C', 'T'), |
| 22 |
'S': ('C', 'G'), |
| 23 |
'W': ('A', 'T'), |
| 24 |
'K': ('G', 'T'), |
| 25 |
'M': ('A', 'C'), |
| 26 |
'B': ('C', 'G', 'T'), |
| 27 |
'D': ('A', 'G', 'T'), |
| 28 |
'H': ('A', 'C', 'T'), |
| 29 |
'V': ('A', 'C', 'G'), |
| 30 |
'N': ('A', 'C', 'G', 'T') |
| 31 |
} |
| 32 |
|
| 33 |
def file_reader(fname, read_quals=False): |
| 34 |
'''Iterates over a FASTA or FASTQ file, yielding the next sequence in the file until there are no more sequences''' |
| 35 |
f = utils.open_file_read(fname) |
| 36 |
line = f.readline() |
| •37 |
phylip_regex = re.compile(r'^\s*[0-9]+\s+[0-9]+$') |
| 38 |
gbk_regex = re.compile(r'^LOCUS\s+\S') |
| 39 |
|
| 40 |
if line.startswith('>'): |
| 41 |
seq = Fasta() |
| 42 |
previous_lines[f] = line |
| 43 |
elif line.startswith('##gff-version 3'): |
| 44 |
seq = Fasta() |
| 45 |
# if a GFF file, need to skip past all the annotation |
| 46 |
# and get to the fasta sequences at the end of the file |
| 47 |
while not line.startswith('>'): |
| 48 |
line = f.readline() |
| 49 |
if not line: |
| 50 |
utils.close(f) |
| 51 |
raise Error('No sequences found in GFF file "' + fname + '"') |
| 52 |
|
| 53 |
seq = Fasta() |
| 54 |
previous_lines[f] = line |
| 55 |
elif line.startswith('ID ') and line[5] != ' ': |
| 56 |
seq = Embl() |
| 57 |
previous_lines[f] = line |
| 58 |
elif gbk_regex.search(line): |
| 59 |
seq = Embl() |
| 60 |
previous_lines[f] = line |
| 61 |
elif line.startswith('@'): |
| 62 |
seq = Fastq() |
| 63 |
previous_lines[f] = line |
| 64 |
elif phylip_regex.search(line): |
| 65 |
# phylip format could be interleaved or not, need to look at next |
| 66 |
# couple of lines to figure that out. Don't expect these files to |
| 67 |
# be too huge, so just store all the sequences in memory |
| 68 |
number_of_seqs, bases_per_seq = line.strip().split() |
| 69 |
number_of_seqs = int(number_of_seqs) |
| 70 |
bases_per_seq = int(bases_per_seq) |
| 71 |
got_blank_line = False |
| 72 |
|
| 73 |
first_line = line |
| 74 |
seq_lines = [] |
| 75 |
while 1: |
| 76 |
line = f.readline() |
| 77 |
if line == '': |
| 78 |
break |
| 79 |
elif line == '\n': |
| 80 |
got_blank_line = True |
| 81 |
else: |
| 82 |
seq_lines.append(line.rstrip()) |
| 83 |
utils.close(f) |
| 84 |
|
| 85 |
if len(seq_lines) == 1 or len(seq_lines) == number_of_seqs: |
| 86 |
sequential = True |
| 87 |
elif seq_lines[0][10] != ' ' and seq_lines[1][10] == ' ': |
| 88 |
sequential = True |
| 89 |
else: |
| 90 |
sequential = False |
| 91 |
|
| 92 |
# if the 11th char of second sequence line is a space, then the file is sequential, e.g.: |
| 93 |
# GAGCCCGGGC AATACAGGGT AT |
| 94 |
# as opposed to: |
| 95 |
# Salmo gairAAGCCTTGGC AGTGCAGGGT |
| 96 |
if sequential: |
| 97 |
current_id = None |
| 98 |
current_seq = '' |
| 99 |
for line in seq_lines: |
| 100 |
if len(current_seq) == bases_per_seq or len(current_seq) == 0: |
| 101 |
if current_id is not None: |
| 102 |
yield Fasta(current_id, current_seq.replace('-', '')) |
| 103 |
current_seq = '' |
| 104 |
current_id, new_bases = line[0:10].rstrip(), line.rstrip()[10:] |
| 105 |
else: |
| 106 |
new_bases = line.rstrip() |
| 107 |
|
| 108 |
current_seq += new_bases.replace(' ','') |
| 109 |
|
| 110 |
yield Fasta(current_id, current_seq.replace('-', '')) |
| 111 |
else: |
| 112 |
# seaview files start all seqs at pos >=12. Other files start |
| 113 |
# their sequence at the start of the line |
| 114 |
if seq_lines[number_of_seqs + 1][0] == ' ': |
| 115 |
first_gap_pos = seq_lines[0].find(' ') |
| 116 |
end_of_gap = first_gap_pos |
| 117 |
while seq_lines[0][end_of_gap] == ' ': |
| 118 |
end_of_gap += 1 |
| 119 |
first_seq_base = end_of_gap |
| 120 |
else: |
| 121 |
first_seq_base = 10 |
| 122 |
|
| 123 |
seqs = [] |
| 124 |
for i in range(number_of_seqs): |
| 125 |
name, bases = seq_lines[i][0:first_seq_base].rstrip(), seq_lines[i][first_seq_base:] |
| 126 |
seqs.append(Fasta(name, bases)) |
| 127 |
|
| 128 |
for i in range(number_of_seqs, len(seq_lines)): |
| 129 |
seqs[i%number_of_seqs].seq += seq_lines[i] |
| 130 |
|
| 131 |
for fa in seqs: |
| 132 |
fa.seq = fa.seq.replace(' ','').replace('-','') |
| 133 |
yield fa |
| 134 |
|
| 135 |
return |
| 136 |
elif line == '': |
| 137 |
utils.close(f) |
| 138 |
return |
| 139 |
else: |
| 140 |
utils.close(f) |
| 141 |
raise Error('Error determining file type from file "' + fname + '". First line is:\n' + line.rstrip()) |
| 142 |
|
| 143 |
try: |
| 144 |
while seq.get_next_from_file(f, read_quals): |
| 145 |
yield seq |
| 146 |
finally: |
| 147 |
utils.close(f) |
| 148 |
|
| 149 |
|
| 150 |
class Fasta: |
| 151 |
'''Class to store and manipulate FASTA sequences. They have two things: a name and a sequence''' |
| 152 |
# this defines the line length when printing sequences |
| 153 |
line_length = 60 |
| 154 |
|
| 155 |
def _get_id_from_header_line(self, line): |
| 156 |
if line.startswith('>'): |
| 157 |
return line.rstrip()[1:] |
| 158 |
else: |
| 159 |
raise Error('Error! expected line starting with ">", but got this:\n', line) |
| 160 |
|
| 161 |
|
| 162 |
def __init__(self, id_in=None, seq_in=None): |
| 163 |
self.id = id_in |
| 164 |
self.seq = seq_in |
| 165 |
|
| 166 |
def __eq__(self, other): |
| 167 |
return type(other) is type(self) and self.__dict__ == other.__dict__ |
| 168 |
|
| 169 |
def __ne__(self, other): |
| 170 |
return not self.__eq__(other) |
| 171 |
|
| 172 |
def __len__(self): |
| 173 |
return len(self.seq) |
| 174 |
|
| 175 |
def subseq(self, start, end): |
| 176 |
'''Returns Fasta object with the same name, of the bases from start to end, but not including end''' |
| 177 |
return Fasta(self.id, self.seq[start:end]) |
| 178 |
|
| 179 |
def split_capillary_id(self): |
| 180 |
'''Gets the prefix and suffix of an name of a capillary read, e.g. xxxxx.p1k or xxxx.q1k. Returns a tuple (prefix, suffx)''' |
| 181 |
try: |
| 182 |
a = self.id.rsplit('.', 1) |
| 183 |
if a[1].startswith('p'): |
| 184 |
dir = 'fwd' |
| 185 |
elif a[1].startswith('q'): |
| 186 |
dir = 'rev' |
| 187 |
else: |
| 188 |
dir = 'unk' |
| 189 |
|
| 190 |
return {'prefix': a[0], 'dir': dir, 'suffix':a[1]} |
| 191 |
except: |
| 192 |
raise Error('Error in split_capillary_id() on ID', self.id) |
| 193 |
|
| 194 |
def expand_nucleotides(self): |
| 195 |
'''Assumes sequence is nucleotides. Returns list of all combinations of redundant nucleotides. e.g. R is A or G, so CRT would have combinations CAT and CGT''' |
| 196 |
s = list(self.seq) |
| 197 |
for i in range(len(s)): |
| 198 |
if s[i] in redundant_nts: |
| 199 |
s[i] = ''.join(redundant_nts[s[i]]) |
| 200 |
|
| 201 |
seqs = [] |
| 202 |
for x in itertools.product(*s): |
| 203 |
seqs.append(Fasta(self.id + '.' + str(len(seqs) + 1), ''.join(x))) |
| 204 |
return seqs |
| 205 |
|
| 206 |
def strip_after_first_whitespace(self): |
| 207 |
'''Removes everything in the name after the first whitespace character''' |
| 208 |
self.id = self.id.split()[0] |
| 209 |
|
| 210 |
def strip_illumina_suffix(self): |
| 211 |
'''Removes any trailing /1 or /2 off the end of the name''' |
| 212 |
if self.id.endswith('/1') or self.id.endswith('/2'): |
| 213 |
self.id = self.id[:-2] |
| 214 |
|
| 215 |
def revcomp(self): |
| 216 |
'''Reverse complements the sequence''' |
| 217 |
self.seq = self.seq.translate(str.maketrans("ATCGatcg", "TAGCtagc"))[::-1] |
| 218 |
|
| 219 |
def is_all_Ns(self, start=0, end=None): |
| 220 |
'''Returns true if the sequence is all Ns (upper or lower case)''' |
| 221 |
if end is not None: |
| 222 |
if start > end: |
| 223 |
raise Error('Error in is_all_Ns. Start coord must be <= end coord') |
| 224 |
end += 1 |
| 225 |
else: |
| 226 |
end = len(self) |
| 227 |
|
| 228 |
if len(self) == 0: |
| 229 |
return False |
| 230 |
else: |
| 231 |
return re.search('[^Nn]', self.seq[start:end]) is None |
| 232 |
|
| 233 |
def trim_Ns(self): |
| 234 |
'''Removes any leading or trailing N or n characters from the sequence''' |
| 235 |
self.seq = self.seq.strip('Nn') |
| 236 |
|
| 237 |
def add_insertions(self, skip=10, window=1, test=False): |
| 238 |
'''Adds a random base within window bases around every skip bases. e.g. skip=10, window=1 means a random base added somwhere in theintervals [9,11], [19,21] ... ''' |
| 239 |
assert 2 * window < skip |
| 240 |
new_seq = list(self.seq) |
| 241 |
for i in range(len(self) - skip, 0, -skip): |
| 242 |
pos = random.randrange(i - window, i + window + 1) |
| 243 |
base = random.choice(['A', 'C', 'G', 'T']) |
| 244 |
if test: |
| 245 |
base = 'N' |
| 246 |
new_seq.insert(pos, base) |
| 247 |
|
| 248 |
self.seq = ''.join(new_seq) |
| 249 |
|
| 250 |
def replace_bases(self, old, new): |
| 251 |
'''Replaces all occurrences of 'old' with 'new' ''' |
| 252 |
self.seq = self.seq.replace(old, new) |
| 253 |
|
| 254 |
|
| 255 |
def replace_non_acgt(self): |
| 256 |
'''Replace all non acgt characters with an N (case insensitive)''' |
| 257 |
self.seq = re.sub(r'''[^acgtACGTnN]''', 'N', self.seq) |
| 258 |
|
| 259 |
|
| 260 |
def replace_interval(self, start, end, new): |
| 261 |
'''Replaces the sequence from start to end with the sequence "new"''' |
| 262 |
if start > end or start > len(self) - 1 or end > len(self) - 1: |
| 263 |
raise Error('Error replacing bases ' + str(start) + '-' + str(end) + ' in sequence ' + self.id) |
| 264 |
|
| 265 |
self.seq = self.seq[0:start] + new + self.seq[end + 1:] |
| 266 |
|
| 267 |
def gaps(self, min_length = 1): |
| 268 |
'''Finds the positions of all gaps in the sequence that are at least min_length long. Returns a list of Intervals. Coords are zero-based''' |
| 269 |
gaps = [] |
| 270 |
regex = re.compile('N+', re.IGNORECASE) |
| 271 |
for m in regex.finditer(self.seq): |
| 272 |
if m.span()[1] - m.span()[0] + 1 >= min_length: |
| 273 |
gaps.append(intervals.Interval(m.span()[0], m.span()[1] - 1)) |
| 274 |
return gaps |
| 275 |
|
| 276 |
def contig_coords(self): |
| 277 |
'''Finds coords of contigs, i.e. everything that's not a gap (N or n). Returns a list of Intervals. Coords are zero-based''' |
| 278 |
# contigs are the opposite of gaps, so work out the coords from the gap coords |
| 279 |
gaps = self.gaps() |
| 280 |
|
| 281 |
if len(gaps) == 0: |
| 282 |
return [intervals.Interval(0, len(self) - 1)] |
| 283 |
|
| 284 |
coords = [0] |
| 285 |
for g in gaps: |
| 286 |
if g.start == 0: |
| 287 |
coords = [g.end + 1] |
| 288 |
else: |
| 289 |
coords += [g.start - 1, g.end + 1] |
| 290 |
|
| 291 |
if coords[-1] < len(self): |
| 292 |
coords.append(len(self) - 1) |
| 293 |
|
| 294 |
return [intervals.Interval(coords[i], coords[i+1]) for i in range(0, len(coords)-1,2)] |
| 295 |
|
| 296 |
|
| 297 |
def orfs(self, frame=0, revcomp=False): |
| 298 |
'''Returns a list of ORFs that the sequence has, starting on the given |
| 299 |
frame. Each returned ORF is an interval.Interval object. |
| 300 |
If revomp=True, then finds the ORFs of the reverse complement |
| 301 |
of the sequence.''' |
| 302 |
assert frame in [0,1,2] |
| 303 |
if revcomp: |
| 304 |
self.revcomp() |
| 305 |
|
| 306 |
aa_seq = self.translate(frame=frame).seq.rstrip('X') |
| 307 |
if revcomp: |
| 308 |
self.revcomp() |
| 309 |
|
| 310 |
orfs = _orfs_from_aa_seq(aa_seq) |
| 311 |
for i in range(len(orfs)): |
| 312 |
if revcomp: |
| 313 |
start = len(self) - (orfs[i].end * 3 + 3) - frame |
| 314 |
end = len(self) - (orfs[i].start * 3) - 1 - frame |
| 315 |
else: |
| 316 |
start = orfs[i].start * 3 + frame |
| 317 |
end = orfs[i].end * 3 + 2 + frame |
| 318 |
|
| 319 |
orfs[i] = intervals.Interval(start, end) |
| 320 |
|
| 321 |
return orfs |
| 322 |
|
| 323 |
|
| 324 |
def all_orfs(self, min_length=300): |
| 325 |
'''Finds all open reading frames in the sequence, that are at least as |
| 326 |
long as min_length. Includes ORFs on the reverse strand. |
| 327 |
Returns a list of ORFs, where each element is a tuple: |
| 328 |
(interval.Interval, bool) |
| 329 |
where bool=True means on the reverse strand''' |
| 330 |
orfs = [] |
| 331 |
for frame in [0,1,2]: |
| 332 |
for revcomp in [False, True]: |
| 333 |
orfs.extend([(t, revcomp) for t in self.orfs(frame=frame, revcomp=revcomp) if len(t)>=min_length]) |
| 334 |
|
| 335 |
return sorted(orfs, key=lambda t:t[0]) |
| 336 |
|
| 337 |
|
| 338 |
def is_complete_orf(self): |
| 339 |
'''Returns true iff length is >= 6, is a multiple of 3, and there is exactly one stop codon in the sequence and it is at the end''' |
| 340 |
if len(self) %3 != 0 or len(self) < 6: |
| 341 |
return False |
| 342 |
|
| 343 |
orfs = self.orfs() |
| 344 |
complete_orf = intervals.Interval(0, len(self) - 1) |
| 345 |
for orf in orfs: |
| 346 |
if orf == complete_orf: |
| 347 |
return True |
| 348 |
return False |
| 349 |
|
| 350 |
|
| 351 |
def looks_like_gene(self): |
| 352 |
'''Returns true iff: length >=6, length is a multiple of 3, first codon is start, last codon is a stop and has no other stop codons''' |
| 353 |
return self.is_complete_orf() \ |
| 354 |
and len(self) >= 6 \ |
| 355 |
and len(self) %3 == 0 \ |
| 356 |
and self.seq[0:3].upper() in genetic_codes.starts[genetic_code] |
| 357 |
|
| 358 |
|
| 359 |
def make_into_gene(self): |
| 360 |
'''Tries to make into a gene sequence. Tries all three reading frames and both strands. Returns a tuple (new sequence, strand, frame) if it was successful. Otherwise returns None.''' |
| 361 |
for reverse in [True, False]: |
| 362 |
for frame in range(3): |
| 363 |
new_seq = copy.copy(self) |
| 364 |
if reverse: |
| 365 |
new_seq.revcomp() |
| 366 |
new_seq.seq = new_seq[frame:] |
| 367 |
if len(new_seq) % 3: |
| 368 |
new_seq.seq = new_seq.seq[:-(len(new_seq) % 3)] |
| 369 |
|
| 370 |
new_aa_seq = new_seq.translate() |
| 371 |
if len(new_aa_seq) >= 2 and new_seq[0:3] in genetic_codes.starts[genetic_code] and new_aa_seq[-1] == '*' and '*' not in new_aa_seq[:-1]: |
| 372 |
strand = '-' if reverse else '+' |
| 373 |
return new_seq, strand, frame |
| 374 |
|
| 375 |
return None |
| 376 |
|
| 377 |
|
| 378 |
# Fills the object with the next sequence in the file. Returns |
| 379 |
# True if this was successful, False if no more sequences in the file. |
| 380 |
# If reading a file of quality scores, set read_quals = True |
| 381 |
def get_next_from_file(self, f, read_quals=False): |
| 382 |
if f in previous_lines: |
| 383 |
if previous_lines[f] == None: |
| 384 |
self.id = self.seq = None |
| 385 |
return False |
| 386 |
else: |
| 387 |
self.id = self._get_id_from_header_line(previous_lines[f]) |
| 388 |
else: |
| 389 |
line = '\n' |
| 390 |
while line == '\n': |
| 391 |
line = f.readline() |
| 392 |
self.id = self._get_id_from_header_line(line) |
| 393 |
|
| 394 |
self.seq = '' |
| 395 |
seq_lines = [] # much faster to store the seq lines in an array, |
| 396 |
# then join at the end |
| 397 |
|
| 398 |
while 1: |
| 399 |
line = f.readline() |
| 400 |
|
| 401 |
if line.startswith('>'): |
| 402 |
previous_lines[f] = line.rstrip() |
| 403 |
break |
| 404 |
elif line == '': |
| 405 |
previous_lines[f] = None |
| 406 |
break |
| 407 |
else: |
| 408 |
seq_lines.append(line.rstrip()) |
| 409 |
|
| 410 |
if read_quals: |
| 411 |
self.seq = ' '.join(seq_lines) |
| 412 |
else: |
| 413 |
self.seq = ''.join(seq_lines) |
| 414 |
return True |
| 415 |
|
| 416 |
def __str__(self): |
| 417 |
if Fasta.line_length == 0: |
| 418 |
return '>' + self.id + '\n' + self.seq |
| 419 |
else: |
| 420 |
return '>' + self.id + '\n' + '\n'.join(self.seq[i:i+Fasta.line_length] for i in range(0, len(self), Fasta.line_length)) |
| 421 |
|
| 422 |
def __getitem__(self, index): |
| 423 |
return self.seq[index] |
| 424 |
|
| 425 |
def trim(self, start, end): |
| 426 |
'''Removes first 'start'/'end' bases off the start/end of the sequence''' |
| 427 |
self.seq = self.seq[start:len(self.seq) - end] |
| 428 |
|
| 429 |
# qual_scores should be a list of quality scores |
| 430 |
def to_Fastq(self, qual_scores): |
| 431 |
'''Returns a Fastq object. qual_scores expected to be a list of numbers, like you would get in a .qual file''' |
| 432 |
if len(self) != len(qual_scores): |
| 433 |
raise Error('Error making Fastq from Fasta, lengths differ.', self.id) |
| 434 |
return Fastq(self.id, self.seq, ''.join([chr(max(0, min(x, 93)) + 33) for x in qual_scores])) |
| 435 |
|
| 436 |
def search(self, search_string): |
| 437 |
'''Finds every occurrence (including overlapping ones) of the search_string, including on the reverse strand. Returns a list where each element is a tuple (position, strand) where strand is in ['-', '+']. Positions are zero-based''' |
| 438 |
seq = self.seq.upper() |
| 439 |
search_string = search_string.upper() |
| 440 |
pos = 0 |
| 441 |
found = seq.find(search_string, pos) |
| 442 |
hits = [] |
| 443 |
|
| 444 |
while found != -1: |
| 445 |
hits.append((found, '+')) |
| 446 |
pos = found + 1 |
| 447 |
found = seq.find(search_string, pos) |
| 448 |
|
| 449 |
|
| 450 |
pos = 0 |
| 451 |
search_string = Fasta('x', search_string) |
| 452 |
search_string.revcomp() |
| 453 |
search_string = search_string.seq |
| 454 |
found = seq.find(search_string, pos) |
| 455 |
|
| 456 |
while found != -1: |
| 457 |
hits.append((found, '-')) |
| 458 |
pos = found + 1 |
| 459 |
found = seq.find(search_string, pos) |
| 460 |
|
| 461 |
return hits |
| 462 |
|
| 463 |
def translate(self, frame=0): |
| 464 |
'''Returns a Fasta sequence, translated into amino acids. Starts translating from 'frame', where frame expected to be 0,1 or 2''' |
| 465 |
return Fasta(self.id, ''.join([genetic_codes.codes[genetic_code].get(self.seq[x:x+3].upper(), 'X') for x in range(frame, len(self)-1-frame, 3)])) |
| 466 |
|
| 467 |
def gc_content(self, as_decimal=True): |
| 468 |
"""Returns the GC content for the sequence. |
| 469 |
Notes: |
| 470 |
This method ignores N when calculating the length of the sequence. |
| 471 |
It does not, however ignore other ambiguous bases. It also only |
| 472 |
includes the ambiguous base S (G or C). In this sense the method is |
| 473 |
conservative with its calculation. |
| 474 |
|
| 475 |
Args: |
| 476 |
as_decimal (bool): Return the result as a decimal. Setting to False |
| 477 |
will return as a percentage. i.e for the sequence GCAT it will |
| 478 |
return 0.5 by default and 50.00 if set to False. |
| 479 |
|
| 480 |
Returns: |
| 481 |
float: GC content calculated as the number of G, C, and S divided |
| 482 |
by the number of (non-N) bases (length). |
| 483 |
|
| 484 |
""" |
| 485 |
gc_total = 0.0 |
| 486 |
num_bases = 0.0 |
| 487 |
n_tuple = tuple('nN') |
| 488 |
accepted_bases = tuple('cCgGsS') |
| 489 |
|
| 490 |
# counter sums all unique characters in sequence. Case insensitive. |
| 491 |
for base, count in Counter(self.seq).items(): |
| 492 |
|
| 493 |
# dont count N in the number of bases |
| 494 |
if base not in n_tuple: |
| 495 |
num_bases += count |
| 496 |
|
| 497 |
if base in accepted_bases: # S is a G or C |
| 498 |
gc_total += count |
| 499 |
|
| 500 |
gc_content = gc_total / num_bases |
| 501 |
|
| 502 |
if not as_decimal: # return as percentage |
| 503 |
gc_content *= 100 |
| 504 |
|
| 505 |
return gc_content |
| 506 |
|
| 507 |
|
| 508 |
|
| 509 |
class Embl(Fasta): |
| 510 |
'''Exactly the same as Fasta, but reading seqs from a file works differently''' |
| 511 |
def __eq__(self, other): |
| 512 |
return type(other) in [Fasta, Embl] and type(self) in [Fasta, Embl] and self.__dict__ == other.__dict__ |
| 513 |
|
| 514 |
def _get_id_from_header_line(self, line): |
| 515 |
if line.startswith('ID ') and line[5] != ' ': |
| 516 |
return line.split()[1].rstrip(';') |
| 517 |
elif line.startswith('LOCUS'): |
| 518 |
return line.split()[1] |
| 519 |
else: |
| 520 |
raise Error('Error! expected line starting with "ID" or "LOCUS", but got this:\n', line) |
| 521 |
|
| 522 |
def get_next_from_file(self, f, read_quals=False): |
| 523 |
if f in previous_lines: |
| 524 |
line = '' |
| 525 |
if previous_lines[f] == None: |
| 526 |
self.id = self.seq = None |
| 527 |
return False |
| 528 |
else: |
| 529 |
self.id = self._get_id_from_header_line(previous_lines[f]) |
| 530 |
else: |
| 531 |
line = '\n' |
| 532 |
while line == '\n': |
| 533 |
line = f.readline() |
| 534 |
self.id = self._get_id_from_header_line(line) |
| 535 |
|
| 536 |
self.seq = '' |
| 537 |
seq_lines = [] |
| 538 |
|
| 539 |
while not (line.startswith('SQ') or line.rstrip() == 'ORIGIN'): |
| 540 |
line = f.readline() |
| 541 |
if line == '': |
| 542 |
raise Error('Error! No SQ or ORIGIN line found for sequence ' + self.id) |
| 543 |
|
| 544 |
line = f.readline() |
| 545 |
|
| 546 |
while not line.startswith('//'): |
| 547 |
if line == '' or line[0] != ' ': |
| 548 |
raise Error('Error! Did not find end of sequence ' + self.id) |
| 549 |
seq_lines.append(''.join(line.rstrip().strip(' 0123456789').split())) |
| 550 |
line = f.readline() |
| 551 |
|
| 552 |
|
| 553 |
while 1: |
| 554 |
if line.startswith('ID') or line.startswith('LOCUS'): |
| 555 |
previous_lines[f] = line.rstrip() |
| 556 |
break |
| 557 |
elif line == '': |
| 558 |
previous_lines[f] = None |
| 559 |
break |
| 560 |
|
| 561 |
line = f.readline() |
| 562 |
|
| 563 |
self.seq = ''.join(seq_lines) |
| 564 |
return True |
| 565 |
|
| 566 |
class Fastq(Fasta): |
| 567 |
'''Class to store and manipulate FASTQ sequences. They have three things: a name, sequence and string of quality scores''' |
| 568 |
def __init__(self, id_in=None, seq_in=None, qual_in=None): |
| 569 |
super().__init__(id_in, seq_in) |
| 570 |
self.qual = qual_in |
| 571 |
if (not self.seq == self.qual == None) and len(self.qual) != len(self.seq): |
| 572 |
raise Error('Error constructing Fastq. Mismatch in sequence and quality length\n' + str(self)) |
| 573 |
|
| 574 |
def __str__(self): |
| 575 |
return '@' + self.id + '\n' + self.seq + '\n+\n' + self.qual |
| 576 |
|
| 577 |
def __eq__(self, other): |
| 578 |
return type(other) is type(self) and self.__dict__ == other.__dict__ |
| 579 |
|
| 580 |
def subseq(self, start, end): |
| 581 |
'''Returns Fastq object with the same name, of the bases from start to end, but not including end''' |
| 582 |
return Fastq(self.id, self.seq[start:end], self.qual[start:end]) |
| 583 |
|
| 584 |
def get_next_from_file(self, f, read_quals=False): |
| 585 |
if f in previous_lines: |
| 586 |
line = previous_lines[f] |
| 587 |
del previous_lines[f] |
| 588 |
else: |
| 589 |
line = f.readline() |
| 590 |
|
| 591 |
while line == '\n': |
| 592 |
line = f.readline() |
| 593 |
|
| 594 |
if not line: |
| 595 |
self = Fastq('', '', '') |
| 596 |
return False |
| 597 |
|
| 598 |
if not line.startswith('@'): |
| 599 |
raise Error('Error getting next sequence from fastq file. Got line:\n' + line) |
| 600 |
|
| 601 |
self.id = line.rstrip()[1:] |
| 602 |
line = f.readline() |
| 603 |
if not line: |
| 604 |
raise Error('Error getting next sequence from fastq file, sequence has ID ' + self.id) |
| 605 |
|
| 606 |
self.seq = line.strip() |
| 607 |
|
| 608 |
line = f.readline() |
| 609 |
if not (line and line.startswith('+')): |
| 610 |
raise Error('Error getting next sequence from fastq file, no line starting with +, sequence has ID ' + self.id) |
| 611 |
|
| 612 |
line = f.readline() |
| 613 |
if not line: |
| 614 |
raise Error('Error getting next sequence from fastq file, sequence has ID ' + self.id) |
| 615 |
|
| 616 |
self.qual = line.rstrip() |
| 617 |
return True |
| 618 |
|
| 619 |
def revcomp(self): |
| 620 |
'''Reverse complements the sequence''' |
| 621 |
super().revcomp() |
| 622 |
self.qual = self.qual[::-1] |
| 623 |
|
| 624 |
def trim(self, start, end): |
| 625 |
'''Removes first 'start'/'end' bases off the start/end of the sequence''' |
| 626 |
super().trim(start, end) |
| 627 |
self.qual = self.qual[start:len(self.qual) - end] |
| 628 |
|
| 629 |
def to_Fasta_and_qual(self): |
| 630 |
quals = [ord(x) - 33 for x in self.qual] |
| 631 |
return (Fasta(self.id, self.seq), quals) |
| 632 |
|
| 633 |
def expand_nucleotides(self): |
| 634 |
return [Fastq(x.id, x.seq, self.qual) for x in super().expand_nucleotides()] |
| 635 |
|
| 636 |
def trim_Ns(self): |
| 637 |
'''Removes any leading or trailing N or n characters from the sequence''' |
| 638 |
# get index of first base that is not an N |
| 639 |
i = 0 |
| 640 |
while i < len(self) and self.seq[i] in 'nN': |
| 641 |
i += 1 |
| 642 |
|
| 643 |
# strip off start of sequence and quality |
| 644 |
self.seq = self.seq[i:] |
| 645 |
self.qual = self.qual[i:] |
| 646 |
|
| 647 |
# strip the ends |
| 648 |
self.seq = self.seq.rstrip('Nn') |
| 649 |
self.qual = self.qual[:len(self.seq)] |
| 650 |
|
| 651 |
def replace_interval(self, start, end, new, qual_string): |
| 652 |
'''Replaces the sequence from start to end with the sequence "new"''' |
| 653 |
if len(new) != len(qual_string): |
| 654 |
raise Error('Length of new seq and qual string in replace_interval() must be equal. Cannot continue') |
| 655 |
super().replace_interval(start, end, new) |
| 656 |
self.qual = self.qual[0:start] + qual_string + self.qual[end + 1:] |
| 657 |
|
| 658 |
def translate(self): |
| 659 |
'''Returns a Fasta sequence, translated into amino acids. Starts translating from 'frame', where frame expected to be 0,1 or 2''' |
| 660 |
fa = super().translate() |
| 661 |
return Fastq(fa.id, fa.seq, 'I'*len(fa.seq)) |
| 662 |
|
| 663 |
def make_into_gene(self): |
| 664 |
got = super().make_into_gene() |
| 665 |
if got is None: |
| 666 |
return None |
| 667 |
seq, strand, frame = got |
| 668 |
new_seq = copy.copy(self) |
| 669 |
|
| 670 |
if strand == '-': |
| 671 |
new_seq.revcomp() |
| 672 |
|
| 673 |
new_seq.seq = new_seq.seq[frame:frame + len(seq)] |
| 674 |
new_seq.qual = new_seq.qual[frame:frame + len(seq)] |
| 675 |
return new_seq, strand, frame |
| 676 |
|
| 677 |
|
| 678 |
def _orfs_from_aa_seq(seq): |
| 679 |
orfs = [] |
| 680 |
pos = 0 |
| 681 |
while pos < len(seq): |
| 682 |
next_stop = seq.find('*', pos) |
| 683 |
if next_stop == -1: |
| 684 |
orfs.append(intervals.Interval(pos, len(seq)-1)) |
| 685 |
break |
| 686 |
elif next_stop > pos: |
| 687 |
orfs.append(intervals.Interval(pos, next_stop)) |
| 688 |
pos = next_stop + 1 |
| 689 |
return orfs |