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