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