remove edge weight logic in dot; add adjacency list JSON output
[scpubgit/stemmatology.git] / base / lib / Text / Tradition.pm
CommitLineData
dd3b58b0 1package Text::Tradition;
2
65ed66b9 3use JSON qw / from_json /;
4a8828f0 4use Module::Load;
dd3b58b0 5use Moose;
951ddfe8 6use Moose::Util qw/ does_role apply_all_roles /;
4889be4f 7use Safe::Isa;
8e1394aa 8use Text::Tradition::Collation;
951ddfe8 9use Text::Tradition::Error;
8e1394aa 10use Text::Tradition::Witness;
951ddfe8 11use TryCatch;
dd3b58b0 12
331c2dbf 13use vars qw( $VERSION );
ed09db2f 14$VERSION = "1.3";
37bf09f4 15
16# Enable plugin(s) if available
17eval { with 'Text::Tradition::HasStemma'; };
ed5b9b70 18# Don't warn normally
19# if( $@ ) {
20# warn "Text::Tradition::Analysis not found. Disabling stemma analysis functionality";
21# };
e92d4229 22eval { with 'Text::Tradition::Language'; };
8943ff68 23eval { with 'Text::Tradition::Ownership'; };
331c2dbf 24
dd3b58b0 25has 'collation' => (
8e1394aa 26 is => 'ro',
27 isa => 'Text::Tradition::Collation',
28 writer => '_save_collation',
29 );
dd3b58b0 30
3b853983 31has 'witness_hash' => (
32 traits => ['Hash'],
33 isa => 'HashRef[Text::Tradition::Witness]',
8e1394aa 34 handles => {
3b853983 35 witness => 'get',
36 add_witness => 'set',
37 del_witness => 'delete',
38 has_witness => 'exists',
39 witnesses => 'values',
8e1394aa 40 },
3b853983 41 default => sub { {} },
8e1394aa 42 );
c5104dc0 43
df6d9812 44has 'name' => (
45 is => 'rw',
46 isa => 'Str',
47 default => 'Tradition',
48 );
56cf65bd 49
3579c22b 50has '_initialized' => (
10943ab0 51 is => 'ro',
52 isa => 'Bool',
53 default => undef,
54 writer => '_init_done',
55 );
56
4889be4f 57# Create the witness if necessary before trying to add it
910a0a6d 58around 'add_witness' => sub {
59 my $orig = shift;
60 my $self = shift;
4889be4f 61 my $new_wit;
62 if( @_ == 1 && $_[0]->$_isa( 'Text::Tradition::Witness' ) ) {
63 $new_wit = shift;
64 } else {
65 my %args = @_ == 1 ? %{$_[0]} : @_;
66 $args{'tradition'} = $self;
67 $new_wit = Text::Tradition::Witness->new( %args );
68 }
3b853983 69 $self->$orig( $new_wit->sigil => $new_wit );
910a0a6d 70 return $new_wit;
71};
331c2dbf 72
3b853983 73# Allow deletion of witness by object as well as by sigil
74around 'del_witness' => sub {
75 my $orig = shift;
76 my $self = shift;
77 my @key_args;
78 foreach my $arg ( @_ ) {
79 push( @key_args,
80 ref( $arg ) eq 'Text::Tradition::Witness' ? $arg->sigil : $arg );
81 }
82 return $self->$orig( @key_args );
83};
84
85# Don't allow an empty hash value
86around 'witness' => sub {
87 my( $orig, $self, $arg ) = @_;
88 return unless $self->has_witness( $arg );
89 return $self->$orig( $arg );
90};
91
4889be4f 92# Cope with witness sigil changes
93sub rename_witness {
94 my( $self, $sig, $newsig ) = @_;
4889be4f 95 my $wit = $self->witness( $sig );
96 $self->throw( "No such witness $sig" ) unless $wit;
97 $self->throw( "Cannot rename witness that has already been collated" )
98 if $wit->is_collated;
99 $wit = $self->del_witness( $sig );
100 try {
101 $wit->_set_sigil( $newsig );
102 } catch ( $e ) {
103 # Don't lose the witness if the rename failed
104 $self->add_witness( $wit );
105 $self->throw( $e );
106 }
107 $self->add_witness( $wit );
108}
109
331c2dbf 110=head1 NAME
111
112Text::Tradition - a software model for a set of collated texts
113
114=head1 SYNOPSIS
115
116 use Text::Tradition;
117 my $t = Text::Tradition->new(
118 'name' => 'this is a text',
119 'input' => 'TEI',
120 'file' => '/path/to/tei_parallel_seg_file.xml' );
121
122 my @text_wits = $t->witnesses();
123 my $manuscript_a = $t->witness( 'A' );
82fa4d57 124
125 $t = Text::Tradition->new();
126 $t->add_witness( 'sourcetype' => 'xmldesc',
127 'file' => '/path/to/teitranscription.xml' );
128 $t->add_witness( 'sourcetype => 'plaintext', 'sigil' => 'Q',
129 'string' => 'The quick brown fox jumped over the lazy dogs' );
130 ## TODO
131 $t->collate_texts;
331c2dbf 132
133 my $text_path_svg = $t->collation->as_svg();
134 ## See Text::Tradition::Collation for more on text collation itself
135
136=head1 DESCRIPTION
137
138Text::Tradition is a library for representation and analysis of collated
139texts, particularly medieval ones. A 'tradition' refers to the aggregation
140of surviving versions of a text, generally preserved in multiple
141manuscripts (or 'witnesses'). A Tradition object thus has one more more
142Witnesses, as well as a Collation that represents the unity of all versions
143of the text.
144
145=head1 METHODS
146
147=head2 new
148
149Creates and returns a new text tradition object. The following options are
150accepted.
151
152General options:
153
154=over 4
155
156=item B<name> - The name of the text.
157
158=back
159
160Initialization based on a collation file:
161
162=over 4
163
164=item B<input> - The input format of the collation file. Can be one of the
165following:
166
167=over 4
168
169=item * Self - a GraphML format produced by this module
170
171=item * CollateX - a GraphML format produced by CollateX
172
173=item * CTE - a TEI XML format produced by Classical Text Editor
174
a445ce40 175=item * JSON - an alignment table in JSON format, as produced by CollateX and
176other tools
331c2dbf 177
178=item * TEI - a TEI parallel segmentation format file
179
a445ce40 180=item * Tabular - a spreadsheet collation. See the documentation for
181L<Text::Tradition::Parser::Tabular> for an explanation of additional options.
331c2dbf 182
183=back
184
185=item B<file> - The name of the file that contains the data. One of 'file'
186or 'string' should be specified.
187
188=item B<string> - A text string that contains the data. One of 'file' or
189'string' should be specified.
190
331c2dbf 191=back
192
193Initialization based on a list of witnesses [NOT YET IMPLEMENTED]:
194
195=over 4
196
197=item B<witnesses> - A reference to an array of Text::Tradition::Witness
198objects that carry the text to be collated.
199
200=item B<collator> - A reference to a collation program that will accept
201Witness objects.
202
203=back
204
205=head2 B<witnesses>
206
207Return the Text::Tradition::Witness objects associated with this tradition,
208as an array.
209
044d1e45 210=head2 B<witness>( $sigil )
211
212Returns the Text::Tradition::Witness object whose sigil is $sigil, or undef
213if there is no such object within the tradition.
214
331c2dbf 215=head2 B<add_witness>( %opts )
216
217Instantiate a new witness with the given options (see documentation for
218Text::Tradition::Witness) and add it to the tradition.
219
044d1e45 220=head2 B<del_witness>( $sigil )
221
222Delete the witness with the given sigil from the tradition. Returns the
223witness object for the deleted witness.
224
b34fd19d 225=head2 B<rename_witness>( $oldsigil, $newsigil )
226
227Safely rename (i.e., assign a new sigil to) the given witness. At the moment
228this can only be done when the witness does not yet appear in the collation.
229
331c2dbf 230=begin testing
231
4889be4f 232use TryCatch;
331c2dbf 233use_ok( 'Text::Tradition', "can use module" );
234
235my $t = Text::Tradition->new( 'name' => 'empty' );
236is( ref( $t ), 'Text::Tradition', "initialized an empty Tradition object" );
237is( $t->name, 'empty', "object has the right name" );
238is( scalar $t->witnesses, 0, "object has no witnesses" );
239
240my $simple = 't/data/simple.txt';
241my $s = Text::Tradition->new(
242 'name' => 'inline',
243 'input' => 'Tabular',
244 'file' => $simple,
245 );
246is( ref( $s ), 'Text::Tradition', "initialized a Tradition object" );
247is( $s->name, 'inline', "object has the right name" );
248is( scalar $s->witnesses, 3, "object has three witnesses" );
249
044d1e45 250my $wit_a = $s->witness('A');
251is( ref( $wit_a ), 'Text::Tradition::Witness', "Found a witness A" );
252if( $wit_a ) {
253 is( $wit_a->sigil, 'A', "Witness A has the right sigil" );
254}
255is( $s->witness('X'), undef, "There is no witness X" );
256ok( !exists $s->{'witnesses'}->{'X'}, "Witness key X not created" );
257
4889be4f 258my $wit_d = $s->add_witness( 'sigil' => 'D', 'sourcetype' => 'plaintext',
259 'string' => 'je suis depourvu de foi' );
044d1e45 260is( ref( $wit_d ), 'Text::Tradition::Witness', "new witness created" );
261is( $wit_d->sigil, 'D', "witness has correct sigil" );
331c2dbf 262is( scalar $s->witnesses, 4, "object now has four witnesses" );
263
4889be4f 264try {
265 $s->rename_witness( 'D', 'Invalid Sigil' );
266 ok( 0, "Renamed witness with bad sigil" );
267} catch ( Text::Tradition::Error $e ) {
4889be4f 268 is( $s->witness('D'), $wit_d, "Held onto witness during bad rename" );
269}
270
271try {
272 $s->rename_witness( 'D', 'Q' );
273 ok( 1, "Rename of witness succeeded" );
274 is( $s->witness('Q'), $wit_d, "Witness available under new sigil" );
275 ok( !$s->has_witness('D'), "Witness no longer available under old sigil" );
276} catch ( Text::Tradition::Error $e ) {
277 ok( 0, "Failed to rename witness: " . $e->message );
278}
279
280my $del = $s->del_witness( 'Q' );
044d1e45 281is( $del, $wit_d, "Deleted correct witness" );
3b853983 282is( scalar $s->witnesses, 3, "object has three witnesses again" );
283
4889be4f 284try {
285 $s->rename_witness( 'A', 'WitA' );
286 ok( 0, "Successfully renamed an already collated witness" );
287} catch ( Text::Tradition::Error $e ) {
288 is( $e->message, 'Cannot rename witness that has already been collated',
289 "Refused to rename an already-collated witness" );
290}
331c2dbf 291
292=end testing
293
294=cut
910a0a6d 295
df6d9812 296
8e1394aa 297sub BUILD {
298 my( $self, $init_args ) = @_;
fae52efd 299
300 # First, make a collation object. This will use only those arguments in
301 # init_args that apply to the collation.
302 my $collation = Text::Tradition::Collation->new( %$init_args,
303 'tradition' => $self );
304 $self->_save_collation( $collation );
c5104dc0 305
fae52efd 306 if( exists $init_args->{'input'} ) {
910a0a6d 307 # Call the appropriate parser on the given data
a731e73a 308 my @format_standalone = qw/ Self CollateText CollateX CTE JSON TEI Tabular /;
dfc37e38 309 my @format_basetext = qw/ KUL /;
310 my $use_base;
311 my $format = $init_args->{'input'};
dfc37e38 312 if( $format && !( grep { $_ eq $format } @format_standalone )
313 && !( grep { $_ eq $format } @format_basetext ) ) {
314 warn "Unrecognized input format $format; not parsing";
910a0a6d 315 return;
316 }
dfc37e38 317 if( $format && grep { $_ eq $format } @format_basetext ) {
318 $use_base = 1;
319 if( !exists $init_args->{'base'} ) {
320 warn "Cannot make a collation from $format without a base text";
321 return;
322 }
323 }
4a8828f0 324
910a0a6d 325 # Now do the parsing.
910a0a6d 326 if( $format ) {
dfc37e38 327 if( $use_base ) {
328 $format = 'BaseText'; # Use the BaseText module for parsing,
329 # but retain the original input arg.
910a0a6d 330 }
331 my $mod = "Text::Tradition::Parser::$format";
332 load( $mod );
dfc37e38 333 $mod->can('parse')->( $self, $init_args );
910a0a6d 334 }
c5104dc0 335 }
10943ab0 336 $self->_init_done( 1 );
fae52efd 337 return $self;
338}
339
d1a7f940 340=head2 clear_collation
341
342Blow away the existing collation object and mark all witnesses as uncollated.
343Not to be used lightly.
344
345=cut
346
347sub clear_collation {
348 my $self = shift;
349 $self->_save_collation( Text::Tradition::Collation->new( tradition => $self ) );
350 map { $_->is_collated( 0 ) } $self->witnesses;
351}
352
fae52efd 353=head2 add_json_witnesses( $jsonstring, $options )
354
355Adds a set of witnesses from a JSON array specification. This is a wrapper
356to parse the JSON and call add_witness (with the specified $options) for
357each element therein.
358
359=cut
360
361sub add_json_witnesses {
362 my( $self, $jsonstr, $extraopts ) = @_;
65ed66b9 363 my $witarray = from_json( $jsonstr );
364 foreach my $witspec ( @{$witarray->{witnesses}} ) {
fae52efd 365 my $opts = $extraopts || {};
366 $opts->{'sourcetype'} = 'json';
367 $opts->{'object'} = $witspec;
368 $self->add_witness( $opts );
369 }
8e1394aa 370}
c5104dc0 371
951ddfe8 372sub throw {
142698b8 373 my $self = shift;
951ddfe8 374 Text::Tradition::Error->throw(
375 'ident' => 'Tradition error',
376 'message' => $_[0],
377 );
378}
379
dd3b58b0 380no Moose;
381__PACKAGE__->meta->make_immutable;
331c2dbf 382
383
384=head1 BUGS / TODO
385
386=over
387
388=item * Allow tradition to be initialized via passing to a collator.
389
390=back
391
392=head1 LICENSE
393
394This package is free software and is provided "as is" without express
395or implied warranty. You can redistribute it and/or modify it under
396the same terms as Perl itself.
397
398=head1 AUTHOR
399
400Tara L Andrews E<lt>aurum@cpan.orgE<gt>