1 package Text::Tradition::Analysis;
7 use Text::Tradition::Stemma;
9 use vars qw/ @EXPORT_OK /;
10 @EXPORT_OK = qw/ run_analysis group_variants wit_stringify /;
13 my( $class, $args ) = @_;
15 bless( $self, $class );
17 foreach my $t ( @{$args->{'traditions'}} ) {
18 $self->run_analysis( $t->{'file'}, $t->{'stemmadot'} );
24 my( $self, $file, $stemmadot ) = @_;
30 # Read in the file and stemma
31 my $tradition = Text::Tradition->new(
36 $data->{'title'} = $tradition->name;
38 my $stemma = Text::Tradition::Stemma->new(
39 'collation' => $tradition->collation,
42 # We will return the stemma picture
43 $svg = $stemma->as_svg( { size => "8,7.5" } );;
44 $data->{'svg'} = $svg;
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.
49 map { $wits->{$_} = 1 } $stemma->witnesses;
50 my $all_wits_table = $tradition->collation->make_alignment_table( 'refs', $wits );
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.
56 my ( $total, $genealogical, $conflicts ) = ( 0, 0, 0 );
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.
64 my @not_collated = grep { $wits->{$_} == 1 } keys %$wits;
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.
71 my $col_rdgs = shift @$all_wits_table;
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
78 if( $rdg->is_lacuna ) {
79 $rdg_text = undef; # Don't count lacunae
80 push( @$lacunose, $col_wits->[$j] );
82 $rdg_text = $rdg->text;
83 # Get the rank from any real reading; they should be identical.
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 );
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;
102 # Keep track of our widest row
103 $html_columns = scalar @$groups if scalar @$groups > $html_columns;
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];
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'}};
120 # Now run the same analysis given the calculated distance tree(s).
121 # my @trees = @{$stemma->distance_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
132 # Record that we used this variant in an analysis
133 push( @$variants, $variant_row );
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;
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 );
152 my( $c, $wits ) = @_;
153 my $variant_groups = [];
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.
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.
166 my $col_rdgs = shift @$all_wits_table;
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
173 if( $rdg->is_lacuna ) {
174 $rdg_text = undef; # Don't count lacunae
175 push( @$lacunose, $col_wits->[$j] );
177 $rdg_text = $rdg->text;
178 # Get the rank from any real reading; they should be identical.
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],
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;
196 push( @$variant_groups, $groups );
198 return $variant_groups;
201 # variant_row -> genealogical
202 # -> readings [ { text, group, conflict, missing } ]
204 sub analyze_variant_location {
205 my( $group_readings, $groups, $graph, $lacunose, $undirected ) = @_;
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;
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;
228 $part->delete_vertices(
229 grep { !ref( $contig->{$_} ) && $contig->{$_} ne $gst } $graph->vertices );
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.
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;
266 } # else it is a single-node group, nothing to calculate.
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.
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};
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}};
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}}
300 # Save the relevant subgraph.
301 $subgraph->{$gst} = { 'graph' => $part,
302 'root' => $group_root,
303 'reachable' => $reachable };
305 push( @{$variant_row->{'readings'}}, $reading );
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 ) {
312 foreach ( keys %$contig ) {
313 next unless ref $contig->{$_};
314 if( scalar @{$contig->{$_}} > 1 ) {
315 push( @resolve, $_ );
317 $contig->{$_} = scalar @{$contig->{$_}} ? $contig->{$_}->[0] : '';
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 ) {
340 if( !$still_reachable{$v}
341 && ( $contig->{$v} eq $gst
342 || ( exists $still_contig->{$v}
343 && $still_contig->{$v} eq $gst ) ) ) {
345 if( exists $still_contig->{$h} ) {
347 $conflict->{$group_readings->{$gst}} =
348 $group_readings->{$still_contig->{$h}};
350 $still_contig->{$h} = $gst;
353 } # else we don't need $h in this group.
358 # Now, assuming no conflict, we have some hypothetical vertices in
359 # $still_contig that are the "real" group memberships. Replace these
361 unless ( keys %$conflict ) {
362 foreach my $v ( keys %$contig ) {
363 next unless ref $contig->{$v};
364 $contig->{$v} = $still_contig->{$v};
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->{$_} }
375 $rdg->{'group'} = wit_stringify( \@members );
378 $variant_row->{'genealogical'} = !( keys %$conflict );
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;
392 # Then delete a hypothetical root with only one successor, moving the
394 while( $tree->successors( $root ) == 1 && ref $contighash->{$root} ) {
395 my @nextroot = $tree->successors( $root );
396 $tree->delete_vertex( $root );
397 $root = $nextroot[0];
399 # The tree has been modified in place, but we need to know the new root.
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 ) = @_;
407 if( $wit =~ /^(.*)\Q$acstr\E$/ ) {
409 $skip = grep { $_ =~ /^\Q$real\E$/ } @$arr;
411 push( @$arr, $wit ) unless $skip;
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.
417 my( $readings ) = @_;
418 my $total = keys %$readings;
419 foreach my $var ( keys %$readings ) {
420 $total-- if @{$readings->{$var}} == 1;
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 );
428 return( $groups, $text );
431 # Take an array of witness groupings and produce a string like
432 # ['A','B'] / ['C','D','E'] / ['F']
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 ];
443 foreach my $g ( @$groups ) {
444 push( @gst, '[' . join( ',', map { "'$_'" } @$g ) . ']' );
446 return join( ' / ', @gst );