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.
- Solves
- Feature recognition
- Time
- O(n^3) worst
- Space
- O(n^2) extra
- Where
- n = the number of vertices of the part
- Model
- Word RAM
- Properties
- deterministicexactiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 with integer vertices, the section of a prismatic part. The stock is its bounding box, and is the area to remove. The cutter moves along the four axis directions. A point of is reachable from side if the straight segment from it to the side of does not pass through the interior of . The output is a list of rectangles in , each with the sides of it lies on and the sides it is reached from, such that:
- the reachable features cover exactly the reachable points of ,
- the remaining points of are covered by rectangles marked as undercuts,
- .
The algorithm
Line L1 builds the grid of all vertex coordinates. Every edge of lies on a grid line, so each cell lies wholly in or wholly in . Line L2 enumerates the hints. A hint is a unit piece of the boundary between a cell of and a cell of , and its normal points from into . The piece is a floor if is up, a wall if is sideways. Line L3 sweeps in direction to the side of the stock. If the strip holds a cell of , the face cannot be reached from side , and the hint is dropped. Line L4 widens the strip across , one row or column at a time, while the new cells are all in . 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 that no completed block covers, if there are any. In each row it takes the maximal run of cells around them and marks it as an undercut.
HINT-RECOGNIZE(P)- 1
build the grid of the vertex coordinates of P; D ← the cells not in P; W ← the bounding box F ← an empty map from blocks to sets of sides- 2
for each cell c of D and side s such that the neighbour of c opposite to s is a cell of P do strip ← the cells from c to the side s of W- 3
if strip holds a cell of P then continue - 4
widen strip across s, one row or column at a time, while the new cells are in D - 5
add s to F[strip] - 6
for each row, record as an undercut every maximal run of D cells in it that holds a cell covered by no block of F- 7
return 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 answers "are all cells of this block in ?" 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 cells, and that never happens with the bounding box as stock (see Correctness).
Example
Take the block with a stepped slot cut into its top: a wide upper slot over a narrow lower slot . The vertices are
The grid lines are and . The floor of the upper slot is split by the lower slot into two pieces, and at . 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 at | up | , empty | widened to , a slot |
| floor piece at | up | , empty | widened to , the same slot |
| wall at , | right | runs into | dropped |
| wall at , | left | runs into | dropped |
| floor at | up | , empty | cannot widen, , a slot |
| wall at , | right | runs into | dropped |
| wall at , | left | runs into | dropped |
So there are two features, the wide slot and the deep narrow slot , both reached from the top. They overlap in , and . 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 and a wider head , the floor of the head gives the slot . The cells and cannot be reached from any side. Line L6 takes the run of cells around them in their row, , and marks it as an undercut.
Correctness
The proof file proves the following.
- Cells are pure, as in volume decomposition: edges of lie on grid lines, so a cell is wholly inside or outside .
- Every row and every column holds a cell of . is connected and is its bounding box, so spans the full range of and of , and it has interior points in every open column and row.
- Completed blocks are reachable. A block from line L5 lies in and reaches the side of . Each of its cells has its whole strip to side inside the block, so every point of the block is reachable from .
- Every reachable cell is covered. Take a cell of reachable from side . Walk from in the direction opposite to . By 2, the walk meets a cell of . The last cell of before it carries a hint with normal . The hint's strip contains and stays in , so it passes line L3, and its block covers .
- 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 , 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.
- The expression is exact. All blocks lie in , and together they cover every cell of . So their union is , and .
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 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. is a closed region bounded by a simple rectilinear polygon with integer vertices, so is regular and . Let and be the distinct vertex coordinates, and let be the bounding box (line L1). The grid is the union of the lines and inside . The open cell is , with and . The removal area is . For a set of cells, is the closure of the union of its open cells. A block is a set of cells , and is a closed rectangle.
The sides of are top, bottom, left and right, with normals , , and . For a cell and a side , the strip of to is the block of cells from to the side in the direction of the normal of . For example, the strip of to the top is .
Lemma 1 (cells are pure). Each open cell lies in or in . Let and be the two kinds. Then and , and line L1 puts in exactly the cells of .
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 and, being connected, lies on one side of it. The closure claims follow because is closed with empty interior, so removing it from an open set does not change the closure.
Reachability. A point of an open cell is reachable from side if the segment from to the side of , in the direction of the normal of , misses . A cell is reachable from if its points are.
Lemma 2. A cell of is reachable from if and only if every cell of its strip to is in . Then all its points are reachable from .
Proof. The segment from to side 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 , the segment meets that open cell, which lies in . If all cells of the strip are in , the segment meets no point of inside those open cells, which lie outside . A point where it crosses a grid line between two such cells is not in either, since every neighbourhood of meets those open cells, which lie outside . The condition depends only on the cell, so it holds for all points of the cell at once.
Lemma 3 (every row and column holds a cell of ). For every there is a with , and for every there is an with .
Proof. The interior of the region bounded by a simple polygon is connected and open, so its projection to the -axis is an open interval . The projection is continuous and , so the projection of , which is because is the bounding box, lies in . Hence . Pick in and a point of . Since is open, we can move slightly so that it lies on no grid line, while keeping the point in and fixed. The point then lies in an open cell of column , which meets and so is in by Lemma 1. Rows are the same with the axes swapped.
Lemma 4 (completion). Let be a hint of line L2. If some cell of the strip of to is in , line L3 drops the hint. Otherwise lines L3 and L4 return a block with these properties. (a) Every cell of is in , and contains the strip of to . (b) reaches the side : for the top, where is the row of . (c) Every cell of is reachable from .
Proof. Line L3 tests the strip with the prefix sums, which count the cells of in a block exactly, so it drops the hint exactly when the strip holds a cell of . Take the top; the other sides are the same after a rotation. The block starts as the strip . Line L4 adds the column or over the rows only when all its cells are in . So (a) and (b) hold by induction over the growth steps. For (c), the strip to the top of a cell of is , which lies in because . All its cells are in 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 steps.
Lemma 5 (every reachable cell is covered). Let be reachable from . Then some block that line L5 records for side contains .
Proof. Take the top and . By Lemma 3, column holds a cell of . By Lemma 2 the cells are all in , so every cell of in column lies below row . Let with be the highest one. Then the cells are in . The cell is in , and its neighbour opposite the top, , is in , so is a hint of line L2. Its strip consists of cells of : those up to row by the choice of , and those above by the reachability of . So line L3 keeps the hint, and by Lemma 4(a) its block contains the strip, which contains .
Lemma 6 (open sides). A block recorded in line L5 for side has among its open sides. No block of cells of 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 only, against Lemma 3. Top and bottom are the same. So at most two sides are open, and two open sides are adjacent.
Lemma 7 (undercut runs). Let be the set of cells of covered by no block of line L5. Each run that line L6 records consists of cells of , contains a cell of , and has no open side. Every cell of lies in a recorded run.
Proof. Line L6 takes, in each row, the maximal runs of consecutive cells of and records those that contain a cell of . A cell lies in exactly one maximal run of its row, which is then recorded. By Lemma 5, is reachable from no side. If the run of contained the first or last cell of the row, it would contain the strip of to the left or the right, and would be reachable by Lemma 2. If the run lay in row or row , the strip of to the bottom or the top would be alone, and would again be reachable. So the run has no open side.
Theorem. Let be the blocks of line L5 and the runs of line L6. Then:
- every block of consists of cells of , so ;
- the union of over is ;
- ;
- a point of an open cell of lies in a block of if and only if its cell is reachable from some side;
- the blocks of are reached from the sides that line L5 records, which are among their open sides, and the runs of have no open side.
Proof. Part 1 is Lemma 4(a) and Lemma 7. For part 2, the blocks of cover every cell of outside by the definition of , and the runs of cover by Lemma 7. So the union of the closed blocks is a finite union of closed sets. It contains every open cell of and so its closure , and by part 1 it lies in .
For part 3, write . The open cells of are open and disjoint from every open cell of , so they miss the closure and lie in . Taking closures, . Conversely, is an open set that misses every open cell of , so it lies in . An open set satisfies , so .
For part 4, a cell in a block of is reachable by Lemma 4(c), and a reachable cell lies in a block of 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.
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 is the maximal run of columns around the hint's column for which the block consists of cells of . Two such runs for the same are equal or disjoint, because the union of two overlapping runs would also qualify. So the distinct top blocks with lower row hold at most cells together. Summing over and the four sides gives marked cells, which is for 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 vertices the grid has cells and hints. With prefix sums, line L3 is . Line L4 widens by at most rows or columns at each. So the hints cost 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 cells, and over the lines and four sides, the marking costs . Line L6 scans each row once, in . Building the grid costs with a point-in-polygon test per cell. The total is time and 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 , 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 . 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.
# 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
- 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)
- 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
- 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
- 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.
| 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 0YXFJ0 Edit this page History Report an error Markdown