]> git.donarmstrong.com Git - biopieces.git/blob - code_ruby/lib/maasha/seq.rb
disabling backtrack which causes compile error
[biopieces.git] / code_ruby / lib / maasha / seq.rb
1 # Copyright (C) 2007-2012 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/bits'
26 #require 'maasha/seq/backtrack'
27 require 'maasha/seq/digest'
28 #require 'maasha/seq/patscan'
29 require 'maasha/seq/patternmatcher'
30 require 'maasha/seq/trim'
31 require 'narray'
32
33 # Residue alphabets
34 DNA     = %w[a t c g]
35 RNA     = %w[a u c g]
36 PROTEIN = %w[f l s y c w p h q r i m t n k v a d e g]
37 INDELS  = %w[. - _ ~]
38
39 # Translation table 11
40 # (http://www.ncbi.nlm.nih.gov/Taxonomy/taxonomyhome.html/index.cgi?chapter=cgencodes#SG11)
41 #   AAs  = FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG
42 # Starts = ---M---------------M------------MMMM---------------M------------
43 # Base1  = TTTTTTTTTTTTTTTTCCCCCCCCCCCCCCCCAAAAAAAAAAAAAAAAGGGGGGGGGGGGGGGG
44 # Base2  = TTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGG
45 # Base3  = TCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAG
46 TRANS_TAB11_START = {
47   "TTG" => "M", "CTG" => "M", "ATT" => "M", "ATC" => "M",
48   "ATA" => "M", "ATG" => "M", "GTG" => "M"
49 }
50
51 TRANS_TAB11 = {
52   "TTT" => "F", "TCT" => "S", "TAT" => "Y", "TGT" => "C",
53   "TTC" => "F", "TCC" => "S", "TAC" => "Y", "TGC" => "C",
54   "TTA" => "L", "TCA" => "S", "TAA" => "*", "TGA" => "*",
55   "TTG" => "L", "TCG" => "S", "TAG" => "*", "TGG" => "W",
56   "CTT" => "L", "CCT" => "P", "CAT" => "H", "CGT" => "R",
57   "CTC" => "L", "CCC" => "P", "CAC" => "H", "CGC" => "R",
58   "CTA" => "L", "CCA" => "P", "CAA" => "Q", "CGA" => "R",
59   "CTG" => "L", "CCG" => "P", "CAG" => "Q", "CGG" => "R",
60   "ATT" => "I", "ACT" => "T", "AAT" => "N", "AGT" => "S",
61   "ATC" => "I", "ACC" => "T", "AAC" => "N", "AGC" => "S",
62   "ATA" => "I", "ACA" => "T", "AAA" => "K", "AGA" => "R",
63   "ATG" => "M", "ACG" => "T", "AAG" => "K", "AGG" => "R",
64   "GTT" => "V", "GCT" => "A", "GAT" => "D", "GGT" => "G",
65   "GTC" => "V", "GCC" => "A", "GAC" => "D", "GGC" => "G",
66   "GTA" => "V", "GCA" => "A", "GAA" => "E", "GGA" => "G",
67   "GTG" => "V", "GCG" => "A", "GAG" => "E", "GGG" => "G"
68 }
69
70 # Quality scores bases
71 SCORE_BASE = 64
72 SCORE_MIN  = 0
73 SCORE_MAX  = 40
74
75 # Error class for all exceptions to do with Seq.
76 class SeqError < StandardError; end
77
78 class Seq
79   #include Patscan
80   include PatternMatcher
81   include Digest
82   include Trim
83
84   attr_accessor :seq_name, :seq, :type, :qual
85
86   # Class method to instantiate a new Sequence object given
87   # a Biopiece record.
88   def self.new_bp(record)
89     seq_name = record[:SEQ_NAME]
90     seq      = record[:SEQ]
91     type     = record[:SEQ_TYPE]
92     qual     = record[:SCORES]
93
94     self.new(seq_name, seq, type, qual)
95   end
96
97   # Class method that generates all possible oligos of a specifed length and type.
98   def self.generate_oligos(length, type)
99     raise SeqError, "Cannot generate negative oligo length: #{length}" if length <= 0
100
101     case type.downcase
102     when /dna/     then alph = DNA
103     when /rna/     then alph = RNA
104     when /protein/ then alph = PROTEIN
105     else
106       raise SeqError, "Unknown sequence type: #{type}"
107     end
108
109     oligos = [""]
110
111     (1 .. length).each do
112       list = []
113
114       oligos.each do |oligo|
115         alph.each do |char|
116           list << oligo + char
117         end
118       end
119
120       oligos = list
121     end
122
123     oligos
124   end
125
126   # Initialize a sequence object with the following arguments:
127   # - seq_name: Name of the sequence.
128   # - seq: The sequence.
129   # - type: The sequence type - DNA, RNA, or protein
130   # - qual: An Illumina type quality scores string.
131   def initialize(seq_name = nil, seq = nil, type = nil, qual = nil)
132     @seq_name = seq_name
133     @seq      = seq
134     @type     = type
135     @qual     = qual
136   end
137
138   # Method that guesses and returns the sequence type
139   # by inspecting the first 100 residues.
140   def type_guess
141     raise SeqError, "Guess failed: sequence is nil" if self.seq.nil?
142
143     case self.seq[0 ... 100].downcase
144     when /[flpqie]/ then return "protein"
145     when /[u]/      then return "rna"
146     else                 return "dna"
147     end
148   end
149
150   # Method that guesses and sets the sequence type
151   # by inspecting the first 100 residues.
152   def type_guess!
153     self.type = self.type_guess
154   end
155
156   # Returns the length of a sequence.
157   def length
158     self.seq.nil? ? 0 : self.seq.length
159   end
160
161   alias :len :length
162
163   # Return the number indels in a sequence.
164   def indels
165     regex = Regexp.new(/[#{Regexp.escape(INDELS.join(""))}]/)
166     self.seq.scan(regex).size
167   end
168
169   # Method to remove indels from seq and qual if qual.
170   def indels_remove
171     if self.qual.nil?
172       self.seq.delete!(Regexp.escape(INDELS.join('')))
173     else
174       na_seq  = NArray.to_na(self.seq, "byte")
175       na_qual = NArray.to_na(self.qual, "byte")
176       mask    = NArray.byte(self.length)
177
178       INDELS.each do |c|
179         mask += na_seq.eq(c.ord)
180       end
181
182       mask = mask.eq(0)
183
184       self.seq  = na_seq[mask].to_s
185       self.qual = na_qual[mask].to_s
186     end
187
188     self
189   end
190
191   # Method that returns true is a given sequence type is DNA.
192   def is_dna?
193     self.type == 'dna'
194   end
195
196   # Method that returns true is a given sequence type is RNA.
197   def is_rna?
198     self.type == 'rna'
199   end
200
201   # Method that returns true is a given sequence type is protein.
202   def is_protein?
203     self.type == 'protein'
204   end
205
206   # Method to transcribe DNA to RNA.
207   def to_rna
208     raise SeqError, "Cannot transcribe 0 length sequence" if self.length == 0
209     raise SeqError, "Cannot transcribe sequence type: #{self.type}" unless self.is_dna?
210     self.type = 'rna'
211     self.seq.tr!('Tt','Uu')
212   end
213
214   # Method to reverse-transcribe RNA to DNA.
215   def to_dna
216     raise SeqError, "Cannot reverse-transcribe 0 length sequence" if self.length == 0
217     raise SeqError, "Cannot reverse-transcribe sequence type: #{self.type}" unless self.is_rna?
218
219     self.type = 'dna'
220     self.seq.tr!('Uu','Tt')
221   end
222
223   # Method to translate a DNA sequence to protein.
224   def translate!(trans_tab = 11)
225     raise SeqError, "Sequence type must be 'dna' - not #{self.type}" unless self.type == 'dna'
226     raise SeqError, "Sequence length must be a multiplum of 3 - was: #{self.length}" unless (self.length % 3) == 0
227
228     case trans_tab
229     when 11
230       codon_start_hash = TRANS_TAB11_START
231       codon_hash       = TRANS_TAB11
232     else
233       raise SeqError, "Unknown translation table: #{trans_tab}"
234     end
235
236     codon  = self.seq[0 ... 3].upcase
237
238     aa = codon_start_hash[codon]
239
240     raise SeqError, "Unknown start codon: #{codon}" if aa.nil?
241
242     protein = aa
243
244     i = 3
245
246     while i < self.length
247       codon = self.seq[i ... i + 3].upcase
248
249       aa = codon_hash[codon]
250
251       raise SeqError, "Unknown codon: #{codon}" if aa.nil?
252
253       protein << aa
254
255       i += 3
256     end
257
258     self.seq  = protein
259     self.qual = nil
260     self.type = "protein"
261
262     self
263   end
264
265   alias :to_protein! :translate!
266
267   def translate(trans_tab = 11)
268     self.dup.translate!(trans_tab)
269   end
270
271   alias :to_protein :translate
272
273   # Method that given a Seq entry returns a Biopieces record (a hash).
274   def to_bp
275     raise SeqError, "Missing seq_name" if self.seq_name.nil?
276     raise SeqError, "Missing seq"      if self.seq.nil?
277
278     record             = {}
279     record[:SEQ_NAME] = self.seq_name
280     record[:SEQ]      = self.seq
281     record[:SEQ_LEN]  = self.length
282     record[:SCORES]   = self.qual if self.qual
283     record
284   end
285
286   # Method that given a Seq entry returns a FASTA entry (a string).
287   def to_fasta(wrap = nil)
288     raise SeqError, "Missing seq_name" if self.seq_name.nil? or self.seq_name == ''
289     raise SeqError, "Missing seq"      if self.seq.nil?      or self.seq.empty?
290
291     seq_name = self.seq_name.to_s
292     seq      = self.seq.to_s
293
294     unless wrap.nil?
295       seq.gsub!(/(.{#{wrap}})/) do |match|
296         match << $/
297       end
298
299       seq.chomp!
300     end
301
302     ">" + seq_name + $/ + seq + $/
303   end
304
305   # Method that given a Seq entry returns a FASTQ entry (a string).
306   def to_fastq
307     raise SeqError, "Missing seq_name" if self.seq_name.nil?
308     raise SeqError, "Missing seq"      if self.seq.nil?
309     raise SeqError, "Missing qual"     if self.qual.nil?
310
311     seq_name = self.seq_name.to_s
312     seq      = self.seq.to_s
313     qual     = self.qual.to_s
314
315     "@" + seq_name + $/ + seq + $/ + "+" + $/ + qual + $/
316   end
317
318   # Method that generates a unique key for a
319   # DNA sequence and return this key as a Fixnum.
320   def to_key
321     key = 0
322     
323     self.seq.upcase.each_char do |char|
324       key <<= 2
325       
326       case char
327       when 'A' then key |= 0
328       when 'C' then key |= 1
329       when 'G' then key |= 2
330       when 'T' then key |= 3
331       else raise SeqError, "Bad residue: #{char}"
332       end
333     end
334     
335     key
336   end
337
338   # Method to reverse complement sequence.
339   def reverse_complement
340     self.reverse
341     self.complement
342     self
343   end
344
345   alias :revcomp :reverse_complement
346
347   # Method to reverse the sequence.
348   def reverse
349     self.seq.reverse!
350     self.qual.reverse! if self.qual
351     self
352   end
353
354   # Method that complements sequence including ambiguity codes.
355   def complement
356     raise SeqError, "Cannot complement 0 length sequence" if self.length == 0
357
358     if self.is_dna?
359       self.seq.tr!('AGCUTRYWSMKHDVBNagcutrywsmkhdvbn', 'TCGAAYRWSKMDHBVNtcgaayrwskmdhbvn')
360     elsif self.is_rna?
361       self.seq.tr!('AGCUTRYWSMKHDVBNagcutrywsmkhdvbn', 'UCGAAYRWSKMDHBVNucgaayrwskmdhbvn')
362     else
363       raise SeqError, "Cannot complement sequence type: #{self.type}"
364     end
365   end
366
367   # Method to determine the Hamming Distance between
368   # two Sequence objects (case insensitive).
369   def hamming_distance(seq)
370     self.seq.upcase.hamming_distance(seq.seq.upcase)
371   end
372
373   # Method that generates a random sequence of a given length and type.
374   def generate(length, type)
375     raise SeqError, "Cannot generate sequence length < 1: #{length}" if length <= 0
376
377     case type.downcase
378     when "dna"
379       alph = DNA
380     when "rna"
381       alph = RNA
382     when "protein"
383       alph = PROTEIN
384     else
385       raise SeqError, "Unknown sequence type: #{type}"
386     end
387
388     seq_new   = Array.new(length) { alph[rand(alph.size)] }.join("")
389     self.seq  = seq_new
390     self.type = type.downcase
391     seq_new
392   end
393
394   # Method to shuffle a sequence readomly inline.
395   def shuffle!
396     self.seq = self.seq.split('').shuffle!.join
397     self
398   end
399
400   # Method that returns a subsequence of from a given start position
401   # and of a given length.
402   def subseq(start, length = self.length - start)
403     raise SeqError, "subsequence start: #{start} < 0"                                                if start  < 0
404     raise SeqError, "subsequence length: #{length} < 0"                                              if length < 0
405     raise SeqError, "subsequence start + length > Seq.length: #{start} + #{length} > #{self.length}" if start + length > self.length
406
407     if length == 0
408       seq  = ""
409       qual = "" unless self.qual.nil?
410     else
411       stop = start + length - 1
412
413       seq  = self.seq[start .. stop]
414       qual = self.qual[start .. stop] unless self.qual.nil?
415     end
416
417     Seq.new(self.seq_name, seq, self.type, qual)    # TODO changed self.seq_name.dup to self.seq_name -> consequence?
418   end
419
420   # Method that replaces a sequence with a subsequence from a given start position
421   # and of a given length.
422   def subseq!(start, length = self.length - start)
423     s = subseq(start, length)
424
425     self.seq_name = s.seq_name
426     self.seq      = s.seq
427     self.type     = s.type
428     self.qual     = s.qual
429
430     self
431   end
432
433   # Method that returns a subsequence of a given length
434   # beginning at a random position.
435   def subseq_rand(length)
436     if self.length - length + 1 == 0
437       start = 0
438     else
439       start = rand(self.length - length + 1)
440     end
441
442     self.subseq(start, length)
443   end
444
445   # Method that returns the residue compositions of a sequence in
446   # a hash where the key is the residue and the value is the residue
447   # count.
448   def composition
449     comp = Hash.new(0);
450
451     self.seq.upcase.each_char do |char|
452       comp[char] += 1
453     end
454
455     comp
456   end
457
458   # Method that returns the length of the longest homopolymeric stretch
459   # found in a sequence.
460   def homopol_max(min = 1)
461     return 0 if self.seq.nil? or self.seq.empty?
462
463     found = false
464
465     self.seq.upcase.scan(/A{#{min},}|T{#{min},}|G{#{min},}|C{#{min},}|N{#{min},}/) do |match|
466       found = true
467       min   = match.size > min ? match.size : min
468     end
469
470     return 0 unless found
471  
472     min
473   end
474
475   # Method that returns the percentage of hard masked residues
476   # or N's in a sequence.
477   def hard_mask
478     ((self.seq.upcase.scan("N").size.to_f / (self.len - self.indels).to_f) * 100).round(2)
479   end
480
481   # Method that returns the percentage of soft masked residues
482   # or lower cased residues in a sequence.
483   def soft_mask
484     ((self.seq.scan(/[a-z]/).size.to_f / (self.len - self.indels).to_f) * 100).round(2)
485   end
486
487   # Hard masks sequence residues where the corresponding quality score
488   # is below a given cutoff.
489   def mask_seq_hard_old(cutoff)
490     seq    = self.seq.upcase
491     scores = self.qual
492     i      = 0
493
494     scores.each_char do |score|
495       seq[i] = 'N' if score.ord - SCORE_BASE < cutoff
496       i += 1 
497     end
498
499     self.seq = seq
500   end
501
502   # Hard masks sequence residues where the corresponding quality score
503   # is below a given cutoff.
504   def mask_seq_hard!(cutoff)
505     raise SeqError, "seq is nil"  if self.seq.nil?
506     raise SeqError, "qual is nil" if self.qual.nil?
507     raise SeqError, "cufoff value: #{cutoff} out of range #{SCORE_MIN} .. #{SCORE_MAX}" unless (SCORE_MIN .. SCORE_MAX).include? cutoff
508
509     na_seq  = NArray.to_na(self.seq, "byte")
510     na_qual = NArray.to_na(self.qual, "byte")
511     mask    = (na_qual - SCORE_BASE) < cutoff
512     mask   *= na_seq.ne("-".ord)
513
514     na_seq[mask] = 'N'.ord
515
516     self.seq = na_seq.to_s
517
518     self
519   end
520
521   # Soft masks sequence residues where the corresponding quality score
522   # is below a given cutoff.
523   def mask_seq_soft!(cutoff)
524     raise SeqError, "seq is nil"  if self.seq.nil?
525     raise SeqError, "qual is nil" if self.qual.nil?
526     raise SeqError, "cufoff value: #{cutoff} out of range #{SCORE_MIN} .. #{SCORE_MAX}" unless (SCORE_MIN .. SCORE_MAX).include? cutoff
527
528     na_seq  = NArray.to_na(self.seq, "byte")
529     na_qual = NArray.to_na(self.qual, "byte")
530     mask    = (na_qual - SCORE_BASE) < cutoff
531     mask   *= na_seq.ne("-".ord)
532
533     na_seq[mask] ^= ' '.ord
534
535     self.seq = na_seq.to_s
536
537     self
538   end
539
540   # Method that determines if a quality score string can be
541   # absolutely identified as base 33.
542   def qual_base33?
543     self.qual.match(/[!-:]/)
544   end
545
546   # Method that determines if a quality score string can be
547   # absolutely identified as base 64.
548   def qual_base64?
549     self.qual.match(/[K-h]/)
550   end
551
552   # Method to convert quality scores inbetween formats.
553   # Sanger     base 33, range  0-40 
554   # 454        base 64, range  0-40 
555   # Solexa     base 64, range -5-40 
556   # Illumina13 base 64, range  0-40 
557   # Illumina15 base 64, range  3-40 
558   # Illumina18 base 33, range  0-41 
559   def convert_scores!(from, to)
560     unless from == to
561       na_qual = NArray.to_na(self.qual, "byte")
562
563       case from.downcase
564       when "sanger"     then na_qual -= 33
565       when "454"        then na_qual -= 64
566       when "solexa"     then na_qual -= 64
567       when "illumina13" then na_qual -= 64
568       when "illumina15" then na_qual -= 64
569       when "illumina18" then na_qual -= 33
570       else raise SeqError, "unknown quality score encoding: #{from}"
571       end
572
573       case to.downcase
574       when "sanger"     then na_qual += 33
575       when "454"        then na_qual += 64
576       when "solexa"     then na_qual += 64
577       when "illumina13" then na_qual += 64
578       when "illumina15" then na_qual += 64
579       when "illumina18" then na_qual += 33
580       else raise SeqError, "unknown quality score encoding: #{from}"
581       end
582
583       self.qual = na_qual.to_s
584     end
585
586     self
587   end
588
589   # Method to calculate and return the mean quality score.
590   def scores_mean
591     raise SeqError, "Missing qual in entry" if self.qual.nil?
592
593     na_qual = NArray.to_na(self.qual, "byte")
594     na_qual -= SCORE_BASE
595     na_qual.mean
596   end
597
598   # Method to find open reading frames (ORFs).
599   def each_orf(size_min, size_max, start_codons, stop_codons, pick_longest = false)
600     orfs    = []
601     pos_beg = 0
602
603     regex_start = Regexp.new(start_codons.join('|'), true)
604     regex_stop  = Regexp.new(stop_codons.join('|'), true)
605
606     while pos_beg and pos_beg < self.length - size_min
607       if pos_beg = self.seq.index(regex_start, pos_beg)
608         if pos_end = self.seq.index(regex_stop, pos_beg)
609           length = (pos_end - pos_beg) + 3
610
611           if (length % 3) == 0
612             if size_min <= length and length <= size_max
613               subseq = self.subseq(pos_beg, length)
614
615               orfs << [subseq, pos_beg, pos_end + 3]
616             end
617           end
618         end
619
620         pos_beg += 1
621       end
622     end
623
624     if pick_longest
625       orf_hash = {}
626
627       orfs.each { |orf| orf_hash[orf.last] = orf unless orf_hash[orf.last] }
628
629       orfs = orf_hash.values
630     end
631
632     if block_given?
633       orfs.each { |orf| yield orf }
634     else
635       return orfs
636     end
637   end
638 end
639
640 __END__