add support for alignment table input
[scpubgit/stemmatology.git] / lib / Text / Tradition / Collation.pm
CommitLineData
dd3b58b0 1package Text::Tradition::Collation;
d047cd52 2
910a0a6d 3use Encode qw( decode_utf8 );
4use File::Temp;
d047cd52 5use Graph::Easy;
8e1394aa 6use IPC::Run qw( run binary );
910a0a6d 7use Text::CSV_XS;
3265b0ce 8use Text::Tradition::Collation::Path;
b15511bf 9use Text::Tradition::Collation::Reading;
10use Text::Tradition::Collation::Relationship;
11use Text::Tradition::Collation::Segment;
df6d9812 12use XML::LibXML;
dd3b58b0 13use Moose;
14
15has 'graph' => (
d047cd52 16 is => 'ro',
17 isa => 'Graph::Easy',
18 handles => {
910a0a6d 19 add_reading => 'add_node',
20 del_reading => 'del_node',
21 del_segment => 'del_node',
22 add_path => 'add_edge',
23 del_path => 'del_edge',
24 reading => 'node',
25 path => 'edge',
26 readings => 'nodes',
27 segments => 'nodes',
28 paths => 'edges',
29 relationships => 'edges',
d047cd52 30 },
31 default => sub { Graph::Easy->new( undirected => 0 ) },
32 );
910a0a6d 33
dd3b58b0 34
f6066bac 35has 'tradition' => ( # TODO should this not be ro?
8e1394aa 36 is => 'rw',
d047cd52 37 isa => 'Text::Tradition',
38 );
dd3b58b0 39
8e1394aa 40has 'svg' => (
41 is => 'ro',
42 isa => 'Str',
43 writer => '_save_svg',
44 predicate => 'has_svg',
45 );
46
8e1394aa 47has 'graphml' => (
48 is => 'ro',
df6d9812 49 isa => 'Str',
8e1394aa 50 writer => '_save_graphml',
51 predicate => 'has_graphml',
52 );
53
910a0a6d 54has 'csv' => (
55 is => 'ro',
56 isa => 'Str',
57 writer => '_save_csv',
58 predicate => 'has_csv',
59 );
60
3a1f2523 61# Keeps track of the lemmas within the collation. At most one lemma
62# per position in the graph.
63has 'lemmata' => (
64 is => 'ro',
65 isa => 'HashRef[Maybe[Str]]',
66 default => sub { {} },
67 );
68
4a8828f0 69has 'wit_list_separator' => (
7854e12e 70 is => 'rw',
71 isa => 'Str',
72 default => ', ',
73 );
74
75has 'baselabel' => (
76 is => 'rw',
77 isa => 'Str',
78 default => 'base text',
79 );
4a8828f0 80
1f563ac3 81has 'collapsed' => (
15d2d3df 82 is => 'rw',
83 isa => 'Bool',
84 );
85
86has 'linear' => (
87 is => 'rw',
88 isa => 'Bool',
89 default => 1,
90 );
1f563ac3 91
ef9d481f 92has 'ac_label' => (
93 is => 'rw',
94 isa => 'Str',
95 default => ' (a.c.)',
96 );
97
1f563ac3 98
dd3b58b0 99# The collation can be created two ways:
100# 1. Collate a set of witnesses (with CollateX I guess) and process
101# the results as in 2.
102# 2. Read a pre-prepared collation in one of a variety of formats,
103# and make the graph from that.
104
105# The graph itself will (for now) be immutable, and the positions
106# within the graph will also be immutable. We need to calculate those
107# positions upon graph construction. The equivalences between graph
108# nodes will be mutable, entirely determined by the user (or possibly
109# by some semantic pre-processing provided by the user.) So the
110# constructor should just make an empty equivalences object. The
111# constructor will also need to make the witness objects, if we didn't
112# come through option 1.
113
d047cd52 114sub BUILD {
115 my( $self, $args ) = @_;
8e1394aa 116 $self->graph->use_class('node', 'Text::Tradition::Collation::Reading');
3265b0ce 117 $self->graph->use_class('edge', 'Text::Tradition::Collation::Path');
d047cd52 118
4a8828f0 119 # Pass through any graph-specific options.
120 my $shape = exists( $args->{'shape'} ) ? $args->{'shape'} : 'ellipse';
121 $self->graph->set_attribute( 'node', 'shape', $shape );
d047cd52 122}
784877d9 123
7854e12e 124# Wrapper around add_path
125
126around add_path => sub {
127 my $orig = shift;
128 my $self = shift;
129
130 # Make sure there are three arguments
131 unless( @_ == 3 ) {
910a0a6d 132 warn "Call add_path with args source, target, witness";
133 return;
7854e12e 134 }
135 # Make sure the proposed path does not yet exist
b15511bf 136 # NOTE 'reading' will currently return readings and segments
7854e12e 137 my( $source, $target, $wit ) = @_;
138 $source = $self->reading( $source )
910a0a6d 139 unless ref( $source ) eq 'Text::Tradition::Collation::Reading';
7854e12e 140 $target = $self->reading( $target )
910a0a6d 141 unless ref( $target ) eq 'Text::Tradition::Collation::Reading';
7854e12e 142 foreach my $path ( $source->edges_to( $target ) ) {
910a0a6d 143 if( $path->label eq $wit && $path->class eq 'edge.path' ) {
144 return;
145 }
7854e12e 146 }
147 # Do the deed
148 $self->$orig( @_ );
149};
150
3265b0ce 151# Wrapper around paths
152around paths => sub {
153 my $orig = shift;
154 my $self = shift;
155
b15511bf 156 my @result = grep { $_->sub_class eq 'path' } $self->$orig( @_ );
df6d9812 157 return @result;
158};
159
160around relationships => sub {
161 my $orig = shift;
162 my $self = shift;
b15511bf 163 my @result = grep { $_->sub_class eq 'relationship' } $self->$orig( @_ );
164 return @result;
165};
166
167around readings => sub {
168 my $orig = shift;
169 my $self = shift;
170 my @result = grep { $_->sub_class ne 'segment' } $self->$orig( @_ );
171 return @result;
172};
173
174around segments => sub {
175 my $orig = shift;
176 my $self = shift;
177 my @result = grep { $_->sub_class eq 'segment' } $self->$orig( @_ );
3265b0ce 178 return @result;
179};
180
7854e12e 181# Wrapper around merge_nodes
784877d9 182
183sub merge_readings {
184 my $self = shift;
185 my $first_node = shift;
186 my $second_node = shift;
187 $first_node->merge_from( $second_node );
188 unshift( @_, $first_node, $second_node );
189 return $self->graph->merge_nodes( @_ );
190}
191
15d2d3df 192# Extra graph-alike utility
193sub has_path {
194 my( $self, $source, $target, $label ) = @_;
195 my @paths = $source->edges_to( $target );
196 my @relevant = grep { $_->label eq $label } @paths;
b15511bf 197 return scalar @relevant;
198}
199
200## Dealing with groups of readings, i.e. segments.
201
202sub add_segment {
203 my( $self, @items ) = @_;
204 my $segment = Text::Tradition::Collation::Segment->new( 'members' => \@items );
205 return $segment;
15d2d3df 206}
207
3265b0ce 208## Dealing with relationships between readings. This is a different
4cdd82f1 209## sort of graph edge. Return a success/failure value and a list of
210## node pairs that have been linked.
3265b0ce 211
212sub add_relationship {
b15511bf 213 my( $self, $source, $target, $options ) = @_;
ef9d481f 214
215 # Make sure there is not another relationship between these two
b15511bf 216 # readings or segments already
ef9d481f 217 $source = $self->reading( $source )
910a0a6d 218 unless ref( $source ) && $source->isa( 'Graph::Easy::Node' );
ef9d481f 219 $target = $self->reading( $target )
910a0a6d 220 unless ref( $target ) && $target->isa( 'Graph::Easy::Node' );
4cdd82f1 221 foreach my $rel ( $source->edges_to( $target ), $target->edges_to( $source ) ) {
910a0a6d 222 if( $rel->class eq 'edge.relationship' ) {
223 return ( undef, "Relationship already exists between these readings" );
224 }
4cdd82f1 225 }
910a0a6d 226 if( $options->{'equal_rank'} && !relationship_valid( $source, $target ) ) {
227 return ( undef, 'Relationship creates witness loop' );
ef9d481f 228 }
229
910a0a6d 230 # TODO Think about positional hilarity if relationships are added after positions
231 # are assigned.
232
4cdd82f1 233 my @joined = ( [ $source->name, $target->name ] ); # Keep track of the nodes we join.
234
235 $options->{'this_relation'} = [ $source, $target ];
f6066bac 236 my $rel;
237 eval { $rel = Text::Tradition::Collation::Relationship->new( %$options ) };
238 if( $@ ) {
239 return ( undef, $@ );
240 }
3265b0ce 241 $self->graph->add_edge( $source, $target, $rel );
910a0a6d 242
243 # TODO Handle global relationship setting
244
4cdd82f1 245 return( 1, @joined );
3265b0ce 246}
247
910a0a6d 248sub relationship_valid {
249 my( $source, $target ) = @_;
250 # Check that linking the source and target in a relationship won't lead
251 # to a path loop for any witness.
252 my @proposed_related = ( $source, $target );
253 push( @proposed_related, $source->related_readings );
254 push( @proposed_related, $target->related_readings );
255 my %pr_ids;
256 map { $pr_ids{ $_->name } = 1 } @proposed_related;
257 # The lists of 'in' and 'out' should not have any element that appears
258 # in 'proposed_related'.
259 foreach my $pr ( @proposed_related ) {
260 foreach my $e ( $pr->incoming ) {
261 if( exists $pr_ids{ $e->from->name } ) {
262 return 0;
263 }
264 }
265 foreach my $e ( $pr->outgoing ) {
266 if( exists $pr_ids{ $e->to->name } ) {
267 return 0;
268 }
269 }
270 }
271 return 1;
272}
273
8e1394aa 274=head2 Output method(s)
275
276=over
277
278=item B<as_svg>
279
280print $graph->as_svg( $recalculate );
281
282Returns an SVG string that represents the graph. Uses GraphViz to do
4a8828f0 283this, because Graph::Easy doesn\'t cope well with long graphs. Unless
8e1394aa 284$recalculate is passed (and is a true value), the method will return a
285cached copy of the SVG after the first call to the method.
286
287=cut
288
289sub as_svg {
290 my( $self, $recalc ) = @_;
291 return $self->svg if $self->has_svg;
292
3265b0ce 293 $self->collapse_graph_paths();
8e1394aa 294
295 my @cmd = qw/dot -Tsvg/;
296 my( $svg, $err );
910a0a6d 297 my $dotfile = File::Temp->new();
d9e873d0 298 ## TODO REMOVE
299 $dotfile->unlink_on_destroy(0);
910a0a6d 300 binmode $dotfile, ':utf8';
301 print $dotfile $self->as_dot();
302 push( @cmd, $dotfile->filename );
303 run( \@cmd, ">", binary(), \$svg );
304 $svg = decode_utf8( $svg );
df6d9812 305 $self->_save_svg( $svg );
3265b0ce 306 $self->expand_graph_paths();
8e1394aa 307 return $svg;
308}
309
df6d9812 310=item B<as_dot>
311
312print $graph->as_dot( $view, $recalculate );
313
314Returns a string that is the collation graph expressed in dot
315(i.e. GraphViz) format. The 'view' argument determines what kind of
316graph is produced.
317 * 'path': a graph of witness paths through the collation (DEFAULT)
318 * 'relationship': a graph of how collation readings relate to
319 each other
320
321=cut
322
323sub as_dot {
324 my( $self, $view ) = @_;
325 $view = 'path' unless $view;
326 # TODO consider making some of these things configurable
327 my $dot = sprintf( "digraph %s {\n", $self->tradition->name );
328 $dot .= "\tedge [ arrowhead=open ];\n";
329 $dot .= "\tgraph [ rankdir=LR ];\n";
330 $dot .= sprintf( "\tnode [ fontsize=%d, fillcolor=%s, style=%s, shape=%s ];\n",
910a0a6d 331 11, "white", "filled", $self->graph->get_attribute( 'node', 'shape' ) );
df6d9812 332
333 foreach my $reading ( $self->readings ) {
910a0a6d 334 # Need not output nodes without separate labels
335 next if $reading->name eq $reading->label;
336 # TODO output readings or segments, but not both
337 next if $reading->class eq 'node.segment';
338 $dot .= sprintf( "\t\"%s\" [ label=\"%s\" ];\n", $reading->name, $reading->label );
df6d9812 339 }
340
341 my @edges = $view eq 'relationship' ? $self->relationships : $self->paths;
342 foreach my $edge ( @edges ) {
910a0a6d 343 my %variables = ( 'color' => '#000000',
344 'fontcolor' => '#000000',
345 'label' => $edge->label,
346 );
347 my $varopts = join( ', ', map { $_.'="'.$variables{$_}.'"' } sort keys %variables );
348 $dot .= sprintf( "\t\"%s\" -> \"%s\" [ %s ];\n",
349 $edge->from->name, $edge->to->name, $varopts );
df6d9812 350 }
df6d9812 351 $dot .= "}\n";
352 return $dot;
353}
354
8e1394aa 355=item B<as_graphml>
356
357print $graph->as_graphml( $recalculate )
358
359Returns a GraphML representation of the collation graph, with
360transposition information and position information. Unless
361$recalculate is passed (and is a true value), the method will return a
362cached copy of the SVG after the first call to the method.
363
364=cut
365
366sub as_graphml {
367 my( $self, $recalc ) = @_;
368 return $self->graphml if $self->has_graphml;
369
370 # Some namespaces
371 my $graphml_ns = 'http://graphml.graphdrawing.org/xmlns';
372 my $xsi_ns = 'http://www.w3.org/2001/XMLSchema-instance';
373 my $graphml_schema = 'http://graphml.graphdrawing.org/xmlns ' .
910a0a6d 374 'http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd';
8e1394aa 375
376 # Create the document and root node
377 my $graphml = XML::LibXML->createDocument( "1.0", "UTF-8" );
378 my $root = $graphml->createElementNS( $graphml_ns, 'graphml' );
379 $graphml->setDocumentElement( $root );
380 $root->setNamespace( $xsi_ns, 'xsi', 0 );
381 $root->setAttributeNS( $xsi_ns, 'schemaLocation', $graphml_schema );
382
f6066bac 383 # TODO Add some global graph data
384
8e1394aa 385 # Add the data keys for nodes
ef9d481f 386 my %node_data_keys;
387 my $ndi = 0;
d9e873d0 388 foreach my $datum ( qw/ name reading identical rank class / ) {
910a0a6d 389 $node_data_keys{$datum} = 'dn'.$ndi++;
390 my $key = $root->addNewChild( $graphml_ns, 'key' );
391 $key->setAttribute( 'attr.name', $datum );
392 $key->setAttribute( 'attr.type', 'string' );
393 $key->setAttribute( 'for', 'node' );
394 $key->setAttribute( 'id', $node_data_keys{$datum} );
8e1394aa 395 }
396
df6d9812 397 # Add the data keys for edges, i.e. witnesses
ef9d481f 398 my $edi = 0;
399 my %edge_data_keys;
b15511bf 400 foreach my $edge_key( qw/ witness_main witness_ante_corr relationship class / ) {
910a0a6d 401 $edge_data_keys{$edge_key} = 'de'.$edi++;
402 my $key = $root->addNewChild( $graphml_ns, 'key' );
403 $key->setAttribute( 'attr.name', $edge_key );
404 $key->setAttribute( 'attr.type', 'string' );
405 $key->setAttribute( 'for', 'edge' );
406 $key->setAttribute( 'id', $edge_data_keys{$edge_key} );
8e1394aa 407 }
ef9d481f 408
8e1394aa 409 # Add the graph, its nodes, and its edges
410 my $graph = $root->addNewChild( $graphml_ns, 'graph' );
411 $graph->setAttribute( 'edgedefault', 'directed' );
412 $graph->setAttribute( 'id', 'g0' ); # TODO make this meaningful
413 $graph->setAttribute( 'parse.edgeids', 'canonical' );
df6d9812 414 $graph->setAttribute( 'parse.edges', scalar($self->paths) );
8e1394aa 415 $graph->setAttribute( 'parse.nodeids', 'canonical' );
df6d9812 416 $graph->setAttribute( 'parse.nodes', scalar($self->readings) );
8e1394aa 417 $graph->setAttribute( 'parse.order', 'nodesfirst' );
418
419 my $node_ctr = 0;
420 my %node_hash;
b15511bf 421 # Add our readings to the graph
b5054ca9 422 foreach my $n ( sort { $a->name cmp $b->name } $self->readings ) {
910a0a6d 423 my $node_el = $graph->addNewChild( $graphml_ns, 'node' );
424 my $node_xmlid = 'n' . $node_ctr++;
425 $node_hash{ $n->name } = $node_xmlid;
426 $node_el->setAttribute( 'id', $node_xmlid );
427 _add_graphml_data( $node_el, $node_data_keys{'name'}, $n->name );
428 _add_graphml_data( $node_el, $node_data_keys{'reading'}, $n->label );
d9e873d0 429 _add_graphml_data( $node_el, $node_data_keys{'rank'}, $n->rank )
430 if $n->has_rank;
910a0a6d 431 _add_graphml_data( $node_el, $node_data_keys{'class'}, $n->sub_class );
432 _add_graphml_data( $node_el, $node_data_keys{'identical'}, $n->primary->name )
433 if $n->has_primary;
8e1394aa 434 }
435
b15511bf 436 # Add any segments we have
437 foreach my $n ( sort { $a->name cmp $b->name } $self->segments ) {
910a0a6d 438 my $node_el = $graph->addNewChild( $graphml_ns, 'node' );
439 my $node_xmlid = 'n' . $node_ctr++;
440 $node_hash{ $n->name } = $node_xmlid;
441 $node_el->setAttribute( 'id', $node_xmlid );
442 _add_graphml_data( $node_el, $node_data_keys{'class'}, $n->sub_class );
443 _add_graphml_data( $node_el, $node_data_keys{'name'}, $n->name );
b15511bf 444 }
445
446 # Add the path, relationship, and segment edges
df6d9812 447 my $edge_ctr = 0;
ef9d481f 448 foreach my $e ( sort { $a->from->name cmp $b->from->name } $self->graph->edges() ) {
910a0a6d 449 my( $name, $from, $to ) = ( 'e'.$edge_ctr++,
450 $node_hash{ $e->from->name() },
451 $node_hash{ $e->to->name() } );
452 my $edge_el = $graph->addNewChild( $graphml_ns, 'edge' );
453 $edge_el->setAttribute( 'source', $from );
454 $edge_el->setAttribute( 'target', $to );
455 $edge_el->setAttribute( 'id', $name );
456 # Add the edge class
457 _add_graphml_data( $edge_el, $edge_data_keys{'class'}, $e->sub_class );
458 if( $e->sub_class eq 'path' ) {
459 # It's a witness path, so add the witness
460 my $base = $e->label;
461 my $key = $edge_data_keys{'witness_main'};
462 # TODO kind of hacky
463 if( $e->label =~ /^(.*?)\s+(\(a\.c\.\))$/ ) {
464 $base = $1;
465 $key = $edge_data_keys{'witness_ante_corr'};
466 }
467 _add_graphml_data( $edge_el, $key, $base );
468 } elsif( $e->sub_class eq 'relationship' ) {
469 # It's a relationship
470 _add_graphml_data( $edge_el, $edge_data_keys{'relationship'}, $e->label );
471 } # else a segment, nothing to record but source, target, class
8e1394aa 472 }
473
474 # Return the thing
df6d9812 475 $self->_save_graphml( $graphml->toString(1) );
476 return $graphml->toString(1);
477}
478
b15511bf 479sub _add_graphml_data {
480 my( $el, $key, $value ) = @_;
481 my $data_el = $el->addNewChild( $el->namespaceURI, 'data' );
482 return unless defined $value;
483 $data_el->setAttribute( 'key', $key );
484 $data_el->appendText( $value );
8e1394aa 485}
486
910a0a6d 487=item B<as_csv>
488
489print $graph->as_csv( $recalculate )
490
491Returns a CSV alignment table representation of the collation graph, one
492row per witness (or witness uncorrected.) Unless $recalculate is passed
493(and is a true value), the method will return a cached copy of the CSV
494after the first call to the method.
495
496=cut
497
498sub as_csv {
499 my( $self, $recalc ) = @_;
500 return $self->csv if $self->has_csv;
501 my $table = $self->make_alignment_table;
502 my $csv = Text::CSV_XS->new( { binary => 1, quote_null => 0 } );
503 my @result;
504 foreach my $row ( @$table ) {
505 $csv->combine( @$row );
506 push( @result, decode_utf8( $csv->string ) );
507 }
508 $self->_save_csv( join( "\n", @result ) );
509 return $self->csv;
510}
511
512sub make_alignment_table {
513 my $self = shift;
514 unless( $self->linear ) {
515 warn "Need a linear graph in order to make an alignment table";
516 return;
517 }
518 my $table;
519 my @all_pos = sort { $a <=> $b } $self->possible_positions;
520 foreach my $wit ( $self->tradition->witnesses ) {
521 my @row = _make_witness_row( $wit->path, \@all_pos );
522 unshift( @row, $wit->sigil );
523 push( @$table, \@row );
524 if( $wit->has_ante_corr ) {
525 my @ac_row = _make_witness_row( $wit->uncorrected_path, \@all_pos );
526 unshift( @ac_row, $wit->sigil . $self->ac_label );
527 push( @$table, \@ac_row );
528 }
529 }
530 # Return a table where the witnesses read in columns rather than rows.
531 my $turned = _turn_table( $table );
532 return $turned;
533}
534
535sub _make_witness_row {
536 my( $path, $positions ) = @_;
537 my %char_hash;
538 map { $char_hash{$_} = undef } @$positions;
539 foreach my $rdg ( @$path ) {
540 $char_hash{$rdg->rank} = $rdg->text;
541 }
542 my @row = map { $char_hash{$_} } @$positions;
543 return @row;
544}
545
546# Helper to turn the witnesses along columns rather than rows. Assumes
547# equal-sized rows.
548sub _turn_table {
549 my( $table ) = @_;
550 my $result = [];
551 return $result unless scalar @$table;
552 my $nrows = scalar @{$table->[0]};
553 foreach my $idx ( 0 .. $nrows - 1 ) {
554 foreach my $wit ( 0 .. $#{$table} ) {
555 $result->[$idx]->[$wit] = $table->[$wit]->[$idx];
556 }
557 }
558 return $result;
559}
560
561
3265b0ce 562sub collapse_graph_paths {
1f563ac3 563 my $self = shift;
3265b0ce 564 # Our collation graph has an path per witness. This is great for
1f563ac3 565 # calculation purposes, but terrible for display. Thus we want to
3265b0ce 566 # display only one path between any two nodes.
1f563ac3 567
568 return if $self->collapsed;
569
3265b0ce 570 print STDERR "Collapsing witness paths in graph...\n";
1f563ac3 571
572 # Don't list out every witness if we have more than half to list.
910a0a6d 573 my $majority = int( scalar( $self->tradition->witnesses ) / 2 ) + 1;
a0093bf2 574 # But don't compress if there are only a few witnesses.
575 $majority = 4 if $majority < 4;
b15511bf 576 foreach my $node ( $self->readings ) {
910a0a6d 577 my $newlabels = {};
578 # We will visit each node, so we only look ahead.
579 foreach my $edge ( $node->outgoing() ) {
580 next unless $edge->class eq 'edge.path';
581 add_hash_entry( $newlabels, $edge->to->name, $edge->name );
582 $self->del_path( $edge );
583 }
584
585 foreach my $newdest ( keys %$newlabels ) {
586 my $label;
587 my @compressed_wits = @{$newlabels->{$newdest}};
588 if( @compressed_wits < $majority ) {
589 $label = join( ', ', sort( @{$newlabels->{$newdest}} ) );
590 } else {
591 ## TODO FIX THIS HACK
592 my @aclabels;
593 foreach my $wit ( @compressed_wits ) {
594 push( @aclabels, $wit ) if( $wit =~ /^(.*?)(\s*\(?a\.\s*c\.\)?)$/ );
595 }
596 $label = join( ', ', 'majority', sort( @aclabels ) );
597 }
598
599 my $newpath = $self->add_path( $node, $self->reading( $newdest ), $label );
600 $newpath->hidden_witnesses( \@compressed_wits );
601 }
1f563ac3 602 }
603
604 $self->collapsed( 1 );
605}
606
3265b0ce 607sub expand_graph_paths {
1f563ac3 608 my $self = shift;
3265b0ce 609 # Our collation graph has only one path between any two nodes.
1f563ac3 610 # This is great for display, but not so great for analysis.
3265b0ce 611 # Expand this so that each witness has its own path between any
1f563ac3 612 # two reading nodes.
613 return unless $self->collapsed;
614
3265b0ce 615 print STDERR "Expanding witness paths in graph...\n";
3265b0ce 616 foreach my $path( $self->paths ) {
910a0a6d 617 my $from = $path->from;
618 my $to = $path->to;
619 warn sprintf( "No hidden witnesses on %s -> %s ?", $from->name, $to->name )
620 unless $path->has_hidden_witnesses;
621 my @wits = @{$path->hidden_witnesses};
622 $self->del_path( $path );
623 foreach ( @wits ) {
624 $self->add_path( $from, $to, $_ );
625 }
1f563ac3 626 }
627 $self->collapsed( 0 );
628}
629
8e1394aa 630=back
631
de51424a 632=head2 Navigation methods
633
634=over
635
8e1394aa 636=item B<start>
637
638my $beginning = $collation->start();
639
640Returns the beginning of the collation, a meta-reading with label '#START#'.
641
642=cut
643
644sub start {
4a8828f0 645 # Return the beginning reading of the graph.
8e1394aa 646 my $self = shift;
647 my( $new_start ) = @_;
648 if( $new_start ) {
910a0a6d 649 $self->del_reading( '#START#' );
650 $self->graph->rename_node( $new_start, '#START#' );
651 }
652 # Make sure the start node has a start position.
d9e873d0 653 unless( $self->reading( '#START#' )->has_rank ) {
654 $self->reading( '#START#' )->rank( '0' );
8e1394aa 655 }
656 return $self->reading('#START#');
657}
658
910a0a6d 659=item B<end>
660
661my $end = $collation->end();
662
663Returns the end of the collation, a meta-reading with label '#END#'.
664
665=cut
666
667sub end {
668 my $self = shift;
669 my( $new_end ) = @_;
670 if( $new_end ) {
671 $self->del_reading( '#END#' );
672 $self->graph->rename_node( $new_end, '#END#' );
673 }
674 return $self->reading('#END#');
675}
676
e2902068 677=item B<reading_sequence>
678
679my @readings = $graph->reading_sequence( $first, $last, $path[, $alt_path] );
680
681Returns the ordered list of readings, starting with $first and ending
682with $last, along the given witness path. If no path is specified,
683assume that the path is that of the base text (if any.)
684
685=cut
686
910a0a6d 687# TODO Think about returning some lazy-eval iterator.
688
e2902068 689sub reading_sequence {
690 my( $self, $start, $end, $witness, $backup ) = @_;
691
930ff666 692 $witness = $self->baselabel unless $witness;
e2902068 693 my @readings = ( $start );
694 my %seen;
695 my $n = $start;
930ff666 696 while( $n && $n ne $end ) {
910a0a6d 697 if( exists( $seen{$n->name()} ) ) {
698 warn "Detected loop at " . $n->name();
699 last;
700 }
701 $seen{$n->name()} = 1;
702
703 my $next = $self->next_reading( $n, $witness, $backup );
704 warn "Did not find any path for $witness from reading " . $n->name
705 unless $next;
706 push( @readings, $next );
707 $n = $next;
e2902068 708 }
709 # Check that the last reading is our end reading.
710 my $last = $readings[$#readings];
711 warn "Last reading found from " . $start->label() .
910a0a6d 712 " for witness $witness is not the end!"
713 unless $last eq $end;
e2902068 714
715 return @readings;
716}
717
4a8828f0 718=item B<next_reading>
8e1394aa 719
4a8828f0 720my $next_reading = $graph->next_reading( $reading, $witpath );
8e1394aa 721
4a8828f0 722Returns the reading that follows the given reading along the given witness
930ff666 723path.
8e1394aa 724
725=cut
726
4a8828f0 727sub next_reading {
e2902068 728 # Return the successor via the corresponding path.
8e1394aa 729 my $self = shift;
4a8828f0 730 return $self->_find_linked_reading( 'next', @_ );
8e1394aa 731}
732
4a8828f0 733=item B<prior_reading>
8e1394aa 734
4a8828f0 735my $prior_reading = $graph->prior_reading( $reading, $witpath );
8e1394aa 736
4a8828f0 737Returns the reading that precedes the given reading along the given witness
930ff666 738path.
8e1394aa 739
740=cut
741
4a8828f0 742sub prior_reading {
e2902068 743 # Return the predecessor via the corresponding path.
8e1394aa 744 my $self = shift;
4a8828f0 745 return $self->_find_linked_reading( 'prior', @_ );
8e1394aa 746}
747
4a8828f0 748sub _find_linked_reading {
e2902068 749 my( $self, $direction, $node, $path, $alt_path ) = @_;
750 my @linked_paths = $direction eq 'next'
910a0a6d 751 ? $node->outgoing() : $node->incoming();
e2902068 752 return undef unless scalar( @linked_paths );
8e1394aa 753
e2902068 754 # We have to find the linked path that contains all of the
755 # witnesses supplied in $path.
756 my( @path_wits, @alt_path_wits );
757 @path_wits = $self->witnesses_of_label( $path ) if $path;
758 @alt_path_wits = $self->witnesses_of_label( $alt_path ) if $alt_path;
759 my $base_le;
760 my $alt_le;
761 foreach my $le ( @linked_paths ) {
910a0a6d 762 if( $le->name eq $self->baselabel ) {
763 $base_le = $le;
764 } else {
765 my @le_wits = $self->witnesses_of_label( $le->name );
766 if( _is_within( \@path_wits, \@le_wits ) ) {
767 # This is the right path.
768 return $direction eq 'next' ? $le->to() : $le->from();
769 } elsif( _is_within( \@alt_path_wits, \@le_wits ) ) {
770 $alt_le = $le;
771 }
772 }
8e1394aa 773 }
e2902068 774 # Got this far? Return the alternate path if it exists.
775 return $direction eq 'next' ? $alt_le->to() : $alt_le->from()
910a0a6d 776 if $alt_le;
e2902068 777
778 # Got this far? Return the base path if it exists.
779 return $direction eq 'next' ? $base_le->to() : $base_le->from()
910a0a6d 780 if $base_le;
e2902068 781
782 # Got this far? We have no appropriate path.
8e1394aa 783 warn "Could not find $direction node from " . $node->label
910a0a6d 784 . " along path $path";
8e1394aa 785 return undef;
786}
787
4a8828f0 788# Some set logic.
789sub _is_within {
790 my( $set1, $set2 ) = @_;
7854e12e 791 my $ret = @$set1; # will be 0, i.e. false, if set1 is empty
4a8828f0 792 foreach my $el ( @$set1 ) {
910a0a6d 793 $ret = 0 unless grep { /^\Q$el\E$/ } @$set2;
4a8828f0 794 }
795 return $ret;
796}
797
de51424a 798
799## INITIALIZATION METHODS - for use by parsers
4a8828f0 800# Walk the paths for each witness in the graph, and return the nodes
e2902068 801# that the graph has in common. If $using_base is true, some
802# different logic is needed.
7e450e44 803# NOTE This does not create paths; it merely finds common readings.
4a8828f0 804
805sub walk_witness_paths {
7e450e44 806 my( $self ) = @_;
4a8828f0 807 # For each witness, walk the path through the graph.
808 # Then we need to find the common nodes.
809 # TODO This method is going to fall down if we have a very gappy
810 # text in the collation.
811 my $paths = {};
3a1f2523 812 my @common_readings;
910a0a6d 813 foreach my $wit ( $self->tradition->witnesses ) {
814 my $curr_reading = $self->start;
7e450e44 815 my @wit_path = $self->reading_sequence( $self->start, $self->end,
910a0a6d 816 $wit->sigil );
817 $wit->path( \@wit_path );
818
819 # Detect the common readings.
820 @common_readings = _find_common( \@common_readings, \@wit_path );
4a8828f0 821 }
822
823 # Mark all the nodes as either common or not.
3a1f2523 824 foreach my $cn ( @common_readings ) {
910a0a6d 825 print STDERR "Setting " . $cn->name . " / " . $cn->label
826 . " as common node\n";
827 $cn->make_common;
4a8828f0 828 }
829 foreach my $n ( $self->readings() ) {
910a0a6d 830 $n->make_variant unless $n->is_common;
4a8828f0 831 }
3a1f2523 832 # Return an array of the common nodes in order.
833 return @common_readings;
4a8828f0 834}
835
930ff666 836sub _find_common {
837 my( $common_readings, $new_path ) = @_;
838 my @cr;
839 if( @$common_readings ) {
910a0a6d 840 foreach my $n ( @$new_path ) {
841 push( @cr, $n ) if grep { $_ eq $n } @$common_readings;
842 }
930ff666 843 } else {
910a0a6d 844 push( @cr, @$new_path );
930ff666 845 }
846 return @cr;
847}
848
849sub _remove_common {
850 my( $common_readings, $divergence ) = @_;
851 my @cr;
852 my %diverged;
853 map { $diverged{$_->name} = 1 } @$divergence;
854 foreach( @$common_readings ) {
910a0a6d 855 push( @cr, $_ ) unless $diverged{$_->name};
930ff666 856 }
857 return @cr;
858}
859
860
7e450e44 861# For use when a collation is constructed from a base text and an apparatus.
862# We have the sequences of readings and just need to add path edges.
e2902068 863
6a222840 864sub make_witness_paths {
865 my( $self ) = @_;
910a0a6d 866 foreach my $wit ( $self->tradition->witnesses ) {
867 print STDERR "Making path for " . $wit->sigil . "\n";
868 $self->make_witness_path( $wit );
7854e12e 869 }
7854e12e 870}
871
6a222840 872sub make_witness_path {
7854e12e 873 my( $self, $wit ) = @_;
874 my @chain = @{$wit->path};
15d2d3df 875 my $sig = $wit->sigil;
7854e12e 876 foreach my $idx ( 0 .. $#chain-1 ) {
910a0a6d 877 $self->add_path( $chain[$idx], $chain[$idx+1], $sig );
7854e12e 878 }
d9e873d0 879 if( $wit->has_ante_corr ) {
880 @chain = @{$wit->uncorrected_path};
881 foreach my $idx( 0 .. $#chain-1 ) {
882 my $source = $chain[$idx];
883 my $target = $chain[$idx+1];
884 $self->add_path( $source, $target, $sig.$self->ac_label )
885 unless $self->has_path( $source, $target, $sig );
886 }
15d2d3df 887 }
e2902068 888}
889
910a0a6d 890sub calculate_ranks {
891 my $self = shift;
892 # Walk a version of the graph where every node linked by a relationship
893 # edge is fundamentally the same node, and do a topological ranking on
894 # the nodes in this graph.
895 my $topo_graph = Graph::Easy->new();
896 my %rel_containers;
897 my $rel_ctr = 0;
898 # Add the nodes
899 foreach my $r ( $self->readings ) {
900 next if exists $rel_containers{$r->name};
901 my @rels = $r->related_readings( 'colocated' );
902 if( @rels ) {
903 # Make a relationship container.
904 push( @rels, $r );
905 my $rn = $topo_graph->add_node( 'rel_container_' . $rel_ctr++ );
906 foreach( @rels ) {
907 $rel_containers{$_->name} = $rn;
908 }
909 } else {
910 # Add a new node to mirror the old node.
911 $rel_containers{$r->name} = $topo_graph->add_node( $r->name );
912 }
4a8828f0 913 }
3a1f2523 914
910a0a6d 915 # Add the edges. Need only one edge between any pair of nodes.
916 foreach my $r ( $self->readings ) {
917 foreach my $n ( $r->neighbor_readings( 'forward' ) ) {
918 $topo_graph->add_edge_once( $rel_containers{$r->name},
919 $rel_containers{$n->name} );
920 }
921 }
922
923 # Now do the rankings, starting with the start node.
924 my $topo_start = $rel_containers{$self->start->name};
925 my $node_ranks = { $topo_start->name => 0 };
926 my @curr_origin = ( $topo_start );
927 # A little iterative function.
928 while( @curr_origin ) {
929 @curr_origin = _assign_rank( $node_ranks, @curr_origin );
930 }
931 # Transfer our rankings from the topological graph to the real one.
932 foreach my $r ( $self->readings ) {
933 $r->rank( $node_ranks->{$rel_containers{$r->name}->name} );
de51424a 934 }
8e1394aa 935}
3a1f2523 936
910a0a6d 937sub _assign_rank {
938 my( $node_ranks, @current_nodes ) = @_;
939 # Look at each of the children of @current_nodes. If all the child's
940 # parents have a rank, assign it the highest rank + 1 and add it to
941 # @next_nodes. Otherwise skip it.
942 my @next_nodes;
943 foreach my $c ( @current_nodes ) {
944 warn "Current reading " . $c->name . "has no rank!"
945 unless exists $node_ranks->{$c->name};
946 # print STDERR "Looking at child of node " . $c->name . ", rank "
947 # . $node_ranks->{$c->name} . "\n";
948 my @children = map { $_->to } $c->outgoing;
949 foreach my $child ( @children ) {
950 next if exists $node_ranks->{$child->name};
951 my $highest_rank = -1;
952 my $skip = 0;
953 my @parents = map { $_->from } $child->incoming;
954 foreach my $parent ( @parents ) {
955 if( exists $node_ranks->{$parent->name} ) {
956 $highest_rank = $node_ranks->{$parent->name}
957 if $highest_rank <= $node_ranks->{$parent->name};
958 } else {
959 $skip = 1;
960 last;
961 }
962 }
963 next if $skip;
964 # print STDERR "Assigning rank " . ( $highest_rank + 1 ) . " to node " . $child->name . "\n";
965 $node_ranks->{$child->name} = $highest_rank + 1;
966 push( @next_nodes, $child );
967 }
968 }
969 return @next_nodes;
4cdd82f1 970}
910a0a6d 971
4cdd82f1 972sub possible_positions {
3a1f2523 973 my $self = shift;
910a0a6d 974 my %all_pos;
975 map { $all_pos{ $_->rank } = 1 } $self->readings;
976 return keys %all_pos;
3a1f2523 977}
978
4cdd82f1 979# TODO think about indexing this.
3a1f2523 980sub readings_at_position {
4cdd82f1 981 my( $self, $position, $strict ) = @_;
4cdd82f1 982 my @answer;
983 foreach my $r ( $self->readings ) {
910a0a6d 984 push( @answer, $r ) if $r->is_at_position( $position, $strict );
4cdd82f1 985 }
3a1f2523 986 return @answer;
987}
988
989## Lemmatizer functions
990
991sub init_lemmata {
992 my $self = shift;
4cdd82f1 993
994 foreach my $position ( $self->possible_positions ) {
910a0a6d 995 $self->lemmata->{$position} = undef;
3a1f2523 996 }
997
998 foreach my $cr ( $self->common_readings ) {
910a0a6d 999 $self->lemmata->{$cr->position->maxref} = $cr->name;
3a1f2523 1000 }
1001}
7e450e44 1002
1003sub common_readings {
1004 my $self = shift;
1005 my @common = grep { $_->is_common } $self->readings();
d9e873d0 1006 return sort { $a->rank <=> $b->rank } @common;
7e450e44 1007}
3a1f2523 1008
1009=item B<lemma_readings>
1010
1011my @state = $graph->lemma_readings( @readings_delemmatized );
1012
1013Takes a list of readings that have just been delemmatized, and returns
1014a set of tuples of the form ['reading', 'state'] that indicates what
1015changes need to be made to the graph.
1016
1017=over
1018
1019=item *
1020
1021A state of 1 means 'lemmatize this reading'
1022
1023=item *
1024
1025A state of 0 means 'delemmatize this reading'
1026
1027=item *
1028
1029A state of undef means 'an ellipsis belongs in the text here because
1030no decision has been made / an earlier decision was backed out'
1031
1032=back
1033
1034=cut
1035
1036sub lemma_readings {
1037 my( $self, @toggled_off_nodes ) = @_;
1038
1039 # First get the positions of those nodes which have been
1040 # toggled off.
1041 my $positions_off = {};
4cdd82f1 1042 map { $positions_off->{ $_->position->reference } = $_->name }
1043 @toggled_off_nodes;
de51424a 1044
3a1f2523 1045 # Now for each position, we have to see if a node is on, and we
4cdd82f1 1046 # have to see if a node has been turned off. The lemmata hash
1047 # should contain fixed positions, range positions whose node was
1048 # just turned off, and range positions whose node is on.
3a1f2523 1049 my @answer;
4cdd82f1 1050 my %fixed_positions;
1051 # TODO One of these is probably redundant.
1052 map { $fixed_positions{$_} = 0 } keys %{$self->lemmata};
1053 map { $fixed_positions{$_} = 0 } keys %{$positions_off};
1054 map { $fixed_positions{$_} = 1 } $self->possible_positions;
1055 foreach my $pos ( sort { Text::Tradition::Collation::Position::str_cmp( $a, $b ) } keys %fixed_positions ) {
910a0a6d 1056 # Find the state of this position. If there is an active node,
1057 # its name will be the state; otherwise the state will be 0
1058 # (nothing at this position) or undef (ellipsis at this position)
1059 my $active = undef;
1060 $active = $self->lemmata->{$pos} if exists $self->lemmata->{$pos};
1061
1062 # Is there a formerly active node that was toggled off?
1063 if( exists( $positions_off->{$pos} ) ) {
1064 my $off_node = $positions_off->{$pos};
1065 if( $active && $active ne $off_node) {
1066 push( @answer, [ $off_node, 0 ], [ $active, 1 ] );
1067 } else {
1068 unless( $fixed_positions{$pos} ) {
1069 $active = 0;
1070 delete $self->lemmata->{$pos};
1071 }
1072 push( @answer, [ $off_node, $active ] );
1073 }
1074
1075 # No formerly active node, so we just see if there is a currently
1076 # active one.
1077 } elsif( $active ) {
1078 # Push the active node, whatever it is.
1079 push( @answer, [ $active, 1 ] );
1080 } else {
1081 # Push the state that is there. Arbitrarily use the first node
1082 # at that position.
1083 my @pos_nodes = $self->readings_at_position( $pos );
1084 push( @answer, [ $pos_nodes[0]->name, $self->lemmata->{$pos} ] );
1085 delete $self->lemmata->{$pos} unless $fixed_positions{$pos};
1086 }
3a1f2523 1087 }
4cdd82f1 1088
3a1f2523 1089 return @answer;
1090}
1091
de51424a 1092=item B<toggle_reading>
1093
1094my @readings_delemmatized = $graph->toggle_reading( $reading_name );
1095
1096Takes a reading node name, and either lemmatizes or de-lemmatizes
1097it. Returns a list of all readings that are de-lemmatized as a result
1098of the toggle.
1099
1100=cut
1101
1102sub toggle_reading {
1103 my( $self, $rname ) = @_;
1104
1105 return unless $rname;
1106 my $reading = $self->reading( $rname );
1107 if( !$reading || $reading->is_common() ) {
910a0a6d 1108 # Do nothing, it's a common node.
1109 return;
de51424a 1110 }
1111
1112 my $pos = $reading->position;
4cdd82f1 1113 my $fixed = $reading->position->fixed;
1114 my $old_state = $self->lemmata->{$pos->reference};
1115
de51424a 1116 my @readings_off;
1117 if( $old_state && $old_state eq $rname ) {
910a0a6d 1118 # Turn off the node. We turn on no others by default.
1119 push( @readings_off, $reading );
de51424a 1120 } else {
910a0a6d 1121 # Turn on the node.
1122 $self->lemmata->{$pos->reference} = $rname;
1123 # Any other 'on' readings in the same position should be off
1124 # if we have a fixed position.
1125 push( @readings_off, $self->same_position_as( $reading, 1 ) )
1126 if $pos->fixed;
1127 # Any node that is an identical transposed one should be off.
1128 push( @readings_off, $reading->identical_readings );
de51424a 1129 }
1130 @readings_off = unique_list( @readings_off );
910a0a6d 1131
de51424a 1132 # Turn off the readings that need to be turned off.
1133 my @readings_delemmatized;
1134 foreach my $n ( @readings_off ) {
910a0a6d 1135 my $npos = $n->position;
1136 my $state = undef;
1137 $state = $self->lemmata->{$npos->reference}
1138 if defined $self->lemmata->{$npos->reference};
1139 if( $state && $state eq $n->name ) {
1140 # this reading is still on, so turn it off
1141 push( @readings_delemmatized, $n );
1142 my $new_state = undef;
1143 if( $npos->fixed && $n eq $reading ) {
1144 # This is the reading that was clicked, so if there are no
1145 # other readings there and this is a fixed position, turn off
1146 # the position. In all other cases, restore the ellipsis.
1147 my @other_n = $self->same_position_as( $n ); # TODO do we need strict?
1148 $new_state = 0 unless @other_n;
1149 }
1150 $self->lemmata->{$npos->reference} = $new_state;
1151 } elsif( $old_state && $old_state eq $n->name ) {
1152 # another reading has already been turned on here
1153 push( @readings_delemmatized, $n );
1154 } # else some other reading was on anyway, so pass.
de51424a 1155 }
1156 return @readings_delemmatized;
1157}
1158
1159sub same_position_as {
4cdd82f1 1160 my( $self, $reading, $strict ) = @_;
de51424a 1161 my $pos = $reading->position;
4cdd82f1 1162 my %onpath = ( $reading->name => 1 );
1163 # TODO This might not always be sufficient. We really want to
1164 # exclude all readings on this one's path between its two
1165 # common points.
1166 map { $onpath{$_->name} = 1 } $reading->neighbor_readings;
1167 my @same = grep { !$onpath{$_->name} }
1168 $self->readings_at_position( $reading->position, $strict );
de51424a 1169 return @same;
1170}
3a1f2523 1171
4a8828f0 1172# Return the string that joins together a list of witnesses for
1173# display on a single path.
1174sub path_label {
1175 my $self = shift;
1176 return join( $self->wit_list_separator, @_ );
1177}
1178
1179sub witnesses_of_label {
de51424a 1180 my( $self, $label ) = @_;
4a8828f0 1181 my $regex = $self->wit_list_separator;
de51424a 1182 my @answer = split( /\Q$regex\E/, $label );
1183 return @answer;
4a8828f0 1184}
8e1394aa 1185
de51424a 1186sub unique_list {
1187 my( @list ) = @_;
1188 my %h;
1189 map { $h{$_->name} = $_ } @list;
1190 return values( %h );
1191}
1192
1f563ac3 1193sub add_hash_entry {
1194 my( $hash, $key, $entry ) = @_;
1195 if( exists $hash->{$key} ) {
910a0a6d 1196 push( @{$hash->{$key}}, $entry );
1f563ac3 1197 } else {
910a0a6d 1198 $hash->{$key} = [ $entry ];
1f563ac3 1199 }
1200}
1201
dd3b58b0 1202no Moose;
1203__PACKAGE__->meta->make_immutable;