first crack at implementing relationships
[scpubgit/stemmatology.git] / lib / Text / Tradition / Collation.pm
index ea194ef..8489ddf 100644 (file)
@@ -3,6 +3,7 @@ package Text::Tradition::Collation;
 use Graph::Easy;
 use IPC::Run qw( run binary );
 use Text::Tradition::Collation::Reading;
+use Text::Tradition::Collation::Path;
 use Moose;
 
 has 'graph' => (
@@ -69,9 +70,15 @@ has 'baselabel' => (
     );
 
 has 'collapsed' => (
-                   is => 'rw',
-                   isa => 'Bool',
-                   );
+    is => 'rw',
+    isa => 'Bool',
+    );
+
+has 'linear' => (
+    is => 'rw',
+    isa => 'Bool',
+    default => 1,
+    );
 
 
 # The collation can be created two ways:
@@ -92,6 +99,7 @@ has 'collapsed' => (
 sub BUILD {
     my( $self, $args ) = @_;
     $self->graph->use_class('node', 'Text::Tradition::Collation::Reading');
+    $self->graph->use_class('edge', 'Text::Tradition::Collation::Path');
 
     # Pass through any graph-specific options.
     my $shape = exists( $args->{'shape'} ) ? $args->{'shape'} : 'ellipse';
@@ -124,6 +132,15 @@ around add_path => sub {
     $self->$orig( @_ );
 };
 
+# Wrapper around paths
+around paths => sub {
+    my $orig = shift;
+    my $self = shift;
+
+    my @result = grep { $_->class eq 'path' } $self->$orig( @_ );
+    return @result;
+};
+
 # Wrapper around merge_nodes
 
 sub merge_readings {
@@ -135,6 +152,50 @@ sub merge_readings {
     return $self->graph->merge_nodes( @_ );
 }
 
+# Extra graph-alike utility
+sub has_path {
+    my( $self, $source, $target, $label ) = @_;
+    my @paths = $source->edges_to( $target );
+    my @relevant = grep { $_->label eq $label } @paths;
+    return scalar @paths;
+}
+
+## Dealing with relationships between readings.  This is a different
+## sort of graph edge.
+
+sub add_relationship {
+    my( $self, $type, $source, $target, $global ) = @_;
+    my $rel = Text::Tradition::Collation::Relationship->new(
+           'sort' => $type,
+           'global' => $global,
+           'orig_relation' => [ $source, $target ],
+    );
+    print STDERR sprintf( "Setting relationship %s between readings %s (%s)"
+                         . " and %s (%s)\n", $type, 
+                         $source->label, $source->name,
+                         $target->label, $target->name );
+    $self->graph->add_edge( $source, $target, $rel );
+    if( $global ) {
+       # Look for all readings with the source label, and if there are
+       # colocated readings with the target label, join them too.
+       foreach my $r ( $self->readings() ) {
+           next unless $r->label eq $source->label;
+           my @colocated = grep { $_->label eq $target->label }
+               $self->same_position_as( $r );
+           if( @colocated ) {
+               warn "Multiple readings with same label at same position!"
+                   if @colocated > 1;
+               my $dup_rel = Text::Tradition::Collation::Relationship->new(
+                   'sort' => $type,
+                   'global' => $global,
+                   'orig_relation' => [ $source, $target ],
+                   );
+               $self->graph->add_edge( $r, $colocated[0], $dup_rel );
+           }
+       }
+    }
+}
+
 =head2 Output method(s)
 
 =over
@@ -154,7 +215,7 @@ sub as_svg {
     my( $self, $recalc ) = @_;
     return $self->svg if $self->has_svg;
     
-    $self->collapse_graph_edges();
+    $self->collapse_graph_paths();
     $self->_save_graphviz( $self->graph->as_graphviz() )
        unless( $self->has_graphviz && !$recalc );
     
@@ -163,7 +224,7 @@ sub as_svg {
     my $in = $self->graphviz;
     run( \@cmd, \$in, ">", binary(), \$svg );
     $self->{'svg'} = $svg;
-    $self->expand_graph_edges();
+    $self->expand_graph_paths();
     return $svg;
 }
 
@@ -272,24 +333,24 @@ sub as_graphml {
     return $graphml;
 }
 
-sub collapse_graph_edges {
+sub collapse_graph_paths {
     my $self = shift;
-    # Our collation graph has an edge per witness.  This is great for
+    # Our collation graph has an path per witness.  This is great for
     # calculation purposes, but terrible for display.  Thus we want to
-    # display only one edge between any two nodes.
+    # display only one path between any two nodes.
 
     return if $self->collapsed;
 
-    print STDERR "Collapsing path edges in graph...\n";
+    print STDERR "Collapsing witness paths in graph...\n";
 
     # Don't list out every witness if we have more than half to list.
     my $majority = int( scalar( @{$self->tradition->witnesses} ) / 2 ) + 1;
     foreach my $node( $self->readings ) {
        my $newlabels = {};
        # We will visit each node, so we only look ahead.
-       foreach my $edge ( $node->outgoing() ) {
-           add_hash_entry( $newlabels, $edge->to->name, $edge->name );
-           $self->del_path( $edge );
+       foreach my $path ( $node->outgoing() ) {
+           add_hash_entry( $newlabels, $path->to->name, $path->name );
+           $self->del_path( $path );
        }
 
        foreach my $newdest ( keys %$newlabels ) {
@@ -299,23 +360,21 @@ sub collapse_graph_edges {
                $label = join( ', ', @{$newlabels->{$newdest}} );
            } else {
                ## TODO FIX THIS HACK
-               my @pclabels;
+               my @aclabels;
                foreach my $wit ( @{$newlabels->{$newdest}} ) {
-                   if( $wit =~ /^(.*?)(\s*\(?p\.\s*c\.\)?)$/ ) {
-                       push( @pclabels, $wit );
+                   if( $wit =~ /^(.*?)(\s*\(?a\.\s*c\.\)?)$/ ) {
+                       push( @aclabels, $wit );
                    } else {
                        push( @compressed_wits, $wit );
                    }
                }
-               $label = join( ', ', 'majority', @pclabels );
+               $label = join( ', ', 'majority', @aclabels );
            }
            
-           my $newedge = 
+           my $newpath = 
                $self->add_path( $node, $self->reading( $newdest ), $label );
            if( @compressed_wits ) {
-               ## TODO fix this hack too.
-               $newedge->set_attribute( 'class', 
-                                        join( '|', @compressed_wits ) );
+               $newpath->hidden_witnesses( \@compressed_wits );
            }
        }
     }
@@ -323,24 +382,24 @@ sub collapse_graph_edges {
     $self->collapsed( 1 );
 }
 
-sub expand_graph_edges {
+sub expand_graph_paths {
     my $self = shift;
-    # Our collation graph has only one edge between any two nodes.
+    # Our collation graph has only one path between any two nodes.
     # This is great for display, but not so great for analysis.
-    # Expand this so that each witness has its own edge between any
+    # Expand this so that each witness has its own path between any
     # two reading nodes.
     return unless $self->collapsed;
     
-    print STDERR "Expanding path edges in graph...\n";
-
-    foreach my $edge( $self->paths ) {
-       my $from = $edge->from;
-       my $to = $edge->to;
-       my @wits = split( /, /, $edge->label );
-       if( grep { $_ eq 'majority' } @wits ) {
-           push( @wits, split( /\|/, $edge->get_attribute( 'class' ) ) );
+    print STDERR "Expanding witness paths in graph...\n";
+    $DB::single = 1;
+    foreach my $path( $self->paths ) {
+       my $from = $path->from;
+       my $to = $path->to;
+       my @wits = split( /, /, $path->label );
+       if( $path->has_hidden_witnesses ) {
+           push( @wits, @{$path->hidden_witnesses} );
        }
-       $self->del_path( $edge );
+       $self->del_path( $path );
        foreach ( @wits ) {
            $self->add_path( $from, $to, $_ );
        }
@@ -555,83 +614,35 @@ sub _remove_common {
 
 
 # An alternative to walk_witness_paths, for use when a collation is
-# constructed from a base text and an apparatus.  Also modifies the
-# collation graph to remove all 'base text' paths and replace them
-# with real witness paths.
+# constructed from a base text and an apparatus.  We have the
+# sequences of readings and just need to add path edges.
 
-sub walk_and_expand_base {
-    my( $self, $end ) = @_;
+sub make_witness_paths {
+    my( $self ) = @_;
 
     my @common_readings;
     foreach my $wit ( @{$self->tradition->witnesses} ) {
-       my $sig = $wit->sigil;
-       $DB::single = 1 if $sig eq 'Vb5';
-       my $post_sig;
-       $post_sig = $wit->post_correctione 
-           if $wit->has_post_correctione;
-       
-       my @wit_path = $self->reading_sequence( $self->start, $end, $sig );
-       $wit->path( \@wit_path );
-       $self->connect_readings_for_witness( $wit );
-       @common_readings = _find_common( \@common_readings, \@wit_path );
-
-       # If there is a post-correctio, get its path and compare.
-       # Add a correction range for each divergence.
-       if( $post_sig ) {
-           my @corr_wit_path = $self->reading_sequence( $self->start, $end, 
-                                                        "$sig$post_sig", $sig );
-
-           # Map ante-corr readings to their indices
-           my %in_orig; 
-           my $i = 0;
-           map { $in_orig{$_->name} = $i++ } @wit_path;
-
-           # Look for divergences
-           my $diverged = 0;
-           my $last_common;
-           my @correction;
-           foreach my $rdg ( @corr_wit_path ) {
-               if( exists( $in_orig{$rdg->name} ) && !$diverged ) {
-                   # We are reading the same here
-                   $last_common = $in_orig{$rdg->name};
-               } elsif ( exists( $in_orig{$rdg->name} ) ) {
-                   # We have been diverging but are reading the same again.
-                   # Add the correction to the witness.
-                   my $offset = $last_common + 1;
-                   my $length = $in_orig{$rdg->name} - $offset;
-                   $wit->add_correction( $offset, $length, @correction );
-                   $diverged = 0;
-                   @common_readings = _remove_common( \@common_readings, \@correction );
-                   @correction = ();
-                   $last_common = $in_orig{$rdg->name};
-               } elsif( $diverged ) {
-                   # We are in the middle of a divergence.
-                   push( @correction, $rdg );
-               } else {
-                   # We have started to diverge.  Note it.
-                   $diverged = 1;
-                   push( @correction, $rdg );
-               }
-           }
-           # Add any divergence that is at the end of the text
-           if( $diverged ) {
-               $wit->add_correction( $last_common+1, $#wit_path, \@correction );
-           }
-       }
-    }
-
-    # Remove any 'base text' paths.
-    foreach my $path ( $self->paths ) {
-       $self->del_path( $path ) 
-           if $path->label eq $self->baselabel;
+       print STDERR "Making path for " . $wit->sigil . "\n";
+       $self->make_witness_path( $wit );
+       @common_readings = _find_common( \@common_readings, $wit->path );
+       @common_readings = _find_common( \@common_readings, $wit->uncorrected_path );
     }
+    return @common_readings;
 }
 
-sub connect_readings_for_witness {
+sub make_witness_path {
     my( $self, $wit ) = @_;
     my @chain = @{$wit->path};
+    my $sig = $wit->sigil;
     foreach my $idx ( 0 .. $#chain-1 ) {
-       $self->add_path( $chain[$idx], $chain[$idx+1], $wit->sigil );
+       $self->add_path( $chain[$idx], $chain[$idx+1], $sig );
+    }
+    @chain = @{$wit->uncorrected_path};
+    foreach my $idx( 0 .. $#chain-1 ) {
+       my $source = $chain[$idx];
+       my $target = $chain[$idx+1];
+       $self->add_path( $source, $target, "$sig (a.c.)" )
+           unless $self->has_path( $source, $target, $sig );
     }
 }
 
@@ -656,8 +667,8 @@ sub calculate_positions {
     foreach my $wit ( @{$self->tradition->witnesses} ) {
        print STDERR "Calculating positions in " . $wit->sigil . "\n";
        _update_positions_from_path( $wit->path, @ordered_common );
-       _update_positions_from_path( $wit->corrected_path, @ordered_common )
-           if $wit->has_post_correctione;
+       _update_positions_from_path( $wit->uncorrected_path, @ordered_common )
+           if $wit->has_ante_corr;
     }
     
     # DEBUG
@@ -676,7 +687,6 @@ sub _update_positions_from_path {
     # that corresponds to its eventual position identifier.  Common
     # nodes always start a new row, and are thus always in the first
     # column.
-    
     my $wit_matrix = [];
     my $cn = 0;  # We should hit the common readings in order.
     my $row = [];
@@ -703,6 +713,7 @@ sub _update_positions_from_path {
        foreach my $di ( 1..scalar(@{$wit_matrix->[$li-1]}) ) {
            my $reading = $wit_matrix->[$li-1]->[$di-1];
            my $position = "$li,$di";
+
            # If we have seen this node before, we need to compare
            # its position with what went before.
            unless( $reading->has_position &&