6891065725ef93c13c4340b3b6eb4ae7dee5bb75
[scpubgit/stemmatology.git] / lib / Text / Tradition / Collation.pm
1 package Text::Tradition::Collation;
2
3 use Encode qw( decode_utf8 );
4 use File::Temp;
5 use Graph;
6 use IPC::Run qw( run binary );
7 use Text::CSV_XS;
8 use Text::Tradition::Collation::Reading;
9 use Text::Tradition::Collation::RelationshipStore;
10 use XML::LibXML;
11 use Moose;
12
13 has 'sequence' => (
14     is => 'ro',
15     isa => 'Graph',
16     default => sub { Graph->new() },
17     handles => {
18         paths => 'edges',
19     },
20     );
21     
22 has 'relations' => (
23         is => 'ro',
24         isa => 'Text::Tradition::Collation::RelationshipStore',
25         handles => {
26                 relationships => 'relationships',
27                 related_readings => 'related_readings',
28         },
29         writer => '_set_relations',
30         );
31
32 has 'tradition' => (
33     is => 'ro',
34     isa => 'Text::Tradition',
35     weak_ref => 1,
36     );
37
38 has 'readings' => (
39         isa => 'HashRef[Text::Tradition::Collation::Reading]',
40         traits => ['Hash'],
41     handles => {
42         reading     => 'get',
43         _add_reading => 'set',
44         del_reading => 'delete',
45         has_reading => 'exists',
46         readings   => 'values',
47     },
48     default => sub { {} },
49         );
50
51 has 'wit_list_separator' => (
52     is => 'rw',
53     isa => 'Str',
54     default => ', ',
55     );
56
57 has 'baselabel' => (
58     is => 'rw',
59     isa => 'Str',
60     default => 'base text',
61     );
62
63 has 'linear' => (
64     is => 'rw',
65     isa => 'Bool',
66     default => 1,
67     );
68
69 has 'ac_label' => (
70     is => 'rw',
71     isa => 'Str',
72     default => ' (a.c.)',
73     );
74     
75 has 'start' => (
76         is => 'ro',
77         isa => 'Text::Tradition::Collation::Reading',
78         writer => '_set_start',
79         weak_ref => 1,
80         );
81
82 has 'end' => (
83         is => 'ro',
84         isa => 'Text::Tradition::Collation::Reading',
85         writer => '_set_end',
86         weak_ref => 1,
87         );
88
89 # The collation can be created two ways:
90 # 1. Collate a set of witnesses (with CollateX I guess) and process
91 #    the results as in 2.
92 # 2. Read a pre-prepared collation in one of a variety of formats,
93 #    and make the graph from that.
94
95 # The graph itself will (for now) be immutable, and the positions
96 # within the graph will also be immutable.  We need to calculate those
97 # positions upon graph construction.  The equivalences between graph
98 # nodes will be mutable, entirely determined by the user (or possibly
99 # by some semantic pre-processing provided by the user.)  So the
100 # constructor should just make an empty equivalences object.  The
101 # constructor will also need to make the witness objects, if we didn't
102 # come through option 1.
103
104 sub BUILD {
105     my $self = shift;
106     $self->_set_relations( Text::Tradition::Collation::RelationshipStore->new( 'collation' => $self ) );
107     $self->_set_start( $self->add_reading( { 'collation' => $self, 'is_start' => 1 } ) );
108     $self->_set_end( $self->add_reading( { 'collation' => $self, 'is_end' => 1 } ) );
109 }
110
111 ### Reading construct/destruct functions
112
113 sub add_reading {
114         my( $self, $reading ) = @_;
115         unless( ref( $reading ) eq 'Text::Tradition::Collation::Reading' ) {
116                 my %args = %$reading;
117                 $reading = Text::Tradition::Collation::Reading->new( 
118                         'collation' => $self,
119                         %args );
120         }
121         # First check to see if a reading with this ID exists.
122         if( $self->reading( $reading->id ) ) {
123                 warn "Collation already has a reading with id " . $reading->id;
124                 return undef;
125         }
126         $self->_add_reading( $reading->id => $reading );
127         # Once the reading has been added, put it in both graphs.
128         $self->sequence->add_vertex( $reading->id );
129         $self->relations->add_reading( $reading->id );
130         return $reading;
131 };
132
133 around del_reading => sub {
134         my $orig = shift;
135         my $self = shift;
136         my $arg = shift;
137         
138         if( ref( $arg ) eq 'Text::Tradition::Collation::Reading' ) {
139                 $arg = $arg->id;
140         }
141         # Remove the reading from the graphs.
142         $self->sequence->delete_vertex( $arg );
143         $self->relations->delete_reading( $arg );
144         
145         # Carry on.
146         $self->$orig( $arg );
147 };
148
149 # merge_readings( $main, $to_be_deleted );
150
151 sub merge_readings {
152         my $self = shift;
153
154         # We only need the IDs for adding paths to the graph, not the reading
155         # objects themselves.
156     my( $kept, $deleted, $combine_char ) = $self->_stringify_args( @_ );
157
158     # The kept reading should inherit the paths and the relationships
159     # of the deleted reading.
160         foreach my $path ( $self->sequence->edges_at( $deleted ) ) {
161                 my @vector = ( $kept );
162                 push( @vector, $path->[1] ) if $path->[0] eq $deleted;
163                 unshift( @vector, $path->[0] ) if $path->[1] eq $deleted;
164                 next if $vector[0] eq $vector[1]; # Don't add a self loop
165                 my %wits = %{$self->sequence->get_edge_attributes( @$path )};
166                 $self->sequence->add_edge( @vector );
167                 my $fwits = $self->sequence->get_edge_attributes( @vector );
168                 @wits{keys %$fwits} = values %$fwits;
169                 $self->sequence->set_edge_attributes( @vector, \%wits );
170         }
171         $self->relations->merge_readings( $kept, $deleted, $combine_char );
172         
173         # Do the deletion deed.
174         if( $combine_char ) {
175                 my $kept_obj = $self->reading( $kept );
176                 my $new_text = join( $combine_char, $kept_obj->text, 
177                         $self->reading( $deleted )->text );
178                 $kept_obj->alter_text( $new_text );
179         }
180         $self->del_reading( $deleted );
181 }
182
183
184 # Helper function for manipulating the graph.
185 sub _stringify_args {
186         my( $self, $first, $second, $arg ) = @_;
187     $first = $first->id
188         if ref( $first ) eq 'Text::Tradition::Collation::Reading';
189     $second = $second->id
190         if ref( $second ) eq 'Text::Tradition::Collation::Reading';        
191     return( $first, $second, $arg );
192 }
193
194 ### Path logic
195
196 sub add_path {
197         my $self = shift;
198
199         # We only need the IDs for adding paths to the graph, not the reading
200         # objects themselves.
201     my( $source, $target, $wit ) = $self->_stringify_args( @_ );
202
203         # Connect the readings
204     $self->sequence->add_edge( $source, $target );
205     # Note the witness in question
206     $self->sequence->set_edge_attribute( $source, $target, $wit, 1 );
207 };
208
209 sub del_path {
210         my $self = shift;
211         my @args;
212         if( ref( $_[0] ) eq 'ARRAY' ) {
213                 my $e = shift @_;
214                 @args = ( @$e, @_ );
215         } else {
216                 @args = @_;
217         }
218
219         # We only need the IDs for adding paths to the graph, not the reading
220         # objects themselves.
221     my( $source, $target, $wit ) = $self->_stringify_args( @args );
222
223         if( $self->sequence->has_edge_attribute( $source, $target, $wit ) ) {
224                 $self->sequence->delete_edge_attribute( $source, $target, $wit );
225         }
226         unless( keys %{$self->sequence->get_edge_attributes( $source, $target )} ) {
227                 $self->sequence->delete_edge( $source, $target );
228         }
229 }
230
231
232 # Extra graph-alike utility
233 sub has_path {
234         my $self = shift;
235     my( $source, $target, $wit ) = $self->_stringify_args( @_ );
236         return undef unless $self->sequence->has_edge( $source, $target );
237         return $self->sequence->has_edge_attribute( $source, $target, $wit );
238 }
239
240 =head2 add_relationship( $reading1, $reading2, $definition )
241
242 Adds the specified relationship between the two readings.  A relationship
243 is transitive (i.e. undirected); the options for its definition may be found
244 in Text::Tradition::Collation::Relationship.
245
246 =cut
247
248 # Wouldn't it be lovely if edges could be objects, and all this type checking
249 # and attribute management could be done via Moose?
250
251 sub add_relationship {
252         my $self = shift;
253     my( $source, $target, $opts ) = $self->_stringify_args( @_ );
254     my( $ret, @vectors ) = $self->relations->add_relationship( $source, 
255         $self->reading( $source ), $target, $self->reading( $target ), $opts );
256     # Force a full rank recalculation every time. Yuck.
257     $self->calculate_ranks() if $ret && $self->end->has_rank;
258     return( $ret, @vectors );
259 }
260
261 =head2 reading_witnesses( $reading )
262
263 Return a list of sigils corresponding to the witnesses in which the reading appears.
264
265 =cut
266
267 sub reading_witnesses {
268         my( $self, $reading ) = @_;
269         # We need only check either the incoming or the outgoing edges; I have
270         # arbitrarily chosen "incoming".  Thus, special-case the start node.
271         if( $reading eq $self->start ) {
272                 return map { $_->sigil } $self->tradition->witnesses;
273         }
274         my %all_witnesses;
275         foreach my $e ( $self->sequence->edges_to( $reading ) ) {
276                 my $wits = $self->sequence->get_edge_attributes( @$e );
277                 @all_witnesses{ keys %$wits } = 1;
278         }
279         return keys %all_witnesses;
280 }
281
282 =head2 Output method(s)
283
284 =over
285
286 =item B<as_svg>
287
288 print $collation->as_svg();
289
290 Returns an SVG string that represents the graph, via as_dot and graphviz.
291
292 =cut
293
294 sub as_svg {
295     my( $self ) = @_;
296         
297     my @cmd = qw/dot -Tsvg/;
298     my( $svg, $err );
299     my $dotfile = File::Temp->new();
300     ## TODO REMOVE
301     # $dotfile->unlink_on_destroy(0);
302     binmode $dotfile, ':utf8';
303     print $dotfile $self->as_dot();
304     push( @cmd, $dotfile->filename );
305     run( \@cmd, ">", binary(), \$svg );
306     $svg = decode_utf8( $svg );
307     return $svg;
308 }
309
310 =item B<svg_subgraph>
311
312 print $collation->svg_subgraph( $from, $to )
313
314 Returns an SVG string that represents the portion of the graph given by the
315 specified range.  The $from and $to variables refer to ranks within the graph.
316
317 =cut
318
319 sub svg_subgraph {
320     my( $self, $from, $to ) = @_;
321     
322     my $dot = $self->as_dot( $from, $to );
323     unless( $dot ) {
324         warn "Could not output a graph with range $from - $to";
325         return;
326     }
327     
328     my @cmd = qw/dot -Tsvg/;
329     my( $svg, $err );
330     my $dotfile = File::Temp->new();
331     ## TODO REMOVE
332     # $dotfile->unlink_on_destroy(0);
333     binmode $dotfile, ':utf8';
334     print $dotfile $dot;
335     push( @cmd, $dotfile->filename );
336     run( \@cmd, ">", binary(), \$svg );
337     $svg = decode_utf8( $svg );
338     return $svg;
339 }
340
341
342 =item B<as_dot>
343
344 print $collation->as_dot();
345
346 Returns a string that is the collation graph expressed in dot
347 (i.e. GraphViz) format.  The 'view' argument determines what kind of
348 graph is produced.
349     * 'path': a graph of witness paths through the collation (DEFAULT)
350     * 'relationship': a graph of how collation readings relate to 
351       each other
352
353 =cut
354
355 sub as_dot {
356     my( $self, $startrank, $endrank ) = @_;
357     
358     # Check the arguments
359     if( $startrank ) {
360         return if $endrank && $startrank > $endrank;
361         return if $startrank > $self->end->rank;
362         }
363         if( defined $endrank ) {
364                 return if $endrank < 0;
365         }
366         
367     # TODO consider making some of these things configurable
368     my $graph_name = $self->tradition->name;
369     $graph_name =~ s/[^\w\s]//g;
370     $graph_name = join( '_', split( /\s+/, $graph_name ) );
371     my $dot = sprintf( "digraph %s {\n", $graph_name );
372     $dot .= "\tedge [ arrowhead=open ];\n";
373     $dot .= "\tgraph [ rankdir=LR,bgcolor=none ];\n";
374     $dot .= sprintf( "\tnode [ fontsize=%d, fillcolor=%s, style=%s, shape=%s ];\n",
375                      11, "white", "filled", "ellipse" );
376
377         # Output substitute start/end readings if necessary
378         if( $startrank ) {
379                 $dot .= "\t\"#SUBSTART#\" [ label=\"...\" ];\n";
380         }
381         if( $endrank ) {
382                 $dot .= "\t\"#SUBEND#\" [ label=\"...\" ];\n";  
383         }
384         my %used;  # Keep track of the readings that actually appear in the graph
385         my %subedges;
386         my %subend;
387     foreach my $reading ( $self->readings ) {
388         # Only output readings within our rank range.
389         next if $startrank && $reading->rank < $startrank;
390         next if $endrank && $reading->rank > $endrank;
391         $used{$reading->id} = 1;
392         $subedges{$reading->id} = '#SUBSTART#' 
393                 if $startrank && $startrank == $reading->rank;
394         $subedges{$reading->id} = '#SUBEND#' 
395                 if $endrank && $endrank == $reading->rank;
396         # Need not output nodes without separate labels
397         next if $reading->id eq $reading->text;
398         my $label = $reading->text;
399         $label =~ s/\"/\\\"/g;
400         $dot .= sprintf( "\t\"%s\" [ label=\"%s\" ];\n", $reading->id, $label );
401     }
402     
403     # Add substitute start and end edges if necessary
404     foreach my $node ( keys %subedges ) {
405                 my @vector = ( $subedges{$node}, $node );
406                 @vector = reverse( @vector ) if $vector[0] =~ /END/;
407         my $witstr = join( ', ', sort $self->reading_witnesses( $self->reading( $node ) ) );
408         my %variables = ( 'color' => '#000000',
409                           'fontcolor' => '#000000',
410                           'label' => $witstr,
411             );
412         my $varopts = join( ', ', map { $_.'="'.$variables{$_}.'"' } sort keys %variables );
413                 $dot .= sprintf( "\t\"%s\" -> \"%s\" [ %s ];\n", @vector, $varopts );
414         }
415         
416         # Add the real edges
417     my @edges = $self->paths;
418     foreach my $edge ( @edges ) {
419         # Do we need to output this edge?
420         if( $used{$edge->[0]} && $used{$edge->[1]} ) {;
421                         my %variables = ( 'color' => '#000000',
422                                                           'fontcolor' => '#000000',
423                                                           'label' => join( ', ', $self->path_display_label( $edge ) ),
424                                 );
425                         my $varopts = join( ', ', map { $_.'="'.$variables{$_}.'"' } sort keys %variables );
426                         # Account for the rank gap if necessary
427                         my $rankgap = $self->reading( $edge->[1] )->rank 
428                                 - $self->reading( $edge->[0] )->rank;
429                         $varopts .= ", minlen=$rankgap" if $rankgap > 1;
430                         $dot .= sprintf( "\t\"%s\" -> \"%s\" [ %s ];\n",
431                                                          $edge->[0], $edge->[1], $varopts );
432         }
433     }
434     
435     $dot .= "}\n";
436     return $dot;
437 }
438
439 sub path_witnesses {
440         my( $self, @edge ) = @_;
441         # If edge is an arrayref, cope.
442         if( @edge == 1 && ref( $edge[0] ) eq 'ARRAY' ) {
443                 my $e = shift @edge;
444                 @edge = @$e;
445         }
446         my @wits = keys %{$self->sequence->get_edge_attributes( @edge )};
447         return sort @wits;
448 }
449
450 sub path_display_label {
451         my( $self, $edge ) = @_;
452         my @wits = $self->path_witnesses( $edge );
453         my $maj = scalar( $self->tradition->witnesses ) * 0.6;
454         if( scalar @wits > $maj ) {
455                 return 'majority';
456         } else {
457                 return join( ', ', @wits );
458         }
459 }
460                 
461
462 =item B<as_graphml>
463
464 print $collation->as_graphml( $recalculate )
465
466 Returns a GraphML representation of the collation graph, with
467 transposition information and position information. Unless
468 $recalculate is passed (and is a true value), the method will return a
469 cached copy of the SVG after the first call to the method.
470
471 =cut
472
473 sub as_graphml {
474     my( $self ) = @_;
475
476     # Some namespaces
477     my $graphml_ns = 'http://graphml.graphdrawing.org/xmlns';
478     my $xsi_ns = 'http://www.w3.org/2001/XMLSchema-instance';
479     my $graphml_schema = 'http://graphml.graphdrawing.org/xmlns ' .
480         'http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd';
481
482     # Create the document and root node
483     my $graphml = XML::LibXML->createDocument( "1.0", "UTF-8" );
484     my $root = $graphml->createElementNS( $graphml_ns, 'graphml' );
485     $graphml->setDocumentElement( $root );
486     $root->setNamespace( $xsi_ns, 'xsi', 0 );
487     $root->setAttributeNS( $xsi_ns, 'schemaLocation', $graphml_schema );
488
489     # Add the data keys for the graph
490     my %graph_data_keys;
491     my $gdi = 0;
492     my @graph_attributes = qw/ version wit_list_separator baselabel linear ac_label /;
493     foreach my $datum ( @graph_attributes ) {
494         $graph_data_keys{$datum} = 'dg'.$gdi++;
495         my $key = $root->addNewChild( $graphml_ns, 'key' );
496         $key->setAttribute( 'attr.name', $datum );
497         $key->setAttribute( 'attr.type', $key eq 'linear' ? 'boolean' : 'string' );
498         $key->setAttribute( 'for', 'graph' );
499         $key->setAttribute( 'id', $graph_data_keys{$datum} );           
500     }
501
502     # Add the data keys for nodes
503     my %node_data_keys;
504     my $ndi = 0;
505     my %node_data = ( 
506         id => 'string',
507         text => 'string',
508         rank => 'string',
509         is_start => 'boolean',
510         is_end => 'boolean',
511         is_lacuna => 'boolean',
512         );
513     foreach my $datum ( keys %node_data ) {
514         $node_data_keys{$datum} = 'dn'.$ndi++;
515         my $key = $root->addNewChild( $graphml_ns, 'key' );
516         $key->setAttribute( 'attr.name', $datum );
517         $key->setAttribute( 'attr.type', $node_data{$datum} );
518         $key->setAttribute( 'for', 'node' );
519         $key->setAttribute( 'id', $node_data_keys{$datum} );
520     }
521
522     # Add the data keys for edges, i.e. witnesses
523     my $edi = 0;
524     my %edge_data_keys;
525     my %edge_data = (
526         class => 'string',                              # Class, deprecated soon
527         witness => 'string',                    # ID/label for a path
528         relationship => 'string',               # ID/label for a relationship
529         extra => 'boolean',                             # Path key
530         colocated => 'boolean',                 # Relationship key
531         non_correctable => 'boolean',   # Relationship key
532         non_independent => 'boolean',   # Relationship key
533         );
534     foreach my $datum ( keys %edge_data ) {
535         $edge_data_keys{$datum} = 'de'.$edi++;
536         my $key = $root->addNewChild( $graphml_ns, 'key' );
537         $key->setAttribute( 'attr.name', $datum );
538         $key->setAttribute( 'attr.type', $edge_data{$datum} );
539         $key->setAttribute( 'for', 'edge' );
540         $key->setAttribute( 'id', $edge_data_keys{$datum} );
541     }
542
543     # Add the collation graph itself
544     my $sgraph = $root->addNewChild( $graphml_ns, 'graph' );
545     $sgraph->setAttribute( 'edgedefault', 'directed' );
546     $sgraph->setAttribute( 'id', $self->tradition->name );
547     $sgraph->setAttribute( 'parse.edgeids', 'canonical' );
548     $sgraph->setAttribute( 'parse.edges', scalar($self->paths) );
549     $sgraph->setAttribute( 'parse.nodeids', 'canonical' );
550     $sgraph->setAttribute( 'parse.nodes', scalar($self->readings) );
551     $sgraph->setAttribute( 'parse.order', 'nodesfirst' );
552             
553     # Collation attribute data
554     foreach my $datum ( @graph_attributes ) {
555         my $value = $datum eq 'version' ? '3.0' : $self->$datum;
556                 _add_graphml_data( $sgraph, $graph_data_keys{$datum}, $value );
557         }
558
559     my $node_ctr = 0;
560     my %node_hash;
561     # Add our readings to the graph
562     foreach my $n ( sort { $a->id cmp $b->id } $self->readings ) {
563         # Add to the main graph
564         my $node_el = $sgraph->addNewChild( $graphml_ns, 'node' );
565         my $node_xmlid = 'n' . $node_ctr++;
566         $node_hash{ $n->id } = $node_xmlid;
567         $node_el->setAttribute( 'id', $node_xmlid );
568         foreach my $d ( keys %node_data ) {
569                 my $nval = $n->$d;
570                 _add_graphml_data( $node_el, $node_data_keys{$d}, $nval )
571                         if defined $nval;
572         }
573     }
574
575     # Add the path edges to the sequence graph
576     my $edge_ctr = 0;
577     foreach my $e ( sort { $a->[0] cmp $b->[0] } $self->sequence->edges() ) {
578         # We add an edge in the graphml for every witness in $e.
579         foreach my $wit ( $self->path_witnesses( $e ) ) {
580                         my( $id, $from, $to ) = ( 'e'.$edge_ctr++,
581                                                                                 $node_hash{ $e->[0] },
582                                                                                 $node_hash{ $e->[1] } );
583                         my $edge_el = $sgraph->addNewChild( $graphml_ns, 'edge' );
584                         $edge_el->setAttribute( 'source', $from );
585                         $edge_el->setAttribute( 'target', $to );
586                         $edge_el->setAttribute( 'id', $id );
587                         
588                         # It's a witness path, so add the witness
589                         my $base = $wit;
590                         my $key = $edge_data_keys{'witness'};
591                         # Is this an ante-corr witness?
592                         my $aclabel = $self->ac_label;
593                         if( $wit =~ /^(.*)\Q$aclabel\E$/ ) {
594                                 # Keep the base witness
595                                 $base = $1;
596                                 # ...and record that this is an 'extra' reading path
597                                 _add_graphml_data( $edge_el, $edge_data_keys{'extra'}, $aclabel );
598                         }
599                         _add_graphml_data( $edge_el, $edge_data_keys{'witness'}, $base );
600                         _add_graphml_data( $edge_el, $edge_data_keys{'class'}, 'path' );
601                 }
602         }
603         
604         # Add the relationship graph to the XML
605         $self->relations->as_graphml( $root );
606
607     # Save and return the thing
608     my $result = decode_utf8( $graphml->toString(1) );
609     return $result;
610 }
611
612 sub _add_graphml_data {
613     my( $el, $key, $value ) = @_;
614     return unless defined $value;
615     my $data_el = $el->addNewChild( $el->namespaceURI, 'data' );
616     $data_el->setAttribute( 'key', $key );
617     $data_el->appendText( $value );
618 }
619
620 =item B<as_csv>
621
622 print $collation->as_csv( $recalculate )
623
624 Returns a CSV alignment table representation of the collation graph, one
625 row per witness (or witness uncorrected.) 
626
627 =cut
628
629 sub as_csv {
630     my( $self ) = @_;
631     my $table = $self->make_alignment_table;
632     my $csv = Text::CSV_XS->new( { binary => 1, quote_null => 0 } );    
633     my @result;
634     # Make the header row
635     $csv->combine( map { $_->{'witness'} } @{$table->{'alignment'}} );
636         push( @result, decode_utf8( $csv->string ) );
637     # Make the rest of the rows
638     foreach my $idx ( 0 .. $table->{'length'} - 1 ) {
639         my @rowobjs = map { $_->{'tokens'}->[$idx] } @{$table->{'alignment'}};
640         my @row = map { $_ ? $_->{'t'} : $_ } @rowobjs;
641         $csv->combine( @row );
642         push( @result, decode_utf8( $csv->string ) );
643     }
644     return join( "\n", @result );
645 }
646
647 =item B<make_alignment_table>
648
649 my $table = $collation->make_alignment_table( $use_refs, \@wits_to_include )
650
651 Return a reference to an alignment table, in a slightly enhanced CollateX
652 format which looks like this:
653
654  $table = { alignment => [ { witness => "SIGIL", 
655                              tokens => [ { t => "READINGTEXT" }, ... ] },
656                            { witness => "SIG2", 
657                              tokens => [ { t => "READINGTEXT" }, ... ] },
658                            ... ],
659             length => TEXTLEN };
660
661 If $use_refs is set to 1, the reading object is returned in the table 
662 instead of READINGTEXT; if not, the text of the reading is returned.
663 If $wits_to_include is set to a hashref, only the witnesses whose sigil
664 keys have a true hash value will be included.
665
666 =cut
667
668 sub make_alignment_table {
669     my( $self, $noderefs, $include ) = @_;
670     unless( $self->linear ) {
671         warn "Need a linear graph in order to make an alignment table";
672         return;
673     }
674     my $table = { 'alignment' => [], 'length' => $self->end->rank - 1 };
675     my @all_pos = ( 1 .. $self->end->rank - 1 );
676     foreach my $wit ( sort { $a->sigil cmp $b->sigil } $self->tradition->witnesses ) {
677         if( $include ) {
678                 next unless $include->{$wit->sigil};
679         }
680         # print STDERR "Making witness row(s) for " . $wit->sigil . "\n";
681         my @wit_path = $self->reading_sequence( $self->start, $self->end, $wit->sigil );
682         my @row = _make_witness_row( \@wit_path, \@all_pos, $noderefs );
683         push( @{$table->{'alignment'}}, 
684                 { 'witness' => $wit->sigil, 'tokens' => \@row } );
685         if( $wit->is_layered ) {
686                 my @wit_ac_path = $self->reading_sequence( $self->start, $self->end, 
687                         $wit->sigil.$self->ac_label, $wit->sigil );
688             my @ac_row = _make_witness_row( \@wit_ac_path, \@all_pos, $noderefs );
689                         push( @{$table->{'alignment'}},
690                                 { 'witness' => $wit->sigil.$self->ac_label, 'tokens' => \@ac_row } );
691         }           
692     }
693         return $table;
694 }
695
696 sub _make_witness_row {
697     my( $path, $positions, $noderefs ) = @_;
698     my %char_hash;
699     map { $char_hash{$_} = undef } @$positions;
700     my $debug = 0;
701     foreach my $rdg ( @$path ) {
702         my $rtext = $rdg->text;
703         $rtext = '#LACUNA#' if $rdg->is_lacuna;
704         print STDERR "rank " . $rdg->rank . "\n" if $debug;
705         # print STDERR "No rank for " . $rdg->id . "\n" unless defined $rdg->rank;
706         $char_hash{$rdg->rank} = $noderefs ? { 't' => $rdg } 
707                                                                            : { 't' => $rtext };
708     }
709     my @row = map { $char_hash{$_} } @$positions;
710     # Fill in lacuna markers for undef spots in the row
711     my $last_el = shift @row;
712     my @filled_row = ( $last_el );
713     foreach my $el ( @row ) {
714         # If we are using node reference, make the lacuna node appear many times
715         # in the table.  If not, use the lacuna tag.
716         if( $last_el && _el_is_lacuna( $last_el ) && !defined $el ) {
717             $el = $noderefs ? $last_el : { 't' => '#LACUNA#' };
718         }
719         push( @filled_row, $el );
720         $last_el = $el;
721     }
722     return @filled_row;
723 }
724
725 # Tiny utility function to say if a table element is a lacuna
726 sub _el_is_lacuna {
727     my $el = shift;
728     return 1 if $el->{'t'} eq '#LACUNA#';
729     return 1 if ref( $el->{'t'} ) eq 'Text::Tradition::Collation::Reading'
730         && $el->{'t'}->is_lacuna;
731     return 0;
732 }
733
734 # Helper to turn the witnesses along columns rather than rows.  Assumes
735 # equal-sized rows.
736 sub _turn_table {
737     my( $table ) = @_;
738     my $result = [];
739     return $result unless scalar @$table;
740     my $nrows = scalar @{$table->[0]};
741     foreach my $idx ( 0 .. $nrows - 1 ) {
742         foreach my $wit ( 0 .. $#{$table} ) {
743             $result->[$idx]->[$wit] = $table->[$wit]->[$idx];
744         }
745     }
746     return $result;        
747 }
748
749 =back
750
751 =head2 Navigation methods
752
753 =over
754
755 =item B<start>
756
757 my $beginning = $collation->start();
758
759 Returns the beginning of the collation, a meta-reading with label '#START#'.
760
761 =item B<end>
762
763 my $end = $collation->end();
764
765 Returns the end of the collation, a meta-reading with label '#END#'.
766
767
768 =item B<reading_sequence>
769
770 my @readings = $collation->reading_sequence( $first, $last, $path[, $alt_path] );
771
772 Returns the ordered list of readings, starting with $first and ending
773 with $last, along the given witness path.  If no path is specified,
774 assume that the path is that of the base text (if any.)
775
776 =cut
777
778 # TODO Think about returning some lazy-eval iterator.
779
780 sub reading_sequence {
781     my( $self, $start, $end, $witness, $backup ) = @_;
782
783     $witness = $self->baselabel unless $witness;
784     my @readings = ( $start );
785     my %seen;
786     my $n = $start;
787     while( $n && $n->id ne $end->id ) {
788         if( exists( $seen{$n->id} ) ) {
789             warn "Detected loop at " . $n->id;
790             last;
791         }
792         $seen{$n->id} = 1;
793         
794         my $next = $self->next_reading( $n, $witness, $backup );
795         unless( $next ) {
796             warn "Did not find any path for $witness from reading " . $n->id;
797             last;
798         }
799         push( @readings, $next );
800         $n = $next;
801     }
802     # Check that the last reading is our end reading.
803     my $last = $readings[$#readings];
804     warn "Last reading found from " . $start->text .
805         " for witness $witness is not the end!"
806         unless $last->id eq $end->id;
807     
808     return @readings;
809 }
810
811 =item B<next_reading>
812
813 my $next_reading = $collation->next_reading( $reading, $witpath );
814
815 Returns the reading that follows the given reading along the given witness
816 path.  
817
818 =cut
819
820 sub next_reading {
821     # Return the successor via the corresponding path.
822     my $self = shift;
823     my $answer = $self->_find_linked_reading( 'next', @_ );
824         return undef unless $answer;
825     return $self->reading( $answer );
826 }
827
828 =item B<prior_reading>
829
830 my $prior_reading = $collation->prior_reading( $reading, $witpath );
831
832 Returns the reading that precedes the given reading along the given witness
833 path.  
834
835 =cut
836
837 sub prior_reading {
838     # Return the predecessor via the corresponding path.
839     my $self = shift;
840     my $answer = $self->_find_linked_reading( 'prior', @_ );
841     return $self->reading( $answer );
842 }
843
844 sub _find_linked_reading {
845     my( $self, $direction, $node, $path, $alt_path ) = @_;
846     my @linked_paths = $direction eq 'next' 
847         ? $self->sequence->edges_from( $node ) 
848         : $self->sequence->edges_to( $node );
849     return undef unless scalar( @linked_paths );
850     
851     # We have to find the linked path that contains all of the
852     # witnesses supplied in $path.
853     my( @path_wits, @alt_path_wits );
854     @path_wits = sort( $self->witnesses_of_label( $path ) ) if $path;
855     @alt_path_wits = sort( $self->witnesses_of_label( $alt_path ) ) if $alt_path;
856     my $base_le;
857     my $alt_le;
858     foreach my $le ( @linked_paths ) {
859         if( $self->sequence->has_edge_attribute( @$le, $self->baselabel ) ) {
860             $base_le = $le;
861         }
862                 my @le_wits = $self->path_witnesses( $le );
863                 if( _is_within( \@path_wits, \@le_wits ) ) {
864                         # This is the right path.
865                         return $direction eq 'next' ? $le->[1] : $le->[0];
866                 } elsif( _is_within( \@alt_path_wits, \@le_wits ) ) {
867                         $alt_le = $le;
868                 }
869     }
870     # Got this far? Return the alternate path if it exists.
871     return $direction eq 'next' ? $alt_le->[1] : $alt_le->[0]
872         if $alt_le;
873
874     # Got this far? Return the base path if it exists.
875     return $direction eq 'next' ? $base_le->[1] : $base_le->[0]
876         if $base_le;
877
878     # Got this far? We have no appropriate path.
879     warn "Could not find $direction node from " . $node->id 
880         . " along path $path";
881     return undef;
882 }
883
884 # Some set logic.
885 sub _is_within {
886     my( $set1, $set2 ) = @_;
887     my $ret = @$set1; # will be 0, i.e. false, if set1 is empty
888     foreach my $el ( @$set1 ) {
889         $ret = 0 unless grep { /^\Q$el\E$/ } @$set2;
890     }
891     return $ret;
892 }
893
894
895 ## INITIALIZATION METHODS - for use by parsers
896
897 # For use when a collation is constructed from a base text and an apparatus.
898 # We have the sequences of readings and just need to add path edges.
899 # When we are done, clear out the witness path attributes, as they are no
900 # longer needed.
901 # TODO Find a way to replace the witness path attributes with encapsulated functions?
902
903 sub make_witness_paths {
904     my( $self ) = @_;
905     foreach my $wit ( $self->tradition->witnesses ) {
906         # print STDERR "Making path for " . $wit->sigil . "\n";
907         $self->make_witness_path( $wit );
908     }
909 }
910
911 sub make_witness_path {
912     my( $self, $wit ) = @_;
913     my @chain = @{$wit->path};
914     my $sig = $wit->sigil;
915     foreach my $idx ( 0 .. $#chain-1 ) {
916         $self->add_path( $chain[$idx], $chain[$idx+1], $sig );
917     }
918     if( $wit->is_layered ) {
919         @chain = @{$wit->uncorrected_path};
920         foreach my $idx( 0 .. $#chain-1 ) {
921             my $source = $chain[$idx];
922             my $target = $chain[$idx+1];
923             $self->add_path( $source, $target, $sig.$self->ac_label )
924                 unless $self->has_path( $source, $target, $sig );
925         }
926     }
927     $wit->clear_path;
928     $wit->clear_uncorrected_path;
929 }
930
931 sub calculate_ranks {
932     my $self = shift;
933     # Walk a version of the graph where every node linked by a relationship 
934     # edge is fundamentally the same node, and do a topological ranking on
935     # the nodes in this graph.
936     my $topo_graph = Graph->new();
937     my %rel_containers;
938     my $rel_ctr = 0;
939     # Add the nodes
940     foreach my $r ( $self->readings ) {
941         next if exists $rel_containers{$r->id};
942         my @rels = $r->related_readings( 'colocated' );
943         if( @rels ) {
944             # Make a relationship container.
945             push( @rels, $r );
946             my $rn = 'rel_container_' . $rel_ctr++;
947             $topo_graph->add_vertex( $rn );
948             foreach( @rels ) {
949                 $rel_containers{$_->id} = $rn;
950             }
951         } else {
952             # Add a new node to mirror the old node.
953             $rel_containers{$r->id} = $r->id;
954             $topo_graph->add_vertex( $r->id );
955         }
956     }
957
958     # Add the edges.
959     foreach my $r ( $self->readings ) {
960         foreach my $n ( $self->sequence->successors( $r->id ) ) {
961                 my( $tfrom, $tto ) = ( $rel_containers{$r->id},
962                         $rel_containers{$n} );
963                 $DB::single = 1 unless $tfrom && $tto;
964             $topo_graph->add_edge( $tfrom, $tto );
965         }
966     }
967     
968     # Now do the rankings, starting with the start node.
969     my $topo_start = $rel_containers{$self->start->id};
970     my $node_ranks = { $topo_start => 0 };
971     my @curr_origin = ( $topo_start );
972     # A little iterative function.
973     while( @curr_origin ) {
974         @curr_origin = _assign_rank( $topo_graph, $node_ranks, @curr_origin );
975     }
976     # Transfer our rankings from the topological graph to the real one.
977     foreach my $r ( $self->readings ) {
978         if( defined $node_ranks->{$rel_containers{$r->id}} ) {
979             $r->rank( $node_ranks->{$rel_containers{$r->id}} );
980         } else {
981             $DB::single = 1;
982             die "No rank calculated for node " . $r->id 
983                 . " - do you have a cycle in the graph?";
984         }
985     }
986 }
987
988 sub _assign_rank {
989     my( $graph, $node_ranks, @current_nodes ) = @_;
990     # Look at each of the children of @current_nodes.  If all the child's 
991     # parents have a rank, assign it the highest rank + 1 and add it to 
992     # @next_nodes.  Otherwise skip it; we will return when the highest-ranked
993     # parent gets a rank.
994     my @next_nodes;
995     foreach my $c ( @current_nodes ) {
996         warn "Current reading $c has no rank!"
997             unless exists $node_ranks->{$c};
998         # print STDERR "Looking at child of node $c, rank " 
999         #     . $node_ranks->{$c} . "\n";
1000         foreach my $child ( $graph->successors( $c ) ) {
1001             next if exists $node_ranks->{$child};
1002             my $highest_rank = -1;
1003             my $skip = 0;
1004             foreach my $parent ( $graph->predecessors( $child ) ) {
1005                 if( exists $node_ranks->{$parent} ) {
1006                     $highest_rank = $node_ranks->{$parent} 
1007                         if $highest_rank <= $node_ranks->{$parent};
1008                 } else {
1009                     $skip = 1;
1010                     last;
1011                 }
1012             }
1013             next if $skip;
1014             my $c_rank = $highest_rank + 1;
1015             # print STDERR "Assigning rank $c_rank to node $child \n";
1016             $node_ranks->{$child} = $c_rank;
1017             push( @next_nodes, $child );
1018         }
1019     }
1020     return @next_nodes;
1021 }
1022
1023 # Another method to make up for rough collation methods.  If the same reading
1024 # appears multiple times at the same rank, collapse the nodes.
1025 sub flatten_ranks {
1026     my $self = shift;
1027     my %unique_rank_rdg;
1028     foreach my $rdg ( $self->readings ) {
1029         next unless $rdg->has_rank;
1030         my $key = $rdg->rank . "||" . $rdg->text;
1031         if( exists $unique_rank_rdg{$key} ) {
1032             # Combine!
1033             # print STDERR "Combining readings at same rank: $key\n";
1034             $self->merge_readings( $unique_rank_rdg{$key}, $rdg );
1035         } else {
1036             $unique_rank_rdg{$key} = $rdg;
1037         }
1038     }
1039 }
1040
1041
1042 ## Utility functions
1043     
1044 # Return the string that joins together a list of witnesses for
1045 # display on a single path.
1046 sub witnesses_of_label {
1047     my( $self, $label ) = @_;
1048     my $regex = $self->wit_list_separator;
1049     my @answer = split( /\Q$regex\E/, $label );
1050     return @answer;
1051 }    
1052
1053 =begin testing
1054
1055 use Text::Tradition;
1056
1057 my $cxfile = 't/data/Collatex-16.xml';
1058 my $t = Text::Tradition->new( 
1059     'name'  => 'inline', 
1060     'input' => 'CollateX',
1061     'file'  => $cxfile,
1062     );
1063 my $c = $t->collation;
1064
1065 is( $c->common_predecessor( $c->reading('n9'), $c->reading('n23') )->id, 
1066     'n20', "Found correct common predecessor" );
1067 is( $c->common_successor( $c->reading('n9'), $c->reading('n23') )->id, 
1068     '#END#', "Found correct common successor" );
1069
1070 is( $c->common_predecessor( $c->reading('n19'), $c->reading('n17') )->id, 
1071     'n16', "Found correct common predecessor for readings on same path" );
1072 is( $c->common_successor( $c->reading('n21'), $c->reading('n26') )->id, 
1073     '#END#', "Found correct common successor for readings on same path" );
1074
1075 =end testing
1076
1077 =cut
1078
1079 ## Return the closest reading that is a predecessor of both the given readings.
1080 sub common_predecessor {
1081         my $self = shift;
1082         return $self->common_in_path( @_, 'predecessors' );
1083 }
1084
1085 sub common_successor {
1086         my $self = shift;
1087         return $self->common_in_path( @_, 'successors' );
1088 }
1089
1090 sub common_in_path {
1091         my( $self, $r1, $r2, $dir ) = @_;
1092         my $iter = $r1->rank > $r2->rank ? $r1->rank : $r2->rank;
1093         $iter = $self->end->rank - $iter if $dir eq 'successors';
1094         my @candidates;
1095         my @last_checked = ( $r1, $r2 );
1096         my %all_seen;
1097         while( !@candidates ) {
1098                 my @new_lc;
1099                 foreach my $lc ( @last_checked ) {
1100                         foreach my $p ( $lc->$dir ) {
1101                                 if( $all_seen{$p->id} ) {
1102                                         push( @candidates, $p );
1103                                 } else {
1104                                         $all_seen{$p->id} = 1;
1105                                         push( @new_lc, $p );
1106                                 }
1107                         }
1108                 }
1109                 @last_checked = @new_lc;
1110         }
1111         my @answer = sort { $a->rank <=> $b->rank } @candidates;
1112         return $dir eq 'predecessors' ? pop( @answer ) : shift ( @answer );
1113 }
1114
1115 no Moose;
1116 __PACKAGE__->meta->make_immutable;
1117
1118 =head1 BUGS / TODO
1119
1120 =over
1121
1122 =item * Think about making Relationship objects again
1123
1124 =back