Algorithmadvanced
Attributed adjacency graph recognition
Also called AAG feature recognition, Joshi-Chang feature recognition.
Joshi and Chang's method that labels the face adjacency graph of a B-rep with edge convexity and finds features as subgraphs that match templates.
- Solves
- Feature recognition
- Time
- O(E log E + n t k! k^2) worst
- Space
- O(E) extra
- Where
- E = the number of polygon edges of the input; k = the largest number of faces in a template; n = the number of faces; t = the number of templates
- Model
- Word RAM
- Properties
- deterministicexactrecursive
- Evidence
- Proof sketchCode in 1 languages
- Origin
- S. Joshi, T. C. Chang, 1988
Attributed adjacency graph recognition finds machining features in a polyhedral solid by looking at a graph instead of at the geometry. Each face of the B-rep is a node, each edge between two faces is an arc, and each arc carries one attribute: 1 if the edge is convex and 0 if it is concave. A depression feature such as a slot or a pocket is a group of faces joined by concave edges, so Joshi and Chang (1988) delete every face whose edges are all convex, and match each connected group that is left with a library of feature graphs. The matching is a labeled subgraph isomorphism test; it is NP-complete in general and fast for the small templates of real libraries.
In plain words
Look at the edges of a part with a slot cut into its top. Most edges stick out, like the edges of a box. The edges at the bottom of the slot go in, like the inside corner of a room.
The method draws a map: one dot for each face of the part, a line between two dots when the faces touch, and a mark on each line that says whether the edge sticks out or goes in. Then it rubs out every dot whose lines all stick out, because a face like that is part of the outside of the box, not of a hole or a slot.
What is left falls apart into small groups. Each group is compared with a picture book of known features: two walls and a floor make a slot, four walls and a floor make a pocket.
The problem
The input is a polyhedral solid, given as planar polygons with integer vertices, and an ordered list of templates. Each polygon is listed counterclockwise when seen from outside the solid, so that its normal , computed by the right-hand rule, points out of the material. The polygons form a closed conforming mesh: every directed edge of a polygon is matched by exactly one edge of another polygon. A face of the solid may be split into several polygons. A template is a small graph whose arcs are labeled with 0 or 1, together with a feature name.
The output is the attributed adjacency graph of the solid, and for each connected component of minus the faces with only convex arcs, the first template that is isomorphic to as a labeled graph, with the map of the faces, or the report that matches no template. This is the surface-based version of feature recognition, with the extra choice of Joshi and Chang that a feature is a whole component.
The algorithm
AAG-RECOGNIZE(B, T)- 1
for each directed edge (p, q) of a polygon P of B, find the polygon P' that holds (q, p) - 2
s ← sign((n_P × n_P') · (q − p)) ▷ exact, integer coordinates - 3
if s = 0 and n_P · n_P' > 0 then merge the faces of P and P' - 4
else if s = 0 then reject B ▷ a knife edge - 5
G ← a node per merged face, an arc {F, F'} labeled 1 for each edge with s > 0 and 0 for s < 0 - 6
H ← G without the nodes whose arcs are all labeled 1 - 7
for each connected component C of H do - 8
for each template t in T, in order, do - 9
if MATCH(t, C) then report (t, C) and continue with the next component - 10
report C as unrecognized MATCH(t, C)- 11
if t and C have different numbers of nodes then return false - 12
map the nodes of t to distinct nodes of C one at a time, by backtracking - 13
keep a partial map only if each pair of mapped nodes has the same label, or no arc, in t and in C - 14
return true if some map covers all nodes of t
The normal of a polygon is its Newell vector, and its two cyclic shifts, which is twice the area times the unit outward normal. For an edge running from to in the loop of , the face of lies on the left of the edge when seen from outside, and the sign at line L2 is positive exactly when the material angle along the edge is less than , a convex edge. Line L3 merges two coplanar polygons that meet along an edge, so the nodes are the true faces even when the input splits them. Two faces with opposite normals along an edge bound a fin of zero thickness or a crack of zero width, and line L4 rejects them. Two faces may share several edges; the arc then carries the set of their labels, and line L6 keeps a node if any of its arcs has a 0.
The templates used here are depression features of a block milled from the top:
| template | faces | concave arcs |
|---|---|---|
| step | wall, floor | wall to floor |
| through slot | two walls, floor | each wall to floor |
| blind step | two walls, floor | all three pairs |
| through hole | four walls | each wall to the next, in a cycle |
| blind slot | three walls, floor | each wall to floor, and the end wall to each side wall |
| four walls, floor | each wall to floor, and each wall to the next, in a cycle |
Example
Take the block and cut from it a through slot , a step and a pocket . The implementation builds the input from unit cubes, so every face comes as unit squares.
| step | lines | result |
|---|---|---|
| pair the edges | L1 | unit squares with directed edges, each matched with its reverse |
| merge | L2 to L4 | the flat edges merge the squares into faces; no knife edge |
| build | L5 | arcs: convex and concave |
| delete | L6 | the bottom, the left, right, front and back faces, and the two pieces of the top face, and with the pocket as a hole, have only convex arcs; nodes go, stay |
| components | L7 | slot wall , slot wall , slot floor, step wall , step floor, pocket floor, four pocket walls |
| match | L8 to L10 | three faces with two concave arcs at the floor: through slot; two faces with one concave arc: step; five faces with a concave wheel: pocket |
Two checks of the signs. The top face and the front face meet along an edge from to , as it runs in the top face, with and up to positive factors. Then , and its dot product with is , convex. The slot floor and the slot wall , whose normal points into the slot, meet along an edge that runs from to in the floor, so that the floor is on its left. Then , and the dot product with is , concave.
Now cut two crossing slots, and , from the block . The common floor is one cross-shaped face, and each slot splits the walls of the other into two, so line L7 finds one component of nine faces: the floor with eight concave arcs to eight wall pieces, and four convex arcs between wall pieces that meet at the outer corners of the block. No template matches, and line L10 reports it. This is the weakness of the method that every later graph-based method tries to fix.
Correctness
Newell's formula gives a positive multiple of the outward normal of each polygon, because the polygons run counterclockwise seen from outside. Along an edge from to in polygon , the vector is parallel to , since both normals are orthogonal to the edge, so the sign at line L2 is zero only when the faces are parallel; then they are coplanar or form a knife edge, and lines L3 and L4 sort the two cases. In a frame with the edge direction , the direction into face , and , write . Then , and the edge is convex exactly when , which is when face bends down from face around the material. So is the attributed adjacency graph of the solid, line L6 and line L7 compute the components of Joshi and Chang, and MATCH, which tries every injective map that keeps all labels, finds an isomorphism exactly when one exists. The full proof gives the details.
What is proved is that the algorithm computes the graph, the components and the matches exactly as defined. That a component is the feature a machinist would name is not provable; it is a modeling choice, and the example of the crossing slots shows where it fails.
Proof: The algorithm computes the attributed adjacency graph exactly and reports the first matching template of each componentfull
Let be a finite set of simple planar polygons with integer vertices that bound a solid . Each polygon is listed counterclockwise when seen from outside , every directed edge of a polygon occurs once, and its reverse occurs once, in another polygon. A face of is a maximal connected planar region of with one outward normal, and the polygons of tile the faces. All arithmetic is on integers, so every sign is computed exactly.
Lemma 1 (normals). For a simple planar polygon listed counterclockwise when seen from the side of the unit normal , the Newell vector equals , where is the area of .
Proof. The component is twice the signed area of the projection of to the plane, by the trapezoid form of the shoelace formula, and the same holds for the other two components with the other two planes. The projection of a planar region of area to the plane orthogonal to the unit vector has signed area , with the sign positive when the loop runs counterclockwise seen from and . So .
By Lemma 1 and the orientation of , is a positive multiple of the outward unit normal of , and the signs at lines L2 and L3 are those of the unit normals.
Lemma 2 (flat edges). Let be an edge of whose reverse lies in , and let . Then is parallel to , and if and only if and are parallel. If and , then and lie in one plane, on the two sides of the edge, and belong to the same face. If and , the solid has zero thickness or a crack of zero width along the edge.
Proof. The edge lies in both planes, so is orthogonal to both normals, and , which is orthogonal to both normals as well, is a multiple of when the normals are not parallel; it is zero exactly when they are parallel. If the normals are parallel, the planes through the common edge with parallel normals coincide. With the same direction, seen from that one outward side, lies on the left of and lies on the left of , which is the other side of the edge line, so together they form a connected planar region with one normal. With opposite directions, the outward sides are opposite, so near the edge the material is either a half-plane fin of zero thickness between the two polygons or all of space except the slit between them.
Lemma 3 (the sign of an edge). Let be an edge of shared with , with normals that are not parallel. The material angle of along the edge is less than if and only if .
Proof. Scale so that , and are unit vectors; this does not change the sign. Let . Seen from outside, runs counterclockwise, so lies on the left of the edge, which is the side of ; and is a right-handed orthonormal frame, since . As is orthogonal to , write with . Then , so the sign of is the sign of .
Work in the plane orthogonal to through a point of the edge, with coordinates along and along . Face is the ray in direction , and the material is on its side , because points out. Polygon holds the edge in the direction , so it lies in the direction , which is the ray . Its outward normal is the ray turned clockwise by , so the material lies on the counterclockwise side of the ray of . The material is thus the sector swept clockwise from the ray to the ray . Its angle is less than exactly when the second ray is in the open lower half plane, ; it equals when , which Lemma 2 excludes, and exceeds when . So the edge is convex if and only if .
Lemma 4 (the graph). After line L5, the merged groups are exactly the faces of , and has an arc between two faces, labeled with the set of the labels of their common edges, exactly when they share an edge, with label 1 for a convex and 0 for a concave edge.
Proof. By Lemma 2, line L3 merges two polygons only when they are in one face, and so every merged group lies in one face. Conversely, let and be polygons of one face . The interior of is connected, and every point of it is in a polygon, on an edge of two polygons of , or at a vertex whose neighborhood in is a disk covered by polygons of that meet in pairs along edges. So a path in the interior of from to that avoids vertices crosses a chain of polygons, each sharing an edge with the next, and each such edge has and , so line L3 merges the chain. An edge between polygons of different faces has non-parallel normals, again by Lemma 2, because two coplanar polygons with the same normal along an edge are in one face; by Lemma 3 its label is the convexity of the edge. Each edge of between two faces is a union of polygon edges, each counted with its label.
Lemma 5 (matching). MATCH returns true if and only if there is a bijection from the nodes of to the nodes of such that, for all pairs , the label of in equals the label of in , with "no arc" as a label of its own.
Proof. If the numbers of nodes differ, there is no bijection, and line L11 returns false. Otherwise, line L12 extends partial injective maps in a fixed order of the nodes of , and line L13 keeps a partial map only if it preserves the labels of all mapped pairs. If the search returns true at line L14, the map covers all nodes, is injective between sets of the same size, so a bijection, and preserves all labels, because each pair was checked when its second node was mapped. Conversely, if exists, each restriction of to the first nodes of the order preserves the labels of its pairs and so passes line L13. The search tries every image for the th node in turn, and reaches the restriction to the first nodes unless it has already returned true. By induction on , the search returns true.
Theorem. AAG-RECOGNIZE rejects if and only if has an edge where two faces meet with opposite normals. Otherwise it returns the attributed adjacency graph of , and for each connected component of the graph obtained from by deleting the nodes all of whose arcs are labeled , it reports the first template of that is isomorphic to as a labeled graph, or reports as unrecognized.
Proof. Line L4 runs exactly at an edge with and , which by Lemma 2 is a knife edge. Otherwise, by Lemma 4, is the attributed adjacency graph. Line L6 deletes exactly the nodes all of whose arcs are convex, and line L7 visits each component of the rest once. For a component , line L8 tries the templates in order and line L9 stops at the first for which MATCH returns true, which by Lemma 5 is the first template isomorphic to ; if there is none, line L10 reports . Every quantity is an integer, so no step depends on rounding.
What is not claimed. The theorem says that the method computes the components and matches that Joshi and Chang define. It does not say that these are the features a process planner wants. That depends on the templates and on how the features interact, and it is judged on test parts, not proved.
Complexity
The costs are in the word RAM, with integer coordinates of bounded size. Pairing the directed edges by sorting takes time, or expected time with a hash table, as in the implementation. The signs are each, and the merges are operations of a union-find structure with path halving, in the worst case. Lines L5 to L7 take time. MATCH only runs on a component with exactly as many faces as the template, and then tries at most maps with label checks each, so the matching takes in the worst case. The template sizes are fixed and small, at most here, so in practice the cost is linear in the size of the B-rep. The extra space is for the edge table and the graph.
Properties
- Exact. With integer vertices every decision is the sign of an integer, and the graph is the true graph of the solid. No tolerance is used.
- Independent of size and position. The graph does not change when a feature is moved or scaled, as long as its faces keep their adjacency. A slot wide and a slot wide have the same graph.
- Depressions only. The deletion rule keeps faces with a concave edge. A boss on a face drags that face into its component, with convex arcs between the walls of the boss, and no depression template matches.
- Components, not subgraphs. A feature must be a whole component of . Two features that touch along a concave edge form one component and are not recognized.
Variants and improvements
- Richer attributes. Labeling arcs only convex or concave makes a V-groove and a step look the same, and a square through hole and a through hole with a rhombic cross section look the same. Later systems add the face type, the angle between the faces, the direction of the normal relative to the tool axis, and loops on a face.
- Subgraph matching. Instead of whole components, search for each template as a labeled induced subgraph of , with Ullmann's algorithm or VF2, so that features inside a larger component are found.
- Virtual links and hints. For interacting features, add arcs for edges that the interaction removed, or start from traces of features and grow them, as in hint-based recognition.
- Curved faces. For cylinders and other curved faces, the convexity of an edge varies along it and needs the normals at a point of the edge, and a face may be tangent to its neighbor, where the sign is zero; these are labeled smooth and treated separately.
- Meshes. For scanned data, a mesh segmentation gives the faces first, and the graph is built on the segments.
When to use it
Use the attributed adjacency graph for prismatic parts with isolated 2.5D features, when the part has no feature history, for example after a neutral B-rep file was read. It is simple, exact and fast. When features interact heavily, or for freeform parts, use it as a first stage and pass the unrecognized components to a volumetric or hint-based method, as surveyed on the feature recognition page. When the part was built with feature-based modeling, read the features from the history instead.
Pitfalls
- Signs near zero. Line L2 is an orientation test of the two normals and the edge. With floating-point vertices, two almost coplanar faces give a tiny value with catastrophic cancellation, and the label can be wrong or an edge that should be merged can be kept. The fix is exact arithmetic on integer or rational vertices, as here, or a floating-point filter with an exact fall back.
- Orientation. If the polygons run clockwise seen from outside, every label flips, all faces have a concave arc, and the whole solid is one component. Check the orientation first, for example with the sign of the volume.
- Split faces. A B-rep from a mesher or a translator often splits a planar face into several pieces. Without the merge at line L3, a floor split in two gives a graph that matches no template.
- Same graph, different shape. The labels do not see angles, so a V-groove is reported as a step. A test of the implementation checks exactly this case.
- Interactions. Cut a slot into the block and drill a square hole down from its floor. The hole walls meet the floor at convex edges, but both are kept, because each has a concave arc elsewhere, so the slot and the hole form one component of seven faces, which matches neither template. If the hole is flush with a slot wall, the two coplanar walls even merge into one face.
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/attributed-adjacency-graph/. The authors are listed in prov/5037C3.jsonl.
"""Feature recognition with the attributed adjacency graph of Joshi and Chang, exactly.
The input is a polyhedral solid given by planar polygons with integer
vertices. Each polygon is listed counterclockwise when seen from outside the
solid, so that its Newell normal points out (the right-hand rule). The
polygons must form a conforming mesh: each directed edge (p, q) of a polygon
is matched by exactly one edge (q, p) of another polygon. A face of the solid
may be given as several polygons; coplanar neighbors are merged into one face.
The edge between two faces is convex (label 1) or concave (label 0) as the
sign of (n_f x n_g) . (q - p) is positive or negative, where (p, q) is the
edge as it runs in the polygon of f. All coordinates are integers, so every
sign is exact.
"""
from itertools import permutations
CONVEX, CONCAVE = 1, 0
def sub(a, b):
return (a[0] - b[0], a[1] - b[1], a[2] - b[2])
def dot(a, b):
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
def cross(a, b):
return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])
def newell(poly):
"""Twice the area vector of a planar polygon; it points out for a counterclockwise loop seen from outside."""
nx = ny = nz = 0
for i, p in enumerate(poly):
q = poly[(i + 1) % len(poly)]
nx += (p[1] - q[1]) * (p[2] + q[2])
ny += (p[2] - q[2]) * (p[0] + q[0])
nz += (p[0] - q[0]) * (p[1] + q[1])
return (nx, ny, nz)
class UnionFind:
def __init__(self, n):
self.parent = list(range(n))
def find(self, a):
while self.parent[a] != a:
self.parent[a] = self.parent[self.parent[a]]
a = self.parent[a]
return a
def union(self, a, b):
self.parent[self.find(a)] = self.find(b)
def build_aag(polys):
"""Return (faces, arcs): faces is a list of sets of polygon indices, and arcs maps a pair (i, j), i < j, of face indices to a frozenset of labels."""
normals = [newell(P) for P in polys]
owner = {}
for k, P in enumerate(polys):
for i, p in enumerate(P):
e = (tuple(p), tuple(P[(i + 1) % len(P)]))
if e in owner:
raise ValueError("a directed edge occurs twice: the solid is not manifold or not oriented")
owner[e] = k
uf = UnionFind(len(polys))
signed = []
for (p, q), k in owner.items():
k2 = owner.get((q, p)) # @line L1
if k2 is None:
raise ValueError("an edge has no partner: the polygons do not close up")
if k2 == k:
continue
s = dot(cross(normals[k], normals[k2]), sub(q, p)) # @line L2
if s == 0 and dot(normals[k], normals[k2]) > 0: # @line L3
uf.union(k, k2)
elif s == 0: # @line L4
raise ValueError("two faces meet at a knife edge")
else:
signed.append((k, k2, CONVEX if s > 0 else CONCAVE))
roots = sorted({uf.find(k) for k in range(len(polys))})
index = {r: i for i, r in enumerate(roots)}
faces = [set() for _ in roots]
for k in range(len(polys)):
faces[index[uf.find(k)]].add(k)
arcs = {}
for k, k2, label in signed: # @line L5
a, b = index[uf.find(k)], index[uf.find(k2)]
if a != b:
key = (min(a, b), max(a, b))
arcs[key] = arcs.get(key, frozenset()) | {label}
return faces, arcs
def neighbors(n, arcs):
adj = [dict() for _ in range(n)]
for (a, b), lab in arcs.items():
adj[a][b] = lab
adj[b][a] = lab
return adj
def match(template, comp, adj):
"""A map from the template nodes onto the component that keeps every label and every non-arc, or None."""
k, t_arcs = template["nodes"], template["arcs"]
if k != len(comp): # @line L11
return None
t_adj = [dict() for _ in range(k)]
for (a, b), lab in t_arcs.items():
t_adj[a][b] = t_adj[b][a] = lab
order = sorted(range(k), key=lambda a: -len(t_adj[a]))
nodes = sorted(comp)
image = {}
def extend(depth):
if depth == k: # @line L14
return True
a = order[depth]
for v in nodes: # @line L12
if v in image.values():
continue
if all(t_adj[a].get(b) == adj[v].get(image[b]) for b in order[:depth]): # @line L13
image[a] = v
if extend(depth + 1):
return True
del image[a]
return False
return dict(image) if extend(0) else None
def recognize(polys, templates):
"""Return (faces, arcs, results); each result is (template name or None, component, map)."""
faces, arcs = build_aag(polys)
adj = neighbors(len(faces), arcs)
kept = {v for v in range(len(faces)) if any(lab != frozenset({CONVEX}) for lab in adj[v].values())} # @line L6
sub_adj = [{w: lab for w, lab in adj[v].items() if w in kept} if v in kept else {} for v in range(len(faces))]
results, seen = [], set()
for v in sorted(kept): # @line L7
if v in seen:
continue
comp, stack = {v}, [v]
while stack:
u = stack.pop()
for w in sub_adj[u]:
if w not in comp:
comp.add(w)
stack.append(w)
seen |= comp
for t in templates: # @line L8
m = match(t, comp, sub_adj)
if m is not None: # @line L9
results.append((t["name"], frozenset(comp), m))
break
else:
results.append((None, frozenset(comp), None)) # @line L10
return faces, arcs, results
def match_brute_force(template, comp, adj):
"""Reference: try every bijection."""
k, t_arcs = template["nodes"], template["arcs"]
if k != len(comp):
return None
nodes = sorted(comp)
for perm in permutations(nodes):
if all(t_arcs.get((a, b), t_arcs.get((b, a))) == adj[perm[a]].get(perm[b]) for a in range(k) for b in range(a + 1, k)):
return dict(enumerate(perm))
return None
# --- templates ---------------------------------------------------------------
def template(name, k, concave_pairs):
return {"name": name, "nodes": k, "arcs": {(a, b): frozenset({CONCAVE}) for a, b in concave_pairs}}
TEMPLATES = [
template("pocket", 5, [(0, 1), (0, 2), (0, 3), (0, 4), (1, 2), (2, 3), (3, 4), (4, 1)]),
template("blind slot", 4, [(0, 1), (0, 2), (0, 3), (1, 2), (2, 3)]),
template("through hole", 4, [(0, 1), (1, 2), (2, 3), (3, 0)]),
template("blind step", 3, [(0, 1), (0, 2), (1, 2)]),
template("through slot", 3, [(0, 1), (0, 2)]),
template("step", 2, [(0, 1)]),
]
# --- building test solids ---------------------------------------------------
def voxel_brep(cells):
"""The boundary of a union of unit cubes, as one outward square per exposed cube face."""
cells = set(cells)
polys = []
for (i, j, k) in cells:
for axis in range(3):
for side in (0, 1):
nb = [i, j, k]
nb[axis] += 1 if side else -1
if tuple(nb) in cells:
continue
c = [i, j, k]
c[axis] += side
u, w = (axis + 1) % 3, (axis + 2) % 3
sq = []
for du, dw in ((0, 0), (1, 0), (1, 1), (0, 1)):
p = list(c)
p[u] += du
p[w] += dw
sq.append(tuple(p))
out = [0, 0, 0]
out[axis] = 1 if side else -1
if dot(newell(sq), tuple(out)) < 0:
sq.reverse()
polys.append(sq)
return polys
def box_cells(x0, x1, y0, y1, z0, z1):
return {(i, j, k) for i in range(x0, x1) for j in range(y0, y1) for k in range(z0, z1)}
def prism(profile, length):
"""A profile in the xz plane, counterclockwise with x to the right and z up, extruded along y from 0 to length."""
cap0 = [(x, 0, z) for (x, z) in profile]
cap1 = [(x, length, z) for (x, z) in reversed(profile)]
sides = []
for i, a in enumerate(profile):
b = profile[(i + 1) % len(profile)]
sides.append([(b[0], 0, b[1]), (a[0], 0, a[1]), (a[0], length, a[1]), (b[0], length, b[1])])
return [cap0, cap1] + sides
def signed_volume6(polys):
"""Six times the volume enclosed by the polygons, positive when they face out."""
total = 0
for P in polys:
for i in range(1, len(P) - 1):
total += dot(P[0], cross(P[i], P[i + 1]))
return total
test_attributed_adjacency_graph.py 273 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/attributed-adjacency-graph/. The authors are listed in prov/5037C3.jsonl.
import random
import unittest
from attributed_adjacency_graph import (
CONCAVE,
CONVEX,
TEMPLATES,
box_cells,
build_aag,
match,
match_brute_force,
neighbors,
prism,
recognize,
signed_volume6,
voxel_brep,
)
def block(W=6, D=4, H=3):
return box_cells(0, W, 0, D, 0, H)
def names(polys):
return sorted(n for n, _, _ in recognize(polys, TEMPLATES)[2] if n is not None)
def unrecognized(polys):
return [c for n, c, _ in recognize(polys, TEMPLATES)[2] if n is None]
# --- a brute-force AAG of a union of unit cubes ------------------------------
def brute_aag(cells):
"""Faces by flood fill of the exposed unit squares, labels by counting the cubes around each unit edge."""
squares = {} # key: frozenset of corners -> (axis, side, plane, (a, b)) with (a, b) the in-plane cell
for (i, j, k) in cells:
for axis in range(3):
for side in (0, 1):
nb = [i, j, k]
nb[axis] += 1 if side else -1
if tuple(nb) in cells:
continue
c = [i, j, k]
c[axis] += side
u, w = (axis + 1) % 3, (axis + 2) % 3
corners = []
for du, dw in ((0, 0), (1, 0), (1, 1), (0, 1)):
p = list(c)
p[u] += du
p[w] += dw
corners.append(tuple(p))
squares[frozenset(corners)] = (axis, side, c[axis], (c[u], c[w]))
by_plane = {}
for key, (axis, side, plane, ab) in squares.items():
by_plane.setdefault((axis, side, plane), {})[ab] = key
face_of = {}
faces = []
for plane, grid in by_plane.items():
for ab, key in grid.items():
if key in face_of:
continue
fid = len(faces)
faces.append(set())
stack = [ab]
face_of[key] = fid
while stack:
a, b = stack.pop()
faces[fid].add(grid[(a, b)])
for nab in ((a + 1, b), (a - 1, b), (a, b + 1), (a, b - 1)):
if nab in grid and grid[nab] not in face_of:
face_of[grid[nab]] = fid
stack.append(nab)
edge_faces = {}
for key in squares:
pts = sorted(key)
for p in pts:
for q in pts:
if p < q and sum(abs(p[t] - q[t]) for t in range(3)) == 1:
edge_faces.setdefault((p, q), []).append(face_of[key])
arcs = {}
for (p, q), fs in edge_faces.items():
if len(fs) != 2:
return None # a non-manifold edge
a, b = fs
if a == b:
continue
axis = next(t for t in range(3) if p[t] != q[t])
u, w = (axis + 1) % 3, (axis + 2) % 3
count = 0
for du in (-1, 0):
for dw in (-1, 0):
c = list(p)
c[u] += du
c[w] += dw
count += tuple(c) in cells
if count == 2:
return None
lab = CONVEX if count == 1 else CONCAVE
key = (min(a, b), max(a, b))
arcs[key] = arcs.get(key, frozenset()) | {lab}
return [frozenset(f) for f in faces], arcs
def canonical(polys, faces, arcs):
"""Faces as sets of square corner sets, so that two AAGs of the same cubes can be compared."""
names_ = [frozenset(frozenset(polys[k]) for k in f) for f in faces]
return set(names_), {frozenset((names_[a], names_[b])): lab for (a, b), lab in arcs.items()}
def brute_recognize(cells):
faces, arcs = brute_aag(cells)
adj = neighbors(len(faces), arcs)
kept = {v for v in range(len(faces)) if any(lab != frozenset({CONVEX}) for lab in adj[v].values())}
sub = [{w: lab for w, lab in adj[v].items() if w in kept} if v in kept else {} for v in range(len(faces))]
out, seen = [], set()
for v in sorted(kept):
if v in seen:
continue
comp, stack = {v}, [v]
while stack:
for w in sub[stack.pop()]:
if w not in comp:
comp.add(w)
stack.append(w)
seen |= comp
name = next((t["name"] for t in TEMPLATES if match_brute_force(t, comp, sub) is not None), None)
out.append((name, frozenset(faces[x] for x in comp)))
return out
class TestSingleFeatures(unittest.TestCase):
def test_each_template_is_recognized(self):
B = block()
cases = {
"step": B - box_cells(5, 6, 0, 4, 2, 3),
"through slot": B - box_cells(2, 4, 0, 4, 2, 3),
"blind slot": B - box_cells(2, 4, 0, 3, 2, 3),
"blind step": B - box_cells(0, 2, 0, 2, 2, 3),
"pocket": B - box_cells(2, 4, 1, 3, 1, 3),
"through hole": B - box_cells(2, 3, 1, 2, 0, 3),
}
for name, cells in cases.items():
polys = voxel_brep(cells)
self.assertGreater(signed_volume6(polys), 0)
self.assertEqual(names(polys), [name], name)
self.assertEqual(unrecognized(polys), [], name)
def test_plain_block_has_no_feature(self):
faces, arcs, res = recognize(voxel_brep(block()), TEMPLATES)
self.assertEqual(len(faces), 6)
self.assertEqual(len(arcs), 12)
self.assertTrue(all(lab == frozenset({CONVEX}) for lab in arcs.values()))
self.assertEqual(res, [])
def test_example_part(self):
cells = block(10, 4, 3) - box_cells(3, 5, 0, 4, 2, 3) - box_cells(9, 10, 0, 4, 2, 3) - box_cells(6, 8, 1, 3, 1, 3)
faces, arcs, res = recognize(voxel_brep(cells), TEMPLATES)
self.assertEqual(len(faces), 17)
self.assertEqual(sum(lab == frozenset({CONCAVE}) for lab in arcs.values()), 11)
self.assertEqual(sorted(n for n, _, _ in res), ["pocket", "step", "through slot"])
class TestAgainstBruteForce(unittest.TestCase):
def test_aag_of_random_parts(self):
rng = random.Random(7)
checked = rejected = 0
for _ in range(120):
W, D, H = rng.randint(3, 7), rng.randint(3, 6), rng.randint(2, 4)
cells = block(W, D, H)
for _ in range(rng.randint(1, 3)):
x0, y0 = rng.randint(0, W - 1), rng.randint(0, D - 1)
x1, y1 = rng.randint(x0 + 1, W), rng.randint(y0 + 1, D)
cells -= box_cells(x0, x1, y0, y1, rng.randint(0, H - 1), H)
if not cells:
continue
polys = voxel_brep(cells)
ref = brute_aag(cells)
if ref is None:
with self.assertRaises(ValueError):
build_aag(polys)
rejected += 1
continue
faces, arcs = build_aag(polys)
# build_aag returns polygon indices; the brute force returns corner sets.
got = canonical(polys, faces, arcs)
want = ({frozenset(f) for f in ref[0]}, {frozenset((ref[0][a], ref[0][b])): lab for (a, b), lab in ref[1].items()})
self.assertEqual(got, want)
checked += 1
mine = {(n, frozenset(frozenset(frozenset(polys[k]) for k in faces[x]) for x in c)) for n, c, _ in recognize(polys, TEMPLATES)[2]}
theirs = set(brute_recognize(cells))
self.assertEqual(mine, theirs)
self.assertGreater(checked, 60)
self.assertGreater(rejected, 0)
def test_backtracking_matches_brute_force(self):
rng = random.Random(11)
labels = [frozenset({CONVEX}), frozenset({CONCAVE}), frozenset({CONVEX, CONCAVE})]
for _ in range(400):
k = rng.randint(1, 6)
arcs = {}
for a in range(k):
for b in range(a + 1, k):
if rng.random() < 0.5:
arcs[(a, b)] = rng.choice(labels[:2] if rng.random() < 0.9 else labels)
# a host graph that is either a relabeling of the template or a random graph of the same size
nodes = list(range(10, 10 + k))
if rng.random() < 0.5:
perm = nodes[:]
rng.shuffle(perm)
host = {(min(perm[a], perm[b]), max(perm[a], perm[b])): lab for (a, b), lab in arcs.items()}
else:
host = {}
for a in nodes:
for b in nodes:
if a < b and rng.random() < 0.5:
host[(a, b)] = rng.choice(labels[:2])
adj = neighbors(10 + k, host)
t = {"name": "t", "nodes": k, "arcs": arcs}
m1, m2 = match(t, set(nodes), adj), match_brute_force(t, set(nodes), adj)
self.assertEqual(m1 is None, m2 is None)
if m1 is not None:
for a in range(k):
for b in range(a + 1, k):
self.assertEqual(arcs.get((a, b)), adj[m1[a]].get(m1[b]))
class TestDegenerateInputs(unittest.TestCase):
def test_crossing_slots_are_not_recognized(self):
cells = block() - box_cells(2, 4, 0, 4, 2, 3) - box_cells(0, 6, 1, 3, 2, 3)
res = recognize(voxel_brep(cells), TEMPLATES)[2]
self.assertEqual(len(res), 1)
self.assertIsNone(res[0][0])
self.assertEqual(len(res[0][1]), 9)
# A square hole drilled down from the floor of a slot joins the slot in one component.
cells = block() - box_cells(1, 5, 0, 4, 2, 3) - box_cells(2, 4, 1, 3, 0, 2)
res = recognize(voxel_brep(cells), TEMPLATES)[2]
self.assertEqual([(n, len(c)) for n, c, _ in res], [(None, 7)])
def test_v_groove_looks_like_a_step(self):
groove = prism([(0, 0), (6, 0), (6, 3), (4, 3), (3, 1), (2, 3), (0, 3)], 4)
self.assertGreater(signed_volume6(groove), 0)
self.assertEqual(names(groove), ["step"])
def test_split_faces_are_merged(self):
plain = prism([(0, 0), (6, 0), (6, 3), (0, 3)], 4)
split = prism([(0, 0), (2, 0), (6, 0), (6, 3), (0, 3)], 4)
self.assertEqual(len(build_aag(plain)[0]), 6)
self.assertEqual(len(build_aag(split)[0]), 6)
def test_inside_out_swaps_the_labels(self):
polys = voxel_brep(block() - box_cells(2, 4, 0, 4, 2, 3))
rev = [list(reversed(P)) for P in polys]
faces, arcs = canonical(polys, *build_aag(polys))
faces2, flipped = canonical(rev, *build_aag(rev))
swap = {CONVEX: CONCAVE, CONCAVE: CONVEX}
self.assertEqual(faces, faces2)
self.assertEqual(flipped, {e: frozenset(swap[x] for x in lab) for e, lab in arcs.items()})
def test_bad_meshes_are_rejected(self):
two = voxel_brep({(0, 0, 0), (1, 1, 0)}) # two cubes that share only an edge
with self.assertRaises(ValueError):
build_aag(two)
with self.assertRaises(ValueError):
build_aag(voxel_brep(block())[1:]) # an open mesh
if __name__ == "__main__":
unittest.main()
History
Joshi and Chang published the attributed adjacency graph in 1988, as heuristics for the recognition of machined features from a 3D solid model. It was one of the first graph-based recognizers and the start of a large literature that added richer attributes, subgraph matching and ways to handle interacting features. The survey of Han, Pratt and Regli in 2000 counts graph-based methods as one of the three main families of feature recognition, with volumetric decomposition and hint-based methods, and names feature interactions as their main limit.
References
- S. Joshi and T. C. Chang, Graph-based heuristics for recognition of machined features from a 3D solid model, Computer-Aided Design 20(2), 58 to 66, 1988, the whole paper (the definition of the attributed adjacency graph, with 0 for a concave and 1 for a convex arc, the deletion of faces with only convex arcs, and the matching of the remaining components with feature graphs)
- 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 graph-based recognition and its trouble with interacting features
- Jami J. Shah and Martti Mäntylä, Parametric and Feature-Based CAD/CAM, Concepts, Techniques, and Applications, Wiley, 1995, the part on feature recognition, graph-based methods (chapter number not checked)
- Michael R. Garey and David S. Johnson, Computers and Intractability, A Guide to the Theory of NP-Completeness, W. H. Freeman, 1979, Appendix A1.4, Subgraph isomorphism (the matching step is NP-complete when the templates are part of the input)
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 5037C3 Edit this page History Report an error Markdown