Algorithm Search⌘K

Algorithmadvanced

Feature structure unification

Also called graph unification.

Merge two feature structures, directed graphs of attribute values, into the most general one that has the information of both, or fail.

Time
O((n + e) α(n) + e log e) expected
Space
O(n + e) extra
Where
e = the number of arcs of the two inputs; n = the number of nodes of the two inputs
Properties
destructivedeterministicexactofflineiterative
Origin
Hassan Aït Kaci, Stuart M. Shieber, 1984

Feature structure unification takes two feature structures, rooted directed graphs whose arcs carry features such as number and whose leaves carry atoms such as singular, and builds the most general structure that has the information of both, or fails when they disagree. Two paths can lead to the same node, which is how a grammar says that two values must be equal. It differs from the first-order unification problem of terms in three ways: features are named, not numbered by position, an empty node plays the role of a variable, and cycles are allowed, so there is no occurs check. It is the one operation of unification-based grammars such as PATR-II, LFG and HPSG, and it adds agreement and other features to CCG and TAG.

The method on this page is the one of Huet's algorithm for terms: put the nodes of both graphs in a disjoint-set forest and merge classes that must be equal. Because features are named, a node can gain new features in a merge, and the algorithm must merge feature tables, not fixed argument lists.

In plain words

A feature structure is a bundle of facts about a phrase. One bundle says that the subject is singular. Another says that the subject is third person. Unification puts the two bundles together, so the result says that the subject is singular and third person. If one bundle says singular and the other says plural, the bundles cannot go together, and unification fails.

Some bundles share parts. A rule can say that the agreement of a verb phrase is the same object as the agreement of its subject. When new facts arrive at one place, they also hold at every place that shares it.

The algorithm keeps groups of nodes that must be the same, starting with the two top nodes. When it joins two groups, a feature that both have gives two more nodes that must be the same, and it joins those too.

The problem

Input. Two feature structures AA and BB with disjoint node sets. Each has a root, a partial function δ(x,f)\delta(x, f) that gives the value of feature ff at node xx, and a partial atom label atom(x)\mathrm{atom}(x). A node with an atom has no features. A node with no atom and no feature is the empty structure [ ][\,].

Order. AA subsumes DD, written A⊑DA \sqsubseteq D, if DD has at least the information of AA: there is a map hh from the nodes of AA to the nodes of DD that sends the root to the root, each arc x→fyx \xrightarrow{f} y to an arc h(x)→fh(y)h(x) \xrightarrow{f} h(y), and each atom to the same atom. In Shieber's terms: every path of AA is a path of DD with the same atom value, and paths that share a node in AA share a node in DD. The empty structure subsumes every structure.

Output. The unification A⊔BA \sqcup B: a structure CC with A⊑CA \sqsubseteq C and B⊑CB \sqsubseteq C such that C⊑DC \sqsubseteq D for every DD that both AA and BB subsume. It is unique up to renaming of the nodes. If no DD is subsumed by both inputs, the output is failure.

Write nn for the number of nodes and ee for the number of arcs of AA and BB together.

The algorithm

Every node has the union-find fields parent and rank, an atom or nothing, and a table of features. Only the table of a class root is used; it holds one value for each feature of the class.

  1. UNIFY(a, b) ▷ a, b: the roots of the two inputs
  2. 1stack ← [(a, b)]
  3. 2while stack is not empty do
  4. 3pop (u, v); x ← FIND(u); y ← FIND(v)
  5. 4if x = y then continue
  6. 5if CLASH(x, y) then return FAIL
  7. 6if rank(x) < rank(y) then swap x and y; parent(y) ← x; if rank(x) = rank(y) then rank(x) ← rank(x) + 1
  8. 7if atom(x) is undefined then atom(x) ← atom(y)
  9. 8(big, small) ← the tables of x and y, the larger first
  10. 9for each feature f with value w in small do
  11. 10if f is in big then push (big[f], w)
  12. 11else big[f] ← w
  13. 12table(x) ← big; clear the table and the atom of y
  14. 13return FIND(a)
  15. CLASH(x, y) is true if x and y have different atoms, or one of them has an atom and the other has a feature.

Line L3 takes a pair of nodes that must be equal and finds their class roots with path compression. Line L6 is union by rank. Lines L8 to L11 merge the two feature tables. A feature in only one table moves over unchanged. A feature in both tables gives a new pair of nodes that must be equal, which goes on the stack. The loop uses a stack, not recursion, so deep structures such as long lists do not overflow the call stack.

The algorithm is destructive: it changes the input graphs. A parser that needs the inputs again copies them first. On failure the inputs are left half merged, so a parser that unifies in place must copy or undo.

Example

Shieber's example of reentrancy, from section 3.2.3 of his book. The tag 1\boxed{1} marks a shared node.

A=[agreement:1 [number:singular]subject:[agreement:1]]B=[subject:[agreement:[person:third]]]A = \begin{bmatrix} \text{agreement}: \boxed{1}\,[\text{number}: \text{singular}] \\ \text{subject}: [\text{agreement}: \boxed{1}] \end{bmatrix} \qquad B = \big[\text{subject}: [\text{agreement}: [\text{person}: \text{third}]]\big]

Call the nodes of AA: rAr_A (root), sAs_A (the subject), gg (the shared agreement) and the atom node of singular. Call the nodes of BB: rBr_B, sBs_B, gBg_B and the atom node of third. The run:

pass pair popped tables merged moved pushed
1 (rA,rB)(r_A, r_B) {agreement, subject} and {subject} none (sA,sB)(s_A, s_B)
2 (sA,sB)(s_A, s_B) {agreement} and {agreement} none (g,gB)(g, g_B)
3 (g,gB)(g, g_B) {number} and {person} person none

After three merges the stack is empty and the result is

A⊔B=[agreement:1 [number:singular, person:third]subject:[agreement:1]]A \sqcup B = \begin{bmatrix} \text{agreement}: \boxed{1}\,[\text{number}: \text{singular},\ \text{person}: \text{third}] \\ \text{subject}: [\text{agreement}: \boxed{1}] \end{bmatrix}

The new fact person: third came in through the subject, and it also holds at the top-level agreement, because the two paths lead to one node. If AA had two separate copies of [number: singular] instead of one shared node, the result would have person: third only under the subject. The tests check both cases.

A clash: [number:singular]⊔[number:plural][\text{number}: \text{singular}] \sqcup [\text{number}: \text{plural}]. Pass 1 merges the roots and pushes the two values of number. Pass 2 finds two different atoms at line L5 and returns failure.

A cycle: A=[a:1 [ ], b:1]A = [a: \boxed{1}\,[\,],\ b: \boxed{1}] and B=[a:[h:2 [ ]], b:2]B = [a: [h: \boxed{2}\,[\,]],\ b: \boxed{2}]. Unification makes the node under aa equal to the node under bb, which is the value of hh inside it. The result has a node xx with x.h=xx.h = x, so the path a h h ha\,h\,h\,h leads back to the node of aa. With an occurs check this would fail; without one it gives a cyclic structure.

Correctness

The claim is a theorem: UNIFY returns A⊔BA \sqcup B when it exists, returns failure exactly when no structure is subsumed by both inputs, and stops after at most e+1e + 1 passes. The full proof is in proofs/correctness.md. Its outline:

  1. Call an equivalence relation on the nodes a unifying congruence if it puts the two roots together and, whenever it puts xx and yy together and both have feature ff, it also puts δ(x,f)\delta(x, f) and δ(y,f)\delta(y, f) together. Let θ\theta be the least one.
  2. If no class of θ\theta holds two different atoms, or an atom and a feature, then the quotient graph by θ\theta is A⊔BA \sqcup B. Any DD that both inputs subsume defines a congruence by "same image in DD", which contains θ\theta, so the quotient maps into DD. If θ\theta has a bad class, then so does that congruence, and no DD exists.
  3. UNIFY keeps the invariant that every pair it joins or pushes is in θ\theta, and that the table of each root holds every feature of its class, with a value that is equal to the value of each member, up to pairs still on the stack. When the stack is empty, the classes are closed under the congruence condition, so they are exactly θ\theta. A clash at line L5 shows a bad class of θ\theta.
Proof: UNIFY returns the most general structure that both inputs subsume, or fails exactly when none exists, and it stopsfull

We use the pseudocode UNIFY of the page and the definitions below. The proof has three parts. Part 1 describes the answer as the least congruence on the nodes of the two inputs. Part 2 shows that this answer is the least upper bound under subsumption, which is Shieber's definition of unification. Part 3 shows that UNIFY computes the least congruence, finds every clash, and stops.

Definitions

A feature structure AA is a finite set of nodes with a root rAr_A, a partial function δA(x,f)\delta_A(x, f) that gives the value of feature ff at node xx, and a partial atom label atom(x)\mathrm{atom}(x). A node with an atom has no features. A node with no atom and no feature is empty. Cycles and shared nodes (reentrancy) are allowed. We assume that every node is reachable from the root.

AA subsumes DD, written A⊑DA \sqsubseteq D, if there is a map hh from the nodes of AA to the nodes of DD with h(rA)=rDh(r_A) = r_D, with h(δA(x,f))=δD(h(x),f)h(\delta_A(x, f)) = \delta_D(h(x), f) whenever δA(x,f)\delta_A(x, f) is defined (so the right side is defined too), and with atom(h(x))=atom(x)\mathrm{atom}(h(x)) = \mathrm{atom}(x) whenever atom(x)\mathrm{atom}(x) is defined. Because every node is reached by a path from the root and each step of a path is forced, hh is unique if it exists. This is the same as Shieber's definition in terms of paths: every path of AA is a path of DD, every atom value of a path of AA is the same in DD, and two paths that lead to one node of AA lead to one node of DD.

Let the inputs AA and BB have disjoint node sets, and let UU be their union, with nn nodes and ee arcs in all. An equivalence relation ≡\equiv on UU is a unifying congruence if

  1. rA≡rBr_A \equiv r_B, and
  2. if x≡yx \equiv y and both δ(x,f)\delta(x, f) and δ(y,f)\delta(y, f) are defined, then δ(x,f)≡δ(y,f)\delta(x, f) \equiv \delta(y, f).

It is consistent if no class holds two nodes with different atoms, and no class holds a node with an atom and a node with a feature. The intersection of unifying congruences is a unifying congruence, and the relation that puts all of UU in one class is one, so there is a least one. Call it θ\theta.

If θ\theta is consistent, the quotient U/θU/\theta is a feature structure: its nodes are the classes, its root is the class of rAr_A, the value of ff at a class CC is the class of δ(x,f)\delta(x, f) for any x∈Cx \in C that has ff (condition 2 makes this independent of the choice), and the atom of CC is the atom of its members, if any. Consistency makes the atoms well defined and keeps atoms and features apart. We keep only the classes reachable from the root.

Part 1 and 2: the quotient is the least upper bound

Lemma 1. If θ\theta is consistent, then A⊑U/θA \sqsubseteq U/\theta and B⊑U/θB \sqsubseteq U/\theta.

Proof. Map each node to its class. The root of AA goes to the root class, and the root of BB goes there too because rA θ rBr_A \,\theta\, r_B. Arcs and atoms are kept by the definition of the quotient. ∎

Lemma 2. If A⊑DA \sqsubseteq D and B⊑DB \sqsubseteq D for some feature structure DD, then θ\theta is consistent and U/θ⊑DU/\theta \sqsubseteq D.

Proof. Let hAh_A and hBh_B be the two maps into DD, and let hh be their union on UU. Define x∼yx \sim y if h(x)=h(y)h(x) = h(y). This is an equivalence relation. It holds for rAr_A and rBr_B, because both go to rDr_D. If x∼yx \sim y and both have ff, then h(δ(x,f))=δD(h(x),f)=δD(h(y),f)=h(δ(y,f))h(\delta(x, f)) = \delta_D(h(x), f) = \delta_D(h(y), f) = h(\delta(y, f)), so condition 2 holds. Hence ∼\sim is a unifying congruence and θ⊆∼\theta \subseteq {\sim}.

A class of θ\theta lies inside a class of ∼\sim, so all its nodes go to one node zz of DD. If two of them had different atoms, zz would carry both. If one had an atom and another had a feature, zz would carry an atom and a feature. Neither is possible in DD, so θ\theta is consistent. The map [x]↦h(x)[x] \mapsto h(x) is well defined on U/θU/\theta because θ⊆∼\theta \subseteq {\sim}, and it keeps the root, the arcs and the atoms because hh does. So U/θ⊑DU/\theta \sqsubseteq D. ∎

Lemmas 1 and 2 say that, when θ\theta is consistent, U/θU/\theta is subsumed by both inputs and subsumes every structure that both inputs subsume. This is Shieber's definition of the unification A⊔BA \sqcup B. When θ\theta is not consistent, Lemma 2 says that no structure is subsumed by both inputs, so unification must fail.

Part 3: UNIFY computes θ\theta

Let PP be the partition of the union-find forest (two nodes are in one block if they have the same root). Let ≈\approx be the equivalence relation generated by PP and by the pairs on the stack. We show four invariants, true at the test of line L2.

  • (I1) ≈⊆θ{\approx} \subseteq \theta.
  • (I2) For every block with root xx, every member yy and every feature ff of yy, the table arcs(x)\mathrm{arcs}(x) has an entry for ff, and arcs(x)[f]≈δ(y,f)\mathrm{arcs}(x)[f] \approx \delta(y, f). If some member has an atom, atom(x)\mathrm{atom}(x) is that atom.
  • (I3) Every block of PP is consistent, and arcs(x)\mathrm{arcs}(x) is empty for a root xx whose block has no member with a feature.
  • (I4) rA≈rBr_A \approx r_B.

Start. Line L1 puts the pair (rA,rB)(r_A, r_B) on the stack. Every block is a single node with its own atom and features. (I1) holds because rA θ rBr_A \,\theta\, r_B. (I2) and (I3) hold because each node is its own root and an input node with an atom has no features. (I4) holds by the pair on the stack.

A step that does not merge. Line L3 pops (u,v)(u, v) and finds the roots xx and yy. If x=yx = y (line L4), then uu and vv were already in one block, so removing the pair does not change ≈\approx. All invariants stay true.

A clash. Suppose line L5 finds a clash between the roots xx and yy. By (I1), u θ vu \,\theta\, v, so xx and yy and their blocks lie in one class of θ\theta. By (I2) and (I3), a root atom is the atom of a member, and a non-empty table means that a member has a feature. So the class of θ\theta holds two different atoms, or an atom and a feature. Then θ\theta is not consistent, and by Lemma 2 failure is the right answer.

A merge. Otherwise lines L6 to L12 join the blocks of xx and yy. The pair (u,v)(u, v) leaves the stack, but uu and vv are now in one block, so ≈\approx does not lose it. The new pairs are (big[f],small[f])(\mathrm{big}[f], \mathrm{small}[f]) for each feature ff in both tables. By (I2) there are members m1m_1 and m2m_2 of the two blocks with big[f]≈δ(m1,f)\mathrm{big}[f] \approx \delta(m_1, f) and small[f]≈δ(m2,f)\mathrm{small}[f] \approx \delta(m_2, f). We have m1 θ m2m_1 \,\theta\, m_2 by (I1), so δ(m1,f) θ δ(m2,f)\delta(m_1, f) \,\theta\, \delta(m_2, f) by condition 2, and the new pair is in θ\theta. So (I1) holds. For (I2), a feature in one table only moves to the merged table with the same value, and a feature in both keeps the value of the big table, which is now ≈\approx to the value of the small table through the new pair. The atom of the new root is the atom of one of the old roots (line L7), and there was no clash, so it is the atom of every member that has one. (I3) holds because there was no clash: the two blocks do not hold different atoms, and they do not hold an atom on one side and a feature on the other. (I4) holds because ≈\approx never loses a pair.

The end. When the stack is empty, ≈\approx is PP. By (I4), rAr_A and rBr_B are in one block. By (I2), if two members yy and y′y' of one block both have ff, then δ(y,f)≈arcs(x)[f]≈δ(y′,f)\delta(y, f) \approx \mathrm{arcs}(x)[f] \approx \delta(y', f), so they are in one block. So PP is a unifying congruence and θ⊆P\theta \subseteq P. With (I1), P=θP = \theta. By (I3), θ\theta is consistent. The roots, their atoms and their tables are exactly the quotient U/θU/\theta: the class of a root xx has the atom atom(x)\mathrm{atom}(x), and its value for ff is the block of arcs(x)[f]\mathrm{arcs}(x)[f]. Line L13 returns the root of the block of rAr_A, which is the root of the quotient. By Lemmas 1 and 2 this is the unification.

Termination

Each pass of the loop pops one pair. A pair is pushed only at line L10, and each push removes one entry of the small table, which is then dropped at line L12. The tables hold at most ee entries in all at the start and never gain new entries, so there are at most ee pushes, and the loop runs at most e+1e + 1 times. A merge joins two blocks, so there are at most n−1n - 1 merges.

Cost

The loop makes at most 2(e+1)2(e + 1) finds and n−1n - 1 unions. With union by rank and path compression they cost O((n+e) α(n))O((n + e)\,\alpha(n)) in all (Tarjan 1975), where α\alpha is the inverse Ackermann function.

The table work at a merge is one lookup for each entry of the small table. Take a merge with a small table of size ss, a big table of size L≥sL \ge s, and cc shared features. It moves s−cs - c entries and drops cc. The merged table has L+s−cL + s - c entries. If c>s/2c > s/2, the moves are fewer than the drops, and over the whole run there are at most ee drops. If c≤s/2c \le s/2, each moved entry goes from a table of size ss to a table of size at least L+s/2≥1.5 sL + s/2 \ge 1.5\,s. A table that holds an entry never gets smaller (a big table becomes a table of size L+s−c≥LL + s - c \ge L), and no table has more than ee entries. So each entry moves at most log⁡1.5e\log_{1.5} e times in merges of the second kind. The table work is O(elog⁡e)O(e \log e) lookups and inserts in all, each of expected constant time with hash tables. The total time is O((n+e) α(n)+elog⁡e)O((n + e)\,\alpha(n) + e \log e) expected.

When every complex node has the same fixed set of features, as for first-order terms where both nodes carry the same function symbol, every entry of the small table is shared, nothing moves, and the bound becomes O((n+e) α(n))O((n + e)\,\alpha(n)), the bound of Huet's algorithm.

Complexity

Time. Each push at line L10 removes one entry from the small table, and no new entries appear, so there are at most ee pushes, at most e+1e + 1 passes and at most 2(e+1)2(e + 1) finds. With union by rank and path compression the finds and the at most n−1n - 1 unions cost O((n+e) α(n))O((n + e)\,\alpha(n)) (Tarjan 1975), where α\alpha is the inverse Ackermann function. This is a theorem in the word-RAM model.

The feature tables add a term. Merging the smaller table into the larger one makes each moved entry land in a table at least 1.5 times as large, except in merges where most entries collide, and collisions are paid for by the pushes. So each entry moves O(log⁡e)O(\log e) times, and the table work is O(elog⁡e)O(e \log e) operations on hash tables, each of expected constant time. The total is O((n+e) α(n)+elog⁡e)O((n + e)\,\alpha(n) + e \log e) expected. If all complex nodes have the same fixed set of features, as for first-order terms with one function symbol per arity, nothing ever moves, and the bound is the O((n+e) α(n))O((n + e)\,\alpha(n)) of Huet's algorithm.

Space. O(n+e)O(n + e) for the parent and rank fields, the tables and the stack. The stack holds at most e+1e + 1 pairs.

Heuristic, not bound. In a chart parser the merge is often not the main cost. The parser must keep its edges unchanged, so it copies structures before it unifies them, and most unifications fail. This is the reason for the non-destructive variants below.

Properties

  • Exact and deterministic. The result is unique up to renaming of nodes.
  • Idempotent, commutative and associative, up to renaming: A⊔A=AA \sqcup A = A, A⊔B=B⊔AA \sqcup B = B \sqcup A, and (A⊔B)⊔C=A⊔(B⊔C)(A \sqcup B) \sqcup C = A \sqcup (B \sqcup C), where both sides fail together. These follow from the description as a least upper bound. The tests check all three on random structures.
  • Identity. The empty structure [ ][\,] is the identity: [ ]⊔A=A[\,] \sqcup A = A.
  • Order. Up to renaming, the feature structures with an added top element for failure form a join-semilattice under ⊑\sqsubseteq, and unification is the join. The empty structure is the bottom.
  • No occurs check. Cycles are allowed. A system that forbids cycles adds an acyclicity test on the result, as Huet's algorithm does for terms.
  • Destructive. The inputs are changed.

Variants and improvements

  • Non-destructive unification. A chart parser uses the same edge in many combinations, so it cannot let unification change it. The simplest fix copies both inputs first. Wroblewski (1987) copies only the parts that change, and Tomabechi (1991) delays copying until the unification has succeeded, so failed unifications, the common case in parsing, copy nothing.
  • Typed feature structures. HPSG gives every node a type from a hierarchy, and unification takes the most general common subtype of the two types, failing when there is none. The merge is the same, with CLASH replaced by a type lookup.
  • Disjunction. Grammars often write a value as a choice, such as "singular or plural". Deciding whether a description with disjunction has any solution is NP-complete (Kasper and Rounds 1986, a theorem). Unification of plain structures stays almost linear; the cost comes from the choices.
  • First-order terms. With positional arguments and a function symbol at each node, the same algorithm is Huet's algorithm, and with an occurs check it computes a most general unifier. For acyclic terms the linear time algorithm of Paterson and Wegman removes the inverse Ackermann factor.

When to use it

Use it in a parser for a unification-based grammar, to combine the features of constituents, and in any program that merges partial records where shared fields must stay shared. For a parser, prefer a non-destructive variant, or copy before unifying. For first-order terms in logic programming, use term unification with its occurs check choice; for typed structures, add the type lattice.

Pitfalls

  • Comparing copies instead of sharing. Two separate nodes with the same contents are not the same node. Unification adds information to one and not to the other. Build reentrant nodes as one node.
  • Forgetting FIND. A node that was merged is no longer a root. Reading its table or its atom without FIND gives stale data.
  • Recursion depth. A recursive version overflows the call stack on long lists, which feature structures use for subcategorization. Use an explicit stack.
  • Failure leaves damage. After a clash the inputs are partly merged. Copy before unifying, or keep a trail of changes and undo them.
  • Hidden cycles. Printing or copying a structure by naive recursion loops forever on a cycle. Mark visited nodes.
  • Atoms against complex nodes. An atom node must not gain features. CLASH must test this case, not only two different atoms.

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.

feature_structure_unification.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/feature-structure-unification/. The authors are listed in prov/W1EW4J.jsonl.

"""Destructive unification of feature structures with union-find.

A feature structure is a rooted directed graph. Each node is either an atom
(a string such as "sg"), or a complex node with a table of features, or an
empty node with no atom and no feature (the variable []). Two paths that lead
to the same node are reentrant. Cycles are allowed: unify does no occurs
check, so it unifies rational (cyclic) structures as Huet's algorithm does for
terms.

unify(a, b) merges the two graphs in place and returns the root of the result,
or None if the structures clash. On a clash the input graphs are left in a
partly merged state; use unify_copy to keep the inputs.

build(spec) makes a structure from nested Python values: a dict is a complex
node, a str is an atom, None is the empty node. A reentrant node is written
("#1", spec) at its first use and "#1" at every other use.
"""


class Node:
    __slots__ = ("parent", "rank", "atom", "arcs")

    def __init__(self, atom=None, arcs=None):
        self.parent = self
        self.rank = 0
        self.atom = atom
        self.arcs = {} if arcs is None else arcs


def find(x):
    """Return the root of the class of x, with path compression."""
    root = x
    while root.parent is not root:
        root = root.parent
    while x.parent is not root:
        x.parent, x = root, x.parent
    return root


def _clash(x, y):
    if x.atom is not None and y.atom is not None:
        return x.atom != y.atom
    if x.atom is not None and y.arcs:
        return True
    if y.atom is not None and x.arcs:
        return True
    return False


def unify(a, b):
    """Unify the structures rooted at a and b in place.

    Return the root of the unified structure, or None on a clash.
    """
    stack = [(a, b)]  # @line L1
    while stack:  # @line L2
        x, y = stack.pop()  # @line L3
        x, y = find(x), find(y)
        if x is y:  # @line L4
            continue
        if _clash(x, y):  # @line L5
            return None
        if x.rank < y.rank:  # @line L6
            x, y = y, x
        y.parent = x
        if x.rank == y.rank:
            x.rank += 1
        if x.atom is None:  # @line L7
            x.atom = y.atom
        big, small = x.arcs, y.arcs  # @line L8
        if len(big) < len(small):
            big, small = small, big
        for f, v in small.items():  # @line L9
            if f in big:  # @line L10
                stack.append((big[f], v))
            else:  # @line L11
                big[f] = v
        x.arcs = big  # @line L12
        y.arcs = {}
        y.atom = None
    return find(a)  # @line L13


def build(spec, tags=None):
    """Build a structure from nested dicts, strings, None and reentrancy tags."""
    if tags is None:
        tags = {}
    if isinstance(spec, tuple):
        tag, inner = spec
        if tag not in tags:
            tags[tag] = Node()
        node = unify(tags[tag], build(inner, tags))
        if node is None:
            raise ValueError("tag " + tag + " has clashing values")
        return node
    if isinstance(spec, str) and spec.startswith("#"):
        if spec not in tags:
            tags[spec] = Node()
        return tags[spec]
    if spec is None:
        return Node()
    if isinstance(spec, str):
        return Node(atom=spec)
    node = Node()
    for f in sorted(spec):
        node.arcs[f] = build(spec[f], tags)
    return node


def nodes_of(root):
    """List the class roots reachable from root, in a fixed order."""
    root = find(root)
    seen = {id(root): root}
    order = [root]
    i = 0
    while i < len(order):
        x = order[i]
        i += 1
        for f in sorted(x.arcs):
            y = find(x.arcs[f])
            if id(y) not in seen:
                seen[id(y)] = y
                order.append(y)
    return order


def copy(root):
    """Return a fresh copy of the structure rooted at root."""
    order = nodes_of(root)
    new = {id(x): Node(atom=x.atom) for x in order}
    for x in order:
        new[id(x)].arcs = {f: new[id(find(v))] for f, v in x.arcs.items()}
    return new[id(order[0])]


def unify_copy(a, b):
    """Unify copies of a and b; the inputs are not changed."""
    return unify(copy(a), copy(b))


def canonical(root):
    """A canonical form: two structures are equal as graphs iff the forms are equal.

    Nodes are numbered in breadth-first order with features in sorted order.
    Because each node has at most one arc per feature, this numbering is the
    same for isomorphic rooted graphs.
    """
    order = nodes_of(root)
    num = {id(x): i for i, x in enumerate(order)}
    return tuple(
        (x.atom, tuple((f, num[id(find(x.arcs[f]))]) for f in sorted(x.arcs)))
        for x in order
    )


def subsumes(general, specific):
    """Return True if general subsumes specific (general is at most as informative).

    Look for a map h from the nodes of general to the nodes of specific with
    h(root) = root, h(x.f) = h(x).f for every arc, and every atom kept. The map
    is forced by the paths, so a breadth-first walk decides it.
    """
    g0, s0 = find(general), find(specific)
    h = {id(g0): s0}
    queue = [g0]
    while queue:
        x = queue.pop()
        y = h[id(x)]
        if x.atom is not None and x.atom != y.atom:
            return False
        for f, v in x.arcs.items():
            if f not in y.arcs:
                return False
            v, w = find(v), find(y.arcs[f])
            if id(v) in h:
                if h[id(v)] is not w:
                    return False
            else:
                h[id(v)] = w
                queue.append(v)
    return True


def get_path(root, path):
    """Follow a path of features from root; return the node or None."""
    x = find(root)
    for f in path:
        if f not in x.arcs:
            return None
        x = find(x.arcs[f])
    return x


def to_spec(root):
    """Inverse of build, with tags "#1", "#2", ... on nodes reached twice."""
    order = nodes_of(root)
    indeg = {id(x): 0 for x in order}
    for x in order:
        for v in x.arcs.values():
            indeg[id(find(v))] += 1
    indeg[id(order[0])] += 1
    tag_of = {}
    for x in order:
        if indeg[id(x)] > 1:
            tag_of[id(x)] = "#" + str(len(tag_of) + 1)
    done = set()

    def walk(x):
        x = find(x)
        if id(x) in tag_of and id(x) in done:
            return tag_of[id(x)]
        done.add(id(x))
        if x.atom is not None:
            body = x.atom
        elif x.arcs:
            body = {f: walk(x.arcs[f]) for f in sorted(x.arcs)}
        else:
            body = None
        if id(x) in tag_of:
            return (tag_of[id(x)], body)
        return body

    return walk(order[0])
test_feature_structure_unification.py 290 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/feature-structure-unification/. The authors are listed in prov/W1EW4J.jsonl.

import random

from feature_structure_unification import (
    Node,
    build,
    canonical,
    copy,
    get_path,
    subsumes,
    to_spec,
    unify,
    unify_copy,
)


def reference_unify(a, b):
    """Least congruence by naive fixed-point iteration, without union-find.

    Number all nodes of the two graphs, start with the two roots in one class,
    and merge the classes of x.f and y.f whenever x and y are in one class and
    both have the feature f, until nothing changes. Return the canonical form
    of the quotient graph, or None if a class holds two atoms or an atom and a
    feature.
    """
    nodes = []
    index = {}

    def collect(x):
        stack = [x]
        while stack:
            y = stack.pop()
            if id(y) in index:
                continue
            index[id(y)] = len(nodes)
            nodes.append(y)
            stack.extend(y.arcs.values())

    collect(a)
    collect(b)
    n = len(nodes)
    arcs = [{f: index[id(v)] for f, v in x.arcs.items()} for x in nodes]
    cls = list(range(n))

    def merge(i, j):
        ci, cj = cls[i], cls[j]
        if ci == cj:
            return False
        for k in range(n):
            if cls[k] == cj:
                cls[k] = ci
        return True

    merge(index[id(a)], index[id(b)])
    changed = True
    while changed:
        changed = False
        for i in range(n):
            for j in range(n):
                if cls[i] != cls[j]:
                    continue
                for f in arcs[i]:
                    if f in arcs[j] and merge(arcs[i][f], arcs[j][f]):
                        changed = True
    atoms = {}
    has_arcs = set()
    for i in range(n):
        c = cls[i]
        if nodes[i].atom is not None:
            atoms.setdefault(c, set()).add(nodes[i].atom)
        if arcs[i]:
            has_arcs.add(c)
    for c, s in atoms.items():
        if len(s) > 1 or c in has_arcs:
            return None
    quotient = {c: Node() for c in set(cls)}
    for c, s in atoms.items():
        quotient[c].atom = next(iter(s))
    for i in range(n):
        for f, j in arcs[i].items():
            quotient[cls[i]].arcs[f] = quotient[cls[j]]
    return canonical(quotient[cls[index[id(a)]]])


def random_structure(rng, size):
    """A random structure with up to size nodes, reentrancy and possible cycles."""
    feats = ["a", "b", "c"]
    root = Node()
    made = [root]
    frontier = [root]
    while frontier and len(made) < size:
        x = frontier.pop(0)
        for f in feats:
            if rng.random() < 0.5:
                continue
            r = rng.random()
            if r < 0.2 and len(made) > 1:
                x.arcs[f] = rng.choice(made)
            elif r < 0.5:
                x.arcs[f] = Node(atom=rng.choice(["x", "y"]))
                made.append(x.arcs[f])
            else:
                y = Node()
                x.arcs[f] = y
                made.append(y)
                frontier.append(y)
    # An atom node must have no arcs; drop the arcs of any atom node.
    for x in made:
        if x.atom is not None:
            x.arcs = {}
    return root


SHIEBER_A = {"agreement": ("#1", {"number": "singular"}), "subject": {"agreement": "#1"}}
SHIEBER_B = {"subject": {"agreement": {"person": "third"}}}


def test_shieber_reentrancy_example():
    r = unify(build(SHIEBER_A), build(SHIEBER_B))
    assert r is not None
    assert to_spec(r) == {
        "agreement": ("#1", {"number": "singular", "person": "third"}),
        "subject": {"agreement": "#1"},
    }
    assert get_path(r, ["agreement"]) is get_path(r, ["subject", "agreement"])


def test_without_reentrancy_the_information_does_not_spread():
    a = build({"agreement": {"number": "singular"}, "subject": {"agreement": {"number": "singular"}}})
    r = unify(a, build(SHIEBER_B))
    assert get_path(r, ["agreement", "person"]) is None
    assert get_path(r, ["subject", "agreement", "person"]).atom == "third"


def test_clash_on_atoms():
    assert unify(build({"number": "singular"}), build({"number": "plural"})) is None


def test_clash_atom_against_complex():
    assert unify(build({"f": "x"}), build({"f": {"g": "x"}})) is None
    assert unify(build("x"), build({"g": "x"})) is None


def test_clash_found_through_reentrancy():
    a = build({"f": ("#1", None), "g": "#1"})
    b = build({"f": "x", "g": "y"})
    assert unify(a, b) is None


def test_empty_structure_is_the_identity():
    rng = random.Random(1)
    for _ in range(50):
        d = random_structure(rng, 8)
        assert canonical(unify(Node(), copy(d))) == canonical(d)
        assert canonical(unify(copy(d), Node())) == canonical(d)


def test_atoms():
    assert unify(build("x"), build("x")).atom == "x"
    assert unify(build("x"), build(None)).atom == "x"
    assert unify(build("x"), build("y")) is None


def test_idempotent():
    rng = random.Random(2)
    for _ in range(200):
        d = random_structure(rng, 10)
        assert canonical(unify(copy(d), copy(d))) == canonical(d)


def test_commutative():
    rng = random.Random(3)
    for _ in range(300):
        a = random_structure(rng, 7)
        b = random_structure(rng, 7)
        ab = unify_copy(a, b)
        ba = unify_copy(b, a)
        assert (ab is None) == (ba is None)
        if ab is not None:
            assert canonical(ab) == canonical(ba)


def test_associative():
    rng = random.Random(4)
    for _ in range(200):
        a, b, c = (random_structure(rng, 6) for _ in range(3))
        ab = unify_copy(a, b)
        left = None if ab is None else unify_copy(ab, c)
        bc = unify_copy(b, c)
        right = None if bc is None else unify_copy(a, bc)
        assert (left is None) == (right is None)
        if left is not None:
            assert canonical(left) == canonical(right)


def test_against_naive_least_congruence():
    rng = random.Random(5)
    fails = 0
    for _ in range(400):
        a = random_structure(rng, 7)
        b = random_structure(rng, 7)
        want = reference_unify(copy(a), copy(b))
        got = unify_copy(a, b)
        if want is None:
            fails += 1
            assert got is None
        else:
            assert got is not None
            assert canonical(got) == want
    assert 20 < fails < 380


def test_result_is_subsumed_by_both_inputs():
    rng = random.Random(6)
    for _ in range(300):
        a = random_structure(rng, 7)
        b = random_structure(rng, 7)
        r = unify_copy(a, b)
        if r is None:
            continue
        assert subsumes(a, r) and subsumes(b, r)


def test_most_general_common_extension():
    # Any structure subsumed by both inputs is subsumed by their unification.
    rng = random.Random(7)
    checked = 0
    for _ in range(400):
        a = random_structure(rng, 5)
        b = random_structure(rng, 5)
        r = unify_copy(a, b)
        if r is None:
            continue
        extra = random_structure(rng, 5)
        bigger = unify_copy(r, extra)
        if bigger is None:
            continue
        assert subsumes(a, bigger) and subsumes(b, bigger)
        assert subsumes(r, bigger)
        checked += 1
    assert checked > 50


def test_inputs_unchanged_by_unify_copy():
    a = build(SHIEBER_A)
    b = build(SHIEBER_B)
    ca, cb = canonical(a), canonical(b)
    unify_copy(a, b)
    assert canonical(a) == ca and canonical(b) == cb


def test_cycle_without_occurs_check():
    a = build({"a": ("#1", None), "b": "#1"})
    b = build({"a": {"h": ("#2", None)}, "b": "#2"})
    r = unify(a, b)
    assert r is not None
    x = get_path(r, ["a"])
    assert get_path(r, ["a", "h"]) is x
    assert get_path(r, ["b", "h", "h", "h"]) is x


def test_subsumption_chain():
    chain = [
        None,
        {"cat": "np"},
        {"cat": "np", "agreement": {"number": "singular"}},
        {"cat": "np", "agreement": {"number": "singular", "person": "third"}},
        {"cat": "np", "agreement": ("#1", {"number": "singular", "person": "third"}), "subject": {"agreement": "#1"}},
    ]
    built = [build(s) for s in chain]
    for i in range(len(built)):
        for j in range(len(built)):
            assert subsumes(built[i], built[j]) == (i <= j)


def test_long_lists_need_no_recursion():
    n = 3000
    a = build(None)
    b = build(None)
    x, y = a, b
    for i in range(n):
        x.arcs["rest"] = Node()
        y.arcs["rest"] = Node()
        x.arcs["first"] = Node(atom="w" + str(i))
        x, y = x.arcs["rest"], y.arcs["rest"]
    r = unify(a, b)
    assert r is not None
    assert get_path(r, ["rest"] * (n - 1) + ["first"]).atom == "w" + str(n - 1)

History

Kay's functional unification grammar and PATR-II, which Shieber and others built at SRI, made unification of feature structures the central operation of a family of grammar formalisms. Huet (1976) had already given an almost linear algorithm for first-order terms that merges equivalence classes with union and find, and that works on rational (cyclic) terms when the occurs check is dropped. Aït-Kaci (1984) adapted that method to his ψ-terms, records with named features and types, as Knight's 1989 survey describes. Shieber's 1986 book gave the account of subsumption, unification as the least upper bound, and feature structures as graphs that grammar writers still use. Kasper and Rounds (1986) gave a logic of feature descriptions and showed that disjunction makes consistency NP-complete.

References

  1. Stuart M. Shieber, An Introduction to Unification-Based Approaches to Grammar, CSLI Lecture Notes 4, 1986, Chapter 3, The Simplest Unification-Based Formalism, section 3.2 The Informational Domain (3.2.2 Subsumption, 3.2.3 Unification, 3.2.4 Feature Structures as Graphs)
  2. Hassan Aït-Kaci, A Lattice-Theoretic Approach to Computation Based on a Calculus of Partially-Ordered Type Structures, the unification of psi-terms with union and find, after Huet
  3. Gérard Huet, Résolution d'équations dans des langages d'ordre 1, 2, ..., omega, the almost linear unification of first-order terms with equivalence classes merged by union and find
  4. Robert E. Tarjan, Efficiency of a Good But Not Linear Set Union Algorithm, the bound for union by rank with path compression
  5. Robert T. Kasper and William C. Rounds, A Logical Semantics for Feature Structures, Proceedings of ACL 1986, 257-266, the consistency problem for feature descriptions with disjunction is NP-complete
  6. Kevin Knight, Unification: A Multidisciplinary Survey, the sections on Huet's algorithm and on unification in computational linguistics

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.expected
  • 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