Algorithm Search⌘K

Algorithmadvanced

Alternating sum of volumes

Also called ASV decomposition, Woo-Kim convex decomposition.

Woo's and Kim's decomposition of a solid into convex hulls and their differences with alternating signs, from which form features are read off.

Time
O(n^2 log n) worst
Space
O(n^2) extra
Where
n = the number of vertices of the polygon
Properties
deterministicexactrecursive
Origin
Tony C. Woo, 1982

The alternating sum of volumes, or ASV, writes a solid as a signed sum of convex solids. Take the convex hull H0H_0 of the solid QQ. What the hull adds is the deficiency Q1=H0−∗QQ_1 = H_0 -^* Q. Take its hull H1H_1, the deficiency of that, and so on. Then

Q=H0−(H1−(H2−⋯ ))=H0−H1+H2−⋯Q = H_0 - (H_1 - (H_2 - \cdots)) = H_0 - H_1 + H_2 - \cdots

when the series ends, with the sum meant as a sum of indicator functions. Woo proposed it in 1982 for feature recognition. Each term is convex, the outer terms give the overall shape, and the inner terms are depressions and protrusions such as slots, pockets and bosses. A convex solid ends in one step. In three dimensions the series need not end: a hull and its deficiency can have the same hull, and then the terms repeat forever. Kim and Wilde found the local cause of this and fixed it with partitioning, the ASVP decomposition, in 1992. This page gives the method for simple polygons in the plane, where it always ends. It proves the expression, gives a 3D solid on which the plain series cycles, and shows how a cut fixes it.

In plain words

Stretch a rubber band around a shape. The band encloses the shape plus some extra regions, the dents. Write the shape as "the band's area minus the dents".

Now each dent is a shape too, and it may have dents of its own. Stretch a band around each dent and repeat. Every band encloses a convex region, so the shape becomes plus a convex region, minus some, plus some more, and so on.

A plain rectangle needs only one band. An L shape needs two: the band around the L, minus a triangle. A stepped slot cut into a block needs three levels. In the plane this always stops. In 3D it can loop forever, unless you cut the solid into pieces first.

The problem

The input is a simple polygon QQ, given counterclockwise with integer or rational vertices and no three consecutive vertices collinear. The output is a tree. Each node stands for a polygon RR and holds its convex hull CH(R)\mathrm{CH}(R), and its children are the nodes of the pockets of RR. The tree must satisfy

R=CH(R)−∗⋃children R′R′R = \mathrm{CH}(R) -^* \bigcup_{\text{children } R'} R'

at every node, so that Q=∑nodes v(−1)depth⁡(v)CH(Rv)Q = \sum_{\text{nodes } v} (-1)^{\operatorname{depth}(v)} \mathrm{CH}(R_v) as indicator functions, off the boundaries.

The algorithm

A vertex of RR touches the hull if it lies on the boundary of CH(R)\mathrm{CH}(R), at a hull corner or inside a hull edge. Line L2 finds these. Line L3 takes two touching vertices that come one after the other along RR. If the boundary chain between them has two or more edges, the region between the chain and the segment joining its ends is a pocket, and the segment is its lid. The chain runs inside the hull, and the lid lies on its boundary. Line L5 reverses the chain to make the pocket counterclockwise, and line L6 recurses on it.

  1. ASV(R)
  2. 1H ← CONVEX-HULL(vertices of R)
  3. 2T ← the indices of the vertices of R that lie on the boundary of H, in order along R
  4. node ← (R, H, children ← empty)
  5. for each pair i, j of consecutive indices in T, cyclically, do
  6. 3chain ← R[i], R[i + 1], ..., R[j]
  7. 4if chain has only one edge then continue
  8. 5pocket ← chain reversed, closed by the lid from R[i] to R[j]
  9. 6append ASV(pocket) to the children of node
  10. return node
  11. CONTAINS(node, p)
  12. 7return p is inside node.H and CONTAINS(c, p) is false for every child c

The hull is computed exactly with the monotone chain, removing collinear points. A vertex that lies inside a hull edge counts as touching, which matters for rectilinear parts. A slot cut into the top face of a block has its upper corners on the top edge of the hull, and they split the boundary into the pocket and the flat pieces around it.

Example

Take the block [0,8]×[0,6][0, 8] \times [0, 6] with a stepped slot in its top: a wide upper slot [2,6]×[4,6][2, 6] \times [4, 6] over a narrow lower one [3,5]×[2,4][3, 5] \times [2, 4]. The vertices are

(0,0),(8,0),(8,6),(6,6),(6,4),(5,4),(5,2),(3,2),(3,4),(2,4),(2,6),(0,6).(0,0), (8,0), (8,6), (6,6), (6,4), (5,4), (5,2), (3,2), (3,4), (2,4), (2,6), (0,6).
depth hull sign area
0 the block, (0,0),(8,0),(8,6),(0,6)(0,0), (8,0), (8,6), (0,6) ++ 48
1 the hull of the slot, (2,4),(3,2),(5,2),(6,4),(6,6),(2,6)(2,4), (3,2), (5,2), (6,4), (6,6), (2,6) −- 14
2 the triangle (3,2),(3,4),(2,4)(3,2), (3,4), (2,4) ++ 1
2 the triangle (6,4),(5,4),(5,2)(6,4), (5,4), (5,2) ++ 1

At depth 0, the vertices (6,6)(6,6) and (2,6)(2,6) touch the top edge of the hull. The chain between them runs down through the slot, and it is the one pocket, the whole stepped slot. Its hull is a hexagon that cuts off the two inner corners of the step. Those corners are the two triangles at depth 2, which are convex and end the recursion. The series gives 48−14+1+1=36=48−1248 - 14 + 1 + 1 = 36 = 48 - 12, the area of the part.

This shows how the terms relate to features. The depth 1 term is the envelope of the whole slot. The depth 2 terms add back the two ledges of the step, the material between the narrow lower slot and the hull of the slot. A feature reader groups the terms back into machining features. Here that gives a wide slot and a narrow slot below it.

Correctness

The proof file proves the planar claims, and the 3D example.

  1. Pockets tile the hull. The touching vertices appear in the same cyclic order along RR and along the boundary of the hull, because two disjoint arcs of RR that joined interleaved boundary points would have to cross inside the hull. So the flat pieces of RR and the lids go once around the hull. Adding winding numbers, the hull's is the sum of RR's and the pockets', and each simple counterclockwise polygon has winding number 0 or 1. So every point inside the hull and on no boundary is in exactly one of RR and the pockets.
  2. The expression is exact. By 1, R=CH(R)−∗⋃R = \mathrm{CH}(R) -^* \bigcup pockets at every node. Unfolding the recursion gives the signed sum of hulls, and line L7 decides membership exactly for points on no edge of the tree.
  3. It ends. A pocket's lid is an edge of the pocket's own hull, so the pocket's own pockets lie along strictly shorter pieces of its chain. A pocket has at most n−1n - 1 vertices when its parent has nn, so the depth is at most n−2n - 2.
  4. Convex inputs end in one step. All vertices of a convex polygon touch its hull, so there are no pockets and the tree is a single node, Q=H0Q = H_0. Conversely, a polygon with no pockets equals its hull by 1.
  5. Non-convergence in three dimensions, and the fix. Let HH be the regular tetrahedron A=(0,0,0)A = (0,0,0), B=(1,1,0)B = (1,1,0), C=(1,0,1)C = (1,0,1), D=(0,1,1)D = (0,1,1), and OO its centre. Let P=OABC∪OACDP = OABC \cup OACD. Its deficiency is OABD∪OBCDOABD \cup OBCD. Both contain all four corners of HH, so both have hull HH. The series is H−H+H−⋯H - H + H - \cdots, and the deficiencies alternate between the two forever. Cutting PP by the plane z=xz = x, which contains OO, AA and CC, gives the two convex tetrahedra OABCOABC and OACDOACD, each of which ends in one step. That is the idea of partitioning in ASVP.

The tests check the planar claims with exact arithmetic against oracles that do not use the code. For 250 random rectilinear polygons with up to 22 cells and 4 levels, and 200 random star-shaped polygons with integer vertices, the tree's membership and the signed sum of hulls both agree with the polygon's membership at 25 or 20 rational points each. Those are points on no line through two vertices, over 10,000 in all. The signed sum of hull areas equals the polygon's area exactly, and every pocket has fewer vertices than its parent. All 300 random convex polygons give a single node. A 3D test samples 1,000 exact points in the tetrahedron and checks the cycle and the cut.

Proof: The planar ASV tree is exact and finite, convex inputs end in one step, and the 3D series can cycle until a cut is madefull

We use the notation and the pseudocode of the page. A polygon RR is simple, given counterclockwise as R[0],…,R[s−1]R[0], \dots, R[s-1] with indices modulo ss, has positive area, and has no three consecutive collinear vertices. We write RR also for the closed region it bounds. H=CH(R)H = \mathrm{CH}(R) is a convex polygon whose corners are vertices of RR. TT is the set of indices of vertices on ∂H\partial H (line L2), listed in increasing order. Since HH has at least three corners, ∣T∣≥3|T| \ge 3. For consecutive i,ji, j in TT (cyclically), the chain γij\gamma_{ij} is the boundary path R[i],R[i+1],…,R[j]R[i], R[i+1], \dots, R[j], and the lid λij\lambda_{ij} is the directed segment from R[i]R[i] to R[j]R[j]. For a closed polygonal curve cc and a point pp not on it, wc(p)w_c(p) is the winding number. For a simple closed polygon, wc(p)w_c(p) is ±1\pm 1 inside and 00 outside, with +1+1 for counterclockwise orientation.

The planar tree

Lemma 1 (order). The vertices R[t]R[t], t∈Tt \in T, appear along ∂H\partial H counterclockwise in the same cyclic order as along RR.

Proof. Suppose not. Then there are four of them a,b,c,da, b, c, d, in this cyclic order along ∂H\partial H, that appear along RR in the order a,c,b,da, c, b, d. So ∂R\partial R splits into four arcs between them, and the arc α\alpha from aa to cc and the arc β\beta from bb to dd are disjoint. Both lie in the closed disc HH, with endpoints on its boundary circle in the interleaved order a,b,c,da, b, c, d. Two such paths in a closed disc must meet: α\alpha splits the disc into two parts, and bb and dd lie in different ones. That contradicts disjointness. Since RR is counterclockwise and H⊇RH \supseteq R, the orientations agree. □\square

Lemma 2 (lids and chains). For consecutive i,ji, j in TT: (a) λij\lambda_{ij} lies in one edge of HH, and it is the arc of ∂H\partial H from R[i]R[i] to R[j]R[j] counterclockwise; (b) if γij\gamma_{ij} has at least two edges, then all its points except R[i]R[i] and R[j]R[j] are in int⁡H\operatorname{int} H; (c) if γij\gamma_{ij} has one edge, it equals λij\lambda_{ij}.

Proof. (a) By Lemma 1, no touching vertex lies strictly between R[i]R[i] and R[j]R[j] on the counterclockwise arc of ∂H\partial H. Every corner of HH is a touching vertex, so that arc contains no corner in its interior. It is therefore a straight piece of one hull edge, and it equals the segment λij\lambda_{ij}. (b) The vertices strictly inside the chain are not on ∂H\partial H, so they are in int⁡H\operatorname{int} H. A segment with one endpoint in int⁡H\operatorname{int} H and the other in HH has all its points except possibly the second endpoint in int⁡H\operatorname{int} H, by convexity. Every edge of a chain with two or more edges has an endpoint inside the chain. (c) is the definition. □\square

So for a chain with two or more edges, the closed curve πij\pi_{ij} that goes along λij\lambda_{ij} and then back along γij\gamma_{ij} reversed is simple. The lid lies on ∂H\partial H, and the rest of the curve lies in int⁡H\operatorname{int} H. This is the pocket of lines L3 to L5: the reversed chain R[j],…,R[i]R[j], \dots, R[i], closed by the edge from R[i]R[i] to R[j]R[j]. Its vertices are vertices of RR. Let Σ\Sigma be the union of ∂R\partial R and ∂H\partial H, a finite union of segments.

Lemma 3 (tiling). Every pocket is counterclockwise. For every point p∉Σp \notin \Sigma: if p∈int⁡Hp \in \operatorname{int} H, then pp is in exactly one of int⁡R\operatorname{int} R and the interiors of the pockets; if p∉Hp \notin H, it is in none of them.

Proof. As 1-cycles, ∂R=∑(i,j)γij\partial R = \sum_{(i,j)} \gamma_{ij} over consecutive pairs. By Lemma 2(a) and Lemma 1, ∑(i,j)λij\sum_{(i,j)} \lambda_{ij} is ∂H\partial H, traversed once counterclockwise. Using γ=λ\gamma = \lambda for one-edge chains,

∂H=∂R+∑pockets(λij−γij)=∂R+∑pocketsπij,\partial H = \partial R + \sum_{\text{pockets}} (\lambda_{ij} - \gamma_{ij}) = \partial R + \sum_{\text{pockets}} \pi_{ij},

so w∂H(p)=wR(p)+∑wπij(p)w_{\partial H}(p) = w_R(p) + \sum w_{\pi_{ij}}(p) for p∉Σp \notin \Sigma. Fix a pocket and let mm be the midpoint of its lid. By Lemma 2, the other chains meet ∂H\partial H only at touching vertices, and the other lids are different arcs of ∂H\partial H. So some small disc UU around mm meets no curve other than the line of this lid. On UU minus the lid, wRw_R and the winding numbers of the other pockets are constant, so they equal their value outside HH, which is 00. At a point of UU just inside HH, the identity gives 1=0+wπij(p)1 = 0 + w_{\pi_{ij}}(p). So πij\pi_{ij} has winding number +1+1 inside, and it is counterclockwise. Now every term is 00 or 11. Inside HH they sum to 11, so exactly one is 11. Outside HH they sum to 00, so all are 00. □\square

Theorem 1 (the expression). For every node vv of the tree with region RvR_v and hull HvH_v,

Rv=Hv−∗⋃children cRc,R_v = H_v -^* \bigcup_{\text{children } c} R_c,

and for every point pp on no edge of any region or hull in the subtree of vv,

[p∈Rv]=CONTAINS(v,p)=∑u in the subtree of v(−1)depth⁡(u)−depth⁡(v)[p∈int⁡Hu].[p \in R_v] = \mathrm{CONTAINS}(v, p) = \sum_{u \text{ in the subtree of } v} (-1)^{\operatorname{depth}(u) - \operatorname{depth}(v)} [p \in \operatorname{int} H_u].

Proof. Write RR, HH for RvR_v, HvH_v, and YY for the union of the pockets. By Lemma 3, int⁡H∖Σ\operatorname{int} H \setminus \Sigma is the disjoint union of int⁡R∖Σ\operatorname{int} R \setminus \Sigma and int⁡Y′∖Σ\operatorname{int} Y' \setminus \Sigma, where Y′Y' ranges over the pockets. The set int⁡R∖Σ\operatorname{int} R \setminus \Sigma is open, lies in HH and misses YY, so it lies in int⁡(H∖Y)\operatorname{int}(H \setminus Y). Conversely, a point of int⁡(H∖Y)∖Σ\operatorname{int}(H \setminus Y) \setminus \Sigma lies in int⁡H\operatorname{int} H and in no pocket, so it is in int⁡R\operatorname{int} R. Since Σ\Sigma is closed with empty interior, U∖Σ‾=U‾\overline{U \setminus \Sigma} = \overline{U} for open UU. So H−∗Y=int⁡(H∖Y)‾=int⁡R‾=RH -^* Y = \overline{\operatorname{int}(H \setminus Y)} = \overline{\operatorname{int} R} = R.

For the second claim, use induction on the height of vv. For pp on no edge, p∉Σp \notin \Sigma, so by Lemma 3, p∈Rp \in R iff p∈int⁡Hp \in \operatorname{int} H and pp is in no pocket. By induction, p∈Rcp \in R_c iff CONTAINS(c,p)(c, p), which is line L7. It is also iff the signed sum over the subtree of cc is 11. Since pp is in at most one pocket, [p∈R]=[p∈int⁡H]−∑c[p∈Rc][p \in R] = [p \in \operatorname{int} H] - \sum_c [p \in R_c]. Expanding each [p∈Rc][p \in R_c] by induction gives the signed sum. □\square

All edges of all regions and hulls in the tree join two vertices of the input polygon. So the theorem holds at every point that lies on no line through two input vertices, which is how the tests choose their points.

Theorem 2 (termination). A pocket of a node with ss vertices has at most s−1s - 1 vertices. So the tree has at most n−2n - 2 levels for an input with nn vertices, and ASV returns.

Proof. The pocket of a chain from ii to jj has (j−i mod s)+1(j - i \bmod s) + 1 vertices. At least one index of TT other than ii and jj lies outside the chain, since ∣T∣≥3|T| \ge 3. So j−i mod s≤s−2j - i \bmod s \le s - 2. Every node with children has at least 4 vertices, since a triangle is convex. So along any path from the root, the number of vertices drops by at least one per level, from nn to at least 33. □\square

Theorem 3 (convex inputs end in one step). The tree of RR is a single node if and only if RR is convex, and then the series is R=H0R = H_0.

Proof. If RR is convex, then H=RH = R, so every vertex is on ∂H\partial H and TT is all indices. Every chain has one edge, line L4 skips all of them, and the node has no children. Conversely, if there are no pockets, then by Lemma 3 every point of int⁡H∖Σ\operatorname{int} H \setminus \Sigma is in int⁡R\operatorname{int} R, so R⊇int⁡H∖Σ‾=HR \supseteq \overline{\operatorname{int} H \setminus \Sigma} = H, and R=HR = H is convex. □\square

The series in three dimensions

The plain series takes Q0=QQ_0 = Q and Qk+1=CH(Qk)−∗QkQ_{k+1} = \mathrm{CH}(Q_k) -^* Q_k, and it ends when some QkQ_k is empty. Then Q=CH(Q0)−CH(Q1)+⋯Q = \mathrm{CH}(Q_0) - \mathrm{CH}(Q_1) + \cdots as indicators, almost everywhere.

Convex input. If QQ is convex, then CH(Q)=Q\mathrm{CH}(Q) = Q and Q1=Q−∗Q=int⁡∅‾=∅Q_1 = Q -^* Q = \overline{\operatorname{int} \emptyset} = \emptyset. The series is Q=H0Q = H_0, one step.

A solid on which it cycles. Let A=(0,0,0)A = (0,0,0), B=(1,1,0)B = (1,1,0), C=(1,0,1)C = (1,0,1), D=(0,1,1)D = (0,1,1). All six distances are 2\sqrt 2, so H=conv{A,B,C,D}H = \mathrm{conv}\{A, B, C, D\} is a regular tetrahedron, of volume 1/31/3. Let O=(A+B+C+D)/4=(12,12,12)O = (A + B + C + D)/4 = (\tfrac12, \tfrac12, \tfrac12), its centre. For each face FF of HH let KF=conv({O}∪F)K_F = \mathrm{conv}(\{O\} \cup F). The four cones KABC,KABD,KACD,KBCDK_{ABC}, K_{ABD}, K_{ACD}, K_{BCD} tile HH. Each x∈H∖{O}x \in H \setminus \{O\} lies on the segment from OO to the point where the ray from OO through xx leaves HH, which lies in some face. Two cones meet only in a common triangle from OO, since their faces lie in different sectors from OO. Each cone has volume 1/121/12.

Let P=KABC∪KACDP = K_{ABC} \cup K_{ACD}. The two tetrahedra share the whole triangle OACOAC, so PP is a solid with five vertices and volume 1/61/6. It is not convex, since its volume is less than that of its hull. By the tiling,

Q1=H−∗P=KABD∪KBCD.Q_1 = H -^* P = K_{ABD} \cup K_{BCD}.

Now PP contains A,B,CA, B, C (in KABCK_{ABC}) and DD (in KACDK_{ACD}), and Q1Q_1 contains A,B,DA, B, D (in KABDK_{ABD}) and CC (in KBCDK_{BCD}). Both lie in HH. So CH(P)=CH(Q1)=H\mathrm{CH}(P) = \mathrm{CH}(Q_1) = H, and again by the tiling, Q2=H−∗Q1=PQ_2 = H -^* Q_1 = P. By induction Q2k=PQ_{2k} = P and Q2k+1=Q1Q_{2k+1} = Q_1 for all kk. Neither is empty, so the series H−H+H−⋯H - H + H - \cdots never ends, and no finite truncation of it equals PP as a sum of hulls.

The cut. Consider f(x,y,z)=z−xf(x, y, z) = z - x. It is 00 at OO, AA and CC, −1-1 at BB and +1+1 at DD. So KABC⊆{f≤0}K_{ABC} \subseteq \{f \le 0\} and KACD⊆{f≥0}K_{ACD} \subseteq \{f \ge 0\}, and they meet in the triangle OACOAC in the plane f=0f = 0. Hence

P∩∗{f≤0}=KABC,P∩∗{f≥0}=KACD,P=KABC∪∗KACD.P \cap^* \{f \le 0\} = K_{ABC}, \qquad P \cap^* \{f \ge 0\} = K_{ACD}, \qquad P = K_{ABC} \cup^* K_{ACD}.

Each piece is convex, so its series ends in one step. The edges OAOA and OCOC are concave edges of PP. Around OAOA, the three cones over the faces at AA meet, each with dihedral angle 2π/32\pi/3 by symmetry, and PP holds two of them, an angle of 4π/34\pi/3. The same holds at OCOC. Cutting along the plane of the triangle OACOAC, through these concave edges, is what partitioning does in ASVP. It makes the pieces' hulls smaller than the hull of the whole. This example is ours, built for this page. Kim and Wilde's general remedy and its proof of convergence are in their paper and are not reproduced here.

What is not claimed

The planar theorems are for simple polygons without holes. The 3D part gives one solid on which the plain series cycles, and shows that one cut ends it. It does not prove that ASVP converges in general, and it does not say which cuts Kim and Wilde's rule makes on other solids. The conversion of terms into features is not covered.

Complexity

A node for a polygon with ss vertices costs O(slog⁡s)O(s \log s) for the hull. The touching vertices are the points left on the boundary when the monotone chain is run again keeping collinear points, which also costs O(slog⁡s)O(s \log s). The pockets of one node have disjoint chains, so all nodes at one depth have O(n)O(n) vertices in total, and there are at most n−2n - 2 depths. That gives O(n2log⁡n)O(n^2 \log n) time and O(n2)O(n^2) space in the worst case. The bound on depth is loose, but deep nesting, as in a spiral, does need many levels. Typical parts have depth 2 to 4, and then the cost is O(nlog⁡n)O(n \log n). The code uses a simpler touching test, O(sh)O(s h) per node for hh hull edges.

In 3D the hulls cost O(slog⁡s)O(s \log s) each with a 3D hull algorithm, but the difference operations between a hull and its region are full Boolean operations on polyhedra, and with non-convergence the plain series has no bound at all.

Properties

  • Exact. All operations are hulls and orientation tests on the input coordinates, so integer or rational input gives an exact tree.
  • Unique. The tree depends only on the polygon, not on a choice. This is the opposite of volume decomposition, where several covers can give the same part.
  • Outside in. The terms are ordered from the outer envelope to the deepest detail. That matches how features nest, and it suits process planning from the stock inward.
  • Convex terms. Every term is a convex polygon or polyhedron, the easiest kind of solid to machine, measure or test points against.

Variants and improvements

  • One hull per deficiency, or one per piece. The step can take a single hull of the whole deficiency, or one hull per connected piece of it. This page takes one per pocket, which gives a tree rather than a single series, and its proofs are for that form. With a single hull, separate dents are merged into one big convex term, which is worse for reading features.
  • ASVP. Kim and Wilde showed that non-convergence has a local cause. Their remedy, remedial partitioning, cuts the solid at concave edges where the plain step would not make progress, and the pieces are decomposed in turn. They proved that this alternating sum of volumes with partitioning always ends.
  • Form feature decomposition. Kim combined the terms of the ASVP into volumetric form features, and these can be converted further into a negative feature decomposition for machining. Later work used them for machining features and for ordering machining steps.
  • Data structures. Tang and Woo gave the data structure and the difference operation for computing the series, and their second paper studied non-convergence and a remedy.
  • Orthogonal polyhedra. For solids with all faces axis-parallel, other exact representations can be converted to an ASV directly.

When to use it

Use ASV when a part should be described from the outside in, as a stock-like convex envelope with nested depressions and protrusions, and when a unique answer is wanted. It works best for polyhedral parts with moderate nesting. In 3D, use ASVP rather than the plain series, since non-convergence is a real case and not a rare corner. If the goal is a set of machining volumes accessible from given directions, volume decomposition or hint-based recognition fit more directly. ASV terms are convex but not necessarily machinable shapes, and they need a further grouping step.

Pitfalls

  • Vertices inside hull edges. If only hull corners count as touching, a vertex in the middle of a hull edge is treated as inside the hull. The pocket then contains a flat piece of the boundary of RR, and it can have zero area. Count every vertex on the hull boundary.
  • Floating-point hulls. A hull built with rounding can drop a vertex that is just on the boundary, or keep one just inside, which changes the tree. Use exact arithmetic or snap carefully.
  • Assuming convergence in 3D. The plain series can cycle, as the tetrahedron example shows. An implementation must detect a deficiency whose hull equals its parent's hull and switch to partitioning.
  • Terms are not features. A single hull term can mix several features, as the slot hull above mixes the wide and narrow slots. Features come only after the terms are grouped.
  • Curved faces. The hull of a solid with curved faces is hard to compute and represent exactly. That is why the early methods were limited to polyhedra, and later work added special handling for blends and cylinders.

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.

alternating_sum_of_volumes.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/alternating-sum-of-volumes/. The authors are listed in prov/7SFHP7.jsonl.

"""Alternating sum of volumes (ASV) of a simple polygon in the plane.

The ASV writes a region Q as its convex hull minus the regions between Q
and the hull, its pockets, and treats each pocket the same way:

    Q = CH(Q) -* (ASV(pocket_1) u ... u ASV(pocket_m)),

so that Q = H_0 - H_1 + H_2 - ... as a signed sum of convex hulls, one sign
per depth of the tree. A pocket is the region between a chain of the
boundary of Q and the hull: the chain runs between two consecutive vertices
of Q that lie on the boundary of the hull, and it has at least two edges.
The segment joining its ends, the lid, lies on the boundary of the hull.

Precondition: the polygon is simple, counterclockwise, with integer or
Fraction coordinates, and no three consecutive vertices are collinear.
Cost: a node with s vertices and h hull edges costs O(s log s) for the hull
and O(s h) for the simple touching test used here. The tree has at most
n - 2 levels, and the nodes of one level have O(n) vertices in total, so
the whole tree takes O(n^3) time with this test in the worst case, and
O(n^2 log n) with an O(s log s) touching test. Space is O(n^2). All
arithmetic is exact.
"""

from __future__ import annotations

from dataclasses import dataclass, field
from fractions import Fraction

Point = tuple


def cross(o: Point, a: Point, b: Point):
    return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])


def convex_hull(points: list[Point]) -> list[Point]:
    """Andrew's monotone chain, counterclockwise, with no collinear vertices."""
    pts = sorted(set(points))
    if len(pts) <= 2:
        return pts
    lower: list[Point] = []
    for p in pts:
        while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0:
            lower.pop()
        lower.append(p)
    upper: list[Point] = []
    for p in reversed(pts):
        while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0:
            upper.pop()
        upper.append(p)
    return lower[:-1] + upper[:-1]


def on_segment(a: Point, b: Point, p: Point) -> bool:
    return (cross(a, b, p) == 0 and min(a[0], b[0]) <= p[0] <= max(a[0], b[0])
            and min(a[1], b[1]) <= p[1] <= max(a[1], b[1]))


def on_hull_boundary(hull: list[Point], p: Point) -> bool:
    h = len(hull)
    return any(on_segment(hull[k], hull[(k + 1) % h], p) for k in range(h))


def strictly_inside_convex(hull: list[Point], x, y) -> bool:
    h = len(hull)
    return h >= 3 and all(cross(hull[k], hull[(k + 1) % h], (x, y)) > 0 for k in range(h))


def area2(poly: list[Point]):
    """Twice the signed area."""
    n = len(poly)
    return sum(poly[k][0] * poly[(k + 1) % n][1] - poly[(k + 1) % n][0] * poly[k][1] for k in range(n))


@dataclass
class Node:
    region: list[Point]                 # the polygon this node stands for
    hull: list[Point]                   # its convex hull
    children: list["Node"] = field(default_factory=list)   # its pockets


def asv(poly: list[Point]) -> Node:
    """The ASV tree of a simple counterclockwise polygon."""
    n = len(poly)
    hull = convex_hull(poly)  # @line L1
    touch = [k for k in range(n) if on_hull_boundary(hull, poly[k])]  # @line L2
    node = Node(poly, hull)
    for t in range(len(touch)):
        i, j = touch[t], touch[(t + 1) % len(touch)]  # @line L3
        steps = (j - i) % n or n
        if steps < 2:
            continue  # @line L4
        chain = [poly[(i + s) % n] for s in range(steps + 1)]
        pocket = chain[::-1]  # @line L5
        node.children.append(asv(pocket))  # @line L6
    return node


def contains(node: Node, x, y) -> bool:
    """Membership in CH -* (union of the children), for a point on no edge of
    any hull or region in the tree."""
    if not strictly_inside_convex(node.hull, x, y):
        return False
    return not any(contains(c, x, y) for c in node.children)  # @line L7


def signed_hulls(node: Node, depth: int = 0) -> list[tuple[int, list[Point]]]:
    """The series as (sign, hull) pairs: Q = sum of sign * CH."""
    out = [((-1) ** depth, node.hull)]
    for c in node.children:
        out += signed_hulls(c, depth + 1)
    return out


def depth(node: Node) -> int:
    return 1 + max((depth(c) for c in node.children), default=0)


def series_value(node: Node, x, y) -> int:
    """The signed sum of the indicators of the hulls at (x, y)."""
    return sum(s for s, h in signed_hulls(node) if strictly_inside_convex(h, x, y))


def series_area(node: Node) -> Fraction:
    return sum((s * Fraction(area2(h), 2) for s, h in signed_hulls(node)), Fraction(0))
test_alternating_sum_of_volumes.py 278 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/alternating-sum-of-volumes/. The authors are listed in prov/7SFHP7.jsonl.

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

from alternating_sum_of_volumes import asv, contains, depth, series_area, series_value, signed_hulls


# ---------- random simple polygons and an independent oracle ----------

def random_orthogonal(rng, size=7):
    """A hole-free polyomino with no pinch points, traced into a
    counterclockwise rectilinear polygon on random integer coordinates."""
    while True:
        target = rng.randint(4, 22)
        cells = {(rng.randrange(size), rng.randrange(size))}
        while len(cells) < target:
            i, j = rng.choice(sorted(cells))
            di, dj = rng.choice([(1, 0), (-1, 0), (0, 1), (0, -1)])
            if 0 <= i + di < size and 0 <= j + dj < size:
                cells.add((i + di, j + dj))
        if ok_polyomino(cells, size):
            break
    W = max(i for i, _ in cells) + 1
    H = max(j for _, j in cells) + 1
    X = sorted(rng.sample(range(-20, 60), W + 1))
    Y = sorted(rng.sample(range(-20, 60), H + 1))
    poly = [(X[i], Y[j]) for i, j in trace(cells)]

    def oracle(x, y):
        i, j = bisect_left(X, x) - 1, bisect_left(Y, y) - 1
        return (i, j) in cells
    return poly, oracle


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]
    return [b for k, b in enumerate(cyc)
            if orient(cyc[k - 1], b, cyc[(k + 1) % len(cyc)]) != 0]


def orient(a, b, c):
    return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])


def random_star(rng):
    """A star-shaped simple polygon: integer points at distinct angles around
    the origin, sorted by angle, with every angular gap below a half turn."""
    while True:
        k = rng.randint(4, 14)
        pts = set()
        while len(pts) < k:
            p = (rng.randint(-30, 30), rng.randint(-30, 30))
            if p != (0, 0):
                pts.add(p)
        pts = sorted(pts, key=angle_key)
        ok = all(orient((0, 0), pts[t], pts[(t + 1) % k]) > 0 for t in range(k))
        ok = ok and all(orient(pts[t - 1], pts[t], pts[(t + 1) % k]) != 0 for t in range(k))
        if ok:
            return pts, lambda x, y, P=pts: crossing_number(P, x, y)


def angle_key(p):
    # exact angular order: half plane first, then by cross product
    half = 0 if (p[1] > 0 or (p[1] == 0 and p[0] > 0)) else 1
    return (half, Fraction(-p[0], abs(p[0]) + abs(p[1])) if half == 0 else Fraction(p[0], abs(p[0]) + abs(p[1])))


def crossing_number(poly, x, y):
    inside = False
    for k in range(len(poly)):
        (x0, y0), (x1, y1) = poly[k], poly[(k + 1) % len(poly)]
        if (y0 > y) != (y1 > y) and x0 + Fraction(x1 - x0) * (y - y0) / (y1 - y0) > x:
            inside = not inside
    return inside


def generic_points(rng, poly, count):
    """Rational points on no line through two vertices of the polygon. Every
    edge of every hull and region in the tree joins two such vertices."""
    xs, ys = [p[0] for p in poly], [p[1] for p in poly]
    # the line through a and b, scaled by 97: u * X + v * Y = w at X = 97 x, Y = 97 y
    lines = [(b[1] - a[1], a[0] - b[0], 97 * ((b[1] - a[1]) * a[0] + (a[0] - b[0]) * a[1]))
             for a, b in combinations(poly, 2)]
    out = []
    while len(out) < count:
        X = rng.randint(97 * min(xs) - 50, 97 * max(xs) + 50)
        Y = rng.randint(97 * min(ys) - 50, 97 * max(ys) + 50)
        if all(u * X + v * Y != w for u, v, w in lines):
            out.append((Fraction(X, 97), Fraction(Y, 97)))
    return out


def twice_area(poly):
    return sum(poly[k][0] * poly[(k + 1) % len(poly)][1] - poly[(k + 1) % len(poly)][0] * poly[k][1]
               for k in range(len(poly)))


# ---------- tests ----------

class TestHandCases(unittest.TestCase):
    def test_convex_input_ends_in_one_step(self):
        sq = [(0, 0), (4, 0), (4, 3), (0, 3)]
        t = asv(sq)
        self.assertEqual(t.children, [])
        self.assertEqual(t.hull, sq)

    def test_l_shape(self):
        L = [(0, 0), (4, 0), (4, 2), (2, 2), (2, 4), (0, 4)]
        t = asv(L)
        self.assertEqual(t.hull, [(0, 0), (4, 0), (4, 2), (2, 4), (0, 4)])
        self.assertEqual([c.region for c in t.children], [[(2, 4), (2, 2), (4, 2)]])
        self.assertEqual(depth(t), 2)
        self.assertEqual(series_area(t), 12)

    def test_stepped_slot_has_three_levels(self):
        P = [(0, 0), (8, 0), (8, 6), (6, 6), (6, 4), (5, 4), (5, 2), (3, 2),
             (3, 4), (2, 4), (2, 6), (0, 6)]
        t = asv(P)
        self.assertEqual(t.hull, [(0, 0), (8, 0), (8, 6), (0, 6)])
        (slot,) = t.children
        self.assertEqual(slot.hull, [(2, 4), (3, 2), (5, 2), (6, 4), (6, 6), (2, 6)])
        self.assertEqual(sorted(c.region for c in slot.children),
                         [[(3, 2), (3, 4), (2, 4)], [(6, 4), (5, 4), (5, 2)]])
        self.assertEqual([(s, len(h)) for s, h in signed_hulls(t)], [(1, 4), (-1, 6), (1, 3), (1, 3)])
        self.assertEqual(series_area(t), 48 - 12)

    def test_random_convex_inputs_end_in_one_step(self):
        rng = random.Random(21)
        from alternating_sum_of_volumes import convex_hull
        for _ in range(300):
            pts = [(rng.randint(-50, 50), rng.randint(-50, 50)) for _ in range(rng.randint(3, 30))]
            h = convex_hull(pts)
            if len(h) < 3:
                continue
            t = asv(h)
            self.assertEqual(t.children, [])
            self.assertEqual(t.hull, convex_hull(h))


class TestAgainstOracle(unittest.TestCase):
    def check(self, poly, oracle, rng, npts):
        t = asv(poly)
        self.assertEqual(series_area(t), Fraction(twice_area(poly), 2))
        # each pocket has fewer vertices than its parent, which bounds the depth
        stack = [t]
        while stack:
            node = stack.pop()
            for c in node.children:
                self.assertLess(len(c.region), len(node.region))
                stack.append(c)
        n = 0
        for x, y in generic_points(rng, poly, npts):
            inside = oracle(x, y)
            self.assertEqual(contains(t, x, y), inside)
            self.assertEqual(series_value(t, x, y), int(inside))
            n += 1
        return n, depth(t)

    def test_orthogonal_polygons(self):
        rng = random.Random(22)
        total, deepest = 0, 0
        for _ in range(250):
            poly, oracle = random_orthogonal(rng)
            n, d = self.check(poly, oracle, rng, 25)
            total += n
            deepest = max(deepest, d)
        self.assertGreater(total, 500)
        self.assertGreaterEqual(deepest, 3)

    def test_star_shaped_polygons(self):
        rng = random.Random(23)
        total = 0
        for _ in range(200):
            poly, oracle = random_star(rng)
            n, _ = self.check(poly, oracle, rng, 20)
            total += n
        self.assertGreater(total, 500)


class TestNonConvergenceIn3D(unittest.TestCase):
    """The 3D example of the page: two of the four cones from the centre of a
    regular tetrahedron. The solid and its deficiency both have all four
    corners, so the hull never shrinks, and cutting along z = x fixes it."""

    # A = (0,0,0), B = (1,1,0), C = (1,0,1), D = (0,1,1), O = (1/2,1/2,1/2),
    # all scaled by S = 202, so that the sample points p / S are exact integers
    S = 202
    A, B, C, D = (0, 0, 0), (S, S, 0), (S, 0, S), (0, S, S)
    O = (S // 2,) * 3

    @staticmethod
    def det3(u, v, w):
        return (u[0] * (v[1] * w[2] - v[2] * w[1]) - u[1] * (v[0] * w[2] - v[2] * w[0])
                + u[2] * (v[0] * w[1] - v[1] * w[0]))

    def in_tet(self, p, a, b, c, d):
        sub = lambda u, v: tuple(x - y for x, y in zip(u, v))
        s = self.det3(sub(b, a), sub(c, a), sub(d, a))
        signs = [self.det3(sub(b, p), sub(c, p), sub(d, p)),
                 self.det3(sub(p, a), sub(c, a), sub(d, a)),
                 self.det3(sub(b, a), sub(p, a), sub(d, a)),
                 self.det3(sub(b, a), sub(c, a), sub(p, a))]
        return all(x * s > 0 for x in signs)

    def test_cycle_and_partition(self):
        A, B, C, D, O = self.A, self.B, self.C, self.D, self.O
        H = lambda p: self.in_tet(p, A, B, C, D)
        P = lambda p: self.in_tet(p, O, A, B, C) or self.in_tet(p, O, A, C, D)
        deficiency = lambda p: self.in_tet(p, O, A, B, D) or self.in_tet(p, O, B, C, D)
        # both P and its deficiency contain all four corners, so both hulls are H
        for corner in (A, B, C, D):
            self.assertTrue(corner in (O, A, B, C) or corner in (O, A, C, D))
            self.assertTrue(corner in (O, A, B, D) or corner in (O, B, C, D))
        rng = random.Random(24)
        checked = 0
        while checked < 1000:
            p = tuple(rng.randint(-20, self.S + 20) for _ in range(3))
            if p[2] == p[0]:
                continue
            cones = [self.in_tet(p, O, *f) for f in ((A, B, C), (A, B, D), (A, C, D), (B, C, D))]
            if not H(p):
                self.assertEqual(sum(cones), 0)
                continue
            if sum(cones) != 1:          # on a shared face of two cones
                continue
            checked += 1
            # ASV step 1: H minus P is the deficiency, step 2: H minus that is P again
            self.assertEqual(H(p) and not P(p), deficiency(p))
            self.assertEqual(H(p) and not deficiency(p), P(p))
            # ASVP: the plane z = x through O, A and C splits P into two tetrahedra
            if p[2] < p[0]:
                self.assertEqual(P(p), self.in_tet(p, O, A, B, C))
            else:
                self.assertEqual(P(p), self.in_tet(p, O, A, C, D))
        # volumes: each cone is a quarter of the tetrahedron, which has volume 1/3
        vol = lambda a, b, c, d: abs(self.det3(*[tuple(x - y for x, y in zip(v, a)) for v in (b, c, d)])) * Fraction(1, 6 * self.S ** 3)
        self.assertEqual(vol(A, B, C, D), Fraction(1, 3))
        self.assertEqual(vol(O, A, B, C) + vol(O, A, C, D), Fraction(1, 6))
        self.assertEqual(vol(O, A, B, D) + vol(O, B, C, D), Fraction(1, 6))


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

History

Woo presented the alternating sum of volumes at an MIT conference on CAD/CAM in 1982, as a way to extract features from a solid by convex hulls and differences. Tang and Woo studied its data structures and its non-convergence in two papers in 1991. Kim, in his Stanford thesis and in two papers with Wilde in 1992, located the local cause of non-convergence and introduced ASVP, which adds partitioning and always converges. In the same year Kim converted the ASVP into a form feature decomposition, and with coauthors went on to machining features, curved faces and incremental updates during the 1990s.

References

  1. Tony C. Woo, Feature extraction by volume decomposition, Proceedings of the Conference on CAD/CAM Technology in Mechanical Engineering, MIT, Cambridge, Massachusetts, 1982, the alternating sum of convex hulls and the reading of features from its terms (page numbers differ between citing sources and were not checked)
  2. Kai Tang and Tony C. Woo, Algorithmic aspects of alternating sum of volumes, part 1, data structure and difference operation, Computer-Aided Design 23(5), 357 to 366, 1991, the representation of the ASV terms and the difference operation between a hull and its region
  3. Kai Tang and Tony C. Woo, Algorithmic aspects of alternating sum of volumes, part 2, nonconvergence and its remedy, Computer-Aided Design 23(6), 435 to 443, 1991, why the series need not end in three dimensions, and a remedy
  4. Yong Se Kim and D. J. Wilde, A convex decomposition using convex hulls and local cause of its non-convergence, Journal of Mechanical Design 114(3), 459 to 467, 1992, the convex decomposition by convex hulls and set differences, and the local cause of its non-convergence
  5. Yong Se Kim and D. J. Wilde, A convergent convex decomposition of polyhedral objects, Journal of Mechanical Design 114(3), 468 to 476, 1992, ASVP, the alternating sum of volumes with partitioning, which cuts at concave edges where needed, and its proof of convergence
  6. Yong Se Kim, Recognition of form features using convex decomposition, Computer-Aided Design 24(9), 461 to 476, 1992, the conversion of the ASVP decomposition into a form feature decomposition by combining its terms

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