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