1 # Copyright (C) 2007-2012 Martin A. Hansen.
3 # This program is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU General Public License
5 # as published by the Free Software Foundation; either version 2
6 # of the License, or (at your option) any later version.
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
13 # You should have received a copy of the GNU General Public License
14 # along with this program; if not, write to the Free Software
15 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 # http://www.gnu.org/copyleft/gpl.html
19 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
21 # This software is part of the Biopieces framework (www.biopieces.org).
23 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
26 require 'maasha/seq/backtrack'
27 require 'maasha/seq/digest'
28 #require 'maasha/seq/patscan'
29 require 'maasha/seq/patternmatcher'
30 require 'maasha/seq/trim'
36 PROTEIN = %w[f l s y c w p h q r i m t n k v a d e g]
39 # Translation table 11
40 # (http://www.ncbi.nlm.nih.gov/Taxonomy/taxonomyhome.html/index.cgi?chapter=cgencodes#SG11)
41 # AAs = FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG
42 # Starts = ---M---------------M------------MMMM---------------M------------
43 # Base1 = TTTTTTTTTTTTTTTTCCCCCCCCCCCCCCCCAAAAAAAAAAAAAAAAGGGGGGGGGGGGGGGG
44 # Base2 = TTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGG
45 # Base3 = TCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAG
47 "TTG" => "M", "CTG" => "M", "ATT" => "M", "ATC" => "M",
48 "ATA" => "M", "ATG" => "M", "GTG" => "M"
52 "TTT" => "F", "TCT" => "S", "TAT" => "Y", "TGT" => "C",
53 "TTC" => "F", "TCC" => "S", "TAC" => "Y", "TGC" => "C",
54 "TTA" => "L", "TCA" => "S", "TAA" => "*", "TGA" => "*",
55 "TTG" => "L", "TCG" => "S", "TAG" => "*", "TGG" => "W",
56 "CTT" => "L", "CCT" => "P", "CAT" => "H", "CGT" => "R",
57 "CTC" => "L", "CCC" => "P", "CAC" => "H", "CGC" => "R",
58 "CTA" => "L", "CCA" => "P", "CAA" => "Q", "CGA" => "R",
59 "CTG" => "L", "CCG" => "P", "CAG" => "Q", "CGG" => "R",
60 "ATT" => "I", "ACT" => "T", "AAT" => "N", "AGT" => "S",
61 "ATC" => "I", "ACC" => "T", "AAC" => "N", "AGC" => "S",
62 "ATA" => "I", "ACA" => "T", "AAA" => "K", "AGA" => "R",
63 "ATG" => "M", "ACG" => "T", "AAG" => "K", "AGG" => "R",
64 "GTT" => "V", "GCT" => "A", "GAT" => "D", "GGT" => "G",
65 "GTC" => "V", "GCC" => "A", "GAC" => "D", "GGC" => "G",
66 "GTA" => "V", "GCA" => "A", "GAA" => "E", "GGA" => "G",
67 "GTG" => "V", "GCG" => "A", "GAG" => "E", "GGG" => "G"
70 # Quality scores bases
75 # Error class for all exceptions to do with Seq.
76 class SeqError < StandardError; end
80 include PatternMatcher
85 attr_accessor :seq_name, :seq, :type, :qual
87 # Class method to instantiate a new Sequence object given
89 def self.new_bp(record)
90 seq_name = record[:SEQ_NAME]
92 type = record[:SEQ_TYPE]
93 qual = record[:SCORES]
95 self.new(seq_name, seq, type, qual)
98 # Class method that generates all possible oligos of a specifed length and type.
99 def self.generate_oligos(length, type)
100 raise SeqError, "Cannot generate negative oligo length: #{length}" if length <= 0
103 when /dna/ then alph = DNA
104 when /rna/ then alph = RNA
105 when /protein/ then alph = PROTEIN
107 raise SeqError, "Unknown sequence type: #{type}"
112 (1 .. length).each do
115 oligos.each do |oligo|
127 # Initialize a sequence object with the following arguments:
128 # - seq_name: Name of the sequence.
129 # - seq: The sequence.
130 # - type: The sequence type - DNA, RNA, or protein
131 # - qual: An Illumina type quality scores string.
132 def initialize(seq_name = nil, seq = nil, type = nil, qual = nil)
139 # Method that guesses and returns the sequence type
140 # by inspecting the first 100 residues.
142 raise SeqError, "Guess failed: sequence is nil" if self.seq.nil?
144 case self.seq[0 ... 100].downcase
145 when /[flpqie]/ then return "protein"
146 when /[u]/ then return "rna"
151 # Method that guesses and sets the sequence type
152 # by inspecting the first 100 residues.
154 self.type = self.type_guess
157 # Returns the length of a sequence.
159 self.seq.nil? ? 0 : self.seq.length
164 # Return the number indels in a sequence.
166 regex = Regexp.new(/[#{Regexp.escape(INDELS.join(""))}]/)
167 self.seq.scan(regex).size
170 # Method to remove indels from seq and qual if qual.
173 self.seq.delete!(Regexp.escape(INDELS.join('')))
175 na_seq = NArray.to_na(self.seq, "byte")
176 na_qual = NArray.to_na(self.qual, "byte")
177 mask = NArray.byte(self.length)
180 mask += na_seq.eq(c.ord)
185 self.seq = na_seq[mask].to_s
186 self.qual = na_qual[mask].to_s
192 # Method that returns true is a given sequence type is DNA.
197 # Method that returns true is a given sequence type is RNA.
202 # Method that returns true is a given sequence type is protein.
204 self.type == 'protein'
207 # Method to transcribe DNA to RNA.
209 raise SeqError, "Cannot transcribe 0 length sequence" if self.length == 0
210 raise SeqError, "Cannot transcribe sequence type: #{self.type}" unless self.is_dna?
212 self.seq.tr!('Tt','Uu')
215 # Method to reverse-transcribe RNA to DNA.
217 raise SeqError, "Cannot reverse-transcribe 0 length sequence" if self.length == 0
218 raise SeqError, "Cannot reverse-transcribe sequence type: #{self.type}" unless self.is_rna?
221 self.seq.tr!('Uu','Tt')
224 # Method to translate a DNA sequence to protein.
225 def translate!(trans_tab = 11)
226 raise SeqError, "Sequence type must be 'dna' - not #{self.type}" unless self.type == 'dna'
227 raise SeqError, "Sequence length must be a multiplum of 3 - was: #{self.length}" unless (self.length % 3) == 0
231 codon_start_hash = TRANS_TAB11_START
232 codon_hash = TRANS_TAB11
234 raise SeqError, "Unknown translation table: #{trans_tab}"
237 codon = self.seq[0 ... 3].upcase
239 aa = codon_start_hash[codon]
241 raise SeqError, "Unknown start codon: #{codon}" if aa.nil?
247 while i < self.length
248 codon = self.seq[i ... i + 3].upcase
250 aa = codon_hash[codon]
252 raise SeqError, "Unknown codon: #{codon}" if aa.nil?
261 self.type = "protein"
266 alias :to_protein! :translate!
268 def translate(trans_tab = 11)
269 self.dup.translate!(trans_tab)
272 alias :to_protein :translate
274 # Method that given a Seq entry returns a Biopieces record (a hash).
276 raise SeqError, "Missing seq_name" if self.seq_name.nil?
277 raise SeqError, "Missing seq" if self.seq.nil?
280 record[:SEQ_NAME] = self.seq_name
281 record[:SEQ] = self.seq
282 record[:SEQ_LEN] = self.length
283 record[:SCORES] = self.qual if self.qual
287 # Method that given a Seq entry returns a FASTA entry (a string).
288 def to_fasta(wrap = nil)
289 raise SeqError, "Missing seq_name" if self.seq_name.nil? or self.seq_name == ''
290 raise SeqError, "Missing seq" if self.seq.nil? or self.seq.empty?
292 seq_name = self.seq_name.to_s
296 seq.gsub!(/(.{#{wrap}})/) do |match|
303 ">" + seq_name + $/ + seq + $/
306 # Method that given a Seq entry returns a FASTQ entry (a string).
308 raise SeqError, "Missing seq_name" if self.seq_name.nil?
309 raise SeqError, "Missing seq" if self.seq.nil?
310 raise SeqError, "Missing qual" if self.qual.nil?
312 seq_name = self.seq_name.to_s
314 qual = self.qual.to_s
316 "@" + seq_name + $/ + seq + $/ + "+" + $/ + qual + $/
319 # Method that generates a unique key for a
320 # DNA sequence and return this key as a Fixnum.
324 self.seq.upcase.each_char do |char|
328 when 'A' then key |= 0
329 when 'C' then key |= 1
330 when 'G' then key |= 2
331 when 'T' then key |= 3
332 else raise SeqError, "Bad residue: #{char}"
339 # Method to reverse complement sequence.
340 def reverse_complement
346 alias :revcomp :reverse_complement
348 # Method to reverse the sequence.
351 self.qual.reverse! if self.qual
355 # Method that complements sequence including ambiguity codes.
357 raise SeqError, "Cannot complement 0 length sequence" if self.length == 0
360 self.seq.tr!('AGCUTRYWSMKHDVBNagcutrywsmkhdvbn', 'TCGAAYRWSKMDHBVNtcgaayrwskmdhbvn')
362 self.seq.tr!('AGCUTRYWSMKHDVBNagcutrywsmkhdvbn', 'UCGAAYRWSKMDHBVNucgaayrwskmdhbvn')
364 raise SeqError, "Cannot complement sequence type: #{self.type}"
368 # Method to determine the Hamming Distance between
369 # two Sequence objects (case insensitive).
370 def hamming_distance(seq)
371 self.seq.upcase.hamming_distance(seq.seq.upcase)
374 # Method that generates a random sequence of a given length and type.
375 def generate(length, type)
376 raise SeqError, "Cannot generate sequence length < 1: #{length}" if length <= 0
386 raise SeqError, "Unknown sequence type: #{type}"
389 seq_new = Array.new(length) { alph[rand(alph.size)] }.join("")
391 self.type = type.downcase
395 # Method to shuffle a sequence readomly inline.
397 self.seq = self.seq.split('').shuffle!.join
401 # Method that returns a subsequence of from a given start position
402 # and of a given length.
403 def subseq(start, length = self.length - start)
404 raise SeqError, "subsequence start: #{start} < 0" if start < 0
405 raise SeqError, "subsequence length: #{length} < 0" if length < 0
406 raise SeqError, "subsequence start + length > Seq.length: #{start} + #{length} > #{self.length}" if start + length > self.length
410 qual = "" unless self.qual.nil?
412 stop = start + length - 1
414 seq = self.seq[start .. stop]
415 qual = self.qual[start .. stop] unless self.qual.nil?
418 Seq.new(self.seq_name.dup, seq, self.type, qual)
421 # Method that replaces a sequence with a subsequence from a given start position
422 # and of a given length.
423 def subseq!(start, length = self.length - start)
424 raise SeqError, "subsequence start: #{start} < 0" if start < 0
425 raise SeqError, "subsequence length: #{length} < 0" if length < 0
426 raise SeqError, "subsequence start + length > Seq.length: #{start} + #{length} > #{self.length}" if start + length > self.length
430 self.qual = "" unless self.qual.nil?
432 stop = start + length - 1
434 self.seq = self.seq[start .. stop]
435 self.qual = self.qual[start .. stop] unless self.qual.nil?
441 # Method that returns a subsequence of a given length
442 # beginning at a random position.
443 def subseq_rand(length)
444 if self.length - length + 1 == 0
447 start = rand(self.length - length + 1)
450 self.subseq(start, length)
453 # Method that returns the residue compositions of a sequence in
454 # a hash where the key is the residue and the value is the residue
459 self.seq.upcase.each_char do |char|
466 # Method that returns the length of the longest homopolymeric stretch
467 # found in a sequence.
468 def homopol_max(min = 1)
469 return 0 if self.seq.nil? or self.seq.empty?
473 self.seq.upcase.scan(/A{#{min},}|T{#{min},}|G{#{min},}|C{#{min},}|N{#{min},}/) do |match|
475 min = match.size > min ? match.size : min
478 return 0 unless found
483 # Method that returns the percentage of hard masked residues
484 # or N's in a sequence.
486 ((self.seq.upcase.scan("N").size.to_f / (self.len - self.indels).to_f) * 100).round(2)
489 # Method that returns the percentage of soft masked residues
490 # or lower cased residues in a sequence.
492 ((self.seq.scan(/[a-z]/).size.to_f / (self.len - self.indels).to_f) * 100).round(2)
495 # Hard masks sequence residues where the corresponding quality score
496 # is below a given cutoff.
497 def mask_seq_hard_old(cutoff)
498 seq = self.seq.upcase
502 scores.each_char do |score|
503 seq[i] = 'N' if score.ord - SCORE_BASE < cutoff
510 # Hard masks sequence residues where the corresponding quality score
511 # is below a given cutoff.
512 def mask_seq_hard!(cutoff)
513 raise SeqError, "seq is nil" if self.seq.nil?
514 raise SeqError, "qual is nil" if self.qual.nil?
515 raise SeqError, "cufoff value: #{cutoff} out of range #{SCORE_MIN} .. #{SCORE_MAX}" unless (SCORE_MIN .. SCORE_MAX).include? cutoff
517 na_seq = NArray.to_na(self.seq, "byte")
518 na_qual = NArray.to_na(self.qual, "byte")
519 mask = (na_qual - SCORE_BASE) < cutoff
520 mask *= na_seq.ne("-".ord)
522 na_seq[mask] = 'N'.ord
524 self.seq = na_seq.to_s
529 # Soft masks sequence residues where the corresponding quality score
530 # is below a given cutoff.
531 def mask_seq_soft!(cutoff)
532 raise SeqError, "seq is nil" if self.seq.nil?
533 raise SeqError, "qual is nil" if self.qual.nil?
534 raise SeqError, "cufoff value: #{cutoff} out of range #{SCORE_MIN} .. #{SCORE_MAX}" unless (SCORE_MIN .. SCORE_MAX).include? cutoff
536 na_seq = NArray.to_na(self.seq, "byte")
537 na_qual = NArray.to_na(self.qual, "byte")
538 mask = (na_qual - SCORE_BASE) < cutoff
539 mask *= na_seq.ne("-".ord)
541 na_seq[mask] ^= ' '.ord
543 self.seq = na_seq.to_s
548 # Method to convert quality scores inbetween formats.
549 # Sanger base 33, range 0-40
550 # Solexa base 64, range -5-40
551 # Illumina13 base 64, range 0-40
552 # Illumina15 base 64, range 3-40
553 # Illumina18 base 33, range 0-41
554 def convert_scores!(from, to)
556 na_qual = NArray.to_na(self.qual, "byte")
559 when "sanger" then na_qual -= 33
560 when "solexa" then na_qual -= 64
561 when "illumina13" then na_qual -= 64
562 when "illumina15" then na_qual -= 64
563 when "illumina18" then na_qual -= 33
564 else raise SeqError, "unknown quality score encoding: #{from}"
568 when "sanger" then na_qual += 33
569 when "solexa" then na_qual += 64
570 when "illumina13" then na_qual += 64
571 when "illumina15" then na_qual += 64
572 when "illumina18" then na_qual += 33
573 else raise SeqError, "unknown quality score encoding: #{from}"
576 self.qual = na_qual.to_s
582 # Method to calculate and return the mean quality score.
584 raise SeqError, "Missing qual in entry" if self.qual.nil?
586 na_qual = NArray.to_na(self.qual, "byte")
587 na_qual -= SCORE_BASE
591 # Method to find open reading frames (ORFs).
592 def each_orf(size_min, size_max, start_codons, stop_codons, pick_longest = false)
596 regex_start = Regexp.new(start_codons.join('|'), true)
597 regex_stop = Regexp.new(stop_codons.join('|'), true)
599 while pos_beg and pos_beg < self.length - size_min
600 if pos_beg = self.seq.index(regex_start, pos_beg)
601 if pos_end = self.seq.index(regex_stop, pos_beg)
602 length = (pos_end - pos_beg) + 3
605 if size_min <= length and length <= size_max
606 subseq = self.subseq(pos_beg, length)
608 orfs << [subseq, pos_beg, pos_end + 3]
620 orfs.each { |orf| orf_hash[orf.last] = orf unless orf_hash[orf.last] }
622 orfs = orf_hash.values
626 orfs.each { |orf| yield orf }