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; |
e05997e2 |
7 | use Graph; |
e79c23c7 |
8 | use Graph::Convert; |
e05997e2 |
9 | use Graph::Reader::Dot; |
e79c23c7 |
10 | use IPC::Run qw/ run binary /; |
40f19742 |
11 | use Moose; |
12 | use Text::Balanced qw/ extract_bracketed /; |
9463b0bf |
13 | |
14 | has collation => ( |
15 | is => 'ro', |
16 | isa => 'Text::Tradition::Collation', |
17 | required => 1, |
18 | ); |
19 | |
20 | has character_matrix => ( |
21 | is => 'ro', |
22 | isa => 'ArrayRef[ArrayRef[Str]]', |
23 | writer => '_save_character_matrix', |
24 | predicate => 'has_character_matrix', |
25 | ); |
e05997e2 |
26 | |
27 | has graph => ( |
28 | is => 'rw', |
29 | isa => 'Graph', |
30 | predicate => 'has_graph', |
31 | ); |
32 | |
33 | has apsp => ( |
34 | is => 'rw', |
35 | isa => 'Graph', |
36 | ); |
40f19742 |
37 | |
38 | has distance_trees => ( |
39 | is => 'ro', |
40 | isa => 'ArrayRef[Graph]', |
41 | writer => '_save_distance_trees', |
42 | predicate => 'has_distance_trees', |
43 | ); |
e05997e2 |
44 | |
45 | sub BUILD { |
46 | my( $self, $args ) = @_; |
47 | # If we have been handed a dotfile, initialize it into a graph. |
48 | if( exists $args->{'dot'} ) { |
e79c23c7 |
49 | # Open the file, assume UTF-8 |
50 | open( my $dot, $args->{'dot'} ) or warn "Failed to read dot file"; |
51 | # TODO don't bother if we haven't opened |
52 | binmode $dot, ":utf8"; |
e05997e2 |
53 | my $reader = Graph::Reader::Dot->new(); |
e79c23c7 |
54 | my $graph = $reader->read_graph( $dot ); |
e05997e2 |
55 | $graph |
56 | ? $self->graph( $graph ) |
57 | : warn "Failed to parse dot file " . $args->{'dot'}; |
58 | } |
59 | |
60 | # If we have a graph, calculate all the shortest paths between nodes, |
61 | # disregarding direction. |
62 | if( $self->has_graph ) { |
63 | my $undirected; |
64 | if( $self->graph->is_directed ) { |
65 | # Make an undirected version. |
66 | $undirected = Graph->new( 'undirected' => 1 ); |
67 | foreach my $v ( $self->graph->vertices ) { |
68 | $undirected->add_vertex( $v ); |
69 | } |
70 | foreach my $e ( $self->graph->edges ) { |
71 | $undirected->add_edge( @$e ); |
72 | } |
73 | } else { |
74 | $undirected = $self->graph; |
75 | } |
76 | $self->apsp( $undirected->APSP_Floyd_Warshall() ); |
77 | } |
78 | } |
40f19742 |
79 | |
e79c23c7 |
80 | # Render the stemma as SVG. |
81 | sub as_svg { |
82 | my $self = shift; |
83 | # TODO add options for display, someday |
84 | my $dgraph = Graph::Convert->as_graph_easy( $self->graph ); |
85 | # Set some class display attributes for 'hypothetical' and 'extant' nodes |
86 | $dgraph->set_attribute( 'flow', 'south' ); |
87 | foreach my $n ( $dgraph->nodes ) { |
88 | if( $n->attribute( 'class' ) eq 'hypothetical' ) { |
89 | $n->set_attribute( 'shape', 'point' ); |
90 | $n->set_attribute( 'pointshape', 'diamond' ); |
91 | } else { |
92 | $n->set_attribute( 'shape', 'ellipse' ); |
93 | } |
94 | } |
95 | |
96 | # Render to svg via graphviz |
97 | my @cmd = qw/dot -Tsvg/; |
98 | my( $svg, $err ); |
99 | my $dotfile = File::Temp->new(); |
100 | ## TODO REMOVE |
101 | # $dotfile->unlink_on_destroy(0); |
102 | binmode $dotfile, ':utf8'; |
103 | print $dotfile $dgraph->as_graphviz(); |
104 | push( @cmd, $dotfile->filename ); |
105 | run( \@cmd, ">", binary(), \$svg ); |
106 | $svg = decode_utf8( $svg ); |
107 | return $svg; |
108 | } |
109 | |
110 | #### Methods for calculating phylogenetic trees #### |
111 | |
40f19742 |
112 | before 'distance_trees' => sub { |
113 | my $self = shift; |
114 | my %args = @_; |
115 | # TODO allow specification of method for calculating distance tree |
116 | if( $args{'recalc'} || !$self->has_distance_trees ) { |
117 | # We need to make a tree before we can return it. |
118 | my( $ok, $result ) = $self->run_phylip_pars(); |
119 | if( $ok ) { |
120 | $self->_save_distance_trees( _parse_newick( $result ) ); |
121 | } else { |
122 | warn "Failed to calculate distance tree: $result"; |
123 | } |
124 | } |
125 | }; |
e05997e2 |
126 | |
9463b0bf |
127 | sub make_character_matrix { |
128 | my $self = shift; |
129 | unless( $self->collation->linear ) { |
910a0a6d |
130 | warn "Need a linear graph in order to make an alignment table"; |
131 | return; |
9463b0bf |
132 | } |
910a0a6d |
133 | my $table = $self->collation->make_alignment_table; |
134 | # Push the names of the witnesses to initialize the rows of the matrix. |
135 | my @matrix = map { [ $self->_normalize_ac( $_ ) ] } @{$table->[0]}; |
136 | $DB::single = 1; |
137 | foreach my $token_index ( 1 .. $#{$table} ) { |
138 | # First implementation: make dumb alignment table, caring about |
139 | # nothing except which reading is in which position. |
140 | my @chars = convert_characters( $table->[$token_index] ); |
141 | foreach my $idx ( 0 .. $#matrix ) { |
142 | push( @{$matrix[$idx]}, $chars[$idx] ); |
143 | } |
9463b0bf |
144 | } |
910a0a6d |
145 | $self->_save_character_matrix( \@matrix ); |
146 | } |
9463b0bf |
147 | |
910a0a6d |
148 | sub _normalize_ac { |
149 | my( $self, $witname ) = @_; |
150 | my $ac = $self->collation->ac_label; |
151 | if( $witname =~ /(.*)\Q$ac\E$/ ) { |
152 | $witname = $1 . '_ac'; |
9463b0bf |
153 | } |
910a0a6d |
154 | return sprintf( "%-10s", $witname ); |
9463b0bf |
155 | } |
9463b0bf |
156 | |
910a0a6d |
157 | sub convert_characters { |
158 | my $row = shift; |
9463b0bf |
159 | # This is a simple algorithm that treats every reading as different. |
160 | # Eventually we will want to be able to specify how relationships |
161 | # affect the character matrix. |
eca16057 |
162 | my %unique = ( '__UNDEF__' => 'X', |
163 | '#LACUNA#' => '?', |
164 | ); |
910a0a6d |
165 | my $ctr = 0; |
166 | foreach my $word ( @$row ) { |
167 | if( $word && !exists $unique{$word} ) { |
168 | $unique{$word} = chr( 65 + $ctr ); |
169 | $ctr++; |
170 | } |
9463b0bf |
171 | } |
910a0a6d |
172 | if( scalar( keys %unique ) > 8 ) { |
40f19742 |
173 | warn "Have more than 8 variants on this location; phylip will break"; |
910a0a6d |
174 | } |
175 | my @chars = map { $_ ? $unique{$_} : $unique{'__UNDEF__' } } @$row; |
176 | return @chars; |
9463b0bf |
177 | } |
178 | |
40f19742 |
179 | sub phylip_pars_input { |
9463b0bf |
180 | my $self = shift; |
181 | $self->make_character_matrix unless $self->has_character_matrix; |
f6066bac |
182 | my $matrix = ''; |
183 | my $rows = scalar @{$self->character_matrix}; |
184 | my $columns = scalar @{$self->character_matrix->[0]} - 1; |
185 | $matrix .= "\t$rows\t$columns\n"; |
186 | foreach my $row ( @{$self->character_matrix} ) { |
910a0a6d |
187 | $matrix .= join( '', @$row ) . "\n"; |
f6066bac |
188 | } |
189 | return $matrix; |
190 | } |
191 | |
40f19742 |
192 | sub run_phylip_pars { |
f6066bac |
193 | my $self = shift; |
9463b0bf |
194 | |
195 | # Set up a temporary directory for all the default Phylip files. |
196 | my $phylip_dir = File::Temp->newdir(); |
eca16057 |
197 | # $phylip_dir->unlink_on_destroy(0); |
f6066bac |
198 | # We need an infile, and we need a command input file. |
9463b0bf |
199 | open( MATRIX, ">$phylip_dir/infile" ) or die "Could not write $phylip_dir/infile"; |
40f19742 |
200 | print MATRIX $self->phylip_pars_input(); |
9463b0bf |
201 | close MATRIX; |
202 | |
203 | open( CMD, ">$phylip_dir/cmdfile" ) or die "Could not write $phylip_dir/cmdfile"; |
204 | ## TODO any configuration parameters we want to set here |
205 | # U Search for best tree? Yes |
206 | # S Search option? More thorough search |
207 | # V Number of trees to save? 100 |
208 | # J Randomize input order of species? No. Use input order |
209 | # O Outgroup root? No, use as outgroup species 1 |
210 | # T Use Threshold parsimony? No, use ordinary parsimony |
211 | # W Sites weighted? No |
212 | # M Analyze multiple data sets? No |
213 | # I Input species interleaved? Yes |
214 | # 0 Terminal type (IBM PC, ANSI, none)? ANSI |
215 | # 1 Print out the data at start of run No |
216 | # 2 Print indications of progress of run Yes |
217 | # 3 Print out tree Yes |
218 | # 4 Print out steps in each site No |
219 | # 5 Print character at all nodes of tree No |
220 | # 6 Write out trees onto tree file? Yes |
221 | print CMD "Y\n"; |
222 | close CMD; |
223 | |
224 | # And then we run the program. |
225 | ### HACKY HACKY |
226 | my $PHYLIP_PATH = '/Users/tla/Projects/phylip-3.69/exe'; |
227 | my $program = "pars"; |
228 | if( $^O eq 'darwin' ) { |
910a0a6d |
229 | $program = "$PHYLIP_PATH/$program.app/Contents/MacOS/$program"; |
9463b0bf |
230 | } else { |
910a0a6d |
231 | $program = "$PHYLIP_PATH/$program"; |
9463b0bf |
232 | } |
233 | |
234 | { |
910a0a6d |
235 | # We need to run it in our temporary directory where we have created |
236 | # all the expected files. |
237 | local $CWD = $phylip_dir; |
238 | my @cmd = ( $program ); |
239 | run \@cmd, '<', 'cmdfile', '>', '/dev/null'; |
9463b0bf |
240 | } |
241 | # Now our output should be in 'outfile' and our tree in 'outtree', |
242 | # both in the temp directory. |
243 | |
244 | my @outtree; |
245 | if( -f "$phylip_dir/outtree" ) { |
910a0a6d |
246 | open( TREE, "$phylip_dir/outtree" ) or die "Could not open outtree for read"; |
247 | @outtree = <TREE>; |
248 | close TREE; |
9463b0bf |
249 | } |
250 | return( 1, join( '', @outtree ) ) if @outtree; |
251 | |
252 | my @error; |
f6066bac |
253 | if( -f "$phylip_dir/outfile" ) { |
910a0a6d |
254 | open( OUTPUT, "$phylip_dir/outfile" ) or die "Could not open output for read"; |
255 | @error = <OUTPUT>; |
256 | close OUTPUT; |
9463b0bf |
257 | } else { |
910a0a6d |
258 | push( @error, "Neither outtree nor output file was produced!" ); |
9463b0bf |
259 | } |
260 | return( undef, join( '', @error ) ); |
261 | } |
262 | |
40f19742 |
263 | sub _parse_newick { |
264 | my $newick = shift; |
265 | my @trees; |
266 | # Parse the result into a tree |
267 | my $forest = Bio::Phylo::IO->parse( |
268 | -format => 'newick', |
269 | -string => $newick, |
270 | ); |
271 | # Turn the tree into a graph, starting with the root node |
272 | foreach my $tree ( @{$forest->get_entities} ) { |
273 | push( @trees, _graph_from_bio( $tree ) ); |
274 | } |
275 | return \@trees; |
276 | } |
277 | |
278 | sub _graph_from_bio { |
279 | my $tree = shift; |
280 | my $graph = Graph->new( 'undirected' => 1 ); |
281 | # Give all the intermediate anonymous nodes a name. |
282 | my $i = 0; |
283 | foreach my $n ( @{$tree->get_entities} ) { |
284 | next if $n->get_name; |
285 | $n->set_name( $i++ ); |
286 | } |
287 | my $root = $tree->get_root->get_name; |
288 | $graph->add_vertex( $root ); |
289 | _add_tree_children( $graph, $root, $tree->get_root->get_children() ); |
290 | return $graph; |
291 | } |
292 | |
293 | sub _add_tree_children { |
294 | my( $graph, $parent, $tree_children ) = @_; |
295 | foreach my $c ( @$tree_children ) { |
296 | my $child = $c->get_name; |
297 | $graph->add_vertex( $child ); |
298 | $graph->add_path( $parent, $child ); |
299 | _add_tree_children( $graph, $child, $c->get_children() ); |
300 | } |
301 | } |
302 | |
9463b0bf |
303 | no Moose; |
304 | __PACKAGE__->meta->make_immutable; |
305 | |
306 | 1; |