Algorithm Search⌘K

Data structurecore

Sequence pair

Also called Murata sequence pair.

Murata and coauthors' pair of block orders that encodes left-of and below relations for any packing, including non-slicing ones, decoded by longest paths.

Time
O(n log n) worst · average · best
Space
O(n) extra
Where
n = the number of blocks
Properties
deterministiciterative
Origin
Hiroshi Murata, Kunihiro Fujiyoshi, Shigetoshi Nakatake, Yoji Kajitani, 1995

A sequence pair is two orders of the same blocks, written (Γ+,Γ−)(\Gamma_+, \Gamma_-). For each pair of blocks, the two orders say whether one block is to the left of the other or below it. The packing of a sequence pair puts every block as far to the left and as low as these relations allow. It is computed by longest paths in the two constraint graphs, or in O(nlog⁡n)O(n \log n) time as a weighted longest common subsequence. Murata, Fujiyoshi, Nakatake and Kajitani introduced it in 1995, and they proved that every packing, slicing or not, has a sequence pair whose packing is not larger. So a search over the (n!)2(n!)^2 pairs, such as an annealing, always contains an optimal rectangle packing.

In plain words

Write the names of the blocks in two lists. If block A comes before block B in both lists, A goes to the left of B. If B comes before A in the first list but A comes before B in the second, A goes below B. Every two blocks are in one of these cases, so every two blocks are kept apart, either side by side or one above the other.

To build the picture, take the blocks in the order of the first list. Push each block to the left until it touches a block that must be on its left, or the wall. Then do the same downward. The result never has two blocks on top of each other.

The abstract type

The type stores a sequence pair of a set of nn blocks. The operations are:

  • RELATION(a,b)(a, b): tell whether aa is left of, right of, below or above bb.
  • 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.
  • PACK-BY-GRAPHS(w,h)(w, h): the same packing, by longest paths in the constraint graphs.
  • SWAP-IN-PLUS(a,b)(a, b) and SWAP-IN-BOTH(a,b)(a, b): the moves of a search.

The rule of this page is: if aa comes before bb in both Γ+\Gamma_+ and Γ−\Gamma_-, then aa is left of bb; if bb comes before aa in Γ+\Gamma_+ and aa comes before bb in Γ−\Gamma_-, then aa is below bb. Some sources swap the roles of the two orders, or of "below" and "above". The structure is the same.

Representation

The two orders are arrays, and two more arrays give the position of each block in each order, so RELATION reads two positions. The four cases of the two comparisons are the four relations: before in both is left, after in both is right, after in Γ+\Gamma_+ and before in Γ−\Gamma_- is below, and the last case is above. Each pair of blocks has exactly one relation, so in the packing each pair is separated by a vertical line or by a horizontal line.

The horizontal constraint graph GhG_h has an edge a→ba \to b of weight waw_a when aa is left of bb, and the vertical graph GvG_v has an edge a→ba \to b of weight hah_a when aa is below bb. Every edge of GhG_h goes forward in Γ+\Gamma_+, and every edge of GvG_v goes forward in Γ−\Gamma_-, so both graphs are DAGs with a known topological order. The packing is xbx_b = the longest path into bb in GhG_h and yby_b = the longest path into bb in GvG_v, the least solution of the difference constraints of the two graphs.

Operations

  1. PACK(Γ+, Γ−, w, h) ▷ pos−(b): the position of b in Γ−, from 1
  2. 1F ← a Fenwick tree of prefix maxima over the positions 1..n, all 0
  3. 2for each block b in the order Γ+ do
  4. 3x_b ← the maximum of F over the positions 1 .. pos−(b) − 1
  5. 4raise F at the position pos−(b) to x_b + w_b
  6. 5F' ← a new Fenwick tree of prefix maxima, all 0
  7. 6for each block b in the reverse of the order Γ+ do
  8. 7y_b ← the maximum of F' over the positions 1 .. pos−(b) − 1
  9. 8raise F' at the position pos−(b) to y_b + h_b
  10. 9return x, y, W = the maximum of F, H = the maximum of F'

When line L3 runs for bb, the tree holds the blocks that come before bb in Γ+\Gamma_+, and the query keeps those that also come before bb in Γ−\Gamma_-. These are exactly the blocks left of bb, so xbx_b is the largest right side among them. Lines L6 to L8 do the same in the reverse order, and select the blocks below bb. This is the weighted longest common subsequence of Tang, Tian and Wong: WW is the largest total width of a sequence of blocks that is common to Γ+\Gamma_+ and Γ−\Gamma_-.

  1. PACK-BY-GRAPHS(Γ+, Γ−, w, h)
  2. 1x_b ← 0 and y_b ← 0 for each block b
  3. 2for each block b in the order Γ+ do
  4. 3for each a before b in Γ+ with pos−(a) < pos−(b) do x_b ← max(x_b, x_a + w_a)
  5. 4for each block b in the order Γ− do
  6. 5for each a before b in Γ− with pos+(a) > pos+(b) do y_b ← max(y_b, y_a + h_a)
  7. 6return x, y, W = max_b (x_b + w_b), H = max_b (y_b + h_b)
  1. SWAP-IN-PLUS(a, b)
  2. 1exchange a and b in Γ+, and exchange pos+(a) and pos+(b)
  3. SWAP-IN-BOTH(a, b)
  4. 2SWAP-IN-PLUS(a, b); exchange a and b in Γ−, and exchange pos−(a) and pos−(b)

A swap in Γ+\Gamma_+ only changes the relation of aa and bb and of the blocks between them. A swap in both orders exchanges the places of aa and bb in the packing, when they have the same size. Murata and coauthors used these two moves and the rotation of a block in their annealing.

Example

A pinwheel of five blocks fills a 3×33 \times 3 square: block 1 (1×21 \times 2) at the lower left, block 2 (2×12 \times 1) at the bottom right, block 3 (1×11 \times 1) in the centre, block 4 (1×21 \times 2) at the right, and block 5 (2×12 \times 1) at the top left. No straight cut splits it, so it is not a slicing floorplan and no Polish expression stores it. The sequence pair Γ+=(5,1,3,4,2)\Gamma_+ = (5, 1, 3, 4, 2), Γ−=(1,2,3,5,4)\Gamma_- = (1, 2, 3, 5, 4) does. The positions in Γ−\Gamma_- are 1→11 \to 1, 2→22 \to 2, 3→33 \to 3, 5→45 \to 4 and 4→54 \to 5.

pass block pos− values in the tree at positions below pos− coordinate the tree is raised at pos− to
x 5 4 none x5=0x_5 = 0 2
x 1 1 none x1=0x_1 = 0 1
x 3 3 1 (block 1) x3=1x_3 = 1 2
x 4 5 1, 2, 2 (blocks 1, 3, 5) x4=2x_4 = 2 3
x 2 2 1 (block 1) x2=1x_2 = 1 3
y 2 2 none y2=0y_2 = 0 1
y 4 5 1 (block 2) y4=1y_4 = 1 3
y 3 3 1 (block 2) y3=1y_3 = 1 2
y 1 1 none y1=0y_1 = 0 2
y 5 4 2, 1, 2 (blocks 1, 2, 3) y5=2y_5 = 2 3

The corners are 1:(0,0)1: (0, 0), 2:(1,0)2: (1, 0), 3:(1,1)3: (1, 1), 4:(2,1)4: (2, 1) and 5:(0,2)5: (0, 2), and W=H=3W = H = 3. The block area is 2+2+1+2+2=92 + 2 + 1 + 2 + 2 = 9, so the packing has no empty space. RELATION(2, 3) is "below": block 3 comes before block 2 in Γ+\Gamma_+, and block 2 comes before block 3 in Γ−\Gamma_-. In the x pass, block 2 does not see blocks 5, 3 and 4, although they come before it in Γ+\Gamma_+, because they come after it in Γ−\Gamma_-: they are above block 2, not to its left.

Correctness

Each pair of blocks gets exactly one of the four relations, because the two comparisons have four outcomes. The edges of GhG_h go forward in Γ+\Gamma_+ and those of GvG_v go forward in Γ−\Gamma_-, so both graphs are acyclic, and the longest paths are the least coordinates that obey every relation. PACK computes the same values: when it visits bb in the order Γ+\Gamma_+, the Fenwick query over the positions before bb in Γ−\Gamma_- ranges over exactly the blocks left of bb. Since every pair is separated in xx or in yy, no two blocks overlap. Any placement that obeys the same relations has coordinates at least as large. Murata and coauthors proved that every placement without overlap obeys the relations of some sequence pair; this is cited with a sketch, and the tests check it for up to four blocks. The full proof of the rest is in the correctness proof.

Proof: The packing of a sequence pair has no overlap and is the least packing that obeys its relationsfull

We use the pseudocode and the convention of the page. Let (Γ+,Γ−)(\Gamma_+, \Gamma_-) be two orders of the same nn blocks, and write a<+ba <_+ b and a<−ba <_- b for "a comes before b" in the two orders. For blocks a≠ba \ne b:

  • aa is left of bb if a<+ba <_+ b and a<−ba <_- b;
  • aa is below bb if b<+ab <_+ a and a<−ba <_- b.

Let GhG_h be the directed graph with an edge a→ba \to b of weight waw_a for each pair with aa left of bb, and GvG_v the graph with an edge a→ba \to b of weight hah_a for each pair with aa below bb. These are the constraint graphs of the pair.

Lemma 1 (one relation per pair). For each pair of distinct blocks a,ba, b, exactly one of these holds: aa left of bb, bb left of aa, aa below bb, bb below aa.

Proof. The two orders give the two bits [a<+b][a <_+ b] and [a<−b][a <_- b]. The four values of the two bits are the four cases: (1,1)(1, 1) is aa left of bb, (0,0)(0, 0) is bb left of aa, (0,1)(0, 1) is aa below bb, and (1,0)(1, 0) is bb below aa. □\square

Lemma 2 (the graphs are acyclic). Every edge a→ba \to b of GhG_h has a<+ba <_+ b, and every edge of GvG_v has a<−ba <_- b. So Γ+\Gamma_+ is a topological order of GhG_h and Γ−\Gamma_- is a topological order of GvG_v, and both graphs are DAGs.

Proof. This is the definition of the two relations. □\square

Lemma 3 (longest paths). Lines L10 to L15 set xbx_b to the length of the longest path into bb in GhG_h and yby_b to the length of the longest path into bb in GvG_v. These are the least values that satisfy xb≥xa+wax_b \ge x_a + w_a for each edge of GhG_h, yb≥ya+hay_b \ge y_a + h_a for each edge of GvG_v, and x,y≥0x, y \ge 0.

Proof. Line L11 visits the blocks in the order Γ+\Gamma_+, which is topological by Lemma 2, so every predecessor aa of bb has its final value when bb is visited. Line L12 then takes the maximum of xa+wax_a + w_a over all edges into bb, which is the recurrence of the longest path in a DAG. The same holds for lines L13 and L14 with Γ−\Gamma_-. By induction along the topological order, any solution of the inequalities has xbx_b at least the longest path value, and the longest path values satisfy all of them. □\square

Lemma 4 (the Fenwick pass). Lines L1 to L4 compute the same xx as Lemma 3, and lines L5 to L8 the same yy.

Proof. Consider line L3 for the block bb with position pp in Γ−\Gamma_-. The blocks already in the tree are exactly the blocks aa with a<+ba <_+ b, because line L2 follows Γ+\Gamma_+. The tree stores at position qq the value xa+wax_a + w_a of the block aa at position qq of Γ−\Gamma_-, if aa has been seen, and 0 otherwise, and a query returns the maximum over positions 1,…,p−11, \ldots, p - 1, that is over the blocks with a<−ba <_- b. So the query returns the maximum of xa+wax_a + w_a over the blocks with a<+ba <_+ b and a<−ba <_- b, which are the blocks left of bb, or 0 if there is none. This is the recurrence of Lemma 3, evaluated in the same order. For yy, line L6 visits the blocks in the reverse of Γ+\Gamma_+, so the blocks seen before bb are those with b<+ab <_+ a, and the query selects those with a<−ba <_- b: the blocks below bb. □\square

Theorem 1 (no overlap). In the packing, no two blocks overlap, and for every pair the relation of Lemma 1 holds in the geometry: if aa is left of bb then xa+wa≤xbx_a + w_a \le x_b, and if aa is below bb then ya+ha≤yby_a + h_a \le y_b. Line L9 returns the width and the height of the bounding box.

Proof. By Lemma 3 every edge constraint holds. By Lemma 1 every pair has an edge in one of the graphs, so the two blocks are separated by a vertical line or by a horizontal line, and their interiors do not meet. The query over all nn positions in line L9 returns the largest xa+wax_a + w_a, which is the right side of the bounding box, and the same for the top. □\square

Theorem 2 (the least packing). Let PP be any placement of the blocks without overlap in which, for each pair, the relation of the sequence pair holds (aa left of bb implies xaP+wa≤xbPx^P_a + w_a \le x^P_b, and the same for below). Then xb≤xbPx_b \le x^P_b and yb≤ybPy_b \le y^P_b for all bb, and the packing is not wider and not higher than PP.

Proof. The coordinates of PP satisfy the inequalities of Lemma 3, so they are at least the least solution. □\square

Cited theorem (every packing has a sequence pair). For every placement PP of the blocks without overlap there is a sequence pair whose packing is not wider and not higher than PP. In particular, some sequence pair gives a packing of least area. This is the main theorem of Murata, Fujiyoshi, Nakatake and Kajitani (IEEE TCAD 15(12), 1996, the section on the gridding procedure). Proof sketch: from the centre of each block draw two monotone staircase lines, one up and to the right and one down and to the left, that go around the other blocks and do not cross the lines of other blocks; this gives the positive locus of the block. The positive loci of different blocks do not cross, so they are ordered from the upper left to the lower right, and this order is Γ+\Gamma_+. The negative loci, which go up and to the left and down and to the right, give Γ−\Gamma_- in the same way. For each pair, the relation that the two loci give is true in PP, so Theorem 2 applies. The tests check the consequence for n≤4n \le 4: the least area over all (n!)2(n!)^2 pairs equals the least area of a packing, found by a search over all positions.

Complexity. The Fenwick tree has nn cells, and each of the 2n2n updates and 2n+22n + 2 queries takes O(log⁡n)O(\log n) time, so PACK takes O(nlog⁡n)O(n \log n) time and O(n)O(n) space. PACK-BY-GRAPHS looks at each ordered pair one time in each pass, so it takes Θ(n2)\Theta(n^2) time. A relation query reads two positions, and a swap updates two entries of each order and of the position maps, in O(1)O(1) time. ■\blacksquare

Complexity

operation time extra space
RELATION O(1)O(1) none
PACK O(nlog⁡n)O(n \log n) O(n)O(n)
PACK-BY-GRAPHS Θ(n2)\Theta(n^2) O(n)O(n), the edges are not stored
SWAP-IN-PLUS, SWAP-IN-BOTH O(1)O(1) none

The constraint graphs can have Θ(n2)\Theta(n^2) edges, for example when Γ+=Γ−\Gamma_+ = \Gamma_- and all blocks are in one row. The original decoding builds them and takes O(n2)O(n^2) time. Tang, Tian and Wong showed in 2000 that the packing is a weighted longest common subsequence and gave the O(nlog⁡n)O(n \log n) method above. Tang and Wong lowered the time to O(nlog⁡log⁡n)O(n \log \log n) in 2001 with a faster priority queue for integer keys. The bound is on the word RAM with the sizes in words.

There are (n!)2(n!)^2 sequence pairs of nn blocks. Many of them give the same packing, so the space is redundant: for example, a row of blocks and a gap-free stack have many pairs each.

Variants

  • Rotations and soft blocks. A search adds the rotation of a block as a move, or changes the shape of a soft block. The pair does not change, only the sizes.
  • Fixed outline. Adya and Markov search over sequence pairs for a packing that fits a given outline, with a cost for the part outside it.
  • Incremental evaluation. A swap changes the relations of a few blocks, and incremental methods update only the coordinates that change.
  • Other representations. The B*-tree and the O-tree store only compacted packings, with less redundancy and a linear decoding. The corner block list of Hong and coauthors stores mosaic floorplans.
  • Constraints. Pre-placed blocks, alignment and symmetry for analog layout can be written as conditions on the two orders.

When to use it

Use a sequence pair when the best packing may be non-slicing and a search will change the packing many times, as in annealing floorplanners for macros. Every pair is a legal packing, the moves are simple swaps, and the decoding is fast. For slicing floorplans, a normalized Polish expression has no redundancy and allows exact sizing of soft blocks. If the decoding time matters most, a B*-tree decodes in linear time.

Pitfalls

  • Mixing up the convention. The meaning of "before in Γ+\Gamma_+ and after in Γ−\Gamma_-" differs between sources. Use one convention in RELATION, in PACK and in the moves.
  • The wrong order for y. The y pass must visit the blocks in the reverse of Γ+\Gamma_+. In the order of Γ+\Gamma_+ the query selects the blocks above, not below.
  • A reused tree. The Fenwick tree of line L1 must start at 0 for each decoding. A tree left over from the x pass or from the last pair gives wrong maxima.
  • Expecting a compact packing. Each block is as low as its "below" relations allow. A block that is "below" bb in the pair but lies to one side of bb in the geometry can still push bb up, so bb can float with empty space under all of it. In a B*-tree packing, each block rests on the floor or on a block below it.
  • Counting floorplans. The (n!)2(n!)^2 pairs do not count distinct packings or floorplans. Many pairs give the same packing.

Implementations

The Python class stores the two orders and their position maps, and implements RELATION, PACK with a Fenwick tree of prefix maxima, PACK-BY-GRAPHS by longest paths in the topological orders, and the two swaps. The tests check the pinwheel, 800 random pairs of up to 12 blocks for equal results of the two decodings and for the absence of overlap with every relation true in the geometry, and, for 3 and 4 blocks, that the best area over all (n!)2(n!)^2 pairs equals the best area of a search over all positions.

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.

sequence_pair.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sequence-pair/. The authors are listed in prov/9NWMQZ.jsonl.

"""The sequence pair of Murata, Fujiyoshi, Nakatake and Kajitani (1995).

A sequence pair is two orders (plus, minus) of the same blocks. The convention
of this module, for two blocks a and b:

- a before b in both orders: a is to the left of b;
- b before a in plus and a before b in minus: a is below b.

The packing puts each block as far to the left and as low as these relations
allow. pack() computes it in O(n log n) time with a Fenwick tree of prefix
maxima, which is the weighted longest common subsequence method of Tang, Tian
and Wong; pack_by_graphs() computes it in O(n^2) time with the horizontal and
vertical constraint graphs.
"""

from typing import Hashable

Block = Hashable


class _PrefixMax:
    """Fenwick tree over positions 1..n that keeps the maximum of a prefix."""

    def __init__(self, n: int) -> None:
        self.t = [0] * (n + 1)

    def update(self, i: int, v: int) -> None:
        while i < len(self.t):
            if self.t[i] < v:
                self.t[i] = v
            i += i & -i

    def query(self, i: int) -> int:
        """Return the maximum over positions 1..i (0 if i = 0)."""
        r = 0
        while i > 0:
            if self.t[i] > r:
                r = self.t[i]
            i -= i & -i
        return r


class SequencePair:
    """A pair of orders of the same blocks."""

    def __init__(self, plus: list[Block], minus: list[Block]) -> None:
        """Store the two orders. Raise ValueError if they are not orders of the same blocks."""
        if len(plus) != len(minus) or set(plus) != set(minus) or len(set(plus)) != len(plus):
            raise ValueError("the two sequences must be orders of the same blocks")
        self.plus = list(plus)
        self.minus = list(minus)
        self._index()

    def _index(self) -> None:
        self.pos_plus = {b: i for i, b in enumerate(self.plus)}
        self.pos_minus = {b: i for i, b in enumerate(self.minus)}

    def check_invariant(self) -> None:
        """Raise AssertionError if the orders or the position maps are broken."""
        assert set(self.plus) == set(self.minus) and len(set(self.plus)) == len(self.plus)
        assert all(self.plus[i] == b for b, i in self.pos_plus.items())
        assert all(self.minus[i] == b for b, i in self.pos_minus.items())

    def relation(self, a: Block, b: Block) -> str:
        """Return "left", "right", "below" or "above": where a is with respect to b. O(1)."""
        p = self.pos_plus[a] < self.pos_plus[b]
        m = self.pos_minus[a] < self.pos_minus[b]
        if p and m:
            return "left"
        if not p and not m:
            return "right"
        return "below" if m else "above"

    def pack(
        self, w: dict[Block, int], h: dict[Block, int]
    ) -> tuple[int, int, dict[Block, int], dict[Block, int]]:
        """Return (W, H, x, y), the lower-left packing of the sequence pair. O(n log n)."""
        n = len(self.plus)
        x: dict[Block, int] = {}
        y: dict[Block, int] = {}
        fx = _PrefixMax(n)  # @line L1
        for b in self.plus:  # @line L2
            p = self.pos_minus[b] + 1
            x[b] = fx.query(p - 1)  # @line L3
            fx.update(p, x[b] + w[b])  # @line L4
        fy = _PrefixMax(n)  # @line L5
        for b in reversed(self.plus):  # @line L6
            p = self.pos_minus[b] + 1
            y[b] = fy.query(p - 1)  # @line L7
            fy.update(p, y[b] + h[b])  # @line L8
        width = fx.query(n)  # @line L9
        height = fy.query(n)
        return width, height, x, y

    def pack_by_graphs(
        self, w: dict[Block, int], h: dict[Block, int]
    ) -> tuple[int, int, dict[Block, int], dict[Block, int]]:
        """The same packing by longest paths in the two constraint graphs. O(n^2)."""
        x = {b: 0 for b in self.plus}  # @line L10
        y = {b: 0 for b in self.plus}
        for b in self.plus:  # plus is a topological order of the horizontal graph  # @line L11
            for a in self.plus[: self.pos_plus[b]]:
                if self.pos_minus[a] < self.pos_minus[b]:  # edge a -> b: a left of b
                    x[b] = max(x[b], x[a] + w[a])  # @line L12
        for b in self.minus:  # minus is a topological order of the vertical graph  # @line L13
            for a in self.minus[: self.pos_minus[b]]:
                if self.pos_plus[a] > self.pos_plus[b]:  # edge a -> b: a below b
                    y[b] = max(y[b], y[a] + h[a])  # @line L14
        width = max((x[b] + w[b] for b in self.plus), default=0)  # @line L15
        height = max((y[b] + h[b] for b in self.plus), default=0)
        return width, height, x, y

    def swap_in_plus(self, a: Block, b: Block) -> None:
        """Swap blocks a and b in the plus order only. O(1)."""
        i, j = self.pos_plus[a], self.pos_plus[b]  # @line L16
        self.plus[i], self.plus[j] = b, a
        self.pos_plus[a], self.pos_plus[b] = j, i

    def swap_in_both(self, a: Block, b: Block) -> None:
        """Swap blocks a and b in both orders. O(1)."""
        self.swap_in_plus(a, b)  # @line L17
        i, j = self.pos_minus[a], self.pos_minus[b]
        self.minus[i], self.minus[j] = b, a
        self.pos_minus[a], self.pos_minus[b] = j, i
test_sequence_pair.py 127 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sequence-pair/. The authors are listed in prov/9NWMQZ.jsonl.

import itertools
import math
import random

import pytest

from sequence_pair import SequencePair


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 rects(x, y, w, h):
    return {b: (x[b], y[b], x[b] + w[b], y[b] + h[b]) for b in x}


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

    A packing can be pushed left and down without growing, until every x is a
    sum of widths of other blocks and every y a sum of heights; so these
    positions are enough.
    """
    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 test_pinwheel_example() -> None:
    sp = SequencePair([5, 1, 3, 4, 2], [1, 2, 3, 5, 4])
    w = {1: 1, 2: 2, 3: 1, 4: 1, 5: 2}
    h = {1: 2, 2: 1, 3: 1, 4: 2, 5: 1}
    width, height, x, y = sp.pack(w, h)
    assert (width, height) == (3, 3)
    assert {b: (x[b], y[b]) for b in w} == {1: (0, 0), 2: (1, 0), 3: (1, 1), 4: (2, 1), 5: (0, 2)}
    assert sp.pack_by_graphs(w, h) == (width, height, x, y)
    assert sp.relation(1, 3) == "left" and sp.relation(2, 3) == "below" and sp.relation(5, 1) == "above"
    assert sp.relation(4, 5) == "right"


def test_bad_input_and_moves() -> None:
    with pytest.raises(ValueError):
        SequencePair([1, 2], [1, 3])
    sp = SequencePair([1, 2, 3], [3, 2, 1])
    sp.swap_in_plus(1, 3)
    assert sp.plus == [3, 2, 1]
    sp.check_invariant()
    sp.swap_in_both(1, 2)
    assert sp.plus == [3, 1, 2] and sp.minus == [3, 1, 2]
    sp.check_invariant()
    assert SequencePair([], []).pack({}, {}) == (0, 0, {}, {})


def test_random_against_graphs_and_no_overlap() -> None:
    rng = random.Random(11)
    for _ in range(800):
        n = rng.randint(1, 12)
        plus = list(range(n))
        minus = list(range(n))
        rng.shuffle(plus)
        rng.shuffle(minus)
        sp = SequencePair(plus, minus)
        w = {b: rng.randint(1, 9) for b in plus}
        h = {b: rng.randint(1, 9) for b in plus}
        res = sp.pack(w, h)
        assert res == sp.pack_by_graphs(w, h)
        width, height, x, y = res
        r = rects(x, y, w, h)
        for a, b in itertools.combinations(plus, 2):
            assert not overlap(r[a], r[b])
            rel = sp.relation(a, b)
            if rel == "left":
                assert r[a][2] <= r[b][0]
            elif rel == "right":
                assert r[b][2] <= r[a][0]
            elif rel == "below":
                assert r[a][3] <= r[b][1]
            else:
                assert r[b][3] <= r[a][1]
        assert width == max(q[2] for q in r.values()) and height == max(q[3] for q in r.values())


def test_count_and_best_over_all_pairs() -> None:
    rng = random.Random(12)
    for trial in range(40):
        n = 3 if trial < 25 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)}
        pairs = [(p, m) for p in itertools.permutations(range(n)) for m in itertools.permutations(range(n))]
        assert len(pairs) == math.factorial(n) ** 2
        best = None
        for p, m in pairs:
            width, height, _, _ = SequencePair(list(p), list(m)).pack(w, h)
            if best is None or width * height < best:
                best = width * height
        assert best == best_packing_area(w, h)

History

Murata, Fujiyoshi, Nakatake and Kajitani presented the sequence pair at ICCAD 1995 and in IEEE Transactions on CAD in 1996, with the gridding proof that every packing has a sequence pair and an annealing over pairs. Tang, Tian and Wong gave the O(nlog⁡n)O(n \log n) decoding by weighted longest common subsequences in 2000, and Tang and Wong the O(nlog⁡log⁡n)O(n \log \log n) decoding FAST-SP in 2001. Adya and Markov used sequence pairs for fixed-outline floorplanning in 2003.

References

  1. Hiroshi Murata, Kunihiro Fujiyoshi, Shigetoshi Nakatake and Yoji Kajitani, VLSI module placement based on rectangle-packing by the sequence-pair, IEEE Transactions on Computer-Aided Design of Integrated Circuits and Systems 15(12), 1518 to 1524, 1996, the definition of the sequence pair, the decoding by the horizontal and vertical constraint graphs, the gridding that gives a sequence pair for every packing, and the annealing over sequence pairs
  2. Hiroshi Murata, Kunihiro Fujiyoshi, Shigetoshi Nakatake and Yoji Kajitani, Rectangle-packing-based module placement, Proceedings of the IEEE/ACM International Conference on Computer-Aided Design, 472 to 479, 1995, the conference version
  3. Xiaoping Tang, Ruiqi Tian and D. F. Wong, Fast evaluation of sequence pair in block placement by longest common subsequence computation, Design, Automation and Test in Europe (DATE), 106 to 111, 2000, the O(n log n) decoding as a weighted longest common subsequence
  4. Xiaoping Tang and D. F. Wong, FAST-SP, a fast algorithm for block placement based on sequence pair, Asia and South Pacific Design Automation Conference (ASP-DAC), 521 to 526, 2001, the O(n log log n) decoding with a faster priority queue
  5. Saurabh N. Adya and Igor L. Markov, Fixed-outline floorplanning, enabling hierarchical design, IEEE Transactions on VLSI Systems 11(6), 1120 to 1135, 2003, annealing over sequence pairs with a fixed outline
  6. 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 (sequence pairs, from a floorplan to a sequence pair and back; 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/9NWMQZ/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/9NWMQZ/text.yaml