]> git.donarmstrong.com Git - biopieces.git/blob - code_ruby/lib/maasha/seq.rb
fixed bug in seq.to_fasta
[biopieces.git] / code_ruby / lib / maasha / seq.rb
1 # Copyright (C) 2007-2011 Martin A. Hansen.
2
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.
7
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.
12
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.
16
17 # http://www.gnu.org/copyleft/gpl.html
18
19 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
20
21 # This software is part of the Biopieces framework (www.biopieces.org).
22
23 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
24
25 require 'maasha/digest'
26 require 'maasha/patternmatcher'
27 require 'maasha/bits'
28 #require 'maasha/patscan'
29
30 # Residue alphabets
31 DNA     = %w[a t c g]
32 RNA     = %w[a u c g]
33 PROTEIN = %w[f l s y c w p h q r i m t n k v a d e g]
34 INDELS  = %w[. - _ ~]
35
36 # Quality scores bases
37 SCORE_PHRED    = 33
38 SCORE_ILLUMINA = 64
39 SCORE_MIN      = 0
40 SCORE_MAX      = 40
41
42 # Error class for all exceptions to do with Seq.
43 class SeqError < StandardError; end
44
45 class Seq
46   #include Patscan
47   include PatternMatcher
48
49   attr_accessor :seq_name, :seq, :type, :qual
50
51   # Class method to instantiate a new Sequence object given
52   # a Biopiece record.
53   def self.new_bp(record)
54     seq_name = record[:SEQ_NAME]
55     seq      = record[:SEQ]
56     type     = record[:SEQ_TYPE]
57     qual     = record[:SCORES]
58
59     self.new(seq_name, seq, type, qual)
60   end
61
62   # Class method that generates all possible oligos of a specifed length and type.
63   def self.generate_oligos(length, type)
64     raise SeqError, "Cannot generate negative oligo length: #{length}" if length <= 0
65
66     case type.downcase
67     when /dna/     then alph = DNA
68     when /rna/     then alph = RNA
69     when /protein/ then alph = PROTEIN
70     else
71       raise SeqError, "Unknown sequence type: #{type}"
72     end
73
74     oligos = [""]
75
76     (1 .. length).each do
77       list = []
78
79       oligos.each do |oligo|
80         alph.each do |char|
81           list << oligo + char
82         end
83       end
84
85       oligos = list
86     end
87
88     oligos
89   end
90
91   # Initialize a sequence object with the following arguments:
92   # - seq_name: Name of the sequence.
93   # - seq: The sequence.
94   # - type: The sequence type - DNA, RNA, or protein
95   # - qual: An Illumina type quality scores string.
96   def initialize(seq_name = nil, seq = nil, type = nil, qual = nil)
97     @seq_name = seq_name
98     @seq      = seq
99     @type     = type
100     @qual     = qual
101   end
102
103   # Method that guesses and returns the sequence type
104   # by inspecting the first 100 residues.
105   def type_guess
106     raise SeqError, "Guess failed: sequence is nil" if self.seq.nil?
107
108     case self.seq[0 ... 100].downcase
109     when /[flpqie]/ then return "protein"
110     when /[u]/      then return "rna"
111     else                 return "dna"
112     end
113   end
114
115   # Method that guesses and sets the sequence type
116   # by inspecting the first 100 residues.
117   def type_guess!
118     self.type = self.type_guess
119   end
120
121   # Returns the length of a sequence.
122   def length
123     self.seq.nil? ? 0 : self.seq.length
124   end
125
126   alias :len :length
127
128   # Return the number indels in a sequence.
129   def indels
130     regex = Regexp.new(/[#{Regexp.escape(INDELS.join(""))}]/)
131     self.seq.scan(regex).size
132   end
133
134   # Method that returns true is a given sequence type is DNA.
135   def is_dna?
136     self.type == 'dna'
137   end
138
139   # Method that returns true is a given sequence type is RNA.
140   def is_rna?
141     self.type == 'rna'
142   end
143
144   # Method that returns true is a given sequence type is protein.
145   def is_protein?
146     self.type == 'protein'
147   end
148
149   # Method to transcribe DNA to RNA.
150   def to_rna
151     raise SeqError, "Cannot transcribe 0 length sequence" if self.length == 0
152     raise SeqError, "Cannot transcribe sequence type: #{self.type}" unless self.is_dna?
153     self.type = 'rna'
154     self.seq.tr!('Tt','Uu')
155   end
156
157   # Method to reverse-transcribe RNA to DNA.
158   def to_dna
159     raise SeqError, "Cannot reverse-transcribe 0 length sequence" if self.length == 0
160     raise SeqError, "Cannot reverse-transcribe sequence type: #{self.type}" unless self.is_rna?
161
162     self.type = 'dna'
163     self.seq.tr!('Uu','Tt')
164   end
165
166   # Method that given a Seq entry returns a Biopieces record (a hash).
167   def to_bp
168     raise SeqError, "Missing seq_name" if self.seq_name.nil?
169     raise SeqError, "Missing seq"      if self.seq.nil?
170
171     record             = {}
172     record[:SEQ_NAME] = self.seq_name
173     record[:SEQ]      = self.seq
174     record[:SEQ_LEN]  = self.length
175     record[:SCORES]   = self.qual if self.qual
176     record
177   end
178
179   # Method that given a Seq entry returns a FASTA entry (a string).
180   def to_fasta(wrap = nil)
181     raise SeqError, "Missing seq_name" if self.seq_name.nil? or self.seq_name == ''
182     raise SeqError, "Missing seq"      if self.seq.nil?      or self.seq.empty?
183
184     seq_name = self.seq_name.to_s
185     seq      = self.seq.to_s
186
187     unless wrap.nil?
188       seq.gsub!(/(.{#{wrap}})/) do |match|
189         match << $/
190       end
191
192       seq.chomp!
193     end
194
195     ">" + seq_name + $/ + seq + $/
196   end
197
198   # Method that given a Seq entry returns a FASTQ entry (a string).
199   def to_fastq
200     raise SeqError, "Missing seq_name" if self.seq_name.nil?
201     raise SeqError, "Missing seq"      if self.seq.nil?
202     raise SeqError, "Missing qual"     if self.qual.nil?
203
204     seq_name = self.seq_name.to_s
205     seq      = self.seq.to_s
206     qual     = self.qual.to_s
207
208     "@" + seq_name + $/ + seq + $/ + "+" + $/ + qual + $/
209   end
210
211   # Method that generates a unique key for a
212   # DNA sequence and return this key as a Fixnum.
213   def to_key
214     key = 0
215     
216     self.seq.upcase.each_char do |char|
217       key <<= 2
218       
219       case char
220       when 'A' then key |= 0
221       when 'C' then key |= 1
222       when 'G' then key |= 2
223       when 'T' then key |= 3
224       else raise SeqError, "Bad residue: #{char}"
225       end
226     end
227     
228     key
229   end
230
231   # Method to reverse complement sequence.
232   def reverse_complement
233     self.reverse
234     self.complement
235     self
236   end
237
238   alias :revcomp :reverse_complement
239
240   # Method to reverse the sequence.
241   def reverse
242     self.seq.reverse!
243     self.qual.reverse! if self.qual
244     self
245   end
246
247   # Method that complements sequence including ambiguity codes.
248   def complement
249     raise SeqError, "Cannot complement 0 length sequence" if self.length == 0
250
251     if self.is_dna?
252       self.seq.tr!('AGCUTRYWSMKHDVBNagcutrywsmkhdvbn', 'TCGAAYRWSKMDHBVNtcgaayrwskmdhbvn')
253     elsif self.is_rna?
254       self.seq.tr!('AGCUTRYWSMKHDVBNagcutrywsmkhdvbn', 'UCGAAYRWSKMDHBVNucgaayrwskmdhbvn')
255     else
256       raise SeqError, "Cannot complement sequence type: #{self.type}"
257     end
258   end
259
260   # Method to determine the Hamming Distance between
261   # two Sequence objects (case insensitive).
262   def hamming_distance(seq)
263     self.seq.upcase.hamming_distance(seq.seq.upcase)
264   end
265
266   # Method that generates a random sequence of a given length and type.
267   def generate(length, type)
268     raise SeqError, "Cannot generate sequence length < 1: #{length}" if length <= 0
269
270     case type.downcase
271     when "dna"
272       alph = DNA
273     when "rna"
274       alph = RNA
275     when "protein"
276       alph = PROTEIN
277     else
278       raise SeqError, "Unknown sequence type: #{type}"
279     end
280
281     seq_new   = Array.new(length) { alph[rand(alph.size)] }.join("")
282     self.seq  = seq_new
283     self.type = type.downcase
284     seq_new
285   end
286
287   # Method to shuffle a sequence readomly inline.
288   def shuffle!
289     self.seq = self.seq.split('').shuffle!.join
290     self
291   end
292
293   # Method that returns a subsequence of from a given start position
294   # and of a given length.
295   def subseq(start, length = self.length - start)
296     raise SeqError, "subsequence start: #{start} < 0"                                                if start  < 0
297     raise SeqError, "subsequence length: #{length} < 1"                                              if length <= 0
298     raise SeqError, "subsequence start + length > Seq.length: #{start} + #{length} > #{self.length}" if start + length > self.length
299
300     stop = start + length - 1
301
302     seq  = self.seq[start .. stop]
303     qual = self.qual[start .. stop] unless self.qual.nil?
304
305     Seq.new(self.seq_name, seq, self.type, qual)
306   end
307
308   # Method that replaces a sequence with a subsequence from a given start position
309   # and of a given length.
310   def subseq!(start, length = self.length - start)
311     raise SeqError, "subsequence start: #{start} < 0"                                                if start  < 0
312     raise SeqError, "subsequence length: #{length} < 1"                                              if length <= 0
313     raise SeqError, "subsequence start + length > Seq.length: #{start} + #{length} > #{self.length}" if start + length > self.length
314
315     stop = start + length - 1
316
317     self.seq  = self.seq[start .. stop]
318     self.qual = self.qual[start .. stop] unless self.qual.nil?
319   end
320
321   # Method that returns a subsequence of a given length
322   # beginning at a random position.
323   def subseq_rand(length)
324     if self.length - length + 1 == 0
325       start = 0
326     else
327       start = rand(self.length - length + 1)
328     end
329
330     self.subseq(start, length)
331   end
332
333   def quality_trim_right(min)
334     raise SeqError, "no sequence"      if self.seq.nil?
335     raise SeqError, "no quality score" if self.qual.nil?
336     raise SeqError, "minimum value: #{min} out of range #{SCORE_MIN} .. #{SCORE_MAX}" unless (SCORE_MIN .. SCORE_MAX).include? min
337
338     regex_right = Regexp.new("[#{(SCORE_ILLUMINA).chr}-#{(SCORE_ILLUMINA + min).chr}]+$")
339
340     self.qual.match(regex_right) do |m|
341       self.subseq!(0, $`.length) if $`.length > 0
342     end
343
344     self
345   end
346
347   def quality_trim_left(min)
348     raise SeqError, "no sequence"      if self.seq.nil?
349     raise SeqError, "no quality score" if self.qual.nil?
350     raise SeqError, "minimum value: #{min} out of range #{SCORE_MIN} .. #{SCORE_MAX}" unless (SCORE_MIN .. SCORE_MAX).include? min
351
352     regex_left  = Regexp.new("^[#{(SCORE_ILLUMINA).chr}-#{(SCORE_ILLUMINA + min).chr}]+")
353
354     self.qual.match(regex_left) do |m|
355       self.subseq!(m.to_s.length, self.length - m.to_s.length) if self.length - m.to_s.length > 0
356     end
357
358     self
359   end
360
361   def quality_trim(min)
362     self.quality_trim_right(min)
363     self.quality_trim_left(min)
364     self
365   end
366
367   # Method that returns the residue compositions of a sequence in
368   # a hash where the key is the residue and the value is the residue
369   # count.
370   def composition
371     comp = Hash.new(0);
372
373     self.seq.upcase.each_char do |char|
374       comp[char] += 1
375     end
376
377     comp
378   end
379
380   # Method that returns the length of the longest homopolymeric stretch
381   # found in a sequence.
382   def homopol_max(min = 1)
383     return 0 if self.seq.nil? or self.seq.empty?
384
385     found = false
386
387     self.seq.upcase.scan(/A{#{min},}|T{#{min},}|G{#{min},}|C{#{min},}|N{#{min},}/) do |match|
388       found = true
389       min   = match.size > min ? match.size : min
390     end
391
392     return 0 unless found
393  
394     min
395   end
396
397   # Method that returns the percentage of hard masked residues
398   # or N's in a sequence.
399   def hard_mask
400     ((self.seq.upcase.scan("N").size.to_f / (self.len - self.indels).to_f) * 100).round(2)
401   end
402
403   # Method that returns the percentage of soft masked residues
404   # or lower cased residues in a sequence.
405   def soft_mask
406     ((self.seq.scan(/[a-z]/).size.to_f / (self.len - self.indels).to_f) * 100).round(2)
407   end
408
409   # Method to convert the quality scores from a specified base
410   # to another base.
411   def convert_phred2illumina!
412     self.qual.gsub!(/./) do |score|
413       score_phred  = score.ord - SCORE_PHRED
414       raise SeqError, "Bad Phred score: #{score} (#{score_phred})" unless (0 .. 41).include? score_phred
415       score_illumina = score_phred + SCORE_ILLUMINA
416       score          = score_illumina.chr
417     end
418   end
419
420   # Method to convert the quality scores from Solexa odd/ratio to
421   # Illumina format.
422   def convert_solexa2illumina!
423     self.qual.gsub!(/./) do |score|
424       score = solexa_char2illumina_char(score)
425     end
426   end
427
428   private
429
430   # Method to convert a Solexa score (odd ratio) to
431   # a phred (probability) integer score.
432   def solexa2phred(score)
433     (10.0 * Math.log(10.0 ** (score / 10.0) + 1.0, 10)).to_i
434   end
435
436   # Method to convert a Solexa score encoded using base
437   # 64 ASCII to a Phred score encoded using base 64 ASCII.
438   def solexa_char2illumina_char(char)
439     score_solexa = char.ord - 64
440     score_phred  = solexa2phred(score_solexa)
441     (score_phred + 64).chr
442   end
443 end
444
445 __END__