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