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