fix some subgraph rendering issues
[scpubgit/stemmatology.git] / lib / Text / Tradition.pm
1 package Text::Tradition;
2
3 use JSON qw / from_json /;
4 use Module::Load;
5 use Moose;
6 use Text::Tradition::Collation;
7 use Text::Tradition::Stemma;
8 use Text::Tradition::Witness;
9
10 use vars qw( $VERSION );
11 $VERSION = "0.5";
12
13 has 'collation' => (
14     is => 'ro',
15     isa => 'Text::Tradition::Collation',
16     writer => '_save_collation',
17     );
18
19 has 'witness_hash' => (
20     traits => ['Hash'],
21     isa => 'HashRef[Text::Tradition::Witness]',
22     handles => {
23         witness     => 'get',
24         add_witness => 'set',
25         del_witness => 'delete',
26         has_witness => 'exists',
27         witnesses   => 'values',
28     },
29     default => sub { {} },
30     );
31
32 has 'name' => (
33     is => 'rw',
34     isa => 'Str',
35     default => 'Tradition',
36     );
37     
38 has 'language' => (
39         is => 'rw',
40         isa => 'Str',
41         predicate => 'has_language',
42         );
43     
44 has 'stemmata' => (
45         traits => ['Array'],
46         isa => 'ArrayRef[Text::Tradition::Stemma]',
47         handles => {
48                 stemmata => 'elements',
49                 _add_stemma => 'push',
50                 stemma => 'get',
51                 stemma_count => 'count',
52                 clear_stemmata => 'clear',
53         },
54         default => sub { [] },
55         );
56   
57 has '_initialized' => (
58         is => 'ro',
59         isa => 'Bool',
60         default => undef,
61         writer => '_init_done',
62         ); 
63
64 # Create the witness before trying to add it
65 around 'add_witness' => sub {
66     my $orig = shift;
67     my $self = shift;
68     # TODO allow add of a Witness object?
69     my %args = @_ == 1 ? %{$_[0]} : @_;
70     $args{'tradition'} = $self;
71     $args{'language'} = $self->language 
72         if( $self->language && !exists $args{'language'} );
73     my $new_wit = Text::Tradition::Witness->new( %args );
74     $self->$orig( $new_wit->sigil => $new_wit );
75     return $new_wit;
76 };
77
78 # Allow deletion of witness by object as well as by sigil
79 around 'del_witness' => sub {
80     my $orig = shift;
81     my $self = shift;
82     my @key_args;
83     foreach my $arg ( @_ ) {
84         push( @key_args, 
85               ref( $arg ) eq 'Text::Tradition::Witness' ? $arg->sigil : $arg );
86     }
87     return $self->$orig( @key_args );
88 };
89
90 # Don't allow an empty hash value
91 around 'witness' => sub {
92     my( $orig, $self, $arg ) = @_;
93     return unless $self->has_witness( $arg );
94     return $self->$orig( $arg );
95 };
96
97 =head1 NAME
98
99 Text::Tradition - a software model for a set of collated texts
100
101 =head1 SYNOPSIS
102
103   use Text::Tradition;
104   my $t = Text::Tradition->new( 
105     'name' => 'this is a text',
106     'input' => 'TEI',
107     'file' => '/path/to/tei_parallel_seg_file.xml' );
108
109   my @text_wits = $t->witnesses();
110   my $manuscript_a = $t->witness( 'A' );
111
112   $t = Text::Tradition->new();
113   $t->add_witness( 'sourcetype' => 'xmldesc', 
114     'file' => '/path/to/teitranscription.xml' );
115   $t->add_witness( 'sourcetype => 'plaintext', 'sigil' => 'Q',
116     'string' => 'The quick brown fox jumped over the lazy dogs' );
117   ## TODO
118   $t->collate_texts;
119   
120   my $text_path_svg = $t->collation->as_svg();
121   ## See Text::Tradition::Collation for more on text collation itself
122     
123 =head1 DESCRIPTION
124
125 Text::Tradition is a library for representation and analysis of collated
126 texts, particularly medieval ones.  A 'tradition' refers to the aggregation
127 of surviving versions of a text, generally preserved in multiple
128 manuscripts (or 'witnesses').  A Tradition object thus has one more more
129 Witnesses, as well as a Collation that represents the unity of all versions
130 of the text.
131
132 =head1 METHODS
133
134 =head2 new
135
136 Creates and returns a new text tradition object.  The following options are
137 accepted.
138
139 General options:
140
141 =over 4
142
143 =item B<name> - The name of the text.
144
145 =back
146
147 Initialization based on a collation file:
148
149 =over 4
150
151 =item B<input> - The input format of the collation file.  Can be one of the
152 following:
153
154 =over 4
155
156 =item * Self - a GraphML format produced by this module
157
158 =item * CollateX - a GraphML format produced by CollateX
159
160 =item * CTE - a TEI XML format produced by Classical Text Editor
161
162 =item * JSON - an alignment table in JSON format, as produced by CollateX and other tools
163
164 =item * KUL - a specific CSV format for variants, not documented here
165
166 =item * TEI - a TEI parallel segmentation format file
167
168 =item * Tabular - a comma- or tab-separated collation.  Takes an additional
169 option, 'sep_char', which defaults to the tab character.
170
171 =back
172
173 =item B<file> - The name of the file that contains the data.  One of 'file'
174 or 'string' should be specified.
175
176 =item B<string> - A text string that contains the data.  One of 'file' or
177 'string' should be specified.
178
179 =item B<base> - The name of a text file that contains the base text, to be
180 used with input formats that require it (currently only KUL).
181
182 =back
183
184 Initialization based on a list of witnesses [NOT YET IMPLEMENTED]:
185
186 =over 4
187
188 =item B<witnesses> - A reference to an array of Text::Tradition::Witness
189 objects that carry the text to be collated.
190
191 =item B<collator> - A reference to a collation program that will accept
192 Witness objects.
193
194 =back
195
196 =head2 B<witnesses>
197
198 Return the Text::Tradition::Witness objects associated with this tradition,
199 as an array.
200
201 =head2 B<witness>( $sigil )
202
203 Returns the Text::Tradition::Witness object whose sigil is $sigil, or undef
204 if there is no such object within the tradition.
205
206 =head2 B<add_witness>( %opts )
207
208 Instantiate a new witness with the given options (see documentation for
209 Text::Tradition::Witness) and add it to the tradition.
210
211 =head2 B<del_witness>( $sigil )
212
213 Delete the witness with the given sigil from the tradition.  Returns the
214 witness object for the deleted witness.
215
216 =begin testing
217
218 use_ok( 'Text::Tradition', "can use module" );
219
220 my $t = Text::Tradition->new( 'name' => 'empty' );
221 is( ref( $t ), 'Text::Tradition', "initialized an empty Tradition object" );
222 is( $t->name, 'empty', "object has the right name" );
223 is( scalar $t->witnesses, 0, "object has no witnesses" );
224
225 my $simple = 't/data/simple.txt';
226 my $s = Text::Tradition->new( 
227     'name'  => 'inline', 
228     'input' => 'Tabular',
229     'file'  => $simple,
230     );
231 is( ref( $s ), 'Text::Tradition', "initialized a Tradition object" );
232 is( $s->name, 'inline', "object has the right name" );
233 is( scalar $s->witnesses, 3, "object has three witnesses" );
234
235 my $wit_a = $s->witness('A');
236 is( ref( $wit_a ), 'Text::Tradition::Witness', "Found a witness A" );
237 if( $wit_a ) {
238     is( $wit_a->sigil, 'A', "Witness A has the right sigil" );
239 }
240 is( $s->witness('X'), undef, "There is no witness X" );
241 ok( !exists $s->{'witnesses'}->{'X'}, "Witness key X not created" );
242
243 my $wit_d = $s->add_witness( 'sigil' => 'D', 'sourcetype' => 'collation' );
244 is( ref( $wit_d ), 'Text::Tradition::Witness', "new witness created" );
245 is( $wit_d->sigil, 'D', "witness has correct sigil" );
246 is( scalar $s->witnesses, 4, "object now has four witnesses" );
247
248 my $del = $s->del_witness( 'D' );
249 is( $del, $wit_d, "Deleted correct witness" );
250 is( scalar $s->witnesses, 3, "object has three witnesses again" );
251
252 # TODO test initialization by witness list when we have it
253
254 =end testing
255
256 =cut
257     
258
259 sub BUILD {
260     my( $self, $init_args ) = @_;
261     
262     # First, make a collation object. This will use only those arguments in
263     # init_args that apply to the collation.
264         my $collation = Text::Tradition::Collation->new( %$init_args,
265                                                                                                         'tradition' => $self );
266         $self->_save_collation( $collation );
267
268     if( exists $init_args->{'input'} ) {
269         # Call the appropriate parser on the given data
270         my @format_standalone = qw/ Self CollateText CollateX CTE JSON TEI Tabular /;
271         my @format_basetext = qw/ KUL /;
272         my $use_base;
273         my $format = $init_args->{'input'};
274         if( $format && !( grep { $_ eq $format } @format_standalone )
275             && !( grep { $_ eq $format } @format_basetext ) ) {
276             warn "Unrecognized input format $format; not parsing";
277             return;
278         }
279         if( $format && grep { $_ eq $format } @format_basetext ) {
280             $use_base = 1;
281             if( !exists $init_args->{'base'} ) {
282                 warn "Cannot make a collation from $format without a base text";
283                 return;
284             }
285         }
286
287         # Now do the parsing. 
288         if( $format ) {
289             if( $use_base ) { 
290                 $format = 'BaseText';   # Use the BaseText module for parsing,
291                                         # but retain the original input arg.
292             }
293             my $mod = "Text::Tradition::Parser::$format";
294             load( $mod );
295             $mod->can('parse')->( $self, $init_args );
296         }
297     }
298     $self->_init_done( 1 );
299     return $self;
300 }
301
302 =head2 add_json_witnesses( $jsonstring, $options )
303
304 Adds a set of witnesses from a JSON array specification. This is a wrapper
305 to parse the JSON and call add_witness (with the specified $options) for
306 each element therein.
307
308 =cut
309
310 sub add_json_witnesses {
311         my( $self, $jsonstr, $extraopts ) = @_;
312         my $witarray = from_json( $jsonstr );
313         foreach my $witspec ( @{$witarray->{witnesses}} ) {
314                 my $opts = $extraopts || {};
315                 $opts->{'sourcetype'} = 'json';
316                 $opts->{'object'} = $witspec;
317                 $self->add_witness( $opts );
318         }
319 }
320
321 =head2 add_stemma( $dotfile )
322
323 Initializes a Text::Tradition::Stemma object from the given dotfile,
324 and associates it with the tradition.
325
326 =begin testing
327
328 use Text::Tradition;
329
330 my $t = Text::Tradition->new( 
331     'name'  => 'simple test', 
332     'input' => 'Tabular',
333     'file'  => 't/data/simple.txt',
334     );
335
336 is( $t->stemma_count, 0, "No stemmas added yet" );
337 my $s;
338 ok( $s = $t->add_stemma( dotfile => 't/data/simple.dot' ), "Added a simple stemma" );
339 is( ref( $s ), 'Text::Tradition::Stemma', "Got a stemma object returned" );
340 is( $t->stemma_count, 1, "Tradition claims to have a stemma" );
341 is( $t->stemma(0), $s, "Tradition hands back the right stemma" );
342
343 =end testing
344
345 =cut
346
347 sub add_stemma {
348         my $self = shift;
349         my %opts = @_;
350         my $stemma_fh;
351         if( $opts{'dotfile'} ) {
352                 open $stemma_fh, '<', $opts{'dotfile'}
353                         or warn "Could not open file " . $opts{'dotfile'};
354         } elsif( $opts{'dot'} ) {
355                 my $str = $opts{'dot'};
356                 open $stemma_fh, '<', \$str;
357         }
358         # Assume utf-8
359         binmode $stemma_fh, ':utf8';
360         my $stemma = Text::Tradition::Stemma->new( 
361                 'collation' => $self->collation,
362                 'dot' => $stemma_fh );
363         $self->_add_stemma( $stemma ) if $stemma;
364         return $stemma;
365 }
366
367 sub lemmatize {
368         my $self = shift;
369         unless( $self->has_language ) {
370                 warn "Please set a language to lemmatize a tradition";
371                 return;
372         }
373         my $mod = "Text::Tradition::Language::" . $self->language;
374         load( $mod );
375         $mod->can( 'lemmatize' )->( $self );
376 }
377
378 no Moose;
379 __PACKAGE__->meta->make_immutable;
380
381
382 =head1 BUGS / TODO
383
384 =over
385
386 =item * Allow tradition to be initialized via passing to a collator.
387
388 =back
389
390 =head1 LICENSE
391
392 This package is free software and is provided "as is" without express
393 or implied warranty.  You can redistribute it and/or modify it under
394 the same terms as Perl itself.
395
396 =head1 AUTHOR
397
398 Tara L Andrews E<lt>aurum@cpan.orgE<gt>