15f4c5cb366b0a976a8bd90c1d359957a4d0426a
[jalview.git] / forester / ruby / evoruby / lib / evo / io / writer / phylip_sequential_writer.rb
1 #
2 # = lib/evo/io/writer/phylip_sequential_writer.rb - PhylipSequentialWriter class
3 #
4 # Copyright::  Copyright (C) 2006-2007 Christian M. Zmasek
5 # License::    GNU Lesser General Public License (LGPL)
6 #
7 # $Id: phylip_sequential_writer.rb,v 1.4 2008/09/03 00:31:38 cmzmasek Exp $
8 #
9 # last modified: 05/16/2007
10
11 require 'lib/evo/io/writer/msa_writer'
12
13 module Evoruby
14
15     class PhylipSequentialWriter < MsaWriter
16
17         MAX_NAME_LENGTH_DEFAULT = 10
18
19         def initialize()
20             @max_name_length = MAX_NAME_LENGTH_DEFAULT
21             @clean           = false
22         end
23
24         def set_max_name_length( length = MAX_NAME_LENGTH_DEFAULT )
25             if length < 1
26                 length = MAX_NAME_LENGTH_DEFAULT
27             end
28             @max_name_length = length
29         end
30
31         def clean( clean = true )
32             @clean = clean
33         end
34
35         def write( msa, path )
36             if ( !msa.is_aligned() )
37                 error_msg = "attempt to write unaligned msa in phylip sequential format"
38                 raise StandardError, error_msg, caller
39             end
40
41
42             Util.check_file_for_writability( path )
43
44             f = File.open( path, "a" )
45
46             f.print( msa.get_number_of_seqs().to_s() )
47             f.print( " " )
48             f.print( msa.get_length().to_s() )
49             f.print( Evoruby::Constants::LINE_DELIMITER )
50             for i in 0 ... msa.get_number_of_seqs()
51                 seq_obj = msa.get_sequence( i )
52                 name = seq_obj.get_name()
53                 seq  = seq_obj.get_sequence_as_string()
54                 name = name.gsub( /\s+$/, '')
55                 name = name.gsub( /\s+/, '_')
56                 name = Util.normalize_seq_name( name, @max_name_length )
57                 f.print( name )
58                 f.print( " " )
59                 if ( @clean )
60                     seq = Util.clean_seq_str( seq )
61                 end
62                 f.print( seq )
63                 f.print( Evoruby::Constants::LINE_DELIMITER )
64             end
65             f.close()
66         end
67
68     end # class PhylipSequentialWriter
69
70 end # module Evoruby