/
featstruct.py
2778 lines (2339 loc) · 101 KB
/
featstruct.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Natural Language Toolkit: Feature Structures
#
# Copyright (C) 2001-2021 NLTK Project
# Author: Edward Loper <edloper@gmail.com>,
# Rob Speer,
# Steven Bird <stevenbird1@gmail.com>
# URL: <http://nltk.sourceforge.net>
# For license information, see LICENSE.TXT
"""
Basic data classes for representing feature structures, and for
performing basic operations on those feature structures. A feature
structure is a mapping from feature identifiers to feature values,
where each feature value is either a basic value (such as a string or
an integer), or a nested feature structure. There are two types of
feature structure, implemented by two subclasses of ``FeatStruct``:
- feature dictionaries, implemented by ``FeatDict``, act like
Python dictionaries. Feature identifiers may be strings or
instances of the ``Feature`` class.
- feature lists, implemented by ``FeatList``, act like Python
lists. Feature identifiers are integers.
Feature structures are typically used to represent partial information
about objects. A feature identifier that is not mapped to a value
stands for a feature whose value is unknown (*not* a feature without
a value). Two feature structures that represent (potentially
overlapping) information about the same object can be combined by
unification. When two inconsistent feature structures are unified,
the unification fails and returns None.
Features can be specified using "feature paths", or tuples of feature
identifiers that specify path through the nested feature structures to
a value. Feature structures may contain reentrant feature values. A
"reentrant feature value" is a single feature value that can be
accessed via multiple feature paths. Unification preserves the
reentrance relations imposed by both of the unified feature
structures. In the feature structure resulting from unification, any
modifications to a reentrant feature value will be visible using any
of its feature paths.
Feature structure variables are encoded using the ``nltk.sem.Variable``
class. The variables' values are tracked using a bindings
dictionary, which maps variables to their values. When two feature
structures are unified, a fresh bindings dictionary is created to
track their values; and before unification completes, all bound
variables are replaced by their values. Thus, the bindings
dictionaries are usually strictly internal to the unification process.
However, it is possible to track the bindings of variables if you
choose to, by supplying your own initial bindings dictionary to the
``unify()`` function.
When unbound variables are unified with one another, they become
aliased. This is encoded by binding one variable to the other.
Lightweight Feature Structures
==============================
Many of the functions defined by ``nltk.featstruct`` can be applied
directly to simple Python dictionaries and lists, rather than to
full-fledged ``FeatDict`` and ``FeatList`` objects. In other words,
Python ``dicts`` and ``lists`` can be used as "light-weight" feature
structures.
>>> from nltk.featstruct import unify
>>> unify(dict(x=1, y=dict()), dict(a='a', y=dict(b='b'))) # doctest: +SKIP
{'y': {'b': 'b'}, 'x': 1, 'a': 'a'}
However, you should keep in mind the following caveats:
- Python dictionaries & lists ignore reentrance when checking for
equality between values. But two FeatStructs with different
reentrances are considered nonequal, even if all their base
values are equal.
- FeatStructs can be easily frozen, allowing them to be used as
keys in hash tables. Python dictionaries and lists can not.
- FeatStructs display reentrance in their string representations;
Python dictionaries and lists do not.
- FeatStructs may *not* be mixed with Python dictionaries and lists
(e.g., when performing unification).
- FeatStructs provide a number of useful methods, such as ``walk()``
and ``cyclic()``, which are not available for Python dicts and lists.
In general, if your feature structures will contain any reentrances,
or if you plan to use them as dictionary keys, it is strongly
recommended that you use full-fledged ``FeatStruct`` objects.
"""
import copy
import re
from functools import total_ordering
from nltk.internals import raise_unorderable_types, read_str
from nltk.sem.logic import (
Expression,
LogicalExpressionException,
LogicParser,
SubstituteBindingsI,
Variable,
)
######################################################################
# Feature Structure
######################################################################
@total_ordering
class FeatStruct(SubstituteBindingsI):
"""
A mapping from feature identifiers to feature values, where each
feature value is either a basic value (such as a string or an
integer), or a nested feature structure. There are two types of
feature structure:
- feature dictionaries, implemented by ``FeatDict``, act like
Python dictionaries. Feature identifiers may be strings or
instances of the ``Feature`` class.
- feature lists, implemented by ``FeatList``, act like Python
lists. Feature identifiers are integers.
Feature structures may be indexed using either simple feature
identifiers or 'feature paths.' A feature path is a sequence
of feature identifiers that stand for a corresponding sequence of
indexing operations. In particular, ``fstruct[(f1,f2,...,fn)]`` is
equivalent to ``fstruct[f1][f2]...[fn]``.
Feature structures may contain reentrant feature structures. A
"reentrant feature structure" is a single feature structure
object that can be accessed via multiple feature paths. Feature
structures may also be cyclic. A feature structure is "cyclic"
if there is any feature path from the feature structure to itself.
Two feature structures are considered equal if they assign the
same values to all features, and have the same reentrancies.
By default, feature structures are mutable. They may be made
immutable with the ``freeze()`` method. Once they have been
frozen, they may be hashed, and thus used as dictionary keys.
"""
_frozen = False
""":ivar: A flag indicating whether this feature structure is
frozen or not. Once this flag is set, it should never be
un-set; and no further modification should be made to this
feature structure."""
##////////////////////////////////////////////////////////////
# { Constructor
##////////////////////////////////////////////////////////////
def __new__(cls, features=None, **morefeatures):
"""
Construct and return a new feature structure. If this
constructor is called directly, then the returned feature
structure will be an instance of either the ``FeatDict`` class
or the ``FeatList`` class.
:param features: The initial feature values for this feature
structure:
- FeatStruct(string) -> FeatStructReader().read(string)
- FeatStruct(mapping) -> FeatDict(mapping)
- FeatStruct(sequence) -> FeatList(sequence)
- FeatStruct() -> FeatDict()
:param morefeatures: If ``features`` is a mapping or None,
then ``morefeatures`` provides additional features for the
``FeatDict`` constructor.
"""
# If the FeatStruct constructor is called directly, then decide
# whether to create a FeatDict or a FeatList, based on the
# contents of the `features` argument.
if cls is FeatStruct:
if features is None:
return FeatDict.__new__(FeatDict, **morefeatures)
elif _is_mapping(features):
return FeatDict.__new__(FeatDict, features, **morefeatures)
elif morefeatures:
raise TypeError(
"Keyword arguments may only be specified "
"if features is None or is a mapping."
)
if isinstance(features, str):
if FeatStructReader._START_FDICT_RE.match(features):
return FeatDict.__new__(FeatDict, features, **morefeatures)
else:
return FeatList.__new__(FeatList, features, **morefeatures)
elif _is_sequence(features):
return FeatList.__new__(FeatList, features)
else:
raise TypeError("Expected string or mapping or sequence")
# Otherwise, construct the object as normal.
else:
return super().__new__(cls, features, **morefeatures)
##////////////////////////////////////////////////////////////
# { Uniform Accessor Methods
##////////////////////////////////////////////////////////////
# These helper functions allow the methods defined by FeatStruct
# to treat all feature structures as mappings, even if they're
# really lists. (Lists are treated as mappings from ints to vals)
def _keys(self):
"""Return an iterable of the feature identifiers used by this
FeatStruct."""
raise NotImplementedError() # Implemented by subclasses.
def _values(self):
"""Return an iterable of the feature values directly defined
by this FeatStruct."""
raise NotImplementedError() # Implemented by subclasses.
def _items(self):
"""Return an iterable of (fid,fval) pairs, where fid is a
feature identifier and fval is the corresponding feature
value, for all features defined by this FeatStruct."""
raise NotImplementedError() # Implemented by subclasses.
##////////////////////////////////////////////////////////////
# { Equality & Hashing
##////////////////////////////////////////////////////////////
def equal_values(self, other, check_reentrance=False):
"""
Return True if ``self`` and ``other`` assign the same value to
to every feature. In particular, return true if
``self[p]==other[p]`` for every feature path *p* such
that ``self[p]`` or ``other[p]`` is a base value (i.e.,
not a nested feature structure).
:param check_reentrance: If True, then also return False if
there is any difference between the reentrances of ``self``
and ``other``.
:note: the ``==`` is equivalent to ``equal_values()`` with
``check_reentrance=True``.
"""
return self._equal(other, check_reentrance, set(), set(), set())
def __eq__(self, other):
"""
Return true if ``self`` and ``other`` are both feature structures,
assign the same values to all features, and contain the same
reentrances. I.e., return
``self.equal_values(other, check_reentrance=True)``.
:see: ``equal_values()``
"""
return self._equal(other, True, set(), set(), set())
def __ne__(self, other):
return not self == other
def __lt__(self, other):
if not isinstance(other, FeatStruct):
# raise_unorderable_types("<", self, other)
# Sometimes feature values can be pure strings,
# so we need to be able to compare with non-featstructs:
return self.__class__.__name__ < other.__class__.__name__
else:
return len(self) < len(other)
def __hash__(self):
"""
If this feature structure is frozen, return its hash value;
otherwise, raise ``TypeError``.
"""
if not self._frozen:
raise TypeError("FeatStructs must be frozen before they " "can be hashed.")
try:
return self._hash
except AttributeError:
self._hash = self._calculate_hashvalue(set())
return self._hash
def _equal(
self, other, check_reentrance, visited_self, visited_other, visited_pairs
):
"""
Return True iff self and other have equal values.
:param visited_self: A set containing the ids of all ``self``
feature structures we've already visited.
:param visited_other: A set containing the ids of all ``other``
feature structures we've already visited.
:param visited_pairs: A set containing ``(selfid, otherid)`` pairs
for all pairs of feature structures we've already visited.
"""
# If we're the same object, then we're equal.
if self is other:
return True
# If we have different classes, we're definitely not equal.
if self.__class__ != other.__class__:
return False
# If we define different features, we're definitely not equal.
# (Perform len test first because it's faster -- we should
# do profiling to see if this actually helps)
if len(self) != len(other):
return False
if set(self._keys()) != set(other._keys()):
return False
# If we're checking reentrance, then any time we revisit a
# structure, make sure that it was paired with the same
# feature structure that it is now. Note: if check_reentrance,
# then visited_pairs will never contain two pairs whose first
# values are equal, or two pairs whose second values are equal.
if check_reentrance:
if id(self) in visited_self or id(other) in visited_other:
return (id(self), id(other)) in visited_pairs
# If we're not checking reentrance, then we still need to deal
# with cycles. If we encounter the same (self, other) pair a
# second time, then we won't learn anything more by examining
# their children a second time, so just return true.
else:
if (id(self), id(other)) in visited_pairs:
return True
# Keep track of which nodes we've visited.
visited_self.add(id(self))
visited_other.add(id(other))
visited_pairs.add((id(self), id(other)))
# Now we have to check all values. If any of them don't match,
# then return false.
for (fname, self_fval) in self._items():
other_fval = other[fname]
if isinstance(self_fval, FeatStruct):
if not self_fval._equal(
other_fval,
check_reentrance,
visited_self,
visited_other,
visited_pairs,
):
return False
else:
if self_fval != other_fval:
return False
# Everything matched up; return true.
return True
def _calculate_hashvalue(self, visited):
"""
Return a hash value for this feature structure.
:require: ``self`` must be frozen.
:param visited: A set containing the ids of all feature
structures we've already visited while hashing.
"""
if id(self) in visited:
return 1
visited.add(id(self))
hashval = 5831
for (fname, fval) in sorted(self._items()):
hashval *= 37
hashval += hash(fname)
hashval *= 37
if isinstance(fval, FeatStruct):
hashval += fval._calculate_hashvalue(visited)
else:
hashval += hash(fval)
# Convert to a 32 bit int.
hashval = int(hashval & 0x7FFFFFFF)
return hashval
##////////////////////////////////////////////////////////////
# { Freezing
##////////////////////////////////////////////////////////////
#: Error message used by mutating methods when called on a frozen
#: feature structure.
_FROZEN_ERROR = "Frozen FeatStructs may not be modified."
def freeze(self):
"""
Make this feature structure, and any feature structures it
contains, immutable. Note: this method does not attempt to
'freeze' any feature value that is not a ``FeatStruct``; it
is recommended that you use only immutable feature values.
"""
if self._frozen:
return
self._freeze(set())
def frozen(self):
"""
Return True if this feature structure is immutable. Feature
structures can be made immutable with the ``freeze()`` method.
Immutable feature structures may not be made mutable again,
but new mutable copies can be produced with the ``copy()`` method.
"""
return self._frozen
def _freeze(self, visited):
"""
Make this feature structure, and any feature structure it
contains, immutable.
:param visited: A set containing the ids of all feature
structures we've already visited while freezing.
"""
if id(self) in visited:
return
visited.add(id(self))
self._frozen = True
for (fname, fval) in sorted(self._items()):
if isinstance(fval, FeatStruct):
fval._freeze(visited)
##////////////////////////////////////////////////////////////
# { Copying
##////////////////////////////////////////////////////////////
def copy(self, deep=True):
"""
Return a new copy of ``self``. The new copy will not be frozen.
:param deep: If true, create a deep copy; if false, create
a shallow copy.
"""
if deep:
return copy.deepcopy(self)
else:
return self.__class__(self)
# Subclasses should define __deepcopy__ to ensure that the new
# copy will not be frozen.
def __deepcopy__(self, memo):
raise NotImplementedError() # Implemented by subclasses.
##////////////////////////////////////////////////////////////
# { Structural Information
##////////////////////////////////////////////////////////////
def cyclic(self):
"""
Return True if this feature structure contains itself.
"""
return self._find_reentrances({})[id(self)]
def walk(self):
"""
Return an iterator that generates this feature structure, and
each feature structure it contains. Each feature structure will
be generated exactly once.
"""
return self._walk(set())
def _walk(self, visited):
"""
Return an iterator that generates this feature structure, and
each feature structure it contains.
:param visited: A set containing the ids of all feature
structures we've already visited while freezing.
"""
raise NotImplementedError() # Implemented by subclasses.
def _walk(self, visited):
if id(self) in visited:
return
visited.add(id(self))
yield self
for fval in self._values():
if isinstance(fval, FeatStruct):
yield from fval._walk(visited)
# Walk through the feature tree. The first time we see a feature
# value, map it to False (not reentrant). If we see a feature
# value more than once, then map it to True (reentrant).
def _find_reentrances(self, reentrances):
"""
Return a dictionary that maps from the ``id`` of each feature
structure contained in ``self`` (including ``self``) to a
boolean value, indicating whether it is reentrant or not.
"""
if id(self) in reentrances:
# We've seen it more than once.
reentrances[id(self)] = True
else:
# This is the first time we've seen it.
reentrances[id(self)] = False
# Recurse to contained feature structures.
for fval in self._values():
if isinstance(fval, FeatStruct):
fval._find_reentrances(reentrances)
return reentrances
##////////////////////////////////////////////////////////////
# { Variables & Bindings
##////////////////////////////////////////////////////////////
def substitute_bindings(self, bindings):
""":see: ``nltk.featstruct.substitute_bindings()``"""
return substitute_bindings(self, bindings)
def retract_bindings(self, bindings):
""":see: ``nltk.featstruct.retract_bindings()``"""
return retract_bindings(self, bindings)
def variables(self):
""":see: ``nltk.featstruct.find_variables()``"""
return find_variables(self)
def rename_variables(self, vars=None, used_vars=(), new_vars=None):
""":see: ``nltk.featstruct.rename_variables()``"""
return rename_variables(self, vars, used_vars, new_vars)
def remove_variables(self):
"""
Return the feature structure that is obtained by deleting
any feature whose value is a ``Variable``.
:rtype: FeatStruct
"""
return remove_variables(self)
##////////////////////////////////////////////////////////////
# { Unification
##////////////////////////////////////////////////////////////
def unify(self, other, bindings=None, trace=False, fail=None, rename_vars=True):
return unify(self, other, bindings, trace, fail, rename_vars)
def subsumes(self, other):
"""
Return True if ``self`` subsumes ``other``. I.e., return true
If unifying ``self`` with ``other`` would result in a feature
structure equal to ``other``.
"""
return subsumes(self, other)
##////////////////////////////////////////////////////////////
# { String Representations
##////////////////////////////////////////////////////////////
def __repr__(self):
"""
Display a single-line representation of this feature structure,
suitable for embedding in other representations.
"""
return self._repr(self._find_reentrances({}), {})
def _repr(self, reentrances, reentrance_ids):
"""
Return a string representation of this feature structure.
:param reentrances: A dictionary that maps from the ``id`` of
each feature value in self, indicating whether that value
is reentrant or not.
:param reentrance_ids: A dictionary mapping from each ``id``
of a feature value to a unique identifier. This is modified
by ``repr``: the first time a reentrant feature value is
displayed, an identifier is added to ``reentrance_ids`` for it.
"""
raise NotImplementedError()
# Mutation: disable if frozen.
_FROZEN_ERROR = "Frozen FeatStructs may not be modified."
_FROZEN_NOTICE = "\n%sIf self is frozen, raise ValueError."
def _check_frozen(method, indent=""):
"""
Given a method function, return a new method function that first
checks if ``self._frozen`` is true; and if so, raises ``ValueError``
with an appropriate message. Otherwise, call the method and return
its result.
"""
def wrapped(self, *args, **kwargs):
if self._frozen:
raise ValueError(_FROZEN_ERROR)
else:
return method(self, *args, **kwargs)
wrapped.__name__ = method.__name__
wrapped.__doc__ = (method.__doc__ or "") + (_FROZEN_NOTICE % indent)
return wrapped
######################################################################
# Feature Dictionary
######################################################################
class FeatDict(FeatStruct, dict):
"""
A feature structure that acts like a Python dictionary. I.e., a
mapping from feature identifiers to feature values, where a feature
identifier can be a string or a ``Feature``; and where a feature value
can be either a basic value (such as a string or an integer), or a nested
feature structure. A feature identifiers for a ``FeatDict`` is
sometimes called a "feature name".
Two feature dicts are considered equal if they assign the same
values to all features, and have the same reentrances.
:see: ``FeatStruct`` for information about feature paths, reentrance,
cyclic feature structures, mutability, freezing, and hashing.
"""
def __init__(self, features=None, **morefeatures):
"""
Create a new feature dictionary, with the specified features.
:param features: The initial value for this feature
dictionary. If ``features`` is a ``FeatStruct``, then its
features are copied (shallow copy). If ``features`` is a
dict, then a feature is created for each item, mapping its
key to its value. If ``features`` is a string, then it is
processed using ``FeatStructReader``. If ``features`` is a list of
tuples ``(name, val)``, then a feature is created for each tuple.
:param morefeatures: Additional features for the new feature
dictionary. If a feature is listed under both ``features`` and
``morefeatures``, then the value from ``morefeatures`` will be
used.
"""
if isinstance(features, str):
FeatStructReader().fromstring(features, self)
self.update(**morefeatures)
else:
# update() checks the types of features.
self.update(features, **morefeatures)
# ////////////////////////////////////////////////////////////
# { Dict methods
# ////////////////////////////////////////////////////////////
_INDEX_ERROR = "Expected feature name or path. Got %r."
def __getitem__(self, name_or_path):
"""If the feature with the given name or path exists, return
its value; otherwise, raise ``KeyError``."""
if isinstance(name_or_path, (str, Feature)):
return dict.__getitem__(self, name_or_path)
elif isinstance(name_or_path, tuple):
try:
val = self
for fid in name_or_path:
if not isinstance(val, FeatStruct):
raise KeyError # path contains base value
val = val[fid]
return val
except (KeyError, IndexError) as e:
raise KeyError(name_or_path) from e
else:
raise TypeError(self._INDEX_ERROR % name_or_path)
def get(self, name_or_path, default=None):
"""If the feature with the given name or path exists, return its
value; otherwise, return ``default``."""
try:
return self[name_or_path]
except KeyError:
return default
def __contains__(self, name_or_path):
"""Return true if a feature with the given name or path exists."""
try:
self[name_or_path]
return True
except KeyError:
return False
def has_key(self, name_or_path):
"""Return true if a feature with the given name or path exists."""
return name_or_path in self
def __delitem__(self, name_or_path):
"""If the feature with the given name or path exists, delete
its value; otherwise, raise ``KeyError``."""
if self._frozen:
raise ValueError(_FROZEN_ERROR)
if isinstance(name_or_path, (str, Feature)):
return dict.__delitem__(self, name_or_path)
elif isinstance(name_or_path, tuple):
if len(name_or_path) == 0:
raise ValueError("The path () can not be set")
else:
parent = self[name_or_path[:-1]]
if not isinstance(parent, FeatStruct):
raise KeyError(name_or_path) # path contains base value
del parent[name_or_path[-1]]
else:
raise TypeError(self._INDEX_ERROR % name_or_path)
def __setitem__(self, name_or_path, value):
"""Set the value for the feature with the given name or path
to ``value``. If ``name_or_path`` is an invalid path, raise
``KeyError``."""
if self._frozen:
raise ValueError(_FROZEN_ERROR)
if isinstance(name_or_path, (str, Feature)):
return dict.__setitem__(self, name_or_path, value)
elif isinstance(name_or_path, tuple):
if len(name_or_path) == 0:
raise ValueError("The path () can not be set")
else:
parent = self[name_or_path[:-1]]
if not isinstance(parent, FeatStruct):
raise KeyError(name_or_path) # path contains base value
parent[name_or_path[-1]] = value
else:
raise TypeError(self._INDEX_ERROR % name_or_path)
clear = _check_frozen(dict.clear)
pop = _check_frozen(dict.pop)
popitem = _check_frozen(dict.popitem)
setdefault = _check_frozen(dict.setdefault)
def update(self, features=None, **morefeatures):
if self._frozen:
raise ValueError(_FROZEN_ERROR)
if features is None:
items = ()
elif hasattr(features, "items") and callable(features.items):
items = features.items()
elif hasattr(features, "__iter__"):
items = features
else:
raise ValueError("Expected mapping or list of tuples")
for key, val in items:
if not isinstance(key, (str, Feature)):
raise TypeError("Feature names must be strings")
self[key] = val
for key, val in morefeatures.items():
if not isinstance(key, (str, Feature)):
raise TypeError("Feature names must be strings")
self[key] = val
##////////////////////////////////////////////////////////////
# { Copying
##////////////////////////////////////////////////////////////
def __deepcopy__(self, memo):
memo[id(self)] = selfcopy = self.__class__()
for (key, val) in self._items():
selfcopy[copy.deepcopy(key, memo)] = copy.deepcopy(val, memo)
return selfcopy
##////////////////////////////////////////////////////////////
# { Uniform Accessor Methods
##////////////////////////////////////////////////////////////
def _keys(self):
return self.keys()
def _values(self):
return self.values()
def _items(self):
return self.items()
##////////////////////////////////////////////////////////////
# { String Representations
##////////////////////////////////////////////////////////////
def __str__(self):
"""
Display a multi-line representation of this feature dictionary
as an FVM (feature value matrix).
"""
return "\n".join(self._str(self._find_reentrances({}), {}))
def _repr(self, reentrances, reentrance_ids):
segments = []
prefix = ""
suffix = ""
# If this is the first time we've seen a reentrant structure,
# then assign it a unique identifier.
if reentrances[id(self)]:
assert id(self) not in reentrance_ids
reentrance_ids[id(self)] = repr(len(reentrance_ids) + 1)
# sorting note: keys are unique strings, so we'll never fall
# through to comparing values.
for (fname, fval) in sorted(self.items()):
display = getattr(fname, "display", None)
if id(fval) in reentrance_ids:
segments.append(f"{fname}->({reentrance_ids[id(fval)]})")
elif (
display == "prefix" and not prefix and isinstance(fval, (Variable, str))
):
prefix = "%s" % fval
elif display == "slash" and not suffix:
if isinstance(fval, Variable):
suffix = "/%s" % fval.name
else:
suffix = "/%s" % repr(fval)
elif isinstance(fval, Variable):
segments.append(f"{fname}={fval.name}")
elif fval is True:
segments.append("+%s" % fname)
elif fval is False:
segments.append("-%s" % fname)
elif isinstance(fval, Expression):
segments.append(f"{fname}=<{fval}>")
elif not isinstance(fval, FeatStruct):
segments.append(f"{fname}={repr(fval)}")
else:
fval_repr = fval._repr(reentrances, reentrance_ids)
segments.append(f"{fname}={fval_repr}")
# If it's reentrant, then add on an identifier tag.
if reentrances[id(self)]:
prefix = f"({reentrance_ids[id(self)]}){prefix}"
return "{}[{}]{}".format(prefix, ", ".join(segments), suffix)
def _str(self, reentrances, reentrance_ids):
"""
:return: A list of lines composing a string representation of
this feature dictionary.
:param reentrances: A dictionary that maps from the ``id`` of
each feature value in self, indicating whether that value
is reentrant or not.
:param reentrance_ids: A dictionary mapping from each ``id``
of a feature value to a unique identifier. This is modified
by ``repr``: the first time a reentrant feature value is
displayed, an identifier is added to ``reentrance_ids`` for
it.
"""
# If this is the first time we've seen a reentrant structure,
# then tack on an id string.
if reentrances[id(self)]:
assert id(self) not in reentrance_ids
reentrance_ids[id(self)] = repr(len(reentrance_ids) + 1)
# Special case: empty feature dict.
if len(self) == 0:
if reentrances[id(self)]:
return ["(%s) []" % reentrance_ids[id(self)]]
else:
return ["[]"]
# What's the longest feature name? Use this to align names.
maxfnamelen = max(len("%s" % k) for k in self.keys())
lines = []
# sorting note: keys are unique strings, so we'll never fall
# through to comparing values.
for (fname, fval) in sorted(self.items()):
fname = ("%s" % fname).ljust(maxfnamelen)
if isinstance(fval, Variable):
lines.append(f"{fname} = {fval.name}")
elif isinstance(fval, Expression):
lines.append(f"{fname} = <{fval}>")
elif isinstance(fval, FeatList):
fval_repr = fval._repr(reentrances, reentrance_ids)
lines.append(f"{fname} = {repr(fval_repr)}")
elif not isinstance(fval, FeatDict):
# It's not a nested feature structure -- just print it.
lines.append(f"{fname} = {repr(fval)}")
elif id(fval) in reentrance_ids:
# It's a feature structure we've seen before -- print
# the reentrance id.
lines.append(f"{fname} -> ({reentrance_ids[id(fval)]})")
else:
# It's a new feature structure. Separate it from
# other values by a blank line.
if lines and lines[-1] != "":
lines.append("")
# Recursively print the feature's value (fval).
fval_lines = fval._str(reentrances, reentrance_ids)
# Indent each line to make room for fname.
fval_lines = [(" " * (maxfnamelen + 3)) + l for l in fval_lines]
# Pick which line we'll display fname on, & splice it in.
nameline = (len(fval_lines) - 1) // 2
fval_lines[nameline] = (
fname + " =" + fval_lines[nameline][maxfnamelen + 2 :]
)
# Add the feature structure to the output.
lines += fval_lines
# Separate FeatStructs by a blank line.
lines.append("")
# Get rid of any excess blank lines.
if lines[-1] == "":
lines.pop()
# Add brackets around everything.
maxlen = max(len(line) for line in lines)
lines = ["[ {}{} ]".format(line, " " * (maxlen - len(line))) for line in lines]
# If it's reentrant, then add on an identifier tag.
if reentrances[id(self)]:
idstr = "(%s) " % reentrance_ids[id(self)]
lines = [(" " * len(idstr)) + l for l in lines]
idline = (len(lines) - 1) // 2
lines[idline] = idstr + lines[idline][len(idstr) :]
return lines
######################################################################
# Feature List
######################################################################
class FeatList(FeatStruct, list):
"""
A list of feature values, where each feature value is either a
basic value (such as a string or an integer), or a nested feature
structure.
Feature lists may contain reentrant feature values. A "reentrant
feature value" is a single feature value that can be accessed via
multiple feature paths. Feature lists may also be cyclic.
Two feature lists are considered equal if they assign the same
values to all features, and have the same reentrances.
:see: ``FeatStruct`` for information about feature paths, reentrance,
cyclic feature structures, mutability, freezing, and hashing.
"""
def __init__(self, features=()):
"""
Create a new feature list, with the specified features.
:param features: The initial list of features for this feature
list. If ``features`` is a string, then it is paresd using
``FeatStructReader``. Otherwise, it should be a sequence
of basic values and nested feature structures.
"""
if isinstance(features, str):
FeatStructReader().fromstring(features, self)
else:
list.__init__(self, features)
# ////////////////////////////////////////////////////////////
# { List methods
# ////////////////////////////////////////////////////////////
_INDEX_ERROR = "Expected int or feature path. Got %r."
def __getitem__(self, name_or_path):
if isinstance(name_or_path, int):
return list.__getitem__(self, name_or_path)
elif isinstance(name_or_path, tuple):
try:
val = self
for fid in name_or_path:
if not isinstance(val, FeatStruct):
raise KeyError # path contains base value
val = val[fid]
return val
except (KeyError, IndexError) as e:
raise KeyError(name_or_path) from e
else:
raise TypeError(self._INDEX_ERROR % name_or_path)
def __delitem__(self, name_or_path):
"""If the feature with the given name or path exists, delete
its value; otherwise, raise ``KeyError``."""
if self._frozen:
raise ValueError(_FROZEN_ERROR)
if isinstance(name_or_path, (int, slice)):
return list.__delitem__(self, name_or_path)
elif isinstance(name_or_path, tuple):
if len(name_or_path) == 0:
raise ValueError("The path () can not be set")
else:
parent = self[name_or_path[:-1]]
if not isinstance(parent, FeatStruct):
raise KeyError(name_or_path) # path contains base value
del parent[name_or_path[-1]]
else:
raise TypeError(self._INDEX_ERROR % name_or_path)
def __setitem__(self, name_or_path, value):
"""Set the value for the feature with the given name or path
to ``value``. If ``name_or_path`` is an invalid path, raise
``KeyError``."""
if self._frozen:
raise ValueError(_FROZEN_ERROR)
if isinstance(name_or_path, (int, slice)):
return list.__setitem__(self, name_or_path, value)
elif isinstance(name_or_path, tuple):
if len(name_or_path) == 0:
raise ValueError("The path () can not be set")