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