back from the dead...
[jalview.git] / forester / ruby / evoruby / lib / evo / io / parser / fasta_parser.rb
1 #
2 # = lib/evo/io/parser/fasta_parser - FastaParser class
3 #
4 # Copyright::  Copyright (C) 20017 Christian M. Zmasek
5 # License::    GNU Lesser General Public License (LGPL)
6 #
7 # last modified: 05/17/2007
8
9 require 'lib/evo/io/parser/msa_parser'
10 require 'lib/evo/msa/msa'
11
12 #require 'iconv'
13
14 module Evoruby
15
16   class FastaParser < MsaParser
17
18     def initialize
19     end
20
21     def parse( path )
22       Util.check_file_for_readability( path )
23       msa = Msa.new
24       current_seq = String.new()
25       name        = String.new()
26       saw_first_seq = false
27       ic = Iconv.new( 'UTF-8//IGNORE', 'UTF-8' )
28       File.open( path ) do | file |
29         while line = file.gets
30           line = ic.iconv( line )
31           if can_ignore?( line, saw_first_seq )
32
33           elsif line =~ /^\s*>\s*(.+)/
34             saw_first_seq = true
35             add_seq( name, current_seq, msa )
36             name = $1
37             current_seq = String.new()
38           elsif line =~ /^\s*(.+)/
39             if name.length < 1
40               error_msg = "format error at: " + line
41               raise IOError, error_msg
42             end
43             # was: seq = $1.rstrip
44             seq =  $1.gsub(/\s+/, '')
45             current_seq << seq
46           else
47             error_msg = "Unexpected line: " + line
48             raise IOError, error_msg
49           end
50         end
51       end
52       add_seq( name, current_seq, msa )
53       return msa
54     end
55
56     private
57
58     def add_seq( name, seq, msa )
59       if name.length > 0 && seq.length > 0
60         msa.add( name, seq )
61       end
62     end
63
64     def can_ignore?( line, saw_first_seq )
65       return ( line !~ /\S/  ||
66          line =~ /^\s*#/ ||
67          ( !saw_first_seq && line =~/^\s*[^>]/ ) )
68     end
69
70   end # class FastaParser
71
72 end # module Evoruby