Algorithm Search⌘K

Algorithmcore

Method of means and medians

Also called MMM clock routing, MMM.

Jackson, Srinivasan and Kuh's clock router that splits the sinks at the median again and again and connects the centre of mass of each half to that of the whole.

Time
O(n log n) worst
Space
Θ(n) extra
Where
n = the number of clock sinks
Properties
deterministicnot exactrecursive
Origin
Mike A. B. Jackson, Arvind Srinivasan, Ernest S. Kuh, 1990

The method of means and medians (MMM) is a clock routing algorithm: it builds a wire tree from the clock source to a set of sinks by splitting the sinks at the median into two halves, alternately by xx and by yy, and joining the centre of mass (the mean) of each set to the centres of mass of its two halves. It generalizes the H-tree to sinks at arbitrary places, and on a full square grid it gives exactly the H-tree. The paths have roughly balanced lengths, but the skew is not zero in general. Jackson, Srinivasan and Kuh published it in 1990.

In plain words

The registers that need the clock are scattered over the chip. Draw a vertical line that puts half of them on each side. Join the middle of all the registers, their average position, to the average position of each side.

Now do the same inside each side, but with a horizontal line. Then use a vertical line again, and so on, until each group holds one register.

Because each cut halves the group, the tree has few levels, and each wire points from a group to the middle of its own half, so no branch goes far out of its way. On a perfect grid of registers every path has the same length. On an uneven placement the paths are only roughly equal, and some registers can get the clock later than others.

The problem

The input is a set of nn sinks with points psp_s in the plane. The output is a rooted tree whose leaves are the sinks, with a point for each internal node and rectilinear wires along the edges, such that the root-to-sink path lengths are close to each other. MMM does not solve a stated optimization problem: it is a construction for the topology and the embedding of clock tree synthesis with no guarantee on skew or wire length, except on a full grid. Its delay model is the path length; the Elmore delay of the result is not balanced either.

The algorithm

  1. MMM(S, axis)
  2. 1c ← the centre of mass of the points of S
  3. 2if |S| = 1 then return a leaf at c
  4. 3order S by the coordinate of axis, ties by the other coordinate; h ← ⌊|S| / 2⌋
  5. 4S₁ ← the first h sinks of S; S₂ ← the other |S| − h sinks
  6. 5T₁ ← MMM(S₁, the other axis); T₂ ← MMM(S₂, the other axis)
  7. 6return a node at c, with wires from c to the roots of T₁ and T₂
  8. 7run MMM(all sinks, x) and connect the clock source to its root

Lines L3 and L4 split SS at its median in the current direction. The implementation sorts the sinks once by xx and once by yy and splits both lists in linear time at each node, which keeps both orders. A final tie break by the sink index makes the order total, so equal points are also split.

Example

Take the sinks s1=(0,6)s_1 = (0, 6), s2=(0,7)s_2 = (0, 7), s3=(2,3)s_3 = (2, 3) and s4=(8,6)s_4 = (8, 6).

set split centre of mass edge to parent
s1,s2,s3,s4s_1, s_2, s_3, s_4 by xx (5/2,11/2)(5/2, 11/2)
s1,s2s_1, s_2 by yy (0,13/2)(0, 13/2) 5/2+1=7/25/2 + 1 = 7/2
s3,s4s_3, s_4 by yy (5,9/2)(5, 9/2) 5/2+1=7/25/2 + 1 = 7/2
s1s_1 and s2s_2 (0,6)(0, 6), (0,7)(0, 7) 1/21/2 each
s3s_3 and s4s_4 (2,3)(2, 3), (8,6)(8, 6) 3+3/2=9/23 + 3/2 = 9/2 each

The paths to s1s_1 and s2s_2 have length 7/2+1/2=47/2 + 1/2 = 4, and the paths to s3s_3 and s4s_4 have length 7/2+9/2=87/2 + 9/2 = 8. The skew under linear delay is 4, and the total wire is 17. The far apart pair s3,s4s_3, s_4 pulls its centre of mass to the middle, and both of its sinks are far from it.

On four sinks (±1,±1)(\pm 1, \pm 1) the root is (0,0)(0, 0), the halves have centres (±1,0)(\pm 1, 0), and every path has length 2, the H-tree on these sinks.

Correctness

The proof is in proofs/correctness.md. The tree is a valid routing tree: each split gives two nonempty halves that partition the set, and the leaves are the sinks at their own points. The depth is exactly ⌈log⁡2n⌉\lceil \log_2 n \rceil, since the larger half has ⌈n/2⌉\lceil n/2 \rceil sinks. On 4k4^k sinks at the centres of a 2k×2k2^k \times 2^k grid on a square of side DD, two levels of splitting reach the centres of the four quarter squares, each at distance D/4+D/4D/4 + D/4 from the centre, and leave four copies of the same problem with half the side. So every path has length D(1−2−k)D (1 - 2^{-k}) and the wire is 32D(2k−1)\frac{3}{2} D (2^k - 1), the values of the H-tree. For other inputs no bound on the skew is proved, and the example above shows a skew of half the longest path.

Proof: The method of means and medians has depth the ceiling of log2 n, runs in O(n log n) time and gives the H-tree on a full gridfull

Model. The input is a list of n≥1n \ge 1 sinks p1,…,pnp_1, \dots, p_n in the plane. The split order on axis aa (0 for xx, 1 for yy) compares (pi[a],pi[1−a],i)(p_i[a], p_i[1 - a], i), which is a total order. For a set SS split on axis aa, the low half is the first ⌊∣S∣/2⌋\lfloor |S|/2 \rfloor sinks of SS in this order and the high half is the rest. The tree has a node for each set that arises, placed at the centre of mass c(S)=1∣S∣∑i∈Spic(S) = \frac{1}{|S|} \sum_{i \in S} p_i, and an edge from the node of each set to the nodes of its two halves, of length the L1 distance between them. The root set is all sinks, split on xx, and the axis alternates with the depth.

Lemma 1 (the output is a routing tree). Each sink is a leaf at its own point, each set of at least two sinks has two nonempty halves that partition it, and every root-to-sink path ends at a distinct sink.

Proof. For ∣S∣≥2|S| \ge 2, both ⌊∣S∣/2⌋≥1\lfloor |S|/2 \rfloor \ge 1 and ∣S∣−⌊∣S∣/2⌋≥1|S| - \lfloor |S|/2 \rfloor \ge 1, and the halves partition SS by definition. Sets shrink strictly, so the recursion ends at sets of size 1, whose centre of mass is the sink itself. The leaves are the singletons of a partition of all sinks, so each sink is reached by exactly one path. □\square

Lemma 2 (the linear split is correct). Let XX and YY be the sinks of SS sorted in the order on axis 0 and on axis 1. Let LL be the first ⌊∣S∣/2⌋\lfloor |S|/2 \rfloor entries of the list for the split axis. Then the entries of XX in LL, in their order in XX, are the low half sorted on axis 0, and the same holds for YY and for the high half.

Proof. LL is the low half by its definition. A sublist of a sorted list, kept in order, is sorted. □\square

Theorem 1 (depth). The tree has depth exactly ⌈log⁡2n⌉\lceil \log_2 n \rceil.

Proof. Let h(n)h(n) be the depth for nn sinks. Then h(1)=0h(1) = 0 and h(n)=1+h(⌈n/2⌉)h(n) = 1 + h(\lceil n/2 \rceil) for n≥2n \ge 2, since the high half is the larger and hh is nondecreasing (by induction, as ⌈n/2⌉\lceil n/2 \rceil is nondecreasing in nn). If 2j−1<n≤2j2^{j - 1} < n \le 2^j with j≥1j \ge 1, then 2j−2<⌈n/2⌉≤2j−12^{j - 2} < \lceil n/2 \rceil \le 2^{j - 1} (for j=1j = 1, ⌈n/2⌉=1\lceil n/2 \rceil = 1). By induction h(n)=1+(j−1)=j=⌈log⁡2n⌉h(n) = 1 + (j - 1) = j = \lceil \log_2 n \rceil. □\square

Theorem 2 (time). With the two lists sorted once at the start, the algorithm runs in O(nlog⁡n)O(n \log n) time.

Proof. The two sorts take O(nlog⁡n)O(n \log n). At a set SS, the centre of mass takes O(∣S∣)O(|S|) arithmetic operations, and by Lemma 2 the four lists of the halves are made by one pass over each list of SS with a mark on the sinks of LL, in O(∣S∣)O(|S|) time. The sets at one depth are disjoint, so each depth costs O(n)O(n), and by Theorem 1 there are ⌈log⁡2n⌉+1\lceil \log_2 n \rceil + 1 depths. □\square

Theorem 3 (full grid). Let n=4kn = 4^k sinks be the centres of the cells of a 2k×2k2^k \times 2^k grid on a square of side DD. Then every root-to-sink path has length D(1−2−k)D (1 - 2^{-k}), so the skew under linear delay is zero, and the total wire length is 32D(2k−1)\frac{3}{2} D (2^k - 1). These are the values of the H-tree on the same sinks.

Proof. By induction on kk. For k=0k = 0 the tree is one sink, with length 0 and wire 0. Let k≥1k \ge 1 and put the square at [0,D]2[0, D]^2. The order on axis 0 lists the sinks column by column, so the low half of size 4k/24^k / 2 is the left 2k−12^{k - 1} columns. Its centre of mass is (D/4,D/2)(D/4, D/2) by symmetry, at distance D/4D/4 from the root at (D/2,D/2)(D/2, D/2); the right half is the mirror. Each half is split on axis 1, and the low half of the left half is its lower 2k−12^{k - 1} rows, a 2k−1×2k−12^{k - 1} \times 2^{k - 1} grid on the square [0,D/2]2[0, D/2]^2, with centre (D/4,D/4)(D/4, D/4) at distance D/4D/4 from (D/4,D/2)(D/4, D/2). The other three quarters are the same up to symmetry. So two levels add D/4+D/4=D/2D/4 + D/4 = D/2 to every path and 2⋅D/4+4⋅D/4=32D2 \cdot D/4 + 4 \cdot D/4 = \frac{3}{2} D to the wire, and leave four copies of the problem with k−1k - 1 and side D/2D/2, whose next split is again on axis 0. The path length is D/2+(D/2)(1−2−(k−1))=D(1−2−k)D/2 + (D/2)(1 - 2^{-(k-1)}) = D (1 - 2^{-k}), and the wire is 32D+4⋅32D2(2k−1−1)=32D(2k−1)\frac{3}{2} D + 4 \cdot \frac{3}{2} \frac{D}{2} (2^{k - 1} - 1) = \frac{3}{2} D (2^k - 1). □\square

Remark (no zero skew in general). The sinks (0,6)(0, 6), (0,7)(0, 7), (2,3)(2, 3) and (8,6)(8, 6) give path lengths 4, 4, 8 and 8, as computed on the page, so Theorem 3 does not extend to arbitrary sinks.

Complexity

The two sorts take O(nlog⁡n)O(n \log n) time. At a set SS the centre of mass and the split of both sorted lists take O(∣S∣)O(|S|) time, the sets at one depth are disjoint, and there are ⌈log⁡2n⌉+1\lceil \log_2 n \rceil + 1 depths, so the total is O(nlog⁡n)O(n \log n). A version that sorts each set again takes O(nlog⁡2n)O(n \log^2 n); one that finds each median by linear-time selection also takes O(nlog⁡n)O(n \log n). The tree has 2n−12n - 1 nodes, so the space is Θ(n)\Theta(n).

Properties

  • The tree is a full binary tree of depth ⌈log⁡2n⌉\lceil \log_2 n \rceil (proved), so the number of branch points on every path is the same up to one.
  • On a full 2k×2k2^k \times 2^k grid of sinks it is the H-tree, with zero skew (proved).
  • In general the skew is not zero, and no bound on it or on the wire length is proved.
  • It is a top-down method: the topology and the embedding come from the same splits, and nothing is computed bottom up from delays.
  • The result depends on the first split direction and on the tie break; a rotation of the input can change the tree.

Variants and improvements

  • Topology for exact zero skew. The most common use is as a topology generator. Tsay's method or deferred-merge embedding on the MMM topology then gives exact zero skew, with the points of the nodes chosen bottom up instead of at the centres of mass.
  • Choice of direction. Instead of alternating, each set can be split along the direction in which it is wider, or along the direction that gives the shorter wires.
  • Weighted sinks. With load capacitances, the centre of mass can be weighted by the loads, and the split can balance the load instead of the count.
  • Recursive geometric matching. A bottom-up alternative pairs the sinks by a minimum matching, joins each pair at a balance point, and repeats on the merged points.

When to use it

Use it to get a balanced topology quickly for an irregular placement of sinks, especially as the first step of an exact zero-skew router. Use it on its own only when an approximately balanced tree is enough. For sinks on a regular array, the H-tree is the same tree with no computation. When the skew must be zero, embed the topology with deferred-merge embedding.

Pitfalls

  • MMM does not give zero skew, even under linear delay, except on special inputs such as a full grid. A claim of zero skew for general sinks is false.
  • The centre of mass of a half can be far from all of its sinks when they are spread out, which gives long wires and large skew, as in the example.
  • The tie break matters when many sinks share a coordinate. Without the second key and the index, a split can put equal points on both sides in an arbitrary way.
  • The length of a path ignores the loads. Two paths of equal length can have very different Elmore delays.

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.

method_of_means_and_medians.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/method-of-means-and-medians/. The authors are listed in prov/JBVF6M.jsonl.
"""Method of means and medians (MMM) for clock routing.

Sinks are points (x, y). The sinks are split at the median, alternately by x
and by y, and the centre of mass of each set is joined by a rectilinear wire
to the centres of mass of its two halves. Two lists, sorted once by (x, y, i)
and by (y, x, i), are split in linear time at each level, so the whole run
takes O(n log n) time. Coordinates are exact Fractions.
"""

from fractions import Fraction


class Node:
    def __init__(self, pt, sinks, kids=(), axis=None):
        self.pt = pt  # centre of mass of the sinks below
        self.sinks = sinks  # sink indices below, in the order of the split axis
        self.kids = list(kids)
        self.axis = axis  # 0 for a split by x, 1 for a split by y


def centre(points, idx):
    k = len(idx)
    return (sum(Fraction(points[i][0]) for i in idx) / k, sum(Fraction(points[i][1]) for i in idx) / k)


def key(points, i, axis):
    p = points[i]
    return (p[axis], p[1 - axis], i)


def split(points, by_x, by_y, axis):
    """Return the two halves (as pairs of sorted lists) of a split on axis."""
    first = by_x if axis == 0 else by_y
    h = len(first) // 2  # @line L3
    low = set(first[:h])  # @line L4
    lx = [i for i in by_x if i in low]
    ly = [i for i in by_y if i in low]
    hx = [i for i in by_x if i not in low]
    hy = [i for i in by_y if i not in low]
    return (lx, ly), (hx, hy)


def build(points, by_x, by_y, axis):
    idx = by_x if axis == 0 else by_y
    c = centre(points, idx)  # @line L1
    if len(idx) == 1:  # @line L2
        return Node(c, list(idx))
    (lx, ly), (hx, hy) = split(points, by_x, by_y, axis)
    left = build(points, lx, ly, 1 - axis)  # @line L5
    right = build(points, hx, hy, 1 - axis)
    return Node(c, list(idx), [left, right], axis)  # @line L6


def mmm(points):
    """Return the root of the MMM tree. The first split is by x."""
    n = len(points)
    by_x = sorted(range(n), key=lambda i: key(points, i, 0))
    by_y = sorted(range(n), key=lambda i: key(points, i, 1))
    return build(points, by_x, by_y, 0)  # @line L7


def l1(p, q):
    return abs(p[0] - q[0]) + abs(p[1] - q[1])


def path_lengths(root):
    """Wire length from the root to each sink, as a dict."""
    out = {}

    def walk(v, acc):
        if not v.kids:
            out[v.sinks[0]] = acc
        for k in v.kids:
            walk(k, acc + l1(v.pt, k.pt))

    walk(root, Fraction(0))
    return out


def wirelength(root):
    return sum(l1(root.pt, k.pt) + wirelength(k) for k in root.kids)


def depth(root):
    return 0 if not root.kids else 1 + max(depth(k) for k in root.kids)
test_method_of_means_and_medians.py 93 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/method-of-means-and-medians/. The authors are listed in prov/JBVF6M.jsonl.

import random
from fractions import Fraction

from method_of_means_and_medians import depth, l1, mmm, path_lengths, wirelength


def naive(points, idx, axis):
    """Reference: sort the set afresh at each level and split it in two."""
    idx = sorted(idx, key=lambda i: (points[i][axis], points[i][1 - axis], i))
    k = len(idx)
    c = (sum(Fraction(points[i][0]) for i in idx) / k, sum(Fraction(points[i][1]) for i in idx) / k)
    if k == 1:
        return (c, idx[0])
    h = k // 2
    return (c, naive(points, idx[:h], 1 - axis), naive(points, idx[h:], 1 - axis))


def as_tuple(v):
    if not v.kids:
        return (v.pt, v.sinks[0])
    return (v.pt, as_tuple(v.kids[0]), as_tuple(v.kids[1]))


def check_splits(points, v):
    """Brute force: every sink of the low half is at most every sink of the
    high half in the split order, the halves have sizes floor and ceil, and
    the point of each node is the centre of mass of its sinks."""
    k = len(v.sinks)
    assert v.pt == (sum(Fraction(points[i][0]) for i in v.sinks) / k, sum(Fraction(points[i][1]) for i in v.sinks) / k)
    if not v.kids:
        assert k == 1
        return
    lo, hi = v.kids
    assert sorted(lo.sinks + hi.sinks) == sorted(v.sinks)
    assert (len(lo.sinks), len(hi.sinks)) == (k // 2, k - k // 2)
    a = v.axis
    for i in lo.sinks:
        for j in hi.sinks:
            assert (points[i][a], points[i][1 - a], i) < (points[j][a], points[j][1 - a], j)
    for kid in v.kids:
        assert kid.axis is None or kid.axis == 1 - a
        check_splits(points, kid)


def test_against_reference_and_brute_force(rng=random.Random(11)):
    for _ in range(300):
        n = rng.randint(1, 40)
        points = [(rng.randint(0, 6), rng.randint(0, 6)) for _ in range(n)]
        root = mmm(points)
        assert as_tuple(root) == naive(points, list(range(n)), 0)
        check_splits(points, root)
        assert sorted(path_lengths(root)) == list(range(n))


def test_depth_bound():
    rng = random.Random(5)
    for n in range(1, 300):
        points = [(rng.randint(0, 50), rng.randint(0, 50)) for _ in range(n)]
        assert depth(mmm(points)) == (n - 1).bit_length()  # the ceiling of log2 n


def test_grid_gives_h_tree():
    # 4^k sinks at the centres of the cells of a 2^k by 2^k grid on a square of
    # side D: every path has length D (1 - 2^-k), and the total wire is
    # 1.5 D (2^k - 1), the values of the H-tree
    for k in range(0, 4):
        m = 2 ** k
        D = 2 * m
        points = [(2 * i + 1, 2 * j + 1) for i in range(m) for j in range(m)]
        root = mmm(points)
        lengths = set(path_lengths(root).values())
        assert lengths == {Fraction(D) * (1 - Fraction(1, m))}
        assert wirelength(root) == Fraction(3, 2) * D * (m - 1)


def test_skew_not_zero_in_general():
    points = [(0, 6), (0, 7), (2, 3), (8, 6)]
    root = mmm(points)
    assert root.pt == (Fraction(5, 2), Fraction(11, 2))
    assert [k.pt for k in root.kids] == [(0, Fraction(13, 2)), (5, Fraction(9, 2))]
    assert path_lengths(root) == {0: 4, 1: 4, 2: 8, 3: 8}
    assert wirelength(root) == 17
    # every edge is exactly the L1 distance of its ends
    assert l1(root.pt, root.kids[1].pt) == Fraction(7, 2)


def test_four_corner_example():
    root = mmm([(-1, -1), (-1, 1), (1, -1), (1, 1)])
    assert set(path_lengths(root).values()) == {2}
    assert wirelength(root) == 6

History

Jackson, Srinivasan and Kuh introduced the method of means and medians at the Design Automation Conference in 1990, to route clock nets in high-performance chips whose sinks are not on a regular grid, where the H-tree of earlier designs does not fit. The following methods kept its recursive topology but replaced the centres of mass with exactly balanced points: Tsay's exact zero skew in 1991, and deferred-merge embedding in 1992.

References

  1. Mike A. B. Jackson, Arvind Srinivasan and Ernest S. Kuh, Clock routing for high-performance ICs, Proceedings of the 27th Design Automation Conference, 573 to 579, 1990, the method of means and medians, the recursive median split in alternating directions and the connection of the centres of mass
  2. Andrew B. Kahng, Jens Lienig, Igor L. Markov and Jin Hu, VLSI Physical Design, From Graph Partitioning to Timing Closure, Springer, 2011, Chapter 7, Specialized Routing, Section 7.5.1, Constructing Trees with Zero Global Skew (method of means and medians)

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 proofH2 full proof
  • correctness: no review record reviews/JBVF6M/proof-correctness.yaml
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