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