]> git.donarmstrong.com Git - biopieces.git/blob - code_ruby/lib/maasha/seq.rb
d8a73d31ba8d660fa08bb6aac9c0c24f91137151
[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/digest'
27 require 'maasha/seq/trim'
28 require 'narray'
29
30 autoload :BackTrack, 'maasha/seq/backtrack.rb'
31 autoload :Dynamic,   'maasha/seq/dynamic.rb'
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
71 # Error class for all exceptions to do with Seq.
72 class SeqError < StandardError; end
73
74 class Seq
75   # Quality scores bases
76   SCORE_BASE = 33
77   SCORE_MIN  = 0
78   SCORE_MAX  = 40
79
80   include Digest
81   include Trim
82
83   attr_accessor :seq_name, :seq, :type, :qual
84
85   # Class method to instantiate a new Sequence object given
86   # a Biopiece record.
87   def self.new_bp(record)
88     seq_name = record[:SEQ_NAME]
89     seq      = record[:SEQ]
90     type     = record[:SEQ_TYPE].to_sym if record[:SEQ_TYPE]
91     qual     = record[:SCORES]
92
93     self.new(seq_name, seq, type, qual)
94   end
95
96   # Class method that generates all possible oligos of a specifed length and type.
97   def self.generate_oligos(length, type)
98     raise SeqError, "Cannot generate negative oligo length: #{length}" if length <= 0
99
100     case type.downcase
101     when :dna     then alph = DNA
102     when :rna     then alph = RNA
103     when :protein then alph = PROTEIN
104     else
105       raise SeqError, "Unknown sequence type: #{type}"
106     end
107
108     oligos = [""]
109
110     (1 .. length).each do
111       list = []
112
113       oligos.each do |oligo|
114         alph.each do |char|
115           list << oligo + char
116         end
117       end
118
119       oligos = list
120     end
121
122     oligos
123   end
124
125   # Initialize a sequence object with the following arguments:
126   # - seq_name: Name of the sequence.
127   # - seq: The sequence.
128   # - type: The sequence type - DNA, RNA, or protein
129   # - qual: An Illumina type quality scores string.
130   def initialize(seq_name = nil, seq = nil, type = nil, qual = nil)
131     @seq_name = seq_name
132     @seq      = seq
133     @type     = type
134     @qual     = qual
135   end
136
137   # Method that guesses and returns the sequence type
138   # by inspecting the first 100 residues.
139   def type_guess
140     raise SeqError, "Guess failed: sequence is nil" if self.seq.nil?
141
142     case self.seq[0 ... 100].downcase
143     when /[flpqie]/ then return :protein
144     when /[u]/      then return :rna
145     else                 return :dna
146     end
147   end
148
149   # Method that guesses and sets the sequence type
150   # by inspecting the first 100 residues.
151   def type_guess!
152     self.type = self.type_guess
153     self
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     self.type = :dna
219     self.seq.tr!('Uu','Tt')
220   end
221
222   # Method to translate a DNA sequence to protein.
223   def translate!(trans_tab = 11)
224     raise SeqError, "Sequence type must be 'dna' - not #{self.type}" unless self.type == :dna
225     raise SeqError, "Sequence length must be a multiplum of 3 - was: #{self.length}" unless (self.length % 3) == 0
226
227     case trans_tab
228     when 11
229       codon_start_hash = TRANS_TAB11_START
230       codon_hash       = TRANS_TAB11
231     else
232       raise SeqError, "Unknown translation table: #{trans_tab}"
233     end
234
235     codon  = self.seq[0 ... 3].upcase
236
237     aa = codon_start_hash[codon]
238
239     raise SeqError, "Unknown start codon: #{codon}" if aa.nil?
240
241     protein = aa
242
243     i = 3
244
245     while i < self.length
246       codon = self.seq[i ... i + 3].upcase
247
248       aa = codon_hash[codon]
249
250       raise SeqError, "Unknown codon: #{codon}" if aa.nil?
251
252       protein << aa
253
254       i += 3
255     end
256
257     self.seq  = protein
258     self.qual = nil
259     self.type = :protein
260
261     self
262   end
263
264   alias :to_protein! :translate!
265
266   def translate(trans_tab = 11)
267     self.dup.translate!(trans_tab)
268   end
269
270   alias :to_protein :translate
271
272   # Method that given a Seq entry returns a Biopieces record (a hash).
273   def to_bp
274     raise SeqError, "Missing seq_name" if self.seq_name.nil?
275     raise SeqError, "Missing seq"      if self.seq.nil?
276
277     record             = {}
278     record[:SEQ_NAME] = self.seq_name
279     record[:SEQ]      = self.seq
280     record[:SEQ_LEN]  = self.length
281     record[:SCORES]   = self.qual if self.qual
282     record
283   end
284
285   # Method that given a Seq entry returns a FASTA entry (a string).
286   def to_fasta(wrap = nil)
287     raise SeqError, "Missing seq_name" if self.seq_name.nil? or self.seq_name == ''
288     raise SeqError, "Missing seq"      if self.seq.nil?      or self.seq.empty?
289
290     seq_name = self.seq_name.to_s
291     seq      = self.seq.to_s
292
293     unless wrap.nil?
294       seq.gsub!(/(.{#{wrap}})/) do |match|
295         match << $/
296       end
297
298       seq.chomp!
299     end
300
301     ">" + seq_name + $/ + seq + $/
302   end
303
304   # Method that given a Seq entry returns a FASTQ entry (a string).
305   def to_fastq
306     raise SeqError, "Missing seq_name" if self.seq_name.nil?
307     raise SeqError, "Missing seq"      if self.seq.nil?
308     raise SeqError, "Missing qual"     if self.qual.nil?
309
310     seq_name = self.seq_name.to_s
311     seq      = self.seq.to_s
312     qual     = self.qual.to_s
313
314     "@" + seq_name + $/ + seq + $/ + "+" + $/ + qual + $/
315   end
316
317   # Method that generates a unique key for a
318   # DNA sequence and return this key as a Fixnum.
319   def to_key
320     key = 0
321     
322     self.seq.upcase.each_char do |char|
323       key <<= 2
324       
325       case char
326       when 'A' then key |= 0
327       when 'C' then key |= 1
328       when 'G' then key |= 2
329       when 'T' then key |= 3
330       else raise SeqError, "Bad residue: #{char}"
331       end
332     end
333     
334     key
335   end
336
337   # Method to reverse the sequence.
338   def reverse
339     Seq.new(self.seq_name, self.seq.reverse, self.type, self.qual ? self.qual.reverse : self.qual)
340   end
341
342   # Method to reverse the sequence.
343   def reverse!
344     self.seq.reverse!
345     self.qual.reverse! if self.qual
346     self
347   end
348
349   # Method that complements sequence including ambiguity codes.
350   def complement
351     raise SeqError, "Cannot complement 0 length sequence" if self.length == 0
352
353     entry          = Seq.new
354     entry.seq_name = self.seq_name
355     entry.type     = self.type
356     entry.qual     = self.qual
357
358     if self.is_dna?
359       entry.seq = self.seq.tr('AGCUTRYWSMKHDVBNagcutrywsmkhdvbn', 'TCGAAYRWSKMDHBVNtcgaayrwskmdhbvn')
360     elsif self.is_rna?
361       entry.seq = self.seq.tr('AGCUTRYWSMKHDVBNagcutrywsmkhdvbn', 'UCGAAYRWSKMDHBVNucgaayrwskmdhbvn')
362     else
363       raise SeqError, "Cannot complement sequence type: #{self.type}"
364     end
365
366     entry
367   end
368
369   # Method that complements sequence including ambiguity codes.
370   def complement!
371     raise SeqError, "Cannot complement 0 length sequence" if self.length == 0
372
373     if self.is_dna?
374       self.seq.tr!('AGCUTRYWSMKHDVBNagcutrywsmkhdvbn', 'TCGAAYRWSKMDHBVNtcgaayrwskmdhbvn')
375     elsif self.is_rna?
376       self.seq.tr!('AGCUTRYWSMKHDVBNagcutrywsmkhdvbn', 'UCGAAYRWSKMDHBVNucgaayrwskmdhbvn')
377     else
378       raise SeqError, "Cannot complement sequence type: #{self.type}"
379     end
380
381     self
382   end
383
384   # Method to determine the Hamming Distance between
385   # two Sequence objects (case insensitive).
386   def hamming_distance(seq)
387     self.seq.upcase.hamming_distance(seq.seq.upcase)
388   end
389
390   # Method that generates a random sequence of a given length and type.
391   def generate(length, type)
392     raise SeqError, "Cannot generate sequence length < 1: #{length}" if length <= 0
393
394     case type
395     when :dna     then alph = DNA
396     when :rna     then alph = RNA
397     when :protein then alph = PROTEIN
398     else
399       raise SeqError, "Unknown sequence type: #{type}"
400     end
401
402     seq_new   = Array.new(length) { alph[rand(alph.size)] }.join("")
403     self.seq  = seq_new
404     self.type = type
405     seq_new
406   end
407
408   # Method to return a new Seq object with shuffled sequence.
409   def shuffle
410     Seq.new(self.seq_name, self.seq.split('').shuffle!.join, self.type, self.qual)
411   end
412
413   # Method to shuffle a sequence randomly inline.
414   def shuffle!
415     self.seq = self.seq.split('').shuffle!.join
416     self
417   end
418
419   # Method to add two Seq objects.
420   def +(entry)
421     new_entry = Seq.new()
422     new_entry.seq  = self.seq  + entry.seq
423     new_entry.type = self.type              if self.type == entry.type
424     new_entry.qual = self.qual + entry.qual if self.qual and entry.qual
425     new_entry
426   end
427
428   # Method to concatenate sequence entries.
429   def <<(entry)
430     raise SeqError, "sequences of different types" unless self.type == entry.type
431     raise SeqError, "qual is missing in one entry" unless self.qual.class == entry.qual.class
432
433     self.seq  << entry.seq
434     self.qual << entry.qual unless entry.qual.nil?
435
436     self
437   end
438
439   # Index method for Seq objects.
440   def [](*args)
441     entry = Seq.new
442     entry.seq_name = self.seq_name
443     entry.seq      = self.seq[*args]
444     entry.type     = self.type
445     entry.qual     = self.qual[*args] unless self.qual.nil?
446
447     entry
448   end
449
450   # Index assignment method for Seq objects.
451   def []=(*args, entry)
452     self.seq[*args]  = entry.seq[*args]
453     self.qual[*args] = entry.qual[*args] unless self.qual.nil?
454
455     self
456   end
457
458   # Method that returns a subsequence of from a given start position
459   # and of a given length.
460   def subseq(start, length = self.length - start)
461     raise SeqError, "subsequence start: #{start} < 0"                                                if start  < 0
462     raise SeqError, "subsequence length: #{length} < 0"                                              if length < 0
463     raise SeqError, "subsequence start + length > Seq.length: #{start} + #{length} > #{self.length}" if start + length > self.length
464
465     if length == 0
466       seq  = ""
467       qual = "" unless self.qual.nil?
468     else
469       stop = start + length - 1
470
471       seq  = self.seq[start .. stop]
472       qual = self.qual[start .. stop] unless self.qual.nil?
473     end
474
475     seq_name = self.seq_name.nil? ? nil : self.seq_name.dup
476
477     Seq.new(seq_name, seq, self.type, qual)
478   end
479
480   # Method that replaces a sequence with a subsequence from a given start position
481   # and of a given length.
482   def subseq!(start, length = self.length - start)
483     s = subseq(start, length)
484
485     self.seq_name = s.seq_name
486     self.seq      = s.seq
487     self.type     = s.type
488     self.qual     = s.qual
489
490     self
491   end
492
493   # Method that returns a subsequence of a given length
494   # beginning at a random position.
495   def subseq_rand(length)
496     if self.length - length + 1 == 0
497       start = 0
498     else
499       start = rand(self.length - length + 1)
500     end
501
502     self.subseq(start, length)
503   end
504
505   # Method that returns the residue compositions of a sequence in
506   # a hash where the key is the residue and the value is the residue
507   # count.
508   def composition
509     comp = Hash.new(0);
510
511     self.seq.upcase.each_char do |char|
512       comp[char] += 1
513     end
514
515     comp
516   end
517
518   # Method that returns the length of the longest homopolymeric stretch
519   # found in a sequence.
520   def homopol_max(min = 1)
521     return 0 if self.seq.nil? or self.seq.empty?
522
523     found = false
524
525     self.seq.upcase.scan(/A{#{min},}|T{#{min},}|G{#{min},}|C{#{min},}|N{#{min},}/) do |match|
526       found = true
527       min   = match.size > min ? match.size : min
528     end
529
530     return 0 unless found
531  
532     min
533   end
534
535   # Method that returns the percentage of hard masked residues
536   # or N's in a sequence.
537   def hard_mask
538     ((self.seq.upcase.scan("N").size.to_f / (self.len - self.indels).to_f) * 100).round(2)
539   end
540
541   # Method that returns the percentage of soft masked residues
542   # or lower cased residues in a sequence.
543   def soft_mask
544     ((self.seq.scan(/[a-z]/).size.to_f / (self.len - self.indels).to_f) * 100).round(2)
545   end
546
547   # Hard masks sequence residues where the corresponding quality score
548   # is below a given cutoff.
549   def mask_seq_hard!(cutoff)
550     raise SeqError, "seq is nil"  if self.seq.nil?
551     raise SeqError, "qual is nil" if self.qual.nil?
552     raise SeqError, "cufoff value: #{cutoff} out of range #{SCORE_MIN} .. #{SCORE_MAX}" unless (SCORE_MIN .. SCORE_MAX).include? cutoff
553
554     na_seq  = NArray.to_na(self.seq, "byte")
555     na_qual = NArray.to_na(self.qual, "byte")
556     mask    = (na_qual - SCORE_BASE) < cutoff
557     mask   *= na_seq.ne("-".ord)
558
559     na_seq[mask] = 'N'.ord
560
561     self.seq = na_seq.to_s
562
563     self
564   end
565
566   # Soft masks sequence residues where the corresponding quality score
567   # is below a given cutoff.
568   def mask_seq_soft!(cutoff)
569     raise SeqError, "seq is nil"  if self.seq.nil?
570     raise SeqError, "qual is nil" if self.qual.nil?
571     raise SeqError, "cufoff value: #{cutoff} out of range #{SCORE_MIN} .. #{SCORE_MAX}" unless (SCORE_MIN .. SCORE_MAX).include? cutoff
572
573     na_seq  = NArray.to_na(self.seq, "byte")
574     na_qual = NArray.to_na(self.qual, "byte")
575     mask    = (na_qual - SCORE_BASE) < cutoff
576     mask   *= na_seq.ne("-".ord)
577
578     na_seq[mask] ^= ' '.ord
579
580     self.seq = na_seq.to_s
581
582     self
583   end
584
585   # Method that determines if a quality score string can be
586   # absolutely identified as base 33.
587   def qual_base33?
588     self.qual.match(/[!-:]/) ? true : false
589   end
590  
591   # Method that determines if a quality score string may be base 64.
592   def qual_base64?
593     self.qual.match(/[K-h]/) ? true : false
594   end
595
596   # Method to determine if a quality score is valid accepting only 0-40 range.
597   def qual_valid?(encoding)
598     raise SeqError, "Missing qual" if self.qual.nil?
599
600     case encoding
601     when :base_33 then return true if self.qual.match(/^[!-I]*$/)
602     when :base_64 then return true if self.qual.match(/^[@-h]*$/)
603     else raise SeqError, "unknown quality score encoding: #{encoding}"
604     end
605
606     false
607   end
608
609   # Method to coerce quality scores to be within the 0-40 range.
610   def qual_coerce!(encoding)
611     raise SeqError, "Missing qual" if self.qual.nil?
612
613     case encoding
614     when :base_33 then self.qual.tr!("[J-~]", "I")
615     when :base_64 then self.qual.tr!("[i-~]", "h")
616     else raise SeqError, "unknown quality score encoding: #{encoding}"
617     end 
618
619     self
620   end
621
622   # Method to convert quality scores.
623   def qual_convert!(from, to)
624     raise SeqError, "unknown quality score encoding: #{from}" unless from == :base_33 or from == :base_64
625     raise SeqError, "unknown quality score encoding: #{to}"   unless to   == :base_33 or to   == :base_64
626
627     if from == :base_33 and to == :base_64
628       na_qual   = NArray.to_na(self.qual, "byte")
629       na_qual  += 64 - 33
630       self.qual = na_qual.to_s
631     elsif from == :base_64 and to == :base_33
632       self.qual.tr!("[;-?]", "@")  # Handle negative Solexa values from -5 to -1 (set these to 0).
633       na_qual   = NArray.to_na(self.qual, "byte")
634       na_qual  -= 64 - 33
635       self.qual = na_qual.to_s
636     end
637
638     self
639   end
640
641   # Method to calculate and return the mean quality score.
642   def scores_mean
643     raise SeqError, "Missing qual in entry" if self.qual.nil?
644
645     na_qual = NArray.to_na(self.qual, "byte")
646     na_qual -= SCORE_BASE
647
648     na_qual.mean
649   end
650
651   # Method to find open reading frames (ORFs).
652   def each_orf(size_min, size_max, start_codons, stop_codons, pick_longest = false)
653     orfs    = []
654     pos_beg = 0
655
656     regex_start = Regexp.new(start_codons.join('|'), true)
657     regex_stop  = Regexp.new(stop_codons.join('|'), true)
658
659     while pos_beg and pos_beg < self.length - size_min
660       if pos_beg = self.seq.index(regex_start, pos_beg)
661         if pos_end = self.seq.index(regex_stop, pos_beg)
662           length = (pos_end - pos_beg) + 3
663
664           if (length % 3) == 0
665             if size_min <= length and length <= size_max
666               subseq = self.subseq(pos_beg, length)
667
668               orfs << [subseq, pos_beg, pos_end + 3]
669             end
670           end
671         end
672
673         pos_beg += 1
674       end
675     end
676
677     if pick_longest
678       orf_hash = {}
679
680       orfs.each { |orf| orf_hash[orf.last] = orf unless orf_hash[orf.last] }
681
682       orfs = orf_hash.values
683     end
684
685     if block_given?
686       orfs.each { |orf| yield orf }
687     else
688       return orfs
689     end
690   end
691 end
692
693 __END__