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
- Model
- Word RAM
- Properties
- deterministiciterative
- Evidence
- Full proofCode in 1 languages
- 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, for a vertical cut line and 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 blocks has tokens, and it can be checked, evaluated and normalized in 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 of blocks as a word . Each block of occurs one time, and the other tokens are the operators and . The operations are:
- VALID: tell whether is a normalized Polish expression.
- EVALUATE: given the width and the height of each block, return the width and the height of the floorplan and the lower-left corner of each block.
- NORMALIZE: given any Polish expression, return the normalized expression of the same floorplan.
- TO-TREE: return the slicing tree.
This page uses the convention that puts to the left of , and puts below . 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 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 or . This is reverse Polish notation for an expression tree with two operators. A word with operands and operators is a Polish expression exactly when it has the balloting property: each prefix has more operands than operators.
The two operators are associative on floorplans: and put , and 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
VALID(E, n) ▷ E = e_1 ... e_m- 1
if m ≠ 2n − 1 or the operands of E are not the n blocks, each one time then return false - 2
c ← 0 ▷ operands minus operators so far - 3
for k ← 1 to m do - 4
if e_k is an operand then c ← c + 1 - 5
else - 6
c ← c − 1 - 7
if c < 1 or e_{k−1} = e_k then return false - 8
return true EVALUATE(E, w, h) ▷ also TO-TREE, without the sizes- 9
S ← an empty stack - 10
for k ← 1 to 2n − 1 do - 11
if e_k is a block i then push the leaf i with W = w_i, H = h_i on S - 12
else pop b, then pop a, from S - 13
if e_k = V then W ← W_a + W_b, H ← max(H_a, H_b) - 14
else W ← max(W_a, W_b), H ← H_a + H_b - 15
push the node (e_k, a, b) with W and H on S - 16
r ← the only node in S; PLACE(r, 0, 0) - 17
return W_r, H_r and the corners PLACE(t, x, y)- 18
if t is a leaf i then (x_i, y_i) ← (x, y); return - 19
PLACE(a, x, y) ▷ a and b are the children of t - 20
if t has V then PLACE(b, x + W_a, y) else PLACE(b, x, y + H_a)
VALID counts operands minus operators in . The balloting property says that 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 and 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.
NORMALIZE(E) ▷ E is any Polish expression- 1
T ← the tree of E, built as in lines L9 to L15 - 2
return EMIT(the root of T) EMIT(t)- 3
if t is a leaf i then return the word i - 4
o ← the operator of t; c_1, ..., c_k ← the highest subtrees below t, left to right, whose roots are not o-nodes - 5
return 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 -nodes through . Line L25 writes the chain left-deep, so every right child in the new tree is a part , which is a leaf or carries the other operator.
Example
Take four blocks with the sizes , , and (width by height), and the word .
| the stack after the step (width by height) | |||
|---|---|---|---|
| 1 | 1 | 1 | |
| 2 | 2 | 2 | , |
| 3 | V | 1 | |
| 4 | 3 | 2 | , |
| 5 | 4 | 3 | , , |
| 6 | H | 2 | , |
| 7 | V | 1 |
The value never falls below 1, and the two operators at steps 6 and 7 differ, so VALID returns true. The floorplan is . PLACE puts block 1 at and block 2 at . The part starts at , so block 3 is at and block 4 is at , on top of block 3. The block area is of the 27 units of the floorplan.
The word is a Polish expression, but it is not normalized: the two are next to each other, because the second block group is the right child of a node. NORMALIZE turns it into , with the same three blocks side by side. On three blocks there are normalized expressions, and on four blocks .
Correctness
By the stack argument, a word with operands is a Polish expression if and only if it has 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 of normalized words, with the large Schröder numbers , 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 of blocks is a full binary tree whose leaves are the blocks, each one time, and whose internal nodes carry an operator or . 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 over in which each block occurs exactly one time is a Polish expression if and only if and every prefix has more operands than operators (the balloting property). The tree is then unique, and lines L9 to L15 build it.
Proof. Let be the number of operands minus the number of operators in . Lines L10 to L15 push one item for an operand and replace two items by one for an operator, so after step the stack holds items if no pop failed. A pop fails at step exactly when , that is when . So the loop runs to the end if and only if the balloting property holds, and then the stack holds items. With operands, if and only if there are operators, that is . In that case the single item is a full binary tree whose postorder is , by induction on : each stack item is a tree whose postorder is a factor of , and these factors in stack order make up .
Conversely, the postorder of a full binary tree with leaves has tokens, and each prefix is the postorder of a forest of trees followed by nothing, so it has 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.
Lemma 2 (right children in postorder). Let be an internal node of a full binary tree, at position of the postorder. Then is the right child of .
Proof. The postorder of the subtree of is the postorder of the left subtree, then the postorder of the right subtree, then . The last token of the postorder of a subtree is its root.
Theorem 1 (VALID). VALID returns true if and only if is the postorder of a skewed slicing tree on . 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 . Lines L2 to L7 compute and stop if after an operator. Before the first operator , so the loop checks the balloting property; by Lemma 1, passes these tests if and only if it is a Polish expression of a unique tree . Line L7 also rejects if two equal operators are next to each other. If and are both operators, then by Lemma 2 the node is an internal right child of . If is an operand, the right child of is a leaf. So has two equal operators next to each other if and only if some internal node of has an internal right child with the same operator, that is if and only if is not skewed. The map is one to one by the uniqueness in Lemma 1, and onto by this equivalence.
Lemma 3 (EVALUATE). EVALUATE returns the width and the height of the floorplan of and a placement of the blocks without overlap inside the rectangle, in which each block is at the lower-left corner of its room.
Proof. By Lemma 1, the stack loop builds . By induction on the height of a node , the values and of lines L13 and L14 are the width and height of the smallest rectangle that holds the floorplan of the subtree of : 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 the rectangle . For a node it gives the left part and the right part , which are inside the rectangle of and are separated by the line . The case is the same with the roles of and 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.
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 inside the tree.
Proof. For a node with operator , line L24 collects the maximal subtrees below that are reached through -nodes only and whose roots are leaves or nodes with the other operator. The subtree of puts side by side in this order (for ) or on top of each other in this order (for ), whatever the shape of the -chain, because the operator is associative on rectangles: both sides of the associative law have width , height and the same order of parts, and the same for . Line L25 emits the left-deep chain . In this chain every right child is some , which is a leaf or has the other operator. By induction on the subtrees, each 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 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.
Theorem 2 (counts). The number of normalized Polish expressions on blocks is , where is the th large Schröder number for .
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 leaves and no node with one child. The number of these shapes is the little Schröder number for , and for (OEIS A001003 and A006318, which list this interpretation). With the orders of the leaves, the count is . The tests check the values for against all words.
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 nodes one time. NORMALIZE builds the tree in time and visits each node a constant number of times. So each operation takes time and space.
Complexity
| operation | time | extra space |
|---|---|---|
| VALID | , a set of the operands seen | |
| EVALUATE | , the stack and the tree | |
| NORMALIZE | ||
| TO-TREE |
The word itself takes tokens. With bits for each block name and one bit for each operator, a slicing floorplan of blocks needs about bits. The number of normalized words is , and , so the word is optimal up to the 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 parts has 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 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 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 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 and , 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 blocks gives a tree of depth . 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 , 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.
# 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
- 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
- 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
- Ralph H. J. M. Otten, Automatic floorplan design, Proceedings of the 19th Design Automation Conference, 261 to 267, 1982, slicing structures and their trees
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H2 full proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 77DCRE Edit this page History Report an error Markdown