break out punctuation from the rest of the reading text
[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;
8e1394aa 6use IPC::Run qw( run binary );
910a0a6d 7use Text::CSV_XS;
b15511bf 8use Text::Tradition::Collation::Reading;
22222af9 9use Text::Tradition::Collation::RelationshipStore;
df6d9812 10use XML::LibXML;
dd3b58b0 11use Moose;
12
3a2ebbf4 13has 'sequence' => (
d047cd52 14 is => 'ro',
3a2ebbf4 15 isa => 'Graph',
16 default => sub { Graph->new() },
d047cd52 17 handles => {
3a2ebbf4 18 paths => 'edges',
d047cd52 19 },
d047cd52 20 );
3a2ebbf4 21
22has 'relations' => (
23 is => 'ro',
22222af9 24 isa => 'Text::Tradition::Collation::RelationshipStore',
25 handles => {
26 relationships => 'relationships',
27 related_readings => 'related_readings',
28 },
29 writer => '_set_relations',
3a2ebbf4 30 );
dd3b58b0 31
3a2ebbf4 32has 'tradition' => (
33 is => 'ro',
d047cd52 34 isa => 'Text::Tradition',
8d9a1cd8 35 weak_ref => 1,
d047cd52 36 );
dd3b58b0 37
3a2ebbf4 38has 'readings' => (
39 isa => 'HashRef[Text::Tradition::Collation::Reading]',
40 traits => ['Hash'],
41 handles => {
42 reading => 'get',
43 _add_reading => 'set',
44 del_reading => 'delete',
45 has_reading => 'exists',
46 readings => 'values',
47 },
48 default => sub { {} },
49 );
910a0a6d 50
4a8828f0 51has 'wit_list_separator' => (
7854e12e 52 is => 'rw',
53 isa => 'Str',
54 default => ', ',
55 );
56
57has 'baselabel' => (
58 is => 'rw',
59 isa => 'Str',
60 default => 'base text',
61 );
4a8828f0 62
15d2d3df 63has 'linear' => (
64 is => 'rw',
65 isa => 'Bool',
66 default => 1,
67 );
1f563ac3 68
ef9d481f 69has 'ac_label' => (
70 is => 'rw',
71 isa => 'Str',
72 default => ' (a.c.)',
73 );
3a2ebbf4 74
75has 'start' => (
76 is => 'ro',
77 isa => 'Text::Tradition::Collation::Reading',
78 writer => '_set_start',
79 weak_ref => 1,
80 );
81
82has 'end' => (
83 is => 'ro',
84 isa => 'Text::Tradition::Collation::Reading',
85 writer => '_set_end',
86 weak_ref => 1,
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 {
3a2ebbf4 105 my $self = shift;
22222af9 106 $self->_set_relations( Text::Tradition::Collation::RelationshipStore->new( 'collation' => $self ) );
3a2ebbf4 107 $self->_set_start( $self->add_reading( { 'collation' => $self, 'is_start' => 1 } ) );
108 $self->_set_end( $self->add_reading( { 'collation' => $self, 'is_end' => 1 } ) );
d047cd52 109}
784877d9 110
3a2ebbf4 111### Reading construct/destruct functions
112
113sub add_reading {
114 my( $self, $reading ) = @_;
115 unless( ref( $reading ) eq 'Text::Tradition::Collation::Reading' ) {
116 my %args = %$reading;
117 $reading = Text::Tradition::Collation::Reading->new(
118 'collation' => $self,
119 %args );
120 }
121 # First check to see if a reading with this ID exists.
122 if( $self->reading( $reading->id ) ) {
123 warn "Collation already has a reading with id " . $reading->id;
124 return undef;
125 }
126 $self->_add_reading( $reading->id => $reading );
127 # Once the reading has been added, put it in both graphs.
128 $self->sequence->add_vertex( $reading->id );
22222af9 129 $self->relations->add_reading( $reading->id );
3a2ebbf4 130 return $reading;
eca16057 131};
132
3a2ebbf4 133around del_reading => sub {
134 my $orig = shift;
135 my $self = shift;
136 my $arg = shift;
137
138 if( ref( $arg ) eq 'Text::Tradition::Collation::Reading' ) {
139 $arg = $arg->id;
140 }
3a2ebbf4 141 # Remove the reading from the graphs.
142 $self->sequence->delete_vertex( $arg );
22222af9 143 $self->relations->delete_reading( $arg );
3a2ebbf4 144
145 # Carry on.
146 $self->$orig( $arg );
147};
7854e12e 148
3a2ebbf4 149# merge_readings( $main, $to_be_deleted );
7854e12e 150
3a2ebbf4 151sub merge_readings {
152 my $self = shift;
153
154 # We only need the IDs for adding paths to the graph, not the reading
155 # objects themselves.
49d4f2ac 156 my( $kept, $deleted, $combine_char ) = $self->_stringify_args( @_ );
3a2ebbf4 157
158 # The kept reading should inherit the paths and the relationships
159 # of the deleted reading.
160 foreach my $path ( $self->sequence->edges_at( $deleted ) ) {
161 my @vector = ( $kept );
162 push( @vector, $path->[1] ) if $path->[0] eq $deleted;
163 unshift( @vector, $path->[0] ) if $path->[1] eq $deleted;
49d4f2ac 164 next if $vector[0] eq $vector[1]; # Don't add a self loop
3a2ebbf4 165 my %wits = %{$self->sequence->get_edge_attributes( @$path )};
166 $self->sequence->add_edge( @vector );
167 my $fwits = $self->sequence->get_edge_attributes( @vector );
168 @wits{keys %$fwits} = values %$fwits;
169 $self->sequence->set_edge_attributes( @vector, \%wits );
170 }
22222af9 171 $self->relations->merge_readings( $kept, $deleted, $combine_char );
3a2ebbf4 172
173 # Do the deletion deed.
49d4f2ac 174 if( $combine_char ) {
175 my $kept_obj = $self->reading( $kept );
176 my $new_text = join( $combine_char, $kept_obj->text,
177 $self->reading( $deleted )->text );
178 $kept_obj->alter_text( $new_text );
179 }
3a2ebbf4 180 $self->del_reading( $deleted );
181}
7854e12e 182
3265b0ce 183
3a2ebbf4 184# Helper function for manipulating the graph.
185sub _stringify_args {
186 my( $self, $first, $second, $arg ) = @_;
187 $first = $first->id
188 if ref( $first ) eq 'Text::Tradition::Collation::Reading';
189 $second = $second->id
190 if ref( $second ) eq 'Text::Tradition::Collation::Reading';
191 return( $first, $second, $arg );
192}
df6d9812 193
3a2ebbf4 194### Path logic
195
196sub add_path {
197 my $self = shift;
198
199 # We only need the IDs for adding paths to the graph, not the reading
200 # objects themselves.
201 my( $source, $target, $wit ) = $self->_stringify_args( @_ );
202
203 # Connect the readings
204 $self->sequence->add_edge( $source, $target );
205 # Note the witness in question
206 $self->sequence->set_edge_attribute( $source, $target, $wit, 1 );
b15511bf 207};
208
3a2ebbf4 209sub del_path {
210 my $self = shift;
49d4f2ac 211 my @args;
212 if( ref( $_[0] ) eq 'ARRAY' ) {
213 my $e = shift @_;
214 @args = ( @$e, @_ );
215 } else {
216 @args = @_;
217 }
3a2ebbf4 218
219 # We only need the IDs for adding paths to the graph, not the reading
220 # objects themselves.
49d4f2ac 221 my( $source, $target, $wit ) = $self->_stringify_args( @args );
3a2ebbf4 222
223 if( $self->sequence->has_edge_attribute( $source, $target, $wit ) ) {
49d4f2ac 224 $self->sequence->delete_edge_attribute( $source, $target, $wit );
3a2ebbf4 225 }
226 unless( keys %{$self->sequence->get_edge_attributes( $source, $target )} ) {
227 $self->sequence->delete_edge( $source, $target );
228 }
784877d9 229}
230
3a2ebbf4 231
15d2d3df 232# Extra graph-alike utility
233sub has_path {
3a2ebbf4 234 my $self = shift;
235 my( $source, $target, $wit ) = $self->_stringify_args( @_ );
236 return undef unless $self->sequence->has_edge( $source, $target );
237 return $self->sequence->has_edge_attribute( $source, $target, $wit );
b15511bf 238}
239
3a2ebbf4 240=head2 add_relationship( $reading1, $reading2, $definition )
241
242Adds the specified relationship between the two readings. A relationship
22222af9 243is transitive (i.e. undirected); the options for its definition may be found
244in Text::Tradition::Collation::Relationship.
3a2ebbf4 245
246=cut
247
248# Wouldn't it be lovely if edges could be objects, and all this type checking
249# and attribute management could be done via Moose?
250
251sub add_relationship {
252 my $self = shift;
22222af9 253 my( $source, $target, $opts ) = $self->_stringify_args( @_ );
64ae6270 254 my( $ret, @vectors ) = $self->relations->add_relationship( $source,
255 $self->reading( $source ), $target, $self->reading( $target ), $opts );
256 # Force a full rank recalculation every time. Yuck.
257 $self->calculate_ranks() if $ret && $self->end->has_rank;
258 return( $ret, @vectors );
22222af9 259}
ef9d481f 260
22222af9 261=head2 reading_witnesses( $reading )
910a0a6d 262
22222af9 263Return a list of sigils corresponding to the witnesses in which the reading appears.
3265b0ce 264
22222af9 265=cut
1d310495 266
1d310495 267sub reading_witnesses {
268 my( $self, $reading ) = @_;
269 # We need only check either the incoming or the outgoing edges; I have
96dc90ec 270 # arbitrarily chosen "incoming". Thus, special-case the start node.
271 if( $reading eq $self->start ) {
272 return map { $_->sigil } $self->tradition->witnesses;
273 }
1d310495 274 my %all_witnesses;
275 foreach my $e ( $self->sequence->edges_to( $reading ) ) {
276 my $wits = $self->sequence->get_edge_attributes( @$e );
277 @all_witnesses{ keys %$wits } = 1;
278 }
279 return keys %all_witnesses;
910a0a6d 280}
281
8e1394aa 282=head2 Output method(s)
283
284=over
285
286=item B<as_svg>
287
b22576c6 288print $collation->as_svg();
8e1394aa 289
0068967c 290Returns an SVG string that represents the graph, via as_dot and graphviz.
8e1394aa 291
292=cut
293
294sub as_svg {
3a2ebbf4 295 my( $self ) = @_;
296
8e1394aa 297 my @cmd = qw/dot -Tsvg/;
298 my( $svg, $err );
910a0a6d 299 my $dotfile = File::Temp->new();
d9e873d0 300 ## TODO REMOVE
eca16057 301 # $dotfile->unlink_on_destroy(0);
910a0a6d 302 binmode $dotfile, ':utf8';
303 print $dotfile $self->as_dot();
304 push( @cmd, $dotfile->filename );
305 run( \@cmd, ">", binary(), \$svg );
306 $svg = decode_utf8( $svg );
8e1394aa 307 return $svg;
308}
309
b22576c6 310=item B<svg_subgraph>
311
312print $collation->svg_subgraph( $from, $to )
313
314Returns an SVG string that represents the portion of the graph given by the
315specified range. The $from and $to variables refer to ranks within the graph.
316
317=cut
318
319sub svg_subgraph {
320 my( $self, $from, $to ) = @_;
321
322 my $dot = $self->as_dot( $from, $to );
323 unless( $dot ) {
324 warn "Could not output a graph with range $from - $to";
325 return;
326 }
327
328 my @cmd = qw/dot -Tsvg/;
329 my( $svg, $err );
330 my $dotfile = File::Temp->new();
331 ## TODO REMOVE
332 # $dotfile->unlink_on_destroy(0);
333 binmode $dotfile, ':utf8';
334 print $dotfile $dot;
335 push( @cmd, $dotfile->filename );
336 run( \@cmd, ">", binary(), \$svg );
337 $svg = decode_utf8( $svg );
338 return $svg;
339}
340
341
df6d9812 342=item B<as_dot>
343
b22576c6 344print $collation->as_dot();
df6d9812 345
346Returns a string that is the collation graph expressed in dot
347(i.e. GraphViz) format. The 'view' argument determines what kind of
348graph is produced.
349 * 'path': a graph of witness paths through the collation (DEFAULT)
350 * 'relationship': a graph of how collation readings relate to
351 each other
352
353=cut
354
355sub as_dot {
b22576c6 356 my( $self, $startrank, $endrank ) = @_;
357
358 # Check the arguments
359 if( $startrank ) {
360 return if $endrank && $startrank > $endrank;
361 return if $startrank > $self->end->rank;
362 }
363 if( defined $endrank ) {
364 return if $endrank < 0;
f1b3b33a 365 $endrank = undef if $endrank == $self->end->rank;
b22576c6 366 }
367
df6d9812 368 # TODO consider making some of these things configurable
67da8d6c 369 my $graph_name = $self->tradition->name;
370 $graph_name =~ s/[^\w\s]//g;
371 $graph_name = join( '_', split( /\s+/, $graph_name ) );
372 my $dot = sprintf( "digraph %s {\n", $graph_name );
df6d9812 373 $dot .= "\tedge [ arrowhead=open ];\n";
5f52ddca 374 $dot .= "\tgraph [ rankdir=LR,bgcolor=none ];\n";
df6d9812 375 $dot .= sprintf( "\tnode [ fontsize=%d, fillcolor=%s, style=%s, shape=%s ];\n",
3a2ebbf4 376 11, "white", "filled", "ellipse" );
df6d9812 377
b22576c6 378 # Output substitute start/end readings if necessary
379 if( $startrank ) {
380 $dot .= "\t\"#SUBSTART#\" [ label=\"...\" ];\n";
381 }
382 if( $endrank ) {
383 $dot .= "\t\"#SUBEND#\" [ label=\"...\" ];\n";
384 }
385 my %used; # Keep track of the readings that actually appear in the graph
386 my %subedges;
387 my %subend;
df6d9812 388 foreach my $reading ( $self->readings ) {
b22576c6 389 # Only output readings within our rank range.
390 next if $startrank && $reading->rank < $startrank;
391 next if $endrank && $reading->rank > $endrank;
392 $used{$reading->id} = 1;
393 $subedges{$reading->id} = '#SUBSTART#'
394 if $startrank && $startrank == $reading->rank;
395 $subedges{$reading->id} = '#SUBEND#'
396 if $endrank && $endrank == $reading->rank;
910a0a6d 397 # Need not output nodes without separate labels
3a2ebbf4 398 next if $reading->id eq $reading->text;
8f9cab7b 399 my $label = $reading->text;
400 $label =~ s/\"/\\\"/g;
401 $dot .= sprintf( "\t\"%s\" [ label=\"%s\" ];\n", $reading->id, $label );
df6d9812 402 }
3a2ebbf4 403
b22576c6 404 # Add substitute start and end edges if necessary
405 foreach my $node ( keys %subedges ) {
406 my @vector = ( $subedges{$node}, $node );
407 @vector = reverse( @vector ) if $vector[0] =~ /END/;
408 my $witstr = join( ', ', sort $self->reading_witnesses( $self->reading( $node ) ) );
409 my %variables = ( 'color' => '#000000',
910a0a6d 410 'fontcolor' => '#000000',
b22576c6 411 'label' => $witstr,
910a0a6d 412 );
413 my $varopts = join( ', ', map { $_.'="'.$variables{$_}.'"' } sort keys %variables );
b22576c6 414 $dot .= sprintf( "\t\"%s\" -> \"%s\" [ %s ];\n", @vector, $varopts );
415 }
416
417 # Add the real edges
418 my @edges = $self->paths;
419 foreach my $edge ( @edges ) {
420 # Do we need to output this edge?
421 if( $used{$edge->[0]} && $used{$edge->[1]} ) {;
422 my %variables = ( 'color' => '#000000',
423 'fontcolor' => '#000000',
424 'label' => join( ', ', $self->path_display_label( $edge ) ),
425 );
426 my $varopts = join( ', ', map { $_.'="'.$variables{$_}.'"' } sort keys %variables );
427 # Account for the rank gap if necessary
428 my $rankgap = $self->reading( $edge->[1] )->rank
429 - $self->reading( $edge->[0] )->rank;
430 $varopts .= ", minlen=$rankgap" if $rankgap > 1;
431 $dot .= sprintf( "\t\"%s\" -> \"%s\" [ %s ];\n",
432 $edge->[0], $edge->[1], $varopts );
433 }
df6d9812 434 }
b22576c6 435
df6d9812 436 $dot .= "}\n";
437 return $dot;
438}
439
3a2ebbf4 440sub path_witnesses {
441 my( $self, @edge ) = @_;
442 # If edge is an arrayref, cope.
443 if( @edge == 1 && ref( $edge[0] ) eq 'ARRAY' ) {
444 my $e = shift @edge;
445 @edge = @$e;
446 }
447 my @wits = keys %{$self->sequence->get_edge_attributes( @edge )};
448 return sort @wits;
449}
450
8f9cab7b 451sub path_display_label {
452 my( $self, $edge ) = @_;
453 my @wits = $self->path_witnesses( $edge );
454 my $maj = scalar( $self->tradition->witnesses ) * 0.6;
455 if( scalar @wits > $maj ) {
456 return 'majority';
457 } else {
458 return join( ', ', @wits );
459 }
460}
461
462
8e1394aa 463=item B<as_graphml>
464
b22576c6 465print $collation->as_graphml( $recalculate )
8e1394aa 466
467Returns a GraphML representation of the collation graph, with
468transposition information and position information. Unless
469$recalculate is passed (and is a true value), the method will return a
470cached copy of the SVG after the first call to the method.
471
472=cut
473
474sub as_graphml {
3a2ebbf4 475 my( $self ) = @_;
8e1394aa 476
477 # Some namespaces
478 my $graphml_ns = 'http://graphml.graphdrawing.org/xmlns';
479 my $xsi_ns = 'http://www.w3.org/2001/XMLSchema-instance';
480 my $graphml_schema = 'http://graphml.graphdrawing.org/xmlns ' .
910a0a6d 481 'http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd';
8e1394aa 482
483 # Create the document and root node
484 my $graphml = XML::LibXML->createDocument( "1.0", "UTF-8" );
485 my $root = $graphml->createElementNS( $graphml_ns, 'graphml' );
486 $graphml->setDocumentElement( $root );
487 $root->setNamespace( $xsi_ns, 'xsi', 0 );
488 $root->setAttributeNS( $xsi_ns, 'schemaLocation', $graphml_schema );
489
e309421a 490 # Add the data keys for the graph
491 my %graph_data_keys;
492 my $gdi = 0;
1d310495 493 my @graph_attributes = qw/ version wit_list_separator baselabel linear ac_label /;
e309421a 494 foreach my $datum ( @graph_attributes ) {
495 $graph_data_keys{$datum} = 'dg'.$gdi++;
496 my $key = $root->addNewChild( $graphml_ns, 'key' );
497 $key->setAttribute( 'attr.name', $datum );
498 $key->setAttribute( 'attr.type', $key eq 'linear' ? 'boolean' : 'string' );
499 $key->setAttribute( 'for', 'graph' );
500 $key->setAttribute( 'id', $graph_data_keys{$datum} );
501 }
f6066bac 502
8e1394aa 503 # Add the data keys for nodes
ef9d481f 504 my %node_data_keys;
505 my $ndi = 0;
3a2ebbf4 506 my %node_data = (
507 id => 'string',
255875b8 508 text => 'string',
3a2ebbf4 509 rank => 'string',
510 is_start => 'boolean',
511 is_end => 'boolean',
512 is_lacuna => 'boolean',
513 );
514 foreach my $datum ( keys %node_data ) {
910a0a6d 515 $node_data_keys{$datum} = 'dn'.$ndi++;
516 my $key = $root->addNewChild( $graphml_ns, 'key' );
517 $key->setAttribute( 'attr.name', $datum );
3a2ebbf4 518 $key->setAttribute( 'attr.type', $node_data{$datum} );
910a0a6d 519 $key->setAttribute( 'for', 'node' );
520 $key->setAttribute( 'id', $node_data_keys{$datum} );
8e1394aa 521 }
522
df6d9812 523 # Add the data keys for edges, i.e. witnesses
ef9d481f 524 my $edi = 0;
525 my %edge_data_keys;
3a2ebbf4 526 my %edge_data = (
f523c7a8 527 class => 'string', # Class, deprecated soon
3a2ebbf4 528 witness => 'string', # ID/label for a path
529 relationship => 'string', # ID/label for a relationship
530 extra => 'boolean', # Path key
531 colocated => 'boolean', # Relationship key
532 non_correctable => 'boolean', # Relationship key
533 non_independent => 'boolean', # Relationship key
534 );
535 foreach my $datum ( keys %edge_data ) {
536 $edge_data_keys{$datum} = 'de'.$edi++;
910a0a6d 537 my $key = $root->addNewChild( $graphml_ns, 'key' );
3a2ebbf4 538 $key->setAttribute( 'attr.name', $datum );
539 $key->setAttribute( 'attr.type', $edge_data{$datum} );
910a0a6d 540 $key->setAttribute( 'for', 'edge' );
3a2ebbf4 541 $key->setAttribute( 'id', $edge_data_keys{$datum} );
8e1394aa 542 }
3a2ebbf4 543
22222af9 544 # Add the collation graph itself
2c669bca 545 my $sgraph = $root->addNewChild( $graphml_ns, 'graph' );
546 $sgraph->setAttribute( 'edgedefault', 'directed' );
547 $sgraph->setAttribute( 'id', $self->tradition->name );
548 $sgraph->setAttribute( 'parse.edgeids', 'canonical' );
549 $sgraph->setAttribute( 'parse.edges', scalar($self->paths) );
550 $sgraph->setAttribute( 'parse.nodeids', 'canonical' );
551 $sgraph->setAttribute( 'parse.nodes', scalar($self->readings) );
552 $sgraph->setAttribute( 'parse.order', 'nodesfirst' );
22222af9 553
e309421a 554 # Collation attribute data
555 foreach my $datum ( @graph_attributes ) {
2c669bca 556 my $value = $datum eq 'version' ? '3.0' : $self->$datum;
557 _add_graphml_data( $sgraph, $graph_data_keys{$datum}, $value );
e309421a 558 }
8e1394aa 559
560 my $node_ctr = 0;
561 my %node_hash;
22222af9 562 # Add our readings to the graph
3a2ebbf4 563 foreach my $n ( sort { $a->id cmp $b->id } $self->readings ) {
2c669bca 564 # Add to the main graph
565 my $node_el = $sgraph->addNewChild( $graphml_ns, 'node' );
910a0a6d 566 my $node_xmlid = 'n' . $node_ctr++;
3a2ebbf4 567 $node_hash{ $n->id } = $node_xmlid;
910a0a6d 568 $node_el->setAttribute( 'id', $node_xmlid );
255875b8 569 foreach my $d ( keys %node_data ) {
570 my $nval = $n->$d;
571 _add_graphml_data( $node_el, $node_data_keys{$d}, $nval )
572 if defined $nval;
573 }
b15511bf 574 }
575
2c669bca 576 # Add the path edges to the sequence graph
df6d9812 577 my $edge_ctr = 0;
3a2ebbf4 578 foreach my $e ( sort { $a->[0] cmp $b->[0] } $self->sequence->edges() ) {
579 # We add an edge in the graphml for every witness in $e.
580 foreach my $wit ( $self->path_witnesses( $e ) ) {
581 my( $id, $from, $to ) = ( 'e'.$edge_ctr++,
582 $node_hash{ $e->[0] },
583 $node_hash{ $e->[1] } );
2c669bca 584 my $edge_el = $sgraph->addNewChild( $graphml_ns, 'edge' );
3a2ebbf4 585 $edge_el->setAttribute( 'source', $from );
586 $edge_el->setAttribute( 'target', $to );
587 $edge_el->setAttribute( 'id', $id );
3a2ebbf4 588
589 # It's a witness path, so add the witness
590 my $base = $wit;
591 my $key = $edge_data_keys{'witness'};
592 # Is this an ante-corr witness?
593 my $aclabel = $self->ac_label;
594 if( $wit =~ /^(.*)\Q$aclabel\E$/ ) {
595 # Keep the base witness
596 $base = $1;
597 # ...and record that this is an 'extra' reading path
598 _add_graphml_data( $edge_el, $edge_data_keys{'extra'}, $aclabel );
599 }
600 _add_graphml_data( $edge_el, $edge_data_keys{'witness'}, $base );
f523c7a8 601 _add_graphml_data( $edge_el, $edge_data_keys{'class'}, 'path' );
3a2ebbf4 602 }
603 }
604
22222af9 605 # Add the relationship graph to the XML
606 $self->relations->as_graphml( $root );
8e1394aa 607
94c00c71 608 # Save and return the thing
609 my $result = decode_utf8( $graphml->toString(1) );
94c00c71 610 return $result;
df6d9812 611}
612
b15511bf 613sub _add_graphml_data {
614 my( $el, $key, $value ) = @_;
b15511bf 615 return unless defined $value;
c9bf3dbf 616 my $data_el = $el->addNewChild( $el->namespaceURI, 'data' );
b15511bf 617 $data_el->setAttribute( 'key', $key );
618 $data_el->appendText( $value );
8e1394aa 619}
620
910a0a6d 621=item B<as_csv>
622
b22576c6 623print $collation->as_csv( $recalculate )
910a0a6d 624
625Returns a CSV alignment table representation of the collation graph, one
2c669bca 626row per witness (or witness uncorrected.)
910a0a6d 627
628=cut
629
630sub as_csv {
3a2ebbf4 631 my( $self ) = @_;
910a0a6d 632 my $table = $self->make_alignment_table;
633 my $csv = Text::CSV_XS->new( { binary => 1, quote_null => 0 } );
634 my @result;
2c669bca 635 # Make the header row
636 $csv->combine( map { $_->{'witness'} } @{$table->{'alignment'}} );
637 push( @result, decode_utf8( $csv->string ) );
638 # Make the rest of the rows
639 foreach my $idx ( 0 .. $table->{'length'} - 1 ) {
566f4595 640 my @rowobjs = map { $_->{'tokens'}->[$idx] } @{$table->{'alignment'}};
2c669bca 641 my @row = map { $_ ? $_->{'t'} : $_ } @rowobjs;
642 $csv->combine( @row );
910a0a6d 643 push( @result, decode_utf8( $csv->string ) );
644 }
3a2ebbf4 645 return join( "\n", @result );
910a0a6d 646}
647
2c669bca 648=item B<make_alignment_table>
649
b22576c6 650my $table = $collation->make_alignment_table( $use_refs, \@wits_to_include )
2c669bca 651
566f4595 652Return a reference to an alignment table, in a slightly enhanced CollateX
653format which looks like this:
654
655 $table = { alignment => [ { witness => "SIGIL",
656 tokens => [ { t => "READINGTEXT" }, ... ] },
657 { witness => "SIG2",
658 tokens => [ { t => "READINGTEXT" }, ... ] },
659 ... ],
660 length => TEXTLEN };
661
662If $use_refs is set to 1, the reading object is returned in the table
663instead of READINGTEXT; if not, the text of the reading is returned.
664If $wits_to_include is set to a hashref, only the witnesses whose sigil
665keys have a true hash value will be included.
2c669bca 666
667=cut
9f3ba6f7 668
910a0a6d 669sub make_alignment_table {
08e0fb85 670 my( $self, $noderefs, $include ) = @_;
910a0a6d 671 unless( $self->linear ) {
672 warn "Need a linear graph in order to make an alignment table";
673 return;
674 }
2c669bca 675 my $table = { 'alignment' => [], 'length' => $self->end->rank - 1 };
3a2ebbf4 676 my @all_pos = ( 1 .. $self->end->rank - 1 );
68454b71 677 foreach my $wit ( sort { $a->sigil cmp $b->sigil } $self->tradition->witnesses ) {
2c669bca 678 if( $include ) {
566f4595 679 next unless $include->{$wit->sigil};
2c669bca 680 }
eca16057 681 # print STDERR "Making witness row(s) for " . $wit->sigil . "\n";
1f7aa795 682 my @wit_path = $self->reading_sequence( $self->start, $self->end, $wit->sigil );
683 my @row = _make_witness_row( \@wit_path, \@all_pos, $noderefs );
2c669bca 684 push( @{$table->{'alignment'}},
685 { 'witness' => $wit->sigil, 'tokens' => \@row } );
1f7aa795 686 if( $wit->is_layered ) {
687 my @wit_ac_path = $self->reading_sequence( $self->start, $self->end,
688 $wit->sigil.$self->ac_label, $wit->sigil );
689 my @ac_row = _make_witness_row( \@wit_ac_path, \@all_pos, $noderefs );
2c669bca 690 push( @{$table->{'alignment'}},
691 { 'witness' => $wit->sigil.$self->ac_label, 'tokens' => \@ac_row } );
910a0a6d 692 }
693 }
2c669bca 694 return $table;
910a0a6d 695}
696
697sub _make_witness_row {
0e476982 698 my( $path, $positions, $noderefs ) = @_;
910a0a6d 699 my %char_hash;
700 map { $char_hash{$_} = undef } @$positions;
2c669bca 701 my $debug = 0;
910a0a6d 702 foreach my $rdg ( @$path ) {
eca16057 703 my $rtext = $rdg->text;
704 $rtext = '#LACUNA#' if $rdg->is_lacuna;
2c669bca 705 print STDERR "rank " . $rdg->rank . "\n" if $debug;
3a2ebbf4 706 # print STDERR "No rank for " . $rdg->id . "\n" unless defined $rdg->rank;
2c669bca 707 $char_hash{$rdg->rank} = $noderefs ? { 't' => $rdg }
708 : { 't' => $rtext };
910a0a6d 709 }
710 my @row = map { $char_hash{$_} } @$positions;
eca16057 711 # Fill in lacuna markers for undef spots in the row
712 my $last_el = shift @row;
713 my @filled_row = ( $last_el );
714 foreach my $el ( @row ) {
0e476982 715 # If we are using node reference, make the lacuna node appear many times
716 # in the table. If not, use the lacuna tag.
717 if( $last_el && _el_is_lacuna( $last_el ) && !defined $el ) {
566f4595 718 $el = $noderefs ? $last_el : { 't' => '#LACUNA#' };
eca16057 719 }
720 push( @filled_row, $el );
721 $last_el = $el;
722 }
723 return @filled_row;
910a0a6d 724}
725
0e476982 726# Tiny utility function to say if a table element is a lacuna
727sub _el_is_lacuna {
728 my $el = shift;
2c669bca 729 return 1 if $el->{'t'} eq '#LACUNA#';
730 return 1 if ref( $el->{'t'} ) eq 'Text::Tradition::Collation::Reading'
731 && $el->{'t'}->is_lacuna;
0e476982 732 return 0;
733}
734
910a0a6d 735# Helper to turn the witnesses along columns rather than rows. Assumes
736# equal-sized rows.
737sub _turn_table {
738 my( $table ) = @_;
739 my $result = [];
740 return $result unless scalar @$table;
741 my $nrows = scalar @{$table->[0]};
742 foreach my $idx ( 0 .. $nrows - 1 ) {
743 foreach my $wit ( 0 .. $#{$table} ) {
744 $result->[$idx]->[$wit] = $table->[$wit]->[$idx];
745 }
746 }
747 return $result;
748}
749
8e1394aa 750=back
751
de51424a 752=head2 Navigation methods
753
754=over
755
8e1394aa 756=item B<start>
757
758my $beginning = $collation->start();
759
760Returns the beginning of the collation, a meta-reading with label '#START#'.
761
910a0a6d 762=item B<end>
763
764my $end = $collation->end();
765
766Returns the end of the collation, a meta-reading with label '#END#'.
767
910a0a6d 768
e2902068 769=item B<reading_sequence>
770
b22576c6 771my @readings = $collation->reading_sequence( $first, $last, $path[, $alt_path] );
e2902068 772
773Returns the ordered list of readings, starting with $first and ending
774with $last, along the given witness path. If no path is specified,
775assume that the path is that of the base text (if any.)
776
777=cut
778
910a0a6d 779# TODO Think about returning some lazy-eval iterator.
780
e2902068 781sub reading_sequence {
782 my( $self, $start, $end, $witness, $backup ) = @_;
783
930ff666 784 $witness = $self->baselabel unless $witness;
e2902068 785 my @readings = ( $start );
786 my %seen;
787 my $n = $start;
3a2ebbf4 788 while( $n && $n->id ne $end->id ) {
789 if( exists( $seen{$n->id} ) ) {
790 warn "Detected loop at " . $n->id;
910a0a6d 791 last;
792 }
3a2ebbf4 793 $seen{$n->id} = 1;
910a0a6d 794
795 my $next = $self->next_reading( $n, $witness, $backup );
44771cf2 796 unless( $next ) {
3a2ebbf4 797 warn "Did not find any path for $witness from reading " . $n->id;
44771cf2 798 last;
799 }
910a0a6d 800 push( @readings, $next );
801 $n = $next;
e2902068 802 }
803 # Check that the last reading is our end reading.
804 my $last = $readings[$#readings];
3a2ebbf4 805 warn "Last reading found from " . $start->text .
910a0a6d 806 " for witness $witness is not the end!"
3a2ebbf4 807 unless $last->id eq $end->id;
e2902068 808
809 return @readings;
810}
811
4a8828f0 812=item B<next_reading>
8e1394aa 813
b22576c6 814my $next_reading = $collation->next_reading( $reading, $witpath );
8e1394aa 815
4a8828f0 816Returns the reading that follows the given reading along the given witness
930ff666 817path.
8e1394aa 818
819=cut
820
4a8828f0 821sub next_reading {
e2902068 822 # Return the successor via the corresponding path.
8e1394aa 823 my $self = shift;
3a2ebbf4 824 my $answer = $self->_find_linked_reading( 'next', @_ );
2c669bca 825 return undef unless $answer;
3a2ebbf4 826 return $self->reading( $answer );
8e1394aa 827}
828
4a8828f0 829=item B<prior_reading>
8e1394aa 830
b22576c6 831my $prior_reading = $collation->prior_reading( $reading, $witpath );
8e1394aa 832
4a8828f0 833Returns the reading that precedes the given reading along the given witness
930ff666 834path.
8e1394aa 835
836=cut
837
4a8828f0 838sub prior_reading {
e2902068 839 # Return the predecessor via the corresponding path.
8e1394aa 840 my $self = shift;
3a2ebbf4 841 my $answer = $self->_find_linked_reading( 'prior', @_ );
842 return $self->reading( $answer );
8e1394aa 843}
844
4a8828f0 845sub _find_linked_reading {
e2902068 846 my( $self, $direction, $node, $path, $alt_path ) = @_;
847 my @linked_paths = $direction eq 'next'
3a2ebbf4 848 ? $self->sequence->edges_from( $node )
849 : $self->sequence->edges_to( $node );
e2902068 850 return undef unless scalar( @linked_paths );
8e1394aa 851
e2902068 852 # We have to find the linked path that contains all of the
853 # witnesses supplied in $path.
854 my( @path_wits, @alt_path_wits );
3a2ebbf4 855 @path_wits = sort( $self->witnesses_of_label( $path ) ) if $path;
856 @alt_path_wits = sort( $self->witnesses_of_label( $alt_path ) ) if $alt_path;
e2902068 857 my $base_le;
858 my $alt_le;
859 foreach my $le ( @linked_paths ) {
3a2ebbf4 860 if( $self->sequence->has_edge_attribute( @$le, $self->baselabel ) ) {
910a0a6d 861 $base_le = $le;
910a0a6d 862 }
3a2ebbf4 863 my @le_wits = $self->path_witnesses( $le );
864 if( _is_within( \@path_wits, \@le_wits ) ) {
865 # This is the right path.
866 return $direction eq 'next' ? $le->[1] : $le->[0];
867 } elsif( _is_within( \@alt_path_wits, \@le_wits ) ) {
868 $alt_le = $le;
869 }
8e1394aa 870 }
e2902068 871 # Got this far? Return the alternate path if it exists.
3a2ebbf4 872 return $direction eq 'next' ? $alt_le->[1] : $alt_le->[0]
910a0a6d 873 if $alt_le;
e2902068 874
875 # Got this far? Return the base path if it exists.
3a2ebbf4 876 return $direction eq 'next' ? $base_le->[1] : $base_le->[0]
910a0a6d 877 if $base_le;
e2902068 878
879 # Got this far? We have no appropriate path.
2c669bca 880 warn "Could not find $direction node from " . $node->id
910a0a6d 881 . " along path $path";
8e1394aa 882 return undef;
883}
884
4a8828f0 885# Some set logic.
886sub _is_within {
887 my( $set1, $set2 ) = @_;
7854e12e 888 my $ret = @$set1; # will be 0, i.e. false, if set1 is empty
4a8828f0 889 foreach my $el ( @$set1 ) {
910a0a6d 890 $ret = 0 unless grep { /^\Q$el\E$/ } @$set2;
4a8828f0 891 }
892 return $ret;
893}
894
de51424a 895
896## INITIALIZATION METHODS - for use by parsers
930ff666 897
7e450e44 898# For use when a collation is constructed from a base text and an apparatus.
899# We have the sequences of readings and just need to add path edges.
1f7aa795 900# When we are done, clear out the witness path attributes, as they are no
901# longer needed.
902# TODO Find a way to replace the witness path attributes with encapsulated functions?
e2902068 903
6a222840 904sub make_witness_paths {
905 my( $self ) = @_;
910a0a6d 906 foreach my $wit ( $self->tradition->witnesses ) {
0068967c 907 # print STDERR "Making path for " . $wit->sigil . "\n";
910a0a6d 908 $self->make_witness_path( $wit );
7854e12e 909 }
7854e12e 910}
911
6a222840 912sub make_witness_path {
7854e12e 913 my( $self, $wit ) = @_;
914 my @chain = @{$wit->path};
15d2d3df 915 my $sig = $wit->sigil;
7854e12e 916 foreach my $idx ( 0 .. $#chain-1 ) {
910a0a6d 917 $self->add_path( $chain[$idx], $chain[$idx+1], $sig );
7854e12e 918 }
1f7aa795 919 if( $wit->is_layered ) {
d9e873d0 920 @chain = @{$wit->uncorrected_path};
921 foreach my $idx( 0 .. $#chain-1 ) {
922 my $source = $chain[$idx];
923 my $target = $chain[$idx+1];
924 $self->add_path( $source, $target, $sig.$self->ac_label )
925 unless $self->has_path( $source, $target, $sig );
926 }
15d2d3df 927 }
1f7aa795 928 $wit->clear_path;
929 $wit->clear_uncorrected_path;
e2902068 930}
931
910a0a6d 932sub calculate_ranks {
933 my $self = shift;
934 # Walk a version of the graph where every node linked by a relationship
935 # edge is fundamentally the same node, and do a topological ranking on
936 # the nodes in this graph.
c9bf3dbf 937 my $topo_graph = Graph->new();
910a0a6d 938 my %rel_containers;
939 my $rel_ctr = 0;
940 # Add the nodes
941 foreach my $r ( $self->readings ) {
3a2ebbf4 942 next if exists $rel_containers{$r->id};
910a0a6d 943 my @rels = $r->related_readings( 'colocated' );
944 if( @rels ) {
945 # Make a relationship container.
946 push( @rels, $r );
c9bf3dbf 947 my $rn = 'rel_container_' . $rel_ctr++;
948 $topo_graph->add_vertex( $rn );
910a0a6d 949 foreach( @rels ) {
3a2ebbf4 950 $rel_containers{$_->id} = $rn;
910a0a6d 951 }
952 } else {
953 # Add a new node to mirror the old node.
3a2ebbf4 954 $rel_containers{$r->id} = $r->id;
955 $topo_graph->add_vertex( $r->id );
910a0a6d 956 }
4a8828f0 957 }
3a1f2523 958
3a2ebbf4 959 # Add the edges.
910a0a6d 960 foreach my $r ( $self->readings ) {
3a2ebbf4 961 foreach my $n ( $self->sequence->successors( $r->id ) ) {
962 my( $tfrom, $tto ) = ( $rel_containers{$r->id},
963 $rel_containers{$n} );
49d4f2ac 964 $DB::single = 1 unless $tfrom && $tto;
3a2ebbf4 965 $topo_graph->add_edge( $tfrom, $tto );
910a0a6d 966 }
967 }
968
969 # Now do the rankings, starting with the start node.
3a2ebbf4 970 my $topo_start = $rel_containers{$self->start->id};
c9bf3dbf 971 my $node_ranks = { $topo_start => 0 };
910a0a6d 972 my @curr_origin = ( $topo_start );
973 # A little iterative function.
974 while( @curr_origin ) {
c9bf3dbf 975 @curr_origin = _assign_rank( $topo_graph, $node_ranks, @curr_origin );
910a0a6d 976 }
977 # Transfer our rankings from the topological graph to the real one.
978 foreach my $r ( $self->readings ) {
3a2ebbf4 979 if( defined $node_ranks->{$rel_containers{$r->id}} ) {
980 $r->rank( $node_ranks->{$rel_containers{$r->id}} );
67da8d6c 981 } else {
982 $DB::single = 1;
3a2ebbf4 983 die "No rank calculated for node " . $r->id
67da8d6c 984 . " - do you have a cycle in the graph?";
985 }
de51424a 986 }
8e1394aa 987}
3a1f2523 988
910a0a6d 989sub _assign_rank {
c9bf3dbf 990 my( $graph, $node_ranks, @current_nodes ) = @_;
910a0a6d 991 # Look at each of the children of @current_nodes. If all the child's
992 # parents have a rank, assign it the highest rank + 1 and add it to
c9bf3dbf 993 # @next_nodes. Otherwise skip it; we will return when the highest-ranked
994 # parent gets a rank.
910a0a6d 995 my @next_nodes;
996 foreach my $c ( @current_nodes ) {
c9bf3dbf 997 warn "Current reading $c has no rank!"
998 unless exists $node_ranks->{$c};
999 # print STDERR "Looking at child of node $c, rank "
1000 # . $node_ranks->{$c} . "\n";
1001 foreach my $child ( $graph->successors( $c ) ) {
1002 next if exists $node_ranks->{$child};
910a0a6d 1003 my $highest_rank = -1;
1004 my $skip = 0;
c9bf3dbf 1005 foreach my $parent ( $graph->predecessors( $child ) ) {
1006 if( exists $node_ranks->{$parent} ) {
1007 $highest_rank = $node_ranks->{$parent}
1008 if $highest_rank <= $node_ranks->{$parent};
910a0a6d 1009 } else {
1010 $skip = 1;
1011 last;
1012 }
1013 }
1014 next if $skip;
c9bf3dbf 1015 my $c_rank = $highest_rank + 1;
1016 # print STDERR "Assigning rank $c_rank to node $child \n";
1017 $node_ranks->{$child} = $c_rank;
910a0a6d 1018 push( @next_nodes, $child );
1019 }
1020 }
1021 return @next_nodes;
4cdd82f1 1022}
910a0a6d 1023
0e476982 1024# Another method to make up for rough collation methods. If the same reading
1025# appears multiple times at the same rank, collapse the nodes.
1026sub flatten_ranks {
1027 my $self = shift;
1028 my %unique_rank_rdg;
1029 foreach my $rdg ( $self->readings ) {
1030 next unless $rdg->has_rank;
1031 my $key = $rdg->rank . "||" . $rdg->text;
1032 if( exists $unique_rank_rdg{$key} ) {
1033 # Combine!
0068967c 1034 # print STDERR "Combining readings at same rank: $key\n";
0e476982 1035 $self->merge_readings( $unique_rank_rdg{$key}, $rdg );
1036 } else {
1037 $unique_rank_rdg{$key} = $rdg;
1038 }
1039 }
1040}
1041
1042
fa954f4c 1043## Utility functions
de51424a 1044
4a8828f0 1045# Return the string that joins together a list of witnesses for
1046# display on a single path.
4a8828f0 1047sub witnesses_of_label {
de51424a 1048 my( $self, $label ) = @_;
4a8828f0 1049 my $regex = $self->wit_list_separator;
de51424a 1050 my @answer = split( /\Q$regex\E/, $label );
1051 return @answer;
4a8828f0 1052}
8e1394aa 1053
22222af9 1054=begin testing
1055
1056use Text::Tradition;
1057
1058my $cxfile = 't/data/Collatex-16.xml';
1059my $t = Text::Tradition->new(
1060 'name' => 'inline',
1061 'input' => 'CollateX',
1062 'file' => $cxfile,
1063 );
1064my $c = $t->collation;
1065
1066is( $c->common_predecessor( $c->reading('n9'), $c->reading('n23') )->id,
1067 'n20', "Found correct common predecessor" );
1068is( $c->common_successor( $c->reading('n9'), $c->reading('n23') )->id,
1069 '#END#', "Found correct common successor" );
1070
1071is( $c->common_predecessor( $c->reading('n19'), $c->reading('n17') )->id,
1072 'n16', "Found correct common predecessor for readings on same path" );
1073is( $c->common_successor( $c->reading('n21'), $c->reading('n26') )->id,
1074 '#END#', "Found correct common successor for readings on same path" );
1075
1076=end testing
1077
1078=cut
1079
1080## Return the closest reading that is a predecessor of both the given readings.
1081sub common_predecessor {
1082 my $self = shift;
1083 return $self->common_in_path( @_, 'predecessors' );
1084}
1085
1086sub common_successor {
1087 my $self = shift;
1088 return $self->common_in_path( @_, 'successors' );
1089}
1090
1091sub common_in_path {
1092 my( $self, $r1, $r2, $dir ) = @_;
1093 my $iter = $r1->rank > $r2->rank ? $r1->rank : $r2->rank;
1094 $iter = $self->end->rank - $iter if $dir eq 'successors';
1095 my @candidates;
1096 my @last_checked = ( $r1, $r2 );
1097 my %all_seen;
1098 while( !@candidates ) {
1099 my @new_lc;
1100 foreach my $lc ( @last_checked ) {
1101 foreach my $p ( $lc->$dir ) {
1102 if( $all_seen{$p->id} ) {
1103 push( @candidates, $p );
1104 } else {
1105 $all_seen{$p->id} = 1;
1106 push( @new_lc, $p );
1107 }
1108 }
1109 }
1110 @last_checked = @new_lc;
1111 }
1112 my @answer = sort { $a->rank <=> $b->rank } @candidates;
1113 return $dir eq 'predecessors' ? pop( @answer ) : shift ( @answer );
1114}
1115
dd3b58b0 1116no Moose;
1117__PACKAGE__->meta->make_immutable;
e867486f 1118
1119=head1 BUGS / TODO
1120
1121=over
1122
0068967c 1123=item * Think about making Relationship objects again
e867486f 1124
1125=back