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