28a910944eb61b6e1d36fd4c2e1dce4822e496b6
[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 has graph => (
21     is => 'rw',
22     isa => 'Graph',
23     predicate => 'has_graph',
24     );
25     
26 has distance_trees => (
27     is => 'ro',
28     isa => 'ArrayRef[Graph]',
29     writer => '_save_distance_trees',
30     predicate => 'has_distance_trees',
31     );
32     
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'} ) {
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";
41         my $reader = Graph::Reader::Dot->new();
42         my $graph = $reader->read_graph( $dot );
43         $graph 
44             ? $self->graph( $graph ) 
45             : warn "Failed to parse dot file " . $args->{'dot'};
46     }
47 }
48
49 # Render the stemma as SVG.
50 sub as_svg {
51     my( $self, $opts ) = @_;
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
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     }
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';
78     print $dotfile join( "\n", @lines );
79     push( @cmd, $dotfile->filename );
80     run( \@cmd, ">", binary(), \$svg );
81     $svg = decode_utf8( $svg );
82     return $svg;
83 }
84
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
92 #### Methods for calculating phylogenetic trees ####
93
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 ) {
102             # Save the resulting trees
103             my $trees = _parse_newick( $result );
104             $self->_save_distance_trees( $trees );
105         } else {
106             warn "Failed to calculate distance trees: $result";
107         }
108     }
109 };
110         
111 sub make_character_matrix {
112     my $self = shift;
113     unless( $self->collation->linear ) {
114         warn "Need a linear graph in order to make an alignment table";
115         return;
116     }
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]};
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         }
127     }
128     return \@matrix;
129
130
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';
136     }
137     return sprintf( "%-10s", $witname );
138 }
139
140 sub convert_characters {
141     my $row = shift;
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.
145     my %unique = ( '__UNDEF__' => 'X',
146                    '#LACUNA#'  => '?',
147                  );
148     my %count;
149     my $ctr = 0;
150     foreach my $word ( @$row ) {
151         if( $word && !exists $unique{$word} ) {
152             $unique{$word} = chr( 65 + $ctr );
153             $ctr++;
154         }
155         $count{$word}++ if $word;
156     }
157     # Try to keep variants under 8 by lacunizing any singletons.
158     if( scalar( keys %unique ) > 8 ) {
159                 foreach my $word ( keys %count ) {
160                         if( $count{$word} == 1 ) {
161                                 $unique{$word} = '?';
162                         }
163                 }
164     }
165     my %u = reverse %unique;
166     if( scalar( keys %u ) > 8 ) {
167         warn "Have more than 8 variants on this location; phylip will break";
168     }
169     my @chars = map { $_ ? $unique{$_} : $unique{'__UNDEF__' } } @$row;
170     return @chars;
171 }
172
173 sub phylip_pars_input {
174     my $self = shift;
175     my $character_matrix = $self->make_character_matrix;
176     my $input = '';
177     my $rows = scalar @{$character_matrix};
178     my $columns = scalar @{$character_matrix->[0]} - 1;
179     $input .= "\t$rows\t$columns\n";
180     foreach my $row ( @{$character_matrix} ) {
181         $input .= join( '', @$row ) . "\n";
182     }
183     return $input;
184 }
185
186 sub run_phylip_pars {
187     my $self = shift;
188
189     # Set up a temporary directory for all the default Phylip files.
190     my $phylip_dir = File::Temp->newdir();
191     # $phylip_dir->unlink_on_destroy(0);
192     # We need an infile, and we need a command input file.
193     open( MATRIX, ">$phylip_dir/infile" ) or die "Could not write $phylip_dir/infile";
194     print MATRIX $self->phylip_pars_input();
195     close MATRIX;
196
197     open( CMD, ">$phylip_dir/cmdfile" ) or die "Could not write $phylip_dir/cmdfile";
198     ## TODO any configuration parameters we want to set here
199 #   U                 Search for best tree?  Yes
200 #   S                        Search option?  More thorough search
201 #   V              Number of trees to save?  100
202 #   J     Randomize input order of species?  No. Use input order
203 #   O                        Outgroup root?  No, use as outgroup species 1
204 #   T              Use Threshold parsimony?  No, use ordinary parsimony
205 #   W                       Sites weighted?  No
206 #   M           Analyze multiple data sets?  No
207 #   I            Input species interleaved?  Yes
208 #   0   Terminal type (IBM PC, ANSI, none)?  ANSI
209 #   1    Print out the data at start of run  No
210 #   2  Print indications of progress of run  Yes
211 #   3                        Print out tree  Yes
212 #   4          Print out steps in each site  No
213 #   5  Print character at all nodes of tree  No
214 #   6       Write out trees onto tree file?  Yes
215     print CMD "Y\n";
216     close CMD;
217
218     # And then we run the program.
219     ### HACKY HACKY
220     my $PHYLIP_PATH = '/Users/tla/Projects/phylip-3.69/exe';
221     my $program = "pars";
222     if( $^O eq 'darwin' ) {
223         $program = "$PHYLIP_PATH/$program.app/Contents/MacOS/$program";
224     } else {
225         $program = "$PHYLIP_PATH/$program";
226     }
227
228     {
229         # We need to run it in our temporary directory where we have created
230         # all the expected files.
231         local $CWD = $phylip_dir;
232         my @cmd = ( $program );
233         run \@cmd, '<', 'cmdfile', '>', '/dev/null';
234     }
235     # Now our output should be in 'outfile' and our tree in 'outtree',
236     # both in the temp directory.
237
238     my @outtree;
239     if( -f "$phylip_dir/outtree" ) {
240         open( TREE, "$phylip_dir/outtree" ) or die "Could not open outtree for read";
241         @outtree = <TREE>;
242         close TREE;
243     }
244     return( 1, join( '', @outtree ) ) if @outtree;
245
246     my @error;
247     if( -f "$phylip_dir/outfile" ) {
248         open( OUTPUT, "$phylip_dir/outfile" ) or die "Could not open output for read";
249         @error = <OUTPUT>;
250         close OUTPUT;
251     } else {
252         push( @error, "Neither outtree nor output file was produced!" );
253     }
254     return( undef, join( '', @error ) );
255 }
256
257 sub _parse_newick {
258     my $newick = shift;
259     my @trees;
260     # Parse the result into a tree
261     my $forest = Bio::Phylo::IO->parse( 
262         -format => 'newick',
263         -string => $newick,
264         );
265     # Turn the tree into a graph, starting with the root node
266     foreach my $tree ( @{$forest->get_entities} ) {
267         push( @trees, _graph_from_bio( $tree ) );
268     }
269     return \@trees;
270 }
271
272 sub _graph_from_bio {
273     my $tree = shift;
274     my $graph = Graph->new( 'undirected' => 1 );
275     # Give all the intermediate anonymous nodes a name.
276     my $i = 0;
277     foreach my $n ( @{$tree->get_entities} ) {
278         next if $n->get_name;
279         $n->set_name( $i++ );
280     }
281     my $root = $tree->get_root->get_name;
282     $graph->add_vertex( $root );
283     _add_tree_children( $graph, $root, $tree->get_root->get_children() );
284     return $graph;
285 }
286
287 sub _add_tree_children {
288     my( $graph, $parent, $tree_children ) = @_;
289     foreach my $c ( @$tree_children ) {
290         my $child = $c->get_name;
291         $graph->add_vertex( $child );
292         $graph->add_path( $parent, $child );
293         _add_tree_children( $graph, $child, $c->get_children() );
294     }
295 }
296
297 no Moose;
298 __PACKAGE__->meta->make_immutable;
299     
300 1;