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::Reading;
10 use Text::Tradition::Collation::Relationship;
18 add_reading => 'add_node',
19 add_lacuna => 'add_node',
20 del_reading => 'del_node',
21 add_path => 'add_edge',
22 del_path => 'del_edge',
27 relationships => 'edges',
29 default => sub { Graph::Easy->new( undirected => 0 ) },
33 has 'tradition' => ( # TODO should this not be ro?
35 isa => 'Text::Tradition',
41 writer => '_save_svg',
42 predicate => 'has_svg',
48 writer => '_save_graphml',
49 predicate => 'has_graphml',
55 writer => '_save_csv',
56 predicate => 'has_csv',
59 # Keeps track of the lemmas within the collation. At most one lemma
60 # per position in the graph.
63 isa => 'HashRef[Maybe[Str]]',
64 default => sub { {} },
67 has 'wit_list_separator' => (
76 default => 'base text',
97 # The collation can be created two ways:
98 # 1. Collate a set of witnesses (with CollateX I guess) and process
99 # the results as in 2.
100 # 2. Read a pre-prepared collation in one of a variety of formats,
101 # and make the graph from that.
103 # The graph itself will (for now) be immutable, and the positions
104 # within the graph will also be immutable. We need to calculate those
105 # positions upon graph construction. The equivalences between graph
106 # nodes will be mutable, entirely determined by the user (or possibly
107 # by some semantic pre-processing provided by the user.) So the
108 # constructor should just make an empty equivalences object. The
109 # constructor will also need to make the witness objects, if we didn't
110 # come through option 1.
113 my( $self, $args ) = @_;
114 $self->graph->use_class('node', 'Text::Tradition::Collation::Reading');
115 $self->graph->use_class('edge', 'Text::Tradition::Collation::Path');
117 # Pass through any graph-specific options.
118 my $shape = exists( $args->{'shape'} ) ? $args->{'shape'} : 'ellipse';
119 $self->graph->set_attribute( 'node', 'shape', $shape );
121 # Start and end points for all texts
122 $self->start( 'INIT' );
123 $self->end( 'INIT' );
126 around add_lacuna => sub {
130 my $l = $self->$orig( '#LACUNA_' . $id . '#' );
135 # Wrapper around add_path
137 around add_path => sub {
141 # Make sure there are three arguments
143 warn "Call add_path with args source, target, witness";
146 # Make sure the proposed path does not yet exist
147 # NOTE 'reading' will currently return readings and segments
148 my( $source, $target, $wit ) = @_;
149 $source = $self->reading( $source )
150 unless ref( $source ) eq 'Text::Tradition::Collation::Reading';
151 $target = $self->reading( $target )
152 unless ref( $target ) eq 'Text::Tradition::Collation::Reading';
153 foreach my $path ( $source->edges_to( $target ) ) {
154 if( $path->label eq $wit && $path->class eq 'edge.path' ) {
162 # Wrapper around paths
163 around paths => sub {
167 my @result = grep { $_->sub_class eq 'path' } $self->$orig( @_ );
171 around relationships => sub {
174 my @result = grep { $_->sub_class eq 'relationship' } $self->$orig( @_ );
178 # Wrapper around merge_nodes
181 my $first_node = shift;
182 my $second_node = shift;
183 $first_node->merge_from( $second_node );
184 unshift( @_, $first_node, $second_node );
185 return $self->graph->merge_nodes( @_ );
188 # Extra graph-alike utility
190 my( $self, $source, $target, $label ) = @_;
191 my @paths = $source->edges_to( $target );
192 my @relevant = grep { $_->label eq $label } @paths;
193 return scalar @relevant;
196 ## Dealing with relationships between readings. This is a different
197 ## sort of graph edge. Return a success/failure value and a list of
198 ## node pairs that have been linked.
200 sub add_relationship {
201 my( $self, $source, $target, $options ) = @_;
203 # Make sure there is not another relationship between these two
205 $source = $self->reading( $source )
206 unless ref( $source ) && $source->isa( 'Graph::Easy::Node' );
207 $target = $self->reading( $target )
208 unless ref( $target ) && $target->isa( 'Graph::Easy::Node' );
209 foreach my $rel ( $source->edges_to( $target ), $target->edges_to( $source ) ) {
210 if( $rel->class eq 'edge.relationship' ) {
211 return ( undef, "Relationship already exists between these readings" );
214 if( $options->{'equal_rank'} && !relationship_valid( $source, $target ) ) {
215 return ( undef, 'Relationship creates witness loop' );
218 # TODO Think about positional hilarity if relationships are added after positions
221 my @joined = ( [ $source->name, $target->name ] ); # Keep track of the nodes we join.
223 $options->{'this_relation'} = [ $source, $target ];
225 eval { $rel = Text::Tradition::Collation::Relationship->new( %$options ) };
227 return ( undef, $@ );
229 $self->graph->add_edge( $source, $target, $rel );
231 # TODO Handle global relationship setting
233 return( 1, @joined );
236 sub relationship_valid {
237 my( $source, $target ) = @_;
238 # Check that linking the source and target in a relationship won't lead
239 # to a path loop for any witness.
240 my @proposed_related = ( $source, $target );
241 push( @proposed_related, $source->related_readings );
242 push( @proposed_related, $target->related_readings );
244 map { $pr_ids{ $_->name } = 1 } @proposed_related;
245 # The lists of 'in' and 'out' should not have any element that appears
246 # in 'proposed_related'.
247 foreach my $pr ( @proposed_related ) {
248 foreach my $e ( $pr->incoming ) {
249 if( exists $pr_ids{ $e->from->name } ) {
253 foreach my $e ( $pr->outgoing ) {
254 if( exists $pr_ids{ $e->to->name } ) {
262 =head2 Output method(s)
268 print $graph->as_svg( $recalculate );
270 Returns an SVG string that represents the graph. Uses GraphViz to do
271 this, because Graph::Easy doesn\'t cope well with long graphs. Unless
272 $recalculate is passed (and is a true value), the method will return a
273 cached copy of the SVG after the first call to the method.
278 my( $self, $recalc ) = @_;
279 return $self->svg if $self->has_svg;
281 $self->collapse_graph_paths();
283 my @cmd = qw/dot -Tsvg/;
285 my $dotfile = File::Temp->new();
287 # $dotfile->unlink_on_destroy(0);
288 binmode $dotfile, ':utf8';
289 print $dotfile $self->as_dot();
290 push( @cmd, $dotfile->filename );
291 run( \@cmd, ">", binary(), \$svg );
292 $svg = decode_utf8( $svg );
293 $self->_save_svg( $svg );
294 $self->expand_graph_paths();
300 print $graph->as_dot( $view, $recalculate );
302 Returns a string that is the collation graph expressed in dot
303 (i.e. GraphViz) format. The 'view' argument determines what kind of
305 * 'path': a graph of witness paths through the collation (DEFAULT)
306 * 'relationship': a graph of how collation readings relate to
312 my( $self, $view ) = @_;
313 $view = 'path' unless $view;
314 # TODO consider making some of these things configurable
315 my $dot = sprintf( "digraph %s {\n", $self->tradition->name );
316 $dot .= "\tedge [ arrowhead=open ];\n";
317 $dot .= "\tgraph [ rankdir=LR ];\n";
318 $dot .= sprintf( "\tnode [ fontsize=%d, fillcolor=%s, style=%s, shape=%s ];\n",
319 11, "white", "filled", $self->graph->get_attribute( 'node', 'shape' ) );
321 foreach my $reading ( $self->readings ) {
322 # Need not output nodes without separate labels
323 next if $reading->name eq $reading->label;
324 $dot .= sprintf( "\t\"%s\" [ label=\"%s\" ];\n", $reading->name, $reading->label );
327 my @edges = $view eq 'relationship' ? $self->relationships : $self->paths;
328 foreach my $edge ( @edges ) {
329 my %variables = ( 'color' => '#000000',
330 'fontcolor' => '#000000',
331 'label' => $edge->label,
333 my $varopts = join( ', ', map { $_.'="'.$variables{$_}.'"' } sort keys %variables );
334 $dot .= sprintf( "\t\"%s\" -> \"%s\" [ %s ];\n",
335 $edge->from->name, $edge->to->name, $varopts );
343 print $graph->as_graphml( $recalculate )
345 Returns a GraphML representation of the collation graph, with
346 transposition information and position information. Unless
347 $recalculate is passed (and is a true value), the method will return a
348 cached copy of the SVG after the first call to the method.
353 my( $self, $recalc ) = @_;
354 return $self->graphml if $self->has_graphml;
357 my $graphml_ns = 'http://graphml.graphdrawing.org/xmlns';
358 my $xsi_ns = 'http://www.w3.org/2001/XMLSchema-instance';
359 my $graphml_schema = 'http://graphml.graphdrawing.org/xmlns ' .
360 'http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd';
362 # Create the document and root node
363 my $graphml = XML::LibXML->createDocument( "1.0", "UTF-8" );
364 my $root = $graphml->createElementNS( $graphml_ns, 'graphml' );
365 $graphml->setDocumentElement( $root );
366 $root->setNamespace( $xsi_ns, 'xsi', 0 );
367 $root->setAttributeNS( $xsi_ns, 'schemaLocation', $graphml_schema );
369 # TODO Add some global graph data
371 # Add the data keys for nodes
374 foreach my $datum ( qw/ name reading identical rank class / ) {
375 $node_data_keys{$datum} = 'dn'.$ndi++;
376 my $key = $root->addNewChild( $graphml_ns, 'key' );
377 $key->setAttribute( 'attr.name', $datum );
378 $key->setAttribute( 'attr.type', 'string' );
379 $key->setAttribute( 'for', 'node' );
380 $key->setAttribute( 'id', $node_data_keys{$datum} );
383 # Add the data keys for edges, i.e. witnesses
386 foreach my $edge_key( qw/ witness extra relationship class / ) {
387 $edge_data_keys{$edge_key} = 'de'.$edi++;
388 my $key = $root->addNewChild( $graphml_ns, 'key' );
389 $key->setAttribute( 'attr.name', $edge_key );
390 $key->setAttribute( 'attr.type', $edge_key eq 'extra' ? 'boolean' : 'string' );
391 $key->setAttribute( 'for', 'edge' );
392 $key->setAttribute( 'id', $edge_data_keys{$edge_key} );
395 # Add the graph, its nodes, and its edges
396 my $graph = $root->addNewChild( $graphml_ns, 'graph' );
397 $graph->setAttribute( 'edgedefault', 'directed' );
398 $graph->setAttribute( 'id', $self->tradition->name );
399 $graph->setAttribute( 'parse.edgeids', 'canonical' );
400 $graph->setAttribute( 'parse.edges', scalar($self->paths) );
401 $graph->setAttribute( 'parse.nodeids', 'canonical' );
402 $graph->setAttribute( 'parse.nodes', scalar($self->readings) );
403 $graph->setAttribute( 'parse.order', 'nodesfirst' );
407 # Add our readings to the graph
408 foreach my $n ( sort { $a->name cmp $b->name } $self->readings ) {
409 my $node_el = $graph->addNewChild( $graphml_ns, 'node' );
410 my $node_xmlid = 'n' . $node_ctr++;
411 $node_hash{ $n->name } = $node_xmlid;
412 $node_el->setAttribute( 'id', $node_xmlid );
413 _add_graphml_data( $node_el, $node_data_keys{'name'}, $n->name );
414 _add_graphml_data( $node_el, $node_data_keys{'reading'}, $n->label );
415 _add_graphml_data( $node_el, $node_data_keys{'rank'}, $n->rank )
417 _add_graphml_data( $node_el, $node_data_keys{'class'}, $n->sub_class );
418 _add_graphml_data( $node_el, $node_data_keys{'identical'}, $n->primary->name )
419 if $n->has_primary && $n->primary ne $n;
422 # Add the path and relationship edges
424 foreach my $e ( sort { $a->from->name cmp $b->from->name } $self->graph->edges() ) {
425 my( $name, $from, $to ) = ( 'e'.$edge_ctr++,
426 $node_hash{ $e->from->name() },
427 $node_hash{ $e->to->name() } );
428 my $edge_el = $graph->addNewChild( $graphml_ns, 'edge' );
429 $edge_el->setAttribute( 'source', $from );
430 $edge_el->setAttribute( 'target', $to );
431 $edge_el->setAttribute( 'id', $name );
433 _add_graphml_data( $edge_el, $edge_data_keys{'class'}, $e->sub_class );
435 # For some classes we have extra information to save.
436 if( $e->sub_class eq 'path' ) {
437 # It's a witness path, so add the witness
438 my $base = $e->label;
439 my $key = $edge_data_keys{'witness_main'};
440 # Is this an ante-corr witness?
441 my $aclabel = $self->ac_label;
442 if( $e->label =~ /^(.*)\Q$aclabel\E$/ ) {
443 # Keep the base witness
445 # ...and record that this is an 'extra' reading path
446 _add_graphml_data( $edge_el, $edge_data_keys{'extra'}, 'true' );
448 _add_graphml_data( $edge_el, $edge_data_keys{'witness'}, $base );
449 } elsif( $e->sub_class eq 'relationship' ) {
450 # It's a relationship, so save the relationship type
451 _add_graphml_data( $edge_el, $edge_data_keys{'relationship'}, $e->label );
455 # Save and return the thing
456 my $result = decode_utf8( $graphml->toString(1) );
457 $self->_save_graphml( $result );
461 sub _add_graphml_data {
462 my( $el, $key, $value ) = @_;
463 my $data_el = $el->addNewChild( $el->namespaceURI, 'data' );
464 return unless defined $value;
465 $data_el->setAttribute( 'key', $key );
466 $data_el->appendText( $value );
471 print $graph->as_csv( $recalculate )
473 Returns a CSV alignment table representation of the collation graph, one
474 row per witness (or witness uncorrected.) Unless $recalculate is passed
475 (and is a true value), the method will return a cached copy of the CSV
476 after the first call to the method.
481 my( $self, $recalc ) = @_;
482 return $self->csv if $self->has_csv;
483 my $table = $self->make_alignment_table;
484 my $csv = Text::CSV_XS->new( { binary => 1, quote_null => 0 } );
486 foreach my $row ( @$table ) {
487 $csv->combine( @$row );
488 push( @result, decode_utf8( $csv->string ) );
490 $self->_save_csv( join( "\n", @result ) );
494 # Make an alignment table - $noderefs controls whether the objects
495 # in the table are the nodes or simply their readings.
497 sub make_alignment_table {
498 my( $self, $noderefs ) = @_;
499 unless( $self->linear ) {
500 warn "Need a linear graph in order to make an alignment table";
504 my @all_pos = sort { $a <=> $b } $self->possible_positions;
505 foreach my $wit ( $self->tradition->witnesses ) {
506 # print STDERR "Making witness row(s) for " . $wit->sigil . "\n";
507 my @row = _make_witness_row( $wit->path, \@all_pos, $noderefs );
508 unshift( @row, $wit->sigil );
509 push( @$table, \@row );
510 if( $wit->has_ante_corr ) {
511 my @ac_row = _make_witness_row( $wit->uncorrected_path, \@all_pos, $noderefs );
512 unshift( @ac_row, $wit->sigil . $self->ac_label );
513 push( @$table, \@ac_row );
517 # Return a table where the witnesses read in columns rather than rows.
518 my $turned = _turn_table( $table );
522 sub _make_witness_row {
523 my( $path, $positions, $noderefs ) = @_;
525 map { $char_hash{$_} = undef } @$positions;
526 foreach my $rdg ( @$path ) {
527 my $rtext = $rdg->text;
528 $rtext = '#LACUNA#' if $rdg->is_lacuna;
529 $char_hash{$rdg->rank} = $noderefs ? $rdg : $rtext;
531 my @row = map { $char_hash{$_} } @$positions;
532 # Fill in lacuna markers for undef spots in the row
533 my $last_el = shift @row;
534 my @filled_row = ( $last_el );
535 foreach my $el ( @row ) {
536 # If we are using node reference, make the lacuna node appear many times
537 # in the table. If not, use the lacuna tag.
538 if( $last_el && _el_is_lacuna( $last_el ) && !defined $el ) {
539 $el = $noderefs ? $last_el : '#LACUNA#';
541 push( @filled_row, $el );
547 # Tiny utility function to say if a table element is a lacuna
550 return 1 if $el eq '#LACUNA#';
551 return 1 if ref( $el ) eq 'Text::Tradition::Collation::Reading'
556 # Helper to turn the witnesses along columns rather than rows. Assumes
561 return $result unless scalar @$table;
562 my $nrows = scalar @{$table->[0]};
563 foreach my $idx ( 0 .. $nrows - 1 ) {
564 foreach my $wit ( 0 .. $#{$table} ) {
565 $result->[$idx]->[$wit] = $table->[$wit]->[$idx];
572 sub collapse_graph_paths {
574 # Our collation graph has an path per witness. This is great for
575 # calculation purposes, but terrible for display. Thus we want to
576 # display only one path between any two nodes.
578 return if $self->collapsed;
580 print STDERR "Collapsing witness paths in graph...\n";
582 # Don't list out every witness if we have more than half to list.
583 my $majority = int( scalar( $self->tradition->witnesses ) / 2 ) + 1;
584 # But don't compress if there are only a few witnesses.
585 $majority = 4 if $majority < 4;
586 foreach my $node ( $self->readings ) {
588 # We will visit each node, so we only look ahead.
589 foreach my $edge ( $node->outgoing() ) {
590 next unless $edge->class eq 'edge.path';
591 add_hash_entry( $newlabels, $edge->to->name, $edge->name );
592 $self->del_path( $edge );
595 foreach my $newdest ( keys %$newlabels ) {
597 my @compressed_wits = @{$newlabels->{$newdest}};
598 if( @compressed_wits < $majority ) {
599 $label = join( ', ', sort( @{$newlabels->{$newdest}} ) );
601 ## TODO FIX THIS HACK
603 foreach my $wit ( @compressed_wits ) {
604 push( @aclabels, $wit ) if( $wit =~ /^(.*?)(\s*\(?a\.\s*c\.\)?)$/ );
606 $label = join( ', ', 'majority', sort( @aclabels ) );
609 my $newpath = $self->add_path( $node, $self->reading( $newdest ), $label );
610 $newpath->hidden_witnesses( \@compressed_wits );
614 $self->collapsed( 1 );
617 sub expand_graph_paths {
619 # Our collation graph has only one path between any two nodes.
620 # This is great for display, but not so great for analysis.
621 # Expand this so that each witness has its own path between any
623 return unless $self->collapsed;
625 print STDERR "Expanding witness paths in graph...\n";
626 foreach my $path( $self->paths ) {
627 my $from = $path->from;
629 warn sprintf( "No hidden witnesses on %s -> %s ?", $from->name, $to->name )
630 unless $path->has_hidden_witnesses;
631 my @wits = @{$path->hidden_witnesses};
632 $self->del_path( $path );
634 $self->add_path( $from, $to, $_ );
637 $self->collapsed( 0 );
642 =head2 Navigation methods
648 my $beginning = $collation->start();
650 Returns the beginning of the collation, a meta-reading with label '#START#'.
655 # Return the beginning reading of the graph.
656 my( $self, $new_start ) = @_;
657 my $start = $self->reading( '#START#' );
658 if( ref( $new_start ) eq 'Text::Tradition::Collation::Reading' ) {
659 # Replace the existing start node.
660 $self->del_reading( '#START#' );
661 $self->graph->rename_node( $new_start, '#START#' );
663 } elsif ( $new_start && $new_start eq 'INIT' ) {
664 # Make a new start node.
665 $start = $self->add_reading( '#START#' );
667 # Make sure the start node is a meta node
668 $start->is_meta( 1 );
669 # Make sure the start node has a start position.
670 unless( $start->has_rank ) {
678 my $end = $collation->end();
680 Returns the end of the collation, a meta-reading with label '#END#'.
687 my $end = $self->reading( '#END#' );
688 if( ref( $new_end ) eq 'Text::Tradition::Collation::Reading' ) {
689 $self->del_reading( '#END#' );
690 $self->graph->rename_node( $new_end, '#END#' );
692 } elsif ( $new_end && $new_end eq 'INIT' ) {
693 # Make a new start node.
694 $end = $self->add_reading( '#END#' );
696 # Make sure the start node is a meta node
701 =item B<reading_sequence>
703 my @readings = $graph->reading_sequence( $first, $last, $path[, $alt_path] );
705 Returns the ordered list of readings, starting with $first and ending
706 with $last, along the given witness path. If no path is specified,
707 assume that the path is that of the base text (if any.)
711 # TODO Think about returning some lazy-eval iterator.
713 sub reading_sequence {
714 my( $self, $start, $end, $witness, $backup ) = @_;
716 $witness = $self->baselabel unless $witness;
717 my @readings = ( $start );
720 while( $n && $n ne $end ) {
721 if( exists( $seen{$n->name()} ) ) {
722 warn "Detected loop at " . $n->name();
725 $seen{$n->name()} = 1;
727 my $next = $self->next_reading( $n, $witness, $backup );
728 warn "Did not find any path for $witness from reading " . $n->name
730 push( @readings, $next );
733 # Check that the last reading is our end reading.
734 my $last = $readings[$#readings];
735 warn "Last reading found from " . $start->label() .
736 " for witness $witness is not the end!"
737 unless $last eq $end;
742 =item B<next_reading>
744 my $next_reading = $graph->next_reading( $reading, $witpath );
746 Returns the reading that follows the given reading along the given witness
752 # Return the successor via the corresponding path.
754 return $self->_find_linked_reading( 'next', @_ );
757 =item B<prior_reading>
759 my $prior_reading = $graph->prior_reading( $reading, $witpath );
761 Returns the reading that precedes the given reading along the given witness
767 # Return the predecessor via the corresponding path.
769 return $self->_find_linked_reading( 'prior', @_ );
772 sub _find_linked_reading {
773 my( $self, $direction, $node, $path, $alt_path ) = @_;
774 my @linked_paths = $direction eq 'next'
775 ? $node->outgoing() : $node->incoming();
776 return undef unless scalar( @linked_paths );
778 # We have to find the linked path that contains all of the
779 # witnesses supplied in $path.
780 my( @path_wits, @alt_path_wits );
781 @path_wits = $self->witnesses_of_label( $path ) if $path;
782 @alt_path_wits = $self->witnesses_of_label( $alt_path ) if $alt_path;
785 foreach my $le ( @linked_paths ) {
786 if( $le->name eq $self->baselabel ) {
789 my @le_wits = $self->witnesses_of_label( $le->name );
790 if( _is_within( \@path_wits, \@le_wits ) ) {
791 # This is the right path.
792 return $direction eq 'next' ? $le->to() : $le->from();
793 } elsif( _is_within( \@alt_path_wits, \@le_wits ) ) {
798 # Got this far? Return the alternate path if it exists.
799 return $direction eq 'next' ? $alt_le->to() : $alt_le->from()
802 # Got this far? Return the base path if it exists.
803 return $direction eq 'next' ? $base_le->to() : $base_le->from()
806 # Got this far? We have no appropriate path.
807 warn "Could not find $direction node from " . $node->label
808 . " along path $path";
814 my( $set1, $set2 ) = @_;
815 my $ret = @$set1; # will be 0, i.e. false, if set1 is empty
816 foreach my $el ( @$set1 ) {
817 $ret = 0 unless grep { /^\Q$el\E$/ } @$set2;
823 ## INITIALIZATION METHODS - for use by parsers
824 # Walk the paths for each witness in the graph, and return the nodes
825 # that the graph has in common. If $using_base is true, some
826 # different logic is needed.
827 # NOTE This does not create paths; it merely finds common readings.
829 sub walk_witness_paths {
831 # For each witness, walk the path through the graph.
832 # Then we need to find the common nodes.
833 # TODO This method is going to fall down if we have a very gappy
834 # text in the collation.
837 foreach my $wit ( $self->tradition->witnesses ) {
838 my $curr_reading = $self->start;
839 my @wit_path = $self->reading_sequence( $self->start, $self->end,
841 $wit->path( \@wit_path );
843 # Detect the common readings.
844 @common_readings = _find_common( \@common_readings, \@wit_path );
847 # Mark all the nodes as either common or not.
848 foreach my $cn ( @common_readings ) {
849 print STDERR "Setting " . $cn->name . " / " . $cn->label
850 . " as common node\n";
853 foreach my $n ( $self->readings() ) {
854 $n->make_variant unless $n->is_common;
856 # Return an array of the common nodes in order.
857 return @common_readings;
861 my( $common_readings, $new_path ) = @_;
863 if( @$common_readings ) {
864 foreach my $n ( @$new_path ) {
865 push( @cr, $n ) if grep { $_ eq $n } @$common_readings;
868 push( @cr, @$new_path );
874 my( $common_readings, $divergence ) = @_;
877 map { $diverged{$_->name} = 1 } @$divergence;
878 foreach( @$common_readings ) {
879 push( @cr, $_ ) unless $diverged{$_->name};
885 # For use when a collation is constructed from a base text and an apparatus.
886 # We have the sequences of readings and just need to add path edges.
888 sub make_witness_paths {
890 foreach my $wit ( $self->tradition->witnesses ) {
891 print STDERR "Making path for " . $wit->sigil . "\n";
892 $self->make_witness_path( $wit );
896 sub make_witness_path {
897 my( $self, $wit ) = @_;
898 my @chain = @{$wit->path};
899 my $sig = $wit->sigil;
900 foreach my $idx ( 0 .. $#chain-1 ) {
901 $self->add_path( $chain[$idx], $chain[$idx+1], $sig );
903 if( $wit->has_ante_corr ) {
904 @chain = @{$wit->uncorrected_path};
905 foreach my $idx( 0 .. $#chain-1 ) {
906 my $source = $chain[$idx];
907 my $target = $chain[$idx+1];
908 $self->add_path( $source, $target, $sig.$self->ac_label )
909 unless $self->has_path( $source, $target, $sig );
914 sub calculate_ranks {
916 # Walk a version of the graph where every node linked by a relationship
917 # edge is fundamentally the same node, and do a topological ranking on
918 # the nodes in this graph.
919 my $topo_graph = Graph::Easy->new();
923 foreach my $r ( $self->readings ) {
924 next if exists $rel_containers{$r->name};
925 my @rels = $r->related_readings( 'colocated' );
927 # Make a relationship container.
929 my $rn = $topo_graph->add_node( 'rel_container_' . $rel_ctr++ );
931 $rel_containers{$_->name} = $rn;
934 # Add a new node to mirror the old node.
935 $rel_containers{$r->name} = $topo_graph->add_node( $r->name );
939 # Add the edges. Need only one edge between any pair of nodes.
940 foreach my $r ( $self->readings ) {
941 foreach my $n ( $r->neighbor_readings( 'forward' ) ) {
942 $topo_graph->add_edge_once( $rel_containers{$r->name},
943 $rel_containers{$n->name} );
947 # Now do the rankings, starting with the start node.
948 my $topo_start = $rel_containers{$self->start->name};
949 my $node_ranks = { $topo_start->name => 0 };
950 my @curr_origin = ( $topo_start );
951 # A little iterative function.
952 while( @curr_origin ) {
953 @curr_origin = _assign_rank( $node_ranks, @curr_origin );
955 # Transfer our rankings from the topological graph to the real one.
956 foreach my $r ( $self->readings ) {
957 $r->rank( $node_ranks->{$rel_containers{$r->name}->name} );
962 my( $node_ranks, @current_nodes ) = @_;
963 # Look at each of the children of @current_nodes. If all the child's
964 # parents have a rank, assign it the highest rank + 1 and add it to
965 # @next_nodes. Otherwise skip it.
967 foreach my $c ( @current_nodes ) {
968 warn "Current reading " . $c->name . "has no rank!"
969 unless exists $node_ranks->{$c->name};
970 # print STDERR "Looking at child of node " . $c->name . ", rank "
971 # . $node_ranks->{$c->name} . "\n";
972 my @children = map { $_->to } $c->outgoing;
973 foreach my $child ( @children ) {
974 next if exists $node_ranks->{$child->name};
975 my $highest_rank = -1;
977 my @parents = map { $_->from } $child->incoming;
978 foreach my $parent ( @parents ) {
979 if( exists $node_ranks->{$parent->name} ) {
980 $highest_rank = $node_ranks->{$parent->name}
981 if $highest_rank <= $node_ranks->{$parent->name};
988 # print STDERR "Assigning rank " . ( $highest_rank + 1 ) . " to node " . $child->name . "\n";
989 $node_ranks->{$child->name} = $highest_rank + 1;
990 push( @next_nodes, $child );
996 # Another method to make up for rough collation methods. If the same reading
997 # appears multiple times at the same rank, collapse the nodes.
1000 my %unique_rank_rdg;
1001 foreach my $rdg ( $self->readings ) {
1002 next unless $rdg->has_rank;
1003 my $key = $rdg->rank . "||" . $rdg->text;
1004 if( exists $unique_rank_rdg{$key} ) {
1006 print STDERR "Combining readings at same rank: $key\n";
1007 $self->merge_readings( $unique_rank_rdg{$key}, $rdg );
1009 $unique_rank_rdg{$key} = $rdg;
1015 sub possible_positions {
1018 map { $all_pos{ $_->rank } = 1 } $self->readings;
1019 return keys %all_pos;
1022 # TODO think about indexing this.
1023 sub readings_at_position {
1024 my( $self, $position, $strict ) = @_;
1026 foreach my $r ( $self->readings ) {
1027 push( @answer, $r ) if $r->is_at_position( $position, $strict );
1032 ## Lemmatizer functions
1037 foreach my $position ( $self->possible_positions ) {
1038 $self->lemmata->{$position} = undef;
1041 foreach my $cr ( $self->common_readings ) {
1042 $self->lemmata->{$cr->position->maxref} = $cr->name;
1046 sub common_readings {
1048 my @common = grep { $_->is_common } $self->readings();
1049 return sort { $a->rank <=> $b->rank } @common;
1052 =item B<lemma_readings>
1054 my @state = $graph->lemma_readings( @readings_delemmatized );
1056 Takes a list of readings that have just been delemmatized, and returns
1057 a set of tuples of the form ['reading', 'state'] that indicates what
1058 changes need to be made to the graph.
1064 A state of 1 means 'lemmatize this reading'
1068 A state of 0 means 'delemmatize this reading'
1072 A state of undef means 'an ellipsis belongs in the text here because
1073 no decision has been made / an earlier decision was backed out'
1079 sub lemma_readings {
1080 my( $self, @toggled_off_nodes ) = @_;
1082 # First get the positions of those nodes which have been
1084 my $positions_off = {};
1085 map { $positions_off->{ $_->position->reference } = $_->name }
1088 # Now for each position, we have to see if a node is on, and we
1089 # have to see if a node has been turned off. The lemmata hash
1090 # should contain fixed positions, range positions whose node was
1091 # just turned off, and range positions whose node is on.
1093 my %fixed_positions;
1094 # TODO One of these is probably redundant.
1095 map { $fixed_positions{$_} = 0 } keys %{$self->lemmata};
1096 map { $fixed_positions{$_} = 0 } keys %{$positions_off};
1097 map { $fixed_positions{$_} = 1 } $self->possible_positions;
1098 foreach my $pos ( sort { Text::Tradition::Collation::Position::str_cmp( $a, $b ) } keys %fixed_positions ) {
1099 # Find the state of this position. If there is an active node,
1100 # its name will be the state; otherwise the state will be 0
1101 # (nothing at this position) or undef (ellipsis at this position)
1103 $active = $self->lemmata->{$pos} if exists $self->lemmata->{$pos};
1105 # Is there a formerly active node that was toggled off?
1106 if( exists( $positions_off->{$pos} ) ) {
1107 my $off_node = $positions_off->{$pos};
1108 if( $active && $active ne $off_node) {
1109 push( @answer, [ $off_node, 0 ], [ $active, 1 ] );
1111 unless( $fixed_positions{$pos} ) {
1113 delete $self->lemmata->{$pos};
1115 push( @answer, [ $off_node, $active ] );
1118 # No formerly active node, so we just see if there is a currently
1120 } elsif( $active ) {
1121 # Push the active node, whatever it is.
1122 push( @answer, [ $active, 1 ] );
1124 # Push the state that is there. Arbitrarily use the first node
1126 my @pos_nodes = $self->readings_at_position( $pos );
1127 push( @answer, [ $pos_nodes[0]->name, $self->lemmata->{$pos} ] );
1128 delete $self->lemmata->{$pos} unless $fixed_positions{$pos};
1135 =item B<toggle_reading>
1137 my @readings_delemmatized = $graph->toggle_reading( $reading_name );
1139 Takes a reading node name, and either lemmatizes or de-lemmatizes
1140 it. Returns a list of all readings that are de-lemmatized as a result
1145 sub toggle_reading {
1146 my( $self, $rname ) = @_;
1148 return unless $rname;
1149 my $reading = $self->reading( $rname );
1150 if( !$reading || $reading->is_common() ) {
1151 # Do nothing, it's a common node.
1155 my $pos = $reading->position;
1156 my $fixed = $reading->position->fixed;
1157 my $old_state = $self->lemmata->{$pos->reference};
1160 if( $old_state && $old_state eq $rname ) {
1161 # Turn off the node. We turn on no others by default.
1162 push( @readings_off, $reading );
1165 $self->lemmata->{$pos->reference} = $rname;
1166 # Any other 'on' readings in the same position should be off
1167 # if we have a fixed position.
1168 push( @readings_off, $self->same_position_as( $reading, 1 ) )
1170 # Any node that is an identical transposed one should be off.
1171 push( @readings_off, $reading->identical_readings );
1173 @readings_off = unique_list( @readings_off );
1175 # Turn off the readings that need to be turned off.
1176 my @readings_delemmatized;
1177 foreach my $n ( @readings_off ) {
1178 my $npos = $n->position;
1180 $state = $self->lemmata->{$npos->reference}
1181 if defined $self->lemmata->{$npos->reference};
1182 if( $state && $state eq $n->name ) {
1183 # this reading is still on, so turn it off
1184 push( @readings_delemmatized, $n );
1185 my $new_state = undef;
1186 if( $npos->fixed && $n eq $reading ) {
1187 # This is the reading that was clicked, so if there are no
1188 # other readings there and this is a fixed position, turn off
1189 # the position. In all other cases, restore the ellipsis.
1190 my @other_n = $self->same_position_as( $n ); # TODO do we need strict?
1191 $new_state = 0 unless @other_n;
1193 $self->lemmata->{$npos->reference} = $new_state;
1194 } elsif( $old_state && $old_state eq $n->name ) {
1195 # another reading has already been turned on here
1196 push( @readings_delemmatized, $n );
1197 } # else some other reading was on anyway, so pass.
1199 return @readings_delemmatized;
1202 sub same_position_as {
1203 my( $self, $reading, $strict ) = @_;
1204 my $pos = $reading->position;
1205 my %onpath = ( $reading->name => 1 );
1206 # TODO This might not always be sufficient. We really want to
1207 # exclude all readings on this one's path between its two
1209 map { $onpath{$_->name} = 1 } $reading->neighbor_readings;
1210 my @same = grep { !$onpath{$_->name} }
1211 $self->readings_at_position( $reading->position, $strict );
1215 # Return the string that joins together a list of witnesses for
1216 # display on a single path.
1219 return join( $self->wit_list_separator, @_ );
1222 sub witnesses_of_label {
1223 my( $self, $label ) = @_;
1224 my $regex = $self->wit_list_separator;
1225 my @answer = split( /\Q$regex\E/, $label );
1232 map { $h{$_->name} = $_ } @list;
1233 return values( %h );
1236 sub add_hash_entry {
1237 my( $hash, $key, $entry ) = @_;
1238 if( exists $hash->{$key} ) {
1239 push( @{$hash->{$key}}, $entry );
1241 $hash->{$key} = [ $entry ];
1246 __PACKAGE__->meta->make_immutable;