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 ) },
32 has 'tradition' => ( # TODO should this not be ro?
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 ];
229 eval { $rel = Text::Tradition::Collation::Relationship->new( %$options ) };
231 return ( undef, $@ );
233 $self->graph->add_edge( $source, $target, $rel );
234 if( $options->{'global'} ) {
235 # Look for all readings with the source label, and if there are
236 # colocated readings with the target label, join them too.
237 foreach my $r ( grep { $_->label eq $source->label } $self->readings() ) {
238 next if $r->name eq $source->name;
239 my @colocated = grep { $_->label eq $target->label }
240 $self->same_position_as( $r );
242 warn "Multiple readings with same label at same position!"
244 my $colo = $colocated[0];
245 next if $colo->edges_to( $r ) || $r->edges_to( $colo );
246 $options->{'primary_relation'} = $options->{'this_relation'};
247 $options->{'this_relation'} = [ $r, $colocated[0] ];
248 my $dup_rel = Text::Tradition::Collation::Relationship->new( %$options );
249 $self->graph->add_edge( $r, $colocated[0], $dup_rel );
250 push( @joined, [ $r->name, $colocated[0]->name ] );
254 return( 1, @joined );
257 =head2 Output method(s)
263 print $graph->as_svg( $recalculate );
265 Returns an SVG string that represents the graph. Uses GraphViz to do
266 this, because Graph::Easy doesn\'t cope well with long graphs. Unless
267 $recalculate is passed (and is a true value), the method will return a
268 cached copy of the SVG after the first call to the method.
273 my( $self, $recalc ) = @_;
274 return $self->svg if $self->has_svg;
276 $self->collapse_graph_paths();
278 my @cmd = qw/dot -Tsvg/;
280 my $in = $self->as_dot();
281 run( \@cmd, \$in, ">", binary(), \$svg );
282 $self->_save_svg( $svg );
283 $self->expand_graph_paths();
289 print $graph->as_dot( $view, $recalculate );
291 Returns a string that is the collation graph expressed in dot
292 (i.e. GraphViz) format. The 'view' argument determines what kind of
294 * 'path': a graph of witness paths through the collation (DEFAULT)
295 * 'relationship': a graph of how collation readings relate to
301 my( $self, $view ) = @_;
302 $view = 'path' unless $view;
303 # TODO consider making some of these things configurable
304 my $dot = sprintf( "digraph %s {\n", $self->tradition->name );
305 $dot .= "\tedge [ arrowhead=open ];\n";
306 $dot .= "\tgraph [ rankdir=LR ];\n";
307 $dot .= sprintf( "\tnode [ fontsize=%d, fillcolor=%s, style=%s, shape=%s ];\n",
308 11, "white", "filled", $self->graph->get_attribute( 'node', 'shape' ) );
310 foreach my $reading ( $self->readings ) {
311 # Need not output nodes without separate labels
312 next if $reading->name eq $reading->label;
313 # TODO output readings or segments, but not both
314 next if $reading->class eq 'node.segment';
315 $dot .= sprintf( "\t\"%s\" [ label=\"%s\" ];\n", $reading->name, $reading->label );
318 my @edges = $view eq 'relationship' ? $self->relationships : $self->paths;
319 foreach my $edge ( @edges ) {
320 my %variables = ( 'color' => '#000000',
321 'fontcolor' => '#000000',
322 'label' => $edge->label,
324 my $varopts = join( ', ', map { $_.'="'.$variables{$_}.'"' } sort keys %variables );
325 $dot .= sprintf( "\t\"%s\" -> \"%s\" [ %s ];\n",
326 $edge->from->name, $edge->to->name, $varopts );
334 print $graph->as_graphml( $recalculate )
336 Returns a GraphML representation of the collation graph, with
337 transposition information and position information. Unless
338 $recalculate is passed (and is a true value), the method will return a
339 cached copy of the SVG after the first call to the method.
344 my( $self, $recalc ) = @_;
345 return $self->graphml if $self->has_graphml;
348 my $graphml_ns = 'http://graphml.graphdrawing.org/xmlns';
349 my $xsi_ns = 'http://www.w3.org/2001/XMLSchema-instance';
350 my $graphml_schema = 'http://graphml.graphdrawing.org/xmlns ' .
351 'http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd';
353 # Create the document and root node
354 my $graphml = XML::LibXML->createDocument( "1.0", "UTF-8" );
355 my $root = $graphml->createElementNS( $graphml_ns, 'graphml' );
356 $graphml->setDocumentElement( $root );
357 $root->setNamespace( $xsi_ns, 'xsi', 0 );
358 $root->setAttributeNS( $xsi_ns, 'schemaLocation', $graphml_schema );
360 # TODO Add some global graph data
362 # Add the data keys for nodes
365 foreach my $datum ( qw/ name reading identical position class / ) {
366 $node_data_keys{$datum} = 'dn'.$ndi++;
367 my $key = $root->addNewChild( $graphml_ns, 'key' );
368 $key->setAttribute( 'attr.name', $datum );
369 $key->setAttribute( 'attr.type', 'string' );
370 $key->setAttribute( 'for', 'node' );
371 $key->setAttribute( 'id', $node_data_keys{$datum} );
374 # Add the data keys for edges, i.e. witnesses
377 foreach my $edge_key( qw/ witness_main witness_ante_corr relationship class / ) {
378 $edge_data_keys{$edge_key} = 'de'.$edi++;
379 my $key = $root->addNewChild( $graphml_ns, 'key' );
380 $key->setAttribute( 'attr.name', $edge_key );
381 $key->setAttribute( 'attr.type', 'string' );
382 $key->setAttribute( 'for', 'edge' );
383 $key->setAttribute( 'id', $edge_data_keys{$edge_key} );
386 # Add the graph, its nodes, and its edges
387 my $graph = $root->addNewChild( $graphml_ns, 'graph' );
388 $graph->setAttribute( 'edgedefault', 'directed' );
389 $graph->setAttribute( 'id', 'g0' ); # TODO make this meaningful
390 $graph->setAttribute( 'parse.edgeids', 'canonical' );
391 $graph->setAttribute( 'parse.edges', scalar($self->paths) );
392 $graph->setAttribute( 'parse.nodeids', 'canonical' );
393 $graph->setAttribute( 'parse.nodes', scalar($self->readings) );
394 $graph->setAttribute( 'parse.order', 'nodesfirst' );
398 # Add our readings to the graph
399 foreach my $n ( sort { $a->name cmp $b->name } $self->readings ) {
400 my $node_el = $graph->addNewChild( $graphml_ns, 'node' );
401 my $node_xmlid = 'n' . $node_ctr++;
402 $node_hash{ $n->name } = $node_xmlid;
403 $node_el->setAttribute( 'id', $node_xmlid );
404 _add_graphml_data( $node_el, $node_data_keys{'name'}, $n->name );
405 _add_graphml_data( $node_el, $node_data_keys{'reading'}, $n->label );
406 _add_graphml_data( $node_el, $node_data_keys{'position'}, $n->position->reference )
408 _add_graphml_data( $node_el, $node_data_keys{'class'}, $n->sub_class );
409 _add_graphml_data( $node_el, $node_data_keys{'identical'}, $n->primary->name )
413 # Add any segments we have
414 foreach my $n ( sort { $a->name cmp $b->name } $self->segments ) {
415 my $node_el = $graph->addNewChild( $graphml_ns, 'node' );
416 my $node_xmlid = 'n' . $node_ctr++;
417 $node_hash{ $n->name } = $node_xmlid;
418 $node_el->setAttribute( 'id', $node_xmlid );
419 _add_graphml_data( $node_el, $node_data_keys{'class'}, $n->sub_class );
420 _add_graphml_data( $node_el, $node_data_keys{'name'}, $n->name );
423 # Add the path, relationship, and segment edges
425 foreach my $e ( sort { $a->from->name cmp $b->from->name } $self->graph->edges() ) {
426 my( $name, $from, $to ) = ( 'e'.$edge_ctr++,
427 $node_hash{ $e->from->name() },
428 $node_hash{ $e->to->name() } );
429 my $edge_el = $graph->addNewChild( $graphml_ns, 'edge' );
430 $edge_el->setAttribute( 'source', $from );
431 $edge_el->setAttribute( 'target', $to );
432 $edge_el->setAttribute( 'id', $name );
434 _add_graphml_data( $edge_el, $edge_data_keys{'class'}, $e->sub_class );
435 if( $e->sub_class eq 'path' ) {
436 # It's a witness path, so add the witness
437 my $base = $e->label;
438 my $key = $edge_data_keys{'witness_main'};
440 if( $e->label =~ /^(.*?)\s+(\(a\.c\.\))$/ ) {
442 $key = $edge_data_keys{'witness_ante_corr'};
444 _add_graphml_data( $edge_el, $key, $base );
445 } elsif( $e->sub_class eq 'relationship' ) {
446 # It's a relationship
447 _add_graphml_data( $edge_el, $edge_data_keys{'relationship'}, $e->label );
448 } # else a segment, nothing to record but source, target, class
452 $self->_save_graphml( $graphml->toString(1) );
453 return $graphml->toString(1);
456 sub _add_graphml_data {
457 my( $el, $key, $value ) = @_;
458 my $data_el = $el->addNewChild( $el->namespaceURI, 'data' );
459 return unless defined $value;
460 $data_el->setAttribute( 'key', $key );
461 $data_el->appendText( $value );
464 sub collapse_graph_paths {
466 # Our collation graph has an path per witness. This is great for
467 # calculation purposes, but terrible for display. Thus we want to
468 # display only one path between any two nodes.
470 return if $self->collapsed;
472 print STDERR "Collapsing witness paths in graph...\n";
474 # Don't list out every witness if we have more than half to list.
475 my $majority = int( scalar( @{$self->tradition->witnesses} ) / 2 ) + 1;
476 # But don't compress if there are only a few witnesses.
477 $majority = 4 if $majority < 4;
478 foreach my $node ( $self->readings ) {
480 # We will visit each node, so we only look ahead.
481 foreach my $edge ( $node->outgoing() ) {
482 next unless $edge->class eq 'edge.path';
483 add_hash_entry( $newlabels, $edge->to->name, $edge->name );
484 $self->del_path( $edge );
487 foreach my $newdest ( keys %$newlabels ) {
489 my @compressed_wits = ();
490 if( @{$newlabels->{$newdest}} < $majority ) {
491 $label = join( ', ', sort( @{$newlabels->{$newdest}} ) );
493 ## TODO FIX THIS HACK
495 foreach my $wit ( @{$newlabels->{$newdest}} ) {
496 if( $wit =~ /^(.*?)(\s*\(?a\.\s*c\.\)?)$/ ) {
497 push( @aclabels, $wit );
499 push( @compressed_wits, $wit );
502 $label = join( ', ', 'majority', sort( @aclabels ) );
506 $self->add_path( $node, $self->reading( $newdest ), $label );
507 if( @compressed_wits ) {
508 $newpath->hidden_witnesses( \@compressed_wits );
513 $self->collapsed( 1 );
516 sub expand_graph_paths {
518 # Our collation graph has only one path between any two nodes.
519 # This is great for display, but not so great for analysis.
520 # Expand this so that each witness has its own path between any
522 return unless $self->collapsed;
524 print STDERR "Expanding witness paths in graph...\n";
525 foreach my $path( $self->paths ) {
526 my $from = $path->from;
528 my @wits = split( /, /, $path->label );
529 if( $path->has_hidden_witnesses ) {
530 push( @wits, @{$path->hidden_witnesses} );
532 $self->del_path( $path );
534 $self->add_path( $from, $to, $_ );
537 $self->collapsed( 0 );
542 =head2 Navigation methods
548 my $beginning = $collation->start();
550 Returns the beginning of the collation, a meta-reading with label '#START#'.
555 # Return the beginning reading of the graph.
557 my( $new_start ) = @_;
559 $self->del_reading( '#START#' );
560 $self->graph->rename_node( $new_start, '#START#' );
562 return $self->reading('#START#');
565 =item B<reading_sequence>
567 my @readings = $graph->reading_sequence( $first, $last, $path[, $alt_path] );
569 Returns the ordered list of readings, starting with $first and ending
570 with $last, along the given witness path. If no path is specified,
571 assume that the path is that of the base text (if any.)
575 sub reading_sequence {
576 my( $self, $start, $end, $witness, $backup ) = @_;
578 $witness = $self->baselabel unless $witness;
579 my @readings = ( $start );
582 while( $n && $n ne $end ) {
583 if( exists( $seen{$n->name()} ) ) {
584 warn "Detected loop at " . $n->name();
587 $seen{$n->name()} = 1;
589 my $next = $self->next_reading( $n, $witness, $backup );
590 warn "Did not find any path for $witness from reading " . $n->name
592 push( @readings, $next );
595 # Check that the last reading is our end reading.
596 my $last = $readings[$#readings];
597 warn "Last reading found from " . $start->label() .
598 " for witness $witness is not the end!"
599 unless $last eq $end;
604 =item B<next_reading>
606 my $next_reading = $graph->next_reading( $reading, $witpath );
608 Returns the reading that follows the given reading along the given witness
614 # Return the successor via the corresponding path.
616 return $self->_find_linked_reading( 'next', @_ );
619 =item B<prior_reading>
621 my $prior_reading = $graph->prior_reading( $reading, $witpath );
623 Returns the reading that precedes the given reading along the given witness
629 # Return the predecessor via the corresponding path.
631 return $self->_find_linked_reading( 'prior', @_ );
634 sub _find_linked_reading {
635 my( $self, $direction, $node, $path, $alt_path ) = @_;
636 my @linked_paths = $direction eq 'next'
637 ? $node->outgoing() : $node->incoming();
638 return undef unless scalar( @linked_paths );
640 # We have to find the linked path that contains all of the
641 # witnesses supplied in $path.
642 my( @path_wits, @alt_path_wits );
643 @path_wits = $self->witnesses_of_label( $path ) if $path;
644 @alt_path_wits = $self->witnesses_of_label( $alt_path ) if $alt_path;
647 foreach my $le ( @linked_paths ) {
648 if( $le->name eq $self->baselabel ) {
651 my @le_wits = $self->witnesses_of_label( $le->name );
652 if( _is_within( \@path_wits, \@le_wits ) ) {
653 # This is the right path.
654 return $direction eq 'next' ? $le->to() : $le->from();
655 } elsif( _is_within( \@alt_path_wits, \@le_wits ) ) {
660 # Got this far? Return the alternate path if it exists.
661 return $direction eq 'next' ? $alt_le->to() : $alt_le->from()
664 # Got this far? Return the base path if it exists.
665 return $direction eq 'next' ? $base_le->to() : $base_le->from()
668 # Got this far? We have no appropriate path.
669 warn "Could not find $direction node from " . $node->label
670 . " along path $path";
676 my( $set1, $set2 ) = @_;
677 my $ret = @$set1; # will be 0, i.e. false, if set1 is empty
678 foreach my $el ( @$set1 ) {
679 $ret = 0 unless grep { /^\Q$el\E$/ } @$set2;
685 ## INITIALIZATION METHODS - for use by parsers
686 # Walk the paths for each witness in the graph, and return the nodes
687 # that the graph has in common. If $using_base is true, some
688 # different logic is needed.
690 sub walk_witness_paths {
691 my( $self, $end ) = @_;
692 # For each witness, walk the path through the graph.
693 # Then we need to find the common nodes.
694 # TODO This method is going to fall down if we have a very gappy
695 # text in the collation.
698 foreach my $wit ( @{$self->tradition->witnesses} ) {
699 my $curr_reading = $self->start;
700 my @wit_path = $self->reading_sequence( $self->start, $end,
702 $wit->path( \@wit_path );
704 # Detect the common readings.
705 @common_readings = _find_common( \@common_readings, \@wit_path );
708 # Mark all the nodes as either common or not.
709 foreach my $cn ( @common_readings ) {
710 print STDERR "Setting " . $cn->name . " / " . $cn->label
711 . " as common node\n";
714 foreach my $n ( $self->readings() ) {
715 $n->make_variant unless $n->is_common;
717 # Return an array of the common nodes in order.
718 return @common_readings;
722 my( $common_readings, $new_path ) = @_;
724 if( @$common_readings ) {
725 foreach my $n ( @$new_path ) {
726 push( @cr, $n ) if grep { $_ eq $n } @$common_readings;
729 push( @cr, @$new_path );
735 my( $common_readings, $divergence ) = @_;
738 map { $diverged{$_->name} = 1 } @$divergence;
739 foreach( @$common_readings ) {
740 push( @cr, $_ ) unless $diverged{$_->name};
746 # An alternative to walk_witness_paths, for use when a collation is
747 # constructed from a base text and an apparatus. We have the
748 # sequences of readings and just need to add path edges.
750 sub make_witness_paths {
754 foreach my $wit ( @{$self->tradition->witnesses} ) {
755 print STDERR "Making path for " . $wit->sigil . "\n";
756 $self->make_witness_path( $wit );
757 @common_readings = _find_common( \@common_readings, $wit->path );
758 @common_readings = _find_common( \@common_readings, $wit->uncorrected_path );
760 map { $_->make_common } @common_readings;
761 return @common_readings;
764 sub make_witness_path {
765 my( $self, $wit ) = @_;
766 my @chain = @{$wit->path};
767 my $sig = $wit->sigil;
768 foreach my $idx ( 0 .. $#chain-1 ) {
769 $self->add_path( $chain[$idx], $chain[$idx+1], $sig );
771 @chain = @{$wit->uncorrected_path};
772 foreach my $idx( 0 .. $#chain-1 ) {
773 my $source = $chain[$idx];
774 my $target = $chain[$idx+1];
775 $self->add_path( $source, $target, $sig.$self->ac_label )
776 unless $self->has_path( $source, $target, $sig );
780 sub common_readings {
782 my @common = grep { $_->is_common } $self->readings();
783 return sort { $a->position->cmp_with( $b->position ) } @common;
786 # Calculate the relative positions of nodes in the graph, if they
787 # were not given to us.
788 sub calculate_positions {
789 my( $self, @ordered_common ) = @_;
791 # First assign positions to all the common nodes.
793 foreach my $oc ( @ordered_common ) {
794 $oc->position( $l++, 1 );
797 if( $self->linear ) {
798 # For the space between each common node, we have to find all the chains
799 # from all the witnesses. The longest chain gives us our max, and the
800 # others get min/max ranges to fit.
801 my $first = shift @ordered_common;
802 while( @ordered_common ) {
804 my $next = shift @ordered_common;
806 foreach my $wit ( @{$self->tradition->witnesses} ) {
807 # Key to the path is not important; we just have to get
809 my $length = $self->_track_paths( \%paths, $first, $next, $wit->sigil );
810 $longest = $length unless $longest > $length;
811 if( $wit->has_ante_corr ) {
812 my $length = $self->_track_paths( \%paths, $first, $next,
813 $wit->sigil.$self->ac_label, $wit->sigil );
814 $longest = $length unless $longest > $length;
818 # Transform the path values from unique strings to arrays.
820 foreach my $k ( keys %paths ) {
821 my @v = split( /\s+/, $k );
822 push( @all_paths, \@v );
824 @all_paths = sort { scalar @$b <=> scalar @$a } @all_paths;
826 # Now %paths has all the unique paths, and we know how long the
827 # longest of these is. Assign positions, starting with the
828 # longest. All non-common positions start at 2.
829 foreach my $path ( @all_paths ) {
830 # Initially each element has a minimum position of 2
831 # plus its position in the array (1 is the common
832 # node), and a max position of the longest array
833 # length minus its position in the array.
834 my $range = $longest - scalar @$path;
836 foreach my $i ( 0 .. $#{$path} ) {
837 my $rdg = $self->reading( $path->[$i] );
838 if( $rdg->has_position ) {
839 # This reading has already had a more specific
840 # position set, so we need to take that into
841 # account when calculating the min and max for
843 my $rangeminus = $rdg->position->min - $min;
844 $min = $rdg->position->min + 1;
845 $range = $range - $rangeminus;
847 print STDERR "Negative range for position! " . $rdg->name . "\n"; # May remove this warning
851 $rdg->position( $first->position->common, $min, $min+$range );
853 $longest = $min+$range-2 unless $longest+2 > $min+$range; # min starts at 2 but longest assumes 0 start
857 # Now go through again and make sure the positions are
858 # monotonic. Do this until they are.
861 until( $monotonic ) {
864 foreach my $path ( @all_paths ) {
865 foreach my $i ( 0 .. $#{$path} ) {
866 my $rdg = $self->reading( $path->[$i] );
867 my $prior = $self->reading( $path->[$i-1] ) if $i > 0;
868 my $next = $self->reading( $path->[$i+1] ) if $i < $#{$path};
869 if( $prior && $rdg->position->min <= $prior->position->min ) {
871 $rdg->position->min( $prior->position->min + 1 );
873 if( $next && $rdg->position->max >= $next->position->max ) {
875 if( $next->position->max - 1 >= $rdg->position->min ) {
876 # If moving rdg/max down would not send it below
878 $rdg->position->max( $next->position->max - 1 );
880 # Otherwise increase next/max.
881 $next->position->max( $rdg->position->max + 1 );
882 # ...min will be fixed on the next pass.
887 if( $counter > $#all_paths + 1 && !$monotonic ) {
888 # We risk an infinite loop. Get out of here.
889 warn "Still not monotonic after $counter passes at common point "
890 . $first->position->common;
894 print STDERR "Took $counter passes for monotonicity at " . $first->position->common. "\n"
902 # Non-linear positions are pretty much impossible to pin down.
903 # Any reading might appear anywhere in the graph. I guess we
904 # can do positions where there aren't transpositions...
907 $self->init_lemmata();
910 # Helper function for the guts of calculate_positions.
913 my $track_hash = shift;
914 # Args are first, last, wit, backup
915 my @path = $self->reading_sequence( @_ );
916 # Top and tail the array
919 $track_hash->{join( ' ', map { $_->name } @path )} = $_[2]
924 sub possible_positions {
928 foreach my $r ( $self->readings ) {
929 next unless $r->has_position;
930 $positions{$r->position->maxref} = 1;
932 @answer = keys %positions;
936 # TODO think about indexing this.
937 sub readings_at_position {
938 my( $self, $position, $strict ) = @_;
939 unless( ref( $position ) eq 'Text::Tradition::Collation::Position' ) {
940 $position = Text::Tradition::Collation::Position->new( $position );
943 foreach my $r ( $self->readings ) {
944 push( @answer, $r ) if $r->is_at_position( $position, $strict );
949 ## Lemmatizer functions
954 foreach my $position ( $self->possible_positions ) {
955 $self->lemmata->{$position} = undef;
958 foreach my $cr ( $self->common_readings ) {
959 $self->lemmata->{$cr->position->maxref} = $cr->name;
963 =item B<lemma_readings>
965 my @state = $graph->lemma_readings( @readings_delemmatized );
967 Takes a list of readings that have just been delemmatized, and returns
968 a set of tuples of the form ['reading', 'state'] that indicates what
969 changes need to be made to the graph.
975 A state of 1 means 'lemmatize this reading'
979 A state of 0 means 'delemmatize this reading'
983 A state of undef means 'an ellipsis belongs in the text here because
984 no decision has been made / an earlier decision was backed out'
991 my( $self, @toggled_off_nodes ) = @_;
993 # First get the positions of those nodes which have been
995 my $positions_off = {};
996 map { $positions_off->{ $_->position->reference } = $_->name }
999 # Now for each position, we have to see if a node is on, and we
1000 # have to see if a node has been turned off. The lemmata hash
1001 # should contain fixed positions, range positions whose node was
1002 # just turned off, and range positions whose node is on.
1004 my %fixed_positions;
1005 # TODO One of these is probably redundant.
1006 map { $fixed_positions{$_} = 0 } keys %{$self->lemmata};
1007 map { $fixed_positions{$_} = 0 } keys %{$positions_off};
1008 map { $fixed_positions{$_} = 1 } $self->possible_positions;
1009 foreach my $pos ( sort { Text::Tradition::Collation::Position::str_cmp( $a, $b ) } keys %fixed_positions ) {
1010 # Find the state of this position. If there is an active node,
1011 # its name will be the state; otherwise the state will be 0
1012 # (nothing at this position) or undef (ellipsis at this position)
1014 $active = $self->lemmata->{$pos} if exists $self->lemmata->{$pos};
1016 # Is there a formerly active node that was toggled off?
1017 if( exists( $positions_off->{$pos} ) ) {
1018 my $off_node = $positions_off->{$pos};
1019 if( $active && $active ne $off_node) {
1020 push( @answer, [ $off_node, 0 ], [ $active, 1 ] );
1022 unless( $fixed_positions{$pos} ) {
1024 delete $self->lemmata->{$pos};
1026 push( @answer, [ $off_node, $active ] );
1029 # No formerly active node, so we just see if there is a currently
1031 } elsif( $active ) {
1032 # Push the active node, whatever it is.
1033 push( @answer, [ $active, 1 ] );
1035 # Push the state that is there. Arbitrarily use the first node
1037 my @pos_nodes = $self->readings_at_position( $pos );
1038 push( @answer, [ $pos_nodes[0]->name, $self->lemmata->{$pos} ] );
1039 delete $self->lemmata->{$pos} unless $fixed_positions{$pos};
1046 =item B<toggle_reading>
1048 my @readings_delemmatized = $graph->toggle_reading( $reading_name );
1050 Takes a reading node name, and either lemmatizes or de-lemmatizes
1051 it. Returns a list of all readings that are de-lemmatized as a result
1056 sub toggle_reading {
1057 my( $self, $rname ) = @_;
1059 return unless $rname;
1060 my $reading = $self->reading( $rname );
1061 if( !$reading || $reading->is_common() ) {
1062 # Do nothing, it's a common node.
1066 my $pos = $reading->position;
1067 my $fixed = $reading->position->fixed;
1068 my $old_state = $self->lemmata->{$pos->reference};
1071 if( $old_state && $old_state eq $rname ) {
1072 # Turn off the node. We turn on no others by default.
1073 push( @readings_off, $reading );
1076 $self->lemmata->{$pos->reference} = $rname;
1077 # Any other 'on' readings in the same position should be off
1078 # if we have a fixed position.
1079 push( @readings_off, $self->same_position_as( $reading, 1 ) )
1081 # Any node that is an identical transposed one should be off.
1082 push( @readings_off, $reading->identical_readings );
1084 @readings_off = unique_list( @readings_off );
1086 # Turn off the readings that need to be turned off.
1087 my @readings_delemmatized;
1088 foreach my $n ( @readings_off ) {
1089 my $npos = $n->position;
1091 $state = $self->lemmata->{$npos->reference}
1092 if defined $self->lemmata->{$npos->reference};
1093 if( $state && $state eq $n->name ) {
1094 # this reading is still on, so turn it off
1095 push( @readings_delemmatized, $n );
1096 my $new_state = undef;
1097 if( $npos->fixed && $n eq $reading ) {
1098 # This is the reading that was clicked, so if there are no
1099 # other readings there and this is a fixed position, turn off
1100 # the position. In all other cases, restore the ellipsis.
1101 my @other_n = $self->same_position_as( $n ); # TODO do we need strict?
1102 $new_state = 0 unless @other_n;
1104 $self->lemmata->{$npos->reference} = $new_state;
1105 } elsif( $old_state && $old_state eq $n->name ) {
1106 # another reading has already been turned on here
1107 push( @readings_delemmatized, $n );
1108 } # else some other reading was on anyway, so pass.
1110 return @readings_delemmatized;
1113 sub same_position_as {
1114 my( $self, $reading, $strict ) = @_;
1115 my $pos = $reading->position;
1116 my %onpath = ( $reading->name => 1 );
1117 # TODO This might not always be sufficient. We really want to
1118 # exclude all readings on this one's path between its two
1120 map { $onpath{$_->name} = 1 } $reading->neighbor_readings;
1121 my @same = grep { !$onpath{$_->name} }
1122 $self->readings_at_position( $reading->position, $strict );
1126 # Return the string that joins together a list of witnesses for
1127 # display on a single path.
1130 return join( $self->wit_list_separator, @_ );
1133 sub witnesses_of_label {
1134 my( $self, $label ) = @_;
1135 my $regex = $self->wit_list_separator;
1136 my @answer = split( /\Q$regex\E/, $label );
1143 map { $h{$_->name} = $_ } @list;
1144 return values( %h );
1147 sub add_hash_entry {
1148 my( $hash, $key, $entry ) = @_;
1149 if( exists $hash->{$key} ) {
1150 push( @{$hash->{$key}}, $entry );
1152 $hash->{$key} = [ $entry ];
1157 __PACKAGE__->meta->make_immutable;