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::Position;
10 use Text::Tradition::Collation::Reading;
11 use Text::Tradition::Collation::Relationship;
12 use Text::Tradition::Collation::Segment;
20 add_reading => 'add_node',
21 del_reading => 'del_node',
22 del_segment => 'del_node',
23 add_path => 'add_edge',
24 del_path => 'del_edge',
30 relationships => 'edges',
32 default => sub { Graph::Easy->new( undirected => 0 ) },
36 has 'tradition' => ( # TODO should this not be ro?
38 isa => 'Text::Tradition',
44 writer => '_save_svg',
45 predicate => 'has_svg',
51 writer => '_save_graphml',
52 predicate => 'has_graphml',
58 writer => '_save_csv',
59 predicate => 'has_csv',
62 # Keeps track of the lemmas within the collation. At most one lemma
63 # per position in the graph.
66 isa => 'HashRef[Maybe[Str]]',
67 default => sub { {} },
70 has 'wit_list_separator' => (
79 default => 'base text',
100 # The collation can be created two ways:
101 # 1. Collate a set of witnesses (with CollateX I guess) and process
102 # the results as in 2.
103 # 2. Read a pre-prepared collation in one of a variety of formats,
104 # and make the graph from that.
106 # The graph itself will (for now) be immutable, and the positions
107 # within the graph will also be immutable. We need to calculate those
108 # positions upon graph construction. The equivalences between graph
109 # nodes will be mutable, entirely determined by the user (or possibly
110 # by some semantic pre-processing provided by the user.) So the
111 # constructor should just make an empty equivalences object. The
112 # constructor will also need to make the witness objects, if we didn't
113 # come through option 1.
116 my( $self, $args ) = @_;
117 $self->graph->use_class('node', 'Text::Tradition::Collation::Reading');
118 $self->graph->use_class('edge', 'Text::Tradition::Collation::Path');
120 # Pass through any graph-specific options.
121 my $shape = exists( $args->{'shape'} ) ? $args->{'shape'} : 'ellipse';
122 $self->graph->set_attribute( 'node', 'shape', $shape );
125 # Wrapper around add_path
127 around add_path => sub {
131 # Make sure there are three arguments
133 warn "Call add_path with args source, target, witness";
136 # Make sure the proposed path does not yet exist
137 # NOTE 'reading' will currently return readings and segments
138 my( $source, $target, $wit ) = @_;
139 $source = $self->reading( $source )
140 unless ref( $source ) eq 'Text::Tradition::Collation::Reading';
141 $target = $self->reading( $target )
142 unless ref( $target ) eq 'Text::Tradition::Collation::Reading';
143 foreach my $path ( $source->edges_to( $target ) ) {
144 if( $path->label eq $wit && $path->class eq 'edge.path' ) {
152 # Wrapper around paths
153 around paths => sub {
157 my @result = grep { $_->sub_class eq 'path' } $self->$orig( @_ );
161 around relationships => sub {
164 my @result = grep { $_->sub_class eq 'relationship' } $self->$orig( @_ );
168 around readings => sub {
171 my @result = grep { $_->sub_class ne 'segment' } $self->$orig( @_ );
175 around segments => sub {
178 my @result = grep { $_->sub_class eq 'segment' } $self->$orig( @_ );
182 # Wrapper around merge_nodes
186 my $first_node = shift;
187 my $second_node = shift;
188 $first_node->merge_from( $second_node );
189 unshift( @_, $first_node, $second_node );
190 return $self->graph->merge_nodes( @_ );
193 # Extra graph-alike utility
195 my( $self, $source, $target, $label ) = @_;
196 my @paths = $source->edges_to( $target );
197 my @relevant = grep { $_->label eq $label } @paths;
198 return scalar @relevant;
201 ## Dealing with groups of readings, i.e. segments.
204 my( $self, @items ) = @_;
205 my $segment = Text::Tradition::Collation::Segment->new( 'members' => \@items );
209 ## Dealing with relationships between readings. This is a different
210 ## sort of graph edge. Return a success/failure value and a list of
211 ## node pairs that have been linked.
213 sub add_relationship {
214 my( $self, $source, $target, $options ) = @_;
216 # Make sure there is not another relationship between these two
217 # readings or segments already
218 $source = $self->reading( $source )
219 unless ref( $source ) && $source->isa( 'Graph::Easy::Node' );
220 $target = $self->reading( $target )
221 unless ref( $target ) && $target->isa( 'Graph::Easy::Node' );
222 foreach my $rel ( $source->edges_to( $target ), $target->edges_to( $source ) ) {
223 if( $rel->class eq 'edge.relationship' ) {
224 return ( undef, "Relationship already exists between these readings" );
227 if( $options->{'equal_rank'} && !relationship_valid( $source, $target ) ) {
228 return ( undef, 'Relationship creates witness loop' );
231 # TODO Think about positional hilarity if relationships are added after positions
234 my @joined = ( [ $source->name, $target->name ] ); # Keep track of the nodes we join.
236 $options->{'this_relation'} = [ $source, $target ];
238 eval { $rel = Text::Tradition::Collation::Relationship->new( %$options ) };
240 return ( undef, $@ );
242 $self->graph->add_edge( $source, $target, $rel );
244 # TODO Handle global relationship setting
246 return( 1, @joined );
249 sub relationship_valid {
250 my( $source, $target ) = @_;
251 # Check that linking the source and target in a relationship won't lead
252 # to a path loop for any witness.
253 my @proposed_related = ( $source, $target );
254 push( @proposed_related, $source->related_readings );
255 push( @proposed_related, $target->related_readings );
257 map { $pr_ids{ $_->name } = 1 } @proposed_related;
258 # The lists of 'in' and 'out' should not have any element that appears
259 # in 'proposed_related'.
260 foreach my $pr ( @proposed_related ) {
261 foreach my $e ( $pr->incoming ) {
262 if( exists $pr_ids{ $e->from->name } ) {
266 foreach my $e ( $pr->outgoing ) {
267 if( exists $pr_ids{ $e->to->name } ) {
275 =head2 Output method(s)
281 print $graph->as_svg( $recalculate );
283 Returns an SVG string that represents the graph. Uses GraphViz to do
284 this, because Graph::Easy doesn\'t cope well with long graphs. Unless
285 $recalculate is passed (and is a true value), the method will return a
286 cached copy of the SVG after the first call to the method.
291 my( $self, $recalc ) = @_;
292 return $self->svg if $self->has_svg;
294 $self->collapse_graph_paths();
296 my @cmd = qw/dot -Tsvg/;
298 my $dotfile = File::Temp->new();
299 binmode $dotfile, ':utf8';
300 print $dotfile $self->as_dot();
301 push( @cmd, $dotfile->filename );
302 run( \@cmd, ">", binary(), \$svg );
303 $svg = decode_utf8( $svg );
304 $self->_save_svg( $svg );
305 $self->expand_graph_paths();
311 print $graph->as_dot( $view, $recalculate );
313 Returns a string that is the collation graph expressed in dot
314 (i.e. GraphViz) format. The 'view' argument determines what kind of
316 * 'path': a graph of witness paths through the collation (DEFAULT)
317 * 'relationship': a graph of how collation readings relate to
323 my( $self, $view ) = @_;
324 $view = 'path' unless $view;
325 # TODO consider making some of these things configurable
326 my $dot = sprintf( "digraph %s {\n", $self->tradition->name );
327 $dot .= "\tedge [ arrowhead=open ];\n";
328 $dot .= "\tgraph [ rankdir=LR ];\n";
329 $dot .= sprintf( "\tnode [ fontsize=%d, fillcolor=%s, style=%s, shape=%s ];\n",
330 11, "white", "filled", $self->graph->get_attribute( 'node', 'shape' ) );
332 foreach my $reading ( $self->readings ) {
333 # Need not output nodes without separate labels
334 next if $reading->name eq $reading->label;
335 # TODO output readings or segments, but not both
336 next if $reading->class eq 'node.segment';
337 $dot .= sprintf( "\t\"%s\" [ label=\"%s\" ];\n", $reading->name, $reading->label );
340 my @edges = $view eq 'relationship' ? $self->relationships : $self->paths;
341 foreach my $edge ( @edges ) {
342 my %variables = ( 'color' => '#000000',
343 'fontcolor' => '#000000',
344 'label' => $edge->label,
346 my $varopts = join( ', ', map { $_.'="'.$variables{$_}.'"' } sort keys %variables );
347 $dot .= sprintf( "\t\"%s\" -> \"%s\" [ %s ];\n",
348 $edge->from->name, $edge->to->name, $varopts );
356 print $graph->as_graphml( $recalculate )
358 Returns a GraphML representation of the collation graph, with
359 transposition information and position information. Unless
360 $recalculate is passed (and is a true value), the method will return a
361 cached copy of the SVG after the first call to the method.
366 my( $self, $recalc ) = @_;
367 return $self->graphml if $self->has_graphml;
370 my $graphml_ns = 'http://graphml.graphdrawing.org/xmlns';
371 my $xsi_ns = 'http://www.w3.org/2001/XMLSchema-instance';
372 my $graphml_schema = 'http://graphml.graphdrawing.org/xmlns ' .
373 'http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd';
375 # Create the document and root node
376 my $graphml = XML::LibXML->createDocument( "1.0", "UTF-8" );
377 my $root = $graphml->createElementNS( $graphml_ns, 'graphml' );
378 $graphml->setDocumentElement( $root );
379 $root->setNamespace( $xsi_ns, 'xsi', 0 );
380 $root->setAttributeNS( $xsi_ns, 'schemaLocation', $graphml_schema );
382 # TODO Add some global graph data
384 # Add the data keys for nodes
387 foreach my $datum ( qw/ name reading identical position class / ) {
388 $node_data_keys{$datum} = 'dn'.$ndi++;
389 my $key = $root->addNewChild( $graphml_ns, 'key' );
390 $key->setAttribute( 'attr.name', $datum );
391 $key->setAttribute( 'attr.type', 'string' );
392 $key->setAttribute( 'for', 'node' );
393 $key->setAttribute( 'id', $node_data_keys{$datum} );
396 # Add the data keys for edges, i.e. witnesses
399 foreach my $edge_key( qw/ witness_main witness_ante_corr relationship class / ) {
400 $edge_data_keys{$edge_key} = 'de'.$edi++;
401 my $key = $root->addNewChild( $graphml_ns, 'key' );
402 $key->setAttribute( 'attr.name', $edge_key );
403 $key->setAttribute( 'attr.type', 'string' );
404 $key->setAttribute( 'for', 'edge' );
405 $key->setAttribute( 'id', $edge_data_keys{$edge_key} );
408 # Add the graph, its nodes, and its edges
409 my $graph = $root->addNewChild( $graphml_ns, 'graph' );
410 $graph->setAttribute( 'edgedefault', 'directed' );
411 $graph->setAttribute( 'id', 'g0' ); # TODO make this meaningful
412 $graph->setAttribute( 'parse.edgeids', 'canonical' );
413 $graph->setAttribute( 'parse.edges', scalar($self->paths) );
414 $graph->setAttribute( 'parse.nodeids', 'canonical' );
415 $graph->setAttribute( 'parse.nodes', scalar($self->readings) );
416 $graph->setAttribute( 'parse.order', 'nodesfirst' );
420 # Add our readings to the graph
421 foreach my $n ( sort { $a->name cmp $b->name } $self->readings ) {
422 my $node_el = $graph->addNewChild( $graphml_ns, 'node' );
423 my $node_xmlid = 'n' . $node_ctr++;
424 $node_hash{ $n->name } = $node_xmlid;
425 $node_el->setAttribute( 'id', $node_xmlid );
426 _add_graphml_data( $node_el, $node_data_keys{'name'}, $n->name );
427 _add_graphml_data( $node_el, $node_data_keys{'reading'}, $n->label );
428 _add_graphml_data( $node_el, $node_data_keys{'position'}, $n->position->reference )
430 _add_graphml_data( $node_el, $node_data_keys{'class'}, $n->sub_class );
431 _add_graphml_data( $node_el, $node_data_keys{'identical'}, $n->primary->name )
435 # Add any segments we have
436 foreach my $n ( sort { $a->name cmp $b->name } $self->segments ) {
437 my $node_el = $graph->addNewChild( $graphml_ns, 'node' );
438 my $node_xmlid = 'n' . $node_ctr++;
439 $node_hash{ $n->name } = $node_xmlid;
440 $node_el->setAttribute( 'id', $node_xmlid );
441 _add_graphml_data( $node_el, $node_data_keys{'class'}, $n->sub_class );
442 _add_graphml_data( $node_el, $node_data_keys{'name'}, $n->name );
445 # Add the path, relationship, and segment edges
447 foreach my $e ( sort { $a->from->name cmp $b->from->name } $self->graph->edges() ) {
448 my( $name, $from, $to ) = ( 'e'.$edge_ctr++,
449 $node_hash{ $e->from->name() },
450 $node_hash{ $e->to->name() } );
451 my $edge_el = $graph->addNewChild( $graphml_ns, 'edge' );
452 $edge_el->setAttribute( 'source', $from );
453 $edge_el->setAttribute( 'target', $to );
454 $edge_el->setAttribute( 'id', $name );
456 _add_graphml_data( $edge_el, $edge_data_keys{'class'}, $e->sub_class );
457 if( $e->sub_class eq 'path' ) {
458 # It's a witness path, so add the witness
459 my $base = $e->label;
460 my $key = $edge_data_keys{'witness_main'};
462 if( $e->label =~ /^(.*?)\s+(\(a\.c\.\))$/ ) {
464 $key = $edge_data_keys{'witness_ante_corr'};
466 _add_graphml_data( $edge_el, $key, $base );
467 } elsif( $e->sub_class eq 'relationship' ) {
468 # It's a relationship
469 _add_graphml_data( $edge_el, $edge_data_keys{'relationship'}, $e->label );
470 } # else a segment, nothing to record but source, target, class
474 $self->_save_graphml( $graphml->toString(1) );
475 return $graphml->toString(1);
478 sub _add_graphml_data {
479 my( $el, $key, $value ) = @_;
480 my $data_el = $el->addNewChild( $el->namespaceURI, 'data' );
481 return unless defined $value;
482 $data_el->setAttribute( 'key', $key );
483 $data_el->appendText( $value );
488 print $graph->as_csv( $recalculate )
490 Returns a CSV alignment table representation of the collation graph, one
491 row per witness (or witness uncorrected.) Unless $recalculate is passed
492 (and is a true value), the method will return a cached copy of the CSV
493 after the first call to the method.
498 my( $self, $recalc ) = @_;
499 return $self->csv if $self->has_csv;
500 my $table = $self->make_alignment_table;
501 my $csv = Text::CSV_XS->new( { binary => 1, quote_null => 0 } );
503 foreach my $row ( @$table ) {
504 $csv->combine( @$row );
505 push( @result, decode_utf8( $csv->string ) );
507 $self->_save_csv( join( "\n", @result ) );
511 sub make_alignment_table {
513 unless( $self->linear ) {
514 warn "Need a linear graph in order to make an alignment table";
518 my @all_pos = sort { $a <=> $b } $self->possible_positions;
519 foreach my $wit ( $self->tradition->witnesses ) {
520 my @row = _make_witness_row( $wit->path, \@all_pos );
521 unshift( @row, $wit->sigil );
522 push( @$table, \@row );
523 if( $wit->has_ante_corr ) {
524 my @ac_row = _make_witness_row( $wit->uncorrected_path, \@all_pos );
525 unshift( @ac_row, $wit->sigil . $self->ac_label );
526 push( @$table, \@ac_row );
529 # Return a table where the witnesses read in columns rather than rows.
530 my $turned = _turn_table( $table );
534 sub _make_witness_row {
535 my( $path, $positions ) = @_;
537 map { $char_hash{$_} = undef } @$positions;
538 foreach my $rdg ( @$path ) {
539 $char_hash{$rdg->rank} = $rdg->text;
541 my @row = map { $char_hash{$_} } @$positions;
545 # Helper to turn the witnesses along columns rather than rows. Assumes
550 return $result unless scalar @$table;
551 my $nrows = scalar @{$table->[0]};
552 foreach my $idx ( 0 .. $nrows - 1 ) {
553 foreach my $wit ( 0 .. $#{$table} ) {
554 $result->[$idx]->[$wit] = $table->[$wit]->[$idx];
561 sub collapse_graph_paths {
563 # Our collation graph has an path per witness. This is great for
564 # calculation purposes, but terrible for display. Thus we want to
565 # display only one path between any two nodes.
567 return if $self->collapsed;
569 print STDERR "Collapsing witness paths in graph...\n";
571 # Don't list out every witness if we have more than half to list.
572 my $majority = int( scalar( $self->tradition->witnesses ) / 2 ) + 1;
573 # But don't compress if there are only a few witnesses.
574 $majority = 4 if $majority < 4;
575 foreach my $node ( $self->readings ) {
577 # We will visit each node, so we only look ahead.
578 foreach my $edge ( $node->outgoing() ) {
579 next unless $edge->class eq 'edge.path';
580 add_hash_entry( $newlabels, $edge->to->name, $edge->name );
581 $self->del_path( $edge );
584 foreach my $newdest ( keys %$newlabels ) {
586 my @compressed_wits = @{$newlabels->{$newdest}};
587 if( @compressed_wits < $majority ) {
588 $label = join( ', ', sort( @{$newlabels->{$newdest}} ) );
590 ## TODO FIX THIS HACK
592 foreach my $wit ( @compressed_wits ) {
593 push( @aclabels, $wit ) if( $wit =~ /^(.*?)(\s*\(?a\.\s*c\.\)?)$/ );
595 $label = join( ', ', 'majority', sort( @aclabels ) );
598 my $newpath = $self->add_path( $node, $self->reading( $newdest ), $label );
599 $newpath->hidden_witnesses( \@compressed_wits );
603 $self->collapsed( 1 );
606 sub expand_graph_paths {
608 # Our collation graph has only one path between any two nodes.
609 # This is great for display, but not so great for analysis.
610 # Expand this so that each witness has its own path between any
612 return unless $self->collapsed;
614 print STDERR "Expanding witness paths in graph...\n";
615 foreach my $path( $self->paths ) {
616 my $from = $path->from;
618 warn sprintf( "No hidden witnesses on %s -> %s ?", $from->name, $to->name )
619 unless $path->has_hidden_witnesses;
620 my @wits = @{$path->hidden_witnesses};
621 $self->del_path( $path );
623 $self->add_path( $from, $to, $_ );
626 $self->collapsed( 0 );
631 =head2 Navigation methods
637 my $beginning = $collation->start();
639 Returns the beginning of the collation, a meta-reading with label '#START#'.
644 # Return the beginning reading of the graph.
646 my( $new_start ) = @_;
648 $self->del_reading( '#START#' );
649 $self->graph->rename_node( $new_start, '#START#' );
651 # Make sure the start node has a start position.
652 unless( $self->reading( '#START#' )->has_position ) {
653 $self->reading( '#START#' )->position( '0,0' );
655 return $self->reading('#START#');
660 my $end = $collation->end();
662 Returns the end of the collation, a meta-reading with label '#END#'.
670 $self->del_reading( '#END#' );
671 $self->graph->rename_node( $new_end, '#END#' );
673 return $self->reading('#END#');
676 =item B<reading_sequence>
678 my @readings = $graph->reading_sequence( $first, $last, $path[, $alt_path] );
680 Returns the ordered list of readings, starting with $first and ending
681 with $last, along the given witness path. If no path is specified,
682 assume that the path is that of the base text (if any.)
686 # TODO Think about returning some lazy-eval iterator.
688 sub reading_sequence {
689 my( $self, $start, $end, $witness, $backup ) = @_;
691 $witness = $self->baselabel unless $witness;
692 my @readings = ( $start );
695 while( $n && $n ne $end ) {
696 if( exists( $seen{$n->name()} ) ) {
697 warn "Detected loop at " . $n->name();
700 $seen{$n->name()} = 1;
702 my $next = $self->next_reading( $n, $witness, $backup );
703 warn "Did not find any path for $witness from reading " . $n->name
705 push( @readings, $next );
708 # Check that the last reading is our end reading.
709 my $last = $readings[$#readings];
710 warn "Last reading found from " . $start->label() .
711 " for witness $witness is not the end!"
712 unless $last eq $end;
717 =item B<next_reading>
719 my $next_reading = $graph->next_reading( $reading, $witpath );
721 Returns the reading that follows the given reading along the given witness
727 # Return the successor via the corresponding path.
729 return $self->_find_linked_reading( 'next', @_ );
732 =item B<prior_reading>
734 my $prior_reading = $graph->prior_reading( $reading, $witpath );
736 Returns the reading that precedes the given reading along the given witness
742 # Return the predecessor via the corresponding path.
744 return $self->_find_linked_reading( 'prior', @_ );
747 sub _find_linked_reading {
748 my( $self, $direction, $node, $path, $alt_path ) = @_;
749 my @linked_paths = $direction eq 'next'
750 ? $node->outgoing() : $node->incoming();
751 return undef unless scalar( @linked_paths );
753 # We have to find the linked path that contains all of the
754 # witnesses supplied in $path.
755 my( @path_wits, @alt_path_wits );
756 @path_wits = $self->witnesses_of_label( $path ) if $path;
757 @alt_path_wits = $self->witnesses_of_label( $alt_path ) if $alt_path;
760 foreach my $le ( @linked_paths ) {
761 if( $le->name eq $self->baselabel ) {
764 my @le_wits = $self->witnesses_of_label( $le->name );
765 if( _is_within( \@path_wits, \@le_wits ) ) {
766 # This is the right path.
767 return $direction eq 'next' ? $le->to() : $le->from();
768 } elsif( _is_within( \@alt_path_wits, \@le_wits ) ) {
773 # Got this far? Return the alternate path if it exists.
774 return $direction eq 'next' ? $alt_le->to() : $alt_le->from()
777 # Got this far? Return the base path if it exists.
778 return $direction eq 'next' ? $base_le->to() : $base_le->from()
781 # Got this far? We have no appropriate path.
782 warn "Could not find $direction node from " . $node->label
783 . " along path $path";
789 my( $set1, $set2 ) = @_;
790 my $ret = @$set1; # will be 0, i.e. false, if set1 is empty
791 foreach my $el ( @$set1 ) {
792 $ret = 0 unless grep { /^\Q$el\E$/ } @$set2;
798 ## INITIALIZATION METHODS - for use by parsers
799 # Walk the paths for each witness in the graph, and return the nodes
800 # that the graph has in common. If $using_base is true, some
801 # different logic is needed.
802 # NOTE This does not create paths; it merely finds common readings.
804 sub walk_witness_paths {
806 # For each witness, walk the path through the graph.
807 # Then we need to find the common nodes.
808 # TODO This method is going to fall down if we have a very gappy
809 # text in the collation.
812 foreach my $wit ( $self->tradition->witnesses ) {
813 my $curr_reading = $self->start;
814 my @wit_path = $self->reading_sequence( $self->start, $self->end,
816 $wit->path( \@wit_path );
818 # Detect the common readings.
819 @common_readings = _find_common( \@common_readings, \@wit_path );
822 # Mark all the nodes as either common or not.
823 foreach my $cn ( @common_readings ) {
824 print STDERR "Setting " . $cn->name . " / " . $cn->label
825 . " as common node\n";
828 foreach my $n ( $self->readings() ) {
829 $n->make_variant unless $n->is_common;
831 # Return an array of the common nodes in order.
832 return @common_readings;
836 my( $common_readings, $new_path ) = @_;
838 if( @$common_readings ) {
839 foreach my $n ( @$new_path ) {
840 push( @cr, $n ) if grep { $_ eq $n } @$common_readings;
843 push( @cr, @$new_path );
849 my( $common_readings, $divergence ) = @_;
852 map { $diverged{$_->name} = 1 } @$divergence;
853 foreach( @$common_readings ) {
854 push( @cr, $_ ) unless $diverged{$_->name};
860 # For use when a collation is constructed from a base text and an apparatus.
861 # We have the sequences of readings and just need to add path edges.
863 sub make_witness_paths {
865 foreach my $wit ( $self->tradition->witnesses ) {
866 print STDERR "Making path for " . $wit->sigil . "\n";
867 $self->make_witness_path( $wit );
871 sub make_witness_path {
872 my( $self, $wit ) = @_;
873 my @chain = @{$wit->path};
874 my $sig = $wit->sigil;
875 foreach my $idx ( 0 .. $#chain-1 ) {
876 $self->add_path( $chain[$idx], $chain[$idx+1], $sig );
878 @chain = @{$wit->uncorrected_path};
879 foreach my $idx( 0 .. $#chain-1 ) {
880 my $source = $chain[$idx];
881 my $target = $chain[$idx+1];
882 $self->add_path( $source, $target, $sig.$self->ac_label )
883 unless $self->has_path( $source, $target, $sig );
887 sub calculate_ranks {
889 # Walk a version of the graph where every node linked by a relationship
890 # edge is fundamentally the same node, and do a topological ranking on
891 # the nodes in this graph.
892 my $topo_graph = Graph::Easy->new();
896 foreach my $r ( $self->readings ) {
897 next if exists $rel_containers{$r->name};
898 my @rels = $r->related_readings( 'colocated' );
900 # Make a relationship container.
902 my $rn = $topo_graph->add_node( 'rel_container_' . $rel_ctr++ );
904 $rel_containers{$_->name} = $rn;
907 # Add a new node to mirror the old node.
908 $rel_containers{$r->name} = $topo_graph->add_node( $r->name );
912 # Add the edges. Need only one edge between any pair of nodes.
913 foreach my $r ( $self->readings ) {
914 foreach my $n ( $r->neighbor_readings( 'forward' ) ) {
915 $topo_graph->add_edge_once( $rel_containers{$r->name},
916 $rel_containers{$n->name} );
920 # Now do the rankings, starting with the start node.
921 my $topo_start = $rel_containers{$self->start->name};
922 my $node_ranks = { $topo_start->name => 0 };
923 my @curr_origin = ( $topo_start );
924 # A little iterative function.
925 while( @curr_origin ) {
926 @curr_origin = _assign_rank( $node_ranks, @curr_origin );
928 # Transfer our rankings from the topological graph to the real one.
929 foreach my $r ( $self->readings ) {
930 $r->rank( $node_ranks->{$rel_containers{$r->name}->name} );
935 my( $node_ranks, @current_nodes ) = @_;
936 # Look at each of the children of @current_nodes. If all the child's
937 # parents have a rank, assign it the highest rank + 1 and add it to
938 # @next_nodes. Otherwise skip it.
940 foreach my $c ( @current_nodes ) {
941 warn "Current reading " . $c->name . "has no rank!"
942 unless exists $node_ranks->{$c->name};
943 # print STDERR "Looking at child of node " . $c->name . ", rank "
944 # . $node_ranks->{$c->name} . "\n";
945 my @children = map { $_->to } $c->outgoing;
946 foreach my $child ( @children ) {
947 next if exists $node_ranks->{$child->name};
948 my $highest_rank = -1;
950 my @parents = map { $_->from } $child->incoming;
951 foreach my $parent ( @parents ) {
952 if( exists $node_ranks->{$parent->name} ) {
953 $highest_rank = $node_ranks->{$parent->name}
954 if $highest_rank <= $node_ranks->{$parent->name};
961 # print STDERR "Assigning rank " . ( $highest_rank + 1 ) . " to node " . $child->name . "\n";
962 $node_ranks->{$child->name} = $highest_rank + 1;
963 push( @next_nodes, $child );
969 sub possible_positions {
972 map { $all_pos{ $_->rank } = 1 } $self->readings;
973 return keys %all_pos;
976 # TODO think about indexing this.
977 sub readings_at_position {
978 my( $self, $position, $strict ) = @_;
979 unless( ref( $position ) eq 'Text::Tradition::Collation::Position' ) {
980 $position = Text::Tradition::Collation::Position->new( $position );
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->position->cmp_with( $b->position ) } @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;