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