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 { |
e367f5c0 |
86 | my( $self, $opts ) = @_; |
e79c23c7 |
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 |
e367f5c0 |
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 ); |
106 | } |
e79c23c7 |
107 | my @cmd = qw/dot -Tsvg/; |
108 | my( $svg, $err ); |
109 | my $dotfile = File::Temp->new(); |
110 | ## TODO REMOVE |
111 | # $dotfile->unlink_on_destroy(0); |
112 | binmode $dotfile, ':utf8'; |
e367f5c0 |
113 | print $dotfile join( "\n", @lines ); |
e79c23c7 |
114 | push( @cmd, $dotfile->filename ); |
115 | run( \@cmd, ">", binary(), \$svg ); |
116 | $svg = decode_utf8( $svg ); |
117 | return $svg; |
118 | } |
119 | |
120 | #### Methods for calculating phylogenetic trees #### |
121 | |
40f19742 |
122 | before 'distance_trees' => sub { |
123 | my $self = shift; |
124 | my %args = @_; |
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(); |
129 | if( $ok ) { |
c0ccdb62 |
130 | # Save the resulting trees |
131 | my $trees = _parse_newick( $result ); |
132 | $self->_save_distance_trees( $trees ); |
133 | # and calculate their APSP values. |
134 | my @apsps; |
135 | foreach my $t ( @$trees ) { |
136 | push( @apsps, $t->APSP_Floyd_Warshall() ); |
137 | } |
138 | $self->_save_distance_apsps( \@apsps ); |
40f19742 |
139 | } else { |
c0ccdb62 |
140 | warn "Failed to calculate distance trees: $result"; |
40f19742 |
141 | } |
142 | } |
143 | }; |
e05997e2 |
144 | |
9463b0bf |
145 | sub make_character_matrix { |
146 | my $self = shift; |
147 | unless( $self->collation->linear ) { |
910a0a6d |
148 | warn "Need a linear graph in order to make an alignment table"; |
149 | return; |
9463b0bf |
150 | } |
910a0a6d |
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]}; |
910a0a6d |
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] ); |
160 | } |
9463b0bf |
161 | } |
c0ccdb62 |
162 | return \@matrix; |
910a0a6d |
163 | } |
9463b0bf |
164 | |
910a0a6d |
165 | sub _normalize_ac { |
166 | my( $self, $witname ) = @_; |
167 | my $ac = $self->collation->ac_label; |
168 | if( $witname =~ /(.*)\Q$ac\E$/ ) { |
169 | $witname = $1 . '_ac'; |
9463b0bf |
170 | } |
910a0a6d |
171 | return sprintf( "%-10s", $witname ); |
9463b0bf |
172 | } |
9463b0bf |
173 | |
910a0a6d |
174 | sub convert_characters { |
175 | my $row = shift; |
9463b0bf |
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. |
eca16057 |
179 | my %unique = ( '__UNDEF__' => 'X', |
180 | '#LACUNA#' => '?', |
181 | ); |
910a0a6d |
182 | my $ctr = 0; |
183 | foreach my $word ( @$row ) { |
184 | if( $word && !exists $unique{$word} ) { |
185 | $unique{$word} = chr( 65 + $ctr ); |
186 | $ctr++; |
187 | } |
9463b0bf |
188 | } |
910a0a6d |
189 | if( scalar( keys %unique ) > 8 ) { |
40f19742 |
190 | warn "Have more than 8 variants on this location; phylip will break"; |
910a0a6d |
191 | } |
192 | my @chars = map { $_ ? $unique{$_} : $unique{'__UNDEF__' } } @$row; |
193 | return @chars; |
9463b0bf |
194 | } |
195 | |
40f19742 |
196 | sub phylip_pars_input { |
9463b0bf |
197 | my $self = shift; |
c0ccdb62 |
198 | my $character_matrix = $self->make_character_matrix; |
199 | my $input = ''; |
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"; |
f6066bac |
205 | } |
c0ccdb62 |
206 | return $input; |
f6066bac |
207 | } |
208 | |
40f19742 |
209 | sub run_phylip_pars { |
f6066bac |
210 | my $self = shift; |
9463b0bf |
211 | |
212 | # Set up a temporary directory for all the default Phylip files. |
213 | my $phylip_dir = File::Temp->newdir(); |
eca16057 |
214 | # $phylip_dir->unlink_on_destroy(0); |
f6066bac |
215 | # We need an infile, and we need a command input file. |
9463b0bf |
216 | open( MATRIX, ">$phylip_dir/infile" ) or die "Could not write $phylip_dir/infile"; |
40f19742 |
217 | print MATRIX $self->phylip_pars_input(); |
9463b0bf |
218 | close MATRIX; |
219 | |
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 |
238 | print CMD "Y\n"; |
239 | close CMD; |
240 | |
241 | # And then we run the program. |
242 | ### HACKY HACKY |
243 | my $PHYLIP_PATH = '/Users/tla/Projects/phylip-3.69/exe'; |
244 | my $program = "pars"; |
245 | if( $^O eq 'darwin' ) { |
910a0a6d |
246 | $program = "$PHYLIP_PATH/$program.app/Contents/MacOS/$program"; |
9463b0bf |
247 | } else { |
910a0a6d |
248 | $program = "$PHYLIP_PATH/$program"; |
9463b0bf |
249 | } |
250 | |
251 | { |
910a0a6d |
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'; |
9463b0bf |
257 | } |
258 | # Now our output should be in 'outfile' and our tree in 'outtree', |
259 | # both in the temp directory. |
260 | |
261 | my @outtree; |
262 | if( -f "$phylip_dir/outtree" ) { |
910a0a6d |
263 | open( TREE, "$phylip_dir/outtree" ) or die "Could not open outtree for read"; |
264 | @outtree = <TREE>; |
265 | close TREE; |
9463b0bf |
266 | } |
267 | return( 1, join( '', @outtree ) ) if @outtree; |
268 | |
269 | my @error; |
f6066bac |
270 | if( -f "$phylip_dir/outfile" ) { |
910a0a6d |
271 | open( OUTPUT, "$phylip_dir/outfile" ) or die "Could not open output for read"; |
272 | @error = <OUTPUT>; |
273 | close OUTPUT; |
9463b0bf |
274 | } else { |
910a0a6d |
275 | push( @error, "Neither outtree nor output file was produced!" ); |
9463b0bf |
276 | } |
277 | return( undef, join( '', @error ) ); |
278 | } |
279 | |
40f19742 |
280 | sub _parse_newick { |
281 | my $newick = shift; |
282 | my @trees; |
283 | # Parse the result into a tree |
284 | my $forest = Bio::Phylo::IO->parse( |
285 | -format => 'newick', |
286 | -string => $newick, |
287 | ); |
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 ) ); |
291 | } |
292 | return \@trees; |
293 | } |
294 | |
295 | sub _graph_from_bio { |
296 | my $tree = shift; |
297 | my $graph = Graph->new( 'undirected' => 1 ); |
298 | # Give all the intermediate anonymous nodes a name. |
299 | my $i = 0; |
300 | foreach my $n ( @{$tree->get_entities} ) { |
301 | next if $n->get_name; |
302 | $n->set_name( $i++ ); |
303 | } |
304 | my $root = $tree->get_root->get_name; |
305 | $graph->add_vertex( $root ); |
306 | _add_tree_children( $graph, $root, $tree->get_root->get_children() ); |
307 | return $graph; |
308 | } |
309 | |
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() ); |
317 | } |
318 | } |
319 | |
9463b0bf |
320 | no Moose; |
321 | __PACKAGE__->meta->make_immutable; |
322 | |
323 | 1; |