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