more work on our own graphml format
[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 Graph::Easy;
7 use IPC::Run qw( run binary );
8 use Text::CSV_XS;
9 use Text::Tradition::Collation::Path;
10 use Text::Tradition::Collation::Reading;
11 use Text::Tradition::Collation::Relationship;
12 use XML::LibXML;
13 use Moose;
14
15 has 'graph' => (
16     is => 'ro',
17     isa => 'Graph::Easy',
18     handles => {
19         add_reading => 'add_node',
20         add_lacuna => 'add_node',
21         del_reading => 'del_node',
22         add_path => 'add_edge',
23         del_path => 'del_edge',
24         reading => 'node',
25         path => 'edge',
26         readings => 'nodes',
27         paths => 'edges',
28         relationships => 'edges',
29     },
30     default => sub { Graph::Easy->new( undirected => 0 ) },
31     );
32                 
33
34 has 'tradition' => (  # TODO should this not be ro?
35     is => 'rw',
36     isa => 'Text::Tradition',
37     );
38
39 has 'svg' => (
40     is => 'ro',
41     isa => 'Str',
42     writer => '_save_svg',
43     predicate => 'has_svg',
44     );
45
46 has 'graphml' => (
47     is => 'ro',
48     isa => 'Str',
49     writer => '_save_graphml',
50     predicate => 'has_graphml',
51     );
52
53 has 'csv' => (
54     is => 'ro',
55     isa => 'Str',
56     writer => '_save_csv',
57     predicate => 'has_csv',
58     );
59
60 # Keeps track of the lemmas within the collation.  At most one lemma
61 # per position in the graph.
62 has 'lemmata' => (
63     is => 'ro',
64     isa => 'HashRef[Maybe[Str]]',
65     default => sub { {} },
66     );
67
68 has 'wit_list_separator' => (
69     is => 'rw',
70     isa => 'Str',
71     default => ', ',
72     );
73
74 has 'baselabel' => (
75     is => 'rw',
76     isa => 'Str',
77     default => 'base text',
78     );
79
80 has 'collapsed' => (
81     is => 'rw',
82     isa => 'Bool',
83     );
84
85 has 'linear' => (
86     is => 'rw',
87     isa => 'Bool',
88     default => 1,
89     );
90
91 has 'ac_label' => (
92     is => 'rw',
93     isa => 'Str',
94     default => ' (a.c.)',
95     );
96
97
98 # The collation can be created two ways:
99 # 1. Collate a set of witnesses (with CollateX I guess) and process
100 #    the results as in 2.
101 # 2. Read a pre-prepared collation in one of a variety of formats,
102 #    and make the graph from that.
103
104 # The graph itself will (for now) be immutable, and the positions
105 # within the graph will also be immutable.  We need to calculate those
106 # positions upon graph construction.  The equivalences between graph
107 # nodes will be mutable, entirely determined by the user (or possibly
108 # by some semantic pre-processing provided by the user.)  So the
109 # constructor should just make an empty equivalences object.  The
110 # constructor will also need to make the witness objects, if we didn't
111 # come through option 1.
112
113 sub BUILD {
114     my( $self, $args ) = @_;
115     $self->graph->use_class('node', 'Text::Tradition::Collation::Reading');
116     $self->graph->use_class('edge', 'Text::Tradition::Collation::Path');
117
118     # Pass through any graph-specific options.
119     my $shape = exists( $args->{'shape'} ) ? $args->{'shape'} : 'ellipse';
120     $self->graph->set_attribute( 'node', 'shape', $shape );
121     
122         # Start and end points for all texts
123         $self->start( 'INIT' );
124         $self->end( 'INIT' );
125 }
126
127 around add_lacuna => sub {
128     my $orig = shift;
129     my $self = shift;
130     my $id = shift @_;
131     my $l = $self->$orig( '#LACUNA_' . $id . '#' );
132     $l->is_lacuna( 1 );
133     return $l;
134 };
135
136 # Wrapper around add_path 
137
138 around add_path => sub {
139     my $orig = shift;
140     my $self = shift;
141
142     # Make sure there are three arguments
143     unless( @_ == 3 ) {
144         warn "Call add_path with args source, target, witness";
145         return;
146     }
147     # Make sure the proposed path does not yet exist
148     # NOTE 'reading' will currently return readings and segments
149     my( $source, $target, $wit ) = @_;
150     $source = $self->reading( $source )
151         unless ref( $source ) eq 'Text::Tradition::Collation::Reading';
152     $target = $self->reading( $target )
153         unless ref( $target ) eq 'Text::Tradition::Collation::Reading';
154     foreach my $path ( $source->edges_to( $target ) ) {
155         if( $path->label eq $wit && $path->class eq 'edge.path' ) {
156             return;
157         }
158     }
159     # Do the deed
160     $self->$orig( @_ );
161 };
162
163 # Wrapper around paths
164 around paths => sub {
165     my $orig = shift;
166     my $self = shift;
167
168     my @result = grep { $_->sub_class eq 'path' } $self->$orig( @_ );
169     return @result;
170 };
171
172 around relationships => sub {
173     my $orig = shift;
174     my $self = shift;
175     my @result = grep { $_->sub_class eq 'relationship' } $self->$orig( @_ );
176     return @result;
177 };
178
179 # Wrapper around merge_nodes
180 sub merge_readings {
181     my $self = shift;
182     my $first_node = shift;
183     my $second_node = shift;
184     $first_node->merge_from( $second_node );
185     unshift( @_, $first_node, $second_node );
186     return $self->graph->merge_nodes( @_ );
187 }
188
189 # Extra graph-alike utility
190 sub has_path {
191     my( $self, $source, $target, $label ) = @_;
192     my @paths = $source->edges_to( $target );
193     my @relevant = grep { $_->label eq $label } @paths;
194     return scalar @relevant;
195 }
196
197 ## Dealing with relationships between readings.  This is a different
198 ## sort of graph edge.  Return a success/failure value and a list of
199 ## node pairs that have been linked.
200
201 sub add_relationship {
202     my( $self, $source, $target, $options ) = @_;
203
204     # Make sure there is not another relationship between these two
205     # readings already
206     $source = $self->reading( $source )
207         unless ref( $source ) && $source->isa( 'Graph::Easy::Node' );
208     $target = $self->reading( $target )
209         unless ref( $target ) && $target->isa( 'Graph::Easy::Node' );
210     foreach my $rel ( $source->edges_to( $target ), $target->edges_to( $source ) ) {
211         if( $rel->class eq 'edge.relationship' ) {
212             return ( undef, "Relationship already exists between these readings" );
213         }
214     }
215     if( $options->{'equal_rank'} && !relationship_valid( $source, $target ) ) {
216         return ( undef, 'Relationship creates witness loop' );
217     }
218
219     # TODO Think about positional hilarity if relationships are added after positions
220     # are assigned.
221     
222     my @joined = ( [ $source->name, $target->name ] );  # Keep track of the nodes we join.
223     
224     $options->{'this_relation'} = [ $source, $target ];
225     my $rel;
226     eval { $rel = Text::Tradition::Collation::Relationship->new( %$options ) };
227     if( $@ ) {
228        return ( undef, $@ );
229     }
230     $self->graph->add_edge( $source, $target, $rel );
231     
232     # TODO Handle global relationship setting
233
234     return( 1, @joined );
235 }
236
237 sub relationship_valid {
238     my( $source, $target ) = @_;
239     # Check that linking the source and target in a relationship won't lead
240     # to a path loop for any witness.
241     my @proposed_related = ( $source, $target );
242     push( @proposed_related, $source->related_readings );
243     push( @proposed_related, $target->related_readings );
244     my %pr_ids;
245     map { $pr_ids{ $_->name } = 1 } @proposed_related;
246     # The lists of 'in' and 'out' should not have any element that appears
247     # in 'proposed_related'.
248     foreach my $pr ( @proposed_related ) {
249         foreach my $e ( $pr->incoming ) {
250             if( exists $pr_ids{ $e->from->name } ) {
251                 return 0;
252             }
253         }
254         foreach my $e ( $pr->outgoing ) {
255             if( exists $pr_ids{ $e->to->name } ) {
256                 return 0;
257             }
258         }
259     }
260     return 1;
261 }
262
263 =head2 Output method(s)
264
265 =over
266
267 =item B<as_svg>
268
269 print $graph->as_svg( $recalculate );
270
271 Returns an SVG string that represents the graph.  Uses GraphViz to do
272 this, because Graph::Easy doesn\'t cope well with long graphs. Unless
273 $recalculate is passed (and is a true value), the method will return a
274 cached copy of the SVG after the first call to the method.
275
276 =cut
277
278 sub as_svg {
279     my( $self, $recalc ) = @_;
280     return $self->svg if $self->has_svg;
281     
282     $self->collapse_graph_paths();
283     
284     my @cmd = qw/dot -Tsvg/;
285     my( $svg, $err );
286     my $dotfile = File::Temp->new();
287     ## TODO REMOVE
288     # $dotfile->unlink_on_destroy(0);
289     binmode $dotfile, ':utf8';
290     print $dotfile $self->as_dot();
291     push( @cmd, $dotfile->filename );
292     run( \@cmd, ">", binary(), \$svg );
293     $svg = decode_utf8( $svg );
294     $self->_save_svg( $svg );
295     $self->expand_graph_paths();
296     return $svg;
297 }
298
299 =item B<as_dot>
300
301 print $graph->as_dot( $view, $recalculate );
302
303 Returns a string that is the collation graph expressed in dot
304 (i.e. GraphViz) format.  The 'view' argument determines what kind of
305 graph is produced.
306     * 'path': a graph of witness paths through the collation (DEFAULT)
307     * 'relationship': a graph of how collation readings relate to 
308       each other
309
310 =cut
311
312 sub as_dot {
313     my( $self, $view ) = @_;
314     $view = 'path' unless $view;
315     # TODO consider making some of these things configurable
316     my $dot = sprintf( "digraph %s {\n", $self->tradition->name );
317     $dot .= "\tedge [ arrowhead=open ];\n";
318     $dot .= "\tgraph [ rankdir=LR ];\n";
319     $dot .= sprintf( "\tnode [ fontsize=%d, fillcolor=%s, style=%s, shape=%s ];\n",
320                      11, "white", "filled", $self->graph->get_attribute( 'node', 'shape' ) );
321
322     foreach my $reading ( $self->readings ) {
323         # Need not output nodes without separate labels
324         next if $reading->name eq $reading->label;
325         $dot .= sprintf( "\t\"%s\" [ label=\"%s\" ];\n", $reading->name, $reading->label );
326     }
327
328     my @edges = $view eq 'relationship' ? $self->relationships : $self->paths;
329     foreach my $edge ( @edges ) {
330         my %variables = ( 'color' => '#000000',
331                           'fontcolor' => '#000000',
332                           'label' => $edge->label,
333             );
334         my $varopts = join( ', ', map { $_.'="'.$variables{$_}.'"' } sort keys %variables );
335         $dot .= sprintf( "\t\"%s\" -> \"%s\" [ %s ];\n",
336                          $edge->from->name, $edge->to->name, $varopts );
337     }
338     $dot .= "}\n";
339     return $dot;
340 }
341
342 =item B<as_graphml>
343
344 print $graph->as_graphml( $recalculate )
345
346 Returns a GraphML representation of the collation graph, with
347 transposition information and position information. Unless
348 $recalculate is passed (and is a true value), the method will return a
349 cached copy of the SVG after the first call to the method.
350
351 =cut
352
353 sub as_graphml {
354     my( $self, $recalc ) = @_;
355     return $self->graphml if $self->has_graphml;
356
357     # Some namespaces
358     my $graphml_ns = 'http://graphml.graphdrawing.org/xmlns';
359     my $xsi_ns = 'http://www.w3.org/2001/XMLSchema-instance';
360     my $graphml_schema = 'http://graphml.graphdrawing.org/xmlns ' .
361         'http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd';
362
363     # Create the document and root node
364     my $graphml = XML::LibXML->createDocument( "1.0", "UTF-8" );
365     my $root = $graphml->createElementNS( $graphml_ns, 'graphml' );
366     $graphml->setDocumentElement( $root );
367     $root->setNamespace( $xsi_ns, 'xsi', 0 );
368     $root->setAttributeNS( $xsi_ns, 'schemaLocation', $graphml_schema );
369
370     # Add the data keys for the graph
371     my %graph_data_keys;
372     my $gdi = 0;
373     my @graph_attributes = qw/ wit_list_separator baselabel linear ac_label /;
374     foreach my $datum ( @graph_attributes ) {
375         $graph_data_keys{$datum} = 'dg'.$gdi++;
376         my $key = $root->addNewChild( $graphml_ns, 'key' );
377         $key->setAttribute( 'attr.name', $datum );
378         $key->setAttribute( 'attr.type', $key eq 'linear' ? 'boolean' : 'string' );
379         $key->setAttribute( 'for', 'graph' );
380         $key->setAttribute( 'id', $graph_data_keys{$datum} );           
381     }
382
383     # Add the data keys for nodes
384     my %node_data_keys;
385     my $ndi = 0;
386     foreach my $datum ( qw/ name reading identical rank class / ) {
387         $node_data_keys{$datum} = 'dn'.$ndi++;
388         my $key = $root->addNewChild( $graphml_ns, 'key' );
389         $key->setAttribute( 'attr.name', $datum );
390         $key->setAttribute( 'attr.type', 'string' );
391         $key->setAttribute( 'for', 'node' );
392         $key->setAttribute( 'id', $node_data_keys{$datum} );
393     }
394
395     # Add the data keys for edges, i.e. witnesses
396     my $edi = 0;
397     my %edge_data_keys;
398     my @string_keys = qw/ class witness relationship /;
399     my @bool_keys = qw/ extra equal_rank non_correctable non_independent /;
400     foreach my $edge_key( @string_keys ) {
401         $edge_data_keys{$edge_key} = 'de'.$edi++;
402         my $key = $root->addNewChild( $graphml_ns, 'key' );
403         $key->setAttribute( 'attr.name', $edge_key );
404         $key->setAttribute( 'attr.type', 'string' );
405         $key->setAttribute( 'for', 'edge' );
406         $key->setAttribute( 'id', $edge_data_keys{$edge_key} );
407     }
408     foreach my $edge_key( @bool_keys ) {
409         $edge_data_keys{$edge_key} = 'de'.$edi++;
410         my $key = $root->addNewChild( $graphml_ns, 'key' );
411         $key->setAttribute( 'attr.name', $edge_key );
412         $key->setAttribute( 'attr.type', 'boolean' );
413         $key->setAttribute( 'for', 'edge' );
414         $key->setAttribute( 'id', $edge_data_keys{$edge_key} );
415     }
416     
417     # Add the graph, its nodes, and its edges
418     my $graph = $root->addNewChild( $graphml_ns, 'graph' );
419     $graph->setAttribute( 'edgedefault', 'directed' );
420     $graph->setAttribute( 'id', $self->tradition->name );
421     $graph->setAttribute( 'parse.edgeids', 'canonical' );
422     $graph->setAttribute( 'parse.edges', scalar($self->paths) );
423     $graph->setAttribute( 'parse.nodeids', 'canonical' );
424     $graph->setAttribute( 'parse.nodes', scalar($self->readings) );
425     $graph->setAttribute( 'parse.order', 'nodesfirst' );
426     
427     # Collation attribute data
428     foreach my $datum ( @graph_attributes ) {
429                 _add_graphml_data( $graph, $graph_data_keys{$datum}, $self->$datum );
430         }
431
432     my $node_ctr = 0;
433     my %node_hash;
434     # Add our readings to the graph
435     foreach my $n ( sort { $a->name cmp $b->name } $self->readings ) {
436         my $node_el = $graph->addNewChild( $graphml_ns, 'node' );
437         my $node_xmlid = 'n' . $node_ctr++;
438         $node_hash{ $n->name } = $node_xmlid;
439         $node_el->setAttribute( 'id', $node_xmlid );
440         _add_graphml_data( $node_el, $node_data_keys{'name'}, $n->name );
441         _add_graphml_data( $node_el, $node_data_keys{'reading'}, $n->label );
442         _add_graphml_data( $node_el, $node_data_keys{'rank'}, $n->rank )
443             if $n->has_rank;
444         _add_graphml_data( $node_el, $node_data_keys{'class'}, $n->sub_class );
445         _add_graphml_data( $node_el, $node_data_keys{'identical'}, $n->primary->name )
446             if $n->has_primary && $n->primary ne $n;
447     }
448
449     # Add the path and relationship edges
450     my $edge_ctr = 0;
451     foreach my $e ( sort { $a->from->name cmp $b->from->name } $self->graph->edges() ) {
452         my( $name, $from, $to ) = ( 'e'.$edge_ctr++,
453                                     $node_hash{ $e->from->name() },
454                                     $node_hash{ $e->to->name() } );
455         my $edge_el = $graph->addNewChild( $graphml_ns, 'edge' );
456         $edge_el->setAttribute( 'source', $from );
457         $edge_el->setAttribute( 'target', $to );
458         $edge_el->setAttribute( 'id', $name );
459         # Add the edge class
460         _add_graphml_data( $edge_el, $edge_data_keys{'class'}, $e->sub_class );
461         
462         # For some classes we have extra information to save.
463         if( $e->sub_class eq 'path' ) {
464             # It's a witness path, so add the witness
465             my $base = $e->label;
466             my $key = $edge_data_keys{'witness_main'};
467             # Is this an ante-corr witness?
468             my $aclabel = $self->ac_label;
469             if( $e->label =~ /^(.*)\Q$aclabel\E$/ ) {
470                 # Keep the base witness
471                 $base = $1;
472                 # ...and record that this is an 'extra' reading path
473                 _add_graphml_data( $edge_el, $edge_data_keys{'extra'}, 'true' );
474             }
475             _add_graphml_data( $edge_el, $edge_data_keys{'witness'}, $base );
476         } elsif( $e->sub_class eq 'relationship' ) {
477             # It's a relationship, so save the relationship data
478             _add_graphml_data( $edge_el, $edge_data_keys{'relationship'}, $e->label );
479             _add_graphml_data( $edge_el, $edge_data_keys{'equal_rank'}, $e->equal_rank );
480             _add_graphml_data( $edge_el, $edge_data_keys{'non_correctable'}, $e->non_correctable );
481             _add_graphml_data( $edge_el, $edge_data_keys{'non_independent'}, $e->non_independent );
482         } 
483     }
484
485     # Save and return the thing
486     my $result = decode_utf8( $graphml->toString(1) );
487     $self->_save_graphml( $result );
488     return $result;
489 }
490
491 sub _add_graphml_data {
492     my( $el, $key, $value ) = @_;
493     return unless defined $value;
494     my $data_el = $el->addNewChild( $el->namespaceURI, 'data' );
495     $data_el->setAttribute( 'key', $key );
496     $data_el->appendText( $value );
497 }
498
499 =item B<as_csv>
500
501 print $graph->as_csv( $recalculate )
502
503 Returns a CSV alignment table representation of the collation graph, one
504 row per witness (or witness uncorrected.) Unless $recalculate is passed
505 (and is a true value), the method will return a cached copy of the CSV
506 after the first call to the method.
507
508 =cut
509
510 sub as_csv {
511     my( $self, $recalc ) = @_;
512     return $self->csv if $self->has_csv;
513     my $table = $self->make_alignment_table;
514     my $csv = Text::CSV_XS->new( { binary => 1, quote_null => 0 } );    
515     my @result;
516     foreach my $row ( @$table ) {
517         $csv->combine( @$row );
518         push( @result, decode_utf8( $csv->string ) );
519     }
520     $self->_save_csv( join( "\n", @result ) );
521     return $self->csv;
522 }
523
524 # Make an alignment table - $noderefs controls whether the objects
525 # in the table are the nodes or simply their readings.
526
527 sub make_alignment_table {
528     my( $self, $noderefs ) = @_;
529     unless( $self->linear ) {
530         warn "Need a linear graph in order to make an alignment table";
531         return;
532     }
533     my $table;
534     my @all_pos = sort { $a <=> $b } $self->possible_positions;
535     $DB::single = 1;
536     foreach my $wit ( $self->tradition->witnesses ) {
537         # print STDERR "Making witness row(s) for " . $wit->sigil . "\n";
538         my @row = _make_witness_row( $wit->path, \@all_pos, $noderefs );
539         unshift( @row, $wit->sigil );
540         push( @$table, \@row );
541         if( $wit->has_ante_corr ) {
542             my @ac_row = _make_witness_row( $wit->uncorrected_path, \@all_pos, $noderefs );
543             unshift( @ac_row, $wit->sigil . $self->ac_label );
544             push( @$table, \@ac_row );
545         }           
546     }
547
548     # Return a table where the witnesses read in columns rather than rows.
549     my $turned = _turn_table( $table );
550     return $turned;
551 }
552
553 sub _make_witness_row {
554     my( $path, $positions, $noderefs ) = @_;
555     my %char_hash;
556     map { $char_hash{$_} = undef } @$positions;
557     foreach my $rdg ( @$path ) {
558         my $rtext = $rdg->text;
559         $rtext = '#LACUNA#' if $rdg->is_lacuna;
560         $char_hash{$rdg->rank} = $noderefs ? $rdg : $rtext;
561     }
562     my @row = map { $char_hash{$_} } @$positions;
563     # Fill in lacuna markers for undef spots in the row
564     my $last_el = shift @row;
565     my @filled_row = ( $last_el );
566     foreach my $el ( @row ) {
567         # If we are using node reference, make the lacuna node appear many times
568         # in the table.  If not, use the lacuna tag.
569         if( $last_el && _el_is_lacuna( $last_el ) && !defined $el ) {
570             $el = $noderefs ? $last_el : '#LACUNA#';
571         }
572         push( @filled_row, $el );
573         $last_el = $el;
574     }
575     return @filled_row;
576 }
577
578 # Tiny utility function to say if a table element is a lacuna
579 sub _el_is_lacuna {
580     my $el = shift;
581     return 1 if $el eq '#LACUNA#';
582     return 1 if ref( $el ) eq 'Text::Tradition::Collation::Reading'
583         && $el->is_lacuna;
584     return 0;
585 }
586
587 # Helper to turn the witnesses along columns rather than rows.  Assumes
588 # equal-sized rows.
589 sub _turn_table {
590     my( $table ) = @_;
591     my $result = [];
592     return $result unless scalar @$table;
593     my $nrows = scalar @{$table->[0]};
594     foreach my $idx ( 0 .. $nrows - 1 ) {
595         foreach my $wit ( 0 .. $#{$table} ) {
596             $result->[$idx]->[$wit] = $table->[$wit]->[$idx];
597         }
598     }
599     return $result;        
600 }
601
602
603 sub collapse_graph_paths {
604     my $self = shift;
605     # Our collation graph has an path per witness.  This is great for
606     # calculation purposes, but terrible for display.  Thus we want to
607     # display only one path between any two nodes.
608
609     return if $self->collapsed;
610
611     print STDERR "Collapsing witness paths in graph...\n";
612
613     # Don't list out every witness if we have more than half to list.
614     my $majority = int( scalar( $self->tradition->witnesses ) / 2 ) + 1;
615     # But don't compress if there are only a few witnesses.
616     $majority = 4 if $majority < 4;
617     foreach my $node ( $self->readings ) {
618         my $newlabels = {};
619         # We will visit each node, so we only look ahead.
620         foreach my $edge ( $node->outgoing() ) {
621             next unless $edge->class eq 'edge.path';
622             add_hash_entry( $newlabels, $edge->to->name, $edge->name );
623             $self->del_path( $edge );
624         }
625
626         foreach my $newdest ( keys %$newlabels ) {
627             my $label;
628             my @compressed_wits = @{$newlabels->{$newdest}};
629             if( @compressed_wits < $majority ) {
630                 $label = join( ', ', sort( @{$newlabels->{$newdest}} ) );
631             } else {
632                 ## TODO FIX THIS HACK
633                 my @aclabels;
634                 foreach my $wit ( @compressed_wits ) {
635                     push( @aclabels, $wit ) if( $wit =~ /^(.*?)(\s*\(?a\.\s*c\.\)?)$/ );
636                 }
637                 $label = join( ', ', 'majority', sort( @aclabels ) );
638             }
639             
640             my $newpath = $self->add_path( $node, $self->reading( $newdest ), $label );
641             $newpath->hidden_witnesses( \@compressed_wits );
642         }
643     }
644
645     $self->collapsed( 1 );
646 }
647
648 sub expand_graph_paths {
649     my $self = shift;
650     # Our collation graph has only one path between any two nodes.
651     # This is great for display, but not so great for analysis.
652     # Expand this so that each witness has its own path between any
653     # two reading nodes.
654     return unless $self->collapsed;
655     
656     print STDERR "Expanding witness paths in graph...\n";
657     foreach my $path( $self->paths ) {
658         my $from = $path->from;
659         my $to = $path->to;
660         warn sprintf( "No hidden witnesses on %s -> %s ?", $from->name, $to->name )
661             unless $path->has_hidden_witnesses;
662         my @wits = @{$path->hidden_witnesses};
663         $self->del_path( $path );
664         foreach ( @wits ) {
665             $self->add_path( $from, $to, $_ );
666         }
667     }
668     $self->collapsed( 0 );
669 }
670
671 =back
672
673 =head2 Navigation methods
674
675 =over
676
677 =item B<start>
678
679 my $beginning = $collation->start();
680
681 Returns the beginning of the collation, a meta-reading with label '#START#'.
682
683 =cut
684
685 sub start {
686     # Return the beginning reading of the graph.
687     my( $self, $new_start ) = @_;
688     my $start = $self->reading( '#START#' );
689     if( ref( $new_start ) eq 'Text::Tradition::Collation::Reading' ) {
690         # Replace the existing start node.
691         $self->del_reading( '#START#' );
692         $self->graph->rename_node( $new_start, '#START#' );
693         $start = $new_start;
694     } elsif ( $new_start && $new_start eq 'INIT' ) {
695         # Make a new start node.
696         $start = $self->add_reading( '#START#' );
697     }
698     # Make sure the start node is a meta node
699     $start->is_meta( 1 );
700     # Make sure the start node has a start position.
701     unless( $start->has_rank ) {
702         $start->rank( '0' );
703     }
704     return $start;
705 }
706
707 =item B<end>
708
709 my $end = $collation->end();
710
711 Returns the end of the collation, a meta-reading with label '#END#'.
712
713 =cut
714
715 sub end {
716     my $self = shift;
717     my( $new_end ) = @_;
718     my $end = $self->reading( '#END#' );
719     if( ref( $new_end ) eq 'Text::Tradition::Collation::Reading' ) {
720         $self->del_reading( '#END#' );
721         $self->graph->rename_node( $new_end, '#END#' );
722         $end = $new_end
723     } elsif ( $new_end && $new_end eq 'INIT' ) {
724         # Make a new start node.
725         $end = $self->add_reading( '#END#' );
726     }
727     # Make sure the start node is a meta node
728     $end->is_meta( 1 );
729     return $end;
730 }
731
732 =item B<reading_sequence>
733
734 my @readings = $graph->reading_sequence( $first, $last, $path[, $alt_path] );
735
736 Returns the ordered list of readings, starting with $first and ending
737 with $last, along the given witness path.  If no path is specified,
738 assume that the path is that of the base text (if any.)
739
740 =cut
741
742 # TODO Think about returning some lazy-eval iterator.
743
744 sub reading_sequence {
745     my( $self, $start, $end, $witness, $backup ) = @_;
746
747     $witness = $self->baselabel unless $witness;
748     my @readings = ( $start );
749     my %seen;
750     my $n = $start;
751     while( $n && $n ne $end ) {
752         if( exists( $seen{$n->name()} ) ) {
753             warn "Detected loop at " . $n->name();
754             last;
755         }
756         $seen{$n->name()} = 1;
757         
758         my $next = $self->next_reading( $n, $witness, $backup );
759         warn "Did not find any path for $witness from reading " . $n->name
760             unless $next;
761         push( @readings, $next );
762         $n = $next;
763     }
764     # Check that the last reading is our end reading.
765     my $last = $readings[$#readings];
766     warn "Last reading found from " . $start->label() .
767         " for witness $witness is not the end!"
768         unless $last eq $end;
769     
770     return @readings;
771 }
772
773 =item B<next_reading>
774
775 my $next_reading = $graph->next_reading( $reading, $witpath );
776
777 Returns the reading that follows the given reading along the given witness
778 path.  
779
780 =cut
781
782 sub next_reading {
783     # Return the successor via the corresponding path.
784     my $self = shift;
785     return $self->_find_linked_reading( 'next', @_ );
786 }
787
788 =item B<prior_reading>
789
790 my $prior_reading = $graph->prior_reading( $reading, $witpath );
791
792 Returns the reading that precedes the given reading along the given witness
793 path.  
794
795 =cut
796
797 sub prior_reading {
798     # Return the predecessor via the corresponding path.
799     my $self = shift;
800     return $self->_find_linked_reading( 'prior', @_ );
801 }
802
803 sub _find_linked_reading {
804     my( $self, $direction, $node, $path, $alt_path ) = @_;
805     my @linked_paths = $direction eq 'next' 
806         ? $node->outgoing() : $node->incoming();
807     return undef unless scalar( @linked_paths );
808     
809     # We have to find the linked path that contains all of the
810     # witnesses supplied in $path.
811     my( @path_wits, @alt_path_wits );
812     @path_wits = $self->witnesses_of_label( $path ) if $path;
813     @alt_path_wits = $self->witnesses_of_label( $alt_path ) if $alt_path;
814     my $base_le;
815     my $alt_le;
816     foreach my $le ( @linked_paths ) {
817         if( $le->name eq $self->baselabel ) {
818             $base_le = $le;
819         } else {
820             my @le_wits = $self->witnesses_of_label( $le->name );
821             if( _is_within( \@path_wits, \@le_wits ) ) {
822                 # This is the right path.
823                 return $direction eq 'next' ? $le->to() : $le->from();
824             } elsif( _is_within( \@alt_path_wits, \@le_wits ) ) {
825                 $alt_le = $le;
826             }
827         }
828     }
829     # Got this far? Return the alternate path if it exists.
830     return $direction eq 'next' ? $alt_le->to() : $alt_le->from()
831         if $alt_le;
832
833     # Got this far? Return the base path if it exists.
834     return $direction eq 'next' ? $base_le->to() : $base_le->from()
835         if $base_le;
836
837     # Got this far? We have no appropriate path.
838     warn "Could not find $direction node from " . $node->label 
839         . " along path $path";
840     return undef;
841 }
842
843 # Some set logic.
844 sub _is_within {
845     my( $set1, $set2 ) = @_;
846     my $ret = @$set1; # will be 0, i.e. false, if set1 is empty
847     foreach my $el ( @$set1 ) {
848         $ret = 0 unless grep { /^\Q$el\E$/ } @$set2;
849     }
850     return $ret;
851 }
852
853
854 ## INITIALIZATION METHODS - for use by parsers
855 # Walk the paths for each witness in the graph, and return the nodes
856 # that the graph has in common.  If $using_base is true, some 
857 # different logic is needed.
858 # NOTE This does not create paths; it merely finds common readings.
859
860 sub walk_witness_paths {
861     my( $self ) = @_;
862     # For each witness, walk the path through the graph.
863     # Then we need to find the common nodes.  
864     # TODO This method is going to fall down if we have a very gappy 
865     # text in the collation.
866     my $paths = {};
867     my @common_readings;
868     foreach my $wit ( $self->tradition->witnesses ) {
869         my $curr_reading = $self->start;
870         my @wit_path = $self->reading_sequence( $self->start, $self->end, 
871                                                 $wit->sigil );
872         $wit->path( \@wit_path );
873
874         # Detect the common readings.
875         @common_readings = _find_common( \@common_readings, \@wit_path );
876     }
877
878     # Mark all the nodes as either common or not.
879     foreach my $cn ( @common_readings ) {
880         print STDERR "Setting " . $cn->name . " / " . $cn->label 
881             . " as common node\n";
882         $cn->make_common;
883     }
884     foreach my $n ( $self->readings() ) {
885         $n->make_variant unless $n->is_common;
886     }
887     # Return an array of the common nodes in order.
888     return @common_readings;
889 }
890
891 sub _find_common {
892     my( $common_readings, $new_path ) = @_;
893     my @cr;
894     if( @$common_readings ) {
895         foreach my $n ( @$new_path ) {
896             push( @cr, $n ) if grep { $_ eq $n } @$common_readings;
897         }
898     } else {
899         push( @cr, @$new_path );
900     }
901     return @cr;
902 }
903
904 sub _remove_common {
905     my( $common_readings, $divergence ) = @_;
906     my @cr;
907     my %diverged;
908     map { $diverged{$_->name} = 1 } @$divergence;
909     foreach( @$common_readings ) {
910         push( @cr, $_ ) unless $diverged{$_->name};
911     }
912     return @cr;
913 }
914
915
916 # For use when a collation is constructed from a base text and an apparatus.
917 # We have the sequences of readings and just need to add path edges.
918
919 sub make_witness_paths {
920     my( $self ) = @_;
921     foreach my $wit ( $self->tradition->witnesses ) {
922         print STDERR "Making path for " . $wit->sigil . "\n";
923         $self->make_witness_path( $wit );
924     }
925 }
926
927 sub make_witness_path {
928     my( $self, $wit ) = @_;
929     my @chain = @{$wit->path};
930     my $sig = $wit->sigil;
931     foreach my $idx ( 0 .. $#chain-1 ) {
932         $self->add_path( $chain[$idx], $chain[$idx+1], $sig );
933     }
934     if( $wit->has_ante_corr ) {
935         @chain = @{$wit->uncorrected_path};
936         foreach my $idx( 0 .. $#chain-1 ) {
937             my $source = $chain[$idx];
938             my $target = $chain[$idx+1];
939             $self->add_path( $source, $target, $sig.$self->ac_label )
940                 unless $self->has_path( $source, $target, $sig );
941         }
942     }
943 }
944
945 sub calculate_ranks {
946     my $self = shift;
947     # Walk a version of the graph where every node linked by a relationship 
948     # edge is fundamentally the same node, and do a topological ranking on
949     # the nodes in this graph.
950     my $topo_graph = Graph->new();
951     my %rel_containers;
952     my $rel_ctr = 0;
953     # Add the nodes
954     foreach my $r ( $self->readings ) {
955         next if exists $rel_containers{$r->name};
956         my @rels = $r->related_readings( 'colocated' );
957         if( @rels ) {
958             # Make a relationship container.
959             push( @rels, $r );
960             my $rn = 'rel_container_' . $rel_ctr++;
961             $topo_graph->add_vertex( $rn );
962             foreach( @rels ) {
963                 $rel_containers{$_->name} = $rn;
964             }
965         } else {
966             # Add a new node to mirror the old node.
967             $rel_containers{$r->name} = $r->name;
968             $topo_graph->add_vertex( $r->name );
969         }
970     }
971
972     # Add the edges. Need only one edge between any pair of nodes.
973     foreach my $r ( $self->readings ) {
974         foreach my $n ( $r->neighbor_readings( 'forward' ) ) {
975                 my( $tfrom, $tto ) = ( $rel_containers{$r->name},
976                         $rel_containers{$n->name} );
977             $topo_graph->add_edge( $tfrom, $tto )
978                 unless $topo_graph->has_edge( $tfrom, $tto );
979         }
980     }
981     
982     # Now do the rankings, starting with the start node.
983     my $topo_start = $rel_containers{$self->start->name};
984     my $node_ranks = { $topo_start => 0 };
985     my @curr_origin = ( $topo_start );
986     # A little iterative function.
987     while( @curr_origin ) {
988         @curr_origin = _assign_rank( $topo_graph, $node_ranks, @curr_origin );
989     }
990     # Transfer our rankings from the topological graph to the real one.
991     foreach my $r ( $self->readings ) {
992         $r->rank( $node_ranks->{$rel_containers{$r->name}} );
993     }
994 }
995
996 sub _assign_rank {
997     my( $graph, $node_ranks, @current_nodes ) = @_;
998     # Look at each of the children of @current_nodes.  If all the child's 
999     # parents have a rank, assign it the highest rank + 1 and add it to 
1000     # @next_nodes.  Otherwise skip it; we will return when the highest-ranked
1001     # parent gets a rank.
1002     my @next_nodes;
1003     foreach my $c ( @current_nodes ) {
1004         warn "Current reading $c has no rank!"
1005             unless exists $node_ranks->{$c};
1006         # print STDERR "Looking at child of node $c, rank " 
1007         #     . $node_ranks->{$c} . "\n";
1008         foreach my $child ( $graph->successors( $c ) ) {
1009             next if exists $node_ranks->{$child};
1010             my $highest_rank = -1;
1011             my $skip = 0;
1012             foreach my $parent ( $graph->predecessors( $child ) ) {
1013                 if( exists $node_ranks->{$parent} ) {
1014                     $highest_rank = $node_ranks->{$parent} 
1015                         if $highest_rank <= $node_ranks->{$parent};
1016                 } else {
1017                     $skip = 1;
1018                     last;
1019                 }
1020             }
1021             next if $skip;
1022             my $c_rank = $highest_rank + 1;
1023             # print STDERR "Assigning rank $c_rank to node $child \n";
1024             $node_ranks->{$child} = $c_rank;
1025             push( @next_nodes, $child );
1026         }
1027     }
1028     return @next_nodes;
1029 }
1030
1031 # Another method to make up for rough collation methods.  If the same reading
1032 # appears multiple times at the same rank, collapse the nodes.
1033 sub flatten_ranks {
1034     my $self = shift;
1035     my %unique_rank_rdg;
1036     foreach my $rdg ( $self->readings ) {
1037         next unless $rdg->has_rank;
1038         my $key = $rdg->rank . "||" . $rdg->text;
1039         if( exists $unique_rank_rdg{$key} ) {
1040             # Combine!
1041             print STDERR "Combining readings at same rank: $key\n";
1042             $self->merge_readings( $unique_rank_rdg{$key}, $rdg );
1043         } else {
1044             $unique_rank_rdg{$key} = $rdg;
1045         }
1046     }
1047 }
1048
1049
1050 sub possible_positions {
1051     my $self = shift;
1052     my %all_pos;
1053     map { $all_pos{ $_->rank } = 1 } $self->readings;
1054     return keys %all_pos;
1055 }
1056
1057 # TODO think about indexing this.
1058 sub readings_at_position {
1059     my( $self, $position, $strict ) = @_;
1060     my @answer;
1061     foreach my $r ( $self->readings ) {
1062         push( @answer, $r ) if $r->is_at_position( $position, $strict );
1063     }
1064     return @answer;
1065 }
1066
1067 ## Lemmatizer functions
1068
1069 sub init_lemmata {
1070     my $self = shift;
1071
1072     foreach my $position ( $self->possible_positions ) {
1073         $self->lemmata->{$position} = undef;
1074     }
1075
1076     foreach my $cr ( $self->common_readings ) {
1077         $self->lemmata->{$cr->position->maxref} = $cr->name;
1078     }
1079 }
1080
1081 sub common_readings {
1082     my $self = shift;
1083     my @common = grep { $_->is_common } $self->readings();
1084     return sort { $a->rank <=> $b->rank } @common;
1085 }
1086     
1087 =item B<lemma_readings>
1088
1089 my @state = $graph->lemma_readings( @readings_delemmatized );
1090
1091 Takes a list of readings that have just been delemmatized, and returns
1092 a set of tuples of the form ['reading', 'state'] that indicates what
1093 changes need to be made to the graph.
1094
1095 =over
1096
1097 =item * 
1098
1099 A state of 1 means 'lemmatize this reading'
1100
1101 =item * 
1102
1103 A state of 0 means 'delemmatize this reading'
1104
1105 =item * 
1106
1107 A state of undef means 'an ellipsis belongs in the text here because
1108 no decision has been made / an earlier decision was backed out'
1109
1110 =back
1111
1112 =cut
1113
1114 sub lemma_readings {
1115     my( $self, @toggled_off_nodes ) = @_;
1116
1117     # First get the positions of those nodes which have been
1118     # toggled off.
1119     my $positions_off = {};
1120     map { $positions_off->{ $_->position->reference } = $_->name } 
1121         @toggled_off_nodes;
1122
1123     # Now for each position, we have to see if a node is on, and we
1124     # have to see if a node has been turned off.  The lemmata hash
1125     # should contain fixed positions, range positions whose node was
1126     # just turned off, and range positions whose node is on.
1127     my @answer;
1128     my %fixed_positions;
1129     # TODO One of these is probably redundant.
1130     map { $fixed_positions{$_} = 0 } keys %{$self->lemmata};
1131     map { $fixed_positions{$_} = 0 } keys %{$positions_off};
1132     map { $fixed_positions{$_} = 1 } $self->possible_positions;
1133     foreach my $pos ( sort { Text::Tradition::Collation::Position::str_cmp( $a, $b ) } keys %fixed_positions ) {
1134         # Find the state of this position.  If there is an active node,
1135         # its name will be the state; otherwise the state will be 0 
1136         # (nothing at this position) or undef (ellipsis at this position)
1137         my $active = undef;
1138         $active = $self->lemmata->{$pos} if exists $self->lemmata->{$pos};
1139         
1140         # Is there a formerly active node that was toggled off?
1141         if( exists( $positions_off->{$pos} ) ) {
1142             my $off_node = $positions_off->{$pos};
1143             if( $active && $active ne $off_node) {
1144                 push( @answer, [ $off_node, 0 ], [ $active, 1 ] );
1145             } else {
1146                 unless( $fixed_positions{$pos} ) {
1147                     $active = 0;
1148                     delete $self->lemmata->{$pos};
1149                 }
1150                 push( @answer, [ $off_node, $active ] );
1151             }
1152
1153         # No formerly active node, so we just see if there is a currently
1154         # active one.
1155         } elsif( $active ) {
1156             # Push the active node, whatever it is.
1157             push( @answer, [ $active, 1 ] );
1158         } else {
1159             # Push the state that is there. Arbitrarily use the first node
1160             # at that position.
1161             my @pos_nodes = $self->readings_at_position( $pos );
1162             push( @answer, [ $pos_nodes[0]->name, $self->lemmata->{$pos} ] );
1163             delete $self->lemmata->{$pos} unless $fixed_positions{$pos};
1164         }
1165     }
1166
1167     return @answer;
1168 }
1169
1170 =item B<toggle_reading>
1171
1172 my @readings_delemmatized = $graph->toggle_reading( $reading_name );
1173
1174 Takes a reading node name, and either lemmatizes or de-lemmatizes
1175 it. Returns a list of all readings that are de-lemmatized as a result
1176 of the toggle.
1177
1178 =cut
1179
1180 sub toggle_reading {
1181     my( $self, $rname ) = @_;
1182     
1183     return unless $rname;
1184     my $reading = $self->reading( $rname );
1185     if( !$reading || $reading->is_common() ) {
1186         # Do nothing, it's a common node.
1187         return;
1188     } 
1189     
1190     my $pos = $reading->position;
1191     my $fixed = $reading->position->fixed;
1192     my $old_state = $self->lemmata->{$pos->reference};
1193
1194     my @readings_off;
1195     if( $old_state && $old_state eq $rname ) {
1196         # Turn off the node. We turn on no others by default.
1197         push( @readings_off, $reading );
1198     } else {
1199         # Turn on the node.
1200         $self->lemmata->{$pos->reference} = $rname;
1201         # Any other 'on' readings in the same position should be off
1202         # if we have a fixed position.
1203         push( @readings_off, $self->same_position_as( $reading, 1 ) )
1204             if $pos->fixed;
1205         # Any node that is an identical transposed one should be off.
1206         push( @readings_off, $reading->identical_readings );
1207     }
1208     @readings_off = unique_list( @readings_off );
1209         
1210     # Turn off the readings that need to be turned off.
1211     my @readings_delemmatized;
1212     foreach my $n ( @readings_off ) {
1213         my $npos = $n->position;
1214         my $state = undef;
1215         $state = $self->lemmata->{$npos->reference}
1216             if defined $self->lemmata->{$npos->reference};
1217         if( $state && $state eq $n->name ) { 
1218             # this reading is still on, so turn it off
1219             push( @readings_delemmatized, $n );
1220             my $new_state = undef;
1221             if( $npos->fixed && $n eq $reading ) {
1222                 # This is the reading that was clicked, so if there are no
1223                 # other readings there and this is a fixed position, turn off 
1224                 # the position.  In all other cases, restore the ellipsis.
1225                 my @other_n = $self->same_position_as( $n ); # TODO do we need strict?
1226                 $new_state = 0 unless @other_n;
1227             }
1228             $self->lemmata->{$npos->reference} = $new_state;
1229         } elsif( $old_state && $old_state eq $n->name ) { 
1230             # another reading has already been turned on here
1231             push( @readings_delemmatized, $n );
1232         } # else some other reading was on anyway, so pass.
1233     }
1234     return @readings_delemmatized;
1235 }
1236
1237 sub same_position_as {
1238     my( $self, $reading, $strict ) = @_;
1239     my $pos = $reading->position;
1240     my %onpath = ( $reading->name => 1 );
1241     # TODO This might not always be sufficient.  We really want to
1242     # exclude all readings on this one's path between its two
1243     # common points.
1244     map { $onpath{$_->name} = 1 } $reading->neighbor_readings;
1245     my @same = grep { !$onpath{$_->name} } 
1246         $self->readings_at_position( $reading->position, $strict );
1247     return @same;
1248 }
1249
1250 # Return the string that joins together a list of witnesses for
1251 # display on a single path.
1252 sub path_label {
1253     my $self = shift;
1254     return join( $self->wit_list_separator, @_ );
1255 }
1256
1257 sub witnesses_of_label {
1258     my( $self, $label ) = @_;
1259     my $regex = $self->wit_list_separator;
1260     my @answer = split( /\Q$regex\E/, $label );
1261     return @answer;
1262 }    
1263
1264 sub unique_list {
1265     my( @list ) = @_;
1266     my %h;
1267     map { $h{$_->name} = $_ } @list;
1268     return values( %h );
1269 }
1270
1271 sub add_hash_entry {
1272     my( $hash, $key, $entry ) = @_;
1273     if( exists $hash->{$key} ) {
1274         push( @{$hash->{$key}}, $entry );
1275     } else {
1276         $hash->{$key} = [ $entry ];
1277     }
1278 }
1279
1280 no Moose;
1281 __PACKAGE__->meta->make_immutable;