script/nexplot.pl untested

filter: Statementstmt 0.0% 0 / 490 Branchbran 0.0% 0 / 194 Conditioncond 0.0% 0 / 116 MC/DCmcdc 0.0% 0 / 74 Subroutinesub 0.0% 0 / 27 Podpod 0.0% 0 / 22 totaltotal 0.0% 0 / 923 CC 91 SCAR 54.8
CC
91
Cov
0%
read_nexus
756.0
parseArgs
342.0
__print_label
56.0
CRAP 240.8
1 #!/usr/local/bin/perl -w
2  
3 ######################################################################
4 # nexplot.pl (was plottree.pl prior to 9/15/03; the complete revision
5 # log from plottree.pl is in the initial version of nexplot.pl)
6 ######################################################################
7 #
8 # $Author: thladish $
9 # $Date: 2006/08/24 06:41:57 $
10 # $Revision: 1.36 $
11 # $Id: nexplot.pl,v 1.36 2006/08/24 06:41:57 thladish Exp $
12  
13 use Data::Dumper;
14 use Bio::NEXUS;
15 use strict;
16 use Getopt::Std;
17 use Pod::Usage;
18  
19 #
20 # GLOBAL VARS
21 #
22 my $DEBUG = 0; #get verbose messages on stdout if true.
23  
24 #20040119 todo 1. do they all need to be global?
25  
26 my %runtimeOptions; # Contains hash of options defined by the user
27 my $inputFile; # The NEXUS file to read from
28 my $verticalOtuSpacing; # Vertical spacing between OTUs (in PostScript points, 72 pts = 1 inch)
29 my $defaultFont; # The default font used for displaying OTU names and the title
30 my $titleFont; # Font typically used for displaying titles (as of now, $defaultFont)
31 my $fontSize; # Typical font size for displaying OTU names
32 my $lowerXbound; # Lower X bound for tree
33 my $lowerYbound; # Lower Y bound for tree (above scale)
34 my $blockWidth; # Frequency of spaces between characters to display (thiss equen cefor examp le=5)
35 my $pageDimensionRatio; # Ratio of page height to width
36 my $pageWidthInches; # Page width in inches
37 my $pageHeightInches; # Page height in inches
38 my $pageWidthPoints; # Page width in points
39 my $pageHeightPoints; # Page height in points
40 my $treeWidth; # Width of tree in points
41 my $histogramHeight; # Height of weight histogram in points
42 my $treeHeight; # Height of tree in points
43 my %sequences; # Character entries for each OTU (key'd by name)
44 my @trees; # Trees in the NEXUS file
45 my %setsColors; # User-specified set names with corresponding colors
46 my @setsColorsKeys; # Keeps track of the order of sets specified by user
47 my $nodeColorMap; # Colors of nodes as established by SPAN block in NEXUS
48 my @weights; # Weights in the NEXUS file
49 my $treeName; # The name of the tree being displayed
50 my @columnLabels; # Array containing character labels
51 my %dataPresent; # Indicates NEXUS data presence/absence (key'd by element)
52 my $amp; # Conversion factor between x coordinates and PostScript x points
53 my $root; # Root node of $tree
54 my @nodes; # Holds list of nodes (OTUs and internal nodes)
55 my $tree; # Tree selected to be displayed
56  
57 ######################################################################
58 #
59 # hard-coded values, including default parameter values
60 #
61 ######################################################################
62  
63 my $defaultDefaultFont = 'Times-Roman'; # font to use for OTU labels
64 my $defaultSpaceBetweenRows = 18; # in POINTS, vertical space between rows (tree tips)
65 my $defaultBlockWidth = 10; # number of columns between space columns
66 my $defaultFontToSpaceRatio = 0.8; # ratio of font height to space between rows
67 my $defaultPageHeightInches = 11; # page height in inches for your default page size
68 my $defaultPageWidthInches = 8.5; # page width in inches for your default page size
69 my $treeLineWidth = 2; # width of tree lines
70 my $boxLineWidth = 1; # width of bounding box line
71 my $referenceLineWidth = 1.8; # width of reference lines between tree & matrix
72 my $treeNodeRadius = 2; # radius of dot representing a node
73 my $characterFont = 'Courier'; # font to use for character matrix
74 my $RGBcolorHash = { red => '1.0 0.0 0.0',
75 green => '0.0 0.5 0.0',
76 forest => '0.0 0.2 0.0',
77 blue => '0.0 0.0 1.0',
78 aqua => '0.0 0.5 0.5',
79 orange => '1.0 0.3 0.0',
80 purple => '0.4 0.0 0.6',
81 grey => '0.4 0.4 0.4',
82 gray => '0.4 0.4 0.4',
83 brown => '0.5 0.2 0.0',
84 pink => '0.9 0.0 0.4',
85 black => '0.0 0.0 0.0',
86 };
87  
88 &parseArgs(); # Parse arguments, validate them, and set them correctly.
89 &read_nexus(); # Read in the NEXUS file and extract relevant information.
90  
91 &__prolog(); # Print prolog: Define some functions, print header info, etc.
92 &__psSetup(); # Set up the plot boundaries; perform plot rotation if necessary.
93  
94 # PRINT TREE AND OTHER ELEMENTS IF PRESENT
95 &__print_tree($root, $lowerXbound, $lowerYbound) if (!$runtimeOptions{'m'});
96 &__print_matrix($root, $lowerXbound, $lowerYbound) if ($runtimeOptions{'m'});
97  
98 if (!($runtimeOptions{t})) { # Character labels, weights
99 &__print_char_labels(@columnLabels) if @columnLabels;
100 &__plot_wts(@weights) if ($dataPresent{weights});
101 }
102  
103 &__print_boot_strap() if ($runtimeOptions{b});
104 &__end_post_script();
105  
106 close(OUTPUT) if ($runtimeOptions{f});
107  
108 exit;
109  
110  
111 #################################################################### SUBROUTINES
112  
113 sub parseArgs {
114 warn("Setting up options...\n") if $DEBUG;
115 getopts('hdc:vbgirtmosaf:C:BF:W:H:I:T:S:R:VU:', \%runtimeOptions) or die "ERROR: Unknown options and/or options requiring arguments do not have them.\n";
116 $runtimeOptions{h} and pod2usage(VERBOSE => 1);
117 $runtimeOptions{d} and pod2usage(VERBOSE => 2);
118  
119 if ( $runtimeOptions{ 'V' } ) { die '$Id: nexplot.pl,v 1.36 2006/08/24 06:41:57 thladish Exp $',"\n"; }
120
121 $inputFile = shift @ARGV;
122 $inputFile or pod2usage(VERBOSE => 0);
123 $treeName = shift @ARGV;
124  
125 # die if options are selected that will conflict when enabled together.
126 # cannot enable any mix of -s (multiple pages 1 page tall), -o (multiple pages), and -a (one page autofit).
127 if(($runtimeOptions{'s'} && $runtimeOptions{o}) || ($runtimeOptions{'s'} && $runtimeOptions{a}) || ($runtimeOptions{o} && $runtimeOptions{a})) {
128 die "ERROR: Only one page setup option may be enabled at once.\n";
129 }
130 # cannot specify invalid cladogram option
131 if ($runtimeOptions{c}) {
132 if (! ($runtimeOptions{c} =~ /(normal|accelerated)/i)) {
133 die "ERROR: Cladogram option is invalid.\n";
134 }
135 }
136 # cannot specify both tree-only and matrix-only options
137 if ($runtimeOptions{t} && $runtimeOptions{'m'}) {
138 die "ERROR: The tree-only and matrix-only options cannot be enabled at the same time.\n";
139 }
140 # where we are going to print output to. only selected if
141 if($runtimeOptions{f}) {
142 open (OUTPUT,">$runtimeOptions{f}") or die("You do not have the permissions to create this file.\n");
143 select (OUTPUT);
144 }
145 # use nexus sets and user-specified colors
146 if($runtimeOptions{U}) {
147 my @keys = (split(/\s+/,$runtimeOptions{U}));
148 %setsColors = (@keys);
149 my $j = 0;
150 for (my $i = 0; $i < scalar(@keys); $i++) {
151 if ($j == 0) {
152 push (@setsColorsKeys, $keys[$i]);
153 $j = 1;
154 } elsif ($j == 1) {
155 $j = 0;
156 }
157 }
158 };
159
160 $defaultFont = ( exists($runtimeOptions{F}) ? $runtimeOptions{F} : $defaultDefaultFont );
161 $titleFont = $defaultFont;
162 $blockWidth = ( exists($runtimeOptions{C}) && &isNumber($runtimeOptions{C}) ? $runtimeOptions{C} : $defaultBlockWidth );
163 $verticalOtuSpacing = ( exists($runtimeOptions{S}) && &isNumber($runtimeOptions{S},'S') ? $runtimeOptions{S} * 72 : $defaultSpaceBetweenRows );
164 my $fontToSpacingRatio = ( $runtimeOptions{R} && isNumber($runtimeOptions{R},'R') ? $runtimeOptions{R} : $defaultFontToSpaceRatio ); # default ratio
165 $pageWidthInches = ( exists($runtimeOptions{W}) && &isNumber($runtimeOptions{W},'W') ? $runtimeOptions{W} : $defaultPageWidthInches );
166 $pageHeightInches = ( exists($runtimeOptions{H}) && &isNumber($runtimeOptions{H},'H') ? $runtimeOptions{H} : $defaultPageHeightInches );
167 $pageDimensionRatio = $pageHeightInches / $pageWidthInches; # Use to determine whether plot should be rotated
168
169 $pageWidthPoints=$pageWidthInches*72; # Convert to points (for PostScript)
170 $pageHeightPoints=$pageHeightInches*72;
171 $fontSize = $fontToSpacingRatio * $verticalOtuSpacing;
172 $lowerXbound = 0; # Relative to tree
173 $lowerYbound = $fontSize + 20; # Give space for scale
174 $histogramHeight = 3 * $verticalOtuSpacing; # height of histogram
175  
176 $treeWidth = ( exists($runtimeOptions{T}) && &isNumber($runtimeOptions{T},'T') ? $runtimeOptions{T} * 72 : 720 ); # max horizontal tree width
177 }
178  
179 sub isNumber {
180 my $arg=$_[0];
181 my $var=$_[1];
182 $arg =~ /(\d+\.?\d*|\.\d+)/ or die "Execution failed: Incorrect number: $arg for option $var\n";
183 }
184  
185 sub read_nexus {
186 # Parse nexus file
187 my $nexusObject;
188 my $taxSets;
189 if($runtimeOptions{v}) {
190 $DEBUG=1;
191 $nexusObject = new Bio::NEXUS($inputFile,1);
192 } else {
193 $nexusObject = new Bio::NEXUS($inputFile);
194 }
195 # Read in NEXUS blocks from NEXUS object
196 foreach my $block ( @{$nexusObject->get_blocks()} ) {
197 if ($block->{'type'} =~ /characters/i && (! $runtimeOptions{I} || $block->{'title'} =~ /$runtimeOptions{I}/)) {
198 warn("Grabbing characters block from NEXUS file...\n") if $DEBUG;
199 my $characterLabels = $block->get_charlabels;
200 my $seqLength = $block->get_nchar;
201 %sequences = %{$block->get_otuset->get_seq_string_hash};
202 warn("Setting column labels...\n") if ( $DEBUG );
203 if ($characterLabels && @$characterLabels) {
204 @columnLabels = @$characterLabels;
205 } elsif ($seqLength) { # not labeled, e.g., typical dna or aa seq alignment
206 @columnLabels = ();
207 for (1 .. $seqLength) {push @columnLabels, $_;}
208 }
209 $dataPresent{characters} = 1;
210
211 if ( $nexusObject->get_block('assumptions') ) {
212 my @assumptions_blocks = @{ $nexusObject->get_blocks('assumptions') };
213 for my $asmpt_block (@assumptions_blocks) {
214 if ( (@assumptions_blocks == 1) || ($asmpt_block->get_link( 'characters' ) eq $block->get_title() )) {
215 @weights = ();
216 warn("Grabbing assumptions block from NEXUS file...\n") if $DEBUG;
217 foreach my $assumption(@{$asmpt_block->get_assumptions()}) {
218 if( $assumption->is_wt() ) {
219 @weights=@{$assumption->get_weights()};
220 $dataPresent{weights} = 1;
221 $dataPresent{'CORE_column_scores'} = ( $assumption->get_name() eq 'CORE_column_scores' ) ? 1 : 0;
222 }
223 if ( $DEBUG ) {
224 warn("No weights found in this file\n") unless $dataPresent{weights};
225 warn("Weights have been found in this file\n") if $dataPresent{weights};
226 }
227 }
228 }
229 }
230 }
231 }
232 if ($block->{'type'} =~ /trees/i) {
233 warn("Grabbing trees block from NEXUS file...\n") if $DEBUG;
234 $tree = $block->get_tree($treeName);
235 # EXTRACT TREE DATA
236 $treeName = $tree->get_name() || "unnamed";
237 $tree->_set_xcoord($treeWidth,$runtimeOptions{c});
238 $tree->_set_ycoord($lowerYbound,$verticalOtuSpacing);
239 @nodes = @{$tree->get_nodes()};
240 $root = $tree->get_rootnode();
241 warn("Getting names of OTUs in tree...\n") if ( $DEBUG );
242 my @sorted;
243 for my $node (@nodes) {
244 push @sorted, $node->_get_xcoord();
245 }
246 @sorted = sort { $a <=> $b } @sorted;
247 $amp = $treeWidth / pop @sorted; # unit of branch length
248 for my $node (@nodes) {
249 $node->_set_xcoord( $node->_get_xcoord() * $amp );
250 }
251 $dataPresent{trees} = 1;
252 }
253 if ($block->{'type'} =~ /sets/i && $runtimeOptions{U}) {
254 warn("Grabbing sets block from NEXUS file...\n") if $DEBUG;
255 $taxSets = $block->get_taxsets();
256 }
257 }
258 if ($dataPresent{characters} != 1 && $runtimeOptions{I}) {
259 die ("Specified Characters Block not found\n");
260 }
261
262 if ($runtimeOptions{U}) {
263 my $taxlabels = $nexusObject->get_block('taxa')->get_taxlabels();
264 for my $userSetName (@setsColorsKeys) {
265 if ($nexusObject->get_block('sets')) {
266 for my $taxSetName (keys %$taxSets) {
267 if ($userSetName eq $taxSetName) {
268 for my $taxon (@{$$taxSets{$taxSetName}}) {
269 ${$nodeColorMap}{$taxon} = $$RGBcolorHash{$setsColors{$userSetName}};
270 }
271 }
272 }
273 }
274 for my $taxlabel (@$taxlabels) {
275 if ($userSetName eq $taxlabel) {
276 ${$nodeColorMap}{$taxlabel} = $$RGBcolorHash{$setsColors{$userSetName}};
277 }
278 }
279 }
280 }
281 # propagating taxonomic coloring up the tree
282 if ( defined( $nodeColorMap ) ) {
283 $root = $tree->get_rootnode();
284 &AssignStateToNode( $root, "0 0 0", $nodeColorMap );
285 }
286 die "No tree in file $inputFile\n" unless $tree;
287 }
288  
289 sub AssignStateToNode {
290 # AssignStateToNode -- propagate colors or other states up a tree
291 #
292 # Technically, what we are doing here is reconstructing ancestral states
293 # based on a transition model of infinite cost (zero rate), so that no
294 # transitions are allowed. Thus, an ancestor is assigned to a state
295 # _i_ if and only if all of its descendants are assigned to state _i_.
296 #
297 # this function
298 # * probably should be put in a library and named something like
299 # "AssignAncestralStatesByConsensus";
300 # * maps states to the *names* of nodes, not to their object refs;
301 # * allows for polytomies;
302 # * does not assume all OTUs have defined states, but note that
303 # any undefined states of OTUs *will remain undefined*
304 my $node = shift; # node object
305 my $unknownState = shift; # state to assign when no other assignment can be made
306 my $map = shift; # hash with any available states
307  
308 my $name = $node->{'name'};
309 my $lastState = undef;
310 my $assignable = 1;
311  
312 # return if state already exists OR if the node is an OTU
313 return if (defined($map->{$name}) || $node->is_otu() );
314  
315 # Go through children and make sure all children are the same state
316 foreach my $child (@{$node->children()}) {
317 my $childname = $child->{'name'};
318 &AssignStateToNode($child, $unknownState, $map) unless $map->{$childname};
319 if ( defined($lastState) && $$map{$childname} ne $lastState ) {
320 $assignable = 0;
321 }
322 $lastState = $map->{$childname};
323 }
324 return( $map->{ $name } = ( $assignable ? $lastState : $unknownState ) );
325 }
326  
327 sub __prolog {
328 print "%!PS-Adobe-3.0\n";
329 print "%%Pages: 1\n";
330 print "%%Title: ", $treeName, "\n";
331 print "%%Creator: Weigang Qiu / Peter Yang, CARB, UMBI, Rockville, MD\n";
332 print "%%CreationDate: ", `date`; # backtick for unix shell command "date"
333 print "%%BoundingBox: 0 0 $pageWidthPoints $pageHeightPoints\n" unless $runtimeOptions{o};
334 print "%%Orientation: Portrait\n";
335 print "%%EndComments\n\n";
336 print "%%BeginProlog\n";
337 # Hard copy: use BigPrint program from "Postscript cookbook"
338 # Current margins: 1/2" inch margins all around
339 # Substituted clipping path for this command:
340 # leftmargin botmargin pagewidth pageheight rectclip
341 if ($runtimeOptions{o} || $runtimeOptions{'s'}) {
342 print<<END_OF_BIGPRINT;
343  
344 /inch {72 mul} def
345 /leftmargin .5 inch def
346 /botmargin .5 inch def
347 /pagewidth $pageWidthInches 1 sub inch def
348 /pageheight $pageHeightInches 1 sub inch def
349  
350 /BigPrint
351 {
352 /rows exch def
353 /columns exch def
354 /bigpictureproc exch def
355 leftmargin botmargin pagewidth pageheight rectclip
356 leftmargin botmargin translate
357 0 1 rows 1 sub
358 { /rowcount exch def
359 0 1 columns 1 sub
360 { /colcount exch def
361 gsave
362  
363 pagewidth colcount mul neg
364 pageheight rowcount mul neg
365 translate
366  
367 bigpictureproc
368  
369 gsave showpage grestore
370 grestore
371 } for
372 } for
373 } def
374  
375 END_OF_BIGPRINT
376  
377 }
378  
379 # "vshow" from cookbook: vertical text (for char labels)
380 # Modifications:
381 # Move up. Original: "0 lineskip neg rmoveto", moving down
382 # No centering. Original: "thechar stringwidth pop 2 div neg 0 rmoveto "
383 print <<END_OF_VSHOW;
384 /vshowdict 4 dict def
385 /vshow
386 { vshowdict begin
387 /thestring exch def
388 /lineskip exch def
389 thestring
390 { /charcode exch def
391 /thechar ( ) dup
392 0 charcode put def
393 0 lineskip rmoveto
394 gsave
395 thechar stringwidth pop neg 0 rmoveto
396 thechar show
397 grestore
398 } forall
399 end
400 } def
401 END_OF_VSHOW
402 print <<END_OF_SHOWCHARLABELS;
403 /showCharLabels {
404 /letterwidth exch def
405 /blockWidth exch def
406 /size exch def
407 /numLabels exch def
408 /charLabels exch def
409 /arrayPos 0 def
410 /realPos 1 def
411 {
412 arrayPos numLabels gt {exit} if
413 arrayPos 0 ne arrayPos blockWidth mod 0 eq and {/realPos realPos 1 add def} if
414 letterwidth realPos mul 0 moveto
415 size charLabels arrayPos get vshow
416 /arrayPos arrayPos 1 add def
417 /realPos realPos 1 add def
418 } loop
419 } def
420 END_OF_SHOWCHARLABELS
421  
422 # Define quick function for line drawing
423 print "\t/l {newpath moveto lineto stroke} def\n";
424 printf "/defaultfont /$defaultFont findfont $fontSize scalefont def\n";
425  
426 printf "/titlefont /%s-Bold findfont %.f scalefont def\n", $titleFont, $fontSize*2;
427 print "/characterfont /$characterFont findfont $fontSize scalefont def\n";
428 print "%%EndProlog\n\n";
429 }
430  
431 sub __psSetup {
432 my $upperYbound;
433 print "%%BeginSetup\n",
434 "\t1 setlinecap\n",
435 "\t1 setlinejoin\n",
436 "\t$treeLineWidth setlinewidth newpath\n",
437 "%%EndSetup\n",
438 "%%Page: 1\n%%BeginPageSetup\n";
439  
440  
441 # DETERMINE PLOT BOUNDARIES
442 $treeHeight = 0;
443  
444 # Find tree maximum (x and y directions)
445 print "/treemax 0 def\n";
446 printf "\t\tcharacterfont setfont\n";
447 print "\t\t/letterwidth (a) stringwidth pop def\n";
448 print "defaultfont setfont\n";
449 &__find_treemax($root);
450 print "/treemax treemax 36 add def\n"; # give space for printing character table
451  
452 # Find x boundary
453 # If only the tree needs to be printed (either by choice or because there is
454 # nothing else, treemax will be used as the x boundary.
455 if($dataPresent{characters} && (! $runtimeOptions{t})) {
456 &__find_xbound($root);
457 } else {
458 print "/xbound treemax def\n";
459 }
460  
461 # Determine y boundary
462 $upperYbound = $treeHeight;
463 $upperYbound += 1/2 * $verticalOtuSpacing;
464 if (! $runtimeOptions{t}) {
465 $upperYbound += &__find_longest_label(@columnLabels) if @columnLabels;
466 $upperYbound += 4 * $verticalOtuSpacing if $dataPresent{weights};
467 $upperYbound += $verticalOtuSpacing unless $dataPresent{weights};
468 }
469 else {
470 $upperYbound += $fontSize * 2;
471 }
472 print "/ybound $upperYbound def\n";
473 &__scale_rotate();
474 print "%%EndPageSetup\n";
475 }
476  
477 sub __find_treemax {
478 # Finds the maximum x and y ranges of the tree
479 my $node = shift;
480 my $name = $node->get_name();
481 my $x1 = $node->_get_xcoord();
482 my $y1 = $node->_get_ycoord();
483 if ($node->is_otu() || $runtimeOptions{i}) {
484 # For each item, computes branch length with name and compares to highest known value
485 my ($x, $y) = ($x1 + 7.5, $y1 - 2.5);
486 printf "/branchlength ($name) stringwidth pop $x add ceiling def\n";
487 print "treemax branchlength le {/treemax branchlength def} if\n";
488 $treeHeight=$y if ($y > $treeHeight);
489 }
490 if (not $node->is_otu() ) {
491 foreach my $child (@{$node->get_children()} ) {
492 &__find_treemax($child);
493 }
494 }
495 }
496  
497 sub __find_xbound {
498 # Picks first OTU and finds treemax plus character length, that is,
499 # the x range of the entire plot
500 my ($node) = @_;
501 my $sequence = $sequences{ $node->get_name() };
502 my $x1 = $node->_get_xcoord();
503 my $y1 = $node->_get_ycoord();
504 if (not $node->is_otu()) {
505 foreach my $child (@{$node->get_children()} ) {
506 return 1 if &__find_xbound($child, $x1, $y1);
507 }
508 return 0;
509 }
510 my ($x, $y) = ($x1 + 7.5, $y1 - 2.5);
511 if (defined $sequence) {
512 my $display_seq = &__seqForDisplay($sequence);
513 print "characterfont setfont\n";
514 print "/xbound treemax (",$display_seq, ") stringwidth pop add def \n";
515 return 1;
516 }
517 return 0;
518 }
519  
520 sub __find_longest_label {
521 my @array = @_;
522 my $str = $array[$#array];
523 $str =~ s/-/\|/;
524 my $len=(length($str))*$fontSize;
525 return $len;
526 }
527  
528 sub __scale_rotate {
529 # DETERMINE EFFECTS OF PAGE FORMATTING OPTIONS
530 if ($runtimeOptions{a}) {
531 print "/pagehp ybound def /pagewp xbound def\n";
532 } else {
533 print "/pagehp $pageHeightPoints def /pagewp $pageWidthPoints def\n";
534 }
535 print "<< /PageSize [ pagewp pagehp ] >> setpagedevice\n";
536 print "gsave\n";
537 # If BigPrint is enabled, then convert the actual code into a function that BigPrint
538 # can use to split up into multiple sheets of paper. If not, then this function definition
539 # is not needed.
540 if ($runtimeOptions{o}) {
541 # Determine number of pages needed to print if page is kept the same and if page is rotated.
542 # Then choose the option with the lesser number of pages. (Only used with BigPrint option.)
543 # If plot is landscape, move origin to the right and rotate 90 degrees
544 print "/xcolr ybound 40 add pagewp 72 sub div ceiling def\n";
545 print "/ycolr xbound 40 add pagehp 72 sub div ceiling def\n";
546 print "/nprotate xcolr ycolr mul def\n";
547 print "/ycols ybound 40 add pagehp 72 sub div ceiling def\n";
548 print "/xcols xbound 40 add pagewp 72 sub div ceiling def\n";
549 print "/npsame xcols ycols mul def\n";
550 # print "nprotate = npsame = \n";
551 print "/pageratio pagehp pagewp div def\n";
552 print "npsame 1 eq nprotate 1 eq and \n";
553 print "{/rotatepage ybound xbound div 1 le pageratio 1 le ne def}\n";
554 print "{npsame nprotate ge {/rotatepage false def /xcol xcols def /ycol ycols def}\n";
555 print " {/rotatepage true def /xcol xcolr def /ycol ycolr def} ifelse}\n";
556 print "ifelse \n";
557 print "/printposter { gsave \n";
558 print "\trotatepage\n";
559 print "\t\{ybound 40 add ", $pageWidthPoints - 72, " div ceiling ", $pageWidthPoints-72, " mul \n";
560 print "\t0 translate 90 rotate 20 20 translate\}\n";
561 print "\t{20 20 translate} ifelse\n";
562 # print "\t0 translate \n"; # Used for debugging purposes
563 # __print_circle(0,0,5,1,1,0);
564 # print "90 rotate 36 36 translate\}\n";
565 # print "\t{\n";
566 # __print_circle(0,0,5,1,1,0);
567 # print "36 36 translate} ifelse\n";
568 }
569 elsif ($runtimeOptions{'s'}) {
570 print "/sca pagehp 72 sub ybound 45 add div def\n";
571 print "/xcol xbound sca mul pagewp 72 sub div ceiling def \n";
572 print "/ycol 1 def\n";
573 print "/pageratio pagehp pagewp div def\n";
574 print "/printposter { gsave \n";
575 print "20 sca mul 20 sca mul translate sca sca scale\n";
576 # __print_circle(0,0,5,1,0,0); # Used for debugging purposes
577 }
578 else {
579 print "/pageratio pagehp pagewp div def\n";
580 print "/rotatepage ybound xbound div 1 le pageratio 1 le ne def\n";
581 print "/ysca pagehp 72 sub ybound div def\n";
582 print "/xsca pagewp 72 sub xbound div def\n";
583 print "rotatepage\n";
584 print "\t{pagewp 36 sub 36 translate 90 rotate\n";
585 print "\t/xsca pagehp 72 sub xbound div def\n";
586 print "\t/ysca pagewp 72 sub ybound div def\} {36 36 translate} ifelse\n";
587 print "\tysca xsca le {ysca ysca scale} {xsca xsca scale} ifelse \n";
588 }
589 }
590  
591 sub __print_tree {
592 my ($node, $x0, $y0) = @_;
593 my $name = $node->get_name();
594 my $x1 = $node->_get_xcoord();
595 my $y1 = $node->_get_ycoord();
596 my $color = $nodeColorMap->{$name};
597 # print "\%START TREE\n";
598 print "$treeLineWidth setlinewidth\n";
599 &__print_line($x0, $y1, $x1, $y1, $color );
600 &__print_line($x0, $y0, $x0, $y1, $color) unless $node eq $root;
601 &__print_label($node, $x1 + 7.5, $y1 - 2.5, $color ) if $node->is_otu() || $runtimeOptions{i};
602 if (not $node->is_otu) {
603 foreach my $child (@{$node->get_children()} ) {
604 &__print_tree($child, $x1, $y1);
605 }
606 &__print_circle($x1, $y1, $treeNodeRadius, $color );
607 }
608 # print "\%END TREE\n";
609 }
610  
611 sub __print_matrix {
612 my ($node, $x0, $y0) = @_;
613 my $name = $node->get_name();
614 my $x = $node->_get_xcoord();
615 my $y = $node->_get_ycoord();
616 if ( ! $node->is_otu() ) {
617 foreach my $child (@{$node->get_children()} ) {
618 &__print_matrix($child,$x,$y);
619 }
620 } else {
621 my $color = $nodeColorMap->{$name};
622 printf "\t\t0 %.2f moveto ",$y;
623 print "(",$name,") show\n";
624 print "\t\t8 2.5 rmoveto\n";
625 printf "\t\t0.8 setgray $referenceLineWidth setlinewidth treemax 8 sub %.2f lineto stroke 0 setgray\n", $y+2.5;
626 printf "\t\ttreemax %.2f moveto ", $y;
627 &__print_sequence($sequences{$name}, $color);
628 }
629 }
630  
631 sub __print_label {
632 # print "\%START LABEL\n";
633 my ($node, $x, $y, $color) = @_;
634 $color = ( defined($color) ? $color : "0 0 0" );
635 print "\t\t$color setrgbcolor\n";
636
637 # Print either left justified or right justified names
638 print "\t\tdefaultfont setfont\n";
639 if ($runtimeOptions{r} && $node->is_otu()) {
640 printf "\t\ttreemax 8 sub ($node->{'name'}) stringwidth pop sub %.2f moveto ", $y;
641 } else {
642 printf "\t\t%.2f %.2f moveto ", $x, $y;
643 }
644 print "(", $node->{'name'}, ") show\n";
645 if ($node->is_otu()) {
646 if ($runtimeOptions{g} || !$runtimeOptions{t}) {
647 if ($runtimeOptions{r}) {
648 printf "\t\ttreemax 15.5 sub ($node->{'name'}) stringwidth pop sub %.2f moveto\n", $y+2.5;
649 printf "\t\t0.8 setgray $referenceLineWidth setlinewidth %.2f 8 add %.2f lineto stroke 0 setgray\n", $x, $y+2.5;
650 } else {
651 print "\t\t8 2.5 rmoveto\n";
652 printf "\t\t0.8 setgray $referenceLineWidth setlinewidth treemax 8 sub %.2f lineto stroke 0 setgray\n", $y+2.5;
653 }
654 # restore tree line width
655 print "\t\t$treeLineWidth setlinewidth \n";
656 }
657 if (defined $sequences{$node->{'name'}} && (! $runtimeOptions{t})) {
658 printf "\t\tcharacterfont setfont\n";
659 printf "\t\ttreemax %.2f moveto ", $y;
660 &__print_sequence($sequences{$node->{'name'}}, $color)
661 }
662 }
663 # print "\%END LABEL\n";
664 }
665  
666 sub __print_sequence() {
667 my $sequence = shift;
668 my $color = shift;
669 $color = ( defined($color) ? $color : "0 0 0" );
670 $sequence = uc(&__seqForDisplay($sequence));
671 # Print character table
672 print "\t\t$color setrgbcolor\n";
673 # for (my $i=0; $i<((length $sequence)/10) ; $i++) {
674 # print "(", substr($sequence, $i*10, 10), ") show\n";
675 # }
676 print "(", uc $sequence, ") show\n";
677 }
678  
679 sub __seqForDisplay() {
680 my $string = shift;
681 $string =~ tr/01/.+/;
682 my @tmp = split (//, $string);
683 my $tmp_string = "";
684 for (my $i = 0; $i <= $#tmp; $i++) {
685 if ($i && (($i % $blockWidth) == 0) ) { $tmp_string .= " " . $tmp[$i] }
686 else { $tmp_string .= $tmp[$i]; }
687 }
688 return $tmp_string;
689 }
690  
691 sub __print_circle {
692 my ($x, $y, $r, $color ) = @_;
693 $color = ( defined($color) ? $color : "0 0 0" );
694 print "\t$color setrgbcolor\n";
695 printf "\tnewpath %.2f %.2f %.2f %.2f %.2f arc fill stroke\n", $x, $y, $r, 0, 360;
696 }
697  
698  
699 sub __print_line {
700 my ($x0, $y0, $x1, $y1,$color) = @_;
701 $color = ( defined($color) ? $color : "0 0 0" );
702 print "\t",$color," setrgbcolor\n";
703 printf "\t%.2f %.2f %.2f %.2f l\n", $x0, $y0, $x1, $y1;
704 }
705  
706 sub __print_char_labels {
707 my @array = @_;
708 warn "WARNING: No labels\n" unless @array;
709 print "\n%%Character labels\n";
710 print "\tgsave\n";
711 printf "\t\tcharacterfont setfont\n";
712 # print "\t\t/letterwidth (a) stringwidth pop def\n";
713 if ($dataPresent{weights}) {
714 printf "\t\ttreemax %.2f translate\n", $treeHeight + 4 * $verticalOtuSpacing;
715 } else {
716 printf "\t\ttreemax %.2f translate\n", $treeHeight + $verticalOtuSpacing;
717 }
718 print "/charLabels ";
719 foreach my $label (@array) {
720 $label =~ s/-/\|/;
721 $label = reverse $label;
722 print "($label) ";
723 }
724 print $#array + 1, " packedarray def\n";
725 print "charLabels $#array $fontSize $blockWidth letterwidth showCharLabels\n";
726 print "\tgrestore\n\n";
727 }
728  
729 sub __plot_wts {
730 my @array = @_;
731 warn "WARNING: No weights\n" unless @array;
732 print "\n%%Histogram of character weights\n";
733 print "\tgsave\n";
734 printf "\t\tcharacterfont setfont\n";
735 printf "\t\t%.2f setlinewidth 0 setlinecap\n", $fontSize/3;
736 printf "\t\ttreemax (a) stringwidth pop 2 div sub %.2f translate\n", $treeHeight + $verticalOtuSpacing;
737 print "\t\tnewpath\n";
738 my $blank = 1;
739 my $max = $dataPresent{'CORE_column_scores'} ? 9 : __max(@array);
740 for (my $i = 0; $i <=$#array; $i++) {
741 my $value = ($array[$i] =~ /^[\d\.]+$/) ? $array[$i] : 0;
742 my $height = $value * $histogramHeight/$max;
743 if ( $i && ($i % $blockWidth) == 0 ) { # char #11, #21, etc.
744 $blank ++;
745 }
746 printf "\t\t\tletterwidth %d mul 0 moveto ", $i+$blank;
747 printf "letterwidth %d mul %.2f lineto\n", $i+$blank, $height;
748 }
749 print "\t\t0 setgray stroke\n";
750 print "\tgrestore\n";
751 }
752  
753 sub __print_boot_strap()
754 {
755 print "\tgsave\n";
756 printf "\t\tdefaultfont setfont 0.4 0.2 0 setrgbcolor\n"; # brown
757 print "\t\t/numwidth (99.99) stringwidth pop def\n";
758 foreach my $node (@nodes) {
759 next unless $node->get_support_value(); # print only non-zero values and only if defined in the tree
760 printf "\t\t%.2f (%.2f ) stringwidth pop sub %.2f moveto ", $node->_get_xcoord(), $node->get_support_value(), $node->_get_ycoord() + 7.2;
761 printf "(%.2f) show\n", $node->get_support_value();
762 }
763 print "\tgrestore\n";
764 }
765  
766 sub __end_post_script()
767 {
768 # PRINT SCALE
769 if ( (! $runtimeOptions{'m'}) && $dataPresent{trees} && (!($tree->is_cladogram())) ) {
770 print "\tgsave\n";
771 print "\t\tdefaultfont setfont\n";
772 printf "\t\t%.2f %.2f moveto\n", $lowerXbound, $fontSize*.45;
773 print "\t\t(0.1 substitution/site) show\n";
774 print "\tgrestore\n";
775 &__print_line($lowerXbound, $fontSize + 5, $lowerXbound + $amp / 10, $fontSize + 5);
776 &__print_line($lowerXbound, $fontSize + 10, $lowerXbound, $fontSize + 5);
777 &__print_line($lowerXbound + $amp / 10, $fontSize + 10, $lowerXbound + $amp / 10, $fontSize + 5);
778 }
779  
780 # PRINT END OF FILE
781 if ($runtimeOptions{B}) { # draw a box around what Postscript has determined is the plot
782 print "newpath 0 0 moveto xbound 0 lineto xbound ybound lineto 0 ybound lineto 0 0 lineto closepath\n";
783 print "$boxLineWidth setlinewidth stroke\n";
784 }
785 # print tree name
786 print "\ttitlefont setfont\n";
787 print "\ttreemax 2 div (", $treeName, ") stringwidth pop 2 div sub ybound $treeHeight sub 2 div $treeHeight add moveto\n";
788 print "\t(", $treeName, ") show\n";
789  
790 if ($runtimeOptions{o} || $runtimeOptions{'s'} ) {
791 # Draw bounding box
792 print "\tnewpath\n";
793 print "\t\t-20 ybound 20 add moveto\n";
794 print "\t\txbound 20 add ybound 20 add lineto\n";
795 print "\t\txbound 20 add -20 lineto\n";
796 print "\t\t-20 -20 lineto\n";
797 print "\t closepath\n";
798 print "\t\t\.05 inch setlinewidth 0.8 setgray stroke\n\n";
799 # End function definition
800 print "grestore \n";
801 print "\} def\n";
802 # Use BigPrint to convert to multiple sheets
803 print "\{printposter\} xcol ycol BigPrint\n";
804 print "grestore\n";
805 } else {
806 print "grestore\n";
807 }
808  
809 print "%%PageTrailer\n";
810 print "showpage\n" unless ($runtimeOptions{o} || $runtimeOptions{'s'});
811 print "%%Trailer\n";
812 print "%%EOF\n";
813 }
814  
815 sub __max {
816 my @array = @_;
817 my $max = 1;
818 for my $element (@array) {
819 next unless $element =~ /^[\d\.]+$/;
820 $max = ($max < $element) ? $element : $max;
821 }
822 return $max;
823 }
824  
825 ################# POD Documentation ##################
826  
827  
828 __END__