aa0680a77e0e6b4edb27860c43bc0c8902f0de67
[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' => (
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 = Text::Tradition::Collation::Relationship->new( %$options );
229     $self->graph->add_edge( $source, $target, $rel );
230     if( $options->{'global'} ) {
231         # Look for all readings with the source label, and if there are
232         # colocated readings with the target label, join them too.
233         foreach my $r ( grep { $_->label eq $source->label } $self->readings() ) {
234             next if $r->name eq $source->name;
235             my @colocated = grep { $_->label eq $target->label }
236                 $self->same_position_as( $r );
237             if( @colocated ) {
238                 warn "Multiple readings with same label at same position!"
239                     if @colocated > 1;
240                 my $colo = $colocated[0];
241                 next if $colo->edges_to( $r ) || $r->edges_to( $colo );
242                 $options->{'primary_relation'} = $options->{'this_relation'};
243                 $options->{'this_relation'} = [ $r, $colocated[0] ];
244                 my $dup_rel = Text::Tradition::Collation::Relationship->new( %$options );
245                 $self->graph->add_edge( $r, $colocated[0], $dup_rel );
246                 push( @joined, [ $r->name, $colocated[0]->name ] );
247             }
248         }
249     }
250     return( 1, @joined );
251 }
252
253 =head2 Output method(s)
254
255 =over
256
257 =item B<as_svg>
258
259 print $graph->as_svg( $recalculate );
260
261 Returns an SVG string that represents the graph.  Uses GraphViz to do
262 this, because Graph::Easy doesn\'t cope well with long graphs. Unless
263 $recalculate is passed (and is a true value), the method will return a
264 cached copy of the SVG after the first call to the method.
265
266 =cut
267
268 sub as_svg {
269     my( $self, $recalc ) = @_;
270     return $self->svg if $self->has_svg;
271     
272     $self->collapse_graph_paths();
273     
274     my @cmd = qw/dot -Tsvg/;
275     my( $svg, $err );
276     my $in = $self->as_dot();
277     run( \@cmd, \$in, ">", binary(), \$svg );
278     $self->_save_svg( $svg );
279     $self->expand_graph_paths();
280     return $svg;
281 }
282
283 =item B<as_dot>
284
285 print $graph->as_dot( $view, $recalculate );
286
287 Returns a string that is the collation graph expressed in dot
288 (i.e. GraphViz) format.  The 'view' argument determines what kind of
289 graph is produced.
290     * 'path': a graph of witness paths through the collation (DEFAULT)
291     * 'relationship': a graph of how collation readings relate to 
292       each other
293
294 =cut
295
296 sub as_dot {
297     my( $self, $view ) = @_;
298     $view = 'path' unless $view;
299     # TODO consider making some of these things configurable
300     my $dot = sprintf( "digraph %s {\n", $self->tradition->name );
301     $dot .= "\tedge [ arrowhead=open ];\n";
302     $dot .= "\tgraph [ rankdir=LR ];\n";
303     $dot .= sprintf( "\tnode [ fontsize=%d, fillcolor=%s, style=%s, shape=%s ];\n",
304                      11, "white", "filled", $self->graph->get_attribute( 'node', 'shape' ) );
305
306     foreach my $reading ( $self->readings ) {
307         # Need not output nodes without separate labels
308         next if $reading->name eq $reading->label;
309         # TODO output readings or segments, but not both
310         next if $reading->class eq 'node.segment';
311         $dot .= sprintf( "\t\"%s\" [ label=\"%s\" ]\n", $reading->name, $reading->label );
312     }
313
314     my @edges = $view eq 'relationship' ? $self->relationships : $self->paths;
315     foreach my $edge ( @edges ) {
316         $dot .= sprintf( "\t\"%s\" -> \"%s\" [ color=\"%s\", fontcolor=\"%s\", label=\"%s\" ]\n",
317                          $edge->from->name, $edge->to->name, '#000000', '#000000', $edge->label );
318     }
319
320     $dot .= "}\n";
321     return $dot;
322 }
323
324 =item B<as_graphml>
325
326 print $graph->as_graphml( $recalculate )
327
328 Returns a GraphML representation of the collation graph, with
329 transposition information and position information. Unless
330 $recalculate is passed (and is a true value), the method will return a
331 cached copy of the SVG after the first call to the method.
332
333 =cut
334
335 sub as_graphml {
336     my( $self, $recalc ) = @_;
337     return $self->graphml if $self->has_graphml;
338
339     # Some namespaces
340     my $graphml_ns = 'http://graphml.graphdrawing.org/xmlns';
341     my $xsi_ns = 'http://www.w3.org/2001/XMLSchema-instance';
342     my $graphml_schema = 'http://graphml.graphdrawing.org/xmlns ' .
343         'http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd';
344
345     # Create the document and root node
346     my $graphml = XML::LibXML->createDocument( "1.0", "UTF-8" );
347     my $root = $graphml->createElementNS( $graphml_ns, 'graphml' );
348     $graphml->setDocumentElement( $root );
349     $root->setNamespace( $xsi_ns, 'xsi', 0 );
350     $root->setAttributeNS( $xsi_ns, 'schemaLocation', $graphml_schema );
351
352     # Add the data keys for nodes
353     my %node_data_keys;
354     my $ndi = 0;
355     foreach my $datum ( qw/ name reading identical position class / ) {
356         $node_data_keys{$datum} = 'dn'.$ndi++;
357         my $key = $root->addNewChild( $graphml_ns, 'key' );
358         $key->setAttribute( 'attr.name', $datum );
359         $key->setAttribute( 'attr.type', 'string' );
360         $key->setAttribute( 'for', 'node' );
361         $key->setAttribute( 'id', $node_data_keys{$datum} );
362     }
363
364     # Add the data keys for edges, i.e. witnesses
365     my $edi = 0;
366     my %edge_data_keys;
367     foreach my $edge_key( qw/ witness_main witness_ante_corr relationship class / ) {
368         $edge_data_keys{$edge_key} = 'de'.$edi++;
369         my $key = $root->addNewChild( $graphml_ns, 'key' );
370         $key->setAttribute( 'attr.name', $edge_key );
371         $key->setAttribute( 'attr.type', 'string' );
372         $key->setAttribute( 'for', 'edge' );
373         $key->setAttribute( 'id', $edge_data_keys{$edge_key} );
374     }
375     
376     # Add the graph, its nodes, and its edges
377     my $graph = $root->addNewChild( $graphml_ns, 'graph' );
378     $graph->setAttribute( 'edgedefault', 'directed' );
379     $graph->setAttribute( 'id', 'g0' ); # TODO make this meaningful
380     $graph->setAttribute( 'parse.edgeids', 'canonical' );
381     $graph->setAttribute( 'parse.edges', scalar($self->paths) );
382     $graph->setAttribute( 'parse.nodeids', 'canonical' );
383     $graph->setAttribute( 'parse.nodes', scalar($self->readings) );
384     $graph->setAttribute( 'parse.order', 'nodesfirst' );
385
386     my $node_ctr = 0;
387     my %node_hash;
388     # Add our readings to the graph
389     foreach my $n ( sort { $a->name cmp $b->name } $self->readings ) {
390         my $node_el = $graph->addNewChild( $graphml_ns, 'node' );
391         my $node_xmlid = 'n' . $node_ctr++;
392         $node_hash{ $n->name } = $node_xmlid;
393         $node_el->setAttribute( 'id', $node_xmlid );
394         _add_graphml_data( $node_el, $node_data_keys{'name'}, $n->name );
395         _add_graphml_data( $node_el, $node_data_keys{'reading'}, $n->label );
396         _add_graphml_data( $node_el, $node_data_keys{'position'}, $n->position );
397         _add_graphml_data( $node_el, $node_data_keys{'class'}, $n->sub_class );
398         _add_graphml_data( $node_el, $node_data_keys{'identical'}, $n->primary->name )
399             if $n->has_primary;
400     }
401
402     # Add any segments we have
403     foreach my $n ( sort { $a->name cmp $b->name } $self->segments ) {
404         my $node_el = $graph->addNewChild( $graphml_ns, 'node' );
405         my $node_xmlid = 'n' . $node_ctr++;
406         $node_hash{ $n->name } = $node_xmlid;
407         $node_el->setAttribute( 'id', $node_xmlid );
408         _add_graphml_data( $node_el, $node_data_keys{'class'}, $n->sub_class );
409         _add_graphml_data( $node_el, $node_data_keys{'name'}, $n->name );
410     }
411
412     # Add the path, relationship, and segment edges
413     my $edge_ctr = 0;
414     foreach my $e ( sort { $a->from->name cmp $b->from->name } $self->graph->edges() ) {
415         my( $name, $from, $to ) = ( 'e'.$edge_ctr++,
416                                     $node_hash{ $e->from->name() },
417                                     $node_hash{ $e->to->name() } );
418         my $edge_el = $graph->addNewChild( $graphml_ns, 'edge' );
419         $edge_el->setAttribute( 'source', $from );
420         $edge_el->setAttribute( 'target', $to );
421         $edge_el->setAttribute( 'id', $name );
422         # Add the edge class
423         _add_graphml_data( $edge_el, $edge_data_keys{'class'}, $e->sub_class );
424         if( $e->sub_class eq 'path' ) {
425             # It's a witness path, so add the witness
426             my $base = $e->label;
427             my $key = $edge_data_keys{'witness_main'};
428             # TODO kind of hacky
429             if( $e->label =~ /^(.*?)\s+(\(a\.c\.\))$/ ) {
430                 $base = $1;
431                 $key = $edge_data_keys{'witness_ante_corr'};
432             }
433             _add_graphml_data( $edge_el, $key, $base );
434         } elsif( $e->sub_class eq 'relationship' ) {
435             # It's a relationship
436             _add_graphml_data( $edge_el, $edge_data_keys{'relationship'}, $e->label );
437         } # else a segment, nothing to record but source, target, class
438     }
439
440     # Return the thing
441     $self->_save_graphml( $graphml->toString(1) );
442     return $graphml->toString(1);
443 }
444
445 sub _add_graphml_data {
446     my( $el, $key, $value ) = @_;
447     my $data_el = $el->addNewChild( $el->namespaceURI, 'data' );
448     return unless defined $value;
449     $data_el->setAttribute( 'key', $key );
450     $data_el->appendText( $value );
451 }
452
453 sub collapse_graph_paths {
454     my $self = shift;
455     # Our collation graph has an path per witness.  This is great for
456     # calculation purposes, but terrible for display.  Thus we want to
457     # display only one path between any two nodes.
458
459     return if $self->collapsed;
460
461     print STDERR "Collapsing witness paths in graph...\n";
462
463     # Don't list out every witness if we have more than half to list.
464     my $majority = int( scalar( @{$self->tradition->witnesses} ) / 2 ) + 1;
465     # But don't compress if there are only a few witnesses.
466     $majority = 4 if $majority < 4;
467     foreach my $node ( $self->readings ) {
468         my $newlabels = {};
469         # We will visit each node, so we only look ahead.
470         foreach my $edge ( $node->outgoing() ) {
471             next unless $edge->class eq 'edge.path';
472             add_hash_entry( $newlabels, $edge->to->name, $edge->name );
473             $self->del_path( $edge );
474         }
475
476         foreach my $newdest ( keys %$newlabels ) {
477             my $label;
478             my @compressed_wits = ();
479             if( @{$newlabels->{$newdest}} < $majority ) {
480                 $label = join( ', ', sort( @{$newlabels->{$newdest}} ) );
481             } else {
482                 ## TODO FIX THIS HACK
483                 my @aclabels;
484                 foreach my $wit ( @{$newlabels->{$newdest}} ) {
485                     if( $wit =~ /^(.*?)(\s*\(?a\.\s*c\.\)?)$/ ) {
486                         push( @aclabels, $wit );
487                     } else {
488                         push( @compressed_wits, $wit );
489                     }
490                 }
491                 $label = join( ', ', 'majority', sort( @aclabels ) );
492             }
493             
494             my $newpath = 
495                 $self->add_path( $node, $self->reading( $newdest ), $label );
496             if( @compressed_wits ) {
497                 $newpath->hidden_witnesses( \@compressed_wits );
498             }
499         }
500     }
501
502     $self->collapsed( 1 );
503 }
504
505 sub expand_graph_paths {
506     my $self = shift;
507     # Our collation graph has only one path between any two nodes.
508     # This is great for display, but not so great for analysis.
509     # Expand this so that each witness has its own path between any
510     # two reading nodes.
511     return unless $self->collapsed;
512     
513     print STDERR "Expanding witness paths in graph...\n";
514     foreach my $path( $self->paths ) {
515         my $from = $path->from;
516         my $to = $path->to;
517         my @wits = split( /, /, $path->label );
518         if( $path->has_hidden_witnesses ) {
519             push( @wits, @{$path->hidden_witnesses} );
520         }
521         $self->del_path( $path );
522         foreach ( @wits ) {
523             $self->add_path( $from, $to, $_ );
524         }
525     }
526     $self->collapsed( 0 );
527 }
528
529 =back
530
531 =head2 Navigation methods
532
533 =over
534
535 =item B<start>
536
537 my $beginning = $collation->start();
538
539 Returns the beginning of the collation, a meta-reading with label '#START#'.
540
541 =cut
542
543 sub start {
544     # Return the beginning reading of the graph.
545     my $self = shift;
546     my( $new_start ) = @_;
547     if( $new_start ) {
548         $self->del_reading( '#START#' );
549         $self->graph->rename_node( $new_start, '#START#' );
550     }
551     return $self->reading('#START#');
552 }
553
554 =item B<reading_sequence>
555
556 my @readings = $graph->reading_sequence( $first, $last, $path[, $alt_path] );
557
558 Returns the ordered list of readings, starting with $first and ending
559 with $last, along the given witness path.  If no path is specified,
560 assume that the path is that of the base text (if any.)
561
562 =cut
563
564 sub reading_sequence {
565     my( $self, $start, $end, $witness, $backup ) = @_;
566
567     $witness = $self->baselabel unless $witness;
568     my @readings = ( $start );
569     my %seen;
570     my $n = $start;
571     while( $n && $n ne $end ) {
572         if( exists( $seen{$n->name()} ) ) {
573             warn "Detected loop at " . $n->name();
574             last;
575         }
576         $seen{$n->name()} = 1;
577         
578         my $next = $self->next_reading( $n, $witness, $backup );
579         warn "Did not find any path for $witness from reading " . $n->name
580             unless $next;
581         push( @readings, $next );
582         $n = $next;
583     }
584     # Check that the last reading is our end reading.
585     my $last = $readings[$#readings];
586     warn "Last reading found from " . $start->label() .
587         " for witness $witness is not the end!"
588         unless $last eq $end;
589     
590     return @readings;
591 }
592
593 =item B<next_reading>
594
595 my $next_reading = $graph->next_reading( $reading, $witpath );
596
597 Returns the reading that follows the given reading along the given witness
598 path.  
599
600 =cut
601
602 sub next_reading {
603     # Return the successor via the corresponding path.
604     my $self = shift;
605     return $self->_find_linked_reading( 'next', @_ );
606 }
607
608 =item B<prior_reading>
609
610 my $prior_reading = $graph->prior_reading( $reading, $witpath );
611
612 Returns the reading that precedes the given reading along the given witness
613 path.  
614
615 =cut
616
617 sub prior_reading {
618     # Return the predecessor via the corresponding path.
619     my $self = shift;
620     return $self->_find_linked_reading( 'prior', @_ );
621 }
622
623 sub _find_linked_reading {
624     my( $self, $direction, $node, $path, $alt_path ) = @_;
625     my @linked_paths = $direction eq 'next' 
626         ? $node->outgoing() : $node->incoming();
627     return undef unless scalar( @linked_paths );
628     
629     # We have to find the linked path that contains all of the
630     # witnesses supplied in $path.
631     my( @path_wits, @alt_path_wits );
632     @path_wits = $self->witnesses_of_label( $path ) if $path;
633     @alt_path_wits = $self->witnesses_of_label( $alt_path ) if $alt_path;
634     my $base_le;
635     my $alt_le;
636     foreach my $le ( @linked_paths ) {
637         if( $le->name eq $self->baselabel ) {
638             $base_le = $le;
639         } else {
640             my @le_wits = $self->witnesses_of_label( $le->name );
641             if( _is_within( \@path_wits, \@le_wits ) ) {
642                 # This is the right path.
643                 return $direction eq 'next' ? $le->to() : $le->from();
644             } elsif( _is_within( \@alt_path_wits, \@le_wits ) ) {
645                 $alt_le = $le;
646             }
647         }
648     }
649     # Got this far? Return the alternate path if it exists.
650     return $direction eq 'next' ? $alt_le->to() : $alt_le->from()
651         if $alt_le;
652
653     # Got this far? Return the base path if it exists.
654     return $direction eq 'next' ? $base_le->to() : $base_le->from()
655         if $base_le;
656
657     # Got this far? We have no appropriate path.
658     warn "Could not find $direction node from " . $node->label 
659         . " along path $path";
660     return undef;
661 }
662
663 # Some set logic.
664 sub _is_within {
665     my( $set1, $set2 ) = @_;
666     my $ret = @$set1; # will be 0, i.e. false, if set1 is empty
667     foreach my $el ( @$set1 ) {
668         $ret = 0 unless grep { /^\Q$el\E$/ } @$set2;
669     }
670     return $ret;
671 }
672
673
674 ## INITIALIZATION METHODS - for use by parsers
675 # Walk the paths for each witness in the graph, and return the nodes
676 # that the graph has in common.  If $using_base is true, some 
677 # different logic is needed.
678
679 sub walk_witness_paths {
680     my( $self, $end ) = @_;
681     # For each witness, walk the path through the graph.
682     # Then we need to find the common nodes.  
683     # TODO This method is going to fall down if we have a very gappy 
684     # text in the collation.
685     my $paths = {};
686     my @common_readings;
687     foreach my $wit ( @{$self->tradition->witnesses} ) {
688         my $curr_reading = $self->start;
689         my @wit_path = $self->reading_sequence( $self->start, $end, 
690                                                 $wit->sigil );
691         $wit->path( \@wit_path );
692
693         # Detect the common readings.
694         @common_readings = _find_common( \@common_readings, \@wit_path );
695     }
696
697     # Mark all the nodes as either common or not.
698     foreach my $cn ( @common_readings ) {
699         print STDERR "Setting " . $cn->name . " / " . $cn->label 
700             . " as common node\n";
701         $cn->make_common;
702     }
703     foreach my $n ( $self->readings() ) {
704         $n->make_variant unless $n->is_common;
705     }
706     # Return an array of the common nodes in order.
707     return @common_readings;
708 }
709
710 sub _find_common {
711     my( $common_readings, $new_path ) = @_;
712     my @cr;
713     if( @$common_readings ) {
714         foreach my $n ( @$new_path ) {
715             push( @cr, $n ) if grep { $_ eq $n } @$common_readings;
716         }
717     } else {
718         push( @cr, @$new_path );
719     }
720     return @cr;
721 }
722
723 sub _remove_common {
724     my( $common_readings, $divergence ) = @_;
725     my @cr;
726     my %diverged;
727     map { $diverged{$_->name} = 1 } @$divergence;
728     foreach( @$common_readings ) {
729         push( @cr, $_ ) unless $diverged{$_->name};
730     }
731     return @cr;
732 }
733
734
735 # An alternative to walk_witness_paths, for use when a collation is
736 # constructed from a base text and an apparatus.  We have the
737 # sequences of readings and just need to add path edges.
738
739 sub make_witness_paths {
740     my( $self ) = @_;
741
742     my @common_readings;
743     foreach my $wit ( @{$self->tradition->witnesses} ) {
744         print STDERR "Making path for " . $wit->sigil . "\n";
745         $self->make_witness_path( $wit );
746         @common_readings = _find_common( \@common_readings, $wit->path );
747         @common_readings = _find_common( \@common_readings, $wit->uncorrected_path );
748     }
749     map { $_->make_common } @common_readings;
750     return @common_readings;
751 }
752
753 sub make_witness_path {
754     my( $self, $wit ) = @_;
755     my @chain = @{$wit->path};
756     my $sig = $wit->sigil;
757     foreach my $idx ( 0 .. $#chain-1 ) {
758         $self->add_path( $chain[$idx], $chain[$idx+1], $sig );
759     }
760     @chain = @{$wit->uncorrected_path};
761     foreach my $idx( 0 .. $#chain-1 ) {
762         my $source = $chain[$idx];
763         my $target = $chain[$idx+1];
764         $self->add_path( $source, $target, $sig.$self->ac_label )
765             unless $self->has_path( $source, $target, $sig );
766     }
767 }
768
769 sub common_readings {
770     my $self = shift;
771     my @common = grep { $_->is_common } $self->readings();
772     return sort { $a->position->cmp_with( $b->position ) } @common;
773 }
774
775 # Calculate the relative positions of nodes in the graph, if they
776 # were not given to us.
777 sub calculate_positions {
778     my( $self, @ordered_common ) = @_;
779
780     # First assign positions to all the common nodes.
781     my $l = 1;
782     foreach my $oc ( @ordered_common ) {
783         $oc->position( $l++, 1 );
784     }
785
786     if( $self->linear ) {
787         # For the space between each common node, we have to find all the chains
788         # from all the witnesses.  The longest chain gives us our max, and the
789         # others get min/max ranges to fit.
790         my $first = shift @ordered_common;
791         while( @ordered_common ) {
792             my %paths;
793             my $next = shift @ordered_common;
794             my $longest = 0;
795             foreach my $wit ( @{$self->tradition->witnesses} ) {
796                 # Key to the path is not important; we just have to get
797                 # all unique paths.
798                 my $length = $self->_track_paths( \%paths, $first, $next, $wit->sigil );
799                 $longest = $length unless $longest > $length;
800                 if( $wit->has_ante_corr ) {
801                     my $length = $self->_track_paths( \%paths, $first, $next, 
802                                                       $wit->sigil.$self->ac_label, $wit->sigil );
803                     $longest = $length unless $longest > $length;
804                 }
805             }
806             
807             # Transform the path values from unique strings to arrays.
808             foreach my $k ( keys %paths ) {
809                 my @v = split( /\s+/, $paths{$k} );
810                 $paths{$k} = \@v;
811             }
812             
813             # Now %paths has all the unique paths, and we know how long the
814             # longest of these is.  Assign positions, starting with the
815             # longest.  All non-common positions start at 2.
816             foreach my $path ( sort { scalar @$b <=> scalar @$a } values %paths  ) {
817                 my $range = $longest - scalar @$path;
818                 foreach my $i ( 0 .. $#{$path} ) {
819                     my $min = $i+2;
820                     my $rdg = $self->reading( $path->[$i] );
821                     unless( $rdg->has_position ) {
822                         $rdg->position( $first->position->common, $min, $min+$range );
823                     }
824                 }
825             }
826             
827             $first = $next;
828         }
829     } else {
830
831         # Non-linear positions are pretty much impossible to pin down.
832         # Any reading might appear anywhere in the graph.  I guess we
833         # can do positions where there aren't transpositions...
834
835     }
836                 
837     $self->init_lemmata();
838 }
839
840 # Helper function for the guts of calculate_positions.
841 sub _track_paths {
842     my $self = shift;
843     my $track_hash = shift;
844     # Args are first, last, wit, backup
845     my @path = $self->reading_sequence( @_ );
846     # Top and tail the array
847     shift @path;
848     pop @path;
849     $track_hash->{$_[2]} = join( ' ', map { $_->name } @path )
850         if @path;
851     return @path;
852 }
853  
854 sub possible_positions {
855     my $self = shift;
856     my @answer;
857     my %positions = ();
858     foreach my $r ( $self->readings ) {
859         next unless $r->has_position;
860         $positions{$r->position->maxref} = 1;
861     }
862     @answer = keys %positions;
863     return @answer;
864 }
865
866 # TODO think about indexing this.
867 sub readings_at_position {
868     my( $self, $position, $strict ) = @_;
869     unless( ref( $position ) eq 'Text::Tradition::Collation::Position' ) {
870         $position = Text::Tradition::Collation::Position->new( $position );
871     }
872     my @answer;
873     foreach my $r ( $self->readings ) {
874         push( @answer, $r ) if $r->is_at_position( $position, $strict );
875     }
876     return @answer;
877 }
878
879 ## Lemmatizer functions
880
881 sub init_lemmata {
882     my $self = shift;
883
884     foreach my $position ( $self->possible_positions ) {
885         $self->lemmata->{$position} = undef;
886     }
887
888     foreach my $cr ( $self->common_readings ) {
889         $self->lemmata->{$cr->position->maxref} = $cr->name;
890     }
891 }
892     
893 =item B<lemma_readings>
894
895 my @state = $graph->lemma_readings( @readings_delemmatized );
896
897 Takes a list of readings that have just been delemmatized, and returns
898 a set of tuples of the form ['reading', 'state'] that indicates what
899 changes need to be made to the graph.
900
901 =over
902
903 =item * 
904
905 A state of 1 means 'lemmatize this reading'
906
907 =item * 
908
909 A state of 0 means 'delemmatize this reading'
910
911 =item * 
912
913 A state of undef means 'an ellipsis belongs in the text here because
914 no decision has been made / an earlier decision was backed out'
915
916 =back
917
918 =cut
919
920 sub lemma_readings {
921     my( $self, @toggled_off_nodes ) = @_;
922
923     # First get the positions of those nodes which have been
924     # toggled off.
925     my $positions_off = {};
926     map { $positions_off->{ $_->position->reference } = $_->name } 
927         @toggled_off_nodes;
928
929     # Now for each position, we have to see if a node is on, and we
930     # have to see if a node has been turned off.  The lemmata hash
931     # should contain fixed positions, range positions whose node was
932     # just turned off, and range positions whose node is on.
933     my @answer;
934     my %fixed_positions;
935     # TODO One of these is probably redundant.
936     map { $fixed_positions{$_} = 0 } keys %{$self->lemmata};
937     map { $fixed_positions{$_} = 0 } keys %{$positions_off};
938     map { $fixed_positions{$_} = 1 } $self->possible_positions;
939     foreach my $pos ( sort { Text::Tradition::Collation::Position::str_cmp( $a, $b ) } keys %fixed_positions ) {
940         # Find the state of this position.  If there is an active node,
941         # its name will be the state; otherwise the state will be 0 
942         # (nothing at this position) or undef (ellipsis at this position)
943         my $active = undef;
944         $active = $self->lemmata->{$pos} if exists $self->lemmata->{$pos};
945         
946         # Is there a formerly active node that was toggled off?
947         if( exists( $positions_off->{$pos} ) ) {
948             my $off_node = $positions_off->{$pos};
949             if( $active && $active ne $off_node) {
950                 push( @answer, [ $off_node, 0 ], [ $active, 1 ] );
951             } else {
952                 unless( $fixed_positions{$pos} ) {
953                     $active = 0;
954                     delete $self->lemmata->{$pos};
955                 }
956                 push( @answer, [ $off_node, $active ] );
957             }
958
959         # No formerly active node, so we just see if there is a currently
960         # active one.
961         } elsif( $active ) {
962             # Push the active node, whatever it is.
963             push( @answer, [ $active, 1 ] );
964         } else {
965             # Push the state that is there. Arbitrarily use the first node
966             # at that position.
967             my @pos_nodes = $self->readings_at_position( $pos );
968             push( @answer, [ $pos_nodes[0]->name, $self->lemmata->{$pos} ] );
969             delete $self->lemmata->{$pos} unless $fixed_positions{$pos};
970         }
971     }
972
973     return @answer;
974 }
975
976 =item B<toggle_reading>
977
978 my @readings_delemmatized = $graph->toggle_reading( $reading_name );
979
980 Takes a reading node name, and either lemmatizes or de-lemmatizes
981 it. Returns a list of all readings that are de-lemmatized as a result
982 of the toggle.
983
984 =cut
985
986 sub toggle_reading {
987     my( $self, $rname ) = @_;
988     
989     return unless $rname;
990     my $reading = $self->reading( $rname );
991     if( !$reading || $reading->is_common() ) {
992         # Do nothing, it's a common node.
993         return;
994     } 
995     
996     my $pos = $reading->position;
997     my $fixed = $reading->position->fixed;
998     my $old_state = $self->lemmata->{$pos->reference};
999
1000     my @readings_off;
1001     if( $old_state && $old_state eq $rname ) {
1002         # Turn off the node. We turn on no others by default.
1003         push( @readings_off, $reading );
1004     } else {
1005         # Turn on the node.
1006         $self->lemmata->{$pos->reference} = $rname;
1007         # Any other 'on' readings in the same position should be off
1008         # if we have a fixed position.
1009         push( @readings_off, $self->same_position_as( $reading, 1 ) )
1010             if $pos->fixed;
1011         # Any node that is an identical transposed one should be off.
1012         push( @readings_off, $reading->identical_readings );
1013     }
1014     @readings_off = unique_list( @readings_off );
1015         
1016     # Turn off the readings that need to be turned off.
1017     my @readings_delemmatized;
1018     foreach my $n ( @readings_off ) {
1019         my $npos = $n->position;
1020         my $state = undef;
1021         $state = $self->lemmata->{$npos->reference}
1022             if defined $self->lemmata->{$npos->reference};
1023         if( $state && $state eq $n->name ) { 
1024             # this reading is still on, so turn it off
1025             push( @readings_delemmatized, $n );
1026             my $new_state = undef;
1027             if( $npos->fixed && $n eq $reading ) {
1028                 # This is the reading that was clicked, so if there are no
1029                 # other readings there and this is a fixed position, turn off 
1030                 # the position.  In all other cases, restore the ellipsis.
1031                 my @other_n = $self->same_position_as( $n ); # TODO do we need strict?
1032                 $new_state = 0 unless @other_n;
1033             }
1034             $self->lemmata->{$npos->reference} = $new_state;
1035         } elsif( $old_state && $old_state eq $n->name ) { 
1036             # another reading has already been turned on here
1037             push( @readings_delemmatized, $n );
1038         } # else some other reading was on anyway, so pass.
1039     }
1040     return @readings_delemmatized;
1041 }
1042
1043 sub same_position_as {
1044     my( $self, $reading, $strict ) = @_;
1045     my $pos = $reading->position;
1046     my %onpath = ( $reading->name => 1 );
1047     # TODO This might not always be sufficient.  We really want to
1048     # exclude all readings on this one's path between its two
1049     # common points.
1050     map { $onpath{$_->name} = 1 } $reading->neighbor_readings;
1051     my @same = grep { !$onpath{$_->name} } 
1052         $self->readings_at_position( $reading->position, $strict );
1053     return @same;
1054 }
1055
1056 # Return the string that joins together a list of witnesses for
1057 # display on a single path.
1058 sub path_label {
1059     my $self = shift;
1060     return join( $self->wit_list_separator, @_ );
1061 }
1062
1063 sub witnesses_of_label {
1064     my( $self, $label ) = @_;
1065     my $regex = $self->wit_list_separator;
1066     my @answer = split( /\Q$regex\E/, $label );
1067     return @answer;
1068 }    
1069
1070 sub unique_list {
1071     my( @list ) = @_;
1072     my %h;
1073     map { $h{$_->name} = $_ } @list;
1074     return values( %h );
1075 }
1076
1077 sub add_hash_entry {
1078     my( $hash, $key, $entry ) = @_;
1079     if( exists $hash->{$key} ) {
1080         push( @{$hash->{$key}}, $entry );
1081     } else {
1082         $hash->{$key} = [ $entry ];
1083     }
1084 }
1085
1086 no Moose;
1087 __PACKAGE__->meta->make_immutable;