1 package Text::Tradition::Stemma;
4 use Encode qw( decode_utf8 );
9 use Graph::Reader::Dot;
10 use IPC::Run qw/ run binary /;
15 isa => 'Text::Tradition::Collation',
23 predicate => 'has_graph',
26 has distance_trees => (
28 isa => 'ArrayRef[Graph]',
29 writer => '_save_distance_trees',
30 predicate => 'has_distance_trees',
33 has distance_program => (
40 my( $self, $args ) = @_;
41 # If we have been handed a dotfile, initialize it into a graph.
42 if( exists $args->{'dot'} ) {
43 $self->graph_from_dot( $args->{'dot'} );
48 my( $self, $dotfh ) = @_;
50 binmode( $dotfh, ':utf8' );
51 my $reader = Graph::Reader::Dot->new();
52 my $graph = $reader->read_graph( $dotfh );
54 $self->graph( $graph );
55 # Go through the nodes and set any non-hypothetical node to extant.
56 foreach my $v ( $self->graph->vertices ) {
57 $self->graph->set_vertex_attribute( $v, 'class', 'extant' )
58 unless $self->graph->has_vertex_attribute( $v, 'class' );
61 warn "Failed to parse dot in $dotfh";
66 my( $self, $opts ) = @_;
68 # Get default and specified options
72 'hshape' => 'plaintext', # Shape for the hypothetical nodes
75 'fillcolor' => 'white',
76 'shape' => 'ellipse', # Shape for the extant nodes
79 'arrowhead' => 'open',
81 @graphopts{ keys %{$opts->{'graph'}} } = values %{$opts->{'graph'}}
83 @nodeopts{ keys %{$opts->{'node'}} } = values %{$opts->{'node'}}
85 @edgeopts{ keys %{$opts->{'edge'}} } = values %{$opts->{'edge'}}
89 push( @dotlines, 'digraph stemma {' );
90 ## Print out the global attributes
91 push( @dotlines, _make_dotline( 'graph', %graphopts ) ) if keys %graphopts;
92 push( @dotlines, _make_dotline( 'edge', %edgeopts ) ) if keys %edgeopts;
93 ## Delete our special attributes from the node set before continuing
94 my $hshape = delete $nodeopts{'hshape'};
95 my $htext = delete $nodeopts{'htext'};
96 push( @dotlines, _make_dotline( 'node', %nodeopts ) ) if keys %nodeopts;
98 # Add each of the nodes.
99 foreach my $n ( $self->graph->vertices ) {
100 if( $self->graph->get_vertex_attribute( $n, 'class' ) eq 'hypothetical' ) {
101 # Apply our display settings for hypothetical nodes.
102 push( @dotlines, _make_dotline( $n, 'shape' => $hshape, 'label' => $htext ) );
104 # Use the default display settings.
105 push( @dotlines, " $n;" );
108 # Add each of our edges.
109 foreach my $e ( $self->graph->edges ) {
110 my( $from, $to ) = @$e;
111 push( @dotlines, " $from -> $to;" );
113 push( @dotlines, '}' );
115 return join( "\n", @dotlines );
119 # Another version of dot output meant for graph editing, thus
124 push( @dotlines, 'digraph stemma {' );
125 my @real; # A cheap sort
126 foreach my $n ( sort $self->graph->vertices ) {
127 my $c = $self->graph->get_vertex_attribute( $n, 'class' );
128 $c = 'extant' unless $c;
129 if( $c eq 'extant' ) {
132 push( @dotlines, _make_dotline( $n, 'class' => $c ) );
135 # Now do the real ones
136 foreach my $n ( @real ) {
137 push( @dotlines, _make_dotline( $n, 'class' => 'extant' ) );
139 foreach my $e ( sort _by_vertex $self->graph->edges ) {
140 my( $from, $to ) = @$e;
141 push( @dotlines, " $from -> $to;" );
143 push( @dotlines, '}' );
144 return join( "\n", @dotlines );
148 my( $obj, %attr ) = @_;
150 foreach my $k ( keys %attr ) {
153 push( @pairs, "$k=\"$v\"" );
155 return sprintf( " %s [ %s ];", $obj, join( ', ', @pairs ) );
159 return $a->[0].$a->[1] cmp $b->[0].$b->[1];
162 # Render the stemma as SVG.
164 my( $self, $opts ) = @_;
165 my $dot = $self->as_dot( $opts );
166 my @cmd = qw/dot -Tsvg/;
168 my $dotfile = File::Temp->new();
170 # $dotfile->unlink_on_destroy(0);
171 binmode $dotfile, ':utf8';
173 push( @cmd, $dotfile->filename );
174 run( \@cmd, ">", binary(), \$svg );
175 $svg = decode_utf8( $svg );
181 my @wits = grep { $self->graph->get_vertex_attribute( $_, 'class' ) eq 'extant' }
182 $self->graph->vertices;
186 #### Methods for calculating phylogenetic trees ####
188 before 'distance_trees' => sub {
191 'program' => 'phylip_pars',
193 # TODO allow specification of method for calculating distance tree
194 if( !$self->has_distance_trees
195 || $args{'program'} ne $self->distance_program ) {
196 # We need to make a tree before we can return it.
197 my $dsub = 'run_' . $args{'program'};
198 my( $ok, $result ) = $self->$dsub();
200 # Save the resulting trees
201 my $trees = _parse_newick( $result );
202 $self->_save_distance_trees( $trees );
203 $self->distance_program( $args{'program'} );
205 warn "Failed to calculate distance trees: $result";
210 sub make_character_matrix {
212 unless( $self->collation->linear ) {
213 warn "Need a linear graph in order to make an alignment table";
216 my $table = $self->collation->make_alignment_table;
217 # Push the names of the witnesses to initialize the rows of the matrix.
218 my @matrix = map { [ $self->_normalize_ac( $_->{'witness'} ) ] }
219 @{$table->{'alignment'}};
220 foreach my $token_index ( 0 .. $table->{'length'} - 1) {
221 # First implementation: make dumb alignment table, caring about
222 # nothing except which reading is in which position.
223 my @pos_readings = map { $_->{'tokens'}->[$token_index] }
224 @{$table->{'alignment'}};
225 my @pos_text = map { $_ ? $_->{'t'} : $_ } @pos_readings;
226 my @chars = convert_characters( \@pos_text );
227 foreach my $idx ( 0 .. $#matrix ) {
228 push( @{$matrix[$idx]}, $chars[$idx] );
235 my( $self, $witname ) = @_;
236 my $ac = $self->collation->ac_label;
237 if( $witname =~ /(.*)\Q$ac\E$/ ) {
238 $witname = $1 . '_ac';
240 return sprintf( "%-10s", $witname );
243 sub convert_characters {
245 # This is a simple algorithm that treats every reading as different.
246 # Eventually we will want to be able to specify how relationships
247 # affect the character matrix.
248 my %unique = ( '__UNDEF__' => 'X',
253 foreach my $word ( @$row ) {
254 if( $word && !exists $unique{$word} ) {
255 $unique{$word} = chr( 65 + $ctr );
258 $count{$word}++ if $word;
260 # Try to keep variants under 8 by lacunizing any singletons.
261 if( scalar( keys %unique ) > 8 ) {
262 foreach my $word ( keys %count ) {
263 if( $count{$word} == 1 ) {
264 $unique{$word} = '?';
268 my %u = reverse %unique;
269 if( scalar( keys %u ) > 8 ) {
270 warn "Have more than 8 variants on this location; phylip will break";
272 my @chars = map { $_ ? $unique{$_} : $unique{'__UNDEF__' } } @$row;
276 sub phylip_pars_input {
278 my $character_matrix = $self->make_character_matrix;
280 my $rows = scalar @{$character_matrix};
281 my $columns = scalar @{$character_matrix->[0]} - 1;
282 $input .= "\t$rows\t$columns\n";
283 foreach my $row ( @{$character_matrix} ) {
284 $input .= join( '', @$row ) . "\n";
289 sub run_phylip_pars {
292 # Set up a temporary directory for all the default Phylip files.
293 my $phylip_dir = File::Temp->newdir();
294 # $phylip_dir->unlink_on_destroy(0);
295 # We need an infile, and we need a command input file.
296 open( MATRIX, ">$phylip_dir/infile" ) or die "Could not write $phylip_dir/infile";
297 print MATRIX $self->phylip_pars_input();
300 open( CMD, ">$phylip_dir/cmdfile" ) or die "Could not write $phylip_dir/cmdfile";
301 ## TODO any configuration parameters we want to set here
302 # U Search for best tree? Yes
303 # S Search option? More thorough search
304 # V Number of trees to save? 100
305 # J Randomize input order of species? No. Use input order
306 # O Outgroup root? No, use as outgroup species 1
307 # T Use Threshold parsimony? No, use ordinary parsimony
308 # W Sites weighted? No
309 # M Analyze multiple data sets? No
310 # I Input species interleaved? Yes
311 # 0 Terminal type (IBM PC, ANSI, none)? ANSI
312 # 1 Print out the data at start of run No
313 # 2 Print indications of progress of run Yes
314 # 3 Print out tree Yes
315 # 4 Print out steps in each site No
316 # 5 Print character at all nodes of tree No
317 # 6 Write out trees onto tree file? Yes
321 # And then we run the program.
322 my $program = File::Which::which( 'pars' );
323 unless( -x $program ) {
324 return( undef, "Phylip pars not found in path" );
328 # We need to run it in our temporary directory where we have created
329 # all the expected files.
330 local $CWD = $phylip_dir;
331 my @cmd = ( $program );
332 run \@cmd, '<', 'cmdfile', '>', '/dev/null';
334 # Now our output should be in 'outfile' and our tree in 'outtree',
335 # both in the temp directory.
338 if( -f "$phylip_dir/outtree" ) {
339 open( TREE, "$phylip_dir/outtree" ) or die "Could not open outtree for read";
343 return( 1, join( '', @outtree ) ) if @outtree;
346 if( -f "$phylip_dir/outfile" ) {
347 open( OUTPUT, "$phylip_dir/outfile" ) or die "Could not open output for read";
351 push( @error, "Neither outtree nor output file was produced!" );
353 return( undef, join( '', @error ) );
359 # Parse the result into a tree
360 my $forest = Bio::Phylo::IO->parse(
364 # Turn the tree into a graph, starting with the root node
365 foreach my $tree ( @{$forest->get_entities} ) {
366 push( @trees, _graph_from_bio( $tree ) );
371 sub _graph_from_bio {
373 my $graph = Graph->new( 'undirected' => 1 );
374 # Give all the intermediate anonymous nodes a name.
376 foreach my $n ( @{$tree->get_entities} ) {
377 next if $n->get_name;
378 $n->set_name( $i++ );
380 my $root = $tree->get_root->get_name;
381 $graph->add_vertex( $root );
382 _add_tree_children( $graph, $root, $tree->get_root->get_children() );
386 sub _add_tree_children {
387 my( $graph, $parent, $tree_children ) = @_;
388 foreach my $c ( @$tree_children ) {
389 my $child = $c->get_name;
390 $graph->add_vertex( $child );
391 $graph->add_path( $parent, $child );
392 _add_tree_children( $graph, $child, $c->get_children() );
397 __PACKAGE__->meta->make_immutable;