split tree pruning into its own function; s158 works now
[scpubgit/stemmatology.git] / lib / Text / Tradition / Analysis.pm
CommitLineData
d71100ed 1package Text::Tradition::Analysis;
2
3use strict;
4use warnings;
5use Text::Tradition;
6use Text::Tradition::Stemma;
7
8sub new {
9 my( $class, $args ) = @_;
10 my $self = {};
d71100ed 11 bless( $self, $class );
e367f5c0 12 $self->{'data'} = [];
13 foreach my $t ( @{$args->{'traditions'}} ) {
14 $self->run_analysis( $t->{'file'}, $t->{'stemmadot'} );
15 }
d71100ed 16 return $self;
17}
18
19sub run_analysis {
732152b1 20 my( $self, $file, $stemmadot ) = @_;
d71100ed 21 # What we will return
22 my $svg;
23 my $variants = [];
e367f5c0 24 my $data = {};
d71100ed 25
3d79e248 26 # Read in the file and stemma
d71100ed 27 my $tradition = Text::Tradition->new(
3d79e248 28 'input' => 'Self',
29 'file' => $file,
d71100ed 30 'linear' => 1,
31 );
e367f5c0 32 $data->{'title'} = $tradition->name;
732152b1 33
d71100ed 34 my $stemma = Text::Tradition::Stemma->new(
35 'collation' => $tradition->collation,
36 'dot' => $stemmadot,
37 );
38 # We will return the stemma picture
e367f5c0 39 $svg = $stemma->as_svg( { size => "8,7.5" } );;
40 $data->{'svg'} = $svg;
d71100ed 41
42 # We have the collation, so get the alignment table with witnesses in rows.
43 # Also return the reading objects in the table, rather than just the words.
08e0fb85 44 my $wits = {};
45 map { $wits->{$_} = 1 } $stemma->witnesses;
46 my $all_wits_table = $tradition->collation->make_alignment_table( 'refs', $wits );
d71100ed 47
48 # For each column in the alignment table, we want to see if the existing
49 # groupings of witnesses match our stemma hypothesis. We also want, at the
50 # end, to produce an HTML table with all the variants.
51 my $html_columns = 0;
732152b1 52 my ( $total, $genealogical, $conflicts ) = ( 0, 0, 0 );
d71100ed 53
54 # Strip the list of sigla and save it for correlation to the readings.
55 my $col_wits = shift @$all_wits_table;
56
57 # We will return a data structure, an array for each row that looks like:
58 # { id = X, genealogical = Y, readings = [ text = X, group = Y], empty = N }
59 foreach my $i ( 0 .. $#$all_wits_table ) {
60 # For each column in the table, group the readings by witness.
61 my $rdg_wits = {};
62 my $col_rdgs = shift @$all_wits_table;
63 my $rank;
c4e11e3f 64 my $lacunose = [];
d71100ed 65 foreach my $j ( 0 .. $#{$col_rdgs} ) {
66 my $rdg = $col_rdgs->[$j];
d71100ed 67 my $rdg_text = '(omitted)'; # Initialize in case of empty reading
68 if( $rdg ) {
c4e11e3f 69 if( $rdg->is_lacuna ) {
70 $rdg_text = undef; # Don't count lacunae
71 push( @$lacunose, $col_wits->[$j] );
72 } else {
73 $rdg_text = $rdg->text;
74 # Get the rank from any real reading; they should be identical.
75 $rank = $rdg->rank;
76 }
d71100ed 77 }
78 if( defined $rdg_text ) {
79 # Initialize the witness array if we haven't got one yet
80 $rdg_wits->{$rdg_text} = [] unless $rdg_wits->{$rdg_text};
81 # Add the relevant witness, subject to a.c. logic
82 add_variant_wit( $rdg_wits->{$rdg_text}, $col_wits->[$j],
83 $tradition->collation->ac_label );
84 }
85 }
86
87 # See if this column has any potentially genealogical variants.
88 # If not, skip to the next.
89 $total++ unless scalar keys %$rdg_wits == 1;
90 my( $groups, $readings ) = useful_variant( $rdg_wits );
91 next unless $groups && $readings;
92
d71100ed 93 # Keep track of our widest row
94 $html_columns = scalar @$groups if scalar @$groups > $html_columns;
95
96 # We can already look up witnesses for a reading; we also want to look
97 # up readings for a given witness.
98 my $group_readings = {};
99 foreach my $x ( 0 .. $#$groups ) {
100 $group_readings->{wit_stringify( $groups->[$x] )} = $readings->[$x];
101 }
102
103 # For all the groups with more than one member, collect the list of all
104 # contiguous vertices needed to connect them.
231d71fc 105 $DB::single = 1;
732152b1 106 my $variant_row = analyze_variant_location( $group_readings, $groups,
08e0fb85 107 $stemma->graph, $lacunose );
732152b1 108 $variant_row->{'id'} = $rank;
109 $genealogical++ if $variant_row->{'genealogical'};
110 $conflicts += grep { $_->{'conflict'} } @{$variant_row->{'readings'}};
111
d71100ed 112 # Now run the same analysis given the calculated distance tree(s).
732152b1 113# my @trees = @{$stemma->distance_trees};
114# if( @trees ) {
115# foreach my $tree ( 0 .. $#trees ) {
c4a4fb1b 116# my $dc = analyze_variant_location( $group_readings, $groups, $tree, $lacunose, 'undirected' );
732152b1 117# foreach my $rdg ( keys %$dc ) {
118# my $var = $dc->{$rdg};
119# # TODO Do something with this
120# }
121# }
122# }
123
d71100ed 124 # Record that we used this variant in an analysis
125 push( @$variants, $variant_row );
126 }
127
732152b1 128 # Go through our variant rows, after we have seen all of them once,
129 # and add the number of empty columns needed by each.
d71100ed 130 foreach my $row ( @$variants ) {
131 my $empty = $html_columns - scalar @{$row->{'readings'}};
132 $row->{'empty'} = $empty;
133 }
134
732152b1 135 # Populate self with our analysis data.
e367f5c0 136 $data->{'variants'} = $variants;
137 $data->{'variant_count'} = $total;
138 $data->{'conflict_count'} = $conflicts;
139 $data->{'genealogical_count'} = $genealogical;
140 push( @{$self->{'data'}}, $data );
d71100ed 141}
142
732152b1 143# variant_row -> genealogical
144# -> readings [ { text, group, conflict, missing } ]
145
d71100ed 146sub analyze_variant_location {
c4a4fb1b 147 my( $group_readings, $groups, $graph, $lacunose, $undirected ) = @_;
231d71fc 148 my $contig = {};
149 my $subgraph = {};
c4a4fb1b 150 my $is_conflicted;
d71100ed 151 my $conflict = {};
231d71fc 152 my $missing = {};
153 map { $missing->{$_} = 1 } @$lacunose;
732152b1 154 my $variant_row = { 'readings' => [] };
94a077d6 155 # Mark each ms as in its own group, first.
156 foreach my $g ( @$groups ) {
157 my $gst = wit_stringify( $g );
231d71fc 158 map { $contig->{$_} = $gst } @$g;
94a077d6 159 }
c4a4fb1b 160 # Now for each unmarked node in the graph, initialize an array
161 # for possible group memberships. We will use this later to
162 # resolve potential conflicts.
231d71fc 163 map { $contig->{$_} = [] unless $contig->{$_} } $graph->vertices;
d71100ed 164 foreach my $g ( sort { scalar @$b <=> scalar @$a } @$groups ) {
c4a4fb1b 165 my $gst = wit_stringify( $g ); # This is the group name
166 my $reachable = { $g->[0] => 1 };
08e0fb85 167 # Copy the graph, and delete all non-members from the new graph.
c4a4fb1b 168 my $part = $graph->copy;
169 my $group_root;
170 $part->delete_vertices(
231d71fc 171 grep { !ref( $contig->{$_} ) && $contig->{$_} ne $gst } $graph->vertices );
c4a4fb1b 172
173 # Now look to see if our group is connected.
174 if( $undirected ) { # For use with distance trees etc.
175 # Find all vertices reachable from the first (arbitrary) group
176 # member. If we are genealogical this should include them all.
177 map { $reachable->{$_} = 1 } $part->all_reachable( $g->[0] );
178 # TODO This is a terrible way to do distance trees, since all
179 # non-leaf nodes are included in every graph part now. We may
180 # have to go back to SPDP.
181 } else {
182 if( @$g > 1 ) {
183 # Dispense with the trivial case of one reading.
184 # We have to take directionality into account.
185 # How many root nodes do we have?
231d71fc 186 my @roots = grep { ref( $contig->{$_} ) || $contig->{$_} eq $gst }
c4a4fb1b 187 $part->source_vertices;
188 # Assuming that @$g > 1, find the first root node that has at
189 # least one successor belonging to our group. If this reading
190 # is genealogical, there should be only one, but we will check
191 # that implicitly later.
192 my $nodes_in_subtree = 0;
193 foreach my $root ( @roots ) {
231d71fc 194 # Prune the tree to get rid of extraneous hypotheticals.
195 $root = prune_subtree( $part, $root, $contig );
c4a4fb1b 196 # Get all the successor nodes of our root.
197 my $tmp_reach = { $root => 1 };
198 map { $tmp_reach->{$_} = 1 } $part->all_successors( $root );
199 # Skip this root if none of our successors are in our group
200 # (e.g. isolated 'hypothetical' witnesses with no group)
231d71fc 201 next unless grep { $contig->{$_} } keys %$tmp_reach;
c4a4fb1b 202 if( keys %$tmp_reach > $nodes_in_subtree ) {
203 $nodes_in_subtree = keys %$tmp_reach;
204 $reachable = $tmp_reach;
205 $group_root = $root;
206 }
207 }
208 } # else it is a single-node group, nothing to calculate.
209 }
210
211 # None of the 'reachable' nodes should be marked as being in another
212 # group. Paint the 'hypotheticals' with our group while we are at it,
213 # unless there is a conflict present.
214 foreach ( keys %$reachable ) {
231d71fc 215 if( ref $contig->{$_} ) {
216 push( @{$contig->{$_}}, $gst );
217 } elsif( $contig->{$_} ne $gst ) {
218 $conflict->{$group_readings->{$gst}} = $group_readings->{$contig->{$_}};
c4a4fb1b 219 } # else it is an 'extant' node marked with our group already.
d71100ed 220 }
08e0fb85 221 # None of the unreachable nodes should be in our group either.
222 foreach ( $part->vertices ) {
c4a4fb1b 223 next if $reachable->{$_};
231d71fc 224 if( $contig->{$_} eq $gst ) {
c4a4fb1b 225 $conflict->{$group_readings->{$gst}} = $group_readings->{$gst};
226 last;
227 }
08e0fb85 228 }
229
c4a4fb1b 230 # Now, if we have a conflict, we can write the reading in full. If not,
231 # we have to save the subgraph so that we can resolve possible conflicts
232 # on hypothetical nodes.
233 $is_conflicted = 1 if exists $conflict->{$group_readings->{$gst}};
234
732152b1 235 # Write the reading.
236 my $reading = { 'text' => $group_readings->{$gst},
237 'missing' => wit_stringify( $lacunose ),
c4a4fb1b 238 'group' => $gst }; # This will change if we find no conflict
239 if( $is_conflicted ) {
240 $reading->{'conflict'} = $conflict->{$group_readings->{$gst}}
732152b1 241 } else {
c4a4fb1b 242 # Save the relevant subgraph.
231d71fc 243 $subgraph->{$gst} = { 'graph' => $part,
c4a4fb1b 244 'root' => $group_root,
245 'reachable' => $reachable };
732152b1 246 }
247 push( @{$variant_row->{'readings'}}, $reading );
d71100ed 248 }
c4a4fb1b 249
250 # Now that we have gone through all the rows, check the hypothetical
251 # readings for conflict if we haven't found one yet.
231d71fc 252 if( keys %$subgraph && !keys %$conflict ) {
c4a4fb1b 253 my @resolve;
231d71fc 254 foreach ( keys %$contig ) {
255 next unless ref $contig->{$_};
256 if( scalar @{$contig->{$_}} > 1 ) {
c4a4fb1b 257 push( @resolve, $_ );
258 } else {
231d71fc 259 $contig->{$_} = scalar @{$contig->{$_}} ? $contig->{$_}->[0] : '';
c4a4fb1b 260 }
261 }
262 # Do we still have a possible conflict?
231d71fc 263 my $still_contig = {};
c4a4fb1b 264 foreach my $h ( @resolve ) {
265 # For each of the hypothetical readings with more than one possibility,
266 # try deleting it from each of its member subgraphs in turn, and see
267 # if that breaks the contiguous grouping.
268 # TODO This can still break in a corner case where group A can use
269 # either vertex 1 or 2, and group B can use either vertex 2 or 1.
270 # Revisit this if necessary; it could get brute-force nasty.
231d71fc 271 foreach my $gst ( @{$contig->{$h}} ) {
272 my $gpart = $subgraph->{$gst}->{'graph'}->copy;
273 my $reachable = $subgraph->{$gst}->{'reachable'};
c4a4fb1b 274 $gpart->delete_vertex( $h );
275 # Is everything else still reachable from the root?
276 # TODO If $h was the root, see if we still have a single root.
231d71fc 277 my %still_reachable = ( $subgraph->{$gst}->{'root'} => 1 );
c4a4fb1b 278 map { $still_reachable{$_} = 1 }
231d71fc 279 $gpart->all_successors( $subgraph->{$gst}->{'root'} );
c4a4fb1b 280 foreach my $v ( keys %$reachable ) {
281 next if $v eq $h;
282 if( !$still_reachable{$v}
231d71fc 283 && ( $contig->{$v} eq $gst
284 || ( exists $still_contig->{$v}
285 && $still_contig->{$v} eq $gst ) ) ) {
c4a4fb1b 286 # We need $h.
231d71fc 287 if( exists $still_contig->{$h} ) {
c4a4fb1b 288 # Conflict!
289 $conflict->{$group_readings->{$gst}} =
231d71fc 290 $group_readings->{$still_contig->{$h}};
c4a4fb1b 291 } else {
231d71fc 292 $still_contig->{$h} = $gst;
c4a4fb1b 293 }
294 last;
295 } # else we don't need $h in this group.
296 }
297 }
298 }
299
300 # Now, assuming no conflict, we have some hypothetical vertices in
301 # $still_contig that are the "real" group memberships. Replace these
302 # in $contig.
303 unless ( keys %$conflict ) {
231d71fc 304 foreach my $v ( keys %$contig ) {
305 next unless ref $contig->{$v};
306 $contig->{$v} = $still_contig->{$v};
c4a4fb1b 307 }
308 }
309 }
310
311 # Now write the group and conflict information into the respective rows.
312 foreach my $rdg ( @{$variant_row->{'readings'}} ) {
313 $rdg->{'conflict'} = $conflict->{$rdg->{'text'}};
314 next if $rdg->{'conflict'};
231d71fc 315 my @members = grep { $contig->{$_} eq $rdg->{'group'} && !$missing->{$_} }
316 keys %$contig;
c4a4fb1b 317 $rdg->{'group'} = wit_stringify( \@members );
318 }
319
08e0fb85 320 $variant_row->{'genealogical'} = !( keys %$conflict );
732152b1 321 return $variant_row;
d71100ed 322}
323
231d71fc 324sub prune_subtree {
325 my( $tree, $root, $contighash ) = @_;
326 # First, delete hypothetical leaves / orphans until there are none left.
327 my @orphan_hypotheticals = grep { ref( $contighash->{$_} ) }
328 $tree->successorless_vertices;
329 while( @orphan_hypotheticals ) {
330 $tree->delete_vertices( @orphan_hypotheticals );
331 @orphan_hypotheticals = grep { ref( $contighash->{$_} ) }
332 $tree->successorless_vertices;
333 }
334 # Then delete a hypothetical root with only one successor, moving the
335 # root to the child.
336 while( $tree->successors( $root ) == 1 && ref $contighash->{$root} ) {
337 my @nextroot = $tree->successors( $root );
338 $tree->delete_vertex( $root );
339 $root = $nextroot[0];
340 }
341 # The tree has been modified in place, but we need to know the new root.
342 return $root;
343}
d71100ed 344# Add the variant, subject to a.c. representation logic.
345# This assumes that we will see the 'main' version before the a.c. version.
346sub add_variant_wit {
347 my( $arr, $wit, $acstr ) = @_;
348 my $skip;
349 if( $wit =~ /^(.*)\Q$acstr\E$/ ) {
350 my $real = $1;
351 $skip = grep { $_ =~ /^\Q$real\E$/ } @$arr;
352 }
353 push( @$arr, $wit ) unless $skip;
354}
355
356# Return an answer if the variant is useful, i.e. if there are at least 2 variants
357# with at least 2 witnesses each.
358sub useful_variant {
359 my( $readings ) = @_;
360 my $total = keys %$readings;
361 foreach my $var ( keys %$readings ) {
362 $total-- if @{$readings->{$var}} == 1;
363 }
364 return( undef, undef ) if $total <= 1;
365 my( $groups, $text );
366 foreach my $var ( keys %$readings ) {
367 push( @$groups, $readings->{$var} );
368 push( @$text, $var );
369 }
370 return( $groups, $text );
371}
372
373# Take an array of witness groupings and produce a string like
374# ['A','B'] / ['C','D','E'] / ['F']
375
376sub wit_stringify {
377 my $groups = shift;
378 my @gst;
379 # If we were passed an array of witnesses instead of an array of
380 # groupings, then "group" the witnesses first.
381 unless( ref( $groups->[0] ) ) {
382 my $mkgrp = [ $groups ];
383 $groups = $mkgrp;
384 }
385 foreach my $g ( @$groups ) {
386 push( @gst, '[' . join( ',', map { "'$_'" } @$g ) . ']' );
387 }
388 return join( ' / ', @gst );
389}
390
3911;