allow automatic sizing of stemma; put more data into the visualizer
[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         
45         my $all_wits_table = $tradition->collation->make_alignment_table( 'refs' );
46         
47         # For each column in the alignment table, we want to see if the existing
48         # groupings of witnesses match our stemma hypothesis. We also want, at the
49         # end, to produce an HTML table with all the variants.
50         my $html_columns = 0;
51         my ( $total, $genealogical, $conflicts ) = ( 0, 0, 0 );
52         
53         # Strip the list of sigla and save it for correlation to the readings.
54         my $col_wits = shift @$all_wits_table;
55         
56         # We will return a data structure, an array for each row that looks like:
57         # { id = X, genealogical = Y, readings = [ text = X, group = Y], empty = N }
58         foreach my $i ( 0 .. $#$all_wits_table ) {
59                 # For each column in the table, group the readings by witness.
60                 my $rdg_wits = {};
61                 my $col_rdgs = shift @$all_wits_table;
62                 my $rank;
63                 my $lacunose = [];
64                 foreach my $j ( 0 .. $#{$col_rdgs} ) {
65                         my $rdg = $col_rdgs->[$j];
66                         my $rdg_text = '(omitted)';  # Initialize in case of empty reading
67                         if( $rdg ) {
68                             if( $rdg->is_lacuna ) {
69                                 $rdg_text = undef;   # Don't count lacunae
70                                 push( @$lacunose, $col_wits->[$j] );
71                             } else {
72                                 $rdg_text = $rdg->text; 
73                                     # Get the rank from any real reading; they should be identical.
74                                     $rank = $rdg->rank;
75                                 }
76                         }
77                         if( defined $rdg_text ) {
78                                 # Initialize the witness array if we haven't got one yet
79                                 $rdg_wits->{$rdg_text} = [] unless $rdg_wits->{$rdg_text};
80                                 # Add the relevant witness, subject to a.c. logic
81                                 add_variant_wit( $rdg_wits->{$rdg_text}, $col_wits->[$j],
82                                         $tradition->collation->ac_label );
83                         }
84                 }
85                 
86                 # See if this column has any potentially genealogical variants.
87                 # If not, skip to the next.
88                 $total++ unless scalar keys %$rdg_wits == 1;
89                 my( $groups, $readings ) = useful_variant( $rdg_wits );
90                 next unless $groups && $readings;  
91                 
92                 # Keep track of our widest row
93                 $html_columns = scalar @$groups if scalar @$groups > $html_columns;
94                 
95                 # We can already look up witnesses for a reading; we also want to look
96                 # up readings for a given witness.
97                 my $group_readings = {};
98                 foreach my $x ( 0 .. $#$groups ) {
99                         $group_readings->{wit_stringify( $groups->[$x] )} = $readings->[$x];
100                 }
101                 
102                 # For all the groups with more than one member, collect the list of all
103                 # contiguous vertices needed to connect them.
104                 # TODO: deal with a.c. reading logic
105                 my $variant_row = analyze_variant_location( $group_readings, $groups, 
106                     $stemma->apsp, $lacunose );
107                 $variant_row->{'id'} = $rank;
108                 $genealogical++ if $variant_row->{'genealogical'};
109                 $conflicts += grep { $_->{'conflict'} } @{$variant_row->{'readings'}};
110
111                 # Now run the same analysis given the calculated distance tree(s).
112 #               my @trees = @{$stemma->distance_trees};
113 #               if( @trees ) {
114 #             foreach my $tree ( 0 .. $#trees ) {
115 #                 my $dc = analyze_variant_location( $group_readings, $groups,    
116 #                                                    $stemma->distance_apsps->[$tree] );
117 #                 foreach my $rdg ( keys %$dc ) {
118 #                     my $var = $dc->{$rdg};
119 #                     # TODO Do something with this
120 #                 }
121 #             }
122 #           }
123
124                 # Record that we used this variant in an analysis
125                 push( @$variants, $variant_row );
126         }
127         
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.
130         foreach my $row ( @$variants ) {
131                 my $empty = $html_columns - scalar @{$row->{'readings'}};
132                 $row->{'empty'} = $empty;
133         }
134         
135         # Populate self with our analysis data.
136         $data->{'variants'} = $variants;
137         $data->{'variant_count'} = $total;
138         $data->{'conflict_count'} = $conflicts;
139         $data->{'genealogical_count'} = $genealogical;
140         push( @{$self->{'data'}}, $data );
141 }
142
143 # variant_row -> genealogical
144 #             -> readings [ { text, group, conflict, missing } ]
145
146 sub analyze_variant_location {
147     my( $group_readings, $groups, $apsp, $lacunose ) = @_;
148     my %contig;
149     my $conflict = {};
150     my %missing;
151     map { $missing{$_} = 1 } @$lacunose;
152     my $variant_row = { 'readings' => [] };
153     foreach my $g ( sort { scalar @$b <=> scalar @$a } @$groups ) {
154         my @members = @$g;
155         my $gst = wit_stringify( $g ); # $gst is now the name of this group.
156         map { $contig{$_} = $gst } @members; # All members are in this group.
157         while( @members ) {
158             # Gather the list of vertices that are needed to join all members.
159             my $curr = pop @members;
160             foreach my $m ( @members ) {
161                 foreach my $v ( $apsp->path_vertices( $curr, $m ) ) {
162                     $contig{$v} = $gst unless exists $contig{$v};
163                     next if $contig{$v} eq $gst;
164                     # Record what is conflicting. TODO do we use this?
165                     $conflict->{$group_readings->{$gst}} = $group_readings->{$contig{$v}};
166                 }
167             }
168         }
169         # Write the reading.
170         my $reading = { 'text' => $group_readings->{$gst},
171                         'missing' => wit_stringify( $lacunose ),
172                         'conflict' => exists( $conflict->{$group_readings->{$gst}} ) };
173         if( $reading->{'conflict'} ) {
174             $reading->{'group'} = $gst;
175         } else {
176             my @all_vertices = grep { $contig{$_} eq $gst && !$missing{$_} } keys %contig;
177             $reading->{'group'} = wit_stringify( \@all_vertices );
178         }
179         push( @{$variant_row->{'readings'}}, $reading );
180     }
181     $variant_row->{'genealogical'} = keys %$conflict ? undef : 1;
182     return $variant_row;
183 }
184
185 # Add the variant, subject to a.c. representation logic.
186 # This assumes that we will see the 'main' version before the a.c. version.
187 sub add_variant_wit {
188     my( $arr, $wit, $acstr ) = @_;
189     my $skip;
190     if( $wit =~ /^(.*)\Q$acstr\E$/ ) {
191         my $real = $1;
192         $skip = grep { $_ =~ /^\Q$real\E$/ } @$arr;
193     } 
194     push( @$arr, $wit ) unless $skip;
195 }
196
197 # Return an answer if the variant is useful, i.e. if there are at least 2 variants
198 # with at least 2 witnesses each.
199 sub useful_variant {
200     my( $readings ) = @_;
201     my $total = keys %$readings;
202     foreach my $var ( keys %$readings ) {
203         $total-- if @{$readings->{$var}} == 1;
204     }
205     return( undef, undef ) if $total <= 1;
206     my( $groups, $text );
207     foreach my $var ( keys %$readings ) {
208         push( @$groups, $readings->{$var} );
209         push( @$text, $var );
210     }
211     return( $groups, $text );
212 }
213
214 # Take an array of witness groupings and produce a string like
215 # ['A','B'] / ['C','D','E'] / ['F']
216
217 sub wit_stringify {
218     my $groups = shift;
219     my @gst;
220     # If we were passed an array of witnesses instead of an array of 
221     # groupings, then "group" the witnesses first.
222     unless( ref( $groups->[0] ) ) {
223         my $mkgrp = [ $groups ];
224         $groups = $mkgrp;
225     }
226     foreach my $g ( @$groups ) {
227         push( @gst, '[' . join( ',', map { "'$_'" } @$g ) . ']' );
228     }
229     return join( ' / ', @gst );
230 }
231     
232 1;