blib/lib/Bio/Graphics/Browser2/GFFhelper.pm untested

filter: Statementstmt 0.0% 0 / 260 Branchbran 0.0% 0 / 88 Conditioncond 0.0% 0 / 103 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 33 Podpod 0.0% 0 / 24 totaltotal 0.0% 0 / 508 CC 45 SCAR 32.2
CC
45
Cov
0%
read_gff
72.0
get_range
56.0
parse_gff_line
42.0
CRAP 25.0
1 # $Id$
2  
3 =head1 NAME
4  
5 Bio::Graphics::Browser2::GFFhelper -- Helps gbrowse plugins handle GFF
6  
7 =head1 SYNOPSIS
8  
9 package Bio::Graphics::Browser2::Plugin::MyPlugin;
10  
11 use vars qw/@ISA $ROLLBACK/;
12  
13 @ISA = qw/ Bio::Graphics::Browser2::Plugin
14 Bio::Graphics::Browser2::GFFhelper /;
15  
16 $ROLLBACK = '/tmp/';
17  
18 # other plugin subs skipped...
19  
20 sub save_segment {
21 my ($self, $segment) = @_;
22 return 0 unless $ROLLBACK;
23 $self->{rb_loc} ||= $ROLLBACK;
24 $self->save_state($segment);
25 1;
26 }
27  
28 sub gff_from_rollback {
29 my $self = shift;
30 my $conf = $self->configuration;
31  
32 # don't save a persistent rb_id, look for a CGI param each time
33 my $rollback = $self->config_param('rb_id');
34  
35 my $gff = $self->rollback($rollback);
36  
37 # this is a rollback to an earlier version of an existing segment
38 # we don't need DNA, just the GFF
39 $gff;
40 }
41  
42 # read GFF2 dialects
43 sub gff {
44 my $self = shift;
45 my $gff = shift;
46  
47 # set a flag to add a header to the GFF
48 $self->{header} = 1;
49  
50 # set sequence name in case the GFF does not have it
51 $self->refseq('L16622');
52  
53 # process the GFF, convert it to GFF3, get the sequence
54 my ($newGFF, $dna) = $self->read_gff($gff);
55 return ($newGFF, $dna);
56 }
57  
58 =head1 DESCRIPTION
59  
60 This modules helps process GFF prior to loading into the database and provides
61 rollback capability for feature editors/loaders
62  
63 =head2 GFF help
64  
65 This module deals with the different GFF2 dialects and changes
66 them to GFF3 format. It also allows conversion of Bio::DB::GFF::Feature
67 objects to Bio::SeqFeature::Generic objects, which is required for consistent
68 feature and attribute handling across different input/output formats.
69  
70 =head2 Sequence Extraction
71  
72 If DNA is appended to the GFF, it will be extracted. The read_gff
73 method returns a string containing processed GFF and also a sequence
74 string.
75  
76 =head2 Rollbacks
77  
78 The state of a segment can be captured and saved in case the user
79 wishes to revert to an earlier version of the segment after
80 editing/deleting features. The last 10 modified segments are saved
81 in a round-robin rotation. In plugins that inherit
82 methods from this module, the $ROLLBACK variable must be defined
83 with a string containing the path to a directory where the web
84 user ('apache', 'nobody', etc.) has write access. If $ROLLBACK
85 is undefined, the rollback functionality is disabled.
86  
87 =head1 FEEDBACK
88  
89 See the GMOD website for information on bug submission http://www.gmod.org
90  
91 =head1 AUTHOR - Sheldon McKay
92  
93 Email smckay@bcgsc.bc.ca
94  
95 This package and its accompanying libraries is free software; you can
96 redistribute it and/or modify it under the terms of the GPL (either
97 version 1, or at your option, any later version) or the Artistic
98 License 2.0. Refer to LICENSE for the full license text. In addition,
99 please see DISCLAIMER.txt for disclaimers of warranty.
100  
101  
102 =cut
103  
104 package Bio::Graphics::Browser2::GFFhelper;
105  
106 use strict;
107 use IO::String;
108 use Bio::Root::Root;
109 use CGI qw/:standard/;
110 use Bio::DB::GFF::Homol;
111 use Bio::SeqFeature::Generic;
112 use Storable qw/store retrieve/;
113  
114 use Data::Dumper;
115  
116 use vars qw/ @ISA /;
117  
118 @ISA = qw/ Bio::Root::Root /;
119  
120  
121 sub read_gff {
122 my ($self, $text) = @_;
123 $self->throw("No GFF to parse") unless $text;
124 my $seqid = $self->refseq;
125  
126 my (@seq, $gff) = ();
127  
128 # give up if the GFF is not correctly formatted
129 $self->throw("This does not look like GFF to me\n$text")
130 if $text !~ /^(\S+\s+){7}\S+/m || $text =~ /^LOCUS|^FT/m;
131
132 for ( split "\n", $text ) {
133 # save the sequence
134 push @seq, $_ and next if /^>/ || !/\S\s+\S/;
135  
136 # interpret the header
137 if ( /\#\#sequence-region\s+(\S+)\s+(-?\d+)\s+(-?\d+)/ ) {
138 $self->refseq($1);
139 $self->start($2);
140 $self->end($3);
141 }
142
143 # save the GFF
144 $gff .= $_ . "\n" if /\S\s+\S/ && !/^(>|##)/;
145 }
146  
147 # dump fasta header and assemble the sequence
148 shift @seq if @seq && $seq[0] =~ />/;
149 $self->seq(join '', @seq);
150  
151 # make sure the sequence name and range are defined
152 unless ( $self->start && $self->end && $self->refseq) {
153 $self->get_range($gff);
154 }
155  
156 return $self->fix_gff($gff);
157 }
158  
159 # Create a list of pseudo Bio::DB::GFF::Feature objects
160 # the attributes will be saved as a hash rather
161 # than a canned database query
162 sub parse_gff {
163 my ($self, $gff) = @_;
164 my @feats = ();
165 for ( split "\n", $gff ) {
166 next if /^\#\#/ || !/\t/ || /reference\tcomponent/i;
167 push @feats, $self->parse_gff_line($_);
168 }
169 @feats;
170 }
171  
172 sub parse_gff_line {
173 my ($self, $gff_line) = @_;
174 my $groupobj;
175 my $seqid = $self->refseq;
176 my $db = $self->database;
177 $gff_line =~ s/\"//g;
178  
179 my ( $ref, $source, $method, $start, $stop,
180 $score, $strand, $phase, $group) = split "\t", $gff_line;
181 next unless defined($ref) && defined($method) && defined($start) && defined($stop);
182 foreach (\$score,\$strand,\$phase) {
183 undef $$_ if $$_ eq '.';
184 }
185
186 $seqid ||= $ref;
187  
188 $db->preferred_groups(['gene', 'mRNA']);
189 my ($gclass,$gname,$tstart,$tstop,$attributes) = $db->split_group($group);
190
191 # create a group or target object
192 if ( $tstart && $tstop ) {
193 $groupobj = FakeHomol->new($gclass,$gname,$tstart,$tstop);
194 }
195 elsif ( $gname && $gclass ) {
196 $groupobj = Bio::DB::GFF::Featname->new($gclass,$gname);
197 }
198  
199 # create a Bio::DB::GFF::Feature
200 my @args = ( undef, $seqid, $start, $stop, $method );
201 push @args, ($source, $score, $strand, $phase, undef );
202
203 my $f = Bio::DB::GFF::Feature->new(@args);
204
205 $f->group($groupobj) if $groupobj;
206
207 # save the attributes!
208 $f->{attributes} = $attributes;
209 $f;
210 }
211  
212  
213 # rework the GFF feature attributes into GFF3
214 sub new_gff_string {
215 my ($self, $f, $version) = @_;
216 $f->version($version || 3);
217 my @gff = split "\t", $f->gff_string(1);
218 my $segment = $self->segments->[0];
219 my $source = $self->{source} || $f->source_tag;
220 my $refseq = $self->refseq || $segment->ref;
221 my $atts = $f->{attributes};
222
223 $gff[1] = $source if $source;
224 $gff[0] = $refseq if $refseq;
225 chomp $gff[-1];
226  
227 my @group_field;
228 for ( @$atts ) {
229 push @group_field, _escape($_->[0]) . '=' . _escape($_->[1]);
230 }
231 my $group_field = join ';', @group_field;
232  
233 my $gff = join "\t", @gff;
234
235 if ( $group_field ) {
236 $gff .= $f->class ? ";$group_field" : "\t$group_field";
237 }
238  
239 $gff;
240 }
241  
242 sub fix_gff {
243 my ($self, $gff) = @_;
244  
245 # convert features to Bio::SeqFeature::Generic objects
246 my @feats = $self->parse_gff($gff);
247  
248 # rebuild the GFF as GFF3
249 my @gff = map { $self->new_gff_string($_) } @feats;
250
251 # add a header if required
252 unshift @gff, $self->gff_header(3) if $self->{header};
253 return (join "\n", @gff) . "\n";
254 }
255  
256 sub gff_header {
257 my $self = shift;
258 my $ver = shift || 3;
259 my $exists = shift;
260 my $date = localtime;
261 my $start = $self->start || 0;
262 my $end = $self->end || 0;
263 my $ref = $self->refseq;
264 my $seq = $self->seq || '';
265 $start = 1 if $start > 1;
266 $end = (length $seq) + 1 if $end < length $seq;
267  
268 my $header = "##gff-version $ver\n##date $date\n";
269
270 # don't give GFF.pm this line if the segment exists
271 $header .= "##sequence-region $ref $start $end\n" unless $exists;
272
273 $header .= "##source Bio::Graphics::Browser2::GFFhelper.pm";
274 $header;
275 }
276  
277 sub origin {
278 my ($self, $gff) = @_;
279 my $desc = $self->{desc};
280 my $start = 1;
281 my $end = length $self->seq;
282 my $ref = $self->refseq;
283 my $src = $self->{source};
284
285 my $group = "ID=Accession:$ref";
286 $group .= ';Note=' . _escape($desc) if $desc;
287 $gff . join ("\t", $ref, $src, 'origin', $start, $end, '.', '.', '.', $group);
288 }
289  
290 # convert the feature into a Bio::SeqFeature::Generic object
291 sub gff2Generic {
292 my ($self, $f) = @_;
293  
294 my $feat = Bio::SeqFeature::Generic->new( -primary_tag => $f->primary_tag,
295 -source_tag => $f->source_tag,
296 -phase => $f->phase,
297 -score => $f->score,
298 -start => $f->start,
299 -end => $f->end,
300 -strand => $f->strand );
301  
302 my $att = $self->process_attributes($f);
303 for my $t ( keys %$att ) {
304 my @v = (ref $att->{$t}) ? @{$att->{$t}} : ($att->{$t});
305 for my $v ( @v ) {
306 $feat->add_tag_value( $t => $v );
307 }
308 }
309
310 $feat;
311 }
312  
313  
314 sub process_attributes {
315 my ($self, $f) = @_;
316  
317 my $att = $f->attributes || $self->{missing_attributes};
318  
319 # handle GFF2.5 targets
320 if ( my $t = $f->target ) {
321 my $tclass = $t->class;
322 my $tname = $t->name;
323 $att->{Target} = "$tclass:$tname";
324 $att->{tstart} = [$t->start];
325 $att->{tend} = [$t->end];
326 }
327 elsif ( $f->group ) {
328 my $class = $f->class;
329 my $name = $f->name;
330 push @{$att->{$class}}, $name if $class && $name;
331 }
332 for ( keys %$att ) {
333 # make sure the value is an array ref
334 my $V = $att->{$_};
335 $V = [$V] unless ref $V;
336 for my $v ( @{$V} ) {
337 $v =~ s/;/,/g;
338 $v =~ s/\"|\s+$//g;
339 }
340 }
341  
342 $att;
343 }
344  
345  
346 ####################################
347 # Sequence attribute getter/setters
348 ####################################
349 *ref = *refseq;
350 sub refseq {
351 my ($self, $id) = @_;
352 return $self->{seq}->{id} unless $id;
353 $self->{seq}->{id} = $id;
354 $self->{seq}->{id};
355 }
356  
357 sub start {
358 my ($self, $start) = @_;
359 return $self->{seq}->{start} unless $start;
360 $self->{seq}->{start} = $start;
361 $self->{seq}->{start};
362 }
363  
364 sub end {
365 my ($self, $end) = @_;
366 return $self->{seq}->{end} unless $end;
367 $self->{seq}->{end} = $end;
368 $self->{seq}->{end};
369 }
370  
371 sub seq {
372 my ($self, $seq) = @_;
373 return $self->{seq}->{seq} unless $seq;
374 $self->{seq}->{seq} = $seq;
375 $self->{seq}->{seq};
376 }
377  
378 # we need to get the sequence name and range if it was not specified
379 # elsewhere
380 sub get_range {
381 my ($self, $gff ) = @_;
382 my @nums = ();
383  
384 for ( split "\n", $gff ) {
385 next if /\#/;
386 my @word = split "\t", $_;
387 next if !$word[3] || !$word[4];
388 $self->refseq($word[0])
389 unless $word[0] =~ /\.|SEQ/ || $self->refseq;
390 push @nums, @word[3,4] if $word[3] =~ /^\d+$/ && $word[4] =~ /^\d+$/;
391 }
392  
393 # give up if the sequence has no name
394 $self->throw("A Sequence ID is required for this GFF file")
395 unless $self->refseq;
396
397 my @sorted = sort { $a <=> $b } @nums if @nums;
398 $self->start($sorted[0]);
399 $self->end($sorted[-1]);
400 }
401 ####################################
402  
403  
404 ###################################
405 # Rollback functions
406 ###################################
407  
408 sub save_state {
409 my ($self, $segment) = @_;
410 $segment || $self->throw('No segment');
411 my $path = $self->{rb_loc};
412 $path .= '/' unless $path =~ /\/$/;
413 my $file = $path . 'rollback';
414 my $key = $segment . ' ' . localtime;
415  
416 my $cache = -e $file ? retrieve( $file ) : {};
417 $cache->{$key}->{timestamp} = time;
418 $cache->{$key}->{gff} = [];
419  
420 my @feats = grep {
421 $_->start >= $segment->start - 1 &&
422 $_->end <= $segment->end + 1 &&
423 lc $_->method ne 'component';
424 } $segment->features;
425  
426 for ( @feats ) {
427 push @{$cache->{$key}->{gff}}, $_->gff3_string;
428 }
429  
430 # limit the number of saved segments to 10
431 my @keys = _keys_by_date($cache);
432 if ( @keys > 10 ) {
433 my $count;
434 for ( @keys ) {
435 next unless ++$count > 9;
436 delete $cache->{$_};
437 }
438 }
439  
440 store $cache, $file;
441 }
442  
443 # return a list of keys, newest first
444 sub _keys_by_date {
445 my $h = shift;
446 return map { $_->[1] }
447 sort { $b->[0] <=> $a->[0] }
448 map { [$h->{$_}->{timestamp}, $_] }
449 keys %$h;
450 }
451  
452 # retrieves a cached segment or a list of saved segments
453 sub rollback {
454 my ($self, $key) = @_;
455 my $path = $self->{rb_loc};
456 $path .= '/' unless $path =~ /\/$/;
457 my $file = $path . 'rollback';
458 -e $file || return '';
459 my $cache = retrieve( $file );
460  
461 if ( $key ) {
462 my @gff = @{$cache->{$key}->{gff}};
463 return $self->gff_header(3,1) . "\n" . join '', @gff;
464 }
465 else {
466 return _keys_by_date($cache);
467 }
468 }
469  
470  
471 # called by configure_form methods if req'd
472 sub rollback_form {
473 my ($self, $msg, $filter) = @_;
474  
475 # make sure we only get what we want to see
476 my @keys = $filter ? grep { /$filter/ } $self->rollback
477 : $self->rollback;
478 @keys || return '';
479  
480 my $rb = $self->config_name('rb_id');
481  
482 # first menu item empty
483 unshift @keys, '';
484  
485 my $help = a( { -onclick => "alert('$msg')",
486 -href => "javascript:void(0)",
487 -title => "help" }, ' [?]' );
488  
489 return table(
490 [
491 Tr( { -class => 'searchtitle' },
492 [
493 td( font( { -color => 'black' },
494 b('Restore saved segment') )),
495 td( { -class => 'searchbody' },
496 h3( popup_menu ( -name => $rb,
497 -values => \@keys ), $help))
498 ]
499 )
500 ]
501 );
502 }
503  
504 ###################################################
505  
506 # internal method stolen from Bio::DB::GFF
507 # GFF3-ify our attributes
508 sub _escape {
509 my $self = shift;
510 my $toencode = shift || $self;
511 $toencode =~ s/([^a-zA-Z0-9_. :?^*\(\)\[\]@!-])/uc sprintf("%%%02x",ord($1))/eg;
512 $toencode =~ tr/ /+/;
513 $toencode;
514 }
515  
516  
517 1;
518  
519  
520 package FakeHomol;
521  
522 sub new {
523 my $caller = shift;
524 my ( $class, $name, $start, $stop ) = @_;
525 my $self = { class => $class,
526 name => $name,
527 start => $start,
528 stop => $stop };
529 return bless $self;
530 }
531  
532 sub start {
533 my ($self, $start) = @_;
534 $self->{start} ||= $start;
535 $self->{start};
536 }
537  
538 *stop = *end;
539 sub end {
540 my ($self, $end) = @_;
541 $self->{stop} ||= $end;
542 $self->{stop};
543 }
544  
545 sub class {
546 my ($self, $class) = @_;
547 $self->{class} ||= $class;
548 $self->{class};
549 }
550  
551 sub name {
552 my ($self, $name) = @_;
553 $self->{name} ||= $name;
554 $self->{name};
555 }
556  
557 1;