]> git.donarmstrong.com Git - biopieces.git/blob - code_ruby/lib/maasha/seq.rb
added Class method Seq.new_bp to seq.rb
[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
40 # Error class for all exceptions to do with Seq.
41 class SeqError < StandardError; end
42
43 class Seq
44   #include Patscan
45   include PatternMatcher
46
47   attr_accessor :seq_name, :seq, :type, :qual
48
49   # Class method to instantiate a new Sequence object given
50   # a Biopiece record.
51   def self.new_bp(record)
52     seq_name = record[:SEQ_NAME]
53     seq      = record[:SEQ]
54     type     = record[:SEQ_TYPE]
55     qual     = record[:SCORES]
56
57     self.new(seq_name, seq, type, qual)
58   end
59
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
63
64     case type.downcase
65     when /dna/     then alph = DNA
66     when /rna/     then alph = RNA
67     when /protein/ then alph = PROTEIN
68     else
69       raise SeqError, "Unknown sequence type: #{type}"
70     end
71
72     oligos = [""]
73
74     (1 .. length).each do
75       list = []
76
77       oligos.each do |oligo|
78         alph.each do |char|
79           list << oligo + char
80         end
81       end
82
83       oligos = list
84     end
85
86     oligos
87   end
88
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)
95     @seq_name = seq_name
96     @seq      = seq
97     @type     = type
98     @qual     = qual
99   end
100
101   # Method that guesses and returns the sequence type
102   # by inspecting the first 100 residues.
103   def type_guess
104     raise SeqError, "Guess failed: sequence is nil" if self.seq.nil?
105
106     case self.seq[0 ... 100].downcase
107     when /[flpqie]/ then return "protein"
108     when /[u]/      then return "rna"
109     else                 return "dna"
110     end
111   end
112
113   # Method that guesses and sets the sequence type
114   # by inspecting the first 100 residues.
115   def type_guess!
116     self.type = self.type_guess
117   end
118
119   # Returns the length of a sequence.
120   def length
121     self.seq.nil? ? 0 : self.seq.length
122   end
123
124   alias :len :length
125
126   # Return the number indels in a sequence.
127   def indels
128     regex = Regexp.new(/[#{Regexp.escape(INDELS.join(""))}]/)
129     self.seq.scan(regex).size
130   end
131
132   # Method that returns true is a given sequence type is DNA.
133   def is_dna?
134     self.type == 'dna'
135   end
136
137   # Method that returns true is a given sequence type is RNA.
138   def is_rna?
139     self.type == 'rna'
140   end
141
142   # Method that returns true is a given sequence type is protein.
143   def is_protein?
144     self.type == 'protein'
145   end
146
147   # Method to transcribe DNA to RNA.
148   def 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?
151     self.type = 'rna'
152     self.seq.tr!('Tt','Uu')
153   end
154
155   # Method to reverse-transcribe RNA to DNA.
156   def 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?
159
160     self.type = 'dna'
161     self.seq.tr!('Uu','Tt')
162   end
163
164   # Method that given a Seq entry returns a Biopieces record (a hash).
165   def to_bp
166     raise SeqError, "Missing seq_name" if self.seq_name.nil?
167     raise SeqError, "Missing seq"      if self.seq.nil?
168
169     record             = {}
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
174     record
175   end
176
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?
181
182     seq_name = self.seq_name
183     seq      = self.seq
184
185     unless wrap.nil?
186       seq.gsub!(/(.{#{wrap}})/) do |match|
187         match << $/
188       end
189
190       seq.chomp!
191     end
192
193     ">" + seq_name + $/ + seq + $/
194   end
195
196   # Method that given a Seq entry returns a FASTQ entry (a string).
197   def to_fastq
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?
201
202     seq_name = self.seq_name
203     seq      = self.seq
204     qual     = self.qual
205
206     "@" + seq_name + $/ + seq + $/ + "+" + $/ + qual + $/
207   end
208
209   # Method that generates a unique key for a
210   # DNA sequence and return this key as a Fixnum.
211   def to_key
212     key = 0
213     
214     self.seq.upcase.each_char do |char|
215       key <<= 2
216       
217       case 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}"
223       end
224     end
225     
226     key
227   end
228
229   # Method to reverse complement sequence.
230   def reverse_complement
231     self.reverse
232     self.complement
233   end
234
235   alias :revcomp :reverse_complement
236
237   # Method to reverse the sequence.
238   def reverse
239     self.seq.reverse!
240   end
241
242   # Method that complements sequence including ambiguity codes.
243   def complement
244     raise SeqError, "Cannot complement 0 length sequence" if self.length == 0
245
246     if self.is_dna?
247       self.seq.tr!( 'AGCUTRYWSMKHDVBNagcutrywsmkhdvbn', 'TCGAAYRWSKMDHBVNtcgaayrwskmdhbvn' )
248     elsif self.is_rna?
249       self.seq.tr!( 'AGCUTRYWSMKHDVBNagcutrywsmkhdvbn', 'UCGAAYRWSKMDHBVNucgaayrwskmdhbvn' )
250     else
251       raise SeqError, "Cannot complement sequence type: #{self.type}"
252     end
253   end
254
255   # Method to determine the Hamming Distance between
256   # two Sequence objects (case insensitive).
257   def hamming_distance(seq)
258     self.seq.upcase.hamming_distance(seq.seq.upcase)
259   end
260
261   # Method that generates a random sequence of a given length and type.
262   def generate(length, type)
263     raise SeqError, "Cannot generate sequence length < 1: #{length}" if length <= 0
264
265     case type.downcase
266     when "dna"
267       alph = DNA
268     when "rna"
269       alph = RNA
270     when "protein"
271       alph = PROTEIN
272     else
273       raise SeqError, "Unknown sequence type: #{type}"
274     end
275
276     seq_new   = Array.new(length) { alph[rand(alph.size)] }.join("")
277     self.seq  = seq_new
278     self.type = type.downcase
279     seq_new
280   end
281
282   # Method that returns a subsequence of from a given start position
283   # and of a given length.
284   def subseq(start, length = self.length - start)
285     raise SeqError, "subsequence start: #{start} < 0"                                                if start  < 0
286     raise SeqError, "subsequence length: #{length} < 1"                                              if length <= 0
287     raise SeqError, "subsequence start + length > Seq.length: #{start} + #{length} > #{self.length}" if start + length > self.length
288
289     stop = start + length - 1
290
291     seq  = self.seq[start .. stop]
292     qual = self.qual[start .. stop] unless self.qual.nil?
293
294     Seq.new(self.seq_name, seq, self.type, qual)
295   end
296
297   # Method that replaces a sequence with a subsequence from a given start position
298   # and of a given length.
299   def subseq!(start, length = self.length - start)
300     raise SeqError, "subsequence start: #{start} < 0"                                                if start  < 0
301     raise SeqError, "subsequence length: #{length} < 1"                                              if length <= 0
302     raise SeqError, "subsequence start + length > Seq.length: #{start} + #{length} > #{self.length}" if start + length > self.length
303
304     stop = start + length - 1
305
306     self.seq  = self.seq[start .. stop]
307     self.qual = self.qual[start .. stop] unless self.qual.nil?
308   end
309
310   # Method that returns a subsequence of a given length
311   # beginning at a random position.
312   def subseq_rand(length)
313     if self.length - length + 1 == 0
314       start = 0
315     else
316       start = rand(self.length - length + 1)
317     end
318
319     self.subseq(start, length)
320   end
321
322   # Method that returns the residue compositions of a sequence in
323   # a hash where the key is the residue and the value is the residue
324   # count.
325   def composition
326     comp = Hash.new(0);
327
328     self.seq.upcase.each_char do |char|
329       comp[char] += 1
330     end
331
332     comp
333   end
334
335   # Method that returns the length of the longest homopolymeric stretch
336   # found in a sequence.
337   def homopol_max(min = 1)
338     return 0 if self.seq.nil? or self.seq.empty?
339
340     found = false
341
342     self.seq.upcase.scan(/A{#{min},}|T{#{min},}|G{#{min},}|C{#{min},}|N{#{min},}/) do |match|
343       found = true
344       min   = match.size > min ? match.size : min
345     end
346
347     return 0 unless found
348  
349     min
350   end
351
352   # Method that returns the percentage of hard masked residues
353   # or N's in a sequence.
354   def hard_mask
355     ((self.seq.upcase.scan("N").size.to_f / (self.len - self.indels).to_f) * 100).round(2)
356   end
357
358   # Method that returns the percentage of soft masked residues
359   # or lower cased residues in a sequence.
360   def soft_mask
361     ((self.seq.scan(/[a-z]/).size.to_f / (self.len - self.indels).to_f) * 100).round(2)
362   end
363
364   # Method to convert the quality scores from a specified base
365   # to another base.
366   def convert_phred2illumina!
367     self.qual.gsub!(/./) do |score|
368       score_phred  = score.ord - SCORE_PHRED
369       raise SeqError, "Bad Phred score: #{score} (#{score_phred})" unless (0 .. 41).include? score_phred
370       score_illumina = score_phred + SCORE_ILLUMINA
371       score          = score_illumina.chr
372     end
373   end
374
375   # Method to convert the quality scores from Solexa odd/ratio to
376   # Illumina format.
377   def convert_solexa2illumina!
378     self.qual.gsub!(/./) do |score|
379       score = solexa_char2illumina_char(score)
380     end
381   end
382
383   private
384
385   # Method to convert a Solexa score (odd ratio) to
386   # a phred (probability) integer score.
387   def solexa2phred(score)
388     (10.0 * Math.log(10.0 ** (score / 10.0) + 1.0, 10)).to_i
389   end
390
391   # Method to convert a Solexa score encoded using base
392   # 64 ASCII to a Phred score encoded using base 64 ASCII.
393   def solexa_char2illumina_char(char)
394     score_solexa = char.ord - 64
395     score_phred  = solexa2phred(score_solexa)
396     (score_phred + 64).chr
397   end
398 end
399
400 __END__