move more procedural stuff out of Stemma.pm into StemmaUtil
[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::Temp;
e05997e2 6use Graph;
7use Graph::Reader::Dot;
e79c23c7 8use IPC::Run qw/ run binary /;
b02332ca 9use Text::Tradition::StemmaUtil qw/ character_input phylip_pars parse_newick /;
40f19742 10use Moose;
9463b0bf 11
12has collation => (
13 is => 'ro',
14 isa => 'Text::Tradition::Collation',
15 required => 1,
8d9a1cd8 16 weak_ref => 1,
9463b0bf 17 );
18
e05997e2 19has graph => (
20 is => 'rw',
21 isa => 'Graph',
22 predicate => 'has_graph',
23 );
24
40f19742 25has distance_trees => (
26 is => 'ro',
27 isa => 'ArrayRef[Graph]',
28 writer => '_save_distance_trees',
29 predicate => 'has_distance_trees',
30 );
c0ccdb62 31
0f5d05c6 32has distance_program => (
33 is => 'rw',
34 isa => 'Str',
35 default => '',
36 );
37
e05997e2 38sub BUILD {
39 my( $self, $args ) = @_;
40 # If we have been handed a dotfile, initialize it into a graph.
41 if( exists $args->{'dot'} ) {
8d9a1cd8 42 $self->graph_from_dot( $args->{'dot'} );
e05997e2 43 }
c0ccdb62 44}
45
8d9a1cd8 46sub graph_from_dot {
47 my( $self, $dotfh ) = @_;
48 # Assume utf-8
49 binmode( $dotfh, ':utf8' );
50 my $reader = Graph::Reader::Dot->new();
51 my $graph = $reader->read_graph( $dotfh );
7a7c249c 52 if( $graph ) {
53 $self->graph( $graph );
54 # Go through the nodes and set any non-hypothetical node to extant.
55 foreach my $v ( $self->graph->vertices ) {
56 $self->graph->set_vertex_attribute( $v, 'class', 'extant' )
57 unless $self->graph->has_vertex_attribute( $v, 'class' );
58 }
59 } else {
60 warn "Failed to parse dot in $dotfh";
61 }
8d9a1cd8 62}
63
64sub as_dot {
e367f5c0 65 my( $self, $opts ) = @_;
7a7c249c 66
67 # Get default and specified options
68 my %graphopts = ();
69 my %nodeopts = (
70 'fontsize' => 11,
71 'hshape' => 'plaintext', # Shape for the hypothetical nodes
72 'htext' => '*',
73 'style' => 'filled',
74 'fillcolor' => 'white',
75 'shape' => 'ellipse', # Shape for the extant nodes
76 );
77 my %edgeopts = (
78 'arrowhead' => 'open',
79 );
80 @graphopts{ keys %{$opts->{'graph'}} } = values %{$opts->{'graph'}}
81 if $opts->{'graph'};
82 @nodeopts{ keys %{$opts->{'node'}} } = values %{$opts->{'node'}}
83 if $opts->{'node'};
84 @edgeopts{ keys %{$opts->{'edge'}} } = values %{$opts->{'edge'}}
85 if $opts->{'edge'};
86
87 my @dotlines;
88 push( @dotlines, 'digraph stemma {' );
89 ## Print out the global attributes
90 push( @dotlines, _make_dotline( 'graph', %graphopts ) ) if keys %graphopts;
91 push( @dotlines, _make_dotline( 'edge', %edgeopts ) ) if keys %edgeopts;
92 ## Delete our special attributes from the node set before continuing
93 my $hshape = delete $nodeopts{'hshape'};
94 my $htext = delete $nodeopts{'htext'};
95 push( @dotlines, _make_dotline( 'node', %nodeopts ) ) if keys %nodeopts;
96
97 # Add each of the nodes.
98 foreach my $n ( $self->graph->vertices ) {
99 if( $self->graph->get_vertex_attribute( $n, 'class' ) eq 'hypothetical' ) {
100 # Apply our display settings for hypothetical nodes.
101 push( @dotlines, _make_dotline( $n, 'shape' => $hshape, 'label' => $htext ) );
e79c23c7 102 } else {
7a7c249c 103 # Use the default display settings.
104 push( @dotlines, " $n;" );
e79c23c7 105 }
106 }
7a7c249c 107 # Add each of our edges.
108 foreach my $e ( $self->graph->edges ) {
109 my( $from, $to ) = @$e;
110 push( @dotlines, " $from -> $to;" );
111 }
112 push( @dotlines, '}' );
e79c23c7 113
7a7c249c 114 return join( "\n", @dotlines );
115}
116
117
118# Another version of dot output meant for graph editing, thus
119# much simpler.
120sub editable {
121 my $self = shift;
122 my @dotlines;
123 push( @dotlines, 'digraph stemma {' );
124 my @real; # A cheap sort
125 foreach my $n ( sort $self->graph->vertices ) {
126 my $c = $self->graph->get_vertex_attribute( $n, 'class' );
127 $c = 'extant' unless $c;
128 if( $c eq 'extant' ) {
129 push( @real, $n );
130 } else {
131 push( @dotlines, _make_dotline( $n, 'class' => $c ) );
132 }
e367f5c0 133 }
7a7c249c 134 # Now do the real ones
135 foreach my $n ( @real ) {
136 push( @dotlines, _make_dotline( $n, 'class' => 'extant' ) );
137 }
138 foreach my $e ( sort _by_vertex $self->graph->edges ) {
139 my( $from, $to ) = @$e;
140 push( @dotlines, " $from -> $to;" );
141 }
142 push( @dotlines, '}' );
143 return join( "\n", @dotlines );
144}
145
146sub _make_dotline {
147 my( $obj, %attr ) = @_;
148 my @pairs;
149 foreach my $k ( keys %attr ) {
150 my $v = $attr{$k};
151 $v =~ s/\"/\\\"/g;
152 push( @pairs, "$k=\"$v\"" );
153 }
154 return sprintf( " %s [ %s ];", $obj, join( ', ', @pairs ) );
8d9a1cd8 155}
156
7a7c249c 157sub _by_vertex {
158 return $a->[0].$a->[1] cmp $b->[0].$b->[1];
159}
8d9a1cd8 160
161# Render the stemma as SVG.
162sub as_svg {
163 my( $self, $opts ) = @_;
164 my $dot = $self->as_dot( $opts );
e79c23c7 165 my @cmd = qw/dot -Tsvg/;
166 my( $svg, $err );
167 my $dotfile = File::Temp->new();
168 ## TODO REMOVE
169 # $dotfile->unlink_on_destroy(0);
170 binmode $dotfile, ':utf8';
8d9a1cd8 171 print $dotfile $dot;
e79c23c7 172 push( @cmd, $dotfile->filename );
173 run( \@cmd, ">", binary(), \$svg );
174 $svg = decode_utf8( $svg );
175 return $svg;
176}
177
08e0fb85 178sub witnesses {
179 my $self = shift;
180 my @wits = grep { $self->graph->get_vertex_attribute( $_, 'class' ) eq 'extant' }
181 $self->graph->vertices;
182 return @wits;
183}
184
e79c23c7 185#### Methods for calculating phylogenetic trees ####
186
40f19742 187before 'distance_trees' => sub {
188 my $self = shift;
0f5d05c6 189 my %args = (
190 'program' => 'phylip_pars',
191 @_ );
40f19742 192 # TODO allow specification of method for calculating distance tree
0f5d05c6 193 if( !$self->has_distance_trees
194 || $args{'program'} ne $self->distance_program ) {
40f19742 195 # We need to make a tree before we can return it.
0f5d05c6 196 my $dsub = 'run_' . $args{'program'};
197 my( $ok, $result ) = $self->$dsub();
40f19742 198 if( $ok ) {
c0ccdb62 199 # Save the resulting trees
b02332ca 200 my $trees = parse_newick( $result );
c0ccdb62 201 $self->_save_distance_trees( $trees );
0f5d05c6 202 $self->distance_program( $args{'program'} );
40f19742 203 } else {
c0ccdb62 204 warn "Failed to calculate distance trees: $result";
40f19742 205 }
206 }
207};
f6066bac 208
40f19742 209sub run_phylip_pars {
b02332ca 210 my $self = shift;
211 my $cdata = character_input( $self->collation->make_alignment_table() );
212 return phylip_pars( $cdata );
40f19742 213}
214
9463b0bf 215no Moose;
216__PACKAGE__->meta->make_immutable;
217
2181;