some more look and feel tweaks
[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         # Our object needs to have a stemma graph and a variant table.
12         my( $title, $svg, $variants ) = run_analysis( $args->{'file'}, $args->{'stemmadot'} );
13         $self->{'svg'} = $svg;
14         $self->{'title'} = $title;
15         $self->{'variants'} = $variants;
16         
17         bless( $self, $class ); 
18         return $self;
19 }
20
21 sub run_analysis {
22         my( $file, $stemmadot ) = @_;
23         # What we will return
24         my $svg;
25         my $variants = [];
26         
27         # Read in the file and stemma   
28         my $tradition = Text::Tradition->new( 
29                 'input'  => 'Self',
30                 'file'   => $file,
31                 'linear' => 1,
32                 );
33         my $stemma = Text::Tradition::Stemma->new(
34                 'collation' => $tradition->collation,
35                 'dot' => $stemmadot,
36                 );
37         # We will return the stemma picture
38         $svg = $stemma->as_svg;
39         ### DIRTY HACK
40         $svg =~ s/transform=\"scale\(1 1\)/transform=\"scale\(0.7 0.7\)/;
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 $html_data = [];
52         my $total = 0; # Keep track of the total number of variant locations
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                 # Initialize the data structure for the row that we will return
94                 my $variant_row = {'id' => $rank, 'readings' => [] };
95                 # Keep track of our widest row
96                 $html_columns = scalar @$groups if scalar @$groups > $html_columns;
97                 
98                 # We can already look up witnesses for a reading; we also want to look
99                 # up readings for a given witness.
100                 my $group_readings = {};
101                 foreach my $x ( 0 .. $#$groups ) {
102                         $group_readings->{wit_stringify( $groups->[$x] )} = $readings->[$x];
103                 }
104                 
105                 # For all the groups with more than one member, collect the list of all
106                 # contiguous vertices needed to connect them.
107                 # TODO: deal with a.c. reading logic
108                 my $conflict = analyze_variant_location( $group_readings, $groups, $stemma->apsp );
109                 $variant_row->{'genealogical'} = keys %$conflict ? undef : 1;
110                 foreach my $grp ( sort keys %$group_readings ) {
111                         my $rdg = $group_readings->{$grp};
112                         my $in_conflict = exists $conflict->{$rdg};
113                         push( @{$variant_row->{'readings'}}, 
114                               { 'text' => $rdg, 'group' => $grp, 'conflict' => $in_conflict,
115                                 'missing' => wit_stringify( $lacunose ) } );
116                 }
117                 
118                 # Now run the same analysis given the calculated distance tree(s).
119 #               foreach my $tree ( 0 .. $#{$stemma->distance_trees} ) {
120 #                       my $dc = analyze_variant_location( $group_readings, $groups,    
121 #                                                                                          $stemma->distance_apsps->[$tree] );
122 #                       foreach my $rdg ( keys %$dc ) {
123 #                               my $var = $dc->{$rdg};
124 #                       }
125 #               }
126         
127                 # Record that we used this variant in an analysis
128                 push( @$variants, $variant_row );
129         }
130         
131         # Go through our variant rows and add the number of empty columns we need.
132         foreach my $row ( @$variants ) {
133                 my $empty = $html_columns - scalar @{$row->{'readings'}};
134                 $row->{'empty'} = $empty;
135         }
136         
137         return( $tradition->name, $svg, $variants );
138 }
139
140 sub analyze_variant_location {
141     my( $group_readings, $groups, $apsp ) = @_;
142     my %contig;
143     my $conflict = {};
144     foreach my $g ( sort { scalar @$b <=> scalar @$a } @$groups ) {
145         my @members = @$g;
146         my $gst = wit_stringify( $g );
147         map { $contig{$_} = $gst } @members; # The witnesses need themselves to be 
148                                              # in their collection.
149         next unless @members > 1;
150         my $curr = pop @members;
151         foreach my $m ( @members ) {
152             foreach my $v ( $apsp->path_vertices( $curr, $m ) ) {
153                 $contig{$v} = $gst unless exists $contig{$v};
154                 next if $contig{$v} eq $gst;
155                 # print STDERR "Conflict at $v between group $gst and group " 
156                 #     . $contig{$v} . "\n";
157                 # Record what is conflicting.
158                 $conflict->{$group_readings->{$gst}} = $group_readings->{$contig{$v}};
159             }
160         }
161     }
162     return $conflict;
163 }
164
165 # Add the variant, subject to a.c. representation logic.
166 # This assumes that we will see the 'main' version before the a.c. version.
167 sub add_variant_wit {
168     my( $arr, $wit, $acstr ) = @_;
169     my $skip;
170     if( $wit =~ /^(.*)\Q$acstr\E$/ ) {
171         my $real = $1;
172         $skip = grep { $_ =~ /^\Q$real\E$/ } @$arr;
173     } 
174     push( @$arr, $wit ) unless $skip;
175 }
176
177 # Return an answer if the variant is useful, i.e. if there are at least 2 variants
178 # with at least 2 witnesses each.
179 sub useful_variant {
180     my( $readings ) = @_;
181     my $total = keys %$readings;
182     foreach my $var ( keys %$readings ) {
183         $total-- if @{$readings->{$var}} == 1;
184     }
185     return( undef, undef ) if $total <= 1;
186     my( $groups, $text );
187     foreach my $var ( keys %$readings ) {
188         push( @$groups, $readings->{$var} );
189         push( @$text, $var );
190     }
191     return( $groups, $text );
192 }
193
194 # Take an array of witness groupings and produce a string like
195 # ['A','B'] / ['C','D','E'] / ['F']
196
197 sub wit_stringify {
198     my $groups = shift;
199     my @gst;
200     # If we were passed an array of witnesses instead of an array of 
201     # groupings, then "group" the witnesses first.
202     unless( ref( $groups->[0] ) ) {
203         my $mkgrp = [ $groups ];
204         $groups = $mkgrp;
205     }
206     foreach my $g ( @$groups ) {
207         push( @gst, '[' . join( ',', map { "'$_'" } @$g ) . ']' );
208     }
209     return join( ' / ', @gst );
210 }
211     
212 1;