Algorithm Search⌘K

Algorithmadvanced

Swap transition system

Also called non-projective swap parsing.

Arc-standard parsing with an extra swap move that reorders words, so it builds any non-projective tree, in quadratic time at worst and near linear time on treebanks.

Time
Θ(n^2) worstΘ(n) best
Space
Θ(n) extra
Where
n = the number of words, with a scorer of constant cost for each of a fixed number of transitions
Properties
deterministicofflineiterative
Origin
Joakim Nivre, 2009

The swap transition system extends arc-standard parsing so that it can build every dependency tree, not only the projective ones. It adds one move, SWAP, which takes the second word of the stack and puts it back at the front of the buffer. This changes the order in which words meet on the stack. Arcs are still made only between the two top stack words, so the system builds a projective tree over a reordered sentence, and every tree is projective under some order of its words: its projective order, given by an inorder traversal. Nivre (2009) proposed the system. With kk swaps a parse takes 2n+2k2n + 2k moves for nn words. Each pair of words can be swapped at most once, so k≤n(n−1)/2k \le n(n - 1)/2 and the worst case is quadratic. On treebanks, few swaps are needed, and the time is close to linear. The title of the paper speaks of expected linear time; that is a statement about real data, not a bound.

In plain words

Arc-standard parsing reads the words onto a pile and joins the two words on top. It can only join words that become neighbours on the pile, so it cannot build arrows that cross. The swap system adds one more move: take the word under the top and put it back in front of the unread words. The two words now come in the opposite order. By doing this several times, the parser can bring words that belong together next to each other, join them, and leave the rest for later. A word that has been put back can come up again later. Any tree can be built this way, but each swap costs two extra moves, so many swaps make the parse slower.

The problem

The input is a sentence w1⋯wnw_1 \cdots w_n with features and a scoring function on the legal transitions of a configuration. The output is a labeled dependency tree, with crossing arcs allowed. In the version on this page the root may have several children, since RIGHT-ARC can attach any number of words to the root. The single-root rule of arc-standard parsing, RIGHT-ARC from the root only when the buffer is empty, can be added in the same way.

The algorithm

Configurations are as in arc-standard parsing, but the buffer is now a list that SWAP can add to, not just a suffix of the sentence. The initial configuration is ([0],[1,…,n],∅)([0], [1, \ldots, n], \emptyset), the terminal ones are ([0],[ ],A)([0], [\,], A), and the words are compared by their original positions. The transitions, for each label ll:

transition before after condition
SHIFT (σ,b∣β,A)(\sigma, b \mid \beta, A) (σ∣b,β,A)(\sigma \mid b, \beta, A)
LEFT-ARCl_l (σ∣s1∣s0,β,A)(\sigma \mid s_1 \mid s_0, \beta, A) (σ∣s0,β,A∪{s0→ls1})(\sigma \mid s_0, \beta, A \cup \{s_0 \xrightarrow{l} s_1\}) s1≠0s_1 \ne 0
RIGHT-ARCl_l (σ∣s1∣s0,β,A)(\sigma \mid s_1 \mid s_0, \beta, A) (σ∣s1,β,A∪{s1→ls0})(\sigma \mid s_1, \beta, A \cup \{s_1 \xrightarrow{l} s_0\})
SWAP (σ∣s1∣s0,β,A)(\sigma \mid s_1 \mid s_0, \beta, A) (σ∣s0,s1∣β,A)(\sigma \mid s_0, s_1 \mid \beta, A) 0<s1<s00 < s_1 < s_0

The condition s1<s0s_1 < s_0 lets SWAP only undo the original order of a pair, so a pair is never swapped back and the parser cannot loop.

  1. SWAP-PARSE(x, score)
  2. 1c <- ([0], [1, ..., n], {})
  3. 2while c is not terminal do
  4. 3for each legal transition t of c
  5. 4compute score(c, t), and keep the best t
  6. 5if t = SHIFT then move the front of the buffer onto the stack
  7. 6if t = LEFT-ARC_l then add s0 -l-> s1 and remove s1 from the stack
  8. 7if t = RIGHT-ARC_l then add s1 -l-> s0 and remove s0 from the stack
  9. 8if t = SWAP then move s1 from the stack to the front of the buffer
  10. 9return the tree A

The oracle. For a gold tree, let pos(w)\mathrm{pos}(w) be the rank of ww in its projective order: the inorder traversal that visits, at each word, the subtrees of its left dependents, then the word, then the subtrees of its right dependents, each group in word order. In a configuration with top words s1,s0s_1, s_0: choose LEFT-ARC if s0s_0 is the gold head of s1s_1 and s1s_1 has all its dependents; RIGHT-ARC if s1s_1 is the gold head of s0s_0 and s0s_0 has all its dependents; SWAP if pos(s0)<pos(s1)\mathrm{pos}(s_0) < \mathrm{pos}(s_1); else SHIFT.

Example

A small tree. The head list [-1, 3, 0, 2] has the arcs 0→20 \to 2, 2→32 \to 3 and 3→13 \to 1. The arc 3→13 \to 1 passes over word 2, the head of 3, so the tree is not projective. Its projective order is 0, 2, 1, 3. The oracle:

step transition stack buffer new arc
0 0 1 2 3
1 SH 0 1 2 3
2 SH 0 1 2 3
3 SWAP 0 2 1 3
4 SH 0 2 1 3
5 SH 0 2 1 3
6 LA 0 2 3 3→13 \to 1
7 RA 0 2 2→32 \to 3
8 RA 0 0→20 \to 2

At step 3, word 2 comes before word 1 in the projective order, so SWAP puts word 1 back. After that the stack meets the words in the order 0, 2, 1, 3, in which the tree is projective, and the rest is arc-standard parsing. There are 8=2⋅3+2⋅18 = 2 \cdot 3 + 2 \cdot 1 moves.

A longer sentence. In A hearing is scheduled on the issue today, with the heads [-1, 2, 3, 0, 3, 2, 7, 5, 4], the phrase on the issue belongs to hearing but comes after is scheduled. The projective order is 0 1 2 5 6 7 3 4 8: the phrase moves before is scheduled. The oracle of this page swaps eagerly, word by word, and uses 6 swaps and 28 moves. A search over all sequences finds that 2 swaps suffice, 20 moves: first build on the issue into one subtree headed by on, then swap on past scheduled and past is. The tests check all three numbers.

Correctness

Every run ends in a tree. If the buffer is not empty, SHIFT is legal; otherwise RIGHT-ARC is legal while the stack has two words. So the parser never gets stuck before a terminal configuration. Each word gets its head when it leaves the stack by an arc, and a word that has left the stack this way never comes back; SWAP puts back only words without a head. In a terminal configuration every word has thus exactly one head, and no cycle can form, because a word with a head is never again a head. The result is a tree, but not always a projective one.

Termination. A SWAP inverts a pair of words, and a pair cannot be swapped back, so there are at most n(n−1)/2n(n - 1)/2 swaps. Between swaps the run behaves as in arc-standard parsing.

Every tree is reached. A tree is projective with respect to its projective order. Run arc-standard parsing on the words in that order, and replace each SHIFT of a word ww by shifting the words in front of ww in the buffer, shifting ww, and swapping those words back one by one. The SWAPs are legal because the buffer stays in the original order. So every tree has a sequence. The proof is in the correctness proof. The tests build all complete sequences for n≤4n \le 4 and find all (n+1)n−1(n + 1)^{n - 1} trees, and they run the oracle on every tree with n≤5n \le 5.

Proof: The swap system is sound and complete for all dependency trees, and every run ends after 2n + 2k transitions with k at most n(n - 1)/2full

The words are 1,…,n1, \ldots, n and 0 is the root. A configuration is (σ,β,A)(\sigma, \beta, A) with stack σ\sigma, buffer β\beta (a list of words) and arc set AA; s0s_0 is the stack top and s1s_1 the word below it. Words are compared by their positions in the sentence.

Lemma 1 (invariant). In every configuration of a run:

  • (a) 0 is at the bottom of the stack and nowhere else, and no arc enters 0;
  • (b) every word is in exactly one of three places: on the stack, in the buffer, or removed; a word is removed exactly when it has a head in AA, and it then has exactly one;
  • (c) no removed word is ever again on the stack or in the buffer;
  • (d) AA has no cycle.

Proof. At the start, σ=[0]\sigma = [0], β=[1,…,n]\beta = [1, \ldots, n] and A=∅A = \emptyset. SHIFT and SWAP move one word between the buffer and the stack, add no arc, and never move 0: SWAP needs s1>0s_1 > 0. LEFT-ARC adds s0→s1s_0 \to s_1 with s1≠0s_1 \ne 0 and removes s1s_1; RIGHT-ARC adds s1→s0s_1 \to s_0 and removes s0s_0; in both cases the dependent was on the stack, so by (b) it had no head, and it now has one. No arc into 0 is added, since LEFT-ARC needs s1≠0s_1 \ne 0 and s0≠0s_0 \ne 0 because 0 is at the bottom. Removed words are not on the stack or in the buffer, and no transition brings a word back from the removed ones, which gives (c). For (d): a new arc h→dh \to d closes a cycle only if AA already has a path of arcs from dd to hh. Such a path ends with an arc into hh, so hh would have a head. But hh stays on the stack, so by (b) it has no head, and no cycle closes. □\square

Lemma 2 (no pair is swapped twice). For words u<vu < v, there is at most one SWAP with s1=us_1 = u and s0=vs_0 = v, and there is never a SWAP with s1=vs_1 = v and s0=us_0 = u.

Proof. The second part is the condition s1<s0s_1 < s_0. For the first, define the relative order of uu and vv while both are on the stack or in the buffer, reading the stack from bottom to top and then the buffer from front to back. SHIFT keeps this sequence as it is (the front of the buffer becomes the new top of the stack), and LEFT-ARC and RIGHT-ARC only delete words from it. SWAP exchanges s1s_1 and s0s_0, two neighbours in this sequence, and changes no other relative order. At the start, uu comes before vv. The only transition that changes their order is a SWAP with s1=us_1 = u, s0=vs_0 = v, which puts vv before uu; after that, the only one that could change it back is a SWAP with s1=vs_1 = v, s0=us_0 = u, which is never legal. □\square

Theorem 3 (soundness and termination). Every run ends after exactly 2n+2k2n + 2k transitions, where k≤n(n−1)/2k \le n(n - 1)/2 is its number of swaps, in a terminal configuration whose arcs form a dependency tree rooted at 0.

Proof. Termination. By Lemma 2 there are at most n(n−1)/2n(n - 1)/2 swaps. Let Φ=2∣β∣+∣σ∣\Phi = 2|\beta| + |\sigma|. SHIFT lowers Φ\Phi by 1, LEFT-ARC and RIGHT-ARC lower it by 1, and SWAP raises it by 1. Φ\Phi is 2n+12n + 1 at the start and at least 1, so a run with kk swaps has at most 2n+k2n + k transitions of the other kinds, and is finite.

No dead end. If the configuration is not terminal, the buffer is not empty and SHIFT is legal, or the buffer is empty and the stack has at least two words, and RIGHT-ARC is legal.

Count. At the end, Φ=1\Phi = 1, so the number of SHIFT, LEFT-ARC and RIGHT-ARC transitions is 2n+k2n + k. Each of the nn words is removed once, by an arc, so there are nn arcs and n+kn + k shifts. The total is 2n+2k2n + 2k.

Tree. In the terminal configuration, σ=[0]\sigma = [0] and β\beta is empty, so by (b) every word is removed and has exactly one head. By (a) 0 has none, and by (d) there is no cycle. So following heads from any word ends at 0, and AA is a dependency tree. □\square

The projective order. For a dependency tree GG, define the order πG\pi_G by an inorder traversal: at a word vv with left dependents l1<⋯<lal_1 < \cdots < l_a and right dependents r1<⋯<rmr_1 < \cdots < r_m, visit the subtrees of l1,…,lal_1, \ldots, l_a, then vv, then the subtrees of r1,…,rmr_1, \ldots, r_m; start at 0. In πG\pi_G, each subtree is a block of consecutive words, so GG is projective when the words are put in the order πG\pi_G. Write pos(w)\mathrm{pos}(w) for the rank of ww in πG\pi_G.

Theorem 4 (completeness). For every dependency tree GG there is a run that ends with A=GA = G.

Proof. Let w0=0,w1,…,wnw_0 = 0, w_1, \ldots, w_n be the words in the order πG\pi_G. By the completeness of arc-standard parsing, applied to the sentence w1⋯wnw_1 \cdots w_n in which GG is projective, there is an arc-standard sequence TT that builds GG; in it, the jj-th SHIFT pushes wjw_j, and every arc is made between the two top stack words. We change TT into a run of the swap system that keeps two properties before each SHIFT of TT: (P1) the stack and the arc set are the same as in the arc-standard run; (P2) the buffer is the list of words not yet pushed, in sentence order.

Both hold at the start. LEFT-ARC and RIGHT-ARC of TT are copied unchanged: they are legal in the swap system under the same conditions, and they do not touch the buffer. A SHIFT of TT that pushes wjw_j is replaced as follows. By (P2), the buffer is in sentence order and holds wjw_j; let u1<⋯<upu_1 < \cdots < u_p be the words in front of wjw_j, all smaller than wjw_j. Do SHIFT p+1p + 1 times, which pushes u1,…,up,wju_1, \ldots, u_p, w_j, and then SWAP pp times. The first SWAP has s1=up<wj=s0s_1 = u_p < w_j = s_0 and up>0u_p > 0, so it is legal, and it puts upu_p at the front of the buffer. The next has s1=up−1<wjs_1 = u_{p - 1} < w_j and puts up−1u_{p - 1} in front of upu_p, and so on. After the pp swaps, wjw_j is on top of the old stack and the buffer is u1,…,upu_1, \ldots, u_p followed by the rest, in sentence order. So (P1) and (P2) hold again, and the arc-standard run and the new run end together, with A=GA = G. □\square

The run of Theorem 4 uses, for each wjw_j, as many swaps as there are words still unpushed that come before wjw_j in the sentence but after it in πG\pi_G; in total, the number of pairs whose order in the sentence is the opposite of their order in πG\pi_G. The oracle of the main page can do better, because it may make an arc and remove a word before that word has to be moved. The tests check, for every tree with n≤5n \le 5, that the oracle builds the tree in 2n+2k2n + 2k transitions with kk at most the number of such pairs, and they compare kk with the least number of swaps, found by search, for every tree with n≤4n \le 4 and 150 sampled trees with n=5n = 5. They also build all complete sequences for n≤4n \le 4 and find that the trees they produce are exactly all (n+1)n−1(n + 1)^{n - 1} dependency trees, which checks Theorems 3 and 4.

Complexity

Number of transitions. Let kk be the number of swaps. SHIFT and SWAP move a word between the buffer and the stack in opposite directions, so there are n+kn + k shifts, and there are nn arcs. The total is 2n+2k2n + 2k. Since k≤n(n−1)/2k \le n(n - 1)/2, a run has at most n+n2n + n^2 transitions, and a parser that swaps every pair reaches this bound.

The oracle's swaps. Let inv\mathrm{inv} be the number of pairs of words whose order in the sentence is the opposite of their order in the projective order, and kmin⁡k_{\min} the least number of swaps of any sequence for the tree. Then the eager oracle uses kk swaps with kmin⁡≤k≤invk_{\min} \le k \le \mathrm{inv}. For projective trees k=0k = 0. kk can be smaller than inv\mathrm{inv}, because an arc can remove a word before it has to be moved: for the tree [-1, 0, 0, 2, 1], k=1k = 1 and inv=2\mathrm{inv} = 2. The largest kk over all trees of nn words is 0, 0, 1, 2, 4, 7 for n=1n = 1 to 6. The tests check the upper bound for every tree with n≤5n \le 5, and compare kk with kmin⁡k_{\min}, found by search, for every tree with n≤4n \le 4 and 150 sampled trees with n=5n = 5.

Time. With a scorer of constant cost, Θ(n+k)\Theta(n + k), which is Θ(n)\Theta(n) at best and Θ(n2)\Theta(n^2) at worst. Nivre (2009) reports that on treebanks the number of swaps stays small, so the running time is close to linear in practice.

Space. Θ(n)\Theta(n): the buffer never holds more than nn words.

Properties

  • Sound and complete for all trees. Every terminal configuration holds a dependency tree, and every tree, projective or not, has a sequence.
  • Projective trees need no swap. For a projective tree the projective order is the word order, and the oracle gives exactly the arc-standard sequence.
  • Sorting by adjacent exchanges. SWAP exchanges two neighbours, much as bubble sort does; the number of inversions between the word order and the projective order bounds the swaps the oracle needs, as it bounds the exchanges of bubble sort.
  • Spurious ambiguity. A tree has many sequences, with different numbers of swaps, as the hearing example shows.
  • Not exact. The greedy parser can miss the best tree. Unlike the projective systems, there is no known polynomial dynamic program over its sequences for arc scores; for exact non-projective search with arc scores, use MST parsing.

Variants and improvements

  • Lazy swapping. Nivre, Kuhlmann and Hall (2009) delay each SWAP until the words to be moved form a complete subtree, so that whole phrases move at once and fewer swaps are needed. On the hearing example the best sequence, found by search in the tests, moves the subtree of on as one unit in this way.
  • Other scorers. The scorer is separate from the system, so beam search and neural scorers can be used with the swap system as with arc-standard parsing.
  • Training on own errors. The dynamic oracle method needs the cost of each move. For the swap system these costs are harder to compute than for arc-eager or arc-hybrid parsing, and the oracle of this page is static.
  • Other routes to crossing arcs. Pseudo-projective parsing transforms the treebank into projective trees and undoes the transformation after parsing. Graph-based parsers find the best tree of all directly, with MST parsing.

When to use it

Use the swap system when a transition-based parser must produce non-projective trees, for languages with free word order or treebanks with many crossing arcs, and greedy or beam parsing at near linear speed is wanted. When exact search with arc scores is wanted, use MST parsing. When the treebank is almost all projective, a projective system with fewer moves is simpler.

Pitfalls

  • Comparing by stack order instead of word order. The condition s1<s0s_1 < s_0 uses the original positions. Without it, the parser can swap a pair back and forth for ever.
  • SWAP with the root. The root must stay at the bottom of the stack; SWAP requires s1>0s_1 > 0.
  • Eager oracle, many swaps. The eager oracle moves words one at a time and can use many more swaps than needed (6 against 2 on the hearing example), which gives the classifier longer sequences to learn. Lazy swapping helps.
  • The projective order. The oracle must use the inorder traversal with the left dependents before the head and the right dependents after it, each group in word order. Another order can make the gold tree non-projective under it, and the oracle then fails.
  • Expected linear time is not a bound. On a hostile input, or with a bad classifier, the parse takes quadratic time.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

swap_transition_system.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/swap-transition-system/. The authors are listed in prov/CCPJNB.jsonl.

"""The swap transition system of Nivre (2009) for non-projective dependency parsing.

The words are 1..n and 0 is the artificial root. A configuration is
(stack, buffer, arcs); the stack starts as [0] with its top s0 last and s1
under it, and the buffer starts as [1, ..., n]. The transitions are
("SH", None), ("LA", label), ("RA", label) and ("SW", None):

    SHIFT        (sigma, b|beta, A)        => (sigma|b, beta, A)
    LEFT-ARC_l   (sigma|s1|s0, beta, A)    => (sigma|s0, beta, A + {(s0, l, s1)})    needs s1 != 0
    RIGHT-ARC_l  (sigma|s1|s0, beta, A)    => (sigma|s1, beta, A + {(s1, l, s0)})
    SWAP         (sigma|s1|s0, beta, A)    => (sigma|s0, s1|beta, A)                 needs 0 < s1 < s0

The terminal configuration is ([0], [], A). Without SWAP this is arc-standard.
A complete sequence with k swaps has 2n + 2k transitions, and k <= n(n - 1) / 2.

The oracle is the one of Nivre (2009), figure 4: LEFT-ARC or RIGHT-ARC when the
gold arc joins s0 and s1 and the dependent has all its own dependents, SWAP
when s0 comes before s1 in the projective order of the gold tree, else SHIFT.
"""

from typing import Callable, List, Optional, Sequence, Tuple

Transition = Tuple[str, Optional[str]]
SHIFT: Transition = ("SH", None)
SWAP: Transition = ("SW", None)


class Config:
    def __init__(self, n: int):
        self.n = n
        self.stack: List[int] = [0]
        self.buffer: List[int] = list(range(1, n + 1))
        self.heads = [-1] * (n + 1)
        self.labels: List[Optional[str]] = [None] * (n + 1)

    def is_terminal(self) -> bool:
        return not self.buffer and len(self.stack) == 1

    def copy(self) -> "Config":
        c = Config(self.n)
        c.stack = list(self.stack)
        c.buffer = list(self.buffer)
        c.heads = list(self.heads)
        c.labels = list(self.labels)
        return c


def is_legal(c: Config, t: Transition) -> bool:
    kind = t[0]
    if kind == "SH":
        return bool(c.buffer)
    if len(c.stack) < 2:
        return False
    s1, s0 = c.stack[-2], c.stack[-1]
    if kind == "LA":
        return s1 != 0
    if kind == "RA":
        return True
    if kind == "SW":
        return 0 < s1 < s0
    raise ValueError(f"unknown transition {t}")


def apply(c: Config, t: Transition) -> None:
    kind, label = t
    if kind == "SH":
        c.stack.append(c.buffer.pop(0))  # @line L5
    elif kind == "LA":
        s0 = c.stack.pop()  # @line L6
        s1 = c.stack.pop()
        c.heads[s1], c.labels[s1] = s0, label
        c.stack.append(s0)
    elif kind == "RA":
        s0 = c.stack.pop()  # @line L7
        c.heads[s0], c.labels[s0] = c.stack[-1], label
    else:
        s0 = c.stack.pop()  # @line L8
        s1 = c.stack.pop()
        c.stack.append(s0)
        c.buffer.insert(0, s1)


def legal_transitions(c: Config, label_set: Sequence[str]) -> List[Transition]:
    out = [t for t in (SHIFT, SWAP) if is_legal(c, t)]
    for kind in ("LA", "RA"):
        for lab in label_set:
            if is_legal(c, (kind, lab)):
                out.append((kind, lab))
    return out


Scorer = Callable[[Config, Transition], float]


def parse(n: int, score: Scorer, label_set: Sequence[str] = ("dep",)):
    """Greedy parsing. Returns (heads, labels, transitions)."""
    c = Config(n)  # @line L1
    seq: List[Transition] = []
    while not c.is_terminal():  # @line L2
        best = None
        for t in legal_transitions(c, label_set):  # @line L3
            s = score(c, t)  # @line L4
            if best is None or s > best[0]:
                best = (s, t)
        apply(c, best[1])
        seq.append(best[1])
    return c.heads, c.labels, seq  # @line L9


def projective_order(heads: Sequence[int]) -> List[int]:
    """Return pos with pos[w] the rank of word w in the inorder traversal of the tree.

    Each node comes after the subtrees of its left dependents and before the
    subtrees of its right dependents, all in word order. Ordering the words by
    pos makes the tree projective.
    """
    n = len(heads) - 1
    kids: List[List[int]] = [[] for _ in range(n + 1)]
    for d in range(1, n + 1):
        kids[heads[d]].append(d)
    order: List[int] = []
    todo: List[Tuple[int, bool]] = [(0, False)]
    while todo:
        v, emit = todo.pop()
        if emit:
            order.append(v)
            continue
        left = [d for d in kids[v] if d < v]
        right = [d for d in kids[v] if d > v]
        for d in reversed(right):
            todo.append((d, False))
        todo.append((v, True))
        for d in reversed(left):
            todo.append((d, False))
    pos = [0] * (n + 1)
    for r, v in enumerate(order):
        pos[v] = r
    return pos


def oracle(c: Config, gold_heads: Sequence[int], gold_labels: Sequence[Optional[str]], pos: Sequence[int]) -> Optional[Transition]:
    if len(c.stack) >= 2:
        s1, s0 = c.stack[-2], c.stack[-1]

        def complete(w):
            return all(c.heads[d] == w for d in range(1, c.n + 1) if gold_heads[d] == w)

        if s1 != 0 and gold_heads[s1] == s0 and complete(s1):
            return ("LA", gold_labels[s1])
        if gold_heads[s0] == s1 and complete(s0):
            return ("RA", gold_labels[s0])
        if pos[s0] < pos[s1]:
            return SWAP
    return SHIFT if c.buffer else None


def oracle_sequence(gold_heads: Sequence[int], gold_labels: Optional[Sequence[Optional[str]]] = None) -> List[Transition]:
    """Return the oracle sequence that builds the gold tree, projective or not."""
    n = len(gold_heads) - 1
    if gold_labels is None:
        gold_labels = [None] + ["dep"] * n
    pos = projective_order(gold_heads)
    c = Config(n)
    seq: List[Transition] = []
    while not c.is_terminal():
        t = oracle(c, gold_heads, gold_labels, pos)
        if t is None or not is_legal(c, t):
            raise ValueError("the oracle is stuck")
        apply(c, t)
        seq.append(t)
    if c.heads != list(gold_heads):
        raise ValueError("the oracle built another tree")
    return seq
test_swap_transition_system.py 162 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/swap-transition-system/. The authors are listed in prov/CCPJNB.jsonl.

import heapq
import itertools
import random

from swap_transition_system import (
    SHIFT,
    SWAP,
    Config,
    apply,
    is_legal,
    legal_transitions,
    oracle_sequence,
    parse,
    projective_order,
)

# A hearing is scheduled on the issue today
HEARING = [-1, 2, 3, 0, 3, 2, 7, 5, 4]


def is_tree(heads):
    n = len(heads) - 1
    for d in range(1, n + 1):
        x, steps = d, 0
        while x != 0:
            x, steps = heads[x], steps + 1
            if x == -1 or steps > n:
                return False
    return True


def is_projective_under(heads, pos):
    """Projectivity of the tree when word w is placed at position pos[w]."""
    n = len(heads) - 1
    at = sorted(range(n + 1), key=lambda w: pos[w])
    for d in range(1, n + 1):
        h = heads[d]
        lo, hi = sorted((pos[h], pos[d]))
        for k in at[lo + 1:hi]:
            x = k
            while x != h and x != 0:
                x = heads[x]
            if x != h:
                return False
    return True


def all_trees(n):
    return [[-1] + list(hs) for hs in itertools.product(range(n + 1), repeat=n) if is_tree([-1] + list(hs))]


TREES = {n: all_trees(n) for n in range(1, 6)}


def key(c):
    return (tuple(c.stack), tuple(c.buffer), tuple(c.heads))


def terminal_trees(n):
    """All trees in terminal configurations reachable from the start, by search."""
    seen, out, todo = set(), set(), [Config(n)]
    while todo:
        c = todo.pop()
        if key(c) in seen:
            continue
        seen.add(key(c))
        if c.is_terminal():
            out.add(tuple(c.heads))
            continue
        for t in legal_transitions(c, ["dep"]):
            c2 = c.copy()
            apply(c2, t)
            todo.append(c2)
    return out


def min_swaps(gold):
    """The fewest swaps of any sequence that builds the gold tree (search by swaps)."""
    n = len(gold) - 1
    tie = itertools.count()
    pq = [(0, next(tie), Config(n))]
    seen = set()
    while pq:
        k, _, c = heapq.heappop(pq)
        if key(c) in seen:
            continue
        seen.add(key(c))
        if c.is_terminal():
            return k
        for t in legal_transitions(c, ["dep"]):
            if t[0] in ("LA", "RA"):
                s1, s0 = c.stack[-2], c.stack[-1]
                if (t[0] == "LA" and gold[s1] != s0) or (t[0] == "RA" and gold[s0] != s1):
                    continue
            c2 = c.copy()
            apply(c2, t)
            heapq.heappush(pq, (k + (t[0] == "SW"), next(tie), c2))
    raise AssertionError("no sequence")


def test_projective_order():
    pos = projective_order(HEARING)
    assert sorted(range(9), key=lambda w: pos[w]) == [0, 1, 2, 5, 6, 7, 3, 4, 8]
    for n in range(1, 6):
        for heads in TREES[n]:
            assert is_projective_under(heads, projective_order(heads))


def test_example_sequence():
    seq = oracle_sequence(HEARING)
    assert seq.count(SWAP) == 6 and len(seq) == 28
    assert min_swaps(HEARING) == 2


def test_oracle_builds_every_tree():
    # The search for the least number of swaps is slow, so for n = 5 it runs
    # on a fixed sample of 150 of the 1296 trees; the other checks run on all.
    sample = set(map(tuple, random.Random(7).sample(TREES[5], 150)))
    for n in range(1, 6):
        for heads in TREES[n]:
            seq = oracle_sequence(heads)  # raises if the tree is not built
            k = seq.count(SWAP)
            assert len(seq) == 2 * n + 2 * k
            assert k <= n * (n - 1) // 2 and len(seq) <= n + n * n
            pos = projective_order(heads)
            inversions = sum(1 for a in range(1, n + 1) for b in range(a + 1, n + 1) if pos[a] > pos[b])
            assert k <= inversions
            if n <= 4 or tuple(heads) in sample:
                assert min_swaps(heads) <= k
            if inversions == 0:
                assert k == 0


def test_sound_and_complete():
    for n in range(1, 5):
        assert terminal_trees(n) == {tuple(t) for t in TREES[n]}


def test_greedy_terminates_with_a_tree():
    rng = random.Random(3)
    for _ in range(300):
        n = rng.randint(1, 9)
        heads, labels, seq = parse(n, lambda c, t: rng.random(), ["x"])
        assert is_tree(heads)
        k = seq.count(SWAP)
        assert len(seq) == 2 * n + 2 * k <= n + n * n


def test_preconditions():
    c = Config(2)
    assert is_legal(c, SHIFT) and not is_legal(c, SWAP) and not is_legal(c, ("RA", "x"))
    apply(c, SHIFT)
    assert not is_legal(c, ("LA", "x")) and not is_legal(c, SWAP) and is_legal(c, ("RA", "x"))
    apply(c, SHIFT)
    assert is_legal(c, SWAP)
    apply(c, SWAP)
    assert c.stack == [0, 2] and c.buffer == [1]
    apply(c, SHIFT)
    assert not is_legal(c, SWAP)  # 2 > 1: the same pair cannot be swapped back

History

Before 2009, transition-based parsers handled crossing arcs by pseudo-projective transformations of the treebank, or by systems that could add arcs between words further apart on the stack. Nivre (2009) proposed the SWAP move, proved that the extended system is sound and complete for all trees, gave the oracle that sorts the words into the projective order, and reported that the number of swaps on several treebanks was small, so the parser ran in about linear time on real data. Later in 2009, Nivre, Kuhlmann and Hall proposed lazy swapping, which moves whole subtrees and needs fewer swaps.

References

  1. Joakim Nivre, Non-projective dependency parsing in expected linear time, ACL-IJCNLP 2009, the SWAP transition, the proof of soundness and completeness for all trees, the oracle based on the projective order, the quadratic worst case and the experiments
  2. Joakim Nivre, Algorithms for deterministic incremental dependency parsing, Computational Linguistics 34(4), 513-553, 2008, the arc-standard system that the swap system extends

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example