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/digest'
27 require 'maasha/seq/trim'
30 autoload :BackTrack, 'maasha/seq/backtrack.rb'
31 autoload :Dynamic, 'maasha/seq/dynamic.rb'
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"
71 # Error class for all exceptions to do with Seq.
72 class SeqError < StandardError; end
75 # Quality scores bases
83 attr_accessor :seq_name, :seq, :type, :qual
85 # Class method to instantiate a new Sequence object given
87 def self.new_bp(record)
88 seq_name = record[:SEQ_NAME]
90 type = record[:SEQ_TYPE].to_sym if record[:SEQ_TYPE]
91 qual = record[:SCORES]
93 self.new(seq_name, seq, type, qual)
96 # Class method that generates all possible oligos of a specifed length and type.
97 def self.generate_oligos(length, type)
98 raise SeqError, "Cannot generate negative oligo length: #{length}" if length <= 0
101 when :dna then alph = DNA
102 when :rna then alph = RNA
103 when :protein then alph = PROTEIN
105 raise SeqError, "Unknown sequence type: #{type}"
110 (1 .. length).each do
113 oligos.each do |oligo|
125 # Initialize a sequence object with the following arguments:
126 # - seq_name: Name of the sequence.
127 # - seq: The sequence.
128 # - type: The sequence type - DNA, RNA, or protein
129 # - qual: An Illumina type quality scores string.
130 def initialize(seq_name = nil, seq = nil, type = nil, qual = nil)
137 # Method that guesses and returns the sequence type
138 # by inspecting the first 100 residues.
140 raise SeqError, "Guess failed: sequence is nil" if self.seq.nil?
142 case self.seq[0 ... 100].downcase
143 when /[flpqie]/ then return :protein
144 when /[u]/ then return :rna
149 # Method that guesses and sets the sequence type
150 # by inspecting the first 100 residues.
152 self.type = self.type_guess
156 # Returns the length of a sequence.
158 self.seq.nil? ? 0 : self.seq.length
163 # Return the number indels in a sequence.
165 regex = Regexp.new(/[#{Regexp.escape(INDELS.join(""))}]/)
166 self.seq.scan(regex).size
169 # Method to remove indels from seq and qual if qual.
172 self.seq.delete!(Regexp.escape(INDELS.join('')))
174 na_seq = NArray.to_na(self.seq, "byte")
175 na_qual = NArray.to_na(self.qual, "byte")
176 mask = NArray.byte(self.length)
179 mask += na_seq.eq(c.ord)
184 self.seq = na_seq[mask].to_s
185 self.qual = na_qual[mask].to_s
191 # Method that returns true is a given sequence type is DNA.
196 # Method that returns true is a given sequence type is RNA.
201 # Method that returns true is a given sequence type is protein.
203 self.type == :protein
206 # Method to transcribe DNA to RNA.
208 raise SeqError, "Cannot transcribe 0 length sequence" if self.length == 0
209 raise SeqError, "Cannot transcribe sequence type: #{self.type}" unless self.is_dna?
211 self.seq.tr!('Tt','Uu')
214 # Method to reverse-transcribe RNA to DNA.
216 raise SeqError, "Cannot reverse-transcribe 0 length sequence" if self.length == 0
217 raise SeqError, "Cannot reverse-transcribe sequence type: #{self.type}" unless self.is_rna?
219 self.seq.tr!('Uu','Tt')
222 # Method to translate a DNA sequence to protein.
223 def translate!(trans_tab = 11)
224 raise SeqError, "Sequence type must be 'dna' - not #{self.type}" unless self.type == :dna
225 raise SeqError, "Sequence length must be a multiplum of 3 - was: #{self.length}" unless (self.length % 3) == 0
229 codon_start_hash = TRANS_TAB11_START
230 codon_hash = TRANS_TAB11
232 raise SeqError, "Unknown translation table: #{trans_tab}"
235 codon = self.seq[0 ... 3].upcase
237 aa = codon_start_hash[codon]
239 raise SeqError, "Unknown start codon: #{codon}" if aa.nil?
245 while i < self.length
246 codon = self.seq[i ... i + 3].upcase
248 aa = codon_hash[codon]
250 raise SeqError, "Unknown codon: #{codon}" if aa.nil?
264 alias :to_protein! :translate!
266 def translate(trans_tab = 11)
267 self.dup.translate!(trans_tab)
270 alias :to_protein :translate
272 # Method that given a Seq entry returns a Biopieces record (a hash).
274 raise SeqError, "Missing seq_name" if self.seq_name.nil?
275 raise SeqError, "Missing seq" if self.seq.nil?
278 record[:SEQ_NAME] = self.seq_name
279 record[:SEQ] = self.seq
280 record[:SEQ_LEN] = self.length
281 record[:SCORES] = self.qual if self.qual
285 # Method that given a Seq entry returns a FASTA entry (a string).
286 def to_fasta(wrap = nil)
287 raise SeqError, "Missing seq_name" if self.seq_name.nil? or self.seq_name == ''
288 raise SeqError, "Missing seq" if self.seq.nil? or self.seq.empty?
290 seq_name = self.seq_name.to_s
294 seq.gsub!(/(.{#{wrap}})/) do |match|
301 ">" + seq_name + $/ + seq + $/
304 # Method that given a Seq entry returns a FASTQ entry (a string).
306 raise SeqError, "Missing seq_name" if self.seq_name.nil?
307 raise SeqError, "Missing seq" if self.seq.nil?
308 raise SeqError, "Missing qual" if self.qual.nil?
310 seq_name = self.seq_name.to_s
312 qual = self.qual.to_s
314 "@" + seq_name + $/ + seq + $/ + "+" + $/ + qual + $/
317 # Method that generates a unique key for a
318 # DNA sequence and return this key as a Fixnum.
322 self.seq.upcase.each_char do |char|
326 when 'A' then key |= 0
327 when 'C' then key |= 1
328 when 'G' then key |= 2
329 when 'T' then key |= 3
330 else raise SeqError, "Bad residue: #{char}"
337 # Method to reverse the sequence.
339 Seq.new(self.seq_name, self.seq.reverse, self.type, self.qual ? self.qual.reverse : self.qual)
342 # Method to reverse the sequence.
345 self.qual.reverse! if self.qual
349 # Method that complements sequence including ambiguity codes.
351 raise SeqError, "Cannot complement 0 length sequence" if self.length == 0
354 entry.seq_name = self.seq_name
355 entry.type = self.type
356 entry.qual = self.qual
359 entry.seq = self.seq.tr('AGCUTRYWSMKHDVBNagcutrywsmkhdvbn', 'TCGAAYRWSKMDHBVNtcgaayrwskmdhbvn')
361 entry.seq = self.seq.tr('AGCUTRYWSMKHDVBNagcutrywsmkhdvbn', 'UCGAAYRWSKMDHBVNucgaayrwskmdhbvn')
363 raise SeqError, "Cannot complement sequence type: #{self.type}"
369 # Method that complements sequence including ambiguity codes.
371 raise SeqError, "Cannot complement 0 length sequence" if self.length == 0
374 self.seq.tr!('AGCUTRYWSMKHDVBNagcutrywsmkhdvbn', 'TCGAAYRWSKMDHBVNtcgaayrwskmdhbvn')
376 self.seq.tr!('AGCUTRYWSMKHDVBNagcutrywsmkhdvbn', 'UCGAAYRWSKMDHBVNucgaayrwskmdhbvn')
378 raise SeqError, "Cannot complement sequence type: #{self.type}"
384 # Method to determine the Hamming Distance between
385 # two Sequence objects (case insensitive).
386 def hamming_distance(seq)
387 self.seq.upcase.hamming_distance(seq.seq.upcase)
390 # Method that generates a random sequence of a given length and type.
391 def generate(length, type)
392 raise SeqError, "Cannot generate sequence length < 1: #{length}" if length <= 0
395 when :dna then alph = DNA
396 when :rna then alph = RNA
397 when :protein then alph = PROTEIN
399 raise SeqError, "Unknown sequence type: #{type}"
402 seq_new = Array.new(length) { alph[rand(alph.size)] }.join("")
408 # Method to return a new Seq object with shuffled sequence.
410 Seq.new(self.seq_name, self.seq.split('').shuffle!.join, self.type, self.qual)
413 # Method to shuffle a sequence randomly inline.
415 self.seq = self.seq.split('').shuffle!.join
419 # Method to concatenate sequence entries.
421 raise SeqError, "sequences of different types" unless self.type == entry.type
422 raise SeqError, "qual is missing in one entry" unless self.qual.class == entry.qual.class
424 self.seq << entry.seq
425 self.qual << entry.qual unless entry.qual.nil?
430 # Method that returns a subsequence of from a given start position
431 # and of a given length.
432 def subseq(start, length = self.length - start)
433 raise SeqError, "subsequence start: #{start} < 0" if start < 0
434 raise SeqError, "subsequence length: #{length} < 0" if length < 0
435 raise SeqError, "subsequence start + length > Seq.length: #{start} + #{length} > #{self.length}" if start + length > self.length
439 qual = "" unless self.qual.nil?
441 stop = start + length - 1
443 seq = self.seq[start .. stop]
444 qual = self.qual[start .. stop] unless self.qual.nil?
447 Seq.new(self.seq_name, seq, self.type, qual) # TODO changed self.seq_name.dup to self.seq_name -> consequence?
450 # Method that replaces a sequence with a subsequence from a given start position
451 # and of a given length.
452 def subseq!(start, length = self.length - start)
453 s = subseq(start, length)
455 self.seq_name = s.seq_name
463 # Method that returns a subsequence of a given length
464 # beginning at a random position.
465 def subseq_rand(length)
466 if self.length - length + 1 == 0
469 start = rand(self.length - length + 1)
472 self.subseq(start, length)
475 # Method that returns the residue compositions of a sequence in
476 # a hash where the key is the residue and the value is the residue
481 self.seq.upcase.each_char do |char|
488 # Method that returns the length of the longest homopolymeric stretch
489 # found in a sequence.
490 def homopol_max(min = 1)
491 return 0 if self.seq.nil? or self.seq.empty?
495 self.seq.upcase.scan(/A{#{min},}|T{#{min},}|G{#{min},}|C{#{min},}|N{#{min},}/) do |match|
497 min = match.size > min ? match.size : min
500 return 0 unless found
505 # Method that returns the percentage of hard masked residues
506 # or N's in a sequence.
508 ((self.seq.upcase.scan("N").size.to_f / (self.len - self.indels).to_f) * 100).round(2)
511 # Method that returns the percentage of soft masked residues
512 # or lower cased residues in a sequence.
514 ((self.seq.scan(/[a-z]/).size.to_f / (self.len - self.indels).to_f) * 100).round(2)
517 # Hard masks sequence residues where the corresponding quality score
518 # is below a given cutoff.
519 def mask_seq_hard!(cutoff)
520 raise SeqError, "seq is nil" if self.seq.nil?
521 raise SeqError, "qual is nil" if self.qual.nil?
522 raise SeqError, "cufoff value: #{cutoff} out of range #{SCORE_MIN} .. #{SCORE_MAX}" unless (SCORE_MIN .. SCORE_MAX).include? cutoff
524 na_seq = NArray.to_na(self.seq, "byte")
525 na_qual = NArray.to_na(self.qual, "byte")
526 mask = (na_qual - SCORE_BASE) < cutoff
527 mask *= na_seq.ne("-".ord)
529 na_seq[mask] = 'N'.ord
531 self.seq = na_seq.to_s
536 # Soft masks sequence residues where the corresponding quality score
537 # is below a given cutoff.
538 def mask_seq_soft!(cutoff)
539 raise SeqError, "seq is nil" if self.seq.nil?
540 raise SeqError, "qual is nil" if self.qual.nil?
541 raise SeqError, "cufoff value: #{cutoff} out of range #{SCORE_MIN} .. #{SCORE_MAX}" unless (SCORE_MIN .. SCORE_MAX).include? cutoff
543 na_seq = NArray.to_na(self.seq, "byte")
544 na_qual = NArray.to_na(self.qual, "byte")
545 mask = (na_qual - SCORE_BASE) < cutoff
546 mask *= na_seq.ne("-".ord)
548 na_seq[mask] ^= ' '.ord
550 self.seq = na_seq.to_s
555 # Method that determines if a quality score string can be
556 # absolutely identified as base 33.
558 self.qual.match(/[!-:]/) ? true : false
561 # Method that determines if a quality score string may be base 64.
563 self.qual.match(/[K-h]/) ? true : false
566 # Method to determine if a quality score is valid accepting only 0-40 range.
567 def qual_valid?(encoding)
568 raise SeqError, "Missing qual" if self.qual.nil?
571 when :base_33 then return true if self.qual.match(/^[!-I]*$/)
572 when :base_64 then return true if self.qual.match(/^[@-h]*$/)
573 else raise SeqError, "unknown quality score encoding: #{encoding}"
579 # Method to coerce quality scores to be within the 0-40 range.
580 def qual_coerce!(encoding)
581 raise SeqError, "Missing qual" if self.qual.nil?
584 when :base_33 then self.qual.tr!("[J-~]", "I")
585 when :base_64 then self.qual.tr!("[i-~]", "h")
586 else raise SeqError, "unknown quality score encoding: #{encoding}"
592 # Method to convert quality scores.
593 def qual_convert!(from, to)
594 raise SeqError, "unknown quality score encoding: #{from}" unless from == :base_33 or from == :base_64
595 raise SeqError, "unknown quality score encoding: #{to}" unless to == :base_33 or to == :base_64
597 if from == :base_33 and to == :base_64
598 na_qual = NArray.to_na(self.qual, "byte")
600 self.qual = na_qual.to_s
601 elsif from == :base_64 and to == :base_33
602 self.qual.tr!("[;-?]", "@") # Handle negative Solexa values from -5 to -1 (set these to 0).
603 na_qual = NArray.to_na(self.qual, "byte")
605 self.qual = na_qual.to_s
611 # Method to calculate and return the mean quality score.
613 raise SeqError, "Missing qual in entry" if self.qual.nil?
615 na_qual = NArray.to_na(self.qual, "byte")
616 na_qual -= SCORE_BASE
621 # Method to find open reading frames (ORFs).
622 def each_orf(size_min, size_max, start_codons, stop_codons, pick_longest = false)
626 regex_start = Regexp.new(start_codons.join('|'), true)
627 regex_stop = Regexp.new(stop_codons.join('|'), true)
629 while pos_beg and pos_beg < self.length - size_min
630 if pos_beg = self.seq.index(regex_start, pos_beg)
631 if pos_end = self.seq.index(regex_stop, pos_beg)
632 length = (pos_end - pos_beg) + 3
635 if size_min <= length and length <= size_max
636 subseq = self.subseq(pos_beg, length)
638 orfs << [subseq, pos_beg, pos_end + 3]
650 orfs.each { |orf| orf_hash[orf.last] = orf unless orf_hash[orf.last] }
652 orfs = orf_hash.values
656 orfs.each { |orf| yield orf }