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