lacuna nodes need to be marked as such on read
[scpubgit/stemmatology.git] / TreeOfTexts / lib / TreeOfTexts / Model / Analysis.pm
1 package TreeOfTexts::Model::Analysis;
2
3 use strict;
4 use warnings;
5 use Exporter 'import';
6 use Text::Tradition;
7 use Text::Tradition::Stemma;
8
9 use vars qw/ @EXPORT_OK /;
10 @EXPORT_OK = qw/ run_analysis /;
11
12 my $tradition; # Global for convenience, ew.
13 # Returns 
14 sub run_analysis {
15         my( $file, $stemmadot ) = @_;
16         # What we will return
17         my $svg;
18         my $variants = [];
19         
20         # Read in the file and stemma
21         my @lines;
22         open( INFILE, "$file" ) or die "Could not read $file";
23         binmode INFILE, ':utf8';
24         @lines = <INFILE>;
25         close INFILE;
26         
27         $tradition = Text::Tradition->new( 
28                 'Self' => join( '', @lines ),
29                 'linear' => 1,
30                 );
31         my $stemma = Text::Tradition::Stemma->new(
32                 'collation' => $tradition->collation,
33                 'dot' => $stemmadot,
34                 );
35         # We will return the stemma picture
36         $svg = $stemma->as_svg;
37         
38         # We have the collation, so get the alignment table with witnesses in rows.
39         # Also return the reading objects in the table, rather than just the words.
40         
41         my $all_wits_table = $tradition->collation->make_alignment_table( 'refs' );
42         
43         # For each column in the alignment table, we want to see if the existing
44         # groupings of witnesses match our stemma hypothesis. We also want, at the
45         # end, to produce an HTML table with all the variants.
46         my $html_columns = 0;
47         my $html_data = [];
48         my $total = 0; # Keep track of the total number of variant locations
49         
50         # Strip the list of sigla and save it for correlation to the readings.
51         my $col_wits = shift @$all_wits_table;
52         
53         # We will return a data structure, an array for each row that looks like:
54         # { id = X, genealogical = Y, readings = [ text = X, group = Y], empty = N }
55         foreach my $i ( 0 .. $#$all_wits_table ) {
56                 # For each column in the table, group the readings by witness.
57                 my $rdg_wits = {};
58                 my $col_rdgs = shift @$all_wits_table;
59                 my $rank;
60                 foreach my $j ( 0 .. $#{$col_rdgs} ) {
61                         my $rdg = $col_rdgs->[$j];
62                         $rank = $rdg->rank if $rdg && !$rank;  # Make a note of our rank
63                         my $rdg_text = '(omitted)';  # Initialize in case of empty reading
64                         if( $rdg ) {
65                                 $rdg_text = $rdg->is_lacuna ? undef : $rdg->text; # Don't count lacunae
66                         }
67                         if( defined $rdg_text ) {
68                                 # Initialize the witness array if we haven't got one yet
69                                 $rdg_wits->{$rdg_text} = [] unless $rdg_wits->{$rdg_text};
70                                 # Add the relevant witness, subject to a.c. logic
71                                 add_variant_wit( $rdg_wits->{$rdg_text}, $col_wits->[$j] );
72                         }
73                 }
74                 
75                 # See if this column has any potentially genealogical variants.
76                 # If not, skip to the next.
77                 $total++ unless scalar keys %$rdg_wits == 1;
78                 my( $groups, $readings ) = useful_variant( $rdg_wits );
79                 next unless $groups && $readings;  
80                 
81                 # Initialize the data structure for the row that we will return
82                 my $variant_row = {'id' => $rank, 'readings' => [] };
83                 # Keep track of our widest row
84                 $html_columns = scalar @$groups if scalar @$groups > $html_columns;
85                 
86                 # We can already look up witnesses for a reading; we also want to look
87                 # up readings for a given witness.
88                 my $group_readings = {};
89                 foreach my $x ( 0 .. $#$groups ) {
90                         $group_readings->{wit_stringify( $groups->[$x] )} = $readings->[$x];
91                 }
92                 
93                 # For all the groups with more than one member, collect the list of all
94                 # contiguous vertices needed to connect them.
95                 # TODO: deal with a.c. reading logic
96                 my $sc = analyze_variant_location( $group_readings, $groups, $stemma->apsp );
97                 $variant_row->{'genealogical'} = keys %$sc ? 1 : undef;
98                 foreach my $grp ( sort keys %$group_readings ) {
99                         my $rdg = $group_readings->{$grp};
100                         push( @{$variant_row->{'readings'}}, { 'text' => $rdg, 'group' => $grp } );
101                 }
102                 
103                 # Now run the same analysis given the calculated distance tree(s).
104 #               foreach my $tree ( 0 .. $#{$stemma->distance_trees} ) {
105 #                       my $dc = analyze_variant_location( $group_readings, $groups,    
106 #                                                                                          $stemma->distance_apsps->[$tree] );
107 #                       foreach my $rdg ( keys %$dc ) {
108 #                               my $var = $dc->{$rdg};
109 #                       }
110 #               }
111         
112                 # Record that we used this variant in an analysis
113                 push( @$variants, $variant_row );
114         }
115         
116         # Go through our variant rows and add the number of empty columns we need.
117         foreach my $row ( @$variants ) {
118                 my $empty = $html_columns - scalar @{$row->{'readings'}};
119                 $row->{'empty'} = $empty;
120         }
121         
122         return( $svg, $variants );
123 }
124
125 sub analyze_variant_location {
126     my( $group_readings, $groups, $apsp ) = @_;
127     my %contig;
128     my $conflict = {};
129     foreach my $g ( sort { scalar @$b <=> scalar @$a } @$groups ) {
130         my @members = @$g;
131         my $gst = wit_stringify( $g );
132         map { $contig{$_} = $gst } @members; # The witnesses need themselves to be 
133                                              # in their collection.
134         next unless @members > 1;
135         my $curr = pop @members;
136         foreach my $m ( @members ) {
137             foreach my $v ( $apsp->path_vertices( $curr, $m ) ) {
138                 $contig{$v} = $gst unless exists $contig{$v};
139                 next if $contig{$v} eq $gst;
140                 # print STDERR "Conflict at $v between group $gst and group " 
141                 #     . $contig{$v} . "\n";
142                 # Record what is conflicting.
143                 $conflict->{$group_readings->{$gst}} = $group_readings->{$contig{$v}};
144             }
145         }
146     }
147     return $conflict;
148 }
149
150 # Add the variant, subject to a.c. representation logic.
151 # This assumes that we will see the 'main' version before the a.c. version.
152 sub add_variant_wit {
153     my( $arr, $wit ) = @_;
154     my $acstr = $tradition->collation->ac_label;
155     my $skip;
156     if( $wit =~ /^(.*)\Q$acstr\E$/ ) {
157         my $real = $1;
158         $skip = grep { $_ =~ /^\Q$real\E$/ } @$arr;
159     } 
160     push( @$arr, $wit ) unless $skip;
161 }
162
163 # Return an answer if the variant is useful, i.e. if there are at least 2 variants
164 # with at least 2 witnesses each.
165 sub useful_variant {
166     my( $readings ) = @_;
167     my $total = keys %$readings;
168     foreach my $var ( keys %$readings ) {
169         $total-- if @{$readings->{$var}} == 1;
170     }
171     return( undef, undef ) if $total <= 1;
172     my( $groups, $text );
173     foreach my $var ( keys %$readings ) {
174         push( @$groups, $readings->{$var} );
175         push( @$text, $var );
176     }
177     return( $groups, $text );
178 }
179
180 # Take an array of witness groupings and produce a string like
181 # ['A','B'] / ['C','D','E'] / ['F']
182
183 sub wit_stringify {
184     my $groups = shift;
185     my @gst;
186     # If we were passed an array of witnesses instead of an array of 
187     # groupings, then "group" the witnesses first.
188     unless( ref( $groups->[0] ) ) {
189         my $mkgrp = [ $groups ];
190         $groups = $mkgrp;
191     }
192     foreach my $g ( @$groups ) {
193         push( @gst, '[' . join( ',', map { "'$_'" } @$g ) . ']' );
194     }
195     return join( ' / ', @gst );
196 }
197     
198 1;