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