change analysis graph calculation - closer but not correct yet.
[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         
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;
64                 my $lacunose = [];
65                 foreach my $j ( 0 .. $#{$col_rdgs} ) {
66                         my $rdg = $col_rdgs->[$j];
67                         my $rdg_text = '(omitted)';  # Initialize in case of empty reading
68                         if( $rdg ) {
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                                 }
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                 
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.
105                 # TODO: deal with a.c. reading logic
106                 $DB::single = 1 if $rank == 25;
107                 my $variant_row = analyze_variant_location( $group_readings, $groups, 
108                     $stemma->graph, $lacunose );
109                 $variant_row->{'id'} = $rank;
110                 $genealogical++ if $variant_row->{'genealogical'};
111                 $conflicts += grep { $_->{'conflict'} } @{$variant_row->{'readings'}};
112
113                 # Now run the same analysis given the calculated distance tree(s).
114 #               my @trees = @{$stemma->distance_trees};
115 #               if( @trees ) {
116 #             foreach my $tree ( 0 .. $#trees ) {
117 #                 my $dc = analyze_variant_location( $group_readings, $groups, $tree );
118 #                 foreach my $rdg ( keys %$dc ) {
119 #                     my $var = $dc->{$rdg};
120 #                     # TODO Do something with this
121 #                 }
122 #             }
123 #           }
124
125                 # Record that we used this variant in an analysis
126                 push( @$variants, $variant_row );
127         }
128         
129         # Go through our variant rows, after we have seen all of them once,
130         # and add the number of empty columns needed by each.
131         foreach my $row ( @$variants ) {
132                 my $empty = $html_columns - scalar @{$row->{'readings'}};
133                 $row->{'empty'} = $empty;
134         }
135         
136         # Populate self with our analysis data.
137         $data->{'variants'} = $variants;
138         $data->{'variant_count'} = $total;
139         $data->{'conflict_count'} = $conflicts;
140         $data->{'genealogical_count'} = $genealogical;
141         push( @{$self->{'data'}}, $data );
142 }
143
144 # variant_row -> genealogical
145 #             -> readings [ { text, group, conflict, missing } ]
146
147 sub analyze_variant_location {
148     my( $group_readings, $groups, $graph, $lacunose ) = @_;
149     my %contig;
150     my $conflict = {};
151     my %missing;
152     map { $missing{$_} = 1 } @$lacunose;
153     my $variant_row = { 'readings' => [] };
154     # Mark each ms as in its own group, first.
155     foreach my $g ( @$groups ) {
156         my $gst = wit_stringify( $g );
157         map { $contig{$_} = $gst } @$g;
158     }
159     foreach my $g ( sort { scalar @$b <=> scalar @$a } @$groups ) {
160         my $gst = wit_stringify( $g );
161         # Copy the graph, and delete all non-members from the new graph.
162         my $part = $graph->undirected_copy;
163         map { $part->delete_vertex( $_ ) 
164                 if $contig{$_} && $contig{$_} ne $gst } $graph->vertices;
165         # Now all the members of the group should still be reachable 
166         # from the first member. 
167         my %reachable = ( $g->[0] => 1 );       
168         map { $reachable{$_} = 1 } $part->all_reachable( $g->[0] );
169
170         # ...and none of these nodes should be marked as being in another 
171         # group.
172         foreach ( keys %reachable ) {
173             if( $contig{$_} && $contig{$_} ne $gst ) {
174                 $conflict->{$group_readings->{$gst}} = $group_readings->{$contig{$_}};
175             } else {
176                 $contig{$_} = $gst;
177             }
178         }
179         # None of the unreachable nodes should be in our group either.
180         foreach ( $part->vertices ) {
181             next if $reachable{$_};
182             $conflict->{$group_readings->{$gst}} = $group_readings->{$gst}
183                 if $contig{$_} && $contig{$_} eq $gst;
184         }
185         
186         # Write the reading.
187         my $reading = { 'text' => $group_readings->{$gst},
188                         'missing' => wit_stringify( $lacunose ),
189                         'conflict' => exists( $conflict->{$group_readings->{$gst}} ) };
190         if( $reading->{'conflict'} ) {
191             $reading->{'group'} = $gst;
192         } else {
193             my @all_vertices = grep { !$missing{$_} } keys %reachable;
194             $reading->{'group'} = wit_stringify( \@all_vertices );
195         }
196         push( @{$variant_row->{'readings'}}, $reading );
197     }
198     $variant_row->{'genealogical'} = !( keys %$conflict );
199     return $variant_row;
200 }
201
202 # Add the variant, subject to a.c. representation logic.
203 # This assumes that we will see the 'main' version before the a.c. version.
204 sub add_variant_wit {
205     my( $arr, $wit, $acstr ) = @_;
206     my $skip;
207     if( $wit =~ /^(.*)\Q$acstr\E$/ ) {
208         my $real = $1;
209         $skip = grep { $_ =~ /^\Q$real\E$/ } @$arr;
210     } 
211     push( @$arr, $wit ) unless $skip;
212 }
213
214 # Return an answer if the variant is useful, i.e. if there are at least 2 variants
215 # with at least 2 witnesses each.
216 sub useful_variant {
217     my( $readings ) = @_;
218     my $total = keys %$readings;
219     foreach my $var ( keys %$readings ) {
220         $total-- if @{$readings->{$var}} == 1;
221     }
222     return( undef, undef ) if $total <= 1;
223     my( $groups, $text );
224     foreach my $var ( keys %$readings ) {
225         push( @$groups, $readings->{$var} );
226         push( @$text, $var );
227     }
228     return( $groups, $text );
229 }
230
231 # Take an array of witness groupings and produce a string like
232 # ['A','B'] / ['C','D','E'] / ['F']
233
234 sub wit_stringify {
235     my $groups = shift;
236     my @gst;
237     # If we were passed an array of witnesses instead of an array of 
238     # groupings, then "group" the witnesses first.
239     unless( ref( $groups->[0] ) ) {
240         my $mkgrp = [ $groups ];
241         $groups = $mkgrp;
242     }
243     foreach my $g ( @$groups ) {
244         push( @gst, '[' . join( ',', map { "'$_'" } @$g ) . ']' );
245     }
246     return join( ' / ', @gst );
247 }
248     
249 1;