Algorithm Search⌘K

Algorithmcore

Head rules

Also called head percolation table, Magerman-Collins head rules.

A table that picks the head child of each phrase type, used to lexicalize trees and to convert constituency trees to dependencies.

Time
O(s l) worstΘ(s) best
Space
Θ(s) extra
Where
l = the length of the longest priority list of the table; n = the number of words; s = the number of nodes of the tree
Properties
deterministicofflineiterative
Origin
David M. Magerman, Michael Collins, 1995

Head rules pick, for each phrase in a parse tree, the one child that is its head: the verb phrase in a sentence, the noun in a noun phrase, the preposition in a prepositional phrase. The rules are a table indexed by the parent label. Each entry gives a scan direction and a priority list of child labels. Once every phrase has a head child, each phrase gets a head word passed up from below. This is what a lexicalized PCFG needs, and it also turns a constituency tree into a dependency tree: the head word of each non-head child depends on the head word of the phrase. Magerman used such a table in 1995 and Collins published the version that most later work copies in his 1999 thesis. The conversion is linear in the size of the tree. The table itself is a heuristic: it encodes linguistic choices, and other tables give other heads.

In plain words

A phrase such as "the big dog" is about one word, "dog", its head. If we know the head of every phrase, we know which word each other word attaches to: "the" and "big" attach to "dog", and "dog" attaches to whatever word heads the phrase above it.

The head rules find the head with a short recipe for each kind of phrase. For a prepositional phrase, look from the right for a preposition. For a verb phrase, look from the left for a verb, then a modal, then another verb phrase, and so on down a list. If nothing in the list is found, take the first child on the side where the search starts. Noun phrases have their own recipe, which looks for the last noun.

Applied from the bottom of the tree to the top, this gives every word one head word: a dependency tree.

The problem

The input is a constituency tree tt over the words w1,…,wnw_1, \ldots, w_n, such as a tree of the Penn treebank: internal nodes carry phrase labels (S, NP, VP, PP, ...), preterminals carry part-of-speech tags, and the leaves are the words. The output has two parts.

  1. For each internal node vv with children u1,…,umu_1, \ldots, u_m, an index c(v)∈{1,…,m}c(v) \in \{1, \ldots, m\}, the head child. The head word head(v)\mathrm{head}(v) is the word of vv itself if vv is a preterminal, and head(uc(v))\mathrm{head}(u_{c(v)}) otherwise.
  2. The dependency tree hh: for every word dd, its head h(d)∈{0,…,n}h(d) \in \{0, \ldots, n\}, with 0 the artificial root. At each node vv and each child uku_k with k≠c(v)k \ne c(v), the word head(uk)\mathrm{head}(u_k) gets the head head(v)\mathrm{head}(v). The head word of the whole tree gets the head 0, so the root has exactly one child.

There is no single correct answer to part 1. A head table is a convention, and the problem is to apply a given table exactly. The rest of this page uses the table of Collins (1999), with the labels of the Penn Treebank. Function tags and indices are removed before lookup, so NP-SBJ-1 is looked up as NP.

The algorithm

A table entry is a pair (dir, list). "Left" means the children are scanned from the left, "right" from the right. The outer loop goes through the list in priority order and the inner loop through the children, so a label early in the list beats a label that is closer to the start. Part of the Collins table:

parent dir priority list
S left TO IN VP S SBAR ADJP UCP NP
VP left TO VBD VBN MD VBZ VB VBG VBP VP ADJP NN NNS NP
PP right IN TO VBG VBN RP FW
SBAR left WHNP WHPP WHADVP WHADJP IN DT S SQ SINV SBAR FRAG
ADJP left NNS QP NN $ ADVP JJ VBN VBG ADJP JJR NP JJS DT FW RBR RBS SBAR RB
ADVP right RB RBR RBS FW ADVP TO CD JJR JJ IN NP JJS NN
PRN left (empty)
FRAG right (empty)

The implementation holds the full table, with 24 entries and the NP rule. NP has its own rule, NP-HEAD, which goes by position within a set of labels: the first child from the right that is a noun tag, not the noun with the highest priority.

  1. HEAD-CHILD(X, Y1 … Ym) ▷ X: parent label; Y1 … Ym: child labels
  2. 1if m = 1 then return 1
  3. 2if X = NP then return NP-HEAD(Y1 … Ym)
  4. 3(dir, list) ← table[X], or (left, empty list) if X has no entry
  5. 4order ← 1, 2, …, m if dir = left, else m, m-1, …, 1
  6. 5for each label Z in list, in priority order do
  7. 6for each k in order do
  8. 7if Yk = Z then return k
  9. 8return the first index of order
  10. DEPENDENCIES(t) ▷ t: a tree over the words w1 … wn
  11. 9for each node v of t, children before parents do
  12. 10if v is a preterminal over word i then head(v) ← i
  13. 11else c ← HEAD-CHILD(label of v, labels of its children u1 … um); head(v) ← head(uc)
  14. 12for each k ≠ c do h(head(uk)) ← head(v)
  15. 13h(head(root)) ← 0
  16. 14return h
  17. NP-HEAD(Y1 … Ym)
  18. 15if Ym = POS then return m
  19. 16for each step (dir, set) in the list below, in order do
  20. 17for each k in the order of dir do
  21. 18if Yk ∈ set then return k
  22. 19return m

The steps of line L16 are: from the right, any of NN NNP NNPS NNS NX POS JJR; from the left, NP; from the right, any of $ ADJP PRN; from the right, CD; from the right, any of JJ JJS RB QP. Line L15 makes the possessive marker the head of a possessive NP such as "John 's", so that the whole phrase can attach to the noun it modifies. Line L8 is the fallback when no child label is in the list; for the entries with an empty list, such as PRN and FRAG, it is the only rule. Lines L9 to L12 visit the tree children first, so the head words of the children are known when line L11 needs them. The implementation keeps them on a stack instead of using recursion, because treebank trees can be deep.

Example

Take the tree

[S [NP-SBJ The company] [VP [MD will] [VP [VB sell] [NP its assets] [PP [TO to] [NP investors]]]] [. .]][_S\ [_{NP\text{-}SBJ}\ \text{The company}]\ [_{VP}\ [_{MD}\ \text{will}]\ [_{VP}\ [_{VB}\ \text{sell}]\ [_{NP}\ \text{its assets}]\ [_{PP}\ [_{TO}\ \text{to}]\ [_{NP}\ \text{investors}]]]]\ [_.\ .]]

with the words numbered 1 to 9: The, company, will, sell, its, assets, to, investors, ".". The preterminals are DT NN, MD, VB, PRP$ NNS, TO, NNS and the period. The walk finishes the phrases in this order.

step node child labels rule that fires head child head word arcs written
1 NP-SBJ DT NN NP-HEAD, first step NN company The → company
2 NP PRP$ NNS NP-HEAD, first step NNS assets its → assets
3 NP NNS line L1 NNS investors none
4 PP TO NP PP, right: no IN, then TO TO to investors → to
5 VP VB NP PP VP, left: VB is the first label of the list present VB sell assets → sell, to → sell
6 VP MD VP VP, left: MD comes before VP in the list MD will sell → will
7 S NP-SBJ VP . S, left: no TO or IN, then VP VP will company → will, . → will

Line L13 gives "will" the head 0. The result, with h(d)h(d) for d=1,…,9d = 1, \ldots, 9, is h=(2,3,0,3,6,4,4,7,3)h = (2, 3, 0, 3, 6, 4, 4, 7, 3). Step 6 shows a choice of the table: Collins makes the modal the head of the verb group, so the main verb "sell" depends on "will". Universal Dependencies makes the opposite choice. The tests check this tree and the sentence of Figure 1 of Klein and Manning (2004), "Factory payrolls fell in September", whose result h=(2,3,0,3,4)h = (2, 3, 0, 3, 4) matches the dependencies in that figure.

Correctness

Whatever the table says, the output is a dependency tree in the sense of the area: every word has exactly one head, the root 0 has exactly one child, there is no cycle, and the tree is projective. Each constituent is a connected piece of it: exactly one word of its span, the head word, has its head outside the span.

The key invariant is about a finished node vv: every word of its span except head(v)\mathrm{head}(v) has its final head inside the span and reaches head(v)\mathrm{head}(v) by following heads. A new node keeps the invariant because line L12 attaches the head words of the other children to the head word of the head child, and no later step touches a word of the span except head(v)\mathrm{head}(v). Projectivity follows because an arc written at vv joins two words of the span of vv, every word between them is in that span, and every word of the span is below head(v)\mathrm{head}(v). The full proof is in the correctness proof.

This is a theorem about the shape of the output. That the heads are linguistically right is a different claim, and it is only a heuristic.

Proof: Head rules turn every constituency tree into a projective dependency tree in which each constituent is a connected piece headed by its head wordfull

We use the pseudocode HEAD-CHILD and DEPENDENCIES of the page. The input is a finite ordered tree tt whose leaves are the words w1,…,wnw_1, \ldots, w_n, left to right, with n≥1n \ge 1. Each internal node has at least one child. The head table can be any table: the proof uses only that HEAD-CHILD returns one index between 1 and the number of children. That is the part we prove. Whether the chosen heads are good linguistic heads is a separate question, and the table is a heuristic for it.

For a node vv, yield(v)\mathrm{yield}(v) is the set of the positions of the words below vv. For a word ii, h(i)h(i) is the value that DEPENDENCIES writes for ii, with 0 standing for the artificial root. A word yy is a descendant of a word xx when following hh from yy reaches xx after zero or more steps.

Lemma 1: HEAD-CHILD returns a valid index

For a node with m≥1m \ge 1 children, HEAD-CHILD returns an index kk with 1≤k≤m1 \le k \le m.

Proof. Line L1 returns 1 when m=1m = 1. Line L7 returns an index of the scan order of line L4, which lists 1,…,m1, \ldots, m in some order. Line L8 returns the first index of that order. The NP branch is the same: lines L15 to L19 return mm, an index found by a scan of 1,…,m1, \ldots, m, or mm. □\square

Lemma 2: yields are intervals

For every node vv, yield(v)\mathrm{yield}(v) is an interval {a,…,b}\{a, \ldots, b\} of positions, and the yields of the children of vv, in order, are consecutive intervals that cover it.

Proof. The words are numbered in the left-to-right order of the leaves, and the leaves below a node are a contiguous run of that order, since the tree is ordered. □\square

Lemma 3: the invariant of the walk

DEPENDENCIES visits the nodes children first. When it has finished a node vv, it has set head(v)∈yield(v)\mathrm{head}(v) \in \mathrm{yield}(v), and:

  1. every word i∈yield(v)i \in \mathrm{yield}(v) with i≠head(v)i \ne \mathrm{head}(v) has an arc, and h(i)∈yield(v)h(i) \in \mathrm{yield}(v);
  2. following hh from any word of yield(v)\mathrm{yield}(v) reaches head(v)\mathrm{head}(v) after at most ∣yield(v)∣−1|\mathrm{yield}(v)| - 1 steps;
  3. no arc is written for head(v)\mathrm{head}(v) yet, and no arc written later changes h(i)h(i) for a word i∈yield(v)i \in \mathrm{yield}(v) other than head(v)\mathrm{head}(v).

Proof. By induction on the height of vv. A preterminal over word ii gets head(v)=i\mathrm{head}(v) = i at line L10 and writes no arc, so parts 1 and 2 hold. For part 3, see the last paragraph.

Let vv have the children u1,…,umu_1, \ldots, u_m, which are finished before vv because the walk is children first. Line L11 picks cc, a valid index by Lemma 1, and sets head(v)=head(uc)\mathrm{head}(v) = \mathrm{head}(u_c). Line L12 writes h(head(uk))=head(uc)h(\mathrm{head}(u_k)) = \mathrm{head}(u_c) for each k≠ck \ne c. These words lie in disjoint yields by Lemma 2, so each gets one arc here.

Part 1: a word ii of yield(uk)\mathrm{yield}(u_k) other than head(uk)\mathrm{head}(u_k) has h(i)∈yield(uk)⊆yield(v)h(i) \in \mathrm{yield}(u_k) \subseteq \mathrm{yield}(v) by part 1 for uku_k. The word head(uk)\mathrm{head}(u_k) with k≠ck \ne c now has h=head(uc)∈yield(v)h = \mathrm{head}(u_c) \in \mathrm{yield}(v).

Part 2: from a word of yield(uk)\mathrm{yield}(u_k), part 2 for uku_k reaches head(uk)\mathrm{head}(u_k) in at most ∣yield(uk)∣−1|\mathrm{yield}(u_k)| - 1 steps, and one more step reaches head(v)\mathrm{head}(v) if k≠ck \ne c. The total is at most ∣yield(uk)∣≤∣yield(v)∣−1|\mathrm{yield}(u_k)| \le |\mathrm{yield}(v)| - 1 when k≠ck \ne c, since ucu_c has at least one word outside yield(uk)\mathrm{yield}(u_k).

Part 3: line L12 at a node uu writes arcs only for the head words of the children of uu. If uu is a proper ancestor of vv, the only word of yield(v)\mathrm{yield}(v) that is the head word of a child of uu is head(v)\mathrm{head}(v), because the head word of a node is passed up only from its head child. If uu is not an ancestor of vv and not below it, its yield is disjoint from yield(v)\mathrm{yield}(v). So after vv is finished, the only word of yield(v)\mathrm{yield}(v) that can still get an arc is head(v)\mathrm{head}(v). □\square

Theorem

The list hh returned by DEPENDENCIES is a dependency tree on the words 1,…,n1, \ldots, n with the root 0: exactly one word has h(i)=0h(i) = 0, every other word has a head among the words, and following hh from any word reaches 0. The tree is projective. For every node vv of tt, exactly one word of yield(v)\mathrm{yield}(v), namely head(v)\mathrm{head}(v), has its head outside yield(v)\mathrm{yield}(v) or at 0, and every other word of yield(v)\mathrm{yield}(v) reaches head(v)\mathrm{head}(v) through words of yield(v)\mathrm{yield}(v).

Proof. Apply Lemma 3 to the root rr, whose yield is all of 1,…,n1, \ldots, n. Every word except head(r)\mathrm{head}(r) has a head among the words (part 1), and line L13 sets h(head(r))=0h(\mathrm{head}(r)) = 0. By part 2 every word reaches head(r)\mathrm{head}(r), and then 0, so there is no cycle.

Constituents: fix a node vv. By part 3 the arcs of the words of yield(v)\mathrm{yield}(v) other than head(v)\mathrm{head}(v) are final when vv is finished. By part 1 their heads lie in yield(v)\mathrm{yield}(v), and by part 2 they reach head(v)\mathrm{head}(v) inside yield(v)\mathrm{yield}(v). The word head(v)\mathrm{head}(v) gets its head later at an ancestor, outside yield(v)\mathrm{yield}(v) because the yields of the other children are disjoint from it, or 0 at line L13.

Projectivity: take an arc h(d)=xh(d) = x with d≠xd \ne x, written at line L12 while processing a node vv. Then x=head(v)x = \mathrm{head}(v), and both dd and xx are in yield(v)\mathrm{yield}(v), which is an interval by Lemma 2. So every word strictly between them is in yield(v)\mathrm{yield}(v), and by part 2 for vv it reaches head(v)=x\mathrm{head}(v) = x. Every word between dd and xx is thus a descendant of xx, which is the definition of a projective arc. □\square

The subtree of head(v)\mathrm{head}(v) in the final tree can be larger than yield(v)\mathrm{yield}(v): when vv is the head child of its parent, the heads of its siblings attach to head(v)\mathrm{head}(v) too.

Termination and cost

Each node is pushed once unfinished and once finished, so the walk of line L9 runs 2s2s times for a tree of ss nodes. HEAD-CHILD on a node with mm children scans at most mm children once for each of the at most ℓ\ell labels of the priority list, so its cost is O(mℓ)O(m \ell), and the sum of mm over all nodes is s−1s - 1. The total time is O(sℓ)O(s \ell), which is linear for a fixed table. ■\blacksquare

Complexity

Time. For a node with mm children, HEAD-CHILD runs the loop of lines L5 to L7 at most ℓ⋅m\ell \cdot m times, where ℓ\ell is the length of the longest priority list. The sum of mm over all nodes is s−1s - 1 for a tree of ss nodes, so the time is O(sℓ)O(s \ell) on the word RAM. With a fixed table, ℓ≤18\ell \le 18 is a constant and the time is Θ(s)\Theta(s). If the first label of each list matches at once, every node costs O(1)O(1) after its children, which gives the best case Θ(s)\Theta(s).

Space. The explicit stack of the walk and the stack of head words hold O(s)O(s) entries, and the output has n+1n + 1 entries.

Properties

  • Deterministic and total. Every node gets exactly one head child, because line L8 always has an answer.
  • The output is projective. No conversion by head rules can produce crossing arcs. Non-projective structure in a treebank lives in its traces and empty elements, which head rules ignore.
  • One root child. The root gets exactly one dependent, the head word of the top node.
  • Local. The head of a node depends only on its own label and the labels of its children, not on the words.
  • The list order beats the child order. The outer loop runs over the list, so a VP with the children NN VBD picks VBD, the second child, because VBD comes before NN in the list.

Variants and improvements

  • Coordination. Collins also moves the head in a coordinated phrase: when the child just before the chosen head is CC, the head moves to the conjunct before it. The CoreNLP implementation does this in a separate step. The code on this page leaves it out.
  • Other tables. Some later converters choose content words as heads, so the main verb heads a verb group and the noun heads a prepositional phrase. Universal Dependencies follows this choice. The algorithm stays the same; only the table changes, and the code takes the table as an argument.
  • Lexicalization. In a lexicalized PCFG, each nonterminal carries its head word and tag. The head rules decide which child passes its head up, and the model generates the other children as dependents of that head.

When to use it

Use a head table when a treebank has only phrase-structure trees and you need head words: to train a lexicalized parser, to make gold dependencies for dependency parsing or an attachment score, or to evaluate an unsupervised model such as the dependency model with valence. Use the same table for training and evaluation, and name it. If the treebank already has dependency annotation, use that instead.

Pitfalls

  • Priority order and position order mixed up. Lines L5 and L6 loop over the list first and the children second. Swapping them makes line L7 return the first child in the scan whose label is anywhere in the list. For a VP with the children NN VBD, the swapped loops return NN, while the right answer is VBD, which comes earlier in the list.
  • Function tags not stripped. The Penn Treebank writes NP-SBJ, PP-LOC or NP-1. Looking these up without removing the suffix makes line L3 miss the entry and fall back to the leftmost child.
  • Empty elements and traces. Remove -NONE- preterminals and their empty parents before line L9, or they become words of the dependency tree.
  • Different tables give different scores. Klein and Manning (2004) report that making determiners the heads of noun phrases changes the directed accuracy of their model on WSJ10 from 43.2% to 55.7%. This is a measurement. An attachment score is only comparable with the same head table.
  • Deep trees. A recursive walk can hit Python's recursion limit on long right-branching phrases. Line L9 needs an explicit stack.

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.

head_rules.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/head-rules/. The authors are listed in prov/EXAQEX.jsonl.

"""Head rules: pick the head child of each phrase and turn a tree into dependencies.

A tree is (label, children). A preterminal is (tag, word) with word a string.
An internal node is (label, list of trees). The table is the head table of
Collins (1999, appendix A) in the form used by the Stanford CollinsHeadFinder,
without its extra AUX and NX entries for the parent. Function tags such as the
"-SBJ" in "NP-SBJ" are removed before a label is looked up.

The words are numbered 1 to n from the left. to_dependencies returns the list
h with h[i] the head of word i, h[0] unused, and 0 for the word that heads the
whole sentence.
"""

from typing import Dict, List, Sequence, Tuple, Union

Tree = Tuple[str, Union[str, list]]

LEFT, RIGHT = "left", "right"

# label -> (direction, priority list). "left" scans the children from the left,
# "right" from the right, once for each label of the list in order.
COLLINS: Dict[str, Tuple[str, Tuple[str, ...]]] = {
    "ADJP": (LEFT, ("NNS", "QP", "NN", "$", "ADVP", "JJ", "VBN", "VBG", "ADJP", "JJR",
                    "NP", "JJS", "DT", "FW", "RBR", "RBS", "SBAR", "RB")),
    "ADVP": (RIGHT, ("RB", "RBR", "RBS", "FW", "ADVP", "TO", "CD", "JJR", "JJ", "IN",
                     "NP", "JJS", "NN")),
    "CONJP": (RIGHT, ("CC", "RB", "IN")),
    "FRAG": (RIGHT, ()),
    "INTJ": (LEFT, ()),
    "LST": (RIGHT, ("LS", ":")),
    "NAC": (LEFT, ("NN", "NNS", "NNP", "NNPS", "NP", "NAC", "EX", "$", "CD", "QP",
                   "PRP", "VBG", "JJ", "JJS", "JJR", "ADJP", "FW")),
    "PP": (RIGHT, ("IN", "TO", "VBG", "VBN", "RP", "FW")),
    "PRN": (LEFT, ()),
    "PRT": (RIGHT, ("RP",)),
    "QP": (LEFT, ("$", "IN", "NNS", "NN", "JJ", "RB", "DT", "CD", "NCD", "QP", "JJR",
                  "JJS")),
    "RRC": (RIGHT, ("VP", "NP", "ADVP", "ADJP", "PP")),
    "S": (LEFT, ("TO", "IN", "VP", "S", "SBAR", "ADJP", "UCP", "NP")),
    "SBAR": (LEFT, ("WHNP", "WHPP", "WHADVP", "WHADJP", "IN", "DT", "S", "SQ", "SINV",
                    "SBAR", "FRAG")),
    "SBARQ": (LEFT, ("SQ", "S", "SINV", "SBARQ", "FRAG")),
    "SINV": (LEFT, ("VBZ", "VBD", "VBP", "VB", "MD", "VP", "S", "SINV", "ADJP", "NP")),
    "SQ": (LEFT, ("VBZ", "VBD", "VBP", "VB", "MD", "VP", "SQ")),
    "UCP": (RIGHT, ()),
    "VP": (LEFT, ("TO", "VBD", "VBN", "MD", "VBZ", "VB", "VBG", "VBP", "VP", "ADJP",
                  "NN", "NNS", "NP")),
    "WHADJP": (LEFT, ("CC", "WRB", "JJ", "ADJP")),
    "WHADVP": (RIGHT, ("CC", "WRB")),
    "WHNP": (LEFT, ("WDT", "WP", "WP$", "WHADJP", "WHPP", "WHNP")),
    "WHPP": (RIGHT, ("IN", "TO", "FW")),
    "X": (RIGHT, ()),
}

# The NP rule of Collins: a list of (direction, label set) steps. Within one step
# the scan goes by position and stops at the first child whose label is in the set.
NP_STEPS = (
    (RIGHT, frozenset(("NN", "NNP", "NNPS", "NNS", "NX", "POS", "JJR"))),
    (LEFT, frozenset(("NP",))),
    (RIGHT, frozenset(("$", "ADJP", "PRN"))),
    (RIGHT, frozenset(("CD",))),
    (RIGHT, frozenset(("JJ", "JJS", "RB", "QP"))),
)


def base_label(label: str) -> str:
    """Return the label without function tags and indices: NP-SBJ-1 gives NP."""
    if label.startswith("-"):
        return label  # -NONE-, -LRB-, -RRB-
    for sep in "-=":
        k = label.find(sep)
        if k > 0:
            label = label[:k]
    return label


def _order(direction: str, m: int) -> range:
    return range(m) if direction == LEFT else range(m - 1, -1, -1)


def np_head(labels: Sequence[str]) -> int:
    """Return the 0-based index of the head child of an NP with these child labels."""
    m = len(labels)
    if labels[m - 1] == "POS":  # @line L15
        return m - 1
    for direction, wanted in NP_STEPS:  # @line L16
        for k in _order(direction, m):  # @line L17
            if labels[k] in wanted:  # @line L18
                return k
    return m - 1  # @line L19


def head_child(label: str, child_labels: Sequence[str], table=None) -> int:
    """Return the 0-based index of the head child of a node.

    label is the parent label and child_labels the labels of its children, in
    order. An unknown parent label scans from the left with an empty list, so
    its head is the leftmost child.
    """
    if table is None:
        table = COLLINS
    labels = [base_label(x) for x in child_labels]
    m = len(labels)
    if m == 0:
        raise ValueError("a node without children has no head child")
    if m == 1:  # @line L1
        return 0
    x = base_label(label)
    if x == "NP" and table is COLLINS:  # @line L2
        return np_head(labels)
    direction, priority = table.get(x, (LEFT, ()))  # @line L3
    order = _order(direction, m)  # @line L4
    for z in priority:  # @line L5
        for k in order:  # @line L6
            if labels[k] == z:  # @line L7
                return k
    return order[0]  # @line L8


def is_preterminal(t: Tree) -> bool:
    return isinstance(t[1], str)


def words(t: Tree) -> List[str]:
    """Return the words of t, left to right."""
    out: List[str] = []
    stack = [t]
    while stack:
        u = stack.pop()
        if is_preterminal(u):
            out.append(u[1])
        else:
            stack.extend(reversed(u[1]))
    return out


def to_dependencies(t: Tree, table=None) -> List[int]:
    """Return h with h[i] the head word of word i (1-based) and 0 for the root word.

    Each node passes up the head word of its head child. Every other child
    attaches its head word to that word. The walk is iterative, children first.
    """
    n = len(words(t))
    h = [0] * (n + 1)
    heads: List[int] = []  # lexical heads of the finished subtrees, left to right
    position = 0
    stack: List[Tuple[Tree, bool]] = [(t, False)]
    while stack:  # @line L9
        u, done = stack.pop()
        if is_preterminal(u):
            position += 1
            heads.append(position)  # @line L10
            continue
        kids = u[1]
        if not kids:
            raise ValueError("an internal node has no children")
        if not done:
            stack.append((u, True))
            for c in reversed(kids):
                stack.append((c, False))
            continue
        m = len(kids)
        child_heads = heads[len(heads) - m:]
        del heads[len(heads) - m:]
        c = head_child(u[0], [k[0] for k in kids], table)  # @line L11
        for k in range(m):  # @line L12
            if k != c:
                h[child_heads[k]] = child_heads[c]
        heads.append(child_heads[c])
    h[heads[0]] = 0  # @line L13
    return h  # @line L14


def read_tree(s: str) -> Tree:
    """Read a tree in Penn Treebank bracket form, such as (S (NP (NN dogs)) (VP (VBP bark)))."""
    tokens = s.replace("(", " ( ").replace(")", " ) ").split()
    pos = 0

    def parse() -> Tree:
        nonlocal pos
        if tokens[pos] != "(":
            raise ValueError("expected (")
        pos += 1
        label = tokens[pos]
        pos += 1
        if tokens[pos] not in ("(", ")"):
            word = tokens[pos]
            pos += 1
            if tokens[pos] != ")":
                raise ValueError("expected ) after a word")
            pos += 1
            return (label, word)
        kids = []
        while tokens[pos] == "(":
            kids.append(parse())
        if tokens[pos] != ")":
            raise ValueError("expected )")
        pos += 1
        return (label, kids)

    tree = parse()
    if pos != len(tokens):
        raise ValueError("text after the tree")
    return tree
test_head_rules.py 186 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/head-rules/. The authors are listed in prov/EXAQEX.jsonl.

import random

from head_rules import (COLLINS, base_label, head_child, np_head, read_tree,
                        to_dependencies, words)


def deps(s):
    return to_dependencies(read_tree(s))


def test_klein_manning_figure() -> None:
    # Klein and Manning (2004), Figure 1: Factory payrolls fell in September.
    s = "(S (NP (NN Factory) (NNS payrolls)) (VP (VBD fell) (PP (IN in) (NP (NN September)))))"
    assert deps(s) == [0, 2, 3, 0, 3, 4]


def test_page_example() -> None:
    s = ("(S (NP-SBJ (DT The) (NN company)) (VP (MD will) (VP (VB sell) "
         "(NP (PRP$ its) (NNS assets)) (PP (TO to) (NP (NNS investors))))) (. .))")
    t = read_tree(s)
    assert words(t) == ["The", "company", "will", "sell", "its", "assets", "to", "investors", "."]
    assert to_dependencies(t) == [0, 2, 3, 0, 3, 6, 4, 4, 7, 3]


def test_np_rule() -> None:
    assert np_head(["DT", "JJ", "NN"]) == 2
    assert np_head(["NP", "PP"]) == 0
    assert np_head(["NNP", "POS"]) == 1
    assert np_head(["NP", "NN"]) == 1
    assert np_head(["CD", "NNS"]) == 1
    assert np_head(["DT", "CD"]) == 1
    assert np_head(["DT", "JJ"]) == 1
    assert np_head(["DT", "DT"]) == 1
    assert np_head(["NN", "NN", "PP"]) == 1
    assert np_head(["NP", ",", "NP", ","]) == 0
    # possessive: John 's dog. The inner NP is headed by 's, the outer by dog.
    assert deps("(NP (NP (NNP John) (POS 's)) (NN dog))") == [0, 2, 3, 0]


def test_table_rules() -> None:
    assert head_child("PP", ["IN", "NP"]) == 0
    assert head_child("PP", ["TO", "NP"]) == 0
    assert head_child("PP", ["NP", "IN"]) == 1
    assert head_child("SBAR", ["IN", "S"]) == 0
    assert head_child("SBAR", ["WHNP", "S"]) == 0
    assert head_child("VP", ["MD", "VP"]) == 0
    assert head_child("VP", ["VB", "NP", "PP"]) == 0
    assert head_child("VP", ["ADVP", "VBD", "NP"]) == 1
    assert head_child("S", ["NP-SBJ", "VP", "."]) == 1
    assert head_child("ADVP", ["RB", "RB"]) == 1  # right to left
    assert head_child("ADJP", ["RB", "JJ"]) == 1
    # priority beats position: S lists VP before NP
    assert head_child("S", ["VP", "NP"]) == 0
    assert head_child("VP", ["NN", "VBD"]) == 1
    # no match: the first child in the scan direction
    assert head_child("ADJP", [",", "CC"]) == 0
    assert head_child("ADVP", [",", "CC"]) == 1
    assert head_child("FRAG", ["NP", "PP", "."]) == 2
    assert head_child("PRN", ["-LRB-", "NP", "-RRB-"]) == 0
    # unknown label: leftmost
    assert head_child("ZZZ", ["A", "B", "C"]) == 0
    # single child
    assert head_child("NP", ["PRP"]) == 0


def test_labels() -> None:
    assert base_label("NP-SBJ-1") == "NP"
    assert base_label("PP-LOC=2") == "PP"
    assert base_label("-NONE-") == "-NONE-"
    assert base_label("-LRB-") == "-LRB-"
    assert head_child("PP-LOC", ["IN", "NP-1"]) == 0


def test_custom_table() -> None:
    table = {"PP": ("left", ("NP",))}
    assert head_child("PP", ["IN", "NP"], table) == 1
    assert deps("(PP (IN in) (NP (NN May)))") == [0, 0, 1]
    assert to_dependencies(read_tree("(PP (IN in) (NP (NN May)))"), table) == [0, 2, 0]


LABELS = sorted(COLLINS) + ["NP", "NP", "NX", "ZZ"]
TAGS = ["NN", "NNS", "NNP", "VB", "VBD", "MD", "IN", "TO", "DT", "JJ", "RB", "CD", "POS", ",", ".", "CC"]


def random_tree(rng, n):
    """A random tree with n words (preterminals) and random labels."""
    nodes = [(rng.choice(TAGS), "w") for _ in range(n)]
    while len(nodes) > 1:
        a = rng.randrange(len(nodes))
        b = rng.randrange(a + 1, min(len(nodes), a + 4) + 1)
        kids = nodes[a:b]
        nodes[a:b] = [(rng.choice(LABELS), kids)]
        if rng.random() < 0.2:
            nodes[a] = (rng.choice(LABELS), [nodes[a]])  # a unary node
    if not isinstance(nodes[0][1], list):
        nodes[0] = ("S", [nodes[0]])
    return nodes[0]


def reference(t, start, h):
    """Recursive reference: return the head word of t, whose first word is start."""
    if isinstance(t[1], str):
        return start
    heads = []
    pos = start
    for c in t[1]:
        heads.append(reference(c, pos, h))
        pos += len(words(c))
    c = head_child(t[0], [k[0] for k in t[1]])
    for k, x in enumerate(heads):
        if k != c:
            h[x] = heads[c]
    return heads[c]


def spans(t, start, out):
    """Collect the (first word, last word) of every internal node."""
    n = len(words(t))
    if not isinstance(t[1], str):
        out.append((start, start + n - 1))
        pos = start
        for c in t[1]:
            spans(c, pos, out)
            pos += len(words(c))
    return out


def ancestors(h, i):
    out = set()
    while i != 0:
        i = h[i]
        if i in out or len(out) > len(h):
            raise AssertionError("cycle")
        out.add(i)
    return out


def test_random_trees() -> None:
    rng = random.Random(7)
    for trial in range(600):
        n = rng.randint(1, 12)
        t = random_tree(rng, n)
        h = to_dependencies(t)
        assert len(h) == n + 1
        ref = [0] * (n + 1)
        root = reference(t, 1, ref)
        ref[root] = 0
        assert h == ref
        # a tree: one root word and no cycle
        assert sum(1 for i in range(1, n + 1) if h[i] == 0) == 1
        anc = {i: ancestors(h, i) for i in range(1, n + 1)}
        # projective: every word strictly between a head and its dependent is
        # a descendant of the head
        for d in range(1, n + 1):
            if h[d] == 0:
                continue
            lo, hi = sorted((d, h[d]))
            for x in range(lo + 1, hi):
                assert h[d] in anc[x]
        # every constituent is a subtree: exactly one word of its span has
        # its head outside the span
        for a, b in spans(t, 1, []):
            outside = [i for i in range(a, b + 1) if not a <= h[i] <= b]
            assert len(outside) == 1


def test_deep_tree() -> None:
    # a right-branching tree 3000 levels deep: the walk is iterative
    t = ("NN", "w")
    for _ in range(3000):
        t = ("NP", [("DT", "w"), t])
    h = to_dependencies(t)
    assert h[3001] == 0
    assert all(h[i] == 3001 for i in range(1, 3001))


def test_read_tree_errors() -> None:
    for bad in ["(S (NP", "(S (NN a b))", "(S (NN a)) x", "NN"]:
        try:
            read_tree(bad)
        except (ValueError, IndexError):
            continue
        raise AssertionError(bad)

History

Head words entered statistical parsing in the early 1990s, when parsers began to condition rule choices on lexical items. Magerman (1995) passed head words up the trees of his decision-tree parser with a table of this kind. Collins revised the table for his parsers of the late 1990s and printed it in appendix A of his 1999 thesis, together with the special NP rule. That table, as implemented in tools such as the CollinsHeadFinder of Stanford CoreNLP, became the standard way to read dependencies off the Penn Treebank, and it was used to make the gold dependencies of many papers, for example the WSJ10 evaluation of Klein and Manning (2004).

References

  1. Michael Collins, Head-Driven Statistical Models for Natural Language Parsing, PhD thesis, Appendix A, the head table and the special rule for NP
  2. David M. Magerman, Statistical Decision-Tree Models for Parsing, ACL 1995, pp. 276 to 283
  3. Michael Collins, Head-Driven Statistical Models for Natural Language Parsing, Computational Linguistics 29(4), 2003, pp. 589 to 637, the head-driven models that use the head table
  4. Dan Klein and Christopher D. Manning, Corpus-Based Induction of Syntactic Structure, Models of Dependency and Constituency, ACL 2004, the evaluation section, gold dependencies read off the Penn Treebank with the Collins head rules, and the change of the NP head to the determiner
  5. Stanford CoreNLP, CollinsHeadFinder, an implementation of the head finder of the Collins thesis, the table nonTerminalInfo and the coordination fix in postOperationFix

Where this leads

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
  • a scene preset for the example