1 # Copyright (C) 2007-2011 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 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
25 require 'maasha/digest'
26 require 'maasha/patternmatcher'
28 #require 'maasha/patscan'
33 PROTEIN = %w[f l s y c w p h q r i m t n k v a d e g]
36 # Quality scores bases
40 # Error class for all exceptions to do with Seq.
41 class SeqError < StandardError; end
45 include PatternMatcher
47 attr_accessor :seq_name, :seq, :type, :qual
49 # Class method to instantiate a new Sequence object given
51 def self.new_bp(record)
52 seq_name = record[:SEQ_NAME]
54 type = record[:SEQ_TYPE]
55 qual = record[:SCORES]
57 self.new(seq_name, seq, type, qual)
60 # Class method that generates all possible oligos of a specifed length and type.
61 def self.generate_oligos(length, type)
62 raise SeqError, "Cannot generate negative oligo length: #{length}" if length <= 0
65 when /dna/ then alph = DNA
66 when /rna/ then alph = RNA
67 when /protein/ then alph = PROTEIN
69 raise SeqError, "Unknown sequence type: #{type}"
77 oligos.each do |oligo|
89 # Initialize a sequence object with the following arguments:
90 # - seq_name: Name of the sequence.
91 # - seq: The sequence.
92 # - type: The sequence type - DNA, RNA, or protein
93 # - qual: An Illumina type quality scores string.
94 def initialize(seq_name = nil, seq = nil, type = nil, qual = nil)
101 # Method that guesses and returns the sequence type
102 # by inspecting the first 100 residues.
104 raise SeqError, "Guess failed: sequence is nil" if self.seq.nil?
106 case self.seq[0 ... 100].downcase
107 when /[flpqie]/ then return "protein"
108 when /[u]/ then return "rna"
113 # Method that guesses and sets the sequence type
114 # by inspecting the first 100 residues.
116 self.type = self.type_guess
119 # Returns the length of a sequence.
121 self.seq.nil? ? 0 : self.seq.length
126 # Return the number indels in a sequence.
128 regex = Regexp.new(/[#{Regexp.escape(INDELS.join(""))}]/)
129 self.seq.scan(regex).size
132 # Method that returns true is a given sequence type is DNA.
137 # Method that returns true is a given sequence type is RNA.
142 # Method that returns true is a given sequence type is protein.
144 self.type == 'protein'
147 # Method to transcribe DNA to RNA.
149 raise SeqError, "Cannot transcribe 0 length sequence" if self.length == 0
150 raise SeqError, "Cannot transcribe sequence type: #{self.type}" unless self.is_dna?
152 self.seq.tr!('Tt','Uu')
155 # Method to reverse-transcribe RNA to DNA.
157 raise SeqError, "Cannot reverse-transcribe 0 length sequence" if self.length == 0
158 raise SeqError, "Cannot reverse-transcribe sequence type: #{self.type}" unless self.is_rna?
161 self.seq.tr!('Uu','Tt')
164 # Method that given a Seq entry returns a Biopieces record (a hash).
166 raise SeqError, "Missing seq_name" if self.seq_name.nil?
167 raise SeqError, "Missing seq" if self.seq.nil?
170 record[:SEQ_NAME] = self.seq_name
171 record[:SEQ] = self.seq
172 record[:SEQ_LEN] = self.length
173 record[:SCORES] = self.qual if self.qual
177 # Method that given a Seq entry returns a FASTA entry (a string).
178 def to_fasta(wrap = nil)
179 raise SeqError, "Missing seq_name" if self.seq_name.nil?
180 raise SeqError, "Missing seq" if self.seq.nil?
182 seq_name = self.seq_name.to_s
186 seq.gsub!(/(.{#{wrap}})/) do |match|
193 ">" + seq_name + $/ + seq + $/
196 # Method that given a Seq entry returns a FASTQ entry (a string).
198 raise SeqError, "Missing seq_name" if self.seq_name.nil?
199 raise SeqError, "Missing seq" if self.seq.nil?
200 raise SeqError, "Missing qual" if self.qual.nil?
202 seq_name = self.seq_name.to_s
204 qual = self.qual.to_s
206 "@" + seq_name + $/ + seq + $/ + "+" + $/ + qual + $/
209 # Method that generates a unique key for a
210 # DNA sequence and return this key as a Fixnum.
214 self.seq.upcase.each_char do |char|
218 when 'A' then key |= 0
219 when 'C' then key |= 1
220 when 'G' then key |= 2
221 when 'T' then key |= 3
222 else raise SeqError, "Bad residue: #{char}"
229 # Method to reverse complement sequence.
230 def reverse_complement
235 alias :revcomp :reverse_complement
237 # Method to reverse the sequence.
240 self.qual.reverse! if self.qual
243 # Method that complements sequence including ambiguity codes.
245 raise SeqError, "Cannot complement 0 length sequence" if self.length == 0
248 self.seq.tr!( 'AGCUTRYWSMKHDVBNagcutrywsmkhdvbn', 'TCGAAYRWSKMDHBVNtcgaayrwskmdhbvn' )
250 self.seq.tr!( 'AGCUTRYWSMKHDVBNagcutrywsmkhdvbn', 'UCGAAYRWSKMDHBVNucgaayrwskmdhbvn' )
252 raise SeqError, "Cannot complement sequence type: #{self.type}"
256 # Method to determine the Hamming Distance between
257 # two Sequence objects (case insensitive).
258 def hamming_distance(seq)
259 self.seq.upcase.hamming_distance(seq.seq.upcase)
262 # Method that generates a random sequence of a given length and type.
263 def generate(length, type)
264 raise SeqError, "Cannot generate sequence length < 1: #{length}" if length <= 0
274 raise SeqError, "Unknown sequence type: #{type}"
277 seq_new = Array.new(length) { alph[rand(alph.size)] }.join("")
279 self.type = type.downcase
283 # Method to shuffle a sequence readomly inline.
285 self.seq = self.seq.split('').shuffle!.join
289 # Method that returns a subsequence of from a given start position
290 # and of a given length.
291 def subseq(start, length = self.length - start)
292 raise SeqError, "subsequence start: #{start} < 0" if start < 0
293 raise SeqError, "subsequence length: #{length} < 1" if length <= 0
294 raise SeqError, "subsequence start + length > Seq.length: #{start} + #{length} > #{self.length}" if start + length > self.length
296 stop = start + length - 1
298 seq = self.seq[start .. stop]
299 qual = self.qual[start .. stop] unless self.qual.nil?
301 Seq.new(self.seq_name, seq, self.type, qual)
304 # Method that replaces a sequence with a subsequence from a given start position
305 # and of a given length.
306 def subseq!(start, length = self.length - start)
307 raise SeqError, "subsequence start: #{start} < 0" if start < 0
308 raise SeqError, "subsequence length: #{length} < 1" if length <= 0
309 raise SeqError, "subsequence start + length > Seq.length: #{start} + #{length} > #{self.length}" if start + length > self.length
311 stop = start + length - 1
313 self.seq = self.seq[start .. stop]
314 self.qual = self.qual[start .. stop] unless self.qual.nil?
317 # Method that returns a subsequence of a given length
318 # beginning at a random position.
319 def subseq_rand(length)
320 if self.length - length + 1 == 0
323 start = rand(self.length - length + 1)
326 self.subseq(start, length)
329 # Method that returns the residue compositions of a sequence in
330 # a hash where the key is the residue and the value is the residue
335 self.seq.upcase.each_char do |char|
342 # Method that returns the length of the longest homopolymeric stretch
343 # found in a sequence.
344 def homopol_max(min = 1)
345 return 0 if self.seq.nil? or self.seq.empty?
349 self.seq.upcase.scan(/A{#{min},}|T{#{min},}|G{#{min},}|C{#{min},}|N{#{min},}/) do |match|
351 min = match.size > min ? match.size : min
354 return 0 unless found
359 # Method that returns the percentage of hard masked residues
360 # or N's in a sequence.
362 ((self.seq.upcase.scan("N").size.to_f / (self.len - self.indels).to_f) * 100).round(2)
365 # Method that returns the percentage of soft masked residues
366 # or lower cased residues in a sequence.
368 ((self.seq.scan(/[a-z]/).size.to_f / (self.len - self.indels).to_f) * 100).round(2)
371 # Method to convert the quality scores from a specified base
373 def convert_phred2illumina!
374 self.qual.gsub!(/./) do |score|
375 score_phred = score.ord - SCORE_PHRED
376 raise SeqError, "Bad Phred score: #{score} (#{score_phred})" unless (0 .. 41).include? score_phred
377 score_illumina = score_phred + SCORE_ILLUMINA
378 score = score_illumina.chr
382 # Method to convert the quality scores from Solexa odd/ratio to
384 def convert_solexa2illumina!
385 self.qual.gsub!(/./) do |score|
386 score = solexa_char2illumina_char(score)
392 # Method to convert a Solexa score (odd ratio) to
393 # a phred (probability) integer score.
394 def solexa2phred(score)
395 (10.0 * Math.log(10.0 ** (score / 10.0) + 1.0, 10)).to_i
398 # Method to convert a Solexa score encoded using base
399 # 64 ASCII to a Phred score encoded using base 64 ASCII.
400 def solexa_char2illumina_char(char)
401 score_solexa = char.ord - 64
402 score_phred = solexa2phred(score_solexa)
403 (score_phred + 64).chr