Algorithm Search⌘K

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
Properties
deterministicnot exactnot in placeofflineiterative
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 a×aa \times a matrix AAAA with non-negative entries. For a workload of qq queries, where query kk uses the set of attributes UkU_k and runs fkf_k times in total over all sites, the attribute affinity matrix is AA(i,j)=∑fkAA(i, j) = \sum f_k over the queries kk that use both AiA_i and AjA_j. The bond of two columns is bond(x,y)=∑zAA(z,x) AA(z,y)\mathrm{bond}(x, y) = \sum_z AA(z, x) \, AA(z, y), the inner product of the two columns, and the bond with an empty place outside the order is 0. For an order c1,…,cac_1, \dots, c_a of the columns, with the rows in the same order, the global affinity measure is

AM=∑j=1a(bond(cj,cj−1)+bond(cj,cj+1))=2∑j=1a−1bond(cj,cj+1).AM = \sum_{j=1}^{a} \big(\mathrm{bond}(c_j, c_{j-1}) + \mathrm{bond}(c_j, c_{j+1})\big) = 2 \sum_{j=1}^{a-1} \mathrm{bond}(c_j, c_{j+1}).

The goal is an order with a large AMAM. For a symmetric matrix whose rows and columns move together, AMAM is the measure of effectiveness of McCormick et al. Finding the order of largest AMAM 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

  1. BEA(AA) ▷ AA is a symmetric a × a matrix; the result is an order of the columns and the clustered matrix
  2. 1order ← (A_1, A_2)
  3. 2for k = 3, ..., a do
  4. 3for each place loc = 0, ..., k - 1 in order do ▷ between the neighbors A_i and A_j, or at an end
  5. 4value(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)
  6. 5insert A_k into order at the leftmost place of largest value
  7. 6CA ← AA with its rows and columns both in the order of order
  8. 7return order, CA

Line L4 is the change of AMAM caused by the insertion: the pair Ai,AjA_i, A_j stops being neighbors, and the pairs Ai,AkA_i, A_k and Ak,AjA_k, A_j 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 TATA and a bottom part BABA. For each split point, CTQCTQ is the total frequency of the queries that use only attributes of TATA, CBQCBQ the same for BABA, and COQCOQ the total frequency of the queries that use both parts. The step picks the split point with the largest z=CTQ⋅CBQ−COQ2z = CTQ \cdot CBQ - COQ^2 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 A1A_1 to A4A_4 and a key. The workload has four queries: {A1,A3}\{A_1, A_3\} runs 45 times, {A2,A3}\{A_2, A_3\} 5 times, {A2,A4}\{A_2, A_4\} 75 times and {A3,A4}\{A_3, A_4\} 3 times. The affinity matrix is

A1A_1 A2A_2 A3A_3 A4A_4
A1A_1 45 0 45 0
A2A_2 0 80 5 75
A3A_3 45 5 53 3
A4A_4 0 75 3 78

The bonds that the run needs are bond(A1,A2)=225\mathrm{bond}(A_1, A_2) = 225, bond(A1,A3)=4410\mathrm{bond}(A_1, A_3) = 4410, bond(A1,A4)=135\mathrm{bond}(A_1, A_4) = 135, bond(A2,A3)=890\mathrm{bond}(A_2, A_3) = 890, bond(A2,A4)=11865\mathrm{bond}(A_2, A_4) = 11865 and bond(A3,A4)=768\mathrm{bond}(A_3, A_4) = 768.

  • Line L1 gives the order A1A2A_1 A_2.
  • For A3A_3, the three places give cont=8820\mathrm{cont} = 8820 (before A1A_1), 1015010150 (between A1A_1 and A2A_2) and 17801780 (after A2A_2). The order becomes A1A3A2A_1 A_3 A_2.
  • For A4A_4, the four places give 270270, −7014-7014, 2348623486 and 2373023730. The largest is at the end, and the order becomes A1A3A2A4A_1 A_3 A_2 A_4.

The order has AM=2(4410+890+11865)=34330AM = 2(4410 + 890 + 11865) = 34330. A search over all 24 orders shows that no order is better here; the starting order A1A2A3A4A_1 A_2 A_3 A_4 has AM=3766AM = 3766. The clustered matrix has two blocks, {A1,A3}\{A_1, A_3\} and {A2,A4}\{A_2, A_4\}, with small entries outside them.

The split step tries three points. After A1A_1: CTQ=0CTQ = 0, CBQ=83CBQ = 83, COQ=45COQ = 45, z=−2025z = -2025. After A3A_3: CTQ=45CTQ = 45, CBQ=75CBQ = 75, COQ=8COQ = 8, z=3311z = 3311. After A2A_2: CTQ=50CTQ = 50, CBQ=0CBQ = 0, COQ=78COQ = 78, z=−6084z = -6084. The best point is after A3A_3, so the fragments are (key,A1,A3)(\text{key}, A_1, A_3) and (key,A2,A4)(\text{key}, A_2, A_4). Only the 8 runs of the two queries that read A3A_3 together with A2A_2 or A4A_4 need both fragments.

Correctness

BEA is a heuristic, so "correct" here means two facts, both proved on the proof page. First, AMAM 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 12∑i,jaij(ai,j−1+ai,j+1+ai−1,j+ai+1,j)\tfrac{1}{2} \sum_{i,j} a_{ij} (a_{i,j-1} + a_{i,j+1} + a_{i-1,j} + a_{i+1,j}) equals 2∑jbond(cj,cj+1)2 \sum_j \mathrm{bond}(c_j, c_{j+1}). Second, the value of line L4 is exactly the change of AMAM, so line L5 picks the best of the kk possible insertions of AkA_k (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. AAAA is a symmetric a×aa \times a matrix with non-negative entries. For two columns xx and yy, bond(x,y)=∑z=1aAA(z,x) AA(z,y)\mathrm{bond}(x, y) = \sum_{z=1}^{a} AA(z, x) \, AA(z, y), and bond(x,y)=0\mathrm{bond}(x, y) = 0 when xx or yy is the empty place A0A_0 or Aa+1A_{a+1} outside the order. For an order c1,…,cmc_1, \dots, c_m of some of the columns, with the rows in the same order, the global affinity measure is

AM(c1,…,cm)=∑j=1m(bond(cj,cj−1)+bond(cj,cj+1))=2∑j=1m−1bond(cj,cj+1),AM(c_1, \dots, c_m) = \sum_{j=1}^{m} \big(\mathrm{bond}(c_j, c_{j-1}) + \mathrm{bond}(c_j, c_{j+1})\big) = 2 \sum_{j=1}^{m-1} \mathrm{bond}(c_j, c_{j+1}),

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 BB be the matrix AAAA with its rows and its columns both put in the order c1,…,cac_1, \dots, c_a. The measure of effectiveness of McCormick, Schweitzer and White,

ME(B)=12∑i,jBij (Bi,j−1+Bi,j+1+Bi−1,j+Bi+1,j),ME(B) = \tfrac{1}{2} \sum_{i, j} B_{ij} \, (B_{i, j-1} + B_{i, j+1} + B_{i-1, j} + B_{i+1, j}),

with Bij=0B_{ij} = 0 outside the matrix, equals AM(c1,…,ca)AM(c_1, \dots, c_a).

Proof. The column part is ∑i,jBij(Bi,j−1+Bi,j+1)=∑j∑iBijBi,j+1+∑j∑iBijBi,j−1\sum_{i, j} B_{ij} (B_{i, j-1} + B_{i, j+1}) = \sum_j \sum_i B_{ij} B_{i, j+1} + \sum_j \sum_i B_{ij} B_{i, j-1}. The inner sum ∑iBijBi,j+1\sum_i B_{ij} B_{i, j+1} runs over all rows, so it does not depend on the order of the rows, and it equals bond(cj,cj+1)\mathrm{bond}(c_j, c_{j+1}). Each of the two sums is ∑j=1a−1bond(cj,cj+1)\sum_{j=1}^{a-1} \mathrm{bond}(c_j, c_{j+1}), so the column part is 2∑jbond(cj,cj+1)2 \sum_j \mathrm{bond}(c_j, c_{j+1}). Because AAAA is symmetric and the rows have the same order as the columns, BB is symmetric, so the row part ∑i,jBij(Bi−1,j+Bi+1,j)\sum_{i,j} B_{ij} (B_{i-1, j} + B_{i+1, j}) equals the column part. Then ME(B)=12⋅2⋅2∑jbond(cj,cj+1)=AMME(B) = \tfrac{1}{2} \cdot 2 \cdot 2 \sum_j \mathrm{bond}(c_j, c_{j+1}) = AM. □\square

Lemma 2 (contribution). Let c1,…,cmc_1, \dots, c_m be an order and let AkA_k be a column that is not in it. Put AkA_k between AiA_i and AjA_j, two neighbors of the order (or an empty place at an end). Then the new order has

AMnew−AMold=cont(Ai,Ak,Aj)=2 bond(Ai,Ak)+2 bond(Ak,Aj)−2 bond(Ai,Aj).AM_{\text{new}} - AM_{\text{old}} = \mathrm{cont}(A_i, A_k, A_j) = 2\,\mathrm{bond}(A_i, A_k) + 2\,\mathrm{bond}(A_k, A_j) - 2\,\mathrm{bond}(A_i, A_j).

Proof. By the second form of AMAM, the measure is twice the sum of the bonds of neighboring pairs. The insertion removes the neighbor pair (Ai,Aj)(A_i, A_j) and adds the pairs (Ai,Ak)(A_i, A_k) and (Ak,Aj)(A_k, A_j). All other neighbor pairs stay. If AiA_i or AjA_j is an empty place, its bonds are 0 and the formula still holds. □\square

Theorem 1 (correctness of the order). BEA returns an order of all aa columns, and the matrix of line L6 is AAAA with its rows and columns in that order. For each k≥3k \ge 3, the order after step kk has the largest AMAM among all orders that insert AkA_k into the order after step k−1k - 1.

Proof. Line L1 places A1A_1 and A2A_2. For each kk from 3 to aa, line L2 takes the column AkA_k, which is not placed yet. Lines L3 and L4 compute cont\mathrm{cont} for each of the kk places of the current order of k−1k - 1 columns, and line L5 inserts AkA_k at a place with the largest value. By Lemma 2 the value at each place is the change of AMAM, and AMoldAM_{\text{old}} is the same for all places, so the chosen order has the largest AMAM among the kk candidates. Each column is inserted once, so the final order holds every column once. Line L6 orders the rows as the columns. □\square

Theorem 2 (no global guarantee). BEA does not always return an order of largest AMAM.

Proof. Take a=4a = 4 and three queries: q1q_1 uses A1A_1 and A2A_2 four times, q2q_2 uses A1A_1 and A4A_4 twice, and q3q_3 uses A1A_1 and A3A_3 once. The affinity matrix has the rows (7,4,1,2)(7, 4, 1, 2), (4,4,0,0)(4, 4, 0, 0), (1,0,1,0)(1, 0, 1, 0) and (2,0,0,2)(2, 0, 0, 2). The bonds needed are bond(A1,A2)=44\mathrm{bond}(A_1, A_2) = 44, bond(A1,A3)=8\mathrm{bond}(A_1, A_3) = 8, bond(A1,A4)=18\mathrm{bond}(A_1, A_4) = 18, bond(A2,A3)=4\mathrm{bond}(A_2, A_3) = 4, bond(A2,A4)=8\mathrm{bond}(A_2, A_4) = 8 and bond(A3,A4)=2\mathrm{bond}(A_3, A_4) = 2. BEA starts with A1A2A_1 A_2. For A3A_3 the contributions at the three places are 1616, −64-64 and 88, so it gives A3A1A2A_3 A_1 A_2. For A4A_4 they are 44, 2424, −36-36 and 1616, so it gives A3A4A1A2A_3 A_4 A_1 A_2 with AM=2(2+18+44)=128AM = 2(2 + 18 + 44) = 128. The order A3A2A1A4A_3 A_2 A_1 A_4 has AM=2(4+44+18)=132AM = 2(4 + 44 + 18) = 132. □\square

Remark (the exact problem). By the second form of AMAM, an order of largest AMAM is a path through all columns of largest total weight, where the weight of the pair {x,y}\{x, y\} is 2 bond(x,y)2\,\mathrm{bond}(x, y). 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 O(a3)O(a^3) time and O(a2)O(a^2) space.

Proof. There are a(a+1)/2a(a + 1)/2 bonds, each a sum of aa products, so the table of bonds takes O(a3)O(a^3) time and O(a2)O(a^2) space. Step kk evaluates kk contributions, each with three lookups, and an insertion into a list of length k−1k - 1 in O(k)O(k) time. The sum over k≤ak \le a is O(a2)O(a^2). Line L6 copies a2a^2 entries. The total is O(a3)O(a^3). Without the table, each contribution costs O(a)O(a) and the steps cost O(a3)O(a^3) in total, which is the same bound. □\square

The split step. For a split point ii of the order, let TATA be the first ii attributes and BABA the rest. CTQCTQ is the total frequency of the queries whose attributes all lie in TATA, CBQCBQ the same for BABA, and COQCOQ 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 CTQ+CBQ+COQCTQ + CBQ + COQ is the total frequency. The step returns a split point with the largest z=CTQ⋅CBQ−COQ2z = CTQ \cdot CBQ - COQ^2. 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 a(a+1)/2a(a+1)/2 bonds costs O(a3)O(a^3). Step kk looks at kk places with three lookups each, so all steps cost O(a2)O(a^2). The total is O(a3)O(a^3). Building the affinity matrix from the workload costs O(qa2)O(q a^2) more.
  • Space. O(a2)O(a^2) for the matrix and the table of bonds.
  • The split step. A direct count over all split points and queries costs O(a2q)O(a^2 q).

Properties

  • Not optimal (theorem). Take four attributes and the queries {A1,A2}\{A_1, A_2\} 4 times, {A1,A4}\{A_1, A_4\} 2 times and {A1,A3}\{A_1, A_3\} once. BEA gives A3A4A1A2A_3 A_4 A_1 A_2 with AM=128AM = 128, but A3A2A1A4A_3 A_2 A_1 A_4 has AM=132AM = 132. 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, O(a3)O(a^3) 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.

bond_energy_algorithm.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • 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