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