Algorithmadvanced
Volume decomposition feature recognition
Also called cell-based feature recognition, delta volume decomposition.
Recognises machining features by splitting the removal volume, stock minus part, into cells and merging the cells into feature volumes such as slots, steps and pockets.
- Solves
- Feature recognition
- Time
- O(n^4 + m^k n^2) worst
- Space
- O(m n^2) extra
- Where
- k = the size of a minimum cover; m = the number of maximal rectangles of the removal area; n = the number of vertices of the part
- Model
- Word RAM
- Properties
- deterministicexactrecursive
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Hiroshi Sakurai, 1995
Volume decomposition recognises machining features from the material that has to be removed, not from the faces of the part. Given a part and its stock , the removal volume, or delta volume, is . The method cuts into cells by extending the faces of the part, merges the cells into large simple volumes, and picks a set of those volumes that covers . Each chosen volume is a feature, such as a slot, a step or a pocket, depending on which of its sides lie on the boundary of the stock. Because it works on volumes, the method copes with interacting features whose faces are split or partly missing. It also gives an exact certificate: the part equals the stock minus the union of the features. Sakurai gave the cell decomposition in 1995, and Woo and Sakurai refined it into maximal features in 2002. This page gives the method for a rectilinear polygon in the plane. There it is exact and short, and the page proves that the output expression equals the part.
In plain words
You have a block of metal, and the drawing of the finished part. Everything that is in the block but not in the part must be cut away. Volume decomposition looks at that waste material and asks how to describe it as a few simple shapes, each of which a cutter could remove in one go.
To do it, it extends every face of the part across the whole block, like slicing a cake along every edge line. The slices that are waste get glued back together into the biggest boxes that stay inside the waste. Then it keeps the fewest boxes that together cover all the waste.
Each box is a feature. A box open at the top is a slot or a pocket. A box open on two sides is a step. Subtract the boxes from the block and you get the part back exactly.
The problem
The input is a simple rectilinear polygon , given as a list of vertices with integer coordinates, the 2D section of a prismatic part. The stock is the bounding box of , so is the area to remove. The output is a list of axis-parallel rectangles , each with the sides of it touches, such that
- each lies in and is maximal: no larger axis-parallel rectangle inside contains it,
- , so ,
- is as small as possible.
A rectangle that touches the top side of can be cut from the top. One that touches two adjacent sides is a step. One that touches no side is an undercut, like the wide head of a T-slot under its narrow neck. No tool moving along an axis from outside can reach it, and the method reports it with no open sides.
The algorithm
Line L1 builds the grid from all vertex coordinates. Every edge of lies on a grid line, so each open grid cell lies wholly inside or wholly outside , and line L2 classifies it by its centre. Lines L3 and L4 list the maximal blocks of cells in . A block is a range of cell columns times a range of cell rows. It is kept if all its cells are in and it cannot grow by one row or column of cells on any side. Line L5 is a depth-first branch and bound for the smallest set cover of the cells by maximal blocks. It always branches on the first uncovered cell, since some chosen block must contain it.
RECOGNIZE(P)- 1
xs, ys ← the sorted distinct x and y coordinates of the vertices of P; W ← [xs_first, xs_last] × [ys_first, ys_last] - 2
D ← the grid cells whose centre is not inside P B ← empty listfor each block of cells [i0, i1) × [j0, j1) of the grid do- 3
if the block holds a cell not in D then skip it - 4
if the block grown by one row or column on some side lies in D then skip it append the block to Bcover ← MIN-COVER(D, B)- 5
return W and the rectangles of cover, each with its sides that lie on the boundary of W MIN-COVER(D, B)best ← BSEARCH(chosen, covered):if |chosen| ≥ |best| then returnc ← the first cell of D in sorted order that is not in coveredif there is no such c then best ← chosen and return- 6
for each block b of B that contains c do SEARCH(chosen + [b], covered ∪ cells(b)) SEARCH([], ∅) and return best
A 2D prefix sum over the cells answers "are all cells of this block in ?" in constant time, which makes lines L3 and L4 cost per block. The maximal blocks are the maximal all-ones submatrices of the cell matrix, the objects of the maximal rectangle problem.
Example
Take the block with a stepped slot cut into its top: a wide upper slot and a narrow lower slot below it. The part has the 12 vertices
| step | result |
|---|---|
| grid lines (L1) | , , so cells |
| delta cells (L2) | , , , |
| maximal blocks (L3, L4) | and |
| cover (L5) | both are needed: the cell is only in , and is only in |
| features (L6) | open at the top, a wide shallow slot; open at the top, a narrow deep slot |
The result is . The areas check: . The two features overlap in . That overlap is the point of maximal volumes. The narrow slot is reported at its full depth from the top, where a cutter enters, and not as the closed box floating under the wide slot. A face-based recognizer sees the floor of the wide slot split in two by the narrow one, and has to work to find either feature.
A second case shows a corner. For the part with vertices , the delta area is an L shape at the top right. Its maximal rectangles are and , both open on the right and on the top, so both are steps. They overlap in the corner square , which either step can take.
A T-slot shows the third kind. Cut a neck into the top of , with a head under it. The cover is , open at the top, and the head , which has no open side. The expression is still exact, but the head is an undercut.
Correctness
The proof file proves that the output is right, in four steps.
- Cells are pure. Every edge of lies on a grid line, so an open cell meets no point of the boundary of . A connected set that misses the boundary lies in the interior or in the exterior. So the centre test of line L2 classifies the whole cell.
- Blocks lie in , and the cover is . Line L3 keeps only blocks of cells, and MIN-COVER returns blocks that contain every cell. So the union of the output rectangles is the closure of the union of the cells, which is . Taking the regularized difference from gives . For a point on no grid line, this means exactly when is inside and inside none of the .
- Maximal means maximal in . Any rectangle with nonempty interior that lies in only meets cells, so the smallest block of cells containing it lies in . So a block that cannot grow by one row or column is not contained in any larger rectangle in .
- The cover is minimum among all rectangles. By step 3, any family of rectangles whose union is can be replaced, one for one, by maximal blocks with the same union. So the fewest maximal blocks is the fewest rectangles of any kind. The search finds it, because any cover contains a block through the first uncovered cell, and the bound only cuts branches that cannot beat the best cover found.
The tests check all of this against an oracle that does not use the code under test. They generate random simple rectilinear polygons, as polyominoes with no holes and no pinch points, traced into vertex lists and mapped onto random integer coordinates. The oracle answers membership from the generating cells. For 300 random parts, the expression of the output agrees with the oracle at 60 random points with denominator 97 and at four points next to every vertex, over 18,000 points in all. Every block is checked to lie in and to be blocked on all four sides, for 200 parts. The cover size equals a brute-force minimum over all subsets of the maximal blocks for 250 parts, and also for 400 random cell sets that are not delta areas. In 140 of those 400 sets some maximal block is redundant, which is where the search matters. The polygon cases rarely have one.
Proof: The recovered features are maximal rectangles in the delta area, their union is the delta area, the stock minus them is the part, and their number is minimumfull
We use the notation and the pseudocode of the page. is a closed region bounded by a simple rectilinear polygon with integer vertices. Since the polygon is simple, is regular, so . Let and be the distinct vertex coordinates (line L1), and let be the bounding box. The grid lines are the lines and , and is their union restricted to . The open cell is . The delta area is
For a set of cells we write .
Lemma 1 (cells are pure). Each open cell lies in or in , and line L2 puts it in exactly in the second case.
Proof. Each edge of the polygon is horizontal or vertical, and its two endpoints are vertices, so the edge lies on a grid line. Hence , and an open cell misses . Then is a split of the connected set into two disjoint open sets, so one of them is empty. The centre of is not on , so the crossing number test decides correctly whether it is in , and that decides the whole cell.
Let be the set of cells in and the rest.
Lemma 2. and .
Proof. The cells and partition , and is a finite union of segments, closed with empty interior. For any open set , : every neighbourhood of a point of meets in a nonempty open set, which is not inside . Take . By Lemma 1, , so . Take , which equals . By Lemma 1, , so .
A block is , its cell set is , and its rectangle is . Line L3 keeps only if . Line L4 drops it if one of the four blocks that add a row or column on one side is inside the grid and has all its cells in . Let be the list that is built.
Lemma 3 (rectangles in ). Let be a closed axis-parallel rectangle with nonempty interior. Then exactly when and every cell that meets is in . Then the smallest block with has all its cells in .
Proof. Suppose and a cell meets . Then is a nonempty open subset of . If were in , this set would lie in . But meets the open set nowhere, a contradiction. Conversely, if every cell that meets is in , then lies in the union of cells, and . For the second claim, the cells of are exactly the cells whose open interval in meets the open range of , and the same in . Each such cell meets , so it is in .
Lemma 4 (maximality). For , no closed axis-parallel rectangle contains strictly.
Proof. Suppose . Then reaches beyond on some side, say the right, so forces . Then meets the interior of each cell for , since it contains a strip for some . By Lemma 3, those cells are in , so the block grown by one column on the right has all its cells in , and line L4 would have dropped . The other three sides are the same.
Lemma 5 (the search). MIN-COVER returns a subfamily of whose cells cover , and no smaller subfamily of covers .
Proof. Every block of that contains a given cell of lies in , and each cell lies in some block of : the one-cell block of that cell is in , and growing it one row or column at a time while it stays in ends at a block of , because the grid is finite. So the initial value of best is a cover. A call SEARCH(chosen, covered) keeps covered . It sets best only when every cell is covered, so best is always a cover. Let be a minimum cover of size . We claim that unless best already has size , the search reaches a call with chosen and every cell covered. Start at the root, where chosen . At a call with chosen , holds if some cell is uncovered, because covers and chosen does not. So the bound cuts only if , which is impossible for a cover, or if already. Otherwise some contains , and line L5 recurses on chosen . The size grows by one at each step, so within steps all cells are covered and best becomes a cover of size . Best only ever shrinks, so it ends with size .
Theorem. Let be the rectangles returned at line L6. Then
- each lies in and is maximal among axis-parallel rectangles in ,
- and ,
- no family of fewer closed axis-parallel rectangles has union ,
- for a point on no grid line, exactly when and for every .
Proof. (1) Each for a block . Its cells are in , so by Lemma 2, and Lemma 4 gives maximality.
(2) By Lemma 5 the blocks cover , and they hold only cells. So , since a finite union of closures is the closure of the union. Then . The set contains every cell, since those are open and miss . It lies in : a point of in lies in , and a point on is not interior to . So , and Lemma 2 gives equality.
(3) Let be closed axis-parallel rectangles with union . Drop those with empty interior. The union of the rest is closed and contains for a finite union of segments, which is dense in the regular set . So it is still . For each remaining , Lemma 3 gives a block with cells in and , and growing it as in Lemma 5 gives a block with . Every cell is an open subset of , so the finitely many closed sets cover it. Then one of them meets in a set with nonempty interior, since a finite union of closed sets with empty interior in has empty interior. So meets , which makes it a cell of and of . So the blocks cover , and by Lemma 5, .
(4) If is on no grid line, then lies in an open cell or outside . If outside, it is neither in nor in . If in cell , then iff (Lemma 1). Also iff iff , since is not on the boundary of any block rectangle. By (2), iff is in some . So iff and lies in no .
Termination. Line L2 and the block loop are finite loops over blocks. In SEARCH, each recursive call adds a block whose cells include an uncovered cell, so covered grows strictly and the depth is at most . The branching is at most , so the search tree is finite.
What is not claimed. The theorem is about the planar case with the bounding box. It says nothing about which minimum cover is returned when there are several, or that a minimum cover is the best machining plan. The open sides of a rectangle are only the sides on . A rectangle with no open side, like the head of a T-slot, is correct as a set but cannot be reached along an axis. In three dimensions, the cell and cover steps are the same in principle. But the faces to extend, the number of cells and the convexity of the merged cells all need the 3D treatments of the cited papers, which this proof does not cover.
Complexity
A part with vertices has at most distinct and distinct coordinates, so the grid has cells. Line L2 runs a point-in-polygon test per cell, each, for . Lines L3 and L4 look at blocks at each with prefix sums. MIN-COVER branches over at most blocks per level, for at most levels, and each search node finds the first uncovered cell in . So the worst case is time, and the stored cell sets of the blocks take space.
The exponential part is honest. A minimum cover of a rectilinear polygon by rectangles is NP-hard in general, and the cover step is a set cover. In practice the delta area of a part splits into a few separate regions with few maximal rectangles each, and the search is fast. In the tests the largest instance from a part had 8 maximal blocks. The 3D methods use heuristics or greedy set cover for this step, or keep all covers as alternative interpretations.
Properties
- Exact. Integer coordinates, rational cell centres, and a proof that the expression equals the part. No tolerances.
- Interpretation-free in the union. By the first fact of feature interaction, every cover gives the same part. Which minimum cover is returned depends on the order of the search, so the features can differ between equally small answers.
- Maximal features overlap. The chosen rectangles are maximal, so they often overlap. That suits machining, where a region cut twice costs a little time but a region missed is an error.
- Independent of the boundary data structure. Only the vertex list is used. A face-based method needs the adjacency of faces and their convexity.
Variants and improvements
- Maximal convex cells. Sakurai's 3D method cuts the delta volume with the planes of faces at concave edges, the only faces that can split it into convex pieces. The cells are then merged into the largest convex unions, the maximal convex cells, and features are composed from those.
- Maximal volumes. Woo and Sakurai extend the faces of the delta volume to form large, simple maximal volumes. They then select a cover and convert each volume into a maximal feature, a type that machining can use directly. This page follows that pattern in 2D.
- Multiple interpretations. Tseng and Joshi composed the blocks of the removal volume in several ways and returned every interpretation. A process planner then picks the one with the best tool sequence.
- Curved faces. Sakurai and Dave extended cell decomposition to cylinders and other curved faces, where extending a face is no longer a plane cut.
- Fast cells. Cutting by all face planes makes many cells, and building them dominates the cost. Later work, such as Woo's fast cell-based decomposition of 2003, aims to reduce the number of cells and the time to build them.
When to use it
Use volume decomposition for prismatic parts machined from a block, when features interact and face patterns break, and when a certificate is wanted that the features remove exactly the right material. It suits 2.5D milling, where each feature is a prism along the tool axis. For simple parts with isolated features, a graph method such as the attributed adjacency graph is faster and gives named feature types directly. For parts with free-form faces, the cell count can grow fast. The related alternating sum of volumes decomposes by convex hulls instead of cells, and hint-based recognition grows features from traces.
Pitfalls
- Too many cells. Extending every face across the whole stock makes cells in 2D and in 3D, most of them in . Extend only the faces that can split , those at concave edges, as Sakurai does.
- Classifying cells near the boundary. The centre test is exact only when every boundary edge lies on a grid line. With floating point and nearly equal coordinates, a cell can be a sliver of width that is misclassified. Snap or merge coordinates first.
- Inaccessible regions. A rectangle that touches no side of cannot be cut along an axis from outside. Since is simple, every connected piece of reaches the boundary of , but a single rectangle need not. The head of a T-slot is a maximal rectangle with no open side. Such features need a special tool or another setup, and a planner must not treat them as plain pockets.
- Minimum is not best. The fewest features may not be the cheapest to machine. A cover with one extra feature can avoid a deep narrow cut. Treat the cover as one interpretation among several.
- Exponential search. Without a bound on the number of maximal blocks, the exact cover can explode. Fall back to a greedy cover and report it as such.
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/volume-decomposition-feature-recognition/. The authors are listed in prov/Y3M61K.jsonl.
"""Cell-based feature recognition for a rectilinear polygon in the plane.
The part P is a simple rectilinear polygon with integer vertices, given as a
list of vertices in order. The stock W is its bounding box, and the removal
volume, here an area, is the delta D = W minus P. The method:
1. Extends every edge of P to a full line across W. The lines cut W into
grid cells, and each cell lies in P or in D.
2. Composes the cells of D into all maximal rectangles of D cells: those
that cannot grow by one row or column of cells and stay in D.
3. Picks a set of maximal rectangles that covers every D cell, with the
fewest rectangles, by a depth-first branch and bound.
4. Returns the expression P = W -* (R_1 u ... u R_k), where -* is the
regularized difference, and for each rectangle the sides that lie on the
boundary of W, which say from where a tool can enter.
The expression is exact: the chosen rectangles lie in D and cover it, so
their union is D, and W -* D = P.
Precondition: the polygon is simple and rectilinear, with integer
coordinates, and its vertices are distinct.
Cost: for n vertices the grid has c = O(n^2) cells. Step 2 checks O(c^2)
rectangles in O(1) each with prefix sums. Step 3 is a set cover search,
O(m^k c) in the worst case for m maximal rectangles and an optimal cover of
size k, since set cover is NP-hard in general.
"""
from __future__ import annotations
from fractions import Fraction
Point = tuple[int, int]
Rect = tuple[int, int, int, int] # x0, y0, x1, y1
def point_in_polygon(poly: list[Point], x: Fraction, y: Fraction) -> bool:
"""Crossing number test for a point that is not on the boundary."""
inside = False
n = len(poly)
for k in range(n):
(x0, y0), (x1, y1) = poly[k], poly[(k + 1) % n]
if (y0 > y) != (y1 > y):
xc = x0 + Fraction(x1 - x0) * (y - y0) / (y1 - y0)
if xc > x:
inside = not inside
return inside
class Decomposition:
def __init__(self, poly: list[Point]):
self.poly = poly
xs = sorted({p[0] for p in poly}) # @line L1
ys = sorted({p[1] for p in poly})
self.xs, self.ys = xs, ys
self.stock = (xs[0], ys[0], xs[-1], ys[-1])
nx, ny = len(xs) - 1, len(ys) - 1
self.nx, self.ny = nx, ny
self.delta = set()
for i in range(nx):
for j in range(ny):
cx, cy = Fraction(xs[i] + xs[i + 1], 2), Fraction(ys[j] + ys[j + 1], 2)
if not point_in_polygon(poly, cx, cy): # @line L2
self.delta.add((i, j))
# prefix sums of D cells, to test a block of cells in O(1)
S = [[0] * (ny + 1) for _ in range(nx + 1)]
for i in range(nx):
for j in range(ny):
S[i + 1][j + 1] = S[i][j + 1] + S[i + 1][j] - S[i][j] + ((i, j) in self.delta)
self._S = S
def all_delta(self, i0: int, j0: int, i1: int, j1: int) -> bool:
"""Are all cells i0 <= i < i1, j0 <= j < j1 in D?"""
if not (0 <= i0 < i1 <= self.nx and 0 <= j0 < j1 <= self.ny):
return False
S = self._S
return S[i1][j1] - S[i0][j1] - S[i1][j0] + S[i0][j0] == (i1 - i0) * (j1 - j0)
def maximal_blocks(self) -> list[tuple[int, int, int, int]]:
"""All maximal blocks of D cells, as cell index ranges [i0, i1) x [j0, j1)."""
out = []
for i0 in range(self.nx):
for i1 in range(i0 + 1, self.nx + 1):
for j0 in range(self.ny):
for j1 in range(j0 + 1, self.ny + 1):
if not self.all_delta(i0, j0, i1, j1): # @line L3
continue
if (self.all_delta(i0 - 1, j0, i1, j1) or self.all_delta(i0, j0, i1 + 1, j1)
or self.all_delta(i0, j0 - 1, i1, j1) or self.all_delta(i0, j0, i1, j1 + 1)):
continue # @line L4
out.append((i0, j0, i1, j1))
return out
def to_rect(self, b) -> Rect:
i0, j0, i1, j1 = b
return (self.xs[i0], self.ys[j0], self.xs[i1], self.ys[j1])
def open_sides(self, r: Rect) -> tuple[str, ...]:
"""The sides of r on the boundary of the stock, from which it is open."""
X0, Y0, X1, Y1 = self.stock
sides = []
if r[0] == X0: sides.append("left")
if r[2] == X1: sides.append("right")
if r[1] == Y0: sides.append("bottom")
if r[3] == Y1: sides.append("top")
return tuple(sides)
def minimum_cover(cells: set, blocks: list) -> list:
"""The fewest blocks whose cells cover all of cells, by depth-first
branch and bound on the first uncovered cell."""
members = [frozenset((i, j) for i in range(b[0], b[2]) for j in range(b[1], b[3])) for b in blocks]
by_cell: dict = {}
for k, m in enumerate(members):
for c in m:
by_cell.setdefault(c, []).append(k)
order = sorted(cells)
best = [list(range(len(blocks)))]
def search(chosen: list, covered: frozenset):
if len(chosen) >= len(best[0]):
return
first = next((c for c in order if c not in covered), None)
if first is None:
best[0] = list(chosen)
return
for k in by_cell[first]: # @line L5
search(chosen + [k], covered | members[k])
search([], frozenset())
return [blocks[k] for k in best[0]]
def recognize(poly: list[Point]):
"""Return (stock, features), where features is a list of (rectangle,
open sides), such that P = stock -* (union of the rectangles)."""
dec = Decomposition(poly)
blocks = dec.maximal_blocks()
cover = minimum_cover(dec.delta, blocks)
rects = sorted(dec.to_rect(b) for b in cover)
return dec.stock, [(r, dec.open_sides(r)) for r in rects] # @line L6
def in_expression(stock: Rect, rects: list[Rect], x: Fraction, y: Fraction) -> bool:
"""Membership in stock -* (union of rects), for a point on no grid line."""
X0, Y0, X1, Y1 = stock
if not (X0 < x < X1 and Y0 < y < Y1):
return False
return not any(a < x < c and b < y < d for a, b, c, d in rects)
test_volume_decomposition_feature_recognition.py 220 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/volume-decomposition-feature-recognition/. The authors are listed in prov/Y3M61K.jsonl.
import random
import unittest
from bisect import bisect_left
from fractions import Fraction
from itertools import combinations
from volume_decomposition_feature_recognition import Decomposition, in_expression, minimum_cover, recognize
def random_part(rng, size=7, ncells=None):
"""A random simple rectilinear polygon: a polyomino with no holes and no
pinch vertices, on random integer coordinates. Returns the vertex list
and an independent membership oracle built from the cells."""
while True:
target = ncells or rng.randint(4, 22)
cells = {(rng.randrange(size), rng.randrange(size))}
while len(cells) < target:
i, j = rng.choice(sorted(cells))
di, dj = rng.choice([(1, 0), (-1, 0), (0, 1), (0, -1)])
if 0 <= i + di < size and 0 <= j + dj < size:
cells.add((i + di, j + dj))
if ok_polyomino(cells, size):
break
mi, mj = min(i for i, _ in cells), min(j for _, j in cells)
cells = {(i - mi, j - mj) for i, j in cells}
W, H = max(i for i, _ in cells) + 1, max(j for _, j in cells) + 1
X = sorted(rng.sample(range(-20, 60), W + 1))
Y = sorted(rng.sample(range(-20, 60), H + 1))
poly = [(X[i], Y[j]) for i, j in trace(cells)]
def oracle(x, y):
i, j = bisect_left(X, x) - 1, bisect_left(Y, y) - 1
return (i, j) in cells
return poly, oracle, cells, X, Y
def ok_polyomino(cells, size):
# no holes: every empty cell of the padded grid reaches the outside
empty = {(i, j) for i in range(-1, size + 1) for j in range(-1, size + 1)} - cells
seen, stack = {(-1, -1)}, [(-1, -1)]
while stack:
i, j = stack.pop()
for c in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)):
if c in empty and c not in seen:
seen.add(c)
stack.append(c)
if seen != empty:
return False
# no pinch: no 2 by 2 block with a checkerboard pattern
for i in range(-1, size):
for j in range(-1, size):
a, b = (i, j) in cells, (i + 1, j + 1) in cells
c, d = (i + 1, j) in cells, (i, j + 1) in cells
if a == b and c == d and a != c:
return False
return True
def trace(cells):
"""The boundary of the cells as one counterclockwise cycle of corners,
with collinear corners removed."""
nxt = {}
for i, j in cells:
if (i, j - 1) not in cells: nxt[(i, j)] = (i + 1, j)
if (i + 1, j) not in cells: nxt[(i + 1, j)] = (i + 1, j + 1)
if (i, j + 1) not in cells: nxt[(i + 1, j + 1)] = (i, j + 1)
if (i - 1, j) not in cells: nxt[(i, j + 1)] = (i, j)
start = min(nxt)
cyc, p = [start], nxt[start]
while p != start:
cyc.append(p)
p = nxt[p]
out = []
for k in range(len(cyc)):
a, b, c = cyc[k - 1], cyc[k], cyc[(k + 1) % len(cyc)]
if (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]) != 0:
out.append(b)
return out
def generic_points(rng, poly, count):
"""Random rational points with denominator 97, never on a grid line."""
xs, ys = [p[0] for p in poly], [p[1] for p in poly]
pts = []
while len(pts) < count:
a = rng.randint(97 * (min(xs) - 2), 97 * (max(xs) + 2))
b = rng.randint(97 * (min(ys) - 2), 97 * (max(ys) + 2))
if a % 97 and b % 97:
pts.append((Fraction(a, 97), Fraction(b, 97)))
# and points close to every vertex, in all four quadrants
for x, y in poly:
for sx in (-1, 1):
for sy in (-1, 1):
pts.append((x + Fraction(sx, 97), y + Fraction(sy, 89)))
return pts
class TestHandCases(unittest.TestCase):
def test_slot(self):
poly = [(0, 0), (6, 0), (6, 4), (4, 4), (4, 2), (2, 2), (2, 4), (0, 4)]
stock, feats = recognize(poly)
self.assertEqual(stock, (0, 0, 6, 4))
self.assertEqual(feats, [((2, 2, 4, 4), ("top",))])
def test_stepped_slot(self):
poly = [(0, 0), (8, 0), (8, 6), (6, 6), (6, 4), (5, 4), (5, 2), (3, 2),
(3, 4), (2, 4), (2, 6), (0, 6)]
dec = Decomposition(poly)
self.assertEqual(len(dec.delta), 4) # three cells in the upper band, one below
self.assertEqual(sorted(dec.maximal_blocks()), [(1, 2, 4, 3), (2, 1, 3, 3)])
stock, feats = recognize(poly)
self.assertEqual([r for r, _ in feats], [(2, 4, 6, 6), (3, 2, 5, 6)])
def test_t_slot_head_has_no_open_side(self):
poly = [(0, 0), (8, 0), (8, 6), (5, 6), (5, 4), (7, 4), (7, 2), (1, 2),
(1, 4), (3, 4), (3, 6), (0, 6)]
stock, feats = recognize(poly)
self.assertEqual(feats, [((1, 2, 7, 4), ()), ((3, 2, 5, 6), ("top",))])
def test_two_interacting_steps(self):
poly = [(0, 0), (6, 0), (6, 1), (5, 1), (5, 3), (3, 3), (3, 4), (0, 4)]
stock, feats = recognize(poly)
self.assertEqual(feats, [((3, 3, 6, 4), ("right", "top")), ((5, 1, 6, 4), ("right", "top"))])
class TestAgainstOracle(unittest.TestCase):
def test_expression_equals_part(self):
rng = random.Random(11)
checked = 0
for _ in range(300):
poly, oracle, *_ = random_part(rng)
stock, feats = recognize(poly)
rects = [r for r, _ in feats]
for x, y in generic_points(rng, poly, 60):
self.assertEqual(in_expression(stock, rects, x, y), oracle(x, y))
checked += 1
# every feature lies in the delta volume
for a, b, c, d in rects:
for _ in range(10):
x = Fraction(rng.randint(97 * a + 1, 97 * c - 1), 97)
y = Fraction(rng.randint(97 * b + 1, 97 * d - 1), 97)
if x.denominator > 1 and y.denominator > 1:
self.assertFalse(oracle(x, y))
self.assertGreater(checked, 500)
def test_blocks_are_maximal(self):
rng = random.Random(12)
for _ in range(200):
poly, oracle, *_ = random_part(rng)
dec = Decomposition(poly)
xs, ys = dec.xs, dec.ys
def centre(i, j):
return Fraction(xs[i] + xs[i + 1], 2), Fraction(ys[j] + ys[j + 1], 2)
for i0, j0, i1, j1 in dec.maximal_blocks():
for i in range(i0, i1):
for j in range(j0, j1):
self.assertFalse(oracle(*centre(i, j)))
# each side is blocked by the part or by the stock
for strip in ([(i0 - 1, j) for j in range(j0, j1)], [(i1, j) for j in range(j0, j1)],
[(i, j0 - 1) for i in range(i0, i1)], [(i, j1) for i in range(i0, i1)]):
outside = any(not (0 <= i < dec.nx and 0 <= j < dec.ny) for i, j in strip)
self.assertTrue(outside or any(oracle(*centre(i, j)) for i, j in strip))
def test_cover_is_minimum(self):
rng = random.Random(13)
compared = 0
for _ in range(250):
poly, oracle, *_ = random_part(rng)
dec = Decomposition(poly)
blocks = dec.maximal_blocks()
if len(blocks) > 12:
continue
cover = minimum_cover(dec.delta, blocks)
cells = lambda b: {(i, j) for i in range(b[0], b[2]) for j in range(b[1], b[3])}
best = next(k for k in range(len(blocks) + 1)
for sub in combinations(blocks, k)
if set().union(*[cells(b) for b in sub]) >= dec.delta)
self.assertEqual(len(cover), best)
compared += 1
self.assertGreater(compared, 100)
def test_cover_search_on_random_cell_sets(self):
# Delta volumes of simple parts seldom have a redundant maximal block,
# so the search is also checked on arbitrary sets of cells.
rng = random.Random(14)
compared = redundant = 0
cells = lambda b: {(i, j) for i in range(b[0], b[2]) for j in range(b[1], b[3])}
for _ in range(400):
n = rng.randint(3, 5)
D = {(i, j) for i in range(n) for j in range(n) if rng.random() < 0.65}
if not D:
continue
inside = lambda b: 0 <= b[0] and 0 <= b[1] and b[2] <= n and b[3] <= n and cells(b) <= D
blocks = [b for b in ((i0, j0, i1, j1) for i0 in range(n) for i1 in range(i0 + 1, n + 1)
for j0 in range(n) for j1 in range(j0 + 1, n + 1))
if inside(b) and not any(inside(g) for g in ((b[0] - 1, b[1], b[2], b[3]),
(b[0], b[1] - 1, b[2], b[3]),
(b[0], b[1], b[2] + 1, b[3]),
(b[0], b[1], b[2], b[3] + 1)))]
if len(blocks) > 12:
continue
cover = minimum_cover(D, blocks)
self.assertEqual(set().union(*[cells(b) for b in cover]), D)
best = next(k for k in range(len(blocks) + 1)
for sub in combinations(blocks, k)
if set().union(*[cells(b) for b in sub]) >= D)
self.assertEqual(len(cover), best)
compared += 1
redundant += best < len(blocks)
self.assertGreater(compared, 200)
self.assertGreater(redundant, 50)
if __name__ == "__main__":
unittest.main()
History
Volumetric feature recognition began with the alternating sums of convex hulls of Woo in 1982 and the work of Kim in the early 1990s. Cell-based methods came next. Tseng and Joshi decomposed the removal volume into blocks and generated multiple interpretations of interacting features in 1994. Sakurai published the decomposition of polyhedral delta volumes into maximal convex cells in 1995, and with Dave extended it to curved objects in 1996. Woo and Sakurai's maximal volumes of 2002 reduced the number of interpretations and the work. The survey of Han, Pratt and Regli in 2000 placed these methods beside graph-based and hint-based recognition, and found that each handles some interactions that the others miss.
References
- Hiroshi Sakurai, Volume decomposition and feature recognition, part 1, polyhedral objects, Computer-Aided Design 27(11), 833 to 843, 1995, the decomposition of the delta volume into maximal convex cells by the half spaces of faces at concave edges, and the composition of cells into features
- Hiroshi Sakurai and Parag Dave, Volume decomposition and feature recognition, part II, curved objects, Computer-Aided Design 28(6/7), 519 to 537, 1996, the extension of the cell decomposition to parts with curved faces
- Yoonhwan Woo and Hiroshi Sakurai, Recognition of maximal features by volume decomposition, Computer-Aided Design 34(3), 195 to 207, 2002, maximal volumes from extended faces of the delta volume, and the three steps of decomposition, selection and conversion into maximal features
- Yuan-Jye Tseng and Sanjay B. Joshi, Recognizing multiple interpretations of interacting machining features, Computer-Aided Design 26(9), 667 to 688, 1994, the decomposition of the removal volume into blocks and the generation of several feature interpretations by combining them
- JungHyun Han, Mike Pratt and William C. Regli, Manufacturing feature recognition from solid models, a status report, IEEE Transactions on Robotics and Automation 16(6), 782 to 796, 2000, the section on volumetric decomposition methods, cell-based decomposition and convex decomposition
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 | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag Y3M61K Edit this page History Report an error Markdown