Algorithm Search⌘K

Data structurecore

B*-tree floorplan representation

Also called B*-tree floorplan.

Chang and coauthors' ordered binary tree for compacted packings in which a left child is the block to the right and a right child the block above.

Time
O(n) worst · average · best
Space
O(n) extra
Where
n = the number of blocks
Properties
deterministiciterative
Origin
Yun Chih Chang, Yao Wen Chang, Guang Ming Wu, Shu Wei Wu, 2000

A B*-tree is an ordered binary tree whose nodes are the blocks of a floorplan. The root is the block at the lower-left corner. The left child of a block bb is placed just to the right of bb, and the right child of bb is placed above bb at the same xx. Every block then drops down until it rests on the floor or on a block below it. Chang, Chang, Wu and Wu introduced it in 2000 as a binary form of the O-tree. A contour of the placed blocks gives the packing in O(n)O(n) time. Every packing that is compact to the left and down has a B*-tree, so a search over trees, such as an annealing, can reach a packing of least area, slicing or not.

In plain words

Put the first block in the lower-left corner. For each block, you can name one block that goes directly to its right and one block that goes directly above it, starting at its left side. These choices form a tree.

To build the picture, visit the tree from the root, always the right-hand block first and then the block above. When you visit a block, you already know where its left side is. Slide it down from the top until it lands on the floor or on a block. Keep a record of the skyline of the blocks so far, so that you can see at once how high a block lands.

The abstract type

The type stores a B*-tree on a set of nn blocks. The operations are:

  • PACK(w,h)(w, h): given the width wbw_b and the height hbh_b of each block, return the lower-left corner (xb,yb)(x_b, y_b) of each block and the width WW and the height HH of the packing.
  • ROTATE(b)(b): exchange wbw_b and hbh_b.
  • SWAP(a,b)(a, b): exchange the places of two blocks in the tree.
  • MOVE(b,p,side)(b, p, \text{side}): delete bb and insert it again as the left or the right child of pp.

These are the three perturbations of Chang and coauthors. Each tree is a legal floorplan, so every move gives a packing without overlap.

Representation

Each node has a left child, a right child and, for the moves, a parent. The packing rules are:

  • the root has x=0x = 0;
  • the left child cc of bb has xc=xb+wbx_c = x_b + w_b, so cc is to the right of bb and touches it;
  • the right child cc of bb has xc=xbx_c = x_b, so cc is above bb with the same left side.

The blocks are placed in preorder, so the parent of a block is placed before it. The yy of a block is the highest top of the blocks already placed whose xx-ranges meet its own. The contour stores these tops: it is a doubly linked list of horizontal segments that covers [0,∞)[0, \infty), the same picture as the output of the skyline problem. Each block keeps a pointer to its own segment of the contour. Its right child starts the walk at this segment, and its left child at the next one.

Operations

  1. PACK(T, w, h)
  2. 1contour ← one segment [0, ∞) at height 0
  3. 2stack ← (root, the first segment of the contour)
  4. 3while the stack is not empty do pop (b, s) ▷ s starts at x_b
  5. 4x_b ← the left end of s; e ← x_b + w_b
  6. 5y_b ← the largest height of the segments from s on that start before e
  7. 6replace those segments by [x_b, e) at height y_b + h_b, and keep the part of the last one after e
  8. 7record (x_b, y_b); W ← max(W, e); H ← max(H, y_b + h_b)
  9. 8if b has a right child c then push (c, s)
  10. 9if b has a left child c then push (c, the segment after s)
  11. 10return x, y, W, H

The left child is pushed last, so it is popped next, and preorder is kept. Line L9 gives the left child the segment that starts at xb+wbx_b + w_b, which is where the left child goes. Line L8 gives the right child the segment of bb itself, which starts at xbx_b. The blocks of the left subtree of bb are placed in between, but all of them are to the right of xb+wbx_b + w_b, so they do not change the segment of bb.

ROTATE changes only the sizes. SWAP exchanges two labels. MOVE deletes a node: a node with at most one child is replaced by that child, and a node with two children is first swapped down along its left children until it has one child. Then it inserts the node at a free or used child place of pp, and the old child of that place becomes a child of the new node on the same side.

Example

Take five blocks: A is 3×23 \times 2, B is 2×32 \times 3, C is 2×12 \times 1, D is 2×22 \times 2 and E is 3×13 \times 1 (width by height). The tree has the root A, with B as the left child of A, C as the left child of B, D as the right child of A, and E as the left child of D. The preorder is A, B, C, D, E.

block rule xx segments walked yy contour after the block
A root 0 [0,∞)[0, \infty) at 0 0 [0,3)[0,3):2, [3,∞)[3,\infty):0
B left of A 3 [3,∞)[3, \infty) at 0 0 [0,3)[0,3):2, [3,5)[3,5):3, [5,∞)[5,\infty):0
C left of B 5 [5,∞)[5, \infty) at 0 0 [0,3)[0,3):2, [3,5)[3,5):3, [5,7)[5,7):1, [7,∞)[7,\infty):0
D right of A 0 [0,3)[0, 3) at 2 2 [0,2)[0,2):4, [2,3)[2,3):2, [3,5)[3,5):3, [5,7)[5,7):1, [7,∞)[7,\infty):0
E left of D 2 [2,3)[2,3) at 2, [3,5)[3,5) at 3 3 [0,2)[0,2):4, [2,5)[2,5):4, [5,7)[5,7):1, [7,∞)[7,\infty):0

The packing is 7×47 \times 4, area 28, for a block area of 6+6+2+4+3=216 + 6 + 2 + 4 + 3 = 21. Block E is the left child of D, so its left side is at the right side of D, x=2x = 2. It lands on B, not on A, because B is higher. Below E, over [2,3)[2, 3), there is a gap of height 1 above A. Block D starts its walk at the segment of A, which the blocks B and C did not change.

Correctness

The parent of each block is placed first, so each xx is known when it is needed. The contour list stays a correct skyline: a block replaces the segments under its xx-range by one segment at its top, which is not lower than the old heights there. The walk of a block starts at the segment that begins at its left side, because a left child is popped right after its parent and a right child starts at the segment of its parent, which the left subtree does not touch. So each yy is the highest top under the block, the same value as a direct search over all placed blocks. Any two blocks either have disjoint xx-ranges or the later one is above the earlier one, so there is no overlap. Every block rests on the floor or on a block, so the packing is compact downward. The full proof is in the correctness proof.

Two things are not true, and the tests check both. The packing need not be compact to the left: with three unit squares, the root A, its left child B and the right child C of B, block C is at (1,1)(1, 1), but (0,1)(0, 1) is free. And two trees can give the same packing: with the root A, the right child D of A and the left child E of D, the squares are at A=(0,0)A = (0, 0), D=(0,1)D = (0, 1), E=(1,0)E = (1, 0), which is also the packing of the tree with E as the left child and D as the right child of A. What Chang and coauthors prove is the other direction: each placement that is compact to the left and down (an admissible placement) is the packing of at least one B*-tree. Its left child is the lowest block that touches its right side, and its right child is the lowest block above it with the same xx. This is cited, and the tests check its consequence for up to four blocks: the least area over all trees equals the least area of any packing.

Proof: The contour packing of a B*-tree is the naive packing, has no overlap, is compact downward and takes linear timefull

We use the pseudocode of the page. A B*-tree is an ordered binary tree on the nn blocks. The rules are: the root has x=0x = 0; if cc is the left child of bb then xc=xb+wbx_c = x_b + w_b; if cc is the right child of bb then xc=xbx_c = x_b. The blocks are placed in preorder, and each block gets

yb=max⁡({0}∪{ ya+ha:a placed before b, xa<xb+wb, xb<xa+wa }),y_b = \max\bigl(\{0\} \cup \{\, y_a + h_a : a \text{ placed before } b,\ x_a < x_b + w_b,\ x_b < x_a + w_a \,\}\bigr),

the height of the highest earlier block whose xx-range meets the xx-range of bb in an interval of positive length. This is the naive packing of the tests. The proof shows that lines L1 to L10 compute it.

Lemma 1 (the x values are defined). In preorder, the parent of a block comes before the block, so xbx_b is known when bb is placed. Every block of the left subtree of pp has x≥xp+wpx \ge x_p + w_p, and every block of the subtree of pp has x≥xpx \ge x_p.

Proof. The first claim is the definition of preorder. For the second, induct on the depth below pp: the left child of pp has x=xp+wpx = x_p + w_p, and any child cc of a block dd has xc≥xdx_c \ge x_d because widths are positive. □\square

Lemma 2 (the contour). Call a list of segments [x0,x1)[x_0, x_1) with a height top\mathit{top} a contour if the segments are in increasing order, the first starts at 0, each starts where the one before it ends, the last ends at ∞\infty, and for each point t≥0t \ge 0 the height of the segment that contains tt is max⁡({0}∪{ya+ha:a placed,xa≤t<xa+wa})\max(\{0\} \cup \{y_a + h_a : a \text{ placed}, x_a \le t < x_a + w_a\}). Before each pop of line L3 the list from the head is a contour.

Proof. Line L1 makes one segment [0,∞)[0, \infty) at height 0, which is a contour of no blocks. Assume the list is a contour, and that a block bb is popped with a segment ss in the list with s.x0=xbs.x_0 = x_b (Lemma 3). The walk visits ss and the segments after it while they start before e=xb+wbe = x_b + w_b. These are exactly the segments that meet [xb,e)[x_b, e). Line L6 sets ss to [xb,e)[x_b, e) at height yb+hby_b + h_b, keeps the part [e,⋅)[e, \cdot) of the last segment visited if that segment goes past ee, and links ss to the first segment that starts at ee or later. The heights outside [xb,e)[x_b, e) do not change, and inside it the new height is yb+hby_b + h_b. This is at least the old height there, because yby_b is the largest old height on [xb,e)[x_b, e) (Lemma 4). So the new list is the contour of the placed blocks with bb. □\square

Lemma 3 (the start segment). When a block bb is popped with a segment ss, the segment ss is in the list and s.x0=xbs.x_0 = x_b.

Proof. For the root, ss is the head with x0=0x_0 = 0. Let bb be the left child of pp. It was pushed last, right after pp was placed, so it is popped next. At that time ss is the segment after the segment of pp, and it starts at the end xp+wp=xbx_p + w_p = x_b of the segment of pp. Let bb be the right child of pp, pushed with the segment sps_p of pp, with sp.x0=xp=xbs_p.x_0 = x_p = x_b. Between the placement of pp and the pop of bb, only the blocks of the left subtree of pp are placed, since the stack is a preorder stack. The placement of a block cc changes the fields only of its own start segment, whose x0=xcx_0 = x_c, and it unlinks only segments that start strictly between xcx_c and xc+wcx_c + w_c. By Lemma 1, xc≥xp+wp>xpx_c \ge x_p + w_p > x_p. So sps_p starts before xcx_c: it is not the start segment of cc and it is not unlinked. It is not changed and it stays in the list. □\square

Lemma 4 (the y value). Line L5 and the walk set yby_b to the value of the naive packing.

Proof. By Lemma 3 the walk starts at the segment that contains xbx_b, and it visits the segments that meet [xb,xb+wb)[x_b, x_b + w_b). By Lemma 2 the largest height among them is the largest ya+hay_a + h_a over the placed blocks aa whose xx-range meets [xb,xb+wb)[x_b, x_b + w_b), or 0. Two half-open intervals meet if and only if xa<xb+wbx_a < x_b + w_b and xb<xa+wax_b < x_a + w_a. This is the formula of the naive packing. □\square

Theorem 1 (no overlap and down-compaction). In the packing, no two blocks overlap. Each block lies on the floor (yb=0y_b = 0) or touches from above a block whose xx-range meets its own in an interval of positive length, so no block can move down. The returned WW and HH are the width and the height of the bounding box.

Proof. Let aa be placed before bb. If their xx-ranges do not meet, the two blocks are separated by a vertical line. If they meet, then yb≥ya+hay_b \ge y_a + h_a by Lemma 4, and the blocks are separated by a horizontal line. If yb>0y_b > 0, then yby_b is the top ya+hay_a + h_a of a block aa with a meeting xx-range, and bb rests on it. Line L7 and the next line keep the largest right side and the largest top. □\square

Not claimed. The packing need not be compact to the left. Take three unit squares, the root AA, its left child BB and the right child CC of BB. Then A=(0,0)A = (0, 0), B=(1,0)B = (1, 0) and C=(1,1)C = (1, 1), and CC can move left to (0,1)(0, 1). The map from trees to packings is not one to one: the tree with root AA, right child DD of AA and left child EE of DD gives A=(0,0)A = (0, 0), D=(0,1)D = (0, 1), E=(1,0)E = (1, 0), and so does the tree with root AA, left child EE and right child DD. The tests check both examples.

Cited theorem (every admissible placement has a B-tree).* Call a placement admissible if no block can move left or down. Chang, Chang, Wu and Wu (DAC 2000, the section on the B*-tree representation) show that for each admissible placement there is a unique B*-tree, built by a depth-first search from the block at the lower-left corner: the left child of bb is the lowest block that touches the right side of bb with x=xb+wbx = x_b + w_b, and the right child is the lowest block above bb with the same xx. Any placement without overlap becomes admissible when the blocks are moved left and down in turn, and these moves do not make the bounding box larger, so some B*-tree gives a packing of least area. The tests check this consequence for n≤4n \le 4: the least area over all n!⋅Cnn! \cdot C_n trees equals the least area found by a search over all positions.

Complexity. Each pop of line L3 does O(1)O(1) work plus one step for each segment that the walk visits. Every visited segment other than the start segment is unlinked, or is the last segment, which is replaced by the new segment [e,⋅)[e, \cdot). Each placement makes at most one new segment, so at most n+1n + 1 segments are ever made and at most n+1n + 1 are ever unlinked or replaced. The total number of steps of all walks is at most n+(n+1)n + (n + 1), and PACK takes O(n)O(n) time and O(n)O(n) space. The naive packing compares each block with all the blocks before it, Θ(n2)\Theta(n^2) time. SWAP renames two nodes, and DELETE and INSERT change O(1)O(1) links once the node and its parent are known; DELETE of a node with two children first swaps it down a path, O(h)O(h) steps for a tree of height hh. ■\blacksquare

Complexity

operation time extra space
PACK with the contour O(n)O(n) O(n)O(n)
PACK by a direct search over the placed blocks Θ(n2)\Theta(n^2) O(n)O(n)
ROTATE, SWAP O(1)O(1) none
MOVE O(1)O(1) to relink, plus the swaps down a path for a node with two children none

PACK is linear because each segment that a walk passes, except the first, is removed from the contour or cut at the end of the block. Each block makes at most one new segment, so at most n+1n + 1 segments are made and removed in total, and all walks together take O(n)O(n) steps. This is an amortized bound: one block can walk over many segments.

There are CnC_n binary trees with nn nodes, where CnC_n is the nnth Catalan number, and n!n! ways to put the blocks on the nodes. So there are n!⋅Cn=(2n)!/(n+1)!n! \cdot C_n = (2n)!/(n+1)! B*-trees, which is less than the (n!)2(n!)^2 of a sequence pair for n≥3n \ge 3. For n=4n = 4 there are 24⋅14=33624 \cdot 14 = 336 trees, against 576 sequence pairs.

Variants

  • The O-tree. The O-tree of Guo, Cheng and Yoshimura stores the same packings with an ordered tree. The left-child right-sibling form of an O-tree is a B*-tree.
  • Fixed outline. Chen and Chang's floorplanner of 2006 searches over B*-trees with a three-stage annealing for a packing inside a fixed outline, and also handles buses between blocks.
  • Symmetry and analog layout. Trees in which a symmetric group of blocks forms one island are used for analog placement.
  • Hierarchical B-trees.* A node can stand for a cluster of blocks with its own tree.
  • Soft blocks. A search can change the shape of a soft block between packings; the tree does not change.

When to use it

Use a B*-tree in a search for compact packings of hard blocks, such as macros, when the packing is evaluated very many times. The packing takes linear time, the moves are simple, and there is less redundancy than in a sequence pair. If the floorplan must be slicing, use a normalized Polish expression, which also allows exact sizing of soft blocks. If the relations of every pair must be read in O(1)O(1) time, for example for constraints between blocks, a sequence pair is simpler.

Pitfalls

  • Swapping the meaning of the children. In the B*-tree the left child is to the right of its parent, and the right child is above. Some texts draw it the other way. Use one convention in PACK and in the moves.
  • Starting every walk at the head. If each block walks the contour from x=0x = 0, PACK takes quadratic time. Start at the segment of the parent, or at the one after it.
  • The order of the pushes. Push the right child first and the left child last, so that the left child is popped next and its segment is still the one after the segment of the parent.
  • Counting packings by trees. Different trees can give the same packing, as in the example above, so n!⋅Cnn! \cdot C_n is not the number of distinct packings.
  • Expecting a left-compact packing. A block can have free space to its left, because its xx is fixed by its parent. A compaction step after the packing removes it, but then the tree of the result is a different tree.

Implementations

The Python class stores the tree as two maps, left and right, and implements PACK with the linked contour in preorder, a direct quadratic packing for the tests, SWAP, DELETE and INSERT. SWAP renames the keys of the maps, in O(n)O(n) time; with parent pointers it takes O(1)O(1) time. Rotation changes the size maps. The tests pack all 336336 trees of four blocks, and all smaller trees, with random sizes, and check that the contour and the direct packing agree, that there is no overlap, that every block rests on the floor or on a block, and that the child rules hold. For three and four blocks they check that the best area over all trees equals the best area of a search over all positions. They also run random moves on trees of up to 30 blocks.

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.

b_star_tree_floorplan.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/b-star-tree-floorplan/. The authors are listed in prov/WA1GJ6.jsonl.

"""The B*-tree of Chang, Chang, Wu and Wu (2000) for compacted packings.

The root is at the lower-left corner. The left child of a block b is placed
just to the right of b (x = x_b + w_b), and the right child of b is placed
above b with the same x (x = x_b). Each block is dropped onto the contour of
the blocks placed before it, in preorder. The contour is a linked list of
segments; each block keeps a pointer to its own segment, from which its
children start their walk, so a full packing takes amortized O(n) time.
"""

from typing import Optional

INF = float("inf")


class _Seg:
    """A piece [x0, x1) of the contour at height top."""

    __slots__ = ("x0", "x1", "top", "next")

    def __init__(self, x0: int, x1: float, top: int, nxt: Optional["_Seg"]) -> None:
        self.x0, self.x1, self.top, self.next = x0, x1, top, nxt


class BStarTree:
    """An ordered binary tree on the blocks: left[b] is to the right of b, right[b] is above b."""

    def __init__(self, root: Optional[int], left: dict[int, Optional[int]], right: dict[int, Optional[int]]) -> None:
        self.root = root
        self.left = dict(left)
        self.right = dict(right)

    def blocks(self) -> list[int]:
        """Return the blocks in preorder."""
        out = []
        stack = [self.root] if self.root is not None else []
        while stack:
            b = stack.pop()
            out.append(b)
            if self.right.get(b) is not None:
                stack.append(self.right[b])
            if self.left.get(b) is not None:
                stack.append(self.left[b])
        return out

    def check_invariant(self) -> None:
        """Raise AssertionError unless every block has one parent and the tree is connected."""
        seen = self.blocks()
        assert len(seen) == len(set(seen))
        kids = [c for d in (self.left, self.right) for c in d.values() if c is not None]
        assert len(kids) == len(set(kids)) and self.root not in kids
        assert set(seen) == set(kids) | ({self.root} if self.root is not None else set())

    def pack(self, w: dict[int, int], h: dict[int, int]) -> tuple[int, int, dict[int, tuple[int, int]]]:
        """Return (W, H, pos) of the packing, with the contour. Amortized O(n) time."""
        head = _Seg(0, INF, 0, None)  # @line L1
        seg: dict[int, _Seg] = {}
        pos: dict[int, tuple[int, int]] = {}
        width = height = 0
        if self.root is None:
            return 0, 0, pos
        stack: list[tuple[int, _Seg]] = [(self.root, head)]  # @line L2
        while stack:  # @line L3
            b, start = stack.pop()
            x = start.x0  # @line L4
            end = x + w[b]
            y = 0  # @line L5
            s: Optional[_Seg] = start
            last = start
            while s is not None and s.x0 < end:
                if s.top > y:
                    y = s.top
                last = s
                s = s.next
            rest = _Seg(end, last.x1, last.top, last.next) if last.x1 > end else last.next  # @line L6
            start.x1, start.top, start.next = end, y + h[b], rest
            seg[b] = start
            pos[b] = (x, y)  # @line L7
            width, height = max(width, end), max(height, y + h[b])
            if self.right.get(b) is not None:  # @line L8
                stack.append((self.right[b], start))
            if self.left.get(b) is not None:  # @line L9
                stack.append((self.left[b], start.next))
        return width, height, pos  # @line L10

    def pack_naive(self, w: dict[int, int], h: dict[int, int]) -> tuple[int, int, dict[int, tuple[int, int]]]:
        """The same packing without a contour: each y is the highest top over the x-range. O(n^2)."""
        pos: dict[int, tuple[int, int]] = {}
        if self.root is None:
            return 0, 0, pos
        xs = {self.root: 0}
        for b in self.blocks():
            x = xs[b]
            y = 0
            for a, (xa, ya) in pos.items():
                if xa < x + w[b] and x < xa + w[a]:
                    y = max(y, ya + h[a])
            pos[b] = (x, y)
            if self.left.get(b) is not None:
                xs[self.left[b]] = x + w[b]
            if self.right.get(b) is not None:
                xs[self.right[b]] = x
        return max(x + w[b] for b, (x, _) in pos.items()), max(y + h[b] for b, (_, y) in pos.items()), pos

    def swap(self, a: int, b: int) -> None:
        """Exchange the places of blocks a and b in the tree.

        This version renames the keys of the two maps, in O(n) time. With parent
        pointers in the nodes the same swap takes O(1) time.
        """
        ren = {a: b, b: a}
        f = lambda v: ren.get(v, v) if v is not None else None  # noqa: E731
        self.root = f(self.root)
        self.left = {f(k): f(v) for k, v in self.left.items()}
        self.right = {f(k): f(v) for k, v in self.right.items()}

    def _parent(self, b: int) -> tuple[Optional[int], Optional[str]]:
        for side, d in (("left", self.left), ("right", self.right)):
            for k, v in d.items():
                if v == b:
                    return k, side
        return None, None

    def delete(self, b: int) -> None:
        """Remove block b. A node with two children is first swapped down along left children."""
        while self.left.get(b) is not None and self.right.get(b) is not None:
            self.swap(b, self.left[b])
        child = self.left.get(b) if self.left.get(b) is not None else self.right.get(b)
        p, side = self._parent(b)
        if p is None:
            self.root = child
        else:
            (self.left if side == "left" else self.right)[p] = child
        self.left.pop(b, None)
        self.right.pop(b, None)

    def insert(self, b: int, p: Optional[int], side: str) -> None:
        """Make b the child of p on the given side; the old child moves under b on the same side."""
        self.left[b] = None
        self.right[b] = None
        if p is None:
            old, self.root = self.root, b
            self.left[b] = old
            return
        d = self.left if side == "left" else self.right
        old = d.get(p)
        d[p] = b
        (self.left if side == "left" else self.right)[b] = old
test_b_star_tree_floorplan.py 191 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/b-star-tree-floorplan/. The authors are listed in prov/WA1GJ6.jsonl.

import itertools
import random

from b_star_tree_floorplan import BStarTree


def overlap(a, b) -> bool:
    return a[0] < b[2] and b[0] < a[2] and a[1] < b[3] and b[1] < a[3]


def shapes(n: int):
    """All binary tree shapes with n nodes, as nested (left, right) tuples; None is empty."""
    if n == 0:
        return [None]
    out = []
    for k in range(n):
        for a in shapes(k):
            for b in shapes(n - 1 - k):
                out.append((a, b))
    return out


def label(shape, names):
    """Turn a shape into a BStarTree, naming the nodes in preorder by names."""
    left, right = {}, {}
    it = iter(names)

    def rec(s):
        if s is None:
            return None
        b = next(it)
        left[b] = rec(s[0])
        right[b] = rec(s[1])
        return b

    root = rec(shape)
    return BStarTree(root, left, right)


def all_trees(n: int):
    for s in shapes(n):
        for p in itertools.permutations(range(n)):
            yield label(s, p)


def random_tree(n: int, rng: random.Random) -> BStarTree:
    t = BStarTree(None, {}, {})
    order = list(range(n))
    rng.shuffle(order)
    placed = []
    for b in order:
        if not placed:
            t.insert(b, None, "left")
        else:
            t.insert(b, rng.choice(placed), rng.choice(["left", "right"]))
        placed.append(b)
    return t


def best_packing_area(w: dict, h: dict) -> int:
    """Least bounding-box area of a packing, by brute force over positions (sums of other sizes)."""
    blocks = list(w)

    def sums(vals):
        s = {0}
        for v in vals:
            s |= {t + v for t in s}
        return sorted(s)

    cand = {b: [(px, py) for px in sums([w[c] for c in blocks if c != b]) for py in sums([h[c] for c in blocks if c != b])] for b in blocks}
    best = [sum(w.values()) * max(h.values())]
    placed: list = []

    def rec(k: int, wid: int, hei: int) -> None:
        if wid * hei >= best[0]:
            return
        if k == len(blocks):
            best[0] = wid * hei
            return
        b = blocks[k]
        for px, py in cand[b]:
            r = (px, py, px + w[b], py + h[b])
            if any(overlap(r, q) for q in placed):
                continue
            placed.append(r)
            rec(k + 1, max(wid, r[2]), max(hei, r[3]))
            placed.pop()

    rec(0, 0, 0)
    return best[0]


def check_packing(t: BStarTree, w: dict, h: dict) -> None:
    res = t.pack(w, h)
    assert res == t.pack_naive(w, h)
    width, height, pos = res
    r = {b: (x, y, x + w[b], y + h[b]) for b, (x, y) in pos.items()}
    for a, b in itertools.combinations(r, 2):
        assert not overlap(r[a], r[b])
    for b, (x, y) in pos.items():
        # down-compact: on the floor or resting on a block below it
        assert y == 0 or any(q[3] == y and q[0] < r[b][2] and r[b][0] < q[2] for a, q in r.items() if a != b)
        if t.left.get(b) is not None:
            assert pos[t.left[b]][0] == x + w[b]
        if t.right.get(b) is not None:
            assert pos[t.right[b]][0] == x
    assert width == max(q[2] for q in r.values()) and height == max(q[3] for q in r.values())


def test_example() -> None:
    # root 0; 0.left = 1, 1.left = 2, 0.right = 3, 3.left = 4
    t = BStarTree(0, {0: 1, 1: 2, 2: None, 3: 4, 4: None}, {0: 3, 1: None, 2: None, 3: None, 4: None})
    w = {0: 3, 1: 2, 2: 2, 3: 2, 4: 3}
    h = {0: 2, 1: 3, 2: 1, 3: 2, 4: 1}
    width, height, pos = t.pack(w, h)
    assert pos == {0: (0, 0), 1: (3, 0), 2: (5, 0), 3: (0, 2), 4: (2, 3)}
    assert (width, height) == (7, 4)
    assert t.blocks() == [0, 1, 2, 3, 4]
    check_packing(t, w, h)


def test_not_left_compact_and_not_injective() -> None:
    one = {0: 1, 1: 1, 2: 1}
    # 0.left = 1, 1.right = 2: block 2 sits at (1, 1) although (0, 1) is free
    t = BStarTree(0, {0: 1, 1: None, 2: None}, {0: None, 1: 2, 2: None})
    assert t.pack(one, one)[2] == {0: (0, 0), 1: (1, 0), 2: (1, 1)}
    # two different trees, one packing
    t1 = BStarTree(0, {0: None, 1: 2, 2: None}, {0: 1, 1: None, 2: None})
    t2 = BStarTree(0, {0: 2, 1: None, 2: None}, {0: 1, 1: None, 2: None})
    assert t1.pack(one, one)[2] == t2.pack(one, one)[2] == {0: (0, 0), 1: (0, 1), 2: (1, 0)}


def test_all_small_trees() -> None:
    rng = random.Random(21)
    counts = [len(shapes(n)) for n in range(7)]
    assert counts == [1, 1, 2, 5, 14, 42, 132]
    for n in range(1, 5):
        trees = list(all_trees(n))
        assert len(trees) == counts[n] * [1, 1, 2, 6, 24][n]
        for _ in range(6):
            w = {b: rng.randint(1, 4) for b in range(n)}
            h = {b: rng.randint(1, 4) for b in range(n)}
            for t in trees:
                t.check_invariant()
                check_packing(t, w, h)


def test_best_tree_is_best_packing() -> None:
    rng = random.Random(22)
    for trial in range(30):
        n = 3 if trial < 18 else 4
        w = {b: rng.randint(1, 5 if n == 3 else 3) for b in range(n)}
        h = {b: rng.randint(1, 5 if n == 3 else 3) for b in range(n)}
        best = min(wd * ht for wd, ht, _ in (t.pack(w, h) for t in all_trees(n)))
        assert best == best_packing_area(w, h)


def test_random_trees_and_moves() -> None:
    rng = random.Random(23)
    for _ in range(300):
        n = rng.randint(1, 30)
        t = random_tree(n, rng)
        t.check_invariant()
        w = {b: rng.randint(1, 9) for b in range(n)}
        h = {b: rng.randint(1, 9) for b in range(n)}
        check_packing(t, w, h)
        for _ in range(5):
            op = rng.randrange(3)
            if op == 0 and n >= 2:
                a, b = rng.sample(range(n), 2)
                t.swap(a, b)
            elif op == 1:
                b = rng.randrange(n)
                w[b], h[b] = h[b], w[b]  # rotate block b
            elif n >= 2:
                b = rng.randrange(n)
                t.delete(b)
                t.check_invariant()
                assert sorted(t.blocks()) == sorted(set(range(n)) - {b})
                p = rng.choice(t.blocks())
                t.insert(b, p, rng.choice(["left", "right"]))
            t.check_invariant()
            assert sorted(t.blocks()) == list(range(n))
            check_packing(t, w, h)


def test_empty() -> None:
    assert BStarTree(None, {}, {}).pack({}, {}) == (0, 0, {})

History

Guo, Cheng and Yoshimura introduced the O-tree and admissible placements at DAC 1999. Chang, Chang, Wu and Wu gave the B*-tree at DAC 2000. It is a binary tree, so the moves need no balance of parentheses, and the packing with a contour takes amortized linear time. Chen and Chang used B*-trees with a fast annealing for fixed-outline and bus-driven floorplanning in 2006, and B*-trees became a common representation in floorplanners and in analog placement.

References

  1. Yun-Chih Chang, Yao-Wen Chang, Guang-Ming Wu and Shu-Wei Wu, B*-trees, a new representation for non-slicing floorplans, Proceedings of the 37th Design Automation Conference, 458 to 463, 2000, the definition of the B*-tree, the construction of the tree of an admissible placement, the contour packing in amortized linear time, and the three perturbations of the annealing
  2. Pei-Ning Guo, Chung-Kuan Cheng and Takeshi Yoshimura, An O-tree representation of non-slicing floorplan and its applications, Proceedings of the 36th Design Automation Conference, 268 to 273, 1999, the O-tree, admissible placements, and the contour that the B*-tree takes over
  3. Tung-Chieh Chen and Yao-Wen Chang, Modern floorplanning based on B*-tree and fast simulated annealing, IEEE Transactions on Computer-Aided Design of Integrated Circuits and Systems 25(4), 637 to 650, 2006, fixed-outline and bus-driven floorplanning with B*-trees and a three-stage annealing
  4. Andrew B. Kahng, Jens Lienig, Igor L. Markov and Jin Hu, VLSI Physical Design, From Graph Partitioning to Timing Closure, second edition, Springer, 2022, Chapter 3, Chip Planning (floorplan representations; general locator)

Where this leads

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/WA1GJ6/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)
WritingW4 complete
  • a review of the text: no review record reviews/WA1GJ6/text.yaml