]> git.donarmstrong.com Git - biopieces.git/blob - code_ruby/lib/maasha/seq.rb
changed layout of ruby source
[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/patscan'
28
29 # Residue alphabets
30 DNA     = %w[a t c g]
31 RNA     = %w[a u c g]
32 PROTEIN = %w[f l s y c w p h q r i m t n k v a d e g]
33 INDELS  = %w[. - _ ~]
34
35 # Quality scores bases
36 SCORE_PHRED    = 33
37 SCORE_ILLUMINA = 64
38
39 # Error class for all exceptions to do with Seq.
40 class SeqError < StandardError; end
41
42 class Seq
43   #include Patscan
44   include PatternMatcher
45
46   attr_accessor :seq_name, :seq, :type, :qual
47
48   # Method that generates all possible oligos of a specifed length and type.
49   def self.generate_oligos(length, type)
50     raise SeqError, "Cannot generate negative oligo length: #{length}" if length <= 0
51
52     case type.downcase
53     when /dna/     then alph = DNA
54     when /rna/     then alph = RNA
55     when /protein/ then alph = PROTEIN
56     else
57       raise SeqError, "Unknown sequence type: #{type}"
58     end
59
60     oligos = [""]
61
62     (1 .. length).each do
63       list = []
64
65       oligos.each do |oligo|
66         alph.each do |char|
67           list << oligo + char
68         end
69       end
70
71       oligos = list
72     end
73
74     oligos
75   end
76
77   # Initialize a sequence object with the following arguments:
78   # - seq_name: Name of the sequence.
79   # - seq: The sequence.
80   # - type: The sequence type - DNA, RNA, or protein
81   # - qual: An Illumina type quality scores string.
82   def initialize(seq_name = nil, seq = nil, type = nil, qual = nil)
83     @seq_name = seq_name
84     @seq      = seq
85     @type     = type
86     @qual     = qual
87   end
88
89   # Returns the length of a sequence.
90   def length
91     self.seq.nil? ? 0 : self.seq.length
92   end
93
94   alias :len :length
95
96   # Return the number indels in a sequence.
97   def indels
98     regex = Regexp.new(/[#{Regexp.escape(INDELS.join(""))}]/)
99     self.seq.scan(regex).size
100   end
101
102   # Method that returns true is a given sequence type is DNA.
103   def is_dna?
104     self.type == 'dna'
105   end
106
107   # Method that returns true is a given sequence type is RNA.
108   def is_rna?
109     self.type == 'rna'
110   end
111
112   # Method that returns true is a given sequence type is protein.
113   def is_protein?
114     self.type == 'protein'
115   end
116
117   # Method to transcribe DNA to RNA.
118   def to_rna
119     raise SeqError, "Cannot transcribe 0 length sequence" if self.length == 0
120     raise SeqError, "Cannot transcribe sequence type: #{self.type}" unless self.is_dna?
121     self.type = 'rna'
122     self.seq.tr!('Tt','Uu')
123   end
124
125   # Method to reverse-transcribe RNA to DNA.
126   def to_dna
127     raise SeqError, "Cannot reverse-transcribe 0 length sequence" if self.length == 0
128     raise SeqError, "Cannot reverse-transcribe sequence type: #{self.type}" unless self.is_rna?
129
130     self.type = 'dna'
131     self.seq.tr!('Uu','Tt')
132   end
133
134   # Method that given a Seq entry returns a Biopieces record (a hash).
135   def to_bp
136     raise SeqError, "Missing seq_name" if self.seq_name.nil?
137     raise SeqError, "Missing seq"      if self.seq.nil?
138
139     record             = {}
140     record[:SEQ_NAME] = self.seq_name
141     record[:SEQ]      = self.seq
142     record[:SEQ_LEN]  = self.length
143     record[:SCORES]   = self.qual if self.qual
144     record
145   end
146
147   # Method that given a Seq entry returns a FASTA entry (a string).
148   def to_fasta(wrap = nil)
149     raise SeqError, "Missing seq_name" if self.seq_name.nil?
150     raise SeqError, "Missing seq"      if self.seq.nil?
151
152     seq_name = self.seq_name
153     seq      = self.seq
154
155     unless wrap.nil?
156       seq.gsub!(/(.{#{wrap}})/) do |match|
157         match << "\n"
158       end
159
160       seq.chomp!
161     end
162
163     ">#{seq_name}\n#{seq}\n"
164   end
165
166   # Method that generates a unique key for a
167   # DNA sequence and return this key as a Fixnum.
168   def to_key
169     key = 0
170     
171     self.seq.upcase.each_char do |char|
172       key <<= 2
173       
174       case char
175       when 'A' then key |= 0
176       when 'C' then key |= 1
177       when 'G' then key |= 2
178       when 'T' then key |= 3
179       else raise SeqError, "Bad residue: #{char}"
180       end
181     end
182     
183     key
184   end
185
186   # Method to reverse complement sequence.
187   def reverse_complement
188     self.reverse
189     self.complement
190   end
191
192   alias :revcomp :reverse_complement
193
194   # Method to reverse the sequence.
195   def reverse
196     self.seq.reverse!
197   end
198
199   # Method that complements sequence including ambiguity codes.
200   def complement
201     raise SeqError, "Cannot complement 0 length sequence" if self.length == 0
202
203     if self.is_dna?
204       self.seq.tr!( 'AGCUTRYWSMKHDVBNagcutrywsmkhdvbn', 'TCGAAYRWSKMDHBVNtcgaayrwskmdhbvn' )
205     elsif self.is_rna?
206       self.seq.tr!( 'AGCUTRYWSMKHDVBNagcutrywsmkhdvbn', 'UCGAAYRWSKMDHBVNucgaayrwskmdhbvn' )
207     else
208       raise SeqError, "Cannot complement sequence type: #{self.type}"
209     end
210   end
211
212   # Method that generates a random sequence of a given length and type.
213   def generate(length, type)
214     raise SeqError, "Cannot generate sequence length < 1: #{length}" if length <= 0
215
216     case type.downcase
217     when "dna"
218       alph = DNA
219     when "rna"
220       alph = RNA
221     when "protein"
222       alph = PROTEIN
223     else
224       raise SeqError, "Unknown sequence type: #{type}"
225     end
226
227     seq_new   = Array.new(length) { alph[rand(alph.size)] }.join("")
228     self.seq  = seq_new
229     self.type = type.downcase
230     seq_new
231   end
232
233   # Method that returns a subsequence of from a given start position
234   # and of a given length.
235   def subseq(start, length = self.length - start)
236     raise SeqError, "subsequence start: #{start} < 0"                                                if start  < 0
237     raise SeqError, "subsequence length: #{length} < 1"                                              if length <= 0
238     raise SeqError, "subsequence start + length > Seq.length: #{start} + #{length} > #{self.length}" if start + length > self.length
239
240     stop = start + length - 1
241
242     seq  = self.seq[start .. stop]
243     qual = self.qual[start .. stop] unless self.qual.nil?
244
245     Seq.new(self.seq_name, seq, self.type, qual)
246   end
247
248   # Method that replaces a sequence with a subsequence from a given start position
249   # and of a given length.
250   def subseq!(start, length = self.length - start)
251     raise SeqError, "subsequence start: #{start} < 0"                                                if start  < 0
252     raise SeqError, "subsequence length: #{length} < 1"                                              if length <= 0
253     raise SeqError, "subsequence start + length > Seq.length: #{start} + #{length} > #{self.length}" if start + length > self.length
254
255     stop = start + length - 1
256
257     self.seq  = self.seq[start .. stop]
258     self.qual = self.qual[start .. stop] unless self.qual.nil?
259   end
260
261   # Method that returns a subsequence of a given length
262   # beginning at a random position.
263   def subseq_rand(length)
264     if self.length - length + 1 == 0
265       start = 0
266     else
267       start = rand(self.length - length + 1)
268     end
269
270     self.subseq(start, length)
271   end
272
273   # Method that returns the residue compositions of a sequence in
274   # a hash where the key is the residue and the value is the residue
275   # count.
276   def composition
277     comp = Hash.new(0);
278
279     self.seq.upcase.each_char do |char|
280       comp[char] += 1
281     end
282
283     comp
284   end
285
286   # Method that returns the length of the longest homopolymeric stretch
287   # found in a sequence.
288   def homopol_max(min = 1)
289     return 0 if self.seq.nil? or self.seq.empty?
290
291     found = false
292
293     self.seq.upcase.scan(/A{#{min},}|T{#{min},}|G{#{min},}|C{#{min},}|N{#{min},}/) do |match|
294       found = true
295       min   = match.size > min ? match.size : min
296     end
297
298     return 0 unless found
299  
300     min
301   end
302
303   # Method that returns the percentage of hard masked residues
304   # or N's in a sequence.
305   def hard_mask
306     ((self.seq.upcase.scan("N").size.to_f / (self.len - self.indels).to_f) * 100).round(2)
307   end
308
309   # Method that returns the percentage of soft masked residues
310   # or lower cased residues in a sequence.
311   def soft_mask
312     ((self.seq.scan(/[a-z]/).size.to_f / (self.len - self.indels).to_f) * 100).round(2)
313   end
314
315   # Method to convert the quality scores from a specified base
316   # to another base.
317   def convert_phred2illumina!
318     self.qual.gsub!(/./) do |score|
319       score_phred  = score.ord - SCORE_PHRED
320       raise SeqError, "Bad Phred score: #{score} (#{score_phred})" unless (0 .. 40).include? score_phred
321       score_illumina = score_phred + SCORE_ILLUMINA
322       score          = score_illumina.chr
323     end
324   end
325
326   # Method to convert the quality scores from Solexa odd/ratio to
327   # Illumina format.
328   def convert_solexa2illumina!
329     self.qual.gsub!(/./) do |score|
330       score = solexa_char2illumina_char(score)
331     end
332   end
333
334   private
335
336   # Method to convert a Solexa score (odd ratio) to
337   # a phred (probability) integer score.
338   def solexa2phred(score)
339     (10.0 * Math.log(10.0 ** (score / 10.0) + 1.0, 10)).to_i
340   end
341
342   # Method to convert a Solexa score encoded using base
343   # 64 ASCII to a Phred score encoded using base 64 ASCII.
344   def solexa_char2illumina_char(char)
345     score_solexa = char.ord - 64
346     score_phred  = solexa2phred(score_solexa)
347     (score_phred + 64).chr
348   end
349 end
350
351 __END__