fix acquisition of rank for row
[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( $svg, $variants ) = run_analysis( $args->{'file'}, $args->{'stemmadot'} );
13         $self->{'svg'} = $svg;
14         $self->{'variants'} = $variants;
15         
16         bless( $self, $class ); 
17         return $self;
18 }
19
20 sub run_analysis {
21         my( $file, $stemmadot ) = @_;
22         # What we will return
23         my $svg;
24         my $variants = [];
25         
26         # Read in the file and stemma
27         my @lines;
28         open( INFILE, "$file" ) or die "Could not read $file";
29         binmode INFILE, ':utf8';
30         @lines = <INFILE>;
31         close INFILE;
32         
33         my $tradition = Text::Tradition->new( 
34                 'Self' => join( '', @lines ),
35                 'linear' => 1,
36                 );
37         my $stemma = Text::Tradition::Stemma->new(
38                 'collation' => $tradition->collation,
39                 'dot' => $stemmadot,
40                 );
41         # We will return the stemma picture
42         $svg = $stemma->as_svg;
43         ### DIRTY HACK
44         $svg =~ s/transform=\"scale\(1 1\)/transform=\"scale\(0.7 0.7\)/;
45         
46         # We have the collation, so get the alignment table with witnesses in rows.
47         # Also return the reading objects in the table, rather than just the words.
48         
49         my $all_wits_table = $tradition->collation->make_alignment_table( 'refs' );
50         
51         # For each column in the alignment table, we want to see if the existing
52         # groupings of witnesses match our stemma hypothesis. We also want, at the
53         # end, to produce an HTML table with all the variants.
54         my $html_columns = 0;
55         my $html_data = [];
56         my $total = 0; # Keep track of the total number of variant locations
57         
58         # Strip the list of sigla and save it for correlation to the readings.
59         my $col_wits = shift @$all_wits_table;
60         
61         # We will return a data structure, an array for each row that looks like:
62         # { id = X, genealogical = Y, readings = [ text = X, group = Y], empty = N }
63         foreach my $i ( 0 .. $#$all_wits_table ) {
64                 # For each column in the table, group the readings by witness.
65                 my $rdg_wits = {};
66                 my $col_rdgs = shift @$all_wits_table;
67                 my $rank;
68                 foreach my $j ( 0 .. $#{$col_rdgs} ) {
69                         my $rdg = $col_rdgs->[$j];
70                         my $rdg_text = '(omitted)';  # Initialize in case of empty reading
71                         if( $rdg ) {
72                                 $rdg_text = $rdg->is_lacuna ? undef : $rdg->text; # Don't count lacunae
73                                 # Get the rank from any real reading; they should be identical.
74                                 $rank = $rdg->rank unless $rank || $rdg->is_lacuna;
75                         }
76                         if( defined $rdg_text ) {
77                                 # Initialize the witness array if we haven't got one yet
78                                 $rdg_wits->{$rdg_text} = [] unless $rdg_wits->{$rdg_text};
79                                 # Add the relevant witness, subject to a.c. logic
80                                 add_variant_wit( $rdg_wits->{$rdg_text}, $col_wits->[$j],
81                                         $tradition->collation->ac_label );
82                         }
83                 }
84                 
85                 # See if this column has any potentially genealogical variants.
86                 # If not, skip to the next.
87                 $total++ unless scalar keys %$rdg_wits == 1;
88                 my( $groups, $readings ) = useful_variant( $rdg_wits );
89                 next unless $groups && $readings;  
90                 
91                 # Initialize the data structure for the row that we will return
92                 my $variant_row = {'id' => $rank, 'readings' => [] };
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                 my $sc = analyze_variant_location( $group_readings, $groups, $stemma->apsp );
107                 $variant_row->{'genealogical'} = keys %$sc ? 1 : undef;
108                 foreach my $grp ( sort keys %$group_readings ) {
109                         my $rdg = $group_readings->{$grp};
110                         push( @{$variant_row->{'readings'}}, { 'text' => $rdg, 'group' => $grp } );
111                 }
112                 
113                 # Now run the same analysis given the calculated distance tree(s).
114 #               foreach my $tree ( 0 .. $#{$stemma->distance_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 #                       }
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 and add the number of empty columns we need.
127         foreach my $row ( @$variants ) {
128                 my $empty = $html_columns - scalar @{$row->{'readings'}};
129                 $row->{'empty'} = $empty;
130         }
131         
132         return( $svg, $variants );
133 }
134
135 sub analyze_variant_location {
136     my( $group_readings, $groups, $apsp ) = @_;
137     my %contig;
138     my $conflict = {};
139     foreach my $g ( sort { scalar @$b <=> scalar @$a } @$groups ) {
140         my @members = @$g;
141         my $gst = wit_stringify( $g );
142         map { $contig{$_} = $gst } @members; # The witnesses need themselves to be 
143                                              # in their collection.
144         next unless @members > 1;
145         my $curr = pop @members;
146         foreach my $m ( @members ) {
147             foreach my $v ( $apsp->path_vertices( $curr, $m ) ) {
148                 $contig{$v} = $gst unless exists $contig{$v};
149                 next if $contig{$v} eq $gst;
150                 # print STDERR "Conflict at $v between group $gst and group " 
151                 #     . $contig{$v} . "\n";
152                 # Record what is conflicting.
153                 $conflict->{$group_readings->{$gst}} = $group_readings->{$contig{$v}};
154             }
155         }
156     }
157     return $conflict;
158 }
159
160 # Add the variant, subject to a.c. representation logic.
161 # This assumes that we will see the 'main' version before the a.c. version.
162 sub add_variant_wit {
163     my( $arr, $wit, $acstr ) = @_;
164     my $skip;
165     if( $wit =~ /^(.*)\Q$acstr\E$/ ) {
166         my $real = $1;
167         $skip = grep { $_ =~ /^\Q$real\E$/ } @$arr;
168     } 
169     push( @$arr, $wit ) unless $skip;
170 }
171
172 # Return an answer if the variant is useful, i.e. if there are at least 2 variants
173 # with at least 2 witnesses each.
174 sub useful_variant {
175     my( $readings ) = @_;
176     my $total = keys %$readings;
177     foreach my $var ( keys %$readings ) {
178         $total-- if @{$readings->{$var}} == 1;
179     }
180     return( undef, undef ) if $total <= 1;
181     my( $groups, $text );
182     foreach my $var ( keys %$readings ) {
183         push( @$groups, $readings->{$var} );
184         push( @$text, $var );
185     }
186     return( $groups, $text );
187 }
188
189 # Take an array of witness groupings and produce a string like
190 # ['A','B'] / ['C','D','E'] / ['F']
191
192 sub wit_stringify {
193     my $groups = shift;
194     my @gst;
195     # If we were passed an array of witnesses instead of an array of 
196     # groupings, then "group" the witnesses first.
197     unless( ref( $groups->[0] ) ) {
198         my $mkgrp = [ $groups ];
199         $groups = $mkgrp;
200     }
201     foreach my $g ( @$groups ) {
202         push( @gst, '[' . join( ',', map { "'$_'" } @$g ) . ']' );
203     }
204     return join( ' / ', @gst );
205 }
206     
207 1;