1 package Text::Tradition::Collation;
4 use IPC::Run qw( run binary );
5 use Text::Tradition::Collation::Path;
6 use Text::Tradition::Collation::Reading;
7 use Text::Tradition::Collation::Relationship;
8 use Text::Tradition::Collation::Segment;
16 add_reading => 'add_node',
17 del_reading => 'del_node',
18 add_path => 'add_edge',
19 del_path => 'del_edge',
25 relationships => 'edges',
27 default => sub { Graph::Easy->new( undirected => 0 ) },
33 isa => 'Text::Tradition',
39 writer => '_save_svg',
40 predicate => 'has_svg',
46 writer => '_save_graphml',
47 predicate => 'has_graphml',
50 # Keeps track of the lemmas within the collation. At most one lemma
51 # per position in the graph.
54 isa => 'HashRef[Maybe[Str]]',
55 default => sub { {} },
58 has 'wit_list_separator' => (
67 default => 'base text',
88 # The collation can be created two ways:
89 # 1. Collate a set of witnesses (with CollateX I guess) and process
90 # the results as in 2.
91 # 2. Read a pre-prepared collation in one of a variety of formats,
92 # and make the graph from that.
94 # The graph itself will (for now) be immutable, and the positions
95 # within the graph will also be immutable. We need to calculate those
96 # positions upon graph construction. The equivalences between graph
97 # nodes will be mutable, entirely determined by the user (or possibly
98 # by some semantic pre-processing provided by the user.) So the
99 # constructor should just make an empty equivalences object. The
100 # constructor will also need to make the witness objects, if we didn't
101 # come through option 1.
104 my( $self, $args ) = @_;
105 $self->graph->use_class('node', 'Text::Tradition::Collation::Reading');
106 $self->graph->use_class('edge', 'Text::Tradition::Collation::Path');
108 # Pass through any graph-specific options.
109 my $shape = exists( $args->{'shape'} ) ? $args->{'shape'} : 'ellipse';
110 $self->graph->set_attribute( 'node', 'shape', $shape );
113 # Wrapper around add_path
115 around add_path => sub {
119 # Make sure there are three arguments
121 warn "Call add_path with args source, target, witness";
124 # Make sure the proposed path does not yet exist
125 # NOTE 'reading' will currently return readings and segments
126 my( $source, $target, $wit ) = @_;
127 $source = $self->reading( $source )
128 unless ref( $source ) eq 'Text::Tradition::Collation::Reading';
129 $target = $self->reading( $target )
130 unless ref( $target ) eq 'Text::Tradition::Collation::Reading';
131 foreach my $path ( $source->edges_to( $target ) ) {
132 if( $path->label eq $wit && $path->class eq 'edge.path' ) {
140 # Wrapper around paths
141 around paths => sub {
145 my @result = grep { $_->sub_class eq 'path' } $self->$orig( @_ );
149 around relationships => sub {
152 my @result = grep { $_->sub_class eq 'relationship' } $self->$orig( @_ );
156 around readings => sub {
159 my @result = grep { $_->sub_class ne 'segment' } $self->$orig( @_ );
163 around segments => sub {
166 my @result = grep { $_->sub_class eq 'segment' } $self->$orig( @_ );
170 # Wrapper around merge_nodes
174 my $first_node = shift;
175 my $second_node = shift;
176 $first_node->merge_from( $second_node );
177 unshift( @_, $first_node, $second_node );
178 return $self->graph->merge_nodes( @_ );
181 # Extra graph-alike utility
183 my( $self, $source, $target, $label ) = @_;
184 my @paths = $source->edges_to( $target );
185 my @relevant = grep { $_->label eq $label } @paths;
186 return scalar @relevant;
189 ## Dealing with groups of readings, i.e. segments.
192 my( $self, @items ) = @_;
193 my $segment = Text::Tradition::Collation::Segment->new( 'members' => \@items );
197 ## Dealing with relationships between readings. This is a different
198 ## sort of graph edge.
200 sub add_relationship {
201 my( $self, $source, $target, $options ) = @_;
203 # Make sure there is not another relationship between these two
204 # readings or segments already
205 $source = $self->reading( $source )
206 unless ref( $source ) && $source->isa( 'Graph::Easy::Node' );
207 $target = $self->reading( $target )
208 unless ref( $target ) && $target->isa( 'Graph::Easy::Node' );
209 foreach my $rel ( $source->edges_to( $target ) ) {
210 if( $rel->label eq $options->{'type'} && $rel->class eq 'edge.relationship' ) {
214 $options->{'orig_relation'} = [ $source, $target ];
216 my $rel = Text::Tradition::Collation::Relationship->new( %$options );
217 $self->graph->add_edge( $source, $target, $rel );
218 if( $options->{'global'} ) {
219 # Look for all readings with the source label, and if there are
220 # colocated readings with the target label, join them too.
221 foreach my $r ( $self->readings() ) {
222 next unless $r->label eq $source->label;
223 my @colocated = grep { $_->label eq $target->label }
224 $self->same_position_as( $r );
226 warn "Multiple readings with same label at same position!"
228 my $dup_rel = Text::Tradition::Collation::Relationship->new( %$options );
229 $self->graph->add_edge( $r, $colocated[0], $dup_rel );
235 =head2 Output method(s)
241 print $graph->as_svg( $recalculate );
243 Returns an SVG string that represents the graph. Uses GraphViz to do
244 this, because Graph::Easy doesn\'t cope well with long graphs. Unless
245 $recalculate is passed (and is a true value), the method will return a
246 cached copy of the SVG after the first call to the method.
251 my( $self, $recalc ) = @_;
252 return $self->svg if $self->has_svg;
254 $self->collapse_graph_paths();
256 my @cmd = qw/dot -Tsvg/;
258 my $in = $self->as_dot();
259 run( \@cmd, \$in, ">", binary(), \$svg );
260 $self->_save_svg( $svg );
261 $self->expand_graph_paths();
267 print $graph->as_dot( $view, $recalculate );
269 Returns a string that is the collation graph expressed in dot
270 (i.e. GraphViz) format. The 'view' argument determines what kind of
272 * 'path': a graph of witness paths through the collation (DEFAULT)
273 * 'relationship': a graph of how collation readings relate to
279 my( $self, $view ) = @_;
280 $view = 'path' unless $view;
281 # TODO consider making some of these things configurable
282 my $dot = sprintf( "digraph %s {\n", $self->tradition->name );
283 $dot .= "\tedge [ arrowhead=open ];\n";
284 $dot .= "\tgraph [ rankdir=LR ];\n";
285 $dot .= sprintf( "\tnode [ fontsize=%d, fillcolor=%s, style=%s, shape=%s ];\n",
286 11, "white", "filled", $self->graph->get_attribute( 'node', 'shape' ) );
288 foreach my $reading ( $self->readings ) {
289 # Need not output nodes without separate labels
290 next if $reading->name eq $reading->label;
291 # TODO output readings or segments, but not both
292 next if $reading->class eq 'node.segment';
293 $dot .= sprintf( "\t\"%s\" [ label=\"%s\" ]\n", $reading->name, $reading->label );
296 my @edges = $view eq 'relationship' ? $self->relationships : $self->paths;
297 foreach my $edge ( @edges ) {
298 $dot .= sprintf( "\t\"%s\" -> \"%s\" [ color=\"%s\", fontcolor=\"%s\", label=\"%s\" ]\n",
299 $edge->from->name, $edge->to->name, '#000000', '#000000', $edge->label );
308 print $graph->as_graphml( $recalculate )
310 Returns a GraphML representation of the collation graph, with
311 transposition information and position information. Unless
312 $recalculate is passed (and is a true value), the method will return a
313 cached copy of the SVG after the first call to the method.
318 my( $self, $recalc ) = @_;
319 return $self->graphml if $self->has_graphml;
322 my $graphml_ns = 'http://graphml.graphdrawing.org/xmlns';
323 my $xsi_ns = 'http://www.w3.org/2001/XMLSchema-instance';
324 my $graphml_schema = 'http://graphml.graphdrawing.org/xmlns ' .
325 'http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd';
327 # Create the document and root node
328 my $graphml = XML::LibXML->createDocument( "1.0", "UTF-8" );
329 my $root = $graphml->createElementNS( $graphml_ns, 'graphml' );
330 $graphml->setDocumentElement( $root );
331 $root->setNamespace( $xsi_ns, 'xsi', 0 );
332 $root->setAttributeNS( $xsi_ns, 'schemaLocation', $graphml_schema );
334 # Add the data keys for nodes
337 foreach my $datum ( qw/ name reading identical position class / ) {
338 $node_data_keys{$datum} = 'dn'.$ndi++;
339 my $key = $root->addNewChild( $graphml_ns, 'key' );
340 $key->setAttribute( 'attr.name', $datum );
341 $key->setAttribute( 'attr.type', 'string' );
342 $key->setAttribute( 'for', 'node' );
343 $key->setAttribute( 'id', $node_data_keys{$datum} );
346 # Add the data keys for edges, i.e. witnesses
349 foreach my $edge_key( qw/ witness_main witness_ante_corr relationship class / ) {
350 $edge_data_keys{$edge_key} = 'de'.$edi++;
351 my $key = $root->addNewChild( $graphml_ns, 'key' );
352 $key->setAttribute( 'attr.name', $edge_key );
353 $key->setAttribute( 'attr.type', 'string' );
354 $key->setAttribute( 'for', 'edge' );
355 $key->setAttribute( 'id', $edge_data_keys{$edge_key} );
358 # Add the graph, its nodes, and its edges
359 my $graph = $root->addNewChild( $graphml_ns, 'graph' );
360 $graph->setAttribute( 'edgedefault', 'directed' );
361 $graph->setAttribute( 'id', 'g0' ); # TODO make this meaningful
362 $graph->setAttribute( 'parse.edgeids', 'canonical' );
363 $graph->setAttribute( 'parse.edges', scalar($self->paths) );
364 $graph->setAttribute( 'parse.nodeids', 'canonical' );
365 $graph->setAttribute( 'parse.nodes', scalar($self->readings) );
366 $graph->setAttribute( 'parse.order', 'nodesfirst' );
370 # Add our readings to the graph
371 foreach my $n ( sort { $a->name cmp $b->name } $self->readings ) {
372 my $node_el = $graph->addNewChild( $graphml_ns, 'node' );
373 my $node_xmlid = 'n' . $node_ctr++;
374 $node_hash{ $n->name } = $node_xmlid;
375 $node_el->setAttribute( 'id', $node_xmlid );
376 _add_graphml_data( $node_el, $node_data_keys{'name'}, $n->name );
377 _add_graphml_data( $node_el, $node_data_keys{'reading'}, $n->label );
378 _add_graphml_data( $node_el, $node_data_keys{'position'}, $n->position );
379 _add_graphml_data( $node_el, $node_data_keys{'class'}, $n->sub_class );
380 _add_graphml_data( $node_el, $node_data_keys{'identical'}, $n->primary->name )
384 # Add any segments we have
385 foreach my $n ( sort { $a->name cmp $b->name } $self->segments ) {
386 my $node_el = $graph->addNewChild( $graphml_ns, 'node' );
387 my $node_xmlid = 'n' . $node_ctr++;
388 $node_hash{ $n->name } = $node_xmlid;
389 $node_el->setAttribute( 'id', $node_xmlid );
390 _add_graphml_data( $node_el, $node_data_keys{'class'}, $n->sub_class );
391 _add_graphml_data( $node_el, $node_data_keys{'name'}, $n->name );
394 # Add the path, relationship, and segment edges
396 foreach my $e ( sort { $a->from->name cmp $b->from->name } $self->graph->edges() ) {
397 my( $name, $from, $to ) = ( 'e'.$edge_ctr++,
398 $node_hash{ $e->from->name() },
399 $node_hash{ $e->to->name() } );
400 my $edge_el = $graph->addNewChild( $graphml_ns, 'edge' );
401 $edge_el->setAttribute( 'source', $from );
402 $edge_el->setAttribute( 'target', $to );
403 $edge_el->setAttribute( 'id', $name );
405 _add_graphml_data( $edge_el, $edge_data_keys{'class'}, $e->sub_class );
406 if( $e->sub_class eq 'path' ) {
407 # It's a witness path, so add the witness
408 my $base = $e->label;
409 my $key = $edge_data_keys{'witness_main'};
411 if( $e->label =~ /^(.*?)\s+(\(a\.c\.\))$/ ) {
413 $key = $edge_data_keys{'witness_ante_corr'};
415 _add_graphml_data( $edge_el, $key, $base );
416 } elsif( $e->sub_class eq 'relationship' ) {
417 # It's a relationship
418 _add_graphml_data( $edge_el, $edge_data_keys{'relationship'}, $e->label );
419 } # else a segment, nothing to record but source, target, class
423 $self->_save_graphml( $graphml->toString(1) );
424 return $graphml->toString(1);
427 sub _add_graphml_data {
428 my( $el, $key, $value ) = @_;
429 my $data_el = $el->addNewChild( $el->namespaceURI, 'data' );
430 return unless defined $value;
431 $data_el->setAttribute( 'key', $key );
432 $data_el->appendText( $value );
435 sub collapse_graph_paths {
437 # Our collation graph has an path per witness. This is great for
438 # calculation purposes, but terrible for display. Thus we want to
439 # display only one path between any two nodes.
441 return if $self->collapsed;
443 print STDERR "Collapsing witness paths in graph...\n";
445 # Don't list out every witness if we have more than half to list.
446 my $majority = int( scalar( @{$self->tradition->witnesses} ) / 2 ) + 1;
447 # But don't compress if there are only a few witnesses.
448 $majority = 4 if $majority < 4;
449 foreach my $node ( $self->readings ) {
451 # We will visit each node, so we only look ahead.
452 foreach my $edge ( $node->outgoing() ) {
453 next unless $edge->class eq 'edge.path';
454 add_hash_entry( $newlabels, $edge->to->name, $edge->name );
455 $self->del_path( $edge );
458 foreach my $newdest ( keys %$newlabels ) {
460 my @compressed_wits = ();
461 if( @{$newlabels->{$newdest}} < $majority ) {
462 $label = join( ', ', sort( @{$newlabels->{$newdest}} ) );
464 ## TODO FIX THIS HACK
466 foreach my $wit ( @{$newlabels->{$newdest}} ) {
467 if( $wit =~ /^(.*?)(\s*\(?a\.\s*c\.\)?)$/ ) {
468 push( @aclabels, $wit );
470 push( @compressed_wits, $wit );
473 $label = join( ', ', 'majority', sort( @aclabels ) );
477 $self->add_path( $node, $self->reading( $newdest ), $label );
478 if( @compressed_wits ) {
479 $newpath->hidden_witnesses( \@compressed_wits );
484 $self->collapsed( 1 );
487 sub expand_graph_paths {
489 # Our collation graph has only one path between any two nodes.
490 # This is great for display, but not so great for analysis.
491 # Expand this so that each witness has its own path between any
493 return unless $self->collapsed;
495 print STDERR "Expanding witness paths in graph...\n";
496 foreach my $path( $self->paths ) {
497 my $from = $path->from;
499 my @wits = split( /, /, $path->label );
500 if( $path->has_hidden_witnesses ) {
501 push( @wits, @{$path->hidden_witnesses} );
503 $self->del_path( $path );
505 $self->add_path( $from, $to, $_ );
508 $self->collapsed( 0 );
513 =head2 Navigation methods
519 my $beginning = $collation->start();
521 Returns the beginning of the collation, a meta-reading with label '#START#'.
526 # Return the beginning reading of the graph.
528 my( $new_start ) = @_;
530 $self->del_reading( '#START#' );
531 $self->graph->rename_node( $new_start, '#START#' );
533 return $self->reading('#START#');
536 =item B<reading_sequence>
538 my @readings = $graph->reading_sequence( $first, $last, $path[, $alt_path] );
540 Returns the ordered list of readings, starting with $first and ending
541 with $last, along the given witness path. If no path is specified,
542 assume that the path is that of the base text (if any.)
546 sub reading_sequence {
547 my( $self, $start, $end, $witness, $backup ) = @_;
549 $witness = $self->baselabel unless $witness;
550 my @readings = ( $start );
553 while( $n && $n ne $end ) {
554 if( exists( $seen{$n->name()} ) ) {
555 warn "Detected loop at " . $n->name();
558 $seen{$n->name()} = 1;
560 my $next = $self->next_reading( $n, $witness, $backup );
561 warn "Did not find any path for $witness from reading " . $n->name
563 push( @readings, $next );
566 # Check that the last reading is our end reading.
567 my $last = $readings[$#readings];
568 warn "Last reading found from " . $start->label() .
569 " for witness $witness is not the end!"
570 unless $last eq $end;
575 =item B<next_reading>
577 my $next_reading = $graph->next_reading( $reading, $witpath );
579 Returns the reading that follows the given reading along the given witness
585 # Return the successor via the corresponding path.
587 return $self->_find_linked_reading( 'next', @_ );
590 =item B<prior_reading>
592 my $prior_reading = $graph->prior_reading( $reading, $witpath );
594 Returns the reading that precedes the given reading along the given witness
600 # Return the predecessor via the corresponding path.
602 return $self->_find_linked_reading( 'prior', @_ );
605 sub _find_linked_reading {
606 my( $self, $direction, $node, $path, $alt_path ) = @_;
607 my @linked_paths = $direction eq 'next'
608 ? $node->outgoing() : $node->incoming();
609 return undef unless scalar( @linked_paths );
611 # We have to find the linked path that contains all of the
612 # witnesses supplied in $path.
613 my( @path_wits, @alt_path_wits );
614 @path_wits = $self->witnesses_of_label( $path ) if $path;
615 @alt_path_wits = $self->witnesses_of_label( $alt_path ) if $alt_path;
618 foreach my $le ( @linked_paths ) {
619 if( $le->name eq $self->baselabel ) {
622 my @le_wits = $self->witnesses_of_label( $le->name );
623 if( _is_within( \@path_wits, \@le_wits ) ) {
624 # This is the right path.
625 return $direction eq 'next' ? $le->to() : $le->from();
626 } elsif( _is_within( \@alt_path_wits, \@le_wits ) ) {
631 # Got this far? Return the alternate path if it exists.
632 return $direction eq 'next' ? $alt_le->to() : $alt_le->from()
635 # Got this far? Return the base path if it exists.
636 return $direction eq 'next' ? $base_le->to() : $base_le->from()
639 # Got this far? We have no appropriate path.
640 warn "Could not find $direction node from " . $node->label
641 . " along path $path";
647 my( $set1, $set2 ) = @_;
648 my $ret = @$set1; # will be 0, i.e. false, if set1 is empty
649 foreach my $el ( @$set1 ) {
650 $ret = 0 unless grep { /^\Q$el\E$/ } @$set2;
656 ## INITIALIZATION METHODS - for use by parsers
657 # Walk the paths for each witness in the graph, and return the nodes
658 # that the graph has in common. If $using_base is true, some
659 # different logic is needed.
661 sub walk_witness_paths {
662 my( $self, $end ) = @_;
663 # For each witness, walk the path through the graph.
664 # Then we need to find the common nodes.
665 # TODO This method is going to fall down if we have a very gappy
666 # text in the collation.
669 foreach my $wit ( @{$self->tradition->witnesses} ) {
670 my $curr_reading = $self->start;
671 my @wit_path = $self->reading_sequence( $self->start, $end,
673 $wit->path( \@wit_path );
675 # Detect the common readings.
676 @common_readings = _find_common( \@common_readings, \@wit_path );
679 # Mark all the nodes as either common or not.
680 foreach my $cn ( @common_readings ) {
681 print STDERR "Setting " . $cn->name . " / " . $cn->label
682 . " as common node\n";
685 foreach my $n ( $self->readings() ) {
686 $n->make_variant unless $n->is_common;
688 # Return an array of the common nodes in order.
689 return @common_readings;
693 my( $common_readings, $new_path ) = @_;
695 if( @$common_readings ) {
696 foreach my $n ( @$new_path ) {
697 push( @cr, $n ) if grep { $_ eq $n } @$common_readings;
700 push( @cr, @$new_path );
706 my( $common_readings, $divergence ) = @_;
709 map { $diverged{$_->name} = 1 } @$divergence;
710 foreach( @$common_readings ) {
711 push( @cr, $_ ) unless $diverged{$_->name};
717 # An alternative to walk_witness_paths, for use when a collation is
718 # constructed from a base text and an apparatus. We have the
719 # sequences of readings and just need to add path edges.
721 sub make_witness_paths {
725 foreach my $wit ( @{$self->tradition->witnesses} ) {
726 print STDERR "Making path for " . $wit->sigil . "\n";
727 $self->make_witness_path( $wit );
728 @common_readings = _find_common( \@common_readings, $wit->path );
729 @common_readings = _find_common( \@common_readings, $wit->uncorrected_path );
731 map { $_->make_common } @common_readings;
732 return @common_readings;
735 sub make_witness_path {
736 my( $self, $wit ) = @_;
737 my @chain = @{$wit->path};
738 my $sig = $wit->sigil;
739 foreach my $idx ( 0 .. $#chain-1 ) {
740 $self->add_path( $chain[$idx], $chain[$idx+1], $sig );
742 @chain = @{$wit->uncorrected_path};
743 foreach my $idx( 0 .. $#chain-1 ) {
744 my $source = $chain[$idx];
745 my $target = $chain[$idx+1];
746 $self->add_path( $source, $target, $sig.$self->ac_label )
747 unless $self->has_path( $source, $target, $sig );
751 sub common_readings {
753 my @common = grep { $_->is_common } $self->readings();
754 return sort { _cmp_position( $a->position, $b->position ) } @common;
757 # Calculate the relative positions of nodes in the graph, if they
758 # were not given to us.
759 sub calculate_positions {
760 my( $self, @ordered_common ) = @_;
762 # We have to calculate the position identifiers for each word,
763 # keyed on the common nodes. This will be 'fun'. The end result
764 # is a hash per witness, whose key is the word node and whose
765 # value is its position in the text. Common nodes are always N,1
766 # so have identical positions in each text.
769 foreach my $wit ( @{$self->tradition->witnesses} ) {
770 print STDERR "Calculating positions in " . $wit->sigil . "\n";
771 _update_positions_from_path( $wit->path, @ordered_common );
772 _update_positions_from_path( $wit->uncorrected_path, @ordered_common )
773 if $wit->has_ante_corr;
777 foreach my $r ( $self->readings() ) {
778 print STDERR "Reading " . $r->name . "/" . $r->label . " has no position\n"
779 unless( $r->has_position );
782 $self->init_lemmata();
785 sub _update_positions_from_path {
786 my( $path, @ordered_common ) = @_;
788 # First we walk the given path, making a matrix for the witness
789 # that corresponds to its eventual position identifier. Common
790 # nodes always start a new row, and are thus always in the first
793 my $cn = 0; # We should hit the common readings in order.
795 foreach my $wn ( @{$path} ) {
796 if( $wn eq $ordered_common[$cn] ) {
797 # Set up to look for the next common node, and
798 # start a new row of words.
800 push( @$wit_matrix, $row ) if scalar( @$row );
805 push( @$wit_matrix, $row ); # Push the last row onto the matrix
807 # Now we have a matrix per witness, so that each row in the
808 # matrix begins with a common node, and continues with all the
809 # variant words that appear in the witness. We turn this into
810 # real positions in row,cell format. But we need some
811 # trickery in order to make sure that each node gets assigned
812 # to only one position.
814 foreach my $li ( 1..scalar(@$wit_matrix) ) {
815 foreach my $di ( 1..scalar(@{$wit_matrix->[$li-1]}) ) {
816 my $reading = $wit_matrix->[$li-1]->[$di-1];
817 my $position = "$li,$di";
819 # If we have seen this node before, we need to compare
820 # its position with what went before.
821 unless( $reading->has_position &&
822 _cmp_position( $position, $reading->position ) < 1 ) {
823 # The new position ID replaces the old one.
824 $reading->position( $position );
825 } # otherwise, the old position needs to stay.
833 my @pos_a = split(/,/, $a );
834 my @pos_b = split(/,/, $b );
836 my $big_cmp = $pos_a[0] <=> $pos_b[0];
837 return $big_cmp if $big_cmp;
839 return $pos_a[1] <=> $pos_b[1];
840 } elsif ( $b ) { # a is undefined
842 } elsif ( $a ) { # b is undefined
845 return 0; # they are both undefined
851 map { $positions{$_->position} = 1 } $self->readings;
852 my @answer = sort { _cmp_position( $a, $b ) } keys( %positions );
856 sub readings_at_position {
857 my( $self, $pos ) = @_;
858 my @answer = grep { $_->position eq $pos } $self->readings;
862 ## Lemmatizer functions
867 foreach my $position ( $self->all_positions ) {
868 $self->lemmata->{$position} = undef;
871 foreach my $cr ( $self->common_readings ) {
872 $self->lemmata->{$cr->position} = $cr->name;
876 =item B<lemma_readings>
878 my @state = $graph->lemma_readings( @readings_delemmatized );
880 Takes a list of readings that have just been delemmatized, and returns
881 a set of tuples of the form ['reading', 'state'] that indicates what
882 changes need to be made to the graph.
888 A state of 1 means 'lemmatize this reading'
892 A state of 0 means 'delemmatize this reading'
896 A state of undef means 'an ellipsis belongs in the text here because
897 no decision has been made / an earlier decision was backed out'
904 my( $self, @toggled_off_nodes ) = @_;
906 # First get the positions of those nodes which have been
908 my $positions_off = {};
909 map { $positions_off->{ $_->position } = $_->name } @toggled_off_nodes;
911 # Now for each position, we have to see if a node is on, and we
912 # have to see if a node has been turned off.
914 foreach my $pos ( $self->all_positions() ) {
915 # Find the state of this position. If there is an active node,
916 # its name will be the state; otherwise the state will be 0
917 # (nothing at this position) or undef (ellipsis at this position)
918 my $active = $self->lemmata->{$pos};
920 # Is there a formerly active node that was toggled off?
921 if( exists( $positions_off->{$pos} ) ) {
922 my $off_node = $positions_off->{$pos};
923 if( $active && $active ne $off_node) {
924 push( @answer, [ $off_node, 0 ], [ $active, 1 ] );
926 push( @answer, [ $off_node, $active ] );
929 # No formerly active node, so we just see if there is a currently
932 # Push the active node, whatever it is.
933 push( @answer, [ $active, 1 ] );
935 # Push the state that is there. Arbitrarily use the first node
937 my @pos_nodes = $self->readings_at_position( $pos );
938 push( @answer, [ $pos_nodes[0]->name, $self->lemmata->{$pos} ] );
945 =item B<toggle_reading>
947 my @readings_delemmatized = $graph->toggle_reading( $reading_name );
949 Takes a reading node name, and either lemmatizes or de-lemmatizes
950 it. Returns a list of all readings that are de-lemmatized as a result
956 my( $self, $rname ) = @_;
958 return unless $rname;
959 my $reading = $self->reading( $rname );
960 if( !$reading || $reading->is_common() ) {
961 # Do nothing, it's a common node.
965 my $pos = $reading->position;
966 my $old_state = $self->lemmata->{$pos};
968 if( $old_state && $old_state eq $rname ) {
969 # Turn off the node. We turn on no others by default.
970 push( @readings_off, $reading );
973 $self->lemmata->{$pos} = $rname;
974 # Any other 'on' readings in the same position should be off.
975 push( @readings_off, $self->same_position_as( $reading ) );
976 # Any node that is an identical transposed one should be off.
977 push( @readings_off, $reading->identical_readings );
979 @readings_off = unique_list( @readings_off );
981 # Turn off the readings that need to be turned off.
982 my @readings_delemmatized;
983 foreach my $n ( @readings_off ) {
984 my $state = $self->lemmata->{$n->position};
985 if( $state && $state eq $n->name ) {
986 # this reading is still on, so turn it off
987 push( @readings_delemmatized, $n );
988 my $new_state = undef;
989 if( $n eq $reading ) {
990 # This is the reading that was clicked, so if there are no
991 # other readings there, turn off the position. In all other
992 # cases, restore the ellipsis.
993 my @other_n = $self->same_position_as( $n );
994 $new_state = 0 unless @other_n;
996 $self->lemmata->{$n->position} = $new_state;
997 } elsif( $old_state && $old_state eq $n->name ) {
998 # another reading has already been turned on here
999 push( @readings_delemmatized, $n );
1000 } # else some other reading was on anyway, so pass.
1002 return @readings_delemmatized;
1005 sub same_position_as {
1006 my( $self, $reading ) = @_;
1007 my $pos = $reading->position;
1008 my @same = grep { $_ ne $reading } $self->readings_at_position( $reading->position );
1012 # Return the string that joins together a list of witnesses for
1013 # display on a single path.
1016 return join( $self->wit_list_separator, @_ );
1019 sub witnesses_of_label {
1020 my( $self, $label ) = @_;
1021 my $regex = $self->wit_list_separator;
1022 my @answer = split( /\Q$regex\E/, $label );
1029 map { $h{$_->name} = $_ } @list;
1030 return values( %h );
1033 sub add_hash_entry {
1034 my( $hash, $key, $entry ) = @_;
1035 if( exists $hash->{$key} ) {
1036 push( @{$hash->{$key}}, $entry );
1038 $hash->{$key} = [ $entry ];
1043 __PACKAGE__->meta->make_immutable;