Interset/Atom.pm untested

filter: Statementstmt 0.0% 0 / 172 Branchbran 0.0% 0 / 38 Conditioncond 0.0% 0 / 9 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 20 Podpod 0.0% 0 / 11 totaltotal 0.0% 0 / 250 CC 20 SCAR 31.2
CC
20
Cov
0%
_encoding_step
72.0
_get_decision_for_value
30.0
decode
12.0
CRAP 22.7
1 # ABSTRACT: Atomic driver for a surface feature.
2 # Copyright © 2014 Dan Zeman <zeman@ufal.mff.cuni.cz>
3  
4 package Lingua::Interset::Atom;
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;
15 use Lingua::Interset::FeatureStructure qw(feature_valid);
16 extends 'Lingua::Interset::Tagset';
17  
18  
19  
20 has 'surfeature' => ( isa => 'Str', is => 'ro', required => 1, documentation => 'Name of the surface feature the atom describes.' );
21 # Example of a decoding map:
22 # { 'M' => ['gender' => 'masc', 'animateness' => 'anim'],
23 # 'I' => ['gender' => 'masc', 'animateness' => 'inan'],
24 # 'F' => ['gender' => 'fem'],
25 # 'N' => ['gender' => 'neut'] }
26 has 'decode_map' => ( isa => 'HashRef', is => 'ro', required => 1 );
27 # Example of an encoding map:
28 # The top-level hash must have just one key, a name of a known feature (it is a hash for cosmetic reasons).
29 # '@' denotes the default and will be translated to an else block
30 # { 'gender' => { 'masc' => { 'animateness' => { 'inan' => 'I',
31 # '@' => 'M' }},
32 # 'fem' => 'F',
33 # '@' => 'N' }}
34 has 'encode_map' => ( isa => 'HashRef', is => 'ro', required => 1 );
35 # Atoms are typically used as micro drivers for individual features within drivers for structured tagsets.
36 # If this is the case, the atom may need to be able to identify the tagset it works for, in order to be able to interpret values of the 'other' feature.
37 has 'tagset' => ( isa => 'Str', is => 'ro', 'default' => '', documentation => 'Identifier of tagset that this atom is part of. Used when querying the other feature.' );
38  
39  
40  
41 #------------------------------------------------------------------------------
42 # Decodes a physical tag (string) and returns the corresponding feature
43 # structure.
44 #------------------------------------------------------------------------------
45 sub decode
46 {
47 my $self = shift;
48 my $tag = shift;
49 my $fs = Lingua::Interset::FeatureStructure->new();
50 my $map = $self->decode_map();
51 $tag = '' if(!defined($tag));
52 my $assignments = $map->{$tag};
53 if($assignments)
54 {
55 $fs->add(@{$assignments});
56 }
57 return $fs;
58 }
59  
60  
61  
62 #------------------------------------------------------------------------------
63 # Decodes a physical tag (string) and adds the feature values to an existing
64 # feature structure.
65 #------------------------------------------------------------------------------
66 sub decode_and_merge_hard
67 {
68 my $self = shift;
69 my $tag = shift;
70 my $fs = shift; # Lingua::Interset::FeatureStructure
71 my $fs1 = $self->decode($tag);
72 my $hash = $fs1->get_hash();
73 # Special behavior is defined if the 'other' feature in both hashes is a hash of subfeatures.
74 _merge_other_subhashes($fs->other(), $hash->{other}, $hash);
75 $fs->merge_hash_hard($hash);
76 return $fs;
77 }
78  
79  
80  
81 #------------------------------------------------------------------------------
82 # Decodes a physical tag (string) and adds the feature values to an existing
83 # feature structure.
84 #------------------------------------------------------------------------------
85 sub decode_and_merge_soft
86 {
87 my $self = shift;
88 my $tag = shift;
89 my $fs = shift; # Lingua::Interset::FeatureStructure
90 my $fs1 = $self->decode($tag);
91 my $hash = $fs1->get_hash();
92 # Special behavior is defined if the 'other' feature in both hashes is a hash of subfeatures.
93 _merge_other_subhashes($fs->other(), $hash->{other}, $hash);
94 $fs->merge_hash_soft($hash);
95 return $fs;
96 }
97  
98  
99  
100 #------------------------------------------------------------------------------
101 # Special merging of the 'other' feature in the case that it is a sub-hash of
102 # subfeatures.
103 #------------------------------------------------------------------------------
104 sub _merge_other_subhashes
105 {
106 my $tgt_other = shift;
107 my $src_other = shift;
108 my $src_fs_hash = shift; # we will remove other from here after processing its contents
109 if(ref($src_other) eq 'HASH' && ref($tgt_other) eq 'HASH')
110 {
111 my @keys = keys(%{$src_other});
112 foreach my $key (@keys)
113 {
114 # The value is probably a plain scalar but it is not guaranteed, so we must create a deep copy.
115 $tgt_other->{$key} = Lingua::Interset::FeatureStructure::_duplicate_recursive($src_other->{$key});
116 }
117 delete($src_fs_hash->{other});
118 }
119 }
120  
121  
122  
123 #------------------------------------------------------------------------------
124 # Takes feature structure and returns the corresponding physical tag (string).
125 #------------------------------------------------------------------------------
126 sub encode
127 {
128 my $self = shift;
129 my $fs = shift; # Lingua::Interset::FeatureStructure
130 my $map = $self->encode_map();
131 return $self->_encoding_step($map, $fs);
132 }
133  
134  
135  
136 #------------------------------------------------------------------------------
137 # A recursive static function that takes encoding map (hash reference with one
138 # feature name as the only key) and returns surface tag (string).
139 #------------------------------------------------------------------------------
140 sub _encoding_step
141 {
142 my $self = shift;
143 my $map = shift; # reference to hash with only one key
144 my $fs = shift; # Lingua::Interset::FeatureStructure
145 # Example of an encoding map:
146 # The top-level hash must have just one key, a name of a known feature (it is a hash for cosmetic reasons).
147 # '@' denotes the default and will be translated to an else block
148 # { 'gender' => { 'masc' => { 'animateness' => { 'inan' => 'I',
149 # '@' => 'M' }},
150 # 'fem' => 'F',
151 # '@' => 'N' }}
152 my @keys = keys(%{$map});
153 if(scalar(@keys)==1)
154 {
155 my $feature = $keys[0];
156 my $value;
157 if($feature eq 'other')
158 {
159 my $tagset = $self->tagset();
160 if($tagset eq '')
161 {
162 my $surfeature = $self->surfeature();
163 confess("Encoding map (surface feature = '$surfeature') refers to 'other' but the 'tagset' attribute of the atom is empty");
164 }
165 $value = $fs->get_other_for_tagset($tagset);
166 }
167 elsif($feature =~ m-^other/(.+)$-)
168 {
169 my $subfeature = $1;
170 my $tagset = $self->tagset();
171 if($tagset eq '')
172 {
173 my $surfeature = $self->surfeature();
174 confess("Encoding map (surface feature = '$surfeature') refers to 'other' but the 'tagset' attribute of the atom is empty");
175 }
176 $value = $fs->get_other_subfeature($tagset, $subfeature);
177 }
178 elsif(feature_valid($feature))
179 {
180 $value = $fs->get_joined($feature);
181 }
182 else
183 {
184 confess("Unknown feature '$feature'");
185 }
186 my $valuehash = $map->{$feature};
187 my $target = _get_decision_for_value($value, $valuehash); # output string or next-level map
188 if(ref($target) eq 'HASH')
189 {
190 return $self->_encoding_step($target, $fs);
191 }
192 else
193 {
194 return $target;
195 }
196 }
197 else
198 {
199 # Tagset drivers normally do not throw exceptions but if we are here it means we have badly designed code, not input data.
200 confess("The feature-level hash in encoding map must have just one key (feature name); instead, we have ".scalar(@keys).": ".join(', ', @keys));
201 }
202 }
203  
204  
205  
206 #------------------------------------------------------------------------------
207 # Returns reference to list of known tags.
208 #------------------------------------------------------------------------------
209 sub list
210 {
211 my $self = shift;
212 my %tagset;
213 # Collect tags that we are prepared to decode.
214 my $dmap = $self->decode_map();
215 foreach my $tag (keys(%{$dmap}))
216 {
217 $tagset{$tag}++;
218 }
219 # Collect tags reachable through our encoding map.
220 # There should not really be any additional tags not known from $dmap.
221 # But as a sanity check, we will scan them anyway.
222 my $emap = $self->encode_map();
223 $self->_list_step($emap, \%tagset);
224 my @list = sort(keys(%tagset));
225 return \@list;
226 }
227  
228  
229  
230 #------------------------------------------------------------------------------
231 # A recursive static function that takes encoding map (hash reference with one
232 # feature name as the only key) and a reference to a hash where we collect
233 # results. It adds all tags reachable via the map to the collection.
234 #------------------------------------------------------------------------------
235 sub _list_step
236 {
237 my $self = shift;
238 my $map = shift; # reference to hash with only one key
239 my $tagset = shift; # reference to hash where we collect surface tags
240 # Example of an encoding map:
241 # The top-level hash must have just one key, a name of a known feature (it is a hash for cosmetic reasons).
242 # '@' denotes the default and will be translated to an else block
243 # { 'gender' => { 'masc' => { 'animateness' => { 'inan' => 'I',
244 # '@' => 'M' }},
245 # 'fem' => 'F',
246 # '@' => 'N' }}
247 my @keys = keys(%{$map});
248 if(scalar(@keys)==1)
249 {
250 my $feature = $keys[0];
251 my $valuehash = $map->{$feature};
252 my @values = keys(%{$valuehash});
253 foreach my $value (@values)
254 {
255 my $target = $valuehash->{$value};
256 if(ref($target) eq 'HASH')
257 {
258 $self->_list_step($target, $tagset);
259 }
260 else
261 {
262 $tagset->{$target}++;
263 }
264 }
265 }
266 else
267 {
268 # Tagset drivers normally do not throw exceptions but if we are here it means we have badly designed code, not input data.
269 confess("The feature-level hash in encoding map must have just one key (feature name); instead, we have ".scalar(@keys).": ".join(', ', @keys));
270 }
271 }
272  
273  
274  
275 #------------------------------------------------------------------------------
276 # Takes references to two one-dimensional arrays and returns their intersection
277 # as a list. If an element occurs more than once in one of the arrays, it will
278 # occur at most once in the result.
279 #------------------------------------------------------------------------------
280 sub intersection
281 {
282 my $a = shift;
283 my $b = shift;
284 if(ref($a) ne 'ARRAY' || ref($b) ne 'ARRAY')
285 {
286 confess("Expected two array references as parameters");
287 }
288 my %bmap;
289 foreach my $belement (@{$b})
290 {
291 $bmap{$belement}++;
292 }
293 my @intersection;
294 my %imap;
295 foreach my $aelement (@{$a})
296 {
297 if(exists($bmap{$aelement}) && !exists($imap{$aelement}))
298 {
299 push(@intersection, $aelement);
300 $imap{$aelement}++;
301 }
302 }
303 return @intersection;
304 }
305  
306  
307  
308 #------------------------------------------------------------------------------
309 # Takes a feature value and a hash indexed by feature values. A value can be a
310 # list of values separated by vertical bars (e.g. 'masc|fem'). The function
311 # first tries to find an exact match. If it fails, it takes all hash keys,
312 # tries to interpret them as lists and find the value in the list (or, if the
313 # value sought for is also a list, to find the largest intersection of the
314 # lists). If it still fails, it looks for the hash key '@', which means
315 # "everything else".
316 #------------------------------------------------------------------------------
317 sub _get_decision_for_value
318 {
319 my $value = shift;
320 my $valuehash = shift;
321 if(exists($valuehash->{$value}))
322 {
323 return $valuehash->{$value};
324 }
325 else
326 {
327 # The sought value could be a list of values.
328 # One or more of the hash keys could also be lists of values.
329 # If there are multiple matching answers and we must select one, we still want the atom to behave deterministically.
330 # Hence we sort the keys (otherwise their order is really random).
331 my @keys = sort(keys(%{$valuehash}));
332 my $maxn = 0;
333 my $maxkey;
334 foreach my $key (@keys)
335 {
336 my @a = split(/\|/, $value);
337 my @b = split(/\|/, $key);
338 my @i = intersection(\@a, \@b);
339 my $n = scalar(@i);
340 if($n>$maxn)
341 {
342 $maxn = $n;
343 $maxkey = $key;
344 }
345 }
346 # Did we find anything?
347 if(defined($maxkey))
348 {
349 return $valuehash->{$maxkey};
350 }
351 # Do we at least have a default decision?
352 elsif(exists($valuehash->{'@'}))
353 {
354 return $valuehash->{'@'};
355 }
356 }
357 }
358  
359  
360  
361 #------------------------------------------------------------------------------
362 # Takes references to one or more other atoms and merges (adds) their decoding
363 # maps to our decoding map. Ordering of the atoms matters: if several atoms
364 # define decoding of the same feature, the first definition will be used and
365 # the others will be ignored. The atom $self comes first.
366 #------------------------------------------------------------------------------
367 sub merge_atoms
368 {
369 my $self = shift;
370 my @atoms = @_;
371 my $dmap = $self->decode_map();
372 foreach my $atom (@atoms)
373 {
374 my $admap = $atom->decode_map();
375 foreach my $key (keys(%{$admap}))
376 {
377 unless(defined($dmap->{$key}))
378 {
379 $dmap->{$key} = $admap->{$key};
380 }
381 }
382 }
383 return $dmap;
384 }
385  
386  
387  
388 1;
389  
390 __END__
391  
392 =pod
393  
394 =encoding UTF-8
395  
396 =head1 NAME
397  
398 Lingua::Interset::Atom - Atomic driver for a surface feature.
399  
400 =head1 VERSION
401  
402 version 3.015
403  
404 =head1 SYNOPSIS
405  
406 use Lingua::Interset::Atom;
407  
408 my $atom = Lingua::Interset::Atom->new
409 (
410 'surfeature' => 'gender',
411 'decode_map' =>
412  
413 { 'M' => ['gender' => 'masc', 'animateness' => 'anim'],
414 'I' => ['gender' => 'masc', 'animateness' => 'inan'],
415 'F' => ['gender' => 'fem'],
416 'N' => ['gender' => 'neut'] },
417  
418 'encode_map' =>
419  
420 { 'gender' => { 'masc' => { 'animateness' => { 'inan' => 'I',
421 '@' => 'M' }},
422 'fem' => 'F',
423 '@' => 'N' }}
424 );
425  
426 =head1 DESCRIPTION
427  
428 Atom is a special case of a tagset driver.
429 As the name suggests, the surface tags are considered atomic, i.e. indivisible.
430 It provides environment for easy mapping between surface strings and Interset features.
431  
432 While Atom can be used to implement drivers of tagsets whose tags are not structured
433 (such as en::penn or sv::mamba), they should also provide means of defining
434 “sub-drivers” for individual surface features within drivers of complex tagsets.
435 For example, the Czech tags in the Prague Dependency Treebank are always strings
436 of 15 characters where the I<i>-th position in the string encodes the I<i>-th surface feature
437 (which may or may not directly correspond to a feature in Interset).
438 A driver for the PDT tagset could internally construct atomic drivers for PDT
439 gender, number, case etc.
440  
441 =head1 ATTRIBUTES
442  
443 =head2 surfeature
444  
445 Name of the surface feature the atom describes.
446 If the atom describes a whole tagset, the tagset id could be stored here.
447 The surface features may be structured differently from Interset,
448 e.g. there might be an I<agreement> feature, which would map to the Interset features of
449 C<person> and C<number>.
450  
451 =head2 decode_map
452  
453 A compact description of mapping from the surface tags to the Interset feature values.
454 It is a hash reference.
455 Hash keys are surface tags.
456 Hash values are references to arrays of assignments.
457 The arrays must have even number of elements and every pair of elements is a feature-value pair.
458  
459 Example:
460  
461 { 'M' => ['gender' => 'masc', 'animateness' => 'anim'],
462 'I' => ['gender' => 'masc', 'animateness' => 'inan'],
463 'F' => ['gender' => 'fem'],
464 'N' => ['gender' => 'neut'] }
465  
466 Vertical bars may be used to separate multiple values of one feature.
467 The C<other> feature can have a structured value, so you can use standard Perl syntax to describe hash and/or array references.
468  
469 { 'name_of_dog' => [ 'pos' => 'noun', 'nountype' => 'prop', 'other' => { 'named_entity_type' => 'dog' } ],
470 'wh_word' => [ 'pos' => 'noun|adj|adv', 'prontype' => 'int|rel' ] }
471  
472 =head2 encode_map
473  
474 A compact description of mapping from the Interset feature structure to the surface tags.
475 It is a hash reference, possibly with nested hashes.
476 The top-level hash must always have just one key, which is a name of an Interset feature.
477 (It could be encoded without the hash but I believe that the whole map looks better this way.)
478  
479 The top-level key leads to a second-level hash, which is indexed by the values of the feature.
480 It is not necessary that all possible values are listed.
481 A special value C<@>, if present, means “everything else”.
482 It is recommended to always mark the default value using C<@>.
483 Even if we list all currently known values of the feature, new values may be introduced to Interset in future
484 and we do not want to have to get back to all tagsets and update their encoding maps.
485 (On the other hand, if there are values that the C<decode()> method of the current atom
486 does not generate but we still have a preferred output for them, the preference must
487 be made explicit. For instance, if the language does not have the pluperfect tense,
488 it may still define that it be encoded the same way as the past tense.)
489  
490 A feature may have a I<multi-value> (several values joined and separated by vertical
491 bars). A value (multi- or not) is always first sought using the exact match. If the
492 search fails, both the current feature value and the keys of the value hash are treated
493 as lists of values and their largest intersection is sought for. If no overlap is found,
494 the default C<@> decision is taken.
495  
496 Example:
497  
498 { 'gender' => { 'masc' => { 'animateness' => { 'inan' => 'I',
499 '@' => 'M' }},
500 'fem|masc' => 'T',
501 'fem' => 'F',
502 '@' => 'N' }}
503  
504 The C<other> feature, if queried by the map, receives special treatment.
505 First, the C<tagset> attribute must be filled in and its value is checked against the C<tagset> feature.
506 The value is only processed if the tagset ids match (otherwise an empty value is assumed).
507 String values and array values (given as vertical-bar-separated strings) are processed
508 similarly to normal features.
509 In addition, it is possible to have a hash of subfeatures stored in C<other>,
510 and to query them as 'other/subfeature'.
511  
512 Example:
513  
514 { 'other/subfeature1' => { 'x' => 'X',
515 'y' => 'Y',
516 '@' => { 'other/subfeature2' => { '1' => 'S',
517 '@' => '' }}}}
518  
519 The corresponding C<decode_map> would be in this case:
520  
521 {
522 'X' => ['other' => {'subfeature1' => 'x'}],
523 'Y' => ['other' => {'subfeature1' => 'y'}],
524 'S' => ['other' => {'subfeature2' => '1'}]
525 }
526  
527 Note that in general it is not possible to automatically derive the C<encode_map> from the C<decode_map>
528 or vice versa. However, there are simple instances of atoms where this is possible.
529  
530 =head2 tagset
531  
532 Optional identifier of the tagset that this atom is part of.
533 It is required when the encoding map queries values of the C<other> feature
534 (to check against the C<tagset> feature that the values come from the same tagset).
535 Default is empty string.
536  
537 =head1 METHODS
538  
539 =head2 decode()
540  
541 my $fs = $driver->decode ($tag);
542  
543 Takes a tag (string) and returns a L<Lingua::Interset::FeatureStructure> object
544 with corresponding feature values set.
545  
546 =head2 decode_and_merge_hard()
547  
548 my $fs = $driver1->decode ($tag1);
549 $driver2->decode_and_merge_hard ($tag2, $fs);
550  
551 Takes a tag (string) and a L<Lingua::Interset::FeatureStructure> object.
552 Adds the feature values corresponding to the tag to the existing feature structure.
553 Replaces previous values in case of conflict.
554  
555 =head2 decode_and_merge_soft()
556  
557 my $fs = $driver1->decode ($tag1);
558 $driver2->decode_and_merge_soft ($tag2, $fs);
559  
560 Takes a tag (string) and a L<Lingua::Interset::FeatureStructure> object.
561 Adds the feature values corresponding to the tag to the existing feature structure.
562 Merges lists of values in case a feature had already a value set.
563  
564 =head2 encode()
565  
566 my $tag = $driver->encode ($fs);
567  
568 Takes a L<Lingua::Interset::FeatureStructure> object and
569 returns the tag (string) in the given tagset that corresponds to the feature values.
570 Note that some features may be ignored because they cannot be represented
571 in the given tagset.
572  
573 =head2 list()
574  
575 my $list_of_tags = $driver->list();
576  
577 Returns the reference to the list of all known tags in this particular tagset.
578 This is not directly needed to decode, encode or convert tags but it is very useful
579 for testing and advanced operations over the tagset.
580 Note however that many tagset drivers contain only an approximate list,
581 created by collecting tag occurrences in some corpus.
582  
583 =head2 merge_atoms()
584  
585 $atom0->merge($atom1, $atom2, ..., $atomN);
586  
587 Takes references to one or more other atoms and merges (adds) their decoding
588 maps to our decoding map. Ordering of the atoms matters: if several atoms
589 define decoding of the same feature, the first definition will be used and
590 the others will be ignored. The atom C<$self> comes first.
591  
592 Note that the I<encoding> map will I<not change>.
593 This method is useful for tagsets where feature values appear without naming
594 the feature. For example, instead of
595  
596 gender=masc|number=sing|case=nom
597  
598 the tag only contains
599  
600 masc|sing|nom
601  
602 Such tagsets require asymmetric processing.
603 There is one big atom that decodes any feature value regardless of which
604 feature it belongs to. But it does not encode anything.
605 Then there are many small atoms for individual features.
606 We cannot use them for decoding because we do not know which atom to pick
607 until we have decoded the value. But we will use them for encoding because
608 we know which features and in what order we want to encode for a particular
609 part of speech.
610  
611 We could define both the big decoding atom and the small encoding atoms
612 manually. There is a drawback to it: we would be describing each feature twice
613 at two different places in the source code. The C<merge_atoms()> method gives
614 us a better way: we will define the small atoms (both for decoding and
615 encoding) and then create the big decoding atom by merging the small ones:
616  
617 # This code goes in a tagset driver, e.g. Lingua::Interset::Tagset::CS::Mytagset,
618 # in a function that builds all necessary atoms, e.g. sub _create_atoms.
619 my %atoms;
620 $atoms{genderanim} = $self->create_atom
621 (
622 'surfeature' => 'genderanim',
623 'decode_map' =>
624 {
625 'ma' => ['gender' => 'masc', 'animateness' => 'anim'],
626 'mi' => ['gender' => 'masc', 'animateness' => 'inan'],
627 'f' => ['gender' => 'fem'],
628 'n' => ['gender' => 'neut']
629 },
630 'encode_map' =>
631 {
632 'gender' => { 'masc' => { 'animateness' => { 'inan' => 'mi',
633 '@' => 'ma' }},
634 'fem' => 'f',
635 '@' => 'n' }
636 }
637 );
638 $atoms{number} = $self->create_simple_atom
639 (
640 'intfeature' => 'number',
641 'simple_decode_map' =>
642 {
643 'sg' => 'sing',
644 'pl' => 'plur'
645 }
646 );
647 $atoms{feature} = $self->create_atom
648 (
649 'surfeature' => 'feature',
650 'decode_map' => {},
651 'encode_map' => { 'pos' => {} } # The encoding map cannot be empty even if we are not going to use it.
652 );
653 $atoms{feature}->merge_atoms($atoms{genderanim}, $atoms{number});
654  
655 =head1 SEE ALSO
656  
657 L<Lingua::Interset::Tagset>,
658 L<Lingua::Interset::FeatureStructure>
659  
660 =head1 AUTHOR
661  
662 Dan Zeman <zeman@ufal.mff.cuni.cz>
663  
664 =head1 COPYRIGHT AND LICENSE
665  
666 This software is copyright (c) 2019 by Univerzita Karlova (Charles University).
667  
668 This is free software; you can redistribute it and/or modify it under
669 the same terms as the Perl 5 programming language system itself.
670  
671 =cut