1 package Text::Tradition::Collation;
4 use IPC::Run qw( run binary );
5 use Text::Tradition::Collation::Reading;
12 add_reading => 'add_node',
13 del_reading => 'del_node',
14 add_path => 'add_edge',
15 del_path => 'del_edge',
21 default => sub { Graph::Easy->new( undirected => 0 ) },
27 isa => 'Text::Tradition',
33 writer => '_save_svg',
34 predicate => 'has_svg',
40 writer => '_save_graphviz',
41 predicate => 'has_graphviz',
46 isa => 'XML::LibXML::Document',
47 writer => '_save_graphml',
48 predicate => 'has_graphml',
51 # Keeps track of the lemmas within the collation. At most one lemma
52 # per position in the graph.
55 isa => 'HashRef[Maybe[Str]]',
56 default => sub { {} },
59 has 'wit_list_separator' => (
68 default => 'base text',
71 # The collation can be created two ways:
72 # 1. Collate a set of witnesses (with CollateX I guess) and process
73 # the results as in 2.
74 # 2. Read a pre-prepared collation in one of a variety of formats,
75 # and make the graph from that.
77 # The graph itself will (for now) be immutable, and the positions
78 # within the graph will also be immutable. We need to calculate those
79 # positions upon graph construction. The equivalences between graph
80 # nodes will be mutable, entirely determined by the user (or possibly
81 # by some semantic pre-processing provided by the user.) So the
82 # constructor should just make an empty equivalences object. The
83 # constructor will also need to make the witness objects, if we didn't
84 # come through option 1.
87 my( $self, $args ) = @_;
88 $self->graph->use_class('node', 'Text::Tradition::Collation::Reading');
90 # Pass through any graph-specific options.
91 my $shape = exists( $args->{'shape'} ) ? $args->{'shape'} : 'ellipse';
92 $self->graph->set_attribute( 'node', 'shape', $shape );
95 # Wrapper around add_path
97 around add_path => sub {
101 # Make sure there are three arguments
103 warn "Call add_path with args source, target, witness";
106 # Make sure the proposed path does not yet exist
107 my( $source, $target, $wit ) = @_;
108 $source = $self->reading( $source )
109 unless ref( $source ) eq 'Text::Tradition::Collation::Reading';
110 $target = $self->reading( $target )
111 unless ref( $target ) eq 'Text::Tradition::Collation::Reading';
112 foreach my $path ( $source->edges_to( $target ) ) {
113 if( $path->label eq $wit ) {
121 # Wrapper around merge_nodes
125 my $first_node = shift;
126 my $second_node = shift;
127 $first_node->merge_from( $second_node );
128 unshift( @_, $first_node, $second_node );
129 return $self->graph->merge_nodes( @_ );
132 =head2 Output method(s)
138 print $graph->as_svg( $recalculate );
140 Returns an SVG string that represents the graph. Uses GraphViz to do
141 this, because Graph::Easy doesn\'t cope well with long graphs. Unless
142 $recalculate is passed (and is a true value), the method will return a
143 cached copy of the SVG after the first call to the method.
148 my( $self, $recalc ) = @_;
149 return $self->svg if $self->has_svg;
151 $self->_save_graphviz( $self->graph->as_graphviz() )
152 unless( $self->has_graphviz && !$recalc );
154 my @cmd = qw/dot -Tsvg/;
156 my $in = $self->graphviz;
157 run( \@cmd, \$in, ">", binary(), \$svg );
158 $self->{'svg'} = $svg;
164 print $graph->as_graphml( $recalculate )
166 Returns a GraphML representation of the collation graph, with
167 transposition information and position information. Unless
168 $recalculate is passed (and is a true value), the method will return a
169 cached copy of the SVG after the first call to the method.
174 my( $self, $recalc ) = @_;
175 return $self->graphml if $self->has_graphml;
178 my $graphml_ns = 'http://graphml.graphdrawing.org/xmlns';
179 my $xsi_ns = 'http://www.w3.org/2001/XMLSchema-instance';
180 my $graphml_schema = 'http://graphml.graphdrawing.org/xmlns ' .
181 'http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd';
183 # Create the document and root node
184 my $graphml = XML::LibXML->createDocument( "1.0", "UTF-8" );
185 my $root = $graphml->createElementNS( $graphml_ns, 'graphml' );
186 $graphml->setDocumentElement( $root );
187 $root->setNamespace( $xsi_ns, 'xsi', 0 );
188 $root->setAttributeNS( $xsi_ns, 'schemaLocation', $graphml_schema );
190 # Add the data keys for nodes
191 my @node_data = ( 'name', 'token', 'identical', 'position' );
192 foreach my $ndi ( 0 .. $#node_data ) {
193 my $key = $root->addNewChild( $graphml_ns, 'key' );
194 $key->setAttribute( 'attr.name', $node_data[$ndi] );
195 $key->setAttribute( 'attr.type', 'string' );
196 $key->setAttribute( 'for', 'node' );
197 $key->setAttribute( 'id', 'd'.$ndi );
200 # Add the data keys for edges
203 foreach my $wit ( $self->getWitnessList ) {
204 my $wit_key = 'w' . $wit_ctr++;
205 $wit_hash{$wit} = $wit_key;
206 my $key = $root->addNewChild( $graphml_ns, 'key' );
207 $key->setAttribute( 'attr.name', $wit );
208 $key->setAttribute( 'attr.type', 'string' );
209 $key->setAttribute( 'for', 'edge' );
210 $key->setAttribute( 'id', $wit_key );
213 # Add the graph, its nodes, and its edges
214 my $graph = $root->addNewChild( $graphml_ns, 'graph' );
215 $graph->setAttribute( 'edgedefault', 'directed' );
216 $graph->setAttribute( 'id', 'g0' ); # TODO make this meaningful
217 $graph->setAttribute( 'parse.edgeids', 'canonical' );
218 $graph->setAttribute( 'parse.edges', $self->edges() );
219 $graph->setAttribute( 'parse.nodeids', 'canonical' );
220 $graph->setAttribute( 'parse.nodes', $self->nodes() );
221 $graph->setAttribute( 'parse.order', 'nodesfirst' );
225 foreach my $n ( $self->readings ) {
226 my %this_node_data = ();
227 foreach my $ndi ( 0 .. $#node_data ) {
229 $this_node_data{'d'.$ndi} = $n->name if $node_data[$ndi] eq 'name';
230 $this_node_data{'d'.$ndi} = $n->label
231 if $node_data[$ndi] eq 'token';
232 $this_node_data{'d'.$ndi} = $n->primary->name if $n->has_primary;
233 $this_node_data{'d'.$ndi} =
234 $self->{'positions'}->node_position( $n )
235 if $node_data[$ndi] eq 'position';
237 my $node_el = $graph->addNewChild( $graphml_ns, 'node' );
238 my $node_xmlid = 'n' . $node_ctr++;
239 $node_hash{ $n->name } = $node_xmlid;
240 $node_el->setAttribute( 'id', $node_xmlid );
242 foreach my $dk ( keys %this_node_data ) {
243 my $d_el = $node_el->addNewChild( $graphml_ns, 'data' );
244 $d_el->setAttribute( 'key', $dk );
245 $d_el->appendTextChild( $this_node_data{$dk} );
249 foreach my $e ( $self->edges() ) {
250 my( $name, $from, $to ) = ( $e->name,
251 $node_hash{ $e->from()->name() },
252 $node_hash{ $e->to()->name() } );
253 my $edge_el = $graph->addNewChild( $graphml_ns, 'edge' );
254 $edge_el->setAttribute( 'source', $from );
255 $edge_el->setAttribute( 'target', $to );
256 $edge_el->setAttribute( 'id', $name );
257 # TODO Got to add the witnesses
261 $self->_save_graphml( $graphml );
267 =head2 Navigation methods
273 my $beginning = $collation->start();
275 Returns the beginning of the collation, a meta-reading with label '#START#'.
280 # Return the beginning reading of the graph.
282 my( $new_start ) = @_;
284 $self->del_reading( '#START#' );
285 $self->graph->rename_node( $new_start, '#START#' );
287 return $self->reading('#START#');
290 =item B<reading_sequence>
292 my @readings = $graph->reading_sequence( $first, $last, $path[, $alt_path] );
294 Returns the ordered list of readings, starting with $first and ending
295 with $last, along the given witness path. If no path is specified,
296 assume that the path is that of the base text (if any.)
300 sub reading_sequence {
301 my( $self, $start, $end, $witness, $backup ) = @_;
303 $witness = $self->baselabel unless $witness;
304 my @readings = ( $start );
307 while( $n && $n ne $end ) {
308 if( exists( $seen{$n->name()} ) ) {
309 warn "Detected loop at " . $n->name();
312 $seen{$n->name()} = 1;
314 my $next = $self->next_reading( $n, $witness, $backup );
315 warn "Did not find any path for $witness from reading " . $n->name
317 push( @readings, $next );
320 # Check that the last reading is our end reading.
321 my $last = $readings[$#readings];
322 warn "Last reading found from " . $start->label() .
323 " for witness $witness is not the end!"
324 unless $last eq $end;
329 =item B<next_reading>
331 my $next_reading = $graph->next_reading( $reading, $witpath );
333 Returns the reading that follows the given reading along the given witness
339 # Return the successor via the corresponding path.
341 return $self->_find_linked_reading( 'next', @_ );
344 =item B<prior_reading>
346 my $prior_reading = $graph->prior_reading( $reading, $witpath );
348 Returns the reading that precedes the given reading along the given witness
354 # Return the predecessor via the corresponding path.
356 return $self->_find_linked_reading( 'prior', @_ );
359 sub _find_linked_reading {
360 my( $self, $direction, $node, $path, $alt_path ) = @_;
361 my @linked_paths = $direction eq 'next'
362 ? $node->outgoing() : $node->incoming();
363 return undef unless scalar( @linked_paths );
365 # We have to find the linked path that contains all of the
366 # witnesses supplied in $path.
367 my( @path_wits, @alt_path_wits );
368 @path_wits = $self->witnesses_of_label( $path ) if $path;
369 @alt_path_wits = $self->witnesses_of_label( $alt_path ) if $alt_path;
372 foreach my $le ( @linked_paths ) {
373 if( $le->name eq $self->baselabel ) {
376 my @le_wits = $self->witnesses_of_label( $le->name );
377 if( _is_within( \@path_wits, \@le_wits ) ) {
378 # This is the right path.
379 return $direction eq 'next' ? $le->to() : $le->from();
380 } elsif( _is_within( \@alt_path_wits, \@le_wits ) ) {
385 # Got this far? Return the alternate path if it exists.
386 return $direction eq 'next' ? $alt_le->to() : $alt_le->from()
389 # Got this far? Return the base path if it exists.
390 return $direction eq 'next' ? $base_le->to() : $base_le->from()
393 # Got this far? We have no appropriate path.
394 warn "Could not find $direction node from " . $node->label
395 . " along path $path";
401 my( $set1, $set2 ) = @_;
402 my $ret = @$set1; # will be 0, i.e. false, if set1 is empty
403 foreach my $el ( @$set1 ) {
404 $ret = 0 unless grep { /^\Q$el\E$/ } @$set2;
410 ## INITIALIZATION METHODS - for use by parsers
411 # Walk the paths for each witness in the graph, and return the nodes
412 # that the graph has in common. If $using_base is true, some
413 # different logic is needed.
415 sub walk_witness_paths {
416 my( $self, $end ) = @_;
417 # For each witness, walk the path through the graph.
418 # Then we need to find the common nodes.
419 # TODO This method is going to fall down if we have a very gappy
420 # text in the collation.
423 foreach my $wit ( @{$self->tradition->witnesses} ) {
424 my $curr_reading = $self->start;
425 my @wit_path = $self->reading_sequence( $self->start, $end,
427 $wit->path( \@wit_path );
429 # Detect the common readings.
430 @common_readings = _find_common( \@common_readings, \@wit_path );
433 # Mark all the nodes as either common or not.
434 foreach my $cn ( @common_readings ) {
435 print STDERR "Setting " . $cn->name . " / " . $cn->label
436 . " as common node\n";
439 foreach my $n ( $self->readings() ) {
440 $n->make_variant unless $n->is_common;
442 # Return an array of the common nodes in order.
443 return @common_readings;
447 my( $common_readings, $new_path ) = @_;
449 if( @$common_readings ) {
450 foreach my $n ( @$new_path ) {
451 push( @cr, $n ) if grep { $_ eq $n } @$common_readings;
454 push( @cr, @$new_path );
460 my( $common_readings, $divergence ) = @_;
463 map { $diverged{$_->name} = 1 } @$divergence;
464 foreach( @$common_readings ) {
465 push( @cr, $_ ) unless $diverged{$_->name};
471 # An alternative to walk_witness_paths, for use when a collation is
472 # constructed from a base text and an apparatus. Also modifies the
473 # collation graph to remove all 'base text' paths and replace them
474 # with real witness paths.
476 sub walk_and_expand_base {
477 my( $self, $end ) = @_;
480 foreach my $wit ( @{$self->tradition->witnesses} ) {
481 my $sig = $wit->sigil;
483 $post_sig = $wit->post_correctione
484 if $wit->has_post_correctione;
486 # $DB::single = 1 if $wit->sigil eq 'Vb11';
487 my @wit_path = $self->reading_sequence( $self->start, $end, $sig );
488 $wit->path( \@wit_path );
489 $self->connect_readings_for_witness( $wit );
490 @common_readings = _find_common( \@common_readings, \@wit_path );
492 # If there is a post-correctio, get its path and compare.
493 # Add a correction range for each divergence.
495 my @corr_wit_path = $self->reading_sequence( $self->start, $end,
496 "$sig$post_sig", $sig );
498 # Map ante-corr readings to their indices
501 map { $in_orig{$_->name} = $i++ } @wit_path;
503 # Look for divergences
507 $DB::single = 1 if $sig eq 'Vb12';
508 foreach my $rdg ( @corr_wit_path ) {
509 if( exists( $in_orig{$rdg->name} ) && !$diverged ) {
510 # We are reading the same here
511 $last_common = $in_orig{$rdg->name};
512 } elsif ( exists( $in_orig{$rdg->name} ) ) {
513 # We have been diverging but are reading the same again.
514 # Add the correction to the witness.
515 my $offset = $last_common + 1;
516 my $length = $in_orig{$rdg->name} - $offset;
517 $wit->add_correction( $offset, $length, @correction );
519 @common_readings = _remove_common( \@common_readings, \@correction );
521 $last_common = $in_orig{$rdg->name};
522 } elsif( $diverged ) {
523 # We are in the middle of a divergence.
524 push( @correction, $rdg );
526 # We have started to diverge. Note it.
528 push( @correction, $rdg );
531 # Add any divergence that is at the end of the text
533 $wit->add_correction( $last_common+1, $#wit_path, \@correction );
538 # Remove any 'base text' paths.
539 foreach my $path ( $self->paths ) {
540 $self->del_path( $path )
541 if $path->label eq $self->baselabel;
545 sub connect_readings_for_witness {
546 my( $self, $wit ) = @_;
547 my @chain = @{$wit->path};
548 foreach my $idx ( 0 .. $#chain-1 ) {
549 $self->add_path( $chain[$idx], $chain[$idx+1], $wit->sigil );
553 sub common_readings {
555 my @common = grep { $_->is_common } $self->readings();
556 return sort { _cmp_position( $a->position, $b->position ) } @common;
559 # Calculate the relative positions of nodes in the graph, if they
560 # were not given to us.
561 sub calculate_positions {
562 my( $self, @ordered_common ) = @_;
564 # We have to calculate the position identifiers for each word,
565 # keyed on the common nodes. This will be 'fun'. The end result
566 # is a hash per witness, whose key is the word node and whose
567 # value is its position in the text. Common nodes are always N,1
568 # so have identical positions in each text.
571 foreach my $wit ( @{$self->tradition->witnesses} ) {
572 print STDERR "Calculating positions in " . $wit->sigil . "\n";
573 _update_positions_from_path( $wit->path, @ordered_common );
574 _update_positions_from_path( $wit->corrected_path, @ordered_common )
575 if $wit->has_post_correctione;
579 foreach my $r ( $self->readings() ) {
580 print STDERR "Reading " . $r->name . "/" . $r->label . " has no position\n"
581 unless( $r->has_position );
584 $self->init_lemmata();
587 sub _update_positions_from_path {
588 my( $path, @ordered_common ) = @_;
590 # First we walk the given path, making a matrix for the witness
591 # that corresponds to its eventual position identifier. Common
592 # nodes always start a new row, and are thus always in the first
596 my $cn = 0; # We should hit the common readings in order.
598 foreach my $wn ( @{$path} ) {
599 if( $wn eq $ordered_common[$cn] ) {
600 # Set up to look for the next common node, and
601 # start a new row of words.
603 push( @$wit_matrix, $row ) if scalar( @$row );
608 push( @$wit_matrix, $row ); # Push the last row onto the matrix
610 # Now we have a matrix per witness, so that each row in the
611 # matrix begins with a common node, and continues with all the
612 # variant words that appear in the witness. We turn this into
613 # real positions in row,cell format. But we need some
614 # trickery in order to make sure that each node gets assigned
615 # to only one position.
617 foreach my $li ( 1..scalar(@$wit_matrix) ) {
618 foreach my $di ( 1..scalar(@{$wit_matrix->[$li-1]}) ) {
619 my $reading = $wit_matrix->[$li-1]->[$di-1];
620 my $position = "$li,$di";
621 # If we have seen this node before, we need to compare
622 # its position with what went before.
623 unless( $reading->has_position &&
624 _cmp_position( $position, $reading->position ) < 1 ) {
625 # The new position ID replaces the old one.
626 $reading->position( $position );
627 } # otherwise, the old position needs to stay.
635 my @pos_a = split(/,/, $a );
636 my @pos_b = split(/,/, $b );
638 my $big_cmp = $pos_a[0] <=> $pos_b[0];
639 return $big_cmp if $big_cmp;
641 return $pos_a[1] <=> $pos_b[1];
642 } elsif ( $b ) { # a is undefined
644 } elsif ( $a ) { # b is undefined
647 return 0; # they are both undefined
653 map { $positions{$_->position} = 1 } $self->readings;
654 my @answer = sort { _cmp_position( $a, $b ) } keys( %positions );
658 sub readings_at_position {
659 my( $self, $pos ) = @_;
660 my @answer = grep { $_->position eq $pos } $self->readings;
664 ## Lemmatizer functions
669 foreach my $position ( $self->all_positions ) {
670 $self->lemmata->{$position} = undef;
673 foreach my $cr ( $self->common_readings ) {
674 $self->lemmata->{$cr->position} = $cr->name;
678 =item B<lemma_readings>
680 my @state = $graph->lemma_readings( @readings_delemmatized );
682 Takes a list of readings that have just been delemmatized, and returns
683 a set of tuples of the form ['reading', 'state'] that indicates what
684 changes need to be made to the graph.
690 A state of 1 means 'lemmatize this reading'
694 A state of 0 means 'delemmatize this reading'
698 A state of undef means 'an ellipsis belongs in the text here because
699 no decision has been made / an earlier decision was backed out'
706 my( $self, @toggled_off_nodes ) = @_;
708 # First get the positions of those nodes which have been
710 my $positions_off = {};
711 map { $positions_off->{ $_->position } = $_->name } @toggled_off_nodes;
713 # Now for each position, we have to see if a node is on, and we
714 # have to see if a node has been turned off.
716 foreach my $pos ( $self->all_positions() ) {
717 # Find the state of this position. If there is an active node,
718 # its name will be the state; otherwise the state will be 0
719 # (nothing at this position) or undef (ellipsis at this position)
720 my $active = $self->lemmata->{$pos};
722 # Is there a formerly active node that was toggled off?
723 if( exists( $positions_off->{$pos} ) ) {
724 my $off_node = $positions_off->{$pos};
725 if( $active && $active ne $off_node) {
726 push( @answer, [ $off_node, 0 ], [ $active, 1 ] );
728 push( @answer, [ $off_node, $active ] );
731 # No formerly active node, so we just see if there is a currently
734 # Push the active node, whatever it is.
735 push( @answer, [ $active, 1 ] );
737 # Push the state that is there. Arbitrarily use the first node
739 my @pos_nodes = $self->readings_at_position( $pos );
740 push( @answer, [ $pos_nodes[0]->name, $self->lemmata->{$pos} ] );
747 =item B<toggle_reading>
749 my @readings_delemmatized = $graph->toggle_reading( $reading_name );
751 Takes a reading node name, and either lemmatizes or de-lemmatizes
752 it. Returns a list of all readings that are de-lemmatized as a result
758 my( $self, $rname ) = @_;
760 return unless $rname;
761 my $reading = $self->reading( $rname );
762 if( !$reading || $reading->is_common() ) {
763 # Do nothing, it's a common node.
767 my $pos = $reading->position;
768 my $old_state = $self->lemmata->{$pos};
770 if( $old_state && $old_state eq $rname ) {
771 # Turn off the node. We turn on no others by default.
772 push( @readings_off, $reading );
775 $self->lemmata->{$pos} = $rname;
776 # Any other 'on' readings in the same position should be off.
777 push( @readings_off, $self->same_position_as( $reading ) );
778 # Any node that is an identical transposed one should be off.
779 push( @readings_off, $reading->identical_readings );
781 @readings_off = unique_list( @readings_off );
783 # Turn off the readings that need to be turned off.
784 my @readings_delemmatized;
785 foreach my $n ( @readings_off ) {
786 my $state = $self->lemmata->{$n->position};
787 if( $state && $state eq $n->name ) {
788 # this reading is still on, so turn it off
789 push( @readings_delemmatized, $n );
790 my $new_state = undef;
791 if( $n eq $reading ) {
792 # This is the reading that was clicked, so if there are no
793 # other readings there, turn off the position. In all other
794 # cases, restore the ellipsis.
795 my @other_n = $self->same_position_as( $n );
796 $new_state = 0 unless @other_n;
798 $self->lemmata->{$n->position} = $new_state;
799 } elsif( $old_state && $old_state eq $n->name ) {
800 # another reading has already been turned on here
801 push( @readings_delemmatized, $n );
802 } # else some other reading was on anyway, so pass.
804 return @readings_delemmatized;
807 sub same_position_as {
808 my( $self, $reading ) = @_;
809 my $pos = $reading->position;
810 my @same = grep { $_ ne $reading } $self->readings_at_position( $reading->position );
814 # Return the string that joins together a list of witnesses for
815 # display on a single path.
818 return join( $self->wit_list_separator, @_ );
821 sub witnesses_of_label {
822 my( $self, $label ) = @_;
823 my $regex = $self->wit_list_separator;
824 my @answer = split( /\Q$regex\E/, $label );
831 map { $h{$_->name} = $_ } @list;
836 __PACKAGE__->meta->make_immutable;