Get rid of Graph::Easy; add stemma tests
[scpubgit/stemmatology.git] / lib / Text / Tradition / Stemma.pm
CommitLineData
9463b0bf 1package Text::Tradition::Stemma;
2
40f19742 3use Bio::Phylo::IO;
e79c23c7 4use Encode qw( decode_utf8 );
9463b0bf 5use File::chdir;
6use File::Temp;
e05997e2 7use Graph;
8use Graph::Reader::Dot;
e79c23c7 9use IPC::Run qw/ run binary /;
40f19742 10use Moose;
9463b0bf 11
12has collation => (
13 is => 'ro',
14 isa => 'Text::Tradition::Collation',
15 required => 1,
8d9a1cd8 16 weak_ref => 1,
9463b0bf 17 );
18
e05997e2 19has graph => (
20 is => 'rw',
21 isa => 'Graph',
22 predicate => 'has_graph',
23 );
24
40f19742 25has distance_trees => (
26 is => 'ro',
27 isa => 'ArrayRef[Graph]',
28 writer => '_save_distance_trees',
29 predicate => 'has_distance_trees',
30 );
c0ccdb62 31
e05997e2 32sub BUILD {
33 my( $self, $args ) = @_;
34 # If we have been handed a dotfile, initialize it into a graph.
35 if( exists $args->{'dot'} ) {
8d9a1cd8 36 $self->graph_from_dot( $args->{'dot'} );
e05997e2 37 }
c0ccdb62 38}
39
8d9a1cd8 40sub graph_from_dot {
41 my( $self, $dotfh ) = @_;
42 # Assume utf-8
43 binmode( $dotfh, ':utf8' );
44 my $reader = Graph::Reader::Dot->new();
45 my $graph = $reader->read_graph( $dotfh );
7a7c249c 46 if( $graph ) {
47 $self->graph( $graph );
48 # Go through the nodes and set any non-hypothetical node to extant.
49 foreach my $v ( $self->graph->vertices ) {
50 $self->graph->set_vertex_attribute( $v, 'class', 'extant' )
51 unless $self->graph->has_vertex_attribute( $v, 'class' );
52 }
53 } else {
54 warn "Failed to parse dot in $dotfh";
55 }
8d9a1cd8 56}
57
58sub as_dot {
e367f5c0 59 my( $self, $opts ) = @_;
7a7c249c 60
61 # Get default and specified options
62 my %graphopts = ();
63 my %nodeopts = (
64 'fontsize' => 11,
65 'hshape' => 'plaintext', # Shape for the hypothetical nodes
66 'htext' => '*',
67 'style' => 'filled',
68 'fillcolor' => 'white',
69 'shape' => 'ellipse', # Shape for the extant nodes
70 );
71 my %edgeopts = (
72 'arrowhead' => 'open',
73 );
74 @graphopts{ keys %{$opts->{'graph'}} } = values %{$opts->{'graph'}}
75 if $opts->{'graph'};
76 @nodeopts{ keys %{$opts->{'node'}} } = values %{$opts->{'node'}}
77 if $opts->{'node'};
78 @edgeopts{ keys %{$opts->{'edge'}} } = values %{$opts->{'edge'}}
79 if $opts->{'edge'};
80
81 my @dotlines;
82 push( @dotlines, 'digraph stemma {' );
83 ## Print out the global attributes
84 push( @dotlines, _make_dotline( 'graph', %graphopts ) ) if keys %graphopts;
85 push( @dotlines, _make_dotline( 'edge', %edgeopts ) ) if keys %edgeopts;
86 ## Delete our special attributes from the node set before continuing
87 my $hshape = delete $nodeopts{'hshape'};
88 my $htext = delete $nodeopts{'htext'};
89 push( @dotlines, _make_dotline( 'node', %nodeopts ) ) if keys %nodeopts;
90
91 # Add each of the nodes.
92 foreach my $n ( $self->graph->vertices ) {
93 if( $self->graph->get_vertex_attribute( $n, 'class' ) eq 'hypothetical' ) {
94 # Apply our display settings for hypothetical nodes.
95 push( @dotlines, _make_dotline( $n, 'shape' => $hshape, 'label' => $htext ) );
e79c23c7 96 } else {
7a7c249c 97 # Use the default display settings.
98 push( @dotlines, " $n;" );
e79c23c7 99 }
100 }
7a7c249c 101 # Add each of our edges.
102 foreach my $e ( $self->graph->edges ) {
103 my( $from, $to ) = @$e;
104 push( @dotlines, " $from -> $to;" );
105 }
106 push( @dotlines, '}' );
e79c23c7 107
7a7c249c 108 return join( "\n", @dotlines );
109}
110
111
112# Another version of dot output meant for graph editing, thus
113# much simpler.
114sub editable {
115 my $self = shift;
116 my @dotlines;
117 push( @dotlines, 'digraph stemma {' );
118 my @real; # A cheap sort
119 foreach my $n ( sort $self->graph->vertices ) {
120 my $c = $self->graph->get_vertex_attribute( $n, 'class' );
121 $c = 'extant' unless $c;
122 if( $c eq 'extant' ) {
123 push( @real, $n );
124 } else {
125 push( @dotlines, _make_dotline( $n, 'class' => $c ) );
126 }
e367f5c0 127 }
7a7c249c 128 # Now do the real ones
129 foreach my $n ( @real ) {
130 push( @dotlines, _make_dotline( $n, 'class' => 'extant' ) );
131 }
132 foreach my $e ( sort _by_vertex $self->graph->edges ) {
133 my( $from, $to ) = @$e;
134 push( @dotlines, " $from -> $to;" );
135 }
136 push( @dotlines, '}' );
137 return join( "\n", @dotlines );
138}
139
140sub _make_dotline {
141 my( $obj, %attr ) = @_;
142 my @pairs;
143 foreach my $k ( keys %attr ) {
144 my $v = $attr{$k};
145 $v =~ s/\"/\\\"/g;
146 push( @pairs, "$k=\"$v\"" );
147 }
148 return sprintf( " %s [ %s ];", $obj, join( ', ', @pairs ) );
8d9a1cd8 149}
150
7a7c249c 151sub _by_vertex {
152 return $a->[0].$a->[1] cmp $b->[0].$b->[1];
153}
8d9a1cd8 154
155# Render the stemma as SVG.
156sub as_svg {
157 my( $self, $opts ) = @_;
158 my $dot = $self->as_dot( $opts );
e79c23c7 159 my @cmd = qw/dot -Tsvg/;
160 my( $svg, $err );
161 my $dotfile = File::Temp->new();
162 ## TODO REMOVE
163 # $dotfile->unlink_on_destroy(0);
164 binmode $dotfile, ':utf8';
8d9a1cd8 165 print $dotfile $dot;
e79c23c7 166 push( @cmd, $dotfile->filename );
167 run( \@cmd, ">", binary(), \$svg );
168 $svg = decode_utf8( $svg );
169 return $svg;
170}
171
08e0fb85 172sub witnesses {
173 my $self = shift;
174 my @wits = grep { $self->graph->get_vertex_attribute( $_, 'class' ) eq 'extant' }
175 $self->graph->vertices;
176 return @wits;
177}
178
e79c23c7 179#### Methods for calculating phylogenetic trees ####
180
40f19742 181before 'distance_trees' => sub {
182 my $self = shift;
183 my %args = @_;
184 # TODO allow specification of method for calculating distance tree
185 if( $args{'recalc'} || !$self->has_distance_trees ) {
186 # We need to make a tree before we can return it.
187 my( $ok, $result ) = $self->run_phylip_pars();
188 if( $ok ) {
c0ccdb62 189 # Save the resulting trees
190 my $trees = _parse_newick( $result );
191 $self->_save_distance_trees( $trees );
40f19742 192 } else {
c0ccdb62 193 warn "Failed to calculate distance trees: $result";
40f19742 194 }
195 }
196};
e05997e2 197
9463b0bf 198sub make_character_matrix {
199 my $self = shift;
200 unless( $self->collation->linear ) {
910a0a6d 201 warn "Need a linear graph in order to make an alignment table";
202 return;
9463b0bf 203 }
910a0a6d 204 my $table = $self->collation->make_alignment_table;
205 # Push the names of the witnesses to initialize the rows of the matrix.
206 my @matrix = map { [ $self->_normalize_ac( $_ ) ] } @{$table->[0]};
910a0a6d 207 foreach my $token_index ( 1 .. $#{$table} ) {
208 # First implementation: make dumb alignment table, caring about
209 # nothing except which reading is in which position.
210 my @chars = convert_characters( $table->[$token_index] );
211 foreach my $idx ( 0 .. $#matrix ) {
212 push( @{$matrix[$idx]}, $chars[$idx] );
213 }
9463b0bf 214 }
c0ccdb62 215 return \@matrix;
910a0a6d 216}
9463b0bf 217
910a0a6d 218sub _normalize_ac {
219 my( $self, $witname ) = @_;
220 my $ac = $self->collation->ac_label;
221 if( $witname =~ /(.*)\Q$ac\E$/ ) {
222 $witname = $1 . '_ac';
9463b0bf 223 }
910a0a6d 224 return sprintf( "%-10s", $witname );
9463b0bf 225}
9463b0bf 226
910a0a6d 227sub convert_characters {
228 my $row = shift;
9463b0bf 229 # This is a simple algorithm that treats every reading as different.
230 # Eventually we will want to be able to specify how relationships
231 # affect the character matrix.
eca16057 232 my %unique = ( '__UNDEF__' => 'X',
233 '#LACUNA#' => '?',
234 );
a7fb3133 235 my %count;
910a0a6d 236 my $ctr = 0;
237 foreach my $word ( @$row ) {
238 if( $word && !exists $unique{$word} ) {
239 $unique{$word} = chr( 65 + $ctr );
240 $ctr++;
241 }
a7fb3133 242 $count{$word}++ if $word;
9463b0bf 243 }
a7fb3133 244 # Try to keep variants under 8 by lacunizing any singletons.
910a0a6d 245 if( scalar( keys %unique ) > 8 ) {
a7fb3133 246 foreach my $word ( keys %count ) {
247 if( $count{$word} == 1 ) {
248 $unique{$word} = '?';
249 }
250 }
251 }
252 my %u = reverse %unique;
253 if( scalar( keys %u ) > 8 ) {
40f19742 254 warn "Have more than 8 variants on this location; phylip will break";
910a0a6d 255 }
256 my @chars = map { $_ ? $unique{$_} : $unique{'__UNDEF__' } } @$row;
257 return @chars;
9463b0bf 258}
259
40f19742 260sub phylip_pars_input {
9463b0bf 261 my $self = shift;
c0ccdb62 262 my $character_matrix = $self->make_character_matrix;
263 my $input = '';
264 my $rows = scalar @{$character_matrix};
265 my $columns = scalar @{$character_matrix->[0]} - 1;
266 $input .= "\t$rows\t$columns\n";
267 foreach my $row ( @{$character_matrix} ) {
268 $input .= join( '', @$row ) . "\n";
f6066bac 269 }
c0ccdb62 270 return $input;
f6066bac 271}
272
40f19742 273sub run_phylip_pars {
f6066bac 274 my $self = shift;
9463b0bf 275
276 # Set up a temporary directory for all the default Phylip files.
277 my $phylip_dir = File::Temp->newdir();
eca16057 278 # $phylip_dir->unlink_on_destroy(0);
f6066bac 279 # We need an infile, and we need a command input file.
9463b0bf 280 open( MATRIX, ">$phylip_dir/infile" ) or die "Could not write $phylip_dir/infile";
40f19742 281 print MATRIX $self->phylip_pars_input();
9463b0bf 282 close MATRIX;
283
284 open( CMD, ">$phylip_dir/cmdfile" ) or die "Could not write $phylip_dir/cmdfile";
285 ## TODO any configuration parameters we want to set here
286# U Search for best tree? Yes
287# S Search option? More thorough search
288# V Number of trees to save? 100
289# J Randomize input order of species? No. Use input order
290# O Outgroup root? No, use as outgroup species 1
291# T Use Threshold parsimony? No, use ordinary parsimony
292# W Sites weighted? No
293# M Analyze multiple data sets? No
294# I Input species interleaved? Yes
295# 0 Terminal type (IBM PC, ANSI, none)? ANSI
296# 1 Print out the data at start of run No
297# 2 Print indications of progress of run Yes
298# 3 Print out tree Yes
299# 4 Print out steps in each site No
300# 5 Print character at all nodes of tree No
301# 6 Write out trees onto tree file? Yes
302 print CMD "Y\n";
303 close CMD;
304
305 # And then we run the program.
306 ### HACKY HACKY
307 my $PHYLIP_PATH = '/Users/tla/Projects/phylip-3.69/exe';
308 my $program = "pars";
309 if( $^O eq 'darwin' ) {
910a0a6d 310 $program = "$PHYLIP_PATH/$program.app/Contents/MacOS/$program";
9463b0bf 311 } else {
910a0a6d 312 $program = "$PHYLIP_PATH/$program";
9463b0bf 313 }
314
315 {
910a0a6d 316 # We need to run it in our temporary directory where we have created
317 # all the expected files.
318 local $CWD = $phylip_dir;
319 my @cmd = ( $program );
320 run \@cmd, '<', 'cmdfile', '>', '/dev/null';
9463b0bf 321 }
322 # Now our output should be in 'outfile' and our tree in 'outtree',
323 # both in the temp directory.
324
325 my @outtree;
326 if( -f "$phylip_dir/outtree" ) {
910a0a6d 327 open( TREE, "$phylip_dir/outtree" ) or die "Could not open outtree for read";
328 @outtree = <TREE>;
329 close TREE;
9463b0bf 330 }
331 return( 1, join( '', @outtree ) ) if @outtree;
332
333 my @error;
f6066bac 334 if( -f "$phylip_dir/outfile" ) {
910a0a6d 335 open( OUTPUT, "$phylip_dir/outfile" ) or die "Could not open output for read";
336 @error = <OUTPUT>;
337 close OUTPUT;
9463b0bf 338 } else {
910a0a6d 339 push( @error, "Neither outtree nor output file was produced!" );
9463b0bf 340 }
341 return( undef, join( '', @error ) );
342}
343
40f19742 344sub _parse_newick {
345 my $newick = shift;
346 my @trees;
347 # Parse the result into a tree
348 my $forest = Bio::Phylo::IO->parse(
349 -format => 'newick',
350 -string => $newick,
351 );
352 # Turn the tree into a graph, starting with the root node
353 foreach my $tree ( @{$forest->get_entities} ) {
354 push( @trees, _graph_from_bio( $tree ) );
355 }
356 return \@trees;
357}
358
359sub _graph_from_bio {
360 my $tree = shift;
361 my $graph = Graph->new( 'undirected' => 1 );
362 # Give all the intermediate anonymous nodes a name.
363 my $i = 0;
364 foreach my $n ( @{$tree->get_entities} ) {
365 next if $n->get_name;
366 $n->set_name( $i++ );
367 }
368 my $root = $tree->get_root->get_name;
369 $graph->add_vertex( $root );
370 _add_tree_children( $graph, $root, $tree->get_root->get_children() );
371 return $graph;
372}
373
374sub _add_tree_children {
375 my( $graph, $parent, $tree_children ) = @_;
376 foreach my $c ( @$tree_children ) {
377 my $child = $c->get_name;
378 $graph->add_vertex( $child );
379 $graph->add_path( $parent, $child );
380 _add_tree_children( $graph, $child, $c->get_children() );
381 }
382}
383
9463b0bf 384no Moose;
385__PACKAGE__->meta->make_immutable;
386
3871;