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