convert Catalyst app to use KiokuDB backend
[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 {
3837c155 14 my( $tradition, $stemma ) = @_;
d71100ed 15 # What we will return
d71100ed 16 my $variants = [];
e367f5c0 17 my $data = {};
3837c155 18
d71100ed 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.
08e0fb85 21 my $wits = {};
22 map { $wits->{$_} = 1 } $stemma->witnesses;
d71100ed 23 # For each column in the alignment table, we want to see if the existing
f6c8ea08 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.
26 my $max_variants = 0;
732152b1 27 my ( $total, $genealogical, $conflicts ) = ( 0, 0, 0 );
d71100ed 28
e4386ba9 29 my $t0 = Benchmark->new();
f6c8ea08 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'};
d71100ed 35
f6c8ea08 36 $max_variants = scalar @$groups if scalar @$groups > $max_variants;
d71100ed 37
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];
43 }
44
45 # For all the groups with more than one member, collect the list of all
46 # contiguous vertices needed to connect them.
f6c8ea08 47 my $variant_loc = analyze_variant_location( $group_readings, $groups,
08e0fb85 48 $stemma->graph, $lacunose );
f6c8ea08 49 $variant_loc->{'id'} = $rank;
50 $genealogical++ if $variant_loc->{'genealogical'};
51 $conflicts += grep { $_->{'conflict'} } @{$variant_loc->{'readings'}};
732152b1 52
d71100ed 53 # Now run the same analysis given the calculated distance tree(s).
732152b1 54# my @trees = @{$stemma->distance_trees};
55# if( @trees ) {
56# foreach my $tree ( 0 .. $#trees ) {
c4a4fb1b 57# my $dc = analyze_variant_location( $group_readings, $groups, $tree, $lacunose, 'undirected' );
732152b1 58# foreach my $rdg ( keys %$dc ) {
59# my $var = $dc->{$rdg};
60# # TODO Do something with this
61# }
62# }
63# }
64
d71100ed 65 # Record that we used this variant in an analysis
f6c8ea08 66 push( @$variants, $variant_loc );
d71100ed 67 }
e4386ba9 68 my $t1 = Benchmark->new();
69 print STDERR "Analysis of graph for " . $tradition->name . " took "
70 . timestr( timediff( $t1, $t0 ) ) . "seconds\n";
d71100ed 71
f6c8ea08 72 # Go through our variant locations, after we have seen all of them once,
732152b1 73 # and add the number of empty columns needed by each.
d71100ed 74 foreach my $row ( @$variants ) {
f6c8ea08 75 my $empty = $max_variants - scalar @{$row->{'readings'}};
d71100ed 76 $row->{'empty'} = $empty;
77 }
78
e367f5c0 79 $data->{'variants'} = $variants;
80 $data->{'variant_count'} = $total;
81 $data->{'conflict_count'} = $conflicts;
82 $data->{'genealogical_count'} = $genealogical;
3837c155 83 return $data;
d71100ed 84}
85
d1348d38 86sub group_variants {
87 my( $c, $wits ) = @_;
88 my $variant_groups = [];
89
f6c8ea08 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.
d1348d38 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.
98 }
f6c8ea08 99 my @not_collated = grep { $wits->{$_} == 1 } keys %$wits;
d1348d38 100 foreach my $i ( 0 .. $#$all_wits_table ) {
101 # For each column in the table, group the readings by witness.
102 my $rdg_wits = {};
103 my $col_rdgs = shift @$all_wits_table;
d1348d38 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
108 if( $rdg ) {
109 if( $rdg->is_lacuna ) {
110 $rdg_text = undef; # Don't count lacunae
111 push( @$lacunose, $col_wits->[$j] );
112 } else {
113 $rdg_text = $rdg->text;
d1348d38 114 }
115 }
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],
121 $c->ac_label );
122 }
123 }
124
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;
129
f6c8ea08 130 push( @$variant_groups,
131 { 'groups' => $groups, 'readings' => $readings, 'lacunose' => $lacunose } );
d1348d38 132 }
133 return $variant_groups;
134}
135
f6c8ea08 136
137
732152b1 138# variant_row -> genealogical
139# -> readings [ { text, group, conflict, missing } ]
140
d71100ed 141sub analyze_variant_location {
c4a4fb1b 142 my( $group_readings, $groups, $graph, $lacunose, $undirected ) = @_;
231d71fc 143 my $contig = {};
144 my $subgraph = {};
c4a4fb1b 145 my $is_conflicted;
d71100ed 146 my $conflict = {};
231d71fc 147 my $missing = {};
148 map { $missing->{$_} = 1 } @$lacunose;
732152b1 149 my $variant_row = { 'readings' => [] };
94a077d6 150 # Mark each ms as in its own group, first.
151 foreach my $g ( @$groups ) {
152 my $gst = wit_stringify( $g );
231d71fc 153 map { $contig->{$_} = $gst } @$g;
94a077d6 154 }
c4a4fb1b 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.
231d71fc 158 map { $contig->{$_} = [] unless $contig->{$_} } $graph->vertices;
d71100ed 159 foreach my $g ( sort { scalar @$b <=> scalar @$a } @$groups ) {
c4a4fb1b 160 my $gst = wit_stringify( $g ); # This is the group name
161 my $reachable = { $g->[0] => 1 };
08e0fb85 162 # Copy the graph, and delete all non-members from the new graph.
c4a4fb1b 163 my $part = $graph->copy;
164 my $group_root;
165 $part->delete_vertices(
231d71fc 166 grep { !ref( $contig->{$_} ) && $contig->{$_} ne $gst } $graph->vertices );
c4a4fb1b 167
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.
176 } else {
177 if( @$g > 1 ) {
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?
231d71fc 181 my @roots = grep { ref( $contig->{$_} ) || $contig->{$_} eq $gst }
c4a4fb1b 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 ) {
231d71fc 189 # Prune the tree to get rid of extraneous hypotheticals.
190 $root = prune_subtree( $part, $root, $contig );
c4a4fb1b 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)
231d71fc 196 next unless grep { $contig->{$_} } keys %$tmp_reach;
c4a4fb1b 197 if( keys %$tmp_reach > $nodes_in_subtree ) {
198 $nodes_in_subtree = keys %$tmp_reach;
199 $reachable = $tmp_reach;
200 $group_root = $root;
201 }
202 }
203 } # else it is a single-node group, nothing to calculate.
204 }
205
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 ) {
231d71fc 210 if( ref $contig->{$_} ) {
211 push( @{$contig->{$_}}, $gst );
212 } elsif( $contig->{$_} ne $gst ) {
213 $conflict->{$group_readings->{$gst}} = $group_readings->{$contig->{$_}};
c4a4fb1b 214 } # else it is an 'extant' node marked with our group already.
d71100ed 215 }
08e0fb85 216 # None of the unreachable nodes should be in our group either.
217 foreach ( $part->vertices ) {
c4a4fb1b 218 next if $reachable->{$_};
231d71fc 219 if( $contig->{$_} eq $gst ) {
c4a4fb1b 220 $conflict->{$group_readings->{$gst}} = $group_readings->{$gst};
221 last;
222 }
08e0fb85 223 }
224
c4a4fb1b 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}};
229
732152b1 230 # Write the reading.
231 my $reading = { 'text' => $group_readings->{$gst},
232 'missing' => wit_stringify( $lacunose ),
c4a4fb1b 233 'group' => $gst }; # This will change if we find no conflict
234 if( $is_conflicted ) {
235 $reading->{'conflict'} = $conflict->{$group_readings->{$gst}}
732152b1 236 } else {
c4a4fb1b 237 # Save the relevant subgraph.
231d71fc 238 $subgraph->{$gst} = { 'graph' => $part,
c4a4fb1b 239 'root' => $group_root,
240 'reachable' => $reachable };
732152b1 241 }
242 push( @{$variant_row->{'readings'}}, $reading );
d71100ed 243 }
c4a4fb1b 244
245 # Now that we have gone through all the rows, check the hypothetical
246 # readings for conflict if we haven't found one yet.
231d71fc 247 if( keys %$subgraph && !keys %$conflict ) {
c4a4fb1b 248 my @resolve;
231d71fc 249 foreach ( keys %$contig ) {
250 next unless ref $contig->{$_};
251 if( scalar @{$contig->{$_}} > 1 ) {
c4a4fb1b 252 push( @resolve, $_ );
253 } else {
231d71fc 254 $contig->{$_} = scalar @{$contig->{$_}} ? $contig->{$_}->[0] : '';
c4a4fb1b 255 }
256 }
257 # Do we still have a possible conflict?
231d71fc 258 my $still_contig = {};
c4a4fb1b 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.
231d71fc 266 foreach my $gst ( @{$contig->{$h}} ) {
267 my $gpart = $subgraph->{$gst}->{'graph'}->copy;
268 my $reachable = $subgraph->{$gst}->{'reachable'};
c4a4fb1b 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.
231d71fc 272 my %still_reachable = ( $subgraph->{$gst}->{'root'} => 1 );
c4a4fb1b 273 map { $still_reachable{$_} = 1 }
231d71fc 274 $gpart->all_successors( $subgraph->{$gst}->{'root'} );
c4a4fb1b 275 foreach my $v ( keys %$reachable ) {
276 next if $v eq $h;
277 if( !$still_reachable{$v}
231d71fc 278 && ( $contig->{$v} eq $gst
279 || ( exists $still_contig->{$v}
280 && $still_contig->{$v} eq $gst ) ) ) {
c4a4fb1b 281 # We need $h.
231d71fc 282 if( exists $still_contig->{$h} ) {
c4a4fb1b 283 # Conflict!
284 $conflict->{$group_readings->{$gst}} =
231d71fc 285 $group_readings->{$still_contig->{$h}};
c4a4fb1b 286 } else {
231d71fc 287 $still_contig->{$h} = $gst;
c4a4fb1b 288 }
289 last;
290 } # else we don't need $h in this group.
291 }
292 }
293 }
294
295 # Now, assuming no conflict, we have some hypothetical vertices in
296 # $still_contig that are the "real" group memberships. Replace these
297 # in $contig.
298 unless ( keys %$conflict ) {
231d71fc 299 foreach my $v ( keys %$contig ) {
300 next unless ref $contig->{$v};
301 $contig->{$v} = $still_contig->{$v};
c4a4fb1b 302 }
303 }
304 }
305
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'};
231d71fc 310 my @members = grep { $contig->{$_} eq $rdg->{'group'} && !$missing->{$_} }
311 keys %$contig;
c4a4fb1b 312 $rdg->{'group'} = wit_stringify( \@members );
313 }
314
08e0fb85 315 $variant_row->{'genealogical'} = !( keys %$conflict );
732152b1 316 return $variant_row;
d71100ed 317}
318
231d71fc 319sub prune_subtree {
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;
328 }
329 # Then delete a hypothetical root with only one successor, moving the
330 # root to the child.
331 while( $tree->successors( $root ) == 1 && ref $contighash->{$root} ) {
332 my @nextroot = $tree->successors( $root );
333 $tree->delete_vertex( $root );
334 $root = $nextroot[0];
335 }
336 # The tree has been modified in place, but we need to know the new root.
337 return $root;
338}
d71100ed 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.
341sub add_variant_wit {
342 my( $arr, $wit, $acstr ) = @_;
343 my $skip;
344 if( $wit =~ /^(.*)\Q$acstr\E$/ ) {
345 my $real = $1;
346 $skip = grep { $_ =~ /^\Q$real\E$/ } @$arr;
347 }
348 push( @$arr, $wit ) unless $skip;
349}
350
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.
353sub useful_variant {
354 my( $readings ) = @_;
355 my $total = keys %$readings;
356 foreach my $var ( keys %$readings ) {
357 $total-- if @{$readings->{$var}} == 1;
358 }
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 );
364 }
365 return( $groups, $text );
366}
367
368# Take an array of witness groupings and produce a string like
369# ['A','B'] / ['C','D','E'] / ['F']
370
371sub wit_stringify {
372 my $groups = shift;
373 my @gst;
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 ];
378 $groups = $mkgrp;
379 }
380 foreach my $g ( @$groups ) {
381 push( @gst, '[' . join( ',', map { "'$_'" } @$g ) . ']' );
382 }
383 return join( ' / ', @gst );
384}
385
3861;