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