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