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