Interset/Tagset.pm untested

filter: Statementstmt 0.0% 0 / 179 Branchbran 0.0% 0 / 32 Conditioncond 0.0% 0 / 6 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 25 Podpod 0.0% 0 / 14 totaltotal 0.0% 0 / 256 CC 17 SCAR 27.8
CC
17
Cov
0%
create_merged_atom
42.0
test_tag
42.0
_build_permitted_structures
20.0
CRAP 16.0
1 # ABSTRACT: The root class for all physical tagsets covered by DZ Interset 2.0.
2 # Copyright © 2012, 2014 Dan Zeman <zeman@ufal.mff.cuni.cz>
3  
4 package Lingua::Interset::Tagset;
5 use strict;
6 use warnings;
7 our $VERSION = '3.015';
8  
9 use utf8;
10 use open ':utf8';
11 use namespace::autoclean;
12 use Moose;
13 use MooseX::SemiAffordanceAccessor; # attribute x is written using set_x($value) and read using x()
14 use Lingua::Interset::FeatureStructure;
15 use Lingua::Interset::Trie;
16 use Lingua::Interset::Atom;
17 use Lingua::Interset::SimpleAtom;
18  
19  
20  
21 has 'permitted_structures' => ( isa => 'Lingua::Interset::Trie', is => 'ro', builder => '_build_permitted_structures', lazy => 1 );
22 has 'permitted_values' => ( isa => 'HashRef', is => 'ro', builder => '_build_permitted_values', lazy => 1 );
23  
24  
25  
26 #------------------------------------------------------------------------------
27 # Returns the tagset id that should be set as the value of the 'tagset' feature
28 # during decoding. Every derived class must (re)define this method! The result
29 # should correspond to the last two parts in package name, lowercased.
30 # Specifically, it should be the ISO 639-2 language code, followed by '::' and
31 # a language-specific tagset id. Example: 'cs::multext'.
32 #------------------------------------------------------------------------------
33 sub get_tagset_id
34 {
35 confess("The get_tagset_id() method has not been redefined in a class derived from Lingua::Interset::Tagset");
36 }
37  
38  
39  
40 #------------------------------------------------------------------------------
41 # Decodes a physical tag (string) and returns the corresponding feature
42 # structure.
43 #------------------------------------------------------------------------------
44 sub decode
45 {
46 my $self = shift;
47 my $tag = shift;
48 confess('Not implemented. A derived class must provide implementation of the decode() method');
49 }
50  
51  
52  
53 #------------------------------------------------------------------------------
54 # Takes feature structure and returns the corresponding physical tag (string).
55 #------------------------------------------------------------------------------
56 sub encode
57 {
58 my $self = shift;
59 my $fs = shift; # Lingua::Interset::FeatureStructure
60 confess('Not implemented. A derived class must provide implementation of the encode() method');
61 }
62  
63  
64  
65 #------------------------------------------------------------------------------
66 # Takes feature structure and returns the corresponding physical tag (string).
67 # Unlike encode(), this method ensures that the result is a known tag of the
68 # target tagset. Positional tagsets allow in principle encoding feature-value
69 # combination that never occur in the original corpus but may make sense when
70 # converted from another tagset. Strict encoding can block this if desired.
71 # Note however, that using strict encoding may result in unnecessary loss or
72 # bias of information. For example, Interset says that it's the third person
73 # but strict encoding may realize that only first or second persons occur with
74 # the combination of values that have been processed before: then you will get
75 # the first person on the output!
76 #------------------------------------------------------------------------------
77 sub encode_strict
78 {
79 my $self = shift;
80 my $fs = shift; # Lingua::Interset::FeatureStructure
81 confess('Undefined Interset feature structure') if(!defined($fs));
82 # We are going to damage the feature structure so we should make its copy first.
83 # The caller may still need the original structure!
84 my $fs1 = $fs->duplicate();
85 my $permitted = $self->permitted_structures();
86 $fs1->enforce_permitted_values($permitted);
87 return $self->encode($fs1);
88 }
89  
90  
91  
92 #------------------------------------------------------------------------------
93 # Returns reference to list of known tags.
94 #------------------------------------------------------------------------------
95 sub list
96 {
97 my $self = shift;
98 confess('Not implemented. A derived class must provide implementation of the list() method');
99 }
100  
101  
102  
103 #------------------------------------------------------------------------------
104 # Creates an atomic driver and returns it. Derived classes may want to use
105 # atoms to define decoding and encoding of individual surface features.
106 #------------------------------------------------------------------------------
107 sub create_atom
108 {
109 my $self = shift;
110 my @parameters = (@_, 'tagset' => $self->get_tagset_id());
111 my $atom = Lingua::Interset::Atom->new(@parameters);
112 return $atom;
113 }
114  
115  
116  
117 #------------------------------------------------------------------------------
118 # Creates a simple atomic driver and returns it. Derived classes may want to use
119 # atoms to define decoding and encoding of individual surface features.
120 #------------------------------------------------------------------------------
121 sub create_simple_atom
122 {
123 my $self = shift;
124 my @parameters = (@_, 'tagset' => $self->get_tagset_id());
125 my $atom = Lingua::Interset::SimpleAtom->new(@parameters);
126 return $atom;
127 }
128  
129  
130  
131 #------------------------------------------------------------------------------
132 # Creates and returns an atomic driver with an empty encoding map and a huge
133 # decoding map that is a merger of decoding maps from other atomic drivers.
134 # Derived classes may want to use atoms to define decoding and encoding of
135 # individual surface features. If the feature values appear without feature
136 # names in the tags, we may need a huge decoding map for all the features, and
137 # many small encoding maps for individual features. It is advantageous to
138 # define the small atoms (both for decoding and encoding) and then merge them
139 # automatically and get the big decoding map.
140 #------------------------------------------------------------------------------
141 sub create_merged_atom
142 {
143 my $self = shift;
144 my @parameters = @_;
145 my %parameters = @parameters;
146 confess("The 'atoms' parameter is required") unless(defined($parameters{atoms}));
147 unless(defined($parameters{surfeature}))
148 {
149 $parameters{surfeature} = 'feature';
150 }
151 unless(defined($parameters{decode_map}))
152 {
153 $parameters{decode_map} = {};
154 }
155 unless(defined($parameters{encode_map}))
156 {
157 # The encoding map cannot be empty even if we are not going to use it.
158 $parameters{encode_map} = { 'pos' => {} };
159 }
160 my $atom = $self->create_atom(%parameters);
161 if(defined($parameters{atoms}))
162 {
163 $atom->merge_atoms(@{$parameters{atoms}});
164 }
165 return $atom;
166 }
167  
168  
169  
170 ###############################################################################
171 # COLLECTING PERMITTED FEATURE VALUES OF A TAGSET
172 ###############################################################################
173  
174  
175  
176 #------------------------------------------------------------------------------
177 # Filters a list of tags so that the resulting list contains only tags that
178 # can result from conversion from a different tagset. These tags do not depend
179 # on the 'other' feature. It is not to say that decoding them necessarily
180 # leaves the feature empty. However, these tags are default with respect to the
181 # feature, so if the feature is not available, encoder picks the default tag.
182 #
183 # Note that it is not guaranteed that the resulting list is a subset of the
184 # original list. It is possible, though undesirable, that decode -> strip other
185 # -> encode creates an unknown tag.
186 #------------------------------------------------------------------------------
187 sub list_other_resistant_tags
188 {
189 my $self = shift;
190 my $list0 = shift; # reference to array
191 my $decode = shift; # reference to driver-specific decoding function
192 my $encode = shift; # reference to driver-specific encoding function
193 my %result;
194 foreach my $tag0 (@{$list0})
195 {
196 my $fs = $self->decode($tag0);
197 $fs->set_other('');
198 my $tag1 = $self->encode($fs);
199 $result{$tag1}++;
200 }
201 my @list1 = sort(keys(%result));
202 return \@list1;
203 }
204  
205  
206  
207 #------------------------------------------------------------------------------
208 # Creates the trie description of all permitted feature structures (Lingua::
209 # Interset::Trie) and returns a reference to it. The trie is constructed lazily
210 # on the first demand. The builder reads the list of known tags, decodes each
211 # tag, converts all array values to scalars (by sorting and joining them) and
212 # remembers permitted feature structures in the trie.
213 #------------------------------------------------------------------------------
214 sub _build_permitted_structures
215 {
216 my $self = shift;
217 my $no_other = shift; ###!!!
218 # This is a lazy attribute and the builder can be called anytime, even
219 # from map() or grep(). Avoid damaging the caller's $_!
220 local $_;
221 my $list = $self->list();
222 # Make sure that the list of possible tags is not empty.
223 # If it is, the driver's list() function is probably not implemented.
224 unless(scalar(@{$list}))
225 {
226 confess('Cannot figure out the permitted values because the list of possible tags is empty');
227 }
228 my @features = Lingua::Interset::FeatureStructure::priority_features();
229 my $trie = Lingua::Interset::Trie->new('features' => \@features);
230 foreach my $tag (@{$list})
231 {
232 my $fs = $self->decode($tag);
233 # If required, skip tags that set the 'other' feature.
234 ###!!! Alternatively, we need not skip the tag.
235 ###!!! Instead, strip the 'other' information, make sure that we have a valid tag (by encoding and decoding once more),
236 ###!!! then add feature values to the tree.
237 next if($no_other && $fs->other());
238 # Loop over known features (in the order of feature priority).
239 my $pointer = $trie->root_hash();
240 foreach my $f (@features)
241 {
242 # Make sure the value is not an array.
243 my $v = $fs->get_joined($f);
244 # Supply tag only if this is the last feature in the list.
245 my $t = $f eq $features[$#features] ? $tag : undef;
246 $pointer = $trie->add_value($pointer, $v, $t);
247 }
248 }
249 return $trie;
250 }
251  
252  
253  
254 #------------------------------------------------------------------------------
255 # Creates a hash of permitted feature values for this tagset:
256 # ($hash{$feature}{$value} != 0) => tagset permits $value of $feature
257 # Note that a value that is permitted in one context may not be permitted in
258 # another. Unlike in permitted_structures, this hash just ignores context.
259 # The builder reads a list of tags, decodes each tag and remembers occurrences
260 # of feature values in the hash. It returns a reference to the hash.
261 #------------------------------------------------------------------------------
262 sub _build_permitted_values
263 {
264 my $self = shift;
265 # This is a lazy attribute and the builder can be called anytime, even
266 # from map() or grep(). Avoid damaging the caller's $_!
267 local $_;
268 my $list = $self->list();
269 # Make sure that the list of possible tags is not empty.
270 # If it is, probably the driver's list() function is not implemented.
271 unless(defined($list) && scalar(@{$list}))
272 {
273 confess('Cannot figure out the permitted values because the list of possible tags is empty');
274 }
275 my @features = Lingua::Interset::FeatureStructure::priority_features();
276 my %values;
277 foreach my $tag (@{$list})
278 {
279 my $fs = $self->decode($tag);
280 foreach my $f (@features)
281 {
282 # Make sure the value is always a list of values.
283 my @v = $fs->get_list($f);
284 foreach my $v (@v)
285 {
286 $values{$f}{$v}++;
287 }
288 }
289 }
290 return \%values;
291 }
292  
293  
294  
295 ###############################################################################
296 # TESTING AND DEBUGGING THE DRIVER
297 ###############################################################################
298  
299  
300  
301 #------------------------------------------------------------------------------
302 # Tells whether a tag is known to this tagset driver in the sense that it is
303 # returned by the list() method. Being an unknown tag does not mean that it
304 # cannot be decoded!
305 #------------------------------------------------------------------------------
306 sub is_known_tag
307 {
308 my $self = shift;
309 my $tag = shift;
310 ###!!! This test would be faster if we had a hash of known tags.
311 ###!!! (It will only matter for large tagsets if they are queried many times.)
312 ###!!! We could create a hash when this method is invoked the first time.
313 ###!!! Then we would keep it as a cache.
314 my $list = $self->list();
315 my $ok = grep {$_ eq $tag} (@{$list});
316 return $ok;
317 }
318  
319  
320  
321 #------------------------------------------------------------------------------
322 # Tests processing a particular tag (presumably a known one, from the list()
323 # method). Checks that decoding the tag sets only known features and values
324 # and that no information gets lost when we encode the feature structure again.
325 #------------------------------------------------------------------------------
326 sub test_tag
327 {
328 my $self = shift;
329 my $tag = shift;
330 # Optional reference to the variable where we count tags that set 'other'.
331 my $n_other = shift;
332 # Optional reference to the hash where we collect tags that survive removing the value of 'other'.
333 my $other_survivors = shift;
334 my @errors;
335 my $n_errors = 0;
336 # Decode the tag and create the Interset feature structure.
337 my $f = $self->decode($tag);
338 my $sfs = $f->as_string();
339 if($f->other() ne '')
340 {
341 ${$n_other}++;
342 # Non-empty other should be always accompanied by a non-empty tagset.
343 # (Actually we expect tagset to be never empty. But it is really needed only if the other feature is set.)
344 if($f->tagset() eq '')
345 {
346 my $message = "Error: nonempty other without specifying the source tagset\n";
347 $message .= " src = \"$tag\"\n";
348 $message .= " sfs = $sfs\n";
349 push(@errors, $message);
350 $n_errors++;
351 }
352 }
353 # Test that encode(decode(tag))=tag (reproducibility).
354 my $tag1 = $self->encode($f);
355 if($tag1 ne $tag)
356 {
357 my $message = "Error: encode(decode(x)) != x\n";
358 $message .= " src = \"$tag\"\n";
359 $message .= " tgt = \"$tag1\"\n";
360 $message .= " sfs = $sfs\n";
361 push(@errors, $message);
362 $n_errors++;
363 }
364 # Decoding a tag, removing information stored in the 'other' feature and
365 # encoding should render a known tag (a default one if the original tag cannot
366 # be completely restored because of the missing information). This is important
367 # for figuring out the permitted feature combinations when converting from a
368 # different tagset.
369 $f->set_tagset('');
370 $f->set_other('');
371 my $tag2 = $self->encode($f);
372 # Is the resulting tag known?
373 if(!$self->is_known_tag($tag2))
374 {
375 my $sfs2 = $f->as_string();
376 my $message = "Error: encode(decode(x)-other) gives an unknown tag\n";
377 $message .= " src = \"$tag\"\n";
378 $message .= " tgt = \"$tag2\"\n";
379 $message .= " sfo = $sfs\n";
380 $message .= " sfs = $sfs2\n";
381 push(@errors, $message);
382 $n_errors++;
383 }
384 elsif(defined($other_survivors))
385 {
386 $other_survivors->{$tag2}++;
387 }
388 return @errors;
389 }
390  
391  
392  
393 #------------------------------------------------------------------------------
394 # Takes all tags in the tagset and tests their processing by the driver.
395 # Returns a list of printable error messages. An empty list means the test was
396 # passed successfully.
397 #------------------------------------------------------------------------------
398 sub test
399 {
400 my $self = shift;
401 my $list = $self->list();
402 my @errors;
403 foreach my $tag (@{$list})
404 {
405 my @tag_errors = $self->test_tag($tag);
406 push(@errors, @tag_errors) if(@tag_errors);
407 }
408 return @errors;
409 }
410  
411  
412  
413 1;
414  
415 __END__
416  
417 =pod
418  
419 =encoding UTF-8
420  
421 =head1 NAME
422  
423 Lingua::Interset::Tagset - The root class for all physical tagsets covered by DZ Interset 2.0.
424  
425 =head1 VERSION
426  
427 version 3.015
428  
429 =head1 SYNOPSIS
430  
431 package Lingua::Interset::MY::Tagset;
432 use Moose;
433 extends 'Lingua::Interset::Tagset';
434 use Lingua::Interset::FeatureStructure;
435  
436 sub decode
437 {
438 my $self = shift;
439 my $tag = shift;
440 my $fs = Lingua::Interset::FeatureStructure->new();
441 ...
442 return $fs;
443 }
444  
445 sub encode
446 {
447 my $self = shift;
448 my $fs = shift; # Lingua::Interset::FeatureStructure
449 my $tag;
450 ...
451 return $tag;
452 }
453  
454 sub list
455 {
456 my $self = shift;
457 return ['NOUN', 'VERB', 'OTHER'];
458 }
459  
460 1;
461  
462 =head1 DESCRIPTION
463  
464 DZ Interset is a universal framework for reading, writing, converting and
465 interpreting part-of-speech and morphosyntactic tags from multiple tagsets
466 of many different natural languages.
467  
468 The C<Tagset> class is the inheritance root for all classes describing
469 physical tagsets (sets of strings of characters). It defines decoding of tags, encoding
470 and list of known tags.
471  
472 =head1 ATTRIBUTES
473  
474 =head2 permitted_structures
475  
476 A L<Lingua::Interset::Trie> object that represents all feature structures
477 permitted by this tagset. These are structures that result from decoding
478 one of the I<known tags> returned by the C<list()> method.
479  
480 This data structure is used to implement strict encoding (see the C<encode_strict()> method).
481  
482 =head2 permitted_values
483  
484 Reference to a hash that contains all feature values set by the C<decode()> method
485 for at least one of the I<known tags>.
486 If the tagset permits C<$value> of C<$feature>, then
487  
488 $driver->permitted_values->{$feature}{$value} != 0
489  
490 Note that a value that is permitted in one context may not be permitted in
491 another.
492 (For example, I<plural number> could be allowed for a I<noun> but not for an I<adverb>.)
493 Unlike in C<permitted_structures>, this hash just ignores context.
494  
495 =head1 METHODS
496  
497 =head2 get_tagset_id()
498  
499 Returns the tagset id that should be set as the value of the 'tagset' feature
500 during decoding. Every derived class must implement this method, even though
501 the derived class is also responsible for setting the value in its C<decode()>
502 method.
503  
504 The ID should correspond to the last two parts in package name, lowercased.
505 Specifically, it should be the ISO 639-2 language, followed by C<::>
506 and a language-specific tagset ID. Example: C<cs::multext>.
507  
508 =head2 decode()
509  
510 my $fs = $driver->decode ($tag);
511  
512 Takes a tag (string) and returns a L<Lingua::Interset::FeatureStructure> object
513 with corresponding feature values set.
514  
515 Every derived class must implement this method.
516 The C<Tagset> class contains an empty implementation,
517 which will throw an exception if inherited and called.
518  
519 =head2 encode()
520  
521 my $tag = $driver->encode ($fs);
522  
523 Takes a L<Lingua::Interset::FeatureStructure> object and
524 returns the tag (string) in the given tagset that corresponds to the feature values.
525 Note that some features may be ignored because they cannot be represented
526 in the given tagset.
527  
528 Every derived class must implement this method.
529 The C<Tagset> class contains an empty implementation,
530 which will throw an exception if inherited and called.
531  
532 =head2 encode_strict()
533  
534 my $tag = $driver->encode_strict ($fs);
535  
536 Takes a feature structure (L<Lingua::Interset::FeatureStructure>) and
537 returns a tag that matches the contents of the feature structure.
538  
539 Unlike C<encode()>, C<encode_strict()> always returns a I<known tag>, i.e.
540 one that is returned by the C<list()> method of the Tagset object. Many tagsets
541 consist of I<structured> tags, i.e. they can be defined as a compact representation
542 of a feature structure (a set of attribute-value pairs). It is in principle possible
543 to encode such combinations of features and values that did not appear in the original
544 tagset. For example, a tagset for Czech is unlikely to contain a tag saying that
545 a word is preposition and at the same time setting non-empty value for gender.
546 Yet it is possible to create such a tag because the tagset encodes part of speech
547 and gender independently.
548  
549 If this is undesirable behavior, the application should call C<encode_strict()>
550 instead of C<encode()>. Then it will be guaranteed that the resulting tag is one
551 of those returned by C<list()>. Nevertheless, think twice whether you really need
552 the guarantee, as it does not come for free. The necessity to replace forbidden
553 feature values by permitted ones may sometimes lead to surprising or confusing
554 results.
555  
556 This method is implemented directly within the C<Tagset> class,
557 relying on custom implementations of C<list()>, C<decode()> and C<encode()>.
558  
559 =head2 list()
560  
561 my $list_of_tags = $driver->list();
562  
563 Returns the reference to the list of all known tags in this particular tagset.
564 This is not directly needed to decode, encode or convert tags but it is very useful
565 for testing and advanced operations over the tagset.
566 Note however that many tagset drivers contain only an approximate list,
567 created by collecting tag occurrences in some corpus.
568  
569 Every derived class must implement this method.
570 The C<Tagset> class contains an empty implementation,
571 which will throw an exception if inherited and called.
572  
573 =head1 SEE ALSO
574  
575 L<Lingua::Interset>,
576 L<Lingua::Interset::FeatureStructure>,
577 L<Lingua::Interset::Trie>
578  
579 =head1 AUTHOR
580  
581 Dan Zeman <zeman@ufal.mff.cuni.cz>
582  
583 =head1 COPYRIGHT AND LICENSE
584  
585 This software is copyright (c) 2019 by Univerzita Karlova (Charles University).
586  
587 This is free software; you can redistribute it and/or modify it under
588 the same terms as the Perl 5 programming language system itself.
589  
590 =cut