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