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