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