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]
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?
220 self.seq.tr!('Uu','Tt')
223 # Method to translate a DNA sequence to protein.
224 def translate!(trans_tab = 11)
225 raise SeqError, "Sequence type must be 'dna' - not #{self.type}" unless self.type == 'dna'
226 raise SeqError, "Sequence length must be a multiplum of 3 - was: #{self.length}" unless (self.length % 3) == 0
230 codon_start_hash = TRANS_TAB11_START
231 codon_hash = TRANS_TAB11
233 raise SeqError, "Unknown translation table: #{trans_tab}"
236 codon = self.seq[0 ... 3].upcase
238 aa = codon_start_hash[codon]
240 raise SeqError, "Unknown start codon: #{codon}" if aa.nil?
246 while i < self.length
247 codon = self.seq[i ... i + 3].upcase
249 aa = codon_hash[codon]
251 raise SeqError, "Unknown codon: #{codon}" if aa.nil?
260 self.type = "protein"
265 alias :to_protein! :translate!
267 def translate(trans_tab = 11)
268 self.dup.translate!(trans_tab)
271 alias :to_protein :translate
273 # Method that given a Seq entry returns a Biopieces record (a hash).
275 raise SeqError, "Missing seq_name" if self.seq_name.nil?
276 raise SeqError, "Missing seq" if self.seq.nil?
279 record[:SEQ_NAME] = self.seq_name
280 record[:SEQ] = self.seq
281 record[:SEQ_LEN] = self.length
282 record[:SCORES] = self.qual if self.qual
286 # Method that given a Seq entry returns a FASTA entry (a string).
287 def to_fasta(wrap = nil)
288 raise SeqError, "Missing seq_name" if self.seq_name.nil? or self.seq_name == ''
289 raise SeqError, "Missing seq" if self.seq.nil? or self.seq.empty?
291 seq_name = self.seq_name.to_s
295 seq.gsub!(/(.{#{wrap}})/) do |match|
302 ">" + seq_name + $/ + seq + $/
305 # Method that given a Seq entry returns a FASTQ entry (a string).
307 raise SeqError, "Missing seq_name" if self.seq_name.nil?
308 raise SeqError, "Missing seq" if self.seq.nil?
309 raise SeqError, "Missing qual" if self.qual.nil?
311 seq_name = self.seq_name.to_s
313 qual = self.qual.to_s
315 "@" + seq_name + $/ + seq + $/ + "+" + $/ + qual + $/
318 # Method that generates a unique key for a
319 # DNA sequence and return this key as a Fixnum.
323 self.seq.upcase.each_char do |char|
327 when 'A' then key |= 0
328 when 'C' then key |= 1
329 when 'G' then key |= 2
330 when 'T' then key |= 3
331 else raise SeqError, "Bad residue: #{char}"
338 # Method to reverse the sequence.
340 Seq.new(self.seq_name, self.seq.reverse, self.type, self.qual ? self.qual.reverse : self.qual)
343 # Method to reverse the sequence.
346 self.qual.reverse! if self.qual
350 # Method that complements sequence including ambiguity codes.
352 raise SeqError, "Cannot complement 0 length sequence" if self.length == 0
355 entry.seq_name = self.seq_name
356 entry.type = self.type
357 entry.qual = self.qual
360 entry.seq = self.seq.tr('AGCUTRYWSMKHDVBNagcutrywsmkhdvbn', 'TCGAAYRWSKMDHBVNtcgaayrwskmdhbvn')
362 entry.seq = self.seq.tr('AGCUTRYWSMKHDVBNagcutrywsmkhdvbn', 'UCGAAYRWSKMDHBVNucgaayrwskmdhbvn')
364 raise SeqError, "Cannot complement sequence type: #{self.type}"
370 # Method that complements sequence including ambiguity codes.
372 raise SeqError, "Cannot complement 0 length sequence" if self.length == 0
375 self.seq.tr!('AGCUTRYWSMKHDVBNagcutrywsmkhdvbn', 'TCGAAYRWSKMDHBVNtcgaayrwskmdhbvn')
377 self.seq.tr!('AGCUTRYWSMKHDVBNagcutrywsmkhdvbn', 'UCGAAYRWSKMDHBVNucgaayrwskmdhbvn')
379 raise SeqError, "Cannot complement sequence type: #{self.type}"
385 # Method to determine the Hamming Distance between
386 # two Sequence objects (case insensitive).
387 def hamming_distance(seq)
388 self.seq.upcase.hamming_distance(seq.seq.upcase)
391 # Method that generates a random sequence of a given length and type.
392 def generate(length, type)
393 raise SeqError, "Cannot generate sequence length < 1: #{length}" if length <= 0
403 raise SeqError, "Unknown sequence type: #{type}"
406 seq_new = Array.new(length) { alph[rand(alph.size)] }.join("")
408 self.type = type.downcase
412 # Method to return a new Seq object with shuffled sequence.
414 Seq.new(self.seq_name, self.seq.split('').shuffle!.join, self.type, self.qual)
417 # Method to shuffle a sequence randomly inline.
419 self.seq = self.seq.split('').shuffle!.join
423 # Method to concatenate sequence entries.
425 raise SeqError, "sequences of different types" unless self.type == entry.type
426 raise SeqError, "qual is missing in one entry" unless self.qual.class == entry.qual.class
428 self.seq << entry.seq
429 self.qual << entry.qual unless entry.qual.nil?
434 # Method that returns a subsequence of from a given start position
435 # and of a given length.
436 def subseq(start, length = self.length - start)
437 raise SeqError, "subsequence start: #{start} < 0" if start < 0
438 raise SeqError, "subsequence length: #{length} < 0" if length < 0
439 raise SeqError, "subsequence start + length > Seq.length: #{start} + #{length} > #{self.length}" if start + length > self.length
443 qual = "" unless self.qual.nil?
445 stop = start + length - 1
447 seq = self.seq[start .. stop]
448 qual = self.qual[start .. stop] unless self.qual.nil?
451 Seq.new(self.seq_name, seq, self.type, qual) # TODO changed self.seq_name.dup to self.seq_name -> consequence?
454 # Method that replaces a sequence with a subsequence from a given start position
455 # and of a given length.
456 def subseq!(start, length = self.length - start)
457 s = subseq(start, length)
459 self.seq_name = s.seq_name
467 # Method that returns a subsequence of a given length
468 # beginning at a random position.
469 def subseq_rand(length)
470 if self.length - length + 1 == 0
473 start = rand(self.length - length + 1)
476 self.subseq(start, length)
479 # Method that returns the residue compositions of a sequence in
480 # a hash where the key is the residue and the value is the residue
485 self.seq.upcase.each_char do |char|
492 # Method that returns the length of the longest homopolymeric stretch
493 # found in a sequence.
494 def homopol_max(min = 1)
495 return 0 if self.seq.nil? or self.seq.empty?
499 self.seq.upcase.scan(/A{#{min},}|T{#{min},}|G{#{min},}|C{#{min},}|N{#{min},}/) do |match|
501 min = match.size > min ? match.size : min
504 return 0 unless found
509 # Method that returns the percentage of hard masked residues
510 # or N's in a sequence.
512 ((self.seq.upcase.scan("N").size.to_f / (self.len - self.indels).to_f) * 100).round(2)
515 # Method that returns the percentage of soft masked residues
516 # or lower cased residues in a sequence.
518 ((self.seq.scan(/[a-z]/).size.to_f / (self.len - self.indels).to_f) * 100).round(2)
521 # Hard masks sequence residues where the corresponding quality score
522 # is below a given cutoff.
523 def mask_seq_hard!(cutoff)
524 raise SeqError, "seq is nil" if self.seq.nil?
525 raise SeqError, "qual is nil" if self.qual.nil?
526 raise SeqError, "cufoff value: #{cutoff} out of range #{SCORE_MIN} .. #{SCORE_MAX}" unless (SCORE_MIN .. SCORE_MAX).include? cutoff
528 na_seq = NArray.to_na(self.seq, "byte")
529 na_qual = NArray.to_na(self.qual, "byte")
530 mask = (na_qual - SCORE_BASE) < cutoff
531 mask *= na_seq.ne("-".ord)
533 na_seq[mask] = 'N'.ord
535 self.seq = na_seq.to_s
540 # Soft masks sequence residues where the corresponding quality score
541 # is below a given cutoff.
542 def mask_seq_soft!(cutoff)
543 raise SeqError, "seq is nil" if self.seq.nil?
544 raise SeqError, "qual is nil" if self.qual.nil?
545 raise SeqError, "cufoff value: #{cutoff} out of range #{SCORE_MIN} .. #{SCORE_MAX}" unless (SCORE_MIN .. SCORE_MAX).include? cutoff
547 na_seq = NArray.to_na(self.seq, "byte")
548 na_qual = NArray.to_na(self.qual, "byte")
549 mask = (na_qual - SCORE_BASE) < cutoff
550 mask *= na_seq.ne("-".ord)
552 na_seq[mask] ^= ' '.ord
554 self.seq = na_seq.to_s
559 # Method that determines if a quality score string can be
560 # absolutely identified as base 33.
562 self.qual.match(/[!-:]/) ? true : false
565 # Method that determines if a quality score string may be base 64.
567 self.qual.match(/[K-h]/) ? true : false
570 # Method to determine if a quality score is valid accepting only 0-40 range.
571 def qual_valid?(encoding)
572 raise SeqError, "Missing qual" if self.qual.nil?
575 when :base_33 then return true if self.qual.match(/^[!-I]*$/)
576 when :base_64 then return true if self.qual.match(/^[@-h]*$/)
577 else raise SeqError, "unknown quality score encoding: #{encoding}"
583 # Method to coerce quality scores to be within the 0-40 range.
584 def qual_coerce!(encoding)
585 raise SeqError, "Missing qual" if self.qual.nil?
588 when :base_33 then self.qual.tr!("[J-~]", "I")
589 when :base_64 then self.qual.tr!("[i-~]", "h")
590 else raise SeqError, "unknown quality score encoding: #{encoding}"
596 # Method to convert quality scores.
597 def qual_convert!(from, to)
598 raise SeqError, "unknown quality score encoding: #{from}" unless from == :base_33 or from == :base_64
599 raise SeqError, "unknown quality score encoding: #{to}" unless to == :base_33 or to == :base_64
601 if from == :base_33 and to == :base_64
602 na_qual = NArray.to_na(self.qual, "byte")
604 self.qual = na_qual.to_s
605 elsif from == :base_64 and to == :base_33
606 self.qual.tr!("[;-?]", "@") # Handle negative Solexa values from -5 to -1 (set these to 0).
607 na_qual = NArray.to_na(self.qual, "byte")
609 self.qual = na_qual.to_s
615 # Method to calculate and return the mean quality score.
617 raise SeqError, "Missing qual in entry" if self.qual.nil?
619 na_qual = NArray.to_na(self.qual, "byte")
620 na_qual -= SCORE_BASE
625 # Method to find open reading frames (ORFs).
626 def each_orf(size_min, size_max, start_codons, stop_codons, pick_longest = false)
630 regex_start = Regexp.new(start_codons.join('|'), true)
631 regex_stop = Regexp.new(stop_codons.join('|'), true)
633 while pos_beg and pos_beg < self.length - size_min
634 if pos_beg = self.seq.index(regex_start, pos_beg)
635 if pos_end = self.seq.index(regex_stop, pos_beg)
636 length = (pos_end - pos_beg) + 3
639 if size_min <= length and length <= size_max
640 subseq = self.subseq(pos_beg, length)
642 orfs << [subseq, pos_beg, pos_end + 3]
654 orfs.each { |orf| orf_hash[orf.last] = orf unless orf_hash[orf.last] }
656 orfs = orf_hash.values
660 orfs.each { |orf| yield orf }