1 package Text::Tradition::Collation;
3 use Encode qw( decode_utf8 );
6 use IPC::Run qw( run binary );
8 use Text::Tradition::Collation::Reading;
15 default => sub { Graph->new() },
24 default => sub { Graph->new( undirected => 1 ) },
26 relationships => 'edges',
32 isa => 'Text::Tradition',
37 isa => 'HashRef[Text::Tradition::Collation::Reading]',
41 _add_reading => 'set',
42 del_reading => 'delete',
43 has_reading => 'exists',
46 default => sub { {} },
49 has 'wit_list_separator' => (
58 default => 'base text',
75 isa => 'Text::Tradition::Collation::Reading',
76 writer => '_set_start',
82 isa => 'Text::Tradition::Collation::Reading',
87 # The collation can be created two ways:
88 # 1. Collate a set of witnesses (with CollateX I guess) and process
89 # the results as in 2.
90 # 2. Read a pre-prepared collation in one of a variety of formats,
91 # and make the graph from that.
93 # The graph itself will (for now) be immutable, and the positions
94 # within the graph will also be immutable. We need to calculate those
95 # positions upon graph construction. The equivalences between graph
96 # nodes will be mutable, entirely determined by the user (or possibly
97 # by some semantic pre-processing provided by the user.) So the
98 # constructor should just make an empty equivalences object. The
99 # constructor will also need to make the witness objects, if we didn't
100 # come through option 1.
104 $self->_set_start( $self->add_reading( { 'collation' => $self, 'is_start' => 1 } ) );
105 $self->_set_end( $self->add_reading( { 'collation' => $self, 'is_end' => 1 } ) );
108 ### Reading construct/destruct functions
111 my( $self, $reading ) = @_;
112 unless( ref( $reading ) eq 'Text::Tradition::Collation::Reading' ) {
113 my %args = %$reading;
114 $reading = Text::Tradition::Collation::Reading->new(
115 'collation' => $self,
118 # First check to see if a reading with this ID exists.
119 if( $self->reading( $reading->id ) ) {
120 warn "Collation already has a reading with id " . $reading->id;
123 $self->_add_reading( $reading->id => $reading );
124 # Once the reading has been added, put it in both graphs.
125 $self->sequence->add_vertex( $reading->id );
126 $self->relations->add_vertex( $reading->id );
130 around del_reading => sub {
135 if( ref( $arg ) eq 'Text::Tradition::Collation::Reading' ) {
138 # Remove the reading from the graphs.
139 $self->sequence->delete_vertex( $arg );
140 $self->relations->delete_vertex( $arg );
143 $self->$orig( $arg );
146 # merge_readings( $main, $to_be_deleted );
151 # We only need the IDs for adding paths to the graph, not the reading
152 # objects themselves.
153 my( $kept, $deleted, $combine_char ) = $self->_stringify_args( @_ );
155 # The kept reading should inherit the paths and the relationships
156 # of the deleted reading.
157 foreach my $path ( $self->sequence->edges_at( $deleted ) ) {
158 my @vector = ( $kept );
159 push( @vector, $path->[1] ) if $path->[0] eq $deleted;
160 unshift( @vector, $path->[0] ) if $path->[1] eq $deleted;
161 next if $vector[0] eq $vector[1]; # Don't add a self loop
162 my %wits = %{$self->sequence->get_edge_attributes( @$path )};
163 $self->sequence->add_edge( @vector );
164 my $fwits = $self->sequence->get_edge_attributes( @vector );
165 @wits{keys %$fwits} = values %$fwits;
166 $self->sequence->set_edge_attributes( @vector, \%wits );
168 foreach my $rel ( $self->relations->edges_at( $deleted ) ) {
169 my @vector = ( $kept );
170 push( @vector, $rel->[0] eq $deleted ? $rel->[1] : $rel->[0] );
171 next if $vector[0] eq $vector[1]; # Don't add a self loop
172 # Is there a relationship here already? If so, keep it.
173 # TODO Warn about conflicting relationships
174 next if $self->relations->has_edge( @vector );
175 # If not, adopt the relationship that would be deleted.
176 $self->relations->add_edge( @vector );
177 my $attr = $self->relations->get_edge_attributes( @$rel );
178 $self->relations->set_edge_attributes( @vector, $attr );
181 # Do the deletion deed.
182 if( $combine_char ) {
183 my $kept_obj = $self->reading( $kept );
184 my $new_text = join( $combine_char, $kept_obj->text,
185 $self->reading( $deleted )->text );
186 $kept_obj->alter_text( $new_text );
188 $self->del_reading( $deleted );
192 # Helper function for manipulating the graph.
193 sub _stringify_args {
194 my( $self, $first, $second, $arg ) = @_;
196 if ref( $first ) eq 'Text::Tradition::Collation::Reading';
197 $second = $second->id
198 if ref( $second ) eq 'Text::Tradition::Collation::Reading';
199 return( $first, $second, $arg );
207 # We only need the IDs for adding paths to the graph, not the reading
208 # objects themselves.
209 my( $source, $target, $wit ) = $self->_stringify_args( @_ );
211 # Connect the readings
212 $self->sequence->add_edge( $source, $target );
213 # Note the witness in question
214 $self->sequence->set_edge_attribute( $source, $target, $wit, 1 );
220 if( ref( $_[0] ) eq 'ARRAY' ) {
227 # We only need the IDs for adding paths to the graph, not the reading
228 # objects themselves.
229 my( $source, $target, $wit ) = $self->_stringify_args( @args );
231 if( $self->sequence->has_edge_attribute( $source, $target, $wit ) ) {
232 $self->sequence->delete_edge_attribute( $source, $target, $wit );
234 unless( keys %{$self->sequence->get_edge_attributes( $source, $target )} ) {
235 $self->sequence->delete_edge( $source, $target );
240 # Extra graph-alike utility
243 my( $source, $target, $wit ) = $self->_stringify_args( @_ );
244 return undef unless $self->sequence->has_edge( $source, $target );
245 return $self->sequence->has_edge_attribute( $source, $target, $wit );
248 ### Relationship logic
250 =head2 add_relationship( $reading1, $reading2, $definition )
252 Adds the specified relationship between the two readings. A relationship
253 is transitive (i.e. undirected), and must have the following attributes
254 specified in the hashref $definition:
258 =item * type - Can be one of spelling, orthographic, grammatical, meaning, repetition, transposition. The first three are only valid relationships between readings that occur at the same point in the text.
260 =item * non_correctable - (Optional) True if the reading would not have been corrected independently.
262 =item * non_independent - (Optional) True if the variant is unlikely to have occurred independently in unrelated witnesses.
264 =item * global - (Optional) A meta-attribute, to set the same relationship between readings with the same text whenever they occur in the same place.
270 # Wouldn't it be lovely if edges could be objects, and all this type checking
271 # and attribute management could be done via Moose?
273 sub add_relationship {
275 my( $source, $target, $options ) = $self->_stringify_args( @_ );
278 if( !defined $options->{'type'} ||
279 $options->{'type'} !~ /^(spelling|orthographic|grammatical|meaning|lookalike|repetition|transposition)$/i ) {
280 my $t = $options->{'type'} ? $options->{'type'} : '';
281 return( undef, "Invalid or missing type " . $options->{'type'} );
283 unless ( $options->{'type'} =~ /^(repetition|transposition)$/ ) {
284 $options->{'colocated'} = 1;
287 # Make sure there is not another relationship between these two
289 if( $self->relations->has_edge( $source, $target ) ) {
290 return ( undef, "Relationship already exists between these readings" );
292 if( !$self->relationship_valid( $source, $target, $options->{'type'} ) ) {
293 return ( undef, 'Relationship creates witness loop' );
296 my @vector = ( $source, $target );
297 $self->relations->add_edge( @vector );
298 $self->relations->set_edge_attributes( @vector, $options );
300 # TODO Handle global relationship setting
302 return( 1, @vector );
305 sub relationship_valid {
306 my( $self, $source, $target, $rel ) = @_;
307 if( $rel eq 'repetition' ) {
309 } elsif ( $rel eq 'transposition' ) {
310 # Check that the two readings do not appear in the same witness.
312 map { $seen_wits{$_} = 1 } $self->reading_witnesses( $source );
313 foreach my $w ( $self->reading_witnesses( $target ) ) {
314 return 0 if $seen_wits{$w};
318 # Check that linking the source and target in a relationship won't lead
319 # to a path loop for any witness. First make a lookup table of all the
320 # readings related to either the source or the target.
321 my @proposed_related = ( $source, $target );
322 push( @proposed_related, $self->related_readings( $source, 'colocated' ) );
323 push( @proposed_related, $self->related_readings( $target, 'colocated' ) );
325 map { $pr_ids{ $_ } = 1 } @proposed_related;
327 # None of these proposed related readings should have a neighbor that
328 # is also in proposed_related.
329 foreach my $pr ( keys %pr_ids ) {
330 foreach my $neighbor( $self->sequence->neighbors( $pr ) ) {
331 return 0 if exists $pr_ids{$neighbor};
338 # Return a list of the witnesses in which the reading appears.
339 sub reading_witnesses {
340 my( $self, $reading ) = @_;
341 # We need only check either the incoming or the outgoing edges; I have
342 # arbitrarily chosen "incoming".
344 foreach my $e ( $self->sequence->edges_to( $reading ) ) {
345 my $wits = $self->sequence->get_edge_attributes( @$e );
346 @all_witnesses{ keys %$wits } = 1;
348 return keys %all_witnesses;
351 sub related_readings {
352 my( $self, $reading, $colocated ) = @_;
354 if( ref( $reading ) eq 'Text::Tradition::Collation::Reading' ) {
355 $reading = $reading->id;
357 # print STDERR "Returning related objects\n";
359 # print STDERR "Returning related object names\n";
361 my @related = $self->relations->all_reachable( $reading );
363 my @colo = grep { $self->relations->has_edge_attribute( $reading, $_, 'colocated' ) } @related;
366 return $return_object ? map { $self->reading( $_ ) } @related : @related;
369 =head2 Output method(s)
375 print $graph->as_svg( $recalculate );
377 Returns an SVG string that represents the graph. Uses GraphViz to do
378 this, because Graph::Easy doesn\'t cope well with long graphs. Unless
379 $recalculate is passed (and is a true value), the method will return a
380 cached copy of the SVG after the first call to the method.
387 my @cmd = qw/dot -Tsvg/;
389 my $dotfile = File::Temp->new();
391 # $dotfile->unlink_on_destroy(0);
392 binmode $dotfile, ':utf8';
393 print $dotfile $self->as_dot();
394 push( @cmd, $dotfile->filename );
395 run( \@cmd, ">", binary(), \$svg );
396 $svg = decode_utf8( $svg );
402 print $graph->as_dot( $view, $recalculate );
404 Returns a string that is the collation graph expressed in dot
405 (i.e. GraphViz) format. The 'view' argument determines what kind of
407 * 'path': a graph of witness paths through the collation (DEFAULT)
408 * 'relationship': a graph of how collation readings relate to
414 my( $self, $view ) = @_;
415 $view = 'sequence' unless $view;
416 # TODO consider making some of these things configurable
417 my $graph_name = $self->tradition->name;
418 $graph_name =~ s/[^\w\s]//g;
419 $graph_name = join( '_', split( /\s+/, $graph_name ) );
420 my $dot = sprintf( "digraph %s {\n", $graph_name );
421 $dot .= "\tedge [ arrowhead=open ];\n";
422 $dot .= "\tgraph [ rankdir=LR ];\n";
423 $dot .= sprintf( "\tnode [ fontsize=%d, fillcolor=%s, style=%s, shape=%s ];\n",
424 11, "white", "filled", "ellipse" );
426 foreach my $reading ( $self->readings ) {
427 # Need not output nodes without separate labels
428 next if $reading->id eq $reading->text;
429 $dot .= sprintf( "\t\"%s\" [ label=\"%s\" ];\n", $reading->id, $reading->text );
432 # TODO do something sensible for relationships
434 my @edges = $self->paths;
435 foreach my $edge ( @edges ) {
436 my %variables = ( 'color' => '#000000',
437 'fontcolor' => '#000000',
438 'label' => join( ', ', $self->path_witnesses( $edge ) ),
440 my $varopts = join( ', ', map { $_.'="'.$variables{$_}.'"' } sort keys %variables );
441 $dot .= sprintf( "\t\"%s\" -> \"%s\" [ %s ];\n",
442 $edge->[0], $edge->[1], $varopts );
449 my( $self, @edge ) = @_;
450 # If edge is an arrayref, cope.
451 if( @edge == 1 && ref( $edge[0] ) eq 'ARRAY' ) {
455 my @wits = keys %{$self->sequence->get_edge_attributes( @edge )};
461 print $graph->as_graphml( $recalculate )
463 Returns a GraphML representation of the collation graph, with
464 transposition information and position information. Unless
465 $recalculate is passed (and is a true value), the method will return a
466 cached copy of the SVG after the first call to the method.
474 my $graphml_ns = 'http://graphml.graphdrawing.org/xmlns';
475 my $xsi_ns = 'http://www.w3.org/2001/XMLSchema-instance';
476 my $graphml_schema = 'http://graphml.graphdrawing.org/xmlns ' .
477 'http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd';
479 # Create the document and root node
480 my $graphml = XML::LibXML->createDocument( "1.0", "UTF-8" );
481 my $root = $graphml->createElementNS( $graphml_ns, 'graphml' );
482 $graphml->setDocumentElement( $root );
483 $root->setNamespace( $xsi_ns, 'xsi', 0 );
484 $root->setAttributeNS( $xsi_ns, 'schemaLocation', $graphml_schema );
486 # Add the data keys for the graph
489 my @graph_attributes = qw/ version wit_list_separator baselabel linear ac_label /;
490 foreach my $datum ( @graph_attributes ) {
491 $graph_data_keys{$datum} = 'dg'.$gdi++;
492 my $key = $root->addNewChild( $graphml_ns, 'key' );
493 $key->setAttribute( 'attr.name', $datum );
494 $key->setAttribute( 'attr.type', $key eq 'linear' ? 'boolean' : 'string' );
495 $key->setAttribute( 'for', 'graph' );
496 $key->setAttribute( 'id', $graph_data_keys{$datum} );
499 # Add the data keys for nodes
506 is_start => 'boolean',
508 is_lacuna => 'boolean',
510 foreach my $datum ( keys %node_data ) {
511 $node_data_keys{$datum} = 'dn'.$ndi++;
512 my $key = $root->addNewChild( $graphml_ns, 'key' );
513 $key->setAttribute( 'attr.name', $datum );
514 $key->setAttribute( 'attr.type', $node_data{$datum} );
515 $key->setAttribute( 'for', 'node' );
516 $key->setAttribute( 'id', $node_data_keys{$datum} );
519 # Add the data keys for edges, i.e. witnesses
523 class => 'string', # Path or relationship?
524 witness => 'string', # ID/label for a path
525 relationship => 'string', # ID/label for a relationship
526 extra => 'boolean', # Path key
527 colocated => 'boolean', # Relationship key
528 non_correctable => 'boolean', # Relationship key
529 non_independent => 'boolean', # Relationship key
531 foreach my $datum ( keys %edge_data ) {
532 $edge_data_keys{$datum} = 'de'.$edi++;
533 my $key = $root->addNewChild( $graphml_ns, 'key' );
534 $key->setAttribute( 'attr.name', $datum );
535 $key->setAttribute( 'attr.type', $edge_data{$datum} );
536 $key->setAttribute( 'for', 'edge' );
537 $key->setAttribute( 'id', $edge_data_keys{$datum} );
540 # Add the collation graph itself
541 my $graph = $root->addNewChild( $graphml_ns, 'graph' );
542 $graph->setAttribute( 'edgedefault', 'directed' );
543 $graph->setAttribute( 'id', $self->tradition->name );
544 $graph->setAttribute( 'parse.edgeids', 'canonical' );
545 $graph->setAttribute( 'parse.edges', scalar($self->paths) );
546 $graph->setAttribute( 'parse.nodeids', 'canonical' );
547 $graph->setAttribute( 'parse.nodes', scalar($self->readings) );
548 $graph->setAttribute( 'parse.order', 'nodesfirst' );
550 # Collation attribute data
551 foreach my $datum ( @graph_attributes ) {
552 my $value = $datum eq 'version' ? '2.0' : $self->$datum;
553 _add_graphml_data( $graph, $graph_data_keys{$datum}, $value );
558 # Add our readings to the graph
559 foreach my $n ( sort { $a->id cmp $b->id } $self->readings ) {
560 my $node_el = $graph->addNewChild( $graphml_ns, 'node' );
561 my $node_xmlid = 'n' . $node_ctr++;
562 $node_hash{ $n->id } = $node_xmlid;
563 $node_el->setAttribute( 'id', $node_xmlid );
564 foreach my $d ( keys %node_data ) {
566 _add_graphml_data( $node_el, $node_data_keys{$d}, $nval )
573 foreach my $e ( sort { $a->[0] cmp $b->[0] } $self->sequence->edges() ) {
574 # We add an edge in the graphml for every witness in $e.
575 foreach my $wit ( $self->path_witnesses( $e ) ) {
576 my( $id, $from, $to ) = ( 'e'.$edge_ctr++,
577 $node_hash{ $e->[0] },
578 $node_hash{ $e->[1] } );
579 my $edge_el = $graph->addNewChild( $graphml_ns, 'edge' );
580 $edge_el->setAttribute( 'source', $from );
581 $edge_el->setAttribute( 'target', $to );
582 $edge_el->setAttribute( 'id', $id );
584 _add_graphml_data( $edge_el, $edge_data_keys{'class'}, 'path' );
586 # It's a witness path, so add the witness
588 my $key = $edge_data_keys{'witness'};
589 # Is this an ante-corr witness?
590 my $aclabel = $self->ac_label;
591 if( $wit =~ /^(.*)\Q$aclabel\E$/ ) {
592 # Keep the base witness
594 # ...and record that this is an 'extra' reading path
595 _add_graphml_data( $edge_el, $edge_data_keys{'extra'}, $aclabel );
597 _add_graphml_data( $edge_el, $edge_data_keys{'witness'}, $base );
601 # Add the relationship edges
602 foreach my $e ( sort { $a->[0] cmp $b->[0] } $self->relationships ) {
603 my( $id, $from, $to ) = ( 'e'.$edge_ctr++,
604 $node_hash{ $e->[0] },
605 $node_hash{ $e->[1] } );
606 my $edge_el = $graph->addNewChild( $graphml_ns, 'edge' );
607 $edge_el->setAttribute( 'source', $from );
608 $edge_el->setAttribute( 'target', $to );
609 $edge_el->setAttribute( 'id', $id );
611 _add_graphml_data( $edge_el, $edge_data_keys{'class'}, 'relationship' );
613 my $data = $self->relations->get_edge_attributes( @$e );
614 # It's a relationship, so save the relationship data
615 _add_graphml_data( $edge_el, $edge_data_keys{'relationship'}, $data->{type} );
616 _add_graphml_data( $edge_el, $edge_data_keys{'colocated'}, $data->{colocated} );
617 if( exists $data->{non_correctable} ) {
618 _add_graphml_data( $edge_el, $edge_data_keys{'non_correctable'},
619 $data->{non_correctable} );
621 if( exists $data->{non_independent} ) {
622 _add_graphml_data( $edge_el, $edge_data_keys{'non_independent'},
623 $data->{non_independent} );
627 # Save and return the thing
628 my $result = decode_utf8( $graphml->toString(1) );
632 sub _add_graphml_data {
633 my( $el, $key, $value ) = @_;
634 return unless defined $value;
635 my $data_el = $el->addNewChild( $el->namespaceURI, 'data' );
636 $data_el->setAttribute( 'key', $key );
637 $data_el->appendText( $value );
642 print $graph->as_csv( $recalculate )
644 Returns a CSV alignment table representation of the collation graph, one
645 row per witness (or witness uncorrected.) Unless $recalculate is passed
646 (and is a true value), the method will return a cached copy of the CSV
647 after the first call to the method.
653 my $table = $self->make_alignment_table;
654 my $csv = Text::CSV_XS->new( { binary => 1, quote_null => 0 } );
656 foreach my $row ( @$table ) {
657 $csv->combine( @$row );
658 push( @result, decode_utf8( $csv->string ) );
660 return join( "\n", @result );
663 # Make an alignment table - $noderefs controls whether the objects
664 # in the table are the nodes or simply their readings.
666 sub make_alignment_table {
667 my( $self, $noderefs, $include ) = @_;
668 unless( $self->linear ) {
669 warn "Need a linear graph in order to make an alignment table";
673 my @all_pos = ( 1 .. $self->end->rank - 1 );
674 foreach my $wit ( $self->tradition->witnesses ) {
675 # print STDERR "Making witness row(s) for " . $wit->sigil . "\n";
676 my @wit_path = $self->reading_sequence( $self->start, $self->end, $wit->sigil );
677 my @row = _make_witness_row( \@wit_path, \@all_pos, $noderefs );
678 unshift( @row, $wit->sigil );
679 push( @$table, \@row );
680 if( $wit->is_layered ) {
681 my @wit_ac_path = $self->reading_sequence( $self->start, $self->end,
682 $wit->sigil.$self->ac_label, $wit->sigil );
683 my @ac_row = _make_witness_row( \@wit_ac_path, \@all_pos, $noderefs );
684 unshift( @ac_row, $wit->sigil . $self->ac_label );
685 push( @$table, \@ac_row );
691 # Winnow out the rows for any witness not included.
692 foreach my $row ( @$table ) {
693 next unless $include->{$row->[0]};
694 push( @$winnowed, $row );
699 # Return a table where the witnesses read in columns rather than rows.
700 my $turned = _turn_table( $table );
701 # TODO We should really go through and delete empty rows.
705 sub _make_witness_row {
706 my( $path, $positions, $noderefs ) = @_;
708 map { $char_hash{$_} = undef } @$positions;
709 foreach my $rdg ( @$path ) {
710 my $rtext = $rdg->text;
711 $rtext = '#LACUNA#' if $rdg->is_lacuna;
712 # print STDERR "No rank for " . $rdg->id . "\n" unless defined $rdg->rank;
713 $char_hash{$rdg->rank} = $noderefs ? $rdg : $rtext;
715 my @row = map { $char_hash{$_} } @$positions;
716 # Fill in lacuna markers for undef spots in the row
717 my $last_el = shift @row;
718 my @filled_row = ( $last_el );
719 foreach my $el ( @row ) {
720 # If we are using node reference, make the lacuna node appear many times
721 # in the table. If not, use the lacuna tag.
722 if( $last_el && _el_is_lacuna( $last_el ) && !defined $el ) {
723 $el = $noderefs ? $last_el : '#LACUNA#';
725 push( @filled_row, $el );
731 # Tiny utility function to say if a table element is a lacuna
734 return 1 if $el eq '#LACUNA#';
735 return 1 if ref( $el ) eq 'Text::Tradition::Collation::Reading'
740 # Helper to turn the witnesses along columns rather than rows. Assumes
745 return $result unless scalar @$table;
746 my $nrows = scalar @{$table->[0]};
747 foreach my $idx ( 0 .. $nrows - 1 ) {
748 foreach my $wit ( 0 .. $#{$table} ) {
749 $result->[$idx]->[$wit] = $table->[$wit]->[$idx];
757 =head2 Navigation methods
763 my $beginning = $collation->start();
765 Returns the beginning of the collation, a meta-reading with label '#START#'.
769 my $end = $collation->end();
771 Returns the end of the collation, a meta-reading with label '#END#'.
774 =item B<reading_sequence>
776 my @readings = $graph->reading_sequence( $first, $last, $path[, $alt_path] );
778 Returns the ordered list of readings, starting with $first and ending
779 with $last, along the given witness path. If no path is specified,
780 assume that the path is that of the base text (if any.)
784 # TODO Think about returning some lazy-eval iterator.
786 sub reading_sequence {
787 my( $self, $start, $end, $witness, $backup ) = @_;
789 $witness = $self->baselabel unless $witness;
790 my @readings = ( $start );
793 while( $n && $n->id ne $end->id ) {
794 if( exists( $seen{$n->id} ) ) {
795 warn "Detected loop at " . $n->id;
800 my $next = $self->next_reading( $n, $witness, $backup );
802 warn "Did not find any path for $witness from reading " . $n->id;
805 push( @readings, $next );
808 # Check that the last reading is our end reading.
809 my $last = $readings[$#readings];
810 warn "Last reading found from " . $start->text .
811 " for witness $witness is not the end!"
812 unless $last->id eq $end->id;
817 =item B<next_reading>
819 my $next_reading = $graph->next_reading( $reading, $witpath );
821 Returns the reading that follows the given reading along the given witness
827 # Return the successor via the corresponding path.
829 my $answer = $self->_find_linked_reading( 'next', @_ );
830 return $self->reading( $answer );
833 =item B<prior_reading>
835 my $prior_reading = $graph->prior_reading( $reading, $witpath );
837 Returns the reading that precedes the given reading along the given witness
843 # Return the predecessor via the corresponding path.
845 my $answer = $self->_find_linked_reading( 'prior', @_ );
846 return $self->reading( $answer );
849 sub _find_linked_reading {
850 my( $self, $direction, $node, $path, $alt_path ) = @_;
851 my @linked_paths = $direction eq 'next'
852 ? $self->sequence->edges_from( $node )
853 : $self->sequence->edges_to( $node );
854 return undef unless scalar( @linked_paths );
856 # We have to find the linked path that contains all of the
857 # witnesses supplied in $path.
858 my( @path_wits, @alt_path_wits );
859 @path_wits = sort( $self->witnesses_of_label( $path ) ) if $path;
860 @alt_path_wits = sort( $self->witnesses_of_label( $alt_path ) ) if $alt_path;
863 foreach my $le ( @linked_paths ) {
864 if( $self->sequence->has_edge_attribute( @$le, $self->baselabel ) ) {
867 my @le_wits = $self->path_witnesses( $le );
868 if( _is_within( \@path_wits, \@le_wits ) ) {
869 # This is the right path.
870 return $direction eq 'next' ? $le->[1] : $le->[0];
871 } elsif( _is_within( \@alt_path_wits, \@le_wits ) ) {
875 # Got this far? Return the alternate path if it exists.
876 return $direction eq 'next' ? $alt_le->[1] : $alt_le->[0]
879 # Got this far? Return the base path if it exists.
880 return $direction eq 'next' ? $base_le->[1] : $base_le->[0]
883 # Got this far? We have no appropriate path.
884 warn "Could not find $direction node from " . $node->label
885 . " along path $path";
891 my( $set1, $set2 ) = @_;
892 my $ret = @$set1; # will be 0, i.e. false, if set1 is empty
893 foreach my $el ( @$set1 ) {
894 $ret = 0 unless grep { /^\Q$el\E$/ } @$set2;
900 ## INITIALIZATION METHODS - for use by parsers
902 # For use when a collation is constructed from a base text and an apparatus.
903 # We have the sequences of readings and just need to add path edges.
904 # When we are done, clear out the witness path attributes, as they are no
906 # TODO Find a way to replace the witness path attributes with encapsulated functions?
908 sub make_witness_paths {
910 foreach my $wit ( $self->tradition->witnesses ) {
911 print STDERR "Making path for " . $wit->sigil . "\n";
912 $self->make_witness_path( $wit );
916 sub make_witness_path {
917 my( $self, $wit ) = @_;
918 my @chain = @{$wit->path};
919 my $sig = $wit->sigil;
920 foreach my $idx ( 0 .. $#chain-1 ) {
921 $self->add_path( $chain[$idx], $chain[$idx+1], $sig );
923 if( $wit->is_layered ) {
924 @chain = @{$wit->uncorrected_path};
925 foreach my $idx( 0 .. $#chain-1 ) {
926 my $source = $chain[$idx];
927 my $target = $chain[$idx+1];
928 $self->add_path( $source, $target, $sig.$self->ac_label )
929 unless $self->has_path( $source, $target, $sig );
933 $wit->clear_uncorrected_path;
936 sub calculate_ranks {
938 # Walk a version of the graph where every node linked by a relationship
939 # edge is fundamentally the same node, and do a topological ranking on
940 # the nodes in this graph.
941 my $topo_graph = Graph->new();
945 foreach my $r ( $self->readings ) {
946 next if exists $rel_containers{$r->id};
947 my @rels = $r->related_readings( 'colocated' );
949 # Make a relationship container.
951 my $rn = 'rel_container_' . $rel_ctr++;
952 $topo_graph->add_vertex( $rn );
954 $rel_containers{$_->id} = $rn;
957 # Add a new node to mirror the old node.
958 $rel_containers{$r->id} = $r->id;
959 $topo_graph->add_vertex( $r->id );
964 foreach my $r ( $self->readings ) {
965 foreach my $n ( $self->sequence->successors( $r->id ) ) {
966 my( $tfrom, $tto ) = ( $rel_containers{$r->id},
967 $rel_containers{$n} );
968 $DB::single = 1 unless $tfrom && $tto;
969 $topo_graph->add_edge( $tfrom, $tto );
973 # Now do the rankings, starting with the start node.
974 my $topo_start = $rel_containers{$self->start->id};
975 my $node_ranks = { $topo_start => 0 };
976 my @curr_origin = ( $topo_start );
977 # A little iterative function.
978 while( @curr_origin ) {
979 @curr_origin = _assign_rank( $topo_graph, $node_ranks, @curr_origin );
981 # Transfer our rankings from the topological graph to the real one.
982 foreach my $r ( $self->readings ) {
983 if( defined $node_ranks->{$rel_containers{$r->id}} ) {
984 $r->rank( $node_ranks->{$rel_containers{$r->id}} );
987 die "No rank calculated for node " . $r->id
988 . " - do you have a cycle in the graph?";
994 my( $graph, $node_ranks, @current_nodes ) = @_;
995 # Look at each of the children of @current_nodes. If all the child's
996 # parents have a rank, assign it the highest rank + 1 and add it to
997 # @next_nodes. Otherwise skip it; we will return when the highest-ranked
998 # parent gets a rank.
1000 foreach my $c ( @current_nodes ) {
1001 warn "Current reading $c has no rank!"
1002 unless exists $node_ranks->{$c};
1003 # print STDERR "Looking at child of node $c, rank "
1004 # . $node_ranks->{$c} . "\n";
1005 foreach my $child ( $graph->successors( $c ) ) {
1006 next if exists $node_ranks->{$child};
1007 my $highest_rank = -1;
1009 foreach my $parent ( $graph->predecessors( $child ) ) {
1010 if( exists $node_ranks->{$parent} ) {
1011 $highest_rank = $node_ranks->{$parent}
1012 if $highest_rank <= $node_ranks->{$parent};
1019 my $c_rank = $highest_rank + 1;
1020 # print STDERR "Assigning rank $c_rank to node $child \n";
1021 $node_ranks->{$child} = $c_rank;
1022 push( @next_nodes, $child );
1028 # Another method to make up for rough collation methods. If the same reading
1029 # appears multiple times at the same rank, collapse the nodes.
1032 my %unique_rank_rdg;
1033 foreach my $rdg ( $self->readings ) {
1034 next unless $rdg->has_rank;
1035 my $key = $rdg->rank . "||" . $rdg->text;
1036 if( exists $unique_rank_rdg{$key} ) {
1038 print STDERR "Combining readings at same rank: $key\n";
1039 $self->merge_readings( $unique_rank_rdg{$key}, $rdg );
1041 $unique_rank_rdg{$key} = $rdg;
1047 ## Utility functions
1049 # Return the string that joins together a list of witnesses for
1050 # display on a single path.
1051 sub witnesses_of_label {
1052 my( $self, $label ) = @_;
1053 my $regex = $self->wit_list_separator;
1054 my @answer = split( /\Q$regex\E/, $label );
1059 __PACKAGE__->meta->make_immutable;
1065 =item * Rationalize edge classes
1067 =item * Port the internal graph from Graph::Easy to Graph