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