Algorithm Search⌘K

Algorithmadvanced

Symmetric-feasible sequence pair

Also called Balasa-Lampaert symmetric placement.

Balasa and Lampaert's condition on a sequence pair under which a symmetric packing exists, letting annealing search only placements that meet symmetry constraints.

Time
O(n) check · repairO(n^2) relations_and_y
Space
O(n^2) extra
Where
g = the number of cells in the symmetric set; n = the number of cells
Properties
deterministiciterative
Origin
Florin Balasa, Koen Lampaert, 2000

A symmetric-feasible sequence pair is a sequence pair whose two orders treat a symmetric set the same way as its mirror image does, so that the packing can place the group mirror-symmetric about one vertical axis. Its topic is analog sizing and layout, one of the five topics of this sub-area. Balasa and Lampaert gave the condition in 2000 and proved that every such pair has a symmetric placement. The condition is cheap to test and to restore after a move, so an annealing placer can search only these pairs, and every pair it sees meets the symmetry constraint.

In plain words

A sequence pair is two lists of the blocks. Two blocks in the same order in both lists sit side by side; two blocks in opposite orders sit one above the other.

In analog layout, some blocks come in matched pairs that must be mirror images about one vertical line, and some blocks must sit on that line. Most pairs of lists cannot give such a picture: they might ask a matched pair to sit one above the other.

The rule says: read the group's blocks in the first list, swap each block for its partner, and reverse. That must be the order in which the group's blocks appear in the second list. If the lists obey this, a mirror picture exists. If a move breaks it, rewrite the group's slots of the second list in this order to fix it. So the search only visits good lists.

The problem

Given rectangular cells with widths wuw_u and heights huh_u, and one symmetric set GG with a pairing sym:G→G\mathrm{sym} : G \to G (pairs of cells of equal size, and self-symmetric cells with sym(s)=s\mathrm{sym}(s) = s), find a placement without overlap, of small area, in which the cells of each pair have the same yy and centers mirrored about a common vertical axis x=Xx = X, and each self-symmetric cell has its center on the axis. This is floorplanning with the symmetry constraint. Cells outside GG are free.

A sequence pair (Γ+,Γ−)(\Gamma^+, \Gamma^-) is two orders of the cells, with positions p+p^+ and p−p^-. As on the sequence-pair page, uu is left of vv when uu is before vv in both orders, and uu is below vv when uu is after vv in Γ+\Gamma^+ and before vv in Γ−\Gamma^-. The pair is symmetric-feasible when

p+(x)<p+(y)  ⟺  p−(sym(y))<p−(sym(x))for all distinct x,y∈G.p^+(x) < p^+(y) \iff p^-(\mathrm{sym}(y)) < p^-(\mathrm{sym}(x)) \quad \text{for all distinct } x, y \in G.

The algorithm

The search is simulated annealing over sequence pairs, as for plain floorplans. Each move changes one or both orders. REPAIR then restores the condition: it takes the group cells in their Γ+\Gamma^+ order, maps each to its partner, reverses this list, and writes it into the slots that the group cells take in Γ−\Gamma^-. The free cells keep their slots. The cost of a pair is the area (and wire length) of SYM-PACK.

  1. SYM-PACK(Γ+, Γ−, w, h, sym) ▷ one symmetric set, axis vertical
  2. 1if the pair is not symmetric-feasible then return NONE
  3. 2for all cells u ≠ v, find whether u is left of v or below v
  4. 3merge the two cells of each pair into one node of the vertical graph
  5. 4order the nodes topologically along the below arcs
  6. 5y(node) ← the longest path to it, with arc weight h_u; each cell takes the y of its node
  7. 6constraints on x_u ≥ 0, X and W: x_u + w_u ≤ x_v for u left of v; x_u + w_u ≤ W;
  8. x_s + w_s / 2 = X for a self-symmetric s; x_u + x_sym(u) + w_u = 2X for a pair
  9. 7solve the linear program: minimize W subject to the constraints of L6
  10. 8return x, y, the axis X, the width W and the height max (y_u + h_u)

Line L1 takes O(n)O(n) time: list the group cells in the order of Γ−\Gamma^-, and compare with the reversed list of mirrors in the order of Γ+\Gamma^+. Line L3 is what gives the two cells of a pair one yy. Line L6 is not a system of difference constraints, because a pair adds a sum xu+xsym(u)x_u + x_{\mathrm{sym}(u)}. So the code solves a small linear program, with an exact simplex method in fractions.

Example

Take four cells: a pair a,a′a, a' of size 1×11 \times 1, a self-symmetric cell ss of size 2×12 \times 1 (width by height), and a free cell ff of size 1×21 \times 2. Let Γ+=(f,a′,a,s)\Gamma^+ = (f, a', a, s) and Γ−=(f,s,a′,a)\Gamma^- = (f, s, a', a).

The group cells in Γ+\Gamma^+ are a′,a,sa', a, s. Their mirrors are a,a′,sa, a', s, and reversed this is s,a′,as, a', a, which is the order of the group in Γ−\Gamma^-. So the pair is symmetric-feasible.

cells order in Γ+\Gamma^+ order in Γ−\Gamma^- relation
ff, any other ff first ff first ff left of it
a′a', aa a′a' first a′a' first a′a' left of aa
a′a', ss a′a' first ss first ss below a′a'
aa, ss aa first ss first ss below aa

So ss is at y=0y = 0, the node {a,a′}\{a, a'\} at y=1y = 1, and ff at y=0y = 0. For xx: ff is at 0, a′a' is at least 1, aa is at least 2, and ss is at least 1. The program gives xa′=1x_{a'} = 1, xa=2x_a = 2 and the axis X=2X = 2. The centers of the pair are at 1.5 and 2.5, and xs=X−1=1x_s = X - 1 = 1. The width is 3 and the height is 2, so the area 6 equals the total area of the cells, with no gap.

The order Γ−=(f,s,a,a′)\Gamma^- = (f, s, a, a') breaks the condition: a′a' is before aa in Γ+\Gamma^+ but aa is before a′a' in Γ−\Gamma^-, so aa would be below a′a', and the two cells of a pair could not share one yy. REPAIR rewrites the group slots as s,a′,as, a', a and gives back the order above.

Correctness

The full proofs are in the proof file. The key lemma: if the condition holds and u≠vu \ne v are in the group, then uu left of vv implies sym(v)\mathrm{sym}(v) left of sym(u)\mathrm{sym}(u), and uu below vv implies sym(u)\mathrm{sym}(u) below sym(v)\mathrm{sym}(v). Each follows from two uses of the condition. The same condition, read for y=sym(x)y = \mathrm{sym}(x), says that the two cells of a pair are in the same order in both lists, so they are side by side and never one above the other. For two self-symmetric cells it says the orders are opposite, so they are stacked on the axis and never side by side.

From the lemma, the merged vertical graph of line L3 has no cycle: the potential f(x)=p−(x)+p−(sym(x))f(x) = p^-(x) + p^-(\mathrm{sym}(x)) rises along every below relation between group cells, and is the same for the two cells of a pair. So lines L4 and L5 give the least yy that keeps every below relation and gives each pair one yy.

For a group with no free cells, the proof file builds a symmetric xx directly: average the least placement with its mirror image. The mirror keeps the relations by the key lemma, so the average keeps them too, and it has the same width. With free cells, Balasa and Lampaert prove that a symmetric placement that keeps the relations always exists. This page cites that result and does not prove it. Given that it exists, line L7 finds the one of least width. The xx and yy constraints share no variable, so SYM-PACK gives the least area among the symmetric placements that keep the relations of the pair.

Proof: The key lemma of symmetric-feasible sequence pairs, and what SYM-PACK returnspartial

Notation. The cells have widths ww and heights hh. A sequence pair is two orders Γ+\Gamma^+ and Γ−\Gamma^- of the cells, with positions p+(u)p^+(u) and p−(u)p^-(u). As on the sequence pair page, uu is left of vv if p+(u)<p+(v)p^+(u) < p^+(v) and p−(u)<p−(v)p^-(u) < p^-(v), and uu is below vv if p+(u)>p+(v)p^+(u) > p^+(v) and p−(u)<p−(v)p^-(u) < p^-(v). Every two distinct cells are in exactly one of these four relations (uu left of vv, vv left of uu, uu below vv, vv below uu).

A symmetric set GG is a set of cells with an involution sym:G→G\mathrm{sym} : G \to G. A pair is {u,sym(u)}\{u, \mathrm{sym}(u)\} with u≠sym(u)u \neq \mathrm{sym}(u), and the two cells have the same width and height. A self-symmetric cell has sym(s)=s\mathrm{sym}(s) = s. The pair (Γ+,Γ−)(\Gamma^+, \Gamma^-) is symmetric-feasible for GG if

(C)p+(x)<p+(y)  ⟺  p−(sym(y))<p−(sym(x))for all distinct x,y∈G.(C) \qquad p^+(x) < p^+(y) \iff p^-(\mathrm{sym}(y)) < p^-(\mathrm{sym}(x)) \quad \text{for all distinct } x, y \in G.

A placement is symmetric if there is a vertical axis x=Xx = X such that the two cells of each pair have the same yy and centers mirrored about the axis, and each self-symmetric cell has its center on the axis.

Lemma 1 (the key lemma). Let (C)(C) hold, and let u≠vu \neq v be in GG.

  1. If uu is left of vv, then sym(v)\mathrm{sym}(v) is left of sym(u)\mathrm{sym}(u).
  2. If uu is below vv, then sym(u)\mathrm{sym}(u) is below sym(v)\mathrm{sym}(v).
  3. The two cells of a pair are in a left-of relation, not a below relation.
  4. Two self-symmetric cells are in a below relation, not a left-of relation.

Proof. (1) p+(u)<p+(v)p^+(u) < p^+(v), so (C)(C) with x=ux = u, y=vy = v gives p−(sym(v))<p−(sym(u))p^-(\mathrm{sym}(v)) < p^-(\mathrm{sym}(u)). Apply (C)(C) to x=sym(v)x = \mathrm{sym}(v), y=sym(u)y = \mathrm{sym}(u), which are distinct: p+(sym(v))<p+(sym(u))p^+(\mathrm{sym}(v)) < p^+(\mathrm{sym}(u)) if and only if p−(u)<p−(v)p^-(u) < p^-(v), which holds. So sym(v)\mathrm{sym}(v) is before sym(u)\mathrm{sym}(u) in both orders.

(2) p+(v)<p+(u)p^+(v) < p^+(u), so (C)(C) with x=vx = v, y=uy = u gives p−(sym(u))<p−(sym(v))p^-(\mathrm{sym}(u)) < p^-(\mathrm{sym}(v)). Apply (C)(C) to x=sym(u)x = \mathrm{sym}(u), y=sym(v)y = \mathrm{sym}(v): p+(sym(u))<p+(sym(v))p^+(\mathrm{sym}(u)) < p^+(\mathrm{sym}(v)) if and only if p−(v)<p−(u)p^-(v) < p^-(u), which is false. So p+(sym(u))>p+(sym(v))p^+(\mathrm{sym}(u)) > p^+(\mathrm{sym}(v)) and p−(sym(u))<p−(sym(v))p^-(\mathrm{sym}(u)) < p^-(\mathrm{sym}(v)).

(3) Take x=ux = u, y=sym(u)y = \mathrm{sym}(u). Then (C)(C) reads p+(u)<p+(sym(u))  ⟺  p−(u)<p−(sym(u))p^+(u) < p^+(\mathrm{sym}(u)) \iff p^-(u) < p^-(\mathrm{sym}(u)). The two cells are in the same order in both sequences.

(4) For s≠ts \neq t self-symmetric, (C)(C) reads p+(s)<p+(t)  ⟺  p−(t)<p−(s)p^+(s) < p^+(t) \iff p^-(t) < p^-(s). The two cells are in opposite orders. □\square

Lemma 1 is what makes symmetry possible. Part 3 says that the two cells of a pair are never asked to be one above the other, so they can share one yy. Part 4 says that the self-symmetric cells, which all sit on the axis, are never asked to be side by side. Parts 1 and 2 say that the relations inside the group look the same in a mirror.

Lemma 2 (the count). Let GG have gg cells among nn. For each Γ+\Gamma^+, exactly n!/g!n!/g! orders Γ−\Gamma^- satisfy (C)(C). So there are (n!)2/g!(n!)^2/g! symmetric-feasible pairs.

Proof. Condition (C)(C) says that the order of the group cells in Γ−\Gamma^- is the list of the mirrors sym(x)\mathrm{sym}(x) of the group cells, taken in the reverse of their order in Γ+\Gamma^+. This fixes one of the g!g! relative orders of GG in Γ−\Gamma^-, and leaves the rest of Γ−\Gamma^- free. Each relative order is taken by n!/g!n!/g! permutations. □\square

The same argument shows that REPAIR, which keeps the slots of GG in Γ−\Gamma^- and refills them in this forced order, returns a symmetric-feasible pair, and returns Γ−\Gamma^- itself when (C)(C) already holds.

Lemma 3 (the merged vertical graph is acyclic). Let (C)(C) hold. Merge the two cells of each pair into one node, and draw an arc from the node of uu to the node of vv when uu is below vv. This graph has no cycle.

Proof. The below relation itself is a strict partial order: if uu is below vv and vv is below tt, then uu is before tt in Γ−\Gamma^- and after tt in Γ+\Gamma^+. Suppose the merged graph has a cycle. Write it as a closed walk of below relations u1u_1 below v1v_1, u2u_2 below v2v_2, ..., where ui+1u_{i+1} is viv_i or its mirror. If ui+1=viu_{i+1} = v_i at every step, transitivity gives u1u_1 below u1u_1, which is false. So the walk changes to the mirror at least once. Join the runs between two changes by transitivity. This gives group cells a1,b1,…,ak,bka_1, b_1, \ldots, a_k, b_k with aia_i below bib_i and ai+1=sym(bi)a_{i+1} = \mathrm{sym}(b_i), indices mod kk.

Let f(x)=p−(x)+p−(sym(x))f(x) = p^-(x) + p^-(\mathrm{sym}(x)) for x∈Gx \in G. If aa is below bb, then p−(a)<p−(b)p^-(a) < p^-(b), and by Lemma 1 (2) sym(a)\mathrm{sym}(a) is below sym(b)\mathrm{sym}(b), so p−(sym(a))<p−(sym(b))p^-(\mathrm{sym}(a)) < p^-(\mathrm{sym}(b)). So f(a)<f(b)f(a) < f(b). Also f(sym(b))=f(b)f(\mathrm{sym}(b)) = f(b). Around the cycle, f(a1)<f(b1)=f(a2)<⋯<f(bk)=f(a1)f(a_1) < f(b_1) = f(a_2) < \cdots < f(b_k) = f(a_1), which is false. □\square

Theorem 4 (the yy coordinates). Lines L3 to L5 give each cell the least yy such that every below relation holds and the two cells of each pair have the same yy.

Proof. By Lemma 3, line L4 orders all nodes. The constraints yv≥yu+huy_v \ge y_u + h_u for uu below vv, with one variable per node, form a system of difference constraints on a DAG. The longest-path values of line L5 satisfy it, and every solution is at least these values, by induction along the order. □\square

Theorem 5 (the group alone). Let (C)(C) hold, and let every cell be in GG. Let xLx^L be the least xx coordinates that keep the left-of relations (longest paths in the horizontal graph), and T=max⁡u(xuL+wu)T = \max_u (x^L_u + w_u) the least width. Then

au=12(xuL+T−wu−xsym(u)L)a_u = \tfrac12 \big( x^L_u + T - w_u - x^L_{\mathrm{sym}(u)} \big)

keeps every left-of relation, fits in [0,T][0, T], and is symmetric about X=T/2X = T/2. So for a group alone, symmetry costs no width.

Proof. Let mu=T−wu−xsym(u)Lm_u = T - w_u - x^L_{\mathrm{sym}(u)}. As wsym(u)=wuw_{\mathrm{sym}(u)} = w_u and 0≤xsym(u)L≤T−wu0 \le x^L_{\mathrm{sym}(u)} \le T - w_u, we have 0≤mu≤T−wu0 \le m_u \le T - w_u. If uu is left of vv, then by Lemma 1 (1) sym(v)\mathrm{sym}(v) is left of sym(u)\mathrm{sym}(u), so xsym(v)L+wv≤xsym(u)Lx^L_{\mathrm{sym}(v)} + w_v \le x^L_{\mathrm{sym}(u)}, and so mu+wu=T−xsym(u)L≤T−wv−xsym(v)L=mvm_u + w_u = T - x^L_{\mathrm{sym}(u)} \le T - w_v - x^L_{\mathrm{sym}(v)} = m_v. So mm keeps the relations, and xLx^L does too. The constraints are linear, so the mean a=(xL+m)/2a = (x^L + m)/2 keeps them and fits in [0,T][0, T]. Finally au+asym(u)=T−wua_u + a_{\mathrm{sym}(u)} = T - w_u, so the centers au+wu/2a_u + w_u/2 and asym(u)+wu/2a_{\mathrm{sym}(u)} + w_u/2 add to TT, and a self-symmetric cell has the center T/2T/2. □\square

Free cells. With cells outside GG, the mirror mm above breaks the relations between free cells and group cells, and Theorem 5 does not apply. Balasa and Lampaert prove that every symmetric-feasible pair still has a symmetric placement that keeps all the relations of the pair (Balasa and Lampaert 2000, the section on symmetric-feasible sequence pairs). This page does not repeat that proof. Line L7 solves the linear program of line L6, so it finds such a placement when one exists. In the tests it found one for every symmetric-feasible pair that was tried, and line L7 raises an error if it ever does not.

Theorem 6 (what SYM-PACK returns). If line L7 succeeds, the placement keeps every relation of the pair, is symmetric, and has the least width and the least height among all such placements. So its area is the least among the symmetric placements that keep the relations of the pair.

Proof. Every left-of relation and the symmetry equations are rows of the program of line L6, and WW bounds every right edge. The program minimizes WW, so the width is the least. The yy part is Theorem 4, and the symmetry of yy holds because each pair is one node. Two cells in a relation do not overlap, and every two cells are in a relation, so no two cells overlap. The xx and yy constraints share no variable, so the least width and the least height are reached together. □\square

What is proved here: Lemmas 1 to 3 and Theorems 4 to 6, and the symmetric xx placement for a group with no free cells. What is cited: the existence of a symmetric placement when free cells are present. What is measured: the tests check the count of Lemma 2, Lemma 1 on all pairs of 4 cells, the placements of random instances, and, on two small instances, that the best area over all symmetric-feasible pairs equals the best area of a search over a half-unit grid.

Complexity

  • The test and the repair. O(n)O(n) time with the position arrays.
  • The search space. For each Γ+\Gamma^+, exactly n!/g!n!/g! orders Γ−\Gamma^- pass the test, so there are (n!)2/g!(n!)^2/g! symmetric-feasible pairs among the (n!)2(n!)^2 pairs. With several groups of sizes g1,g2,…g_1, g_2, \ldots, the conditions fix the relative orders of disjoint sets, and the count is (n!)2/∏kgk!(n!)^2 / \prod_k g_k!.
  • The packing. Lines L2 to L5 take O(n2)O(n^2) time. The program of line L7 has n+2n + 2 variables and O(n2)O(n^2) rows. Interior-point methods solve it in polynomial time. The exact simplex method of the code has no polynomial bound, but it is fast at the sizes of an analog placement.

These counts are proved. The time of a whole annealing run depends on the schedule, and there is no bound on the quality it reaches.

Properties

  • Every visited placement is symmetric. A placer that applies REPAIR after each move never needs a penalty for broken symmetry.
  • No loss of optimality for the relations. By Theorem 6 of the proof file, the packing is the least symmetric one for its pair. In the two exhaustive tests of the implementation, the best packing over all symmetric-feasible pairs equals the best symmetric placement found by a grid search. This is measured on small instances; it is not a theorem of this page.
  • Symmetry without width cost for a group alone. For a group with no free cells, the least symmetric width equals the least width without symmetry.
  • One axis per group. Different groups have their own axes, which the program can tie together if the circuit needs one axis for all.

Variants and improvements

  • Several symmetric sets. The condition is applied to each group, and the program has one axis variable for each.
  • A horizontal axis. Swap the roles of the left-of and below relations.
  • The solution space. Balasa, Maruvada and Krishnamoorthy study how a placer explores the space of symmetric-feasible codes.
  • Symmetry islands. The ASF-B*-tree keeps a group in a compact region with a tree whose every packing is symmetric by construction.
  • Common centroid. Matched devices made of many unit cells use a common-centroid layout, which mirror symmetry about one axis does not give.

When to use it

Use it in an annealing placer for analog blocks with mirror symmetry, when the placer already uses sequence pairs. It is a good fit for a few symmetric sets among tens of cells. For tight proximity of a group, or for a group that must form one connected region, a tree that builds islands is a better fit.

Pitfalls

  • Testing only the pairs. The condition must hold for every two distinct cells of the group, not only for the cells of each pair. A test that only checks partners passes pairs that have no symmetric placement. For two pairs a,a′a, a' and b,b′b, b', the orders Γ+=(b,a,a′,b′)\Gamma^+ = (b, a, a', b') and Γ−=(a,b,b′,a′)\Gamma^- = (a, b, b', a') keep each pair side by side, but put aa below bb and b′b' below a′a'. As each pair shares one yy, the pair a,a′a, a' would be both below and above the pair b,b′b, b'.
  • Plain longest paths for xx. The least xx of each cell is in general not symmetric. Moving each cell to the mirror position after the longest path can create overlaps with free cells. The xx step must solve the symmetry equations and the relations together.
  • Half units. The axis and the cell positions can be at half units, as for a self-symmetric cell of odd width with its center on an axis at a whole unit. Round to the manufacturing grid only after the whole group is placed, and round the two cells of a pair together.
  • Cells of different size in a pair. The condition does not check sizes. The two cells of a pair must have the same width and height, or no mirror placement exists.

Implementations

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.

symmetric_feasible_sequence_pair.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/symmetric-feasible-sequence-pair/. The authors are listed in prov/RFE075.jsonl.

"""Symmetric-feasible sequence pairs and a symmetric packing of them.

Cells are 0 .. n - 1 with widths w and heights h. A sequence pair is two
permutations gp (Gamma+) and gm (Gamma-) of the cells. One symmetric set with
a vertical axis is a dict sym: each cell of the group maps to its partner, and a
self-symmetric cell maps to itself. Cells not in sym are free.

Relations (as on the sequence-pair page): u is left of v if u is before v in
both sequences; u is below v if u is after v in gp and before v in gm.
"""

from fractions import Fraction


def positions(seq: list) -> dict:
    return {c: i for i, c in enumerate(seq)}


def is_symmetric_feasible(gp: list, gm: list, sym: dict) -> bool:
    """Balasa and Lampaert's condition: for distinct x, y in the group,
    pos+(x) < pos+(y) if and only if pos-(sym y) < pos-(sym x)."""
    pp, pm = positions(gp), positions(gm)
    g = list(sym)
    return all((pp[x] < pp[y]) == (pm[sym[y]] < pm[sym[x]]) for x in g for y in g if x != y)


def repair(gp: list, gm: list, sym: dict) -> list:
    """Return a new gm that keeps the slots of the group cells and of the free
    cells, and refills the group slots in the only order that the condition
    allows: the mirrors of the group cells, in the reverse order of gp."""
    forced = [sym[x] for x in reversed([c for c in gp if c in sym])]
    it = iter(forced)
    return [next(it) if c in sym else c for c in gm]


def _simplex_min(c: list, rows: list):
    """Minimize c.x subject to rows (a, sense, b) with sense in '<=', '=', '>=', and x >= 0.
    Exact two-phase simplex in Fraction with Bland's rule. Returns (value, x) or None when
    infeasible. The callers here always have a bounded objective."""
    n, m = len(c), len(rows)
    ns = sum(1 for _, sense, _ in rows if sense != "=")
    N = n + ns + m
    T, basis, s = [], [], n
    for i, (a, sense, b) in enumerate(rows):
        row = [Fraction(0)] * (N + 1)
        for j in range(n):
            row[j] = Fraction(a[j])
        if sense != "=":
            row[s] = Fraction(1 if sense == "<=" else -1)
            s += 1
        row[N] = Fraction(b)
        if row[N] < 0:
            row = [-v for v in row]
        row[n + ns + i] = Fraction(1)
        T.append(row)
        basis.append(n + ns + i)

    def pivot(r: int, col: int) -> None:
        pv = T[r][col]
        T[r] = [v / pv for v in T[r]]
        for i in range(len(T)):
            if i != r and T[i][col] != 0:
                f = T[i][col]
                T[i] = [a - f * b for a, b in zip(T[i], T[r])]
        basis[r] = col

    def run(cost: list, allowed: range) -> None:
        while True:
            enter = None
            for j in allowed:
                if j not in basis and cost[j] - sum(cost[basis[i]] * T[i][j] for i in range(len(T))) < 0:
                    enter = j
                    break
            if enter is None:
                return
            best = None
            for i in range(len(T)):
                if T[i][enter] > 0:
                    ratio = T[i][N] / T[i][enter]
                    if best is None or ratio < best[0] or (ratio == best[0] and basis[i] < basis[best[1]]):
                        best = (ratio, i)
            if best is None:
                raise ArithmeticError("unbounded linear program")
            pivot(best[1], enter)

    run([0] * (n + ns) + [1] * m, range(N))
    if sum(T[i][N] for i in range(len(T)) if basis[i] >= n + ns) != 0:
        return None
    for i in range(len(T) - 1, -1, -1):  # drive the artificial variables out
        if basis[i] >= n + ns:
            j = next((j for j in range(n + ns) if T[i][j] != 0), None)
            if j is None:
                del T[i], basis[i]  # a redundant row
            else:
                pivot(i, j)
    run(list(c) + [0] * (N - n), range(n + ns))
    x = [Fraction(0)] * n
    for i, b in enumerate(basis):
        if b < n:
            x[b] = T[i][N]
    return sum(Fraction(ci) * xi for ci, xi in zip(c, x)), x


def sym_pack(gp: list, gm: list, w: list, h: list, sym: dict):
    """A placement with the group mirrored about one vertical axis, that keeps
    every relation of the sequence pair, with the least width and the least
    height among such placements. Returns None if the pair is not
    symmetric-feasible."""
    n = len(gp)
    if not is_symmetric_feasible(gp, gm, sym):  # @line L1
        return None
    pp, pm = positions(gp), positions(gm)
    left = [(u, v) for u in range(n) for v in range(n) if pp[u] < pp[v] and pm[u] < pm[v]]  # @line L2
    below = [(u, v) for u in range(n) for v in range(n) if pp[u] > pp[v] and pm[u] < pm[v]]
    node = {u: min(u, sym.get(u, u)) for u in range(n)}  # @line L3: a pair is one node
    succ: dict = {node[u]: [] for u in range(n)}
    indeg = {k: 0 for k in succ}
    for u, v in below:
        succ[node[u]].append((u, node[v]))
        indeg[node[v]] += 1
    order, stack = [], [k for k in succ if indeg[k] == 0]  # @line L4: Kahn's order
    while stack:
        k = stack.pop()
        order.append(k)
        for _, t in succ[k]:
            indeg[t] -= 1
            if indeg[t] == 0:
                stack.append(t)
    assert len(order) == len(succ), "the merged vertical graph has a cycle"
    ynode = {k: Fraction(0) for k in succ}
    for k in order:  # @line L5: longest paths
        for u, t in succ[k]:
            ynode[t] = max(ynode[t], ynode[k] + h[u])
    y = [ynode[node[u]] for u in range(n)]
    # x: variables x_0 .. x_{n-1}, X (the axis), W (the width); minimize W
    nv = n + 2
    X, W = n, n + 1
    rows = []

    def row(coef: dict, sense: str, b) -> None:
        a = [0] * nv
        for k, v in coef.items():
            a[k] += v
        rows.append((a, sense, b))

    for u, v in left:  # @line L6
        row({v: 1, u: -1}, ">=", w[u])
    for u in range(n):
        row({W: 1, u: -1}, ">=", w[u])
    for u, v in sym.items():
        if u == v:
            row({u: 2, X: -2}, "=", -w[u])  # center of u on the axis
        elif u < v:
            row({u: 1, v: 1, X: -2}, "=", -w[u])  # centers mirrored about the axis
    res = _simplex_min([0] * n + [0, 1], rows)  # @line L7
    if res is None:
        raise ArithmeticError("no symmetric x placement; this contradicts Balasa and Lampaert's theorem")
    width, sol = res
    x = sol[:n]
    height = max((y[u] + h[u] for u in range(n)), default=Fraction(0))
    return {"x": x, "y": y, "axis": sol[X], "width": width, "height": height}  # @line L8
test_symmetric_feasible_sequence_pair.py 171 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/symmetric-feasible-sequence-pair/. The authors are listed in prov/RFE075.jsonl.

import itertools
import math
import random
from fractions import Fraction

from symmetric_feasible_sequence_pair import _simplex_min, is_symmetric_feasible, positions, repair, sym_pack


def check_placement(gp, gm, w, h, sym, p) -> None:
    n = len(gp)
    x, y, ax = p["x"], p["y"], p["axis"]
    pp, pm = positions(gp), positions(gm)
    for u in range(n):
        assert x[u] >= 0 and y[u] >= 0
        assert x[u] + w[u] <= p["width"] and y[u] + h[u] <= p["height"]
    assert p["width"] == max(x[u] + w[u] for u in range(n))
    for u in range(n):
        for v in range(n):
            if u == v:
                continue
            if pp[u] < pp[v] and pm[u] < pm[v]:
                assert x[u] + w[u] <= x[v]
            if pp[u] > pp[v] and pm[u] < pm[v]:
                assert y[u] + h[u] <= y[v]
            # no overlap, checked directly on the rectangles
            assert x[u] + w[u] <= x[v] or x[v] + w[v] <= x[u] or y[u] + h[u] <= y[v] or y[v] + h[v] <= y[u]
    for u, v in sym.items():
        assert y[u] == y[v]
        assert (x[u] + Fraction(w[u], 2)) + (x[v] + Fraction(w[v], 2)) == 2 * ax


def test_small_example() -> None:
    # cells: 0 and 1 a pair (1 x 1), 2 self-symmetric (2 x 1), 3 free (1 x 2)
    w, h, sym = [1, 1, 2, 1], [1, 1, 1, 2], {0: 1, 1: 0, 2: 2}
    gp, gm = [3, 1, 0, 2], [3, 2, 1, 0]
    assert is_symmetric_feasible(gp, gm, sym)
    p = sym_pack(gp, gm, w, h, sym)
    check_placement(gp, gm, w, h, sym, p)
    assert (p["width"], p["height"], p["axis"]) == (3, 2, 2)
    assert sym_pack(gp, [3, 2, 0, 1], w, h, sym) is None


def test_count_of_feasible_pairs() -> None:
    for n, sym in ((3, {0: 1, 1: 0}), (3, {0: 0, 1: 1, 2: 2}), (4, {0: 1, 1: 0, 2: 3, 3: 2}), (4, {0: 1, 1: 0, 2: 2})):
        perms = list(itertools.permutations(range(n)))
        cnt = sum(1 for a in perms for b in perms if is_symmetric_feasible(list(a), list(b), sym))
        assert cnt == math.factorial(n) ** 2 // math.factorial(len(sym))


def test_repair() -> None:
    rng = random.Random(2000)
    sym = {0: 1, 1: 0, 2: 2, 3: 4, 4: 3}
    for _ in range(300):
        gp, gm = list(range(7)), list(range(7))
        rng.shuffle(gp)
        rng.shuffle(gm)
        gm2 = repair(gp, gm, sym)
        assert is_symmetric_feasible(gp, gm2, sym)
        assert [c for c in gm2 if c not in sym] == [c for c in gm if c not in sym]
        assert repair(gp, gm2, sym) == gm2


def test_mirror_lemma_on_all_pairs() -> None:
    sym = {0: 1, 1: 0, 2: 2, 3: 3}
    perms = list(itertools.permutations(range(4)))
    for a in perms:
        for b in perms:
            if not is_symmetric_feasible(list(a), list(b), sym):
                continue
            pp, pm = positions(a), positions(b)
            for u in sym:
                for v in sym:
                    if u == v:
                        continue
                    if pp[u] < pp[v] and pm[u] < pm[v]:  # u left of v
                        assert pp[sym[v]] < pp[sym[u]] and pm[sym[v]] < pm[sym[u]]
                    if pp[u] > pp[v] and pm[u] < pm[v]:  # u below v
                        assert pp[sym[u]] > pp[sym[v]] and pm[sym[u]] < pm[sym[v]]
            assert (pp[0] < pp[1]) == (pm[0] < pm[1])  # a pair is side by side
            assert (pp[2] < pp[3]) != (pm[2] < pm[3])  # self-symmetric cells are stacked


def brute_min_area(w, h, sym, free, xmax, ymax):
    """The least bounding-box area of a symmetric, overlap-free placement with x on a
    half-unit grid and y on the unit grid, found by trying every grid position."""
    halves = [Fraction(k, 2) for k in range(2 * xmax + 1)]
    ys = list(range(ymax + 1))
    pairs = [(u, v) for u, v in sym.items() if u < v]
    selfs = [u for u, v in sym.items() if u == v]
    best = None
    n = len(w)
    spots = list(itertools.product(halves, ys))
    for ax in halves:
        for choice in itertools.product(*([spots] * len(pairs) + [ys] * len(selfs) + [spots] * len(free))):
            x, y = [None] * n, [None] * n
            k = 0
            for u, v in pairs:
                x[u], y[u] = choice[k]
                x[v], y[v] = 2 * ax - w[u] - x[u], y[u]
                k += 1
            for s in selfs:
                x[s], y[s] = ax - Fraction(w[s], 2), choice[k]
                k += 1
            for f in free:
                x[f], y[f] = choice[k]
                k += 1
            if min(x) < 0:
                continue
            ok = all(x[a] + w[a] <= x[b] or x[b] + w[b] <= x[a] or y[a] + h[a] <= y[b] or y[b] + h[b] <= y[a] for a in range(n) for b in range(a + 1, n))
            if ok:
                area = max(x[a] + w[a] for a in range(n)) * max(y[a] + h[a] for a in range(n))
                best = area if best is None else min(best, area)
    return best


def best_over_pairs(w, h, sym):
    n = len(w)
    perms = list(itertools.permutations(range(n)))
    best = None
    for a in perms:
        for b in perms:
            p = sym_pack(list(a), list(b), w, h, sym)
            if p is None:
                continue
            check_placement(list(a), list(b), w, h, sym, p)
            area = p["width"] * p["height"]
            best = area if best is None else min(best, area)
    return best


def test_exhaustive_against_grid_search() -> None:
    # a pair 1 x 1, a self-symmetric cell 2 x 1 and a free cell 1 x 2
    w, h, sym = [1, 1, 2, 1], [1, 1, 1, 2], {0: 1, 1: 0, 2: 2}
    assert best_over_pairs(w, h, sym) == brute_min_area(w, h, sym, [3], 4, 3) == 6
    # two pairs: 2 x 1 and 1 x 2
    w, h, sym = [2, 2, 1, 1], [1, 1, 2, 2], {0: 1, 1: 0, 2: 3, 3: 2}
    assert best_over_pairs(w, h, sym) == brute_min_area(w, h, sym, [], 4, 3)


def test_random_instances_always_pack() -> None:
    rng = random.Random(7)
    for _ in range(60):
        n = rng.randint(4, 7)
        w = [rng.randint(1, 4) for _ in range(n)]
        h = [rng.randint(1, 4) for _ in range(n)]
        cells = list(range(n))
        rng.shuffle(cells)
        sym = {}
        for i in range(rng.randint(0, 2)):
            a, b = cells.pop(), cells.pop()
            w[b], h[b] = w[a], h[a]
            sym[a], sym[b] = b, a
        for i in range(rng.randint(0, min(2, len(cells)))):
            s = cells.pop()
            sym[s] = s
        gp, gm = list(range(n)), list(range(n))
        rng.shuffle(gp)
        rng.shuffle(gm)
        gm = repair(gp, gm, sym)
        p = sym_pack(gp, gm, w, h, sym)
        check_placement(gp, gm, w, h, sym, p)


def test_simplex_small() -> None:
    # min x + y with x + 2y >= 4, 3x + y >= 6: optimum at (8/5, 6/5)
    val, x = _simplex_min([1, 1], [([1, 2], ">=", 4), ([3, 1], ">=", 6)])
    assert val == Fraction(14, 5) and x == [Fraction(8, 5), Fraction(6, 5)]
    assert _simplex_min([1], [([1], "<=", -1)]) is None

History

Murata, Fujiyoshi, Nakatake and Kajitani gave the sequence pair in 1995. Balasa and Lampaert gave the symmetric-feasible condition, with the proof that every such pair has a symmetric placement and an annealing placer that keeps the condition, in IEEE Transactions on CAD in 2000. Balasa, Maruvada and Krishnamoorthy studied the search space in 2004. Later analog placers moved to trees, such as the ASF-B*-tree of Lin and Lin in 2007, which also keep a group in one region.

References

  1. Florin Balasa and Koen Lampaert, Symmetry within the sequence-pair representation in the context of placement for analog design, IEEE Transactions on Computer-Aided Design of Integrated Circuits and Systems 19(7), 721 to 731, 2000, the definition of a symmetric-feasible sequence pair, the theorem that such a pair has a symmetric placement, the size of the reduced search space, and the annealing placer
  2. F. Balasa, S. C. Maruvada and K. Krishnamoorthy, On the exploration of the solution space in analog placement with symmetry constraints, IEEE TCAD 23(2), 177 to 191, 2004, the exploration of the space of symmetric-feasible codes
  3. 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 sequence pair and its decoding by constraint graphs
  4. Georges G. E. Gielen and Rob A. Rutenbar, Computer-aided design of analog and mixed-signal integrated circuits, Proceedings of the IEEE 88(12), 1825 to 1854, 2000, the section on analog placement under symmetry constraints

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 proofH1 sketch
  • a full proof of correctness
  • a full proof of time.check
  • a full proof of time.relations_and_y
  • a full proof of time.repair
  • a full proof of space.extra
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)
WritingW2 basic
  • a scene preset for the example