a little light refactoring
[scpubgit/stemmatology.git] / lib / Text / Tradition / Analysis.pm
1 package Text::Tradition::Analysis;
2
3 use strict;
4 use warnings;
5 use Benchmark;
6 use Exporter 'import';
7 use Text::Tradition;
8 use Text::Tradition::Stemma;
9
10 use vars qw/ @EXPORT_OK /;
11 @EXPORT_OK = qw/ run_analysis group_variants wit_stringify /;
12
13 sub new {
14         my( $class, $args ) = @_;
15         my $self = {};
16         bless( $self, $class ); 
17         $self->{'data'} = [];
18         foreach my $t ( @{$args->{'traditions'}} ) {
19             $self->run_analysis( $t->{'file'}, $t->{'stemmadot'} );
20         }
21         return $self;
22 }
23
24 sub run_analysis {
25         my( $self, $file, $stemmadot ) = @_;
26         # What we will return
27         my $svg;
28         my $variants = [];
29         my $data = {};
30         
31         # Read in the file and stemma   
32         my $tradition = Text::Tradition->new( 
33                 'input'  => 'Self',
34                 'file'   => $file,
35                 'linear' => 1,
36                 );
37         $data->{'title'} = $tradition->name;
38         
39         my $stemma = Text::Tradition::Stemma->new(
40                 'collation' => $tradition->collation,
41                 'dot' => $stemmadot,
42                 );
43         # We will return the stemma picture
44         $svg = $stemma->as_svg( { size => "8,7.5" } );;
45         $data->{'svg'} = $svg;
46         
47         # We have the collation, so get the alignment table with witnesses in rows.
48         # Also return the reading objects in the table, rather than just the words.
49         my $wits = {};
50         map { $wits->{$_} = 1 } $stemma->witnesses;
51         # For each column in the alignment table, we want to see if the existing
52         # groupings of witnesses match our stemma hypothesis. We also need to keep
53         # track of the maximum number of variants at any one location.
54         my $max_variants = 0;
55         my ( $total, $genealogical, $conflicts ) = ( 0, 0, 0 );
56         
57     my $t0 = Benchmark->new();
58     my $variant_groups = group_variants( $tradition->collation, $wits );
59     foreach my $rank ( 0 .. $#{$variant_groups} ) {
60         my $groups = $variant_groups->[$rank]->{'groups'};
61         my $readings = $variant_groups->[$rank]->{'readings'};
62         my $lacunose = $variant_groups->[$rank]->{'lacunose'};
63                 
64                 $max_variants = scalar @$groups if scalar @$groups > $max_variants;
65                 
66                 # We can already look up witnesses for a reading; we also want to look
67                 # up readings for a given witness.
68                 my $group_readings = {};
69                 foreach my $x ( 0 .. $#$groups ) {
70                         $group_readings->{wit_stringify( $groups->[$x] )} = $readings->[$x];
71                 }
72                 
73                 # For all the groups with more than one member, collect the list of all
74                 # contiguous vertices needed to connect them.
75                 my $variant_loc = analyze_variant_location( $group_readings, $groups, 
76                     $stemma->graph, $lacunose );
77                 $variant_loc->{'id'} = $rank;
78                 $genealogical++ if $variant_loc->{'genealogical'};
79                 $conflicts += grep { $_->{'conflict'} } @{$variant_loc->{'readings'}};
80
81                 # Now run the same analysis given the calculated distance tree(s).
82 #               my @trees = @{$stemma->distance_trees};
83 #               if( @trees ) {
84 #             foreach my $tree ( 0 .. $#trees ) {
85 #                 my $dc = analyze_variant_location( $group_readings, $groups, $tree, $lacunose, 'undirected' );
86 #                 foreach my $rdg ( keys %$dc ) {
87 #                     my $var = $dc->{$rdg};
88 #                     # TODO Do something with this
89 #                 }
90 #             }
91 #           }
92
93                 # Record that we used this variant in an analysis
94                 push( @$variants, $variant_loc );
95         }
96     my $t1 = Benchmark->new();
97     print STDERR "Analysis of graph for " . $tradition->name . " took " 
98         . timestr( timediff( $t1, $t0 ) ) . "seconds\n";
99         
100         # Go through our variant locations, after we have seen all of them once,
101         # and add the number of empty columns needed by each.
102         foreach my $row ( @$variants ) {
103                 my $empty = $max_variants - scalar @{$row->{'readings'}};
104                 $row->{'empty'} = $empty;
105         }
106         
107         # Populate self with our analysis data.
108         $data->{'variants'} = $variants;
109         $data->{'variant_count'} = $total;
110         $data->{'conflict_count'} = $conflicts;
111         $data->{'genealogical_count'} = $genealogical;
112         push( @{$self->{'data'}}, $data );
113 }
114
115 sub group_variants {
116         my( $c, $wits ) = @_;
117         my $variant_groups = [];
118         
119         # We have the collation, so get the alignment table with witnesses in rows.
120         # Also return the reading objects in the table, rather than just the words.
121         my $all_wits_table = $c->make_alignment_table( 'refs', $wits );
122         # Strip the list of sigla and save it for correlation to the readings.
123         my $col_wits = shift @$all_wits_table;
124         # Any witness in the stemma that has no row should be noted.
125     foreach ( @$col_wits ) {
126         $wits->{$_}++; # Witnesses present in table and stemma now have value 2.
127     }
128     my @not_collated = grep { $wits->{$_} == 1 } keys %$wits;
129         foreach my $i ( 0 .. $#$all_wits_table ) {
130                 # For each column in the table, group the readings by witness.
131                 my $rdg_wits = {};
132                 my $col_rdgs = shift @$all_wits_table;
133                 my $lacunose = [ @not_collated ];
134                 foreach my $j ( 0 .. $#{$col_rdgs} ) {
135                         my $rdg = $col_rdgs->[$j];
136                         my $rdg_text = '(omitted)';  # Initialize in case of empty reading
137                         if( $rdg ) {
138                             if( $rdg->is_lacuna ) {
139                                 $rdg_text = undef;   # Don't count lacunae
140                                 push( @$lacunose, $col_wits->[$j] );
141                             } else {
142                                 $rdg_text = $rdg->text; 
143                                 }
144                         }
145                         if( defined $rdg_text ) {
146                                 # Initialize the witness array if we haven't got one yet
147                                 $rdg_wits->{$rdg_text} = [] unless $rdg_wits->{$rdg_text};
148                                 # Add the relevant witness, subject to a.c. logic
149                                 add_variant_wit( $rdg_wits->{$rdg_text}, $col_wits->[$j],
150                                         $c->ac_label );
151                         }
152                 }
153                 
154                 # See if this column has any potentially genealogical variants.
155                 # If not, skip to the next.
156                 my( $groups, $readings ) = useful_variant( $rdg_wits );
157                 next unless $groups && $readings;  
158
159                 push( @$variant_groups, 
160                     { 'groups' => $groups, 'readings' => $readings, 'lacunose' => $lacunose } );
161         }
162         return $variant_groups;
163 }
164
165
166
167 # variant_row -> genealogical
168 #             -> readings [ { text, group, conflict, missing } ]
169
170 sub analyze_variant_location {
171     my( $group_readings, $groups, $graph, $lacunose, $undirected ) = @_;
172     my $contig = {};
173     my $subgraph = {};
174     my $is_conflicted;
175     my $conflict = {};
176     my $missing = {};
177     map { $missing->{$_} = 1 } @$lacunose;
178     my $variant_row = { 'readings' => [] };
179     # Mark each ms as in its own group, first.
180     foreach my $g ( @$groups ) {
181         my $gst = wit_stringify( $g );
182         map { $contig->{$_} = $gst } @$g;
183     }
184     # Now for each unmarked node in the graph, initialize an array
185     # for possible group memberships.  We will use this later to
186     # resolve potential conflicts.
187     map { $contig->{$_} = [] unless $contig->{$_} } $graph->vertices;
188     foreach my $g ( sort { scalar @$b <=> scalar @$a } @$groups ) {
189         my $gst = wit_stringify( $g );  # This is the group name
190         my $reachable = { $g->[0] => 1 };
191         # Copy the graph, and delete all non-members from the new graph.
192         my $part = $graph->copy;
193         my $group_root;
194         $part->delete_vertices( 
195             grep { !ref( $contig->{$_} ) && $contig->{$_} ne $gst } $graph->vertices );
196                 
197         # Now look to see if our group is connected.
198         if( $undirected ) { # For use with distance trees etc.
199             # Find all vertices reachable from the first (arbitrary) group
200             # member.  If we are genealogical this should include them all. 
201             map { $reachable->{$_} = 1 } $part->all_reachable( $g->[0] );
202             # TODO This is a terrible way to do distance trees, since all
203             # non-leaf nodes are included in every graph part now. We may
204             # have to go back to SPDP.
205         } else {
206             if( @$g > 1 ) {
207                 # Dispense with the trivial case of one reading.
208                 # We have to take directionality into account.
209                 # How many root nodes do we have?
210                 my @roots = grep { ref( $contig->{$_} ) || $contig->{$_} eq $gst } 
211                     $part->source_vertices;
212                 # Assuming that @$g > 1, find the first root node that has at
213                 # least one successor belonging to our group. If this reading
214                 # is genealogical, there should be only one, but we will check
215                 # that implicitly later.
216                 my $nodes_in_subtree = 0;
217                 foreach my $root ( @roots ) {
218                     # Prune the tree to get rid of extraneous hypotheticals.
219                     $root = prune_subtree( $part, $root, $contig );
220                     # Get all the successor nodes of our root.
221                     my $tmp_reach = { $root => 1 };
222                     map { $tmp_reach->{$_} = 1 } $part->all_successors( $root );
223                     # Skip this root if none of our successors are in our group
224                     # (e.g. isolated 'hypothetical' witnesses with no group)
225                     next unless grep { $contig->{$_} } keys %$tmp_reach;
226                     if( keys %$tmp_reach > $nodes_in_subtree ) {
227                         $nodes_in_subtree = keys %$tmp_reach;
228                         $reachable = $tmp_reach;
229                         $group_root = $root;
230                     }
231                 }
232             } # else it is a single-node group, nothing to calculate.
233         }
234         
235         # None of the 'reachable' nodes should be marked as being in another 
236         # group.  Paint the 'hypotheticals' with our group while we are at it,
237         # unless there is a conflict present.
238         foreach ( keys %$reachable ) {
239             if( ref $contig->{$_} ) {
240                 push( @{$contig->{$_}}, $gst );
241             } elsif( $contig->{$_} ne $gst ) {
242                 $conflict->{$group_readings->{$gst}} = $group_readings->{$contig->{$_}};
243             } # else it is an 'extant' node marked with our group already.
244         }
245         # None of the unreachable nodes should be in our group either.
246         foreach ( $part->vertices ) {
247             next if $reachable->{$_};
248             if( $contig->{$_} eq $gst ) {
249                 $conflict->{$group_readings->{$gst}} = $group_readings->{$gst};
250                 last;
251             }
252         }
253         
254         # Now, if we have a conflict, we can write the reading in full.  If not, 
255         # we have to save the subgraph so that we can resolve possible conflicts 
256         # on hypothetical nodes.
257         $is_conflicted = 1 if exists $conflict->{$group_readings->{$gst}};
258         
259         # Write the reading.
260         my $reading = { 'text' => $group_readings->{$gst},
261                         'missing' => wit_stringify( $lacunose ),
262                         'group' => $gst };  # This will change if we find no conflict
263         if( $is_conflicted ) {
264             $reading->{'conflict'} = $conflict->{$group_readings->{$gst}}
265         } else {
266             # Save the relevant subgraph.
267             $subgraph->{$gst} = { 'graph' => $part,
268                                 'root' => $group_root,
269                                 'reachable' => $reachable };
270         }
271         push( @{$variant_row->{'readings'}}, $reading );
272     }
273     
274     # Now that we have gone through all the rows, check the hypothetical
275     # readings for conflict if we haven't found one yet.
276     if( keys %$subgraph && !keys %$conflict ) {
277         my @resolve;
278         foreach ( keys %$contig ) {
279             next unless ref $contig->{$_};
280             if( scalar @{$contig->{$_}} > 1 ) {
281                 push( @resolve, $_ );
282             } else {
283                 $contig->{$_} = scalar @{$contig->{$_}} ? $contig->{$_}->[0] : '';
284             }
285         }
286         # Do we still have a possible conflict?
287         my $still_contig = {};
288         foreach my $h ( @resolve ) {
289             # For each of the hypothetical readings with more than one possibility,
290             # try deleting it from each of its member subgraphs in turn, and see
291             # if that breaks the contiguous grouping.
292             # TODO This can still break in a corner case where group A can use 
293             # either vertex 1 or 2, and group B can use either vertex 2 or 1.
294             # Revisit this if necessary; it could get brute-force nasty.
295             foreach my $gst ( @{$contig->{$h}} ) {
296                 my $gpart = $subgraph->{$gst}->{'graph'}->copy;
297                 my $reachable = $subgraph->{$gst}->{'reachable'};
298                 $gpart->delete_vertex( $h );
299                 # Is everything else still reachable from the root?
300                 # TODO If $h was the root, see if we still have a single root.
301                 my %still_reachable = ( $subgraph->{$gst}->{'root'} => 1 );
302                 map { $still_reachable{$_} = 1 }
303                     $gpart->all_successors( $subgraph->{$gst}->{'root'} );
304                 foreach my $v ( keys %$reachable ) {
305                     next if $v eq $h;
306                     if( !$still_reachable{$v}
307                         && ( $contig->{$v} eq $gst 
308                              || ( exists $still_contig->{$v} 
309                                   && $still_contig->{$v} eq $gst ) ) ) {
310                         # We need $h.
311                         if( exists $still_contig->{$h} ) {
312                             # Conflict!
313                             $conflict->{$group_readings->{$gst}} = 
314                                 $group_readings->{$still_contig->{$h}};
315                         } else {
316                             $still_contig->{$h} = $gst;
317                         }
318                         last;
319                     } # else we don't need $h in this group.
320                 }
321             }
322         }
323         
324         # Now, assuming no conflict, we have some hypothetical vertices in
325         # $still_contig that are the "real" group memberships.  Replace these
326         # in $contig.
327         unless ( keys %$conflict ) {
328             foreach my $v ( keys %$contig ) {
329                 next unless ref $contig->{$v};
330                 $contig->{$v} = $still_contig->{$v};
331             }
332         }
333     }
334             
335     # Now write the group and conflict information into the respective rows.
336     foreach my $rdg ( @{$variant_row->{'readings'}} ) {
337         $rdg->{'conflict'} = $conflict->{$rdg->{'text'}};
338         next if $rdg->{'conflict'};
339         my @members = grep { $contig->{$_} eq $rdg->{'group'} && !$missing->{$_} } 
340             keys %$contig;
341         $rdg->{'group'} = wit_stringify( \@members );
342     }
343     
344     $variant_row->{'genealogical'} = !( keys %$conflict );
345     return $variant_row;
346 }
347
348 sub prune_subtree {
349     my( $tree, $root, $contighash ) = @_;
350     # First, delete hypothetical leaves / orphans until there are none left.
351     my @orphan_hypotheticals = grep { ref( $contighash->{$_} ) } 
352         $tree->successorless_vertices;
353     while( @orphan_hypotheticals ) {
354         $tree->delete_vertices( @orphan_hypotheticals );
355         @orphan_hypotheticals = grep { ref( $contighash->{$_} ) } 
356             $tree->successorless_vertices;
357     }
358     # Then delete a hypothetical root with only one successor, moving the
359     # root to the child.
360     while( $tree->successors( $root ) == 1 && ref $contighash->{$root} ) {
361         my @nextroot = $tree->successors( $root );
362         $tree->delete_vertex( $root );
363         $root = $nextroot[0];
364     }
365     # The tree has been modified in place, but we need to know the new root.
366     return $root;
367 }
368 # Add the variant, subject to a.c. representation logic.
369 # This assumes that we will see the 'main' version before the a.c. version.
370 sub add_variant_wit {
371     my( $arr, $wit, $acstr ) = @_;
372     my $skip;
373     if( $wit =~ /^(.*)\Q$acstr\E$/ ) {
374         my $real = $1;
375         $skip = grep { $_ =~ /^\Q$real\E$/ } @$arr;
376     } 
377     push( @$arr, $wit ) unless $skip;
378 }
379
380 # Return an answer if the variant is useful, i.e. if there are at least 2 variants
381 # with at least 2 witnesses each.
382 sub useful_variant {
383     my( $readings ) = @_;
384     my $total = keys %$readings;
385     foreach my $var ( keys %$readings ) {
386         $total-- if @{$readings->{$var}} == 1;
387     }
388     return( undef, undef ) if $total <= 1;
389     my( $groups, $text );
390     foreach my $var ( keys %$readings ) {
391         push( @$groups, $readings->{$var} );
392         push( @$text, $var );
393     }
394     return( $groups, $text );
395 }
396
397 # Take an array of witness groupings and produce a string like
398 # ['A','B'] / ['C','D','E'] / ['F']
399
400 sub wit_stringify {
401     my $groups = shift;
402     my @gst;
403     # If we were passed an array of witnesses instead of an array of 
404     # groupings, then "group" the witnesses first.
405     unless( ref( $groups->[0] ) ) {
406         my $mkgrp = [ $groups ];
407         $groups = $mkgrp;
408     }
409     foreach my $g ( @$groups ) {
410         push( @gst, '[' . join( ',', map { "'$_'" } @$g ) . ']' );
411     }
412     return join( ' / ', @gst );
413 }
414     
415 1;