simplify Directory and add exceptions;
[scpubgit/stemmatology.git] / lib / Text / Tradition / Analysis.pm
CommitLineData
d71100ed 1package Text::Tradition::Analysis;
2
3use strict;
4use warnings;
e4386ba9 5use Benchmark;
d1348d38 6use Exporter 'import';
d71100ed 7use Text::Tradition;
8use Text::Tradition::Stemma;
9
d1348d38 10use vars qw/ @EXPORT_OK /;
11@EXPORT_OK = qw/ run_analysis group_variants wit_stringify /;
12
d71100ed 13sub run_analysis {
56cf65bd 14 my( $tradition ) = @_;
d71100ed 15 # What we will return
d71100ed 16 my $variants = [];
e367f5c0 17 my $data = {};
56cf65bd 18
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";
22 return undef;
23 }
24 my $stemma = $tradition->stemma;
3837c155 25
d71100ed 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.
08e0fb85 28 my $wits = {};
29 map { $wits->{$_} = 1 } $stemma->witnesses;
d71100ed 30 # For each column in the alignment table, we want to see if the existing
f6c8ea08 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.
33 my $max_variants = 0;
732152b1 34 my ( $total, $genealogical, $conflicts ) = ( 0, 0, 0 );
d71100ed 35
e4386ba9 36 my $t0 = Benchmark->new();
f6c8ea08 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'};
d71100ed 42
f6c8ea08 43 $max_variants = scalar @$groups if scalar @$groups > $max_variants;
d71100ed 44
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];
50 }
51
52 # For all the groups with more than one member, collect the list of all
53 # contiguous vertices needed to connect them.
f6c8ea08 54 my $variant_loc = analyze_variant_location( $group_readings, $groups,
08e0fb85 55 $stemma->graph, $lacunose );
f6c8ea08 56 $variant_loc->{'id'} = $rank;
57 $genealogical++ if $variant_loc->{'genealogical'};
58 $conflicts += grep { $_->{'conflict'} } @{$variant_loc->{'readings'}};
732152b1 59
d71100ed 60 # Now run the same analysis given the calculated distance tree(s).
732152b1 61# my @trees = @{$stemma->distance_trees};
62# if( @trees ) {
63# foreach my $tree ( 0 .. $#trees ) {
c4a4fb1b 64# my $dc = analyze_variant_location( $group_readings, $groups, $tree, $lacunose, 'undirected' );
732152b1 65# foreach my $rdg ( keys %$dc ) {
66# my $var = $dc->{$rdg};
67# # TODO Do something with this
68# }
69# }
70# }
71
d71100ed 72 # Record that we used this variant in an analysis
f6c8ea08 73 push( @$variants, $variant_loc );
d71100ed 74 }
e4386ba9 75 my $t1 = Benchmark->new();
76 print STDERR "Analysis of graph for " . $tradition->name . " took "
77 . timestr( timediff( $t1, $t0 ) ) . "seconds\n";
d71100ed 78
f6c8ea08 79 # Go through our variant locations, after we have seen all of them once,
732152b1 80 # and add the number of empty columns needed by each.
d71100ed 81 foreach my $row ( @$variants ) {
f6c8ea08 82 my $empty = $max_variants - scalar @{$row->{'readings'}};
d71100ed 83 $row->{'empty'} = $empty;
84 }
85
e367f5c0 86 $data->{'variants'} = $variants;
87 $data->{'variant_count'} = $total;
88 $data->{'conflict_count'} = $conflicts;
89 $data->{'genealogical_count'} = $genealogical;
3837c155 90 return $data;
d71100ed 91}
92
d1348d38 93sub group_variants {
94 my( $c, $wits ) = @_;
95 my $variant_groups = [];
96
f6c8ea08 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.
d1348d38 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.
b5c47c25 101 my @table_wits = map { $_->{'witness'} } @{$all_wits_table->{'alignment'}};
d1348d38 102 # Any witness in the stemma that has no row should be noted.
b5c47c25 103 foreach ( @table_wits ) {
d1348d38 104 $wits->{$_}++; # Witnesses present in table and stemma now have value 2.
105 }
f6c8ea08 106 my @not_collated = grep { $wits->{$_} == 1 } keys %$wits;
b5c47c25 107 foreach my $i ( 0 .. $all_wits_table->{'length'} - 1 ) {
d1348d38 108 # For each column in the table, group the readings by witness.
109 my $rdg_wits = {};
b5c47c25 110 my @col_rdgs = map { $_->{tokens}->[$i] } @{$all_wits_table->{'alignment'}};
d1348d38 111 my $lacunose = [ @not_collated ];
b5c47c25 112 foreach my $j ( 0 .. $#col_rdgs ) {
113 my $rdg = $col_rdgs[$j];
d1348d38 114 my $rdg_text = '(omitted)'; # Initialize in case of empty reading
115 if( $rdg ) {
b5c47c25 116 if( $rdg->{'t'}->is_lacuna ) {
d1348d38 117 $rdg_text = undef; # Don't count lacunae
b5c47c25 118 push( @$lacunose, $table_wits[$j] );
d1348d38 119 } else {
b5c47c25 120 $rdg_text = $rdg->{'t'}->text;
d1348d38 121 }
122 }
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
b5c47c25 127 add_variant_wit( $rdg_wits->{$rdg_text}, $table_wits[$j],
d1348d38 128 $c->ac_label );
129 }
130 }
131
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;
136
f6c8ea08 137 push( @$variant_groups,
138 { 'groups' => $groups, 'readings' => $readings, 'lacunose' => $lacunose } );
d1348d38 139 }
140 return $variant_groups;
141}
142
f6c8ea08 143
144
732152b1 145# variant_row -> genealogical
146# -> readings [ { text, group, conflict, missing } ]
147
d71100ed 148sub analyze_variant_location {
c4a4fb1b 149 my( $group_readings, $groups, $graph, $lacunose, $undirected ) = @_;
231d71fc 150 my $contig = {};
151 my $subgraph = {};
c4a4fb1b 152 my $is_conflicted;
d71100ed 153 my $conflict = {};
231d71fc 154 my $missing = {};
155 map { $missing->{$_} = 1 } @$lacunose;
732152b1 156 my $variant_row = { 'readings' => [] };
94a077d6 157 # Mark each ms as in its own group, first.
158 foreach my $g ( @$groups ) {
159 my $gst = wit_stringify( $g );
231d71fc 160 map { $contig->{$_} = $gst } @$g;
94a077d6 161 }
c4a4fb1b 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.
231d71fc 165 map { $contig->{$_} = [] unless $contig->{$_} } $graph->vertices;
d71100ed 166 foreach my $g ( sort { scalar @$b <=> scalar @$a } @$groups ) {
c4a4fb1b 167 my $gst = wit_stringify( $g ); # This is the group name
168 my $reachable = { $g->[0] => 1 };
08e0fb85 169 # Copy the graph, and delete all non-members from the new graph.
c4a4fb1b 170 my $part = $graph->copy;
171 my $group_root;
172 $part->delete_vertices(
231d71fc 173 grep { !ref( $contig->{$_} ) && $contig->{$_} ne $gst } $graph->vertices );
c4a4fb1b 174
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.
183 } else {
184 if( @$g > 1 ) {
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?
231d71fc 188 my @roots = grep { ref( $contig->{$_} ) || $contig->{$_} eq $gst }
c4a4fb1b 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 ) {
231d71fc 196 # Prune the tree to get rid of extraneous hypotheticals.
197 $root = prune_subtree( $part, $root, $contig );
c4a4fb1b 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)
231d71fc 203 next unless grep { $contig->{$_} } keys %$tmp_reach;
c4a4fb1b 204 if( keys %$tmp_reach > $nodes_in_subtree ) {
205 $nodes_in_subtree = keys %$tmp_reach;
206 $reachable = $tmp_reach;
207 $group_root = $root;
208 }
209 }
210 } # else it is a single-node group, nothing to calculate.
211 }
212
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 ) {
231d71fc 217 if( ref $contig->{$_} ) {
218 push( @{$contig->{$_}}, $gst );
219 } elsif( $contig->{$_} ne $gst ) {
220 $conflict->{$group_readings->{$gst}} = $group_readings->{$contig->{$_}};
c4a4fb1b 221 } # else it is an 'extant' node marked with our group already.
d71100ed 222 }
08e0fb85 223 # None of the unreachable nodes should be in our group either.
224 foreach ( $part->vertices ) {
c4a4fb1b 225 next if $reachable->{$_};
231d71fc 226 if( $contig->{$_} eq $gst ) {
c4a4fb1b 227 $conflict->{$group_readings->{$gst}} = $group_readings->{$gst};
228 last;
229 }
08e0fb85 230 }
231
c4a4fb1b 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}};
236
732152b1 237 # Write the reading.
238 my $reading = { 'text' => $group_readings->{$gst},
239 'missing' => wit_stringify( $lacunose ),
c4a4fb1b 240 'group' => $gst }; # This will change if we find no conflict
241 if( $is_conflicted ) {
242 $reading->{'conflict'} = $conflict->{$group_readings->{$gst}}
732152b1 243 } else {
c4a4fb1b 244 # Save the relevant subgraph.
231d71fc 245 $subgraph->{$gst} = { 'graph' => $part,
c4a4fb1b 246 'root' => $group_root,
247 'reachable' => $reachable };
732152b1 248 }
249 push( @{$variant_row->{'readings'}}, $reading );
d71100ed 250 }
c4a4fb1b 251
252 # Now that we have gone through all the rows, check the hypothetical
253 # readings for conflict if we haven't found one yet.
231d71fc 254 if( keys %$subgraph && !keys %$conflict ) {
c4a4fb1b 255 my @resolve;
231d71fc 256 foreach ( keys %$contig ) {
257 next unless ref $contig->{$_};
258 if( scalar @{$contig->{$_}} > 1 ) {
c4a4fb1b 259 push( @resolve, $_ );
260 } else {
231d71fc 261 $contig->{$_} = scalar @{$contig->{$_}} ? $contig->{$_}->[0] : '';
c4a4fb1b 262 }
263 }
264 # Do we still have a possible conflict?
231d71fc 265 my $still_contig = {};
c4a4fb1b 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.
231d71fc 273 foreach my $gst ( @{$contig->{$h}} ) {
274 my $gpart = $subgraph->{$gst}->{'graph'}->copy;
275 my $reachable = $subgraph->{$gst}->{'reachable'};
c4a4fb1b 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.
231d71fc 279 my %still_reachable = ( $subgraph->{$gst}->{'root'} => 1 );
c4a4fb1b 280 map { $still_reachable{$_} = 1 }
231d71fc 281 $gpart->all_successors( $subgraph->{$gst}->{'root'} );
c4a4fb1b 282 foreach my $v ( keys %$reachable ) {
283 next if $v eq $h;
284 if( !$still_reachable{$v}
231d71fc 285 && ( $contig->{$v} eq $gst
286 || ( exists $still_contig->{$v}
287 && $still_contig->{$v} eq $gst ) ) ) {
c4a4fb1b 288 # We need $h.
231d71fc 289 if( exists $still_contig->{$h} ) {
c4a4fb1b 290 # Conflict!
291 $conflict->{$group_readings->{$gst}} =
231d71fc 292 $group_readings->{$still_contig->{$h}};
c4a4fb1b 293 } else {
231d71fc 294 $still_contig->{$h} = $gst;
c4a4fb1b 295 }
296 last;
297 } # else we don't need $h in this group.
298 }
299 }
300 }
301
302 # Now, assuming no conflict, we have some hypothetical vertices in
303 # $still_contig that are the "real" group memberships. Replace these
304 # in $contig.
305 unless ( keys %$conflict ) {
231d71fc 306 foreach my $v ( keys %$contig ) {
307 next unless ref $contig->{$v};
308 $contig->{$v} = $still_contig->{$v};
c4a4fb1b 309 }
310 }
311 }
312
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'};
231d71fc 317 my @members = grep { $contig->{$_} eq $rdg->{'group'} && !$missing->{$_} }
318 keys %$contig;
c4a4fb1b 319 $rdg->{'group'} = wit_stringify( \@members );
320 }
321
08e0fb85 322 $variant_row->{'genealogical'} = !( keys %$conflict );
732152b1 323 return $variant_row;
d71100ed 324}
325
231d71fc 326sub prune_subtree {
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;
335 }
336 # Then delete a hypothetical root with only one successor, moving the
337 # root to the child.
338 while( $tree->successors( $root ) == 1 && ref $contighash->{$root} ) {
339 my @nextroot = $tree->successors( $root );
340 $tree->delete_vertex( $root );
341 $root = $nextroot[0];
342 }
343 # The tree has been modified in place, but we need to know the new root.
344 return $root;
345}
d71100ed 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.
348sub add_variant_wit {
349 my( $arr, $wit, $acstr ) = @_;
350 my $skip;
351 if( $wit =~ /^(.*)\Q$acstr\E$/ ) {
352 my $real = $1;
353 $skip = grep { $_ =~ /^\Q$real\E$/ } @$arr;
354 }
355 push( @$arr, $wit ) unless $skip;
356}
357
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.
360sub useful_variant {
361 my( $readings ) = @_;
362 my $total = keys %$readings;
363 foreach my $var ( keys %$readings ) {
364 $total-- if @{$readings->{$var}} == 1;
365 }
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 );
371 }
372 return( $groups, $text );
373}
374
375# Take an array of witness groupings and produce a string like
376# ['A','B'] / ['C','D','E'] / ['F']
377
378sub wit_stringify {
379 my $groups = shift;
380 my @gst;
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 ];
385 $groups = $mkgrp;
386 }
387 foreach my $g ( @$groups ) {
388 push( @gst, '[' . join( ',', map { "'$_'" } @$g ) . ']' );
389 }
390 return join( ' / ', @gst );
391}
392
3931;