Phylo/Treedrawer/Png.pm untested

filter: Statementstmt 0.0% 0 / 211 Branchbran 0.0% 0 / 32 Conditioncond 0.0% 0 / 52 MC/DCmcdc 0.0% 0 / 34 Subroutinesub 0.0% 0 / 22 Podpod 0.0% 0 / 15 totaltotal 0.0% 0 / 366 CC 17 SCAR 24.4
CC
17
Cov
0%
_draw_pies
30.0
_make_color
20.0
_draw_text
20.0
CRAP 11.5
1 package Bio::Phylo::Treedrawer::Png;
2 use strict;
3 use warnings;
4 use base 'Bio::Phylo::Treedrawer::Abstract';
5 use Bio::Phylo::Util::Exceptions 'throw';
6 use Bio::Phylo::Util::CONSTANT qw'looks_like_hash _PI_';
7 use Bio::Phylo::Util::Dependency qw'GD::Simple GD::Polyline GD::Polygon GD';
8 use Bio::Phylo::Util::Logger;
9  
10 my $logger = Bio::Phylo::Util::Logger->new;
11 my $PI = _PI_;
12 my $AA = 3;
13 my $whiteHex = 'FFFFFF';
14 my $blackHex = '000000';
15 my %colors;
16  
17 =begin comment
18  
19 This module does all the heavy lifting for PNG, GIF and JPEG bitmap images. It
20 achieves anti-aliasing by first multiplying all coordinates, radii and line-
21 widths with a constant (default is $AA), then in the last-before-final step
22 the entire bitmap is downsampled, during which GD averages adjacent pixels,
23 which has the effect of anti-aliasing. This approach is taken because GD
24 doesn't seem to recognize line-widths if anti-aliasing has been turned on.
25 Because TrueType fonts are already anti-aliased we record where text needs to
26 end up after downsampling, and then in the last step we add the text into the
27 downsampled image.
28  
29 =end comment
30  
31 =head1 NAME
32  
33 Bio::Phylo::Treedrawer::Png - Graphics format writer used by treedrawer, no
34 serviceable parts inside
35  
36 =head1 DESCRIPTION
37  
38 This module creates a png file from a Bio::Phylo::Forest::DrawTree
39 object. It is called by the L<Bio::Phylo::Treedrawer> object, so look there to
40 learn how to create tree drawings.
41  
42  
43 =begin comment
44  
45 Translates a six-letter HEX code to rgb, i.e. three numbers between 0 and 255
46  
47 =end comment
48  
49 =cut
50  
51 sub _hex2rgb ($) {
52 my $hex = shift;
53 my ( $r, $g, $b ) = ( 0, 0, 0 );
54 if ( $hex =~ m/^(..)(..)(..)$/ ) {
55 $r = hex($1);
56 $g = hex($2);
57 $b = hex($3);
58 }
59 return $r, $g, $b;
60 }
61  
62 =begin comment
63  
64 Allocates colors in the index, uses caching
65  
66 =end comment
67  
68 =cut
69  
70 sub _make_color {
71 my ( $self, $hex ) = @_;
72 $hex = uc $hex;
73 if ( exists $colors{$hex} ) {
74 return $colors{$hex};
75 }
76 if ( not $hex ) {
77 if ( not $colors{$blackHex} ) {
78 $colors{$blackHex} = $self->_api->colorAllocate( _hex2rgb $blackHex );
79 }
80 return $colors{$blackHex};
81 }
82 my $colorObj = $self->_api->colorAllocate( _hex2rgb $hex );
83 $colors{$hex} = $colorObj;
84 return $colorObj;
85 }
86  
87 # returns multiplication factor for anti-aliasing
88  
89 sub _aa { shift->{'AA'} || $AA }
90  
91 # multiplies all arguments by the anti-aliasing upsampling factor
92  
93 sub _upsample {
94 my ( $self, @value ) = @_;
95 my $aa = $self->_aa;
96 my @result;
97 push @result, $_ * $aa for @value;
98 return @result;
99 }
100  
101 =begin comment
102  
103 Type : Constructor
104 Title : _new
105 Usage : my $png = Bio::Phylo::Treedrawer::Png->_new(%args);
106 Function: Initializes a Bio::Phylo::Treedrawer::Png object.
107 Alias :
108 Returns : A Bio::Phylo::Treedrawer::Png object.
109 Args : none.
110  
111 =end comment
112  
113 =cut
114  
115 sub _new {
116 my $class = shift;
117 my %opt = looks_like_hash @_;
118
119 # instantiate object
120 my $aa = $opt{'-aa'} || $AA;
121 my $td = $opt{'-drawer'};
122 delete $opt{'-aa'};
123 my $self = $class->SUPER::_new( %opt );
124 $self->{'AA'} = $aa;
125 $self->{'TXT'} = [];
126 $self->{'API'} = GD::Image->new(
127 $self->_upsample( $td->get_width, $td->get_height ),
128 1,
129 );
130
131 # set background color
132 $self->_api->fill( 0,0, $self->_make_color( $whiteHex ) );
133
134 return $self;
135 }
136  
137 =begin comment
138  
139 Downsamples the bitmap that has been created so far, in order to achieve an
140 anti-aliasing effect. Then adds the text strings in the correct coordinates
141 for the downsampled image.
142  
143 =end comment
144  
145 =cut
146  
147 sub _downsample {
148 $logger->debug("downsampling");
149 my $self = shift;
150 my ( $w, $h ) = ( $self->_drawer->get_width, $self->_drawer->get_height );
151 my $aa = $self->_aa;
152 my $result = GD::Image->new( $w, $h, 1 );
153 $result->copyResampled( $self->_api, 0, 0, 0, 0, $w, $h, $w * $aa, $h * $aa);
154 for my $txtargs ( @{ $self->{'TXT'} } ) {
155 $result->stringFT( @{ $txtargs } );
156 }
157 return $result;
158 }
159  
160 =begin comment
161  
162 # finish drawing, export PNG
163  
164 =end comment
165  
166 =cut
167  
168 sub _finish {
169 return shift->_downsample->png;
170 }
171  
172 =begin comment
173  
174 # -x1 => $x1,
175 # -x2 => $x2,
176 # -y1 => $y1,
177 # -y2 => $y2,
178 # -width => $width,
179 # -color => $color
180  
181 =end comment
182  
183 =cut
184  
185 sub _draw_curve {
186 $logger->debug("drawing curved branch");
187 my $self = shift;
188 my %args = @_;
189 my @keys = qw(-x1 -y1 -x2 -y2 -width -color -api);
190 my ( $x1, $y1, $x3, $y3, $linewidth, $color, $api ) = @args{@keys};
191
192 # create upsampled coordinates
193 ($x1,$y1,$x3,$y3,$linewidth) = $self->_upsample($x1,$y1,$x3,$y3,$linewidth);
194 my ( $x2, $y2 ) = ( $x1, $y3 );
195
196 my $img = $api || $self->_api;
197 $img->setThickness( $linewidth || $self->_aa );
198
199 # set control points
200 my $poly = GD::Polyline->new();
201 $poly->addPt( $x1, $y1 );
202 $poly->addPt( $x1, ( $y1 + $y3 + $y3 ) / 3 );
203 $poly->addPt( ( $x1 + $x1 + $x3 ) / 3, $y3 );
204 $poly->addPt( $x3, $y3 );
205
206 $img->polydraw( $poly->toSpline(), $self->_make_color( $color ) );
207 }
208  
209 =begin comment
210  
211 # -x1 => $x1,
212 # -x2 => $x2,
213 # -y1 => $y1,
214 # -y2 => $y2,
215 # -width => $width,
216 # -color => $color
217  
218 =end comment
219  
220 =cut
221  
222 sub _draw_arc {
223 $logger->debug("drawing arc");
224 my $self = shift;
225
226 # process arguments
227 my %args = @_;
228 my @keys = qw(-x1 -y1 -x2 -y2 -radius -width -color -api);
229 my ($x1,$y1,$x2,$y2,$radius,$linewidth,$linecolor,$api) = @args{@keys};
230 ($x1,$y1,$x2,$y2,$radius,$linewidth) = $self->_upsample($x1,$y1,$x2,$y2,$radius,$linewidth);
231  
232 # get center of arc
233 my $drawer = $self->_drawer;
234 my $cx = $drawer->get_width * $self->_aa / 2;
235 my $cy = $drawer->get_height * $self->_aa / 2;
236
237 # get width and height (are equal for arcs)
238 my ( $width, $height );
239 $width = $height = $radius * 2;
240
241 # change line thickness
242 my $img = $api || $self->_api;
243 $img->setThickness( $linewidth || $self->_aa );
244
245 # compute start and end
246 my ( $r1, $start ) = $drawer->cartesian_to_polar( $x1 - $cx, $y1 - $cy );
247 my ( $r2, $end ) = $drawer->cartesian_to_polar( $x2 - $cx, $y2 - $cy );
248 $start += 360 if $start < 0;
249 $end += 360 if $end < 0;
250
251 # draw
252 $img->arc($cx,$cy,$width,$height,$start,$end,$self->_make_color($linecolor));
253 }
254  
255 =begin comment
256  
257 # required:
258 # -x1 => $x1,
259 # -y1 => $y1,
260 # -x2 => $x2,
261 # -y2 => $y2,
262 # -x3 => $x3,
263 # -y3 => $y3,
264  
265 # optional:
266 # -fill => $fill,
267 # -stroke => $stroke,
268 # -width => $width,
269 # -url => $url,
270 # -api => $api,
271  
272 =end comment
273  
274 =cut
275  
276 sub _draw_triangle {
277 my $self = shift;
278 $logger->debug("drawing triangle @_");
279 my %args = @_;
280 my @keys = qw(-x1 -y1 -x2 -y2 -x3 -y3 -fill -stroke -width -url -api);
281 my ( $x1, $y1, $x2, $y2, $x3, $y3, $fill, $stroke, $width, $url, $api ) =
282 @args{@keys};
283 if ($url) {
284 $logger->warn( ref($self) . " can't embed links" );
285 }
286 my $img = $api || $self->_api;
287  
288 # create polygon
289 my $poly = GD::Polygon->new();
290 $poly->addPt( $x1, $y1 );
291 $poly->addPt( $x2, $y2 );
292 $poly->addPt( $x3, $y3 );
293 $poly->addPt( $x1, $y1 );
294  
295 # set line thickness
296 $img->setThickness( $width || 1 );
297  
298 # create antialiased stroke color
299 my $strokeColorObj = $self->_make_color( $stroke || $blackHex );
300 $img->setAntiAliased($strokeColorObj);
301  
302 # create fill color
303 my $fillColorObj = $self->_make_color( $fill || $whiteHex );
304  
305 # draw polygon
306 $img->polydraw( $poly, GD::gdAntiAliased );
307  
308 # fill polygon
309 $img->fill(
310 ( ( $x1 + $x2 + $x3 ) / 3 ),
311 ( ( $y1 + $y2 + $y3 ) / 3 ),
312 $fillColorObj
313 );
314 }
315  
316 =begin comment
317  
318 Type : Internal method.
319 Title : _draw_pies
320 Usage : $svg->_draw_pies();
321 Function: Draws likelihood pies
322 Returns :
323 Args : None.
324 Comments:
325  
326 =end comment
327  
328 =cut
329  
330 sub _draw_pies {
331 my $self = shift;
332 my %piecolors;
333 $self->_tree->visit_level_order(
334 sub {
335 my $node = shift;
336 if ( not $node->get_collapsed and my $values = $node->get_generic('pie') ) {
337
338 # get center coordinates and radius
339 my ( $cx, $cy ) = ( $node->get_x, $node->get_y );
340 my $method = sprintf 'get_%s_radius', $node->is_internal ? 'node' : 'tip';
341 my $r = $self->_drawer->$method($node);
342 ( $cx, $cy, $r ) = $self->_upsample( $cx, $cy, $r );
343
344 # calculate sum of all pie values
345 my @keys = keys %{$values};
346 my $total;
347 $total += $values->{$_} for @keys;
348
349 my $start = 0;
350 for my $i ( 0 .. $#keys ) {
351 my $key = $keys[$i];
352 next if not $values->{$key};
353
354 # allocate pie chunk color
355 if ( not defined $piecolors{$key} ) {
356 my $fraction = int($i / $#keys * 255);
357 my $hex = uc(sprintf("%.2x",$fraction)) x 3;
358 $logger->debug("$fraction = $hex");
359 $piecolors{$key} = $self->_make_color($hex);
360 }
361
362 # calculate slice angle
363 my $slice = $values->{$key} / $total * 360;
364 $self->_api->filledArc( $cx, $cy, $r, $r, $start, $slice + $start, $piecolors{$key} );
365 $start += $slice;
366 }
367
368 # final circle around node
369 $self->_api->arc( $cx, $cy, $r, $r, 0, 360, $self->_make_color($blackHex) );
370 }
371 }
372 );
373 }
374  
375 =begin comment
376  
377 # -x1 => $x1,
378 # -x2 => $x2,
379 # -y1 => $y1,
380 # -y2 => $y2,
381 # -width => $width,
382 # -color => $color
383  
384 =end comment
385  
386 =cut
387  
388 sub _draw_line {
389 $logger->debug("drawing line");
390 my $self = shift;
391 my %args = @_;
392 my @keys = qw(-x1 -y1 -x2 -y2 -width -color -api);
393 my ( $x1, $y1, $x2, $y2, $width, $color, $api ) = @args{@keys};
394 ( $x1, $y1, $x2, $y2, $width ) = $self->_upsample( $x1, $y1, $x2, $y2, $width );
395 my $img = $api || $self->_api;
396 $img->setThickness( $width || $self->_aa );
397 $img->line( $x1, $y1, $x2, $y2, $self->_make_color( $color ) );
398 }
399  
400 =begin comment
401  
402 # -x1 => $x1,
403 # -x2 => $x2,
404 # -y1 => $y1,
405 # -y2 => $y2,
406 # -width => $width,
407 # -color => $color
408  
409 =end comment
410  
411 =cut
412  
413 sub _draw_multi {
414 $logger->debug("drawing multi line");
415 my $self = shift;
416 my %args = @_;
417 my @keys = qw(-x1 -y1 -x2 -y2 -width -color -api);
418 my ( $x1, $y1, $x3, $y3, $linewidth, $color, $api ) = @args{@keys};
419 ($x1,$y1,$x3,$y3,$linewidth) = $self->_upsample($x1,$y1,$x3,$y3,$linewidth);
420 my ( $x2, $y2 ) = ( $x1, $y3 );
421 my $img = $api || $self->_api;
422 my $poly = GD::Polyline->new();
423 $poly->addPt( $x1, $y1 );
424 $poly->addPt( $x2, $y2 );
425 $poly->addPt( $x3, $y3 );
426 $img->setThickness( $linewidth || $self->_aa );
427 $img->polydraw( $poly, $self->_make_color( $color ) );
428 }
429  
430 =begin comment
431  
432 # required:
433 # -x => $x,
434 # -y => $y,
435 # -text => $text,
436 #
437 # optional:
438 # -url => $url,
439  
440 =end comment
441  
442 =cut
443  
444 sub _draw_text {
445 $logger->debug("drawing text");
446 my $self = shift;
447 my %args = @_;
448 my @keys = qw(-x -y -text -url -size -api -rotation);
449 my ( $x, $y, $text, $url, $size, $api, $rotation ) = @args{@keys};
450 if ($url) {
451 $logger->warn( ref($self) . " can't embed links" );
452 }
453
454 # to place the text, we need to calculate where the vertical and horizontal
455 # offsets end up given the rotation. We compute these offsets by taking the
456 # difference between the provided $x,$y coordinates (which include the
457 # offsets) and those in $rotation->[1],$rotation->[2], which normally is
458 # the location of the terminal node next to which the text is placed and
459 # around which it is rotated.
460 my $radius_x = $x - $rotation->[1];
461 my $radius_y = $y - $rotation->[2];
462
463 # for the vertical offset we need to add 90 degrees
464 my $rotation1 = $rotation->[0] + 90;
465 $rotation1 -= 360 if $rotation1 > 360;
466 my ( $x1, $y1 ) = $self->_drawer->polar_to_cartesian( $radius_x, $rotation->[0] );
467 my ( $x2, $y2 ) = $self->_drawer->polar_to_cartesian( $radius_y, $rotation1 );
468
469 # rotations in GD are counter-clockwise, so need to be "inverted"
470 my $gdrotation = ( $rotation->[0] - 360 ) * - 1;
471 $gdrotation -= 360 if $gdrotation > 360;
472
473 push @{ $self->{'TXT'} }, [
474 $self->_make_color($blackHex),
475 '/System/Library/Fonts/Thonburi.ttf',
476 $size || 12,
477 $gdrotation / 180 * _PI_,
478 $rotation->[1] + $x1 + $x2,
479 $rotation->[2] + $y1 + $y2,
480 $text
481 ];
482 }
483  
484 =begin comment
485  
486 # -x => $x,
487 # -y => $y,
488 # -width => $width,
489 # -stroke => $color,
490 # -radius => $radius,
491 # -fill => $file,
492 # -api => $api,
493 # -url => $url,
494  
495 =end comment
496  
497 =cut
498  
499 sub _draw_circle {
500 $logger->debug("drawing circle");
501 my $self = shift;
502 my %args = @_;
503 my @keys = qw(-x -y -width -stroke -radius -fill -api -url);
504 my ( $x, $y, $width, $stroke, $radius, $fill, $api, $url ) = @args{@keys};
505 if ($url) {
506 $logger->warn( ref($self) . " can't embed links" );
507 }
508 ( $x, $y, $width, $radius ) = $self->_upsample( $x, $y, $width, $radius );
509 my @args = ( $x, $y, $radius, $radius );
510 my $img = $api || $self->_api;
511 if ( defined $fill ) {
512 $img->filledEllipse( @args, $self->_make_color($fill || $whiteHex) );
513 }
514 $img->ellipse( @args, $self->_make_color($stroke) );
515 }
516  
517 =head1 SEE ALSO
518  
519 There is a mailing list at L<https://groups.google.com/forum/#!forum/bio-phylo>
520 for any user or developer questions and discussions.
521  
522 =over
523  
524 =item L<Bio::Phylo::Treedrawer>
525  
526 The pdf treedrawer is called by the L<Bio::Phylo::Treedrawer> object. Look there
527 to learn how to create tree drawings.
528  
529 =item L<Bio::Phylo::Manual>
530  
531 Also see the manual: L<Bio::Phylo::Manual> and L<http://rutgervos.blogspot.com>.
532  
533 =back
534  
535 =head1 CITATION
536  
537 If you use Bio::Phylo in published research, please cite it:
538  
539 B<Rutger A Vos>, B<Jason Caravas>, B<Klaas Hartmann>, B<Mark A Jensen>
540 and B<Chase Miller>, 2011. Bio::Phylo - phyloinformatic analysis using Perl.
541 I<BMC Bioinformatics> B<12>:63.
542 L<http://dx.doi.org/10.1186/1471-2105-12-63>
543  
544 =cut
545  
546 1;