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' ) {
139 # Remove the reading from the graphs.
140 $self->sequence->delete_vertex( $arg );
141 $self->relations->delete_vertex( $arg );
144 $self->$orig( $arg );
147 # merge_readings( $main, $to_be_deleted );
152 # We only need the IDs for adding paths to the graph, not the reading
153 # objects themselves.
154 my( $kept, $deleted ) = $self->_stringify_args( @_ );
156 # The kept reading should inherit the paths and the relationships
157 # of the deleted reading.
158 foreach my $path ( $self->sequence->edges_at( $deleted ) ) {
159 my @vector = ( $kept );
160 push( @vector, $path->[1] ) if $path->[0] eq $deleted;
161 unshift( @vector, $path->[0] ) if $path->[1] eq $deleted;
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 # Is there a relationship here already? If so, keep it.
172 # TODO Warn about conflicting relationships
173 next if $self->relations->has_edge( @vector );
174 # If not, adopt the relationship that would be deleted.
175 $self->relations->add_edge( @vector );
176 my $attr = $self->relations->get_edge_attributes( @$rel );
177 $self->relations->set_edge_attributes( @vector, $attr );
180 # Do the deletion deed.
181 $self->del_reading( $deleted );
185 # Helper function for manipulating the graph.
186 sub _stringify_args {
187 my( $self, $first, $second, $arg ) = @_;
189 if ref( $first ) eq 'Text::Tradition::Collation::Reading';
190 $second = $second->id
191 if ref( $second ) eq 'Text::Tradition::Collation::Reading';
192 return( $first, $second, $arg );
200 # We only need the IDs for adding paths to the graph, not the reading
201 # objects themselves.
202 my( $source, $target, $wit ) = $self->_stringify_args( @_ );
204 # Connect the readings
205 $self->sequence->add_edge( $source, $target );
206 # Note the witness in question
207 $self->sequence->set_edge_attribute( $source, $target, $wit, 1 );
213 # We only need the IDs for adding paths to the graph, not the reading
214 # objects themselves.
215 my( $source, $target, $wit ) = $self->_stringify_args( @_ );
217 if( $self->sequence->has_edge_attribute( $source, $target, $wit ) ) {
218 $self->sequence->del_edge_attribute( $source, $target, $wit );
220 unless( keys %{$self->sequence->get_edge_attributes( $source, $target )} ) {
221 $self->sequence->delete_edge( $source, $target );
226 # Extra graph-alike utility
229 my( $source, $target, $wit ) = $self->_stringify_args( @_ );
230 return undef unless $self->sequence->has_edge( $source, $target );
231 return $self->sequence->has_edge_attribute( $source, $target, $wit );
234 ### Relationship logic
236 =head2 add_relationship( $reading1, $reading2, $definition )
238 Adds the specified relationship between the two readings. A relationship
239 is transitive (i.e. undirected), and must have the following attributes
240 specified in the hashref $definition:
244 =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.
246 =item * non_correctable - (Optional) True if the reading would not have been corrected independently.
248 =item * non_independent - (Optional) True if the variant is unlikely to have occurred independently in unrelated witnesses.
250 =item * global - (Optional) A meta-attribute, to set the same relationship between readings with the same text whenever they occur in the same place.
256 # Wouldn't it be lovely if edges could be objects, and all this type checking
257 # and attribute management could be done via Moose?
259 sub add_relationship {
261 my( $source, $target, $options ) = $self->_stringify_args( @_ );
264 if( !defined $options->{'type'} ||
265 $options->{'type'} !~ /^(spelling|orthographic|grammatical|meaning|repetition|transposition)$/i ) {
266 my $t = $options->{'type'} ? $options->{'type'} : '';
267 return( undef, "Invalid or missing type" . $options->{'type'} );
269 if( $options->{'type'} =~ /^(spelling|orthographic|grammatical|meaning)$/ ) {
270 $options->{'colocated'} = 1;
273 # Make sure there is not another relationship between these two
275 if( $self->relations->has_edge( $source, $target ) ) {
276 return ( undef, "Relationship already exists between these readings" );
278 if( $options->{'colocated'} && !$self->relationship_valid( $source, $target ) ) {
279 return ( undef, 'Relationship creates witness loop' );
282 my @vector = ( $source, $target );
283 $self->relations->add_edge( @vector );
284 $self->relations->set_edge_attributes( @vector, $options );
286 # TODO Handle global relationship setting
288 return( 1, @vector );
291 sub relationship_valid {
292 my( $self, $source, $target ) = @_;
293 # Check that linking the source and target in a relationship won't lead
294 # to a path loop for any witness. First make a lookup table of all the
295 # readings related to either the source or the target.
296 my @proposed_related = ( $source, $target );
297 push( @proposed_related, $source->related_readings( 'colocated' ) );
298 push( @proposed_related, $target->related_readings( 'colocated' ) );
300 map { $pr_ids{ $_->id } = 1 } @proposed_related;
302 # None of these proposed related readings should have a neighbor that
303 # is also in proposed_related.
304 foreach my $pr ( keys %pr_ids ) {
305 foreach my $neighbor( $self->sequence->neighbors( $pr ) ) {
306 return 0 if exists $pr_ids{$neighbor};
313 sub related_readings {
314 my( $self, $reading, $colocated ) = @_;
316 if( ref( $reading ) eq 'Text::Tradition::Collation::Reading' ) {
317 $reading = $reading->id;
319 # print STDERR "Returning related objects\n";
321 # print STDERR "Returning related object names\n";
323 my @related = $self->relations->all_reachable( $reading );
325 my @colo = grep { $self->relations->has_edge_attribute( $reading, $_, 'colocated' ) } @related;
328 return $return_object ? map { $self->reading( $_ ) } @related : @related;
331 =head2 Output method(s)
337 print $graph->as_svg( $recalculate );
339 Returns an SVG string that represents the graph. Uses GraphViz to do
340 this, because Graph::Easy doesn\'t cope well with long graphs. Unless
341 $recalculate is passed (and is a true value), the method will return a
342 cached copy of the SVG after the first call to the method.
349 my @cmd = qw/dot -Tsvg/;
351 my $dotfile = File::Temp->new();
353 # $dotfile->unlink_on_destroy(0);
354 binmode $dotfile, ':utf8';
355 print $dotfile $self->as_dot();
356 push( @cmd, $dotfile->filename );
357 run( \@cmd, ">", binary(), \$svg );
358 $svg = decode_utf8( $svg );
364 print $graph->as_dot( $view, $recalculate );
366 Returns a string that is the collation graph expressed in dot
367 (i.e. GraphViz) format. The 'view' argument determines what kind of
369 * 'path': a graph of witness paths through the collation (DEFAULT)
370 * 'relationship': a graph of how collation readings relate to
376 my( $self, $view ) = @_;
377 $view = 'sequence' unless $view;
378 # TODO consider making some of these things configurable
379 my $graph_name = $self->tradition->name;
380 $graph_name =~ s/[^\w\s]//g;
381 $graph_name = join( '_', split( /\s+/, $graph_name ) );
382 my $dot = sprintf( "digraph %s {\n", $graph_name );
383 $dot .= "\tedge [ arrowhead=open ];\n";
384 $dot .= "\tgraph [ rankdir=LR ];\n";
385 $dot .= sprintf( "\tnode [ fontsize=%d, fillcolor=%s, style=%s, shape=%s ];\n",
386 11, "white", "filled", "ellipse" );
388 foreach my $reading ( $self->readings ) {
389 # Need not output nodes without separate labels
390 next if $reading->id eq $reading->text;
391 $dot .= sprintf( "\t\"%s\" [ label=\"%s\" ];\n", $reading->id, $reading->text );
394 # TODO do something sensible for relationships
396 my @edges = $self->paths;
397 foreach my $edge ( @edges ) {
398 my %variables = ( 'color' => '#000000',
399 'fontcolor' => '#000000',
400 'label' => join( ', ', $self->path_witnesses( $edge ) ),
402 my $varopts = join( ', ', map { $_.'="'.$variables{$_}.'"' } sort keys %variables );
403 $dot .= sprintf( "\t\"%s\" -> \"%s\" [ %s ];\n",
404 $edge->[0], $edge->[1], $varopts );
411 my( $self, @edge ) = @_;
412 # If edge is an arrayref, cope.
413 if( @edge == 1 && ref( $edge[0] ) eq 'ARRAY' ) {
417 my @wits = keys %{$self->sequence->get_edge_attributes( @edge )};
423 print $graph->as_graphml( $recalculate )
425 Returns a GraphML representation of the collation graph, with
426 transposition information and position information. Unless
427 $recalculate is passed (and is a true value), the method will return a
428 cached copy of the SVG after the first call to the method.
436 my $graphml_ns = 'http://graphml.graphdrawing.org/xmlns';
437 my $xsi_ns = 'http://www.w3.org/2001/XMLSchema-instance';
438 my $graphml_schema = 'http://graphml.graphdrawing.org/xmlns ' .
439 'http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd';
441 # Create the document and root node
442 my $graphml = XML::LibXML->createDocument( "1.0", "UTF-8" );
443 my $root = $graphml->createElementNS( $graphml_ns, 'graphml' );
444 $graphml->setDocumentElement( $root );
445 $root->setNamespace( $xsi_ns, 'xsi', 0 );
446 $root->setAttributeNS( $xsi_ns, 'schemaLocation', $graphml_schema );
448 # Add the data keys for the graph
451 my @graph_attributes = qw/ wit_list_separator baselabel linear ac_label /;
452 foreach my $datum ( @graph_attributes ) {
453 $graph_data_keys{$datum} = 'dg'.$gdi++;
454 my $key = $root->addNewChild( $graphml_ns, 'key' );
455 $key->setAttribute( 'attr.name', $datum );
456 $key->setAttribute( 'attr.type', $key eq 'linear' ? 'boolean' : 'string' );
457 $key->setAttribute( 'for', 'graph' );
458 $key->setAttribute( 'id', $graph_data_keys{$datum} );
461 # Add the data keys for nodes
468 is_start => 'boolean',
470 is_lacuna => 'boolean',
472 foreach my $datum ( keys %node_data ) {
473 $node_data_keys{$datum} = 'dn'.$ndi++;
474 my $key = $root->addNewChild( $graphml_ns, 'key' );
475 $key->setAttribute( 'attr.name', $datum );
476 $key->setAttribute( 'attr.type', $node_data{$datum} );
477 $key->setAttribute( 'for', 'node' );
478 $key->setAttribute( 'id', $node_data_keys{$datum} );
481 # Add the data keys for edges, i.e. witnesses
485 class => 'string', # Path or relationship?
486 witness => 'string', # ID/label for a path
487 relationship => 'string', # ID/label for a relationship
488 extra => 'boolean', # Path key
489 colocated => 'boolean', # Relationship key
490 non_correctable => 'boolean', # Relationship key
491 non_independent => 'boolean', # Relationship key
493 foreach my $datum ( keys %edge_data ) {
494 $edge_data_keys{$datum} = 'de'.$edi++;
495 my $key = $root->addNewChild( $graphml_ns, 'key' );
496 $key->setAttribute( 'attr.name', $datum );
497 $key->setAttribute( 'attr.type', $edge_data{$datum} );
498 $key->setAttribute( 'for', 'edge' );
499 $key->setAttribute( 'id', $edge_data_keys{$datum} );
502 # Add the collation graph itself
503 my $graph = $root->addNewChild( $graphml_ns, 'graph' );
504 $graph->setAttribute( 'edgedefault', 'directed' );
505 $graph->setAttribute( 'id', $self->tradition->name );
506 $graph->setAttribute( 'parse.edgeids', 'canonical' );
507 $graph->setAttribute( 'parse.edges', scalar($self->paths) );
508 $graph->setAttribute( 'parse.nodeids', 'canonical' );
509 $graph->setAttribute( 'parse.nodes', scalar($self->readings) );
510 $graph->setAttribute( 'parse.order', 'nodesfirst' );
512 # Collation attribute data
513 foreach my $datum ( @graph_attributes ) {
514 _add_graphml_data( $graph, $graph_data_keys{$datum}, $self->$datum );
519 # Add our readings to the graph
520 foreach my $n ( sort { $a->id cmp $b->id } $self->readings ) {
521 my $node_el = $graph->addNewChild( $graphml_ns, 'node' );
522 my $node_xmlid = 'n' . $node_ctr++;
523 $node_hash{ $n->id } = $node_xmlid;
524 $node_el->setAttribute( 'id', $node_xmlid );
525 _add_graphml_data( $node_el, $node_data_keys{'id'}, $n->id );
526 _add_graphml_data( $node_el, $node_data_keys{'reading'}, $n->text );
527 _add_graphml_data( $node_el, $node_data_keys{'rank'}, $n->rank )
533 foreach my $e ( sort { $a->[0] cmp $b->[0] } $self->sequence->edges() ) {
534 # We add an edge in the graphml for every witness in $e.
535 foreach my $wit ( $self->path_witnesses( $e ) ) {
536 my( $id, $from, $to ) = ( 'e'.$edge_ctr++,
537 $node_hash{ $e->[0] },
538 $node_hash{ $e->[1] } );
539 my $edge_el = $graph->addNewChild( $graphml_ns, 'edge' );
540 $edge_el->setAttribute( 'source', $from );
541 $edge_el->setAttribute( 'target', $to );
542 $edge_el->setAttribute( 'id', $id );
544 _add_graphml_data( $edge_el, $edge_data_keys{'class'}, 'path' );
546 # It's a witness path, so add the witness
548 my $key = $edge_data_keys{'witness'};
549 # Is this an ante-corr witness?
550 my $aclabel = $self->ac_label;
551 if( $wit =~ /^(.*)\Q$aclabel\E$/ ) {
552 # Keep the base witness
554 # ...and record that this is an 'extra' reading path
555 _add_graphml_data( $edge_el, $edge_data_keys{'extra'}, $aclabel );
557 _add_graphml_data( $edge_el, $edge_data_keys{'witness'}, $base );
561 # Add the relationship edges
562 foreach my $e ( sort { $a->[0] cmp $b->[0] } $self->relationships ) {
563 my( $id, $from, $to ) = ( 'e'.$edge_ctr++,
564 $node_hash{ $e->[0] },
565 $node_hash{ $e->[1] } );
566 my $edge_el = $graph->addNewChild( $graphml_ns, 'edge' );
567 $edge_el->setAttribute( 'source', $from );
568 $edge_el->setAttribute( 'target', $to );
569 $edge_el->setAttribute( 'id', $id );
571 _add_graphml_data( $edge_el, $edge_data_keys{'class'}, 'relationship' );
573 my $data = $self->relations->get_edge_attributes( @$e );
574 # It's a relationship, so save the relationship data
575 _add_graphml_data( $edge_el, $edge_data_keys{'relationship'}, $data->{type} );
576 _add_graphml_data( $edge_el, $edge_data_keys{'colocated'}, $data->{colocated} );
577 if( exists $data->{non_correctable} ) {
578 _add_graphml_data( $edge_el, $edge_data_keys{'non_correctable'},
579 $data->{non_correctable} );
581 if( exists $data->{non_independent} ) {
582 _add_graphml_data( $edge_el, $edge_data_keys{'non_independent'},
583 $data->{non_independent} );
587 # Save and return the thing
588 my $result = decode_utf8( $graphml->toString(1) );
592 sub _add_graphml_data {
593 my( $el, $key, $value ) = @_;
594 return unless defined $value;
595 my $data_el = $el->addNewChild( $el->namespaceURI, 'data' );
596 $data_el->setAttribute( 'key', $key );
597 $data_el->appendText( $value );
602 print $graph->as_csv( $recalculate )
604 Returns a CSV alignment table representation of the collation graph, one
605 row per witness (or witness uncorrected.) Unless $recalculate is passed
606 (and is a true value), the method will return a cached copy of the CSV
607 after the first call to the method.
613 my $table = $self->make_alignment_table;
614 my $csv = Text::CSV_XS->new( { binary => 1, quote_null => 0 } );
616 foreach my $row ( @$table ) {
617 $csv->combine( @$row );
618 push( @result, decode_utf8( $csv->string ) );
620 return join( "\n", @result );
623 # Make an alignment table - $noderefs controls whether the objects
624 # in the table are the nodes or simply their readings.
626 sub make_alignment_table {
627 my( $self, $noderefs, $include ) = @_;
628 unless( $self->linear ) {
629 warn "Need a linear graph in order to make an alignment table";
633 my @all_pos = ( 1 .. $self->end->rank - 1 );
634 foreach my $wit ( $self->tradition->witnesses ) {
635 # print STDERR "Making witness row(s) for " . $wit->sigil . "\n";
636 my @wit_path = $self->reading_sequence( $self->start, $self->end, $wit->sigil );
637 my @row = _make_witness_row( \@wit_path, \@all_pos, $noderefs );
638 unshift( @row, $wit->sigil );
639 push( @$table, \@row );
640 if( $wit->is_layered ) {
641 my @wit_ac_path = $self->reading_sequence( $self->start, $self->end,
642 $wit->sigil.$self->ac_label, $wit->sigil );
643 my @ac_row = _make_witness_row( \@wit_ac_path, \@all_pos, $noderefs );
644 unshift( @ac_row, $wit->sigil . $self->ac_label );
645 push( @$table, \@ac_row );
651 # Winnow out the rows for any witness not included.
652 foreach my $row ( @$table ) {
653 next unless $include->{$row->[0]};
654 push( @$winnowed, $row );
659 # Return a table where the witnesses read in columns rather than rows.
660 my $turned = _turn_table( $table );
661 # TODO We should really go through and delete empty rows.
665 sub _make_witness_row {
666 my( $path, $positions, $noderefs ) = @_;
668 map { $char_hash{$_} = undef } @$positions;
669 foreach my $rdg ( @$path ) {
670 my $rtext = $rdg->text;
671 $rtext = '#LACUNA#' if $rdg->is_lacuna;
672 # print STDERR "No rank for " . $rdg->id . "\n" unless defined $rdg->rank;
673 $char_hash{$rdg->rank} = $noderefs ? $rdg : $rtext;
675 my @row = map { $char_hash{$_} } @$positions;
676 # Fill in lacuna markers for undef spots in the row
677 my $last_el = shift @row;
678 my @filled_row = ( $last_el );
679 foreach my $el ( @row ) {
680 # If we are using node reference, make the lacuna node appear many times
681 # in the table. If not, use the lacuna tag.
682 if( $last_el && _el_is_lacuna( $last_el ) && !defined $el ) {
683 $el = $noderefs ? $last_el : '#LACUNA#';
685 push( @filled_row, $el );
691 # Tiny utility function to say if a table element is a lacuna
694 return 1 if $el eq '#LACUNA#';
695 return 1 if ref( $el ) eq 'Text::Tradition::Collation::Reading'
700 # Helper to turn the witnesses along columns rather than rows. Assumes
705 return $result unless scalar @$table;
706 my $nrows = scalar @{$table->[0]};
707 foreach my $idx ( 0 .. $nrows - 1 ) {
708 foreach my $wit ( 0 .. $#{$table} ) {
709 $result->[$idx]->[$wit] = $table->[$wit]->[$idx];
717 =head2 Navigation methods
723 my $beginning = $collation->start();
725 Returns the beginning of the collation, a meta-reading with label '#START#'.
729 my $end = $collation->end();
731 Returns the end of the collation, a meta-reading with label '#END#'.
734 =item B<reading_sequence>
736 my @readings = $graph->reading_sequence( $first, $last, $path[, $alt_path] );
738 Returns the ordered list of readings, starting with $first and ending
739 with $last, along the given witness path. If no path is specified,
740 assume that the path is that of the base text (if any.)
744 # TODO Think about returning some lazy-eval iterator.
746 sub reading_sequence {
747 my( $self, $start, $end, $witness, $backup ) = @_;
749 $witness = $self->baselabel unless $witness;
750 my @readings = ( $start );
753 while( $n && $n->id ne $end->id ) {
754 if( exists( $seen{$n->id} ) ) {
755 warn "Detected loop at " . $n->id;
760 my $next = $self->next_reading( $n, $witness, $backup );
761 $DB::single = 1 if $next->id eq $end->id;
763 warn "Did not find any path for $witness from reading " . $n->id;
766 push( @readings, $next );
769 # Check that the last reading is our end reading.
770 my $last = $readings[$#readings];
771 warn "Last reading found from " . $start->text .
772 " for witness $witness is not the end!"
773 unless $last->id eq $end->id;
778 =item B<next_reading>
780 my $next_reading = $graph->next_reading( $reading, $witpath );
782 Returns the reading that follows the given reading along the given witness
788 # Return the successor via the corresponding path.
790 my $answer = $self->_find_linked_reading( 'next', @_ );
791 return $self->reading( $answer );
794 =item B<prior_reading>
796 my $prior_reading = $graph->prior_reading( $reading, $witpath );
798 Returns the reading that precedes the given reading along the given witness
804 # Return the predecessor via the corresponding path.
806 my $answer = $self->_find_linked_reading( 'prior', @_ );
807 return $self->reading( $answer );
810 sub _find_linked_reading {
811 my( $self, $direction, $node, $path, $alt_path ) = @_;
812 my @linked_paths = $direction eq 'next'
813 ? $self->sequence->edges_from( $node )
814 : $self->sequence->edges_to( $node );
815 return undef unless scalar( @linked_paths );
817 # We have to find the linked path that contains all of the
818 # witnesses supplied in $path.
819 my( @path_wits, @alt_path_wits );
820 @path_wits = sort( $self->witnesses_of_label( $path ) ) if $path;
821 @alt_path_wits = sort( $self->witnesses_of_label( $alt_path ) ) if $alt_path;
824 foreach my $le ( @linked_paths ) {
825 if( $self->sequence->has_edge_attribute( @$le, $self->baselabel ) ) {
828 my @le_wits = $self->path_witnesses( $le );
829 if( _is_within( \@path_wits, \@le_wits ) ) {
830 # This is the right path.
831 return $direction eq 'next' ? $le->[1] : $le->[0];
832 } elsif( _is_within( \@alt_path_wits, \@le_wits ) ) {
836 # Got this far? Return the alternate path if it exists.
837 return $direction eq 'next' ? $alt_le->[1] : $alt_le->[0]
840 # Got this far? Return the base path if it exists.
841 return $direction eq 'next' ? $base_le->[1] : $base_le->[0]
844 # Got this far? We have no appropriate path.
845 warn "Could not find $direction node from " . $node->label
846 . " along path $path";
852 my( $set1, $set2 ) = @_;
853 my $ret = @$set1; # will be 0, i.e. false, if set1 is empty
854 foreach my $el ( @$set1 ) {
855 $ret = 0 unless grep { /^\Q$el\E$/ } @$set2;
861 ## INITIALIZATION METHODS - for use by parsers
863 # For use when a collation is constructed from a base text and an apparatus.
864 # We have the sequences of readings and just need to add path edges.
865 # When we are done, clear out the witness path attributes, as they are no
867 # TODO Find a way to replace the witness path attributes with encapsulated functions?
869 sub make_witness_paths {
871 foreach my $wit ( $self->tradition->witnesses ) {
872 print STDERR "Making path for " . $wit->sigil . "\n";
873 $self->make_witness_path( $wit );
877 sub make_witness_path {
878 my( $self, $wit ) = @_;
879 my @chain = @{$wit->path};
880 my $sig = $wit->sigil;
881 foreach my $idx ( 0 .. $#chain-1 ) {
882 $self->add_path( $chain[$idx], $chain[$idx+1], $sig );
884 if( $wit->is_layered ) {
885 @chain = @{$wit->uncorrected_path};
886 foreach my $idx( 0 .. $#chain-1 ) {
887 my $source = $chain[$idx];
888 my $target = $chain[$idx+1];
889 $self->add_path( $source, $target, $sig.$self->ac_label )
890 unless $self->has_path( $source, $target, $sig );
894 $wit->clear_uncorrected_path;
897 sub calculate_ranks {
899 # Walk a version of the graph where every node linked by a relationship
900 # edge is fundamentally the same node, and do a topological ranking on
901 # the nodes in this graph.
902 my $topo_graph = Graph->new();
906 foreach my $r ( $self->readings ) {
907 next if exists $rel_containers{$r->id};
908 my @rels = $r->related_readings( 'colocated' );
910 # Make a relationship container.
912 my $rn = 'rel_container_' . $rel_ctr++;
913 $topo_graph->add_vertex( $rn );
915 $rel_containers{$_->id} = $rn;
918 # Add a new node to mirror the old node.
919 $rel_containers{$r->id} = $r->id;
920 $topo_graph->add_vertex( $r->id );
925 foreach my $r ( $self->readings ) {
926 foreach my $n ( $self->sequence->successors( $r->id ) ) {
927 my( $tfrom, $tto ) = ( $rel_containers{$r->id},
928 $rel_containers{$n} );
929 $topo_graph->add_edge( $tfrom, $tto );
933 # Now do the rankings, starting with the start node.
934 my $topo_start = $rel_containers{$self->start->id};
935 my $node_ranks = { $topo_start => 0 };
936 my @curr_origin = ( $topo_start );
937 # A little iterative function.
938 while( @curr_origin ) {
939 @curr_origin = _assign_rank( $topo_graph, $node_ranks, @curr_origin );
941 # Transfer our rankings from the topological graph to the real one.
942 foreach my $r ( $self->readings ) {
943 if( defined $node_ranks->{$rel_containers{$r->id}} ) {
944 $r->rank( $node_ranks->{$rel_containers{$r->id}} );
947 die "No rank calculated for node " . $r->id
948 . " - do you have a cycle in the graph?";
954 my( $graph, $node_ranks, @current_nodes ) = @_;
955 # Look at each of the children of @current_nodes. If all the child's
956 # parents have a rank, assign it the highest rank + 1 and add it to
957 # @next_nodes. Otherwise skip it; we will return when the highest-ranked
958 # parent gets a rank.
960 foreach my $c ( @current_nodes ) {
961 warn "Current reading $c has no rank!"
962 unless exists $node_ranks->{$c};
963 # print STDERR "Looking at child of node $c, rank "
964 # . $node_ranks->{$c} . "\n";
965 foreach my $child ( $graph->successors( $c ) ) {
966 next if exists $node_ranks->{$child};
967 my $highest_rank = -1;
969 foreach my $parent ( $graph->predecessors( $child ) ) {
970 if( exists $node_ranks->{$parent} ) {
971 $highest_rank = $node_ranks->{$parent}
972 if $highest_rank <= $node_ranks->{$parent};
979 my $c_rank = $highest_rank + 1;
980 # print STDERR "Assigning rank $c_rank to node $child \n";
981 $node_ranks->{$child} = $c_rank;
982 push( @next_nodes, $child );
988 # Another method to make up for rough collation methods. If the same reading
989 # appears multiple times at the same rank, collapse the nodes.
993 foreach my $rdg ( $self->readings ) {
994 next unless $rdg->has_rank;
995 my $key = $rdg->rank . "||" . $rdg->text;
996 if( exists $unique_rank_rdg{$key} ) {
998 print STDERR "Combining readings at same rank: $key\n";
999 $self->merge_readings( $unique_rank_rdg{$key}, $rdg );
1001 $unique_rank_rdg{$key} = $rdg;
1007 ## Utility functions
1009 # Return the string that joins together a list of witnesses for
1010 # display on a single path.
1011 sub witnesses_of_label {
1012 my( $self, $label ) = @_;
1013 my $regex = $self->wit_list_separator;
1014 my @answer = split( /\Q$regex\E/, $label );
1019 __PACKAGE__->meta->make_immutable;
1025 =item * Rationalize edge classes
1027 =item * Port the internal graph from Graph::Easy to Graph