Algorithm Search⌘K

Data structureadvanced

O-tree

Also called ordered tree floorplan.

Guo, Cheng and Yoshimura's ordered tree for an admissible packing, encoded by a 2n bit string and a permutation, which is decoded in linear time.

Time
O(n) worst · average · best
Space
O(n) extra
Where
n = the number of blocks
Properties
deterministiciterative
Origin
Pei Ning Guo, Chung Kuan Cheng, Takeshi Yoshimura, 1999

An O-tree is an ordered tree that stores a packing of nn blocks. Its root is a virtual block of width 0 that stands for the left side of the chip, and each child is placed just to the right of its parent. The blocks are placed in depth-first order, and each one drops down onto the blocks placed before it. The tree is stored as a string of 2n2n bits for its shape and a permutation of the blocks for its labels, and a contour gives the packing in O(n)O(n) time. Guo, Cheng and Yoshimura introduced it in 1999, with admissible placements: placements in which no block can move left or down. Its left-child right-sibling form is the B*-tree of the same packing.

In plain words

Think of the left side of the chip as a wall. Some blocks touch the wall; they are the children of the wall. Each block can have blocks that touch its right side; they are its children. Children keep an order, from the lowest to the highest.

To build the picture, walk the tree from the wall: go to the first child, then to its first child, and so on, and come back to try the next child. Each time you reach a block, its left side is where its parent ends. Drop it down until it lands. The tree shape is a list of down and up steps, two steps for each block.

The abstract type

The type stores an O-tree (T,π)(T, \pi) of 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.
  • PARENTS: return the parent of each block, or the root.
  • TO-B-STAR and FROM-B-STAR: change to the B*-tree of the same packing and back.

Guo and coauthors search over O-trees by deleting a block and inserting it at another place of the tree, and they turn a horizontal O-tree into a vertical one, built in the same way from the bottom side, to compact a packing in the other direction.

Representation

TT is a string of nn zeros and nn ones. Read from the left, it is a depth-first walk of the tree: a 0 goes down to the next child of the current node, and a 1 goes back up to the parent. A string is a tree if and only if no prefix has more ones than zeros, the condition of balanced parentheses with 0 as an open and 1 as a close parenthesis. Some sources use the opposite bits. π\pi lists the blocks in the order in which the walk reaches them, which is preorder.

The packing rules are:

  • the root RR is a virtual block with xR=0x_R = 0 and wR=0w_R = 0;
  • a child cc of pp has xc=xp+wpx_c = x_p + w_p;
  • each block, in the order of π\pi, gets the highest top of the blocks before it whose xx-ranges meet its own.

So the children of a node all start at the same xx, and a later child sits above an earlier one. The storage is 2n2n bits for TT and n⌈log⁡2n⌉n \lceil \log_2 n \rceil bits for π\pi.

The left-child right-sibling form turns the O-tree into a binary tree: the left child of a block is its first child, and the right child is its next sibling. The first child of RR is the root. This is exactly a B*-tree, and both rules give the same xx: a first child is at xp+wpx_p + w_p, and a next sibling at the xx of the sibling before it.

Operations

  1. PACK(T, π, w, h)
  2. 1contour ← one segment [0, ∞) at height 0
  3. 2stack ← (R, the first segment) ▷ each entry: a node, the segment where its next child starts
  4. 3for each bit t of T, from the left do
  5. 4if t = 1 then pop the stack; go on with the next bit
  6. 5b ← the next block of π; (p, s) ← the top entry of the stack
  7. 6x_b ← the left end of s; e ← x_b + w_b
  8. 7y_b ← the largest height of the segments from s on that start before e
  9. 8replace those segments by [x_b, e) at height y_b + h_b, keep the part of the last one after e; record (x_b, y_b), W, H
  10. 9set the segment of the top entry to s; push (b, the segment after s)
  11. 10return x, y, W, H

A first child of bb is the next block after bb, so the segment that line L9 pushes still starts at xb+wbx_b + w_b when it is used. A later sibling of bb starts at the segment of bb, which line L9 stores in the entry of the parent. The subtree of bb lies to the right of xb+wbx_b + w_b and does not change that segment.

Example

Take the five blocks of the B*-tree example: 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. Let T=0001110011T = 0001110011 and π=(A,B,C,D,E)\pi = (A, B, C, D, E). The walk goes down to A, B and C, up three times to RR, down to D and E, and up two times. So A and D are the children of RR, B is the child of A, C is the child of B, and E is the child of D.

bit block parent xx yy why
0 A RR 0 0 the floor
0 B A 3 0 the floor
0 C B 5 0 the floor
1, 1, 1 back to RR
0 D RR 0 2 on top of A
0 E D 2 3 on top of B, which is higher than A over [2,5)[2, 5)
1, 1 back to RR

The packing is 7×47 \times 4. Its left-child right-sibling form has the root A, the left child B of A, the left child C of B, the right child D of A (the next sibling of A) and the left child E of D. That is the tree of the B*-tree example, with the same packing.

Correctness

The string defines a unique ordered tree when no prefix has more ones than zeros, and the walk meets the blocks in preorder, so a parent is placed before its children and each xx is known in time. Each walk of line L7 starts at the segment that begins at xbx_b: for a first child, the segment pushed by its parent a moment before; for a later sibling, the segment of the sibling before it, which the subtree of that sibling does not touch. So each yy is the highest top below the block, and no two blocks overlap. Its left-child right-sibling form places the blocks in the same order and at the same xx, so the O-tree and its B*-tree give the same packing. The full proof is in the correctness proof.

The packing is compact downward but not always to the left, and two O-trees can give the same packing; the tests check an example of each. Guo and coauthors prove that each admissible placement has an O-tree, and that alternate changes between horizontal and vertical O-trees make any placement admissible. This is cited. The tests check its consequence for up to four blocks: the least area over all O-trees equals the least area of any packing.

Proof: The contour packing of an O-tree is correct, takes linear time, and equals the packing of its left-child right-sibling B*-treefull

We use the pseudocode and the conventions of the page. An O-tree on nn blocks is an ordered tree with n+1n + 1 nodes whose root RR is a virtual block with xR=0x_R = 0 and wR=0w_R = 0. It is given by a string TT of nn zeros and nn ones, a depth-first walk in which 0 goes down to the next child and 1 goes back up, and by the list π\pi of the blocks in the order in which the walk meets them. The packing rules are: a child cc of pp has xc=xp+wpx_c = x_p + w_p, the blocks are placed in the order π\pi, and

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

Lemma 1 (the string is a tree). A string of nn zeros and nn ones is the walk of an ordered tree with n+1n + 1 nodes if and only if no prefix has more ones than zeros. The tree is unique, and its nodes other than the root are met in preorder.

Proof. Read the string with a stack that holds the root. A 0 makes a new child of the top node, after the children made before, and pushes it. A 1 pops. The prefix condition says that a 1 never pops the root, and the equal counts say that the walk ends at the root. Each tree gives back its own walk, so the map is a bijection. A node is made when the walk first reaches it, after its parent and before its later siblings, which is preorder. □\square

Lemma 2 (the start segment). When line L5 takes a block bb with parent pp, the segment ss in the top entry of the stack is in the contour and s.x0=xbs.x_0 = x_b.

Proof. If bb is the first child of pp, the entry of pp was pushed when pp was placed, with the segment after the segment of pp, which starts at xp+wp=xbx_p + w_p = x_b. No block was placed in between, because the bit after the 0 of pp is the 0 of bb. For p=Rp = R the segment is the head, which starts at 0=xb0 = x_b. If bb has an earlier sibling aa, line L9 stored the segment of aa in the entry of pp, with x0=xa=xp+wp=xbx_0 = x_a = x_p + w_p = x_b. Between the placement of aa and that of bb only the subtree of aa is placed. Each of its blocks cc has xc≥xa+wa>xax_c \ge x_a + w_a > x_a, by induction on the depth below aa. A placement of cc changes the fields only of its own start segment, which starts at xcx_c, and unlinks only segments that start strictly between xcx_c and xc+wcx_c + w_c. So the segment of aa is not changed and stays in the contour. □\square

Lemma 3 (the contour and the y values). Before each block is placed, the list from the head is the contour of the placed blocks: increasing segments that cover [0,∞)[0, \infty), where the height at each point tt is the largest top ya+hay_a + h_a of a placed block with xa≤t<xa+wax_a \le t < x_a + w_a, or 0. Lines L6 and L7 set yby_b to the value of the formula.

Proof. At line L1 there are no blocks and one segment at height 0. By Lemma 2 the walk of line L7 starts at the segment that contains xbx_b and visits the segments that meet [xb,xb+wb)[x_b, x_b + w_b), so yby_b is the largest height on that interval. By the contour property this is the formula, because 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. Line L8 sets the height on [xb,xb+wb)[x_b, x_b + w_b) to yb+hby_b + h_b, which is not lower than the old heights there, and keeps all other heights. So the contour property holds after the placement. □\square

Theorem 1 (no overlap). In the packing no two blocks overlap, each block lies on the floor or on a block below it, and 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 meet, then yb≥ya+hay_b \ge y_a + h_a by Lemma 3; if not, a vertical line separates them. If yb>0y_b > 0, then yby_b is the top of a block whose xx-range meets that of bb, and bb rests on it. Line L8 and the next line keep the largest right side and the largest top. □\square

Theorem 2 (the B-tree of an O-tree).* Let BB be the left-child right-sibling form of the O-tree without RR: the left child of a block is its first child, the right child of a block is its next sibling, and the root of BB is the first child of RR. Then BB is a B*-tree, the map from O-trees to B*-trees on the same blocks is a bijection, and the packing of the O-tree equals the packing of BB.

Proof. The left-child right-sibling form is a bijection between ordered forests and binary trees, and the children of RR form an ordered forest of the nn blocks; FROM-B-STAR walks it back. The preorder of BB visits a block, then the subtree of its left child (the subtrees of its children in the O-tree) and then the subtree of its right child (its later siblings and their subtrees). This is the preorder of the O-tree, so the blocks are placed in the same order. The xx rules agree: the first child cc of pp is the left child of pp in BB, and both rules give xp+wpx_p + w_p. A later sibling cc of aa is the right child of aa in BB, and the O-tree rule gives xp+wp=xax_p + w_p = x_a, the B*-tree rule for a right child. The first child of RR and its siblings have x=0x = 0 in both. With the same order and the same xx values, the formula for yy is the same, so the packings are equal. □\square

Not claimed. The packing need not be compact to the left, and two O-trees can give the same packing. Take three unit squares. The O-tree T=001011T = 001011, π=(A,B,C)\pi = (A, B, C) makes AA the child of RR and BB, CC the two children of AA. It puts AA at (0,0)(0, 0), BB at (1,0)(1, 0) and CC at (1,1)(1, 1), and CC can move left to (0,1)(0, 1). The O-trees T=010011T = 010011, π=(A,D,E)\pi = (A, D, E) and T=001101T = 001101, π=(A,E,D)\pi = (A, E, D) are different, and both put AA at (0,0)(0, 0), DD at (0,1)(0, 1) and EE at (1,0)(1, 0). The tests check both examples. Guo, Cheng and Yoshimura prove, in the section on admissible placements of their DAC 1999 paper, that each admissible placement has an O-tree, and that a placement can be made admissible by turns of horizontal and vertical O-trees. This is cited. The tests check its consequence for n≤4n \le 4: the least area over all O-trees equals the least area of any packing.

Complexity. Each bit is read one time. A 1 pops one entry in O(1)O(1) time. A 0 does O(1)O(1) work plus one step for each segment of its walk. As for the B*-tree, every segment of a walk other than the first is unlinked or cut, and each placement makes at most one new segment, so all walks together take at most 2n+12n + 1 steps. The packing takes O(n)O(n) time and O(n)O(n) space, and so do PARENTS, TO-B-STAR and FROM-B-STAR. The number of O-trees is Cn⋅n!C_n \cdot n!, where CnC_n is the number of tree strings with nn zeros, the nnth Catalan number. ■\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)
PARENTS, TO-B-STAR, FROM-B-STAR O(n)O(n) O(n)O(n)
check that a string is a tree O(n)O(n) O(1)O(1)

PACK reads each bit one time. Each segment that a walk passes, except the first, is removed or cut, and each block makes at most one new segment, so all walks together take O(n)O(n) steps. There are CnC_n tree strings with nn zeros, where CnC_n is the nnth Catalan number, so there are n!⋅Cnn! \cdot C_n O-trees, as many as B*-trees. This is fewer than the (n!)2(n!)^2 sequence pairs for n≥3n \ge 3.

Variants

  • Horizontal and vertical O-trees. The tree on this page is the horizontal O-tree, with the left wall as the root. The vertical O-tree has the bottom side as the root, with xx and yy exchanged. Turns between the two compact a packing in both directions.
  • The B-tree.* The B*-tree stores the same trees as binary trees, which makes deletion and insertion simpler and removes the need to keep the bit string valid.
  • Soft blocks and constraints. Later works add soft blocks, pre-placed blocks and other constraints to O-tree searches.

When to use it

Use an O-tree when a compact code of a packing matters, for example to store many packings, or when the search changes the tree by deletions and insertions of whole subtrees. The code needs about n(2+log⁡2n)n (2 + \log_2 n) bits. For most searches the B*-tree is simpler, since its moves need no change of a bit string. For slicing floorplans, a normalized Polish expression is the usual code.

Pitfalls

  • Forgetting the virtual root. The root is the left wall, not a block. There are n+1n + 1 nodes and 2n2n bits. Without the virtual root, the blocks that touch the left wall have no common parent, and the tree is a forest.
  • Invalid strings. A move that changes bits must keep the prefix condition and the equal counts. Otherwise the walk pops the root or ends inside the tree.
  • The wrong start segment for a sibling. A later sibling starts at the segment of the sibling before it, not at the segment after its parent: the segment after the parent may have been cut by the subtrees in between.
  • Counting packings by trees. Two O-trees can give the same packing, so n!⋅Cnn! \cdot C_n is an upper bound on the number of packings of nn blocks, not the count.

Implementations

The Python class stores the bit string and the permutation and implements the tree test, PARENTS, PACK with the linked contour, a direct quadratic packing for the tests, TO-B-STAR and FROM-B-STAR. The tests check all O-trees of up to four blocks with random sizes: the two packings agree, there is no overlap, the xx rule and the rest on the floor or on a block hold, the packing equals that of the B*-tree form, and FROM-B-STAR gives the same O-tree back. For three and four blocks, the best area over all O-trees equals the best area of a search over all positions. They also check 300 random O-trees of up to 40 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.

o_tree_floorplan.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/o-tree-floorplan/. The authors are listed in prov/GM5XEG.jsonl.

"""The horizontal O-tree of Guo, Cheng and Yoshimura (1999).

An O-tree on n blocks is an ordered tree with n + 1 nodes. The root is a
virtual block of width 0 at x = 0, the left wall. A child c of a node p has
x_c = x_p + w_p. The tree is stored as a 2n-bit string T, written in a
depth-first walk (0: go down to a new child, 1: go back up), and a list perm
of the blocks in the order the walk meets them. The blocks are placed in that
order, and each block drops onto the contour of the blocks before it, so the
packing takes 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


def is_tree_string(bits: str) -> bool:
    """True if bits is a walk of an ordered tree: every prefix has at least as many 0 as 1, and the counts are equal."""
    depth = 0
    for c in bits:
        if c == "0":
            depth += 1
        elif c == "1":
            depth -= 1
            if depth < 0:
                return False
        else:
            return False
    return depth == 0


class OTree:
    """An O-tree given by its bit string and its permutation."""

    def __init__(self, bits: str, perm: list[int]) -> None:
        """Raise ValueError unless bits is a tree string with one 0 for each block of perm."""
        if not is_tree_string(bits) or bits.count("0") != len(perm) or len(set(perm)) != len(perm):
            raise ValueError("not an O-tree")
        self.bits = bits
        self.perm = list(perm)

    def parents(self) -> dict[int, Optional[int]]:
        """Return the parent of each block; None is the virtual root. O(n)."""
        par: dict[int, Optional[int]] = {}
        stack: list[Optional[int]] = [None]
        k = 0
        for c in self.bits:
            if c == "0":
                b = self.perm[k]
                k += 1
                par[b] = stack[-1]
                stack.append(b)
            else:
                stack.pop()
        return par

    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. O(n) time."""
        head = _Seg(0, INF, 0, None)  # @line L1
        pos: dict[int, tuple[int, int]] = {}
        width = height = 0
        # each stack entry is [block, the contour segment where its next child starts]
        stack: list[list] = [[None, head]]  # @line L2
        k = 0
        for c in self.bits:  # @line L3
            if c == "1":
                stack.pop()  # @line L4
                continue
            b = self.perm[k]  # @line L5
            k += 1
            entry = stack[-1]
            start = entry[1]
            x = start.x0  # @line L6
            end = x + w[b]
            y = 0
            s: Optional[_Seg] = start
            last = start
            while s is not None and s.x0 < end:  # @line L7
                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 L8
            start.x1, start.top, start.next = end, y + h[b], rest
            pos[b] = (x, y)
            width, height = max(width, end), max(height, y + h[b])
            entry[1] = start  # the next sibling of b starts where b starts  # @line L9
            stack.append([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)."""
        par = self.parents()
        pos: dict[int, tuple[int, int]] = {}
        for b in self.perm:
            p = par[b]
            x = 0 if p is None else pos[p][0] + w[p]
            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 not pos:
            return 0, 0, pos
        return max(x + w[b] for b, (x, _) in pos.items()), max(y + h[b] for b, (_, y) in pos.items()), pos

    def to_b_star(self) -> tuple[Optional[int], dict[int, Optional[int]], dict[int, Optional[int]]]:
        """Return (root, left, right) of the left-child right-sibling form: a B*-tree. O(n)."""
        left: dict[int, Optional[int]] = {b: None for b in self.perm}
        right: dict[int, Optional[int]] = {b: None for b in self.perm}
        first_child: Optional[int] = None
        # last[i] is the last child seen so far of the node at depth i of the stack
        stack: list[Optional[int]] = [None]
        last: list[Optional[int]] = [None]
        k = 0
        for c in self.bits:
            if c == "1":
                stack.pop()
                last.pop()
                continue
            b = self.perm[k]
            k += 1
            p, prev = stack[-1], last[-1]
            if prev is not None:
                right[prev] = b
            elif p is not None:
                left[p] = b
            else:
                first_child = b
            last[-1] = b
            stack.append(b)
            last.append(None)
        return first_child, left, right

    @staticmethod
    def from_b_star(root: Optional[int], left: dict, right: dict) -> "OTree":
        """The inverse of to_b_star: the O-tree whose left-child right-sibling form is the given tree. O(n)."""
        bits: list[str] = []
        perm: list[int] = []

        # the children of a node are its left child and then the chain of right children
        def walk(first: Optional[int]) -> None:
            stack = [(first, 0)]
            while stack:
                b, state = stack.pop()
                if b is None:
                    continue
                if state == 0:
                    bits.append("0")
                    perm.append(b)
                    stack.append((b, 1))
                    stack.append((left.get(b), 0))
                else:
                    bits.append("1")
                    stack.append((right.get(b), 0))

        walk(root)
        return OTree("".join(bits), perm)
test_o_tree_floorplan.py 182 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/o-tree-floorplan/. The authors are listed in prov/GM5XEG.jsonl.

import itertools
import random

import pytest

from o_tree_floorplan import OTree, is_tree_string


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 tree_strings(n: int) -> list[str]:
    """All strings with n zeros and n ones whose prefixes never have more ones than zeros."""
    out = []

    def rec(s: str, zeros: int, ones: int) -> None:
        if zeros == ones == n:
            out.append(s)
            return
        if zeros < n:
            rec(s + "0", zeros + 1, ones)
        if ones < zeros:
            rec(s + "1", zeros, ones + 1)

    rec("", 0, 0)
    return out


def b_star_pack(root, left, right, w, h):
    """Reference packing of a B*-tree by its rules, with a direct search for each y."""
    pos = {}
    if root is None:
        return pos
    stack = [(root, 0)]
    while stack:
        b, x = stack.pop()
        y = max([pos[a][1] + h[a] for a in pos if pos[a][0] < x + w[b] and x < pos[a][0] + w[a]], default=0)
        pos[b] = (x, y)
        if right.get(b) is not None:
            stack.append((right[b], x))
        if left.get(b) is not None:
            stack.append((left[b], x + w[b]))
    return pos


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(t: OTree, 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])
    par = t.parents()
    for b, (x, y) in pos.items():
        p = par[b]
        assert x == (0 if p is None else pos[p][0] + w[p])
        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)
    root, left, right = t.to_b_star()
    assert b_star_pack(root, left, right, w, h) == pos
    back = OTree.from_b_star(root, left, right)
    assert (back.bits, back.perm) == (t.bits, t.perm)


def test_example() -> None:
    a, b, c, d, e = range(5)
    t = OTree("0001110011", [a, b, c, d, e])
    w = {a: 3, b: 2, c: 2, d: 2, e: 3}
    h = {a: 2, b: 3, c: 1, d: 2, e: 1}
    width, height, pos = t.pack(w, h)
    assert pos == {a: (0, 0), b: (3, 0), c: (5, 0), d: (0, 2), e: (2, 3)}
    assert (width, height) == (7, 4)
    assert t.parents() == {a: None, b: a, c: b, d: None, e: d}
    assert t.to_b_star() == (a, {a: b, b: c, c: None, d: e, e: None}, {a: d, b: None, c: None, d: None, e: None})
    check(t, w, h)


def test_not_left_compact_and_not_injective() -> None:
    a, b, c, d, e = range(5)
    one = {v: 1 for v in range(5)}
    assert OTree("001011", [a, b, c]).pack(one, one)[2] == {a: (0, 0), b: (1, 0), c: (1, 1)}
    p1 = OTree("010011", [a, d, e]).pack(one, one)[2]
    p2 = OTree("001101", [a, e, d]).pack(one, one)[2]
    assert p1 == p2 == {a: (0, 0), d: (0, 1), e: (1, 0)}


def test_bad_input() -> None:
    for bits, perm in [("01", [1, 2]), ("10", [1]), ("0011", [1, 1]), ("0", [1]), ("0x", [1])]:
        with pytest.raises(ValueError):
            OTree(bits, perm)
    assert not is_tree_string("0110") and is_tree_string("0101") and is_tree_string("")
    assert OTree("", []).pack({}, {}) == (0, 0, {})


def test_all_small_trees() -> None:
    rng = random.Random(31)
    assert [len(tree_strings(n)) for n in range(7)] == [1, 1, 2, 5, 14, 42, 132]
    for n in range(1, 5):
        trees = [OTree(s, list(p)) for s in tree_strings(n) for p in itertools.permutations(range(n))]
        assert len(trees) == len(tree_strings(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:
                check(t, w, h)


def test_best_tree_is_best_packing() -> None:
    rng = random.Random(32)
    for trial in range(30):
        n = 3 if trial < 18 else 4
        top = 5 if n == 3 else 3
        w = {b: rng.randint(1, top) for b in range(n)}
        h = {b: rng.randint(1, top) for b in range(n)}
        best = min(
            wd * ht
            for s in tree_strings(n)
            for p in itertools.permutations(range(n))
            for wd, ht, _ in [OTree(s, list(p)).pack(w, h)]
        )
        assert best == best_packing_area(w, h)


def random_tree_string(n: int, rng: random.Random) -> str:
    """A random tree string: a random walk that stays at depth 0 or more."""
    s, zeros, ones = [], 0, 0
    while ones < n:
        if zeros < n and (ones == zeros or rng.random() < 0.5):
            s.append("0")
            zeros += 1
        else:
            s.append("1")
            ones += 1
    return "".join(s)


def test_random_larger() -> None:
    rng = random.Random(33)
    for _ in range(300):
        n = rng.randint(1, 40)
        perm = list(range(n))
        rng.shuffle(perm)
        t = OTree(random_tree_string(n, rng), perm)
        w = {b: rng.randint(1, 9) for b in range(n)}
        h = {b: rng.randint(1, 9) for b in range(n)}
        check(t, w, h)

History

Guo, Cheng and Yoshimura introduced the O-tree at DAC 1999, with admissible placements, the 2n2n-bit code, the linear-time packing and a search by deletions and insertions. Chang, Chang, Wu and Wu gave the B*-tree at DAC 2000 as a binary tree for the same packings, and it replaced the O-tree in many later floorplanners.

References

  1. 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 definition of the horizontal and the vertical O-tree, the encoding by a 2n-bit string and a permutation, the linear-time packing with a contour, admissible placements, and the search with deletions and insertions
  2. 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 binary tree form of the O-tree and the comparison with it
  3. 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)

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/GM5XEG/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/GM5XEG/text.yaml