move more procedural stuff out of Stemma.pm into StemmaUtil
[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::StemmaUtil qw/ character_input phylip_pars parse_newick /;
10 use Moose;
11
12 has collation => (
13     is => 'ro',
14     isa => 'Text::Tradition::Collation',
15     required => 1,
16     weak_ref => 1,
17     );  
18
19 has graph => (
20     is => 'rw',
21     isa => 'Graph',
22     predicate => 'has_graph',
23     );
24     
25 has distance_trees => (
26     is => 'ro',
27     isa => 'ArrayRef[Graph]',
28     writer => '_save_distance_trees',
29     predicate => 'has_distance_trees',
30     );
31     
32 has distance_program => (
33         is => 'rw',
34         isa => 'Str',
35         default => '',
36         );
37     
38 sub BUILD {
39     my( $self, $args ) = @_;
40     # If we have been handed a dotfile, initialize it into a graph.
41     if( exists $args->{'dot'} ) {
42         $self->graph_from_dot( $args->{'dot'} );
43     }
44 }
45
46 sub 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 );
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         }
62 }
63
64 sub as_dot {
65     my( $self, $opts ) = @_;
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 ) );
102         } else {
103                 # Use the default display settings.
104             push( @dotlines, "  $n;" );
105         }
106     }
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, '}' );
113     
114     return join( "\n", @dotlines );
115 }
116
117
118 # Another version of dot output meant for graph editing, thus
119 # much simpler.
120 sub 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                 }
133     }
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
146 sub _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 ) );
155 }
156         
157 sub _by_vertex {
158         return $a->[0].$a->[1] cmp $b->[0].$b->[1];
159 }
160
161 # Render the stemma as SVG.
162 sub as_svg {
163     my( $self, $opts ) = @_;
164     my $dot = $self->as_dot( $opts );
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';
171     print $dotfile $dot;
172     push( @cmd, $dotfile->filename );
173     run( \@cmd, ">", binary(), \$svg );
174     $svg = decode_utf8( $svg );
175     return $svg;
176 }
177
178 sub 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
185 #### Methods for calculating phylogenetic trees ####
186
187 before 'distance_trees' => sub {
188     my $self = shift;
189     my %args = (
190         'program' => 'phylip_pars',
191         @_ );
192     # TODO allow specification of method for calculating distance tree
193     if( !$self->has_distance_trees
194         || $args{'program'} ne $self->distance_program ) {
195         # We need to make a tree before we can return it.
196         my $dsub = 'run_' . $args{'program'};
197         my( $ok, $result ) = $self->$dsub();
198         if( $ok ) {
199             # Save the resulting trees
200             my $trees = parse_newick( $result );
201             $self->_save_distance_trees( $trees );
202             $self->distance_program( $args{'program'} );
203         } else {
204             warn "Failed to calculate distance trees: $result";
205         }
206     }
207 };
208
209 sub run_phylip_pars {
210         my $self = shift;
211         my $cdata = character_input( $self->collation->make_alignment_table() );
212         return phylip_pars( $cdata );
213 }
214
215 no Moose;
216 __PACKAGE__->meta->make_immutable;
217     
218 1;