Algorithm Search⌘K

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.

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
Properties
deterministicexactrecursive
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 TT of templates. Each polygon is listed counterclockwise when seen from outside the solid, so that its normal nPn_P, computed by the right-hand rule, points out of the material. The polygons form a closed conforming mesh: every directed edge (p,q)(p, q) of a polygon is matched by exactly one edge (q,p)(q, p) 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 GG of the solid, and for each connected component CC of GG minus the faces with only convex arcs, the first template that is isomorphic to CC as a labeled graph, with the map of the faces, or the report that CC 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

  1. AAG-RECOGNIZE(B, T)
  2. 1for each directed edge (p, q) of a polygon P of B, find the polygon P' that holds (q, p)
  3. 2s ← sign((n_P × n_P') · (q − p)) ▷ exact, integer coordinates
  4. 3if s = 0 and n_P · n_P' > 0 then merge the faces of P and P'
  5. 4else if s = 0 then reject B ▷ a knife edge
  6. 5G ← a node per merged face, an arc {F, F'} labeled 1 for each edge with s > 0 and 0 for s < 0
  7. 6H ← G without the nodes whose arcs are all labeled 1
  8. 7for each connected component C of H do
  9. 8for each template t in T, in order, do
  10. 9if MATCH(t, C) then report (t, C) and continue with the next component
  11. 10report C as unrecognized
  12. MATCH(t, C)
  13. 11if t and C have different numbers of nodes then return false
  14. 12map the nodes of t to distinct nodes of C one at a time, by backtracking
  15. 13keep a partial map only if each pair of mapped nodes has the same label, or no arc, in t and in C
  16. 14return true if some map covers all nodes of t

The normal of a polygon is its Newell vector, ∑i(yi−yi+1)(zi+zi+1)\sum_i (y_i - y_{i+1})(z_i + z_{i+1}) and its two cyclic shifts, which is twice the area times the unit outward normal. For an edge running from pp to qq in the loop of PP, the face of PP 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 π\pi, 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
pocket four walls, floor each wall to floor, and each wall to the next, in a cycle

Example

Take the block [0,10]×[0,4]×[0,3][0, 10] \times [0, 4] \times [0, 3] and cut from it a through slot [3,5]×[0,4]×[2,3][3, 5] \times [0, 4] \times [2, 3], a step [9,10]×[0,4]×[2,3][9, 10] \times [0, 4] \times [2, 3] and a pocket [6,8]×[1,3]×[1,3][6, 8] \times [1, 3] \times [1, 3]. The implementation builds the input from unit cubes, so every face comes as unit squares.

step lines result
pair the edges L1 182182 unit squares with 728728 directed edges, each matched with its reverse
merge L2 to L4 the flat edges merge the squares into 1717 faces; no knife edge
build GG L5 4242 arcs: 3131 convex and 1111 concave
delete L6 the bottom, the left, right, front and back faces, and the two pieces of the top face, x∈[0,3]x \in [0, 3] and x∈[5,9]x \in [5, 9] with the pocket as a hole, have only convex arcs; 77 nodes go, 1010 stay
components L7 {\{slot wall x=3x = 3, slot wall x=5x = 5, slot floor}\}, {\{step wall x=9x = 9, 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 z=3z = 3 and the front face y=0y = 0 meet along an edge from (0,0,3)(0, 0, 3) to (3,0,3)(3, 0, 3), as it runs in the top face, with ntop=(0,0,1)n_{top} = (0, 0, 1) and nfront=(0,−1,0)n_{front} = (0, -1, 0) up to positive factors. Then ntop×nfront=(1,0,0)n_{top} \times n_{front} = (1, 0, 0), and its dot product with q−p=(3,0,0)q - p = (3, 0, 0) is 3>03 > 0, convex. The slot floor z=2z = 2 and the slot wall x=3x = 3, whose normal (1,0,0)(1, 0, 0) points into the slot, meet along an edge that runs from (3,4,2)(3, 4, 2) to (3,0,2)(3, 0, 2) in the floor, so that the floor is on its left. Then (0,0,1)×(1,0,0)=(0,1,0)(0, 0, 1) \times (1, 0, 0) = (0, 1, 0), and the dot product with (0,−4,0)(0, -4, 0) is −4<0-4 < 0, concave.

Now cut two crossing slots, [2,4]×[0,4]×[2,3][2, 4] \times [0, 4] \times [2, 3] and [0,6]×[1,3]×[2,3][0, 6] \times [1, 3] \times [2, 3], from the block [0,6]×[0,4]×[0,3][0, 6] \times [0, 4] \times [0, 3]. 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 pp to qq in polygon PP, the vector nP×nP′n_P \times n_{P'} is parallel to q−pq - p, 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 uu, the direction d=nP×ud = n_P \times u into face PP, and nPn_P, write nP′=αd+βnPn_{P'} = \alpha d + \beta n_P. Then (nP×nP′)⋅u=−α(n_P \times n_{P'}) \cdot u = -\alpha, and the edge is convex exactly when α<0\alpha < 0, which is when face P′P' bends down from face PP around the material. So GG 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 BB be a finite set of simple planar polygons with integer vertices that bound a solid SS. Each polygon is listed counterclockwise when seen from outside SS, every directed edge (p,q)(p, q) of a polygon occurs once, and its reverse (q,p)(q, p) occurs once, in another polygon. A face of SS is a maximal connected planar region of ∂S\partial S with one outward normal, and the polygons of BB tile the faces. All arithmetic is on integers, so every sign is computed exactly.

Lemma 1 (normals). For a simple planar polygon PP listed counterclockwise when seen from the side of the unit normal ν\nu, the Newell vector NPN_P equals 2Aν2 A \nu, where A>0A > 0 is the area of PP.

Proof. The xx component ∑i(yi−yi+1)(zi+zi+1)\sum_i (y_i - y_{i+1})(z_i + z_{i+1}) is twice the signed area of the projection of PP to the yzyz 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 AA to the plane orthogonal to the unit vector ee has signed area A ν⋅eA\, \nu \cdot e, with the sign positive when the loop runs counterclockwise seen from ee and ν⋅e>0\nu \cdot e > 0. So NP=2A(ν⋅e1,ν⋅e2,ν⋅e3)=2AνN_P = 2A(\nu \cdot e_1, \nu \cdot e_2, \nu \cdot e_3) = 2A\nu. □\square

By Lemma 1 and the orientation of BB, nP=NPn_P = N_P is a positive multiple of the outward unit normal of PP, and the signs at lines L2 and L3 are those of the unit normals.

Lemma 2 (flat edges). Let (p,q)(p, q) be an edge of PP whose reverse lies in P′P', and let u=q−pu = q - p. Then nP×nP′n_P \times n_{P'} is parallel to uu, and s=0s = 0 if and only if nPn_P and nP′n_{P'} are parallel. If s=0s = 0 and nP⋅nP′>0n_P \cdot n_{P'} > 0, then PP and P′P' lie in one plane, on the two sides of the edge, and belong to the same face. If s=0s = 0 and nP⋅nP′<0n_P \cdot n_{P'} < 0, the solid has zero thickness or a crack of zero width along the edge.

Proof. The edge lies in both planes, so uu is orthogonal to both normals, and nP×nP′n_P \times n_{P'}, which is orthogonal to both normals as well, is a multiple of uu 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, PP lies on the left of (p,q)(p, q) and P′P' lies on the left of (q,p)(q, p), 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. □\square

Lemma 3 (the sign of an edge). Let (p,q)(p, q) be an edge of PP shared with P′P', with normals that are not parallel. The material angle of SS along the edge is less than π\pi if and only if (nP×nP′)⋅(q−p)>0(n_P \times n_{P'}) \cdot (q - p) > 0.

Proof. Scale so that n=nPn = n_P, n′=nP′n' = n_{P'} and u=(q−p)/∣q−p∣u = (q - p)/|q - p| are unit vectors; this does not change the sign. Let d=n×ud = n \times u. Seen from outside, PP runs counterclockwise, so PP lies on the left of the edge, which is the side of dd; and (d,n,u)(d, n, u) is a right-handed orthonormal frame, since d×n=(n×u)×n=ud \times n = (n \times u) \times n = u. As n′n' is orthogonal to uu, write n′=αd+βnn' = \alpha d + \beta n with α2+β2=1\alpha^2 + \beta^2 = 1. Then n×n′=α n×d=−αun \times n' = \alpha\, n \times d = -\alpha u, so the sign of (n×n′)⋅u(n \times n') \cdot u is the sign of −α-\alpha.

Work in the plane orthogonal to uu through a point of the edge, with coordinates xx along dd and yy along nn. Face PP is the ray in direction (1,0)(1, 0), and the material is on its side y<0y < 0, because nn points out. Polygon P′P' holds the edge in the direction −u-u, so it lies in the direction d′=n′×(−u)=u×n′=α u×d+β u×n=αn−βdd' = n' \times (-u) = u \times n' = \alpha\, u \times d + \beta\, u \times n = \alpha n - \beta d, which is the ray (−β,α)(-\beta, \alpha). Its outward normal (α,β)(\alpha, \beta) is the ray turned clockwise by π/2\pi/2, so the material lies on the counterclockwise side of the ray of P′P'. The material is thus the sector swept clockwise from the ray (1,0)(1, 0) to the ray (−β,α)(-\beta, \alpha). Its angle is less than π\pi exactly when the second ray is in the open lower half plane, α<0\alpha < 0; it equals π\pi when α=0\alpha = 0, which Lemma 2 excludes, and exceeds π\pi when α>0\alpha > 0. So the edge is convex if and only if −α>0-\alpha > 0. □\square

Lemma 4 (the graph). After line L5, the merged groups are exactly the faces of SS, and GG 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 PP and P′P' be polygons of one face FF. The interior of FF is connected, and every point of it is in a polygon, on an edge of two polygons of FF, or at a vertex whose neighborhood in FF is a disk covered by polygons of FF that meet in pairs along edges. So a path in the interior of FF from PP to P′P' that avoids vertices crosses a chain of polygons, each sharing an edge with the next, and each such edge has s=0s = 0 and nP⋅nP′>0n_P \cdot n_{P'} > 0, 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 SS between two faces is a union of polygon edges, each counted with its label. □\square

Lemma 5 (matching). MATCH(t,C)(t, C) returns true if and only if there is a bijection φ\varphi from the nodes of tt to the nodes of CC such that, for all pairs a≠ba \ne b, the label of {a,b}\{a, b\} in tt equals the label of {φ(a),φ(b)}\{\varphi(a), \varphi(b)\} in CC, 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 tt, 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 φ\varphi exists, each restriction of φ\varphi to the first jj nodes of the order preserves the labels of its pairs and so passes line L13. The search tries every image for the jjth node in turn, and reaches the restriction to the first j+1j + 1 nodes unless it has already returned true. By induction on jj, the search returns true. □\square

Theorem. AAG-RECOGNIZE(B,T)(B, T) rejects BB if and only if SS has an edge where two faces meet with opposite normals. Otherwise it returns the attributed adjacency graph GG of SS, and for each connected component CC of the graph HH obtained from GG by deleting the nodes all of whose arcs are labeled {1}\{1\}, it reports the first template of TT that is isomorphic to CC as a labeled graph, or reports CC as unrecognized.

Proof. Line L4 runs exactly at an edge with s=0s = 0 and nP⋅nP′<0n_P \cdot n_{P'} < 0, which by Lemma 2 is a knife edge. Otherwise, by Lemma 4, GG 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 CC, line L8 tries the templates in order and line L9 stops at the first tt for which MATCH returns true, which by Lemma 5 is the first template isomorphic to CC; if there is none, line L10 reports CC. Every quantity is an integer, so no step depends on rounding. ■\blacksquare

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 EE directed edges by sorting takes O(Elog⁡E)O(E \log E) time, or O(E)O(E) expected time with a hash table, as in the implementation. The signs are O(1)O(1) each, and the merges are EE operations of a union-find structure with path halving, O(Elog⁡E)O(E \log E) in the worst case. Lines L5 to L7 take O(E)O(E) time. MATCH only runs on a component with exactly as many faces as the template, and then tries at most k!k! maps with O(k2)O(k^2) label checks each, so the matching takes O(ntk!k2)O(n t k! k^2) in the worst case. The template sizes are fixed and small, at most 55 here, so in practice the cost is linear in the size of the B-rep. The extra space is O(E)O(E) 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 11 wide and a slot 100100 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 HH. 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 HH, 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 [1,5]×[0,4]×[2,3][1, 5] \times [0, 4] \times [2, 3] into the block [0,6]×[0,4]×[0,3][0, 6] \times [0, 4] \times [0, 3] and drill a square hole [2,4]×[1,3]×[0,2][2, 4] \times [1, 3] \times [0, 2] 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.

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

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

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