]> git.donarmstrong.com Git - function2gene.git/blob - bin/function2gene
Add results to table; modify the search parssers to work better. Fix error in get_ncb...
[function2gene.git] / bin / function2gene
1 #! /usr/bin/perl
2 # function2gene, is part of the function2gene suite and is released
3 # under the terms of the GPL version 2, or any later version, at your
4 # option. See the file README and COPYING for more information.
5 # Copyright 2007 by Don Armstrong <don@donarmstrong.com>.
6
7
8 use threads;
9 use warnings;
10 use strict;
11
12 use Getopt::Long;
13 use Pod::Usage;
14
15 use Storable;
16
17 =head1 NAME
18
19   function2gene - Call out to each of the search modules to search for
20   each of the terms
21
22 =head1 SYNOPSIS
23
24  function2gene --keywords keywords.txt --results gene_search_results
25
26  Options:
27   --keywords newline delineated list of keywords to search for
28   --results directory to store results in
29   --database databases to search
30   --restart-at mode to start searching at
31   --debug, -d debugging level (Default 0)
32   --help, -h display this help
33   --man, -m display manual
34
35 =head1 OPTIONS
36
37 =over
38
39 =item B<--keywords>
40
41 A file which contains a newline delinated list of keywords to search
42 for. Can be specified multiple times. Lines starting with # or ; are
43 ignored.
44
45 =item B<--results>
46
47 Directory in which to store results; also stores the current state of
48 the system
49
50 =item B<--database>
51
52 Databases to search, can be specified multiple times. [Defaults to
53 NCBI, GeneCards and Harvester, the only currently supported
54 databases.]
55
56 =item B<--restart-at>
57
58 If you need to restart the process at a particular state (which has
59 already been completed) specify this option.
60
61 =item B<--debug, -d>
62
63 Debug verbosity. (Default 0)
64
65 =item B<--help, -h>
66
67 Display brief useage information.
68
69 =item B<--man, -m>
70
71 Display this manual.
72
73 =back
74
75 =head1 EXAMPLES
76
77    # Search all databases for transferrin
78    echo 'transferrin' > keywords.txt
79    function2gene --keywords keywords.txt --results keyword_results
80
81 =cut
82
83
84 use vars qw($DEBUG);
85 use Cwd qw(abs_path);
86 use IO::File;
87 use Storable qw(thaw freeze);
88 use File::Basename qw(basename dirname);
89 use Thread::Queue;
90
91 my %options = (databases       => [],
92                keywords        => [],
93                debug           => 0,
94                help            => 0,
95                man             => 0,
96                results         => '',
97                );
98
99 GetOptions(\%options,'keywords=s@','databases=s@',
100            'restart_at|restart-at=s','results=s',
101            'debug|d+','help|h|?','man|m');
102
103 pod2usage() if $options{help};
104 pod2usage({verbose=>2}) if $options{man};
105
106 my $base_dir = dirname(abs_path($0));
107
108 my $ERRORS='';
109
110 $ERRORS.="restart-at must be one of get, parse or combine\n" if
111      exists $options{restart_at} and $options{restart_at} !~ /^(?:get|parse|combine)$/;
112
113 $ERRORS.="unknown database(s)" if
114      @{$options{databases}} and
115      grep {$_ !~ /^(?:ncbi|genecard|harvester)$/i} @{$options{databases}};
116
117 if (not length $options{results}) {
118      $ERRORS.="results directory not specified";
119 }
120 elsif (not -d $options{results} or not -w $options{results}) {
121      $ERRORS.="results directory $options{results} does not exist or is not writeable";
122 }
123
124 pod2usage($ERRORS) if length $ERRORS;
125
126 if (not @{$options{databases}}) {
127      $options{databases} = [qw(ncbi genecard harvester)]
128 }
129
130 $DEBUG = $options{debug};
131
132 # There are three states for our engine
133 # Getting results
134 # Parsing them
135 # Combining results
136
137 # first, check to see if the state in the result directory exists
138
139 my %state;
140
141 $options{keywords} = [map {abs_path($_)} @{$options{keywords}}];
142
143 chdir $options{results} or die "Unable to chdir to $options{results}";
144
145 if (-e "do_it_all_state") {
146      ADVISE("Using existing state information");
147      my $state_fh = IO::File->new("do_it_all_state",'r') or die
148           "Unable to open state file for reading: $!";
149      local $/;
150      my $state_file = <$state_fh>;
151      %state = %{thaw($state_file)} or die "Unable to thaw state file";
152 }
153 else {
154      ADVISE("Starting new run");
155      %state = (keywords => [],
156                databases => [map {lc($_)} @{$options{databases}}],
157                done_keywords => {
158                                  get => {},
159                                  parse => {},
160                                  combine => {},
161                                 },
162               );
163 }
164
165 my @new_keywords;
166 if (@{$options{keywords}}) {
167      # uniqify keywords
168      my %old_keywords;
169      @old_keywords{@{$state{keywords}}} = (1) x @{$state{keywords}};
170      for my $keyword_file (@{$options{keywords}}) {
171           my $keyword_fh = IO::File->new($keyword_file,'r') or die
172                "Unable to open $keyword_file for reading: $!";
173           while (<$keyword_fh>) {
174                next if /^\s*[#;]/;
175                next unless /\w+/;
176                chomp;
177                if (not $old_keywords{$_}) {
178                     DEBUG("Adding new keyword '$_'");
179                     push @new_keywords, $_;
180                }
181                else {
182                     DEBUG("Not adding duplicate keyword '$_'");
183                }
184           }
185      }
186      push @{$state{keywords}},@new_keywords;
187 }
188
189 if (exists $options{restart_at} and length $options{restart_at}) {
190      if (lc($options{restart_at}) eq 'get') {
191           delete $state{done_keywords}{get};
192           delete $state{done_keywords}{parse};
193           delete $state{done_keywords}{combine};
194      }
195      elsif (lc($options{restart_at}) eq 'parse') {
196           delete $state{done_keywords}{parse};
197           delete $state{done_keywords}{combine};
198      }
199      elsif (lc($options{restart_at}) eq 'combine') {
200           delete $state{done_keywords}{combine};
201      }
202 }
203
204 # now we need to figure out what has to happen
205 # for each keyword, we check to see if we've got results, parsed
206 # results, and combined it. If not, we queue up those actions.
207
208 my %actions = (combine => 0,
209                get     => {},
210                parse   => {},
211               );
212
213 if (not @{$state{keywords}}) {
214      ADVISE("There are no keywords specified");
215 }
216
217 for my $keyword (@{$state{keywords}}) {
218      for my $database (@{$state{databases}}) {
219           if (not exists $state{done_keywords}{get}{$database}{$keyword}) {
220                push @{$actions{get}{$database}}, $keyword;
221                delete $state{done_keywords}{parse}{$database}{$keyword} if
222                     exists $state{done_keywords}{parse}{$database}{$keyword};
223                delete $state{done_keywords}{combine}{$database}{$keyword} if
224                     exists $state{done_keywords}{combine}{$database}{$keyword};
225           }
226           if (not exists $state{done_keywords}{parse}{$database}{$keyword}) {
227                push @{$actions{parse}{$database}},$keyword;
228                delete $state{done_keywords}{combine}{$database}{$keyword} if
229                     exists $state{done_keywords}{combine}{$database}{$keyword};
230           }
231           if (not exists $state{done_keywords}{combine}{$database}{$keyword}) {
232               $actions{combine} = 1;
233           }
234      }
235 }
236
237
238 for my $state (qw(get parse)) {
239      my %databases;
240      for my $database (keys %{$actions{$state}}) {
241           next unless @{$actions{$state}{$database}};
242           $databases{$database}{queue} = Thread::Queue->new
243                or die "Unable to create new thread queue";
244           $databases{$database}{thread} = threads->create(\&handle_action,$state,$database,$databases{$database}{queue})
245                or die "Unable to create new thread";
246           $databases{$database}{queue}->enqueue(@{$actions{$state}{$database}});
247           $databases{$database}{queue}->enqueue(undef);
248      }
249      my $ERRORS=0;
250      for my $database (keys %databases) {
251           my ($actioned_keywords,$failed_keywords) = @{$databases{$database}{thread}->join||[]};
252           if (not defined $failed_keywords) {
253                ADVISE("Something bad happened during '$state' of '$database'");
254                $ERRORS = 1;
255           }
256           elsif (@{$failed_keywords}) {
257                ADVISE("These keywords failed during '$state' of '$database':",@{$failed_keywords});
258                $ERRORS=1;
259           }
260           @{$state{done_keywords}{$state}{$database}}{@{$actioned_keywords}} = (1) x @{$actioned_keywords};
261           delete @{$state{done_keywords}{$state}{$database}}{@{$failed_keywords}};
262      }
263      save_state(\%state);
264      if ($ERRORS) {
265           WARN("Stoping, as there are errors");
266           exit 1;
267      }
268 }
269
270 if ($actions{combine}) {
271      save_state(\%state);
272      # deal with combining results
273      my @parsed_results = map { my $db = $_;
274                                 map {
275                                      "parsed_results_${db}_${_}.txt"
276                                 } keys %{$state{done_keywords}{parse}{$db}}
277                            } keys %{$state{done_keywords}{parse}};
278
279      write_command_to_file('combined_results.txt',
280                            "$base_dir/combine_results",
281                            @parsed_results,
282                           );
283      for my $result (@parsed_results) {
284           $result =~ s/^parsed_results_//;
285           $result =~ s/\.txt$//;
286           my ($db,$keyword) = split /_/, $result, 2;
287           $state{done_keywords}{combined}{$db}{$keyword} = 1;
288      }
289      save_state(\%state);
290      ADVISE("Finished; results in $options{results}/combined_results");
291 }
292 else {
293      ADVISE('Nothing to do. [Perhaps you wanted --restart-at?]');
294 }
295
296 sub handle_action{
297      my ($state,$database,$queue) = @_;
298      my $keyword;
299      my $actioned_keywords = [];
300      my $failed_keywords = [];
301      DEBUG("Beginning to handle actions for state '$state' database '$database'");
302      while ($keyword = $queue->dequeue) {
303           DEBUG("Handling state '$state' database '$database' keyword '$keyword'");
304           # handle the action, baybee
305           if ($state eq 'get') {
306                my $command_fh;
307                eval {
308                     open($command_fh,'|-',
309                          "$base_dir/get_${database}_results",
310                         ) or die "unable to execute '$base_dir/get_${database}_results'";
311                     print {$command_fh} "$keyword\n" or die "unable to print $keyword to 'get_${database}_results'";
312                     close($command_fh) or die "Unable to close filehandle";
313                     if ($? != 0) {
314                          die "get_${database}_results with keyword $keyword failed with error code ".($?>>8);
315                     }
316                };
317                if ($@) {
318                     WARN($@);
319                     push @{$failed_keywords}, $keyword;
320                     next;
321                }
322           }
323           elsif ($state eq 'parse') {
324                eval {
325                     write_command_to_file("parsed_results_${database}_${keyword}.txt",
326                                           "$base_dir/parse_${database}_results",
327                                           '--keywords',
328                                           $keyword,
329                                          );
330                };
331                if ($@) {
332                     WARN("parse_${database}_results failed with $@");
333                     push @{$failed_keywords}, $keyword;
334                     next;
335                }
336           }
337           else {
338                die "I don't know how to handle state $state";
339           }
340           ADVISE("$state results from '$database' for '$keyword'");
341           push @{$actioned_keywords},$keyword;
342      }
343      return [$actioned_keywords,$failed_keywords];
344 }
345
346 sub save_state{
347      my ($state) = @_;
348      my $state_fh = IO::File->new("do_it_all_state",'w') or die
349           "Unable to open state file for writing: $!";
350      print {$state_fh} freeze($state) or die "Unable to freeze state file";
351      close $state_fh or die "Unable to close state file: $!";
352 }
353
354 sub write_command_to_file{
355      my ($file,@command) = @_;
356      my $fh = IO::File->new($file,'w') or
357           die "Unable to open $file for writing: $!";
358      my $command_fh;
359      open($command_fh,'-|',
360           @command,
361          ) or die "Unable to execute $command[0] $!";
362      print {$fh} <$command_fh>;
363      close $fh;
364      close $command_fh or die "$command[0] failed with ".($?>>8);
365 }
366
367
368 sub ADVISE{
369      print STDOUT map {($_,qq(\n))} @_;
370 }
371
372 sub DEBUG{
373      print STDERR map {($_,qq(\n))} @_;
374 }
375
376
377 sub WARN {
378      print STDERR map {($_,qq(\n))} @_;
379 }
380
381 __END__