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