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