[Bio] / FigKernelPackages / P2P.pm Repository:
ViewVC logotype

Annotation of /FigKernelPackages/P2P.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.30 - (view) (download) (as text)

1 : olson 1.1 #
2 :     # This module contains the code for the P2P update protocol.
3 :     #
4 :     # Package P2P contains the namespace declarations, and possibly toplevel utility
5 :     # routines. (get_relay ?)
6 :     #
7 :     # Package P2P::Relay contains methods for contacting the P2P relay service. The actual
8 :     # implementation of the relay service is not contained here - it is a standalone module
9 :     # that can be installed on a web server that does not have a full SEED installed.
10 :     #
11 :     # Package P2P::Requestor contains the requestor-side code for the update protocol.
12 :     #
13 :     # Package P2P::Service contains the web service implementation routines for the
14 :     # protocol.
15 :     #
16 :    
17 :     package P2P;
18 :    
19 :     use FIG_Config;
20 :    
21 : olson 1.24 use AnyDBM_File;
22 : olson 1.19 use Fcntl;
23 :    
24 : olson 1.1 use strict;
25 :     use Exporter;
26 :     use base qw(Exporter);
27 :    
28 : olson 1.15 use Time::HiRes qw( usleep ualarm gettimeofday tv_interval );
29 :    
30 : olson 1.1 use Data::Dumper;
31 :    
32 :     use vars qw(@EXPORT @EXPORT_OK);
33 :     @EXPORT = ();
34 :     @EXPORT_OK = qw($ns_p2p $ns_relay);
35 :    
36 :     our $ns_p2p = "http://thefig.info/schemas/p2p_update";
37 :     our $ns_relay = "http://thefig.info/schemas/p2p_relay";
38 :    
39 : olson 1.21 my $peg_batch_size = 1000;
40 :     my $anno_batch_size = 1000;
41 :     my $assign_batch_size = 1000;
42 : olson 1.23 my $fin_batch_size = 1000;
43 : olson 1.21
44 : olson 1.22 my $log_fh;
45 : olson 1.23 my $html_fh;
46 : olson 1.22
47 : olson 1.1 =pod
48 :    
49 : olson 1.25 =head1 perform_update($peer, $last_update, $skip_tough_search, $update_thru, $log_file, $html_file, $assignment_policy))
50 : olson 1.1
51 :     Perform a peer-to-peer update with the given peer. $peer is an instance of
52 :     P2P::Requestor which can connect to the peer. It is expected that the
53 :     SEED infrastructure will create this requestor appropriately for the
54 :     particular circumstance (direct connection, thru relay, etc).
55 :    
56 :     This code executes the high-level protocol, maintaining state between
57 :     calls to the peer to exchange the actual information.
58 :    
59 : olson 1.25 $last_update: Search for updates since this time.
60 :     $skip_tough_search: Do not use the time-consuming $fig->tough_search method as a last resort for peg mapping.
61 :     $update_thru: Search for updates until this time. Undef means to search for all since $last_update.
62 :     $log_file: Write logging information to this file.
63 :     $html_file: Write a HTML summary to this file.
64 :     $assignment_policy: If a list reference, contains the list of users from which we will accept assignments. If a code ref, a predicate that is passed ($peg, $timestamp, $author, $function) and returns true if the assignment should be made.
65 :    
66 : olson 1.1 =cut
67 :    
68 :     sub perform_update
69 :     {
70 : olson 1.25 my($fig, $peer, $last_update, $skip_tough_search, $update_thru, $log_file, $html_file,
71 :     $assignment_policy) = @_;
72 :    
73 :     my $allow_assignment;
74 : olson 1.22
75 :     $log_file = "/dev/null" unless $log_file ne "";
76 :     open($log_fh, ">>$log_file") or die "Cannot open logfile $log_file: $!\n";
77 :     $log_fh->autoflush(1);
78 :    
79 : olson 1.23 $html_file = "/dev/null" unless $html_file ne "";
80 :     open($html_fh, ">$html_file") or die "Cannot open htmlfile $html_file: $!\n";
81 :     $html_fh->autoflush(1);
82 :    
83 : olson 1.27 if (!defined($assignment_policy))
84 :     {
85 :     $allow_assignment = sub { 1;};
86 :     }
87 :     elsif (ref($assignment_policy) eq "CODE")
88 : olson 1.25 {
89 :     $allow_assignment = $assignment_policy;
90 :     }
91 :     elsif (ref($assignment_policy) eq "ARRAY")
92 :     {
93 :     my $ahash = {};
94 :     map { $ahash->{$_}++; } @$assignment_policy;
95 :     $allow_assignment = sub {
96 :     return $ahash->{$_[2]};
97 :     };
98 :     }
99 :     elsif (ref($assignment_policy) eq "HASH")
100 :     {
101 :     $allow_assignment = sub {
102 :     return $assignment_policy->{$_[2]};
103 :     };
104 :     }
105 :     else
106 :     {
107 :     print $log_fh "Invalid assignment policy $assignment_policy\n";
108 :     die "Invalid assignment policy $assignment_policy\n";
109 :     }
110 :    
111 : olson 1.23 my $now = localtime();
112 :     my $last_str = localtime($last_update);
113 :     print $html_fh <<END;
114 :     <h1>P2P Update at $now</h1>
115 :     Peer URL $peer->{url}<br>
116 :     Update from: $last_str<br>
117 :     END
118 :    
119 :     print $log_fh "Beginning P2P update at $now\n";
120 : olson 1.22 print $log_fh " Peer URL: $peer->{url}\n";
121 : olson 1.23 print $log_fh " Update from: $last_str\n";
122 : olson 1.22 print $log_fh "\n";
123 : olson 1.1
124 : olson 1.20 my $ret = $peer->request_update($last_update, $update_thru);
125 : olson 1.1
126 :     if (!$ret or ref($ret) ne "ARRAY")
127 :     {
128 : olson 1.18 die "perform_update: request_update failed\n";
129 : olson 1.1 }
130 :    
131 : olson 1.15 my($session, $target_release, $num_assignments, $num_annos, $num_pegs, $num_genomes,
132 : olson 1.1 $target_time, $compatible) = @$ret;
133 :    
134 : olson 1.18 print "perform_update: session=$session target=@$target_release num_annos=$num_annos\n";
135 : olson 1.1 print " num_pegs=$num_pegs num_genomes=$num_genomes target_time=$target_time compat=$compatible\n";
136 :    
137 : olson 1.22 my @my_release = $fig->get_release_info();
138 :    
139 :     print $log_fh "Session id = $session\n";
140 :     print $log_fh "Target release information: \n\t", join("\n\t", @$target_release), "\n";
141 :     print $log_fh "My release information: \n\t", join("\n\t", @my_release), "\n";
142 :     print $log_fh "$num_annos annotations\n";
143 :     print $log_fh "$num_assignments assignments\n";
144 :     print $log_fh "$num_pegs pegs\n";
145 :    
146 : olson 1.23 print $html_fh "Session id = $session<br>\n";
147 :     print $html_fh "Target release information: <br>\n\t", join("<br>\n\t", @$target_release), "<br>\n";
148 :     print $html_fh "My release information: <br>\n\t", join("<br>\n\t", @my_release), "<br>\n";
149 :     print $html_fh "$num_annos annotations<br>\n";
150 :     print $html_fh "$num_assignments assignments<br>\n";
151 :     print $html_fh "$num_pegs pegs<br>\n";
152 :    
153 : olson 1.1 #
154 : olson 1.19 # We now know the data release for our peer.
155 :     #
156 : olson 1.24 # Open up the peg translation cache database (a AnyDBM_File) tied
157 : olson 1.19 # to %peg_cache. We needn't worry about keeping it in a directory
158 :     # based on our current release, as it the cache directory is kept *in*
159 :     # the current data release directory.
160 :     #
161 :    
162 :     my $cache_handle;
163 :     my %peg_cache;
164 :     if ($target_release->[1] ne "")
165 :     {
166 :     my $cache_file = "pegcache.$target_release->[1].db";
167 : olson 1.30 my $cache_dir = "$FIG_Config::fig/var/P2PQueue";
168 :     &FIG::verify_dir("$FIG_Config::fig/var");
169 : olson 1.19 $fig->verify_dir($cache_dir);
170 :    
171 : olson 1.24 $cache_handle = tie(%peg_cache, "AnyDBM_File", "$cache_dir/$cache_file",
172 :     O_CREAT | O_RDWR, 0666);
173 : olson 1.19 $cache_handle or warn "Could not tie peg_cache to $cache_dir/$cache_file: $!\n";
174 :     }
175 :    
176 :     #
177 : olson 1.21 # peg_mapping is the local mapping from remote->local peg. This might
178 :     # be replacable by peg_cache from above.
179 : olson 1.1 #
180 : olson 1.21 my %peg_mapping;
181 : olson 1.1
182 : olson 1.21
183 : olson 1.1 #
184 : olson 1.21 # We have the information now to begin the update process. Retrieve the pegs.
185 : olson 1.1 #
186 :    
187 : olson 1.21 _compute_peg_mapping($fig, $peer, $session, $num_pegs, \%peg_mapping, \%peg_cache, $cache_handle,
188 :     $skip_tough_search);
189 : olson 1.7
190 : olson 1.24 eval { $cache_handle->sync();};
191 : olson 1.19 untie %peg_cache;
192 :    
193 :     #
194 : olson 1.15 # Create a list of locally-mapped annotations on a per-genome
195 :     # basis.
196 :     #
197 :    
198 :     my %genome_annos;
199 : olson 1.19
200 :     #
201 :     # %genome_assignments is a hash mapping from genome to a hashref
202 :     # that maps peg to function (since assignments are unique).
203 :     #
204 :     # (Hm. Unless two remote pegs map to the same local peg; unclear what to do
205 :     # then. Punt for now).
206 :     #
207 :     my %genome_assignments;
208 : olson 1.15
209 : olson 1.21 #
210 :     # Retrieve the annotations, and generate a list of mapped annotations.
211 :     #
212 :    
213 :     for (my $anno_start = 0; $anno_start < $num_annos; $anno_start += $anno_batch_size)
214 : olson 1.15 {
215 : olson 1.21 my $anno_req_len = $num_annos - $anno_start;
216 :     $anno_req_len = $anno_batch_size if $anno_req_len > $anno_batch_size;
217 : olson 1.15
218 : olson 1.21 print "Retrieve $anno_req_len annos at $anno_start\n";
219 : olson 1.22 print $log_fh "Retrieve $anno_req_len annos at $anno_start\n";
220 : olson 1.21
221 :     my $annos = $peer->get_annotations($session, $anno_start, $anno_req_len);
222 : olson 1.15
223 : olson 1.21 for my $anno (@$annos)
224 :     {
225 :     my($his_id, $ts, $author, $anno) = @$anno;
226 :    
227 :     my $my_id = $peg_mapping{$his_id};
228 :     next unless $my_id;
229 : olson 1.15
230 : olson 1.21 my $genome = $fig->genome_of($my_id);
231 :    
232 :     push(@{$genome_annos{$genome}}, [$my_id, $ts, $author, $anno]);
233 :     }
234 : olson 1.15 }
235 :    
236 : olson 1.19 #
237 :     # Do the same for the assignments
238 :     #
239 :    
240 : olson 1.20 # print Dumper($assignments);
241 :    
242 : olson 1.21
243 :     for (my $assign_start = 0; $assign_start < $num_assignments; $assign_start += $assign_batch_size)
244 : olson 1.19 {
245 : olson 1.21 my $assign_req_len = $num_assignments - $assign_start;
246 :     $assign_req_len = $assign_batch_size if $assign_req_len > $assign_batch_size;
247 : olson 1.19
248 : olson 1.21 print "Retrieve $assign_req_len assigns at $assign_start\n";
249 : olson 1.22 print $log_fh "Retrieve $assign_req_len assigns at $assign_start\n";
250 : olson 1.21
251 :     my $assignments = $peer->get_assignments($session, $assign_start, $assign_req_len);
252 :    
253 :     for my $assign (@$assignments)
254 :     {
255 :     my($his_id, $ts, $author, $func) = @$assign;
256 : olson 1.19
257 : olson 1.21 my $my_id = $peg_mapping{$his_id};
258 :     next unless $my_id;
259 : olson 1.19
260 : olson 1.21 my $genome = $fig->genome_of($my_id);
261 : olson 1.19
262 : olson 1.21 $genome_assignments{$genome}->{$my_id} = [$my_id, $ts, $author, $func];
263 :     }
264 : olson 1.19 }
265 :    
266 :     # print Dumper(\%genome_annos);
267 : olson 1.15
268 :     #
269 :     # Now install annotations.
270 :     #
271 :    
272 :     for my $genome (keys(%genome_annos))
273 :     {
274 : olson 1.19 #
275 :     # Plan: Apply the merge_annotations.pl logic. Read the annotations
276 :     # from the per-org annotations file, add the new ones here, sort, and remove duplicates.
277 :     # Write the results to the annotations file.
278 :     #
279 :     # When we are all done, rerun the index_annotations script.
280 :     #
281 :     # Why not do that incrementally? Partly because the annotation_seeks table doesn't
282 :     # have a column for the genome id, so a removal of old data would require a
283 :     # string-match query; since a complete reindex of the annotations is pretty
284 :     # fast (60 sec on a G4 laptop on a firewire disk), it's not clear whether the incremental
285 :     # update would actually be a win.
286 :     #
287 :    
288 :     my @annos = @{$genome_annos{$genome}};
289 :     my $assignments = $genome_assignments{$genome};
290 :     #
291 :     # %assignment_annos is a hash from peg to the list
292 :     # of annotations for that peg.
293 :     #
294 :     my %assignment_annos;
295 :    
296 :     my $dir = "$FIG_Config::organisms/$genome";
297 :     my $anno_file = "$dir/annotations";
298 :     my $anno_bak = "$dir/annotations." . time;
299 :    
300 :     my $new_count = @annos;
301 :    
302 :     #
303 :     # Rename the annotations file to a new name based on the current time.
304 :     #
305 :    
306 : olson 1.23 my $gs = $fig->genus_species($genome);
307 :     print $html_fh "<h1>Updates for $genome ($gs)</h1>\n";
308 :    
309 : olson 1.19 if (-f $anno_file)
310 :     {
311 :     rename($anno_file, $anno_bak) or die "Cannot rename $anno_file to $anno_bak: $!";
312 : olson 1.22 print $log_fh "Moved annotations file $anno_file to backup $anno_bak\n";
313 : olson 1.19 }
314 :    
315 :     if (open(my $fh, "<$anno_bak"))
316 :     {
317 :     #
318 :     # While we are scanning here, we look for the latest local assignment
319 :     # for any peg for which we are installing an assignment.
320 :     #
321 :     local($/) = "\n//\n";
322 :    
323 :     my($chunk, $peg, $ts, $author, $anno);
324 :    
325 :     while (defined($chunk = <$fh>))
326 :     {
327 :     chomp $chunk;
328 :     ($peg, $ts, $author, $anno) = split(/\n/, $chunk, 4);
329 :    
330 :     if ($peg =~ /^fig\|/ and $ts =~ /^\d+$/)
331 :     {
332 : olson 1.26 #
333 : olson 1.28 # The last field marks this as an "old" annotation (that is,
334 :     # already in place in this system), so we don't
335 : olson 1.26 # log its installation later.
336 :     #
337 :     my $ent = [$peg, $ts, $author, $anno, 1];
338 : olson 1.19 push(@annos, $ent);
339 :    
340 :     if (defined($assignments->{$peg}))
341 :     {
342 :     #
343 :     # We have an incoming assignment for this peg.
344 :     # Don't parse anything yet, but push the annotation
345 :     # on a list so we can sort by date.
346 :     #
347 :     push(@{$assignment_annos{$peg}}, $ent);
348 :     }
349 :     }
350 :     }
351 :     close($fh);
352 :     }
353 :    
354 :     #
355 :     # Determine if we are going to install an assignment.
356 :     #
357 :    
358 : olson 1.23 my $cgi_url = &FIG::cgi_url();
359 :     print $html_fh "<h2>Assignments made</h2>\n";
360 : olson 1.25 print $html_fh "<table border=\"1\">\n";
361 : olson 1.23 print $html_fh "<tr><th>PEG</th><th>Old assignment</th><th>New assignment</th><tr>\n";
362 :    
363 : olson 1.19 for my $peg (keys %$assignments)
364 :     {
365 : olson 1.20 my(undef, $ts, $author, $func) = @{$assignments->{$peg}};
366 :    
367 :     #
368 :     # Sort the existing annotations for this peg by date.
369 :     #
370 : olson 1.26 # Recall that this list has entries [$peg, $timestamp, $author, $anno, $old_flag]
371 : olson 1.20 #
372 :    
373 :     my @eannos;
374 :     if (ref($assignment_annos{$peg}))
375 :     {
376 :     @eannos = sort { $b->[1] <=> $a->[1] } @{$assignment_annos{$peg}};
377 :     }
378 :     else
379 :     {
380 :     #
381 :     # No assignment annotations found.
382 :     #
383 :     @eannos = ();
384 :     }
385 :    
386 :     # print "Assignment annos for $peg: ", Dumper(\@eannos);
387 : olson 1.19
388 :     #
389 : olson 1.20 # Filter out just the master assignments that are newer than
390 :     # the one we are contemplating putting in place.
391 : olson 1.19 #
392 :    
393 : olson 1.20 my @cand = grep {
394 :     ($_->[1] > $ts) and ($_->[3] =~ /Set master function to/)
395 :     } @eannos;
396 :    
397 :     if (@cand > 0)
398 :     {
399 :     #
400 :     # Here is were some policy needs to be put in place --
401 :     # we have a more recent annotation on the current system.
402 :     #
403 :     # For now, we will not install an assignment if there is any
404 :     # newer assignment in place.
405 :     #
406 :    
407 :     warn "Skipping assignment for $peg $func due to more recent assignment $cand[0]->[3]\n";
408 : olson 1.22 print $log_fh "Skipping assignment for $peg $func due to more recent assignment $cand[0]->[3]\n";
409 : olson 1.20 }
410 :     else
411 :     {
412 :     #
413 :     # Nothing is blocking us. While we are testing, just slam this assignment in.
414 :     #
415 : olson 1.19
416 : olson 1.20 my $old = $fig->function_of($peg, 'master');
417 :    
418 : olson 1.25 if ($old ne $func and &$allow_assignment($peg, $ts, $author, $func))
419 : olson 1.21 {
420 : olson 1.23 my $l = "$cgi_url/protein.cgi?prot=$peg";
421 :     print $html_fh "<tr><td><a href=\"$l\">$peg</a></td><td>$old</td><td>$func</td></tr>\n";
422 :    
423 : olson 1.21 print "Assign $peg $func\n";
424 : olson 1.22 print $log_fh "Assign $peg $func\n";
425 :     print $log_fh " was $old\n";
426 : olson 1.21 $fig->assign_function($peg, 'master', $func);
427 : olson 1.23
428 : olson 1.21 }
429 : olson 1.20 }
430 : olson 1.19 }
431 :    
432 : olson 1.23 print $html_fh "</table>\n";
433 :    
434 :     print $html_fh "<h2>Annotations added</h2>\n";
435 : olson 1.25 print $html_fh "<table border=\"1\">\n";
436 : olson 1.23 print $html_fh "<tr><th>PEG</th><th>Time</th><th>Author</th><th>Annotation</th></tr>\n";
437 :    
438 : olson 1.19 open(my $outfh, ">$anno_file") or die "Cannot open new annotation file $anno_file: $!\n";
439 :    
440 :     my $last;
441 :     my @sorted = sort { ($a->[0] cmp $b->[0]) or ($a->[1] <=> $b->[1]) } @annos;
442 :     my $inst = 0;
443 :     my $dup = 0;
444 :     foreach my $ann (@sorted)
445 :     {
446 : olson 1.29 my $txt = join("\n", @$ann[0..3]);
447 : olson 1.19 #
448 :     # Drop the trailing \n if there is one; we will add it back when we print and
449 :     # want to ensure the file format remains sane.
450 :     #
451 :     chomp $txt;
452 :     if ($txt ne $last)
453 :     {
454 : olson 1.23 my $peg = $ann->[0];
455 :     my $l = "$cgi_url/protein.cgi?prot=$peg";
456 : olson 1.26 if (!$ann->[4])
457 :     {
458 :     print $html_fh "<tr>" . join("\n", map { "<td>$_</td>" }
459 :     "<a href=\"$l\">$peg</a>",
460 :     scalar(localtime($ann->[1])), $ann->[2], $ann->[3])
461 :     . "</tr>\n";
462 :     }
463 : olson 1.23
464 : olson 1.19 print $outfh "$txt\n//\n";
465 :     $last = $txt;
466 : olson 1.21 # print "Inst $ann->[0] $ann->[1] $ann->[2]\n";
467 : olson 1.19 $inst++;
468 :     }
469 :     else
470 :     {
471 : olson 1.21 # print "Dup $ann->[0] $ann->[1] $ann->[2]\n";
472 : olson 1.19 $dup++;
473 :     }
474 :     }
475 : olson 1.23 print $html_fh "</table>\n";
476 : olson 1.19 close($outfh);
477 :     chmod(0666, $anno_file) or warn "Cannot chmod 0666 $anno_file: $!\n";
478 :     print "Wrote $anno_file. $new_count new annos, $inst installed, $dup duplicates\n";
479 : olson 1.22 print $log_fh "Wrote $anno_file. $new_count new annos, $inst installed, $dup duplicates\n";
480 : olson 1.15 }
481 : olson 1.23 close($html_fh);
482 : olson 1.1 }
483 :    
484 : olson 1.21 #
485 :     # Compute the peg mapping for a session.
486 :     #
487 :     # $fig Active FIG instance
488 :     # $peer P2P peer for this session.
489 :     # $session P2P session ID
490 :     # $peg_mapping Hash ref for the remote -> local PEG mapping
491 :     # $peg_cache Hash ref for the persistent remote -> local PEG mapping cache db.
492 : olson 1.24 # $cache_handle AnyDBM_File handle corresponding to $peg_cache.
493 : olson 1.21 #
494 :     sub _compute_peg_mapping
495 :     {
496 :     my($fig, $peer, $session, $num_pegs, $peg_mapping, $peg_cache, $cache_handle, $skip_tough_search) = @_;
497 :    
498 :     #
499 :     # genome_map is a hash mapping from target genome id to a list of
500 :     # pegs on the target. This is used to construct a finalize_pegs request after
501 :     # the first phase of peg mapping.
502 :     #
503 :    
504 :     my %genome_map;
505 :    
506 :     #
507 :     # target_genome_info is a hash mapping from target genome
508 :     # identifier to the target-side information on the genome -
509 :     # number of contigs, number of nucleotides, checksum.
510 :     #
511 :     # We accumulate it here across possibly multiple batches of
512 :     # peg retrievals in order to create a single finalization
513 :     # list.
514 :     #
515 :    
516 :     my %target_genome_info;
517 :    
518 :     #
519 :     # For very large transfers, we need to batch the peg processing.
520 :     #
521 :    
522 :     for (my $peg_start = 0; $peg_start < $num_pegs; $peg_start += $peg_batch_size)
523 :     {
524 :     my $peg_req_len = $num_pegs - $peg_start;
525 :     $peg_req_len = $peg_batch_size if $peg_req_len > $peg_batch_size;
526 :    
527 :     print "Getting $peg_req_len pegs at $peg_start\n";
528 : olson 1.22 print $log_fh "Getting $peg_req_len pegs at $peg_start\n";
529 : olson 1.21 my $ret = $peer->get_pegs($session, $peg_start, $peg_req_len);
530 :    
531 :     if (!$ret or ref($ret) ne "ARRAY")
532 :     {
533 :     die "perform_update: get_pegs failed\n";
534 :     }
535 :    
536 :     my($peg_list, $genome_list) = @$ret;
537 :    
538 :     for my $gent (@$genome_list)
539 :     {
540 :     $target_genome_info{$gent->[0]} = $gent;
541 :     }
542 :    
543 :     _compute_peg_mapping_batch($fig, $peer, $session, $peg_mapping, $peg_cache, $cache_handle,
544 :     $peg_list, \%genome_map);
545 :     }
546 :    
547 :     #
548 :     # We have finished first pass. Now go over the per-genome mappings that need to be made.
549 :     #
550 :     # $genome_map{$genome_id} is a list of pegs that reside on that genome.
551 :     # The pegs and genome id are both target-based identifiers.
552 :     #
553 :     # %target_genome_info defines the list of genome information we have on the remote
554 :     # side.
555 :     #
556 :     # We build a request to be passed to finalize_pegs. Each entry in the request is either
557 :     # ['peg_genome', $peg] which means that we have a genome that corresponds to the
558 :     # genome the peg is in. We can attempt to map via contig locations.
559 :     #
560 :     # If that is not the case, we pass a request entry of ['peg_unknown', $peg]
561 :     # which will result in the sequence data being returned.
562 :     #
563 :    
564 :     my @finalize_req = ();
565 :    
566 :     #
567 :     # local_genome maps a target peg identifier to the local genome id it translates to.
568 :     #
569 :     my %local_genome;
570 :    
571 :     for my $genome (keys(%target_genome_info))
572 :     {
573 :     my($tg, $n_contigs, $n_nucs, $cksum) = @{$target_genome_info{$genome}};
574 :    
575 :     $tg eq $genome or die "Invalid entry in target_genome_info for $genome => $tg, $n_contigs, $n_nucs, $cksum";
576 :    
577 :     #
578 :     # Don't bother unless we have any pegs to look up.
579 :     #
580 :     next unless defined($genome_map{$genome});
581 :    
582 :     #
583 :     # Determine if we have a local genome installed that matches precisely the
584 :     # genome on the target side.
585 :     #
586 :     my $my_genome = $fig->find_genome_by_content($genome, $n_contigs, $n_nucs, $cksum);
587 :    
588 :     my $pegs = $genome_map{$genome};
589 :    
590 :     if ($my_genome)
591 :     {
592 :     #
593 :     # We do have such a local genome. Generate a peg_genome request to
594 :     # get the location information from the target side.
595 :     #
596 :     # Also remember the local genome mapping for this peg.
597 :     #
598 :    
599 :     print "$genome mapped to $my_genome\n";
600 : olson 1.22 print $log_fh "$genome mapped to $my_genome\n";
601 : olson 1.21 for my $peg (@$pegs)
602 :     {
603 :     push(@finalize_req, ['peg_genome', $peg]);
604 :     $local_genome{$peg} = $my_genome;
605 :     }
606 :    
607 :     }
608 :     else
609 :     {
610 :     #
611 :     # We don't have such a genome. We need to retrieve the
612 :     # sequence data in order to finish mapping.
613 :     #
614 :     push(@finalize_req, map { ['peg_unknown', $_] } @$pegs);
615 :     }
616 :     }
617 :    
618 :     #
619 :     # We've built our finalization request. Handle it (possibly with batching here too).
620 :     #
621 :    
622 :     _process_finalization_request($fig, $peer, $session, $peg_mapping, $peg_cache, $cache_handle,
623 :     \%local_genome, \@finalize_req, $skip_tough_search);
624 :    
625 :     }
626 :    
627 :     #
628 :     # Process one batch of PEGs.
629 :     #
630 :     # Same args as _compute_peg_mapping, with the addition of:
631 :     #
632 :     # $peg_list List of pegs to be processed
633 :     # $genome_map Hash maintaining list of genomes with their pegs.
634 :     # $target_genome_info Hash maintaining overall list of target-side genome information.
635 :     #
636 :     sub _compute_peg_mapping_batch
637 :     {
638 :     my($fig, $peer, $session, $peg_mapping, $peg_cache, $cache_handle,
639 :     $peg_list, $genome_map, $target_genome_info) = @_;
640 :    
641 :     #
642 :     # Walk the list of pegs as returned from get_pegs() and determine what has to
643 :     # be done.
644 :     #
645 :     # If the entry is ['peg', $peg], we can use the peg ID as is.
646 :     #
647 :     # If the entry is ['peg_info', $peg, $alias_list, $genome], the peg
648 :     # has the given aliases, and is in the given genome.
649 :     #
650 :     for my $peg_info (@$peg_list)
651 :     {
652 :     my($key, $peg, @rest) = @$peg_info;
653 :    
654 :     if ($key eq 'peg')
655 :     {
656 :     #
657 :     # Peg id is directly usable.
658 :     #
659 :     $peg_mapping->{$peg} = $peg;
660 :     }
661 :     elsif ($key eq 'peg_info')
662 :     {
663 :     #
664 :     # Peg id not directly usable. See if we have it in the cache.
665 :     #
666 :    
667 :     if ((my $cached = $peg_cache->{$peg}) ne "")
668 :     {
669 :     #
670 :     # Cool, we've cached the result. Use it.
671 :     #
672 :    
673 :     $peg_mapping->{$peg} = $cached;
674 :     # warn "Found cached mapping $peg => $cached\n";
675 :     next;
676 :     }
677 :    
678 :     #
679 :     # It is not cached. Attempt to resolve by means of alias IDs.
680 :     #
681 :    
682 :     my($alias_list, $genome_id) = @rest;
683 :    
684 :     for my $alias (@$alias_list)
685 :     {
686 :     my $mapped = $fig->by_alias($alias);
687 :     if ($mapped)
688 :     {
689 :     print "$peg maps to $mapped via $alias\n";
690 : olson 1.22 print $log_fh "$peg maps to $mapped via $alias\n";
691 : olson 1.21 $peg_mapping->{$peg}= $mapped;
692 :     $peg_cache->{$peg} = $mapped;
693 :     last;
694 :     }
695 :     }
696 :    
697 :     #
698 :     # If we weren't able to resolve by ID,
699 :     # add to %genome_map as a PEG that will need
700 :     # to be resolved by means of contig location.
701 :     #
702 :    
703 :     if (!defined($peg_mapping->{$peg}))
704 :     {
705 :     push(@{$genome_map->{$genome_id}}, $peg);
706 :     print "$peg did not map on first pass\n";
707 : olson 1.22 print $log_fh "$peg did not map on first pass\n";
708 : olson 1.21 }
709 :     }
710 :     }
711 :    
712 :     #
713 :     # Flush the cache to write out any computed mappings.
714 :     #
715 : olson 1.24 eval { $cache_handle->sync();};
716 : olson 1.21
717 :     }
718 :    
719 :     sub _process_finalization_request
720 :     {
721 :     my($fig, $peer, $session, $peg_mapping, $peg_cache, $cache_handle,
722 :     $local_genome, $finalize_req, $skip_tough_search) = @_;
723 :    
724 :     #
725 :     # Immediately return unless there's something to do.
726 :     #
727 :     return unless ref($finalize_req) and @$finalize_req > 0;
728 : olson 1.1
729 : olson 1.21 while (@$finalize_req > 0)
730 :     {
731 :     my @req = splice(@$finalize_req, 0, $fin_batch_size);
732 :    
733 :     print "Invoking finalize_pegs on ", int(@req), " pegs\n";
734 : olson 1.22 print $log_fh "Invoking finalize_pegs on ", int(@req), " pegs\n";
735 : olson 1.21 my $ret = $peer->finalize_pegs($session, \@req);
736 :    
737 :     if (!$ret or ref($ret) ne "ARRAY")
738 :     {
739 :     die "perform_update: finalize_pegs failed\n";
740 :     }
741 :    
742 :     #
743 :     # The return is a list of either location entries or
744 :     # sequence data. Attempt to finish up the mapping.
745 :     #
746 :    
747 :     my(%sought, %sought_seq);
748 :    
749 :    
750 :     my $dbh = $fig->db_handle();
751 :     for my $entry (@$ret)
752 :     {
753 :     my($what, $peg, @rest) = @$entry;
754 :    
755 :     if ($what eq "peg_loc")
756 :     {
757 :     my($strand, $start, $end, $cksum, $seq) = @rest;
758 :    
759 :     #
760 :     # We have a contig location. Try to find a matching contig
761 :     # here, and see if it maps to something.
762 :     #
763 :    
764 :     my $my_genome = $local_genome->{$peg};
765 :     my $local_contig = $fig->find_contig_with_checksum($my_genome, $cksum);
766 :     if ($local_contig)
767 :     {
768 :     #
769 :     # Now look up the local peg. We match on the end location; depending on the strand
770 :     # the feature is on, we want to look at either minloc or maxloc.
771 :     #
772 :    
773 : olson 1.27 my($start_loc, $end_loc);
774 :    
775 :     if ($strand eq '-')
776 :     {
777 :     $start_loc = 'maxloc';
778 :     $end_loc = 'minloc';
779 :     }
780 :     else
781 :     {
782 :     $start_loc = 'minloc';
783 :     $end_loc = 'maxloc';
784 :     }
785 : olson 1.21
786 : olson 1.27 my $res = $dbh->SQL(qq!SELECT id, $start_loc from features
787 :     WHERE $end_loc = $end and genome = '$my_genome' and
788 : olson 1.21 contig = '$local_contig'
789 :     !);
790 :    
791 :     if ($res and @$res > 0)
792 :     {
793 : olson 1.27 my $id;
794 :     if (@$res == 1)
795 :     {
796 :     #
797 :     # Found a unique mapping.
798 :     #
799 :     $id = $res->[0]->[0];
800 :     }
801 :     else
802 :     {
803 :     #
804 :     # Multiple mappings found. See if one matches the
805 :     # start location. If it doesn't, pick the one that
806 :     # is closest in length.
807 :     #
808 :    
809 :     my @lens;
810 :    
811 :     for my $res_ent (@$res)
812 :     {
813 :     my($rid, $rloc) = @$res_ent;
814 :    
815 :     push(@lens, [$rid, abs($rloc - $end - ($start - $end))]);
816 :     warn "Matching $rid $rloc to $start\n";
817 :     if ($rloc == $start)
818 :     {
819 :     $id = $rid;
820 :     warn "Matched $rid\n";
821 :     last;
822 :     }
823 :     }
824 :    
825 :     if (!$id)
826 :     {
827 :     my @slens = sort { $a->[1] <=> $b->[1]} @lens;
828 :     my $len;
829 :     ($id, $len) = @{$slens[0]};
830 :     warn "No unique match found, picking closest match $id (len=$len)\n";
831 :     }
832 :     }
833 :    
834 : olson 1.21 $peg_mapping->{$peg} = $id;
835 :     $peg_cache->{$peg} = $id;
836 :     print "Mapped $peg to $id via contigs\n";
837 :     }
838 :     else
839 :     {
840 :     print "failed: $peg $my_genome and contig $local_contig start=$start end=$end strand=$strand\n";
841 : olson 1.22 print $log_fh "failed: $peg $my_genome and contig $local_contig start=$start end=$end strand=$strand\n";
842 : olson 1.23 print $html_fh "Contig match failed: $peg $my_genome contig $local_contig start $start end $end strand $strand<br>\n";
843 : olson 1.21 $sought{$peg}++;
844 :     $sought_seq{$peg} = $seq;
845 :     }
846 :     }
847 :     else
848 :     {
849 :     print "Mapping failed for $my_genome checksum $cksum\n";
850 : olson 1.22 print $log_fh "Mapping failed for $my_genome checksum $cksum\n";
851 : olson 1.23 print $html_fh "Mapping failed for $my_genome checksum $cksum<br>\n";
852 : olson 1.21 $sought{$peg}++;
853 :     $sought_seq{$peg} = $seq;
854 :     }
855 :     }
856 :     elsif ($what eq "peg_seq")
857 :     {
858 :     my($seq) = @rest;
859 :    
860 :     $sought{$peg}++;
861 :     $sought_seq{$peg} = $seq;
862 :     }
863 :     }
864 :    
865 :     #
866 :     # Now see if we need to do a tough search.
867 :     #
868 :    
869 :     if (keys(%sought) > 0 and !$skip_tough_search)
870 :     {
871 :     my %trans;
872 :    
873 :     print "Starting tough search\n";
874 : olson 1.22 print $log_fh "Starting tough search\n";
875 : olson 1.21
876 :     $fig->tough_search(undef, \%sought_seq, \%trans, \%sought);
877 :     print "Tough search translated: \n";
878 : olson 1.22 print $log_fh "Tough search translated: \n";
879 : olson 1.21 while (my($tpeg, $ttrans) = each(%trans))
880 :     {
881 :     print " $tpeg -> $ttrans\n";
882 : olson 1.22 print $log_fh " $tpeg -> $ttrans\n";
883 : olson 1.21 $peg_mapping->{$tpeg} = $ttrans;
884 :     $peg_cache->{$tpeg} = $ttrans;
885 :     }
886 :     }
887 :     }
888 :     }
889 : olson 1.15
890 : olson 1.1 #############
891 :     #
892 :     # P2P Relay
893 :     #
894 :     #############
895 :    
896 :    
897 :     package P2P::Relay;
898 :     use strict;
899 :    
900 :     use Data::Dumper;
901 :     use SOAP::Lite;
902 :    
903 :     use P2P;
904 :    
905 :     sub new
906 :     {
907 :     my($class, $url) = @_;
908 :    
909 : olson 1.25 my $creds = [];
910 : olson 1.24
911 :     my $proxy = SOAP::Lite->uri($P2P::ns_relay)->proxy([$url,
912 :     credentials => $creds]);
913 : olson 1.1
914 :     my $self = {
915 :     url => $url,
916 :     proxy => $proxy,
917 :     };
918 :     return bless($self, $class);
919 :     }
920 :    
921 :     sub enumerate_annotation_systems
922 :     {
923 :     my($self) = @_;
924 :    
925 :     return $self->{proxy}->enumerate_annotation_systems()->result;
926 :     }
927 :    
928 :     sub fetch_queries
929 :     {
930 :     my($self, $id) = @_;
931 :    
932 :     my $reply = $self->{proxy}->fetch_queries($id);
933 :    
934 :     if ($reply->fault)
935 :     {
936 :     print "Failed to fetch queries: ", $reply->faultcode, " ", $reply->faultstring, "\n";
937 :     return undef;
938 :     }
939 :    
940 :     return $reply->result;
941 :     }
942 :    
943 :     sub deposit_answer
944 :     {
945 :     my($self, $id, $key, $answer) = @_;
946 :    
947 :     my $reply = $self->{proxy}->deposit_answer($id, $key,
948 :     SOAP::Data->type('base64')->value($answer));
949 :    
950 :     if ($reply->fault)
951 :     {
952 :     print "deposit_answer got fault: ", $reply->faultcode, " ", $reply->faultstring, "\n";
953 :     return undef;
954 :     }
955 :    
956 :     return $reply;
957 :     }
958 :    
959 :     =pod
960 :    
961 :     =head1 await_result
962 :    
963 :     Await the result from a possibly-asynchronous soap request.
964 :    
965 :     Look at the reply that we have. If it's a deferred reply, loop polling
966 :     the relay for the actual result.
967 :    
968 :     We determine if the reply is a deferred reply by examining the namespace
969 :     URI of the response. A response will be generated from the relay's namespace,
970 :     rather than that of the application itself.
971 :    
972 :     =cut
973 :    
974 :     sub await_result
975 :     {
976 :     my($self, $reply) = @_;
977 :    
978 :     while (1)
979 :     {
980 :     #
981 :     # Retrieve the namespace of the response, which is the first
982 :     # element in the body of the message.
983 :     #
984 :     my $ns = $reply->namespaceuriof('/Envelope/Body/[1]');
985 : olson 1.20 # print "Reply ns=$ns want $P2P::ns_relay\n";
986 : olson 1.1
987 :     if ($ns eq $P2P::ns_relay)
988 :     {
989 :     my $val = $reply->result;
990 : olson 1.20 # print "got val=", Dumper($val);
991 : olson 1.1 if ($val->[0] eq 'deferred')
992 :     {
993 :     #
994 :     # Sleep a little, then try to retrieve the response.
995 :     #
996 :    
997 :     sleep(1);
998 :     my $id = $val->[1];
999 :    
1000 :     print "Retrieving reply\n";
1001 :     $reply = $self->{proxy}->call_completed($id);
1002 :     }
1003 :     else
1004 :     {
1005 :     #
1006 :     # We're not sure what to do here..
1007 :     #
1008 :     return undef;
1009 :     }
1010 :     }
1011 :     else
1012 :     {
1013 :     #
1014 :     # We got an actual response. Return it.
1015 :     #
1016 :    
1017 :     return $reply;
1018 :     }
1019 :     }
1020 :     }
1021 :    
1022 :     #############
1023 :     #
1024 :     # P2P Requestor
1025 :     #
1026 :     #############
1027 :    
1028 :     package P2P::Requestor;
1029 :     use strict;
1030 :    
1031 :     use Data::Dumper;
1032 : olson 1.15 use Time::HiRes qw( usleep ualarm gettimeofday tv_interval );
1033 : olson 1.1
1034 :     use SOAP::Lite;
1035 : olson 1.15
1036 :     #use SOAP::Lite +trace => [qw(transport dispatch result debug)];
1037 : olson 1.1 use P2P;
1038 :    
1039 :     #
1040 :     # Create a new Requestor. It contains a reference to the FIG instance
1041 :     # so that we can run the protocol completely from in here.
1042 :     #
1043 :    
1044 :     sub new
1045 :     {
1046 : olson 1.24 my($class, $fig, $url, $peer_id, $relay, $credentials) = @_;
1047 : olson 1.1
1048 : olson 1.24 $credentials = [] unless ref($credentials);
1049 :    
1050 : olson 1.27 my $proxy = SOAP::Lite->uri($ns_p2p)->proxy($url, timeout => 3600);
1051 :    
1052 :     for my $cred (@$credentials)
1053 :     {
1054 :     $proxy->transport->credentials(@$cred);
1055 :     }
1056 : olson 1.1
1057 :     my $self = {
1058 :     fig => $fig,
1059 :     url => $url,
1060 :     peer_id => $peer_id,
1061 :     proxy => $proxy,
1062 :     relay => $relay,
1063 :     };
1064 :     return bless($self, $class);
1065 :     }
1066 :    
1067 :     #
1068 :     # First step: Request an update.
1069 :     #
1070 :     # We need to determine some notion of what our release is, since we are not
1071 :     # currently tagging them explicitly. Until we delve into this more,
1072 :     # I am going to return a null release, which means the same-release
1073 :     # optimization won't be able to kick in.
1074 :     #
1075 :     # We also need to determine the last time we got an update from this
1076 :     # system.
1077 :     #
1078 :    
1079 :     sub request_update
1080 :     {
1081 : olson 1.20 my($self, $last_update, $update_thru) = @_;
1082 : olson 1.1
1083 : olson 1.18 my $rel = [$self->{fig}->get_release_info()];
1084 : olson 1.1
1085 :     if (!defined($last_update))
1086 :     {
1087 :     $last_update = $self->{fig}->get_peer_last_update($self->{peer_id});
1088 :     }
1089 : olson 1.17
1090 :     print "Requesting update via $self->{proxy}\n";
1091 : olson 1.20 my $reply = $self->{proxy}->request_update($rel, $last_update, $update_thru);
1092 :     # print "Got reply ", Dumper($reply);
1093 : olson 1.1
1094 :     if ($self->{relay})
1095 :     {
1096 :     $reply = $self->{relay}->await_result($reply);
1097 :     }
1098 :    
1099 :     if ($reply->fault)
1100 :     {
1101 :     print "request_update triggered fault: ", $reply->faultcode, " ", $reply->faultstring, "\n";
1102 :     return undef;
1103 :     }
1104 :    
1105 :     return $reply->result;
1106 :     }
1107 :    
1108 :     =pod
1109 :    
1110 :     =head1 get_pegs($session_id, $start, $length)
1111 :    
1112 :    
1113 :     =cut
1114 :    
1115 :     sub get_pegs
1116 :     {
1117 :     my($self, $session_id, $start, $length) = @_;
1118 :    
1119 :     return $self->call("get_pegs", $session_id, $start, $length);
1120 :     }
1121 :    
1122 : olson 1.6 sub finalize_pegs
1123 :     {
1124 :     my($self, $session_id, $request) = @_;
1125 :    
1126 :     return $self->call("finalize_pegs", $session_id, $request);
1127 :     }
1128 :    
1129 : olson 1.15 sub get_annotations
1130 :     {
1131 :     my($self, $session_id, $start, $length) = @_;
1132 :    
1133 :     return $self->call("get_annotations", $session_id, $start, $length);
1134 :     }
1135 :    
1136 : olson 1.19 sub get_assignments
1137 :     {
1138 :     my($self, $session_id, $start, $length) = @_;
1139 :    
1140 :     return $self->call("get_assignments", $session_id, $start, $length);
1141 :     }
1142 :    
1143 : olson 1.1 sub call
1144 :     {
1145 :     my($self, $func, @args) = @_;
1146 : olson 1.15
1147 :     my $t0 = [gettimeofday()];
1148 :     print "Calling $func\n";
1149 : olson 1.1 my $reply = $self->{proxy}->$func(@args);
1150 : olson 1.15 my $t1 = [gettimeofday()];
1151 :    
1152 :     my $elap = tv_interval($t0, $t1);
1153 :     print "Call to $func took $elap\n";
1154 : olson 1.1
1155 :     if ($self->{relay})
1156 :     {
1157 :     $reply = $self->{relay}->await_result($reply);
1158 :     }
1159 :    
1160 :     if ($reply->fault)
1161 :     {
1162 :     print "$func triggered fault: ", $reply->faultcode, " ", $reply->faultstring, "\n";
1163 :     return undef;
1164 :     }
1165 :    
1166 :     return $reply->result;
1167 :     }
1168 :    
1169 :    
1170 :     #############
1171 :     #
1172 :     # P2P Service
1173 :     #
1174 :     # Code in this module is invoked on the target on behalf of a requestor.
1175 :     #
1176 :     #############
1177 :    
1178 :     package P2P::Service;
1179 :    
1180 :     use Data::Dumper;
1181 :    
1182 :     use FIG;
1183 :     use FIG_Config;
1184 :     use strict;
1185 :    
1186 :     use File::Temp qw(tempdir);
1187 :     use File::Basename;
1188 :    
1189 :     sub request_update
1190 :     {
1191 : olson 1.20 my($class, $his_release, $last_update, $update_thru)= @_;
1192 : olson 1.1
1193 :     #
1194 :     # Verify input.
1195 :     #
1196 :    
1197 :     if ($last_update !~ /^\d+$/)
1198 :     {
1199 :     die "request_update: last_update must be a number (not '$last_update')\n";
1200 :     }
1201 :    
1202 : olson 1.20 if ($update_thru eq "")
1203 :     {
1204 :     $update_thru = time + 10000;
1205 :     }
1206 :    
1207 : olson 1.1 #
1208 :     # Create a new session id and a spool directory to use for storage
1209 :     # of information about it. This can go in the tempdir since it is
1210 :     # not persistent.
1211 :     #
1212 :    
1213 :     &FIG::verify_dir("$FIG_Config::temp/p2p_spool");
1214 : olson 1.22 my $spool_dir = tempdir(DIR => "$FIG_Config::temp/p2p_spool");
1215 : olson 1.1
1216 : olson 1.22 #my $spool_dir = "$FIG_Config::temp/p2p_spool/test";
1217 : olson 1.1 &FIG::verify_dir($spool_dir);
1218 :    
1219 :     my $session_id = basename($spool_dir);
1220 :     my $now = time;
1221 :    
1222 :     #
1223 :     # Gather the list of pegs and annotations for the update.
1224 :     #
1225 :    
1226 :     my $fig = new FIG;
1227 :    
1228 :     my $all_genomes = [$fig->genomes];
1229 :    
1230 :     my %all_genomes = map { $_ => 1 } @$all_genomes;
1231 :    
1232 :     my %pegs;
1233 : olson 1.15
1234 :     #
1235 :     # We keep track of usernames that have been seen, so that
1236 :     # we can both update our local user database and
1237 :     # we can report them to our peer.
1238 :     #
1239 :    
1240 :     my %users;
1241 : olson 1.1
1242 :     my $num_annos = 0;
1243 :     my $num_genomes = 0;
1244 :     my $num_pegs = 0;
1245 : olson 1.15 my $num_assignments = 0;
1246 : olson 1.1
1247 :     my $anno_fh;
1248 :     open($anno_fh, ">$spool_dir/annos");
1249 :    
1250 :     my $peg_fh;
1251 :     open($peg_fh, ">$spool_dir/pegs");
1252 :    
1253 :     my $genome_fh;
1254 :     open($genome_fh, ">$spool_dir/genomes");
1255 :    
1256 : olson 1.15 my $assign_fh;
1257 :     open($assign_fh, ">$spool_dir/assignments");
1258 :    
1259 : olson 1.25 #
1260 :     # We originally used a query to get the PEGs that needed to have annotations
1261 :     # sent. Unfortunately, this performed very poorly due to all of the resultant
1262 :     # seeking around in the annotations files.
1263 :     #
1264 :     # The code below just runs through all of the anno files looking for annos.
1265 :     #
1266 :     # A better way to do this would be to do a query to retrieve the genome id's for
1267 :     # genomes that have updates. The problem here is that the annotation_seeks
1268 :     # table doesn't have an explicit genome field.
1269 :     #
1270 :     # Surprisingly, to me anyway, the following query appers to run quickly, in both
1271 :     # postgres and mysql:
1272 :     #
1273 :     # SELECT distinct(substring(fid from 5 for position('.peg.' in fid) - 5))
1274 :     # FROM annotation_seeks
1275 :     # WHERE dateof > some-date.
1276 :     #
1277 :     # The output of that can be parsed to get the genome id and just those
1278 :     # annotations files searched.
1279 :     #
1280 :    
1281 : olson 1.1 for my $genome (@$all_genomes)
1282 :     {
1283 :     my $num_annos_for_genome = 0;
1284 : olson 1.15 my %assignment;
1285 : olson 1.1
1286 :     my $genome_dir = "$FIG_Config::organisms/$genome";
1287 :     next unless -d $genome_dir;
1288 :    
1289 :     my $afh;
1290 :     if (open($afh, "$genome_dir/annotations"))
1291 :     {
1292 :     my($fid, $anno_time, $who, $anno_text);
1293 :     local($/);
1294 :     $/ = "//\n";
1295 :     while (my $ann = <$afh>)
1296 :     {
1297 :     chomp $ann;
1298 :    
1299 :     if ((($fid, $anno_time, $who, $anno_text) =
1300 :     ($ann =~ /^(fig\|\d+\.\d+\.peg\.\d+)\n(\d+)\n(\S+)\n(.*\S)/s)) and
1301 : olson 1.20 $anno_time > $last_update and
1302 :     $anno_time < $update_thru)
1303 : olson 1.1
1304 :     {
1305 :     #
1306 : olson 1.15 # Update users list.
1307 :     #
1308 :    
1309 :     $users{$who}++;
1310 :    
1311 :     #
1312 : olson 1.1 # Look up aliases if we haven't seen this fid before.
1313 :     #
1314 :    
1315 :     if (!defined($pegs{$fid}))
1316 :     {
1317 :     my @aliases = $fig->feature_aliases($fid);
1318 :    
1319 :     print $peg_fh join("\t", $fid, $genome, @aliases), "\n";
1320 :     $num_pegs++;
1321 :     }
1322 :    
1323 :     print $anno_fh "$ann//\n";
1324 :    
1325 :     $pegs{$fid}++;
1326 :    
1327 :     $num_annos_for_genome++;
1328 :     $num_annos++;
1329 : olson 1.15
1330 :     #
1331 :     # While we're here, see if this is an assignment. We check in the
1332 :     # %assignment hash, which is keyed on fid, to see if we already
1333 :     # saw an assignment for this fid. If we have, we keep this one only if
1334 :     # the assignment time on it is later than the one we saw already.
1335 :     #
1336 :     # We are only looking at master assignments for now. We will need
1337 :     # to return to this issue and reexamine it, but in order to move
1338 :     # forward I am only matching master assignments.
1339 :     #
1340 :    
1341 :     if ($anno_text =~ /Set master function to\n(\S[^\n]+\S)/)
1342 :     {
1343 :     my $func = $1;
1344 :    
1345 :     my $other = $assignment{$fid};
1346 :    
1347 :     #
1348 :     # If we haven't seen an assignment for this fid,
1349 :     # or if it the other assignment has a timestamp that
1350 :     # is earlier than this one, set the assignment.
1351 :     #
1352 :    
1353 :     if (!defined($other) or
1354 :     ($other->[1] < $anno_time))
1355 :     {
1356 :     $assignment{$fid} = [$fid, $anno_time, $who, $func];
1357 :     }
1358 :     }
1359 : olson 1.1 }
1360 :     }
1361 :     close($afh);
1362 : olson 1.15
1363 :     #
1364 :     # Write out the assignments that remain.
1365 :     #
1366 :    
1367 :     for my $fid (sort keys(%assignment))
1368 :     {
1369 :     print $assign_fh join("\t", @{$assignment{$fid}}), "\n";
1370 :     $num_assignments++;
1371 :     }
1372 : olson 1.1 }
1373 : olson 1.15
1374 : olson 1.1
1375 :     #
1376 :     # Determine genome information if we have annotations for this one.
1377 :     #
1378 :    
1379 :     if ($num_annos_for_genome > 0)
1380 :     {
1381 :     $num_genomes++;
1382 :     if (open(my $cfh, "<$genome_dir/COUNTS"))
1383 :     {
1384 :     if ($_ = <$cfh>)
1385 :     {
1386 :     chomp;
1387 :     my($cgenome, $n_contigs, $total_nucs, $cksum) = split(/\t/, $_);
1388 :     if ($cgenome ne $genome)
1389 :     {
1390 :     warn "Hm, $genome has a COUNTS file with genome=$cgenome that does not match\n";
1391 :     }
1392 :     else
1393 :     {
1394 :     print $genome_fh join("\t",
1395 :     $genome, $num_annos_for_genome, $n_contigs,
1396 :     $total_nucs, $cksum), "\n";
1397 :     }
1398 :     }
1399 :     }
1400 :     }
1401 :    
1402 :     }
1403 :     close($anno_fh);
1404 :     close($peg_fh);
1405 :     close($genome_fh);
1406 : olson 1.15 close($assign_fh);
1407 : olson 1.1
1408 :     print "Pegs: $num_pegs\n";
1409 :     print "Genomes: $num_genomes\n";
1410 :     print "Annos: $num_annos\n";
1411 :    
1412 :     #
1413 :     # Check compatibility.
1414 :     #
1415 :    
1416 : olson 1.18 my $my_release = [$fig->get_release_info()];
1417 :    
1418 :     #
1419 :     # Release id is $my_release->[1].
1420 :     #
1421 :    
1422 :     my $compatible;
1423 :     if ($my_release->[1] ne "" and $his_release->[1] ne "")
1424 :     {
1425 :     #
1426 :     # Both releases must be defined for them to be compatible.
1427 :     #
1428 :     # At some point we need to consider the derived-release issue.
1429 :     #
1430 :    
1431 :     $compatible = $my_release->[1] eq $his_release->[1];
1432 :     }
1433 :     else
1434 :     {
1435 :     $compatible = 0;
1436 :     }
1437 : olson 1.1
1438 :     open(my $fh, ">$spool_dir/INFO");
1439 :     print $fh "requestor_release\t$his_release\n";
1440 :     print $fh "last_update\t$last_update\n";
1441 : olson 1.20 print $fh "update_thru\t$update_thru\n";
1442 : olson 1.1 print $fh "cur_update\t$now\n";
1443 :     print $fh "target_release\t$my_release\n";
1444 :     print $fh "compatible\t$compatible\n";
1445 :     print $fh "num_pegs\t$num_pegs\n";
1446 :     print $fh "num_genomes\t$num_genomes\n";
1447 :     print $fh "num_annos\t$num_annos\n";
1448 : olson 1.15 print $fh "num_assignments\t$num_assignments\n";
1449 : olson 1.1 close($fh);
1450 :    
1451 : olson 1.15 #
1452 :     # Construct list of users, and pdate local user database.
1453 :     #
1454 :    
1455 :     my @users = keys(%users);
1456 : olson 1.17 # $fig->ensure_users(\@users);
1457 : olson 1.15
1458 :     return [$session_id, $my_release, $num_assignments, $num_annos, $num_pegs, $num_genomes,
1459 : olson 1.16 $now, $compatible, \@users];
1460 : olson 1.1 }
1461 :    
1462 :    
1463 :     sub get_pegs
1464 :     {
1465 :     my($self, $session_id, $start, $len) = @_;
1466 :     my(%session_info);
1467 :    
1468 :     my $spool_dir = "$FIG_Config::temp/p2p_spool/$session_id";
1469 :    
1470 :     -d $spool_dir or die "Invalid session id $session_id";
1471 :    
1472 :     #
1473 :     # Read in the cached information for this session.
1474 :     #
1475 :    
1476 :     open(my $info_fh, "<$spool_dir/INFO") or die "Cannot open INFO file: $!";
1477 :     while (<$info_fh>)
1478 :     {
1479 :     chomp;
1480 :     my($var, $val) = split(/\t/, $_, 2);
1481 :     $session_info{$var} = $val;
1482 :     }
1483 :     close($info_fh);
1484 :    
1485 :     #
1486 :     # Sanity check start and length.
1487 :     #
1488 :    
1489 :     if ($start < 0 or $start >= $session_info{num_pegs})
1490 :     {
1491 :     die "Invalid start position $start";
1492 :     }
1493 :    
1494 :     if ($len < 0 or ($start + $len - 1) >= $session_info{num_pegs})
1495 :     {
1496 :     die "Invalid length $len";
1497 :     }
1498 :    
1499 :     #
1500 :     # Open file, spin to the starting line, then start reading.
1501 :     #
1502 :    
1503 :     open(my $peg_fh, "<$spool_dir/pegs") or die "Cannot open pegs file: $!";
1504 :    
1505 :     my $peg_output = [];
1506 :     my $genome_output = [];
1507 :    
1508 :     my $peg_num = 0;
1509 :     my $genomes_to_show = [];
1510 :     my %genomes_to_show;
1511 :    
1512 :     my($fid, $genome, @aliases);
1513 :    
1514 :     while (<$peg_fh>)
1515 :     {
1516 :     next if ($peg_num < $start);
1517 :    
1518 :     last if ($peg_num > ($start + $len));
1519 :    
1520 :     chomp;
1521 :    
1522 :     #
1523 :     # OK, this is a peg to process.
1524 :     # It's easy if we're compatible.
1525 :     #
1526 :    
1527 :     ($fid, $genome, @aliases) = split(/\t/, $_);
1528 :    
1529 :     if ($session_info{compatible})
1530 :     {
1531 :     push(@$peg_output, ['peg', $fid]);
1532 :     }
1533 :     else
1534 :     {
1535 :     if (!$genomes_to_show{$genome})
1536 :     {
1537 :     push(@$genomes_to_show, $genome);
1538 :     $genomes_to_show{$genome}++;
1539 :     }
1540 :     push(@$peg_output, ['peg_info', $fid, [@aliases], $genome]);
1541 :     }
1542 :     }
1543 :     continue
1544 :     {
1545 :     $peg_num++;
1546 :     }
1547 :    
1548 :     #
1549 :     # Read the genomes file, returning information about genomes referenced
1550 :     # in the pegs returned.
1551 :     #
1552 :    
1553 :     my $n_left = @$genomes_to_show;
1554 :    
1555 :     open(my $gfh, "<$spool_dir/genomes") or die "Cannot open genomes file: $!";
1556 :     while ($n_left > 0 and $_ = <$gfh>)
1557 :     {
1558 :     chomp;
1559 :    
1560 :     my($genome, $n_annos, $n_contigs, $n_nucs, $cksum) = split(/\t/);
1561 :    
1562 :     if ($genomes_to_show{$genome})
1563 :     {
1564 :     push(@$genome_output, [$genome, $n_contigs, $n_nucs, $cksum]);
1565 :     $n_left--;
1566 :     }
1567 :     }
1568 :     close($gfh);
1569 :    
1570 :     return [$peg_output, $genome_output];
1571 :     }
1572 : olson 1.6
1573 :     sub finalize_pegs
1574 :     {
1575 :     my($self, $session, $request) = @_;
1576 :     my($out);
1577 :    
1578 :     my $fig = new FIG;
1579 :    
1580 :     #
1581 :     # Walk the request handling appropriately. This is fairly easy, as it
1582 :     # is just a matter of pulling either sequence or location/contig data.
1583 :     #
1584 :    
1585 :     for my $item (@$request)
1586 :     {
1587 :     my($what, $peg) = @$item;
1588 :    
1589 :     if ($what eq "peg_genome")
1590 :     {
1591 :     #
1592 :     # Return the location and contig checksum for this peg.
1593 :     #
1594 : olson 1.13 # We also include the sequence in case the contig mapping doesn't work.
1595 :     #
1596 : olson 1.6
1597 :     my $loc = $fig->feature_location($peg);
1598 :     my $contig = $fig->contig_of($loc);
1599 : olson 1.7 my $cksum = $fig->contig_checksum($fig->genome_of($peg), $contig);
1600 : olson 1.13 my $seq = $fig->get_translation($peg);
1601 : olson 1.6
1602 :     push(@$out, ['peg_loc', $peg,
1603 : olson 1.13 $fig->strand_of($peg),
1604 : olson 1.6 $fig->beg_of($loc), $fig->end_of($loc),
1605 : olson 1.13 $cksum, $seq]);
1606 : olson 1.6
1607 :     }
1608 : olson 1.7 elsif ($what eq "peg_unknown")
1609 : olson 1.6 {
1610 :     my $seq = $fig->get_translation($peg);
1611 :     push(@$out, ['peg_seq', $peg, $seq]);
1612 :     }
1613 :     }
1614 :     return $out;
1615 :     }
1616 :    
1617 : olson 1.15
1618 :     sub get_annotations
1619 :     {
1620 :     my($self, $session_id, $start, $len) = @_;
1621 :    
1622 :     #
1623 :     # This is now easy; just run thru the saved annotations and return.
1624 :     #
1625 :    
1626 :     my(%session_info);
1627 :    
1628 :     my $spool_dir = "$FIG_Config::temp/p2p_spool/$session_id";
1629 :    
1630 :     -d $spool_dir or die "Invalid session id $session_id";
1631 :    
1632 :     #
1633 :     # Read in the cached information for this session.
1634 :     #
1635 :    
1636 :     open(my $info_fh, "<$spool_dir/INFO") or die "Cannot open INFO file: $!";
1637 :     while (<$info_fh>)
1638 :     {
1639 :     chomp;
1640 :     my($var, $val) = split(/\t/, $_, 2);
1641 :     $session_info{$var} = $val;
1642 :     }
1643 :     close($info_fh);
1644 :    
1645 :     #
1646 :     # Sanity check start and length.
1647 :     #
1648 :    
1649 :     if ($start < 0 or $start >= $session_info{num_annos})
1650 :     {
1651 :     die "Invalid start position $start";
1652 :     }
1653 :    
1654 :     if ($len < 0 or ($start + $len - 1) >= $session_info{num_annos})
1655 :     {
1656 :     die "Invalid length $len";
1657 :     }
1658 :    
1659 :     #
1660 :     # Open file, spin to the starting line, then start reading.
1661 :     #
1662 :    
1663 :     open(my $anno_fh, "<$spool_dir/annos") or die "Cannot open annos file: $!";
1664 :    
1665 :     my $anno_output = [];
1666 :    
1667 :     my $anno_num = 0;
1668 :    
1669 :     local $/ = "//\n";
1670 :     while (<$anno_fh>)
1671 :     {
1672 :     next if ($anno_num < $start);
1673 :    
1674 :     last if ($anno_num > ($start + $len));
1675 :    
1676 :     chomp;
1677 :    
1678 :     my($id, $date, $author, $anno) = split(/\n/, $_, 4);
1679 :    
1680 :     push(@$anno_output, [$id, $date, $author, $anno]);
1681 :     }
1682 :     continue
1683 :     {
1684 :     $anno_num++;
1685 :     }
1686 :    
1687 :     return $anno_output;
1688 :     }
1689 : olson 1.19
1690 :     sub get_assignments
1691 :     {
1692 :     my($self, $session_id, $start, $len) = @_;
1693 :    
1694 :     #
1695 :     # This is now easy; just run thru the saved assignments and return.
1696 :     #
1697 :    
1698 :     my(%session_info);
1699 :    
1700 :     my $spool_dir = "$FIG_Config::temp/p2p_spool/$session_id";
1701 :    
1702 :     -d $spool_dir or die "Invalid session id $session_id";
1703 :    
1704 :     #
1705 :     # Read in the cached information for this session.
1706 :     #
1707 :    
1708 :     open(my $info_fh, "<$spool_dir/INFO") or die "Cannot open INFO file: $!";
1709 :     while (<$info_fh>)
1710 :     {
1711 :     chomp;
1712 :     my($var, $val) = split(/\t/, $_, 2);
1713 :     $session_info{$var} = $val;
1714 :     }
1715 :     close($info_fh);
1716 :    
1717 :     #
1718 :     # Sanity check start and length.
1719 :     #
1720 :    
1721 :     if ($start < 0 or $start >= $session_info{num_assignments})
1722 :     {
1723 :     die "Invalid start position $start";
1724 :     }
1725 :    
1726 :     if ($len < 0 or ($start + $len - 1) >= $session_info{num_assignments})
1727 :     {
1728 :     die "Invalid length $len";
1729 :     }
1730 :    
1731 :     #
1732 :     # Open file, spin to the starting line, then start reading.
1733 :     #
1734 :    
1735 :     open(my $assign_fh, "<$spool_dir/assignments") or die "Cannot open assignments file: $!";
1736 :    
1737 :     my $assign_output = [];
1738 :    
1739 :     my $assign_num = 0;
1740 :    
1741 :     while (<$assign_fh>)
1742 :     {
1743 :     next if ($assign_num < $start);
1744 :    
1745 :     last if ($assign_num > ($start + $len));
1746 :    
1747 :     chomp;
1748 :    
1749 :     my($id, $date, $author, $func) = split(/\t/, $_, 4);
1750 :    
1751 :     push(@$assign_output, [$id, $date, $author, $func]);
1752 :     }
1753 :     continue
1754 :     {
1755 :     $assign_num++;
1756 :     }
1757 :    
1758 :     return $assign_output;
1759 :     }
1760 :    
1761 : olson 1.22 1;

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3