From: Tara L Andrews Date: Mon, 13 Feb 2012 22:26:04 +0000 (+0100) Subject: refactored Analysis module with associated changes X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=commitdiff_plain;h=7f52eac8cd00b160ea9e828790cbd093dc444feb;p=scpubgit%2Fstemmatology.git refactored Analysis module with associated changes --- diff --git a/lib/Text/Tradition.pm b/lib/Text/Tradition.pm index 8bed34d..a5c5a41 100644 --- a/lib/Text/Tradition.pm +++ b/lib/Text/Tradition.pm @@ -38,7 +38,7 @@ has 'stemmata' => ( traits => ['Array'], isa => 'ArrayRef[Text::Tradition::Stemma]', handles => { - all_stemmata => 'elements', + stemmata => 'elements', _add_stemma => 'push', stemma => 'get', stemma_count => 'count', diff --git a/lib/Text/Tradition/Analysis.pm b/lib/Text/Tradition/Analysis.pm index 910f994..2de129c 100644 --- a/lib/Text/Tradition/Analysis.pm +++ b/lib/Text/Tradition/Analysis.pm @@ -10,146 +10,209 @@ use Text::Tradition::Stemma; use vars qw/ @EXPORT_OK /; @EXPORT_OK = qw/ run_analysis group_variants analyze_variant_location wit_stringify /; +=head1 NAME + +Text::Tradition::Analysis - functions for stemma analysis of a tradition + +=head1 SYNOPSIS + + use Text::Tradition; + use Text::Tradition::Analysis qw/ run_analysis analyze_variant_location /; + my $t = Text::Tradition->new( + 'name' => 'this is a text', + 'input' => 'TEI', + 'file' => '/path/to/tei_parallel_seg_file.xml' ); + $t->add_stemma( 'dotfile' => $stemmafile ); + + my $variant_data = run_analysis( $tradition ); + # Recalculate rank $n treating all orthographic variants as equivalent + my $reanalyze = analyze_variant_location( $tradition, $n, 0, 'orthographic' ); + +=head1 DESCRIPTION + +Text::Tradition is a library for representation and analysis of collated +texts, particularly medieval ones. The Collation is the central feature of +a Tradition, where the text, its sequence of readings, and its relationships +between readings are actually kept. + +=head1 SUBROUTINES + +=head2 run_analysis( $tradition, $stemma_id, @merge_relationship_types ) + +Runs the analysis described in analyze_variant_location on every location +in the collation of the given tradition, against the stemma specified in +$stemma_id. If $stemma_id is not specified, it defaults to 0 (referencing +the first stemma saved for the tradition.) + +The optional @merge_relationship_types contains a list of relationship types +to treat as equivalent for the analysis. + +=begin testing + +use Text::Tradition; +use Text::Tradition::Analysis qw/ run_analysis analyze_variant_location /; + +my $datafile = 't/data/florilegium_tei_ps.xml'; +my $tradition = Text::Tradition->new( 'input' => 'TEI', + 'name' => 'test0', + 'file' => $datafile ); +my $s = $tradition->add_stemma( 'dotfile' => 't/data/florilegium.dot' ); +is( ref( $s ), 'Text::Tradition::Stemma', "Added stemma to tradition" ); + +my $data = run_analysis( $tradition ); +# TODO should be 21! +is( $data->{'genealogical_count'}, 42, "Got right genealogical count" ); +is( $data->{'conflict_count'}, 17, "Got right conflict count" ); +is( $data->{'variant_count'}, 58, "Got right total variant number" ); + +=end testing + +=cut + sub run_analysis { - my( $tradition ) = @_; - # What we will return - my $variants = []; - my $data = {}; + my( $tradition, $stemma_id, @collapse ) = @_; + $stemma_id = 0 unless $stemma_id; - # We need a stemma in order to run this... - unless( $tradition->stemma_count ) { - warn "Tradition '" . $tradition->name . "' has no stemma to analyze"; - return undef; - } - my $stemma = $tradition->stemma(0); # TODO allow multiple - - # We have the collation, so get the alignment table with witnesses in rows. - # Also return the reading objects in the table, rather than just the words. - my $wits = {}; - map { $wits->{$_} = 1 } $stemma->witnesses; - # For each column in the alignment table, we want to see if the existing - # groupings of witnesses match our stemma hypothesis. We also need to keep - # track of the maximum number of variants at any one location. - my $max_variants = 0; - my ( $genealogical, $conflicts ) = ( 0, 0, 0 ); + # Run the variant analysis on every rank in the graph that doesn't + # have a common reading. Return the results. + my @variants; # holds results from analyze_variant_location + my $genealogical; # counter of 'genealogical' variants + my $conflicts; # counter of conflicting readings - my $variant_groups = group_variants( $tradition->collation, $wits ); - foreach my $rank ( 0 .. $#{$variant_groups} ) { - my $groups = $variant_groups->[$rank]->{'groups'}; - my $readings = $variant_groups->[$rank]->{'readings'}; - my $lacunose = $variant_groups->[$rank]->{'lacunose'}; - - $max_variants = scalar @$groups if scalar @$groups > $max_variants; - - # We can already look up witnesses for a reading; we also want to look - # up readings for a given witness. - my $group_readings = {}; - foreach my $x ( 0 .. $#$groups ) { - $group_readings->{wit_stringify( $groups->[$x] )} = $readings->[$x]; - } - - # For all the groups with more than one member, collect the list of all - # contiguous vertices needed to connect them. - my $variant_loc = analyze_variant_location( $group_readings, $groups, - $stemma->graph, $lacunose ); - $variant_loc->{'id'} = $rank; - $genealogical++ if $variant_loc->{'genealogical'}; - $conflicts += grep { $_->{'conflict'} } @{$variant_loc->{'readings'}}; - - # Now run the same analysis given the calculated distance tree(s). -# my @trees = @{$stemma->distance_trees}; -# if( @trees ) { -# foreach my $tree ( 0 .. $#trees ) { -# my $dc = analyze_variant_location( $group_readings, $groups, $tree, $lacunose, 'undirected' ); -# foreach my $rdg ( keys %$dc ) { -# my $var = $dc->{$rdg}; -# # TODO Do something with this -# } -# } -# } - - # Record that we used this variant in an analysis - push( @$variants, $variant_loc ); + # Find and mark 'common' ranks for exclusion. + my %common_rank; + foreach my $rdg ( $tradition->collation->common_readings ) { + $common_rank{$rdg->rank} = 1; } - - # Go through our variant locations, after we have seen all of them once, - # and add the number of empty columns needed by each. - foreach my $row ( @$variants ) { - my $empty = $max_variants - scalar @{$row->{'readings'}}; - $row->{'empty'} = $empty; + + foreach my $rank ( 1 .. $tradition->collation->end->rank-1 ) { + next if $common_rank{$rank}; + my $variant_row = analyze_variant_location( + $tradition, $rank, $stemma_id, @collapse ); + push( @variants, $variant_row ); + $genealogical++ if $variant_row->{'genealogical'}; + $conflicts += grep { $_->{'conflict'} } @{$variant_row->{'readings'}}; } - $data->{'variants'} = $variants; - $data->{'variant_count'} = $tradition->collation->end->rank - 1; - $data->{'conflict_count'} = $conflicts; - $data->{'genealogical_count'} = $genealogical; - return $data; + return { + 'variants' => \@variants, + 'variant_count' => scalar @variants, # TODO redundant + 'conflict_count' => $conflicts, + 'genealogical_count' => $genealogical, + }; } +=head2 group_variants( $tradition, $rank, $lacunose, @merge_relationship_types ) + +Groups the variants at the given $rank of the collation, treating any +relationships in @merge_relationship_types as equivalent. $lacunose should +be a reference to an array, to which the sigla of lacunose witnesses at this +rank will be appended. + +Returns two ordered lists $readings, $groups, where $readings->[$n] is attested +by the witnesses listed in $groups->[$n]. + +=cut + +# Return group_readings, groups, lacunose sub group_variants { - my( $c, $wits ) = @_; - my $variant_groups = []; + my( $tradition, $rank, $lacunose, $collapse ) = @_; + my $c = $tradition->collation; + # Get the alignment table readings + my %readings_at_rank; + my @gap_wits; + foreach my $tablewit ( @{$tradition->collation->alignment_table->{'alignment'}} ) { + my $rdg = $tablewit->{'tokens'}->[$rank-1]; + if( $rdg && $rdg->{'t'}->is_lacuna ) { + push( @$lacunose, $tablewit->{'witness'} ); + } elsif( $rdg ) { + $readings_at_rank{$rdg->{'t'}->text} = $rdg->{'t'}; + } else { + push( @gap_wits, $tablewit->{'witness'} ); + } + } - # We have the collation, so get the alignment table with witnesses in rows. - # Also return the reading objects in the table, rather than just the words. - my $all_wits_table = $c->make_alignment_table( 'refs', $wits ); - # Strip the list of sigla and save it for correlation to the readings. - my @table_wits = map { $_->{'witness'} } @{$all_wits_table->{'alignment'}}; - # Any witness in the stemma that has no row should be noted. - foreach ( @table_wits ) { - $wits->{$_}++; # Witnesses present in table and stemma now have value 2. - } - my @not_collated = grep { $wits->{$_} == 1 } keys %$wits; - foreach my $i ( 0 .. $all_wits_table->{'length'} - 1 ) { - # For each column in the table, group the readings by witness. - my $rdg_wits = {}; - my @col_rdgs = map { $_->{tokens}->[$i] } @{$all_wits_table->{'alignment'}}; - my $lacunose = [ @not_collated ]; - foreach my $j ( 0 .. $#col_rdgs ) { - my $rdg = $col_rdgs[$j]; - my $rdg_text = '(omitted)'; # Initialize in case of empty reading - if( $rdg ) { - if( $rdg->{'t'}->is_lacuna ) { - $rdg_text = undef; # Don't count lacunae - push( @$lacunose, $table_wits[$j] ); - } else { - $rdg_text = $rdg->{'t'}->text; - } - } - if( defined $rdg_text ) { - # Initialize the witness array if we haven't got one yet - $rdg_wits->{$rdg_text} = [] unless $rdg_wits->{$rdg_text}; - # Add the relevant witness, subject to a.c. logic - add_variant_wit( $rdg_wits->{$rdg_text}, $table_wits[$j], - $c->ac_label ); + # Group the readings, collapsing groups by relationship if needed + my %grouped_readings; + foreach my $rdg ( sort { $b->witnesses <=> $a->witnesses } values %readings_at_rank ) { + # Skip readings that have been collapsed into others. + next if exists $grouped_readings{$rdg->text} && !$grouped_readings{$rdg->text}; + my @wits = $rdg->witnesses; + if( $collapse ) { + my $filter = sub { my $r = $_[0]; grep { $_ eq $r->type } @$collapse; }; + foreach my $other ( $rdg->related_readings( $filter ) ) { + push( @wits, $other->witnesses ); + $grouped_readings{$other->text} = 0; } } - - # See if this column has any potentially genealogical variants. - # If not, skip to the next. - my( $groups, $readings ) = useful_variant( $rdg_wits ); - next unless $groups && $readings; - - push( @$variant_groups, - { 'groups' => $groups, 'readings' => $readings, 'lacunose' => $lacunose } ); + $grouped_readings{$rdg->text} = \@wits; + } + $grouped_readings{'(omitted)'} = \@gap_wits if @gap_wits; + # Get rid of our collapsed readings + map { delete $grouped_readings{$_} unless $grouped_readings{$_} } + keys %grouped_readings + if $collapse; + + # Return the readings and groups, sorted by size + my( @readings, @groups ); + foreach my $r ( sort { @{$grouped_readings{$b}} <=> @{$grouped_readings{$a}} } + keys %grouped_readings ) { + push( @readings, $r ); + push( @groups, $grouped_readings{$r} ); } - return $variant_groups; + return( \@readings, \@groups ); } +=head2 analyze_variant_location( $tradition, $rank, $stemma_id, @merge_relationship_types ) +Runs an analysis of the given tradition, at the location given in $rank, +against the graph of the stemma specified in $stemma_id. The argument +@merge_relationship_types is an optional list of relationship types for +which readings so related should be treated as equivalent. -# variant_row -> genealogical -# -> readings [ { text, group, conflict, missing } ] +Returns a data structure as follows: + + { 'id' => $rank, + 'genealogical' => boolean, + 'readings => [ { text => $reading_text, + group => [ witnesses ], + conflict => [ conflicting ], + missing => [ excluded ] }, ... ] + } +where 'conflicting' is the list of witnesses whose readings conflict with +this group, and 'excluded' is the list of witnesses either not present in +the stemma or lacunose at this location. + +=cut sub analyze_variant_location { - my( $group_readings, $groups, $graph, $lacunose, $undirected ) = @_; + my( $tradition, $rank, $sid, @collapse ) = @_; + $DB::single = 1 if @collapse; + # Get the readings in this tradition at this rank + my @rank_rdgs = grep { $_->rank == $rank } $tradition->collation->readings; + # Get the applicable stemma + my $undirected; # TODO Allow undirected distance tree analysis too + my $stemma = $tradition->stemma( $sid ); + my $graph = $stemma->graph; + # Figure out which witnesses we are working with + my @lacunose = _set( 'symmdiff', [ $stemma->witnesses ], + [ map { $_->sigil } $tradition->witnesses ] ); + + # Now group the readings + my( $readings, $groups ) = + group_variants( $tradition, $rank, \@lacunose, \@collapse ); + my $group_readings = {}; + # Lookup table group string -> readings + foreach my $x ( 0 .. $#$groups ) { + $group_readings->{wit_stringify( $groups->[$x] )} = $readings->[$x]; + } + + # Now do the work. my $contig = {}; my $subgraph = {}; my $is_conflicted; my $conflict = {}; - my $missing = {}; - map { $missing->{$_} = 1 } @$lacunose; - my $variant_row = { 'readings' => [] }; + my $variant_row = { 'id' => $rank, 'readings' => [] }; # Mark each ms as in its own group, first. foreach my $g ( @$groups ) { my $gst = wit_stringify( $g ); @@ -190,7 +253,7 @@ sub analyze_variant_location { my $nodes_in_subtree = 0; foreach my $root ( @roots ) { # Prune the tree to get rid of extraneous hypotheticals. - $root = prune_subtree( $part, $root, $contig ); + $root = _prune_subtree( $part, $root, $contig ); # Get all the successor nodes of our root. my $tmp_reach = { $root => 1 }; map { $tmp_reach->{$_} = 1 } $part->all_successors( $root ); @@ -232,7 +295,7 @@ sub analyze_variant_location { # Write the reading. my $reading = { 'text' => $group_readings->{$gst}, - 'missing' => wit_stringify( $lacunose ), + 'missing' => wit_stringify( \@lacunose ), 'group' => $gst }; # This will change if we find no conflict if( $is_conflicted ) { $reading->{'conflict'} = $conflict->{$group_readings->{$gst}} @@ -307,10 +370,12 @@ sub analyze_variant_location { } # Now write the group and conflict information into the respective rows. + my %missing; + map { $missing{$_} = 1 } @lacunose; # quick lookup table foreach my $rdg ( @{$variant_row->{'readings'}} ) { $rdg->{'conflict'} = $conflict->{$rdg->{'text'}}; next if $rdg->{'conflict'}; - my @members = grep { $contig->{$_} eq $rdg->{'group'} && !$missing->{$_} } + my @members = grep { $contig->{$_} eq $rdg->{'group'} && !$missing{$_} } keys %$contig; $rdg->{'group'} = wit_stringify( \@members ); } @@ -319,7 +384,7 @@ sub analyze_variant_location { return $variant_row; } -sub prune_subtree { +sub _prune_subtree { my( $tree, $root, $contighash ) = @_; # First, delete hypothetical leaves / orphans until there are none left. my @orphan_hypotheticals = grep { ref( $contighash->{$_} ) } @@ -351,25 +416,12 @@ sub add_variant_wit { push( @$arr, $wit ) unless $skip; } -# Return an answer if the variant is useful, i.e. if there are at least 2 variants -# with at least 2 witnesses each. -sub useful_variant { - my( $readings ) = @_; - my $total = keys %$readings; - foreach my $var ( keys %$readings ) { - $total-- if @{$readings->{$var}} == 1; - } - return( undef, undef ) if $total <= 1; - my( $groups, $text ); - foreach my $var ( keys %$readings ) { - push( @$groups, $readings->{$var} ); - push( @$text, $var ); - } - return( $groups, $text ); -} +=head2 wit_stringify( $groups ) + +Takes an array of witness groupings and produces a string like +['A','B'] / ['C','D','E'] / ['F'] -# Take an array of witness groupings and produce a string like -# ['A','B'] / ['C','D','E'] / ['F'] +=cut sub wit_stringify { my $groups = shift; @@ -385,5 +437,32 @@ sub wit_stringify { } return join( ' / ', @gst ); } - -1; \ No newline at end of file + +sub _set { + my( $op, $lista, $listb ) = @_; + my %union; + my %scalars; + map { $union{$_} = 1; $scalars{$_} = $_ } @$lista; + map { $union{$_} += 1; $scalars{$_} = $_ } @$listb; + my @set; + if( $op eq 'intersection' ) { + @set = grep { $union{$_} == 2 } keys %union; + } elsif( $op eq 'symmdiff' ) { + @set = grep { $union{$_} == 1 } keys %union; + } elsif( $op eq 'union' ) { + @set = keys %union; + } + return map { $scalars{$_} } @set; +} + +1; + +=head1 LICENSE + +This package is free software and is provided "as is" without express +or implied warranty. You can redistribute it and/or modify it under +the same terms as Perl itself. + +=head1 AUTHOR + +Tara L Andrews Eaurum@cpan.orgE diff --git a/lib/Text/Tradition/Collation.pm b/lib/Text/Tradition/Collation.pm index 2b5dbeb..081a134 100644 --- a/lib/Text/Tradition/Collation.pm +++ b/lib/Text/Tradition/Collation.pm @@ -95,6 +95,13 @@ has 'cached_svg' => ( predicate => 'has_cached_svg', clearer => 'wipe_svg', ); + +has 'cached_table' => ( + is => 'rw', + isa => 'HashRef', + predicate => 'has_cached_table', + clearer => 'wipe_table', + ); =head1 NAME @@ -246,6 +253,12 @@ sub BUILD { ### Reading construct/destruct functions +sub _clear_cache { + my $self = shift; + $self->wipe_svg if $self->has_cached_svg; + $self->wipe_table if $self->has_cached_table; +} + sub add_reading { my( $self, $reading ) = @_; unless( ref( $reading ) eq 'Text::Tradition::Collation::Reading' ) { @@ -258,6 +271,7 @@ sub add_reading { if( $self->reading( $reading->id ) ) { throw( "Collation already has a reading with id " . $reading->id ); } + $self->_clear_cache; $self->_add_reading( $reading->id => $reading ); # Once the reading has been added, put it in both graphs. $self->sequence->add_vertex( $reading->id ); @@ -274,6 +288,7 @@ around del_reading => sub { $arg = $arg->id; } # Remove the reading from the graphs. + $self->_clear_cache; $self->sequence->delete_vertex( $arg ); $self->relations->delete_reading( $arg ); @@ -289,6 +304,7 @@ sub merge_readings { # We only need the IDs for adding paths to the graph, not the reading # objects themselves. my( $kept, $deleted, $combine_char ) = $self->_stringify_args( @_ ); + $self->_clear_cache; # The kept reading should inherit the paths and the relationships # of the deleted reading. @@ -344,6 +360,7 @@ sub add_path { # objects themselves. my( $source, $target, $wit ) = $self->_stringify_args( @_ ); + $self->_clear_cache; # Connect the readings $self->sequence->add_edge( $source, $target ); # Note the witness in question @@ -364,6 +381,7 @@ sub del_path { # objects themselves. my( $source, $target, $wit ) = $self->_stringify_args( @args ); + $self->_clear_cache; if( $self->sequence->has_edge_attribute( $source, $target, $wit ) ) { $self->sequence->delete_edge_attribute( $source, $target, $wit ); } @@ -392,6 +410,7 @@ be called via $tradition->del_witness. sub clear_witness { my( $self, @sigils ) = @_; + $self->_clear_cache; # Clear the witness(es) out of the paths foreach my $e ( $self->paths ) { foreach my $sig ( @sigils ) { @@ -414,6 +433,7 @@ sub add_relationship { $self->reading( $source ), $target, $self->reading( $target ), $opts ); # Force a full rank recalculation every time. Yuck. $self->calculate_ranks() if $self->end->has_rank; + $self->_clear_cache; return @vectors; } @@ -688,7 +708,16 @@ sub _path_display_label { return join( ', ', @wits ); } } - + +=head2 witnesses_at_rank + +Returns a list of witnesses that are not lacunose, for a given rank. + +=cut + +sub witnesses_at_rank { + my( $self, $rank ) = @_; +} =head2 as_graphml @@ -893,7 +922,7 @@ row per witness (or witness uncorrected.) sub as_csv { my( $self ) = @_; - my $table = $self->make_alignment_table; + my $table = $self->alignment_table; my $csv = Text::CSV_XS->new( { binary => 1, quote_null => 0 } ); my @result; # Make the header row @@ -902,14 +931,14 @@ sub as_csv { # Make the rest of the rows foreach my $idx ( 0 .. $table->{'length'} - 1 ) { my @rowobjs = map { $_->{'tokens'}->[$idx] } @{$table->{'alignment'}}; - my @row = map { $_ ? $_->{'t'} : $_ } @rowobjs; + my @row = map { $_ ? $_->{'t'}->text : $_ } @rowobjs; $csv->combine( @row ); push( @result, decode_utf8( $csv->string ) ); } return join( "\n", @result ); } -=head2 make_alignment_table( $use_refs, $include_witnesses ) +=head2 alignment_table( $use_refs, $include_witnesses ) Return a reference to an alignment table, in a slightly enhanced CollateX format which looks like this: @@ -929,8 +958,12 @@ keys have a true hash value will be included. =cut -sub make_alignment_table { - my( $self, $noderefs, $include ) = @_; +sub alignment_table { + my( $self ) = @_; + my $include; # see if we can ditch this + ## DEBUG + return $self->cached_table if $self->has_cached_table; + # Make sure we can do this throw( "Need a linear graph in order to make an alignment table" ) unless $self->linear; @@ -944,22 +977,23 @@ sub make_alignment_table { } # print STDERR "Making witness row(s) for " . $wit->sigil . "\n"; my @wit_path = $self->reading_sequence( $self->start, $self->end, $wit->sigil ); - my @row = _make_witness_row( \@wit_path, \@all_pos, $noderefs ); + my @row = _make_witness_row( \@wit_path, \@all_pos ); push( @{$table->{'alignment'}}, { 'witness' => $wit->sigil, 'tokens' => \@row } ); if( $wit->is_layered ) { my @wit_ac_path = $self->reading_sequence( $self->start, $self->end, $wit->sigil.$self->ac_label ); - my @ac_row = _make_witness_row( \@wit_ac_path, \@all_pos, $noderefs ); + my @ac_row = _make_witness_row( \@wit_ac_path, \@all_pos ); push( @{$table->{'alignment'}}, { 'witness' => $wit->sigil.$self->ac_label, 'tokens' => \@ac_row } ); } } - return $table; + $self->cached_table( $table ); + return $table; } sub _make_witness_row { - my( $path, $positions, $noderefs ) = @_; + my( $path, $positions ) = @_; my %char_hash; map { $char_hash{$_} = undef } @$positions; my $debug = 0; @@ -968,8 +1002,7 @@ sub _make_witness_row { $rtext = '#LACUNA#' if $rdg->is_lacuna; print STDERR "rank " . $rdg->rank . "\n" if $debug; # print STDERR "No rank for " . $rdg->id . "\n" unless defined $rdg->rank; - $char_hash{$rdg->rank} = $noderefs ? { 't' => $rdg } - : { 't' => $rtext }; + $char_hash{$rdg->rank} = { 't' => $rdg }; } my @row = map { $char_hash{$_} } @$positions; # Fill in lacuna markers for undef spots in the row @@ -978,8 +1011,8 @@ sub _make_witness_row { foreach my $el ( @row ) { # If we are using node reference, make the lacuna node appear many times # in the table. If not, use the lacuna tag. - if( $last_el && _el_is_lacuna( $last_el ) && !defined $el ) { - $el = $noderefs ? $last_el : { 't' => '#LACUNA#' }; + if( $last_el && $last_el->{'t'}->is_lacuna && !defined $el ) { + $el = $last_el; } push( @filled_row, $el ); $last_el = $el; @@ -987,30 +1020,6 @@ sub _make_witness_row { return @filled_row; } -# Tiny utility function to say if a table element is a lacuna -sub _el_is_lacuna { - my $el = shift; - return 1 if $el->{'t'} eq '#LACUNA#'; - return 1 if ref( $el->{'t'} ) eq 'Text::Tradition::Collation::Reading' - && $el->{'t'}->is_lacuna; - return 0; -} - -# Helper to turn the witnesses along columns rather than rows. Assumes -# equal-sized rows. -sub _turn_table { - my( $table ) = @_; - my $result = []; - return $result unless scalar @$table; - my $nrows = scalar @{$table->[0]}; - foreach my $idx ( 0 .. $nrows - 1 ) { - foreach my $wit ( 0 .. $#{$table} ) { - $result->[$idx]->[$wit] = $table->[$wit]->[$idx]; - } - } - return $result; -} - =head1 NAVIGATION METHODS =head2 reading_sequence( $first, $last, $sigil, $backup ) @@ -1464,9 +1473,11 @@ is_deeply( \@marked, \@expected, "Found correct list of common readings" ); sub calculate_common_readings { my $self = shift; my @common; - my $table = $self->make_alignment_table( 1 ); + my $table = $self->alignment_table; foreach my $idx ( 0 .. $table->{'length'} - 1 ) { - my @row = map { $_->{'tokens'}->[$idx]->{'t'} } @{$table->{'alignment'}}; + my @row = map { $_->{'tokens'}->[$idx] + ? $_->{'tokens'}->[$idx]->{'t'} : '' } + @{$table->{'alignment'}}; my %hash; foreach my $r ( @row ) { if( $r ) { diff --git a/lib/Text/Tradition/Collation/Reading.pm b/lib/Text/Tradition/Collation/Reading.pm index 80f737c..d1c69f7 100644 --- a/lib/Text/Tradition/Collation/Reading.pm +++ b/lib/Text/Tradition/Collation/Reading.pm @@ -173,6 +173,17 @@ sub related_readings { return $self->collation->related_readings( $self, @_ ); } +=head2 witnesses + +Calls Collation's reading_witnesses with $self as the first argument. + +=cut + +sub witnesses { + my $self = shift; + return $self->collation->reading_witnesses( $self, @_ ); +} + =head2 predecessors Returns a list of Reading objects that immediately precede $self in the collation. diff --git a/lib/Text/Tradition/Collation/RelationshipStore.pm b/lib/Text/Tradition/Collation/RelationshipStore.pm index 334b5fe..133c09a 100644 --- a/lib/Text/Tradition/Collation/RelationshipStore.pm +++ b/lib/Text/Tradition/Collation/RelationshipStore.pm @@ -369,23 +369,27 @@ sub relationship_valid { } } -=head2 related_readings( $reading, $colocated_only ) +=head2 related_readings( $reading, $filter ) Returns a list of readings that are connected via relationship links to $reading. -If $colocated_only is true, restricts the list to those readings that are in the -same logical location (and therefore have the same rank in the collation graph.) +If $filter is set to a subroutine ref, returns only those related readings where +$filter( $relationship ) returns a true value. =cut sub related_readings { - my( $self, $reading, $colocated ) = @_; + my( $self, $reading, $filter ) = @_; my $return_object; if( ref( $reading ) eq 'Text::Tradition::Collation::Reading' ) { $reading = $reading->id; $return_object = 1; } my @answer; - if( $colocated ) { + if( $filter ) { + # Backwards compat + if( $filter eq 'colocated' ) { + $filter = sub { $_[0]->colocated }; + } my %found = ( $reading => 1 ); my $check = [ $reading ]; my $iter = 0; @@ -393,7 +397,7 @@ sub related_readings { my $more = []; foreach my $r ( @$check ) { foreach my $nr ( $self->graph->neighbors( $r ) ) { - if( $self->get_relationship( $r, $nr )->colocated ) { + if( &$filter( $self->get_relationship( $r, $nr ) ) ) { push( @$more, $nr ) unless exists $found{$nr}; $found{$nr} = 1; } @@ -401,6 +405,7 @@ sub related_readings { } $check = $more; } + delete $found{$reading}; @answer = keys %found; } else { @answer = $self->graph->all_reachable( $reading ); diff --git a/script/save_to_db.pl b/script/save_to_db.pl index 3b85d09..69e4fca 100755 --- a/script/save_to_db.pl +++ b/script/save_to_db.pl @@ -80,8 +80,7 @@ if( $list ) { print STDERR "...collation has " . scalar( $c->readings ) . " readings\n"; print STDERR "...collation has " . scalar( $c->paths ) . " paths\n"; print STDERR "...collation has " . scalar( $c->relationships ) . " relationship links\n"; - my $s = $t->stemma; - if( $s ) { + foreach my $s ( $t->stemmata ) { print STDERR "...associated stemma has graph " . $s->graph . "\n"; } } diff --git a/stemmaweb/lib/stemmaweb/Controller/Root.pm b/stemmaweb/lib/stemmaweb/Controller/Root.pm index 23971b6..cd6cb76 100644 --- a/stemmaweb/lib/stemmaweb/Controller/Root.pm +++ b/stemmaweb/lib/stemmaweb/Controller/Root.pm @@ -90,7 +90,7 @@ sub alignment :Local :Args(1) { my( $self, $c, $textid ) = @_; my $m = $c->model('Directory'); my $collation = $m->tradition( $textid )->collation; - my $alignment = $collation->make_alignment_table; + my $alignment = $collation->alignment_table; # Turn the table, so that witnesses are by column and the rows # are by rank. diff --git a/t/data/florilegium.dot b/t/data/florilegium.dot new file mode 100644 index 0000000..9419d10 --- /dev/null +++ b/t/data/florilegium.dot @@ -0,0 +1,44 @@ +digraph Stemma { + "α" [ class=hypothetical ]; + "γ" [ class=hypothetical ]; + "δ" [ class=hypothetical ]; + 2 [ class=hypothetical,label="*" ]; + 3 [ class=hypothetical,label="*" ]; + 4 [ class=hypothetical,label="*" ]; + 5 [ class=hypothetical,label="*" ]; + 7 [ class=hypothetical,label="*" ]; + A [ class=extant ]; + B [ class=extant ]; + C [ class=extant ]; + D [ class=extant ]; + E [ class=extant ]; + F [ class=extant ]; + G [ class=extant ]; + H [ class=extant ]; + K [ class=extant ]; + P [ class=extant ]; + Q [ class=extant ]; + S [ class=extant ]; + T [ class=extant ]; + "α" -> A; + "α" -> T; + "α" -> "δ"; + "δ" -> 2; + 2 -> C; + 2 -> B; + B -> P; + B -> S; + "δ" -> "γ"; + "γ" -> 3; + 3 -> F; + 3 -> H; + "γ" -> 4; + 4 -> D; + 4 -> 5; + 5 -> Q; + 5 -> K; + 5 -> 7; + 7 -> E; + 7 -> G; +} + \ No newline at end of file diff --git a/t/stemma.t b/t/stemma.t index 45f1f3f..697d0d2 100644 --- a/t/stemma.t +++ b/t/stemma.t @@ -30,7 +30,7 @@ ok( $stemma->isa( 'Text::Tradition::Stemma' ), 'Got the right sort of object' ); is( $stemma->graph, '1-2,1-A,2-B,2-C', "Got the correct graph" ); # Test for character matrix creation -my $mstr = character_input( $c->make_alignment_table() ); +my $mstr = character_input( $c->alignment_table() ); ## check number of rows my @mlines = split( "\n", $mstr ); my $msig = shift @mlines; diff --git a/t/text_tradition_analysis.t b/t/text_tradition_analysis.t new file mode 100644 index 0000000..080ad5e --- /dev/null +++ b/t/text_tradition_analysis.t @@ -0,0 +1,31 @@ +#!/usr/bin/perl -w + +use strict; +use Test::More 'no_plan'; +$| = 1; + + + +# =begin testing +{ +use Text::Tradition; +use Text::Tradition::Analysis qw/ run_analysis analyze_variant_location /; + +my $datafile = 't/data/florilegium_tei_ps.xml'; +my $tradition = Text::Tradition->new( 'input' => 'TEI', + 'name' => 'test0', + 'file' => $datafile ); +my $s = $tradition->add_stemma( 'dotfile' => 't/data/florilegium.dot' ); +is( ref( $s ), 'Text::Tradition::Stemma', "Added stemma to tradition" ); + +my $data = run_analysis( $tradition ); +# TODO should be 21! +is( $data->{'genealogical_count'}, 42, "Got right genealogical count" ); +is( $data->{'conflict_count'}, 17, "Got right conflict count" ); +is( $data->{'variant_count'}, 58, "Got right total variant number" ); +} + + + + +1;