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