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/seq/digest'
29 require 'maasha/seq/trim'
31 #require 'maasha/patscan'
36 PROTEIN = %w[f l s y c w p h q r i m t n k v a d e g]
39 # Quality scores bases
44 # Error class for all exceptions to do with Seq.
45 class SeqError < StandardError; end
49 include PatternMatcher
54 attr_accessor :seq_name, :seq, :type, :qual
56 # Class method to instantiate a new Sequence object given
58 def self.new_bp(record)
59 seq_name = record[:SEQ_NAME]
61 type = record[:SEQ_TYPE]
62 qual = record[:SCORES]
64 self.new(seq_name, seq, type, qual)
67 # Class method that generates all possible oligos of a specifed length and type.
68 def self.generate_oligos(length, type)
69 raise SeqError, "Cannot generate negative oligo length: #{length}" if length <= 0
72 when /dna/ then alph = DNA
73 when /rna/ then alph = RNA
74 when /protein/ then alph = PROTEIN
76 raise SeqError, "Unknown sequence type: #{type}"
84 oligos.each do |oligo|
96 # Initialize a sequence object with the following arguments:
97 # - seq_name: Name of the sequence.
98 # - seq: The sequence.
99 # - type: The sequence type - DNA, RNA, or protein
100 # - qual: An Illumina type quality scores string.
101 def initialize(seq_name = nil, seq = nil, type = nil, qual = nil)
108 # Method that guesses and returns the sequence type
109 # by inspecting the first 100 residues.
111 raise SeqError, "Guess failed: sequence is nil" if self.seq.nil?
113 case self.seq[0 ... 100].downcase
114 when /[flpqie]/ then return "protein"
115 when /[u]/ then return "rna"
120 # Method that guesses and sets the sequence type
121 # by inspecting the first 100 residues.
123 self.type = self.type_guess
126 # Returns the length of a sequence.
128 self.seq.nil? ? 0 : self.seq.length
133 # Return the number indels in a sequence.
135 regex = Regexp.new(/[#{Regexp.escape(INDELS.join(""))}]/)
136 self.seq.scan(regex).size
139 # Method to remove indels from seq and qual if qual.
142 self.seq.delete!(Regexp.escape(INDELS.join('')))
144 na_seq = NArray.to_na(self.seq, "byte")
145 na_qual = NArray.to_na(self.qual, "byte")
146 mask = NArray.byte(self.length)
149 mask += na_seq.eq(c.ord)
154 self.seq = na_seq[mask].to_s
155 self.qual = na_qual[mask].to_s
161 # Method that returns true is a given sequence type is DNA.
166 # Method that returns true is a given sequence type is RNA.
171 # Method that returns true is a given sequence type is protein.
173 self.type == 'protein'
176 # Method to transcribe DNA to RNA.
178 raise SeqError, "Cannot transcribe 0 length sequence" if self.length == 0
179 raise SeqError, "Cannot transcribe sequence type: #{self.type}" unless self.is_dna?
181 self.seq.tr!('Tt','Uu')
184 # Method to reverse-transcribe RNA to DNA.
186 raise SeqError, "Cannot reverse-transcribe 0 length sequence" if self.length == 0
187 raise SeqError, "Cannot reverse-transcribe sequence type: #{self.type}" unless self.is_rna?
190 self.seq.tr!('Uu','Tt')
193 # Method that given a Seq entry returns a Biopieces record (a hash).
195 raise SeqError, "Missing seq_name" if self.seq_name.nil?
196 raise SeqError, "Missing seq" if self.seq.nil?
199 record[:SEQ_NAME] = self.seq_name
200 record[:SEQ] = self.seq
201 record[:SEQ_LEN] = self.length
202 record[:SCORES] = self.qual if self.qual
206 # Method that given a Seq entry returns a FASTA entry (a string).
207 def to_fasta(wrap = nil)
208 raise SeqError, "Missing seq_name" if self.seq_name.nil? or self.seq_name == ''
209 raise SeqError, "Missing seq" if self.seq.nil? or self.seq.empty?
211 seq_name = self.seq_name.to_s
215 seq.gsub!(/(.{#{wrap}})/) do |match|
222 ">" + seq_name + $/ + seq + $/
225 # Method that given a Seq entry returns a FASTQ entry (a string).
227 raise SeqError, "Missing seq_name" if self.seq_name.nil?
228 raise SeqError, "Missing seq" if self.seq.nil?
229 raise SeqError, "Missing qual" if self.qual.nil?
231 seq_name = self.seq_name.to_s
233 qual = self.qual.to_s
235 "@" + seq_name + $/ + seq + $/ + "+" + $/ + qual + $/
238 # Method that generates a unique key for a
239 # DNA sequence and return this key as a Fixnum.
243 self.seq.upcase.each_char do |char|
247 when 'A' then key |= 0
248 when 'C' then key |= 1
249 when 'G' then key |= 2
250 when 'T' then key |= 3
251 else raise SeqError, "Bad residue: #{char}"
258 # Method to reverse complement sequence.
259 def reverse_complement
265 alias :revcomp :reverse_complement
267 # Method to reverse the sequence.
270 self.qual.reverse! if self.qual
274 # Method that complements sequence including ambiguity codes.
276 raise SeqError, "Cannot complement 0 length sequence" if self.length == 0
279 self.seq.tr!('AGCUTRYWSMKHDVBNagcutrywsmkhdvbn', 'TCGAAYRWSKMDHBVNtcgaayrwskmdhbvn')
281 self.seq.tr!('AGCUTRYWSMKHDVBNagcutrywsmkhdvbn', 'UCGAAYRWSKMDHBVNucgaayrwskmdhbvn')
283 raise SeqError, "Cannot complement sequence type: #{self.type}"
287 # Method to determine the Hamming Distance between
288 # two Sequence objects (case insensitive).
289 def hamming_distance(seq)
290 self.seq.upcase.hamming_distance(seq.seq.upcase)
293 # Method that generates a random sequence of a given length and type.
294 def generate(length, type)
295 raise SeqError, "Cannot generate sequence length < 1: #{length}" if length <= 0
305 raise SeqError, "Unknown sequence type: #{type}"
308 seq_new = Array.new(length) { alph[rand(alph.size)] }.join("")
310 self.type = type.downcase
314 # Method to shuffle a sequence readomly inline.
316 self.seq = self.seq.split('').shuffle!.join
320 # Method that returns a subsequence of from a given start position
321 # and of a given length.
322 def subseq(start, length = self.length - start)
323 raise SeqError, "subsequence start: #{start} < 0" if start < 0
324 raise SeqError, "subsequence length: #{length} < 0" if length < 0
325 raise SeqError, "subsequence start + length > Seq.length: #{start} + #{length} > #{self.length}" if start + length > self.length
330 qual = "" unless self.qual.nil?
332 stop = start + length - 1
334 seq = self.seq[start .. stop]
335 qual = self.qual[start .. stop] unless self.qual.nil?
339 Seq.new(self.seq_name, seq, self.type, qual)
342 # Method that replaces a sequence with a subsequence from a given start position
343 # and of a given length.
344 def subseq!(start, length = self.length - start)
345 raise SeqError, "subsequence start: #{start} < 0" if start < 0
346 raise SeqError, "subsequence length: #{length} < 0" if length < 0
347 raise SeqError, "subsequence start + length > Seq.length: #{start} + #{length} > #{self.length}" if start + length > self.length
351 self.qual = "" unless self.qual.nil?
353 stop = start + length - 1
355 self.seq = self.seq[start .. stop]
356 self.qual = self.qual[start .. stop] unless self.qual.nil?
362 # Method that returns a subsequence of a given length
363 # beginning at a random position.
364 def subseq_rand(length)
365 if self.length - length + 1 == 0
368 start = rand(self.length - length + 1)
371 self.subseq(start, length)
374 # Method that returns the residue compositions of a sequence in
375 # a hash where the key is the residue and the value is the residue
380 self.seq.upcase.each_char do |char|
387 # Method that returns the length of the longest homopolymeric stretch
388 # found in a sequence.
389 def homopol_max(min = 1)
390 return 0 if self.seq.nil? or self.seq.empty?
394 self.seq.upcase.scan(/A{#{min},}|T{#{min},}|G{#{min},}|C{#{min},}|N{#{min},}/) do |match|
396 min = match.size > min ? match.size : min
399 return 0 unless found
404 # Method that returns the percentage of hard masked residues
405 # or N's in a sequence.
407 ((self.seq.upcase.scan("N").size.to_f / (self.len - self.indels).to_f) * 100).round(2)
410 # Method that returns the percentage of soft masked residues
411 # or lower cased residues in a sequence.
413 ((self.seq.scan(/[a-z]/).size.to_f / (self.len - self.indels).to_f) * 100).round(2)
416 # Hard masks sequence residues where the corresponding quality score
417 # is below a given cutoff.
418 def mask_seq_hard_old(cutoff)
419 seq = self.seq.upcase
423 scores.each_char do |score|
424 seq[i] = 'N' if score.ord - SCORE_BASE < cutoff
431 # Hard masks sequence residues where the corresponding quality score
432 # is below a given cutoff.
433 def mask_seq_hard!(cutoff)
434 raise SeqError, "seq is nil" if self.seq.nil?
435 raise SeqError, "qual is nil" if self.qual.nil?
436 raise SeqError, "cufoff value: #{cutoff} out of range #{SCORE_MIN} .. #{SCORE_MAX}" unless (SCORE_MIN .. SCORE_MAX).include? cutoff
438 na_seq = NArray.to_na(self.seq, "byte")
439 na_qual = NArray.to_na(self.qual, "byte")
440 mask = (na_qual - SCORE_BASE) < cutoff
441 mask *= na_seq.ne("-".ord)
443 na_seq[mask] = 'N'.ord
445 self.seq = na_seq.to_s
450 # Soft masks sequence residues where the corresponding quality score
451 # is below a given cutoff.
452 def mask_seq_soft!(cutoff)
453 raise SeqError, "seq is nil" if self.seq.nil?
454 raise SeqError, "qual is nil" if self.qual.nil?
455 raise SeqError, "cufoff value: #{cutoff} out of range #{SCORE_MIN} .. #{SCORE_MAX}" unless (SCORE_MIN .. SCORE_MAX).include? cutoff
457 na_seq = NArray.to_na(self.seq, "byte")
458 na_qual = NArray.to_na(self.qual, "byte")
459 mask = (na_qual - SCORE_BASE) < cutoff
460 mask *= na_seq.ne("-".ord)
462 na_seq[mask] ^= ' '.ord
464 self.seq = na_seq.to_s
469 # Method to convert quality scores inbetween formats.
470 # Sanger base 33, range 0-40
471 # Solexa base 64, range -5-40
472 # Illumina13 base 64, range 0-40
473 # Illumina15 base 64, range 3-40
474 # Illumina18 base 33, range 0-41
475 def convert_scores!(from, to)
477 na_qual = NArray.to_na(self.qual, "byte")
480 when "sanger" then na_qual -= 33
481 when "solexa" then na_qual -= 64
482 when "illumina13" then na_qual -= 64
483 when "illumina15" then na_qual -= 64
484 when "illumina18" then na_qual -= 33
485 else raise SeqError, "unknown quality score encoding: #{from}"
489 when "sanger" then na_qual += 33
490 when "solexa" then na_qual += 64
491 when "illumina13" then na_qual += 64
492 when "illumina15" then na_qual += 64
493 when "illumina18" then na_qual += 33
494 else raise SeqError, "unknown quality score encoding: #{from}"
497 self.qual = na_qual.to_s