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 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
25 require 'maasha/patternmatcher'
27 require 'maasha/backtrack'
28 require 'maasha/digest'
29 #require 'maasha/patscan'
34 PROTEIN = %w[f l s y c w p h q r i m t n k v a d e g]
37 # Quality scores bases
43 # Error class for all exceptions to do with Seq.
44 class SeqError < StandardError; end
48 include PatternMatcher
52 attr_accessor :seq_name, :seq, :type, :qual
54 # Class method to instantiate a new Sequence object given
56 def self.new_bp(record)
57 seq_name = record[:SEQ_NAME]
59 type = record[:SEQ_TYPE]
60 qual = record[:SCORES]
62 self.new(seq_name, seq, type, qual)
65 # Class method that generates all possible oligos of a specifed length and type.
66 def self.generate_oligos(length, type)
67 raise SeqError, "Cannot generate negative oligo length: #{length}" if length <= 0
70 when /dna/ then alph = DNA
71 when /rna/ then alph = RNA
72 when /protein/ then alph = PROTEIN
74 raise SeqError, "Unknown sequence type: #{type}"
82 oligos.each do |oligo|
94 # Initialize a sequence object with the following arguments:
95 # - seq_name: Name of the sequence.
96 # - seq: The sequence.
97 # - type: The sequence type - DNA, RNA, or protein
98 # - qual: An Illumina type quality scores string.
99 def initialize(seq_name = nil, seq = nil, type = nil, qual = nil)
106 # Method that guesses and returns the sequence type
107 # by inspecting the first 100 residues.
109 raise SeqError, "Guess failed: sequence is nil" if self.seq.nil?
111 case self.seq[0 ... 100].downcase
112 when /[flpqie]/ then return "protein"
113 when /[u]/ then return "rna"
118 # Method that guesses and sets the sequence type
119 # by inspecting the first 100 residues.
121 self.type = self.type_guess
124 # Returns the length of a sequence.
126 self.seq.nil? ? 0 : self.seq.length
131 # Return the number indels in a sequence.
133 regex = Regexp.new(/[#{Regexp.escape(INDELS.join(""))}]/)
134 self.seq.scan(regex).size
137 # Method to remove indels from seq and qual if qual.
140 self.seq.delete!(Regexp.escape(INDELS.join('')))
142 na_seq = NArray.to_na(self.seq, "byte")
143 na_qual = NArray.to_na(self.qual, "byte")
144 mask = NArray.byte(self.length)
147 mask += na_seq.eq(c.ord)
152 self.seq = na_seq[mask].to_s
153 self.qual = na_qual[mask].to_s
159 # Method that returns true is a given sequence type is DNA.
164 # Method that returns true is a given sequence type is RNA.
169 # Method that returns true is a given sequence type is protein.
171 self.type == 'protein'
174 # Method to transcribe DNA to RNA.
176 raise SeqError, "Cannot transcribe 0 length sequence" if self.length == 0
177 raise SeqError, "Cannot transcribe sequence type: #{self.type}" unless self.is_dna?
179 self.seq.tr!('Tt','Uu')
182 # Method to reverse-transcribe RNA to DNA.
184 raise SeqError, "Cannot reverse-transcribe 0 length sequence" if self.length == 0
185 raise SeqError, "Cannot reverse-transcribe sequence type: #{self.type}" unless self.is_rna?
188 self.seq.tr!('Uu','Tt')
191 # Method that given a Seq entry returns a Biopieces record (a hash).
193 raise SeqError, "Missing seq_name" if self.seq_name.nil?
194 raise SeqError, "Missing seq" if self.seq.nil?
197 record[:SEQ_NAME] = self.seq_name
198 record[:SEQ] = self.seq
199 record[:SEQ_LEN] = self.length
200 record[:SCORES] = self.qual if self.qual
204 # Method that given a Seq entry returns a FASTA entry (a string).
205 def to_fasta(wrap = nil)
206 raise SeqError, "Missing seq_name" if self.seq_name.nil? or self.seq_name == ''
207 raise SeqError, "Missing seq" if self.seq.nil? or self.seq.empty?
209 seq_name = self.seq_name.to_s
213 seq.gsub!(/(.{#{wrap}})/) do |match|
220 ">" + seq_name + $/ + seq + $/
223 # Method that given a Seq entry returns a FASTQ entry (a string).
225 raise SeqError, "Missing seq_name" if self.seq_name.nil?
226 raise SeqError, "Missing seq" if self.seq.nil?
227 raise SeqError, "Missing qual" if self.qual.nil?
229 seq_name = self.seq_name.to_s
231 qual = self.qual.to_s
233 "@" + seq_name + $/ + seq + $/ + "+" + $/ + qual + $/
236 # Method that generates a unique key for a
237 # DNA sequence and return this key as a Fixnum.
241 self.seq.upcase.each_char do |char|
245 when 'A' then key |= 0
246 when 'C' then key |= 1
247 when 'G' then key |= 2
248 when 'T' then key |= 3
249 else raise SeqError, "Bad residue: #{char}"
256 # Method to reverse complement sequence.
257 def reverse_complement
263 alias :revcomp :reverse_complement
265 # Method to reverse the sequence.
268 self.qual.reverse! if self.qual
272 # Method that complements sequence including ambiguity codes.
274 raise SeqError, "Cannot complement 0 length sequence" if self.length == 0
277 self.seq.tr!('AGCUTRYWSMKHDVBNagcutrywsmkhdvbn', 'TCGAAYRWSKMDHBVNtcgaayrwskmdhbvn')
279 self.seq.tr!('AGCUTRYWSMKHDVBNagcutrywsmkhdvbn', 'UCGAAYRWSKMDHBVNucgaayrwskmdhbvn')
281 raise SeqError, "Cannot complement sequence type: #{self.type}"
285 # Method to determine the Hamming Distance between
286 # two Sequence objects (case insensitive).
287 def hamming_distance(seq)
288 self.seq.upcase.hamming_distance(seq.seq.upcase)
291 # Method that generates a random sequence of a given length and type.
292 def generate(length, type)
293 raise SeqError, "Cannot generate sequence length < 1: #{length}" if length <= 0
303 raise SeqError, "Unknown sequence type: #{type}"
306 seq_new = Array.new(length) { alph[rand(alph.size)] }.join("")
308 self.type = type.downcase
312 # Method to shuffle a sequence readomly inline.
314 self.seq = self.seq.split('').shuffle!.join
318 # Method that returns a subsequence of from a given start position
319 # and of a given length.
320 def subseq(start, length = self.length - start)
321 raise SeqError, "subsequence start: #{start} < 0" if start < 0
322 raise SeqError, "subsequence length: #{length} < 1" if length <= 0
323 raise SeqError, "subsequence start + length > Seq.length: #{start} + #{length} > #{self.length}" if start + length > self.length
325 stop = start + length - 1
327 seq = self.seq[start .. stop]
328 qual = self.qual[start .. stop] unless self.qual.nil?
330 Seq.new(self.seq_name, seq, self.type, qual)
333 # Method that replaces a sequence with a subsequence from a given start position
334 # and of a given length.
335 def subseq!(start, length = self.length - start)
336 raise SeqError, "subsequence start: #{start} < 0" if start < 0
337 raise SeqError, "subsequence length: #{length} < 1" if length <= 0
338 raise SeqError, "subsequence start + length > Seq.length: #{start} + #{length} > #{self.length}" if start + length > self.length
340 stop = start + length - 1
342 self.seq = self.seq[start .. stop]
343 self.qual = self.qual[start .. stop] unless self.qual.nil?
346 # Method that returns a subsequence of a given length
347 # beginning at a random position.
348 def subseq_rand(length)
349 if self.length - length + 1 == 0
352 start = rand(self.length - length + 1)
355 self.subseq(start, length)
358 def quality_trim_right(min)
359 raise SeqError, "no sequence" if self.seq.nil?
360 raise SeqError, "no quality score" if self.qual.nil?
361 raise SeqError, "minimum value: #{min} out of range #{SCORE_MIN} .. #{SCORE_MAX}" unless (SCORE_MIN .. SCORE_MAX).include? min
363 regex_right = Regexp.new("[#{(SCORE_ILLUMINA).chr}-#{(SCORE_ILLUMINA + min).chr}]+$")
365 self.qual.match(regex_right) do |m|
366 self.subseq!(0, $`.length) if $`.length > 0
372 def quality_trim_left(min)
373 raise SeqError, "no sequence" if self.seq.nil?
374 raise SeqError, "no quality score" if self.qual.nil?
375 raise SeqError, "minimum value: #{min} out of range #{SCORE_MIN} .. #{SCORE_MAX}" unless (SCORE_MIN .. SCORE_MAX).include? min
377 regex_left = Regexp.new("^[#{(SCORE_ILLUMINA).chr}-#{(SCORE_ILLUMINA + min).chr}]+")
379 self.qual.match(regex_left) do |m|
380 self.subseq!(m.to_s.length, self.length - m.to_s.length) if self.length - m.to_s.length > 0
386 def quality_trim(min)
387 self.quality_trim_right(min)
388 self.quality_trim_left(min)
392 # Method that returns the residue compositions of a sequence in
393 # a hash where the key is the residue and the value is the residue
398 self.seq.upcase.each_char do |char|
405 # Method that returns the length of the longest homopolymeric stretch
406 # found in a sequence.
407 def homopol_max(min = 1)
408 return 0 if self.seq.nil? or self.seq.empty?
412 self.seq.upcase.scan(/A{#{min},}|T{#{min},}|G{#{min},}|C{#{min},}|N{#{min},}/) do |match|
414 min = match.size > min ? match.size : min
417 return 0 unless found
422 # Method that returns the percentage of hard masked residues
423 # or N's in a sequence.
425 ((self.seq.upcase.scan("N").size.to_f / (self.len - self.indels).to_f) * 100).round(2)
428 # Method that returns the percentage of soft masked residues
429 # or lower cased residues in a sequence.
431 ((self.seq.scan(/[a-z]/).size.to_f / (self.len - self.indels).to_f) * 100).round(2)
434 # Hard masks sequence residues where the corresponding quality score
435 # is below a given cutoff.
436 def mask_seq_hard!(cutoff)
437 seq = self.seq.upcase
441 scores.each_char do |score|
442 seq[i] = 'N' if score.ord - SCORE_ILLUMINA < cutoff
449 # Soft masks sequence residues where the corresponding quality score
450 # is below a given cutoff.
451 def mask_seq_soft!(cutoff)
452 seq = self.seq.upcase
456 scores.each_char do |score|
457 seq[i] = seq[i].downcase if score.ord - SCORE_ILLUMINA < cutoff
464 # Method to convert the quality scores from a specified base
466 def convert_phred2illumina!
467 self.qual.gsub!(/./) do |score|
468 score_phred = score.ord - SCORE_PHRED
469 raise SeqError, "Bad Phred score: #{score} (#{score_phred})" unless (0 .. 41).include? score_phred
470 score_illumina = score_phred + SCORE_ILLUMINA
471 score = score_illumina.chr
475 # Method to convert the quality scores from Solexa odd/ratio to
477 def convert_solexa2illumina!
478 self.qual.gsub!(/./) do |score|
479 score = solexa_char2illumina_char(score)
485 # Method to convert a Solexa score (odd ratio) to
486 # a phred (probability) integer score.
487 def solexa2phred(score)
488 (10.0 * Math.log(10.0 ** (score / 10.0) + 1.0, 10)).to_i
491 # Method to convert a Solexa score encoded using base
492 # 64 ASCII to a Phred score encoded using base 64 ASCII.
493 def solexa_char2illumina_char(char)
494 score_solexa = char.ord - 64
495 score_phred = solexa2phred(score_solexa)
496 (score_phred + 64).chr