]> git.donarmstrong.com Git - biopieces.git/blob - code_ruby/lib/maasha/seq.rb
fixed SCORE_BASE global var
[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 = 64
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]
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   end
154
155   # Returns the length of a sequence.
156   def length
157     self.seq.nil? ? 0 : self.seq.length
158   end
159
160   alias :len :length
161
162   # Return the number indels in a sequence.
163   def indels
164     regex = Regexp.new(/[#{Regexp.escape(INDELS.join(""))}]/)
165     self.seq.scan(regex).size
166   end
167
168   # Method to remove indels from seq and qual if qual.
169   def indels_remove
170     if self.qual.nil?
171       self.seq.delete!(Regexp.escape(INDELS.join('')))
172     else
173       na_seq  = NArray.to_na(self.seq, "byte")
174       na_qual = NArray.to_na(self.qual, "byte")
175       mask    = NArray.byte(self.length)
176
177       INDELS.each do |c|
178         mask += na_seq.eq(c.ord)
179       end
180
181       mask = mask.eq(0)
182
183       self.seq  = na_seq[mask].to_s
184       self.qual = na_qual[mask].to_s
185     end
186
187     self
188   end
189
190   # Method that returns true is a given sequence type is DNA.
191   def is_dna?
192     self.type == 'dna'
193   end
194
195   # Method that returns true is a given sequence type is RNA.
196   def is_rna?
197     self.type == 'rna'
198   end
199
200   # Method that returns true is a given sequence type is protein.
201   def is_protein?
202     self.type == 'protein'
203   end
204
205   # Method to transcribe DNA to RNA.
206   def to_rna
207     raise SeqError, "Cannot transcribe 0 length sequence" if self.length == 0
208     raise SeqError, "Cannot transcribe sequence type: #{self.type}" unless self.is_dna?
209     self.type = 'rna'
210     self.seq.tr!('Tt','Uu')
211   end
212
213   # Method to reverse-transcribe RNA to DNA.
214   def to_dna
215     raise SeqError, "Cannot reverse-transcribe 0 length sequence" if self.length == 0
216     raise SeqError, "Cannot reverse-transcribe sequence type: #{self.type}" unless self.is_rna?
217
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 complement sequence.
338   def reverse_complement
339     self.reverse
340     self.complement
341     self
342   end
343
344   alias :revcomp :reverse_complement
345
346   # Method to reverse the sequence.
347   def reverse
348     self.seq.reverse!
349     self.qual.reverse! if self.qual
350     self
351   end
352
353   # Method that complements sequence including ambiguity codes.
354   def complement
355     raise SeqError, "Cannot complement 0 length sequence" if self.length == 0
356
357     if self.is_dna?
358       self.seq.tr!('AGCUTRYWSMKHDVBNagcutrywsmkhdvbn', 'TCGAAYRWSKMDHBVNtcgaayrwskmdhbvn')
359     elsif self.is_rna?
360       self.seq.tr!('AGCUTRYWSMKHDVBNagcutrywsmkhdvbn', 'UCGAAYRWSKMDHBVNucgaayrwskmdhbvn')
361     else
362       raise SeqError, "Cannot complement sequence type: #{self.type}"
363     end
364   end
365
366   # Method to determine the Hamming Distance between
367   # two Sequence objects (case insensitive).
368   def hamming_distance(seq)
369     self.seq.upcase.hamming_distance(seq.seq.upcase)
370   end
371
372   # Method that generates a random sequence of a given length and type.
373   def generate(length, type)
374     raise SeqError, "Cannot generate sequence length < 1: #{length}" if length <= 0
375
376     case type.downcase
377     when "dna"
378       alph = DNA
379     when "rna"
380       alph = RNA
381     when "protein"
382       alph = PROTEIN
383     else
384       raise SeqError, "Unknown sequence type: #{type}"
385     end
386
387     seq_new   = Array.new(length) { alph[rand(alph.size)] }.join("")
388     self.seq  = seq_new
389     self.type = type.downcase
390     seq_new
391   end
392
393   # Method to shuffle a sequence readomly inline.
394   def shuffle!
395     self.seq = self.seq.split('').shuffle!.join
396     self
397   end
398
399   # Method that returns a subsequence of from a given start position
400   # and of a given length.
401   def subseq(start, length = self.length - start)
402     raise SeqError, "subsequence start: #{start} < 0"                                                if start  < 0
403     raise SeqError, "subsequence length: #{length} < 0"                                              if length < 0
404     raise SeqError, "subsequence start + length > Seq.length: #{start} + #{length} > #{self.length}" if start + length > self.length
405
406     if length == 0
407       seq  = ""
408       qual = "" unless self.qual.nil?
409     else
410       stop = start + length - 1
411
412       seq  = self.seq[start .. stop]
413       qual = self.qual[start .. stop] unless self.qual.nil?
414     end
415
416     Seq.new(self.seq_name, seq, self.type, qual)    # TODO changed self.seq_name.dup to self.seq_name -> consequence?
417   end
418
419   # Method that replaces a sequence with a subsequence from a given start position
420   # and of a given length.
421   def subseq!(start, length = self.length - start)
422     s = subseq(start, length)
423
424     self.seq_name = s.seq_name
425     self.seq      = s.seq
426     self.type     = s.type
427     self.qual     = s.qual
428
429     self
430   end
431
432   # Method that returns a subsequence of a given length
433   # beginning at a random position.
434   def subseq_rand(length)
435     if self.length - length + 1 == 0
436       start = 0
437     else
438       start = rand(self.length - length + 1)
439     end
440
441     self.subseq(start, length)
442   end
443
444   # Method that returns the residue compositions of a sequence in
445   # a hash where the key is the residue and the value is the residue
446   # count.
447   def composition
448     comp = Hash.new(0);
449
450     self.seq.upcase.each_char do |char|
451       comp[char] += 1
452     end
453
454     comp
455   end
456
457   # Method that returns the length of the longest homopolymeric stretch
458   # found in a sequence.
459   def homopol_max(min = 1)
460     return 0 if self.seq.nil? or self.seq.empty?
461
462     found = false
463
464     self.seq.upcase.scan(/A{#{min},}|T{#{min},}|G{#{min},}|C{#{min},}|N{#{min},}/) do |match|
465       found = true
466       min   = match.size > min ? match.size : min
467     end
468
469     return 0 unless found
470  
471     min
472   end
473
474   # Method that returns the percentage of hard masked residues
475   # or N's in a sequence.
476   def hard_mask
477     ((self.seq.upcase.scan("N").size.to_f / (self.len - self.indels).to_f) * 100).round(2)
478   end
479
480   # Method that returns the percentage of soft masked residues
481   # or lower cased residues in a sequence.
482   def soft_mask
483     ((self.seq.scan(/[a-z]/).size.to_f / (self.len - self.indels).to_f) * 100).round(2)
484   end
485
486   # Hard masks sequence residues where the corresponding quality score
487   # is below a given cutoff.
488   def mask_seq_hard_old(cutoff)
489     seq    = self.seq.upcase
490     scores = self.qual
491     i      = 0
492
493     scores.each_char do |score|
494       seq[i] = 'N' if score.ord - SCORE_BASE < cutoff
495       i += 1 
496     end
497
498     self.seq = seq
499   end
500
501   # Hard masks sequence residues where the corresponding quality score
502   # is below a given cutoff.
503   def mask_seq_hard!(cutoff)
504     raise SeqError, "seq is nil"  if self.seq.nil?
505     raise SeqError, "qual is nil" if self.qual.nil?
506     raise SeqError, "cufoff value: #{cutoff} out of range #{SCORE_MIN} .. #{SCORE_MAX}" unless (SCORE_MIN .. SCORE_MAX).include? cutoff
507
508     na_seq  = NArray.to_na(self.seq, "byte")
509     na_qual = NArray.to_na(self.qual, "byte")
510     mask    = (na_qual - SCORE_BASE) < cutoff
511     mask   *= na_seq.ne("-".ord)
512
513     na_seq[mask] = 'N'.ord
514
515     self.seq = na_seq.to_s
516
517     self
518   end
519
520   # Soft masks sequence residues where the corresponding quality score
521   # is below a given cutoff.
522   def mask_seq_soft!(cutoff)
523     raise SeqError, "seq is nil"  if self.seq.nil?
524     raise SeqError, "qual is nil" if self.qual.nil?
525     raise SeqError, "cufoff value: #{cutoff} out of range #{SCORE_MIN} .. #{SCORE_MAX}" unless (SCORE_MIN .. SCORE_MAX).include? cutoff
526
527     na_seq  = NArray.to_na(self.seq, "byte")
528     na_qual = NArray.to_na(self.qual, "byte")
529     mask    = (na_qual - SCORE_BASE) < cutoff
530     mask   *= na_seq.ne("-".ord)
531
532     na_seq[mask] ^= ' '.ord
533
534     self.seq = na_seq.to_s
535
536     self
537   end
538
539   # Method that determines if a quality score string can be
540   # absolutely identified as base 33.
541   def qual_base33?
542     self.qual.match(/[!-:]/) ? true : false
543   end
544
545   # Method that determines if a quality score string can be
546   # absolutely identified as base 64.
547   def qual_base64?
548     self.qual.match(/[K-h]/) ? true : false
549   end
550
551   # Method to determine if a quality score is valid.
552   def qual_valid?(encoding)
553     raise SeqError, "Missing qual" if self.qual.nil?
554
555     case encoding.downcase
556     when "sanger"     then return true if self.qual.match(/^[!-~]*$/)
557     when "454"        then return true if self.qual.match(/^[@-~]*$/)
558     when "solexa"     then return true if self.qual.match(/^[;-~]*$/)
559     when "illumina13" then return true if self.qual.match(/^[@-~]*$/)
560     when "illumina15" then return true if self.qual.match(/^[@-~]*$/)
561     when "illumina18" then return true if self.qual.match(/^[!-~]*$/)
562     else raise SeqError, "unknown quality score encoding: #{encoding}"
563     end
564
565     false
566   end
567
568   # Method to convert quality scores inbetween formats.
569   # Sanger     base 33, range  0-40 
570   # 454        base 64, range  0-40 
571   # Solexa     base 64, range -5-40 
572   # Illumina13 base 64, range  0-40 
573   # Illumina15 base 64, range  0-40 
574   # Illumina18 base 33, range  0-41 
575   def convert_scores!(from, to)
576     unless from == to
577       na_qual = NArray.to_na(self.qual, "byte")
578
579       case from.downcase
580       when "sanger"     then na_qual -= 33
581       when "454"        then na_qual -= 64
582       when "solexa"     then na_qual -= 64
583       when "illumina13" then na_qual -= 64
584       when "illumina15" then na_qual -= 64
585       when "illumina18" then na_qual -= 33
586       else raise SeqError, "unknown quality score encoding: #{from}"
587       end
588
589       case to.downcase
590       when "sanger"     then na_qual += 33
591       when "454"        then na_qual += 64
592       when "solexa"     then na_qual += 64
593       when "illumina13" then na_qual += 64
594       when "illumina15" then na_qual += 64
595       when "illumina18" then na_qual += 33
596       else raise SeqError, "unknown quality score encoding: #{to}"
597       end
598
599       self.qual = na_qual.to_s
600     end
601
602     self
603   end
604
605   # Method to calculate and return the mean quality score.
606   def scores_mean
607     raise SeqError, "Missing qual in entry" if self.qual.nil?
608
609     na_qual = NArray.to_na(self.qual, "byte")
610     na_qual -= SCORE_BASE
611     na_qual.mean
612   end
613
614   # Method to find open reading frames (ORFs).
615   def each_orf(size_min, size_max, start_codons, stop_codons, pick_longest = false)
616     orfs    = []
617     pos_beg = 0
618
619     regex_start = Regexp.new(start_codons.join('|'), true)
620     regex_stop  = Regexp.new(stop_codons.join('|'), true)
621
622     while pos_beg and pos_beg < self.length - size_min
623       if pos_beg = self.seq.index(regex_start, pos_beg)
624         if pos_end = self.seq.index(regex_stop, pos_beg)
625           length = (pos_end - pos_beg) + 3
626
627           if (length % 3) == 0
628             if size_min <= length and length <= size_max
629               subseq = self.subseq(pos_beg, length)
630
631               orfs << [subseq, pos_beg, pos_end + 3]
632             end
633           end
634         end
635
636         pos_beg += 1
637       end
638     end
639
640     if pick_longest
641       orf_hash = {}
642
643       orfs.each { |orf| orf_hash[orf.last] = orf unless orf_hash[orf.last] }
644
645       orfs = orf_hash.values
646     end
647
648     if block_given?
649       orfs.each { |orf| yield orf }
650     else
651       return orfs
652     end
653   end
654 end
655
656 __END__