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