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
- Model
- Word RAM
- Properties
- destructivedeterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 and with disjoint node sets. Each has a root, a partial function that gives the value of feature at node , and a partial atom label . A node with an atom has no features. A node with no atom and no feature is the empty structure .
Order. subsumes , written , if has at least the information of : there is a map from the nodes of to the nodes of that sends the root to the root, each arc to an arc , and each atom to the same atom. In Shieber's terms: every path of is a path of with the same atom value, and paths that share a node in share a node in . The empty structure subsumes every structure.
Output. The unification : a structure with and such that for every that both and subsume. It is unique up to renaming of the nodes. If no is subsumed by both inputs, the output is failure.
Write for the number of nodes and for the number of arcs of and 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.
UNIFY(a, b) ▷ a, b: the roots of the two inputs- 1
stack ← [(a, b)] - 2
while stack is not empty do - 3
pop (u, v); x ← FIND(u); y ← FIND(v) - 4
if x = y then continue - 5
if CLASH(x, y) then return FAIL - 6
if rank(x) < rank(y) then swap x and y; parent(y) ← x; if rank(x) = rank(y) then rank(x) ← rank(x) + 1 - 7
if atom(x) is undefined then atom(x) ← atom(y) - 8
(big, small) ← the tables of x and y, the larger first - 9
for each feature f with value w in small do - 10
if f is in big then push (big[f], w) - 11
else big[f] ← w - 12
table(x) ← big; clear the table and the atom of y - 13
return FIND(a) 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 marks a shared node.
Call the nodes of : (root), (the subject), (the shared agreement) and the atom node of singular. Call the nodes of : , , and the atom node of third. The run:
| pass | pair popped | tables merged | moved | pushed |
|---|---|---|---|---|
| 1 | {agreement, subject} and {subject} | none | ||
| 2 | {agreement} and {agreement} | none | ||
| 3 | {number} and {person} | person | none |
After three merges the stack is empty and the result is
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 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: . 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: and . Unification makes the node under equal to the node under , which is the value of inside it. The result has a node with , so the path leads back to the node of . With an occurs check this would fail; without one it gives a cyclic structure.
Correctness
The claim is a theorem: UNIFY returns when it exists, returns failure exactly when no structure is subsumed by both inputs, and stops after at most passes. The full proof is in proofs/correctness.md. Its outline:
- Call an equivalence relation on the nodes a unifying congruence if it puts the two roots together and, whenever it puts and together and both have feature , it also puts and together. Let be the least one.
- If no class of holds two different atoms, or an atom and a feature, then the quotient graph by is . Any that both inputs subsume defines a congruence by "same image in ", which contains , so the quotient maps into . If has a bad class, then so does that congruence, and no exists.
- UNIFY keeps the invariant that every pair it joins or pushes is in , 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 . A clash at line L5 shows a bad class of .
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 is a finite set of nodes with a root , a partial function that gives the value of feature at node , and a partial atom label . 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.
subsumes , written , if there is a map from the nodes of to the nodes of with , with whenever is defined (so the right side is defined too), and with whenever is defined. Because every node is reached by a path from the root and each step of a path is forced, is unique if it exists. This is the same as Shieber's definition in terms of paths: every path of is a path of , every atom value of a path of is the same in , and two paths that lead to one node of lead to one node of .
Let the inputs and have disjoint node sets, and let be their union, with nodes and arcs in all. An equivalence relation on is a unifying congruence if
- , and
- if and both and are defined, then .
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 in one class is one, so there is a least one. Call it .
If is consistent, the quotient is a feature structure: its nodes are the classes, its root is the class of , the value of at a class is the class of for any that has (condition 2 makes this independent of the choice), and the atom of 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 is consistent, then and .
Proof. Map each node to its class. The root of goes to the root class, and the root of goes there too because . Arcs and atoms are kept by the definition of the quotient. ∎
Lemma 2. If and for some feature structure , then is consistent and .
Proof. Let and be the two maps into , and let be their union on . Define if . This is an equivalence relation. It holds for and , because both go to . If and both have , then , so condition 2 holds. Hence is a unifying congruence and .
A class of lies inside a class of , so all its nodes go to one node of . If two of them had different atoms, would carry both. If one had an atom and another had a feature, would carry an atom and a feature. Neither is possible in , so is consistent. The map is well defined on because , and it keeps the root, the arcs and the atoms because does. So . ∎
Lemmas 1 and 2 say that, when is consistent, is subsumed by both inputs and subsumes every structure that both inputs subsume. This is Shieber's definition of the unification . When is not consistent, Lemma 2 says that no structure is subsumed by both inputs, so unification must fail.
Part 3: UNIFY computes
Let be the partition of the union-find forest (two nodes are in one block if they have the same root). Let be the equivalence relation generated by and by the pairs on the stack. We show four invariants, true at the test of line L2.
- (I1) .
- (I2) For every block with root , every member and every feature of , the table has an entry for , and . If some member has an atom, is that atom.
- (I3) Every block of is consistent, and is empty for a root whose block has no member with a feature.
- (I4) .
Start. Line L1 puts the pair on the stack. Every block is a single node with its own atom and features. (I1) holds because . (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 and finds the roots and . If (line L4), then and were already in one block, so removing the pair does not change . All invariants stay true.
A clash. Suppose line L5 finds a clash between the roots and . By (I1), , so and and their blocks lie in one class of . 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 holds two different atoms, or an atom and a feature. Then is not consistent, and by Lemma 2 failure is the right answer.
A merge. Otherwise lines L6 to L12 join the blocks of and . The pair leaves the stack, but and are now in one block, so does not lose it. The new pairs are for each feature in both tables. By (I2) there are members and of the two blocks with and . We have by (I1), so by condition 2, and the new pair is in . 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 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 never loses a pair.
The end. When the stack is empty, is . By (I4), and are in one block. By (I2), if two members and of one block both have , then , so they are in one block. So is a unifying congruence and . With (I1), . By (I3), is consistent. The roots, their atoms and their tables are exactly the quotient : the class of a root has the atom , and its value for is the block of . Line L13 returns the root of the block of , 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 entries in all at the start and never gain new entries, so there are at most pushes, and the loop runs at most times. A merge joins two blocks, so there are at most merges.
Cost
The loop makes at most finds and unions. With union by rank and path compression they cost in all (Tarjan 1975), where 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 , a big table of size , and shared features. It moves entries and drops . The merged table has entries. If , the moves are fewer than the drops, and over the whole run there are at most drops. If , each moved entry goes from a table of size to a table of size at least . A table that holds an entry never gets smaller (a big table becomes a table of size ), and no table has more than entries. So each entry moves at most times in merges of the second kind. The table work is lookups and inserts in all, each of expected constant time with hash tables. The total time is 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 , 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 pushes, at most passes and at most finds. With union by rank and path compression the finds and the at most unions cost (Tarjan 1975), where 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 times, and the table work is operations on hash tables, each of expected constant time. The total is 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 of Huet's algorithm.
Space. for the parent and rank fields, the tables and the stack. The stack holds at most 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: , , and , 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: .
- Order. Up to renaming, the feature structures with an added top element for failure form a join-semilattice under , 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.
# 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
- 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)
- 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
- 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
- Robert E. Tarjan, Efficiency of a Good But Not Linear Set Union Algorithm, the bound for union by rank with path compression
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag W1EW4J Edit this page History Report an error Markdown