1 package Text::Tradition::Collation;
3 use Encode qw( decode_utf8 );
6 use IPC::Run qw( run binary );
8 use Text::Tradition::Collation::Path;
9 use Text::Tradition::Collation::Reading;
10 use Text::Tradition::Collation::Relationship;
11 use Text::Tradition::Collation::Segment;
19 add_reading => 'add_node',
20 del_reading => 'del_node',
21 del_segment => 'del_node',
22 add_path => 'add_edge',
23 del_path => 'del_edge',
29 relationships => 'edges',
31 default => sub { Graph::Easy->new( undirected => 0 ) },
35 has 'tradition' => ( # TODO should this not be ro?
37 isa => 'Text::Tradition',
43 writer => '_save_svg',
44 predicate => 'has_svg',
50 writer => '_save_graphml',
51 predicate => 'has_graphml',
57 writer => '_save_csv',
58 predicate => 'has_csv',
61 # Keeps track of the lemmas within the collation. At most one lemma
62 # per position in the graph.
65 isa => 'HashRef[Maybe[Str]]',
66 default => sub { {} },
69 has 'wit_list_separator' => (
78 default => 'base text',
99 # The collation can be created two ways:
100 # 1. Collate a set of witnesses (with CollateX I guess) and process
101 # the results as in 2.
102 # 2. Read a pre-prepared collation in one of a variety of formats,
103 # and make the graph from that.
105 # The graph itself will (for now) be immutable, and the positions
106 # within the graph will also be immutable. We need to calculate those
107 # positions upon graph construction. The equivalences between graph
108 # nodes will be mutable, entirely determined by the user (or possibly
109 # by some semantic pre-processing provided by the user.) So the
110 # constructor should just make an empty equivalences object. The
111 # constructor will also need to make the witness objects, if we didn't
112 # come through option 1.
115 my( $self, $args ) = @_;
116 $self->graph->use_class('node', 'Text::Tradition::Collation::Reading');
117 $self->graph->use_class('edge', 'Text::Tradition::Collation::Path');
119 # Pass through any graph-specific options.
120 my $shape = exists( $args->{'shape'} ) ? $args->{'shape'} : 'ellipse';
121 $self->graph->set_attribute( 'node', 'shape', $shape );
124 # Wrapper around add_path
126 around add_path => sub {
130 # Make sure there are three arguments
132 warn "Call add_path with args source, target, witness";
135 # Make sure the proposed path does not yet exist
136 # NOTE 'reading' will currently return readings and segments
137 my( $source, $target, $wit ) = @_;
138 $source = $self->reading( $source )
139 unless ref( $source ) eq 'Text::Tradition::Collation::Reading';
140 $target = $self->reading( $target )
141 unless ref( $target ) eq 'Text::Tradition::Collation::Reading';
142 foreach my $path ( $source->edges_to( $target ) ) {
143 if( $path->label eq $wit && $path->class eq 'edge.path' ) {
151 # Wrapper around paths
152 around paths => sub {
156 my @result = grep { $_->sub_class eq 'path' } $self->$orig( @_ );
160 around relationships => sub {
163 my @result = grep { $_->sub_class eq 'relationship' } $self->$orig( @_ );
167 around readings => sub {
170 my @result = grep { $_->sub_class ne 'segment' } $self->$orig( @_ );
174 around segments => sub {
177 my @result = grep { $_->sub_class eq 'segment' } $self->$orig( @_ );
181 # Wrapper around merge_nodes
185 my $first_node = shift;
186 my $second_node = shift;
187 $first_node->merge_from( $second_node );
188 unshift( @_, $first_node, $second_node );
189 return $self->graph->merge_nodes( @_ );
192 # Extra graph-alike utility
194 my( $self, $source, $target, $label ) = @_;
195 my @paths = $source->edges_to( $target );
196 my @relevant = grep { $_->label eq $label } @paths;
197 return scalar @relevant;
200 ## Dealing with groups of readings, i.e. segments.
203 my( $self, @items ) = @_;
204 my $segment = Text::Tradition::Collation::Segment->new( 'members' => \@items );
208 ## Dealing with relationships between readings. This is a different
209 ## sort of graph edge. Return a success/failure value and a list of
210 ## node pairs that have been linked.
212 sub add_relationship {
213 my( $self, $source, $target, $options ) = @_;
215 # Make sure there is not another relationship between these two
216 # readings or segments already
217 $source = $self->reading( $source )
218 unless ref( $source ) && $source->isa( 'Graph::Easy::Node' );
219 $target = $self->reading( $target )
220 unless ref( $target ) && $target->isa( 'Graph::Easy::Node' );
221 foreach my $rel ( $source->edges_to( $target ), $target->edges_to( $source ) ) {
222 if( $rel->class eq 'edge.relationship' ) {
223 return ( undef, "Relationship already exists between these readings" );
226 if( $options->{'equal_rank'} && !relationship_valid( $source, $target ) ) {
227 return ( undef, 'Relationship creates witness loop' );
230 # TODO Think about positional hilarity if relationships are added after positions
233 my @joined = ( [ $source->name, $target->name ] ); # Keep track of the nodes we join.
235 $options->{'this_relation'} = [ $source, $target ];
237 eval { $rel = Text::Tradition::Collation::Relationship->new( %$options ) };
239 return ( undef, $@ );
241 $self->graph->add_edge( $source, $target, $rel );
243 # TODO Handle global relationship setting
245 return( 1, @joined );
248 sub relationship_valid {
249 my( $source, $target ) = @_;
250 # Check that linking the source and target in a relationship won't lead
251 # to a path loop for any witness.
252 my @proposed_related = ( $source, $target );
253 push( @proposed_related, $source->related_readings );
254 push( @proposed_related, $target->related_readings );
256 map { $pr_ids{ $_->name } = 1 } @proposed_related;
257 # The lists of 'in' and 'out' should not have any element that appears
258 # in 'proposed_related'.
259 foreach my $pr ( @proposed_related ) {
260 foreach my $e ( $pr->incoming ) {
261 if( exists $pr_ids{ $e->from->name } ) {
265 foreach my $e ( $pr->outgoing ) {
266 if( exists $pr_ids{ $e->to->name } ) {
274 =head2 Output method(s)
280 print $graph->as_svg( $recalculate );
282 Returns an SVG string that represents the graph. Uses GraphViz to do
283 this, because Graph::Easy doesn\'t cope well with long graphs. Unless
284 $recalculate is passed (and is a true value), the method will return a
285 cached copy of the SVG after the first call to the method.
290 my( $self, $recalc ) = @_;
291 return $self->svg if $self->has_svg;
293 $self->collapse_graph_paths();
295 my @cmd = qw/dot -Tsvg/;
297 my $dotfile = File::Temp->new();
299 $dotfile->unlink_on_destroy(0);
300 binmode $dotfile, ':utf8';
301 print $dotfile $self->as_dot();
302 push( @cmd, $dotfile->filename );
303 run( \@cmd, ">", binary(), \$svg );
304 $svg = decode_utf8( $svg );
305 $self->_save_svg( $svg );
306 $self->expand_graph_paths();
312 print $graph->as_dot( $view, $recalculate );
314 Returns a string that is the collation graph expressed in dot
315 (i.e. GraphViz) format. The 'view' argument determines what kind of
317 * 'path': a graph of witness paths through the collation (DEFAULT)
318 * 'relationship': a graph of how collation readings relate to
324 my( $self, $view ) = @_;
325 $view = 'path' unless $view;
326 # TODO consider making some of these things configurable
327 my $dot = sprintf( "digraph %s {\n", $self->tradition->name );
328 $dot .= "\tedge [ arrowhead=open ];\n";
329 $dot .= "\tgraph [ rankdir=LR ];\n";
330 $dot .= sprintf( "\tnode [ fontsize=%d, fillcolor=%s, style=%s, shape=%s ];\n",
331 11, "white", "filled", $self->graph->get_attribute( 'node', 'shape' ) );
333 foreach my $reading ( $self->readings ) {
334 # Need not output nodes without separate labels
335 next if $reading->name eq $reading->label;
336 # TODO output readings or segments, but not both
337 next if $reading->class eq 'node.segment';
338 $dot .= sprintf( "\t\"%s\" [ label=\"%s\" ];\n", $reading->name, $reading->label );
341 my @edges = $view eq 'relationship' ? $self->relationships : $self->paths;
342 foreach my $edge ( @edges ) {
343 my %variables = ( 'color' => '#000000',
344 'fontcolor' => '#000000',
345 'label' => $edge->label,
347 my $varopts = join( ', ', map { $_.'="'.$variables{$_}.'"' } sort keys %variables );
348 $dot .= sprintf( "\t\"%s\" -> \"%s\" [ %s ];\n",
349 $edge->from->name, $edge->to->name, $varopts );
357 print $graph->as_graphml( $recalculate )
359 Returns a GraphML representation of the collation graph, with
360 transposition information and position information. Unless
361 $recalculate is passed (and is a true value), the method will return a
362 cached copy of the SVG after the first call to the method.
367 my( $self, $recalc ) = @_;
368 return $self->graphml if $self->has_graphml;
371 my $graphml_ns = 'http://graphml.graphdrawing.org/xmlns';
372 my $xsi_ns = 'http://www.w3.org/2001/XMLSchema-instance';
373 my $graphml_schema = 'http://graphml.graphdrawing.org/xmlns ' .
374 'http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd';
376 # Create the document and root node
377 my $graphml = XML::LibXML->createDocument( "1.0", "UTF-8" );
378 my $root = $graphml->createElementNS( $graphml_ns, 'graphml' );
379 $graphml->setDocumentElement( $root );
380 $root->setNamespace( $xsi_ns, 'xsi', 0 );
381 $root->setAttributeNS( $xsi_ns, 'schemaLocation', $graphml_schema );
383 # TODO Add some global graph data
385 # Add the data keys for nodes
388 foreach my $datum ( qw/ name reading identical rank class / ) {
389 $node_data_keys{$datum} = 'dn'.$ndi++;
390 my $key = $root->addNewChild( $graphml_ns, 'key' );
391 $key->setAttribute( 'attr.name', $datum );
392 $key->setAttribute( 'attr.type', 'string' );
393 $key->setAttribute( 'for', 'node' );
394 $key->setAttribute( 'id', $node_data_keys{$datum} );
397 # Add the data keys for edges, i.e. witnesses
400 foreach my $edge_key( qw/ witness_main witness_ante_corr relationship class / ) {
401 $edge_data_keys{$edge_key} = 'de'.$edi++;
402 my $key = $root->addNewChild( $graphml_ns, 'key' );
403 $key->setAttribute( 'attr.name', $edge_key );
404 $key->setAttribute( 'attr.type', 'string' );
405 $key->setAttribute( 'for', 'edge' );
406 $key->setAttribute( 'id', $edge_data_keys{$edge_key} );
409 # Add the graph, its nodes, and its edges
410 my $graph = $root->addNewChild( $graphml_ns, 'graph' );
411 $graph->setAttribute( 'edgedefault', 'directed' );
412 $graph->setAttribute( 'id', 'g0' ); # TODO make this meaningful
413 $graph->setAttribute( 'parse.edgeids', 'canonical' );
414 $graph->setAttribute( 'parse.edges', scalar($self->paths) );
415 $graph->setAttribute( 'parse.nodeids', 'canonical' );
416 $graph->setAttribute( 'parse.nodes', scalar($self->readings) );
417 $graph->setAttribute( 'parse.order', 'nodesfirst' );
421 # Add our readings to the graph
422 foreach my $n ( sort { $a->name cmp $b->name } $self->readings ) {
423 my $node_el = $graph->addNewChild( $graphml_ns, 'node' );
424 my $node_xmlid = 'n' . $node_ctr++;
425 $node_hash{ $n->name } = $node_xmlid;
426 $node_el->setAttribute( 'id', $node_xmlid );
427 _add_graphml_data( $node_el, $node_data_keys{'name'}, $n->name );
428 _add_graphml_data( $node_el, $node_data_keys{'reading'}, $n->label );
429 _add_graphml_data( $node_el, $node_data_keys{'rank'}, $n->rank )
431 _add_graphml_data( $node_el, $node_data_keys{'class'}, $n->sub_class );
432 _add_graphml_data( $node_el, $node_data_keys{'identical'}, $n->primary->name )
436 # Add any segments we have
437 foreach my $n ( sort { $a->name cmp $b->name } $self->segments ) {
438 my $node_el = $graph->addNewChild( $graphml_ns, 'node' );
439 my $node_xmlid = 'n' . $node_ctr++;
440 $node_hash{ $n->name } = $node_xmlid;
441 $node_el->setAttribute( 'id', $node_xmlid );
442 _add_graphml_data( $node_el, $node_data_keys{'class'}, $n->sub_class );
443 _add_graphml_data( $node_el, $node_data_keys{'name'}, $n->name );
446 # Add the path, relationship, and segment edges
448 foreach my $e ( sort { $a->from->name cmp $b->from->name } $self->graph->edges() ) {
449 my( $name, $from, $to ) = ( 'e'.$edge_ctr++,
450 $node_hash{ $e->from->name() },
451 $node_hash{ $e->to->name() } );
452 my $edge_el = $graph->addNewChild( $graphml_ns, 'edge' );
453 $edge_el->setAttribute( 'source', $from );
454 $edge_el->setAttribute( 'target', $to );
455 $edge_el->setAttribute( 'id', $name );
457 _add_graphml_data( $edge_el, $edge_data_keys{'class'}, $e->sub_class );
458 if( $e->sub_class eq 'path' ) {
459 # It's a witness path, so add the witness
460 my $base = $e->label;
461 my $key = $edge_data_keys{'witness_main'};
463 if( $e->label =~ /^(.*?)\s+(\(a\.c\.\))$/ ) {
465 $key = $edge_data_keys{'witness_ante_corr'};
467 _add_graphml_data( $edge_el, $key, $base );
468 } elsif( $e->sub_class eq 'relationship' ) {
469 # It's a relationship
470 _add_graphml_data( $edge_el, $edge_data_keys{'relationship'}, $e->label );
471 } # else a segment, nothing to record but source, target, class
475 $self->_save_graphml( $graphml->toString(1) );
476 return $graphml->toString(1);
479 sub _add_graphml_data {
480 my( $el, $key, $value ) = @_;
481 my $data_el = $el->addNewChild( $el->namespaceURI, 'data' );
482 return unless defined $value;
483 $data_el->setAttribute( 'key', $key );
484 $data_el->appendText( $value );
489 print $graph->as_csv( $recalculate )
491 Returns a CSV alignment table representation of the collation graph, one
492 row per witness (or witness uncorrected.) Unless $recalculate is passed
493 (and is a true value), the method will return a cached copy of the CSV
494 after the first call to the method.
499 my( $self, $recalc ) = @_;
500 return $self->csv if $self->has_csv;
501 my $table = $self->make_alignment_table;
502 my $csv = Text::CSV_XS->new( { binary => 1, quote_null => 0 } );
504 foreach my $row ( @$table ) {
505 $csv->combine( @$row );
506 push( @result, decode_utf8( $csv->string ) );
508 $self->_save_csv( join( "\n", @result ) );
512 sub make_alignment_table {
514 unless( $self->linear ) {
515 warn "Need a linear graph in order to make an alignment table";
519 my @all_pos = sort { $a <=> $b } $self->possible_positions;
520 foreach my $wit ( $self->tradition->witnesses ) {
521 my @row = _make_witness_row( $wit->path, \@all_pos );
522 unshift( @row, $wit->sigil );
523 push( @$table, \@row );
524 if( $wit->has_ante_corr ) {
525 my @ac_row = _make_witness_row( $wit->uncorrected_path, \@all_pos );
526 unshift( @ac_row, $wit->sigil . $self->ac_label );
527 push( @$table, \@ac_row );
530 # Return a table where the witnesses read in columns rather than rows.
531 my $turned = _turn_table( $table );
535 sub _make_witness_row {
536 my( $path, $positions ) = @_;
538 map { $char_hash{$_} = undef } @$positions;
539 foreach my $rdg ( @$path ) {
540 $char_hash{$rdg->rank} = $rdg->text;
542 my @row = map { $char_hash{$_} } @$positions;
546 # Helper to turn the witnesses along columns rather than rows. Assumes
551 return $result unless scalar @$table;
552 my $nrows = scalar @{$table->[0]};
553 foreach my $idx ( 0 .. $nrows - 1 ) {
554 foreach my $wit ( 0 .. $#{$table} ) {
555 $result->[$idx]->[$wit] = $table->[$wit]->[$idx];
562 sub collapse_graph_paths {
564 # Our collation graph has an path per witness. This is great for
565 # calculation purposes, but terrible for display. Thus we want to
566 # display only one path between any two nodes.
568 return if $self->collapsed;
570 print STDERR "Collapsing witness paths in graph...\n";
572 # Don't list out every witness if we have more than half to list.
573 my $majority = int( scalar( $self->tradition->witnesses ) / 2 ) + 1;
574 # But don't compress if there are only a few witnesses.
575 $majority = 4 if $majority < 4;
576 foreach my $node ( $self->readings ) {
578 # We will visit each node, so we only look ahead.
579 foreach my $edge ( $node->outgoing() ) {
580 next unless $edge->class eq 'edge.path';
581 add_hash_entry( $newlabels, $edge->to->name, $edge->name );
582 $self->del_path( $edge );
585 foreach my $newdest ( keys %$newlabels ) {
587 my @compressed_wits = @{$newlabels->{$newdest}};
588 if( @compressed_wits < $majority ) {
589 $label = join( ', ', sort( @{$newlabels->{$newdest}} ) );
591 ## TODO FIX THIS HACK
593 foreach my $wit ( @compressed_wits ) {
594 push( @aclabels, $wit ) if( $wit =~ /^(.*?)(\s*\(?a\.\s*c\.\)?)$/ );
596 $label = join( ', ', 'majority', sort( @aclabels ) );
599 my $newpath = $self->add_path( $node, $self->reading( $newdest ), $label );
600 $newpath->hidden_witnesses( \@compressed_wits );
604 $self->collapsed( 1 );
607 sub expand_graph_paths {
609 # Our collation graph has only one path between any two nodes.
610 # This is great for display, but not so great for analysis.
611 # Expand this so that each witness has its own path between any
613 return unless $self->collapsed;
615 print STDERR "Expanding witness paths in graph...\n";
616 foreach my $path( $self->paths ) {
617 my $from = $path->from;
619 warn sprintf( "No hidden witnesses on %s -> %s ?", $from->name, $to->name )
620 unless $path->has_hidden_witnesses;
621 my @wits = @{$path->hidden_witnesses};
622 $self->del_path( $path );
624 $self->add_path( $from, $to, $_ );
627 $self->collapsed( 0 );
632 =head2 Navigation methods
638 my $beginning = $collation->start();
640 Returns the beginning of the collation, a meta-reading with label '#START#'.
645 # Return the beginning reading of the graph.
647 my( $new_start ) = @_;
649 $self->del_reading( '#START#' );
650 $self->graph->rename_node( $new_start, '#START#' );
652 # Make sure the start node has a start position.
653 unless( $self->reading( '#START#' )->has_rank ) {
654 $self->reading( '#START#' )->rank( '0' );
656 return $self->reading('#START#');
661 my $end = $collation->end();
663 Returns the end of the collation, a meta-reading with label '#END#'.
671 $self->del_reading( '#END#' );
672 $self->graph->rename_node( $new_end, '#END#' );
674 return $self->reading('#END#');
677 =item B<reading_sequence>
679 my @readings = $graph->reading_sequence( $first, $last, $path[, $alt_path] );
681 Returns the ordered list of readings, starting with $first and ending
682 with $last, along the given witness path. If no path is specified,
683 assume that the path is that of the base text (if any.)
687 # TODO Think about returning some lazy-eval iterator.
689 sub reading_sequence {
690 my( $self, $start, $end, $witness, $backup ) = @_;
692 $witness = $self->baselabel unless $witness;
693 my @readings = ( $start );
696 while( $n && $n ne $end ) {
697 if( exists( $seen{$n->name()} ) ) {
698 warn "Detected loop at " . $n->name();
701 $seen{$n->name()} = 1;
703 my $next = $self->next_reading( $n, $witness, $backup );
704 warn "Did not find any path for $witness from reading " . $n->name
706 push( @readings, $next );
709 # Check that the last reading is our end reading.
710 my $last = $readings[$#readings];
711 warn "Last reading found from " . $start->label() .
712 " for witness $witness is not the end!"
713 unless $last eq $end;
718 =item B<next_reading>
720 my $next_reading = $graph->next_reading( $reading, $witpath );
722 Returns the reading that follows the given reading along the given witness
728 # Return the successor via the corresponding path.
730 return $self->_find_linked_reading( 'next', @_ );
733 =item B<prior_reading>
735 my $prior_reading = $graph->prior_reading( $reading, $witpath );
737 Returns the reading that precedes the given reading along the given witness
743 # Return the predecessor via the corresponding path.
745 return $self->_find_linked_reading( 'prior', @_ );
748 sub _find_linked_reading {
749 my( $self, $direction, $node, $path, $alt_path ) = @_;
750 my @linked_paths = $direction eq 'next'
751 ? $node->outgoing() : $node->incoming();
752 return undef unless scalar( @linked_paths );
754 # We have to find the linked path that contains all of the
755 # witnesses supplied in $path.
756 my( @path_wits, @alt_path_wits );
757 @path_wits = $self->witnesses_of_label( $path ) if $path;
758 @alt_path_wits = $self->witnesses_of_label( $alt_path ) if $alt_path;
761 foreach my $le ( @linked_paths ) {
762 if( $le->name eq $self->baselabel ) {
765 my @le_wits = $self->witnesses_of_label( $le->name );
766 if( _is_within( \@path_wits, \@le_wits ) ) {
767 # This is the right path.
768 return $direction eq 'next' ? $le->to() : $le->from();
769 } elsif( _is_within( \@alt_path_wits, \@le_wits ) ) {
774 # Got this far? Return the alternate path if it exists.
775 return $direction eq 'next' ? $alt_le->to() : $alt_le->from()
778 # Got this far? Return the base path if it exists.
779 return $direction eq 'next' ? $base_le->to() : $base_le->from()
782 # Got this far? We have no appropriate path.
783 warn "Could not find $direction node from " . $node->label
784 . " along path $path";
790 my( $set1, $set2 ) = @_;
791 my $ret = @$set1; # will be 0, i.e. false, if set1 is empty
792 foreach my $el ( @$set1 ) {
793 $ret = 0 unless grep { /^\Q$el\E$/ } @$set2;
799 ## INITIALIZATION METHODS - for use by parsers
800 # Walk the paths for each witness in the graph, and return the nodes
801 # that the graph has in common. If $using_base is true, some
802 # different logic is needed.
803 # NOTE This does not create paths; it merely finds common readings.
805 sub walk_witness_paths {
807 # For each witness, walk the path through the graph.
808 # Then we need to find the common nodes.
809 # TODO This method is going to fall down if we have a very gappy
810 # text in the collation.
813 foreach my $wit ( $self->tradition->witnesses ) {
814 my $curr_reading = $self->start;
815 my @wit_path = $self->reading_sequence( $self->start, $self->end,
817 $wit->path( \@wit_path );
819 # Detect the common readings.
820 @common_readings = _find_common( \@common_readings, \@wit_path );
823 # Mark all the nodes as either common or not.
824 foreach my $cn ( @common_readings ) {
825 print STDERR "Setting " . $cn->name . " / " . $cn->label
826 . " as common node\n";
829 foreach my $n ( $self->readings() ) {
830 $n->make_variant unless $n->is_common;
832 # Return an array of the common nodes in order.
833 return @common_readings;
837 my( $common_readings, $new_path ) = @_;
839 if( @$common_readings ) {
840 foreach my $n ( @$new_path ) {
841 push( @cr, $n ) if grep { $_ eq $n } @$common_readings;
844 push( @cr, @$new_path );
850 my( $common_readings, $divergence ) = @_;
853 map { $diverged{$_->name} = 1 } @$divergence;
854 foreach( @$common_readings ) {
855 push( @cr, $_ ) unless $diverged{$_->name};
861 # For use when a collation is constructed from a base text and an apparatus.
862 # We have the sequences of readings and just need to add path edges.
864 sub make_witness_paths {
866 foreach my $wit ( $self->tradition->witnesses ) {
867 print STDERR "Making path for " . $wit->sigil . "\n";
868 $self->make_witness_path( $wit );
872 sub make_witness_path {
873 my( $self, $wit ) = @_;
874 my @chain = @{$wit->path};
875 my $sig = $wit->sigil;
876 foreach my $idx ( 0 .. $#chain-1 ) {
877 $self->add_path( $chain[$idx], $chain[$idx+1], $sig );
879 if( $wit->has_ante_corr ) {
880 @chain = @{$wit->uncorrected_path};
881 foreach my $idx( 0 .. $#chain-1 ) {
882 my $source = $chain[$idx];
883 my $target = $chain[$idx+1];
884 $self->add_path( $source, $target, $sig.$self->ac_label )
885 unless $self->has_path( $source, $target, $sig );
890 sub calculate_ranks {
892 # Walk a version of the graph where every node linked by a relationship
893 # edge is fundamentally the same node, and do a topological ranking on
894 # the nodes in this graph.
895 my $topo_graph = Graph::Easy->new();
899 foreach my $r ( $self->readings ) {
900 next if exists $rel_containers{$r->name};
901 my @rels = $r->related_readings( 'colocated' );
903 # Make a relationship container.
905 my $rn = $topo_graph->add_node( 'rel_container_' . $rel_ctr++ );
907 $rel_containers{$_->name} = $rn;
910 # Add a new node to mirror the old node.
911 $rel_containers{$r->name} = $topo_graph->add_node( $r->name );
915 # Add the edges. Need only one edge between any pair of nodes.
916 foreach my $r ( $self->readings ) {
917 foreach my $n ( $r->neighbor_readings( 'forward' ) ) {
918 $topo_graph->add_edge_once( $rel_containers{$r->name},
919 $rel_containers{$n->name} );
923 # Now do the rankings, starting with the start node.
924 my $topo_start = $rel_containers{$self->start->name};
925 my $node_ranks = { $topo_start->name => 0 };
926 my @curr_origin = ( $topo_start );
927 # A little iterative function.
928 while( @curr_origin ) {
929 @curr_origin = _assign_rank( $node_ranks, @curr_origin );
931 # Transfer our rankings from the topological graph to the real one.
932 foreach my $r ( $self->readings ) {
933 $r->rank( $node_ranks->{$rel_containers{$r->name}->name} );
938 my( $node_ranks, @current_nodes ) = @_;
939 # Look at each of the children of @current_nodes. If all the child's
940 # parents have a rank, assign it the highest rank + 1 and add it to
941 # @next_nodes. Otherwise skip it.
943 foreach my $c ( @current_nodes ) {
944 warn "Current reading " . $c->name . "has no rank!"
945 unless exists $node_ranks->{$c->name};
946 # print STDERR "Looking at child of node " . $c->name . ", rank "
947 # . $node_ranks->{$c->name} . "\n";
948 my @children = map { $_->to } $c->outgoing;
949 foreach my $child ( @children ) {
950 next if exists $node_ranks->{$child->name};
951 my $highest_rank = -1;
953 my @parents = map { $_->from } $child->incoming;
954 foreach my $parent ( @parents ) {
955 if( exists $node_ranks->{$parent->name} ) {
956 $highest_rank = $node_ranks->{$parent->name}
957 if $highest_rank <= $node_ranks->{$parent->name};
964 # print STDERR "Assigning rank " . ( $highest_rank + 1 ) . " to node " . $child->name . "\n";
965 $node_ranks->{$child->name} = $highest_rank + 1;
966 push( @next_nodes, $child );
972 sub possible_positions {
975 map { $all_pos{ $_->rank } = 1 } $self->readings;
976 return keys %all_pos;
979 # TODO think about indexing this.
980 sub readings_at_position {
981 my( $self, $position, $strict ) = @_;
983 foreach my $r ( $self->readings ) {
984 push( @answer, $r ) if $r->is_at_position( $position, $strict );
989 ## Lemmatizer functions
994 foreach my $position ( $self->possible_positions ) {
995 $self->lemmata->{$position} = undef;
998 foreach my $cr ( $self->common_readings ) {
999 $self->lemmata->{$cr->position->maxref} = $cr->name;
1003 sub common_readings {
1005 my @common = grep { $_->is_common } $self->readings();
1006 return sort { $a->rank <=> $b->rank } @common;
1009 =item B<lemma_readings>
1011 my @state = $graph->lemma_readings( @readings_delemmatized );
1013 Takes a list of readings that have just been delemmatized, and returns
1014 a set of tuples of the form ['reading', 'state'] that indicates what
1015 changes need to be made to the graph.
1021 A state of 1 means 'lemmatize this reading'
1025 A state of 0 means 'delemmatize this reading'
1029 A state of undef means 'an ellipsis belongs in the text here because
1030 no decision has been made / an earlier decision was backed out'
1036 sub lemma_readings {
1037 my( $self, @toggled_off_nodes ) = @_;
1039 # First get the positions of those nodes which have been
1041 my $positions_off = {};
1042 map { $positions_off->{ $_->position->reference } = $_->name }
1045 # Now for each position, we have to see if a node is on, and we
1046 # have to see if a node has been turned off. The lemmata hash
1047 # should contain fixed positions, range positions whose node was
1048 # just turned off, and range positions whose node is on.
1050 my %fixed_positions;
1051 # TODO One of these is probably redundant.
1052 map { $fixed_positions{$_} = 0 } keys %{$self->lemmata};
1053 map { $fixed_positions{$_} = 0 } keys %{$positions_off};
1054 map { $fixed_positions{$_} = 1 } $self->possible_positions;
1055 foreach my $pos ( sort { Text::Tradition::Collation::Position::str_cmp( $a, $b ) } keys %fixed_positions ) {
1056 # Find the state of this position. If there is an active node,
1057 # its name will be the state; otherwise the state will be 0
1058 # (nothing at this position) or undef (ellipsis at this position)
1060 $active = $self->lemmata->{$pos} if exists $self->lemmata->{$pos};
1062 # Is there a formerly active node that was toggled off?
1063 if( exists( $positions_off->{$pos} ) ) {
1064 my $off_node = $positions_off->{$pos};
1065 if( $active && $active ne $off_node) {
1066 push( @answer, [ $off_node, 0 ], [ $active, 1 ] );
1068 unless( $fixed_positions{$pos} ) {
1070 delete $self->lemmata->{$pos};
1072 push( @answer, [ $off_node, $active ] );
1075 # No formerly active node, so we just see if there is a currently
1077 } elsif( $active ) {
1078 # Push the active node, whatever it is.
1079 push( @answer, [ $active, 1 ] );
1081 # Push the state that is there. Arbitrarily use the first node
1083 my @pos_nodes = $self->readings_at_position( $pos );
1084 push( @answer, [ $pos_nodes[0]->name, $self->lemmata->{$pos} ] );
1085 delete $self->lemmata->{$pos} unless $fixed_positions{$pos};
1092 =item B<toggle_reading>
1094 my @readings_delemmatized = $graph->toggle_reading( $reading_name );
1096 Takes a reading node name, and either lemmatizes or de-lemmatizes
1097 it. Returns a list of all readings that are de-lemmatized as a result
1102 sub toggle_reading {
1103 my( $self, $rname ) = @_;
1105 return unless $rname;
1106 my $reading = $self->reading( $rname );
1107 if( !$reading || $reading->is_common() ) {
1108 # Do nothing, it's a common node.
1112 my $pos = $reading->position;
1113 my $fixed = $reading->position->fixed;
1114 my $old_state = $self->lemmata->{$pos->reference};
1117 if( $old_state && $old_state eq $rname ) {
1118 # Turn off the node. We turn on no others by default.
1119 push( @readings_off, $reading );
1122 $self->lemmata->{$pos->reference} = $rname;
1123 # Any other 'on' readings in the same position should be off
1124 # if we have a fixed position.
1125 push( @readings_off, $self->same_position_as( $reading, 1 ) )
1127 # Any node that is an identical transposed one should be off.
1128 push( @readings_off, $reading->identical_readings );
1130 @readings_off = unique_list( @readings_off );
1132 # Turn off the readings that need to be turned off.
1133 my @readings_delemmatized;
1134 foreach my $n ( @readings_off ) {
1135 my $npos = $n->position;
1137 $state = $self->lemmata->{$npos->reference}
1138 if defined $self->lemmata->{$npos->reference};
1139 if( $state && $state eq $n->name ) {
1140 # this reading is still on, so turn it off
1141 push( @readings_delemmatized, $n );
1142 my $new_state = undef;
1143 if( $npos->fixed && $n eq $reading ) {
1144 # This is the reading that was clicked, so if there are no
1145 # other readings there and this is a fixed position, turn off
1146 # the position. In all other cases, restore the ellipsis.
1147 my @other_n = $self->same_position_as( $n ); # TODO do we need strict?
1148 $new_state = 0 unless @other_n;
1150 $self->lemmata->{$npos->reference} = $new_state;
1151 } elsif( $old_state && $old_state eq $n->name ) {
1152 # another reading has already been turned on here
1153 push( @readings_delemmatized, $n );
1154 } # else some other reading was on anyway, so pass.
1156 return @readings_delemmatized;
1159 sub same_position_as {
1160 my( $self, $reading, $strict ) = @_;
1161 my $pos = $reading->position;
1162 my %onpath = ( $reading->name => 1 );
1163 # TODO This might not always be sufficient. We really want to
1164 # exclude all readings on this one's path between its two
1166 map { $onpath{$_->name} = 1 } $reading->neighbor_readings;
1167 my @same = grep { !$onpath{$_->name} }
1168 $self->readings_at_position( $reading->position, $strict );
1172 # Return the string that joins together a list of witnesses for
1173 # display on a single path.
1176 return join( $self->wit_list_separator, @_ );
1179 sub witnesses_of_label {
1180 my( $self, $label ) = @_;
1181 my $regex = $self->wit_list_separator;
1182 my @answer = split( /\Q$regex\E/, $label );
1189 map { $h{$_->name} = $_ } @list;
1190 return values( %h );
1193 sub add_hash_entry {
1194 my( $hash, $key, $entry ) = @_;
1195 if( exists $hash->{$key} ) {
1196 push( @{$hash->{$key}}, $entry );
1198 $hash->{$key} = [ $entry ];
1203 __PACKAGE__->meta->make_immutable;