1 package Text::Tradition::Stemma;
4 use Encode qw( decode_utf8 );
9 use Graph::Reader::Dot;
10 use IPC::Run qw/ run binary /;
12 use Text::Balanced qw/ extract_bracketed /;
16 isa => 'Text::Tradition::Collation',
20 # TODO Think about making a new class for the graphs, which has apsp as a property.
24 predicate => 'has_graph',
30 writer => '_save_apsp',
33 has distance_trees => (
35 isa => 'ArrayRef[Graph]',
36 writer => '_save_distance_trees',
37 predicate => 'has_distance_trees',
40 has distance_apsps => (
42 isa => 'ArrayRef[Graph]',
43 writer => '_save_distance_apsps',
47 my( $self, $args ) = @_;
48 # If we have been handed a dotfile, initialize it into a graph.
49 if( exists $args->{'dot'} ) {
50 # Open the file, assume UTF-8
51 open( my $dot, $args->{'dot'} ) or warn "Failed to read dot file";
52 # TODO don't bother if we haven't opened
53 binmode $dot, ":utf8";
54 my $reader = Graph::Reader::Dot->new();
55 my $graph = $reader->read_graph( $dot );
57 ? $self->graph( $graph )
58 : warn "Failed to parse dot file " . $args->{'dot'};
62 # If we are saving a new graph, calculate its apsp values.
63 after 'graph' => sub {
64 my( $self, $args ) = @_;
68 if( $self->graph->is_directed ) {
69 # Make an undirected version.
70 $undirected = Graph->new( 'undirected' => 1 );
71 foreach my $v ( $self->graph->vertices ) {
72 $undirected->add_vertex( $v );
74 foreach my $e ( $self->graph->edges ) {
75 $undirected->add_edge( @$e );
78 $undirected = $self->graph;
80 $self->_save_apsp( $undirected->APSP_Floyd_Warshall() );
84 # Render the stemma as SVG.
86 my( $self, $opts ) = @_;
87 # TODO add options for display, someday
88 my $dgraph = Graph::Convert->as_graph_easy( $self->graph );
89 # Set some class display attributes for 'hypothetical' and 'extant' nodes
90 $dgraph->set_attribute( 'flow', 'south' );
91 foreach my $n ( $dgraph->nodes ) {
92 if( $n->attribute( 'class' ) eq 'hypothetical' ) {
93 $n->set_attribute( 'shape', 'point' );
94 $n->set_attribute( 'pointshape', 'diamond' );
96 $n->set_attribute( 'shape', 'ellipse' );
100 # Render to svg via graphviz
101 my @lines = split( /\n/, $dgraph->as_graphviz() );
102 # Add the size attribute
103 if( $opts->{'size'} ) {
104 my $sizeline = " graph [ size=\"" . $opts->{'size'} . "\" ]";
105 splice( @lines, 1, 0, $sizeline );
107 my @cmd = qw/dot -Tsvg/;
109 my $dotfile = File::Temp->new();
111 # $dotfile->unlink_on_destroy(0);
112 binmode $dotfile, ':utf8';
113 print $dotfile join( "\n", @lines );
114 push( @cmd, $dotfile->filename );
115 run( \@cmd, ">", binary(), \$svg );
116 $svg = decode_utf8( $svg );
120 #### Methods for calculating phylogenetic trees ####
122 before 'distance_trees' => sub {
125 # TODO allow specification of method for calculating distance tree
126 if( $args{'recalc'} || !$self->has_distance_trees ) {
127 # We need to make a tree before we can return it.
128 my( $ok, $result ) = $self->run_phylip_pars();
130 # Save the resulting trees
131 my $trees = _parse_newick( $result );
132 $self->_save_distance_trees( $trees );
133 # and calculate their APSP values.
135 foreach my $t ( @$trees ) {
136 push( @apsps, $t->APSP_Floyd_Warshall() );
138 $self->_save_distance_apsps( \@apsps );
140 warn "Failed to calculate distance trees: $result";
145 sub make_character_matrix {
147 unless( $self->collation->linear ) {
148 warn "Need a linear graph in order to make an alignment table";
151 my $table = $self->collation->make_alignment_table;
152 # Push the names of the witnesses to initialize the rows of the matrix.
153 my @matrix = map { [ $self->_normalize_ac( $_ ) ] } @{$table->[0]};
154 foreach my $token_index ( 1 .. $#{$table} ) {
155 # First implementation: make dumb alignment table, caring about
156 # nothing except which reading is in which position.
157 my @chars = convert_characters( $table->[$token_index] );
158 foreach my $idx ( 0 .. $#matrix ) {
159 push( @{$matrix[$idx]}, $chars[$idx] );
166 my( $self, $witname ) = @_;
167 my $ac = $self->collation->ac_label;
168 if( $witname =~ /(.*)\Q$ac\E$/ ) {
169 $witname = $1 . '_ac';
171 return sprintf( "%-10s", $witname );
174 sub convert_characters {
176 # This is a simple algorithm that treats every reading as different.
177 # Eventually we will want to be able to specify how relationships
178 # affect the character matrix.
179 my %unique = ( '__UNDEF__' => 'X',
183 foreach my $word ( @$row ) {
184 if( $word && !exists $unique{$word} ) {
185 $unique{$word} = chr( 65 + $ctr );
189 if( scalar( keys %unique ) > 8 ) {
190 warn "Have more than 8 variants on this location; phylip will break";
192 my @chars = map { $_ ? $unique{$_} : $unique{'__UNDEF__' } } @$row;
196 sub phylip_pars_input {
198 my $character_matrix = $self->make_character_matrix;
200 my $rows = scalar @{$character_matrix};
201 my $columns = scalar @{$character_matrix->[0]} - 1;
202 $input .= "\t$rows\t$columns\n";
203 foreach my $row ( @{$character_matrix} ) {
204 $input .= join( '', @$row ) . "\n";
209 sub run_phylip_pars {
212 # Set up a temporary directory for all the default Phylip files.
213 my $phylip_dir = File::Temp->newdir();
214 # $phylip_dir->unlink_on_destroy(0);
215 # We need an infile, and we need a command input file.
216 open( MATRIX, ">$phylip_dir/infile" ) or die "Could not write $phylip_dir/infile";
217 print MATRIX $self->phylip_pars_input();
220 open( CMD, ">$phylip_dir/cmdfile" ) or die "Could not write $phylip_dir/cmdfile";
221 ## TODO any configuration parameters we want to set here
222 # U Search for best tree? Yes
223 # S Search option? More thorough search
224 # V Number of trees to save? 100
225 # J Randomize input order of species? No. Use input order
226 # O Outgroup root? No, use as outgroup species 1
227 # T Use Threshold parsimony? No, use ordinary parsimony
228 # W Sites weighted? No
229 # M Analyze multiple data sets? No
230 # I Input species interleaved? Yes
231 # 0 Terminal type (IBM PC, ANSI, none)? ANSI
232 # 1 Print out the data at start of run No
233 # 2 Print indications of progress of run Yes
234 # 3 Print out tree Yes
235 # 4 Print out steps in each site No
236 # 5 Print character at all nodes of tree No
237 # 6 Write out trees onto tree file? Yes
241 # And then we run the program.
243 my $PHYLIP_PATH = '/Users/tla/Projects/phylip-3.69/exe';
244 my $program = "pars";
245 if( $^O eq 'darwin' ) {
246 $program = "$PHYLIP_PATH/$program.app/Contents/MacOS/$program";
248 $program = "$PHYLIP_PATH/$program";
252 # We need to run it in our temporary directory where we have created
253 # all the expected files.
254 local $CWD = $phylip_dir;
255 my @cmd = ( $program );
256 run \@cmd, '<', 'cmdfile', '>', '/dev/null';
258 # Now our output should be in 'outfile' and our tree in 'outtree',
259 # both in the temp directory.
262 if( -f "$phylip_dir/outtree" ) {
263 open( TREE, "$phylip_dir/outtree" ) or die "Could not open outtree for read";
267 return( 1, join( '', @outtree ) ) if @outtree;
270 if( -f "$phylip_dir/outfile" ) {
271 open( OUTPUT, "$phylip_dir/outfile" ) or die "Could not open output for read";
275 push( @error, "Neither outtree nor output file was produced!" );
277 return( undef, join( '', @error ) );
283 # Parse the result into a tree
284 my $forest = Bio::Phylo::IO->parse(
288 # Turn the tree into a graph, starting with the root node
289 foreach my $tree ( @{$forest->get_entities} ) {
290 push( @trees, _graph_from_bio( $tree ) );
295 sub _graph_from_bio {
297 my $graph = Graph->new( 'undirected' => 1 );
298 # Give all the intermediate anonymous nodes a name.
300 foreach my $n ( @{$tree->get_entities} ) {
301 next if $n->get_name;
302 $n->set_name( $i++ );
304 my $root = $tree->get_root->get_name;
305 $graph->add_vertex( $root );
306 _add_tree_children( $graph, $root, $tree->get_root->get_children() );
310 sub _add_tree_children {
311 my( $graph, $parent, $tree_children ) = @_;
312 foreach my $c ( @$tree_children ) {
313 my $child = $c->get_name;
314 $graph->add_vertex( $child );
315 $graph->add_path( $parent, $child );
316 _add_tree_children( $graph, $child, $c->get_children() );
321 __PACKAGE__->meta->make_immutable;