inprogress
[jalview.git] / forester / ruby / evoruby / lib / evo / tool / hmmscan_analysis.rb
1 #
2 # = lib/evo/tool/hmmscan_summary.rb - HmmscanSummary class
3 #
4 # Copyright::  Copyright (C) 2012 Christian M. Zmasek
5 # License::    GNU Lesser General Public License (LGPL)
6 #
7 # $Id: hmmscan_parser.rb,v 1.5 2010/12/13 19:00:11 cmzmasek Exp $
8 #
9
10 require 'lib/evo/util/constants'
11 require 'lib/evo/util/util'
12 require 'lib/evo/util/command_line_arguments'
13 require 'lib/evo/io/parser/hmmscan_parser'
14 require 'lib/evo/msa/msa'
15 require 'lib/evo/msa/msa_factory'
16 require 'lib/evo/io/msa_io'
17 require 'lib/evo/io/parser/fasta_parser'
18
19 module Evoruby
20
21   class HmmscanAnalysis
22
23     PRG_NAME       = "hsa"
24     PRG_VERSION    = "1.000"
25     PRG_DESC       = "hmmscan analysis"
26     PRG_DATE       = "130319"
27     COPYRIGHT      = "2013 Christian M Zmasek"
28     CONTACT        = "phyloxml@gmail.com"
29     WWW            = "https://sites.google.com/site/cmzmasek/home/software/forester"
30
31     I_E_VALUE_THRESHOLD_OPTION    = "ie"
32     FS_E_VALUE_THRESHOLD_OPTION   = "pe"
33     TARGET_MODELS                 = "m"
34     EXTRACTION                    = "x"
35     HELP_OPTION_1                 = "help"
36     HELP_OPTION_2                 = "h"
37
38     USE_AVOID_HMMS = true
39     AVOID_HHMS = [ "RRM_1", "RRM_2", "RRM_3", "RRM_4", "RRM_5", "RRM_6" ]
40     LIMIT_FOR_CLOSE_DOMAINS = 20
41
42
43     def run
44
45       Util.print_program_information( PRG_NAME,
46         PRG_VERSION,
47         PRG_DESC,
48         PRG_DATE,
49         COPYRIGHT,
50         CONTACT,
51         WWW,
52         STDOUT )
53
54       begin
55         cla = CommandLineArguments.new( ARGV )
56       rescue ArgumentError => e
57         Util.fatal_error( PRG_NAME, "error: " + e.to_s, STDOUT )
58       end
59
60       if ( cla.is_option_set?( HELP_OPTION_1 ) ||
61            cla.is_option_set?( HELP_OPTION_2 ) )
62         print_help
63         exit( 0 )
64       end
65
66       if ( cla.get_number_of_files != 1 && cla.get_number_of_files != 3 )
67         print_help
68         exit( -1 )
69       end
70
71       allowed_opts = Array.new
72       allowed_opts.push( I_E_VALUE_THRESHOLD_OPTION )
73       allowed_opts.push( FS_E_VALUE_THRESHOLD_OPTION )
74       allowed_opts.push( TARGET_MODELS )
75       allowed_opts.push( EXTRACTION )
76
77       disallowed = cla.validate_allowed_options_as_str( allowed_opts )
78       if ( disallowed.length > 0 )
79         Util.fatal_error( PRG_NAME,
80           "unknown option(s): " + disallowed,
81           STDOUT )
82       end
83
84       inpath = cla.get_file_name( 0 )
85       Util.check_file_for_readability( inpath )
86       seq_file_path = nil
87       extraction_output = nil
88
89       if ( cla.get_number_of_files == 3 )
90         seq_file_path = cla.get_file_name( 1 )
91         Util.check_file_for_readability(  seq_file_path  )
92         extraction_output = cla.get_file_name( 2 )
93         if File.exist?( extraction_output )
94           Util.fatal_error( PRG_NAME, "error: [#{extraction_output}] already exists" )
95         end
96
97       end
98
99       msa = nil
100       if seq_file_path != nil
101         msa = read_fasta_file( seq_file_path )
102       end
103
104       i_e_value_threshold = -1
105       if ( cla.is_option_set?( I_E_VALUE_THRESHOLD_OPTION ) )
106         begin
107           i_e_value_threshold = cla.get_option_value_as_float( I_E_VALUE_THRESHOLD_OPTION )
108         rescue ArgumentError => e
109           Util.fatal_error( PRG_NAME, "error: " + e.to_s, STDOUT )
110         end
111         if ( i_e_value_threshold < 0.0 )
112           Util.fatal_error( PRG_NAME, "attempt to use a negative i-E-value threshold", STDOUT )
113         end
114       end
115
116       fs_e_value_threshold = -1
117       if ( cla.is_option_set?( FS_E_VALUE_THRESHOLD_OPTION ) )
118         begin
119           fs_e_value_threshold = cla.get_option_value_as_float( FS_E_VALUE_THRESHOLD_OPTION )
120         rescue ArgumentError => e
121           Util.fatal_error( PRG_NAME, "error: " + e.to_s, STDOUT )
122         end
123         if ( fs_e_value_threshold < 0.0 )
124           Util.fatal_error( PRG_NAME, "attempt to use a negative E-value threshold", STDOUT )
125         end
126       end
127
128       target_models = []
129       if ( cla.is_option_set?( TARGET_MODELS ) )
130         begin
131           hmm_for_protein_output = cla.get_option_value( TARGET_MODELS )
132           target_models = hmm_for_protein_output.split( "/" );
133         rescue ArgumentError => e
134           Util.fatal_error( PRG_NAME, "error: " + e.to_s, STDOUT )
135         end
136       end
137
138       x_models = []
139       if ( cla.is_option_set?( EXTRACTION ) )
140         begin
141           hmm_for_protein_output = cla.get_option_value( EXTRACTION )
142           x_models = hmm_for_protein_output.split( "~" );
143         rescue ArgumentError => e
144           Util.fatal_error( PRG_NAME, "error: " + e.to_s, STDOUT )
145         end
146       end
147
148       begin
149         parse( inpath,
150           i_e_value_threshold,
151           fs_e_value_threshold,
152           target_models,
153           x_models,
154           msa,
155           extraction_output )
156       rescue IOError => e
157         Util.fatal_error( PRG_NAME, "error: " + e.to_s, STDOUT )
158       end
159
160     end # def run
161
162
163     private
164
165     def read_fasta_file( input )
166       f = MsaFactory.new()
167       msa = nil
168       begin
169         msa = f.create_msa_from_file( input, FastaParser.new() )
170       rescue Exception => e
171         Util.fatal_error( PRG_NAME, "error: " + e.to_s )
172       end
173       msa
174     end
175
176
177     # raises ArgumentError, IOError
178     def parse( inpath,
179         i_e_value_threshold,
180         fs_e_value_threshold,
181         target_models,
182         x_models,
183         msa,
184         extraction_output )
185
186       extraction_output_file = nil
187       if extraction_output != nil
188         extraction_output_file = File.open( extraction_output, "a" )
189       end
190
191       hmmscan_parser = HmmscanParser.new( inpath )
192
193       results = hmmscan_parser.parse
194
195       hmmscan_results_per_protein = []
196
197       query     = ""
198       prev_query = ""
199       results.each do | r |
200         query = r.query
201         if !prev_query.empty? && prev_query != query
202           if !hmmscan_results_per_protein.empty?
203             process_hmmscan_results_per_protein( hmmscan_results_per_protein,
204               fs_e_value_threshold,
205               target_models,
206               x_models,
207               i_e_value_threshold,
208               msa,
209               extraction_output_file )
210           end
211           hmmscan_results_per_protein.clear
212         end
213         prev_query = query
214
215         if USE_AVOID_HMMS
216           if !AVOID_HHMS.include? r.model
217             hmmscan_results_per_protein << r
218           end
219         else
220           hmmscan_results_per_protein << r
221         end
222
223       end
224
225       if !hmmscan_results_per_protein.empty?
226         process_hmmscan_results_per_protein( hmmscan_results_per_protein,
227           fs_e_value_threshold,
228           target_models,
229           x_models,
230           i_e_value_threshold,
231           msa,
232           extraction_output_file )
233       end
234       if extraction_output_file != nil
235         extraction_output_file.close
236       end
237     end # def parse
238
239
240     def process_hmmscan_results_per_protein( hmmscan_results_per_protein,
241         fs_e_value_threshold,
242         target_hmms,
243         x_models,
244         i_e_value_threshold,
245         msa,
246         extraction_output_file )
247
248       raise StandardError, "target hmms is empty" if target_hmms.length < 1
249       raise StandardError, "results is empty" if hmmscan_results_per_protein.length < 1
250
251       # filter according to i-Evalue threshold
252       # abort if fs Evalue too high
253
254       if fs_e_value_threshold >= 0.0
255         hmmscan_results_per_protein.each do | r |
256           target_hmms.each do | hmm |
257             if r.model == hmm && r.fs_e_value > fs_e_value_threshold
258               return
259             end
260           end
261         end
262       end
263
264       hmmscan_results_per_protein_filtered = []
265       matched = Set.new
266
267       hmmscan_results_per_protein.each do | r |
268         if i_e_value_threshold < 0 || r.i_e_value <= i_e_value_threshold
269           hmmscan_results_per_protein_filtered << r
270           target_hmms.each do | hmm |
271             if r.model == hmm
272               matched << hmm
273               break
274             end
275           end
276
277         end
278       end
279
280       if matched.length < target_hmms.length
281         return
282       end
283       if  hmmscan_results_per_protein_filtered.length < 1
284         return
285       end
286
287       hmmscan_results_per_protein_filtered.sort! { |r1,r2| r1.env_from <=> r2.env_from }
288
289       owns = []
290       target_hmms.each do | hmm |
291         hmmscan_results_per_protein_filtered.each do | r |
292           if r.model == hmm
293             owns << r
294             break
295           end
296         end
297       end
298
299       query = nil
300       qlen = nil
301       owns.each do | own |
302         if query == nil
303           query = own.query
304           qlen = own.qlen
305         else
306           raise StandardError, "failed sanity check" if query != own.query || qlen != own.qlen
307           raise StandardError, "failed sanity check: qlen != own.qlen" if qlen != own.qlen
308         end
309       end
310
311       species = nil
312       ll = nil
313       if msa != nil
314         seq = get_sequence( query, msa  )
315         species = get_species( seq )
316         raise StandardError, "could not get species" if species == nil || species.empty?
317         if x_models != nil &&  x_models.length > 0
318           ll = extract_linker( hmmscan_results_per_protein_filtered, x_models, seq,  extraction_output_file )
319         end
320       end
321
322       s = query + "\t"
323       s << species + "\t"
324       owns.each do | own |
325         s << own.fs_e_value.to_s + "\t"
326       end
327
328       s << qlen.to_s + "\t"
329
330       s << hmmscan_results_per_protein_filtered.length.to_s + "\t"
331       hmmscan_results_per_protein_filtered.each do | r |
332         s << r.model + " "
333       end
334       s << "\t"
335       if msa != nil
336         if ll != nil
337           s << ll.to_s
338         end
339         s << "\t"
340       end
341       s <<  make_overview_da( hmmscan_results_per_protein_filtered )
342       s << "\t"
343       s << make_detailed_da( hmmscan_results_per_protein_filtered, qlen )
344       puts s
345
346     end
347
348
349     def extract_linker( hmmscan_results_per_protein_filtered, x_models, seq, extraction_output_file )
350       raise StandardError, "extraction output file is nil" if extraction_output_file == nil
351       prev_r = nil
352       hmmscan_results_per_protein_filtered.each do | r |
353         if  prev_r != nil
354           if ( x_models.length == 2 && prev_r.model == x_models[ 0 ] && r.model == x_models[ 1 ] )
355             ll = output_linker( prev_r.env_to, r.env_from, seq, extraction_output_file )
356             return ll
357           end
358         end
359         prev_r = r
360       end
361       return nil
362     end
363
364
365     def get_sequence( query, msa  )
366       seq = nil
367       indices = msa.find_by_name_start( query , true )
368       if indices.length != 1
369         if query[ -1, 1 ] == "|"
370           query.chop!
371         end
372         seq = msa.get_by_name_pattern( /\b#{Regexp.quote(query)}\b/ )
373       else
374         seq = msa.get_sequence( indices[ 0 ] )
375       end
376       seq
377     end
378
379
380     def get_species( seq )
381       species = nil
382       if seq.get_name =~ /\[([A-Z0-9]{3,5})\]/
383         species = $1
384       end
385       species
386     end
387
388
389     def output_linker( first, last , seq,  output_file )
390       if ( last - first >= 1 )
391         output_file.print( ">" + seq.get_name + " [" +  first.to_s + "-" + last.to_s +  "]" + "\n")
392         output_file.print( seq.get_subsequence( first - 1 , last - 1 ).get_sequence_as_string + "\n" )
393       end
394       last - first + 1
395
396     end
397
398
399     def make_detailed_da( hmmscan_results_per_protein_filtered , qlen )
400       s = ""
401       prev_r = nil
402       hmmscan_results_per_protein_filtered.each do | r |
403         if  prev_r != nil
404           s << make_interdomain_sequence( r.env_from - prev_r.env_to - 1 )
405         else
406           s << make_interdomain_sequence( r.env_from, false )
407         end
408         s << r.model
409         s << "["
410         s << r.env_from.to_s << "-" << r.env_to.to_s
411         s << " " << r.i_e_value.to_s
412         s << "]"
413         prev_r = r
414       end
415       s << make_interdomain_sequence( qlen - prev_r.env_to, false )
416       s
417     end
418
419
420     def make_overview_da( hmmscan_results_per_protein_filtered )
421       overview = ""
422       prev_r = nil
423       hmmscan_results_per_protein_filtered.each do | r |
424         if prev_r == nil
425           overview << r.model
426         else
427           if  ( r.env_from - prev_r.env_to - 1 ) <= LIMIT_FOR_CLOSE_DOMAINS
428             overview << "~" << r.model
429           else
430             overview << "----" << r.model
431           end
432         end
433         prev_r = r
434
435       end
436       overview
437     end
438
439
440     def make_interdomain_sequence( d, mark_short = true )
441       s = ""
442       d /= 20
443       if d >= 10
444         s << "----//----"
445       elsif d >= 1
446         d.times do
447           s << "-"
448         end
449       elsif mark_short
450         s << "~"
451       end
452       s
453     end
454
455
456     def print_help()
457       puts( "Usage:" )
458       puts()
459       puts( "  " + PRG_NAME + ".rb [options] <hmmscan outputfile> <outputfile>" )
460       puts()
461       puts( "  options: -" + I_E_VALUE_THRESHOLD_OPTION  + ": i-E-value threshold, default is no threshold" )
462       puts( "           -" + FS_E_VALUE_THRESHOLD_OPTION  + ": E-value threshold for full protein sequences, only for protein summary" )
463       puts( "           -" + TARGET_MODELS + ": target HMMs" )
464       puts()
465     end
466
467   end # class
468
469 end # module Evoruby