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