move scripts into script/
[scpubgit/stemmatology.git] / lib / Text / Tradition / Analysis.pm
CommitLineData
d71100ed 1package Text::Tradition::Analysis;
2
3use strict;
4use warnings;
d1348d38 5use Exporter 'import';
d71100ed 6use Text::Tradition;
7use Text::Tradition::Stemma;
8
d1348d38 9use vars qw/ @EXPORT_OK /;
10@EXPORT_OK = qw/ run_analysis group_variants wit_stringify /;
11
d71100ed 12sub new {
13 my( $class, $args ) = @_;
14 my $self = {};
d71100ed 15 bless( $self, $class );
e367f5c0 16 $self->{'data'} = [];
17 foreach my $t ( @{$args->{'traditions'}} ) {
18 $self->run_analysis( $t->{'file'}, $t->{'stemmadot'} );
19 }
d71100ed 20 return $self;
21}
22
23sub run_analysis {
732152b1 24 my( $self, $file, $stemmadot ) = @_;
d71100ed 25 # What we will return
26 my $svg;
27 my $variants = [];
e367f5c0 28 my $data = {};
d71100ed 29
3d79e248 30 # Read in the file and stemma
d71100ed 31 my $tradition = Text::Tradition->new(
3d79e248 32 'input' => 'Self',
33 'file' => $file,
d71100ed 34 'linear' => 1,
35 );
e367f5c0 36 $data->{'title'} = $tradition->name;
732152b1 37
d71100ed 38 my $stemma = Text::Tradition::Stemma->new(
39 'collation' => $tradition->collation,
40 'dot' => $stemmadot,
41 );
42 # We will return the stemma picture
e367f5c0 43 $svg = $stemma->as_svg( { size => "8,7.5" } );;
44 $data->{'svg'} = $svg;
d71100ed 45
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.
08e0fb85 48 my $wits = {};
49 map { $wits->{$_} = 1 } $stemma->witnesses;
50 my $all_wits_table = $tradition->collation->make_alignment_table( 'refs', $wits );
d71100ed 51
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.
55 my $html_columns = 0;
732152b1 56 my ( $total, $genealogical, $conflicts ) = ( 0, 0, 0 );
d71100ed 57
58 # Strip the list of sigla and save it for correlation to the readings.
59 my $col_wits = shift @$all_wits_table;
4f343ec0 60 # Any witness in the stemma that has no row should be noted.
61 foreach ( @$col_wits ) {
fa954f4c 62 $wits->{$_}++; # Witnesses present in table and stemma now have value 2.
4f343ec0 63 }
64 my @not_collated = grep { $wits->{$_} == 1 } keys %$wits;
d71100ed 65
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.
70 my $rdg_wits = {};
71 my $col_rdgs = shift @$all_wits_table;
72 my $rank;
4f343ec0 73 my $lacunose = [ @not_collated ];
d71100ed 74 foreach my $j ( 0 .. $#{$col_rdgs} ) {
75 my $rdg = $col_rdgs->[$j];
d71100ed 76 my $rdg_text = '(omitted)'; # Initialize in case of empty reading
77 if( $rdg ) {
c4e11e3f 78 if( $rdg->is_lacuna ) {
79 $rdg_text = undef; # Don't count lacunae
80 push( @$lacunose, $col_wits->[$j] );
81 } else {
82 $rdg_text = $rdg->text;
83 # Get the rank from any real reading; they should be identical.
84 $rank = $rdg->rank;
85 }
d71100ed 86 }
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 );
93 }
94 }
95
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;
101
d71100ed 102 # Keep track of our widest row
103 $html_columns = scalar @$groups if scalar @$groups > $html_columns;
104
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];
110 }
111
112 # For all the groups with more than one member, collect the list of all
113 # contiguous vertices needed to connect them.
732152b1 114 my $variant_row = analyze_variant_location( $group_readings, $groups,
08e0fb85 115 $stemma->graph, $lacunose );
732152b1 116 $variant_row->{'id'} = $rank;
117 $genealogical++ if $variant_row->{'genealogical'};
118 $conflicts += grep { $_->{'conflict'} } @{$variant_row->{'readings'}};
119
d71100ed 120 # Now run the same analysis given the calculated distance tree(s).
732152b1 121# my @trees = @{$stemma->distance_trees};
122# if( @trees ) {
123# foreach my $tree ( 0 .. $#trees ) {
c4a4fb1b 124# my $dc = analyze_variant_location( $group_readings, $groups, $tree, $lacunose, 'undirected' );
732152b1 125# foreach my $rdg ( keys %$dc ) {
126# my $var = $dc->{$rdg};
127# # TODO Do something with this
128# }
129# }
130# }
131
d71100ed 132 # Record that we used this variant in an analysis
133 push( @$variants, $variant_row );
134 }
135
732152b1 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.
d71100ed 138 foreach my $row ( @$variants ) {
139 my $empty = $html_columns - scalar @{$row->{'readings'}};
140 $row->{'empty'} = $empty;
141 }
142
732152b1 143 # Populate self with our analysis data.
e367f5c0 144 $data->{'variants'} = $variants;
145 $data->{'variant_count'} = $total;
146 $data->{'conflict_count'} = $conflicts;
147 $data->{'genealogical_count'} = $genealogical;
148 push( @{$self->{'data'}}, $data );
d71100ed 149}
150
d1348d38 151sub group_variants {
152 my( $c, $wits ) = @_;
153 my $variant_groups = [];
154
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.
161 }
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.
165 my $rdg_wits = {};
166 my $col_rdgs = shift @$all_wits_table;
167 my $rank;
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
172 if( $rdg ) {
173 if( $rdg->is_lacuna ) {
174 $rdg_text = undef; # Don't count lacunae
175 push( @$lacunose, $col_wits->[$j] );
176 } else {
177 $rdg_text = $rdg->text;
178 # Get the rank from any real reading; they should be identical.
179 $rank = $rdg->rank;
180 }
181 }
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],
187 $c->ac_label );
188 }
189 }
190
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;
195
196 push( @$variant_groups, $groups );
197 }
198 return $variant_groups;
199}
200
732152b1 201# variant_row -> genealogical
202# -> readings [ { text, group, conflict, missing } ]
203
d71100ed 204sub analyze_variant_location {
c4a4fb1b 205 my( $group_readings, $groups, $graph, $lacunose, $undirected ) = @_;
231d71fc 206 my $contig = {};
207 my $subgraph = {};
c4a4fb1b 208 my $is_conflicted;
d71100ed 209 my $conflict = {};
231d71fc 210 my $missing = {};
211 map { $missing->{$_} = 1 } @$lacunose;
732152b1 212 my $variant_row = { 'readings' => [] };
94a077d6 213 # Mark each ms as in its own group, first.
214 foreach my $g ( @$groups ) {
215 my $gst = wit_stringify( $g );
231d71fc 216 map { $contig->{$_} = $gst } @$g;
94a077d6 217 }
c4a4fb1b 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.
231d71fc 221 map { $contig->{$_} = [] unless $contig->{$_} } $graph->vertices;
d71100ed 222 foreach my $g ( sort { scalar @$b <=> scalar @$a } @$groups ) {
c4a4fb1b 223 my $gst = wit_stringify( $g ); # This is the group name
224 my $reachable = { $g->[0] => 1 };
08e0fb85 225 # Copy the graph, and delete all non-members from the new graph.
c4a4fb1b 226 my $part = $graph->copy;
227 my $group_root;
228 $part->delete_vertices(
231d71fc 229 grep { !ref( $contig->{$_} ) && $contig->{$_} ne $gst } $graph->vertices );
c4a4fb1b 230
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.
239 } else {
240 if( @$g > 1 ) {
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?
231d71fc 244 my @roots = grep { ref( $contig->{$_} ) || $contig->{$_} eq $gst }
c4a4fb1b 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 ) {
231d71fc 252 # Prune the tree to get rid of extraneous hypotheticals.
253 $root = prune_subtree( $part, $root, $contig );
c4a4fb1b 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)
231d71fc 259 next unless grep { $contig->{$_} } keys %$tmp_reach;
c4a4fb1b 260 if( keys %$tmp_reach > $nodes_in_subtree ) {
261 $nodes_in_subtree = keys %$tmp_reach;
262 $reachable = $tmp_reach;
263 $group_root = $root;
264 }
265 }
266 } # else it is a single-node group, nothing to calculate.
267 }
268
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 ) {
231d71fc 273 if( ref $contig->{$_} ) {
274 push( @{$contig->{$_}}, $gst );
275 } elsif( $contig->{$_} ne $gst ) {
276 $conflict->{$group_readings->{$gst}} = $group_readings->{$contig->{$_}};
c4a4fb1b 277 } # else it is an 'extant' node marked with our group already.
d71100ed 278 }
08e0fb85 279 # None of the unreachable nodes should be in our group either.
280 foreach ( $part->vertices ) {
c4a4fb1b 281 next if $reachable->{$_};
231d71fc 282 if( $contig->{$_} eq $gst ) {
c4a4fb1b 283 $conflict->{$group_readings->{$gst}} = $group_readings->{$gst};
284 last;
285 }
08e0fb85 286 }
287
c4a4fb1b 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}};
292
732152b1 293 # Write the reading.
294 my $reading = { 'text' => $group_readings->{$gst},
295 'missing' => wit_stringify( $lacunose ),
c4a4fb1b 296 'group' => $gst }; # This will change if we find no conflict
297 if( $is_conflicted ) {
298 $reading->{'conflict'} = $conflict->{$group_readings->{$gst}}
732152b1 299 } else {
c4a4fb1b 300 # Save the relevant subgraph.
231d71fc 301 $subgraph->{$gst} = { 'graph' => $part,
c4a4fb1b 302 'root' => $group_root,
303 'reachable' => $reachable };
732152b1 304 }
305 push( @{$variant_row->{'readings'}}, $reading );
d71100ed 306 }
c4a4fb1b 307
308 # Now that we have gone through all the rows, check the hypothetical
309 # readings for conflict if we haven't found one yet.
231d71fc 310 if( keys %$subgraph && !keys %$conflict ) {
c4a4fb1b 311 my @resolve;
231d71fc 312 foreach ( keys %$contig ) {
313 next unless ref $contig->{$_};
314 if( scalar @{$contig->{$_}} > 1 ) {
c4a4fb1b 315 push( @resolve, $_ );
316 } else {
231d71fc 317 $contig->{$_} = scalar @{$contig->{$_}} ? $contig->{$_}->[0] : '';
c4a4fb1b 318 }
319 }
320 # Do we still have a possible conflict?
231d71fc 321 my $still_contig = {};
c4a4fb1b 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.
231d71fc 329 foreach my $gst ( @{$contig->{$h}} ) {
330 my $gpart = $subgraph->{$gst}->{'graph'}->copy;
331 my $reachable = $subgraph->{$gst}->{'reachable'};
c4a4fb1b 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.
231d71fc 335 my %still_reachable = ( $subgraph->{$gst}->{'root'} => 1 );
c4a4fb1b 336 map { $still_reachable{$_} = 1 }
231d71fc 337 $gpart->all_successors( $subgraph->{$gst}->{'root'} );
c4a4fb1b 338 foreach my $v ( keys %$reachable ) {
339 next if $v eq $h;
340 if( !$still_reachable{$v}
231d71fc 341 && ( $contig->{$v} eq $gst
342 || ( exists $still_contig->{$v}
343 && $still_contig->{$v} eq $gst ) ) ) {
c4a4fb1b 344 # We need $h.
231d71fc 345 if( exists $still_contig->{$h} ) {
c4a4fb1b 346 # Conflict!
347 $conflict->{$group_readings->{$gst}} =
231d71fc 348 $group_readings->{$still_contig->{$h}};
c4a4fb1b 349 } else {
231d71fc 350 $still_contig->{$h} = $gst;
c4a4fb1b 351 }
352 last;
353 } # else we don't need $h in this group.
354 }
355 }
356 }
357
358 # Now, assuming no conflict, we have some hypothetical vertices in
359 # $still_contig that are the "real" group memberships. Replace these
360 # in $contig.
361 unless ( keys %$conflict ) {
231d71fc 362 foreach my $v ( keys %$contig ) {
363 next unless ref $contig->{$v};
364 $contig->{$v} = $still_contig->{$v};
c4a4fb1b 365 }
366 }
367 }
368
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'};
231d71fc 373 my @members = grep { $contig->{$_} eq $rdg->{'group'} && !$missing->{$_} }
374 keys %$contig;
c4a4fb1b 375 $rdg->{'group'} = wit_stringify( \@members );
376 }
377
08e0fb85 378 $variant_row->{'genealogical'} = !( keys %$conflict );
732152b1 379 return $variant_row;
d71100ed 380}
381
231d71fc 382sub prune_subtree {
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;
391 }
392 # Then delete a hypothetical root with only one successor, moving the
393 # root to the child.
394 while( $tree->successors( $root ) == 1 && ref $contighash->{$root} ) {
395 my @nextroot = $tree->successors( $root );
396 $tree->delete_vertex( $root );
397 $root = $nextroot[0];
398 }
399 # The tree has been modified in place, but we need to know the new root.
400 return $root;
401}
d71100ed 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.
404sub add_variant_wit {
405 my( $arr, $wit, $acstr ) = @_;
406 my $skip;
407 if( $wit =~ /^(.*)\Q$acstr\E$/ ) {
408 my $real = $1;
409 $skip = grep { $_ =~ /^\Q$real\E$/ } @$arr;
410 }
411 push( @$arr, $wit ) unless $skip;
412}
413
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.
416sub useful_variant {
417 my( $readings ) = @_;
418 my $total = keys %$readings;
419 foreach my $var ( keys %$readings ) {
420 $total-- if @{$readings->{$var}} == 1;
421 }
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 );
427 }
428 return( $groups, $text );
429}
430
431# Take an array of witness groupings and produce a string like
432# ['A','B'] / ['C','D','E'] / ['F']
433
434sub wit_stringify {
435 my $groups = shift;
436 my @gst;
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 ];
441 $groups = $mkgrp;
442 }
443 foreach my $g ( @$groups ) {
444 push( @gst, '[' . join( ',', map { "'$_'" } @$g ) . ']' );
445 }
446 return join( ' / ', @gst );
447}
448
4491;