1 package Text::Tradition::Collation;
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;
17 add_reading => 'add_node',
18 del_reading => 'del_node',
19 add_path => 'add_edge',
20 del_path => 'del_edge',
26 relationships => 'edges',
28 default => sub { Graph::Easy->new( undirected => 0 ) },
34 isa => 'Text::Tradition',
40 writer => '_save_svg',
41 predicate => 'has_svg',
47 writer => '_save_graphml',
48 predicate => 'has_graphml',
51 # Keeps track of the lemmas within the collation. At most one lemma
52 # per position in the graph.
55 isa => 'HashRef[Maybe[Str]]',
56 default => sub { {} },
59 has 'wit_list_separator' => (
68 default => 'base text',
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.
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.
105 my( $self, $args ) = @_;
106 $self->graph->use_class('node', 'Text::Tradition::Collation::Reading');
107 $self->graph->use_class('edge', 'Text::Tradition::Collation::Path');
109 # Pass through any graph-specific options.
110 my $shape = exists( $args->{'shape'} ) ? $args->{'shape'} : 'ellipse';
111 $self->graph->set_attribute( 'node', 'shape', $shape );
114 # Wrapper around add_path
116 around add_path => sub {
120 # Make sure there are three arguments
122 warn "Call add_path with args source, target, witness";
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' ) {
141 # Wrapper around paths
142 around paths => sub {
146 my @result = grep { $_->sub_class eq 'path' } $self->$orig( @_ );
150 around relationships => sub {
153 my @result = grep { $_->sub_class eq 'relationship' } $self->$orig( @_ );
157 around readings => sub {
160 my @result = grep { $_->sub_class ne 'segment' } $self->$orig( @_ );
164 around segments => sub {
167 my @result = grep { $_->sub_class eq 'segment' } $self->$orig( @_ );
171 # Wrapper around merge_nodes
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( @_ );
182 # Extra graph-alike utility
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;
190 ## Dealing with groups of readings, i.e. segments.
193 my( $self, @items ) = @_;
194 my $segment = Text::Tradition::Collation::Segment->new( 'members' => \@items );
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.
202 sub add_relationship {
203 my( $self, $source, $target, $options ) = @_;
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" );
215 return ( undef, "There is a witness path between these readings" );
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" );
225 my @joined = ( [ $source->name, $target->name ] ); # Keep track of the nodes we join.
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 );
238 warn "Multiple readings with same label at same position!"
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 ] );
250 return( 1, @joined );
253 =head2 Output method(s)
259 print $graph->as_svg( $recalculate );
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.
269 my( $self, $recalc ) = @_;
270 return $self->svg if $self->has_svg;
272 $self->collapse_graph_paths();
274 my @cmd = qw/dot -Tsvg/;
276 my $in = $self->as_dot();
277 run( \@cmd, \$in, ">", binary(), \$svg );
278 $self->_save_svg( $svg );
279 $self->expand_graph_paths();
285 print $graph->as_dot( $view, $recalculate );
287 Returns a string that is the collation graph expressed in dot
288 (i.e. GraphViz) format. The 'view' argument determines what kind of
290 * 'path': a graph of witness paths through the collation (DEFAULT)
291 * 'relationship': a graph of how collation readings relate to
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' ) );
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 );
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 );
326 print $graph->as_graphml( $recalculate )
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.
336 my( $self, $recalc ) = @_;
337 return $self->graphml if $self->has_graphml;
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';
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 );
352 # Add the data keys for nodes
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} );
364 # Add the data keys for edges, i.e. witnesses
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} );
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' );
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 )
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 );
412 # Add the path, relationship, and segment edges
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 );
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'};
429 if( $e->label =~ /^(.*?)\s+(\(a\.c\.\))$/ ) {
431 $key = $edge_data_keys{'witness_ante_corr'};
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
441 $self->_save_graphml( $graphml->toString(1) );
442 return $graphml->toString(1);
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 );
453 sub collapse_graph_paths {
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.
459 return if $self->collapsed;
461 print STDERR "Collapsing witness paths in graph...\n";
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 ) {
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 );
476 foreach my $newdest ( keys %$newlabels ) {
478 my @compressed_wits = ();
479 if( @{$newlabels->{$newdest}} < $majority ) {
480 $label = join( ', ', sort( @{$newlabels->{$newdest}} ) );
482 ## TODO FIX THIS HACK
484 foreach my $wit ( @{$newlabels->{$newdest}} ) {
485 if( $wit =~ /^(.*?)(\s*\(?a\.\s*c\.\)?)$/ ) {
486 push( @aclabels, $wit );
488 push( @compressed_wits, $wit );
491 $label = join( ', ', 'majority', sort( @aclabels ) );
495 $self->add_path( $node, $self->reading( $newdest ), $label );
496 if( @compressed_wits ) {
497 $newpath->hidden_witnesses( \@compressed_wits );
502 $self->collapsed( 1 );
505 sub expand_graph_paths {
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
511 return unless $self->collapsed;
513 print STDERR "Expanding witness paths in graph...\n";
514 foreach my $path( $self->paths ) {
515 my $from = $path->from;
517 my @wits = split( /, /, $path->label );
518 if( $path->has_hidden_witnesses ) {
519 push( @wits, @{$path->hidden_witnesses} );
521 $self->del_path( $path );
523 $self->add_path( $from, $to, $_ );
526 $self->collapsed( 0 );
531 =head2 Navigation methods
537 my $beginning = $collation->start();
539 Returns the beginning of the collation, a meta-reading with label '#START#'.
544 # Return the beginning reading of the graph.
546 my( $new_start ) = @_;
548 $self->del_reading( '#START#' );
549 $self->graph->rename_node( $new_start, '#START#' );
551 return $self->reading('#START#');
554 =item B<reading_sequence>
556 my @readings = $graph->reading_sequence( $first, $last, $path[, $alt_path] );
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.)
564 sub reading_sequence {
565 my( $self, $start, $end, $witness, $backup ) = @_;
567 $witness = $self->baselabel unless $witness;
568 my @readings = ( $start );
571 while( $n && $n ne $end ) {
572 if( exists( $seen{$n->name()} ) ) {
573 warn "Detected loop at " . $n->name();
576 $seen{$n->name()} = 1;
578 my $next = $self->next_reading( $n, $witness, $backup );
579 warn "Did not find any path for $witness from reading " . $n->name
581 push( @readings, $next );
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;
593 =item B<next_reading>
595 my $next_reading = $graph->next_reading( $reading, $witpath );
597 Returns the reading that follows the given reading along the given witness
603 # Return the successor via the corresponding path.
605 return $self->_find_linked_reading( 'next', @_ );
608 =item B<prior_reading>
610 my $prior_reading = $graph->prior_reading( $reading, $witpath );
612 Returns the reading that precedes the given reading along the given witness
618 # Return the predecessor via the corresponding path.
620 return $self->_find_linked_reading( 'prior', @_ );
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 );
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;
636 foreach my $le ( @linked_paths ) {
637 if( $le->name eq $self->baselabel ) {
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 ) ) {
649 # Got this far? Return the alternate path if it exists.
650 return $direction eq 'next' ? $alt_le->to() : $alt_le->from()
653 # Got this far? Return the base path if it exists.
654 return $direction eq 'next' ? $base_le->to() : $base_le->from()
657 # Got this far? We have no appropriate path.
658 warn "Could not find $direction node from " . $node->label
659 . " along path $path";
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;
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.
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.
687 foreach my $wit ( @{$self->tradition->witnesses} ) {
688 my $curr_reading = $self->start;
689 my @wit_path = $self->reading_sequence( $self->start, $end,
691 $wit->path( \@wit_path );
693 # Detect the common readings.
694 @common_readings = _find_common( \@common_readings, \@wit_path );
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";
703 foreach my $n ( $self->readings() ) {
704 $n->make_variant unless $n->is_common;
706 # Return an array of the common nodes in order.
707 return @common_readings;
711 my( $common_readings, $new_path ) = @_;
713 if( @$common_readings ) {
714 foreach my $n ( @$new_path ) {
715 push( @cr, $n ) if grep { $_ eq $n } @$common_readings;
718 push( @cr, @$new_path );
724 my( $common_readings, $divergence ) = @_;
727 map { $diverged{$_->name} = 1 } @$divergence;
728 foreach( @$common_readings ) {
729 push( @cr, $_ ) unless $diverged{$_->name};
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.
739 sub make_witness_paths {
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 );
749 map { $_->make_common } @common_readings;
750 return @common_readings;
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 );
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 );
769 sub common_readings {
771 my @common = grep { $_->is_common } $self->readings();
772 return sort { $a->position->cmp_with( $b->position ) } @common;
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 ) = @_;
780 # First assign positions to all the common nodes.
782 foreach my $oc ( @ordered_common ) {
783 $oc->position( $l++, 1 );
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 ) {
793 my $next = shift @ordered_common;
795 foreach my $wit ( @{$self->tradition->witnesses} ) {
796 # Key to the path is not important; we just have to get
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;
807 # Transform the path values from unique strings to arrays.
808 foreach my $k ( keys %paths ) {
809 my @v = split( /\s+/, $paths{$k} );
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} ) {
820 my $rdg = $self->reading( $path->[$i] );
821 unless( $rdg->has_position ) {
822 $rdg->position( $first->position->common, $min, $min+$range );
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...
837 $self->init_lemmata();
840 # Helper function for the guts of calculate_positions.
843 my $track_hash = shift;
844 # Args are first, last, wit, backup
845 my @path = $self->reading_sequence( @_ );
846 # Top and tail the array
849 $track_hash->{$_[2]} = join( ' ', map { $_->name } @path )
854 sub possible_positions {
858 foreach my $r ( $self->readings ) {
859 next unless $r->has_position;
860 $positions{$r->position->maxref} = 1;
862 @answer = keys %positions;
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 );
873 foreach my $r ( $self->readings ) {
874 push( @answer, $r ) if $r->is_at_position( $position, $strict );
879 ## Lemmatizer functions
884 foreach my $position ( $self->possible_positions ) {
885 $self->lemmata->{$position} = undef;
888 foreach my $cr ( $self->common_readings ) {
889 $self->lemmata->{$cr->position->maxref} = $cr->name;
893 =item B<lemma_readings>
895 my @state = $graph->lemma_readings( @readings_delemmatized );
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.
905 A state of 1 means 'lemmatize this reading'
909 A state of 0 means 'delemmatize this reading'
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'
921 my( $self, @toggled_off_nodes ) = @_;
923 # First get the positions of those nodes which have been
925 my $positions_off = {};
926 map { $positions_off->{ $_->position->reference } = $_->name }
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.
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)
944 $active = $self->lemmata->{$pos} if exists $self->lemmata->{$pos};
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 ] );
952 unless( $fixed_positions{$pos} ) {
954 delete $self->lemmata->{$pos};
956 push( @answer, [ $off_node, $active ] );
959 # No formerly active node, so we just see if there is a currently
962 # Push the active node, whatever it is.
963 push( @answer, [ $active, 1 ] );
965 # Push the state that is there. Arbitrarily use the first node
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};
976 =item B<toggle_reading>
978 my @readings_delemmatized = $graph->toggle_reading( $reading_name );
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
987 my( $self, $rname ) = @_;
989 return unless $rname;
990 my $reading = $self->reading( $rname );
991 if( !$reading || $reading->is_common() ) {
992 # Do nothing, it's a common node.
996 my $pos = $reading->position;
997 my $fixed = $reading->position->fixed;
998 my $old_state = $self->lemmata->{$pos->reference};
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 );
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 ) )
1011 # Any node that is an identical transposed one should be off.
1012 push( @readings_off, $reading->identical_readings );
1014 @readings_off = unique_list( @readings_off );
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;
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;
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.
1040 return @readings_delemmatized;
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
1050 map { $onpath{$_->name} = 1 } $reading->neighbor_readings;
1051 my @same = grep { !$onpath{$_->name} }
1052 $self->readings_at_position( $reading->position, $strict );
1056 # Return the string that joins together a list of witnesses for
1057 # display on a single path.
1060 return join( $self->wit_list_separator, @_ );
1063 sub witnesses_of_label {
1064 my( $self, $label ) = @_;
1065 my $regex = $self->wit_list_separator;
1066 my @answer = split( /\Q$regex\E/, $label );
1073 map { $h{$_->name} = $_ } @list;
1074 return values( %h );
1077 sub add_hash_entry {
1078 my( $hash, $key, $entry ) = @_;
1079 if( exists $hash->{$key} ) {
1080 push( @{$hash->{$key}}, $entry );
1082 $hash->{$key} = [ $entry ];
1087 __PACKAGE__->meta->make_immutable;