in progress
[jalview.git] / forester / ruby / scripts / replace_id.rb
1 #!/usr/local/bin/ruby -w
2 #
3 # = replace_id 
4 #
5 # Copyright::  Copyright (C) 2006-2008 Christian M. Zmasek
6 # License::    GNU Lesser General Public License (LGPL)
7 #
8 # $Id: replace_id.rb,v 1.8 2008/08/28 17:09:07 cmzmasek Exp $
9 #
10 # To replace ()by way of example '123_CHI5' with '123_CHICK5'
11 # given a mapping file containing '123_CHICKEN'
12 # (in the form '123_CHICKEN: some description which is ignored').
13 #
14 # Note. This will break if the species id ends with a number (as is 
15 # in the case for many bacteria).
16
17
18 module ForesterScripts
19     
20 if RUBY_VERSION !~ /1.9/
21                   puts( "Your ruby version is #{RUBY_VERSION}, expected 1.9.x " )
22                   exit( -1 )
23             end 
24
25     NUMBER_OF_LETTERS = 3
26
27     if ( ARGV == nil || ARGV.length != 3 )
28         puts( "usage: replace_id.rb <map-file> <infile> <outfile>" )         
29         exit( -1 )
30     end    
31     mapfile = ARGV[ 0 ]
32     infile  = ARGV[ 1 ]
33     outfile = ARGV[ 2 ]
34     
35     
36     if ( File.exists?( outfile ) ) 
37         puts( "outfile [" + outfile + "] already exists" )
38         exit( -1 )  
39     end
40     if ( !File.exists?( infile) )
41         puts( "infile [" + infile + "] does not exist" )
42         exit( -1 ) 
43     end 
44     if ( !File.exists?( mapfile ) ) 
45         puts( "mapfile [" + mapfile + "] does not exist" )
46         exit( -1 ) 
47     end                
48     
49     number_to_complete_id_map = Hash.new
50     
51     File.open( mapfile ) do | file |
52         while line = file.gets
53             if ( line =~ /(\d+_\S+)\s*:/ )
54                 complete_id = $1
55                 complete_id =~ /(\d+)_\S+/
56                 number_to_complete_id_map[ $1 ] = complete_id     
57                 puts( $1 + ' => ' + complete_id )
58             end
59         end
60     end 
61     
62     if ( number_to_complete_id_map.size < 1 ) 
63         puts( "mapping file was empty" )         
64         exit( -1 )    
65     end   
66     
67     data_str = String.new
68     
69     File.open( infile ) do | file |
70         while line = file.gets
71             data_str = data_str + line.chomp
72         end 
73     end     
74     
75     replacements = 0
76     number_to_complete_id_map.each_pair{ |number, id|
77         data_str.gsub!( /\b#{number}_[A-Z]{#{NUMBER_OF_LETTERS}}/, id )         
78     }
79     
80     open( outfile, 'w' ) do |file|
81         file.write( data_str )
82     end      
83     
84     puts( "wrote " + outfile )
85     puts( "OK" )
86     
87 end
88