-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathnode.py
More file actions
1252 lines (1096 loc) · 52.8 KB
/
node.py
File metadata and controls
1252 lines (1096 loc) · 52.8 KB
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
"""Node class and related classes and functions.
In addition to class `Node`, this module contains also helper classes
`CycleError`, `EmptyNode`, `OrdTuple` and `ListOfNodes`
and function `find_minimal_common_treelet`.
"""
import logging
import functools
import udapi.core.coref
from udapi.block.write.textmodetrees import TextModeTrees
from udapi.core.dualdict import DualDict
from udapi.core.feats import Feats
# Pylint complains when we access e.g. node.parent._children or root._descendants
# because it does not know that node.parent is the same class (Node)
# and Root is a "friend" class of Node, so accessing underlined attributes is OK and intended.
# Moreover, pylint has false-positive no-member alarms when accessing node.root._descendants
# (pylint thinks node.root returns a Node instance, but actually it returns a Root instance).
# pylint: disable=protected-access,no-member
# 7 instance attributes and 20 public methods are too low limits (CoNLL-U has 10 columns)
# The set of public attributes/properties and methods of Node was well-thought.
# pylint: disable=too-many-instance-attributes,too-many-public-methods
@functools.total_ordering
class Node(object):
"""Class for representing nodes in Universal Dependency trees.
Attributes `form`, `lemma`, `upos`, `xpos` and `deprel` are public attributes of type `str`,
so you can use e.g. `node.lemma = node.form`.
`node.ord` is a int type property for storing the node's word-order index,
but assigning to it should be done with care, so the non-root nodes have `ord`s 1,2,3...
It is recommended to use one of the `node.shift_*` methods for reordering nodes.
Note that `EmptyNode`s (subclass of `Node`) have decimal ords (and no `shift_*` methods).
For changing dependency structure (topology) of the tree, there is the `parent` property,
e.g. `node.parent = node.parent.parent` and `node.create_child()` method.
Properties `node.children` and `node.descendants` return object of type `ListOfNodes`,
so it is possible to do e.g.
>>> all_children = node.children
>>> left_children = node.children(preceding_only=True)
>>> right_descendants = node.descendants(following_only=True, add_self=True)
Properties `node.feats` and `node.misc` return objects of type `DualDict`, so one can do e.g.:
>>> node = Node()
>>> str(node.feats)
'_'
>>> node.feats = {'Case': 'Nom', 'Person': '1'}`
>>> node.feats = 'Case=Nom|Person=1' # equivalent to the above
>>> node.feats['Case']
'Nom'
>>> node.feats['NonExistent']
''
>>> node.feats['Case'] = 'Gen'
>>> str(node.feats)
'Case=Gen|Person=1'
>>> dict(node.feats)
{'Case': 'Gen', 'Person': '1'}
Handling of enhanced dependencies, multi-word tokens and other node's methods
are described below.
"""
# TODO: Benchmark memory and speed of slots vs. classic dict.
# With Python 3.5 split dict, slots may not be better.
# TODO: Should not we include __weakref__ in slots?
# TODO: Benchmark using node._ord instead node.ord in this file
__slots__ = [
'_ord', # Word-order index of the node (root has 0).
'form', # Word form or punctuation symbol.
'lemma', # Lemma of word form.
'upos', # Universal PoS tag.
'xpos', # Language-specific part-of-speech tag; underscore if not available.
'deprel', # UD dependency relation to the HEAD (root iff HEAD = 0).
'_misc', # Any other annotation as udapi.core.dualdict.DualDict object.
'_raw_deps', # Enhanced dependencies (head-deprel pairs) in their original CoNLLU format.
'_deps', # Deserialized enhanced dependencies in a list of {parent, deprel} dicts.
'_feats', # Morphological features as udapi.core.feats.Feats object.
'_parent', # Parent node.
'_children', # Ord-ordered list of child nodes.
'_root', # Technical root of the tree
'_mwt', # Multi-word token in which this word participates.
'_mentions', # List of udapi.core.coref.CorefMention objects whose span includes this node
]
def __init__(self, root, form=None, lemma=None, upos=None, # pylint: disable=too-many-arguments
xpos=None, feats=None, deprel=None, misc=None):
"""Create a new node and initialize its attributes using the keyword arguments."""
self._root = root
self._ord = None
self.form = form
self.lemma = lemma
self.upos = upos
self.xpos = xpos
self._feats = Feats(feats) if feats and feats != '_' else None
self.deprel = deprel
self._misc = DualDict(misc) if misc and misc != '_' else None
self._raw_deps = '_'
self._deps = None
self._parent = None
self._children = list()
self._mwt = None
self._mentions = list()
def __str__(self):
"""String representation of the Node object: <n.address(), n.form>."""
return f"<{self.address()}, {self.form}>"
def __repr__(self):
"""String representation of the Node object: Node<n.address(), n.form>."""
return f"Node<{self.address()}, {self.form}>"
@property
def root(self):
return self._root
# ord is implemented as a property, so that it can be overriden in EmptyNode and Root
@property
def ord(self):
return self._ord
@ord.setter
def ord(self, new_ord):
self._ord = new_ord
def __lt__(self, other):
"""Calling `nodeA < nodeB` is equivalent to `nodeA.ord < nodeB.ord`.
Note that this does not work as expected for nodes from different trees
because `ord` is the word order within each sentence.
For comparing the word order across trees, use `nodeA.precedes(nodeB)` instead.
"""
return self._ord < other._ord
@property
def udeprel(self):
"""Return the universal part of dependency relation, e.g. `acl` instead of `acl:relcl`.
So you can write `node.udeprel` instead of `node.deprel.split(':')[0]`.
"""
return self.deprel.split(':')[0] if self.deprel is not None else None
@udeprel.setter
def udeprel(self, value):
sdeprel = self.sdeprel
if sdeprel is not None and sdeprel != '':
self.deprel = value + ':' + sdeprel
else:
self.deprel = value
@property
def sdeprel(self):
"""Return the language-specific part of dependency relation.
E.g. if deprel = `acl:relcl` then sdeprel = `relcl`.
If deprel=`acl` then sdeprel = empty string.
If deprel is `None` then `node.sdeprel` will return `None` as well.
"""
if self.deprel is None:
return None
parts = self.deprel.split(':', 1)
if len(parts) == 2:
return parts[1]
return ''
@sdeprel.setter
def sdeprel(self, value):
udeprel = self.udeprel
if value is not None and value != '':
self.deprel = udeprel + ':' + value
else:
self.deprel = udeprel
@property
def feats(self):
"""Property for morphological features stored as a `Feats` object.
Reading:
You can access `node.feats` as a dict, e.g. `if node.feats['Case'] == 'Nom'`.
Features which are not set return an empty string (not None, not KeyError),
so you can safely use e.g. `if node.feats['MyExtra'].find('substring') != -1`.
You can also obtain the string representation of the whole FEATS (suitable for CoNLL-U),
e.g. `if node.feats == 'Case=Nom|Person=1'`.
Writing:
All the following assignment types are supported:
`node.feats['Case'] = 'Nom'`
`node.feats = {'Case': 'Nom', 'Person': '1'}`
`node.feats = 'Case=Nom|Person=1'`
`node.feats = '_'`
The last line has the same result as assigning None or empty string to `node.feats`.
For details about the implementation and other methods (e.g. `node.feats.is_plural()`),
see ``udapi.core.feats.Feats`` which is a subclass of `DualDict`.
"""
if self._feats is None:
self._feats = Feats()
return self._feats
@feats.setter
def feats(self, value):
if self._feats is None:
self._feats = Feats(value)
else:
self._feats.set_mapping(value)
@property
def misc(self):
"""Property for MISC attributes stored as a `DualDict` object.
Reading:
You can access `node.misc` as a dict, e.g. `if node.misc['SpaceAfter'] == 'No'`.
Features which are not set return an empty string (not None, not KeyError),
so you can safely use e.g. `if node.misc['MyExtra'].find('substring') != -1`.
You can also obtain the string representation of the whole MISC (suitable for CoNLL-U),
e.g. `if node.misc == 'SpaceAfter=No|X=Y'`.
Writing:
All the following assignment types are supported:
`node.misc['SpaceAfter'] = 'No'`
`node.misc = {'SpaceAfter': 'No', 'X': 'Y'}`
`node.misc = 'SpaceAfter=No|X=Y'`
`node.misc = '_'`
The last line has the same result as assigning None or empty string to `node.feats`.
For details about the implementation, see ``udapi.core.dualdict.DualDict``.
"""
if self._misc is None:
self._misc = DualDict()
return self._misc
@misc.setter
def misc(self, value):
if self._misc is None:
self._misc = DualDict(value)
else:
self._misc.set_mapping(value)
@property
def raw_deps(self):
"""String serialization of enhanced dependencies as stored in CoNLL-U files.
After the access to the raw enhanced dependencies,
provide the serialization if they were deserialized already.
"""
# TODO: node.deps.append(dep) should be hooked and
# mark the serialized cache dirty, i.e. self._raw_deps = None.
# Afterwards, we can use the following optimization
#if self._raw_deps is not None:
# return self._raw_deps
if self._deps:
self._raw_deps = '|'.join(f"{p}:{r}" for p, r in sorted(set((d['parent'].ord, d['deprel']) for d in self._deps)))
return self._raw_deps
@raw_deps.setter
def raw_deps(self, value):
"""Set serialized enhanced dependencies (the new value is a string).
When updating raw secondary dependencies,
the current version of the deserialized data is deleted.
"""
self._raw_deps = value
self._deps = None
@property
def deps(self):
"""Return enhanced dependencies as a Python list of dicts.
After the first access to the enhanced dependencies,
provide the deserialization of the raw data and save deps to the list.
"""
if self._deps is None:
# Create a list of secondary dependencies.
self._deps = list()
if self._raw_deps == '_':
return self._deps
# Obtain a list of all nodes in the dependency tree.
nodes = [self._root] + self._root._descendants
for raw_dependency in self._raw_deps.split('|'):
# Deprel itself may contain one or more ':' (subtypes).
head, deprel = raw_dependency.split(':', maxsplit=1)
# Empty nodes have to be located differently than normal nodes.
if '.' in head:
try:
parent = next(x for x in self._root.empty_nodes if str(x._ord) == head)
except StopIteration:
raise ValueError(f'Empty node with ord={head} not found')
else:
parent = nodes[int(head)]
self._deps.append({'parent': parent, 'deprel': deprel})
return self._deps
@deps.setter
def deps(self, value):
"""Set deserialized enhanced dependencies (the new value is a list of dicts)."""
self._deps = value
self._raw_deps = None
@property
def parent(self):
"""Return dependency parent (head) node."""
return self._parent
@parent.setter
def parent(self, new_parent):
"""Set a new dependency parent node.
Check if the parent assignment is valid (no cycles) and assign
a new parent (dependency head) for the current node.
If the node had a parent, it is detached first
(from the list of original parent's children).
"""
# If the parent is already assigned, return.
if self._parent is new_parent:
return
# Check for None new_parent and cycles.
if new_parent is None:
raise ValueError(f'Cannot set None as parent: {self}')
if new_parent.is_empty():
raise ValueError(f'Cannot set EmptyNode as parent in basic dependencies: {self}')
if self is new_parent:
raise CycleError('Cannot set a node as its own parent (cycle are forbidden): %s', self)
if self._children and new_parent.is_descendant_of(self):
raise CycleError('Setting the parent of %s to %s would lead to a cycle.', self, new_parent)
# Remove the current Node from the children of the old parent.
# Forbid moving nodes from one tree to another using parent setter.
if self._parent:
self._parent._children.remove(self)
if self._parent._root is not new_parent._root:
raise ValueError('Cannot move nodes between trees with parent setter, '
'use new_root.steal_nodes(nodes_to_be_moved) instead')
# Set the new parent.
self._parent = new_parent
# Append the current node to the new parent children.
if not new_parent._children or self > new_parent._children[-1]:
new_parent._children.append(self)
else:
new_parent._children.append(self)
new_parent._children.sort()
@property
def children(self):
"""Return a list of dependency children (direct dependants) nodes.
The returned nodes are sorted by their ord.
Note that node.children is a property, not a method,
so if you want all the children of a node (excluding the node itself),
you should not use node.children(), but just
node.children
However, the returned result is a callable list, so you can use
nodes1 = node.children(add_self=True)
nodes2 = node.children(following_only=True)
nodes3 = node.children(preceding_only=True)
nodes4 = node.children(preceding_only=True, add_self=True)
as a shortcut for
nodes1 = sorted([node] + node.children, key=lambda n: n.ord)
nodes2 = [n for n in node.children if n.ord > node.ord]
nodes3 = [n for n in node.children if n.ord < node.ord]
nodes4 = [n for n in node.children if n.ord < node.ord] + [node]
See the documentation of ListOfNodes for details.
"""
return ListOfNodes(self._children, origin=self)
@property
def siblings(self):
"""Return a list of dependency sibling nodes.
When used as a property, `node.siblings` is just a shortcut for:
[n for n in node.parent.children if n!=node]
However, it is especially helpful when used as a method,
so e.g. `node.siblings(preceding_only=True)` stands for
[n for n in node.parent.children if n.ord < node.ord]
which is something else than
node.parent.children(preceding_only=True).
See the documentation of ListOfNodes for details.
"""
return ListOfNodes([n for n in self._parent._children if n!=self], origin=self)
@property
def descendants(self):
"""Return a list of all descendants of the current node.
The returned nodes are sorted by their ord.
Note that node.descendants is a property, not a method,
so if you want all the descendants of a node (excluding the node itself),
you should not use node.descendants(), but just
node.descendants
However, the returned result is a callable list, so you can use
nodes1 = node.descendants(add_self=True)
nodes2 = node.descendants(following_only=True)
nodes3 = node.descendants(preceding_only=True)
nodes4 = node.descendants(preceding_only=True, add_self=True)
as a shortcut for
nodes1 = sorted([node] + node.descendants, key=lambda n: n.ord)
nodes2 = [n for n in node.descendants if n.ord > node.ord]
nodes3 = [n for n in node.descendants if n.ord < node.ord]
nodes4 = [n for n in node.descendants if n.ord < node.ord] + [node]
See the documentation of ListOfNodes for details.
"""
# The following code is equivalent to
# ListOfNodes(sorted(self.unordered_descendants()), origin=self)
# but it is faster because there is no extra copying of lists of nodes.
stack = list(self._children)
descendants = ListOfNodes(stack, origin=self)
while(stack):
n = stack.pop()
if n._children:
stack.extend(n._children)
descendants.extend(n._children)
descendants.sort()
return descendants
def is_descendant_of(self, node):
"""Is the current node a descendant of the node given as argument?"""
if node and node._children:
climber = self._parent
while climber:
if climber is node:
return True
climber = climber._parent
return False
def create_child(self, **kwargs):
"""Create and return a new child of the current node."""
new_node = Node(root=self._root, **kwargs)
new_node._ord = len(self._root._descendants) + 1
self._root._descendants.append(new_node)
self._children.append(new_node)
new_node._parent = self
return new_node
def create_empty_child(self, deprel, after=True, **kwargs):
"""Create and return a new empty node child of the current node.
Args:
deprel: the enhanced dependency relation (required to be stored in DEPS)
form, lemma, upos, xpos, feats, misc: as in Node, the default is '_'
after: position the newly created empty node after this `node`?
If True (default), the `new_node.ord` will be `node.ord + 0.1`,
unless there is already an empty node with such ord,
in which case it will be `node.ord + 0.2` etc.
If False, the new node will be placed immediately before `node`.
"""
new_node = EmptyNode(root=self._root, **kwargs)
new_node.deps = [{'parent': self, 'deprel': deprel}]
# self.enh_children.append(new_node) TODO
# new_node.enh_parents.append(self) TODO
base_ord = self._ord if after else self._ord - 1
new_ord = base_ord + 0.1
for empty in self._root.empty_nodes:
if empty._ord > new_ord:
break
if empty._ord == new_ord:
if isinstance(new_ord, OrdTuple):
new_ord.increase()
elif new_ord == base_ord + 0.9:
new_ord = OrdTuple(base_ord, 10)
else:
new_ord = round(new_ord+0.1, 1)
new_node._ord = new_ord
if not self._root.empty_nodes or new_node > self._root.empty_nodes[-1]:
self._root.empty_nodes.append(new_node)
else:
self._root.empty_nodes.append(new_node)
self._root.empty_nodes.sort()
return new_node
# TODO: make private: _unordered_descendants
def unordered_descendants(self):
"""Return a list of all descendants in any order."""
stack = list(self._children)
descendants = list(stack)
while(stack):
n = stack.pop()
if n._children:
stack.extend(n._children)
descendants.extend(n._children)
return descendants
@staticmethod
def is_root():
"""Is the current node a (technical) root?
Returns False for all Node instances, irrespectively of whether is has a parent or not.
True is returned only by instances of udapi.core.root.Root.
"""
return False
@staticmethod
def is_empty():
"""Is the current node an empty node?
Returns False for all Node instances.
True is returned only by instances of the EmptyNode subclass.
"""
return False
def remove(self, children=None):
"""Delete this node (and all its descendants unlsess specified otherwise).
Args:
children: a string specifying what to do if the node has any children.
The default (None) is to delete them (and all their descendants).
`rehang` means to re-attach those children to the parent of the removed node.
`warn` means to issue a warning if any children are present and delete them.
`rehang_warn` means to rehang and warn:-).
"""
self._parent._children.remove(self)
# If there are any children, do the action specified in the "children" parameter.
if children is not None and self._children:
if children.startswith('rehang'):
for child in self._children:
child._parent = self._parent
self._parent._children.extend(self._children)
self._parent._children.sort()
self._children.clear()
if children.endswith('warn'):
logging.warning('%s is being removed by remove(children=%s), '
' but it has (unexpected) children', self, children)
# When self is the only node being removed, it is faster to root._descendants.remove(self)
# and update the ords only where necessary (from self._ord further).
# When removing also its children+descendants, it is faster to recompute root._descendants
# and update all ords (computing leftmost descendant of self would be too slow).
if not self._children:
try:
self._root._descendants.remove(self)
except ValueError:
pass # self may be an already deleted node e.g. if n.remove() called twice
else:
for (new_ord, node) in enumerate(self._root._descendants[self._ord - 1:], self._ord):
node.ord = new_ord
last_ord = 0
for empty in self._root.empty_nodes:
if empty._ord > self._ord:
new_ord = round(empty._ord - 1, 1)
if new_ord <= last_ord:
new_ord = round(last_ord + 0.1, 1)
empty.ord = new_ord
last_ord = empty._ord
else:
# Remember the position of empty nodes, so we can reorder them as well.
empty_follows = None
if self._root.empty_nodes:
will_be_removed = self if children and children.startswith('rehang') else self.descendants(add_self=1)
prev_nonempty = self._root
empty_follows = {}
for node in self._root.descendants_and_empty:
if node.is_empty():
empty_follows[node] = prev_nonempty
elif node not in will_be_removed:
prev_nonempty = node
# TODO nodes_to_remove = self.unordered_descendants()
# and mark all nodes as deleted, remove them from MWT and coref mentions
self._root._descendants = sorted(self._root.unordered_descendants())
for (new_ord, node) in enumerate(self._root._descendants, 1):
node.ord = new_ord
# Decrease ord of empty nodes (keep their fractional part)
# Make sure that e.g. after deleting node with ord=2
# ords "1 1.1 1.2 2 2.1" will become "1 1.1 1.2 1.3".
if empty_follows:
last_ord = 0
for empty in self._root.empty_nodes:
prev_nonempty = empty_follows[empty]
new_ord = round(prev_nonempty._ord + (empty._ord % 1), 1)
while new_ord <= last_ord:
new_ord = round(new_ord + 0.1, 1)
last_ord, empty.ord = new_ord, new_ord
def _shift_before_ord(self, reference_ord, without_children=False):
"""Internal method for changing word order."""
all_nodes = self._root._descendants
empty_nodes = self._root.empty_nodes
# Moving a single node can be faster than nodes_to_move = [self]
if without_children or not self._children:
my_ord = self._ord
if reference_ord > my_ord + 1:
for i_ord in range(my_ord, reference_ord - 1):
all_nodes[i_ord - 1] = all_nodes[i_ord]
all_nodes[i_ord - 1]._ord = i_ord
all_nodes[reference_ord - 2] = self
self._ord = reference_ord - 1
for en in empty_nodes:
if en._ord > my_ord and en._ord < reference_ord:
en._ord -= 1
elif reference_ord < my_ord:
for i_ord in range(my_ord, reference_ord, -1):
all_nodes[i_ord - 1] = all_nodes[i_ord - 2]
all_nodes[i_ord - 1]._ord = i_ord
all_nodes[reference_ord - 1] = self
self._ord = reference_ord
for en in empty_nodes:
# Empty nodes before the first overt token (ID=0.X) will be never moved this way.
# We cannot know whether the caller wanted to place the shifted node before or after them.
if en._ord < my_ord and en._ord > reference_ord:
en._ord += 1
self._parent._children.sort()
return
#TODO: Updating ords of empty nodes is implemented only for the simple case above,
# but it has to be implemented also for the complex case below!
nodes_to_move = self.descendants(add_self=True)
first_ord, last_ord = nodes_to_move[0]._ord, nodes_to_move[-1]._ord
# If there are no "gaps" in nodes_to_move (e.g. when it is projective),
# we can make the shifting a bit faster and simpler.
if last_ord - first_ord + 1 == len(nodes_to_move):
# First, move a node from position src_ord to position trg_ord RIGHT-ward.
trg_ord, src_ord = last_ord, first_ord - 1
while src_ord >= reference_ord:
all_nodes[trg_ord - 1] = all_nodes[src_ord - 1]
all_nodes[trg_ord-1]._ord = trg_ord
trg_ord, src_ord = trg_ord - 1, src_ord - 1
# Second, move a node from position src_ord to position trg_ord LEFT-ward.
trg_ord, src_ord = first_ord, last_ord + 1
while src_ord < reference_ord:
all_nodes[trg_ord - 1] = all_nodes[src_ord - 1]
all_nodes[trg_ord - 1]._ord = trg_ord
trg_ord, src_ord = trg_ord + 1, src_ord + 1
# Third, move nodes_to_move to trg_ord RIGHT-ward.
trg_ord = reference_ord if reference_ord < first_ord else trg_ord
for node in nodes_to_move:
all_nodes[trg_ord - 1], node._ord = node, trg_ord
trg_ord += 1
self._parent._children.sort()
return
# First, move a node from position src_ord to position trg_ord RIGHT-ward.
# src_ord iterates decreasingly over nodes which are not moving.
trg_ord, src_ord, mov_ord = last_ord, last_ord - 1, len(nodes_to_move) - 2
while src_ord >= reference_ord:
while all_nodes[src_ord - 1] is nodes_to_move[mov_ord]:
mov_ord, src_ord = mov_ord - 1, src_ord - 1
if src_ord < reference_ord:
break
else:
all_nodes[trg_ord - 1] = all_nodes[src_ord - 1]
all_nodes[trg_ord - 1]._ord = trg_ord
trg_ord, src_ord = trg_ord - 1, src_ord - 1
# Second, move a node from position src_ord to position trg_ord LEFT-ward.
# src_ord iterates increasingly over nodes which are not moving.
trg_ord, src_ord, mov_ord = first_ord, first_ord + 1, 1
while src_ord < reference_ord:
while mov_ord < len(nodes_to_move) and all_nodes[src_ord - 1] is nodes_to_move[mov_ord]:
mov_ord, src_ord = mov_ord + 1, src_ord + 1
if src_ord >= reference_ord:
break
else:
all_nodes[trg_ord - 1] = all_nodes[src_ord - 1]
all_nodes[trg_ord - 1]._ord = trg_ord
trg_ord, src_ord = trg_ord + 1, src_ord + 1
# Third, move nodes_to_move to trg_ord RIGHT-ward.
trg_ord = reference_ord if reference_ord < first_ord else trg_ord
for node in nodes_to_move:
all_nodes[trg_ord - 1], node._ord = node, trg_ord
trg_ord += 1
self._parent._children.sort()
def shift_after_node(self, reference_node, without_children=False, skip_if_descendant=False):
"""Shift this node after the reference_node."""
if not without_children and reference_node.is_descendant_of(self):
if skip_if_descendant:
return
raise ValueError(f'{reference_node} is a descendant of {self}. Consider without_children=1.')
self._shift_before_ord(reference_node._ord + 1, without_children=without_children)
def shift_before_node(self, reference_node, without_children=False, skip_if_descendant=False):
"""Shift this node before the reference_node."""
if reference_node.is_root():
raise ValueError(f'Cannot shift a node before the root ({reference_node})')
if not without_children and reference_node.is_descendant_of(self):
if skip_if_descendant:
return
raise ValueError(f'{reference_node} is a descendant of {self}. Consider without_children=1.')
self._shift_before_ord(reference_node._ord, without_children=without_children)
def shift_after_subtree(self, reference_node, without_children=False, skip_if_descendant=False):
"""Shift this node (and its subtree) after the subtree rooted by reference_node.
Args:
without_children: shift just this node without its subtree?
"""
if not without_children and reference_node.is_descendant_of(self):
if skip_if_descendant:
return
raise ValueError(f'{reference_node} is a descendant of {self}. Consider without_children=1.')
ref_ord = reference_node._ord
for node in reference_node.unordered_descendants():
if node._ord > ref_ord and node is not self:
ref_ord = node._ord
self._shift_before_ord(ref_ord + 1, without_children=without_children)
def shift_before_subtree(self, reference_node, without_children=0, skip_if_descendant=False):
"""Shift this node (and its subtree) before the subtree rooted by reference_node.
Args:
without_children: shift just this node without its subtree?
"""
if reference_node.is_root():
raise ValueError(f'Cannot shift a node before the root ({reference_node})')
if not without_children and reference_node.is_descendant_of(self):
if skip_if_descendant:
return
raise ValueError(f'{reference_node} is a descendant of {self}. Consider without_children=1.')
ref_ord = reference_node._ord
for node in reference_node.unordered_descendants():
if node._ord < ref_ord and node is not self:
ref_ord = node._ord
self._shift_before_ord(ref_ord, without_children=without_children)
@property
def prev_node(self):
"""Return the previous node according to word order."""
new_ord = self._ord - 1
if new_ord < 0:
return None
if new_ord == 0:
return self._root
return self._root._descendants[new_ord - 1]
@property
def next_node(self):
"""Return the following node according to word order."""
# Note that all_nodes[n].ord == n+1
try:
return self._root._descendants[self._ord]
except IndexError:
return None
def precedes(self, node):
"""Does this node precedes another `node` in word order?
This method handles correctly also nodes from different trees (but the same zone).
If you have nodes from the same tree, it is faster and more elegant to use just `nodeA < nodeB`,
which is equivalent to calling `nodeA.ord < nodeB.ord`.
For sorting nodes from the same tree, you can use `nodes.sort()` or `sorted(nodes)`.
"""
if self._root is node._root:
return self._ord < node._ord
if self._root._zone != node._root._zone:
raise ValueError(f"Cannot compare word order across zones: {self} {node}")
if self._root._bundle._document is not node._root._bundle._document:
raise ValueError(f"Cannot compare word order across documents: {self} {node}")
return self._root._bundle.number < node._root._bundle.number
def is_leaf(self):
"""Is this node a leaf, ie. a node without any children?"""
return not self._children
def _get_attr(self, name): # pylint: disable=too-many-return-statements
if name == 'dir':
if not self._parent or self._parent.is_root():
return 'root'
return 'left' if self.precedes(self._parent) else 'right'
if name == 'edge':
if not self._parent or self._parent.is_root():
return 0
return self._ord - self._parent._ord
if name == 'children':
return len(self._children)
if name == 'siblings':
return 0 if not self._parent else len(self._parent._children) - 1
if name == 'depth':
value = 0
tmp = self
while tmp and not tmp.is_root():
tmp = tmp._parent
value += 1
return value
if name == 'feats_split':
return str(self.feats).split('|')
if name == 'misc_split':
return str(self.misc).split('|')
if name.startswith('feats['):
return self.feats[name[6:-1]]
if name.startswith('misc['):
return self.misc[name[5:-1]]
return getattr(self, name)
def get_attrs(self, attrs, undefs=None, stringify=True):
"""Return multiple attributes or pseudo-attributes, possibly substituting empty ones.
Pseudo-attributes:
p_xy is the (pseudo) attribute xy of the parent node.
c_xy is a list of the (pseudo) attributes xy of the children nodes.
l_xy is the (pseudo) attribute xy of the previous (left in LTR langs) node.
r_xy is the (pseudo) attribute xy of the following (right in LTR langs) node.
dir: 'left' = the node is a left child of its parent,
'right' = the node is a rigth child of its parent,
'root' = the node's parent is the technical root.
edge: length of the edge to parent (`node.ord - node.parent.ord`) or 0 if parent is root
children: number of children nodes.
siblings: number of siblings nodes.
depth: depth in the dependency tree (technical root has depth=0, highest word has depth=1).
feats_split: list of name=value formatted strings of the FEATS.
Args:
attrs: A list of attribute names, e.g. ``['form', 'lemma', 'p_upos']``.
undefs: A value to be used instead of None for empty (undefined) values.
stringify: Apply `str()` on each value (except for None)
"""
values = []
for name in attrs:
nodes = [self]
if name.startswith('p_'):
nodes, name = [self._parent], name[2:]
elif name.startswith('c_'):
nodes, name = self.children, name[2:]
elif name.startswith('l_'):
nodes, name = [self.prev_node], name[2:]
elif name.startswith('r_'):
nodes, name = [self.next_node], name[2:]
for node in (n for n in nodes if n is not None):
if name in {'feats_split', 'misc_split'}:
values.extend(node._get_attr(name))
else:
values.append(node._get_attr(name))
if undefs is not None:
values = [x if x is not None else undefs for x in values]
if stringify:
values = [str(x) if x is not None else None for x in values]
return values
def compute_text(self, use_mwt=True):
"""Return a string representing this subtree's text (detokenized).
Compute the string by concatenating forms of nodes
(words and multi-word tokens) and joining them with a single space,
unless the node has SpaceAfter=No in its misc.
If called on root this method returns a string suitable for storing
in root.text (but it is not stored there automatically).
Technical details:
If called on root, the root's form (<ROOT>) is not included in the string.
If called on non-root nodeA, nodeA's form is included in the string,
i.e. internally descendants(add_self=True) is used.
Note that if the subtree is non-projective, the resulting string may be misleading.
Args:
use_mwt: consider multi-word tokens? (default=True)
"""
string = ''
last_mwt_id = 0
for node in self.descendants(add_self=not self.is_root()):
mwt = node.multiword_token
if use_mwt and mwt:
if node._ord > last_mwt_id:
last_mwt_id = mwt.words[-1]._ord
string += mwt.form
if mwt.misc['SpaceAfter'] != 'No':
string += ' '
else:
string += node.form
if node.misc['SpaceAfter'] != 'No':
string += ' '
return string.rstrip()
def print_subtree(self, **kwargs):
"""deprecated name for draw()"""
logging.warning("node.print_subtree() is deprecated, use node.draw() instead.")
TextModeTrees(**kwargs).process_tree(self)
def draw(self, **kwargs):
"""Print ASCII visualization of the dependency structure of this subtree.
This method is useful for debugging.
Internally udapi.block.write.textmodetrees.TextModeTrees is used for the printing.
All keyword arguments of this method are passed to its constructor,
so you can use e.g.:
files: to redirect sys.stdout to a file
indent: to have wider trees
attributes: to override the default list 'form,upos,deprel'
See TextModeTrees for details and other parameters.
"""
TextModeTrees(**kwargs).process_tree(self)
def address(self):
"""Return full (document-wide) id of the node.
For non-root nodes, the general address format is:
node.bundle.bundle_id + '/' + node.root.zone + '#' + node.ord,
e.g. s123/en_udpipe#4. If zone is empty, the slash is excluded as well,
e.g. s123#4.
"""
return f"{self._root.address() if self._root else '?'}#{self._ord}"
@property
def multiword_token(self):
"""Return the multi-word token which includes this node, or None.
If this node represents a (syntactic) word which is part of a multi-word token,
this method returns the instance of udapi.core.mwt.MWT.
If this nodes is not part of any multi-word token, this method returns None.
"""
return self._mwt
@property
def words(self):
"""Return one-item list with this node.
This property is there for compatibility with udapi.core.mwt.MWT.words.
So that it is possible to use code such as:
for token in root.token_descendants:
words = token.words
...
"""
return [self]
def is_nonprojective(self):
"""Is the node attached to its parent non-projectively?
Is there at least one node between (word-order-wise) this node and its parent
that is not dominated by the parent?
For higher speed, the actual implementation does not find the node(s)
which cause(s) the gap. It only checks the number of parent's descendants in the span
and the total number of nodes in the span.
"""
# Root and its children are always projective
parent = self._parent
if not parent or parent.is_root():
return False
# Edges between neighboring nodes are always projective.
# Check it now to make it a bit faster.
ord1, ord2 = self._ord, parent._ord
if ord1 > ord2:
ord1, ord2 = ord2, ord1
distance = ord2 - ord1
if distance == 1:
return False
# Get all the descendants of parent that are in the span of the edge.
span = [n for n in parent.unordered_descendants() if n._ord > ord1 and n._ord < ord2]
# For projective edges, span must include all the nodes between parent and self.
return len(span) != distance - 1
def is_nonprojective_gap(self):
"""Is the node causing a non-projective gap within another node's subtree?
Is there at least one node X such that
- this node is not a descendant of X, but
- this node is within span of X, i.e. it is between (word-order-wise)
X's leftmost descendant (or X itself) and X's rightmost descendant (or X itself).
"""
ancestors = set([self])
node = self
while node._parent:
node = node._parent
ancestors.add(node)
all_nodes = node._descendants
for left_node in all_nodes[:self._ord - 1]:
if self.precedes(left_node._parent) and left_node._parent not in ancestors:
return True
for right_node in all_nodes[self._ord:]:
if right_node._parent.precedes(self) and right_node._parent not in ancestors:
return True
return False
@property
def no_space_after(self):
"""Boolean property as a shortcut for `node.misc["SpaceAfter"] == "No"`."""
return self.misc["SpaceAfter"] == "No"
@property
def gloss(self):
"""String property as a shortcut for `node.misc["Gloss"]`."""
return self.misc["Gloss"]
@gloss.setter
def gloss(self, new_gloss):
self.misc["Gloss"] = new_gloss
@property
def coref_mentions(self):
self._root.bundle.document._load_coref()
return self._mentions
@property
def coref_entities(self):
self._root.bundle.document._load_coref()
return [m.entity for m in self._mentions if m.entity is not None]
# TODO: is this method useful?