Algorithm Search⌘K

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.

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
Properties
deterministicexactrecursive
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 PP and its stock WW, the removal volume, or delta volume, is D=W−∗PD = W -^* P. The method cuts DD 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 DD. 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 PP, given as a list of vertices with integer coordinates, the 2D section of a prismatic part. The stock WW is the bounding box of PP, so D=W−∗PD = W -^* P is the area to remove. The output is a list of axis-parallel rectangles R1,…,RkR_1, \dots, R_k, each with the sides of WW it touches, such that

  1. each RiR_i lies in DD and is maximal: no larger axis-parallel rectangle inside DD contains it,
  2. R1∪⋯∪Rk=DR_1 \cup \dots \cup R_k = D, so P=W−∗(R1∪⋯∪Rk)P = W -^* (R_1 \cup \dots \cup R_k),
  3. kk is as small as possible.

A rectangle that touches the top side of WW 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 PP lies on a grid line, so each open grid cell lies wholly inside or wholly outside PP, and line L2 classifies it by its centre. Lines L3 and L4 list the maximal blocks of cells in DD. A block is a range of cell columns times a range of cell rows. It is kept if all its cells are in DD 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 DD cells by maximal blocks. It always branches on the first uncovered cell, since some chosen block must contain it.

  1. RECOGNIZE(P)
  2. 1xs, ys ← the sorted distinct x and y coordinates of the vertices of P; W ← [xs_first, xs_last] × [ys_first, ys_last]
  3. 2D ← the grid cells whose centre is not inside P
  4. B ← empty list
  5. for each block of cells [i0, i1) × [j0, j1) of the grid do
  6. 3if the block holds a cell not in D then skip it
  7. 4if the block grown by one row or column on some side lies in D then skip it
  8. append the block to B
  9. cover ← MIN-COVER(D, B)
  10. 5return W and the rectangles of cover, each with its sides that lie on the boundary of W
  11. MIN-COVER(D, B)
  12. best ← B
  13. SEARCH(chosen, covered):
  14. if |chosen| ≥ |best| then return
  15. c ← the first cell of D in sorted order that is not in covered
  16. if there is no such c then best ← chosen and return
  17. 6for each block b of B that contains c do SEARCH(chosen + [b], covered ∪ cells(b))
  18. SEARCH([], ∅) and return best

A 2D prefix sum over the DD cells answers "are all cells of this block in DD?" in constant time, which makes lines L3 and L4 cost O(1)O(1) 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 [0,8]×[0,6][0, 8] \times [0, 6] with a stepped slot cut into its top: a wide upper slot [2,6]×[4,6][2, 6] \times [4, 6] and a narrow lower slot [3,5]×[2,4][3, 5] \times [2, 4] below it. The part has the 12 vertices

(0,0),(8,0),(8,6),(6,6),(6,4),(5,4),(5,2),(3,2),(3,4),(2,4),(2,6),(0,6).(0,0), (8,0), (8,6), (6,6), (6,4), (5,4), (5,2), (3,2), (3,4), (2,4), (2,6), (0,6).
step result
grid lines (L1) x∈{0,2,3,5,6,8}x \in \{0, 2, 3, 5, 6, 8\}, y∈{0,2,4,6}y \in \{0, 2, 4, 6\}, so 5×3=155 \times 3 = 15 cells
delta cells (L2) [2,3]×[4,6][2,3] \times [4,6], [3,5]×[4,6][3,5] \times [4,6], [5,6]×[4,6][5,6] \times [4,6], [3,5]×[2,4][3,5] \times [2,4]
maximal blocks (L3, L4) R1=[2,6]×[4,6]R_1 = [2, 6] \times [4, 6] and R2=[3,5]×[2,6]R_2 = [3, 5] \times [2, 6]
cover (L5) both are needed: the cell [2,3]×[4,6][2,3] \times [4,6] is only in R1R_1, and [3,5]×[2,4][3,5] \times [2,4] is only in R2R_2
features (L6) R1R_1 open at the top, a wide shallow slot; R2R_2 open at the top, a narrow deep slot

The result is P=W−∗([2,6]×[4,6]∪[3,5]×[2,6])P = W -^* ([2, 6] \times [4, 6] \cup [3, 5] \times [2, 6]). The areas check: 8+8−4=12=4⋅2+2⋅28 + 8 - 4 = 12 = 4 \cdot 2 + 2 \cdot 2. The two features overlap in [3,5]×[4,6][3, 5] \times [4, 6]. 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 [3,5]×[2,4][3, 5] \times [2, 4] 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 (0,0),(6,0),(6,1),(5,1),(5,3),(3,3),(3,4),(0,4)(0,0), (6,0), (6,1), (5,1), (5,3), (3,3), (3,4), (0,4), the delta area is an L shape at the top right. Its maximal rectangles are [3,6]×[3,4][3, 6] \times [3, 4] and [5,6]×[1,4][5, 6] \times [1, 4], both open on the right and on the top, so both are steps. They overlap in the corner square [5,6]×[3,4][5, 6] \times [3, 4], which either step can take.

A T-slot shows the third kind. Cut a neck [3,5]×[4,6][3, 5] \times [4, 6] into the top of [0,8]×[0,6][0, 8] \times [0, 6], with a head [1,7]×[2,4][1, 7] \times [2, 4] under it. The cover is [3,5]×[2,6][3, 5] \times [2, 6], open at the top, and the head [1,7]×[2,4][1, 7] \times [2, 4], 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.

  1. Cells are pure. Every edge of PP lies on a grid line, so an open cell meets no point of the boundary of PP. 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.
  2. Blocks lie in DD, and the cover is DD. Line L3 keeps only blocks of DD cells, and MIN-COVER returns blocks that contain every DD cell. So the union of the output rectangles is the closure of the union of the DD cells, which is DD. Taking the regularized difference from WW gives PP. For a point pp on no grid line, this means p∈Pp \in P exactly when pp is inside WW and inside none of the RiR_i.
  3. Maximal means maximal in DD. Any rectangle with nonempty interior that lies in DD only meets DD cells, so the smallest block of cells containing it lies in DD. So a block that cannot grow by one row or column is not contained in any larger rectangle in DD.
  4. The cover is minimum among all rectangles. By step 3, any family of rectangles whose union is DD 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 DD 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. PP is a closed region bounded by a simple rectilinear polygon with integer vertices. Since the polygon is simple, PP is regular, so P=int⁡P‾P = \overline{\operatorname{int} P}. Let x0<⋯<xax_0 < \dots < x_a and y0<⋯<yby_0 < \dots < y_b be the distinct vertex coordinates (line L1), and let W=[x0,xa]×[y0,yb]W = [x_0, x_a] \times [y_0, y_b] be the bounding box. The grid lines are the lines x=xix = x_i and y=yjy = y_j, and GG is their union restricted to WW. The open cell (i,j)(i, j) is Cij=(xi,xi+1)×(yj,yj+1)C_{ij} = (x_i, x_{i+1}) \times (y_j, y_{j+1}). The delta area is

D=W−∗P=int⁡(W∖P)‾.D = W -^* P = \overline{\operatorname{int}(W \setminus P)}.

For a set SS of cells we write ∣S∣=⋃(i,j)∈SCij‾|S| = \overline{\bigcup_{(i,j) \in S} C_{ij}}.

Lemma 1 (cells are pure). Each open cell lies in int⁡P\operatorname{int} P or in R2∖P\mathbb{R}^2 \setminus P, and line L2 puts it in DD 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 ∂P⊆G\partial P \subseteq G, and an open cell CC misses ∂P\partial P. Then C=(C∩int⁡P)∪(C∖P)C = (C \cap \operatorname{int} P) \cup (C \setminus P) is a split of the connected set CC into two disjoint open sets, so one of them is empty. The centre of CC is not on ∂P\partial P, so the crossing number test decides correctly whether it is in PP, and that decides the whole cell. □\square

Let SPS_P be the set of cells in int⁡P\operatorname{int} P and SDS_D the rest.

Lemma 2. P=∣SP∣P = |S_P| and D=∣SD∣D = |S_D|.

Proof. The cells and GG partition WW, and GG is a finite union of segments, closed with empty interior. For any open set UU, U∖G‾=U‾\overline{U \setminus G} = \overline{U}: every neighbourhood of a point of UU meets UU in a nonempty open set, which is not inside GG. Take U=int⁡PU = \operatorname{int} P. By Lemma 1, U∖G=⋃SPCijU \setminus G = \bigcup_{S_P} C_{ij}, so ∣SP∣=int⁡P‾=P|S_P| = \overline{\operatorname{int} P} = P. Take U=int⁡(W∖P)U = \operatorname{int}(W \setminus P), which equals int⁡W∖P\operatorname{int} W \setminus P. By Lemma 1, U∖G=⋃SDCijU \setminus G = \bigcup_{S_D} C_{ij}, so ∣SD∣=U‾=D|S_D| = \overline{U} = D. □\square

A block is β=[i0,i1)×[j0,j1)\beta = [i_0, i_1) \times [j_0, j_1), its cell set is cells⁡(β)\operatorname{cells}(\beta), and its rectangle is R(β)=[xi0,xi1]×[yj0,yj1]=∣cells⁡(β)∣R(\beta) = [x_{i_0}, x_{i_1}] \times [y_{j_0}, y_{j_1}] = |\operatorname{cells}(\beta)|. Line L3 keeps β\beta only if cells⁡(β)⊆SD\operatorname{cells}(\beta) \subseteq S_D. 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 SDS_D. Let BB be the list that is built.

Lemma 3 (rectangles in DD). Let RR be a closed axis-parallel rectangle with nonempty interior. Then R⊆DR \subseteq D exactly when R⊆WR \subseteq W and every cell that meets int⁡R\operatorname{int} R is in SDS_D. Then the smallest block β^\hat\beta with R⊆R(β^)R \subseteq R(\hat\beta) has all its cells in SDS_D.

Proof. Suppose R⊆DR \subseteq D and a cell CC meets int⁡R\operatorname{int} R. Then C∩int⁡RC \cap \operatorname{int} R is a nonempty open subset of DD. If CC were in SPS_P, this set would lie in int⁡P\operatorname{int} P. But D=int⁡W∖P‾D = \overline{\operatorname{int} W \setminus P} meets the open set int⁡P\operatorname{int} P nowhere, a contradiction. Conversely, if every cell that meets int⁡R\operatorname{int} R is in SDS_D, then int⁡R∖G\operatorname{int} R \setminus G lies in the union of SDS_D cells, and R=int⁡R∖G‾⊆∣SD∣=DR = \overline{\operatorname{int} R \setminus G} \subseteq |S_D| = D. For the second claim, the cells of β^\hat\beta are exactly the cells whose open interval in xx meets the open xx range of RR, and the same in yy. Each such cell meets int⁡R\operatorname{int} R, so it is in SDS_D. □\square

Lemma 4 (maximality). For β∈B\beta \in B, no closed axis-parallel rectangle R′⊆DR' \subseteq D contains R(β)R(\beta) strictly.

Proof. Suppose R(β)⊊R′⊆DR(\beta) \subsetneq R' \subseteq D. Then R′R' reaches beyond R(β)R(\beta) on some side, say the right, so R′⊆WR' \subseteq W forces i1<ai_1 < a. Then R′R' meets the interior of each cell Ci1jC_{i_1 j} for j0≤j<j1j_0 \le j < j_1, since it contains a strip [xi1,xi1+ϵ]×[yj0,yj1][x_{i_1}, x_{i_1} + \epsilon] \times [y_{j_0}, y_{j_1}] for some ϵ>0\epsilon > 0. By Lemma 3, those cells are in SDS_D, so the block grown by one column on the right has all its cells in SDS_D, and line L4 would have dropped β\beta. The other three sides are the same. □\square

Lemma 5 (the search). MIN-COVER(SD,B)(S_D, B) returns a subfamily of BB whose cells cover SDS_D, and no smaller subfamily of BB covers SDS_D.

Proof. Every block of BB that contains a given cell of SDS_D lies in BB, and each SDS_D cell lies in some block of BB: the one-cell block of that cell is in SDS_D, and growing it one row or column at a time while it stays in SDS_D ends at a block of BB, because the grid is finite. So the initial value BB of best is a cover. A call SEARCH(chosen, covered) keeps covered =⋃b∈chosencells⁡(b)= \bigcup_{b \in \text{chosen}} \operatorname{cells}(b). It sets best only when every cell is covered, so best is always a cover. Let F∗F^* be a minimum cover of size k∗k^*. We claim that unless best already has size k∗k^*, the search reaches a call with chosen ⊆F∗\subseteq F^* and every cell covered. Start at the root, where chosen =[]⊆F∗= [] \subseteq F^*. At a call with chosen ⊆F∗\subseteq F^*, ∣chosen∣<k∗|\text{chosen}| < k^* holds if some cell cc is uncovered, because F∗F^* covers cc and chosen does not. So the bound ∣chosen∣≥∣best∣|\text{chosen}| \ge |\text{best}| cuts only if ∣best∣≤∣chosen∣<k∗|\text{best}| \le |\text{chosen}| < k^*, which is impossible for a cover, or if ∣best∣=k∗|\text{best}| = k^* already. Otherwise some b∈F∗∖chosenb \in F^* \setminus \text{chosen} contains cc, and line L5 recurses on chosen +[b]⊆F∗+ [b] \subseteq F^*. The size grows by one at each step, so within k∗k^* steps all cells are covered and best becomes a cover of size ∣chosen∣≤k∗|\text{chosen}| \le k^*. Best only ever shrinks, so it ends with size k∗k^*. □\square

Theorem. Let R1,…,RkR_1, \dots, R_k be the rectangles returned at line L6. Then

  1. each RiR_i lies in DD and is maximal among axis-parallel rectangles in DD,
  2. R1∪⋯∪Rk=DR_1 \cup \dots \cup R_k = D and W−∗(R1∪⋯∪Rk)=PW -^* (R_1 \cup \dots \cup R_k) = P,
  3. no family of fewer closed axis-parallel rectangles has union DD,
  4. for a point pp on no grid line, p∈Pp \in P exactly when p∈int⁡Wp \in \operatorname{int} W and p∉int⁡Rip \notin \operatorname{int} R_i for every ii.

Proof. (1) Each Ri=R(β)R_i = R(\beta) for a block β∈B\beta \in B. Its cells are in SDS_D, so Ri⊆∣SD∣=DR_i \subseteq |S_D| = D by Lemma 2, and Lemma 4 gives maximality.

(2) By Lemma 5 the blocks cover SDS_D, and they hold only SDS_D cells. So ⋃iRi=⋃i∣cells⁡(βi)∣=∣SD∣=D\bigcup_i R_i = \bigcup_i |\operatorname{cells}(\beta_i)| = |S_D| = D, since a finite union of closures is the closure of the union. Then W−∗D=int⁡(W∖D)‾W -^* D = \overline{\operatorname{int}(W \setminus D)}. The set int⁡(W∖D)\operatorname{int}(W \setminus D) contains every SPS_P cell, since those are open and miss DD. It lies in PP: a point of W∖PW \setminus P in int⁡W\operatorname{int} W lies in int⁡W∖P⊆D\operatorname{int} W \setminus P \subseteq D, and a point on ∂W\partial W is not interior to W∖DW \setminus D. So ∣SP∣⊆W−∗D⊆P|S_P| \subseteq W -^* D \subseteq P, and Lemma 2 gives equality.

(3) Let Q1,…,QrQ_1, \dots, Q_r be closed axis-parallel rectangles with union DD. Drop those with empty interior. The union of the rest is closed and contains D∖G′D \setminus G' for a finite union G′G' of segments, which is dense in the regular set DD. So it is still DD. For each remaining QtQ_t, Lemma 3 gives a block β^t\hat\beta_t with cells in SDS_D and Qt⊆R(β^t)Q_t \subseteq R(\hat\beta_t), and growing it as in Lemma 5 gives a block βt∈B\beta_t \in B with Qt⊆R(βt)⊆DQ_t \subseteq R(\beta_t) \subseteq D. Every SDS_D cell CC is an open subset of DD, so the finitely many closed sets QtQ_t cover it. Then one of them meets CC in a set with nonempty interior, since a finite union of closed sets with empty interior in CC has empty interior. So CC meets int⁡Qt\operatorname{int} Q_t, which makes it a cell of β^t\hat\beta_t and of βt\beta_t. So the blocks βt\beta_t cover SDS_D, and by Lemma 5, k≤rk \le r.

(4) If pp is on no grid line, then pp lies in an open cell or outside WW. If outside, it is neither in PP nor in int⁡W\operatorname{int} W. If in cell CC, then p∈Pp \in P iff C∈SPC \in S_P (Lemma 1). Also p∈Rip \in R_i iff p∈int⁡Rip \in \operatorname{int} R_i iff C∈cells⁡(βi)C \in \operatorname{cells}(\beta_i), since pp is not on the boundary of any block rectangle. By (2), C∈SDC \in S_D iff CC is in some cells⁡(βi)\operatorname{cells}(\beta_i). So p∈Pp \in P iff p∈int⁡Wp \in \operatorname{int} W and pp lies in no int⁡Ri\operatorname{int} R_i. □\square

Termination. Line L2 and the block loop are finite loops over O(a2b2)O(a^2 b^2) 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 ∣SD∣|S_D|. The branching is at most ∣B∣|B|, so the search tree is finite.

What is not claimed. The theorem is about the planar case with WW 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 ∂W\partial W. 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 nn vertices has at most n/2n/2 distinct xx and n/2n/2 distinct yy coordinates, so the grid has c=O(n2)c = O(n^2) cells. Line L2 runs a point-in-polygon test per cell, O(n)O(n) each, for O(n3)O(n^3). Lines L3 and L4 look at O(n4)O(n^4) blocks at O(1)O(1) each with prefix sums. MIN-COVER branches over at most mm blocks per level, for at most kk levels, and each search node finds the first uncovered cell in O(n2)O(n^2). So the worst case is O(n4+mkn2)O(n^4 + m^k n^2) time, and the stored cell sets of the blocks take O(mn2)O(m n^2) 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 O(n2)O(n^2) cells in 2D and O(n3)O(n^3) in 3D, most of them in PP. Extend only the faces that can split DD, 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 10−1210^{-12} that is misclassified. Snap or merge coordinates first.
  • Inaccessible regions. A rectangle that touches no side of WW cannot be cut along an axis from outside. Since PP is simple, every connected piece of DD reaches the boundary of WW, 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.

volume_decomposition_feature_recognition.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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
  4. 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
  5. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example