Algorithm Search⌘K

Data structurecore

Normalized Polish expression

Also called Polish expression floorplan.

Wong and Liu's postfix word of blocks and cut operators H and V with no repeated operator in a row, which stands one to one for slicing floorplans.

Time
O(n) worst · average · best
Space
O(n) extra
Where
n = the number of blocks
Properties
deterministiciterative
Origin
D. F. Wong, C. L. Liu, 1986

A normalized Polish expression is a word that stores a slicing floorplan. It is the postorder of the slicing tree: each block is an operand, and each cut is an operator, VV for a vertical cut line and HH for a horizontal one. Wong and Liu added one rule in 1986: no two equal operators may stand next to each other. With this rule each slicing floorplan has exactly one word, so a search over the words, such as Wong-Liu floorplanning, does not visit the same floorplan twice. A word of nn blocks has 2n−12n - 1 tokens, and it can be checked, evaluated and normalized in O(n)O(n) time.

In plain words

Write a floorplan the way a calculator with a stack reads a sum. A block name means "put this block on the stack". The letter V means "take the last two parts and put them side by side". The letter H means "take the last two parts and put the first one under the second one". At the end, one part is left, and it is the whole floorplan.

Three blocks in a row can be written in two ways: first join the first two, or first join the last two. The picture is the same. The rule "never two equal letters in a row" keeps only the first way, so each picture has exactly one word.

The abstract type

The type stores a slicing floorplan of a set BB of nn blocks as a word E=e1e2⋯e2n−1E = e_1 e_2 \cdots e_{2n-1}. Each block of BB occurs one time, and the other n−1n - 1 tokens are the operators HH and VV. The operations are:

  • VALID(E)(E): tell whether EE is a normalized Polish expression.
  • EVALUATE(E,w,h)(E, w, h): given the width wiw_i and the height hih_i of each block, return the width WW and the height HH of the floorplan and the lower-left corner of each block.
  • NORMALIZE(E)(E): given any Polish expression, return the normalized expression of the same floorplan.
  • TO-TREE(E)(E): return the slicing tree.

This page uses the convention that E1E2VE_1 E_2 V puts E1E_1 to the left of E2E_2, and E1E2HE_1 E_2 H puts E1E_1 below E2E_2. Wong and Liu write ∗* and ++ for the two operators, and books do not agree on which operand of a horizontal cut goes on top. The structure is the same in all conventions.

Representation

The word is an array of 2n−12n - 1 tokens. A Polish expression is the postorder of a slicing tree, a full binary tree whose leaves are the blocks and whose internal nodes carry HH or VV. This is reverse Polish notation for an expression tree with two operators. A word with nn operands and n−1n - 1 operators is a Polish expression exactly when it has the balloting property: each prefix e1⋯eke_1 \cdots e_k has more operands than operators.

The two operators are associative on floorplans: (a b V) c V(a\,b\,V)\,c\,V and a (b c V) Va\,(b\,c\,V)\,V put aa, bb and cc side by side in the same order. So a floorplan with a chain of three or more parts in one direction has several Polish expressions. A slicing tree is skewed if no right child has the same operator as its parent. A Polish expression is normalized if it has no two equal operators next to each other. In a postorder, an operator that comes just before another operator is the right child of that operator, so the normalized expressions are exactly the postorders of the skewed trees. Each floorplan has one skewed tree: its chains are written left-deep.

Operations

  1. VALID(E, n) ▷ E = e_1 ... e_m
  2. 1if m ≠ 2n − 1 or the operands of E are not the n blocks, each one time then return false
  3. 2c ← 0 ▷ operands minus operators so far
  4. 3for k ← 1 to m do
  5. 4if e_k is an operand then c ← c + 1
  6. 5else
  7. 6c ← c − 1
  8. 7if c < 1 or e_{k−1} = e_k then return false
  9. 8return true
  10. EVALUATE(E, w, h) ▷ also TO-TREE, without the sizes
  11. 9S ← an empty stack
  12. 10for k ← 1 to 2n − 1 do
  13. 11if e_k is a block i then push the leaf i with W = w_i, H = h_i on S
  14. 12else pop b, then pop a, from S
  15. 13if e_k = V then W ← W_a + W_b, H ← max(H_a, H_b)
  16. 14else W ← max(W_a, W_b), H ← H_a + H_b
  17. 15push the node (e_k, a, b) with W and H on S
  18. 16r ← the only node in S; PLACE(r, 0, 0)
  19. 17return W_r, H_r and the corners
  20. PLACE(t, x, y)
  21. 18if t is a leaf i then (x_i, y_i) ← (x, y); return
  22. 19PLACE(a, x, y) ▷ a and b are the children of t
  23. 20if t has V then PLACE(b, x + W_a, y) else PLACE(b, x, y + H_a)

VALID counts operands minus operators in cc. The balloting property says that c≥1c \ge 1 after each token, and line L7 checks this after each operator. The same line rejects two equal operators in a row. EVALUATE is the stack evaluation of a postfix word. The values WW and HH of a node are the size of the smallest rectangle that holds its part of the floorplan. PLACE then goes down the tree and gives each part its corner.

  1. NORMALIZE(E) ▷ E is any Polish expression
  2. 1T ← the tree of E, built as in lines L9 to L15
  3. 2return EMIT(the root of T)
  4. EMIT(t)
  5. 3if t is a leaf i then return the word i
  6. 4o ← the operator of t; c_1, ..., c_k ← the highest subtrees below t, left to right, whose roots are not o-nodes
  7. 5return EMIT(c_1) EMIT(c_2) o EMIT(c_3) o ... EMIT(c_k) o

Line L24 collects the parts of the maximal chain of oo-nodes through tt. Line L25 writes the chain left-deep, so every right child in the new tree is a part cic_i, which is a leaf or carries the other operator.

Example

Take four blocks with the sizes 1:2×31: 2 \times 3, 2:3×22: 3 \times 2, 3:4×13: 4 \times 1 and 4:2×24: 2 \times 2 (width by height), and the word E=1 2 V 3 4 H VE = 1\,2\,V\,3\,4\,H\,V.

kk eke_k cc the stack after the step (width by height)
1 1 1 1: 2×31{:}\,2 \times 3
2 2 2 2×32 \times 3, 2: 3×22{:}\,3 \times 2
3 V 1 (1 2 V): 5×3(1\,2\,V){:}\,5 \times 3
4 3 2 5×35 \times 3, 3: 4×13{:}\,4 \times 1
5 4 3 5×35 \times 3, 4×14 \times 1, 4: 2×24{:}\,2 \times 2
6 H 2 5×35 \times 3, (3 4 H): 4×3(3\,4\,H){:}\,4 \times 3
7 V 1 (1 2 V 3 4 H V): 9×3(1\,2\,V\,3\,4\,H\,V){:}\,9 \times 3

The value cc never falls below 1, and the two operators at steps 6 and 7 differ, so VALID returns true. The floorplan is 9×39 \times 3. PLACE puts block 1 at (0,0)(0, 0) and block 2 at (2,0)(2, 0). The part 3 4 H3\,4\,H starts at x=5x = 5, so block 3 is at (5,0)(5, 0) and block 4 is at (5,1)(5, 1), on top of block 3. The block area is 6+6+4+4=206 + 6 + 4 + 4 = 20 of the 27 units of the floorplan.

The word 1 2 3 V V1\,2\,3\,V\,V is a Polish expression, but it is not normalized: the two VV are next to each other, because the second block group 2 3 V2\,3\,V is the right child of a VV node. NORMALIZE turns it into 1 2 V 3 V1\,2\,V\,3\,V, with the same three blocks side by side. On three blocks there are 3!⋅6=363! \cdot 6 = 36 normalized expressions, and on four blocks 4!⋅22=5284! \cdot 22 = 528.

Correctness

By the stack argument, a word with nn operands is a Polish expression if and only if it has 2n−12n - 1 tokens and the balloting property, and the tree is unique. In a postorder, the token just before an internal node is the root of its right subtree. So two operators next to each other are a node and its internal right child, and VALID accepts exactly the postorders of skewed slicing trees. EVALUATE is correct by induction on the tree: a vertical cut adds the widths and takes the larger height, a horizontal cut does the opposite, and PLACE gives the two parts disjoint rectangles on the two sides of the cut. NORMALIZE keeps the floorplan because the operators are associative, and it returns a skewed tree. Two Polish expressions have the same normalized form exactly when they differ by the associative law. The count n! Sn−1n!\,S_{n-1} of normalized words, with the large Schröder numbers Sk=1,2,6,22,90,394S_k = 1, 2, 6, 22, 90, 394, follows from this. The full proof is in the correctness proof.

Proof: Normalized Polish expressions are exactly the postorders of skewed slicing treesfull

We use the pseudocode and the conventions of the page. A slicing tree on a set BB of nn blocks is a full binary tree whose leaves are the blocks, each one time, and whose internal nodes carry an operator HH or VV. It is skewed if no internal node has a right child that is an internal node with the same operator. A Polish expression is a word that is the postorder of some slicing tree.

Lemma 1 (Polish expressions). A word E=e1⋯emE = e_1 \cdots e_m over B∪{H,V}B \cup \{H, V\} in which each block occurs exactly one time is a Polish expression if and only if m=2n−1m = 2n - 1 and every prefix e1⋯eke_1 \cdots e_k has more operands than operators (the balloting property). The tree is then unique, and lines L9 to L15 build it.

Proof. Let ckc_k be the number of operands minus the number of operators in e1⋯eke_1 \cdots e_k. Lines L10 to L15 push one item for an operand and replace two items by one for an operator, so after step kk the stack holds ckc_k items if no pop failed. A pop fails at step kk exactly when ck−1<2c_{k-1} < 2, that is when ck<1c_k < 1. So the loop runs to the end if and only if the balloting property holds, and then the stack holds cmc_m items. With nn operands, cm=1c_m = 1 if and only if there are n−1n - 1 operators, that is m=2n−1m = 2n - 1. In that case the single item is a full binary tree whose postorder is EE, by induction on kk: each stack item is a tree whose postorder is a factor of EE, and these factors in stack order make up e1⋯eke_1 \cdots e_k.

Conversely, the postorder of a full binary tree with nn leaves has 2n−12n - 1 tokens, and each prefix is the postorder of a forest of j≥1j \ge 1 trees followed by nothing, so it has jj more operands than operators. The tree of a Polish expression is unique, because the stack procedure is forced: the last token is the root, and the run of the stack decides the two subtrees. □\square

Lemma 2 (right children in postorder). Let uu be an internal node of a full binary tree, at position kk of the postorder. Then ek−1e_{k-1} is the right child of uu.

Proof. The postorder of the subtree of uu is the postorder of the left subtree, then the postorder of the right subtree, then uu. The last token of the postorder of a subtree is its root. □\square

Theorem 1 (VALID). VALID returns true if and only if EE is the postorder of a skewed slicing tree on BB. Hence the map from skewed slicing trees to their postorders is a bijection onto the normalized Polish expressions.

Proof. Line L1 checks that the operands are the blocks, each one time, and that m=2n−1m = 2n - 1. Lines L2 to L7 compute ckc_k and stop if ck<1c_k < 1 after an operator. Before the first operator ck≥1c_k \ge 1, so the loop checks the balloting property; by Lemma 1, EE passes these tests if and only if it is a Polish expression of a unique tree TT. Line L7 also rejects EE if two equal operators are next to each other. If ek−1e_{k-1} and eke_k are both operators, then by Lemma 2 the node ek−1e_{k-1} is an internal right child of eke_k. If ek−1e_{k-1} is an operand, the right child of eke_k is a leaf. So EE has two equal operators next to each other if and only if some internal node of TT has an internal right child with the same operator, that is if and only if TT is not skewed. The map is one to one by the uniqueness in Lemma 1, and onto by this equivalence. □\square

Lemma 3 (EVALUATE). EVALUATE returns the width and the height of the floorplan of TT and a placement of the blocks without overlap inside the W×HW \times H rectangle, in which each block is at the lower-left corner of its room.

Proof. By Lemma 1, the stack loop builds TT. By induction on the height of a node tt, the values WtW_t and HtH_t of lines L13 and L14 are the width and height of the smallest rectangle that holds the floorplan of the subtree of tt: a vertical cut puts the two parts side by side, so the widths add and the height is the larger height; a horizontal cut puts the first part below the second, and the roles change. PLACE gives the subtree of tt the rectangle [x,x+Wt)×[y,y+Ht)[x, x + W_t) \times [y, y + H_t). For a VV node it gives the left part [x,x+Wa)×[y,y+Ha)[x, x + W_a) \times [y, y + H_a) and the right part [x+Wa,x+Wa+Wb)×[y,y+Hb)[x + W_a, x + W_a + W_b) \times [y, y + H_b), which are inside the rectangle of tt and are separated by the line X=x+WaX = x + W_a. The HH case is the same with the roles of xx and yy changed. So by induction each block gets a rectangle inside the room of its leaf, the rooms of two different leaves are separated by the cut of their lowest common ancestor, and no two blocks overlap. □\square

Lemma 4 (NORMALIZE). NORMALIZE returns a normalized Polish expression whose floorplan is the floorplan of the input, and two Polish expressions have the same normalized form if and only if one can be changed into the other by the associative law (a o b) o c=a o (b o c)(a\,o\,b)\,o\,c = a\,o\,(b\,o\,c) inside the tree.

Proof. For a node tt with operator oo, line L24 collects the maximal subtrees c1,…,ckc_1, \ldots, c_k below tt that are reached through oo-nodes only and whose roots are leaves or nodes with the other operator. The subtree of tt puts c1,…,ckc_1, \ldots, c_k side by side in this order (for VV) or on top of each other in this order (for HH), whatever the shape of the oo-chain, because the operator is associative on rectangles: both sides of the associative law have width Wa+Wb+WcW_a + W_b + W_c, height max⁡(Ha,Hb,Hc)\max(H_a, H_b, H_c) and the same order of parts, and the same for HH. Line L25 emits the left-deep chain ((c1 o c2) o c3)⋯o ck((c_1\,o\,c_2)\,o\,c_3) \cdots o\,c_k. In this chain every right child is some cic_i, which is a leaf or has the other operator. By induction on the subtrees, each cic_i is emitted in normalized form, so the whole tree is skewed and its postorder is normalized by Theorem 1. The floorplan is the same by associativity, applied inside each chain.

The ordered list c1,…,ckc_1, \ldots, c_k of each maximal chain does not change under the associative law, and two trees with the same chains at every level are related by the associative law, because both can be brought to the left-deep form. So the normalized form is the same exactly for associatively equal trees. □\square

Theorem 2 (counts). The number of normalized Polish expressions on nn blocks is n! Sn−1n!\,S_{n-1}, where SkS_k is the kkth large Schröder number 1,2,6,22,90,394,…1, 2, 6, 22, 90, 394, \ldots for k=0,1,2,…k = 0, 1, 2, \ldots.

Proof. By Theorem 1 and Lemma 4, normalized expressions with a fixed left to right order of the leaves are in bijection with the ordered trees in which every internal node has at least two children, the leaves are the blocks in this order, and the internal nodes carry operators that alternate between a node and its internal children. Such a tree is fixed by its shape and the operator of the root, and the shape is a plane tree with nn leaves and no node with one child. The number of these shapes is the little Schröder number sn=1,1,3,11,45,197s_n = 1, 1, 3, 11, 45, 197 for n=1,…,6n = 1, \ldots, 6, and Sn−1=2snS_{n-1} = 2 s_n for n≥2n \ge 2 (OEIS A001003 and A006318, which list this interpretation). With the n!n! orders of the leaves, the count is n! Sn−1n!\,S_{n-1}. The tests check the values 1,4,36,528,108001, 4, 36, 528, 10800 for n≤5n \le 5 against all words. □\square

Complexity. VALID reads each token one time. EVALUATE does one push for each operand, one pair of pops and one push for each operator, and PLACE visits each of the 2n−12n - 1 nodes one time. NORMALIZE builds the tree in O(n)O(n) time and visits each node a constant number of times. So each operation takes O(n)O(n) time and O(n)O(n) space. ■\blacksquare

Complexity

operation time extra space
VALID O(n)O(n) O(n)O(n), a set of the operands seen
EVALUATE O(n)O(n) O(n)O(n), the stack and the tree
NORMALIZE O(n)O(n) O(n)O(n)
TO-TREE O(n)O(n) O(n)O(n)

The word itself takes 2n−12n - 1 tokens. With ⌈lg⁡n⌉\lceil \lg n \rceil bits for each block name and one bit for each operator, a slicing floorplan of nn blocks needs about nlg⁡n+3nn \lg n + 3n bits. The number of normalized words is n! Sn−1n!\,S_{n-1}, and lg⁡Sn−1=Θ(n)\lg S_{n-1} = \Theta(n), so the word is optimal up to the O(n)O(n) term. The bound is on the word RAM with the block sizes as integers that fit in a word.

Variants

  • Plain Polish expressions. Without the normalization rule a floorplan with a chain of kk parts has Ck−1C_{k-1} words, a Catalan number. Otten's slicing trees are of this kind. A search over them visits the same floorplan many times.
  • Right-deep chains. One can also write every chain right-deep. Then the rule becomes "no left child with the operator of its parent". Both normal forms are in use.
  • Shapes and orientations. If each block has several allowed shapes, EVALUATE carries a shape function instead of one size at each node. Stockmeyer's floorplan sizing does this for the least area.
  • Moves. Wong and Liu change a word by three moves: swap two neighbouring operands (M1), change every operator in a run of operators to the other one (M2), and swap a neighbouring operand and operator (M3) when the result is still normalized. The moves are on the page of Wong-Liu floorplanning.
  • L-shaped blocks. The journal version of Wong and Liu adds operators for L-shaped blocks.
  • Non-slicing floorplans. A Polish expression cannot store a pinwheel of five blocks. The sequence pair, the B*-tree and the O-tree store packings that are not slicing.

When to use it

Use a normalized Polish expression when the floorplans are slicing, as in many hierarchical flows, and when a search changes the floorplan many times. Each word is a different floorplan, the moves are simple, and evaluation with shape functions gives the best sizes of soft blocks. If the best packing may be non-slicing, use a sequence pair or a B*-tree.

Pitfalls

  • Which operand goes on top. The meaning of HH differs between sources. Fix one convention and use it in the evaluation and in the moves.
  • A swap that breaks the balloting property. Swapping an operand with the operator after it reduces the operand count of that prefix by one. Check c≥1c \ge 1 again, and check the two new neighbours of the operator, or the word stops being a normalized expression.
  • Normalization is not checked by the stack. The stack evaluation of 1 2 3 V V1\,2\,3\,V\,V works. A search that does not call VALID can count one floorplan many times.
  • Crossing cuts. Two cut lines that cross at one point give two different words, for example 1 2 H 3 4 H V1\,2\,H\,3\,4\,H\,V and 1 3 V 2 4 V H1\,3\,V\,2\,4\,V\,H, if the parts have the same sizes. The structure regards them as two floorplans, because the cut lines can slide apart.
  • Deep recursion. A left-deep chain of nn blocks gives a tree of depth nn. Write PLACE with an explicit stack.

Implementations

The Python class stores the word as a list of ints and the strings "H" and "V". It checks the word, evaluates it with a stack and an explicit stack for PLACE, returns the slicing tree, and normalizes any Polish expression. The tests check every word of up to five blocks against the set of postorders of all skewed slicing trees, the counts 1,4,36,528,108001, 4, 36, 528, 10800, the evaluation of every slicing tree of up to five blocks against a recursive evaluation, and 600 random trees of up to 40 blocks for the absence of overlap.

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.

normalized_polish_expression.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/normalized-polish-expression/. The authors are listed in prov/77DCRE.jsonl.

"""Normalized Polish expressions of slicing floorplans (Wong and Liu, 1986).

A token is an operand (a block, any int) or an operator, the string "H" or
"V". The convention of this module:

- ``a b V``: a is to the left of b (a vertical cut line). The width is the sum
  of the widths and the height is the larger height.
- ``a b H``: a is below b (a horizontal cut line). The width is the larger
  width and the height is the sum of the heights.

A Polish expression is the postorder of a slicing tree. It is normalized if no
two equal operators are next to each other. Normalized expressions and skewed
slicing trees (no right child with the operator of its parent) are in one to
one correspondence.
"""

from typing import Union

Token = Union[int, str]
Tree = Union[int, tuple]  # a leaf is an int, a node is (op, left, right)
OPERATORS = ("H", "V")


def is_operator(t: Token) -> bool:
    """Return True if t is one of the cut operators "H" and "V"."""
    return t == "H" or t == "V"


def is_normalized(tokens: list[Token], blocks: set[int] | None = None) -> bool:
    """Return True if tokens is a normalized Polish expression.

    If blocks is given, the operands must be exactly these blocks, each one
    time. Otherwise each operand must occur one time.
    """
    operands = [t for t in tokens if not is_operator(t)]
    n = len(operands)
    if n == 0 or len(tokens) != 2 * n - 1 or len(set(operands)) != n:  # @line L1
        return False
    if blocks is not None and set(operands) != set(blocks):
        return False
    c = 0  # @line L2
    for k, t in enumerate(tokens):  # @line L3
        if not is_operator(t):  # @line L4
            c += 1
        else:  # @line L5
            c -= 1  # @line L6
            if c < 1 or tokens[k - 1] == t:  # @line L7
                return False
    return True  # @line L8


def _build(tokens: list[Token], sizes: dict[int, tuple[int, int]] | None) -> list:
    """Build the slicing tree of a Polish expression with a stack.

    A node is a list [op, left, right, width, height]; a leaf is
    [block, None, None, width, height]. Sizes may be None (then 0 by 0).
    """
    stack: list[list] = []  # @line L9
    for t in tokens:  # @line L10
        if not is_operator(t):  # @line L11
            w, h = sizes[t] if sizes is not None else (0, 0)
            stack.append([t, None, None, w, h])
        else:
            if len(stack) < 2:
                raise ValueError("not a Polish expression")
            b = stack.pop()  # @line L12
            a = stack.pop()
            if t == "V":  # @line L13
                w, h = a[3] + b[3], max(a[4], b[4])
            else:  # @line L14
                w, h = max(a[3], b[3]), a[4] + b[4]
            stack.append([t, a, b, w, h])  # @line L15
    if len(stack) != 1:
        raise ValueError("not a Polish expression")
    return stack[0]


class NormalizedPolishExpression:
    """A normalized Polish expression, stored as a list of tokens."""

    def __init__(self, tokens: list[Token]) -> None:
        """Store a copy of tokens. Raise ValueError if they are not normalized."""
        if not is_normalized(tokens):
            raise ValueError("not a normalized Polish expression")
        self.tokens: list[Token] = list(tokens)

    def check_invariant(self) -> None:
        """Raise AssertionError if the stored word is not normalized."""
        assert is_normalized(self.tokens)

    def blocks(self) -> list[int]:
        """Return the operands in the order of the word."""
        return [t for t in self.tokens if not is_operator(t)]

    def evaluate(
        self, sizes: dict[int, tuple[int, int]]
    ) -> tuple[int, int, dict[int, tuple[int, int]]]:
        """Return (W, H, pos): the size of the floorplan and the lower-left corner of each block.

        sizes[b] = (w, h). Each block sits at the lower-left corner of its room.
        Time O(n).
        """
        root = _build(self.tokens, sizes)
        pos: dict[int, tuple[int, int]] = {}
        todo = [(root, 0, 0)]  # @line L16
        while todo:
            t, x, y = todo.pop()
            if t[1] is None:  # @line L18
                pos[t[0]] = (x, y)
                continue
            a, b = t[1], t[2]
            todo.append((a, x, y))  # @line L19
            if t[0] == "V":  # @line L20
                todo.append((b, x + a[3], y))
            else:
                todo.append((b, x, y + a[4]))
        return root[3], root[4], pos  # @line L17

    def to_tree(self) -> Tree:
        """Return the skewed slicing tree as nested tuples (op, left, right)."""
        return _as_tuple(_build(self.tokens, None))

    @staticmethod
    def normalize(tokens: list[Token]) -> "NormalizedPolishExpression":
        """Return the normalized expression of the floorplan of any Polish expression.

        Each maximal chain of equal operators is rebuilt as a left-deep chain,
        which keeps the left to right (or bottom to top) order of its parts, so
        the floorplan does not change. Time O(n).
        """
        root = _build(tokens, None)  # @line L21
        out: list[Token] = []
        work: list = [("emit", root)]  # @line L22
        while work:
            kind, t = work.pop()
            if kind == "op":
                out.append(t)
                continue
            if t[1] is None:  # @line L23
                out.append(t[0])
                continue
            o = t[0]
            parts: list = []  # @line L24
            chain = [t]
            while chain:
                u = chain.pop()
                if u[1] is not None and u[0] == o:
                    chain.append(u[2])
                    chain.append(u[1])
                else:
                    parts.append(u)
            seq: list = [("emit", parts[0]), ("emit", parts[1]), ("op", o)]  # @line L25
            for p in parts[2:]:
                seq.append(("emit", p))
                seq.append(("op", o))
            work.extend(reversed(seq))
        return NormalizedPolishExpression(out)

    @staticmethod
    def from_tree(tree: Tree) -> "NormalizedPolishExpression":
        """Return the normalized expression of the floorplan of a slicing tree."""
        return NormalizedPolishExpression.normalize(postorder(tree))


def _as_tuple(t: list) -> Tree:
    """Turn the list nodes of _build into nested tuples."""
    if t[1] is None:
        return t[0]
    return (t[0], _as_tuple(t[1]), _as_tuple(t[2]))


def postorder(tree: Tree) -> list[Token]:
    """Return the postorder word (Polish expression) of a slicing tree."""
    if not isinstance(tree, tuple):
        return [tree]
    op, a, b = tree
    return postorder(a) + postorder(b) + [op]
test_normalized_polish_expression.py 171 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/normalized-polish-expression/. The authors are listed in prov/77DCRE.jsonl.

import itertools
import random

import pytest

from normalized_polish_expression import (
    NormalizedPolishExpression,
    is_normalized,
    postorder,
)

SCHROEDER = [1, 2, 6, 22, 90, 394]  # large Schroeder numbers S_0 .. S_5


def shapes(n: int) -> list:
    """All full binary tree shapes with n leaves; a leaf is None."""
    if n == 1:
        return [None]
    out = []
    for k in range(1, n):
        for a in shapes(k):
            for b in shapes(n - k):
                out.append((a, b))
    return out


def label(shape, leaves, ops):
    """Put the leaves (in order) and the operators (in preorder) on a shape."""
    li = iter(leaves)
    oi = iter(ops)

    def rec(s):
        if s is None:
            return next(li)
        o = next(oi)
        return (o, rec(s[0]), rec(s[1]))

    return rec(shape)


def all_trees(n: int) -> list:
    """All slicing trees with leaves 1..n (each shape, leaf order and operators)."""
    out = []
    for s in shapes(n):
        for perm in itertools.permutations(range(1, n + 1)):
            for ops in itertools.product("HV", repeat=n - 1):
                out.append(label(s, perm, ops))
    return out


def skewed(t) -> bool:
    """True if no right child has the operator of its parent."""
    if not isinstance(t, tuple):
        return True
    o, a, b = t
    if isinstance(b, tuple) and b[0] == o:
        return False
    return skewed(a) and skewed(b)


def tree_eval(t, sizes, x=0, y=0, pos=None):
    """Recursive reference evaluation of a slicing tree."""
    if pos is None:
        pos = {}
    if not isinstance(t, tuple):
        pos[t] = (x, y)
        return sizes[t][0], sizes[t][1], pos
    o, a, b = t
    wa, ha, _ = tree_eval(a, sizes, x, y, pos)
    if o == "V":
        wb, hb, _ = tree_eval(b, sizes, x + wa, y, pos)
        return wa + wb, max(ha, hb), pos
    wb, hb, _ = tree_eval(b, sizes, x, y + ha, pos)
    return max(wa, wb), ha + hb, pos


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


def test_example() -> None:
    e = NormalizedPolishExpression([1, 2, "V", 3, 4, "H", "V"])
    sizes = {1: (2, 3), 2: (3, 2), 3: (4, 1), 4: (2, 2)}
    w, h, pos = e.evaluate(sizes)
    assert (w, h) == (9, 3)
    assert pos == {1: (0, 0), 2: (2, 0), 3: (5, 0), 4: (5, 1)}
    assert e.to_tree() == ("V", ("V", 1, 2), ("H", 3, 4))


def test_validity_examples() -> None:
    assert is_normalized([1, 2, "V", 3, "V"])
    assert not is_normalized([1, 2, 3, "V", "V"])  # two V in a row
    assert not is_normalized([1, "V", 2])  # balloting fails
    assert not is_normalized([1, 2, "V", 1, "H"])  # repeated operand
    assert not is_normalized([1, 2])  # too few operators
    assert not is_normalized([])
    assert is_normalized([7])
    assert NormalizedPolishExpression.normalize([1, 2, 3, "V", "V"]).tokens == [1, 2, "V", 3, "V"]
    with pytest.raises(ValueError):
        NormalizedPolishExpression([1, 2, 3, "H", "H"])


def test_counts_and_validity_against_all_words() -> None:
    import math

    for n in range(1, 6):
        trees = all_trees(n)
        skew_words = {tuple(postorder(t)) for t in trees if skewed(t)}
        assert len(skew_words) == math.factorial(n) * SCHROEDER[n - 1]
        # Every word with operands 1..n once and n - 1 operators.
        found = set()
        for opos in itertools.combinations(range(2 * n - 1), n - 1):
            for perm in itertools.permutations(range(1, n + 1)):
                for ops in itertools.product("HV", repeat=n - 1):
                    w: list = [None] * (2 * n - 1)
                    for p, o in zip(opos, ops):
                        w[p] = o
                    it = iter(perm)
                    for i in range(2 * n - 1):
                        if w[i] is None:
                            w[i] = next(it)
                    if is_normalized(w):
                        found.add(tuple(w))
        assert found == skew_words


def test_tree_round_trip_and_normalize() -> None:
    rng = random.Random(1)
    for n in range(1, 6):
        trees = all_trees(n)
        classes = set()
        for t in trees:
            sizes = {b: (rng.randint(1, 9), rng.randint(1, 9)) for b in range(1, n + 1)}
            e = NormalizedPolishExpression.from_tree(t)
            e.check_invariant()
            classes.add(tuple(e.tokens))
            assert tree_eval(t, sizes) == e.evaluate(sizes)
            if skewed(t):
                assert e.tokens == postorder(t)
                assert e.to_tree() == t
        assert len(classes) == len({tuple(postorder(t)) for t in trees if skewed(t)})


def random_tree(rng: random.Random, leaves: list[int]):
    if len(leaves) == 1:
        return leaves[0]
    k = rng.randint(1, len(leaves) - 1)
    return (rng.choice("HV"), random_tree(rng, leaves[:k]), random_tree(rng, leaves[k:]))


def test_random_large_no_overlap() -> None:
    rng = random.Random(2)
    for _ in range(600):
        n = rng.randint(1, 40)
        leaves = list(range(n))
        rng.shuffle(leaves)
        t = random_tree(rng, leaves)
        sizes = {b: (rng.randint(1, 20), rng.randint(1, 20)) for b in leaves}
        e = NormalizedPolishExpression.from_tree(t)
        w, h, pos = e.evaluate(sizes)
        assert (w, h, pos) == tree_eval(t, sizes)
        rects = [(pos[b][0], pos[b][1], pos[b][0] + sizes[b][0], pos[b][1] + sizes[b][1]) for b in leaves]
        for r in rects:
            assert 0 <= r[0] and 0 <= r[1] and r[2] <= w and r[3] <= h
        for i in range(n):
            for j in range(i + 1, n):
                assert not overlap(rects[i], rects[j])
        assert w * h >= sum(a * b for a, b in sizes.values())

History

Polish notation is the work of Jan Łukasiewicz in the 1920s, and the postfix form is reverse Polish notation. Otten described slicing structures and their trees for floorplan design in 1982. Wong and Liu introduced normalized Polish expressions in 1986, together with an annealing algorithm that searches over them, and extended them to L-shaped blocks in the 1989 journal version.

References

  1. D. F. Wong and C. L. Liu, A new algorithm for floorplan design, Proceedings of the 23rd ACM/IEEE Design Automation Conference, 101 to 107, 1986, the definition of Polish and normalized Polish expressions, the balloting property, the one to one correspondence with skewed slicing trees, and the moves M1, M2 and M3
  2. D. F. Wong and C. L. Liu, Floorplan design of VLSI circuits, Algorithmica 4, 263 to 291, 1989, the journal version, with normalized Polish expressions and the extension to L-shaped blocks
  3. Ralph H. J. M. Otten, Automatic floorplan design, Proceedings of the 19th Design Automation Conference, 261 to 267, 1982, slicing structures and their trees
  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 and Polish expressions; 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/77DCRE/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/77DCRE/text.yaml