1 package Text::Tradition::Collation;
3 use Encode qw( decode_utf8 );
6 use IPC::Run qw( run binary );
8 use Text::Tradition::Collation::Reading;
9 use Text::Tradition::Collation::RelationshipStore;
16 default => sub { Graph->new() },
24 isa => 'Text::Tradition::Collation::RelationshipStore',
26 relationships => 'relationships',
27 related_readings => 'related_readings',
29 writer => '_set_relations',
34 isa => 'Text::Tradition',
39 isa => 'HashRef[Text::Tradition::Collation::Reading]',
43 _add_reading => 'set',
44 del_reading => 'delete',
45 has_reading => 'exists',
48 default => sub { {} },
51 has 'wit_list_separator' => (
60 default => 'base text',
77 isa => 'Text::Tradition::Collation::Reading',
78 writer => '_set_start',
84 isa => 'Text::Tradition::Collation::Reading',
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.
106 $self->_set_relations( Text::Tradition::Collation::RelationshipStore->new( 'collation' => $self ) );
107 $self->_set_start( $self->add_reading( { 'collation' => $self, 'is_start' => 1 } ) );
108 $self->_set_end( $self->add_reading( { 'collation' => $self, 'is_end' => 1 } ) );
111 ### Reading construct/destruct functions
114 my( $self, $reading ) = @_;
115 unless( ref( $reading ) eq 'Text::Tradition::Collation::Reading' ) {
116 my %args = %$reading;
117 $reading = Text::Tradition::Collation::Reading->new(
118 'collation' => $self,
121 # First check to see if a reading with this ID exists.
122 if( $self->reading( $reading->id ) ) {
123 warn "Collation already has a reading with id " . $reading->id;
126 $self->_add_reading( $reading->id => $reading );
127 # Once the reading has been added, put it in both graphs.
128 $self->sequence->add_vertex( $reading->id );
129 $self->relations->add_reading( $reading->id );
133 around del_reading => sub {
138 if( ref( $arg ) eq 'Text::Tradition::Collation::Reading' ) {
141 # Remove the reading from the graphs.
142 $self->sequence->delete_vertex( $arg );
143 $self->relations->delete_reading( $arg );
146 $self->$orig( $arg );
149 # merge_readings( $main, $to_be_deleted );
154 # We only need the IDs for adding paths to the graph, not the reading
155 # objects themselves.
156 my( $kept, $deleted, $combine_char ) = $self->_stringify_args( @_ );
158 # The kept reading should inherit the paths and the relationships
159 # of the deleted reading.
160 foreach my $path ( $self->sequence->edges_at( $deleted ) ) {
161 my @vector = ( $kept );
162 push( @vector, $path->[1] ) if $path->[0] eq $deleted;
163 unshift( @vector, $path->[0] ) if $path->[1] eq $deleted;
164 next if $vector[0] eq $vector[1]; # Don't add a self loop
165 my %wits = %{$self->sequence->get_edge_attributes( @$path )};
166 $self->sequence->add_edge( @vector );
167 my $fwits = $self->sequence->get_edge_attributes( @vector );
168 @wits{keys %$fwits} = values %$fwits;
169 $self->sequence->set_edge_attributes( @vector, \%wits );
171 $self->relations->merge_readings( $kept, $deleted, $combine_char );
173 # Do the deletion deed.
174 if( $combine_char ) {
175 my $kept_obj = $self->reading( $kept );
176 my $new_text = join( $combine_char, $kept_obj->text,
177 $self->reading( $deleted )->text );
178 $kept_obj->alter_text( $new_text );
180 $self->del_reading( $deleted );
184 # Helper function for manipulating the graph.
185 sub _stringify_args {
186 my( $self, $first, $second, $arg ) = @_;
188 if ref( $first ) eq 'Text::Tradition::Collation::Reading';
189 $second = $second->id
190 if ref( $second ) eq 'Text::Tradition::Collation::Reading';
191 return( $first, $second, $arg );
199 # We only need the IDs for adding paths to the graph, not the reading
200 # objects themselves.
201 my( $source, $target, $wit ) = $self->_stringify_args( @_ );
203 # Connect the readings
204 $self->sequence->add_edge( $source, $target );
205 # Note the witness in question
206 $self->sequence->set_edge_attribute( $source, $target, $wit, 1 );
212 if( ref( $_[0] ) eq 'ARRAY' ) {
219 # We only need the IDs for adding paths to the graph, not the reading
220 # objects themselves.
221 my( $source, $target, $wit ) = $self->_stringify_args( @args );
223 if( $self->sequence->has_edge_attribute( $source, $target, $wit ) ) {
224 $self->sequence->delete_edge_attribute( $source, $target, $wit );
226 unless( keys %{$self->sequence->get_edge_attributes( $source, $target )} ) {
227 $self->sequence->delete_edge( $source, $target );
232 # Extra graph-alike utility
235 my( $source, $target, $wit ) = $self->_stringify_args( @_ );
236 return undef unless $self->sequence->has_edge( $source, $target );
237 return $self->sequence->has_edge_attribute( $source, $target, $wit );
240 =head2 add_relationship( $reading1, $reading2, $definition )
242 Adds the specified relationship between the two readings. A relationship
243 is transitive (i.e. undirected); the options for its definition may be found
244 in Text::Tradition::Collation::Relationship.
248 # Wouldn't it be lovely if edges could be objects, and all this type checking
249 # and attribute management could be done via Moose?
251 sub add_relationship {
253 my( $source, $target, $opts ) = $self->_stringify_args( @_ );
254 my( $ret, @vectors ) = $self->relations->add_relationship( $source,
255 $self->reading( $source ), $target, $self->reading( $target ), $opts );
256 # Force a full rank recalculation every time. Yuck.
257 $self->calculate_ranks() if $ret && $self->end->has_rank;
258 return( $ret, @vectors );
261 =head2 reading_witnesses( $reading )
263 Return a list of sigils corresponding to the witnesses in which the reading appears.
267 sub reading_witnesses {
268 my( $self, $reading ) = @_;
269 # We need only check either the incoming or the outgoing edges; I have
270 # arbitrarily chosen "incoming". Thus, special-case the start node.
271 if( $reading eq $self->start ) {
272 return map { $_->sigil } $self->tradition->witnesses;
275 foreach my $e ( $self->sequence->edges_to( $reading ) ) {
276 my $wits = $self->sequence->get_edge_attributes( @$e );
277 @all_witnesses{ keys %$wits } = 1;
279 return keys %all_witnesses;
282 =head2 Output method(s)
288 print $graph->as_svg( $recalculate );
290 Returns an SVG string that represents the graph, via as_dot and graphviz.
297 my @cmd = qw/dot -Tsvg/;
299 my $dotfile = File::Temp->new();
301 # $dotfile->unlink_on_destroy(0);
302 binmode $dotfile, ':utf8';
303 print $dotfile $self->as_dot();
304 push( @cmd, $dotfile->filename );
305 run( \@cmd, ">", binary(), \$svg );
306 $svg = decode_utf8( $svg );
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 = 'sequence' unless $view;
326 # TODO consider making some of these things configurable
327 my $graph_name = $self->tradition->name;
328 $graph_name =~ s/[^\w\s]//g;
329 $graph_name = join( '_', split( /\s+/, $graph_name ) );
330 my $dot = sprintf( "digraph %s {\n", $graph_name );
331 $dot .= "\tedge [ arrowhead=open ];\n";
332 $dot .= "\tgraph [ rankdir=LR,bgcolor=none ];\n";
333 $dot .= sprintf( "\tnode [ fontsize=%d, fillcolor=%s, style=%s, shape=%s ];\n",
334 11, "white", "filled", "ellipse" );
336 foreach my $reading ( $self->readings ) {
337 # Need not output nodes without separate labels
338 next if $reading->id eq $reading->text;
339 my $label = $reading->text;
340 $label =~ s/\"/\\\"/g;
341 $dot .= sprintf( "\t\"%s\" [ label=\"%s\" ];\n", $reading->id, $label );
344 # TODO do something sensible for relationships
346 my @edges = $self->paths;
347 foreach my $edge ( @edges ) {
348 my %variables = ( 'color' => '#000000',
349 'fontcolor' => '#000000',
350 'label' => join( ', ', $self->path_display_label( $edge ) ),
352 my $varopts = join( ', ', map { $_.'="'.$variables{$_}.'"' } sort keys %variables );
353 # Account for the rank gap if necessary
354 my $rankgap = $self->reading( $edge->[1] )->rank
355 - $self->reading( $edge->[0] )->rank;
356 $varopts .= ", minlen=$rankgap" if $rankgap > 1;
357 $dot .= sprintf( "\t\"%s\" -> \"%s\" [ %s ];\n",
358 $edge->[0], $edge->[1], $varopts );
365 my( $self, @edge ) = @_;
366 # If edge is an arrayref, cope.
367 if( @edge == 1 && ref( $edge[0] ) eq 'ARRAY' ) {
371 my @wits = keys %{$self->sequence->get_edge_attributes( @edge )};
375 sub path_display_label {
376 my( $self, $edge ) = @_;
377 my @wits = $self->path_witnesses( $edge );
378 my $maj = scalar( $self->tradition->witnesses ) * 0.6;
379 if( scalar @wits > $maj ) {
382 return join( ', ', @wits );
389 print $graph->as_graphml( $recalculate )
391 Returns a GraphML representation of the collation graph, with
392 transposition information and position information. Unless
393 $recalculate is passed (and is a true value), the method will return a
394 cached copy of the SVG after the first call to the method.
402 my $graphml_ns = 'http://graphml.graphdrawing.org/xmlns';
403 my $xsi_ns = 'http://www.w3.org/2001/XMLSchema-instance';
404 my $graphml_schema = 'http://graphml.graphdrawing.org/xmlns ' .
405 'http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd';
407 # Create the document and root node
408 my $graphml = XML::LibXML->createDocument( "1.0", "UTF-8" );
409 my $root = $graphml->createElementNS( $graphml_ns, 'graphml' );
410 $graphml->setDocumentElement( $root );
411 $root->setNamespace( $xsi_ns, 'xsi', 0 );
412 $root->setAttributeNS( $xsi_ns, 'schemaLocation', $graphml_schema );
414 # Add the data keys for the graph
417 my @graph_attributes = qw/ version wit_list_separator baselabel linear ac_label /;
418 foreach my $datum ( @graph_attributes ) {
419 $graph_data_keys{$datum} = 'dg'.$gdi++;
420 my $key = $root->addNewChild( $graphml_ns, 'key' );
421 $key->setAttribute( 'attr.name', $datum );
422 $key->setAttribute( 'attr.type', $key eq 'linear' ? 'boolean' : 'string' );
423 $key->setAttribute( 'for', 'graph' );
424 $key->setAttribute( 'id', $graph_data_keys{$datum} );
427 # Add the data keys for nodes
434 is_start => 'boolean',
436 is_lacuna => 'boolean',
438 foreach my $datum ( keys %node_data ) {
439 $node_data_keys{$datum} = 'dn'.$ndi++;
440 my $key = $root->addNewChild( $graphml_ns, 'key' );
441 $key->setAttribute( 'attr.name', $datum );
442 $key->setAttribute( 'attr.type', $node_data{$datum} );
443 $key->setAttribute( 'for', 'node' );
444 $key->setAttribute( 'id', $node_data_keys{$datum} );
447 # Add the data keys for edges, i.e. witnesses
451 class => 'string', # Class, deprecated soon
452 witness => 'string', # ID/label for a path
453 relationship => 'string', # ID/label for a relationship
454 extra => 'boolean', # Path key
455 colocated => 'boolean', # Relationship key
456 non_correctable => 'boolean', # Relationship key
457 non_independent => 'boolean', # Relationship key
459 foreach my $datum ( keys %edge_data ) {
460 $edge_data_keys{$datum} = 'de'.$edi++;
461 my $key = $root->addNewChild( $graphml_ns, 'key' );
462 $key->setAttribute( 'attr.name', $datum );
463 $key->setAttribute( 'attr.type', $edge_data{$datum} );
464 $key->setAttribute( 'for', 'edge' );
465 $key->setAttribute( 'id', $edge_data_keys{$datum} );
468 # Add the collation graph itself
469 my $sgraph = $root->addNewChild( $graphml_ns, 'graph' );
470 $sgraph->setAttribute( 'edgedefault', 'directed' );
471 $sgraph->setAttribute( 'id', $self->tradition->name );
472 $sgraph->setAttribute( 'parse.edgeids', 'canonical' );
473 $sgraph->setAttribute( 'parse.edges', scalar($self->paths) );
474 $sgraph->setAttribute( 'parse.nodeids', 'canonical' );
475 $sgraph->setAttribute( 'parse.nodes', scalar($self->readings) );
476 $sgraph->setAttribute( 'parse.order', 'nodesfirst' );
478 # Collation attribute data
479 foreach my $datum ( @graph_attributes ) {
480 my $value = $datum eq 'version' ? '3.0' : $self->$datum;
481 _add_graphml_data( $sgraph, $graph_data_keys{$datum}, $value );
486 # Add our readings to the graph
487 foreach my $n ( sort { $a->id cmp $b->id } $self->readings ) {
488 # Add to the main graph
489 my $node_el = $sgraph->addNewChild( $graphml_ns, 'node' );
490 my $node_xmlid = 'n' . $node_ctr++;
491 $node_hash{ $n->id } = $node_xmlid;
492 $node_el->setAttribute( 'id', $node_xmlid );
493 foreach my $d ( keys %node_data ) {
495 _add_graphml_data( $node_el, $node_data_keys{$d}, $nval )
500 # Add the path edges to the sequence graph
502 foreach my $e ( sort { $a->[0] cmp $b->[0] } $self->sequence->edges() ) {
503 # We add an edge in the graphml for every witness in $e.
504 foreach my $wit ( $self->path_witnesses( $e ) ) {
505 my( $id, $from, $to ) = ( 'e'.$edge_ctr++,
506 $node_hash{ $e->[0] },
507 $node_hash{ $e->[1] } );
508 my $edge_el = $sgraph->addNewChild( $graphml_ns, 'edge' );
509 $edge_el->setAttribute( 'source', $from );
510 $edge_el->setAttribute( 'target', $to );
511 $edge_el->setAttribute( 'id', $id );
513 # It's a witness path, so add the witness
515 my $key = $edge_data_keys{'witness'};
516 # Is this an ante-corr witness?
517 my $aclabel = $self->ac_label;
518 if( $wit =~ /^(.*)\Q$aclabel\E$/ ) {
519 # Keep the base witness
521 # ...and record that this is an 'extra' reading path
522 _add_graphml_data( $edge_el, $edge_data_keys{'extra'}, $aclabel );
524 _add_graphml_data( $edge_el, $edge_data_keys{'witness'}, $base );
525 _add_graphml_data( $edge_el, $edge_data_keys{'class'}, 'path' );
529 # Add the relationship graph to the XML
530 $self->relations->as_graphml( $root );
532 # Save and return the thing
533 my $result = decode_utf8( $graphml->toString(1) );
537 sub _add_graphml_data {
538 my( $el, $key, $value ) = @_;
539 return unless defined $value;
540 my $data_el = $el->addNewChild( $el->namespaceURI, 'data' );
541 $data_el->setAttribute( 'key', $key );
542 $data_el->appendText( $value );
547 print $graph->as_csv( $recalculate )
549 Returns a CSV alignment table representation of the collation graph, one
550 row per witness (or witness uncorrected.)
556 my $table = $self->make_alignment_table;
557 my $csv = Text::CSV_XS->new( { binary => 1, quote_null => 0 } );
559 # Make the header row
560 $csv->combine( map { $_->{'witness'} } @{$table->{'alignment'}} );
561 push( @result, decode_utf8( $csv->string ) );
562 # Make the rest of the rows
563 foreach my $idx ( 0 .. $table->{'length'} - 1 ) {
564 my @rowobjs = map { $_->{'tokens'}->[$idx] } @{$table->{'alignment'}};
565 my @row = map { $_ ? $_->{'t'} : $_ } @rowobjs;
566 $csv->combine( @row );
567 push( @result, decode_utf8( $csv->string ) );
569 return join( "\n", @result );
572 =item B<make_alignment_table>
574 my $table = $graph->make_alignment_table( $use_refs, \@wits_to_include )
576 Return a reference to an alignment table, in a slightly enhanced CollateX
577 format which looks like this:
579 $table = { alignment => [ { witness => "SIGIL",
580 tokens => [ { t => "READINGTEXT" }, ... ] },
582 tokens => [ { t => "READINGTEXT" }, ... ] },
586 If $use_refs is set to 1, the reading object is returned in the table
587 instead of READINGTEXT; if not, the text of the reading is returned.
588 If $wits_to_include is set to a hashref, only the witnesses whose sigil
589 keys have a true hash value will be included.
593 sub make_alignment_table {
594 my( $self, $noderefs, $include ) = @_;
595 unless( $self->linear ) {
596 warn "Need a linear graph in order to make an alignment table";
599 my $table = { 'alignment' => [], 'length' => $self->end->rank - 1 };
600 my @all_pos = ( 1 .. $self->end->rank - 1 );
601 foreach my $wit ( sort { $a->sigil cmp $b->sigil } $self->tradition->witnesses ) {
603 next unless $include->{$wit->sigil};
605 # print STDERR "Making witness row(s) for " . $wit->sigil . "\n";
606 my @wit_path = $self->reading_sequence( $self->start, $self->end, $wit->sigil );
607 my @row = _make_witness_row( \@wit_path, \@all_pos, $noderefs );
608 push( @{$table->{'alignment'}},
609 { 'witness' => $wit->sigil, 'tokens' => \@row } );
610 if( $wit->is_layered ) {
611 my @wit_ac_path = $self->reading_sequence( $self->start, $self->end,
612 $wit->sigil.$self->ac_label, $wit->sigil );
613 my @ac_row = _make_witness_row( \@wit_ac_path, \@all_pos, $noderefs );
614 push( @{$table->{'alignment'}},
615 { 'witness' => $wit->sigil.$self->ac_label, 'tokens' => \@ac_row } );
621 sub _make_witness_row {
622 my( $path, $positions, $noderefs ) = @_;
624 map { $char_hash{$_} = undef } @$positions;
626 foreach my $rdg ( @$path ) {
627 my $rtext = $rdg->text;
628 $rtext = '#LACUNA#' if $rdg->is_lacuna;
629 print STDERR "rank " . $rdg->rank . "\n" if $debug;
630 # print STDERR "No rank for " . $rdg->id . "\n" unless defined $rdg->rank;
631 $char_hash{$rdg->rank} = $noderefs ? { 't' => $rdg }
634 my @row = map { $char_hash{$_} } @$positions;
635 # Fill in lacuna markers for undef spots in the row
636 my $last_el = shift @row;
637 my @filled_row = ( $last_el );
638 foreach my $el ( @row ) {
639 # If we are using node reference, make the lacuna node appear many times
640 # in the table. If not, use the lacuna tag.
641 if( $last_el && _el_is_lacuna( $last_el ) && !defined $el ) {
642 $el = $noderefs ? $last_el : { 't' => '#LACUNA#' };
644 push( @filled_row, $el );
650 # Tiny utility function to say if a table element is a lacuna
653 return 1 if $el->{'t'} eq '#LACUNA#';
654 return 1 if ref( $el->{'t'} ) eq 'Text::Tradition::Collation::Reading'
655 && $el->{'t'}->is_lacuna;
659 # Helper to turn the witnesses along columns rather than rows. Assumes
664 return $result unless scalar @$table;
665 my $nrows = scalar @{$table->[0]};
666 foreach my $idx ( 0 .. $nrows - 1 ) {
667 foreach my $wit ( 0 .. $#{$table} ) {
668 $result->[$idx]->[$wit] = $table->[$wit]->[$idx];
676 =head2 Navigation methods
682 my $beginning = $collation->start();
684 Returns the beginning of the collation, a meta-reading with label '#START#'.
688 my $end = $collation->end();
690 Returns the end of the collation, a meta-reading with label '#END#'.
693 =item B<reading_sequence>
695 my @readings = $graph->reading_sequence( $first, $last, $path[, $alt_path] );
697 Returns the ordered list of readings, starting with $first and ending
698 with $last, along the given witness path. If no path is specified,
699 assume that the path is that of the base text (if any.)
703 # TODO Think about returning some lazy-eval iterator.
705 sub reading_sequence {
706 my( $self, $start, $end, $witness, $backup ) = @_;
708 $witness = $self->baselabel unless $witness;
709 my @readings = ( $start );
712 while( $n && $n->id ne $end->id ) {
713 if( exists( $seen{$n->id} ) ) {
714 warn "Detected loop at " . $n->id;
719 my $next = $self->next_reading( $n, $witness, $backup );
721 warn "Did not find any path for $witness from reading " . $n->id;
724 push( @readings, $next );
727 # Check that the last reading is our end reading.
728 my $last = $readings[$#readings];
729 warn "Last reading found from " . $start->text .
730 " for witness $witness is not the end!"
731 unless $last->id eq $end->id;
736 =item B<next_reading>
738 my $next_reading = $graph->next_reading( $reading, $witpath );
740 Returns the reading that follows the given reading along the given witness
746 # Return the successor via the corresponding path.
748 my $answer = $self->_find_linked_reading( 'next', @_ );
749 return undef unless $answer;
750 return $self->reading( $answer );
753 =item B<prior_reading>
755 my $prior_reading = $graph->prior_reading( $reading, $witpath );
757 Returns the reading that precedes the given reading along the given witness
763 # Return the predecessor via the corresponding path.
765 my $answer = $self->_find_linked_reading( 'prior', @_ );
766 return $self->reading( $answer );
769 sub _find_linked_reading {
770 my( $self, $direction, $node, $path, $alt_path ) = @_;
771 my @linked_paths = $direction eq 'next'
772 ? $self->sequence->edges_from( $node )
773 : $self->sequence->edges_to( $node );
774 return undef unless scalar( @linked_paths );
776 # We have to find the linked path that contains all of the
777 # witnesses supplied in $path.
778 my( @path_wits, @alt_path_wits );
779 @path_wits = sort( $self->witnesses_of_label( $path ) ) if $path;
780 @alt_path_wits = sort( $self->witnesses_of_label( $alt_path ) ) if $alt_path;
783 foreach my $le ( @linked_paths ) {
784 if( $self->sequence->has_edge_attribute( @$le, $self->baselabel ) ) {
787 my @le_wits = $self->path_witnesses( $le );
788 if( _is_within( \@path_wits, \@le_wits ) ) {
789 # This is the right path.
790 return $direction eq 'next' ? $le->[1] : $le->[0];
791 } elsif( _is_within( \@alt_path_wits, \@le_wits ) ) {
795 # Got this far? Return the alternate path if it exists.
796 return $direction eq 'next' ? $alt_le->[1] : $alt_le->[0]
799 # Got this far? Return the base path if it exists.
800 return $direction eq 'next' ? $base_le->[1] : $base_le->[0]
803 # Got this far? We have no appropriate path.
804 warn "Could not find $direction node from " . $node->id
805 . " along path $path";
811 my( $set1, $set2 ) = @_;
812 my $ret = @$set1; # will be 0, i.e. false, if set1 is empty
813 foreach my $el ( @$set1 ) {
814 $ret = 0 unless grep { /^\Q$el\E$/ } @$set2;
820 ## INITIALIZATION METHODS - for use by parsers
822 # For use when a collation is constructed from a base text and an apparatus.
823 # We have the sequences of readings and just need to add path edges.
824 # When we are done, clear out the witness path attributes, as they are no
826 # TODO Find a way to replace the witness path attributes with encapsulated functions?
828 sub make_witness_paths {
830 foreach my $wit ( $self->tradition->witnesses ) {
831 # print STDERR "Making path for " . $wit->sigil . "\n";
832 $self->make_witness_path( $wit );
836 sub make_witness_path {
837 my( $self, $wit ) = @_;
838 my @chain = @{$wit->path};
839 my $sig = $wit->sigil;
840 foreach my $idx ( 0 .. $#chain-1 ) {
841 $self->add_path( $chain[$idx], $chain[$idx+1], $sig );
843 if( $wit->is_layered ) {
844 @chain = @{$wit->uncorrected_path};
845 foreach my $idx( 0 .. $#chain-1 ) {
846 my $source = $chain[$idx];
847 my $target = $chain[$idx+1];
848 $self->add_path( $source, $target, $sig.$self->ac_label )
849 unless $self->has_path( $source, $target, $sig );
853 $wit->clear_uncorrected_path;
856 sub calculate_ranks {
858 # Walk a version of the graph where every node linked by a relationship
859 # edge is fundamentally the same node, and do a topological ranking on
860 # the nodes in this graph.
861 my $topo_graph = Graph->new();
865 foreach my $r ( $self->readings ) {
866 next if exists $rel_containers{$r->id};
867 my @rels = $r->related_readings( 'colocated' );
869 # Make a relationship container.
871 my $rn = 'rel_container_' . $rel_ctr++;
872 $topo_graph->add_vertex( $rn );
874 $rel_containers{$_->id} = $rn;
877 # Add a new node to mirror the old node.
878 $rel_containers{$r->id} = $r->id;
879 $topo_graph->add_vertex( $r->id );
884 foreach my $r ( $self->readings ) {
885 foreach my $n ( $self->sequence->successors( $r->id ) ) {
886 my( $tfrom, $tto ) = ( $rel_containers{$r->id},
887 $rel_containers{$n} );
888 $DB::single = 1 unless $tfrom && $tto;
889 $topo_graph->add_edge( $tfrom, $tto );
893 # Now do the rankings, starting with the start node.
894 my $topo_start = $rel_containers{$self->start->id};
895 my $node_ranks = { $topo_start => 0 };
896 my @curr_origin = ( $topo_start );
897 # A little iterative function.
898 while( @curr_origin ) {
899 @curr_origin = _assign_rank( $topo_graph, $node_ranks, @curr_origin );
901 # Transfer our rankings from the topological graph to the real one.
902 foreach my $r ( $self->readings ) {
903 if( defined $node_ranks->{$rel_containers{$r->id}} ) {
904 $r->rank( $node_ranks->{$rel_containers{$r->id}} );
907 die "No rank calculated for node " . $r->id
908 . " - do you have a cycle in the graph?";
914 my( $graph, $node_ranks, @current_nodes ) = @_;
915 # Look at each of the children of @current_nodes. If all the child's
916 # parents have a rank, assign it the highest rank + 1 and add it to
917 # @next_nodes. Otherwise skip it; we will return when the highest-ranked
918 # parent gets a rank.
920 foreach my $c ( @current_nodes ) {
921 warn "Current reading $c has no rank!"
922 unless exists $node_ranks->{$c};
923 # print STDERR "Looking at child of node $c, rank "
924 # . $node_ranks->{$c} . "\n";
925 foreach my $child ( $graph->successors( $c ) ) {
926 next if exists $node_ranks->{$child};
927 my $highest_rank = -1;
929 foreach my $parent ( $graph->predecessors( $child ) ) {
930 if( exists $node_ranks->{$parent} ) {
931 $highest_rank = $node_ranks->{$parent}
932 if $highest_rank <= $node_ranks->{$parent};
939 my $c_rank = $highest_rank + 1;
940 # print STDERR "Assigning rank $c_rank to node $child \n";
941 $node_ranks->{$child} = $c_rank;
942 push( @next_nodes, $child );
948 # Another method to make up for rough collation methods. If the same reading
949 # appears multiple times at the same rank, collapse the nodes.
953 foreach my $rdg ( $self->readings ) {
954 next unless $rdg->has_rank;
955 my $key = $rdg->rank . "||" . $rdg->text;
956 if( exists $unique_rank_rdg{$key} ) {
958 # print STDERR "Combining readings at same rank: $key\n";
959 $self->merge_readings( $unique_rank_rdg{$key}, $rdg );
961 $unique_rank_rdg{$key} = $rdg;
969 # Return the string that joins together a list of witnesses for
970 # display on a single path.
971 sub witnesses_of_label {
972 my( $self, $label ) = @_;
973 my $regex = $self->wit_list_separator;
974 my @answer = split( /\Q$regex\E/, $label );
982 my $cxfile = 't/data/Collatex-16.xml';
983 my $t = Text::Tradition->new(
985 'input' => 'CollateX',
988 my $c = $t->collation;
990 is( $c->common_predecessor( $c->reading('n9'), $c->reading('n23') )->id,
991 'n20', "Found correct common predecessor" );
992 is( $c->common_successor( $c->reading('n9'), $c->reading('n23') )->id,
993 '#END#', "Found correct common successor" );
995 is( $c->common_predecessor( $c->reading('n19'), $c->reading('n17') )->id,
996 'n16', "Found correct common predecessor for readings on same path" );
997 is( $c->common_successor( $c->reading('n21'), $c->reading('n26') )->id,
998 '#END#', "Found correct common successor for readings on same path" );
1004 ## Return the closest reading that is a predecessor of both the given readings.
1005 sub common_predecessor {
1007 return $self->common_in_path( @_, 'predecessors' );
1010 sub common_successor {
1012 return $self->common_in_path( @_, 'successors' );
1015 sub common_in_path {
1016 my( $self, $r1, $r2, $dir ) = @_;
1017 my $iter = $r1->rank > $r2->rank ? $r1->rank : $r2->rank;
1018 $iter = $self->end->rank - $iter if $dir eq 'successors';
1020 my @last_checked = ( $r1, $r2 );
1022 while( !@candidates ) {
1024 foreach my $lc ( @last_checked ) {
1025 foreach my $p ( $lc->$dir ) {
1026 if( $all_seen{$p->id} ) {
1027 push( @candidates, $p );
1029 $all_seen{$p->id} = 1;
1030 push( @new_lc, $p );
1034 @last_checked = @new_lc;
1036 my @answer = sort { $a->rank <=> $b->rank } @candidates;
1037 return $dir eq 'predecessors' ? pop( @answer ) : shift ( @answer );
1041 __PACKAGE__->meta->make_immutable;
1047 =item * Think about making Relationship objects again