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.
- Solves
- Feature recognition
- Time
- O(n^2 log n) worst
- Space
- O(n^2) extra
- Where
- n = the number of vertices of the polygon
- Model
- Word RAM
- Properties
- deterministicexactrecursive
- Evidence
- Proof sketchCode in 1 languages
- 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 of the solid . What the hull adds is the deficiency . Take its hull , the deficiency of that, and so on. Then
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 , given counterclockwise with integer or rational vertices and no three consecutive vertices collinear. The output is a tree. Each node stands for a polygon and holds its convex hull , and its children are the nodes of the pockets of . The tree must satisfy
at every node, so that as indicator functions, off the boundaries.
The algorithm
A vertex of touches the hull if it lies on the boundary of , 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 . 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.
ASV(R)- 1
H ← CONVEX-HULL(vertices of R) - 2
T ← the indices of the vertices of R that lie on the boundary of H, in order along R node ← (R, H, children ← empty)for each pair i, j of consecutive indices in T, cyclically, do- 3
chain ← R[i], R[i + 1], ..., R[j] - 4
if chain has only one edge then continue - 5
pocket ← chain reversed, closed by the lid from R[i] to R[j] - 6
append ASV(pocket) to the children of node return nodeCONTAINS(node, p)- 7
return 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 with a stepped slot in its top: a wide upper slot over a narrow lower one . The vertices are
| depth | hull | sign | area |
|---|---|---|---|
| 0 | the block, | 48 | |
| 1 | the hull of the slot, | 14 | |
| 2 | the triangle | 1 | |
| 2 | the triangle | 1 |
At depth 0, the vertices and 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 , 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.
- Pockets tile the hull. The touching vertices appear in the same cyclic order along and along the boundary of the hull, because two disjoint arcs of that joined interleaved boundary points would have to cross inside the hull. So the flat pieces of and the lids go once around the hull. Adding winding numbers, the hull's is the sum of '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 and the pockets.
- The expression is exact. By 1, 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.
- 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 vertices when its parent has , so the depth is at most .
- 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, . Conversely, a polygon with no pockets equals its hull by 1.
- Non-convergence in three dimensions, and the fix. Let be the regular tetrahedron , , , , and its centre. Let . Its deficiency is . Both contain all four corners of , so both have hull . The series is , and the deficiencies alternate between the two forever. Cutting by the plane , which contains , and , gives the two convex tetrahedra and , 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 is simple, given counterclockwise as with indices modulo , has positive area, and has no three consecutive collinear vertices. We write also for the closed region it bounds. is a convex polygon whose corners are vertices of . is the set of indices of vertices on (line L2), listed in increasing order. Since has at least three corners, . For consecutive in (cyclically), the chain is the boundary path , and the lid is the directed segment from to . For a closed polygonal curve and a point not on it, is the winding number. For a simple closed polygon, is inside and outside, with for counterclockwise orientation.
The planar tree
Lemma 1 (order). The vertices , , appear along counterclockwise in the same cyclic order as along .
Proof. Suppose not. Then there are four of them , in this cyclic order along , that appear along in the order . So splits into four arcs between them, and the arc from to and the arc from to are disjoint. Both lie in the closed disc , with endpoints on its boundary circle in the interleaved order . Two such paths in a closed disc must meet: splits the disc into two parts, and and lie in different ones. That contradicts disjointness. Since is counterclockwise and , the orientations agree.
Lemma 2 (lids and chains). For consecutive in : (a) lies in one edge of , and it is the arc of from to counterclockwise; (b) if has at least two edges, then all its points except and are in ; (c) if has one edge, it equals .
Proof. (a) By Lemma 1, no touching vertex lies strictly between and on the counterclockwise arc of . Every corner of 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 . (b) The vertices strictly inside the chain are not on , so they are in . A segment with one endpoint in and the other in has all its points except possibly the second endpoint in , by convexity. Every edge of a chain with two or more edges has an endpoint inside the chain. (c) is the definition.
So for a chain with two or more edges, the closed curve that goes along and then back along reversed is simple. The lid lies on , and the rest of the curve lies in . This is the pocket of lines L3 to L5: the reversed chain , closed by the edge from to . Its vertices are vertices of . Let be the union of and , a finite union of segments.
Lemma 3 (tiling). Every pocket is counterclockwise. For every point : if , then is in exactly one of and the interiors of the pockets; if , it is in none of them.
Proof. As 1-cycles, over consecutive pairs. By Lemma 2(a) and Lemma 1, is , traversed once counterclockwise. Using for one-edge chains,
so for . Fix a pocket and let be the midpoint of its lid. By Lemma 2, the other chains meet only at touching vertices, and the other lids are different arcs of . So some small disc around meets no curve other than the line of this lid. On minus the lid, and the winding numbers of the other pockets are constant, so they equal their value outside , which is . At a point of just inside , the identity gives . So has winding number inside, and it is counterclockwise. Now every term is or . Inside they sum to , so exactly one is . Outside they sum to , so all are .
Theorem 1 (the expression). For every node of the tree with region and hull ,
and for every point on no edge of any region or hull in the subtree of ,
Proof. Write , for , , and for the union of the pockets. By Lemma 3, is the disjoint union of and , where ranges over the pockets. The set is open, lies in and misses , so it lies in . Conversely, a point of lies in and in no pocket, so it is in . Since is closed with empty interior, for open . So .
For the second claim, use induction on the height of . For on no edge, , so by Lemma 3, iff and is in no pocket. By induction, iff CONTAINS, which is line L7. It is also iff the signed sum over the subtree of is . Since is in at most one pocket, . Expanding each by induction gives the signed sum.
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 vertices has at most vertices. So the tree has at most levels for an input with vertices, and ASV returns.
Proof. The pocket of a chain from to has vertices. At least one index of other than and lies outside the chain, since . So . 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 to at least .
Theorem 3 (convex inputs end in one step). The tree of is a single node if and only if is convex, and then the series is .
Proof. If is convex, then , so every vertex is on and 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 is in , so , and is convex.
The series in three dimensions
The plain series takes and , and it ends when some is empty. Then as indicators, almost everywhere.
Convex input. If is convex, then and . The series is , one step.
A solid on which it cycles. Let , , , . All six distances are , so is a regular tetrahedron, of volume . Let , its centre. For each face of let . The four cones tile . Each lies on the segment from to the point where the ray from through leaves , which lies in some face. Two cones meet only in a common triangle from , since their faces lie in different sectors from . Each cone has volume .
Let . The two tetrahedra share the whole triangle , so is a solid with five vertices and volume . It is not convex, since its volume is less than that of its hull. By the tiling,
Now contains (in ) and (in ), and contains (in ) and (in ). Both lie in . So , and again by the tiling, . By induction and for all . Neither is empty, so the series never ends, and no finite truncation of it equals as a sum of hulls.
The cut. Consider . It is at , and , at and at . So and , and they meet in the triangle in the plane . Hence
Each piece is convex, so its series ends in one step. The edges and are concave edges of . Around , the three cones over the faces at meet, each with dihedral angle by symmetry, and holds two of them, an angle of . The same holds at . Cutting along the plane of the triangle , 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 vertices costs 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 . The pockets of one node have disjoint chains, so all nodes at one depth have vertices in total, and there are at most depths. That gives time and 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 . The code uses a simpler touching test, per node for hull edges.
In 3D the hulls cost 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 , 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.
# 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
- 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)
- 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
- 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
- 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
- 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
- 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.
| 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 7SFHP7 Edit this page History Report an error Markdown