Bio-Graphics

 view release on metacpan or  search on metacpan

lib/Bio/Graphics/Panel.pm  view on Meta::CPAN

package Bio::Graphics::Panel;

use strict;
use Bio::Graphics::Glyph::Factory;
use Bio::Graphics::Feature;
use Bio::Graphics::GDWrapper;

# KEYLABELFONT must be treated as string until image_class is established
use constant KEYLABELFONT => 'gdMediumBoldFont';
use constant KEYSPACING   => 5; # extra space between key columns
use constant KEYPADTOP    => 5;  # extra padding before the key starts
use constant KEYCOLOR     => 'wheat';
use constant KEYSTYLE     => 'bottom';
use constant KEYALIGN     => 'left';
use constant GRIDCOLOR    => 'lightcyan';
use constant GRIDMAJORCOLOR    => 'lightgrey';
use constant MISSING_TRACK_COLOR =>'gray';
use constant EXTRA_RIGHT_PADDING => 30;

use base qw(Bio::Root::Root);
our $GlyphScratch;

my %COLORS;  # translation table for symbolic color names to RGB triple
my $IMAGEMAP = 'bgmap00001';
read_colors();

sub api_version { 1.8 }

# Create a new panel of a given width and height, and add lists of features
# one by one
sub new {
  my $class = shift;
  $class    = ref($class) || $class;
  my %options = @_;

  $class->read_colors() unless %COLORS;

  my $length = $options{-length} || 0;
  my $offset = $options{-offset}  || 0;
  my $spacing = $options{-spacing} || 5;
  my $bgcolor = $options{-bgcolor} || 'white';
  my $keyfont = $options{-key_font} || KEYLABELFONT;
  my $keycolor = $options{-key_color} || KEYCOLOR;
  my $keyspacing = $options{-key_spacing} || KEYSPACING;
  my $keystyle = $options{-key_style} || KEYSTYLE;
  my $keyalign = $options{-key_align} || KEYALIGN;
  my $suppress_key = $options{-suppress_key} || 0;
  my $allcallbacks = $options{-all_callbacks} || 0;
  my $gridcolor    = $options{-gridcolor} || GRIDCOLOR;
  my $gridmajorcolor    = $options{-gridmajorcolor} || GRIDMAJORCOLOR;
  my $grid         = $options{-grid}       || 0;
  my $extend_grid  = $options{-extend_grid}|| 0;
  my $flip         = $options{-flip}       || 0;
  my $empty_track_style   = $options{-empty_tracks} || 'key';
  my $autopad      = defined $options{-auto_pad} ? $options{-auto_pad} : 1;
  my $truecolor    = $options{-truecolor}  || 0;
  my $truetype     = $options{-truetype}  || 0;
  my $image_class  = ($options{-image_class} && $options{-image_class} =~ /SVG/)
                      ? 'GD::SVG'
		      : $options{-image_class} || 'GD';  # Allow users to specify GD::SVG using SVG
  my $linkrule     = $options{-link};
  my $titlerule    = $options{-title};
  my $targetrule   = $options{-target};
  my $background   = $options{-background};
  my $postgrid     = $options{-postgrid};
  $options{-stop}||= $options{-end};  # damn damn damn
  my $add_categories= $options{-add_category_labels};

  if (my $seg = $options{-segment}) {
    $offset = eval {$seg->start-1} || 0;
    $length = $seg->length;
  }

  $offset   ||= $options{-start}-1 if defined $options{-start};
  $length   ||= $options{-stop}-$options{-start}+1 
     if defined $options{-start} && defined $options{-stop};

  # bring in the image generator class, since we will need it soon anyway
  eval "require $image_class; 1" or $class->throw($@);

  return bless {
		tracks => [],
		width      => $options{-width} || 600,
		pad_top    => $options{-pad_top}||0,
		pad_bottom => $options{-pad_bottom}||0,
		pad_left   => $options{-pad_left}||0,
		pad_right  => $options{-pad_right}||0,
		global_alpha => $options{-alpha} || 0,
		length => $length,
		offset => $offset,
		gridcolor => $gridcolor,
		gridmajorcolor => $gridmajorcolor,
		grid    => $grid,
		extend_grid    => $extend_grid,
		bgcolor => $bgcolor,
		height => 0, # AUTO
		spacing => $spacing,
		key_font => $keyfont,
		key_color => $keycolor,
		key_spacing => $keyspacing,
		key_style => $keystyle,
		key_align => $keyalign,
		suppress_key => $suppress_key,
		background => $background,
		postgrid   => $postgrid,
		autopad   => $autopad,
		all_callbacks => $allcallbacks,
		truecolor     => $truecolor,
		truetype      => $truetype,
		flip          => $flip,
		linkrule      => $linkrule,
		titlerule     => $titlerule,
		targetrule    => $targetrule,
		empty_track_style  => $empty_track_style,
		image_class  => $image_class,
		image_package => $image_class . '::Image',     # Accessors
		polygon_package => $image_class . '::Polygon',
		add_category_labels => $add_categories,
		key_boxes  => [],
	       },$class;
}

sub rotate {
  my $self = shift;
  my $d    = $self->{rotate};
  $self->{rotate} = shift if @_;
  $d;
}

sub pad_left {
  my $self = shift;
  my $g = $self->{pad_left};
  $self->{pad_left} = shift if @_;
  $g;
}
sub pad_right {
  my $self = shift;
  my $g = $self->{pad_right};
  $self->{pad_right} = shift if @_;
  $g;
}
sub pad_top {
  my $self = shift;
  my $g = $self->{pad_top};
  $self->{pad_top} = shift if @_;
  $g;
}
sub pad_bottom {
  my $self = shift;
  my $g = $self->{pad_bottom};
  $self->{pad_bottom} = shift if @_;
  $g;
}
sub extend_grid {
  my $self = shift;
  my $g = $self->{extend_grid};
  $self->{extend_grid} = shift if @_;
  $g;
}
sub flip {
  my $self = shift;
  my $g = $self->{flip};
  $self->{flip} = shift if @_;
  $g;
}
sub truetype {
  my $self = shift;

lib/Bio/Graphics/Panel.pm  view on Meta::CPAN

  my $self = shift;
  $self->{scale} ||= $self->width/($self->length);
}

sub start { shift->{offset}+1}
sub end   { $_[0]->start + $_[0]->{length}-1}

sub offset { shift->{offset} }
sub width {
  my $self = shift;
  my $d = $self->{width};
  $self->{width} = shift if @_;
  $d;
}

sub left {
  my $self = shift;
  $self->pad_left;
}
sub right {
  my $self = shift;
  $self->pad_left + $self->width; # - $self->pad_right;
}
sub top {
  shift->pad_top;
}
sub bottom {
  my $self = shift;
  $self->height - $self->pad_bottom;
}

sub spacing {
  my $self = shift;
  my $d = $self->{spacing};
  $self->{spacing} = shift if @_;
  $d;
}

sub key_spacing {
  my $self = shift;
  my $d = $self->{key_spacing};
  $self->{key_spacing} = shift if @_;
  $d;
}

sub length {
  my $self = shift;
  my $d = $self->{length};
  if (@_) {
    my $l = shift;
    $l = $l->length if ref($l) && $l->can('length');
    $self->{length} = $l;
  }
  $d;
}

sub gridcolor {shift->{gridcolor}}

sub gridmajorcolor {shift->{gridmajorcolor}}

sub all_callbacks { shift->{all_callbacks} }

sub add_track {
  my $self = shift;
  $self->_do_add_track(scalar(@{$self->{tracks}}),@_);
}

sub unshift_track {
  my $self = shift;
  $self->_do_add_track(0,@_);
}

sub insert_track {
  my $self = shift;
  my $position = shift;
  $self->_do_add_track($position,@_);
}


# create a feature and factory pair
# see Factory.pm for the format of the options
# The thing returned is actually a generic Glyph
sub _do_add_track {
  my $self     = shift;
  my $position = shift;

  # due to indecision, we accept features
  # and/or glyph types in the first two arguments
  my ($features,$glyph_name) = ([],undef);
  while ( @_ && $_[0] !~ /^-/) {
    my $arg = shift;
    $features   = $arg and next if ref($arg);
    $glyph_name = $arg and next unless ref($arg);
  }

  my %args = @_;
  my ($map,$ss,%options);

  foreach (keys %args) {
    (my $canonical = lc $_) =~ s/^-//;
    if ($canonical eq 'glyph') {
      $map = $args{$_};
      delete $args{$_};
    } elsif ($canonical eq 'stylesheet') {
      $ss  = $args{$_};
      delete $args{$_};
    } else {
      $options{$canonical} = $args{$_};
    }
  }

  $glyph_name = $map if defined $map;
  $glyph_name ||= 'generic';

  local $^W = 0;  # uninitialized variable warnings under 5.00503

  my $panel_map =
    ref($map) eq 'CODE' ?  sub {
      my $feature = shift;
      return 'track' if eval { defined $feature->primary_tag && $feature->primary_tag  eq 'track' };
      return 'group' if eval { defined $feature->primary_tag && $feature->primary_tag  eq 'group' };

lib/Bio/Graphics/Panel.pm  view on Meta::CPAN


  -pad_left   Additional whitespace between left     0
	      of image and contents, in pixels

  -pad_right  Additional whitespace between right    0
	      of image and bottom, in pixels

  -bgcolor    Background color for the panel as a    white
	      whole

  -key_color  Background color for the key printed   wheat
              at bottom of panel (if any)

  -key_spacing Spacing between key glyphs in the     10
               key printed at bottom of panel
               (if any)

  -key_font    Font to use in printed key            gdMediumBoldFont
	       captions.

  -key_style   Whether to print key at bottom of     none
	       panel ("bottom"), between each
	       track ("between"), to the left of
               each track ("left"), to the right
               of each track ("right") or
               not at all ("none").

  -add_category_labels                               false
               Whether to add the "category" to
               the track key. The category is
               an optional argument that can
               be attached to each track. If
               a category is present, and this
               option is true, then the category
               will be added to the track label
               in parentheses. For example, if
               -key is "Protein matches" and
               -category is "vertebrate", then
               the track will be labeled
               "Protein matches (vertebrate)".

  -auto_pad    If "left" or "right" keys are in use  true
               then setting auto_pad to a true value
               will allow the panel to adjust its
               width in order to accomodate the
               length of the longest key.

  -empty_tracks What to do when a track is empty.    suppress
              Options are to suppress the track
              completely ("suppress"), to show just
              the key in "between" mode ("key"),
              to draw a thin grey line ("line"),
              or to draw a dashed line ("dashed").

  -flip       flip the drawing coordinates left     false
              to right, so that lower coordinates
              are to the right.  This can be
              useful for drawing (-) strand
              features.

  -all_callbacks Whether to invoke callbacks on      false
               the automatic "track" and "group"
               glyphs.

  -grid        Whether to draw a vertical grid in    false
               the background.  Pass a scalar true
               value to have a grid drawn at
               regular intervals (corresponding
               to the minor ticks of the arrow
	       glyph).  Pass an array reference
               to draw the grid at the specified
               positions.

  -gridcolor   Color of the grid                     lightcyan

  -gridmajorcolor Color of grid major intervals      cyan

  -extend_grid If true, extend the grid into the pad false
               top and pad_bottom regions

  -background  An image or callback to use for the   none
               background of the image. Will be
               invoked I<before> drawing the grid.

  -postgrid    An image or callback to use for the   none
               background of the image.  Will be 
               invoked I<after> drawing the grid.

  -truecolor   Create a truecolor (24-bit) image.    false
               Useful when working with the
               "image" glyph.

  -truetype    Render text using scaleable vector    false
               fonts rather than bitmap fonts.

  -image_class To create output in scalable vector
               graphics (SVG), optionally pass the image
               class parameter 'GD::SVG'. Defaults to
               using vanilla GD. See the corresponding
               image_class() method below for details.

  -link, -title, -target
               These options are used when creating imagemaps
               for display on the web.  See L</"Creating Imagemaps">.


Typically you will pass new() an object that implements the
Bio::RangeI interface, providing a length() method, from which the
panel will derive its scale.

  $panel = Bio::Graphics::Panel->new(-segment => $sequence,
				     -width   => 800);

new() will return undef in case of an error.

Note that if you use the "left" or "right" key styles, you are
responsible for allocating sufficient -pad_left or -pad_right room for
the labels to appear.  The necessary width is the number of characters
in the longest key times the font width (gdMediumBoldFont by default)
plus 3 pixels of internal padding.  The simplest way to calculate this
is to iterate over the possible track labels, find the largest one,

lib/Bio/Graphics/Panel.pm  view on Meta::CPAN

              track label.

  -fgcolor    Foreground color		   black

  -bgcolor    Background color             turquoise

  -linewidth  Width of lines drawn by	   1
	      glyph

  -height     Height of glyph		   10

  -font       Glyph font		   gdSmallFont

  -fontcolor  Primary font color	   black

  -font2color Secondary font color	   turquoise

  -opacity    Value from 0.0 (invisible)   1.0
                to 1.0 (opaque) which
                controls the translucency
                of overlapping features.

  -label      Whether to draw a label	   false

  -description  Whether to draw a          false
              description

  -bump	      Bump direction		   0

  -sort_order Specify layout sort order    "default"

  -feature_limit
              Maximum number of features   undef (unlimited)
                 to display

  -bump_limit Maximum number of levels     undef (unlimited)
              to bump

  -hbumppad   Additional horizontal        0
              padding between bumped
              features

  -strand_arrow Whether to indicate        undef (false)
                 strandedness

  -stranded    Synonym for -strand_arrow   undef (false)

  -part_labels Whether to label individual undef (false)
               subparts.

  -part_label_merge Whether to merge       undef (false)
              adjacent subparts when
              labeling.

  -connector  Type of connector to         none
	      use to connect related
	      features.  Options are
	      "solid," "hat", "dashed", 
              "quill" and "none".

  -all_callbacks Whether to invoke         undef
              callbacks for autogenerated
              "track" and "group" glyphs

  -subpart_callbacks Whether to invoke     false
              callbacks for subparts of
              the glyph.

  -box_subparts Return boxes around feature          0
               subparts rather than around the
               feature itself.

  -link, -title, -target
               These options are used when creating imagemaps
               for display on the web.  See L</"Creating Imagemaps">.

  -filter      Select which features to
               display. Must be a CODE reference.

B<Specifying colors:> Colors can be expressed in either of two ways:
as symbolic names such as "cyan", as HTML-style #RRGGBB triples, and
r,g,b comma-separated numbers. The symbolic names are the 140 colors
defined in the Netscape/Internet Explorer color cube, and can be
retrieved using the Bio::Graphics::Panel-E<gt>color_names() method.

Transparent and semi-transparent colors can be specified using the
following syntax:

     #RRGGBBAA     - red, green, blue and alpha
     r,g,b,a       - red, green, blue, alpha
     blue:alpha    - symbolic name and alpha
     rgb(r,g,b)    - CSS style rgb values
     rgba(r,g,b,a) - CSS style rgba values

Alpha values can be specified as GD style integers ranging from 0
(opaque) to 127 (transparent), or as CSS-style floating point numbers
ranging from 0.0 (transparent) through 1.0 (opaque). As a special
case, a completely transparent color can be specified using the color
named "transparent". In the rgb() and rgba() forms, red, green, blue
values can be specified as percentages, as in rgb(100%,0%,50%);
otherwise, the values are integers from 0 to 255.

In addition, the -fgcolor and -bgcolor options accept the special
color names "featureScore" and "featureRGB". In the first case,
Bio::Graphics will examine each feature in the track for a defined
"score" tag (or the presence of a score() method) with a numeric value
ranging from 0-1000. It will draw a grayscale color ranging from
lightest (0) to darkest (1000). If the color is named "featureRGB",
then Bio::Graphics will look for a tag named "RGB" and will use that
as the color.

B<Foreground color:> The -fgcolor option controls the foreground
color, including the edges of boxes and the like.

B<Background color:> The -bgcolor option controls the background used
for filled boxes and other "solid" glyphs.  The foreground color
controls the color of lines and strings.  The -tkcolor argument
controls the background color of the entire track.

B<Default opacity:>For truecolor images, you can apply a default opacity
value to both foreground and background colors by supplying a B<-opacity>
argument. This is specified as a CSS-style floating point number from
0.0 to 1.0. If the color has an explicit alpha, then the default is
ignored.

B<Track color:> The -tkcolor option used to specify the background of

lib/Bio/Graphics/Panel.pm  view on Meta::CPAN

the feature as its single option and should return true if the feature
is to be shown and false otherwise.

=head2 Options and Callbacks

Instead of providing a constant value to an option, you may subsitute
a code reference.  This code reference will be called every time the
panel needs to configure a glyph.  The callback will be called with
three arguments like this:

   sub callback {
      my ($feature,$option_name,$part_no,$total_parts,$glyph) = @_;
      # do something which results in $option_value being set
      return $option_value;
   }

The five arguments are C<$feature>, a reference to the IO::SeqFeatureI
object, C<$option_name>, the name of the option to configure,
C<$part_no>, an integer index indicating which subpart of the feature
is being drawn, C<$total_parts>, an integer indicating the total
number of subfeatures in the feature, and finally C<$glyph>, the Glyph
object itself.  The latter fields are useful in the case of treating
the first or last subfeature differently, such as using a different
color for the terminal exon of a gene.  Usually you will only need to
examine the first argument.  This example shows a callback examining
the score() attribute of a feature (possibly a BLAST hit) and return
the color "red" for high-scoring features, and "green" for low-scoring
features:

  sub callback {
     my $feature = shift;
     if ($feature->score > 90) {
       return 'red';
     else {
       return 'green';
    }
  }

The callback should return a string indicating the desired value of
the option.  To tell the panel to use the default value for this
option, return the string "*default*".

The callback for -grid is slightly different because at the time this
option is needed there is no glyph defined. In this case, the callback
will get two arguments: the feature and the panel object:

 -glyph => sub {
      my ($feature,$panel) = @_;
      return 'gene' if $panel->length < 10_000;
      return 'box';
    }

When you install a callback for a feature that contains subparts, the
callback will be invoked first for the top-level feature, and then for
each of its subparts (recursively).  You should make sure to examine
the feature's type to determine whether the option is appropriate.

Also be aware that some options are only called for subfeatures. For
example, when using multi-segmented features, the "bgcolor" and
"fgcolor" options apply to the subfeatures and not to the whole
feature; therefore the corresponding callbacks will only be invoked
for the subfeatures and not for the top-level feature. To get
information that applies to the top-level feature, use the glyph's
parent_feature() method. This returns:

   * the parent if called with no arguments or with an argument of (1)
   * the parent's parent if called with an argument of (2)
   * the parent's parent's parent if called with an argument of (3)
   * etc.

The general way to take advantage of this feature is:

   sub callback {
      my ($feature,$option_name,$part_no,$total_parts,$glyph) = @_;
      my $parent = $glyph->parent_feature();

      # do something which results in $option_value being set
      return $option_value;
   }

or, more concisely:

   sub callback {
      my $feature = shift;  # first argument
      my $glyph   = pop;    # last argument
      my $parent = $glyph->parent_feature();

      # do something which results in $option_value being set
      return $option_value;
   }

Some glyphs deliberately disable recursion into subparts.  The
"track", "group", "transcript", "transcript2" and "segments" glyphs
selectively disable the -bump, -label and -description options.  This
is to avoid, for example, a label being attached to each exon in a
transcript, or the various segments of a gapped alignment bumping each
other.  You can override this behavior and force your callback to be
invoked by providing add_track() with a true B<-all_callbacks>
argument.  In this case, you must be prepared to handle configuring
options for the "group" and "track" glyphs.

In particular, this means that in order to control the -bump option
with a callback, you should specify -all_callbacks=E<gt>1, and turn on
bumping when the callback is in the track or group glyphs.

The -subpart_callbacks options is similar, except that when this is
set to true callbacks are invoked for the main glyph and its
subparts. This option only affects the -label and -description
options.

=head2 ACCESSORS

The following accessor methods provide access to various attributes of
the panel object.  Called with no arguments, they each return the
current value of the attribute.  Called with a single argument, they
set the attribute and return its previous value.

Note that in most cases you must change attributes prior to invoking
gd(), png() or boxes().  These three methods all invoke an internal
layout() method which places the tracks and the glyphs within them,
and then caches the result.

   Accessor Name      Description
   -------------      -----------

   width()	      Get/set width of panel
   spacing()	      Get/set spacing between tracks
   key_spacing()      Get/set spacing between keys
   length()	      Get/set length of segment (bp)
   flip()             Get/set coordinate flipping
   pad_top()	      Get/set top padding
   pad_left()	      Get/set left padding
   pad_bottom()	      Get/set bottom padding
   pad_right()	      Get/set right padding
   start()            Get the start of the sequence (bp; read only)
   end()              Get the end of the sequence (bp; read only)
   left()             Get the left side of the drawing area (pixels; read only)
   right()            Get the right side of the drawing area (pixels; read only)

=head2 COLOR METHODS

The following methods are used internally, but may be useful for those
implementing new glyph types.

=over 4

=item @names = Bio::Graphics::Panel-E<gt>color_names

Return the symbolic names of the colors recognized by the panel
object.  In a scalar context, returns an array reference.

=item ($red,$green,$blue) = Bio::Graphics::Panel-E<gt>color_name_to_rgb($color)

Given a symbolic color name, returns the red, green, blue components
of the color.  In a scalar context, returns an array reference to the
rgb triplet.  Returns undef for an invalid color name.

=item @rgb = $panel-E<gt>rgb($index)

Given a GD color index (between 0 and 140), returns the RGB triplet
corresponding to this index.  This method is only useful within a
glyph's draw() routine, after the panel has allocated a GD::Image and
is populating it.

=item $index = $panel-E<gt>translate_color($color)

Given a color, returns the GD::Image index.  The color may be



( run in 1.113 second using v1.01-cache-2.11-cpan-39bf76dae61 )