Algorithmadvanced
Voronoi pocket machining
Also called Held pocket machining.
Held's method that computes the Voronoi diagram of the pocket boundary and reads all offset curves and their topology changes from it for contour-parallel paths.
- Solves
- Pocket machining
- Time
- O(n^2 + K n log n) worst
- Space
- O(n) extra
- Where
- K = number of loops; n = number of edges of the convex pocket
- Model
- Real RAM
- Properties
- deterministicexactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Martin Held, 1991
Voronoi pocket machining builds a contour-parallel toolpath for a pocket from the Voronoi diagram of its boundary. The part of the diagram inside the pocket is the medial axis. Each point of it carries its clearance, the distance to the boundary, and the offset curve at distance is the set of points of the pocket at clearance exactly , so all offsets come from one diagram. Held (1991) made this the core of a pocketing method for areas bounded by segments and circular arcs, with islands. The diagram also shows where an offset splits into parts, and it gives safe links between loops along its arcs. This is a manufacturing method of mechanical CAD, not an EDA router. The code handles convex polygons only, where the medial axis has straight arcs and an exact wavefront builds it.
In plain words
Pour water around the inside of a pocket wall and let it flow inward at the same speed everywhere. The front of the water at each moment has the shape of an offset loop, the loop that a tool center would follow at that distance from the wall.
Mark the places where two fronts from different parts of the wall meet. These marks form a thin tree, the skeleton of the pocket. Each point of the skeleton knows when the water reached it, which is its distance to the wall.
Once the skeleton is known, any loop is found by walking along the skeleton and picking the points with the right distance. The skeleton also shows where a loop breaks into two, and it gives a path from one loop to the next that stays far from the wall.
The problem
The input is a pocket , a tool radius and a step-over . The output is the set of offset loops at distances , and the links between them, as in contour-parallel toolpath, which also proves that the loops cover what the tool can reach when .
The depth of a point is its distance to the boundary of . The medial axis is the closure of the set of points of that have at least two nearest points on the boundary. For a convex polygon with unit outward normals , the depth of is with , and is the closure of the set of points where at least two indices reach the minimum. The offset at distance is .
In a convex polygon, is a tree with straight arcs. Each arc is a piece of the bisector of two edges, and is affine along it. In a pocket with reflex vertices or circular arcs, the Voronoi diagram also has parabolic and other conic arcs, and the offsets have circular arcs around the reflex vertices.
The algorithm
The medial axis of a convex polygon is the track of a wavefront: the offset , whose edges move inward at unit speed as grows. A vertex of is the meeting point of two moved edges, and it moves along their bisector. An edge between neighbours and vanishes at the time when the three moved lines for meet in one point. This is a linear system in , solved by Cramer's rule with exact rationals.
MEDIAL-AXIS(P)- 1
F ← the edges of P in order; start one arc at each vertex, with clearance 0 - 2
while F has more than 3 edges do - 3
for each edge e of F with neighbours p and q: t_e ← time when the lines of p, e, q meet - 4
take e with the smallest t_e, and let N be the meeting point - 5
end the arcs (p, e) and (e, q) at N, with clearance t_e - 6
start the arc (p, q) at N, with clearance t_e - 7
remove e from F - 8
end the three open arcs at the meeting point of the last three lines, and return the arcs VORONOI-POCKET(P, r, s)- 9
A ← MEDIAL-AXIS(P), δmax ← clearance of the deepest node OFFSET(A, d):- 10
collect the point of clearance d on each arc whose clearance range holds d - 11
return the convex hull of the collected points - 12
for d ← r, r + s, r + 2s, ... while d ≤ δmax: append the loop OFFSET(A, d) - 13
if d + s ≤ δmax then link the loop to the next one along the spine
The spine is the chain of arcs from one polygon vertex to the deepest node. The clearance does not decrease along it, so the link between the loops at and is the part of the spine between these two clearances, and the tool stays at clearance at least during the link. Each loop starts where the spine meets it.
In a convex pocket the points of line L10 are in convex position, so line L11 only puts them in order. In a general pocket, line L10 returns one or more closed curves, and Held reads their order from the tree structure of the diagram.
Example
Take the pentagon with vertices , , , , . Its edges have lengths 20, 9, 20, 17 and 10, and the outward unit normals are , , , and .
| step | edge that vanishes | node | clearance |
|---|---|---|---|
| L3 to L7 | the right edge | ||
| L3 to L7 | the left edge | ||
| L8 | the last three edges meet |
The medial axis has arcs: five from the vertices and two between the nodes. With and , the loops are at . The first three are pentagons, for example , , , , at . The loop at is the triangle , , , because both vertical edges have vanished by then. The spine from vertex gives the links , and . The last one bends at the node where the right edge vanished. The deepest node has clearance 8.75, so no loop fits at .
Correctness
Each wavefront vertex between edges and at time satisfies and lies in , so it has depth and two nearest edges: it is on the medial axis. Conversely, a point of the medial axis with depth lies on two different moved lines that support the convex set , so it is a vertex of , and thus on the track of a wavefront vertex. Each edge length of the wavefront is an affine function of , so the edge that vanishes first is the one with the smallest meeting time of line L3. For OFFSET, every point found by line L10 has depth , so it lies in , and every vertex of is a point of the medial axis with clearance , so it is found. The convex hull of a subset of a convex polygon that holds all its vertices is the polygon.
The proof file gives these steps in full for the generic case, where no two events happen at the same time and no two parallel edges meet. Degenerate inputs, such as a rectangle, where two edges vanish at the same time and two parallel edges meet along a segment of constant clearance, are handled by the same steps, one event at a time. For those the code is checked against direct offsets by exact tests, but the proof does not cover them.
Proof: The wavefront builds the medial axis of a convex polygon, and the offsets read from it are exactfull
Setting. is a strictly convex polygon with edges , , unit outward normals and , so . By the convex offset lemma of the contour-parallel proof, the depth of is and . For a set of edges let , and let be the line . is the closure of the set of points of the interior of where at least two indices reach . For two adjacent edges of a polygon, is the meeting point of and .
Assumption (G), the generic case. In each pass of line L3, exactly one edge has the smallest meeting time.
Claim. Under (G), MEDIAL-AXIS stops after passes. Its arcs are segments whose union is , the clearance along each arc is affine in its parameter and runs from to , and the deepest node has clearance . For every , OFFSET.
Termination. Each pass of the loop of line L2 removes one edge from in line L7, so the loop runs exactly times.
Lemma 1 (erosion). If , then for all . Proof. Let . For , , with equality at . So the closed disk of radius around lies in if and only if . Hence if and only if this disk lies in , and the same holds for .
Lemma 2 (edge lengths). Let be a convex polygon with nonempty interior whose edges, in counterclockwise order, lie on the lines , , each with positive length. For consecutive edges , the length of edge of the polygon bounded by the lines is , where are the exterior angles of at the two ends of . Proof. Rotate so that and the edge runs in the direction . The left end moves with a constant velocity with and . Here , so and . The right end moves left at speed by symmetry.
So is affine and strictly decreasing, and it is zero exactly when , that is, when , and meet in one point. The system of line L3 has rows for three distinct unit vectors, which are not collinear points of the circle, so it has one solution , and is the zero of .
Invariant. At each test of line L2, with the clearance of the last event ( at the start):
- (I1) for all ;
- (I2) is a convex polygon with nonempty interior whose edges, in order, lie on for , each with positive length;
- (I3) for each pair of consecutive edges of there is one open arc, which starts at with clearance , and every closed arc runs from to for the pair that was consecutive in during .
At the start, is all edges, , and line L1 starts arc at the vertex . So the invariant holds.
A pass of the loop. Let be the smallest meeting time, for the edge between and . By Lemma 2 every edge length is positive on , and by (G) every with is still positive at . For the lines , , with the fixed exterior angles of and positive lengths, bound a convex polygon. A convex polygon is the intersection of the half-planes of its edges, so this polygon is . Its vertex between consecutive is , which moves on a straight line at constant speed. At , edge has length 0 and , the point of line L4. The polygon has its other edges, all of positive length, on the lines of , and at least three of them, with distinct normals, so its interior is not empty. This gives (I2) for . Also , as the intersection of the half-planes of its edges, and by (I1). By Lemma 1, for all , which gives (I1). Lines L5 and L6 close the arcs of and at and open the arc of at , which gives (I3).
The last step. When has three edges, is a triangle. The three meeting times of Lemma 2 are all the meeting time of the same three lines, so all three edges shrink to the point of line L8 at time , and for means that is empty. So , and is the deepest node.
Each arc lies in . A point of an arc has and lies in , so is reached by two indices. For it is an interior point of . The arc starts at clearance and ends at , and is affine along it. Arcs that start at start at a vertex of , which is in the closure.
Each point of lies on an arc. Let be an interior point of where two indices reach . Then and , so and are two supporting lines of the convex set through , with different normals. If , is a polygon with nonempty interior by the invariant, and a boundary point of such a polygon with two different supporting lines is a vertex. So for a consecutive pair of at time , which is a point of the arc of . If , then and . The points of on the boundary of are limits of such points, and they are vertices of , where arcs start.
OFFSET. Let . Every point that line L10 collects is a point of an arc with clearance , so it has depth and lies in . Every vertex of lies on two edge lines , with that support , so it is reached by two indices: it is in with clearance , and it is collected. A convex polygon is the convex hull of its vertices, so . For no arc has clearance , and .
The links. Arc ends where starts, with the same clearance, so the clearance along the spine does not decrease. A link from the loop at to the loop at is a chain of straight pieces of arcs whose points have clearance between and , so it lies in , and the tool does not touch the wall during it.
What this proof does not cover. When two edges have the same smallest meeting time, or two parallel edges become neighbours, assumption (G) fails. The code then removes the edges one at a time at the same clearance, and an arc between two parallel edges has . For these inputs the tests compare the medial axis and the offsets with direct computations, exactly, on rectangles and on random polygons with parallel sides. That is a check, not a proof.
Complexity
Line L2 runs times, and line L3 solves at most systems of size 3, so the code builds the medial axis in time. A priority queue of the meeting times makes this , because each event changes the meeting times of two edges only. The axis has leaves, inner nodes counted with multiplicity, and arcs. Line L10 scans the arcs, and the hull of line L11 takes , so each loop costs , and if the points are collected in order around the tree. The total is for loops.
For a general pocket with segments and arcs, the Voronoi diagram has size and can be computed in time, for example by Fortune's sweep for segments. Held (1998) uses a wavefront algorithm that is fast in practice.
Properties
- One diagram, all offsets. The diagram is built once. Every offset, at any distance, comes from it in time linear in its size.
- Topology from the diagram. Where the clearance along the axis has a local minimum, at a neck of the pocket, the offsets deeper than that clearance split in two. Where it has a local maximum, a loop shrinks to a point and ends. The diagram shows each such place, so the order of the loops and the places where the tool must lift are known before any loop is cut. In a convex pocket the offsets never split.
- Safe links. The tool center moves along the arcs between loops. Along the spine the clearance does not decrease, so the tool does not cut into the wall.
- Exact in the convex case. With rational edge normals, every node and every loop vertex of the code is rational.
Variants and improvements
- Curvilinear pockets. Held (1998) handles areas bounded by segments and circular arcs. The offsets of such an area are again made of segments and arcs, which a CNC controller can follow directly.
- Islands. The boundary of a pocket with islands has several components. The Voronoi diagram is the same object, and the offsets of the islands and of the outer wall merge where their fronts meet.
- The straight skeleton. The straight skeleton is the track of a wavefront that keeps sharp corners at reflex vertices. It coincides with the medial axis for convex polygons only. Offsets read from it are mitered offsets, not Euclidean ones.
- Medial axis toolpaths. Some methods move the tool along the medial axis itself, to clear the middle of a narrow pocket in one pass.
When to use it
Use the Voronoi method when the pocket has islands, reflex corners or arcs, and when many offsets of the same pocket are needed, as in roughing with a small step-over. For a convex pocket, direct half-plane intersection at each depth is simpler, as on the contour-parallel page.
Pitfalls
- Arcs are required. At a reflex vertex the Voronoi diagram has a parabolic arc between the vertex and an edge, and the offset has a circular arc. A method that uses only straight bisectors builds the straight skeleton, not the medial axis.
- Degenerate events. Several edges can vanish at the same time, and two parallel edges can meet along a segment of constant clearance, as in a rectangle. The code handles them one event at a time with exact arithmetic. With floating point, the order of near-equal events can flip and give a wrong tree.
- Robustness of the diagram. A Voronoi diagram of segments in floating point needs care with nearly parallel and nearly touching segments. See exact geometric computation.
- A hull only in the convex case. Line L11 uses the convex hull to order the points, which is valid only because the offsets of a convex pocket are convex.
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/voronoi-pocket-machining/. The authors are listed in prov/MEJQSV.jsonl.
"""Voronoi pocket machining on a convex polygon, with exact arithmetic.
Held's method computes the Voronoi diagram of the pocket boundary once and
reads every offset curve from it. Inside a convex polygon the Voronoi diagram
of the edges is the medial axis, and it is made of straight pieces of angle
bisectors. This module builds it with a wavefront: all edges move inward at
unit speed, and an edge disappears when its two neighbours meet on it. The
time of that event is the clearance (the distance to the boundary) of the
node where it happens.
Each arc of the medial axis is the track of one wavefront vertex. Its
clearance grows linearly from one end to the other, so the offset at distance
d is read from the arcs: one point on each arc whose clearance range holds d.
The pocket must be strictly convex, counterclockwise, with edges of rational
length, so that the unit normals are rational. A nonconvex pocket has
reflex vertices, and its Voronoi diagram then has parabolic arcs and its
offsets have circular arcs; this module does not handle that case.
"""
from fractions import Fraction
from math import isqrt
Point = tuple[Fraction, Fraction]
def _exact_sqrt(q: Fraction) -> Fraction:
q = Fraction(q)
rn, rd = isqrt(q.numerator), isqrt(q.denominator)
if rn * rn != q.numerator or rd * rd != q.denominator:
raise ValueError("an edge has an irrational length")
return Fraction(rn, rd)
def cross(o: Point, a: Point, b: Point) -> Fraction:
"""The orientation test: positive for a left turn, zero when collinear."""
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
def half_planes(poly):
"""Edge i goes from vertex i to vertex i + 1; it is a x + b y <= c with a unit normal."""
pts = [(Fraction(x), Fraction(y)) for x, y in poly]
n = len(pts)
if n < 3:
raise ValueError("a pocket needs at least 3 vertices")
for i in range(n):
if cross(pts[i], pts[(i + 1) % n], pts[(i + 2) % n]) <= 0:
raise ValueError("the polygon is not strictly convex and counterclockwise")
out = []
for i in range(n):
(x0, y0), (x1, y1) = pts[i], pts[(i + 1) % n]
length = _exact_sqrt((x1 - x0) ** 2 + (y1 - y0) ** 2)
a, b = (y1 - y0) / length, -(x1 - x0) / length
out.append((a, b, a * x0 + b * y0))
return pts, out
def _meet(planes, i, j, k):
"""The point and time where the moved lines of edges i, j and k meet (Cramer's rule)."""
rows = [planes[i], planes[j], planes[k]]
m = [[a, b, Fraction(1)] for a, b, _ in rows]
rhs = [c for _, _, c in rows]
def det(q):
return (q[0][0] * (q[1][1] * q[2][2] - q[1][2] * q[2][1])
- q[0][1] * (q[1][0] * q[2][2] - q[1][2] * q[2][0])
+ q[0][2] * (q[1][0] * q[2][1] - q[1][1] * q[2][0]))
d = det(m)
sol = []
for col in range(3):
q = [row[:] for row in m]
for r in range(3):
q[r][col] = rhs[r]
sol.append(det(q) / d)
return (sol[0], sol[1]), sol[2]
class Arc:
"""The track of the wavefront vertex between edges left and right."""
__slots__ = ("left", "right", "p0", "t0", "p1", "t1", "next")
def __init__(self, left, right, p0, t0):
self.left, self.right = left, right
self.p0, self.t0 = p0, t0
self.p1 = self.t1 = None
self.next = None # the arc that starts where this one ends
def at(self, d) -> list[Point]:
"""The points of the arc with clearance d."""
if not (self.t0 <= d <= self.t1):
return []
if self.t1 == self.t0:
return [self.p0, self.p1]
lam = (d - self.t0) / (self.t1 - self.t0)
return [(self.p0[0] + lam * (self.p1[0] - self.p0[0]), self.p0[1] + lam * (self.p1[1] - self.p0[1]))]
def medial_axis(poly):
"""The medial axis of a convex polygon as a list of arcs, and its deepest node.
The first n arcs start at the polygon vertices: arc i starts at vertex
i + 1, between edges i and i + 1. Every arc ends at a node, and arc.next is
the arc that leaves that node (None at the deepest node).
"""
pts, planes = half_planes(poly)
n = len(pts)
front = list(range(n)) # @line L1
arcs = []
live = {} # (left, right) -> Arc
for i in range(n):
a = Arc(i, (i + 1) % n, pts[(i + 1) % n], Fraction(0))
arcs.append(a)
live[(i, (i + 1) % n)] = a
while len(front) > 3: # @line L2
best = None
m = len(front)
for pos in range(m): # @line L3
p, e, q = front[pos - 1], front[pos], front[(pos + 1) % m]
point, t = _meet(planes, p, e, q)
if best is None or t < best[0]:
best = (t, pos, point)
t, pos, point = best # @line L4
p, e, q = front[pos - 1], front[pos], front[(pos + 1) % m]
a1, a2 = live.pop((p, e)), live.pop((e, q)) # @line L5
new = Arc(p, q, point, t) # @line L6
for a in (a1, a2):
a.p1, a.t1, a.next = point, t, new
arcs.append(new)
live[(p, q)] = new
front.pop(pos) # @line L7
point, t = _meet(planes, *front) # @line L8
for a in live.values():
a.p1, a.t1 = point, t
return arcs, (point, t)
def convex_hull(points: list[Point]) -> list[Point]:
"""Andrew's monotone chain; collinear points are dropped. Exact for rationals."""
pts = sorted(set(points))
if len(pts) <= 2:
return pts
lower, upper = [], []
for p in pts:
while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0:
lower.pop()
lower.append(p)
for p in reversed(pts):
while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0:
upper.pop()
upper.append(p)
hull = lower[:-1] + upper[:-1]
return hull if len(hull) > 2 else [pts[0], pts[-1]]
def offset_from_axis(arcs, d) -> list[Point]:
"""The offset at distance d, read from the medial axis.
Inside a convex pocket the points of clearance d on the arcs are the
vertices of the offset, so the offset is their convex hull.
"""
d = Fraction(d)
found = []
for a in arcs: # @line L10
found.extend(a.at(d))
return convex_hull(found) # @line L11
def spine(arcs, start=0):
"""The chain of arcs from polygon vertex start + 1 to the deepest node."""
chain = []
a = arcs[start]
while a is not None:
chain.append(a)
a = a.next
return chain
def point_on_spine(chain, d) -> Point:
"""The point of clearance d on a chain whose clearance does not decrease."""
for a in chain:
if a.t0 <= d <= a.t1:
return a.at(d)[0]
raise ValueError("no point of this clearance on the chain")
def voronoi_pocket(poly, r, s):
"""Loops at d = r, r + s, ... and the links between them along the medial axis.
Returns (loops, links). Each loop is (d, polygon) and starts at the point
where the spine meets it. Link k goes from loop k to loop k + 1 along the
spine, so it stays at clearance at least r.
"""
r, s = Fraction(r), Fraction(s)
if r <= 0 or s <= 0:
raise ValueError("r and s must be positive")
arcs, (_, deepest) = medial_axis(poly) # @line L9
chain = spine(arcs)
loops, links = [], []
d = r
while d <= deepest: # @line L12
loop = offset_from_axis(arcs, d)
loops.append((d, _start_at(loop, point_on_spine(chain, d))))
nd = d + s
if nd <= deepest: # @line L13
pts = [point_on_spine(chain, d)]
for a in chain:
if d < a.t1 and a.t1 < nd:
pts.append(a.p1)
pts.append(point_on_spine(chain, nd))
links.append(pts)
d = nd
return loops, links
def _start_at(loop, p):
"""Rotate a closed loop so that it starts at p, inserting p on an edge if needed."""
if p in loop:
k = loop.index(p)
return loop[k:] + loop[:k]
m = len(loop)
for i in range(m):
a, b = loop[i], loop[(i + 1) % m]
if 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]):
return [p] + loop[i + 1:] + loop[:i + 1]
raise ValueError("the point is not on the loop")
test_voronoi_pocket_machining.py 201 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/voronoi-pocket-machining/. The authors are listed in prov/MEJQSV.jsonl.
import itertools
import random
from fractions import Fraction as F
import pytest
from voronoi_pocket_machining import (
convex_hull,
cross,
half_planes,
medial_axis,
offset_from_axis,
voronoi_pocket,
)
def unit_vectors():
base = {(F(1), F(0))}
for m in range(2, 5):
for n in range(1, m):
k = m * m + n * n
base.add((F(m * m - n * n, k), F(2 * m * n, k)))
out = set()
for a, b in base:
for x, y in ((a, b), (b, a)):
for sx in (1, -1):
for sy in (1, -1):
out.add((sx * x, sy * y))
return sorted(out)
UNITS = unit_vectors()
def clip(poly, a, b, c):
"""Reference: clip a convex polygon by a x + b y <= c (Sutherland-Hodgman)."""
out = []
for i in range(len(poly)):
p, q = poly[i], poly[(i + 1) % len(poly)]
fp, fq = c - a * p[0] - b * p[1], c - a * q[0] - b * q[1]
if fp >= 0:
out.append(p)
if fp * fq < 0:
t = fp / (fp - fq)
out.append((p[0] + t * (q[0] - p[0]), p[1] + t * (q[1] - p[1])))
return out
def reference_offset(poly, d):
"""The offset by clipping with all moved half-planes, a method that does not use the axis."""
_, planes = half_planes(poly)
q = [(F(x), F(y)) for x, y in poly]
for a, b, c in planes:
q = clip(q, a, b, c - d)
if not q:
return []
return convex_hull(q)
def random_convex(rng):
while True:
normals = rng.sample(UNITS, rng.randrange(3, 9))
poly = [(F(-500), F(-500)), (F(500), F(-500)), (F(500), F(500)), (F(-500), F(500))]
for a, b in normals:
poly = clip(poly, a, b, F(rng.randrange(2, 16)))
if not poly:
break
if len(poly) < 3 or any(abs(x) == 500 or abs(y) == 500 for x, y in poly):
continue
poly = convex_hull(poly)
if len(poly) >= 3:
return poly
def depth(planes, p):
return min(c - a * p[0] - b * p[1] for a, b, c in planes)
def brute_inradius(poly):
"""Largest inscribed circle by trying every triple of edge lines."""
_, planes = half_planes(poly)
best = None
for i, j, k in itertools.combinations(range(len(planes)), 3):
m = [planes[i], planes[j], planes[k]]
a = [[x[0], x[1], F(1)] for x in m]
det = (a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1]) - a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0])
+ a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0]))
if det == 0:
continue
# solve by elimination
rows = [a[t] + [m[t][2]] for t in range(3)]
for col in range(3):
piv = next(r for r in range(col, 3) if rows[r][col] != 0)
rows[col], rows[piv] = rows[piv], rows[col]
for r in range(3):
if r != col and rows[r][col] != 0:
f = rows[r][col] / rows[col][col]
rows[r] = [x - f * y for x, y in zip(rows[r], rows[col])]
x, y, t = (rows[r][3] / rows[r][r] for r in range(3))
if t >= 0 and depth(planes, (x, y)) == t and (best is None or t > best):
best = t
return best
RECT = [(0, 0), (8, 0), (8, 4), (0, 4)]
PENTAGON = [(0, 0), (20, 0), (20, 9), (8, 25), (0, 10)]
TRIANGLE = [(0, 0), (12, 0), (0, 9)]
def test_triangle_has_one_node():
arcs, (node, t) = medial_axis(TRIANGLE)
assert node == (3, 3) and t == 3
assert len(arcs) == 3 and all(a.p1 == (3, 3) for a in arcs)
def test_rectangle_axis_and_offsets():
arcs, (node, t) = medial_axis(RECT)
assert t == 2
ends = sorted({a.p1 for a in arcs})
assert ends == [(2, 2), (6, 2)]
assert offset_from_axis(arcs, 1) == [(1, 1), (7, 1), (7, 3), (1, 3)]
assert offset_from_axis(arcs, 2) == [(2, 2), (6, 2)]
assert offset_from_axis(arcs, F(5, 2)) == []
def test_arcs_are_on_the_medial_axis():
rng = random.Random(5)
for poly in [RECT, PENTAGON, TRIANGLE] + [random_convex(rng) for _ in range(40)]:
_, planes = half_planes(poly)
arcs, _ = medial_axis(poly)
assert len(arcs) == 2 * len(poly) - 3
for a in arcs:
assert a.t0 <= a.t1
mid = ((a.p0[0] + a.p1[0]) / 2, (a.p0[1] + a.p1[1]) / 2)
for p, t in ((a.p0, a.t0), (a.p1, a.t1), (mid, (a.t0 + a.t1) / 2)):
assert depth(planes, p) == t
for e in (a.left, a.right):
ea, eb, ec = planes[e]
assert ec - ea * p[0] - eb * p[1] == t
def test_offsets_match_clipping():
rng = random.Random(9)
for poly in [RECT, PENTAGON, TRIANGLE] + [random_convex(rng) for _ in range(40)]:
arcs, (_, deepest) = medial_axis(poly)
times = sorted({a.t1 for a in arcs})
ds = times + [F(rng.randrange(0, 40), 4) for _ in range(6)] + [deepest + F(1, 7)]
for d in ds:
assert offset_from_axis(arcs, d) == reference_offset(poly, d)
def test_deepest_node_is_the_inradius():
rng = random.Random(13)
for poly in [RECT, PENTAGON] + [random_convex(rng) for _ in range(30)]:
_, (node, t) = medial_axis(poly)
assert t == brute_inradius(poly)
_, planes = half_planes(poly)
assert depth(planes, node) == t
def test_pocket_loops_and_links():
rng = random.Random(17)
for poly in [PENTAGON] + [random_convex(rng) for _ in range(20)]:
_, planes = half_planes(poly)
r = F(rng.randrange(1, 5), 2)
s = r * F(rng.randrange(2, 5), 4)
loops, links = voronoi_pocket(poly, r, s)
assert len(links) == max(0, len(loops) - 1)
for k, (d, loop) in enumerate(loops):
assert d == r + k * s
assert convex_hull(loop) == reference_offset(poly, d)
for k, link in enumerate(links):
assert link[0] == loops[k][1][0] and link[-1] == loops[k + 1][1][0]
ts = [depth(planes, p) for p in link]
assert ts == sorted(ts) and ts[0] >= r
def test_pentagon_example():
arcs, (node, t) = medial_axis(PENTAGON)
assert node == (F(37, 4), F(35, 4)) and t == F(35, 4)
assert sorted({(a.p1, a.t1) for a in arcs[:5]}) == [
((F(8), F(8)), F(8)),
((F(37, 4), F(35, 4)), F(35, 4)),
((F(53, 4), F(27, 4)), F(27, 4)),
]
loops, links = voronoi_pocket(PENTAGON, 2, 2)
assert [(d, len(q)) for d, q in loops] == [(2, 5), (4, 5), (6, 5), (8, 3)]
assert loops[3][1] == [(F(43, 4), 8), (F(64, 7), F(71, 7)), (8, 8)]
assert links[2] == [(14, 6), (F(53, 4), F(27, 4)), (F(43, 4), 8)]
def test_bad_input():
with pytest.raises(ValueError):
medial_axis([(0, 0), (1, 0), (0, 1)])
with pytest.raises(ValueError):
medial_axis([(0, 0), (0, 4), (3, 0)])
with pytest.raises(ValueError):
voronoi_pocket(TRIANGLE, 1, 0)
History
Held's 1991 monograph gave the Voronoi diagram of segments and arcs as the tool for pocket machining, with the offsets, their splits and the order of the loops all read from it. Held, Lukács and Andor (1994) described a full system with this method, and Held (1998) gave a wavefront algorithm for curvilinear polygons.
References
- Martin Held, On the Computational Geometry of Pocket Machining, Lecture Notes in Computer Science 500, Springer, 1991, the chapters on the Voronoi diagram of a pocket boundary, the offsets read from it, and the generation of contour-parallel tool paths
- Martin Held, Voronoi diagrams and offset curves of curvilinear polygons, Computer-Aided Design 30(4), 287-300, 1998, the wavefront algorithm for the Voronoi diagram of an area bounded by segments and circular arcs, and the offsets computed from it
- Martin Held, Gábor Lukács and László Andor, Pocket machining based on contour-parallel tool paths generated by means of proximity maps, Computer-Aided Design 26(3), 189-203, 1994, the use of the Voronoi diagram for the offsets, the detection of uncut regions and the links between loops
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 MEJQSV Edit this page History Report an error Markdown