make tabular parse test work
[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 }
1d310495 278 if( !$self->relationship_valid( $source, $target, $options->{'type'} ) ) {
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 {
1d310495 292 my( $self, $source, $target, $rel ) = @_;
293 if( $rel eq 'repetition' ) {
294 return 1;
295 } elsif ( $rel eq 'transposition' ) {
296 # Check that the two readings do not appear in the same witness.
297 my %seen_wits;
298 map { $seen_wits{$_} = 1 } $self->reading_witnesses( $source );
299 foreach my $w ( $self->reading_witnesses( $target ) ) {
300 return 0 if $seen_wits{$w};
301 }
302 return 1;
303 } else {
304 # Check that linking the source and target in a relationship won't lead
305 # to a path loop for any witness. First make a lookup table of all the
306 # readings related to either the source or the target.
307 my @proposed_related = ( $source, $target );
308 push( @proposed_related, $source->related_readings( 'colocated' ) );
309 push( @proposed_related, $target->related_readings( 'colocated' ) );
310 my %pr_ids;
311 map { $pr_ids{ $_->id } = 1 } @proposed_related;
312
313 # None of these proposed related readings should have a neighbor that
314 # is also in proposed_related.
315 foreach my $pr ( keys %pr_ids ) {
316 foreach my $neighbor( $self->sequence->neighbors( $pr ) ) {
317 return 0 if exists $pr_ids{$neighbor};
318 }
319 }
320 return 1;
321 }
322}
323
324# Return a list of the witnesses in which the reading appears.
325sub reading_witnesses {
326 my( $self, $reading ) = @_;
327 # We need only check either the incoming or the outgoing edges; I have
328 # arbitrarily chosen "incoming".
329 my %all_witnesses;
330 foreach my $e ( $self->sequence->edges_to( $reading ) ) {
331 my $wits = $self->sequence->get_edge_attributes( @$e );
332 @all_witnesses{ keys %$wits } = 1;
333 }
334 return keys %all_witnesses;
910a0a6d 335}
336
3a2ebbf4 337sub related_readings {
338 my( $self, $reading, $colocated ) = @_;
a753cc84 339 my $return_object;
340 if( ref( $reading ) eq 'Text::Tradition::Collation::Reading' ) {
341 $reading = $reading->id;
342 $return_object = 1;
7035e3a6 343# print STDERR "Returning related objects\n";
344# } else {
345# print STDERR "Returning related object names\n";
a753cc84 346 }
3a2ebbf4 347 my @related = $self->relations->all_reachable( $reading );
348 if( $colocated ) {
349 my @colo = grep { $self->relations->has_edge_attribute( $reading, $_, 'colocated' ) } @related;
a753cc84 350 @related = @colo;
351 }
352 return $return_object ? map { $self->reading( $_ ) } @related : @related;
3a2ebbf4 353}
354
8e1394aa 355=head2 Output method(s)
356
357=over
358
359=item B<as_svg>
360
361print $graph->as_svg( $recalculate );
362
363Returns an SVG string that represents the graph. Uses GraphViz to do
4a8828f0 364this, because Graph::Easy doesn\'t cope well with long graphs. Unless
8e1394aa 365$recalculate is passed (and is a true value), the method will return a
366cached copy of the SVG after the first call to the method.
367
368=cut
369
370sub as_svg {
3a2ebbf4 371 my( $self ) = @_;
372
8e1394aa 373 my @cmd = qw/dot -Tsvg/;
374 my( $svg, $err );
910a0a6d 375 my $dotfile = File::Temp->new();
d9e873d0 376 ## TODO REMOVE
eca16057 377 # $dotfile->unlink_on_destroy(0);
910a0a6d 378 binmode $dotfile, ':utf8';
379 print $dotfile $self->as_dot();
380 push( @cmd, $dotfile->filename );
381 run( \@cmd, ">", binary(), \$svg );
382 $svg = decode_utf8( $svg );
8e1394aa 383 return $svg;
384}
385
df6d9812 386=item B<as_dot>
387
388print $graph->as_dot( $view, $recalculate );
389
390Returns a string that is the collation graph expressed in dot
391(i.e. GraphViz) format. The 'view' argument determines what kind of
392graph is produced.
393 * 'path': a graph of witness paths through the collation (DEFAULT)
394 * 'relationship': a graph of how collation readings relate to
395 each other
396
397=cut
398
399sub as_dot {
400 my( $self, $view ) = @_;
3a2ebbf4 401 $view = 'sequence' unless $view;
df6d9812 402 # TODO consider making some of these things configurable
67da8d6c 403 my $graph_name = $self->tradition->name;
404 $graph_name =~ s/[^\w\s]//g;
405 $graph_name = join( '_', split( /\s+/, $graph_name ) );
406 my $dot = sprintf( "digraph %s {\n", $graph_name );
df6d9812 407 $dot .= "\tedge [ arrowhead=open ];\n";
408 $dot .= "\tgraph [ rankdir=LR ];\n";
409 $dot .= sprintf( "\tnode [ fontsize=%d, fillcolor=%s, style=%s, shape=%s ];\n",
3a2ebbf4 410 11, "white", "filled", "ellipse" );
df6d9812 411
412 foreach my $reading ( $self->readings ) {
910a0a6d 413 # Need not output nodes without separate labels
3a2ebbf4 414 next if $reading->id eq $reading->text;
415 $dot .= sprintf( "\t\"%s\" [ label=\"%s\" ];\n", $reading->id, $reading->text );
df6d9812 416 }
3a2ebbf4 417
418 # TODO do something sensible for relationships
df6d9812 419
3a2ebbf4 420 my @edges = $self->paths;
df6d9812 421 foreach my $edge ( @edges ) {
910a0a6d 422 my %variables = ( 'color' => '#000000',
423 'fontcolor' => '#000000',
3a2ebbf4 424 'label' => join( ', ', $self->path_witnesses( $edge ) ),
910a0a6d 425 );
426 my $varopts = join( ', ', map { $_.'="'.$variables{$_}.'"' } sort keys %variables );
427 $dot .= sprintf( "\t\"%s\" -> \"%s\" [ %s ];\n",
3a2ebbf4 428 $edge->[0], $edge->[1], $varopts );
df6d9812 429 }
df6d9812 430 $dot .= "}\n";
431 return $dot;
432}
433
3a2ebbf4 434sub path_witnesses {
435 my( $self, @edge ) = @_;
436 # If edge is an arrayref, cope.
437 if( @edge == 1 && ref( $edge[0] ) eq 'ARRAY' ) {
438 my $e = shift @edge;
439 @edge = @$e;
440 }
441 my @wits = keys %{$self->sequence->get_edge_attributes( @edge )};
442 return sort @wits;
443}
444
8e1394aa 445=item B<as_graphml>
446
447print $graph->as_graphml( $recalculate )
448
449Returns a GraphML representation of the collation graph, with
450transposition information and position information. Unless
451$recalculate is passed (and is a true value), the method will return a
452cached copy of the SVG after the first call to the method.
453
454=cut
455
456sub as_graphml {
3a2ebbf4 457 my( $self ) = @_;
8e1394aa 458
459 # Some namespaces
460 my $graphml_ns = 'http://graphml.graphdrawing.org/xmlns';
461 my $xsi_ns = 'http://www.w3.org/2001/XMLSchema-instance';
462 my $graphml_schema = 'http://graphml.graphdrawing.org/xmlns ' .
910a0a6d 463 'http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd';
8e1394aa 464
465 # Create the document and root node
466 my $graphml = XML::LibXML->createDocument( "1.0", "UTF-8" );
467 my $root = $graphml->createElementNS( $graphml_ns, 'graphml' );
468 $graphml->setDocumentElement( $root );
469 $root->setNamespace( $xsi_ns, 'xsi', 0 );
470 $root->setAttributeNS( $xsi_ns, 'schemaLocation', $graphml_schema );
471
e309421a 472 # Add the data keys for the graph
473 my %graph_data_keys;
474 my $gdi = 0;
1d310495 475 my @graph_attributes = qw/ version wit_list_separator baselabel linear ac_label /;
e309421a 476 foreach my $datum ( @graph_attributes ) {
477 $graph_data_keys{$datum} = 'dg'.$gdi++;
478 my $key = $root->addNewChild( $graphml_ns, 'key' );
479 $key->setAttribute( 'attr.name', $datum );
480 $key->setAttribute( 'attr.type', $key eq 'linear' ? 'boolean' : 'string' );
481 $key->setAttribute( 'for', 'graph' );
482 $key->setAttribute( 'id', $graph_data_keys{$datum} );
483 }
f6066bac 484
8e1394aa 485 # Add the data keys for nodes
ef9d481f 486 my %node_data_keys;
487 my $ndi = 0;
3a2ebbf4 488 my %node_data = (
489 id => 'string',
490 reading => 'string',
491 rank => 'string',
492 is_start => 'boolean',
493 is_end => 'boolean',
494 is_lacuna => 'boolean',
495 );
496 foreach my $datum ( keys %node_data ) {
910a0a6d 497 $node_data_keys{$datum} = 'dn'.$ndi++;
498 my $key = $root->addNewChild( $graphml_ns, 'key' );
499 $key->setAttribute( 'attr.name', $datum );
3a2ebbf4 500 $key->setAttribute( 'attr.type', $node_data{$datum} );
910a0a6d 501 $key->setAttribute( 'for', 'node' );
502 $key->setAttribute( 'id', $node_data_keys{$datum} );
8e1394aa 503 }
504
df6d9812 505 # Add the data keys for edges, i.e. witnesses
ef9d481f 506 my $edi = 0;
507 my %edge_data_keys;
3a2ebbf4 508 my %edge_data = (
509 class => 'string', # Path or relationship?
510 witness => 'string', # ID/label for a path
511 relationship => 'string', # ID/label for a relationship
512 extra => 'boolean', # Path key
513 colocated => 'boolean', # Relationship key
514 non_correctable => 'boolean', # Relationship key
515 non_independent => 'boolean', # Relationship key
516 );
517 foreach my $datum ( keys %edge_data ) {
518 $edge_data_keys{$datum} = 'de'.$edi++;
910a0a6d 519 my $key = $root->addNewChild( $graphml_ns, 'key' );
3a2ebbf4 520 $key->setAttribute( 'attr.name', $datum );
521 $key->setAttribute( 'attr.type', $edge_data{$datum} );
910a0a6d 522 $key->setAttribute( 'for', 'edge' );
3a2ebbf4 523 $key->setAttribute( 'id', $edge_data_keys{$datum} );
8e1394aa 524 }
3a2ebbf4 525
526 # Add the collation graph itself
8e1394aa 527 my $graph = $root->addNewChild( $graphml_ns, 'graph' );
528 $graph->setAttribute( 'edgedefault', 'directed' );
94c00c71 529 $graph->setAttribute( 'id', $self->tradition->name );
8e1394aa 530 $graph->setAttribute( 'parse.edgeids', 'canonical' );
df6d9812 531 $graph->setAttribute( 'parse.edges', scalar($self->paths) );
8e1394aa 532 $graph->setAttribute( 'parse.nodeids', 'canonical' );
df6d9812 533 $graph->setAttribute( 'parse.nodes', scalar($self->readings) );
8e1394aa 534 $graph->setAttribute( 'parse.order', 'nodesfirst' );
e309421a 535
536 # Collation attribute data
537 foreach my $datum ( @graph_attributes ) {
1d310495 538 my $value = $datum eq 'version' ? '2.0' : $self->$datum;
539 _add_graphml_data( $graph, $graph_data_keys{$datum}, $value );
e309421a 540 }
8e1394aa 541
542 my $node_ctr = 0;
543 my %node_hash;
b15511bf 544 # Add our readings to the graph
3a2ebbf4 545 foreach my $n ( sort { $a->id cmp $b->id } $self->readings ) {
910a0a6d 546 my $node_el = $graph->addNewChild( $graphml_ns, 'node' );
547 my $node_xmlid = 'n' . $node_ctr++;
3a2ebbf4 548 $node_hash{ $n->id } = $node_xmlid;
910a0a6d 549 $node_el->setAttribute( 'id', $node_xmlid );
3a2ebbf4 550 _add_graphml_data( $node_el, $node_data_keys{'id'}, $n->id );
551 _add_graphml_data( $node_el, $node_data_keys{'reading'}, $n->text );
d9e873d0 552 _add_graphml_data( $node_el, $node_data_keys{'rank'}, $n->rank )
553 if $n->has_rank;
b15511bf 554 }
555
3a2ebbf4 556 # Add the path edges
df6d9812 557 my $edge_ctr = 0;
3a2ebbf4 558 foreach my $e ( sort { $a->[0] cmp $b->[0] } $self->sequence->edges() ) {
559 # We add an edge in the graphml for every witness in $e.
560 foreach my $wit ( $self->path_witnesses( $e ) ) {
561 my( $id, $from, $to ) = ( 'e'.$edge_ctr++,
562 $node_hash{ $e->[0] },
563 $node_hash{ $e->[1] } );
564 my $edge_el = $graph->addNewChild( $graphml_ns, 'edge' );
565 $edge_el->setAttribute( 'source', $from );
566 $edge_el->setAttribute( 'target', $to );
567 $edge_el->setAttribute( 'id', $id );
568 # Add the edge class
569 _add_graphml_data( $edge_el, $edge_data_keys{'class'}, 'path' );
570
571 # It's a witness path, so add the witness
572 my $base = $wit;
573 my $key = $edge_data_keys{'witness'};
574 # Is this an ante-corr witness?
575 my $aclabel = $self->ac_label;
576 if( $wit =~ /^(.*)\Q$aclabel\E$/ ) {
577 # Keep the base witness
578 $base = $1;
579 # ...and record that this is an 'extra' reading path
580 _add_graphml_data( $edge_el, $edge_data_keys{'extra'}, $aclabel );
581 }
582 _add_graphml_data( $edge_el, $edge_data_keys{'witness'}, $base );
583 }
584 }
585
586 # Add the relationship edges
587 foreach my $e ( sort { $a->[0] cmp $b->[0] } $self->relationships ) {
588 my( $id, $from, $to ) = ( 'e'.$edge_ctr++,
589 $node_hash{ $e->[0] },
590 $node_hash{ $e->[1] } );
591 my $edge_el = $graph->addNewChild( $graphml_ns, 'edge' );
592 $edge_el->setAttribute( 'source', $from );
593 $edge_el->setAttribute( 'target', $to );
594 $edge_el->setAttribute( 'id', $id );
595 # Add the edge class
596 _add_graphml_data( $edge_el, $edge_data_keys{'class'}, 'relationship' );
597
598 my $data = $self->relations->get_edge_attributes( @$e );
599 # It's a relationship, so save the relationship data
600 _add_graphml_data( $edge_el, $edge_data_keys{'relationship'}, $data->{type} );
601 _add_graphml_data( $edge_el, $edge_data_keys{'colocated'}, $data->{colocated} );
602 if( exists $data->{non_correctable} ) {
603 _add_graphml_data( $edge_el, $edge_data_keys{'non_correctable'},
604 $data->{non_correctable} );
605 }
606 if( exists $data->{non_independent} ) {
607 _add_graphml_data( $edge_el, $edge_data_keys{'non_independent'},
608 $data->{non_independent} );
609 }
8e1394aa 610 }
611
94c00c71 612 # Save and return the thing
613 my $result = decode_utf8( $graphml->toString(1) );
94c00c71 614 return $result;
df6d9812 615}
616
b15511bf 617sub _add_graphml_data {
618 my( $el, $key, $value ) = @_;
b15511bf 619 return unless defined $value;
c9bf3dbf 620 my $data_el = $el->addNewChild( $el->namespaceURI, 'data' );
b15511bf 621 $data_el->setAttribute( 'key', $key );
622 $data_el->appendText( $value );
8e1394aa 623}
624
910a0a6d 625=item B<as_csv>
626
627print $graph->as_csv( $recalculate )
628
629Returns a CSV alignment table representation of the collation graph, one
630row per witness (or witness uncorrected.) Unless $recalculate is passed
631(and is a true value), the method will return a cached copy of the CSV
632after the first call to the method.
633
634=cut
635
636sub as_csv {
3a2ebbf4 637 my( $self ) = @_;
910a0a6d 638 my $table = $self->make_alignment_table;
639 my $csv = Text::CSV_XS->new( { binary => 1, quote_null => 0 } );
640 my @result;
641 foreach my $row ( @$table ) {
642 $csv->combine( @$row );
643 push( @result, decode_utf8( $csv->string ) );
644 }
3a2ebbf4 645 return join( "\n", @result );
910a0a6d 646}
647
0e476982 648# Make an alignment table - $noderefs controls whether the objects
649# in the table are the nodes or simply their readings.
9f3ba6f7 650
910a0a6d 651sub make_alignment_table {
08e0fb85 652 my( $self, $noderefs, $include ) = @_;
910a0a6d 653 unless( $self->linear ) {
654 warn "Need a linear graph in order to make an alignment table";
655 return;
656 }
657 my $table;
3a2ebbf4 658 my @all_pos = ( 1 .. $self->end->rank - 1 );
910a0a6d 659 foreach my $wit ( $self->tradition->witnesses ) {
eca16057 660 # print STDERR "Making witness row(s) for " . $wit->sigil . "\n";
1f7aa795 661 my @wit_path = $self->reading_sequence( $self->start, $self->end, $wit->sigil );
662 my @row = _make_witness_row( \@wit_path, \@all_pos, $noderefs );
910a0a6d 663 unshift( @row, $wit->sigil );
664 push( @$table, \@row );
1f7aa795 665 if( $wit->is_layered ) {
666 my @wit_ac_path = $self->reading_sequence( $self->start, $self->end,
667 $wit->sigil.$self->ac_label, $wit->sigil );
668 my @ac_row = _make_witness_row( \@wit_ac_path, \@all_pos, $noderefs );
910a0a6d 669 unshift( @ac_row, $wit->sigil . $self->ac_label );
670 push( @$table, \@ac_row );
671 }
672 }
0e476982 673
08e0fb85 674 if( $include ) {
675 my $winnowed = [];
676 # Winnow out the rows for any witness not included.
677 foreach my $row ( @$table ) {
678 next unless $include->{$row->[0]};
679 push( @$winnowed, $row );
680 }
681 $table = $winnowed;
682 }
683
910a0a6d 684 # Return a table where the witnesses read in columns rather than rows.
685 my $turned = _turn_table( $table );
08e0fb85 686 # TODO We should really go through and delete empty rows.
910a0a6d 687 return $turned;
688}
689
690sub _make_witness_row {
0e476982 691 my( $path, $positions, $noderefs ) = @_;
910a0a6d 692 my %char_hash;
693 map { $char_hash{$_} = undef } @$positions;
694 foreach my $rdg ( @$path ) {
eca16057 695 my $rtext = $rdg->text;
696 $rtext = '#LACUNA#' if $rdg->is_lacuna;
3a2ebbf4 697 # print STDERR "No rank for " . $rdg->id . "\n" unless defined $rdg->rank;
0e476982 698 $char_hash{$rdg->rank} = $noderefs ? $rdg : $rtext;
910a0a6d 699 }
700 my @row = map { $char_hash{$_} } @$positions;
eca16057 701 # Fill in lacuna markers for undef spots in the row
702 my $last_el = shift @row;
703 my @filled_row = ( $last_el );
704 foreach my $el ( @row ) {
0e476982 705 # If we are using node reference, make the lacuna node appear many times
706 # in the table. If not, use the lacuna tag.
707 if( $last_el && _el_is_lacuna( $last_el ) && !defined $el ) {
708 $el = $noderefs ? $last_el : '#LACUNA#';
eca16057 709 }
710 push( @filled_row, $el );
711 $last_el = $el;
712 }
713 return @filled_row;
910a0a6d 714}
715
0e476982 716# Tiny utility function to say if a table element is a lacuna
717sub _el_is_lacuna {
718 my $el = shift;
719 return 1 if $el eq '#LACUNA#';
720 return 1 if ref( $el ) eq 'Text::Tradition::Collation::Reading'
721 && $el->is_lacuna;
722 return 0;
723}
724
910a0a6d 725# Helper to turn the witnesses along columns rather than rows. Assumes
726# equal-sized rows.
727sub _turn_table {
728 my( $table ) = @_;
729 my $result = [];
730 return $result unless scalar @$table;
731 my $nrows = scalar @{$table->[0]};
732 foreach my $idx ( 0 .. $nrows - 1 ) {
733 foreach my $wit ( 0 .. $#{$table} ) {
734 $result->[$idx]->[$wit] = $table->[$wit]->[$idx];
735 }
736 }
737 return $result;
738}
739
8e1394aa 740=back
741
de51424a 742=head2 Navigation methods
743
744=over
745
8e1394aa 746=item B<start>
747
748my $beginning = $collation->start();
749
750Returns the beginning of the collation, a meta-reading with label '#START#'.
751
910a0a6d 752=item B<end>
753
754my $end = $collation->end();
755
756Returns the end of the collation, a meta-reading with label '#END#'.
757
910a0a6d 758
e2902068 759=item B<reading_sequence>
760
761my @readings = $graph->reading_sequence( $first, $last, $path[, $alt_path] );
762
763Returns the ordered list of readings, starting with $first and ending
764with $last, along the given witness path. If no path is specified,
765assume that the path is that of the base text (if any.)
766
767=cut
768
910a0a6d 769# TODO Think about returning some lazy-eval iterator.
770
e2902068 771sub reading_sequence {
772 my( $self, $start, $end, $witness, $backup ) = @_;
773
930ff666 774 $witness = $self->baselabel unless $witness;
e2902068 775 my @readings = ( $start );
776 my %seen;
777 my $n = $start;
3a2ebbf4 778 while( $n && $n->id ne $end->id ) {
779 if( exists( $seen{$n->id} ) ) {
780 warn "Detected loop at " . $n->id;
910a0a6d 781 last;
782 }
3a2ebbf4 783 $seen{$n->id} = 1;
910a0a6d 784
785 my $next = $self->next_reading( $n, $witness, $backup );
3a2ebbf4 786 $DB::single = 1 if $next->id eq $end->id;
44771cf2 787 unless( $next ) {
3a2ebbf4 788 warn "Did not find any path for $witness from reading " . $n->id;
44771cf2 789 last;
790 }
910a0a6d 791 push( @readings, $next );
792 $n = $next;
e2902068 793 }
794 # Check that the last reading is our end reading.
795 my $last = $readings[$#readings];
3a2ebbf4 796 warn "Last reading found from " . $start->text .
910a0a6d 797 " for witness $witness is not the end!"
3a2ebbf4 798 unless $last->id eq $end->id;
e2902068 799
800 return @readings;
801}
802
4a8828f0 803=item B<next_reading>
8e1394aa 804
4a8828f0 805my $next_reading = $graph->next_reading( $reading, $witpath );
8e1394aa 806
4a8828f0 807Returns the reading that follows the given reading along the given witness
930ff666 808path.
8e1394aa 809
810=cut
811
4a8828f0 812sub next_reading {
e2902068 813 # Return the successor via the corresponding path.
8e1394aa 814 my $self = shift;
3a2ebbf4 815 my $answer = $self->_find_linked_reading( 'next', @_ );
816 return $self->reading( $answer );
8e1394aa 817}
818
4a8828f0 819=item B<prior_reading>
8e1394aa 820
4a8828f0 821my $prior_reading = $graph->prior_reading( $reading, $witpath );
8e1394aa 822
4a8828f0 823Returns the reading that precedes the given reading along the given witness
930ff666 824path.
8e1394aa 825
826=cut
827
4a8828f0 828sub prior_reading {
e2902068 829 # Return the predecessor via the corresponding path.
8e1394aa 830 my $self = shift;
3a2ebbf4 831 my $answer = $self->_find_linked_reading( 'prior', @_ );
832 return $self->reading( $answer );
8e1394aa 833}
834
4a8828f0 835sub _find_linked_reading {
e2902068 836 my( $self, $direction, $node, $path, $alt_path ) = @_;
837 my @linked_paths = $direction eq 'next'
3a2ebbf4 838 ? $self->sequence->edges_from( $node )
839 : $self->sequence->edges_to( $node );
e2902068 840 return undef unless scalar( @linked_paths );
8e1394aa 841
e2902068 842 # We have to find the linked path that contains all of the
843 # witnesses supplied in $path.
844 my( @path_wits, @alt_path_wits );
3a2ebbf4 845 @path_wits = sort( $self->witnesses_of_label( $path ) ) if $path;
846 @alt_path_wits = sort( $self->witnesses_of_label( $alt_path ) ) if $alt_path;
e2902068 847 my $base_le;
848 my $alt_le;
849 foreach my $le ( @linked_paths ) {
3a2ebbf4 850 if( $self->sequence->has_edge_attribute( @$le, $self->baselabel ) ) {
910a0a6d 851 $base_le = $le;
910a0a6d 852 }
3a2ebbf4 853 my @le_wits = $self->path_witnesses( $le );
854 if( _is_within( \@path_wits, \@le_wits ) ) {
855 # This is the right path.
856 return $direction eq 'next' ? $le->[1] : $le->[0];
857 } elsif( _is_within( \@alt_path_wits, \@le_wits ) ) {
858 $alt_le = $le;
859 }
8e1394aa 860 }
e2902068 861 # Got this far? Return the alternate path if it exists.
3a2ebbf4 862 return $direction eq 'next' ? $alt_le->[1] : $alt_le->[0]
910a0a6d 863 if $alt_le;
e2902068 864
865 # Got this far? Return the base path if it exists.
3a2ebbf4 866 return $direction eq 'next' ? $base_le->[1] : $base_le->[0]
910a0a6d 867 if $base_le;
e2902068 868
869 # Got this far? We have no appropriate path.
8e1394aa 870 warn "Could not find $direction node from " . $node->label
910a0a6d 871 . " along path $path";
8e1394aa 872 return undef;
873}
874
4a8828f0 875# Some set logic.
876sub _is_within {
877 my( $set1, $set2 ) = @_;
7854e12e 878 my $ret = @$set1; # will be 0, i.e. false, if set1 is empty
4a8828f0 879 foreach my $el ( @$set1 ) {
910a0a6d 880 $ret = 0 unless grep { /^\Q$el\E$/ } @$set2;
4a8828f0 881 }
882 return $ret;
883}
884
de51424a 885
886## INITIALIZATION METHODS - for use by parsers
930ff666 887
7e450e44 888# For use when a collation is constructed from a base text and an apparatus.
889# We have the sequences of readings and just need to add path edges.
1f7aa795 890# When we are done, clear out the witness path attributes, as they are no
891# longer needed.
892# TODO Find a way to replace the witness path attributes with encapsulated functions?
e2902068 893
6a222840 894sub make_witness_paths {
895 my( $self ) = @_;
910a0a6d 896 foreach my $wit ( $self->tradition->witnesses ) {
897 print STDERR "Making path for " . $wit->sigil . "\n";
898 $self->make_witness_path( $wit );
7854e12e 899 }
7854e12e 900}
901
6a222840 902sub make_witness_path {
7854e12e 903 my( $self, $wit ) = @_;
904 my @chain = @{$wit->path};
15d2d3df 905 my $sig = $wit->sigil;
7854e12e 906 foreach my $idx ( 0 .. $#chain-1 ) {
910a0a6d 907 $self->add_path( $chain[$idx], $chain[$idx+1], $sig );
7854e12e 908 }
1f7aa795 909 if( $wit->is_layered ) {
d9e873d0 910 @chain = @{$wit->uncorrected_path};
911 foreach my $idx( 0 .. $#chain-1 ) {
912 my $source = $chain[$idx];
913 my $target = $chain[$idx+1];
914 $self->add_path( $source, $target, $sig.$self->ac_label )
915 unless $self->has_path( $source, $target, $sig );
916 }
15d2d3df 917 }
1f7aa795 918 $wit->clear_path;
919 $wit->clear_uncorrected_path;
e2902068 920}
921
910a0a6d 922sub calculate_ranks {
923 my $self = shift;
924 # Walk a version of the graph where every node linked by a relationship
925 # edge is fundamentally the same node, and do a topological ranking on
926 # the nodes in this graph.
c9bf3dbf 927 my $topo_graph = Graph->new();
910a0a6d 928 my %rel_containers;
929 my $rel_ctr = 0;
930 # Add the nodes
931 foreach my $r ( $self->readings ) {
3a2ebbf4 932 next if exists $rel_containers{$r->id};
910a0a6d 933 my @rels = $r->related_readings( 'colocated' );
934 if( @rels ) {
935 # Make a relationship container.
936 push( @rels, $r );
c9bf3dbf 937 my $rn = 'rel_container_' . $rel_ctr++;
938 $topo_graph->add_vertex( $rn );
910a0a6d 939 foreach( @rels ) {
3a2ebbf4 940 $rel_containers{$_->id} = $rn;
910a0a6d 941 }
942 } else {
943 # Add a new node to mirror the old node.
3a2ebbf4 944 $rel_containers{$r->id} = $r->id;
945 $topo_graph->add_vertex( $r->id );
910a0a6d 946 }
4a8828f0 947 }
3a1f2523 948
3a2ebbf4 949 # Add the edges.
910a0a6d 950 foreach my $r ( $self->readings ) {
3a2ebbf4 951 foreach my $n ( $self->sequence->successors( $r->id ) ) {
952 my( $tfrom, $tto ) = ( $rel_containers{$r->id},
953 $rel_containers{$n} );
954 $topo_graph->add_edge( $tfrom, $tto );
910a0a6d 955 }
956 }
957
958 # Now do the rankings, starting with the start node.
3a2ebbf4 959 my $topo_start = $rel_containers{$self->start->id};
c9bf3dbf 960 my $node_ranks = { $topo_start => 0 };
910a0a6d 961 my @curr_origin = ( $topo_start );
962 # A little iterative function.
963 while( @curr_origin ) {
c9bf3dbf 964 @curr_origin = _assign_rank( $topo_graph, $node_ranks, @curr_origin );
910a0a6d 965 }
966 # Transfer our rankings from the topological graph to the real one.
967 foreach my $r ( $self->readings ) {
3a2ebbf4 968 if( defined $node_ranks->{$rel_containers{$r->id}} ) {
969 $r->rank( $node_ranks->{$rel_containers{$r->id}} );
67da8d6c 970 } else {
971 $DB::single = 1;
3a2ebbf4 972 die "No rank calculated for node " . $r->id
67da8d6c 973 . " - do you have a cycle in the graph?";
974 }
de51424a 975 }
8e1394aa 976}
3a1f2523 977
910a0a6d 978sub _assign_rank {
c9bf3dbf 979 my( $graph, $node_ranks, @current_nodes ) = @_;
910a0a6d 980 # Look at each of the children of @current_nodes. If all the child's
981 # parents have a rank, assign it the highest rank + 1 and add it to
c9bf3dbf 982 # @next_nodes. Otherwise skip it; we will return when the highest-ranked
983 # parent gets a rank.
910a0a6d 984 my @next_nodes;
985 foreach my $c ( @current_nodes ) {
c9bf3dbf 986 warn "Current reading $c has no rank!"
987 unless exists $node_ranks->{$c};
988 # print STDERR "Looking at child of node $c, rank "
989 # . $node_ranks->{$c} . "\n";
990 foreach my $child ( $graph->successors( $c ) ) {
991 next if exists $node_ranks->{$child};
910a0a6d 992 my $highest_rank = -1;
993 my $skip = 0;
c9bf3dbf 994 foreach my $parent ( $graph->predecessors( $child ) ) {
995 if( exists $node_ranks->{$parent} ) {
996 $highest_rank = $node_ranks->{$parent}
997 if $highest_rank <= $node_ranks->{$parent};
910a0a6d 998 } else {
999 $skip = 1;
1000 last;
1001 }
1002 }
1003 next if $skip;
c9bf3dbf 1004 my $c_rank = $highest_rank + 1;
1005 # print STDERR "Assigning rank $c_rank to node $child \n";
1006 $node_ranks->{$child} = $c_rank;
910a0a6d 1007 push( @next_nodes, $child );
1008 }
1009 }
1010 return @next_nodes;
4cdd82f1 1011}
910a0a6d 1012
0e476982 1013# Another method to make up for rough collation methods. If the same reading
1014# appears multiple times at the same rank, collapse the nodes.
1015sub flatten_ranks {
1016 my $self = shift;
1017 my %unique_rank_rdg;
1018 foreach my $rdg ( $self->readings ) {
1019 next unless $rdg->has_rank;
1020 my $key = $rdg->rank . "||" . $rdg->text;
1021 if( exists $unique_rank_rdg{$key} ) {
1022 # Combine!
1023 print STDERR "Combining readings at same rank: $key\n";
1024 $self->merge_readings( $unique_rank_rdg{$key}, $rdg );
1025 } else {
1026 $unique_rank_rdg{$key} = $rdg;
1027 }
1028 }
1029}
1030
1031
fa954f4c 1032## Utility functions
de51424a 1033
4a8828f0 1034# Return the string that joins together a list of witnesses for
1035# display on a single path.
4a8828f0 1036sub witnesses_of_label {
de51424a 1037 my( $self, $label ) = @_;
4a8828f0 1038 my $regex = $self->wit_list_separator;
de51424a 1039 my @answer = split( /\Q$regex\E/, $label );
1040 return @answer;
4a8828f0 1041}
8e1394aa 1042
dd3b58b0 1043no Moose;
1044__PACKAGE__->meta->make_immutable;
e867486f 1045
1046=head1 BUGS / TODO
1047
1048=over
1049
1050=item * Rationalize edge classes
1051
1052=item * Port the internal graph from Graph::Easy to Graph
1053
1054=back