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