first crack at implementing relationships
[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::Reading;
6 use Text::Tradition::Collation::Path;
7 use Moose;
8
9 has 'graph' => (
10     is => 'ro',
11     isa => 'Graph::Easy',
12     handles => {
13         add_reading => 'add_node',
14         del_reading => 'del_node',
15         add_path => 'add_edge',
16         del_path => 'del_edge',
17         reading => 'node',
18         path => 'edge',
19         readings => 'nodes',
20         paths => 'edges',
21     },
22     default => sub { Graph::Easy->new( undirected => 0 ) },
23     );
24                 
25
26 has 'tradition' => (
27     is => 'rw',
28     isa => 'Text::Tradition',
29     );
30
31 has 'svg' => (
32     is => 'ro',
33     isa => 'Str',
34     writer => '_save_svg',
35     predicate => 'has_svg',
36     );
37
38 has 'graphviz' => (
39     is => 'ro',
40     isa => 'Str',
41     writer => '_save_graphviz',
42     predicate => 'has_graphviz',
43     );
44
45 has 'graphml' => (
46     is => 'ro',
47     isa => 'XML::LibXML::Document',
48     writer => '_save_graphml',
49     predicate => 'has_graphml',
50     );
51
52 # Keeps track of the lemmas within the collation.  At most one lemma
53 # per position in the graph.
54 has 'lemmata' => (
55     is => 'ro',
56     isa => 'HashRef[Maybe[Str]]',
57     default => sub { {} },
58     );
59
60 has 'wit_list_separator' => (
61     is => 'rw',
62     isa => 'Str',
63     default => ', ',
64     );
65
66 has 'baselabel' => (
67     is => 'rw',
68     isa => 'Str',
69     default => 'base text',
70     );
71
72 has 'collapsed' => (
73     is => 'rw',
74     isa => 'Bool',
75     );
76
77 has 'linear' => (
78     is => 'rw',
79     isa => 'Bool',
80     default => 1,
81     );
82
83
84 # The collation can be created two ways:
85 # 1. Collate a set of witnesses (with CollateX I guess) and process
86 #    the results as in 2.
87 # 2. Read a pre-prepared collation in one of a variety of formats,
88 #    and make the graph from that.
89
90 # The graph itself will (for now) be immutable, and the positions
91 # within the graph will also be immutable.  We need to calculate those
92 # positions upon graph construction.  The equivalences between graph
93 # nodes will be mutable, entirely determined by the user (or possibly
94 # by some semantic pre-processing provided by the user.)  So the
95 # constructor should just make an empty equivalences object.  The
96 # constructor will also need to make the witness objects, if we didn't
97 # come through option 1.
98
99 sub BUILD {
100     my( $self, $args ) = @_;
101     $self->graph->use_class('node', 'Text::Tradition::Collation::Reading');
102     $self->graph->use_class('edge', 'Text::Tradition::Collation::Path');
103
104     # Pass through any graph-specific options.
105     my $shape = exists( $args->{'shape'} ) ? $args->{'shape'} : 'ellipse';
106     $self->graph->set_attribute( 'node', 'shape', $shape );
107 }
108
109 # Wrapper around add_path 
110
111 around add_path => sub {
112     my $orig = shift;
113     my $self = shift;
114
115     # Make sure there are three arguments
116     unless( @_ == 3 ) {
117         warn "Call add_path with args source, target, witness";
118         return;
119     }
120     # Make sure the proposed path does not yet exist
121     my( $source, $target, $wit ) = @_;
122     $source = $self->reading( $source )
123         unless ref( $source ) eq 'Text::Tradition::Collation::Reading';
124     $target = $self->reading( $target )
125         unless ref( $target ) eq 'Text::Tradition::Collation::Reading';
126     foreach my $path ( $source->edges_to( $target ) ) {
127         if( $path->label eq $wit ) {
128             return;
129         }
130     }
131     # Do the deed
132     $self->$orig( @_ );
133 };
134
135 # Wrapper around paths
136 around paths => sub {
137     my $orig = shift;
138     my $self = shift;
139
140     my @result = grep { $_->class eq 'path' } $self->$orig( @_ );
141     return @result;
142 };
143
144 # Wrapper around merge_nodes
145
146 sub merge_readings {
147     my $self = shift;
148     my $first_node = shift;
149     my $second_node = shift;
150     $first_node->merge_from( $second_node );
151     unshift( @_, $first_node, $second_node );
152     return $self->graph->merge_nodes( @_ );
153 }
154
155 # Extra graph-alike utility
156 sub has_path {
157     my( $self, $source, $target, $label ) = @_;
158     my @paths = $source->edges_to( $target );
159     my @relevant = grep { $_->label eq $label } @paths;
160     return scalar @paths;
161 }
162
163 ## Dealing with relationships between readings.  This is a different
164 ## sort of graph edge.
165
166 sub add_relationship {
167     my( $self, $type, $source, $target, $global ) = @_;
168     my $rel = Text::Tradition::Collation::Relationship->new(
169             'sort' => $type,
170             'global' => $global,
171             'orig_relation' => [ $source, $target ],
172     );
173     print STDERR sprintf( "Setting relationship %s between readings %s (%s)"
174                           . " and %s (%s)\n", $type, 
175                           $source->label, $source->name,
176                           $target->label, $target->name );
177     $self->graph->add_edge( $source, $target, $rel );
178     if( $global ) {
179         # Look for all readings with the source label, and if there are
180         # colocated readings with the target label, join them too.
181         foreach my $r ( $self->readings() ) {
182             next unless $r->label eq $source->label;
183             my @colocated = grep { $_->label eq $target->label }
184                 $self->same_position_as( $r );
185             if( @colocated ) {
186                 warn "Multiple readings with same label at same position!"
187                     if @colocated > 1;
188                 my $dup_rel = Text::Tradition::Collation::Relationship->new(
189                     'sort' => $type,
190                     'global' => $global,
191                     'orig_relation' => [ $source, $target ],
192                     );
193                 $self->graph->add_edge( $r, $colocated[0], $dup_rel );
194             }
195         }
196     }
197 }
198
199 =head2 Output method(s)
200
201 =over
202
203 =item B<as_svg>
204
205 print $graph->as_svg( $recalculate );
206
207 Returns an SVG string that represents the graph.  Uses GraphViz to do
208 this, because Graph::Easy doesn\'t cope well with long graphs. Unless
209 $recalculate is passed (and is a true value), the method will return a
210 cached copy of the SVG after the first call to the method.
211
212 =cut
213
214 sub as_svg {
215     my( $self, $recalc ) = @_;
216     return $self->svg if $self->has_svg;
217     
218     $self->collapse_graph_paths();
219     $self->_save_graphviz( $self->graph->as_graphviz() )
220         unless( $self->has_graphviz && !$recalc );
221     
222     my @cmd = qw/dot -Tsvg/;
223     my( $svg, $err );
224     my $in = $self->graphviz;
225     run( \@cmd, \$in, ">", binary(), \$svg );
226     $self->{'svg'} = $svg;
227     $self->expand_graph_paths();
228     return $svg;
229 }
230
231 =item B<as_graphml>
232
233 print $graph->as_graphml( $recalculate )
234
235 Returns a GraphML representation of the collation graph, with
236 transposition information and position information. Unless
237 $recalculate is passed (and is a true value), the method will return a
238 cached copy of the SVG after the first call to the method.
239
240 =cut
241
242 sub as_graphml {
243     my( $self, $recalc ) = @_;
244     return $self->graphml if $self->has_graphml;
245
246     # Some namespaces
247     my $graphml_ns = 'http://graphml.graphdrawing.org/xmlns';
248     my $xsi_ns = 'http://www.w3.org/2001/XMLSchema-instance';
249     my $graphml_schema = 'http://graphml.graphdrawing.org/xmlns ' .
250         'http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd';
251
252     # Create the document and root node
253     my $graphml = XML::LibXML->createDocument( "1.0", "UTF-8" );
254     my $root = $graphml->createElementNS( $graphml_ns, 'graphml' );
255     $graphml->setDocumentElement( $root );
256     $root->setNamespace( $xsi_ns, 'xsi', 0 );
257     $root->setAttributeNS( $xsi_ns, 'schemaLocation', $graphml_schema );
258
259     # Add the data keys for nodes
260     my @node_data = ( 'name', 'token', 'identical', 'position' );
261     foreach my $ndi ( 0 .. $#node_data ) {
262         my $key = $root->addNewChild( $graphml_ns, 'key' );
263         $key->setAttribute( 'attr.name', $node_data[$ndi] );
264         $key->setAttribute( 'attr.type', 'string' );
265         $key->setAttribute( 'for', 'node' );
266         $key->setAttribute( 'id', 'd'.$ndi );
267     }
268
269     # Add the data keys for edges
270     my %wit_hash;
271     my $wit_ctr = 0;
272     foreach my $wit ( @{$self->tradition->witnesses} ) {
273         my $wit_key = 'w' . $wit_ctr++;
274         $wit_hash{$wit} = $wit_key;
275         my $key = $root->addNewChild( $graphml_ns, 'key' );
276         $key->setAttribute( 'attr.name', $wit );
277         $key->setAttribute( 'attr.type', 'string' );
278         $key->setAttribute( 'for', 'edge' );
279         $key->setAttribute( 'id', $wit_key );
280     }
281
282     # Add the graph, its nodes, and its edges
283     $self->collapse_graph_edges();
284     my $graph = $root->addNewChild( $graphml_ns, 'graph' );
285     $graph->setAttribute( 'edgedefault', 'directed' );
286     $graph->setAttribute( 'id', 'g0' ); # TODO make this meaningful
287     $graph->setAttribute( 'parse.edgeids', 'canonical' );
288     $graph->setAttribute( 'parse.edges', $self->edges() );
289     $graph->setAttribute( 'parse.nodeids', 'canonical' );
290     $graph->setAttribute( 'parse.nodes', $self->nodes() );
291     $graph->setAttribute( 'parse.order', 'nodesfirst' );
292
293     my $node_ctr = 0;
294     my %node_hash;
295     foreach my $n ( $self->readings ) {
296         my %this_node_data = ();
297         foreach my $ndi ( 0 .. $#node_data ) {
298             my $value;
299             $this_node_data{'d'.$ndi} = $n->name if $node_data[$ndi] eq 'name';
300             $this_node_data{'d'.$ndi} = $n->label 
301                 if $node_data[$ndi] eq 'token';
302             $this_node_data{'d'.$ndi} = $n->primary->name if $n->has_primary;
303             $this_node_data{'d'.$ndi} = 
304                 $self->{'positions'}->node_position( $n )
305                 if $node_data[$ndi] eq 'position';
306         }
307         my $node_el = $graph->addNewChild( $graphml_ns, 'node' );
308         my $node_xmlid = 'n' . $node_ctr++;
309         $node_hash{ $n->name } = $node_xmlid;
310         $node_el->setAttribute( 'id', $node_xmlid );
311             
312         foreach my $dk ( keys %this_node_data ) {
313             my $d_el = $node_el->addNewChild( $graphml_ns, 'data' );
314             $d_el->setAttribute( 'key', $dk );
315             $d_el->appendTextChild( $this_node_data{$dk} );
316         }
317     }
318
319     foreach my $e ( $self->paths() ) {
320         my( $name, $from, $to ) = ( $e->name,
321                                     $node_hash{ $e->from()->name() },
322                                     $node_hash{ $e->to()->name() } );
323         my $edge_el = $graph->addNewChild( $graphml_ns, 'edge' );
324         $edge_el->setAttribute( 'source', $from );
325         $edge_el->setAttribute( 'target', $to );
326         $edge_el->setAttribute( 'id', $name );
327         # TODO Got to add the witnesses
328     }
329
330     # Return the thing
331     $self->_save_graphml( $graphml );
332     $self->expand_graph_edges();
333     return $graphml;
334 }
335
336 sub collapse_graph_paths {
337     my $self = shift;
338     # Our collation graph has an path per witness.  This is great for
339     # calculation purposes, but terrible for display.  Thus we want to
340     # display only one path between any two nodes.
341
342     return if $self->collapsed;
343
344     print STDERR "Collapsing witness paths in graph...\n";
345
346     # Don't list out every witness if we have more than half to list.
347     my $majority = int( scalar( @{$self->tradition->witnesses} ) / 2 ) + 1;
348     foreach my $node( $self->readings ) {
349         my $newlabels = {};
350         # We will visit each node, so we only look ahead.
351         foreach my $path ( $node->outgoing() ) {
352             add_hash_entry( $newlabels, $path->to->name, $path->name );
353             $self->del_path( $path );
354         }
355
356         foreach my $newdest ( keys %$newlabels ) {
357             my $label;
358             my @compressed_wits = ();
359             if( @{$newlabels->{$newdest}} < $majority ) {
360                 $label = join( ', ', @{$newlabels->{$newdest}} );
361             } else {
362                 ## TODO FIX THIS HACK
363                 my @aclabels;
364                 foreach my $wit ( @{$newlabels->{$newdest}} ) {
365                     if( $wit =~ /^(.*?)(\s*\(?a\.\s*c\.\)?)$/ ) {
366                         push( @aclabels, $wit );
367                     } else {
368                         push( @compressed_wits, $wit );
369                     }
370                 }
371                 $label = join( ', ', 'majority', @aclabels );
372             }
373             
374             my $newpath = 
375                 $self->add_path( $node, $self->reading( $newdest ), $label );
376             if( @compressed_wits ) {
377                 $newpath->hidden_witnesses( \@compressed_wits );
378             }
379         }
380     }
381
382     $self->collapsed( 1 );
383 }
384
385 sub expand_graph_paths {
386     my $self = shift;
387     # Our collation graph has only one path between any two nodes.
388     # This is great for display, but not so great for analysis.
389     # Expand this so that each witness has its own path between any
390     # two reading nodes.
391     return unless $self->collapsed;
392     
393     print STDERR "Expanding witness paths in graph...\n";
394     $DB::single = 1;
395     foreach my $path( $self->paths ) {
396         my $from = $path->from;
397         my $to = $path->to;
398         my @wits = split( /, /, $path->label );
399         if( $path->has_hidden_witnesses ) {
400             push( @wits, @{$path->hidden_witnesses} );
401         }
402         $self->del_path( $path );
403         foreach ( @wits ) {
404             $self->add_path( $from, $to, $_ );
405         }
406     }
407     $self->collapsed( 0 );
408 }
409
410 =back
411
412 =head2 Navigation methods
413
414 =over
415
416 =item B<start>
417
418 my $beginning = $collation->start();
419
420 Returns the beginning of the collation, a meta-reading with label '#START#'.
421
422 =cut
423
424 sub start {
425     # Return the beginning reading of the graph.
426     my $self = shift;
427     my( $new_start ) = @_;
428     if( $new_start ) {
429         $self->del_reading( '#START#' );
430         $self->graph->rename_node( $new_start, '#START#' );
431     }
432     return $self->reading('#START#');
433 }
434
435 =item B<reading_sequence>
436
437 my @readings = $graph->reading_sequence( $first, $last, $path[, $alt_path] );
438
439 Returns the ordered list of readings, starting with $first and ending
440 with $last, along the given witness path.  If no path is specified,
441 assume that the path is that of the base text (if any.)
442
443 =cut
444
445 sub reading_sequence {
446     my( $self, $start, $end, $witness, $backup ) = @_;
447
448     $witness = $self->baselabel unless $witness;
449     my @readings = ( $start );
450     my %seen;
451     my $n = $start;
452     while( $n && $n ne $end ) {
453         if( exists( $seen{$n->name()} ) ) {
454             warn "Detected loop at " . $n->name();
455             last;
456         }
457         $seen{$n->name()} = 1;
458         
459         my $next = $self->next_reading( $n, $witness, $backup );
460         warn "Did not find any path for $witness from reading " . $n->name
461             unless $next;
462         push( @readings, $next );
463         $n = $next;
464     }
465     # Check that the last reading is our end reading.
466     my $last = $readings[$#readings];
467     warn "Last reading found from " . $start->label() .
468         " for witness $witness is not the end!"
469         unless $last eq $end;
470     
471     return @readings;
472 }
473
474 =item B<next_reading>
475
476 my $next_reading = $graph->next_reading( $reading, $witpath );
477
478 Returns the reading that follows the given reading along the given witness
479 path.  
480
481 =cut
482
483 sub next_reading {
484     # Return the successor via the corresponding path.
485     my $self = shift;
486     return $self->_find_linked_reading( 'next', @_ );
487 }
488
489 =item B<prior_reading>
490
491 my $prior_reading = $graph->prior_reading( $reading, $witpath );
492
493 Returns the reading that precedes the given reading along the given witness
494 path.  
495
496 =cut
497
498 sub prior_reading {
499     # Return the predecessor via the corresponding path.
500     my $self = shift;
501     return $self->_find_linked_reading( 'prior', @_ );
502 }
503
504 sub _find_linked_reading {
505     my( $self, $direction, $node, $path, $alt_path ) = @_;
506     my @linked_paths = $direction eq 'next' 
507         ? $node->outgoing() : $node->incoming();
508     return undef unless scalar( @linked_paths );
509     
510     # We have to find the linked path that contains all of the
511     # witnesses supplied in $path.
512     my( @path_wits, @alt_path_wits );
513     @path_wits = $self->witnesses_of_label( $path ) if $path;
514     @alt_path_wits = $self->witnesses_of_label( $alt_path ) if $alt_path;
515     my $base_le;
516     my $alt_le;
517     foreach my $le ( @linked_paths ) {
518         if( $le->name eq $self->baselabel ) {
519             $base_le = $le;
520         } else {
521             my @le_wits = $self->witnesses_of_label( $le->name );
522             if( _is_within( \@path_wits, \@le_wits ) ) {
523                 # This is the right path.
524                 return $direction eq 'next' ? $le->to() : $le->from();
525             } elsif( _is_within( \@alt_path_wits, \@le_wits ) ) {
526                 $alt_le = $le;
527             }
528         }
529     }
530     # Got this far? Return the alternate path if it exists.
531     return $direction eq 'next' ? $alt_le->to() : $alt_le->from()
532         if $alt_le;
533
534     # Got this far? Return the base path if it exists.
535     return $direction eq 'next' ? $base_le->to() : $base_le->from()
536         if $base_le;
537
538     # Got this far? We have no appropriate path.
539     warn "Could not find $direction node from " . $node->label 
540         . " along path $path";
541     return undef;
542 }
543
544 # Some set logic.
545 sub _is_within {
546     my( $set1, $set2 ) = @_;
547     my $ret = @$set1; # will be 0, i.e. false, if set1 is empty
548     foreach my $el ( @$set1 ) {
549         $ret = 0 unless grep { /^\Q$el\E$/ } @$set2;
550     }
551     return $ret;
552 }
553
554
555 ## INITIALIZATION METHODS - for use by parsers
556 # Walk the paths for each witness in the graph, and return the nodes
557 # that the graph has in common.  If $using_base is true, some 
558 # different logic is needed.
559
560 sub walk_witness_paths {
561     my( $self, $end ) = @_;
562     # For each witness, walk the path through the graph.
563     # Then we need to find the common nodes.  
564     # TODO This method is going to fall down if we have a very gappy 
565     # text in the collation.
566     my $paths = {};
567     my @common_readings;
568     foreach my $wit ( @{$self->tradition->witnesses} ) {
569         my $curr_reading = $self->start;
570         my @wit_path = $self->reading_sequence( $self->start, $end, 
571                                                 $wit->sigil );
572         $wit->path( \@wit_path );
573
574         # Detect the common readings.
575         @common_readings = _find_common( \@common_readings, \@wit_path );
576     }
577
578     # Mark all the nodes as either common or not.
579     foreach my $cn ( @common_readings ) {
580         print STDERR "Setting " . $cn->name . " / " . $cn->label 
581             . " as common node\n";
582         $cn->make_common;
583     }
584     foreach my $n ( $self->readings() ) {
585         $n->make_variant unless $n->is_common;
586     }
587     # Return an array of the common nodes in order.
588     return @common_readings;
589 }
590
591 sub _find_common {
592     my( $common_readings, $new_path ) = @_;
593     my @cr;
594     if( @$common_readings ) {
595         foreach my $n ( @$new_path ) {
596             push( @cr, $n ) if grep { $_ eq $n } @$common_readings;
597         }
598     } else {
599         push( @cr, @$new_path );
600     }
601     return @cr;
602 }
603
604 sub _remove_common {
605     my( $common_readings, $divergence ) = @_;
606     my @cr;
607     my %diverged;
608     map { $diverged{$_->name} = 1 } @$divergence;
609     foreach( @$common_readings ) {
610         push( @cr, $_ ) unless $diverged{$_->name};
611     }
612     return @cr;
613 }
614
615
616 # An alternative to walk_witness_paths, for use when a collation is
617 # constructed from a base text and an apparatus.  We have the
618 # sequences of readings and just need to add path edges.
619
620 sub make_witness_paths {
621     my( $self ) = @_;
622
623     my @common_readings;
624     foreach my $wit ( @{$self->tradition->witnesses} ) {
625         print STDERR "Making path for " . $wit->sigil . "\n";
626         $self->make_witness_path( $wit );
627         @common_readings = _find_common( \@common_readings, $wit->path );
628         @common_readings = _find_common( \@common_readings, $wit->uncorrected_path );
629     }
630     return @common_readings;
631 }
632
633 sub make_witness_path {
634     my( $self, $wit ) = @_;
635     my @chain = @{$wit->path};
636     my $sig = $wit->sigil;
637     foreach my $idx ( 0 .. $#chain-1 ) {
638         $self->add_path( $chain[$idx], $chain[$idx+1], $sig );
639     }
640     @chain = @{$wit->uncorrected_path};
641     foreach my $idx( 0 .. $#chain-1 ) {
642         my $source = $chain[$idx];
643         my $target = $chain[$idx+1];
644         $self->add_path( $source, $target, "$sig (a.c.)" )
645             unless $self->has_path( $source, $target, $sig );
646     }
647 }
648
649 sub common_readings {
650     my $self = shift;
651     my @common = grep { $_->is_common } $self->readings();
652     return sort { _cmp_position( $a->position, $b->position ) } @common;
653 }
654
655 # Calculate the relative positions of nodes in the graph, if they
656 # were not given to us.
657 sub calculate_positions {
658     my( $self, @ordered_common ) = @_;
659
660     # We have to calculate the position identifiers for each word,
661     # keyed on the common nodes.  This will be 'fun'.  The end result
662     # is a hash per witness, whose key is the word node and whose
663     # value is its position in the text.  Common nodes are always N,1
664     # so have identical positions in each text.
665
666     my $node_pos = {};
667     foreach my $wit ( @{$self->tradition->witnesses} ) {
668         print STDERR "Calculating positions in " . $wit->sigil . "\n";
669         _update_positions_from_path( $wit->path, @ordered_common );
670         _update_positions_from_path( $wit->uncorrected_path, @ordered_common )
671             if $wit->has_ante_corr;
672     }
673     
674     # DEBUG
675     foreach my $r ( $self->readings() ) {
676         print STDERR "Reading " . $r->name . "/" . $r->label . " has no position\n"
677             unless( $r->has_position );
678     }
679
680     $self->init_lemmata();
681 }
682
683 sub _update_positions_from_path {
684     my( $path, @ordered_common ) = @_;
685
686     # First we walk the given path, making a matrix for the witness
687     # that corresponds to its eventual position identifier.  Common
688     # nodes always start a new row, and are thus always in the first
689     # column.
690     my $wit_matrix = [];
691     my $cn = 0;  # We should hit the common readings in order.
692     my $row = [];
693     foreach my $wn ( @{$path} ) {
694         if( $wn eq $ordered_common[$cn] ) {
695             # Set up to look for the next common node, and
696             # start a new row of words.
697             $cn++;
698             push( @$wit_matrix, $row ) if scalar( @$row );
699             $row = [];
700         }
701         push( @$row, $wn );
702     }
703     push( @$wit_matrix, $row );  # Push the last row onto the matrix
704
705     # Now we have a matrix per witness, so that each row in the
706     # matrix begins with a common node, and continues with all the
707     # variant words that appear in the witness.  We turn this into
708     # real positions in row,cell format.  But we need some
709     # trickery in order to make sure that each node gets assigned
710     # to only one position.
711     
712     foreach my $li ( 1..scalar(@$wit_matrix) ) {
713         foreach my $di ( 1..scalar(@{$wit_matrix->[$li-1]}) ) {
714             my $reading = $wit_matrix->[$li-1]->[$di-1];
715             my $position = "$li,$di";
716
717             # If we have seen this node before, we need to compare
718             # its position with what went before.
719             unless( $reading->has_position &&
720                     _cmp_position( $position, $reading->position ) < 1 ) {
721                 # The new position ID replaces the old one.
722                 $reading->position( $position );
723             } # otherwise, the old position needs to stay.
724         }
725     }
726 }
727
728 sub _cmp_position {
729     my( $a, $b ) = @_;
730     if ( $a && $b ) {
731         my @pos_a = split(/,/, $a );
732         my @pos_b = split(/,/, $b );
733
734         my $big_cmp = $pos_a[0] <=> $pos_b[0];
735         return $big_cmp if $big_cmp;
736         # else 
737         return $pos_a[1] <=> $pos_b[1];
738     } elsif ( $b ) { # a is undefined
739         return -1;
740     } elsif ( $a ) { # b is undefined
741         return 1;
742     }
743     return 0; # they are both undefined
744 }
745
746 sub all_positions {
747     my $self = shift;
748     my %positions = ();
749     map { $positions{$_->position} = 1 } $self->readings;
750     my @answer = sort { _cmp_position( $a, $b ) } keys( %positions );
751     return @answer;
752 }
753
754 sub readings_at_position {
755     my( $self, $pos ) = @_;
756     my @answer = grep { $_->position eq $pos } $self->readings;
757     return @answer;
758 }
759
760 ## Lemmatizer functions
761
762 sub init_lemmata {
763     my $self = shift;
764     
765     foreach my $position ( $self->all_positions ) {
766         $self->lemmata->{$position} = undef;
767     }
768
769     foreach my $cr ( $self->common_readings ) {
770         $self->lemmata->{$cr->position} = $cr->name;
771     }
772 }
773     
774 =item B<lemma_readings>
775
776 my @state = $graph->lemma_readings( @readings_delemmatized );
777
778 Takes a list of readings that have just been delemmatized, and returns
779 a set of tuples of the form ['reading', 'state'] that indicates what
780 changes need to be made to the graph.
781
782 =over
783
784 =item * 
785
786 A state of 1 means 'lemmatize this reading'
787
788 =item * 
789
790 A state of 0 means 'delemmatize this reading'
791
792 =item * 
793
794 A state of undef means 'an ellipsis belongs in the text here because
795 no decision has been made / an earlier decision was backed out'
796
797 =back
798
799 =cut
800
801 sub lemma_readings {
802     my( $self, @toggled_off_nodes ) = @_;
803
804     # First get the positions of those nodes which have been
805     # toggled off.
806     my $positions_off = {};
807     map { $positions_off->{ $_->position } = $_->name } @toggled_off_nodes;
808
809     # Now for each position, we have to see if a node is on, and we
810     # have to see if a node has been turned off.
811     my @answer;
812     foreach my $pos ( $self->all_positions() ) {
813         # Find the state of this position.  If there is an active node,
814         # its name will be the state; otherwise the state will be 0 
815         # (nothing at this position) or undef (ellipsis at this position)
816         my $active = $self->lemmata->{$pos};
817         
818         # Is there a formerly active node that was toggled off?
819         if( exists( $positions_off->{$pos} ) ) {
820             my $off_node = $positions_off->{$pos};
821             if( $active && $active ne $off_node) {
822                 push( @answer, [ $off_node, 0 ], [ $active, 1 ] );
823             } else {
824                 push( @answer, [ $off_node, $active ] );
825             }
826
827         # No formerly active node, so we just see if there is a currently
828         # active one.
829         } elsif( $active ) {
830             # Push the active node, whatever it is.
831             push( @answer, [ $active, 1 ] );
832         } else {
833             # Push the state that is there. Arbitrarily use the first node
834             # at that position.
835             my @pos_nodes = $self->readings_at_position( $pos );
836             push( @answer, [ $pos_nodes[0]->name, $self->lemmata->{$pos} ] );
837         }
838     }
839     
840     return @answer;
841 }
842
843 =item B<toggle_reading>
844
845 my @readings_delemmatized = $graph->toggle_reading( $reading_name );
846
847 Takes a reading node name, and either lemmatizes or de-lemmatizes
848 it. Returns a list of all readings that are de-lemmatized as a result
849 of the toggle.
850
851 =cut
852
853 sub toggle_reading {
854     my( $self, $rname ) = @_;
855     
856     return unless $rname;
857     my $reading = $self->reading( $rname );
858     if( !$reading || $reading->is_common() ) {
859         # Do nothing, it's a common node.
860         return;
861     } 
862     
863     my $pos = $reading->position;
864     my $old_state = $self->lemmata->{$pos};
865     my @readings_off;
866     if( $old_state && $old_state eq $rname ) {
867         # Turn off the node. We turn on no others by default.
868         push( @readings_off, $reading );
869     } else {
870         # Turn on the node.
871         $self->lemmata->{$pos} = $rname;
872         # Any other 'on' readings in the same position should be off.
873         push( @readings_off, $self->same_position_as( $reading ) );
874         # Any node that is an identical transposed one should be off.
875         push( @readings_off, $reading->identical_readings );
876     }
877     @readings_off = unique_list( @readings_off );
878
879     # Turn off the readings that need to be turned off.
880     my @readings_delemmatized;
881     foreach my $n ( @readings_off ) {
882         my $state = $self->lemmata->{$n->position};
883         if( $state && $state eq $n->name ) { 
884             # this reading is still on, so turn it off
885             push( @readings_delemmatized, $n );
886             my $new_state = undef;
887             if( $n eq $reading ) {
888                 # This is the reading that was clicked, so if there are no
889                 # other readings there, turn off the position.  In all other
890                 # cases, restore the ellipsis.
891                 my @other_n = $self->same_position_as( $n );
892                 $new_state = 0 unless @other_n;
893             }
894             $self->lemmata->{$n->position} = $new_state;
895         } elsif( $old_state && $old_state eq $n->name ) { 
896             # another reading has already been turned on here
897             push( @readings_delemmatized, $n );
898         } # else some other reading was on anyway, so pass.
899     }
900     return @readings_delemmatized;
901 }
902
903 sub same_position_as {
904     my( $self, $reading ) = @_;
905     my $pos = $reading->position;
906     my @same = grep { $_ ne $reading } $self->readings_at_position( $reading->position );
907     return @same;
908 }
909
910 # Return the string that joins together a list of witnesses for
911 # display on a single path.
912 sub path_label {
913     my $self = shift;
914     return join( $self->wit_list_separator, @_ );
915 }
916
917 sub witnesses_of_label {
918     my( $self, $label ) = @_;
919     my $regex = $self->wit_list_separator;
920     my @answer = split( /\Q$regex\E/, $label );
921     return @answer;
922 }    
923
924 sub unique_list {
925     my( @list ) = @_;
926     my %h;
927     map { $h{$_->name} = $_ } @list;
928     return values( %h );
929 }
930
931 sub add_hash_entry {
932     my( $hash, $key, $entry ) = @_;
933     if( exists $hash->{$key} ) {
934         push( @{$hash->{$key}}, $entry );
935     } else {
936         $hash->{$key} = [ $entry ];
937     }
938 }
939
940 no Moose;
941 __PACKAGE__->meta->make_immutable;