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