Algorithm Search⌘K

Algorithmadvanced

Hint-based feature recognition

Also called Vandenbrande-Requicha feature recognition.

Vandenbrande and Requicha's method that searches the B-rep for traces of features, such as opposing parallel faces, then completes and verifies each feature volume.

Time
O(n^3) worst
Space
O(n^2) extra
Where
n = the number of vertices of the part
Properties
deterministicexactiterative
Origin
Jan H. Vandenbrande, Aristides A. G. Requicha, 1993

Hint-based feature recognition looks for traces of features on the boundary of a part, not for complete feature patterns. A trace, or hint, is a small configuration of faces that a feature always leaves behind, even when other features cut into it. Two opposite parallel walls suggest a slot. A cylindrical face suggests a hole. A floor face with walls suggests a pocket. Each hint is completed into the largest feature volume that agrees with it, and the volume is then verified: it must not cut into the part, and a tool must be able to reach it. Vandenbrande and Requicha introduced the method in 1993. It was a response to feature interaction, which destroys the face patterns that graph methods look for but rarely destroys every trace. This page gives an exact version for rectilinear polygons in the plane. The hints are the pieces of the part's boundary, each with its outward normal. Completion sweeps a piece to the stock and widens the sweep, and pieces that cannot be reached are dropped. The page proves that the features cover exactly the reachable part of the removal area. The leftovers are undercuts, and with them the part equals the stock minus the features.

In plain words

A detective doesn't need the whole footprint. A heel mark is enough to say "someone stood here", and then the detective works out the rest.

Hint-based recognition treats the faces of a part the same way. A flat floor with material below it says "something was cut here, from above". So the program pushes that floor straight up until it leaves the block. If the push hits material, no cutter from above could have made that floor, so the clue is dropped. If not, the program widens the shape sideways as far as the empty space allows. That shape is a feature, a slot or a step. Clues that are partly hidden, like a floor split in two by a deeper cut, still work, because each piece of the floor gives the same answer.

The problem

The input is a simple rectilinear polygon PP with integer vertices, the section of a prismatic part. The stock WW is its bounding box, and D=W−∗PD = W -^* P is the area to remove. The cutter moves along the four axis directions. A point of DD is reachable from side ss if the straight segment from it to the side ss of WW does not pass through the interior of PP. The output is a list of rectangles in DD, each with the sides of WW it lies on and the sides it is reached from, such that:

  1. the reachable features cover exactly the reachable points of DD,
  2. the remaining points of DD are covered by rectangles marked as undercuts,
  3. P=W−∗(union of all rectangles)P = W -^* (\text{union of all rectangles}).

The algorithm

Line L1 builds the grid of all vertex coordinates. Every edge of PP lies on a grid line, so each cell lies wholly in PP or wholly in DD. Line L2 enumerates the hints. A hint is a unit piece of the boundary between a cell of PP and a cell cc of DD, and its normal ss points from PP into DD. The piece is a floor if ss is up, a wall if ss is sideways. Line L3 sweeps cc in direction ss to the side of the stock. If the strip holds a cell of PP, the face cannot be reached from side ss, and the hint is dropped. Line L4 widens the strip across ss, one row or column at a time, while the new cells are all in DD. Line L5 records the block and the side it is reached from, so a block found from several hints is kept once. Line L6 handles the cells of DD that no completed block covers, if there are any. In each row it takes the maximal run of DD cells around them and marks it as an undercut.

  1. HINT-RECOGNIZE(P)
  2. 1build the grid of the vertex coordinates of P; D ← the cells not in P; W ← the bounding box
  3. F ← an empty map from blocks to sets of sides
  4. 2for each cell c of D and side s such that the neighbour of c opposite to s is a cell of P do
  5. strip ← the cells from c to the side s of W
  6. 3if strip holds a cell of P then continue
  7. 4widen strip across s, one row or column at a time, while the new cells are in D
  8. 5add s to F[strip]
  9. 6for each row, record as an undercut every maximal run of D cells in it
  10. that holds a cell covered by no block of F
  11. 7return W and every block, with its open sides, its kind and the sides it is reached from

A 2D prefix sum over the cells of DD answers "are all cells of this block in DD?" in constant time, which makes lines L3 and L4 cheap. The kind follows from the open sides: one open side is a slot, and two are a step. Opposite open sides would need a whole row or column of DD cells, and that never happens with the bounding box as stock (see Correctness).

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] over a narrow lower slot [3,5]×[2,4][3, 5] \times [2, 4]. The vertices are

(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).

The grid lines are x∈{0,2,3,5,6,8}x \in \{0, 2, 3, 5, 6, 8\} and y∈{0,2,4,6}y \in \{0, 2, 4, 6\}. The floor of the upper slot is split by the lower slot into two pieces, [2,3][2, 3] and [5,6][5, 6] at y=4y = 4. A face-based recognizer that expects one floor between two walls does not find the upper slot. The seven hints are:

hint normal strip to the stock result
floor piece [2,3][2,3] at y=4y = 4 up [2,3]×[4,6][2,3] \times [4,6], empty widened to [2,6]×[4,6][2,6] \times [4,6], a slot
floor piece [5,6][5,6] at y=4y = 4 up [5,6]×[4,6][5,6] \times [4,6], empty widened to [2,6]×[4,6][2,6] \times [4,6], the same slot
wall at x=2x = 2, y∈[4,6]y \in [4,6] right runs into [6,8]×[4,6][6,8] \times [4,6] dropped
wall at x=6x = 6, y∈[4,6]y \in [4,6] left runs into [0,2]×[4,6][0,2] \times [4,6] dropped
floor [3,5][3,5] at y=2y = 2 up [3,5]×[2,6][3,5] \times [2,6], empty cannot widen, [3,5]×[2,6][3,5] \times [2,6], a slot
wall at x=3x = 3, y∈[2,4]y \in [2,4] right runs into [5,6]×[2,4][5,6] \times [2,4] dropped
wall at x=5x = 5, y∈[2,4]y \in [2,4] left runs into [2,3]×[2,4][2,3] \times [2,4] dropped

So there are two features, the wide slot [2,6]×[4,6][2,6] \times [4,6] and the deep narrow slot [3,5]×[2,6][3,5] \times [2,6], both reached from the top. They overlap in [3,5]×[4,6][3,5] \times [4,6], and P=W−∗(their union)P = W -^* (\text{their union}). Each piece of the split floor alone recovers the whole upper slot. That is the point of a hint.

If the slot is a T-slot instead, with a neck [3,5]×[4,6][3,5] \times [4,6] and a wider head [1,7]×[2,4][1,7] \times [2,4], the floor of the head gives the slot [3,5]×[2,6][3,5] \times [2,6]. The cells [1,3]×[2,4][1,3] \times [2,4] and [5,7]×[2,4][5,7] \times [2,4] cannot be reached from any side. Line L6 takes the run of DD cells around them in their row, [1,7]×[2,4][1,7] \times [2,4], and marks it as an undercut.

Correctness

The proof file proves the following.

  1. Cells are pure, as in volume decomposition: edges of PP lie on grid lines, so a cell is wholly inside or outside PP.
  2. Every row and every column holds a cell of PP. PP is connected and WW is its bounding box, so PP spans the full range of xx and of yy, and it has interior points in every open column and row.
  3. Completed blocks are reachable. A block from line L5 lies in DD and reaches the side ss of WW. Each of its cells has its whole strip to side ss inside the block, so every point of the block is reachable from ss.
  4. Every reachable cell is covered. Take a cell cc of DD reachable from side ss. Walk from cc in the direction opposite to ss. By 2, the walk meets a cell of PP. The last cell of DD before it carries a hint with normal ss. The hint's strip contains cc and stays in DD, so it passes line L3, and its block covers cc.
  5. Undercut runs touch no side of the stock. A run from line L6 holds a cell that, by 4, is not reachable. If the run reached the left or right side of WW, it would contain that cell's strip to the side, and the cell would be reachable. If it lay in the top or bottom row, every cell of it would be reachable through that side. So undercut runs have no open side.
  6. The expression is exact. All blocks lie in DD, and together they cover every cell of DD. So their union is DD, and W−∗D=PW -^* D = P.

The tests check these claims against oracles built from the generating cells, not from the code. Half the random parts are grown polyominoes and half are blocks with winding tunnels carved in from the boundary, which make undercuts. For 600 parts and over 23,000 rational points, the tests check three things. Membership in the stock minus the features equals membership in the part. A point of DD lies in a reachable feature exactly when a brute-force scan along the four axis directions says its cell is reachable. No feature reaches into the part or outside the stock. Undercuts occur in 51 of the 600 parts. Hand cases cover a slot, the stepped slot, the T-slot, a corner with two steps, and a plus shape with four steps.

Proof: The features found from hints cover exactly the reachable part of the removal area, the undercut runs cover the rest, and the stock minus all of them is the partfull

We use the notation and the pseudocode of the page. PP is a closed region bounded by a simple rectilinear polygon with integer vertices, so PP is regular and 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, and let W=[x0,xa]×[y0,yb]W = [x_0, x_a] \times [y_0, y_b] be the bounding box (line L1). The grid GG is the union of the lines x=xix = x_i and y=yjy = y_j inside 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}), with 0≤i<a0 \le i < a and 0≤j<b0 \le j < b. The removal area is D=W−∗P=int⁡(W∖P)‾D = W -^* P = \overline{\operatorname{int}(W \setminus P)}. For a set SS of cells, ∣S∣|S| is the closure of the union of its open cells. A block is a set of cells [i0,i1)×[j0,j1)[i_0, i_1) \times [j_0, j_1), and ∣B∣|B| is a closed rectangle.

The sides of WW are top, bottom, left and right, with normals (0,1)(0,1), (0,−1)(0,-1), (−1,0)(-1,0) and (1,0)(1,0). For a cell cc and a side ss, the strip of cc to ss is the block of cells from cc to the side ss in the direction of the normal of ss. For example, the strip of (i,j)(i, j) to the top is [i,i+1)×[j,b)[i, i+1) \times [j, b).

Lemma 1 (cells are pure). Each open cell lies in int⁡P\operatorname{int} P or in R2∖P\mathbb{R}^2 \setminus P. Let SPS_P and SDS_D be the two kinds. Then P=∣SP∣P = |S_P| and D=∣SD∣D = |S_D|, and line L1 puts in DD exactly the cells of SDS_D.

Proof. This is Lemmas 1 and 2 of the proof for volume decomposition, with the same grid and the same centre test. Every edge of the polygon lies on a grid line, so an open cell misses ∂P\partial P and, being connected, lies on one side of it. The closure claims follow because GG is closed with empty interior, so removing it from an open set does not change the closure. □\square

Reachability. A point pp of an open cell C⊆DC \subseteq D is reachable from side ss if the segment from pp to the side ss of WW, in the direction of the normal of ss, misses int⁡P\operatorname{int} P. A cell is reachable from ss if its points are.

Lemma 2. A cell of SDS_D is reachable from ss if and only if every cell of its strip to ss is in SDS_D. Then all its points are reachable from ss.

Proof. The segment from pp to side ss passes through the open cells of the strip, and between consecutive ones it crosses a grid line at a single point. If a cell of the strip is in SPS_P, the segment meets that open cell, which lies in int⁡P\operatorname{int} P. If all cells of the strip are in SDS_D, the segment meets no point of int⁡P\operatorname{int} P inside those open cells, which lie outside PP. A point qq where it crosses a grid line between two such cells is not in int⁡P\operatorname{int} P either, since every neighbourhood of qq meets those open cells, which lie outside PP. The condition depends only on the cell, so it holds for all points of the cell at once. □\square

Lemma 3 (every row and column holds a cell of PP). For every ii there is a jj with (i,j)∈SP(i, j) \in S_P, and for every jj there is an ii with (i,j)∈SP(i, j) \in S_P.

Proof. The interior of the region bounded by a simple polygon is connected and open, so its projection to the xx-axis is an open interval II. The projection is continuous and P=int⁡P‾P = \overline{\operatorname{int} P}, so the projection of PP, which is [x0,xa][x_0, x_a] because WW is the bounding box, lies in I‾\overline{I}. Hence I=(x0,xa)I = (x_0, x_a). Pick x∗x^* in (xi,xi+1)⊆I(x_i, x_{i+1}) \subseteq I and a point (x∗,y∗)(x^*, y^*) of int⁡P\operatorname{int} P. Since int⁡P\operatorname{int} P is open, we can move y∗y^* slightly so that it lies on no grid line, while keeping the point in int⁡P\operatorname{int} P and x∗x^* fixed. The point then lies in an open cell of column ii, which meets int⁡P\operatorname{int} P and so is in SPS_P by Lemma 1. Rows are the same with the axes swapped. □\square

Lemma 4 (completion). Let (c,s)(c, s) be a hint of line L2. If some cell of the strip of cc to ss is in SPS_P, line L3 drops the hint. Otherwise lines L3 and L4 return a block BB with these properties. (a) Every cell of BB is in SDS_D, and BB contains the strip of cc to ss. (b) BB reaches the side ss: for ss the top, B=[i0,i1)×[j,b)B = [i_0, i_1) \times [j, b) where jj is the row of cc. (c) Every cell of BB is reachable from ss.

Proof. Line L3 tests the strip with the prefix sums, which count the cells of SDS_D in a block exactly, so it drops the hint exactly when the strip holds a cell of SPS_P. Take ss the top; the other sides are the same after a rotation. The block starts as the strip [i,i+1)×[j,b)[i, i+1) \times [j, b). Line L4 adds the column i0−1i_0 - 1 or i1i_1 over the rows [j,b)[j, b) only when all its cells are in SDS_D. So (a) and (b) hold by induction over the growth steps. For (c), the strip to the top of a cell (i′,j′)(i', j') of BB is [i′,i′+1)×[j′,b)[i', i'+1) \times [j', b), which lies in BB because j′≥jj' \ge j. All its cells are in SDS_D by (a), so the cell is reachable by Lemma 2. Each loop of line L4 adds a column inside the grid each time, so it stops after at most aa steps. □\square

Lemma 5 (every reachable cell is covered). Let c∈SDc \in S_D be reachable from ss. Then some block that line L5 records for side ss contains cc.

Proof. Take ss the top and c=(i,j)c = (i, j). By Lemma 3, column ii holds a cell of SPS_P. By Lemma 2 the cells (i,j),…,(i,b−1)(i, j), \dots, (i, b-1) are all in SDS_D, so every cell of SPS_P in column ii lies below row jj. Let (i,k)(i, k) with k<jk < j be the highest one. Then the cells (i,k+1),…,(i,j)(i, k+1), \dots, (i, j) are in SDS_D. The cell d=(i,k+1)d = (i, k+1) is in SDS_D, and its neighbour opposite the top, (i,k)(i, k), is in SPS_P, so (d,top)(d, \text{top}) is a hint of line L2. Its strip [i,i+1)×[k+1,b)[i, i+1) \times [k+1, b) consists of cells of SDS_D: those up to row jj by the choice of kk, and those above by the reachability of cc. So line L3 keeps the hint, and by Lemma 4(a) its block contains the strip, which contains cc. □\square

Lemma 6 (open sides). A block recorded in line L5 for side ss has ss among its open sides. No block of cells of SDS_D has two opposite open sides. So each recorded block has one open side or two adjacent ones, and line L7 calls it a slot or a step.

Proof. The first claim is Lemma 4(b). A block with the left and right sides open spans all columns, so any of its rows consists of cells of SDS_D only, against Lemma 3. Top and bottom are the same. So at most two sides are open, and two open sides are adjacent. □\square

Lemma 7 (undercut runs). Let UU be the set of cells of SDS_D covered by no block of line L5. Each run that line L6 records consists of cells of SDS_D, contains a cell of UU, and has no open side. Every cell of UU lies in a recorded run.

Proof. Line L6 takes, in each row, the maximal runs of consecutive cells of SDS_D and records those that contain a cell of UU. A cell u∈Uu \in U lies in exactly one maximal run of its row, which is then recorded. By Lemma 5, uu is reachable from no side. If the run of uu contained the first or last cell of the row, it would contain the strip of uu to the left or the right, and uu would be reachable by Lemma 2. If the run lay in row 00 or row b−1b-1, the strip of uu to the bottom or the top would be uu alone, and uu would again be reachable. So the run has no open side. □\square

Theorem. Let FF be the blocks of line L5 and RR the runs of line L6. Then:

  1. every block of F∪RF \cup R consists of cells of SDS_D, so ∣B∣⊆D|B| \subseteq D;
  2. the union of ∣B∣|B| over F∪RF \cup R is DD;
  3. W−∗⋃B∈F∪R∣B∣=PW -^* \bigcup_{B \in F \cup R} |B| = P;
  4. a point of an open cell of SDS_D lies in a block of FF if and only if its cell is reachable from some side;
  5. the blocks of FF are reached from the sides that line L5 records, which are among their open sides, and the runs of RR have no open side.

Proof. Part 1 is Lemma 4(a) and Lemma 7. For part 2, the blocks of FF cover every cell of SDS_D outside UU by the definition of UU, and the runs of RR cover UU by Lemma 7. So the union of the closed blocks is a finite union of closed sets. It contains every open cell of SDS_D and so its closure ∣SD∣=D|S_D| = D, and by part 1 it lies in DD.

For part 3, write D=∣SD∣D = |S_D|. The open cells of SPS_P are open and disjoint from every open cell of SDS_D, so they miss the closure DD and lie in int⁡(W∖D)\operatorname{int}(W \setminus D). Taking closures, P=∣SP∣⊆W−∗DP = |S_P| \subseteq W -^* D. Conversely, int⁡(W∖D)\operatorname{int}(W \setminus D) is an open set that misses every open cell of SDS_D, so it lies in ∣SP∣∪G|S_P| \cup G. An open set V⊆P∪GV \subseteq P \cup G satisfies V‾=V∖G‾⊆P\overline{V} = \overline{V \setminus G} \subseteq P, so W−∗D⊆PW -^* D \subseteq P.

For part 4, a cell in a block of FF is reachable by Lemma 4(c), and a reachable cell lies in a block of FF by Lemma 5. A point of an open cell lies in a closed block exactly when its cell belongs to the block. Part 5 is Lemma 6 and Lemma 7. □\square

Termination. The grid is finite and line L2 yields at most four hints per cell. Each completion stops by Lemma 4. The marking of covered cells and the row scan of line L6 visit finitely many cells. So the method stops.

Cost of the marking. For the side top, the block of a kept hint in row jj is the maximal run of columns [i0,i1)[i_0, i_1) around the hint's column for which the block [i0,i1)×[j,b)[i_0, i_1) \times [j, b) consists of cells of SDS_D. Two such runs for the same jj are equal or disjoint, because the union of two overlapping runs would also qualify. So the distinct top blocks with lower row jj hold at most a(b−j)a(b - j) cells together. Summing over jj and the four sides gives O(ab(a+b))O(a b (a + b)) marked cells, which is O(n3)O(n^3) for nn vertices.

What is not claimed. The features are not a minimum set and may overlap. The model is the plane, the bounding box as stock, and tool motion along the four axes only. In 3D, with other stock or other tool directions, Lemmas 3 and 5 can fail, as the page's pitfalls say. The 3D method of Vandenbrande and Requicha has heuristic hint patterns and tests, and no such theorem is claimed for it here.

Complexity

For nn vertices the grid has O(n2)O(n^2) cells and O(n2)O(n^2) hints. With prefix sums, line L3 is O(1)O(1). Line L4 widens by at most O(n)O(n) rows or columns at O(1)O(1) each. So the hints cost O(n3)O(n^3) in all. To find the cells left over, the cells of each distinct block are marked. Two blocks reached from the same side that share their inner edge line, the line of the hint, are equal or disjoint. So the blocks with a given side and inner line hold O(n2)O(n^2) cells, and over the O(n)O(n) lines and four sides, the marking costs O(n3)O(n^3). Line L6 scans each row once, in O(n2)O(n^2). Building the grid costs O(n3)O(n^3) with a point-in-polygon test per cell. The total is O(n3)O(n^3) time and O(n2)O(n^2) space.

In 3D the costs are of another kind. Hints are found by matching small face patterns. Completion and verification need Boolean operations and tests of tool access, which dominate the running time. The number of hints is linear in the number of faces, and each hint's completion depends on how far it can grow.

Properties

  • Robust to interaction. A hint needs only a piece of one face. A feature whose faces are split, shortened or partly removed still leaves pieces, and any one of them suffices.
  • Exact here. Integer coordinates, exact cell centres and constant-time block tests. No tolerances.
  • Redundant and overlapping. Many hints give the same feature, and features overlap. Neither is an error, since machining removes material once, but the output is not a minimum set. A minimum is the business of volume decomposition.
  • Generate and test. The method is a generate-and-test search. Hints generate candidates, completion makes them as large as allowed, and verification rejects bad ones. Adding a feature type means adding a hint pattern, a completion rule and a test.

Variants and improvements

  • Hint patterns in 3D. Vandenbrande and Requicha's hints include opposing parallel planar faces for slots, a cylindrical face for a hole, and a floor face for a pocket. Completion extends the hint to the largest volume of that feature type that does not intrude into the part. Verification checks that the volume is machinable, for example that a tool can approach along an axis.
  • Rating hints. Han and Requicha extended the approach so that hints are ordered by how promising they are, and the strongest are completed first. Weak hints are processed only if needed, which saves work on large parts.
  • Alternative interpretations. Regli, Gupta and Nau generate the feature volumes that traces support and keep the alternatives, so that a process planner can choose. This page keeps every reachable block found from some hint.
  • Combined recognizers. Many systems use graph matching for isolated features, hints for interacting ones, and a volumetric pass for what remains. The undercut pass of line L6 is a small instance of that.
  • Accessibility beyond axes. Here a feature is reached only along the four axes. With more tool directions, as in five-axis machining, the test becomes an accessibility cone computation.

When to use it

Use hint-based recognition for machined parts with many interacting features, where whole face patterns break. It also suits recognizers that grow by adding feature types one at a time. It works well when the hints of each feature type are clear and few, as for holes, slots and pockets. Pure graph matching on the attributed adjacency graph is faster for isolated features. When a provably minimal or unique decomposition is wanted, use volume decomposition or the alternating sum of volumes. When undercuts matter, combine the result with undercut detection and setup planning.

Pitfalls

  • Dropping a hint too early. A wall hint whose strip runs into the part is not reachable from that side, but the same feature is usually found from another hint, such as its floor. Do not report a feature missing until every hint of the area has been tried, or the reachable area is checked as in claim 4.
  • Completing too far. A completion that grows through the part gives a volume that would cut the part. Every growth step must check that the new cells lie in DD, as line L4 does.
  • Counting features by hints. Several hints complete to the same volume. Deduplicate by volume, as line L5 does with the map, or the planner machines the same slot twice.
  • Ignoring leftovers. Hints can miss regions that no tool reaches along an axis, such as the head of a T-slot. Without line L6 the expression is no longer exact, and the part would keep material that should be removed. Report undercuts explicitly.
  • Taking the bounding box for granted. With a stock larger than the bounding box, a row or column can be all DD. Then a cell can be reachable with no hint on its line. Add the faces of the stock as hints, or start the walk of claim 4 from the stock.

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.

hint_based_feature_recognition.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hint-based-feature-recognition/. The authors are listed in prov/0YXFJ0.jsonl.

"""Hint-based feature recognition for a rectilinear polygon in the plane.

The part P is a simple rectilinear polygon with integer vertices, and the
stock W is its bounding box. Every vertex coordinate gives a grid line, and
each grid cell lies in P or in the removal area D = W -* P. The method:

1. Hints. Every unit piece of the boundary of P between a P cell and a D
   cell is a hint, a trace of some feature, with its outward normal: the
   direction from the P cell into the D cell.
2. Completion. Sweep the D cell along the normal to the boundary of W. If
   the strip meets P, the face cannot be reached by a tool moving against
   the normal, and the hint is dropped. Otherwise grow the strip sideways,
   one column of cells at a time, while the new column stays in D.
3. Verification and classification. The completed rectangle lies in D and
   is open on the side the tool comes from, so it is a machinable feature.
   Its open sides give its type: a slot or a step.
4. Leftovers. D cells that no completed feature covers cannot be reached
   along any axis. In each row, the maximal run of D cells around them is
   reported as an undercut.

The result is exact: P = W -* (union of all feature rectangles).

Precondition: the polygon is simple and rectilinear, with integer
coordinates and distinct vertices.
Cost: for n vertices the grid has O(n^2) cells and O(n^2) hints. With 2D
prefix sums each strip test is O(1), and each completion grows by at most
O(n) columns. Distinct blocks reached from one side with the same inner
edge are disjoint, so marking their cells costs O(n^3) in all. The whole
method takes O(n^3) time and O(n^2) space.
"""

from __future__ import annotations

from fractions import Fraction

Rect = tuple[int, int, int, int]       # x0, y0, x1, y1

# the four normals, by the side of the stock that a feature opens onto
NORMALS = {"right": (1, 0), "left": (-1, 0), "top": (0, 1), "bottom": (0, -1)}


def point_in_polygon(poly, x, y) -> bool:
    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) and x0 + Fraction(x1 - x0) * (y - y0) / (y1 - y0) > x:
            inside = not inside
    return inside


class Grid:
    def __init__(self, poly):
        self.xs = sorted({p[0] for p in poly})
        self.ys = sorted({p[1] for p in poly})
        self.nx, self.ny = len(self.xs) - 1, len(self.ys) - 1
        self.stock = (self.xs[0], self.ys[0], self.xs[-1], self.ys[-1])
        self.D = set()
        for i in range(self.nx):
            for j in range(self.ny):
                cx = Fraction(self.xs[i] + self.xs[i + 1], 2)
                cy = Fraction(self.ys[j] + self.ys[j + 1], 2)
                if not point_in_polygon(poly, cx, cy):
                    self.D.add((i, j))
        S = [[0] * (self.ny + 1) for _ in range(self.nx + 1)]
        for i in range(self.nx):
            for j in range(self.ny):
                S[i + 1][j + 1] = S[i][j + 1] + S[i + 1][j] - S[i][j] + ((i, j) in self.D)
        self._S = S

    def all_D(self, i0, j0, i1, j1) -> bool:
        """Are all cells in [i0, i1) x [j0, j1) inside the grid and 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 rect(self, b) -> Rect:
        return (self.xs[b[0]], self.ys[b[1]], self.xs[b[2]], self.ys[b[3]])

    def open_sides(self, b) -> tuple[str, ...]:
        out = []
        if b[0] == 0: out.append("left")
        if b[2] == self.nx: out.append("right")
        if b[1] == 0: out.append("bottom")
        if b[3] == self.ny: out.append("top")
        return tuple(out)


def hints(g: Grid):
    """Every unit boundary piece between a P cell and a D cell, as the D
    cell and the outward normal of P there."""
    for (i, j) in sorted(g.D):
        for side, (di, dj) in NORMALS.items():
            q = (i - di, j - dj)
            if 0 <= q[0] < g.nx and 0 <= q[1] < g.ny and q not in g.D:
                yield (i, j), side


def complete(g: Grid, cell, side):
    """Sweep the cell to the stock along the normal, then grow sideways.
    Returns the block (i0, j0, i1, j1), or None if the strip meets P."""
    i, j = cell
    if side == "top":
        b = [i, j, i + 1, g.ny]
    elif side == "bottom":
        b = [i, 0, i + 1, j + 1]
    elif side == "right":
        b = [i, j, g.nx, j + 1]
    else:
        b = [0, j, i + 1, j + 1]
    if not g.all_D(*b):
        return None  # @line L3
    if side in ("top", "bottom"):
        while g.all_D(b[0] - 1, b[1], b[0], b[3]):
            b[0] -= 1
        while g.all_D(b[2], b[1], b[2] + 1, b[3]):
            b[2] += 1  # @line L4
    else:
        while g.all_D(b[0], b[1] - 1, b[2], b[1]):
            b[1] -= 1
        while g.all_D(b[0], b[3], b[2], b[3] + 1):
            b[3] += 1
    return tuple(b)


def kind(sides: tuple[str, ...]) -> str:
    """One open side is a slot, two (always adjacent, since every row and
    column of the grid holds a P cell) are a step, none is an undercut."""
    return ("undercut", "slot", "step")[len(sides)]


def undercut_runs(g: Grid, covered):
    """In each row, the maximal runs of D cells that hold a cell no feature
    covers. Runs of one row are disjoint, so this takes O(nx * ny) time."""
    out = []
    for j in range(g.ny):
        i = 0
        while i < g.nx:
            if (i, j) not in g.D:
                i += 1
                continue
            k = i
            while k < g.nx and (k, j) in g.D:
                k += 1
            if any((t, j) not in covered for t in range(i, k)):
                out.append((i, j, k, j + 1))
            i = k
    return out


def recognize(poly):
    """Return (stock, features). Each feature is a dict with the rectangle,
    its open sides, its kind, and the sides a tool can come from."""
    g = Grid(poly)  # @line L1
    found: dict = {}
    for cell, side in hints(g):  # @line L2
        b = complete(g, cell, side)
        if b is not None:
            found.setdefault(b, set()).add(side)  # @line L5
    covered = set()
    for b in found:
        covered |= {(i, j) for i in range(b[0], b[2]) for j in range(b[1], b[3])}
    undercuts = {b: set() for b in undercut_runs(g, covered)}  # @line L6
    feats = []
    for b, approach in list(found.items()) + list(undercuts.items()):
        sides = g.open_sides(b)
        feats.append({"rect": g.rect(b), "open": sides, "kind": kind(sides) if approach else "undercut",
                      "approach": tuple(sorted(approach))})
    feats.sort(key=lambda f: (f["kind"] == "undercut", f["rect"]))
    return g.stock, feats  # @line L7


def in_expression(stock: Rect, rects, x, y) -> bool:
    """Membership in stock -* (union of rects), for a point on no grid line."""
    X0, Y0, X1, Y1 = stock
    return X0 < x < X1 and Y0 < y < Y1 and not any(a < x < c and b < y < d for a, b, c, d in rects)
test_hint_based_feature_recognition.py 214 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hint-based-feature-recognition/. The authors are listed in prov/0YXFJ0.jsonl.

import random
import unittest
from bisect import bisect_left
from fractions import Fraction

from hint_based_feature_recognition import Grid, in_expression, recognize


def random_part(rng, size=7):
    """A hole-free polyomino with no pinch points, traced into a simple
    rectilinear polygon on random integer coordinates. Returns the polygon,
    the cells, and the coordinates of the cell grid."""
    while True:
        target = rng.randint(4, 24)
        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))
    return [(X[i], Y[j]) for i, j in trace(cells)], cells, X, Y


def random_carved(rng):
    """A block of cells with winding tunnels carved in from its boundary.
    Tunnels that turn under the material make undercuts, which random growth
    seldom does. Returns the same as random_part."""
    a, b = rng.randint(4, 8), rng.randint(4, 8)
    cells = {(i, j) for i in range(a) for j in range(b)}
    for _ in range(rng.randint(1, 3)):
        i, j = rng.choice([(rng.randrange(a), 0), (rng.randrange(a), b - 1), (0, rng.randrange(b)), (a - 1, rng.randrange(b))])
        di, dj = rng.choice([(1, 0), (-1, 0), (0, 1), (0, -1)])
        for _ in range(rng.randint(2, 10)):
            trial = cells - {(i, j)}
            if (i, j) in cells and len(trial) >= 3 and ok_polyomino(trial, max(a, b)) and connected(trial):
                cells = trial
            if rng.random() < 0.4:
                di, dj = rng.choice([(dj, di), (-dj, -di)])
            i, j = i + di, j + dj
            if not (0 <= i < a and 0 <= j < b):
                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))
    return [(X[i], Y[j]) for i, j in trace(cells)], cells, X, Y


def connected(cells):
    start = next(iter(cells))
    seen, stack = {start}, [start]
    while stack:
        i, j = stack.pop()
        for c in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)):
            if c in cells and c not in seen:
                seen.add(c)
                stack.append(c)
    return len(seen) == len(cells)


def ok_polyomino(cells, size):
    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
    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):
    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 accessible(cells, W, H, i, j):
    """Brute force: can a straight axis move from outside the stock reach
    the empty cell (i, j) without passing through the part?"""
    return (all((i, t) not in cells for t in range(j + 1, H))
            or all((i, t) not in cells for t in range(0, j))
            or all((t, j) not in cells for t in range(i + 1, W))
            or all((t, j) not in cells for t in range(0, i)))


def rect_of(feats, undercut):
    return [f["rect"] for f in feats if (f["kind"] == "undercut") == undercut]


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)]
        _, feats = recognize(poly)
        self.assertEqual(len(feats), 1)
        self.assertEqual((feats[0]["rect"], feats[0]["kind"], feats[0]["approach"]),
                         ((2, 2, 4, 4), "slot", ("top",)))

    def test_stepped_slot_split_floor_still_gives_the_upper_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)]
        _, feats = recognize(poly)
        self.assertEqual([(f["rect"], f["kind"], f["approach"]) for f in feats],
                         [((2, 4, 6, 6), "slot", ("top",)), ((3, 2, 5, 6), "slot", ("top",))])

    def test_t_slot_head_is_an_undercut(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)]
        _, feats = recognize(poly)
        self.assertEqual([(f["rect"], f["kind"]) for f in feats],
                         [((3, 2, 5, 6), "slot"), ((1, 2, 7, 4), "undercut")])

    def test_corner_steps(self):
        poly = [(0, 0), (6, 0), (6, 1), (5, 1), (5, 3), (3, 3), (3, 4), (0, 4)]
        _, feats = recognize(poly)
        self.assertEqual([(f["rect"], f["kind"], f["approach"]) for f in feats],
                         [((3, 3, 6, 4), "step", ("right", "top")), ((5, 1, 6, 4), "step", ("right", "top"))])

    def test_plus_shape_has_four_steps(self):
        plus = [(1, 0), (2, 0), (2, 1), (3, 1), (3, 2), (2, 2), (2, 3), (1, 3), (1, 2), (0, 2), (0, 1), (1, 1)]
        _, feats = recognize(plus)
        self.assertEqual([(f["rect"], f["kind"]) for f in feats],
                         [((0, 0, 1, 1), "step"), ((0, 2, 1, 3), "step"),
                          ((2, 0, 3, 1), "step"), ((2, 2, 3, 3), "step")])
        # each corner square is reached from two sides
        self.assertTrue(all(len(f["approach"]) == 2 for f in feats))


class TestAgainstOracle(unittest.TestCase):
    def test_expression_and_accessibility(self):
        rng = random.Random(31)
        points = with_undercut = 0
        for t in range(600):
            poly, cells, X, Y = random_part(rng) if t % 2 else random_carved(rng)
            W, H = len(X) - 1, len(Y) - 1
            stock, feats = recognize(poly)
            self.assertEqual(stock, (X[0], Y[0], X[-1], Y[-1]))
            acc, und = rect_of(feats, False), rect_of(feats, True)
            with_undercut += bool(und)
            for f in feats:
                if f["kind"] == "undercut":
                    # no tool reaches an undercut, so it touches no side of the stock
                    self.assertEqual(f["open"], ())
                else:
                    # a tool can come in: the approach side is open
                    for side in f["approach"]:
                        self.assertIn(side, f["open"])
            for _ in range(40):
                x = Fraction(rng.randint(97 * X[0] - 30, 97 * X[-1] + 30), 97)
                y = Fraction(rng.randint(97 * Y[0] - 30, 97 * Y[-1] + 30), 97)
                if x.denominator == 1 or y.denominator == 1:
                    continue
                i, j = bisect_left(X, x) - 1, bisect_left(Y, y) - 1
                inside_w = 0 <= i < W and 0 <= j < H
                in_p = (i, j) in cells
                self.assertEqual(in_expression(stock, acc + und, x, y), in_p)
                if inside_w and not in_p:
                    in_acc = any(a < x < c and b < y < d for a, b, c, d in acc)
                    self.assertEqual(in_acc, accessible(cells, W, H, i, j))
                if in_p or not inside_w:
                    # no feature reaches into the part or outside the stock
                    self.assertFalse(any(a < x < c and b < y < d for a, b, c, d in acc + und))
                points += 1
        self.assertGreater(points, 500)
        self.assertGreater(with_undercut, 30)

    def test_every_hint_cell_is_on_the_boundary(self):
        from hint_based_feature_recognition import hints
        rng = random.Random(32)
        for _ in range(100):
            poly, cells, X, Y = random_part(rng)
            g = Grid(poly)
            for (i, j), side in hints(g):
                self.assertIn((i, j), g.D)
                di, dj = {"right": (1, 0), "left": (-1, 0), "top": (0, 1), "bottom": (0, -1)}[side]
                self.assertNotIn((i - di, j - dj), g.D)


if __name__ == "__main__":
    unittest.main()

History

Early feature recognizers matched rules or graphs against the faces of a part, and they failed when features interacted. Vandenbrande, in his thesis work with Requicha at the University of Southern California, proposed in the late 1980s to recognize features from hints and to complete and verify each candidate volume. The 1993 paper in IEEE Transactions on Pattern Analysis and Machine Intelligence is the standard reference. Regli, Gupta and Nau gave an algorithmic treatment of trace-based extraction of alternative features in 1995. Han and Requicha extended the hint-based approach in the 1990s, and the survey of Han, Pratt and Regli in 2000 placed hint-based reasoning beside graph-based and volumetric recognition.

References

  1. Jan H. Vandenbrande and Aristides A. G. Requicha, Spatial reasoning for the automatic recognition of machinable features in solid models, IEEE Transactions on Pattern Analysis and Machine Intelligence 15(12), 1269 to 1285, 1993, the whole paper (hints as partial traces of features, their completion into the largest compatible volumes, and the tests that a completed volume is machinable and does not intrude into the part)
  2. JungHyun Han and Aristides A. G. Requicha, Feature recognition from CAD models, IEEE Computer Graphics and Applications 18(2), 80 to 94, 1998, the extension of the hint-based approach, with hints processed in order of promise and the completion and verification of each feature
  3. William C. Regli, Satyandra K. Gupta and Dana S. Nau, Extracting alternative machining features, an algorithmic approach, Research in Engineering Design 7(3), 173 to 192, 1995, the generation of alternative machining feature volumes from traces in the boundary of the part
  4. 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 hint-based reasoning, beside graph-based and volumetric methods

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