]> git.donarmstrong.com Git - biopieces.git/blob - code_ruby/Maasha/lib/fasta.rb
replacing read_fasta with ruby version
[biopieces.git] / code_ruby / Maasha / lib / fasta.rb
1 # This program is free software; you can redistribute it and/or
2 # modify it under the terms of the GNU General Public License
3 # as published by the Free Software Foundation; either version 2
4 # of the License, or (at your option) any later version.
5
6 # This program is distributed in the hope that it will be useful,
7 # but WITHOUT ANY WARRANTY; without even the implied warranty of
8 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
9 # GNU General Public License for more details.
10
11 # You should have received a copy of the GNU General Public License
12 # along with this program; if not, write to the Free Software
13 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
14
15 # http://www.gnu.org/copyleft/gpl.html
16
17 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
18
19 # This software is part of the Biopieces framework (www.biopieces.org).
20
21 # >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
22
23 require 'seq'
24
25 # Error class for all exceptions to do with FASTA.
26 class FastaError < StandardError; end
27
28 class Fasta
29   include Enumerable
30
31   # Class method allowing open to be used on files.
32   # See File.open.
33   def self.open(*args)
34     ios   = File.open(*args)
35     fasta = self.new(ios)
36
37     if block_given?
38       begin
39         yield fasta
40       ensure
41         ios.close
42       end
43
44       return true
45     else
46       return fasta
47     end
48   end
49
50   def initialize(io, type=nil)
51     @io   = io
52     @type = type
53   end
54
55   # Iterator method for parsing FASTA enries.
56   def each
57     while entry = get_entry do
58       yield entry
59     end
60   end
61
62   # Method to get the next FASTA entry form an ios and return this
63   # as a Seq object. If no entry is found or eof then nil is returned.
64   def get_entry
65     block = @io.gets($/ + '>')
66     return nil if block.nil?
67
68     block.chomp!($/ + '>')
69
70     (seq_name, seq) = block.split($/, 2)
71
72     raise FastaError, "Bad FASTA format" if seq_name.nil? or seq.nil?
73
74     entry          = Seq.new
75     entry.type     = @type.nil? ? nil : @type.downcase
76     entry.seq      = seq.gsub(/\s/, '')
77     entry.seq_name = seq_name.sub(/^>/, '').rstrip
78
79     raise FastaError, "Bad FASTA format" if entry.seq_name.empty?
80     raise FastaError, "Bad FASTA format" if entry.seq.empty?
81
82     entry
83   end
84 end
85
86
87 __END__