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