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       if msa != nil
313         seq = get_sequence( query, msa  )
314         species = get_species( seq )
315         raise StandardError, "could not get species" if species == nil || species.empty?
316         if x_models != nil &&  x_models.length > 0
317           extract_linkers( hmmscan_results_per_protein_filtered, x_models, seq,  extraction_output_file )
318         end
319       end
320
321       s = query + "\t"
322       s << species + "\t"
323       owns.each do | own |
324         s << own.fs_e_value.to_s + "\t"
325       end
326
327       s << qlen.to_s + "\t"
328
329       s << hmmscan_results_per_protein_filtered.length.to_s + "\t"
330       hmmscan_results_per_protein_filtered.each do | r |
331         s << r.model + " "
332       end
333       s << "\t"
334       s <<  make_overview_da( hmmscan_results_per_protein_filtered )
335       s << "\t"
336       s << make_detailed_da( hmmscan_results_per_protein_filtered, qlen )
337       puts s
338
339     end
340
341
342     def extract_linkers( hmmscan_results_per_protein_filtered, x_models, seq, extraction_output_file )
343       raise StandardError, "extraction output file is nil" if extraction_output_file == nil
344       prev_r = nil
345       hmmscan_results_per_protein_filtered.each do | r |
346         if  prev_r != nil
347           if ( x_models.length == 2 && prev_r.model == x_models[ 0 ] && r.model == x_models[ 1 ] )
348             extract_linker( prev_r.env_to, r.env_from, seq, extraction_output_file )
349           end
350         end
351         prev_r = r
352       end
353     end
354
355
356     def get_sequence( query, msa  )
357       seq = nil
358       indices = msa.find_by_name_start( query , true )
359       if indices.length != 1
360         if query[ -1, 1 ] == "|"
361           query.chop!
362         end
363         seq = msa.get_by_name_pattern( /\b#{Regexp.quote(query)}\b/ )
364       else
365         seq = msa.get_sequence( indices[ 0 ] )
366       end
367       seq
368     end
369
370
371     def get_species( seq )
372       species = nil
373       if seq.get_name =~ /\[([A-Z0-9]{3,5})\]/
374         species = $1
375       end
376       species
377     end
378
379
380     def extract_linker( first, last , seq,  output_file )
381       if ( last - first >= 1 )
382         output_file.print( ">" + seq.get_name + " [" +  first.to_s + "-" + last.to_s +  "]" + "\n")
383         output_file.print( seq.get_subsequence( first - 1 , last - 1 ).get_sequence_as_string + "\n" )
384       end
385     end
386
387
388     def make_detailed_da( hmmscan_results_per_protein_filtered , qlen )
389       s = ""
390       prev_r = nil
391       hmmscan_results_per_protein_filtered.each do | r |
392         if  prev_r != nil
393           s << make_interdomain_sequence( r.env_from - prev_r.env_to - 1 )
394         else
395           s << make_interdomain_sequence( r.env_from, false )
396         end
397         s << r.model
398         s << "["
399         s << r.env_from.to_s << "-" << r.env_to.to_s
400         s << " " << r.i_e_value.to_s
401         s << "]"
402         prev_r = r
403       end
404       s << make_interdomain_sequence( qlen - prev_r.env_to, false )
405       s
406     end
407
408
409     def make_overview_da( hmmscan_results_per_protein_filtered )
410       overview = ""
411       prev_r = nil
412       hmmscan_results_per_protein_filtered.each do | r |
413         if prev_r == nil
414           overview << r.model
415         else
416           if  ( r.env_from - prev_r.env_to - 1 ) <= LIMIT_FOR_CLOSE_DOMAINS
417             overview << "~" << r.model
418           else
419             overview << "----" << r.model
420           end
421         end
422         prev_r = r
423
424       end
425       overview
426     end
427
428
429     def make_interdomain_sequence( d, mark_short = true )
430       s = ""
431       d /= 20
432       if d >= 10
433         s << "----//----"
434       elsif d >= 1
435         d.times do
436           s << "-"
437         end
438       elsif mark_short
439         s << "~"
440       end
441       s
442     end
443
444
445     def print_help()
446       puts( "Usage:" )
447       puts()
448       puts( "  " + PRG_NAME + ".rb [options] <hmmscan outputfile> <outputfile>" )
449       puts()
450       puts( "  options: -" + I_E_VALUE_THRESHOLD_OPTION  + ": i-E-value threshold, default is no threshold" )
451       puts( "           -" + FS_E_VALUE_THRESHOLD_OPTION  + ": E-value threshold for full protein sequences, only for protein summary" )
452       puts( "           -" + TARGET_MODELS + ": target HMMs" )
453       puts()
454     end
455
456   end # class
457
458 end # module Evoruby