Algorithmadvanced
Pencil-cut clean-up machining
Also called pencil curve machining, clean-up toolpath.
Traces the curves along concave corners where a ball end tool touches two surfaces at once, to remove material left by larger tools, as Choi and Jerard describe.
- Time
- O(m k) worst
- Space
- O(1) extra
- Where
- k = number of corrector steps per point; m = number of traced points
- Model
- Real RAM
- Properties
- deterministiciterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Byoung K. Choi, Robert B. Jerard, 1998
Pencil-cut machining is a finishing pass that runs a small ball end mill along the concave corners of a part, where two surfaces meet in a valley or a sharp inside edge. A larger tool used before cannot reach into such corners, so it leaves a strip of material there. The pencil path is the curve along which the ball touches both surfaces at once. Its ball centers are the points at the distance from both surfaces, which is the intersection of the two offset surfaces at the distance . The algorithm here traces that intersection with a predictor step along the tangent and a Newton corrector. For two planes the curve is a straight line parallel to the edge at the distance , where is the opening angle, and the tracer follows it exactly.
In plain words
A big round cutter cannot get into an inside corner. It always leaves a little rib of material in the corner, like dust in the corner of a room that a broom cannot reach.
The clean-up pass uses a smaller round cutter and pushes it into the corner as far as it goes, so that it touches both walls. Then it slides the cutter along the corner, always touching both walls. The line that the center of the cutter follows is the pencil line, because it looks like a pencil stroke drawn along the corner.
To find the line on curved walls, the computer takes a small step along the corner, and then pulls the cutter back until it touches both walls again.
The problem
Two surfaces and meet along a concave edge, or come close in a valley, and the free side is where both signed distances are positive. For a ball end mill of radius , let be the signed distance from to minus . The ball with center touches from the free side when . The pencil curve is
the curve of ball centers that touch both surfaces. The task is to compute it as a sequence of cutter locations, with the contact points and , where is the unit normal of at the contact. Pencil curves are needed only where the edge is sharper than the ball, that is where the corner fillet has a radius smaller than . Elsewhere the ball touches one surface at a time.
The algorithm
PENCIL-TRACE(g₁, ∇g₁, g₂, ∇g₂, x₀, h, m)- 1
x ← CORRECT(x₀) ▷ the nearest point with g₁ = g₂ = 0 - 2
path ← [x] - 3
repeat m times - 4
t ← ∇g₁(x) × ∇g₂(x), normalized and turned to agree with the last t - 5
y ← x + h t ▷ predictor along the tangent of the curve - 6
x ← CORRECT(y) ▷ Newton steps back onto the curve - 7
append x to path - 8
return path
CORRECT repeats the step , where and has the rows and , until is below a tolerance. It is the smallest move that solves the linearized equations. The tangent of the curve is orthogonal to both gradients, so it is their cross product. The contact points are , since the gradient of a signed distance is the unit normal.
Example
The floor is with . A wall leans out from the line , , with the normal , so the free side of the wall is . The ball has .
| quantity | value |
|---|---|
| opening angle | |
| pencil line | for all |
| distance from the edge | |
| contact with the floor | |
| contact with the wall |
The wall contact is on the wall, since . Started at the origin, the tracer reaches in one corrector step and then moves along . For a vertical wall, , the line is at , at the distance from the edge.
On a floor and a concave cylinder wall of radius with , the traced pencil curve is the circle of radius at the height 3, to within , and with the step it goes once round in 2136 steps.
Correctness
Theorem. For two planes with unit normals pointing into the free wedge, the centers of the balls of radius that lie in the wedge and touch both planes form the line
where is a point of the edge. The line is parallel to the edge at the distance , the contacts are and , and no ball in the wedge has its center closer to the edge.
The proof is in the proof file. A ball lies on the free side of a plane and touches it exactly when its center is at the distance , so the centers solve two independent linear equations, and the given point solves them because . The distance follows from . For two planes the corrector is exact after one step, since the equations are linear, and the predictor moves along the line. So every traced point is on the closed-form line. The tests check this in exact rational arithmetic, with normals such as and , together with the contacts, the squared distance , and a brute force search that finds no admissible center closer to the edge.
For curved surfaces the result is local: Newton's method converges near the curve where the gradients are independent. The tracer does not check the ball against other parts of the model.
Proof: For a ball touching two planes the pencil path is a line parallel to the edge at the distance r over sin of half the opening angle, and the tracer follows it exactlyfull
Setting. Two planes , , have unit normals that are not parallel, so . The free region, where the tool may be, is the wedge , so the normals point into the free side, and the edge is a concave edge of the part. The opening angle of the wedge satisfies . The tool is a ball of radius . The offset functions of the code are .
Lemma 1. The closed ball lies in the half-space if and only if . It lies in it and touches if and only if , and then the only common point is .
Proof. The smallest value of on the ball is , taken only at , because with equality only when .
Theorem. The centers of the balls that lie in and touch both planes form the line
where is any point of . The line is parallel to the edge, at the distance from it, and the contact points are and . Every center of a ball that lies in , whether it touches the planes or not, is at least as far from as .
Proof. By Lemma 1 the centers are the solutions of the two linear equations . The normals are independent, so the solutions form a line whose direction is orthogonal to both, that is parallel to . Since , . Let . Then , and in the same way . So is a solution, which gives . The edge is the line , and is orthogonal to , so the distance from to is . Now , so
The contacts come from Lemma 1. For the last claim, let be the center of a ball in , and write with . By Lemma 1, , so for both . Then , and the squared distance from to is .
So the pencil path for a concave edge between two planes is the straight line , and its ball is the one that goes deepest into the corner. With the tip of the tool as the reference point, the path of a vertical tool is moved down by .
The tracer on two planes. Line L1 and line L6 call the corrector. For linear with the matrix of rows , one corrector step maps to . The matrix has the determinant , so it is invertible, and . So every point that the corrector returns is on , after one step and with no error in exact arithmetic. Line L4 gives the tangent , so line L5 moves along , and the corrector leaves the point unchanged. Successive points are apart along , or apart when the tangent is not normalized. The tests check, in rational arithmetic with unit normals from Pythagorean quadruples, that every traced point is on the closed-form line at the squared distance and that the contacts lie on the planes. A brute force search over random points checks that no admissible center is closer to the edge.
Curved surfaces. When the are signed distances to smooth surfaces with independent gradients along the curve, the pencil curve is a smooth curve by the implicit function theorem, and the corrector is a Newton method for an underdetermined system, which converges fast from a point close enough to it. This is a local statement. No global result is claimed: the tracer can jump to another branch with a long step, it stops where the gradients become parallel, and it does not check the ball against other surfaces. On a floor and a concave cylinder wall of radius , the pencil curve is the circle of radius at height , and the tests measure that the traced points stay on it to and go once round.
Complexity
Each traced point costs one tangent and corrector steps, and each corrector step evaluates , and their gradients and solves a system. With evaluation, points take time and extra space besides the path. For planes . On a triangle mesh, the evaluation of the offset distances is the main cost, and practical systems use spatial search structures or the z-map of the offset surface.
Properties
- Exact for planar corners. The pencil path of two planes is a straight line at a closed-form position.
- Deepest reach. The pencil ball is the one that goes furthest into the corner. No ball in the corner is closer to the edge.
- Two contacts. Along the path the tool touches both surfaces, so it cuts the rest material from both sides of the corner.
- Local tracing. The tracer follows one branch of the curve from a start point. Finding the start points is a separate step.
Variants and improvements
- Mesh-based detection. On triangle meshes, Park computed pencil curves from an offset mesh and the visibility of its intersections. Kim, Jun and Park found pencil points from scanning paths with two contacts and traced the pencil-cut path from them.
- Bitangency angle. CAM systems mark a point as a pencil point when the two contact normals differ by more than a chosen angle. Small angles find shallow valleys too.
- Multiple pencil passes. Parallel passes on both sides of the pencil curve, at offsets set by the scallop height, clean a wider band after the main pass.
- Five-axis pencil cuts. Tilting the tool lets a longer tool reach deep corners and keeps the holder clear of the walls.
- Corners in 2D. In pocket machining, the same formula gives the position of a tool touching both walls of a corner with angle , at the distance from the corner point.
When to use it
Use pencil cuts after roughing and finishing with a larger ball, on molds and dies with fillets and sharp inside edges. The pass is short and removes the material that the larger tool left in the corners, before the final finishing with a small tool or before a smaller pencil pass. Where the fillet radius is larger than the ball, no pencil curve exists there, and ordinary finishing reaches the corner.
Pitfalls
- Global gouges. The tracer looks only at two surfaces. Near a third surface the ball can gouge, so the path must be checked by gouge detection.
- Tangent surfaces. Where the two surfaces become tangent, the gradients are parallel, the pencil curve ends, and the corrector fails. The trace must stop there.
- Branch jumps. A long step can land the predictor near another branch of the curve, and the corrector then follows the wrong corner. Keep small compared with the size of the features.
- Full load in the corner. The pencil tool cuts on both sides of the corner at once, and the material left by the larger tool can be thick. Several passes with growing depth, or a lower feed, protect the tool.
- Sign of the normals. The formula needs the normals that point into the free region. With one normal reversed the line lies inside the material.
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/pencil-cut-machining/. The authors are listed in prov/K6TS7H.jsonl.
"""Pencil-cut tracing: the path of a ball end mill that touches two surfaces at once.
Each surface is given by a function g(x) = (signed distance of x from the
surface, positive on the free side) - r and its gradient. A ball of radius r
with center x touches surface i exactly when g_i(x) = 0, so the pencil curve
of ball centers is the intersection of the two offset surfaces g_1 = 0 and
g_2 = 0. It is traced by a predictor along the tangent grad g_1 x grad g_2
and a Newton corrector that moves to the nearest point with g_1 = g_2 = 0
(the minimum norm step of the 2 x 3 linear system).
The code works with floats or with Fractions. With Fractions and planes the
corrector is exact; pass normalize=False to step along the raw tangent, so
that no square root is taken.
"""
import math
def dot(a, b):
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
def cross(a, b):
return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])
def correct(g1, dg1, g2, dg2, x, tol=1e-12, max_iter=20):
"""Newton steps to a point with g1 = g2 = 0, each the minimum norm solution
of the linearized system."""
for _ in range(max_iter):
v1, v2 = g1(x), g2(x)
if abs(v1) <= tol and abs(v2) <= tol:
return x
a, b = dg1(x), dg2(x)
aa, ab, bb = dot(a, a), dot(a, b), dot(b, b)
det = aa * bb - ab * ab
if det == 0:
raise ValueError("the two surfaces are tangent here; the pencil curve is not defined")
# solve [[aa, ab], [ab, bb]] (l1, l2) = (v1, v2), then x <- x - l1 a - l2 b
l1 = (bb * v1 - ab * v2) / det
l2 = (aa * v2 - ab * v1) / det
x = tuple(x[i] - l1 * a[i] - l2 * b[i] for i in range(3))
if abs(g1(x)) <= tol and abs(g2(x)) <= tol:
return x
raise ValueError("the corrector did not converge")
def pencil_trace(g1, dg1, g2, dg2, x0, h, m, tol=1e-12, normalize=True):
"""Trace m steps of length h of the pencil curve of ball centers from near x0."""
x = correct(g1, dg1, g2, dg2, x0, tol) # @line L1
path = [x] # @line L2
prev = None
for _ in range(m): # @line L3
t = cross(dg1(x), dg2(x)) # @line L4
if prev is not None and dot(t, prev) < 0:
t = (-t[0], -t[1], -t[2])
prev = t
if normalize:
n = math.sqrt(dot(t, t))
if n == 0:
raise ValueError("the two surfaces are tangent here; the pencil curve is not defined")
t = (t[0] / n, t[1] / n, t[2] / n)
y = (x[0] + h * t[0], x[1] + h * t[1], x[2] + h * t[2]) # @line L5
x = correct(g1, dg1, g2, dg2, y, tol) # @line L6
path.append(x) # @line L7
return path # @line L8
def contacts(x, r, dg1, dg2, unit=True):
"""The two contact points x - r n_i, with n_i the unit normals (the gradients of
signed distances are unit vectors already when unit is True)."""
out = []
for dg in (dg1, dg2):
n = dg(x)
if not unit:
s = math.sqrt(dot(n, n))
n = (n[0] / s, n[1] / s, n[2] / s)
out.append((x[0] - r * n[0], x[1] - r * n[1], x[2] - r * n[2]))
return out
def plane(n, d, r):
"""The offset function and gradient of the plane n . x = d, with unit normal n
pointing to the free side, for a ball of radius r."""
def g(x):
return dot(n, x) - d - r
def dg(x):
return n
return g, dg
test_pencil_cut_machining.py 155 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pencil-cut-machining/. The authors are listed in prov/K6TS7H.jsonl.
import math
import random
from fractions import Fraction as F
import pytest
from pencil_cut_machining import contacts, cross, dot, pencil_trace, plane
# Rational unit vectors from Pythagorean quadruples a^2 + b^2 + c^2 = d^2.
QUADS = [(1, 2, 2, 3), (2, 3, 6, 7), (1, 4, 8, 9), (4, 4, 7, 9), (2, 6, 9, 11), (6, 6, 7, 11), (0, 3, 4, 5), (0, 0, 1, 1)]
def random_unit(rng):
a, b, c, d = rng.choice(QUADS)
v = [F(a, d), F(b, d), F(c, d)]
rng.shuffle(v)
return tuple(x if rng.random() < 0.5 else -x for x in v)
def det3(a, b, c):
return dot(a, cross(b, c))
def closed_form(n1, d1, n2, d2, r):
"""The reference: a point of the edge line, by Cramer's rule, plus
r (n1 + n2) / (1 + n1 . n2)."""
e = cross(n1, n2)
D = det3(n1, n2, e)
rhs = (d1, d2, 0)
cols = []
for k in range(3):
m = [list(n1), list(n2), list(e)]
for i in range(3):
m[i][k] = rhs[i]
cols.append(det3(*m) / D)
p = tuple(cols)
s = r / (1 + dot(n1, n2))
c = tuple(p[i] + s * (n1[i] + n2[i]) for i in range(3))
return p, e, c
def dist2_to_line(x, p, e):
w = tuple(x[i] - p[i] for i in range(3))
return dot(w, w) - dot(w, e) ** 2 / dot(e, e)
def test_two_planes_exact_against_closed_form():
rng = random.Random(3)
done = 0
while done < 60:
n1, n2 = random_unit(rng), random_unit(rng)
e = cross(n1, n2)
if e == (0, 0, 0):
continue
d1, d2 = F(rng.randint(-20, 20), rng.randint(1, 5)), F(rng.randint(-20, 20), rng.randint(1, 5))
r = F(rng.randint(1, 12), rng.randint(1, 4))
g1, dg1 = plane(n1, d1, r)
g2, dg2 = plane(n2, d2, r)
p, e, c = closed_form(n1, d1, n2, d2, r)
x0 = tuple(c[i] + F(rng.randint(-9, 9), 7) for i in range(3))
path = pencil_trace(g1, dg1, g2, dg2, x0, F(1, 3), 5, tol=0, normalize=False)
for k, x in enumerate(path):
# the center is on the closed-form line
assert cross(tuple(x[i] - c[i] for i in range(3)), e) == (0, 0, 0)
# at the distance r / sin(alpha / 2) from the edge: squared, 2 r^2 / (1 + n1 . n2)
assert dist2_to_line(x, p, e) == 2 * r * r / (1 + dot(n1, n2))
# the ball touches both planes, at x - r n_i
q1, q2 = contacts(x, r, dg1, dg2)
assert dot(n1, q1) == d1 and dot(n2, q2) == d2
if k:
step = tuple(x[i] - path[k - 1][i] for i in range(3))
assert step != (0, 0, 0) and cross(step, e) == (0, 0, 0)
done += 1
def test_floor_and_leaning_wall_example():
# floor z = 0, and a wall through the line x = 10, z = 0 with normal (-4, 0, 3)/5
r = F(5)
n1, d1 = (F(0), F(0), F(1)), F(0)
n2 = (F(-4, 5), F(0), F(3, 5))
d2 = dot(n2, (F(10), F(0), F(0)))
g1, dg1 = plane(n1, d1, r)
g2, dg2 = plane(n2, d2, r)
path = pencil_trace(g1, dg1, g2, dg2, (F(0), F(0), F(0)), F(1), 3, tol=0, normalize=False)
for x in path:
assert (x[0], x[2]) == (F(15, 2), F(5))
q1, q2 = contacts(x, r, dg1, dg2)
assert (q1[0], q1[2]) == (F(15, 2), F(0)) and (q2[0], q2[2]) == (F(23, 2), F(2))
ys = [x[1] for x in path]
assert len(set(ys)) == len(ys)
def test_pencil_center_is_the_deepest_admissible_center():
# brute force: every center at distance >= r from both planes (the ball fits
# in the wedge) is at least r / sin(alpha / 2) from the edge
rng = random.Random(8)
for _ in range(20):
n1, n2 = random_unit(rng), random_unit(rng)
if cross(n1, n2) == (0, 0, 0):
continue
n1f, n2f = tuple(map(float, n1)), tuple(map(float, n2))
r = rng.uniform(0.5, 4.0)
g1, dg1 = plane(n1f, 0.0, r)
g2, dg2 = plane(n2f, 0.0, r)
path = pencil_trace(g1, dg1, g2, dg2, (1.0, 2.0, 3.0), 0.5, 2)
e = cross(n1f, n2f)
best = dist2_to_line(path[0], (0.0, 0.0, 0.0), e)
half = math.acos(-dot(n1f, n2f)) / 2 # alpha / 2, alpha the opening angle
assert math.isclose(math.sqrt(best), r / math.sin(half), rel_tol=1e-9)
for _ in range(2000):
x = tuple(rng.uniform(-20, 20) for _ in range(3))
if dot(n1f, x) >= r and dot(n2f, x) >= r:
assert dist2_to_line(x, (0.0, 0.0, 0.0), e) >= best * (1 - 1e-9)
def test_floor_and_cylinder_wall_gives_a_circle():
rho, r = 20.0, 3.0
def g1(x):
return x[2] - r
def dg1(x):
return (0.0, 0.0, 1.0)
def g2(x):
return rho - math.hypot(x[0], x[1]) - r
def dg2(x):
q = math.hypot(x[0], x[1])
return (-x[0] / q, -x[1] / q, 0.0)
h = 0.05
m = int(2 * math.pi * (rho - r) / h)
path = pencil_trace(g1, dg1, g2, dg2, (rho - r + 0.3, 0.1, r + 0.2), h, m)
for x in path:
assert abs(x[2] - r) <= 1e-9
assert abs(math.hypot(x[0], x[1]) - (rho - r)) <= 1e-9
q1, q2 = contacts(x, r, dg1, dg2)
assert abs(q1[2]) <= 1e-9 and abs(math.hypot(q2[0], q2[1]) - rho) <= 1e-9
# the steps follow the circle, so the path goes once round
turn = 0.0
for a, b in zip(path, path[1:]):
turn += math.atan2(a[0] * b[1] - a[1] * b[0], a[0] * b[0] + a[1] * b[1])
assert abs(abs(turn) - m * h / (rho - r)) <= 1e-3
assert abs(abs(turn) - 2 * math.pi) <= h / (rho - r)
def test_parallel_planes_have_no_pencil_curve():
g1, dg1 = plane((0.0, 0.0, 1.0), 0.0, 1.0)
g2, dg2 = plane((0.0, 0.0, -1.0), -10.0, 1.0)
with pytest.raises(ValueError):
pencil_trace(g1, dg1, g2, dg2, (0.0, 0.0, 5.0), 0.1, 3)
History
Clean-up machining of corners came with the CAM systems for sculptured surfaces in the 1990s. Choi and Jerard described pencil-cut paths in their 1998 book, as the path of a ball that touches two surfaces at once. In 2005 Park computed pencil curves from the visibility of intersections on an offset triangle mesh, and Kim, Jun and Park traced pencil-cut and fillet-cut paths on polyhedral models from points with two contacts. Commercial CAM systems offer pencil passes with a bitangency angle as the main setting.
References
- Byoung K. Choi and Robert B. Jerard, Sculptured Surface Machining, Theory and Applications, Kluwer Academic Publishers, 1998, the material on clean-up machining of concave corners and on offset surfaces of the part
- Sang C. Park, Pencil curve detection from visibility data, Computer-Aided Design 37(14), 1492-1498, 2005, the pencil curve as the path of the ball center sliding along a concave edge, and its computation from an offset triangle mesh
- D.-S. Kim, C.-S. Jun and S. C. Park, Tool path generation for clean-up machining by a curve-based approach, Computer-Aided Design 37(9), 967-973, 2005, the detection of pencil points from points with two contacts, and the tracing of pencil-cut and fillet-cut paths on polyhedral models
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 K6TS7H Edit this page History Report an error Markdown