Algorithm Search⌘K

Algorithmadvanced

Smatch

Also called semantic match score.

Score two AMR graphs by the F1 of matching triples under the best variable mapping, found by hill climbing with restarts.

Time
O(r t^2 (m n + m^2)) worst
Space
O(t + m + n) extra
Where
m = the number of variables of the test graph; n = the number of variables of the gold graph; r = the number of restarts; t = the number of triples of both graphs
Properties
randomizednot exactofflineiterative
Origin
Shu Cai, Kevin Knight, 2013

Smatch compares two abstract meaning representation graphs, a test graph from a parser and a gold graph from an annotator, and gives one number between 0 and 1. It writes each graph as a set of triples, maps the variables of the test graph one to one onto the variables of the gold graph, counts the triples that match, and reports the F1 of the best mapping. Finding the best mapping is NP-hard, so the standard tool searches with hill climbing from a concept-matching start plus random restarts, and the score it reports can be slightly below the true Smatch score. It is the usual metric for semantic parsing into AMR, in the way that PARSEVAL is for constituency trees, but it has no fixed alignment to the words, which is why it needs a search.

In plain words

Two people draw the meaning of a sentence as a graph. Each graph has boxes such as "want" and "boy" and labeled arrows such as "the wanter is the boy". The box names in the two drawings are arbitrary, so before comparing them we must decide which box in one drawing goes with which box in the other.

For a given pairing, list every fact of the first drawing and count how many also appear in the second. The score is based on the best pairing: it rewards facts that both drawings share and punishes facts that only one of them has.

Trying every pairing is too slow for large graphs. So the program starts from a good guess, pairing boxes with the same name, and makes the change that helps most until no change helps. It repeats this from a few random guesses and keeps the best result.

The problem

An AMR graph is a set of triples of three kinds: instance(v, c) says that the variable vv is an instance of the concept cc, role(v, w) is a relation between two variables, and role(v, k) gives a variable an attribute with a constant kk, such as polarity(v, -). The test graph TT has mm variables, the gold graph GG has nn variables, and the two graphs have tt triples together.

A mapping φ\varphi sends each test variable to a different gold variable or to nothing. Constants map to themselves. A test triple matches if all its variables are mapped and its image is a triple of GG. Let M(φ)M(\varphi) be the number of matched test triples. Then

P=M∣T∣,R=M∣G∣,F=2PRP+R=2M∣T∣+∣G∣.P = \frac{M}{|T|}, \qquad R = \frac{M}{|G|}, \qquad F = \frac{2PR}{P + R} = \frac{2M}{|T| + |G|}.

Smatch is FF for the mapping with the largest MM. One mapping maximizes PP, RR and FF together, because the denominators do not depend on the mapping. The match count is symmetric: the best MM from TT to GG equals the best MM from GG to TT.

For a corpus, Smatch adds up MM, ∣T∣|T| and ∣G∣|G| over all sentence pairs and then applies the same formulas. This gives more weight to large graphs than the mean of the sentence scores would.

The algorithm

  1. CLIMB(T, G, φ)
  2. 1M ← the number of test triples that match under φ
  3. 2loop
  4. 3for each test variable a and each gold variable g that is unused, or nothing: gain of sending a to g
  5. 4for each pair of test variables a, b: gain of swapping their images
  6. 5if no move has a positive gain then return (M, φ)
  7. 6apply the move with the largest gain; M ← M + gain
  8. SMATCH(T, G, r)
  9. 7(best, φ*) ← CLIMB(T, G, SMART-INIT(T, G))
  10. 8repeat r times: (M, φ) ← CLIMB(T, G, a random one to one mapping)
  11. 9if M > best then (best, φ*) ← (M, φ)
  12. 10return P, R and F for best

SMART-INIT sends each test variable to the first unused gold variable with the same concept, and leaves it unmapped if there is none. Lines L3 and L4 are the two kinds of moves of Cai and Knight: change the image of one variable, and swap the images of two variables. Both keep the mapping one to one. Line L6 takes the steepest move, so this is steepest-ascent hill climbing, and lines L7 to L9 make it random-restart hill climbing. The implementation also has an exact search that tries every mapping, which the tests use as the reference.

Example

The example of Cai and Knight, section 2. The gold graph says "the boy wants to go" and the test graph says "the boy wants the football":

gold: (a / want-01 :ARG0 (b / boy) :ARG1 (c / go-01 :ARG0 b))
test: (x / want-01 :ARG0 (y / boy) :ARG1 (z / football))

The gold graph has 6 triples: three instance triples, ARG0(a, b), ARG1(a, c) and ARG0(c, b). The test graph has 5: three instance triples, ARG0(x, y) and ARG1(x, z). The six full mappings of x,y,zx, y, z onto a,b,ca, b, c give:

image of x,y,zx, y, z matched triples MM
a,b,ca, b, c instance(x, want-01), instance(y, boy), ARG0(x, y), ARG1(x, z) 4
a,c,ba, c, b instance(x, want-01) 1
b,a,cb, a, c none 0
b,c,ab, c, a none 0
c,a,bc, a, b none 0
c,b,ac, b, a instance(y, boy), and ARG0(x, y), whose image is ARG0(c, b) 2

The best mapping is x→ax \to a, y→by \to b, z→cz \to c with M=4M = 4, so P=4/5P = 4/5, R=4/6=2/3R = 4/6 = 2/3, and F=8/11≈0.73F = 8/11 \approx 0.73. The smart start finds this mapping directly here, because want-01 and boy occur once in each graph.

Hill climbing can stop too early. Take the test graph instance(t0, p), instance(t1, q), r(t0, t1) and the gold graph instance(g0, q), instance(g1, q), r(g0, g1). The smart start leaves t0t_0 unmapped, because no gold variable has the concept pp, and sends t1t_1 to g0g_0, with M=1M = 1. No single move raises MM, so the climb stops at 1. The best mapping, t0→g0t_0 \to g_0 and t1→g1t_1 \to g_1, has M=2M = 2: it gives up nothing and gains the relation, but it takes two moves to reach, and the first of them lowers MM. A random restart can start near it.

Correctness

The full proofs are in proofs/correctness.md. The claims:

  • Exact search (theorem). The search over every one to one partial mapping returns the best MM, and so the true Smatch score. It is enough to try mappings that map min⁡(m,n)\min(m, n) variables, because mapping one more variable to an unused gold variable never loses a match.
  • Hill climbing (theorem). Each step raises MM by at least 1, and M≤∣T∣M \le |T|, so CLIMB takes at most ∣T∣|T| steps and stops. Every mapping it holds is one to one, so the reported MM is at most the best MM: the reported score is a lower bound on the true score.
  • Not exact (theorem, with the example above). A climb can stop at a local maximum below the best MM.
  • NP-hardness (theorem). Deciding whether some mapping has M≥kM \ge k is NP-complete. The proof reduces subgraph isomorphism: give every vertex the concept node and turn each edge into two edge triples, one in each direction. Then a graph HH is a subgraph of KK exactly when the best MM equals the number of triples of HH, ∣V(H)∣+2∣E(H)∣|V(H)| + 2|E(H)|. Cai and Knight note that the problem is NP-complete; the reduction on this page is written out for it.
Proof: The exact search gives the Smatch score, hill climbing gives a lower bound and stops, and the best mapping is NP-hard to findfull

We use the definitions and the pseudocode of the page. The test graph TT and the gold graph GG are sets of triples. TT has mm variables and GG has nn variables, and the two sets of variables are disjoint. A mapping φ\varphi sends each test variable to a gold variable or to nothing, and no two test variables go to the same gold variable. A constant maps to itself. A test triple matches under φ\varphi if all its variables are mapped and its image is a triple of GG. M(φ)M(\varphi) is the number of matched test triples, and M∗=max⁡φM(φ)M^* = \max_\varphi M(\varphi).

Part 1: the score is a function of the best match count

For a mapping φ\varphi the precision is P=M(φ)/∣T∣P = M(\varphi)/|T|, the recall is R=M(φ)/∣G∣R = M(\varphi)/|G|, and

F=2PRP+R=2M(φ)2/(∣T∣ ∣G∣)M(φ) (∣T∣+∣G∣)/(∣T∣ ∣G∣)=2M(φ)∣T∣+∣G∣F = \frac{2PR}{P + R} = \frac{2 M(\varphi)^2 / (|T|\,|G|)}{M(\varphi)\,(|T| + |G|)/(|T|\,|G|)} = \frac{2 M(\varphi)}{|T| + |G|}

when M(φ)>0M(\varphi) > 0, and F=0F = 0 when M(φ)=0M(\varphi) = 0. The sizes ∣T∣|T| and ∣G∣|G| do not depend on φ\varphi, so PP, RR and FF all grow with M(φ)M(\varphi), and one mapping maximizes all three. Smatch is FF at M∗M^*.

The match count is symmetric. If φ\varphi is a mapping from TT to GG, its inverse φ−1\varphi^{-1} on the image is a mapping from GG to TT. A test triple tt matches the gold triple φ(t)\varphi(t) exactly when φ−1\varphi^{-1} maps φ(t)\varphi(t) to tt, and φ\varphi is one to one on triples because it is one to one on variables. So the matched triples of the two directions are in bijection, and M∗M^* is the same in both directions.

For a corpus of pairs (Ti,Gi)(T_i, G_i) the score is computed from the sums, P=∑iMi∗/∑i∣Ti∣P = \sum_i M^*_i / \sum_i |T_i|, R=∑iMi∗/∑i∣Gi∣R = \sum_i M^*_i / \sum_i |G_i| and F=2∑iMi∗/(∑i∣Ti∣+∑i∣Gi∣)F = 2 \sum_i M^*_i / (\sum_i |T_i| + \sum_i |G_i|), by the same algebra. This is in general not the mean of the sentence scores.

Part 2: the exact search is correct

The function match_count looks at each test triple once. It skips a triple whose first variable is unmapped, or whose second field is an unmapped variable. Otherwise it forms the image and tests it against GG. This is the definition of a match, so it returns M(φ)M(\varphi).

smatch_brute_force enumerates every one to one partial map from the mm test variables to the nn gold variables: it chooses an ordered list of mm slots from the nn gold variables and mm copies of "nothing", and it removes repeated lists. There are ∑k(mk)n!(n−k)!\sum_{k} \binom{m}{k} \frac{n!}{(n-k)!} of them, where kk is the number of mapped variables. It keeps the largest count, so it returns M∗M^*.

Monotonicity. Let φ\varphi leave a test variable vv unmapped, and let gg be a gold variable outside the image of φ\varphi. Let φ′\varphi' agree with φ\varphi and send vv to gg. Every triple that matches under φ\varphi does not contain vv, because a triple with an unmapped variable never matches, so it has the same image under φ′\varphi' and still matches. Hence M(φ′)≥M(φ)M(\varphi') \ge M(\varphi). Repeating this, a mapping that is maximal (it maps min⁡(m,n)\min(m, n) variables) reaches M∗M^*. So an exact search may restrict itself to maximal mappings. When m≤nm \le n, these are the n!/(n−m)!n!/(n-m)! one to one maps of all test variables.

Part 3: hill climbing stops and gives a lower bound

climb starts from a mapping and looks at two kinds of moves: send one test variable to an unused gold variable or to nothing, and swap the images of two test variables. Each move gives a one to one mapping again. Line L5 stops when no move raises MM. Otherwise line L6 takes the move with the largest gain.

Termination. The gain of a taken move is a positive integer, so MM rises by at least 1 at each step. MM is at most ∣T∣|T|. So climb takes at most ∣T∣|T| steps. Each step looks at m(n+1)+(m2)m(n + 1) + \binom{m}{2} moves. smatch_hill_climb runs climb once from the concept-matching start and once from each of a fixed number of random starts, so it stops.

Lower bound. Every mapping that climb holds is a one to one partial map, so its count is M(φ)≤M∗M(\varphi) \le M^*. The result of smatch_hill_climb is the count of one such mapping, so it is at most M∗M^*, and the score it reports is at most the true Smatch score.

Not always optimal. The result of one climb is a local maximum: no single move raises MM. It need not be M∗M^*. Take

  • TT: instance(t0, p), instance(t1, q), r(t0, t1),
  • GG: instance(g0, q), instance(g1, q), r(g0, g1).

The concept-matching start finds no gold variable with concept pp for t0t_0, and gives t1t_1 the first gold variable with concept qq. So it is t0↦t_0 \mapsto nothing, t1↦g0t_1 \mapsto g_0, with M=1M = 1. The moves are: t0↦g1t_0 \mapsto g_1 (the relation goes to r(g1, g0), which is not in GG, so M=1M = 1), t1↦g1t_1 \mapsto g_1 (M=1M = 1), t1↦t_1 \mapsto nothing (M=0M = 0), and the swap (t0↦g0t_0 \mapsto g_0, t1↦t_1 \mapsto nothing, M=0M = 0). None of them raises MM, so the climb stops at 1. The mapping t0↦g0t_0 \mapsto g_0, t1↦g1t_1 \mapsto g_1 matches instance(t1, q) and r(t0, t1), so M∗=2M^* = 2. The tests check this case and also check, on random graphs, that random restarts find M∗M^* where one climb does not.

Part 4: the best mapping is NP-hard

The decision problem asks, for graphs TT and GG and an integer kk, whether some mapping has M(φ)≥kM(\varphi) \ge k.

It is in NP. A mapping is a certificate of size O(m)O(m), and match_count checks it in time polynomial in ∣T∣+∣G∣|T| + |G|.

It is NP-hard. We reduce from subgraph isomorphism: given undirected graphs HH and KK, is there a one to one map ff from the vertices of HH to the vertices of KK that sends every edge of HH to an edge of KK? This problem is NP-complete, since it contains the clique problem. Build TT from HH: a variable xvx_v with the triple instance(x_v, node) for each vertex vv, and the two triples edge(x_u, x_v) and edge(x_v, x_u) for each edge {u,v}\{u, v\}. Build GG from KK in the same way. Let k=∣V(H)∣+2∣E(H)∣=∣T∣k = |V(H)| + 2|E(H)| = |T|. The construction takes linear time.

If ff exists, the mapping xv↦xf(v)x_v \mapsto x_{f(v)} is one to one. Every instance triple matches, because all concepts are node. Each edge triple edge(x_u, x_v) maps to edge(x_{f(u)}, x_{f(v)}), which is in GG because {f(u),f(v)}\{f(u), f(v)\} is an edge of KK. So M=∣T∣=kM = |T| = k.

If some mapping has M≥k=∣T∣M \ge k = |T|, every test triple matches. An instance triple matches only if its variable is mapped, so every test variable is mapped, and f(v)=f(v) = the vertex of the image of xvx_v is one to one. An edge triple matches only if its image is an edge triple of GG, so ff sends every edge of HH to an edge of KK. So HH is isomorphic to a subgraph of KK.

Hence the decision problem is NP-complete, even with one concept and one role. Computing M∗M^* is therefore NP-hard, and no polynomial time exact algorithm exists unless P = NP. The tests run this reduction on random small graphs and compare it with a direct search for the subgraph. ∎

Complexity

Exact search. There are ∑k(mk)n!(n−k)!≤(n+1)m\sum_{k} \binom{m}{k} \frac{n!}{(n-k)!} \le (n + 1)^m one to one partial mappings, and each takes O(t)O(t) time to score with a hash table of gold triples. For m=n=5m = n = 5 there are 1546. The exact search is only for tiny graphs.

Hill climbing. One step looks at m(n+1)+(m2)m(n + 1) + \binom{m}{2} moves. Scoring a move from scratch takes O(t)O(t), so a step takes O(t(mn+m2))O(t(m n + m^2)), and a climb has at most ∣T∣≤t|T| \le t steps. With rr restarts the worst case is O(r t2(mn+m2))O(r\,t^2 (m n + m^2)), expected with hashing. The space is O(t+m+n)O(t + m + n). The implementation on this page scores moves from scratch for clarity. The standard tool first lists, for each test triple, the pairs of variable images that would make it match, and then computes the gain of a move from the triples that touch the moved variables, which is much faster in practice.

Measurement. Cai and Knight compared the integer program, which is exact, with hill climbing from a smart start and four random restarts on AMR data, and found that hill climbing gave nearly the same scores at a small fraction of the time. That setting is the default of the tool.

Properties

  • Symmetric match count. The best MM from TT to GG equals the best MM from GG to TT, so swapping the graphs swaps PP and RR and keeps FF.
  • Identity. A graph scored against itself, with renamed variables, gets F=1F = 1, and hill climbing finds it from the smart start when every concept occurs once.
  • Lower bound. The reported score never exceeds the true one. More restarts can only raise it.
  • Randomized. The result depends on the random restarts. With a fixed seed it is reproducible.
  • No word alignment. The score depends only on the graphs. Two graphs can score high even if a parser got the concepts from the wrong words.

Variants and improvements

  • Integer program. Cai and Knight also write the search as a 0-1 integer program, with one variable for each pair of test and gold variables and one for each pair of triples that could match, which gives the exact score with a general solver at a much higher cost. See binary integer programming.
  • Fine-grained scores. Later tools split the triples by kind and report separate scores for concepts, named entities, negation, reentrancies and semantic roles, to show where a parser fails.
  • Faster or exact metrics. Later work replaced the search with an exact solver, or with a metric that compares graphs through their paths or through graph kernels, to avoid the randomness of the search.

When to use it

Use Smatch to evaluate an AMR parser against gold graphs, to measure agreement between two annotators, and in general to compare two small labeled graphs whose node names are arbitrary. Report the corpus score, state the number of restarts or use the default, and use the same tool for every system in a comparison. For graphs that come with an alignment to the words, a metric that uses the alignment is cheaper and exact.

Pitfalls

  • Averaging sentence scores. The corpus score sums the counts. The mean of the sentence F values is a different number.
  • Hill climbing noise. Two runs with different seeds can give slightly different scores. Small differences between systems can be within this noise.
  • Variable names. Both graphs must use separate variable names, or a reader must rename them first. Otherwise a test variable can be confused with a gold one.
  • Inverse roles. In PENMAN notation :ARG0-of is the inverse of :ARG0. The reader must turn (b :ARG0-of w) into ARG0(w, b), or equal graphs will not match.
  • Constants and quotes. "Ed" and Ed must be read as the same constant.
  • Tool versions. Tools differ in small details, such as whether the root gets an extra triple. Compare scores only from the same tool.

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.

smatch.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/smatch/. The authors are listed in prov/SMYWR9.jsonl.

"""Smatch: the F1 of matching triples between two AMR graphs.

An AMR graph is a set of triples of three kinds:
  ("instance", v, concept)   the variable v is an instance of concept
  (role, v, w)               a relation between two variables
  (role, v, constant)        an attribute with a constant value
A value is a variable if it is the second field of an instance triple.

A mapping sends each variable of the test graph to a distinct variable of the
gold graph, or to None. A test triple matches if its image under the mapping
(constants map to themselves) is a gold triple. M(m) is the number of matched
test triples. Smatch is the F1 of the best mapping:
  P = M / |test|, R = M / |gold|, F = 2 M / (|test| + |gold|).

smatch_brute_force tries every mapping. smatch_hill_climb is the search of Cai
and Knight 2013: steepest ascent over two moves (remap one variable, swap the
images of two variables), started once from a concept-matching mapping and
then from random mappings. It returns a lower bound on the best M.
"""

from fractions import Fraction
from itertools import permutations
import random


def variables(triples):
    """The variables of a graph, in sorted order."""
    return sorted({t[1] for t in triples if t[0] == "instance"})


def match_count(test, gold, mapping):
    """Number of test triples whose image under mapping is in gold."""
    gold = set(gold)
    tvars = set(variables(test))
    count = 0
    for rel, a, b in set(test):
        a2 = mapping.get(a)
        if a2 is None:
            continue
        if rel == "instance" or b not in tvars:
            b2 = b
        else:
            b2 = mapping.get(b)
            if b2 is None:
                continue
        if (rel, a2, b2) in gold:
            count += 1
    return count


def all_mappings(tvars, gvars):
    """Every injective partial map from tvars to gvars (None means unmapped)."""
    m = len(tvars)
    slots = list(gvars) + [None] * m
    seen = set()
    for perm in permutations(slots, m):
        if perm in seen:
            continue
        seen.add(perm)
        yield dict(zip(tvars, perm))


def smatch_brute_force(test, gold):
    """Exact best match count and one best mapping, by trying every mapping."""
    best, best_map = -1, None
    for mapping in all_mappings(variables(test), variables(gold)):
        c = match_count(test, gold, mapping)
        if c > best:
            best, best_map = c, mapping
    return best, best_map


def smart_init(test, gold):
    """Map each test variable to an unused gold variable with the same concept."""
    concept_t = {t[1]: t[2] for t in test if t[0] == "instance"}
    by_concept = {}
    for t in sorted(set(gold)):
        if t[0] == "instance":
            by_concept.setdefault(t[2], []).append(t[1])
    used = set()
    mapping = {}
    for v in variables(test):
        mapping[v] = None
        for g in by_concept.get(concept_t[v], []):
            if g not in used:
                mapping[v] = g
                used.add(g)
                break
    return mapping


def random_init(test, gold, rng):
    """A random injective partial mapping."""
    tvars = variables(test)
    slots = variables(gold) + [None] * len(tvars)
    rng.shuffle(slots)
    return dict(zip(tvars, slots[: len(tvars)]))


def climb(test, gold, mapping):
    """Steepest ascent from mapping; return (M, mapping) at a local maximum."""
    tvars = variables(test)
    gvars = variables(gold)
    mapping = dict(mapping)  # @line L1
    score = match_count(test, gold, mapping)
    while True:  # @line L2
        best_gain, best_move = 0, None
        used = {g for g in mapping.values() if g is not None}
        for a in tvars:  # @line L3
            for g in gvars + [None]:
                if g == mapping[a] or (g is not None and g in used):
                    continue
                trial = dict(mapping)
                trial[a] = g
                gain = match_count(test, gold, trial) - score
                if gain > best_gain:
                    best_gain, best_move = gain, trial
        for i in range(len(tvars)):  # @line L4
            for j in range(i + 1, len(tvars)):
                a, b = tvars[i], tvars[j]
                if mapping[a] == mapping[b]:
                    continue
                trial = dict(mapping)
                trial[a], trial[b] = mapping[b], mapping[a]
                gain = match_count(test, gold, trial) - score
                if gain > best_gain:
                    best_gain, best_move = gain, trial
        if best_move is None:  # @line L5
            return score, mapping
        mapping, score = best_move, score + best_gain  # @line L6


def smatch_hill_climb(test, gold, restarts=4, seed=0):
    """Best (M, mapping) over one smart start and `restarts` random starts."""
    rng = random.Random(seed)
    best, best_map = climb(test, gold, smart_init(test, gold))  # @line L7
    for _ in range(restarts):  # @line L8
        c, m = climb(test, gold, random_init(test, gold, rng))
        if c > best:  # @line L9
            best, best_map = c, m
    return best, best_map  # @line L10


def prf(match, n_test, n_gold):
    """Precision, recall and F1 as Fractions; 0 when undefined."""
    p = Fraction(match, n_test) if n_test else Fraction(0)
    r = Fraction(match, n_gold) if n_gold else Fraction(0)
    f = Fraction(2 * match, n_test + n_gold) if n_test + n_gold else Fraction(0)
    return p, r, f


def smatch(test, gold, exact=False, restarts=4, seed=0):
    """Return (P, R, F) of the best mapping found."""
    if exact:
        m, _ = smatch_brute_force(test, gold)
    else:
        m, _ = smatch_hill_climb(test, gold, restarts, seed)
    return prf(m, len(set(test)), len(set(gold)))


def corpus_smatch(pairs, exact=False, restarts=4, seed=0):
    """Corpus score: sum the matches and the triple counts over all pairs."""
    total_m = total_t = total_g = 0
    for test, gold in pairs:
        if exact:
            m, _ = smatch_brute_force(test, gold)
        else:
            m, _ = smatch_hill_climb(test, gold, restarts, seed)
        total_m += m
        total_t += len(set(test))
        total_g += len(set(gold))
    return prf(total_m, total_t, total_g)


def _tokens(text):
    out = []
    i = 0
    while i < len(text):
        c = text[i]
        if c.isspace():
            i += 1
        elif c in "()/":
            out.append(c)
            i += 1
        elif c == '"':
            j = text.index('"', i + 1)
            out.append(text[i : j + 1])
            i = j + 1
        else:
            j = i
            while j < len(text) and not text[j].isspace() and text[j] not in '()/"':
                j += 1
            out.append(text[i:j])
            i = j
    return out


def parse_penman(text, prefix=""):
    """Read one AMR in PENMAN notation and return its list of triples.

    Variables get the prefix, so that two graphs can share no names. A role
    that ends in "-of" (but not ":consist-of") is read as the inverse of the
    role without it. Constants keep their quotes off.
    """
    toks = _tokens(text)
    pos = 0
    triples = []
    names = set()

    def node():
        nonlocal pos
        assert toks[pos] == "("
        var = prefix + toks[pos + 1]
        assert toks[pos + 2] == "/"
        concept = toks[pos + 3]
        pos += 4
        names.add(var)
        triples.append(("instance", var, concept))
        while toks[pos] != ")":
            role = toks[pos]
            assert role.startswith(":")
            role = role[1:]
            pos += 1
            if toks[pos] == "(":
                value = node()
                is_var = True
            else:
                value = toks[pos].strip('"')
                pos += 1
                is_var = None
            pending.append((role, var, value, is_var))
        pos += 1
        return var

    pending = []
    node()
    for role, a, b, is_var in pending:
        if is_var is None and prefix + b in names:
            b = prefix + b
        if role.endswith("-of") and role != "consist-of" and b in names:
            triples.append((role[:-3], b, a))
        else:
            triples.append((role, a, b))
    return triples
test_smatch.py 181 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/smatch/. The authors are listed in prov/SMYWR9.jsonl.

from fractions import Fraction
from itertools import permutations
from math import comb, perm
import random

from smatch import (
    all_mappings,
    climb,
    corpus_smatch,
    match_count,
    parse_penman,
    smart_init,
    smatch,
    smatch_brute_force,
    smatch_hill_climb,
)

# The example of Cai and Knight 2013, section 2.
GOLD = parse_penman("(a / want-01 :ARG0 (b / boy) :ARG1 (c / go-01 :ARG0 b))")
TEST = parse_penman("(x / want-01 :ARG0 (y / boy) :ARG1 (z / football))")


def rand_graph(rng, nv, ne, concepts, roles, pre):
    vs = [pre + str(i) for i in range(nv)]
    t = [("instance", v, rng.choice(concepts)) for v in vs]
    for _ in range(ne):
        t.append((rng.choice(roles), rng.choice(vs), rng.choice(vs)))
    if rng.random() < 0.5:
        t.append(("polarity", rng.choice(vs), "-"))
    return sorted(set(t))


def test_reader():
    assert sorted(GOLD) == sorted([
        ("instance", "a", "want-01"),
        ("instance", "b", "boy"),
        ("instance", "c", "go-01"),
        ("ARG0", "a", "b"),
        ("ARG1", "a", "c"),
        ("ARG0", "c", "b"),
    ])
    assert len(TEST) == 5


def test_reader_inverse_role_and_constant():
    g = parse_penman('(b / boy :ARG0-of (w / want-01) :name (n / name :op1 "Ed") :polarity -)', "p.")
    assert ("ARG0", "p.w", "p.b") in g
    assert ("op1", "p.n", "Ed") in g
    assert ("polarity", "p.b", "-") in g


def test_paper_table_of_six_mappings():
    want = {
        ("a", "b", "c"): 4,
        ("a", "c", "b"): 1,
        ("b", "a", "c"): 0,
        ("b", "c", "a"): 0,
        ("c", "a", "b"): 0,
        ("c", "b", "a"): 2,
    }
    for images, m in want.items():
        assert match_count(TEST, GOLD, dict(zip("xyz", images))) == m


def test_paper_score():
    p, r, f = smatch(TEST, GOLD, exact=True)
    assert (p, r, f) == (Fraction(4, 5), Fraction(2, 3), Fraction(8, 11))
    assert round(float(f), 2) == 0.73
    assert smatch(TEST, GOLD) == (p, r, f)


def test_identical_graphs_score_one():
    g2 = parse_penman("(a / want-01 :ARG0 (b / boy) :ARG1 (c / go-01 :ARG0 b))", "g.")
    assert smatch(GOLD, g2, exact=True)[2] == 1
    assert smatch(GOLD, g2)[2] == 1


def test_symmetric_match_count():
    rng = random.Random(1)
    for _ in range(30):
        a = rand_graph(rng, 3, 3, ["p", "q"], ["r", "s"], "t")
        b = rand_graph(rng, 4, 4, ["p", "q"], ["r", "s"], "g")
        assert smatch_brute_force(a, b)[0] == smatch_brute_force(b, a)[0]


def test_number_of_mappings():
    # Injective partial maps from m variables to n variables.
    for m in range(4):
        for n in range(4):
            got = sum(1 for _ in all_mappings(["t" + str(i) for i in range(m)], ["g" + str(i) for i in range(n)]))
            assert got == sum(comb(m, k) * perm(n, k) for k in range(min(m, n) + 1))
    got = sum(1 for _ in all_mappings(list("abcde"), list("ABCDE")))
    assert got == 1546


def test_hill_climbing_stuck_at_local_maximum():
    test = [("instance", "t0", "p"), ("instance", "t1", "q"), ("r", "t0", "t1")]
    gold = [("instance", "g0", "q"), ("instance", "g1", "q"), ("r", "g0", "g1")]
    start = smart_init(test, gold)
    assert start == {"t0": None, "t1": "g0"}
    assert climb(test, gold, start)[0] == 1
    assert smatch_brute_force(test, gold)[0] == 2
    assert match_count(test, gold, {"t0": "g0", "t1": "g1"}) == 2


def test_hill_climbing_never_exceeds_brute_force():
    rng = random.Random(2)
    for trial in range(60):
        a = rand_graph(rng, 5, rng.randint(3, 7), ["p", "q", "r"], ["r", "s"], "t")
        b = rand_graph(rng, rng.randint(3, 5), rng.randint(3, 7), ["p", "q", "r"], ["r", "s"], "g")
        opt, best_map = smatch_brute_force(a, b)
        got, mapping = smatch_hill_climb(a, b, restarts=1, seed=trial)
        assert got <= opt
        assert match_count(a, b, mapping) == got
        assert match_count(a, b, best_map) == opt


def test_restarts_reach_the_optimum():
    rng = random.Random(5)
    cases = []
    for _ in range(120):
        a = rand_graph(rng, 4, rng.randint(2, 6), ["p", "q", "r"], ["r", "s"], "t")
        b = rand_graph(rng, rng.randint(3, 5), rng.randint(2, 6), ["p", "q", "r"], ["r", "s"], "g")
        cases.append((a, b, smatch_brute_force(a, b)[0]))
    stuck_without = sum(smatch_hill_climb(a, b, restarts=0, seed=7)[0] < opt for a, b, opt in cases)
    stuck_with = sum(smatch_hill_climb(a, b, restarts=20, seed=7)[0] < opt for a, b, opt in cases)
    assert stuck_without > 0
    assert stuck_with == 0


def test_corpus_score_sums_counts():
    g2 = parse_penman("(w / want-01 :ARG0 (b / boy))", "g.")
    t2 = parse_penman("(w / want-01 :ARG0 (b / girl))", "t.")
    p, r, f = corpus_smatch([(TEST, GOLD), (t2, g2)], exact=True)
    # Matches 4 + 2, test triples 5 + 3, gold triples 6 + 3.
    assert (p, r, f) == (Fraction(6, 8), Fraction(6, 9), Fraction(12, 17))
    mean_f = (smatch(TEST, GOLD, exact=True)[2] + smatch(t2, g2, exact=True)[2]) / 2
    assert mean_f != f


def test_empty_graph():
    assert smatch([], GOLD, exact=True) == (0, 0, 0)


def has_subgraph(h_edges, nh, g_edges, ng):
    gset = set(g_edges) | {(v, u) for u, v in g_edges}
    for images in permutations(range(ng), nh):
        if all((images[u], images[v]) in gset for u, v in h_edges):
            return True
    return False


def graph_to_amr(edges, n, pre):
    t = [("instance", pre + str(v), "node") for v in range(n)]
    for u, v in edges:
        t.append(("edge", pre + str(u), pre + str(v)))
        t.append(("edge", pre + str(v), pre + str(u)))
    return t


def test_reduction_from_subgraph_isomorphism():
    # H is a subgraph of G iff the best match count is |V(H)| + 2 |E(H)|.
    rng = random.Random(9)
    seen = {True: 0, False: 0}
    for _ in range(40):
        nh, ng = 3, 4
        all_h = [(u, v) for u in range(nh) for v in range(u + 1, nh)]
        all_g = [(u, v) for u in range(ng) for v in range(u + 1, ng)]
        h = [e for e in all_h if rng.random() < 0.6]
        g = [e for e in all_g if rng.random() < 0.5]
        best, _ = smatch_brute_force(graph_to_amr(h, nh, "h"), graph_to_amr(g, ng, "g"))
        answer = has_subgraph(h, nh, g, ng)
        assert (best == nh + 2 * len(h)) == answer
        seen[answer] += 1
    assert seen[True] > 0 and seen[False] > 0
    triangle = [(0, 1), (1, 2), (0, 2)]
    four_cycle = [(0, 1), (1, 2), (2, 3), (0, 3)]
    assert smatch_brute_force(graph_to_amr(triangle, 3, "h"), graph_to_amr(four_cycle, 4, "g"))[0] < 9

History

Cai and Knight introduced Smatch in 2013, the year of the first AMR release by Banarescu and others, who used it to measure agreement between annotators. Cai and Knight wrote the triples, the F1 score and the integer program, and they made hill climbing with a smart start and four random restarts the practical method. Smatch became the standard metric for AMR parsing, and later work added fine-grained scores and exact or faster variants.

References

  1. Shu Cai and Kevin Knight, Smatch: an Evaluation Metric for Semantic Feature Structures, Section 2 (the triples, the example and the score), Section 3 (the integer program, hill climbing, smart initialization and restarts), Table 2 (accuracy and speed of the methods)
  2. Laura Banarescu et al., Abstract Meaning Representation for Sembanking, the PENMAN notation of AMR and the use of Smatch for agreement between annotators

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.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example