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