Algorithmadvanced
Bond energy algorithm
Also called BEA, McCormick bond energy clustering.
A greedy heuristic that permutes the rows and columns of a matrix so that large values sit next to each other. On an attribute affinity matrix it groups attributes that queries use together.
- Time
- O(a^3) worst
- Space
- O(a^2) extra
- Where
- a = the number of attributes (columns of the matrix); q = the number of queries in the workload
- Model
- Word RAM
- Properties
- deterministicnot exactnot in placeofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- William T. McCormick, Paul J. Schweitzer, Thomas W. White, 1972
The bond energy algorithm (BEA) reorders the rows and the columns of a matrix so that large values come together in blocks. McCormick, Schweitzer and White gave it in 1972 as a general method to cluster any data matrix. In database design, its input is the attribute affinity matrix of a workload, and the blocks of the result are groups of attributes that the queries use together, which are good candidates for a vertical fragmentation. BEA is a greedy heuristic: each step is the best possible insertion, but the final order is not always the best order.
In plain words
A table has many columns, and the queries of a workload read only some of them. Two columns are close when many queries read both. BEA puts the columns in a row, one at a time. Each new column goes into the place where it sits next to the columns that it is closest to. At the end, close columns stand side by side, and the row of columns falls into a few groups. A second step cuts the row at the point that best separates the queries, and each part becomes a fragment of the table. Each part also keeps the key, so the table can be put back together.
The problem
The input is a symmetric matrix with non-negative entries. For a workload of queries, where query uses the set of attributes and runs times in total over all sites, the attribute affinity matrix is over the queries that use both and . The bond of two columns is , the inner product of the two columns, and the bond with an empty place outside the order is 0. For an order of the columns, with the rows in the same order, the global affinity measure is
The goal is an order with a large . For a symmetric matrix whose rows and columns move together, is the measure of effectiveness of McCormick et al. Finding the order of largest is a maximum weight Hamiltonian path problem on the columns, a form of the traveling salesman problem, and BEA does not solve it exactly.
The algorithm
BEA(AA) ▷ AA is a symmetric a × a matrix; the result is an order of the columns and the clustered matrix- 1
order ← (A_1, A_2) - 2
for k = 3, ..., a do - 3
for each place loc = 0, ..., k - 1 in order do ▷ between the neighbors A_i and A_j, or at an end - 4
value(loc) ← cont(A_i, A_k, A_j) = 2 bond(A_i, A_k) + 2 bond(A_k, A_j) - 2 bond(A_i, A_j) - 5
insert A_k into order at the leftmost place of largest value - 6
CA ← AA with its rows and columns both in the order of order - 7
return order, CA
Line L4 is the change of caused by the insertion: the pair stops being neighbors, and the pairs and become neighbors. At an end of the order, the missing neighbor is an empty place and its bonds are 0. Line L6 orders the rows the same way as the columns, which keeps the matrix symmetric.
The split step. For vertical fragmentation, a second step cuts the clustered order into a top part and a bottom part . For each split point, is the total frequency of the queries that use only attributes of , the same for , and the total frequency of the queries that use both parts. The step picks the split point with the largest and adds the primary key to both fragments, so that a join on the key gives back the table. This rule is from Navathe et al. (1984). It is a rule of thumb, not the optimum of a cost model.
Example
A relation has the attributes to and a key. The workload has four queries: runs 45 times, 5 times, 75 times and 3 times. The affinity matrix is
| 45 | 0 | 45 | 0 | |
| 0 | 80 | 5 | 75 | |
| 45 | 5 | 53 | 3 | |
| 0 | 75 | 3 | 78 |
The bonds that the run needs are , , , , and .
- Line L1 gives the order .
- For , the three places give (before ), (between and ) and (after ). The order becomes .
- For , the four places give , , and . The largest is at the end, and the order becomes .
The order has . A search over all 24 orders shows that no order is better here; the starting order has . The clustered matrix has two blocks, and , with small entries outside them.
The split step tries three points. After : , , , . After : , , , . After : , , , . The best point is after , so the fragments are and . Only the 8 runs of the two queries that read together with or need both fragments.
Correctness
BEA is a heuristic, so "correct" here means two facts, both proved on the proof page. First, is the bond energy of McCormick et al.: for a symmetric matrix with its rows and columns in the same order, the measure of effectiveness equals . Second, the value of line L4 is exactly the change of , so line L5 picks the best of the possible insertions of (a theorem about each step). There is no guarantee for the final order.
Proof: BEA returns an order of the attributes in which each step is the best insertion, and the global affinity measure is the bond energyfull
We use the line numbers of the pseudocode on the page. is a symmetric matrix with non-negative entries. For two columns and , , and when or is the empty place or outside the order. For an order of some of the columns, with the rows in the same order, the global affinity measure is
where the second form holds because each pair of neighbors is counted once from each side and the bonds with the empty places are 0.
Lemma 1 (AM is the bond energy). Let be the matrix with its rows and its columns both put in the order . The measure of effectiveness of McCormick, Schweitzer and White,
with outside the matrix, equals .
Proof. The column part is . The inner sum runs over all rows, so it does not depend on the order of the rows, and it equals . Each of the two sums is , so the column part is . Because is symmetric and the rows have the same order as the columns, is symmetric, so the row part equals the column part. Then .
Lemma 2 (contribution). Let be an order and let be a column that is not in it. Put between and , two neighbors of the order (or an empty place at an end). Then the new order has
Proof. By the second form of , the measure is twice the sum of the bonds of neighboring pairs. The insertion removes the neighbor pair and adds the pairs and . All other neighbor pairs stay. If or is an empty place, its bonds are 0 and the formula still holds.
Theorem 1 (correctness of the order). BEA returns an order of all columns, and the matrix of line L6 is with its rows and columns in that order. For each , the order after step has the largest among all orders that insert into the order after step .
Proof. Line L1 places and . For each from 3 to , line L2 takes the column , which is not placed yet. Lines L3 and L4 compute for each of the places of the current order of columns, and line L5 inserts at a place with the largest value. By Lemma 2 the value at each place is the change of , and is the same for all places, so the chosen order has the largest among the candidates. Each column is inserted once, so the final order holds every column once. Line L6 orders the rows as the columns.
Theorem 2 (no global guarantee). BEA does not always return an order of largest .
Proof. Take and three queries: uses and four times, uses and twice, and uses and once. The affinity matrix has the rows , , and . The bonds needed are , , , , and . BEA starts with . For the contributions at the three places are , and , so it gives . For they are , , and , so it gives with . The order has .
Remark (the exact problem). By the second form of , an order of largest is a path through all columns of largest total weight, where the weight of the pair is . This is a maximum weight Hamiltonian path, a form of the traveling salesman problem, and the insertion of BEA is the cheapest insertion heuristic for it, run in a fixed order of the columns. The weights here are inner products of non-negative columns, so the general hardness of the traveling salesman problem does not by itself show that this special case is hard; the page makes no claim about that.
Theorem 3 (running time). With all bonds computed first, BEA takes time and space.
Proof. There are bonds, each a sum of products, so the table of bonds takes time and space. Step evaluates contributions, each with three lookups, and an insertion into a list of length in time. The sum over is . Line L6 copies entries. The total is . Without the table, each contribution costs and the steps cost in total, which is the same bound.
The split step. For a split point of the order, let be the first attributes and the rest. is the total frequency of the queries whose attributes all lie in , the same for , and the total frequency of the other queries, which use both sides. A query with at least one attribute is in exactly one of the three groups, so is the total frequency. The step returns a split point with the largest . This is a rule: it prefers two fragments that both serve many queries alone and that few queries need together. It is not derived from a cost model, and it is not proved to minimize any cost.
Complexity
- Time (theorem). A table of all bonds costs . Step looks at places with three lookups each, so all steps cost . The total is . Building the affinity matrix from the workload costs more.
- Space. for the matrix and the table of bonds.
- The split step. A direct count over all split points and queries costs .
Properties
- Not optimal (theorem). Take four attributes and the queries 4 times, 2 times and once. BEA gives with , but has . The tests check this case.
- Depends on the input order. The form on this page inserts the columns in their index order, so a different numbering of the attributes can give a different result.
- Only pairs. The affinity matrix records how often two attributes are used together, not which larger sets of attributes a query reads. Two workloads with the same pair counts give the same clusters.
- Deterministic. With the leftmost place on a tie, the result depends only on the matrix.
- General. Nothing in lines L1 to L7 is about databases. Any non-negative matrix can be clustered this way; the original paper used it on problem decomposition and other data.
Variants and improvements
- The original form. McCormick et al. place one column first and then, at each step, try every column not yet placed at every place, and insert the best pair of column and place. This is the cheapest insertion heuristic for the path problem. It costs more, contributions in total with a table of bonds, and it is also not optimal: the tests show a matrix of five columns where no start column reaches the best order.
- Rectangular matrices. For a data matrix that is not symmetric, the rows and the columns are ordered apart, each by its own bonds, and the measure of effectiveness is the sum of the two parts.
- Better searches for the same objective. Since the objective is a traveling salesman path, any exact solver or a local search such as 2-opt can improve the order. For a small number of attributes, a full search is cheap.
- Many fragments. The split step can be applied again to each part, or the cut can be done at several points at once. The textbook form of the split also shifts the order in a circle and tries the cuts again, so that a block in the middle of the order can be cut out.
- Without the matrix order. Later work groups attributes with other clustering methods or with a cost model of the queries; see vertical fragmentation.
When to use it
Use BEA to get a first proposal of vertical fragments from a workload, when the number of attributes is small to medium and the query frequencies are known. Check the proposal with a cost model, because neither the order nor the split rule is optimal. For row stores with many short queries, also compare with the decomposition storage model, which puts each attribute in its own fragment.
Pitfalls
- Forgetting the key. A vertical fragment without the key cannot be joined back. The split must add the primary key, or a tuple identifier, to each fragment.
- Reading the order as optimal. BEA gives a local choice at each step. A different first pair or a different numbering can give a better order.
- Mixing frequencies and sites. In a distributed workload the frequency of a query is the sum over all sites where it runs. Using the frequency at one site gives a matrix for that site only.
- Splitting only at one point. If the best block is in the middle of the order, a single cut cannot isolate it. Shift the order in a circle or use several cuts.
- Ties. The leftmost place on a tie is a choice. Other choices give other orders with the same steps.
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/bond-energy-algorithm/. The authors are listed in prov/J9KWFD.jsonl.
"""The bond energy algorithm (BEA) and the split step of vertical fragmentation.
Attributes are numbered 0 to n - 1. A workload is a list of queries; query q
uses the set of attributes use[q] and runs freq[q] times in total (summed over
all sites). The attribute affinity matrix is
aff[i][j] = sum of freq[q] over the queries q that use both i and j.
The bond of two columns x and y of a symmetric non-negative matrix M is
bond(x, y) = sum over z of M[z][x] * M[z][y]. For an order of the columns
(and the same order of the rows), the global affinity measure is
AM = sum over j of bond(c_j, c_(j-1)) + bond(c_j, c_(j+1)),
with bond 0 for a neighbor outside the order. It is the measure of
effectiveness of McCormick, Schweitzer and White for a symmetric matrix whose
rows and columns are permuted together.
"""
from itertools import permutations
from collections.abc import Sequence
Matrix = list[list[int]]
def affinity_matrix(n: int, use: Sequence[set[int]], freq: Sequence[int]) -> Matrix:
"""aff[i][j]: the total frequency of the queries that use both attribute i and attribute j."""
aff = [[0] * n for _ in range(n)]
for attrs, f in zip(use, freq):
for i in attrs:
for j in attrs:
aff[i][j] += f
return aff
def bond(m: Matrix, x: int | None, y: int | None) -> int:
"""sum_z m[z][x] * m[z][y]; 0 when x or y is an empty neighbor (None)."""
if x is None or y is None:
return 0
return sum(row[x] * row[y] for row in m)
def global_affinity(m: Matrix, order: Sequence[int]) -> int:
"""AM of a column order: twice the sum of the bonds of neighboring columns."""
return 2 * sum(bond(m, order[k], order[k + 1]) for k in range(len(order) - 1))
def measure_of_effectiveness(m: Matrix, order: Sequence[int]) -> int:
"""McCormick's ME of the matrix with rows and columns both permuted by order, by its definition:
1/2 * sum_ij a_ij (a_i,j-1 + a_i,j+1 + a_i-1,j + a_i+1,j), with zero outside the matrix."""
n = len(order)
a = [[m[order[i]][order[j]] for j in range(n)] for i in range(n)]
get = lambda i, j: a[i][j] if 0 <= i < n and 0 <= j < n else 0
total = 0
for i in range(n):
for j in range(n):
total += a[i][j] * (get(i, j - 1) + get(i, j + 1) + get(i - 1, j) + get(i + 1, j))
return total // 2
def cont(m: Matrix, left: int | None, k: int, right: int | None) -> int:
"""The change of AM when column k goes between left and right."""
return 2 * bond(m, left, k) + 2 * bond(m, k, right) - 2 * bond(m, left, right)
def bea(m: Matrix, trace: list | None = None) -> tuple[list[int], Matrix]:
"""BEA as used for vertical fragmentation: insert the columns in index order,
each at the position of largest contribution (the leftmost one on a tie).
Return the column order and the clustered matrix (rows in the same order)."""
n = len(m)
order = list(range(min(n, 2))) # @line L1
for k in range(2, n): # @line L2
best_loc, best = 0, None
for loc in range(len(order) + 1): # @line L3
left = order[loc - 1] if loc > 0 else None
right = order[loc] if loc < len(order) else None
c = cont(m, left, k, right) # @line L4
if trace is not None:
trace.append((k, loc, c))
if best is None or c > best:
best_loc, best = loc, c
order.insert(best_loc, k) # @line L5
clustered = [[m[i][j] for j in order] for i in order] # @line L6
return order, clustered # @line L7
def bea_original(m: Matrix, first: int = 0) -> list[int]:
"""The form of McCormick et al.: at each step try every unplaced column at every
position and place the one with the largest contribution (cheapest insertion)."""
n = len(m)
if n == 0:
return []
order = [first]
rest = [k for k in range(n) if k != first]
while rest:
best = None
for k in rest:
for loc in range(len(order) + 1):
left = order[loc - 1] if loc > 0 else None
right = order[loc] if loc < len(order) else None
c = cont(m, left, k, right)
if best is None or c > best[0]:
best = (c, k, loc)
_, k, loc = best
order.insert(loc, k)
rest.remove(k)
return order
def best_order(m: Matrix) -> tuple[int, list[int]]:
"""The largest AM over all orders, by brute force (small n only)."""
n = len(m)
if n > 8:
raise ValueError("brute force is for at most 8 columns")
best, arg = -1, list(range(n))
for perm in permutations(range(n)):
v = global_affinity(m, perm)
if v > best:
best, arg = v, list(perm)
return best, arg
def split_scores(order: Sequence[int], use: Sequence[set[int]], freq: Sequence[int]) -> list[tuple[int, int, int, int]]:
"""For each split point i (top = order[:i], bottom = order[i:]) return
(CTQ, CBQ, COQ, z) with z = CTQ * CBQ - COQ ** 2. Queries with no attribute are ignored."""
out = []
for i in range(1, len(order)):
top, bottom = set(order[:i]), set(order[i:])
ctq = cbq = coq = 0
for attrs, f in zip(use, freq):
if not attrs:
continue
if attrs <= top:
ctq += f
elif attrs <= bottom:
cbq += f
else:
coq += f
out.append((ctq, cbq, coq, ctq * cbq - coq * coq))
return out
def split(order: Sequence[int], use: Sequence[set[int]], freq: Sequence[int],
key: Sequence[int] = ()) -> tuple[list[int], list[int]]:
"""Cut the clustered order in two at the split point of largest z (the first one on a tie).
The key attributes are added to both fragments."""
if len(order) < 2:
raise ValueError("need at least two non-key attributes to split")
scores = split_scores(order, use, freq)
i = max(range(len(scores)), key=lambda t: (scores[t][3], -t)) + 1
top = list(key) + [a for a in order[:i] if a not in key]
bottom = list(key) + [a for a in order[i:] if a not in key]
return top, bottom
test_bond_energy_algorithm.py 127 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/bond-energy-algorithm/. The authors are listed in prov/J9KWFD.jsonl.
import random
from itertools import permutations
import pytest
from bond_energy_algorithm import (affinity_matrix, bea, bea_original, best_order, bond, cont,
global_affinity, measure_of_effectiveness, split, split_scores)
def random_workload(rng, n):
q = rng.randint(1, 6)
use = [set(rng.sample(range(n), rng.randint(1, min(3, n)))) for _ in range(q)]
freq = [rng.randint(1, 9) for _ in range(q)]
return use, freq
PAGE_USE = [{0, 2}, {1, 2}, {1, 3}, {2, 3}]
PAGE_FREQ = [45, 5, 75, 3]
def test_page_example():
m = affinity_matrix(4, PAGE_USE, PAGE_FREQ)
assert m == [[45, 0, 45, 0], [0, 80, 5, 75], [45, 5, 53, 3], [0, 75, 3, 78]]
trace = []
order, clustered = bea(m, trace)
assert order == [0, 2, 1, 3]
assert clustered == [[45, 45, 0, 0], [45, 53, 5, 3], [0, 5, 80, 75], [0, 3, 75, 78]]
assert trace == [(2, 0, 8820), (2, 1, 10150), (2, 2, 1780),
(3, 0, 270), (3, 1, -7014), (3, 2, 23486), (3, 3, 23730)]
assert global_affinity(m, order) == 34330 == best_order(m)[0]
assert split_scores(order, PAGE_USE, PAGE_FREQ) == [(0, 83, 45, -2025), (45, 75, 8, 3311), (50, 0, 78, -6084)]
assert split(order, PAGE_USE, PAGE_FREQ) == ([0, 2], [1, 3])
def test_not_optimal_example():
m = affinity_matrix(4, [{0, 1}, {0, 3}, {0, 2}], [4, 2, 1])
order, _ = bea(m)
assert order == [2, 3, 0, 1] and global_affinity(m, order) == 128
assert best_order(m)[0] == 132
assert global_affinity(m, bea_original(m, 0)) == 132
assert global_affinity(m, bea_original(m, 2)) == 128
def test_original_form_can_miss_from_every_start():
m = affinity_matrix(5, [{1, 2, 4}, {1, 2, 3}, {3}, {0, 2, 3}, {2, 3, 4}], [5, 5, 4, 5, 3])
best = max(global_affinity(m, bea_original(m, s)) for s in range(5))
assert best == 2436 < best_order(m)[0] == 2598
@pytest.mark.parametrize("seed", range(40))
def test_am_equals_measure_of_effectiveness(seed):
rng = random.Random(seed)
n = rng.randint(1, 6)
m = affinity_matrix(n, *random_workload(rng, n))
for _ in range(5):
order = list(range(n))
rng.shuffle(order)
assert global_affinity(m, order) == measure_of_effectiveness(m, order)
@pytest.mark.parametrize("seed", range(40))
def test_cont_is_the_change_of_am(seed):
rng = random.Random(1000 + seed)
n = rng.randint(2, 6)
m = affinity_matrix(n, *random_workload(rng, n))
k = rng.randrange(n)
others = [x for x in range(n) if x != k]
rng.shuffle(others)
for loc in range(len(others) + 1):
left = others[loc - 1] if loc > 0 else None
right = others[loc] if loc < len(others) else None
new = others[:loc] + [k] + others[loc:]
assert global_affinity(m, new) - global_affinity(m, others) == cont(m, left, k, right)
@pytest.mark.parametrize("seed", range(40))
def test_each_insertion_is_the_best_position(seed):
rng = random.Random(2000 + seed)
n = rng.randint(1, 7)
m = affinity_matrix(n, *random_workload(rng, n))
order, clustered = bea(m)
assert sorted(order) == list(range(n))
assert clustered == [[m[i][j] for j in order] for i in order]
# Replay: the partial order after each step has the largest AM among all insertions of that column.
partial = list(range(min(n, 2)))
for k in range(2, n):
options = [partial[:loc] + [k] + partial[loc:] for loc in range(len(partial) + 1)]
values = [global_affinity(m, o) for o in options]
partial = options[values.index(max(values))]
assert partial == order
assert global_affinity(m, order) <= best_order(m)[0]
@pytest.mark.parametrize("seed", range(20))
def test_split_matches_definition(seed):
rng = random.Random(3000 + seed)
n = rng.randint(2, 6)
use, freq = random_workload(rng, n)
order, _ = bea(affinity_matrix(n, use, freq))
scores = split_scores(order, use, freq)
for i, (ctq, cbq, coq, z) in enumerate(scores, start=1):
top = set(order[:i])
assert ctq == sum(f for a, f in zip(use, freq) if a and a <= top)
assert cbq == sum(f for a, f in zip(use, freq) if a and not (a & top))
assert ctq + cbq + coq == sum(freq)
assert z == ctq * cbq - coq * coq
top, bottom = split(order, use, freq, key=())
assert sorted(top + bottom) == list(range(n))
best = max(s[3] for s in scores)
assert scores[len(top) - 1][3] == best
def test_key_goes_to_both_fragments():
top, bottom = split([1, 3, 2, 4], [{1, 3}, {2, 4}], [10, 10], key=[0])
assert top == [0, 1, 3] and bottom == [0, 2, 4]
def test_small_cases():
assert bea([]) == ([], [])
assert bea([[5]]) == ([0], [[5]])
assert bond([[1, 2], [3, 4]], 0, 1) == 1 * 2 + 3 * 4
assert bond([[1]], None, 0) == 0
with pytest.raises(ValueError):
split([0], [{0}], [1])
History
McCormick, Schweitzer and White published the bond energy algorithm in Operations Research in 1972. They wanted to find groups in data matrices, such as the parts of a problem that interact, and they measured a permuted matrix by the sum of the products of neighboring entries. Navathe, Ceri, Wiederhold and Dou (1984) built the attribute affinity matrix from a workload, clustered it with BEA, and split the result into vertical fragments. The textbook of Özsu and Valduriez presents this form, with the columns inserted in index order, as the standard method for vertical fragmentation.
References
- William T. McCormick, Paul J. Schweitzer and Thomas W. White, Problem decomposition and data reorganization by a clustering technique, Operations Research 20(5), 1972, pages 993 to 1009, the measure of effectiveness of a permuted matrix and the bond energy algorithm, which places one column at a time at its best position
- Shamkant Navathe, Stefano Ceri, Gio Wiederhold and Jinglie Dou, Vertical partitioning algorithms for database design, ACM Transactions on Database Systems 9(4), 1984, pages 680 to 710, the attribute affinity matrix, its clustering by the bond energy algorithm, and the split of the clustered attributes into fragments
- M. Tamer Özsu and Patrick Valduriez, Principles of Distributed Database Systems, fourth edition, Springer, 2020, Chapter 2, Distributed and Parallel Database Design, the section on vertical fragmentation
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 J9KWFD Edit this page History Report an error Markdown