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'
31 autoload :Dynamic, 'maasha/seq/dynamic'
32 autoload :Homopolymer, 'maasha/seq/homopolymer'
33 autoload :Levenshtein, 'maasha/seq/levenshtein'
34 autoload :Ambiguity, 'maasha/seq/ambiguity'
39 PROTEIN = %w[f l s y c w p h q r i m t n k v a d e g]
42 # Translation table 11
43 # (http://www.ncbi.nlm.nih.gov/Taxonomy/taxonomyhome.html/index.cgi?chapter=cgencodes#SG11)
44 # AAs = FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG
45 # Starts = ---M---------------M------------MMMM---------------M------------
46 # Base1 = TTTTTTTTTTTTTTTTCCCCCCCCCCCCCCCCAAAAAAAAAAAAAAAAGGGGGGGGGGGGGGGG
47 # Base2 = TTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGG
48 # Base3 = TCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAG
50 "TTG" => "M", "CTG" => "M", "ATT" => "M", "ATC" => "M",
51 "ATA" => "M", "ATG" => "M", "GTG" => "M"
55 "TTT" => "F", "TCT" => "S", "TAT" => "Y", "TGT" => "C",
56 "TTC" => "F", "TCC" => "S", "TAC" => "Y", "TGC" => "C",
57 "TTA" => "L", "TCA" => "S", "TAA" => "*", "TGA" => "*",
58 "TTG" => "L", "TCG" => "S", "TAG" => "*", "TGG" => "W",
59 "CTT" => "L", "CCT" => "P", "CAT" => "H", "CGT" => "R",
60 "CTC" => "L", "CCC" => "P", "CAC" => "H", "CGC" => "R",
61 "CTA" => "L", "CCA" => "P", "CAA" => "Q", "CGA" => "R",
62 "CTG" => "L", "CCG" => "P", "CAG" => "Q", "CGG" => "R",
63 "ATT" => "I", "ACT" => "T", "AAT" => "N", "AGT" => "S",
64 "ATC" => "I", "ACC" => "T", "AAC" => "N", "AGC" => "S",
65 "ATA" => "I", "ACA" => "T", "AAA" => "K", "AGA" => "R",
66 "ATG" => "M", "ACG" => "T", "AAG" => "K", "AGG" => "R",
67 "GTT" => "V", "GCT" => "A", "GAT" => "D", "GGT" => "G",
68 "GTC" => "V", "GCC" => "A", "GAC" => "D", "GGC" => "G",
69 "GTA" => "V", "GCA" => "A", "GAA" => "E", "GGA" => "G",
70 "GTG" => "V", "GCG" => "A", "GAG" => "E", "GGG" => "G"
73 # Error class for all exceptions to do with Seq.
74 class SeqError < StandardError; end
77 # Quality scores bases
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].to_sym if 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
158 # Returns the length of a sequence.
160 self.seq.nil? ? 0 : self.seq.length
165 # Return the number indels in a sequence.
167 regex = Regexp.new(/[#{Regexp.escape(INDELS.join(""))}]/)
168 self.seq.scan(regex).size
171 # Method to remove indels from seq and qual if qual.
174 self.seq.delete!(Regexp.escape(INDELS.join('')))
176 na_seq = NArray.to_na(self.seq, "byte")
177 na_qual = NArray.to_na(self.qual, "byte")
178 mask = NArray.byte(self.length)
181 mask += na_seq.eq(c.ord)
186 self.seq = na_seq[mask].to_s
187 self.qual = na_qual[mask].to_s
193 # Method that returns true is a given sequence type is DNA.
198 # Method that returns true is a given sequence type is RNA.
203 # Method that returns true is a given sequence type is protein.
205 self.type == :protein
208 # Method to transcribe DNA to RNA.
210 raise SeqError, "Cannot transcribe 0 length sequence" if self.length == 0
211 raise SeqError, "Cannot transcribe sequence type: #{self.type}" unless self.is_dna?
213 self.seq.tr!('Tt','Uu')
216 # Method to reverse-transcribe RNA to DNA.
218 raise SeqError, "Cannot reverse-transcribe 0 length sequence" if self.length == 0
219 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?
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 the sequence.
341 Seq.new(self.seq_name, self.seq.reverse, self.type, self.qual ? self.qual.reverse : self.qual)
344 # Method to reverse the sequence.
347 self.qual.reverse! if self.qual
351 # Method that complements sequence including ambiguity codes.
353 raise SeqError, "Cannot complement 0 length sequence" if self.length == 0
356 entry.seq_name = self.seq_name
357 entry.type = self.type
358 entry.qual = self.qual
361 entry.seq = self.seq.tr('AGCUTRYWSMKHDVBNagcutrywsmkhdvbn', 'TCGAAYRWSKMDHBVNtcgaayrwskmdhbvn')
363 entry.seq = self.seq.tr('AGCUTRYWSMKHDVBNagcutrywsmkhdvbn', 'UCGAAYRWSKMDHBVNucgaayrwskmdhbvn')
365 raise SeqError, "Cannot complement sequence type: #{self.type}"
371 # Method that complements sequence including ambiguity codes.
373 raise SeqError, "Cannot complement 0 length sequence" if self.length == 0
376 self.seq.tr!('AGCUTRYWSMKHDVBNagcutrywsmkhdvbn', 'TCGAAYRWSKMDHBVNtcgaayrwskmdhbvn')
378 self.seq.tr!('AGCUTRYWSMKHDVBNagcutrywsmkhdvbn', 'UCGAAYRWSKMDHBVNucgaayrwskmdhbvn')
380 raise SeqError, "Cannot complement sequence type: #{self.type}"
386 # Method to determine the Hamming Distance between
387 # two Sequence objects (case insensitive).
388 def hamming_distance(entry, options = nil)
389 if options and options[:ambiguity]
390 Ambiguity.hamming_distance(self.seq, entry.seq)
392 self.seq.upcase.hamming_distance(entry.seq.upcase)
396 # Method to determine the Edit Distance between
397 # two Sequence objects (case insensitive).
398 def edit_distance(entry)
399 Levenshtein.distance(self.seq, entry.seq)
402 # Method that generates a random sequence of a given length and type.
403 def generate(length, type)
404 raise SeqError, "Cannot generate sequence length < 1: #{length}" if length <= 0
407 when :dna then alph = DNA
408 when :rna then alph = RNA
409 when :protein then alph = PROTEIN
411 raise SeqError, "Unknown sequence type: #{type}"
414 seq_new = Array.new(length) { alph[rand(alph.size)] }.join("")
420 # Method to return a new Seq object with shuffled sequence.
422 Seq.new(self.seq_name, self.seq.split('').shuffle!.join, self.type, self.qual)
425 # Method to shuffle a sequence randomly inline.
427 self.seq = self.seq.split('').shuffle!.join
431 # Method to add two Seq objects.
433 new_entry = Seq.new()
434 new_entry.seq = self.seq + entry.seq
435 new_entry.type = self.type if self.type == entry.type
436 new_entry.qual = self.qual + entry.qual if self.qual and entry.qual
440 # Method to concatenate sequence entries.
442 raise SeqError, "sequences of different types" unless self.type == entry.type
443 raise SeqError, "qual is missing in one entry" unless self.qual.class == entry.qual.class
445 self.seq << entry.seq
446 self.qual << entry.qual unless entry.qual.nil?
451 # Index method for Seq objects.
454 entry.seq_name = self.seq_name
455 entry.seq = self.seq[*args]
456 entry.type = self.type
457 entry.qual = self.qual[*args] unless self.qual.nil?
462 # Index assignment method for Seq objects.
463 def []=(*args, entry)
464 self.seq[*args] = entry.seq[*args]
465 self.qual[*args] = entry.qual[*args] unless self.qual.nil?
470 # Method that returns a subsequence of from a given start position
471 # and of a given length.
472 def subseq(start, length = self.length - start)
473 raise SeqError, "subsequence start: #{start} < 0" if start < 0
474 raise SeqError, "subsequence length: #{length} < 0" if length < 0
475 raise SeqError, "subsequence start + length > Seq.length: #{start} + #{length} > #{self.length}" if start + length > self.length
479 qual = "" unless self.qual.nil?
481 stop = start + length - 1
483 seq = self.seq[start .. stop]
484 qual = self.qual[start .. stop] unless self.qual.nil?
487 seq_name = self.seq_name.nil? ? nil : self.seq_name.dup
489 Seq.new(seq_name, seq, self.type, qual)
492 # Method that replaces a sequence with a subsequence from a given start position
493 # and of a given length.
494 def subseq!(start, length = self.length - start)
495 s = subseq(start, length)
497 self.seq_name = s.seq_name
505 # Method that returns a subsequence of a given length
506 # beginning at a random position.
507 def subseq_rand(length)
508 if self.length - length + 1 == 0
511 start = rand(self.length - length + 1)
514 self.subseq(start, length)
517 # Method that returns the residue compositions of a sequence in
518 # a hash where the key is the residue and the value is the residue
523 self.seq.upcase.each_char do |char|
530 # Method that returns the percentage of hard masked residues
531 # or N's in a sequence.
533 ((self.seq.upcase.scan("N").size.to_f / (self.len - self.indels).to_f) * 100).round(2)
536 # Method that returns the percentage of soft masked residues
537 # or lower cased residues in a sequence.
539 ((self.seq.scan(/[a-z]/).size.to_f / (self.len - self.indels).to_f) * 100).round(2)
542 # Hard masks sequence residues where the corresponding quality score
543 # is below a given cutoff.
544 def mask_seq_hard!(cutoff)
545 raise SeqError, "seq is nil" if self.seq.nil?
546 raise SeqError, "qual is nil" if self.qual.nil?
547 raise SeqError, "cufoff value: #{cutoff} out of range #{SCORE_MIN} .. #{SCORE_MAX}" unless (SCORE_MIN .. SCORE_MAX).include? cutoff
549 na_seq = NArray.to_na(self.seq, "byte")
550 na_qual = NArray.to_na(self.qual, "byte")
551 mask = (na_qual - SCORE_BASE) < cutoff
552 mask *= na_seq.ne("-".ord)
554 na_seq[mask] = 'N'.ord
556 self.seq = na_seq.to_s
561 # Soft masks sequence residues where the corresponding quality score
562 # is below a given cutoff.
563 def mask_seq_soft!(cutoff)
564 raise SeqError, "seq is nil" if self.seq.nil?
565 raise SeqError, "qual is nil" if self.qual.nil?
566 raise SeqError, "cufoff value: #{cutoff} out of range #{SCORE_MIN} .. #{SCORE_MAX}" unless (SCORE_MIN .. SCORE_MAX).include? cutoff
568 na_seq = NArray.to_na(self.seq, "byte")
569 na_qual = NArray.to_na(self.qual, "byte")
570 mask = (na_qual - SCORE_BASE) < cutoff
571 mask *= na_seq.ne("-".ord)
573 na_seq[mask] ^= ' '.ord
575 self.seq = na_seq.to_s
580 # Method that determines if a quality score string can be
581 # absolutely identified as base 33.
583 self.qual.match(/[!-:]/) ? true : false
586 # Method that determines if a quality score string may be base 64.
588 self.qual.match(/[K-h]/) ? true : false
591 # Method to determine if a quality score is valid accepting only 0-40 range.
592 def qual_valid?(encoding)
593 raise SeqError, "Missing qual" if self.qual.nil?
596 when :base_33 then return true if self.qual.match(/^[!-I]*$/)
597 when :base_64 then return true if self.qual.match(/^[@-h]*$/)
598 else raise SeqError, "unknown quality score encoding: #{encoding}"
604 # Method to coerce quality scores to be within the 0-40 range.
605 def qual_coerce!(encoding)
606 raise SeqError, "Missing qual" if self.qual.nil?
609 when :base_33 then self.qual.tr!("[J-~]", "I")
610 when :base_64 then self.qual.tr!("[i-~]", "h")
611 else raise SeqError, "unknown quality score encoding: #{encoding}"
617 # Method to convert quality scores.
618 def qual_convert!(from, to)
619 raise SeqError, "unknown quality score encoding: #{from}" unless from == :base_33 or from == :base_64
620 raise SeqError, "unknown quality score encoding: #{to}" unless to == :base_33 or to == :base_64
622 if from == :base_33 and to == :base_64
623 na_qual = NArray.to_na(self.qual, "byte")
625 self.qual = na_qual.to_s
626 elsif from == :base_64 and to == :base_33
627 self.qual.tr!("[;-?]", "@") # Handle negative Solexa values from -5 to -1 (set these to 0).
628 na_qual = NArray.to_na(self.qual, "byte")
630 self.qual = na_qual.to_s
636 # Method to calculate and return the mean quality score.
638 raise SeqError, "Missing qual in entry" if self.qual.nil?
640 na_qual = NArray.to_na(self.qual, "byte")
641 na_qual -= SCORE_BASE
646 # Method to find open reading frames (ORFs).
647 def each_orf(size_min, size_max, start_codons, stop_codons, pick_longest = false)
651 regex_start = Regexp.new(start_codons.join('|'), true)
652 regex_stop = Regexp.new(stop_codons.join('|'), true)
654 while pos_beg and pos_beg < self.length - size_min
655 if pos_beg = self.seq.index(regex_start, pos_beg)
656 if pos_end = self.seq.index(regex_stop, pos_beg)
657 length = (pos_end - pos_beg) + 3
660 if size_min <= length and length <= size_max
661 subseq = self.subseq(pos_beg, length)
663 orfs << [subseq, pos_beg, pos_end + 3]
675 orfs.each { |orf| orf_hash[orf.last] = orf unless orf_hash[orf.last] }
677 orfs = orf_hash.values
681 orfs.each { |orf| yield orf }