Algorithm Search⌘K

Data structurecore

Corner stitching

Also called Ousterhout corner stitching, corner-stitched plane.

Ousterhout's layout structure that tiles the plane with solid and space rectangles, each with four pointers at two corners, for point finding and area search.

Time
O(F + k + e) area_enumerationO(F + k + d) insert_or_deleteO(N) point_find_worst
Space
Θ(n) total
Where
F = the cost of one point find; N = the number of tiles, at most 4n + 1; d = the number of neighbours of the tiles that an update splits or merges; e = the right neighbours of the reported tiles that the enumeration examines; k = the number of tiles that an area query reports; n = the number of solid tiles
Origin
John K. Ousterhout, 1984

Corner stitching is a data structure for a set of disjoint rectangles in the plane that also stores the empty space between them as rectangles. The plane is cut into tiles: every point lies in exactly one tile, which is solid (part of the layout) or space, and space is cut into maximal horizontal strips. Each tile keeps four pointers, the stitches, to neighbours at its lower left and upper right corners, and the queries walk from tile to tile along them. John Ousterhout introduced it in 1984 for the Magic layout editor, where each group of mask layers is one corner stitched plane.

In plain words

Think of a quilt. The chip area is covered with rectangular patches, some filled with material and some empty, with no gap and no overlap. Each empty patch is as wide as it can be, and is cut only where a filled patch starts or ends above or below it.

Each patch knows four neighbours: the one below it at its left end, the one to its left at its bottom end, the one above it at its right end, and the one to its right at its top end. With these four links you can walk to any patch. To find what lies under the cursor, start anywhere and walk up or down, then left or right, until you stand on the point. Empty space is stored, so the question "is this area empty?" costs a short walk along its left side, not a search.

The abstract type

The structure stores a set SS of nn disjoint closed-open rectangles [x0,x1)×[y0,y1)[x_0, x_1) \times [y_0, y_1) with corners in a world rectangle WW. It supports these operations.

  • POINT-FIND(p)(p): the tile that contains the point pp.
  • NEIGHBOURS(t)(t): the tiles that touch one side of the tile tt, in order along that side.
  • AREA-SEARCH(A)(A): some rectangle of SS that meets the rectangle AA, or nil if AA is empty.
  • ENUMERATE(A)(A): every tile that meets AA, solid and space, each once.
  • INSERT(R)(R): add a rectangle RR that meets no rectangle of SS.
  • DELETE(t)(t): remove the rectangle of the solid tile tt.

Layouts with polygons that are not rectangles are cut into rectangles first, as for any rectilinear polygon. Magic keeps the material type in each tile and lets two solid tiles of different types touch. This page treats one type, so solid tiles can also be merged by the user, but the structure never merges them by itself.

Representation

A tile is t=[x0,x1)×[y0,y1)t = [x_0, x_1) \times [y_0, y_1) with a flag solid or space. The tiles form a planar subdivision of WW into axis-parallel rectangles. The four stitches are defined by the point that the target tile contains, for a small ε>0\varepsilon > 0:

stitch target tile contains meaning
bl(t)bl(t) (x0,y0−ε)(x_0, y_0 - \varepsilon) bottom neighbour at the left end
lb(t)lb(t) (x0−ε,y0)(x_0 - \varepsilon, y_0) left neighbour at the bottom end
tr(t)tr(t) (x1−ε,y1)(x_1 - \varepsilon, y_1) top neighbour at the right end
rt(t)rt(t) (x1,y1−ε)(x_1, y_1 - \varepsilon) right neighbour at the top end

A stitch that would leave WW is nil. Ousterhout stores only the lower left corner (x0,y0)(x_0, y_0) of a tile and reads x1x_1 from rt(t)rt(t) and y1y_1 from tr(t)tr(t), so a tile costs one flag, two coordinates and four pointers.

The space tiles are kept in a canonical form. (H) No two space tiles share a piece of a vertical edge. (V) No two space tiles with the same xx-span share a piece of a horizontal edge. Under (H) and (V) the space tiles are the maximal horizontal strips of the free area, and they are a function of the solid tiles only. There are at most 3n+13n + 1 of them, so N≤4n+1N \le 4n + 1 tiles in all. Both facts are proved in proofs/correctness.md.

Operations

  1. POINT-FIND(p = (px, py), t) ▷ t: any start tile, for example the last tile found
  2. 1repeat
  3. 2while py < y0(t) do t ← bl(t)
  4. 3while py ≥ y1(t) do t ← tr(t)
  5. 4if px < x0(t) then t ← lb(t)
  6. 5else if px ≥ x1(t) then t ← rt(t)
  7. 6else return t
  8. TOP-NEIGHBOURS(t) ▷ the other three sides are symmetric
  9. N1 u ← tr(t)
  10. N2 while u ≠ nil and x1(u) > x0(t) do output u; u ← lb(u)
  11. AREA-SEARCH(A = [ax0, ax1) × [ay0, ay1))
  12. A1 t ← POINT-FIND((ax0, ay1 − ε)) ▷ the top tile on the left edge of A
  13. A2 repeat if t is solid then return t
  14. A3 if x1(t) < ax1 then return POINT-FIND((x1(t), min(y1(t), ay1) − ε), t) ▷ solid by (H)
  15. A4 if y0(t) ≤ ay0 then return nil
  16. A5 t ← POINT-FIND((ax0, y0(t) − ε), t)
  17. ENUMERATE(A)
  18. E1 t ← POINT-FIND((ax0, ay1 − ε))
  19. E2 repeat REPORT(t)
  20. E3 if y0(t) ≤ ay0 then return
  21. E4 t ← POINT-FIND((ax0, y0(t) − ε), t)
  22. REPORT(u)
  23. E5 stack ← [u]; while stack is not empty do u ← pop(stack)
  24. E6 output u
  25. E7 if x1(u) ≥ ax1 then continue
  26. E8 for each right neighbour w of u, from rt(u) down, with y1(w) > max(y0(u), ay0) do
  27. E9 if y0(w) < ay1 and max(y0(w), ay0) ≥ y0(u) then push w ▷ u owns w
  28. INSERT(R = [a, b) × [c, d))
  29. I1 if AREA-SEARCH(R) ≠ nil then fail
  30. I2 split the tile at (a, d − ε) horizontally at d
  31. I3 split the tile at (a, c) horizontally at c
  32. I4 C ← the space tiles on the line x = a between c and d, from the top down
  33. I5 split each tile of C vertically at a and at b; mark each middle part solid
  34. I6 merge the middle parts into one solid tile R
  35. I7 for each left and right part s do SETTLE(s) ▷ merge s with space tiles of the same x-span above and below
  36. DELETE(D = [a, b) × [c, d))
  37. D1 mark D as space
  38. D2 split each space left or right neighbour of D at c and at d
  39. D3 H ← the top and bottom edges of these neighbours that lie strictly between c and d
  40. D4 split D horizontally at every height of H into pieces
  41. D5 split each space left or right neighbour of a piece at every height of H
  42. D6 for each piece p do merge p with lb(p) and with rt(p) when they are space with the y-span of p
  43. D7 for each row tile r made in D6 do SETTLE(r)

Split and merge are local. To split tt at a height yy, make the upper part uu, find lb(u)lb(u) by walking up the left neighbours of tt and the new rt(t)rt(t) by walking down its right neighbours, and redirect the stitches of the neighbours whose defining point now lies in uu. A merge redirects the stitches that pointed to the tile that disappears. Each costs time linear in the number of neighbours of the two tiles.

Example

The world is [0,10)×[0,8)[0, 10) \times [0, 8) with two solid tiles A=[2,5)×[2,5)A = [2, 5) \times [2, 5) and B=[6,9)×[4,7)B = [6, 9) \times [4, 7). The canonical space tiles are the seven maximal strips below, which reach the bound 3n+1=73n + 1 = 7.

tile kind blbl lblb trtr rtrt
s1=[0,10)×[0,2)s_1 = [0,10) \times [0,2) space nil nil s3s_3 nil
s2=[0,2)×[2,5)s_2 = [0,2) \times [2,5) space s1s_1 nil s5s_5 AA
A=[2,5)×[2,5)A = [2,5) \times [2,5) solid s1s_1 s2s_2 s5s_5 s4s_4
s3=[5,10)×[2,4)s_3 = [5,10) \times [2,4) space s1s_1 AA s6s_6 nil
s4=[5,6)×[4,5)s_4 = [5,6) \times [4,5) space s3s_3 AA s5s_5 BB
B=[6,9)×[4,7)B = [6,9) \times [4,7) solid s3s_3 s4s_4 s7s_7 s6s_6
s6=[9,10)×[4,7)s_6 = [9,10) \times [4,7) space s3s_3 BB s7s_7 nil
s5=[0,6)×[5,7)s_5 = [0,6) \times [5,7) space s2s_2 nil s7s_7 BB
s7=[0,10)×[7,8)s_7 = [0,10) \times [7,8) space s5s_5 nil nil nil

POINT-FIND((1,6))((1, 6)) from s1s_1: the height 6 is not below s1s_1, so L2 does nothing, and 6≥26 \ge 2 sends L3 to tr(s1)=s3tr(s_1) = s_3 and then to tr(s3)=s6tr(s_3) = s_6, where 4≤6<74 \le 6 < 7. Now 1<91 < 9, so L4 moves to lb(s6)=Blb(s_6) = B, then to lb(B)=s4lb(B) = s_4. In s4s_4 the height 6≥56 \ge 5, so L3 moves to tr(s4)=s5tr(s_4) = s_5, which contains (1,6)(1, 6). The walk visits s1,s3,s6,B,s4,s5s_1, s_3, s_6, B, s_4, s_5.

AREA-SEARCH([5,6)×[0,8))([5, 6) \times [0, 8)), the column between AA and BB: the left edge x=5x = 5 crosses s7s_7, s5s_5, s4s_4, s3s_3 and s1s_1 from the top down. Each is space and reaches x=6x = 6 or more, so line A3 never fires, and the answer is nil: a wire of width 1 fits there. ENUMERATE([1,8)×[1,6))([1, 8) \times [1, 6)) walks down the left edge through s5s_5, s2s_2 and s1s_1, and reports s5s_5, s2s_2, AA, s3s_3, s4s_4, BB, s1s_1. BB has two left neighbours, s4s_4 and s5s_5. It is reported from s4s_4, its owner, and not again from s5s_5, because the point just left of its lower left corner (6,4)(6, 4) lies in s4s_4.

DELETE(A)(A) splits s2s_2 and s4s_4 so that they lie inside the heights of AA, cuts AA at height 4, joins the rows, and settles them. The result has the four space tiles [0,10)×[0,4)[0,10) \times [0,4), [0,6)×[4,7)[0,6) \times [4,7), [9,10)×[4,7)[9,10) \times [4,7) and [0,10)×[7,8)[0,10) \times [7,8), which is the canonical form for BB alone.

Correctness

The proof is in proofs/correctness.md. Under (H) and (V) the space tile that contains a free point is fixed by the solid tiles, and there are at most 3n+13n + 1 space tiles: each new free strip met by an upward sweep is charged to the top-left corner, the bottom right end or the bottom left end of one solid tile. Point find is correct because the vertical phase stops in the row of the target, and each horizontal step moves to the next tile of that row, so the walk never comes back. Area search is correct because of (H): a space tile on the left edge of the area that ends before the right edge has a solid tile as its right neighbour. Enumeration reports each tile once because every tile right of the left edge has exactly one owner, the left neighbour that contains the point just left of its lower left corner inside the area, and only the owner pushes it. Insertion and deletion keep (H) and (V) because they rebuild the strips only where the solid set changed and then merge every changed strip with equal strips above and below.

Proof: Corner stitching keeps a canonical tiling with correct stitches, and its walks find what they claimfull

We use the model and the pseudocode of the page. The world is W=[X0,X1)×[Y0,Y1)W = [X_0, X_1) \times [Y_0, Y_1) with integer corners. A tile is a half-open rectangle [x0,x1)×[y0,y1)[x_0, x_1) \times [y_0, y_1) with integer corners and x0<x1x_0 < x_1, y0<y1y_0 < y_1, marked solid or space. Because all corners are integers, a point (x,y−ε)(x, y - \varepsilon) for a small ε>0\varepsilon > 0 lies in the same tile as the point (x,y−12)(x, y - \tfrac12), and we use the second form. The structure keeps four invariants.

  • (T) The tiles partition WW: each point of WW lies in exactly one tile.
  • (S) For each tile tt: bl(t)bl(t) is the tile that contains (x0,y0−12)(x_0, y_0 - \tfrac12), lb(t)lb(t) the tile that contains (x0−12,y0)(x_0 - \tfrac12, y_0), tr(t)tr(t) the tile that contains (x1−12,y1)(x_1 - \tfrac12, y_1), and rt(t)rt(t) the tile that contains (x1,y1−12)(x_1, y_1 - \tfrac12). A stitch whose point is outside WW is nil.
  • (H) No two space tiles share a piece of a vertical edge.
  • (V) No two space tiles with the same xx-span share a piece of a horizontal edge.

Two tiles are left and right neighbours if the right edge of one lies on the left edge of the other and their yy-spans overlap in an interval of positive length. Top and bottom neighbours are defined in the same way.

The canonical form

For a height yy and a free point (x,y)(x, y) (a point of WW in no solid tile), let σy(x)=[a,b)\sigma_y(x) = [a, b) be the maximal half-open interval that contains xx and is free at height yy.

Lemma 1 (uniqueness). Under (T), (H) and (V), the space tile that contains a free point p=(x,y)p = (x, y) is [a,b)×[c,d)[a, b) \times [c, d), where [a,b)=σy(x)[a, b) = \sigma_y(x) and [c,d)[c, d) is the maximal interval of heights that contains yy such that [a,b)[a, b) is a maximal free interval at every height of [c,d)[c, d). So the space tiles are fixed by the solid tiles.

Proof. Let s=[a′,b′)×[c′,d′)s = [a', b') \times [c', d') be the space tile that contains pp. Every point of ss is free. At each height y′y' of [c′,d′)[c', d'), the point (a′−12,y′)(a' - \tfrac12, y'), if it is in WW, lies in a left neighbour of ss, which is solid by (H). So a′a' is the left end of a maximal free interval at height y′y', and in the same way b′b' is the right end. Hence [a′,b′)=σy′(x)[a', b') = \sigma_{y'}(x) for all y′∈[c′,d′)y' \in [c', d'), and [c′,d′)⊆[c,d)[c', d') \subseteq [c, d) with [a′,b′)=[a,b)[a', b') = [a, b). Suppose d′<dd' < d. Then the free interval at height d′d' is [a,b)[a, b), and the tiles that contain the points (x′′,d′)(x'', d') with a≤x′′<ba \le x'' < b are space tiles. Take the one, s′s', that contains (a,d′)(a, d'). By the argument above applied to s′s', its xx-span is the maximal free interval [a,b)[a, b) at height d′d', so s′s' and ss have the same xx-span and share the edge at height d′d', which (V) forbids. So d′=dd' = d, and in the same way c′=cc' = c. □\square

Lemma 2 (space bound). If there are nn solid tiles, there are at most 3n+13n + 1 space tiles.

Proof. Sweep a horizontal line from Y0Y_0 upward. At each height the free part of the line is a set of maximal free intervals. By Lemma 1, a space tile is a maximal run of heights over which one interval [a,b)[a, b) stays a maximal free interval, so the number of space tiles is the number of times an interval appears: it is a maximal free interval at height yy and either y=Y0y = Y_0 or it is not a maximal free interval at height y−12y - \tfrac12. Let n0n_0 be the number of solid tiles with y0=Y0y_0 = Y_0. At Y0Y_0 these tiles cut the line into at most n0+1n_0 + 1 free intervals. We charge each appearance of [a,b)[a, b) at a height y>Y0y > Y_0 to one solid tile, by these rules.

  1. If a>X0a > X_0, the point (a−12,y)(a - \tfrac12, y) is not free, so it lies in a solid tile UU, and U.x1=aU.x_1 = a because (a,y)(a, y) is free. If U.y0=yU.y_0 = y, charge UU (a right side charge: an interval that starts at the right edge of UU, at the height of the bottom of UU).
  2. Else (a=X0a = X_0, or U.y0<yU.y_0 < y), the point (a−12,y−12)(a - \tfrac12, y - \tfrac12) is outside WW or in UU, so it is not free. If the point (a,y−12)(a, y - \tfrac12) lies in a solid tile TT, then T.y1=yT.y_1 = y (as (a,y)(a, y) is free) and T.x0=aT.x_0 = a (as T≠UT \ne U, because U.x1=aU.x_1 = a). Charge TT (a top-left charge: the top-left corner (T.x0,T.y1)(T.x_0, T.y_1) of TT lies in [a,b)[a, b) at height T.y1T.y_1).
  3. Else the point (a,y−12)(a, y - \tfrac12) is free, and the maximal free interval at height y−12y - \tfrac12 that contains it is [a,e)[a, e), since its left neighbour point is not free. It is not [a,b)[a, b), because [a,b)[a, b) appears at yy. If e>be > b, the point (b,y)(b, y) is not free and (b,y−12)(b, y - \tfrac12) is free, so (b,y)(b, y) lies in a solid tile VV with V.x0=bV.x_0 = b and V.y0=yV.y_0 = y. Charge VV (a left side charge: an interval that ends at the left edge of VV, at the height of the bottom of VV). If e<be < b, the point (e,y−12)(e, y - \tfrac12) lies in a solid tile TT with T.x0=eT.x_0 = e and T.y1=yT.y_1 = y, since (e−12,y−12)(e - \tfrac12, y - \tfrac12) and (e,y)(e, y) are free. Charge TT as a top-left charge.

A solid tile gets at most one charge of each type. For a top-left charge, the corner (T.x0,T.y1)(T.x_0, T.y_1) lies in at most one maximal free interval at height T.y1T.y_1. For a right side charge, exactly one interval starts at U.x1U.x_1 at height U.y0U.y_0, and for a left side charge, exactly one interval ends at V.x0V.x_0 at height V.y0V.y_0. Side charges happen only at heights y>Y0y > Y_0 with yy the bottom of the tile, so the n0n_0 tiles at the bottom of the world get none. So the number of space tiles is at most (n0+1)+n+2(n−n0)≤3n+1(n_0 + 1) + n + 2(n - n_0) \le 3n + 1. □\square

The walks

Lemma 3 (neighbour lists). Under (T) and (S), the four loops of the page list exactly the top, right, bottom and left neighbours of tt, in the stated orders.

Proof. We do the top side; the others follow by symmetry. tr(t)tr(t) contains (x1−12,y1)(x_1 - \tfrac12, y_1), so it is the top neighbour at the right end, and its bottom edge is at y1y_1 (a tile that contains (x1−12,y1)(x_1 - \tfrac12, y_1) and reached below y1y_1 would meet tt). Let uu be a top neighbour with u.x0>t.x0u.x_0 > t.x_0. Then lb(u)lb(u) contains (u.x0−12,u.y0)=(u.x0−12,t.y1)(u.x_0 - \tfrac12, u.y_0) = (u.x_0 - \tfrac12, t.y_1), which is above the top edge of tt, so lb(u)lb(u) is the next top neighbour to the left, and its right edge is u.x0>t.x0u.x_0 > t.x_0. If u.x0≤t.x0u.x_0 \le t.x_0, then lb(u)lb(u) has right edge u.x0≤t.x0u.x_0 \le t.x_0 and is not a top neighbour, and the loop stops. Each step moves strictly left along the line y=t.y1y = t.y_1, so the loop visits each top neighbour once. □\square

Lemma 4 (point find). Under (T) and (S), POINT-FIND returns the tile that contains p=(px,py)p = (p_x, p_y), from any start tile.

Proof. Line L2 moves to bl(t)bl(t), whose top edge is t.y0t.y_0, so the bottom edge strictly decreases and the loop stops with py≥t.y0p_y \ge t.y_0. It never leaves WW, since py≥Y0p_y \ge Y_0 and t.y0>pyt.y_0 > p_y give t.y0>Y0t.y_0 > Y_0. Line L3 moves to tr(t)tr(t), whose bottom edge is t.y1t.y_1, and stops with py<t.y1p_y < t.y_1; it does not undo L2, since every tile it reaches has y0≤pyy_0 \le p_y. So after L2 and L3, t.y0≤py<t.y1t.y_0 \le p_y < t.y_1.

Suppose px<t.x0p_x < t.x_0, so line L4 moves to u=lb(t)u = lb(t), which contains (t.x0−12,t.y0)(t.x_0 - \tfrac12, t.y_0) and has right edge t.x0t.x_0. Then u.y0≤t.y0≤pyu.y_0 \le t.y_0 \le p_y, so L2 does nothing. If py≥u.y1p_y \ge u.y_1, line L3 moves to tr(u)tr(u), which contains (t.x0−12,u.y1)(t.x_0 - \tfrac12, u.y_1). As u.y1≤py<t.y1u.y_1 \le p_y < t.y_1, this point is beside the left edge of tt, so tr(u)tr(u) is again a left neighbour of tt. By induction L3 stops at the tile t′t' that contains (t.x0−12,py)(t.x_0 - \tfrac12, p_y). The case px≥t.x1p_x \ge t.x_1 is the mirror: L5 and then L2 stop at the tile that contains (t.x1,py)(t.x_1, p_y).

So after the first time that L2 and L3 finish, each pass of the outer loop moves from the tile that contains a point (x,py)(x, p_y) to the next tile on the line y=pyy = p_y, to the left if pxp_x is left of the current tile and to the right otherwise. A tile reached by a left step has right edge greater than pxp_x, so the next step, if any, is again a left step; the same holds to the right. The tiles on the line y=pyy = p_y are finitely many and the walk never returns to one, so it stops, and it stops only at line L6, when tt contains pp. □\square

Lemma 5 (area search). Under all four invariants, AREA-SEARCH returns a solid tile that meets A=[ax0,ax1)×[ay0,ay1)A = [a_{x0}, a_{x1}) \times [a_{y0}, a_{y1}) if there is one, and nil otherwise.

Proof. The loop visits, from the top down, the tiles that contain the points (ax0,y)(a_{x0}, y) for ay0≤y<ay1a_{y0} \le y < a_{y1}: line A1 finds the top one, and line A5 finds the tile just below the current one on the line x=ax0x = a_{x0}, by Lemma 4. Each visited tile meets AA. If a visited tile is solid, line A2 returns it. If a visited space tile tt has t.x1<ax1t.x_1 < a_{x1}, the point (t.x1,min⁡(t.y1,ay1)−1)(t.x_1, \min(t.y_1, a_{y1}) - 1) is in AA and in a right neighbour of tt, which is solid by (H), and line A3 returns that tile. If no line returns a tile, every visited tile is space with t.x1≥ax1t.x_1 \ge a_{x1}, so for every height yy of AA the whole row [ax0,ax1)×{y}[a_{x0}, a_{x1}) \times \{y\} lies in one space tile, and AA is free. □\square

Lemma 6 (enumeration). Under all four invariants, ENUMERATE reports every tile that meets AA exactly once.

Proof. For a tile rr that meets AA with r.x0>ax0r.x_0 > a_{x0}, define its owner as the tile that contains (r.x0−12,max⁡(r.y0,ay0))(r.x_0 - \tfrac12, \max(r.y_0, a_{y0})). That point lies in AA (its xx is at least ax0a_{x0} because r.x0>ax0r.x_0 > a_{x0} and the corners are integers, and max⁡(r.y0,ay0)<ay1\max(r.y_0, a_{y0}) < a_{y1} because rr meets AA), so the owner meets AA, and it is the left neighbour of rr whose yy-span contains max⁡(r.y0,ay0)\max(r.y_0, a_{y0}). So a right neighbour ww of a tile uu that meets AA has owner uu exactly when max⁡(w.y0,ay0)≥u.y0\max(w.y_0, a_{y0}) \ge u.y_0, which is the test of line E9 together with w.y0<ay1w.y_0 < a_{y1} and w.y1>max⁡(u.y0,ay0)w.y_1 > \max(u.y_0, a_{y0}), the conditions for ww to meet AA.

The tiles with r.x0≤ax0r.x_0 \le a_{x0} that meet AA are exactly the tiles on the left edge of AA, and the outer loop reports each of them once, as in Lemma 5. The other tiles are reported from their owner. By induction on r.x0r.x_0: the owner has a smaller x0x_0, so it is reported exactly once, and when it is processed, line E9 pushes rr once. No tile is pushed by a tile that is not its owner, and a tile on the left edge has x0≤ax0x_0 \le a_{x0} and is never pushed. □\square

Split and merge keep (T) and (S)

Lemma 7. Each of the four primitives SPLIT-H, SPLIT-V, MERGE-V and MERGE-H keeps (T) and (S).

Proof. (T) holds because a split replaces a tile by two tiles with the same union and a merge replaces two tiles by their union, which is a rectangle by the precondition (the same span on the shared side).

For (S), a stitch of a tile ww is defined by one point qwq_w. The stitch can change only if the tile that contains qwq_w changes, that is, if qwq_w is in the changed tiles, or if ww itself is a changed tile. We give the case SPLIT-H(tt, yy), where t=[x0,x1)×[y0,y1)t = [x_0, x_1) \times [y_0, y_1) becomes t=[x0,x1)×[y0,y)t = [x_0, x_1) \times [y_0, y) and u=[x0,x1)×[y,y1)u = [x_0, x_1) \times [y, y_1).

  • The new tile uu: tr(u)tr(u) and rt(u)rt(u) have the same points as the old tr(t)tr(t) and rt(t)rt(t); bl(u)bl(u) contains (x0,y−12)(x_0, y - \tfrac12), which is in tt; lb(u)lb(u) contains (x0−12,y)(x_0 - \tfrac12, y), the left neighbour of the old tt found by walking up from lb(t)lb(t) while the top edge is at most yy (Lemma 3).
  • The tile tt: tr(t)tr(t) becomes uu, since (x1−12,y)(x_1 - \tfrac12, y) is in uu. rt(t)rt(t) becomes the tile that contains (x1,y−12)(x_1, y - \tfrac12), the right neighbour found by walking down from the old rt(t)rt(t) while the bottom edge is at least yy. bl(t)bl(t) and lb(t)lb(t) keep their points.
  • Other tiles: only stitches whose point lies in the old tt can change. A top neighbour ww of the old tt has qwq_w for bl(w)bl(w) at (w.x0,y1−12)(w.x_0, y_1 - \tfrac12), which is now in uu when it was in tt; the code tests bl(w)=tbl(w) = t. A right neighbour ww has lb(w)lb(w) at (x1−12,w.y0)(x_1 - \tfrac12, w.y_0), which lies in uu exactly when w.y0≥yw.y_0 \ge y; those are the right neighbours that the walk down from rt(t)rt(t) passes. A left neighbour ww has rt(w)rt(w) at (x0,w.y1−12)(x_0, w.y_1 - \tfrac12), which is in uu exactly when y<w.y1≤y1y < w.y_1 \le y_1; the walk over the left neighbours of uu tests rt(w)=trt(w) = t. A bottom neighbour ww has tr(w)tr(w) at (w.x1−12,y0)(w.x_1 - \tfrac12, y_0), which stays in tt. No other stitch has its point in the old tt.

SPLIT-V is the same argument with the axes exchanged. For MERGE-V(lolo, hihi), the stitches whose point is in hihi are blbl of the top neighbours of hihi, lblb of its right neighbours, rtrt of its left neighbours and tr(lo)tr(lo); after the merge these points are in lolo, and the code redirects exactly the stitches equal to hihi. The new tr(lo)tr(lo) and rt(lo)rt(lo) have the points of the old tr(hi)tr(hi) and rt(hi)rt(hi). MERGE-H is the mirror. □\square

Insertion and deletion keep (H) and (V)

Claim 8 (settling). During a sequence of SETTLE calls, every tile that has finished its call and is still alive has no space tile with the same xx-span directly above or below it.

Proof. A call ends only when its tile has no such neighbour. A merge during a later call joins two tiles xx and yy with the same span into mm. The top neighbours of mm are those of the upper tile and its bottom neighbours are those of the lower tile. If a finished tile zz had the span of mm and touched mm, it touched xx or yy, which have that span, which the claim excluded for zz already. □\square

Theorem 9 (insertion). If the four invariants hold and the area R=[a,b)×[c,d)R = [a, b) \times [c, d) is free, then after INSERT they hold again, and RR is one solid tile.

Proof. (T) and (S) hold by Lemma 7. Since RR is free, at every height of [c,d)[c, d) the interval [a,b)[a, b) lies in one maximal free interval, so by Lemma 1 the tiles that meet RR are space tiles that span [a,b)[a, b) entirely, stacked on the line x=ax = a. After the two cuts of lines I2 and I3, they lie inside the heights [c,d)[c, d). Line I5 cuts each of them at aa and bb into a left piece, a middle and a right piece, and line I6 joins the middles, which have the span [a,b)[a, b), into one solid tile equal to RR.

(H): a left piece keeps the left neighbours of its column tile, which are solid by (H) before, and its right neighbour is RR. A right piece is the mirror. The parts cut off at cc and dd keep the left and right neighbours of their old tiles. No other space tile changes its left or right neighbours.

(V): a pair of space tiles with the same span that touch vertically after the insertion must contain a tile that changed. The upper part uu cut off at dd has the span of its old tile, its top neighbours are those of the old tile, and its bottom neighbours are RR and the pieces, which are strictly narrower than uu; the part cut off at cc is the mirror. Every remaining changed space tile is a piece or a product of a merge in line I7, and by Claim 8 it has no space tile with the same span above or below. □\square

Theorem 10 (deletion). If the four invariants hold and D=[a,b)×[c,d)D = [a, b) \times [c, d) is a solid tile, then after DELETE they hold again for the solid tiles without DD.

Proof. (T) and (S) hold by Lemma 7. After line D2, every space left or right neighbour of DD lies inside the heights [c,d)[c, d). Line D4 cuts DD at every top and bottom edge of these neighbours that is strictly inside (c,d)(c, d), and line D5 cuts the neighbours at the same heights. Then for each piece pp of DD, the tiles beside its left edge are either all solid, or exactly one space tile with the same yy-span as pp: the yy-span of a space neighbour is a union of piece spans, and after D5 it is one piece span. That space tile, if it exists, contains (p.x0−12,p.y0)(p.x_0 - \tfrac12, p.y_0) and so it is lb(p)lb(p). The right side is the same with rt(p)rt(p).

(H): line D6 joins each piece with its space neighbours on both sides. A space neighbour of DD is a part of a space tile of the old structure, so its other neighbours on the far side are solid by (H) before. So each row tile runs from a solid tile or the world edge on the left to one on the right. The parts cut off at cc and dd keep the far side neighbours of their old tile and, on the near side, the old solid neighbours below cc or above dd.

(V): as in Theorem 9. A part ℓ\ell cut off above dd has the span of its old tile and that tile's top neighbours. Below it lies the top row tile, which contains ℓ\ell's span and also [a,b)[a, b), so it is wider. The part below cc is the mirror. All other changed space tiles go through SETTLE in line D7, and Claim 8 applies. □\square

Cost

Let deg⁡(t)\deg(t) be the number of neighbours of tt.

  • A neighbour list of tt costs O(1)O(1) for each listed tile (Lemma 3).
  • POINT-FIND visits no tile twice in its first vertical phase, since the heights of the visited tiles change in one direction. After that, by Lemma 4, the right edge of each visited tile (on a walk to the left) is at most the left edge of the tile of the step before, so no tile repeats there either. So it visits at most 2N2N tiles and costs O(N)O(N) for NN tiles in the worst case. The bound is tight: for nn solid unit squares in one row with one unit of space between them, a walk from the left end to the right end of the row crosses all 2n+12n + 1 tiles of the row.
  • ENUMERATE, after its first point find and the walk down the left edge, examines each pair (reported tile, right neighbour) once, so it costs O(k+e)O(k + e), where kk is the number of reported tiles and ee the number of such pairs.
  • A split or a merge of tiles tt and uu costs O(deg⁡(t)+deg⁡(u))O(\deg(t) + \deg(u)). INSERT and DELETE cost the point finds plus O(1+∑deg⁡)O(1 + \sum \deg) over the tiles they split or merge.

Complexity

operation worst case
NEIGHBOURS(t)(t) O(1+number of neighbours on that side)O(1 + \text{number of neighbours on that side})
POINT-FIND O(N)O(N)
AREA-SEARCH O(N)O(N)
ENUMERATE O(F+k+e)O(F + k + e), where FF is the cost of one point find and ee counts the right neighbours of the reported tiles that line E8 examines
INSERT, DELETE O(F+k+d)O(F + k + d)
space Θ(n)\Theta(n), at most 4n+14n + 1 tiles

All bounds are in the real RAM with exact comparisons of coordinates, and no arithmetic is needed. The O(N)O(N) bound of point find is tight: with nn solid unit squares in one row and gaps of width 1, a walk from the left end to the right end of the row crosses all 2n+12n + 1 tiles of the row. The fast case is a measured fact, not a theorem. Ousterhout measured that on real layouts a walk from the previous tile is short and grows about as the square root of the number of tiles, and on a k×kk \times k grid of unit squares with gaps of 1 the mean walk between random points visits about kk tiles (36.7 tiles on average for k=32k = 32, with 2080 tiles). No bound for a class of inputs is proved in the paper. Ousterhout also measured that the structure needs about three times the memory of a plain list of rectangles.

Variants

  • Several planes. Magic keeps one plane for each group of layers that interact, so a design rule between two layers is checked on one plane.
  • Material types. The solid flag becomes a type field. Two solid tiles of different types may touch, and the canonical form is kept for each type with the same rules.
  • Other tile shapes. Mehta and others describe trapezoidal, L-shaped and rectilinear tiles, which cut down the number of tiles for diagonal or L-shaped layouts.
  • Strips in the other direction. Maximal vertical strips are the mirror image and give the same bounds.

When to use it

Use it in an interactive layout editor, for design rule checking near a change, for circuit extraction by walking from tile to tile, and for compaction and maze routing in the free space, where the explicit empty tiles are the graph to search. A trapezoidal map also cuts the free space into simple cells, but it handles segments in any direction and gives expected O(log⁡n)O(\log n) point location with a search structure, while corner stitching handles only axis-parallel rectangles and relies on the locality of the previous query. Mechanical CAD stores parts in an R-tree or a quadtree of bounding boxes: those allow overlapping boxes and do not store empty space, so they answer box queries well but cannot answer "what is the nearest material to the right" with one stitch.

Pitfalls

  • The structure needs disjoint solid tiles. Overlapping rectangles from a layout file must be merged first, for example with a polygon union.
  • The canonical form must be restored after every update. A missed merge does not break point find, but it breaks area search, which uses (H), and the space bound.
  • A point on an edge belongs to the tile on its right or above it, because tiles are half-open. Mixing closed and half-open tiles gives walks that never stop.
  • Point find from a far start is slow. Keep the last tile found as a hint, which is what makes the measured times short.
  • An area search must start on the left edge of the area and use (H). Testing only the tiles that contain the corners misses a solid tile inside the area.

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.

corner_stitching.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/corner-stitching/. The authors are listed in prov/452WNT.jsonl.
"""Corner stitching (Ousterhout 1984) on a bounded world with integer coordinates.

The world is the half-open rectangle [X0, X1) x [Y0, Y1). It is cut into
half-open tiles [x0, x1) x [y0, y1), and every point of the world lies in
exactly one tile. A tile is solid or space. Space tiles are kept in the
canonical form of maximal horizontal strips:

  (H) no two space tiles share a vertical edge, and
  (V) no two space tiles with the same x-span share a horizontal edge.

Each tile has four stitches, defined by the point that the target tile
contains (e is a small positive number):

  bl: the tile that contains (x0, y0 - e)   (bottom neighbour at the left end)
  lb: the tile that contains (x0 - e, y0)   (left neighbour at the bottom end)
  tr: the tile that contains (x1 - e, y1)   (top neighbour at the right end)
  rt: the tile that contains (x1, y1 - e)   (right neighbour at the top end)

A stitch that would leave the world is None. Ousterhout stores only the
lower left corner of a tile and reads x1 and y1 from rt and tr. This code
stores all four coordinates, which is simpler to read and changes no
algorithm.
"""


class Tile:
    __slots__ = ("x0", "y0", "x1", "y1", "solid", "bl", "lb", "tr", "rt", "alive")

    def __init__(self, x0, y0, x1, y1, solid=False):
        self.x0, self.y0, self.x1, self.y1 = x0, y0, x1, y1
        self.solid = solid
        self.bl = self.lb = self.tr = self.rt = None
        self.alive = True

    def rect(self):
        return (self.x0, self.y0, self.x1, self.y1)

    def __repr__(self):
        kind = "solid" if self.solid else "space"
        return f"Tile({self.x0}, {self.y0}, {self.x1}, {self.y1}, {kind})"


def _space(t):
    return t is not None and not t.solid


class Plane:
    """A corner stitched plane over the world [x0, x1) x [y0, y1)."""

    def __init__(self, x0, y0, x1, y1):
        if not (x0 < x1 and y0 < y1):
            raise ValueError("empty world")
        t = Tile(x0, y0, x1, y1)
        self.world = (x0, y0, x1, y1)
        self.tiles = {t}
        self.hint = t

    # ------------------------------------------------------------ neighbours

    def top_neighbors(self, t):
        """Tiles that touch the top edge of t, from right to left."""
        out, u = [], t.tr
        while u is not None and u.x1 > t.x0:
            out.append(u)
            u = u.lb
        return out

    def right_neighbors(self, t):
        """Tiles that touch the right edge of t, from top to bottom."""
        out, u = [], t.rt
        while u is not None and u.y1 > t.y0:
            out.append(u)
            u = u.bl
        return out

    def bottom_neighbors(self, t):
        """Tiles that touch the bottom edge of t, from left to right."""
        out, u = [], t.bl
        while u is not None and u.x0 < t.x1:
            out.append(u)
            u = u.rt
        return out

    def left_neighbors(self, t):
        """Tiles that touch the left edge of t, from bottom to top."""
        out, u = [], t.lb
        while u is not None and u.y0 < t.y1:
            out.append(u)
            u = u.tr
        return out

    # ------------------------------------------------------------ point find

    def point_find(self, x, y, start=None):
        """The tile that contains the point (x, y), by walking the stitches."""
        X0, Y0, X1, Y1 = self.world
        if not (X0 <= x < X1 and Y0 <= y < Y1):
            raise ValueError("point outside the world")
        t = start if start is not None and start.alive else self.hint
        while True:  # @line L1
            while y < t.y0:  # @line L2
                t = t.bl
            while y >= t.y1:  # @line L3
                t = t.tr
            if x < t.x0:  # @line L4
                t = t.lb
            elif x >= t.x1:  # @line L5
                t = t.rt
            else:  # @line L6
                self.hint = t
                return t

    # ------------------------------------------------------------ area search

    def area_search(self, ax0, ay0, ax1, ay1):
        """A solid tile that meets the area [ax0, ax1) x [ay0, ay1), or None."""
        t = self.point_find(ax0, ay1 - 1)  # @line A1
        while True:
            if t.solid:  # @line A2
                return t
            if t.x1 < ax1:  # @line A3
                return self.point_find(t.x1, min(t.y1, ay1) - 1, t)
            if t.y0 <= ay0:  # @line A4
                return None
            t = self.point_find(ax0, t.y0 - 1, t)  # @line A5

    def enumerate_area(self, ax0, ay0, ax1, ay1):
        """Every tile that meets the area, each once, with no marks."""
        out = []
        t = self.point_find(ax0, ay1 - 1)  # @line E1
        while True:
            stack = [t]  # @line E2
            while stack:
                u = stack.pop()
                out.append(u)  # @line E6
                if u.x1 >= ax1:  # @line E7
                    continue
                w = u.rt  # @line E8
                low = max(u.y0, ay0)
                while w is not None and w.y1 > low:
                    if w.y0 < ay1 and max(w.y0, ay0) >= u.y0:  # @line E9
                        stack.append(w)
                    w = w.bl
            if t.y0 <= ay0:  # @line E3
                return out
            t = self.point_find(ax0, t.y0 - 1, t)  # @line E4

    # ------------------------------------------------------------ split and merge

    def _split_h(self, t, y):
        """Cut t at height y. t keeps the lower part; the upper part is returned."""
        top = t.y1
        u = Tile(t.x0, y, t.x1, top, t.solid)
        u.tr, u.rt, u.bl = t.tr, t.rt, t
        w = t.lb
        while w is not None and w.y1 <= y:
            w = w.tr
        u.lb = w
        w = t.rt
        while w is not None and w.y0 >= y:
            w.lb = u  # right neighbours above the cut
            w = w.bl
        t_rt = w
        w = t.tr
        while w is not None and w.x1 > t.x0:
            if w.bl is t:
                w.bl = u
            w = w.lb
        w = u.lb
        while w is not None and w.y0 < top:
            if w.rt is t:
                w.rt = u
            w = w.tr
        t.tr, t.rt, t.y1 = u, t_rt, y
        self.tiles.add(u)
        return u

    def _split_v(self, t, x):
        """Cut t at abscissa x. t keeps the left part; the right part is returned."""
        right = t.x1
        u = Tile(x, t.y0, right, t.y1, t.solid)
        u.rt, u.tr, u.lb = t.rt, t.tr, t
        w = t.bl
        while w is not None and w.x1 <= x:
            w = w.rt
        u.bl = w
        w = t.tr
        while w is not None and w.x0 >= x:
            w.bl = u  # top neighbours right of the cut
            w = w.lb
        t_tr = w
        w = t.rt
        while w is not None and w.y1 > t.y0:
            if w.lb is t:
                w.lb = u
            w = w.bl
        w = u.bl
        while w is not None and w.x0 < right:
            if w.tr is t:
                w.tr = u
            w = w.rt
        t.rt, t.tr, t.x1 = u, t_tr, x
        self.tiles.add(u)
        return u

    def _merge_v(self, lo, hi):
        """Join hi, which lies on lo with the same x-span, into lo."""
        w = hi.tr
        while w is not None and w.x1 > hi.x0:
            if w.bl is hi:
                w.bl = lo
            w = w.lb
        w = hi.rt
        while w is not None and w.y1 > hi.y0:
            if w.lb is hi:
                w.lb = lo
            w = w.bl
        w = hi.lb
        while w is not None and w.y0 < hi.y1:
            if w.rt is hi:
                w.rt = lo
            w = w.tr
        lo.tr, lo.rt, lo.y1 = hi.tr, hi.rt, hi.y1
        self._kill(hi)

    def _merge_h(self, le, ri):
        """Join ri, right of le with the same y-span, into le."""
        w = ri.tr
        while w is not None and w.x1 > ri.x0:
            if w.bl is ri:
                w.bl = le
            w = w.lb
        w = ri.bl
        while w is not None and w.x0 < ri.x1:
            if w.tr is ri:
                w.tr = le
            w = w.rt
        w = ri.rt
        while w is not None and w.y1 > ri.y0:
            if w.lb is ri:
                w.lb = le
            w = w.bl
        le.rt, le.tr, le.x1 = ri.rt, ri.tr, ri.x1
        self._kill(ri)

    def _kill(self, t):
        t.alive = False
        self.tiles.discard(t)
        if self.hint is t:
            self.hint = next(iter(self.tiles))

    def _settle(self, t):
        """Merge the space tile t with space tiles of the same x-span above and below."""
        while t.alive and not t.solid:
            u = t.tr
            if _space(u) and u.x0 == t.x0 and u.x1 == t.x1:
                self._merge_v(t, u)
                continue
            d = t.bl
            if _space(d) and d.x0 == t.x0 and d.x1 == t.x1:
                self._merge_v(d, t)
                t = d
                continue
            return

    # ------------------------------------------------------------ insert and delete

    def insert(self, ax0, ay0, ax1, ay1):
        """Make the area, which must be all space, one new solid tile."""
        X0, Y0, X1, Y1 = self.world
        if not (X0 <= ax0 < ax1 <= X1 and Y0 <= ay0 < ay1 <= Y1):
            raise ValueError("bad rectangle")
        if self.area_search(ax0, ay0, ax1, ay1) is not None:  # @line I1
            raise ValueError("area is not empty")
        t = self.point_find(ax0, ay1 - 1)  # @line I2
        if t.y1 > ay1:
            self._split_h(t, ay1)
        t = self.point_find(ax0, ay0)  # @line I3
        if t.y0 < ay0:
            self._split_h(t, ay0)
        column, t = [], self.point_find(ax0, ay1 - 1)  # @line I4
        while True:
            column.append(t)
            if t.y0 <= ay0:
                break
            t = self.point_find(ax0, t.y0 - 1, t)
        sides, middles = [], []
        for s in column:  # @line I5
            if s.x0 < ax0:
                m = self._split_v(s, ax0)
                sides.append(s)
            else:
                m = s
            if m.x1 > ax1:
                sides.append(self._split_v(m, ax1))
            m.solid = True
            middles.append(m)
        new = middles[-1]  # @line I6
        for m in reversed(middles[:-1]):
            self._merge_v(new, m)
        for s in sides:  # @line I7
            self._settle(s)
        self.hint = new
        return new

    def delete(self, d):
        """Turn the solid tile d into space and restore the canonical form."""
        if not (d.alive and d.solid):
            raise ValueError("not a live solid tile")
        d.solid = False  # @line D1
        c, top = d.y0, d.y1
        for w in self.left_neighbors(d) + self.right_neighbors(d):  # @line D2
            if not w.solid:
                if w.y0 < c:
                    w = self._split_h(w, c)
                if w.y1 > top:
                    self._split_h(w, top)
        cuts = set()  # @line D3
        for w in self.left_neighbors(d) + self.right_neighbors(d):
            if not w.solid:
                cuts.update(h for h in (w.y0, w.y1) if c < h < top)
        cuts = sorted(cuts)
        pieces, t = [], d  # @line D4
        for h in cuts:
            u = self._split_h(t, h)
            pieces.append(t)
            t = u
        pieces.append(t)
        side = []  # @line D5
        for p in pieces:
            for w in self.left_neighbors(p) + self.right_neighbors(p):
                if not w.solid and w not in side:
                    side.append(w)
        for w in side:
            for h in cuts:
                if w.y0 < h < w.y1:
                    w = self._split_h(w, h)
        rows = []
        for p in pieces:  # @line D6
            le = p.lb
            if _space(le) and le.y0 == p.y0 and le.y1 == p.y1:
                self._merge_h(le, p)
                p = le
            ri = p.rt
            if _space(ri) and ri.y0 == p.y0 and ri.y1 == p.y1:
                self._merge_h(p, ri)
            rows.append(p)
        for p in rows:  # @line D7
            self._settle(p)
test_corner_stitching.py 192 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/corner-stitching/. The authors are listed in prov/452WNT.jsonl.

import random

import pytest

from corner_stitching import Plane

W, H = 14, 12


def owner_grid(plane):
    """owner[x][y] is the tile that holds the unit cell [x, x+1) x [y, y+1).
    Every cell must be covered exactly once."""
    X0, Y0, X1, Y1 = plane.world
    owner = [[None] * (Y1 - Y0) for _ in range(X1 - X0)]
    for t in plane.tiles:
        assert t.x0 < t.x1 and t.y0 < t.y1
        for x in range(t.x0, t.x1):
            for y in range(t.y0, t.y1):
                assert owner[x - X0][y - Y0] is None, "tiles overlap"
                owner[x - X0][y - Y0] = t
    assert all(c is not None for col in owner for c in col), "a hole in the tiling"
    return owner


def canonical_space(solids, world):
    """Maximal horizontal strips of the free cells, by brute force over rows."""
    X0, Y0, X1, Y1 = world
    busy = set()
    for (a, b, c, d) in solids:
        for x in range(a, c):
            for y in range(b, d):
                busy.add((x, y))
    out, open_ = set(), {}
    for y in range(Y0, Y1 + 1):
        segs = set()
        if y < Y1:
            x = X0
            while x < X1:
                if (x, y) in busy:
                    x += 1
                    continue
                s = x
                while x < X1 and (x, y) not in busy:
                    x += 1
                segs.add((s, x))
        for seg in list(open_):
            if seg not in segs:
                out.add((seg[0], open_.pop(seg), seg[1], y))
        for seg in segs:
            open_.setdefault(seg, y)
    return out


def check(plane, solids):
    """Compare the whole structure with brute force."""
    X0, Y0, X1, Y1 = plane.world
    owner = owner_grid(plane)

    def at(x, y):
        if X0 <= x < X1 and Y0 <= y < Y1:
            return owner[x - X0][y - Y0]
        return None

    assert {t.rect() for t in plane.tiles if t.solid} == set(solids)
    assert {t.rect() for t in plane.tiles if not t.solid} == canonical_space(solids, plane.world)
    n_space = sum(1 for t in plane.tiles if not t.solid)
    assert n_space <= 3 * len(solids) + 1
    for t in plane.tiles:
        assert t.alive
        assert t.bl is at(t.x0, t.y0 - 1)
        assert t.lb is at(t.x0 - 1, t.y0)
        assert t.tr is at(t.x1 - 1, t.y1)
        assert t.rt is at(t.x1, t.y1 - 1)
    return at


def brute_neighbors(plane, t):
    tiles = plane.tiles
    top = [u for u in tiles if u.y0 == t.y1 and u.x0 < t.x1 and u.x1 > t.x0]
    right = [u for u in tiles if u.x0 == t.x1 and u.y0 < t.y1 and u.y1 > t.y0]
    bottom = [u for u in tiles if u.y1 == t.y0 and u.x0 < t.x1 and u.x1 > t.x0]
    left = [u for u in tiles if u.x1 == t.x0 and u.y0 < t.y1 and u.y1 > t.y0]
    return (
        sorted(top, key=lambda u: -u.x0),
        sorted(right, key=lambda u: -u.y0),
        sorted(bottom, key=lambda u: u.x0),
        sorted(left, key=lambda u: u.y0),
    )


def queries(plane, solids, at, rng):
    tiles = list(plane.tiles)
    for _ in range(30):
        x, y = rng.randrange(W), rng.randrange(H)
        assert plane.point_find(x, y, rng.choice(tiles)) is at(x, y)
    for _ in range(15):
        ax0, ax1 = sorted(rng.sample(range(W + 1), 2))
        ay0, ay1 = sorted(rng.sample(range(H + 1), 2))
        meets = [u for u in tiles if u.x0 < ax1 and u.x1 > ax0 and u.y0 < ay1 and u.y1 > ay0]
        got = plane.enumerate_area(ax0, ay0, ax1, ay1)
        assert len(got) == len(set(map(id, got))), "a tile was reported twice"
        assert set(map(id, got)) == set(map(id, meets))
        hit = plane.area_search(ax0, ay0, ax1, ay1)
        if any(u.solid for u in meets):
            assert hit is not None and hit.solid and hit in meets
        else:
            assert hit is None
    for t in rng.sample(tiles, min(6, len(tiles))):
        want = brute_neighbors(plane, t)
        got = (plane.top_neighbors(t), plane.right_neighbors(t),
               plane.bottom_neighbors(t), plane.left_neighbors(t))
        assert got == want


def test_empty_world():
    p = Plane(0, 0, W, H)
    at = check(p, [])
    assert len(p.tiles) == 1
    assert p.area_search(0, 0, W, H) is None
    queries(p, [], at, random.Random(1))


def test_page_example():
    # The example of the page: world [0, 10) x [0, 8), two solid tiles.
    p = Plane(0, 0, 10, 8)
    a = p.insert(2, 2, 5, 5)
    b = p.insert(6, 4, 9, 7)
    space = sorted(t.rect() for t in p.tiles if not t.solid)
    assert space == [(0, 0, 10, 2), (0, 2, 2, 5), (0, 5, 6, 7), (0, 7, 10, 8),
                     (5, 2, 10, 4), (5, 4, 6, 5), (9, 4, 10, 7)]
    assert a.tr.rect() == (0, 5, 6, 7) and a.rt.rect() == (5, 4, 6, 5)
    assert a.bl.rect() == (0, 0, 10, 2) and a.lb.rect() == (0, 2, 2, 5)
    check(p, [(2, 2, 5, 5), (6, 4, 9, 7)])
    start = p.point_find(0, 0)
    assert p.point_find(7, 5, start) is b
    assert p.area_search(5, 0, 6, 8) is None
    assert p.area_search(4, 6, 7, 8) is b
    p.delete(a)
    check(p, [(6, 4, 9, 7)])


def test_insert_rejects_overlap():
    p = Plane(0, 0, W, H)
    p.insert(3, 3, 6, 6)
    with pytest.raises(ValueError):
        p.insert(5, 5, 8, 8)
    check(p, [(3, 3, 6, 6)])


@pytest.mark.parametrize("seed", range(20))
def test_random_insert_delete(seed):
    rng = random.Random(seed)
    p = Plane(0, 0, W, H)
    solids = {}
    for step in range(150):
        if solids and rng.random() < 0.3:
            r = rng.choice(sorted(solids))
            p.delete(solids.pop(r))
        else:
            w, h = rng.randint(1, 5), rng.randint(1, 4)
            x, y = rng.randrange(W - w + 1), rng.randrange(H - h + 1)
            r = (x, y, x + w, y + h)
            free = all(r[2] <= s[0] or s[2] <= r[0] or r[3] <= s[1] or s[3] <= r[1] for s in solids)
            if free:
                solids[r] = p.insert(*r)
            else:
                with pytest.raises(ValueError):
                    p.insert(*r)
        at = check(p, list(solids))
        if step % 5 == 0:
            queries(p, list(solids), at, rng)


def test_unit_cells_dense():
    # Fill a checkerboard of unit squares, then remove them in random order.
    rng = random.Random(7)
    p = Plane(0, 0, 8, 8)
    solids = {}
    for x in range(8):
        for y in range(8):
            if (x + y) % 2 == 0:
                solids[(x, y, x + 1, y + 1)] = p.insert(x, y, x + 1, y + 1)
    check(p, list(solids))
    keys = sorted(solids)
    rng.shuffle(keys)
    for r in keys:
        p.delete(solids.pop(r))
        check(p, list(solids))
    assert len(p.tiles) == 1

History

Ousterhout published corner stitching in IEEE TCAD in January 1984, and the Magic editor that used it was presented at the Design Automation Conference of the same year. The extractor, the design rule checker, the router and the compactor (plowing) of Magic all work on corner stitched planes. Mehta later gave the exact count 3n+1−k3n + 1 - k of space tiles, where kk counts a kind of corner alignment, and studied the L-shaped variant.

References

  1. John K. Ousterhout, Corner stitching, a data-structuring technique for VLSI layout tools, IEEE Transactions on Computer-Aided Design of Integrated Circuits and Systems 3(1), 87 to 100, 1984, the tiles and the four stitches, the maximal horizontal strips, the algorithms for neighbour finding, point finding, area search, area enumeration, tile creation and tile deletion, and the measurements of memory and of point finding time
  2. John K. Ousterhout, Gordon T. Hamachi, Robert N. Mayo, Walter S. Scott and George S. Taylor, Magic, a VLSI layout system, Proceedings of the 21st Design Automation Conference, 1984, the use of corner stitched planes, one for each group of mask layers, as the database of the Magic editor (check the page range)
  3. Dinesh P. Mehta and Sartaj Sahni (editors), Handbook of Data Structures and Applications, Chapman and Hall/CRC, 2005, Chapter 52, Layout Data Structures, by Dinesh P. Mehta, Section 52.4 (corner stitching, point finding, tile insertion and the storage bound of 3N + 1 minus the number of violations for the space tiles) and Section 52.5 (extensions)

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