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