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