Phylo/Treedrawer/Png.pm untested

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