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 ) = @_;
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";
24 my $stemma = $tradition->stemma;
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.
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.
34 my ( $total, $genealogical, $conflicts ) = ( 0, 0, 0 );
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'};
43 $max_variants = scalar @$groups if scalar @$groups > $max_variants;
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];
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'}};
60 # Now run the same analysis given the calculated distance tree(s).
61 # my @trees = @{$stemma->distance_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
72 # Record that we used this variant in an analysis
73 push( @$variants, $variant_loc );
75 my $t1 = Benchmark->new();
76 print STDERR "Analysis of graph for " . $tradition->name . " took "
77 . timestr( timediff( $t1, $t0 ) ) . "seconds\n";
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;
86 $data->{'variants'} = $variants;
87 $data->{'variant_count'} = $total;
88 $data->{'conflict_count'} = $conflicts;
89 $data->{'genealogical_count'} = $genealogical;
95 my $variant_groups = [];
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.
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.
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
116 if( $rdg->{'t'}->is_lacuna ) {
117 $rdg_text = undef; # Don't count lacunae
118 push( @$lacunose, $table_wits[$j] );
120 $rdg_text = $rdg->{'t'}->text;
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],
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;
137 push( @$variant_groups,
138 { 'groups' => $groups, 'readings' => $readings, 'lacunose' => $lacunose } );
140 return $variant_groups;
145 # variant_row -> genealogical
146 # -> readings [ { text, group, conflict, missing } ]
148 sub analyze_variant_location {
149 my( $group_readings, $groups, $graph, $lacunose, $undirected ) = @_;
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;
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;
172 $part->delete_vertices(
173 grep { !ref( $contig->{$_} ) && $contig->{$_} ne $gst } $graph->vertices );
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.
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;
210 } # else it is a single-node group, nothing to calculate.
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.
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};
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}};
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}}
244 # Save the relevant subgraph.
245 $subgraph->{$gst} = { 'graph' => $part,
246 'root' => $group_root,
247 'reachable' => $reachable };
249 push( @{$variant_row->{'readings'}}, $reading );
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 ) {
256 foreach ( keys %$contig ) {
257 next unless ref $contig->{$_};
258 if( scalar @{$contig->{$_}} > 1 ) {
259 push( @resolve, $_ );
261 $contig->{$_} = scalar @{$contig->{$_}} ? $contig->{$_}->[0] : '';
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 ) {
284 if( !$still_reachable{$v}
285 && ( $contig->{$v} eq $gst
286 || ( exists $still_contig->{$v}
287 && $still_contig->{$v} eq $gst ) ) ) {
289 if( exists $still_contig->{$h} ) {
291 $conflict->{$group_readings->{$gst}} =
292 $group_readings->{$still_contig->{$h}};
294 $still_contig->{$h} = $gst;
297 } # else we don't need $h in this group.
302 # Now, assuming no conflict, we have some hypothetical vertices in
303 # $still_contig that are the "real" group memberships. Replace these
305 unless ( keys %$conflict ) {
306 foreach my $v ( keys %$contig ) {
307 next unless ref $contig->{$v};
308 $contig->{$v} = $still_contig->{$v};
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->{$_} }
319 $rdg->{'group'} = wit_stringify( \@members );
322 $variant_row->{'genealogical'} = !( keys %$conflict );
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;
336 # Then delete a hypothetical root with only one successor, moving the
338 while( $tree->successors( $root ) == 1 && ref $contighash->{$root} ) {
339 my @nextroot = $tree->successors( $root );
340 $tree->delete_vertex( $root );
341 $root = $nextroot[0];
343 # The tree has been modified in place, but we need to know the new root.
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 ) = @_;
351 if( $wit =~ /^(.*)\Q$acstr\E$/ ) {
353 $skip = grep { $_ =~ /^\Q$real\E$/ } @$arr;
355 push( @$arr, $wit ) unless $skip;
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.
361 my( $readings ) = @_;
362 my $total = keys %$readings;
363 foreach my $var ( keys %$readings ) {
364 $total-- if @{$readings->{$var}} == 1;
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 );
372 return( $groups, $text );
375 # Take an array of witness groupings and produce a string like
376 # ['A','B'] / ['C','D','E'] / ['F']
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 ];
387 foreach my $g ( @$groups ) {
388 push( @gst, '[' . join( ',', map { "'$_'" } @$g ) . ']' );
390 return join( ' / ', @gst );