Algorithm Search⌘K

Algorithmadvanced

Similarity flooding

Also called Melnik similarity flooding.

Match two schema graphs by propagating initial similarities of nodes to their neighbors until a fixpoint, then filtering the pairs.

Time
O(s(v + e) + v log v) worst
Space
O(v + e) extra
Where
e = the number of edges of the pairwise connectivity graph; s = the number of fixpoint steps; v = the number of map pairs
Properties
deterministicnot exactnot in placeofflineiterative
Origin
Sergey Melnik, Hector Garcia Molina, Erhard Rahm, 2002

Similarity flooding is a heuristic for schema matching. It turns two schemas into labeled graphs, starts from a guess of how similar each pair of nodes is, and lets the similarity of a pair flow to the pairs next to it until the values settle. A filter then keeps one partner for each node. The method knows nothing about schemas in particular, so it matches any two labeled graphs.

In plain words

Two tables describe the same people with different names. You are fairly sure that the type "string" of one schema is the type "varchar" of the other. If two columns have similar types, the columns are a bit more likely to match. If two tables have columns that match, the tables are more likely to match, and that in turn makes their other columns more likely to match.

Similarity flooding repeats this reasoning in rounds. Each pair of nodes passes part of its score to the pairs that sit next to it in both graphs at the same time. After each round the scores are scaled so that the best one is 1. When the scores stop changing, a final step picks, for each node, at most one partner with a high score.

The problem

The input is two directed graphs AA and BB with labeled edges a→la′a \xrightarrow{l} a', and an initial similarity σ0(a,b)≥0\sigma^0(a, b) \ge 0 for some pairs of a node aa of AA and a node bb of BB. A schema becomes such a graph with nodes for tables, columns and types, and labels such as col and type. The initial values usually come from a string matcher on the names, for example edit distance. The output is a set of pairs (a,b)(a, b) in which each node occurs at most one time. This is a heuristic answer to schema matching, so there is no exact optimum to compare with.

The method uses these objects.

  • A map pair is a pair (a,b)(a, b) of a node of AA and a node of BB.
  • The pairwise connectivity graph has an edge (a,b)→l(a′,b′)(a, b) \xrightarrow{l} (a', b') for each edge a→la′a \xrightarrow{l} a' of AA and each edge b→lb′b \xrightarrow{l} b' of BB with the same label ll.
  • The propagation graph has, for each such edge, a forward edge from (a,b)(a, b) to (a′,b′)(a', b') with weight 1/outl(a,b)1/\mathrm{out}_l(a, b) and a backward edge from (a′,b′)(a', b') to (a,b)(a, b) with weight 1/inl(a′,b′)1/\mathrm{in}_l(a', b'). Here outl(x)\mathrm{out}_l(x) and inl(x)\mathrm{in}_l(x) count the ll-edges out of and into xx in the pairwise connectivity graph. So a pair splits its score equally among its neighbors of each label. This weight rule is one choice, and other rules are possible.
  • The propagation step is φ(σ)(y)=∑w⋅σ(x)\varphi(\sigma)(y) = \sum w \cdot \sigma(x) over the edges x→yx \to y of the propagation graph with weight ww.

The fixpoint formulas differ in what is added back in each step.

formula the next vector before scaling
basic σ+φ(σ)\sigma + \varphi(\sigma)
A σ0+φ(σ)\sigma^0 + \varphi(\sigma)
B φ(σ0+σ)\varphi(\sigma^0 + \sigma)
C (σ0+σ)+φ(σ0+σ)(\sigma^0 + \sigma) + \varphi(\sigma^0 + \sigma)

The algorithm

  1. SIMILARITY-FLOODING(A, B, sigma0, formula, theta, eps, limit)
  2. 1P <- the pairwise connectivity graph of A and B
  3. 2for each edge x -l-> y of P do
  4. 3add x -> y with weight 1/out_l(x), and y -> x with weight 1/in_l(y)
  5. 4sigma <- sigma0
  6. 5repeat
  7. 6choose the base and the argument of the formula
  8. 7next <- base + phi(argument)
  9. 8next <- next / max(next) ▷ only if max(next) > 0
  10. 9r <- the Euclidean distance from next to sigma; sigma <- next
  11. 10until r < eps or limit steps are done
  12. 11run Gale-Shapley on the pairs with sigma >= theta and sigma > 0
  13. 12return the stable pairs

Line L1 builds the pairs of edges with the same label. Lines L2 and L3 give each edge a forward and a backward weight. Lines L5 to L10 iterate the chosen formula, and each step scales the vector so that its largest value is 1. Lines L11 and L12 are the filter. Here the filter is a stable matching found by Gale-Shapley: each node of AA ranks the nodes of BB by the similarity, each node of BB ranks the nodes of AA the same way, and ties are broken by the node order.

Example

Schema AA has a table Emp with the columns Name of type string and Dept of type int. Schema BB has a table Staff with the columns FullName of type varchar and Unit of type integer. The graph of AA has the edges Emp →col\xrightarrow{col} Name, Emp →col\xrightarrow{col} Dept, Name →type\xrightarrow{type} string and Dept →type\xrightarrow{type} int, and BB is the same with its names. The initial similarity is σ0(string,varchar)=σ0(int,integer)=1\sigma^0(\text{string}, \text{varchar}) = \sigma^0(\text{int}, \text{integer}) = 1, and 0 for all other pairs. The names of the tables and the columns have nothing in common, so a name matcher gives them nothing.

The pairwise connectivity graph has 8 edges. The pair (Emp, Staff) has 4 col edges, to (Name, FullName), (Name, Unit), (Dept, FullName) and (Dept, Unit), so each forward weight from (Emp, Staff) is 1/41/4. Each column pair has one type edge, for example (Name, FullName) →type\xrightarrow{type} (string, varchar), and all the other weights are 1.

The first three steps of the basic formula give these values after scaling.

step (Emp, Staff) (Name, FullName), (Dept, Unit) (Name, Unit), (Dept, FullName) (string, varchar), (int, integer) (string, integer), (int, varchar)
0 0 0 0 1 0
1 0 1 0 1 0
2 1 1 0 1 0
3 1 0.75 0.0833 0.6667 0

In step 3, before scaling, (Emp, Staff) has 1+1+1=31 + 1 + 1 = 3, (Name, FullName) has 1+1/4+1=2.251 + 1/4 + 1 = 2.25 and (Name, Unit) has 0+1/4=0.250 + 1/4 = 0.25. Division by 3 gives the row.

The basic formula goes on for 104 steps with ε=10−9\varepsilon = 10^{-9}. It ends with (Emp, Staff) at 1, all four column pairs at 0.3536, and all four type pairs at 0.25. The right column pairs and the wrong ones end with the same value, because the basic formula forgets σ0\sigma^0 (see Correctness). Formula C stops after 43 steps with these values.

pair value
(Emp, Staff) 1
(Name, FullName), (Dept, Unit) 0.9653
(string, varchar), (int, integer) 0.8876
(Name, Unit), (Dept, FullName) 0.1418
(string, integer), (int, varchar) 0.0640

The filter with θ=0.5\theta = 0.5 keeps (Emp, Staff), (Name, FullName), (Dept, Unit), (string, varchar) and (int, integer). The column pairs are found only through the types and the table, which is the point of the method.

Correctness

There is no correct output to prove, because the matching itself is a heuristic. The proof file proves what the procedure guarantees.

  • Lines L1 to L3 build exactly the propagation graph of the definition.
  • Each step keeps all values in [0,1][0, 1] with the largest equal to 1, unless the vector is 0. Only formula B can reach 0.
  • The loop stops after at most the step limit.
  • For the basic formula, assume the propagation graph is connected and σ0\sigma^0 is nonnegative and not zero. Then the iteration is power iteration with the matrix I+MI + M, where MM holds the weights. Each edge has a backward edge, so MM is irreducible, and I+MI + M is primitive. By the Perron-Frobenius theorem, the vector converges to the Perron vector of I+MI + M, scaled to a largest value of 1. The limit does not depend on σ0\sigma^0.
  • The filter returns a stable matching of the pairs at or above the threshold.

The last point but one is a theorem, and it explains the example: the basic formula forgets the initial similarities. Formulas A and C add σ0\sigma^0 in each step, and B adds it inside φ\varphi. Their convergence is not proved here. That they give better matches is a heuristic claim, and only measurements on real schemas can support it.

Proof: Similarity flooding builds the propagation graph, keeps similarities in [0, 1], converges for the basic formula and returns a stable matchingfull

Similarity flooding is a heuristic, so there is no "right" answer to prove against. This file proves what the procedure itself guarantees. It shows that lines L1 to L3 build the propagation graph of the definition, that each step keeps the values in [0,1][0, 1], that the basic formula converges and where it converges to, that the loop stops, and that lines L11 and L12 return a stable matching. Nothing here says that the pairs found are the correct correspondences; that is a heuristic, and only measurements can support it.

Notation. The input graphs have edge sets EAE_A and EBE_B of labeled edges a→la′a \xrightarrow{l} a'. A map pair is a pair (a,b)(a, b) of a node of AA and a node of BB. Let VV be the set of map pairs that are an end of an edge of the pairwise connectivity graph or that have a value in σ0\sigma^0. We write a vector σ:V→R≥0\sigma : V \to \mathbb{R}_{\ge 0}. For a node xx and a label ll, outl(x)\mathrm{out}_l(x) is the number of ll-edges out of xx in the pairwise connectivity graph and inl(x)\mathrm{in}_l(x) is the number of ll-edges into xx.

Lemma 1 (construction). After line L1, the list holds exactly the edges (a,b)→l(a′,b′)(a, b) \xrightarrow{l} (a', b') with a→la′a \xrightarrow{l} a' in EAE_A and b→lb′b \xrightarrow{l} b' in EBE_B, each one time. After lines L2 and L3, the propagation graph has, for each such edge, a forward edge with weight 1/outl((a,b))1/\mathrm{out}_l((a, b)) and a backward edge from (a′,b′)(a', b') to (a,b)(a, b) with weight 1/inl((a′,b′))1/\mathrm{in}_l((a', b')), and no other edge.

Proof. The code puts the edges of BB in lists by label. For each edge a→la′a \xrightarrow{l} a' of AA it adds one edge for each entry (b,b′)(b, b') of the list of ll. So each pair of edges with the same label gives one edge, and no other pair gives an edge. Both inputs pass through a set first, so a repeated input edge counts one time. The counts outl\mathrm{out}_l and inl\mathrm{in}_l are computed over this list before line L2, and lines L2 and L3 add exactly two weighted edges for each list entry. □\square

Let MM be the V×VV \times V matrix with MyxM_{yx} equal to the sum of the weights of the edges x→yx \to y of the propagation graph. Then φ(σ)=Mσ\varphi(\sigma) = M\sigma is the vector that the function _phi computes. MM is nonnegative. For each label ll and each node xx with outl(x)>0\mathrm{out}_l(x) > 0, the forward edges of label ll out of xx have weights that sum to 1, and the same holds for the backward edges into a node. So each column of MM sums to at most twice the number of labels at that node.

Lemma 2 (range). Assume σ0≥0\sigma^0 \ge 0. After each step, all values are in [0,1][0, 1], and the largest value is 1, unless all values are 0.

Proof. By induction on the steps. At the start, σ=σ0≥0\sigma = \sigma^0 \ge 0. In a step, the base and the argument of line L6 are sums of nonnegative vectors, and MM is nonnegative, so the vector of line L7 is nonnegative. If its largest value tt is positive, line L8 divides by tt, so the values are in [0,1][0, 1] and the largest is 1. If t=0t = 0, all values are 0. □\square

The vector can become 0 only for formula B, which drops the base: if no node with a positive value has an edge, then φ(σ0+σ)=0\varphi(\sigma^0 + \sigma) = 0. For the other formulas the base keeps a positive value.

Lemma 3 (termination). The loop of lines L5 to L10 stops after at most the step limit of steps.

Proof. Each pass increases the step count by 1, and line L10 stops the loop when the count reaches the limit. □\square

Theorem (the basic formula). Assume that the undirected graph under the propagation graph is connected, that it has at least one edge, and that σ0≥0\sigma^0 \ge 0 is not zero. Let σk\sigma^k be the vector after kk steps of the basic formula σk+1=(σk+Mσk)/max⁡(σk+Mσk)\sigma^{k+1} = (\sigma^k + M\sigma^k)/\max(\sigma^k + M\sigma^k). Then σk\sigma^k converges to u/max⁡uu / \max u, where uu is the positive Perron vector of I+MI + M. The limit does not depend on σ0\sigma^0.

Proof. Each step multiplies by T=I+MT = I + M and then divides by a positive number. Scaling commutes with multiplication by TT, so σk=Tkσ0/max⁡(Tkσ0)\sigma^k = T^k \sigma^0 / \max(T^k \sigma^0).

TT is nonnegative. Each forward edge x→yx \to y has a backward edge y→xy \to x, and the weights are positive, so Myx>0M_{yx} > 0 if and only if Mxy>0M_{xy} > 0. The undirected graph is connected, so the directed graph of MM is strongly connected, and MM is irreducible. Then T=I+MT = I + M is irreducible and has a positive diagonal, so it is primitive: some power TmT^m has only positive entries.

By the Perron-Frobenius theorem for primitive matrices, TT has a simple eigenvalue ρ>0\rho > 0 that is larger in absolute value than each other eigenvalue, with a positive right eigenvector uu and a positive left eigenvector ww, and Tk/ρk→uw⊤/(w⊤u)T^k / \rho^k \to u w^\top / (w^\top u) as k→∞k \to \infty. So

Tkσ0ρk→w⊤σ0w⊤u u.\frac{T^k \sigma^0}{\rho^k} \to \frac{w^\top \sigma^0}{w^\top u}\, u.

The number w⊤σ0w^\top \sigma^0 is positive, because w>0w > 0, σ0≥0\sigma^0 \ge 0 and σ0≠0\sigma^0 \neq 0. The map v↦v/max⁡vv \mapsto v / \max v is continuous at each nonzero nonnegative vector and does not change under positive scaling. So σk→u/max⁡u\sigma^k \to u / \max u. ■\blacksquare

Consequence. Under the assumptions of the theorem, the basic formula keeps no information from σ0\sigma^0 in the limit. The limit is fixed by the shape of the two graphs alone. With the stopping test of line L10, the procedure returns a vector close to this limit when ε\varepsilon is small and the step limit is large. This is why the formulas A, B and C add σ0\sigma^0 back in each step. For these three formulas this file proves only Lemmas 2 and 3. Their convergence is not proved here, and the loop relies on the step limit.

Theorem (filter). Lines L11 and L12 return a set PP of pairs with these properties. Each node of AA and each node of BB is in at most one pair of PP. Each pair (a,b)(a, b) in PP has σ(a,b)≥θ\sigma(a, b) \ge \theta and σ(a,b)>0\sigma(a, b) > 0. There is no blocking pair: no pair (a,b)(a, b) with σ(a,b)≥θ\sigma(a, b) \ge \theta and σ(a,b)>0\sigma(a, b) > 0, not in PP, such that aa is free or prefers bb to its partner and bb is free or prefers aa to its partner.

Here aa prefers bb to b′b' when σ(a,b)>σ(a,b′)\sigma(a, b) > \sigma(a, b'), or the two values are equal and bb comes before b′b' in the node order. In the same way bb prefers aa to a′a' when σ(a,b)>σ(a′,b)\sigma(a, b) > \sigma(a', b), or the values are equal and aa comes before a′a'. The ties are broken, so both orders are strict.

Proof. The acceptable pairs are those with σ≥θ\sigma \ge \theta and σ>0\sigma > 0, and lines L11 and L12 run the Gale-Shapley proposal algorithm on them with the strict orders above. Each node of AA proposes to each acceptable partner at most one time, in its order of preference, so the loop stops after at most the number of acceptable pairs of proposals. A node of BB holds at most one proposal, and it changes only to a partner that it prefers. So the result is a matching of acceptable pairs.

Assume that (a,b)(a, b) blocks it. Since aa is free or prefers bb to its final partner, aa proposed to bb at some time: a free node of AA at the end has proposed to each acceptable partner, and a matched node of AA proposed to each partner it prefers to its final one. When bb got the proposal of aa, it kept aa or a node it prefers to aa, and its partner only gets better after that. So at the end bb has a partner that it prefers to aa, or aa itself. This contradicts that (a,b)(a, b) blocks. ■\blacksquare

Complexity

Let vv be the number of map pairs that occur in the pairwise connectivity graph or in σ0\sigma^0, let ee be the number of edges of that graph, and let ss be the number of steps.

  • Building the graphs. With the edges of BB grouped by label, line L1 takes O(∣EA∣+∣EB∣+e)O(|E_A| + |E_B| + e) time. The number ee is at most ∣EA∣⋅∣EB∣|E_A| \cdot |E_B|, and it is that large when all edges have the same label.
  • One step. φ\varphi visits each of the 2e2e weighted edges once, and the scaling and the distance visit each of the vv pairs, so a step takes O(v+e)O(v + e) time.
  • The filter. Sorting the preference lists takes O(vlog⁡v)O(v \log v) time, and Gale-Shapley makes at most one proposal for each acceptable pair.
  • Total. O(s(v+e)+vlog⁡v)O(s(v + e) + v \log v) time and O(v+e)O(v + e) extra space.

The number of steps ss is not bounded by the analysis. For the basic formula it depends on the gap between the two largest eigenvalues of I+MI + M. In practice the step limit bounds it.

Properties

  • Deterministic. The order of the nodes fixes the result, including the ties of the filter.
  • Not exact. It is a heuristic and gives no guarantee on the quality of the match.
  • Generic. It uses only the labeled graph. The meaning of the schemas enters through the graph encoding and through σ0\sigma^0.
  • Symmetric. Swapping AA and BB swaps the pairs and gives the same values. The weights depend only on the counts in the pairwise connectivity graph.
  • Structural. A pair gets a high value when its neighbors in both graphs also have high values. Two nodes with no common label on their edges get no flow.

Variants and improvements

  • Fixpoint formulas. The four formulas of the table differ in how much of σ0\sigma^0 they keep. Which one works best on a given kind of schema is a question for measurement.
  • Weight rules. The equal split of this page is one rule. A rule can also weight an edge by the counts of both ends, or give some labels more weight than others.
  • Filters. A plain threshold keeps all pairs above a value and allows many partners. The stable matching of this page gives at most one partner. A maximum-weight one-to-one match is the assignment problem, solved by the Hungarian algorithm. Type rules can also forbid pairs, for example a table with a column.
  • Combination with other matchers. In a matching system, similarity flooding is one structural matcher. Its output is combined with name, instance and constraint matchers, as in the survey of Rahm and Bernstein.

When to use it

Use it when two schemas or models have a similar structure but poor name overlap, and you have a few confident seed pairs. It also fits other labeled graphs, such as XML schemas or two versions of the same model. Do not use it when the structures differ a lot, for example a flat table against a nested model of the same data, because the flow then goes along the wrong edges. Always show its output to a person for review, since it is a heuristic.

Pitfalls

  • The basic formula forgets the seeds. On a connected propagation graph it converges to a vector fixed by the graph shape alone, as in the example. Use a formula that adds σ0\sigma^0 back.
  • Quadratic size. The pairwise connectivity graph can have ∣EA∣⋅∣EB∣|E_A| \cdot |E_B| edges when a few labels cover most edges. Fine labels, such as one label for each kind of edge, keep it small.
  • Global scaling. All parts of the propagation graph are scaled by the same maximum. A small part that is not connected to the main part can fade toward 0 even when its seeds are good.
  • Stopping. The loop may stop at the step limit with a vector that has not settled. Record the residual of line L9 and check it.
  • Ties in the filter. Equal values are broken by the node order, and that choice is arbitrary. Two right answers and two wrong answers with the same value cannot be told apart by the filter.

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.

similarity_flooding.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/similarity-flooding/. The authors are listed in prov/BY6RCV.jsonl.

"""Similarity flooding (Melnik, Garcia-Molina and Rahm 2002).

A graph is a list of edges (source, label, target). Nodes are strings or any
values with a total order. The result of the fixpoint is a dict from map pairs
(a, b), with a a node of A and b a node of B, to a similarity in [0, 1].
"""

from collections import defaultdict
from math import sqrt

Edge = tuple  # (source, label, target)

FORMULAS = ("basic", "A", "B", "C")


def pairwise_connectivity_graph(ga, gb):
    """The edges ((a, b), l, (a2, b2)) for each pair of edges a -l-> a2 in A and b -l-> b2 in B."""
    by_label = defaultdict(list)
    for b, label, b2 in sorted(set(gb)):
        by_label[label].append((b, b2))
    out = []
    for a, label, a2 in sorted(set(ga)):
        for b, b2 in by_label.get(label, ()):
            out.append(((a, b), label, (a2, b2)))
    return out


def propagation_graph(ga, gb):
    """The induced propagation graph: a dict from each node x to a list of (y, w).

    Each edge x -l-> y of the pairwise connectivity graph gives a forward edge
    x -> y with weight 1 / (number of l-edges out of x) and a backward edge
    y -> x with weight 1 / (number of l-edges into y).
    """
    pcg = pairwise_connectivity_graph(ga, gb)  # @line L1
    n_out = defaultdict(int)
    n_in = defaultdict(int)
    for x, label, y in pcg:
        n_out[(x, label)] += 1
        n_in[(y, label)] += 1
    prop = defaultdict(list)
    for x, label, y in pcg:  # @line L2
        prop[x].append((y, 1.0 / n_out[(x, label)]))  # @line L3
        prop[y].append((x, 1.0 / n_in[(y, label)]))
    return prop


def _phi(prop, nodes, vec):
    """phi(vec)(y) = sum of w * vec(x) over the edges x -> y with weight w."""
    res = {x: 0.0 for x in nodes}
    for x in nodes:
        v = vec[x]
        if v:
            for y, w in prop.get(x, ()):
                res[y] += w * v
    return res


def flood(ga, gb, sigma0, formula="basic", eps=1e-9, max_iter=1000):
    """Run the fixpoint. Return (sigma, iterations)."""
    if formula not in FORMULAS:
        raise ValueError("unknown formula " + repr(formula))
    prop = propagation_graph(ga, gb)
    nodes = set(prop)
    for x, edges in prop.items():
        nodes.update(y for y, _ in edges)
    nodes.update(sigma0)
    nodes = sorted(nodes)
    s0 = {x: float(sigma0.get(x, 0.0)) for x in nodes}  # @line L4
    sigma = dict(s0)
    it = 0
    while True:  # @line L5
        if formula == "basic":  # @line L6
            base, arg = sigma, sigma
        elif formula == "A":
            base, arg = s0, sigma
        elif formula == "B":
            base, arg = None, {x: s0[x] + sigma[x] for x in nodes}
        else:
            both = {x: s0[x] + sigma[x] for x in nodes}
            base, arg = both, both
        ph = _phi(prop, nodes, arg)
        new = {x: (base[x] if base is not None else 0.0) + ph[x] for x in nodes}  # @line L7
        top = max(new.values(), default=0.0)
        if top > 0:
            new = {x: v / top for x, v in new.items()}  # @line L8
        res = sqrt(sum((new[x] - sigma[x]) ** 2 for x in nodes))  # @line L9
        sigma = new
        it += 1
        if res < eps or it >= max_iter:  # @line L10
            return sigma, it


def stable_filter(sigma, threshold=0.0):
    """A stable marriage on the pairs with similarity at least threshold.

    Nodes of A propose to nodes of B in decreasing order of similarity; ties are
    broken by the node order. Each node is in at most one pair.
    """
    prefs_a = defaultdict(list)
    rank_b = defaultdict(dict)
    for (a, b), v in sigma.items():
        if v >= threshold and v > 0:
            prefs_a[a].append((-v, b))
            rank_b[b][a] = (-v, a)
    for a in prefs_a:
        prefs_a[a].sort()
    nxt = {a: 0 for a in prefs_a}
    engaged = {}  # b -> a
    free = sorted(prefs_a, reverse=True)
    while free:  # @line L11
        a = free.pop()
        if nxt[a] >= len(prefs_a[a]):
            continue
        _, b = prefs_a[a][nxt[a]]
        nxt[a] += 1
        cur = engaged.get(b)
        if cur is None:
            engaged[b] = a
        elif rank_b[b][a] < rank_b[b][cur]:
            engaged[b] = a
            free.append(cur)
        else:
            free.append(a)
    return sorted((a, b) for b, a in engaged.items())  # @line L12


def similarity_flooding(ga, gb, sigma0, formula="basic", threshold=0.0, eps=1e-9, max_iter=1000):
    """Return (pairs, sigma): the filtered pairs and the final similarities."""
    sigma, _ = flood(ga, gb, sigma0, formula, eps, max_iter)
    return stable_filter(sigma, threshold), sigma
test_similarity_flooding.py 164 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/similarity-flooding/. The authors are listed in prov/BY6RCV.jsonl.

import itertools
import random

from similarity_flooding import (
    FORMULAS,
    flood,
    pairwise_connectivity_graph,
    similarity_flooding,
    stable_filter,
)

A = [("Emp", "col", "Name"), ("Emp", "col", "Dept"), ("Name", "type", "string"), ("Dept", "type", "int")]
B = [("Staff", "col", "Unit"), ("Staff", "col", "FullName"), ("FullName", "type", "varchar"), ("Unit", "type", "integer")]
S0 = {("string", "varchar"): 1.0, ("int", "integer"): 1.0}


def dense_flood(ga, gb, sigma0, formula, iters):
    """The oracle: the matrix of the definition, built from the two graphs directly, and the same iteration."""
    na = sorted({x for a, _, a2 in ga for x in (a, a2)})
    nb = sorted({x for b, _, b2 in gb for x in (b, b2)})
    pairs = sorted(set(itertools.product(na, nb)) | set(sigma0))
    idx = {p: i for i, p in enumerate(pairs)}
    n = len(pairs)
    m = [[0.0] * n for _ in range(n)]  # m[y][x]: weight of x -> y
    sa, sb = sorted(set(ga)), sorted(set(gb))
    for x in pairs:
        for label in sorted({e[1] for e in sa}):
            outs = [(a2, b2) for (a, l1, a2) in sa for (b, l2, b2) in sb
                    if l1 == label and l2 == label and (a, b) == x]
            ins = [(a, b) for (a, l1, a2) in sa for (b, l2, b2) in sb
                   if l1 == label and l2 == label and (a2, b2) == x]
            for y in outs:
                m[idx[y]][idx[x]] += 1.0 / len(outs)
            for y in ins:
                m[idx[y]][idx[x]] += 1.0 / len(ins)
    s0 = [float(sigma0.get(p, 0.0)) for p in pairs]
    s = list(s0)
    for _ in range(iters):
        if formula == "basic":
            base, arg = s, s
        elif formula == "A":
            base, arg = s0, s
        elif formula == "B":
            base, arg = [0.0] * n, [u + v for u, v in zip(s0, s)]
        else:
            arg = [u + v for u, v in zip(s0, s)]
            base = arg
        new = [base[i] + sum(m[i][j] * arg[j] for j in range(n)) for i in range(n)]
        top = max(new, default=0.0)
        if top > 0:
            new = [v / top for v in new]
        s = new
    return {p: s[idx[p]] for p in pairs}


def random_graph(rng, prefix, n_nodes, n_edges, labels):
    nodes = [prefix + str(i) for i in range(n_nodes)]
    return [(rng.choice(nodes), rng.choice(labels), rng.choice(nodes)) for _ in range(n_edges)]


def test_example_pcg():
    pcg = pairwise_connectivity_graph(A, B)
    assert len(pcg) == 8
    assert (("Emp", "Staff"), "col", ("Name", "FullName")) in pcg


def test_example_values():
    sig, it = flood(A, B, S0, "C")
    assert abs(sig[("Emp", "Staff")] - 1.0) < 1e-12
    assert round(sig[("Name", "FullName")], 4) == 0.9653
    assert round(sig[("Dept", "FullName")], 4) == 0.1418
    pairs, _ = similarity_flooding(A, B, S0, "C", threshold=0.5)
    assert pairs == [("Dept", "Unit"), ("Emp", "Staff"), ("Name", "FullName"), ("int", "integer"), ("string", "varchar")]
    # The basic formula forgets the initial similarities: the two column pairs tie.
    sig_b, _ = flood(A, B, S0, "basic")
    assert abs(sig_b[("Name", "FullName")] - sig_b[("Name", "Unit")]) < 1e-6


def test_first_steps_by_hand():
    sig, _ = flood(A, B, S0, "basic", eps=0, max_iter=3)
    assert abs(sig[("Dept", "FullName")] - 1 / 12) < 1e-12
    assert abs(sig[("Name", "FullName")] - 0.75) < 1e-12
    assert abs(sig[("int", "integer")] - 2 / 3) < 1e-12


def test_against_dense_oracle():
    rng = random.Random(7)
    for _ in range(40):
        ga = random_graph(rng, "a", rng.randint(1, 4), rng.randint(0, 6), ["l", "m"])
        gb = random_graph(rng, "b", rng.randint(1, 4), rng.randint(0, 6), ["l", "m"])
        na = sorted({x for a, _, a2 in ga for x in (a, a2)}) or ["a0"]
        nb = sorted({x for b, _, b2 in gb for x in (b, b2)}) or ["b0"]
        s0 = {(x, y): rng.choice([0.0, 0.5, 1.0]) for x in na for y in nb}
        for formula in FORMULAS:
            k = rng.randint(1, 6)
            got, it = flood(ga, gb, s0, formula, eps=0, max_iter=k)
            assert it == k
            want = dense_flood(ga, gb, s0, formula, k)
            for p in set(got) | set(want):
                assert abs(got.get(p, 0.0) - want.get(p, 0.0)) < 1e-9


def test_range_and_symmetry():
    rng = random.Random(11)
    for _ in range(30):
        ga = random_graph(rng, "a", 3, rng.randint(1, 6), ["l", "m"])
        gb = random_graph(rng, "b", 3, rng.randint(1, 6), ["l", "m"])
        s0 = {("a%d" % i, "b%d" % j): rng.random() for i in range(3) for j in range(3)}
        for formula in FORMULAS:
            sig, _ = flood(ga, gb, s0, formula, max_iter=50)
            vals = list(sig.values())
            assert all(-1e-12 <= v <= 1 + 1e-12 for v in vals)
            # Formula B drops sigma0 when no edge propagates, so the vector can be zero.
            assert abs(max(vals) - 1.0) < 1e-12 or max(vals) == 0.0
            rev, _ = flood(gb, ga, {(y, x): v for (x, y), v in s0.items()}, formula, max_iter=50)
            for (x, y), v in sig.items():
                assert abs(rev[(y, x)] - v) < 1e-9


def test_stable_filter_is_stable():
    rng = random.Random(3)
    for _ in range(200):
        na, nb = rng.randint(0, 4), rng.randint(0, 4)
        sig = {("a%d" % i, "b%d" % j): rng.choice([0.0, 0.2, 0.4, 0.6, 0.8, 1.0])
               for i in range(na) for j in range(nb)}
        th = rng.choice([0.0, 0.3, 0.7])
        pairs = stable_filter(sig, th)
        left = [a for a, _ in pairs]
        right = [b for _, b in pairs]
        assert len(set(left)) == len(left) and len(set(right)) == len(right)
        assert all(sig[p] >= th and sig[p] > 0 for p in pairs)
        mate_a = dict(pairs)
        mate_b = {b: a for a, b in pairs}

        def pref_a(a, b):  # smaller is better
            return (-sig[(a, b)], b)

        def pref_b(b, a):
            return (-sig[(a, b)], a)

        for (a, b), v in sig.items():
            if v < th or v <= 0 or mate_a.get(a) == b:
                continue
            a_wants = a not in mate_a or pref_a(a, b) < pref_a(a, mate_a[a])
            b_wants = b not in mate_b or pref_b(b, a) < pref_b(b, mate_b[b])
            assert not (a_wants and b_wants)


def test_edges():
    sig, it = flood([], [], {}, "C")
    assert sig == {} and it == 1
    # No common label: nothing propagates, and the basic formula keeps sigma0 scaled.
    sig, _ = flood([("x", "l", "y")], [("u", "m", "v")], {("x", "u"): 0.5, ("y", "v"): 0.25}, "basic")
    assert sig == {("x", "u"): 1.0, ("y", "v"): 0.5}
    assert stable_filter({}, 0.0) == []
    try:
        flood(A, B, S0, "D")
    except ValueError:
        pass
    else:
        raise AssertionError("an unknown formula must fail")

History

Sergey Melnik, Hector Garcia-Molina and Erhard Rahm presented similarity flooding at ICDE 2002. They described it as a generic graph matching algorithm and applied it to schema matching, where it plays the role of a structural matcher in the sense of the survey of Rahm and Bernstein from 2001. The idea that a node is similar to another when their neighbors are similar also drives other graph scores, and the fixpoint view links the method to PageRank and to power iteration.

References

  1. Sergey Melnik, Hector Garcia-Molina and Erhard Rahm, Similarity flooding: a versatile graph matching algorithm and its application to schema matching, ICDE 2002, pages 117-128
  2. Erhard Rahm and Philip A. Bernstein, A survey of approaches to automatic schema matching, VLDB Journal 10(4), 2001, the classification of matchers
  3. Carl D. Meyer, Matrix Analysis and Applied Linear Algebra, SIAM, 2000, Chapter 8, Perron-Frobenius theory

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