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