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
- Model
- Real RAM
- Evidence
- Full proofCode in 1 languages
- 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 of disjoint closed-open rectangles with corners in a world rectangle . It supports these operations.
- POINT-FIND: the tile that contains the point .
- NEIGHBOURS: the tiles that touch one side of the tile , in order along that side.
- AREA-SEARCH: some rectangle of that meets the rectangle , or nil if is empty.
- ENUMERATE: every tile that meets , solid and space, each once.
- INSERT: add a rectangle that meets no rectangle of .
- DELETE: remove the rectangle of the solid tile .
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 with a flag solid or space. The tiles form a planar subdivision of into axis-parallel rectangles. The four stitches are defined by the point that the target tile contains, for a small :
| stitch | target tile contains | meaning |
|---|---|---|
| bottom neighbour at the left end | ||
| left neighbour at the bottom end | ||
| top neighbour at the right end | ||
| right neighbour at the top end |
A stitch that would leave is nil. Ousterhout stores only the lower left corner of a tile and reads from and from , 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 -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 of them, so tiles in all. Both facts are proved in proofs/correctness.md.
Operations
POINT-FIND(p = (px, py), t) ▷ t: any start tile, for example the last tile found- 1
repeat - 2
while py < y0(t) do t ← bl(t) - 3
while py ≥ y1(t) do t ← tr(t) - 4
if px < x0(t) then t ← lb(t) - 5
else if px ≥ x1(t) then t ← rt(t) - 6
else return t TOP-NEIGHBOURS(t) ▷ the other three sides are symmetricN1 u ← tr(t)N2 while u ≠ nil and x1(u) > x0(t) do output u; u ← lb(u)AREA-SEARCH(A = [ax0, ax1) × [ay0, ay1))A1 t ← POINT-FIND((ax0, ay1 − ε)) ▷ the top tile on the left edge of AA2 repeat if t is solid then return tA3 if x1(t) < ax1 then return POINT-FIND((x1(t), min(y1(t), ay1) − ε), t) ▷ solid by (H)A4 if y0(t) ≤ ay0 then return nilA5 t ← POINT-FIND((ax0, y0(t) − ε), t)ENUMERATE(A)E1 t ← POINT-FIND((ax0, ay1 − ε))E2 repeat REPORT(t)E3 if y0(t) ≤ ay0 then returnE4 t ← POINT-FIND((ax0, y0(t) − ε), t)REPORT(u)E5 stack ← [u]; while stack is not empty do u ← pop(stack)E6 output uE7 if x1(u) ≥ ax1 then continueE8 for each right neighbour w of u, from rt(u) down, with y1(w) > max(y0(u), ay0) doE9 if y0(w) < ay1 and max(y0(w), ay0) ≥ y0(u) then push w ▷ u owns wINSERT(R = [a, b) × [c, d))I1 if AREA-SEARCH(R) ≠ nil then failI2 split the tile at (a, d − ε) horizontally at dI3 split the tile at (a, c) horizontally at cI4 C ← the space tiles on the line x = a between c and d, from the top downI5 split each tile of C vertically at a and at b; mark each middle part solidI6 merge the middle parts into one solid tile RI7 for each left and right part s do SETTLE(s) ▷ merge s with space tiles of the same x-span above and belowDELETE(D = [a, b) × [c, d))D1 mark D as spaceD2 split each space left or right neighbour of D at c and at dD3 H ← the top and bottom edges of these neighbours that lie strictly between c and dD4 split D horizontally at every height of H into piecesD5 split each space left or right neighbour of a piece at every height of HD6 for each piece p do merge p with lb(p) and with rt(p) when they are space with the y-span of pD7 for each row tile r made in D6 do SETTLE(r)
Split and merge are local. To split at a height , make the upper part , find by walking up the left neighbours of and the new by walking down its right neighbours, and redirect the stitches of the neighbours whose defining point now lies in . 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 with two solid tiles and . The canonical space tiles are the seven maximal strips below, which reach the bound .
| tile | kind | ||||
|---|---|---|---|---|---|
| space | nil | nil | nil | ||
| space | nil | ||||
| solid | |||||
| space | nil | ||||
| space | |||||
| solid | |||||
| space | nil | ||||
| space | nil | ||||
| space | nil | nil | nil |
POINT-FIND from : the height 6 is not below , so L2 does nothing, and sends L3 to and then to , where . Now , so L4 moves to , then to . In the height , so L3 moves to , which contains . The walk visits .
AREA-SEARCH, the column between and : the left edge crosses , , , and from the top down. Each is space and reaches or more, so line A3 never fires, and the answer is nil: a wire of width 1 fits there. ENUMERATE walks down the left edge through , and , and reports , , , , , , . has two left neighbours, and . It is reported from , its owner, and not again from , because the point just left of its lower left corner lies in .
DELETE splits and so that they lie inside the heights of , cuts at height 4, joins the rows, and settles them. The result has the four space tiles , , and , which is the canonical form for 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 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 with integer corners. A tile is a half-open rectangle with integer corners and , , marked solid or space. Because all corners are integers, a point for a small lies in the same tile as the point , and we use the second form. The structure keeps four invariants.
- (T) The tiles partition : each point of lies in exactly one tile.
- (S) For each tile : is the tile that contains , the tile that contains , the tile that contains , and the tile that contains . A stitch whose point is outside is nil.
- (H) No two space tiles share a piece of a vertical edge.
- (V) No two space tiles with the same -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 -spans overlap in an interval of positive length. Top and bottom neighbours are defined in the same way.
The canonical form
For a height and a free point (a point of in no solid tile), let be the maximal half-open interval that contains and is free at height .
Lemma 1 (uniqueness). Under (T), (H) and (V), the space tile that contains a free point is , where and is the maximal interval of heights that contains such that is a maximal free interval at every height of . So the space tiles are fixed by the solid tiles.
Proof. Let be the space tile that contains . Every point of is free. At each height of , the point , if it is in , lies in a left neighbour of , which is solid by (H). So is the left end of a maximal free interval at height , and in the same way is the right end. Hence for all , and with . Suppose . Then the free interval at height is , and the tiles that contain the points with are space tiles. Take the one, , that contains . By the argument above applied to , its -span is the maximal free interval at height , so and have the same -span and share the edge at height , which (V) forbids. So , and in the same way .
Lemma 2 (space bound). If there are solid tiles, there are at most space tiles.
Proof. Sweep a horizontal line from 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 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 and either or it is not a maximal free interval at height . Let be the number of solid tiles with . At these tiles cut the line into at most free intervals. We charge each appearance of at a height to one solid tile, by these rules.
- If , the point is not free, so it lies in a solid tile , and because is free. If , charge (a right side charge: an interval that starts at the right edge of , at the height of the bottom of ).
- Else (, or ), the point is outside or in , so it is not free. If the point lies in a solid tile , then (as is free) and (as , because ). Charge (a top-left charge: the top-left corner of lies in at height ).
- Else the point is free, and the maximal free interval at height that contains it is , since its left neighbour point is not free. It is not , because appears at . If , the point is not free and is free, so lies in a solid tile with and . Charge (a left side charge: an interval that ends at the left edge of , at the height of the bottom of ). If , the point lies in a solid tile with and , since and are free. Charge as a top-left charge.
A solid tile gets at most one charge of each type. For a top-left charge, the corner lies in at most one maximal free interval at height . For a right side charge, exactly one interval starts at at height , and for a left side charge, exactly one interval ends at at height . Side charges happen only at heights with the bottom of the tile, so the tiles at the bottom of the world get none. So the number of space tiles is at most .
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 , in the stated orders.
Proof. We do the top side; the others follow by symmetry. contains , so it is the top neighbour at the right end, and its bottom edge is at (a tile that contains and reached below would meet ). Let be a top neighbour with . Then contains , which is above the top edge of , so is the next top neighbour to the left, and its right edge is . If , then has right edge and is not a top neighbour, and the loop stops. Each step moves strictly left along the line , so the loop visits each top neighbour once.
Lemma 4 (point find). Under (T) and (S), POINT-FIND returns the tile that contains , from any start tile.
Proof. Line L2 moves to , whose top edge is , so the bottom edge strictly decreases and the loop stops with . It never leaves , since and give . Line L3 moves to , whose bottom edge is , and stops with ; it does not undo L2, since every tile it reaches has . So after L2 and L3, .
Suppose , so line L4 moves to , which contains and has right edge . Then , so L2 does nothing. If , line L3 moves to , which contains . As , this point is beside the left edge of , so is again a left neighbour of . By induction L3 stops at the tile that contains . The case is the mirror: L5 and then L2 stop at the tile that contains .
So after the first time that L2 and L3 finish, each pass of the outer loop moves from the tile that contains a point to the next tile on the line , to the left if is left of the current tile and to the right otherwise. A tile reached by a left step has right edge greater than , so the next step, if any, is again a left step; the same holds to the right. The tiles on the line are finitely many and the walk never returns to one, so it stops, and it stops only at line L6, when contains .
Lemma 5 (area search). Under all four invariants, AREA-SEARCH returns a solid tile that meets if there is one, and nil otherwise.
Proof. The loop visits, from the top down, the tiles that contain the points for : line A1 finds the top one, and line A5 finds the tile just below the current one on the line , by Lemma 4. Each visited tile meets . If a visited tile is solid, line A2 returns it. If a visited space tile has , the point is in and in a right neighbour of , which is solid by (H), and line A3 returns that tile. If no line returns a tile, every visited tile is space with , so for every height of the whole row lies in one space tile, and is free.
Lemma 6 (enumeration). Under all four invariants, ENUMERATE reports every tile that meets exactly once.
Proof. For a tile that meets with , define its owner as the tile that contains . That point lies in (its is at least because and the corners are integers, and because meets ), so the owner meets , and it is the left neighbour of whose -span contains . So a right neighbour of a tile that meets has owner exactly when , which is the test of line E9 together with and , the conditions for to meet .
The tiles with that meet are exactly the tiles on the left edge of , and the outer loop reports each of them once, as in Lemma 5. The other tiles are reported from their owner. By induction on : the owner has a smaller , so it is reported exactly once, and when it is processed, line E9 pushes once. No tile is pushed by a tile that is not its owner, and a tile on the left edge has and is never pushed.
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 is defined by one point . The stitch can change only if the tile that contains changes, that is, if is in the changed tiles, or if itself is a changed tile. We give the case SPLIT-H(, ), where becomes and .
- The new tile : and have the same points as the old and ; contains , which is in ; contains , the left neighbour of the old found by walking up from while the top edge is at most (Lemma 3).
- The tile : becomes , since is in . becomes the tile that contains , the right neighbour found by walking down from the old while the bottom edge is at least . and keep their points.
- Other tiles: only stitches whose point lies in the old can change. A top neighbour of the old has for at , which is now in when it was in ; the code tests . A right neighbour has at , which lies in exactly when ; those are the right neighbours that the walk down from passes. A left neighbour has at , which is in exactly when ; the walk over the left neighbours of tests . A bottom neighbour has at , which stays in . No other stitch has its point in the old .
SPLIT-V is the same argument with the axes exchanged. For MERGE-V(, ), the stitches whose point is in are of the top neighbours of , of its right neighbours, of its left neighbours and ; after the merge these points are in , and the code redirects exactly the stitches equal to . The new and have the points of the old and . MERGE-H is the mirror.
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 -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 and with the same span into . The top neighbours of are those of the upper tile and its bottom neighbours are those of the lower tile. If a finished tile had the span of and touched , it touched or , which have that span, which the claim excluded for already.
Theorem 9 (insertion). If the four invariants hold and the area is free, then after INSERT they hold again, and is one solid tile.
Proof. (T) and (S) hold by Lemma 7. Since is free, at every height of the interval lies in one maximal free interval, so by Lemma 1 the tiles that meet are space tiles that span entirely, stacked on the line . After the two cuts of lines I2 and I3, they lie inside the heights . Line I5 cuts each of them at and into a left piece, a middle and a right piece, and line I6 joins the middles, which have the span , into one solid tile equal to .
(H): a left piece keeps the left neighbours of its column tile, which are solid by (H) before, and its right neighbour is . A right piece is the mirror. The parts cut off at and 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 cut off at has the span of its old tile, its top neighbours are those of the old tile, and its bottom neighbours are and the pieces, which are strictly narrower than ; the part cut off at 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.
Theorem 10 (deletion). If the four invariants hold and is a solid tile, then after DELETE they hold again for the solid tiles without .
Proof. (T) and (S) hold by Lemma 7. After line D2, every space left or right neighbour of lies inside the heights . Line D4 cuts at every top and bottom edge of these neighbours that is strictly inside , and line D5 cuts the neighbours at the same heights. Then for each piece of , the tiles beside its left edge are either all solid, or exactly one space tile with the same -span as : the -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 and so it is . The right side is the same with .
(H): line D6 joins each piece with its space neighbours on both sides. A space neighbour of 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 and keep the far side neighbours of their old tile and, on the near side, the old solid neighbours below or above .
(V): as in Theorem 9. A part cut off above has the span of its old tile and that tile's top neighbours. Below it lies the top row tile, which contains 's span and also , so it is wider. The part below is the mirror. All other changed space tiles go through SETTLE in line D7, and Claim 8 applies.
Cost
Let be the number of neighbours of .
- A neighbour list of costs 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 tiles and costs for tiles in the worst case. The bound is tight: for 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 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 , where is the number of reported tiles and the number of such pairs.
- A split or a merge of tiles and costs . INSERT and DELETE cost the point finds plus over the tiles they split or merge.
Complexity
| operation | worst case |
|---|---|
| NEIGHBOURS | |
| POINT-FIND | |
| AREA-SEARCH | |
| ENUMERATE | , where is the cost of one point find and counts the right neighbours of the reported tiles that line E8 examines |
| INSERT, DELETE | |
| space | , at most tiles |
All bounds are in the real RAM with exact comparisons of coordinates, and no arithmetic is needed. The bound of point find is tight: with 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 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 grid of unit squares with gaps of 1 the mean walk between random points visits about tiles (36.7 tiles on average for , 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 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.
# 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 of space tiles, where counts a kind of corner alignment, and studied the L-shaped variant.
References
- 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
- 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)
- 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.
| 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 452WNT Edit this page History Report an error Markdown