allow automatic sizing of stemma; put more data into the visualizer
[scpubgit/stemmatology.git] / lib / Text / Tradition / Stemma.pm
1 package Text::Tradition::Stemma;
2
3 use Bio::Phylo::IO;
4 use Encode qw( decode_utf8 );
5 use File::chdir;
6 use File::Temp;
7 use Graph;
8 use Graph::Convert;
9 use Graph::Reader::Dot;
10 use IPC::Run qw/ run binary /;
11 use Moose;
12 use Text::Balanced qw/ extract_bracketed /;
13
14 has collation => (
15     is => 'ro',
16     isa => 'Text::Tradition::Collation',
17     required => 1,
18     );  
19
20 # TODO Think about making a new class for the graphs, which has apsp as a property.
21 has graph => (
22     is => 'rw',
23     isa => 'Graph',
24     predicate => 'has_graph',
25     );
26     
27 has apsp => (
28     is => 'ro',
29     isa => 'Graph',
30     writer => '_save_apsp',
31     );
32     
33 has distance_trees => (
34     is => 'ro',
35     isa => 'ArrayRef[Graph]',
36     writer => '_save_distance_trees',
37     predicate => 'has_distance_trees',
38     );
39     
40 has distance_apsps => (
41     is => 'ro',
42     isa => 'ArrayRef[Graph]',
43     writer => '_save_distance_apsps',
44     );
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'} ) {
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";
54         my $reader = Graph::Reader::Dot->new();
55         my $graph = $reader->read_graph( $dot );
56         $graph 
57             ? $self->graph( $graph ) 
58             : warn "Failed to parse dot file " . $args->{'dot'};
59     }
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.
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         }
80         $self->_save_apsp( $undirected->APSP_Floyd_Warshall() );
81     }       
82 };
83
84 # Render the stemma as SVG.
85 sub as_svg {
86     my( $self, $opts ) = @_;
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 @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     }
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';
113     print $dotfile join( "\n", @lines );
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
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 ) {
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 );
139         } else {
140             warn "Failed to calculate distance trees: $result";
141         }
142     }
143 };
144         
145 sub make_character_matrix {
146     my $self = shift;
147     unless( $self->collation->linear ) {
148         warn "Need a linear graph in order to make an alignment table";
149         return;
150     }
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]};
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         }
161     }
162     return \@matrix;
163
164
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';
170     }
171     return sprintf( "%-10s", $witname );
172 }
173
174 sub convert_characters {
175     my $row = shift;
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.
179     my %unique = ( '__UNDEF__' => 'X',
180                    '#LACUNA#'  => '?',
181                  );
182     my $ctr = 0;
183     foreach my $word ( @$row ) {
184         if( $word && !exists $unique{$word} ) {
185             $unique{$word} = chr( 65 + $ctr );
186             $ctr++;
187         }
188     }
189     if( scalar( keys %unique ) > 8 ) {
190         warn "Have more than 8 variants on this location; phylip will break";
191     }
192     my @chars = map { $_ ? $unique{$_} : $unique{'__UNDEF__' } } @$row;
193     return @chars;
194 }
195
196 sub phylip_pars_input {
197     my $self = shift;
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";
205     }
206     return $input;
207 }
208
209 sub run_phylip_pars {
210     my $self = shift;
211
212     # Set up a temporary directory for all the default Phylip files.
213     my $phylip_dir = File::Temp->newdir();
214     # $phylip_dir->unlink_on_destroy(0);
215     # We need an infile, and we need a command input file.
216     open( MATRIX, ">$phylip_dir/infile" ) or die "Could not write $phylip_dir/infile";
217     print MATRIX $self->phylip_pars_input();
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' ) {
246         $program = "$PHYLIP_PATH/$program.app/Contents/MacOS/$program";
247     } else {
248         $program = "$PHYLIP_PATH/$program";
249     }
250
251     {
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';
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" ) {
263         open( TREE, "$phylip_dir/outtree" ) or die "Could not open outtree for read";
264         @outtree = <TREE>;
265         close TREE;
266     }
267     return( 1, join( '', @outtree ) ) if @outtree;
268
269     my @error;
270     if( -f "$phylip_dir/outfile" ) {
271         open( OUTPUT, "$phylip_dir/outfile" ) or die "Could not open output for read";
272         @error = <OUTPUT>;
273         close OUTPUT;
274     } else {
275         push( @error, "Neither outtree nor output file was produced!" );
276     }
277     return( undef, join( '', @error ) );
278 }
279
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
320 no Moose;
321 __PACKAGE__->meta->make_immutable;
322     
323 1;