Algorithm Search⌘K

Data structurecore

Z-map model

Also called height field stock model.

Represents the stock in 3-axis machining simulation as a grid of heights, each lowered by the tool as it passes over, fast but blind to undercuts.

Time
O(c) cutO(1) query
Space
O(N) extra
Where
N = number of grid columns; c = number of columns in the bounding box of one linear tool move
Properties
deterministicnot exact
Origin
Robert O. Anderson, 1978

A z-map is a model of the stock in 3-axis milling. It puts a grid of vertical lines over the workpiece and stores one number per line: the height of the top of the material there. A cut by a tool that points down lowers each height to the lowest point of the tool's swept volume on that line, if that point is below the old height. The model is the oldest and simplest stock model for NC verification, and it is usually credited to Anderson (1978). A cut costs a constant time per grid line under the tool, and a query of one height costs O(1)O(1). The price is that a column can hold only one interval of material, from the bottom to the top. The model cannot show an undercut, a hole across the tool axis or a cut by a tilted tool. The dexel representation removes this limit.

In plain words

Think of a bed of nails pushed up from below through a board, so that their heads form the top of a block. Each nail has its own height. The block is everything below the nail heads.

A milling cutter comes down from above and moves over the block. Wherever it passes over a nail, it pushes that nail down to the lowest point the cutter reaches there. A nail that the cutter does not reach keeps its height.

To show the result, draw the nail heads as a surface. To check for an error, compare each nail with the height the part should have at that point.

The nails can only show material that goes straight down to the floor. A pocket cut in from the side has nowhere to go.

The abstract type

The domain is a rectangle [x0,x0+(nx−1)h]×[y0,y0+(ny−1)h][x_0, x_0 + (n_x - 1)h] \times [y_0, y_0 + (n_y - 1)h] with a grid of spacing hh, and N=nxnyN = n_x n_y grid points qij=(x0+ih,y0+jh)q_{ij} = (x_0 + ih, y_0 + jh). The model stands for the solid

M=⋃i,j{qij}×[zb,Hij],M = \bigcup_{i,j} \{q_{ij}\} \times [z_b, H_{ij}],

a set of vertical segments, one per grid point, above a fixed bottom zbz_b. The operations are:

  • INIT(top)\mathrm{INIT}(top): a block with all Hij=topH_{ij} = top.
  • CUT(c0,c1,r)\mathrm{CUT}(c_0, c_1, r): remove the volume swept by a ball-end mill of radius rr, axis along +z+z, whose ball center moves on the segment from c0c_0 to c1c_1.
  • HEIGHT(i,j)\mathrm{HEIGHT}(i, j) and INSIDE(i,j,z)\mathrm{INSIDE}(i, j, z): read a height, and test zb≤z≤Hijz_b \le z \le H_{ij}.
  • VOLUME\mathrm{VOLUME}: the estimate h2∑ij(Hij−zb)h^2 \sum_{ij} (H_{ij} - z_b).

A toolpath given as cutter location data is a sequence of such moves. This page uses the ball center as the reference point of the tool. Many systems use the tip, which is the center minus rr along the axis.

Representation

The model is an nx×nyn_x \times n_y array of heights, nothing more. The grid is often the pixel grid of the screen in a view from above, so that the z-map is close to a z-buffer that is kept between frames. Two facts about the tool make one height enough:

  • The tool axis is parallel to zz, and the tool includes its shank, which goes up without end. So on each vertical line, the swept tool is a ray [zlo,∞)[z_{lo}, \infty), and the material that stays is again one segment [zb,min⁡(H,zlo)][z_b, \min(H, z_{lo})].
  • The removal is a set difference, so the order of the moves does not change the result: the final height is the minimum over all moves.

On the vertical line at qq, write d(t)d(t) for the horizontal distance from qq to the ball center c(t)=c0+t(c1−c0)c(t) = c_0 + t(c_1 - c_0). Where d(t)≤rd(t) \le r, the lowest point of the ball on the line is f(t)=cz(t)−r2−d(t)2f(t) = c_z(t) - \sqrt{r^2 - d(t)^2}. So zlo=min⁡f(t)z_{lo} = \min f(t) over the t∈[0,1]t \in [0, 1] with d(t)≤rd(t) \le r. The function ff is convex, and its minimum has a closed form, the stationary point clamped to the interval.

Operations

  1. CUT(H, c0, c1, r) ▷ ball centers c0, c1; radius r
  2. 1box ← the xy box of c0 and c1, grown by r on each side
  3. 2for each grid point q = (x_i, y_j) in box do
  4. 3zlo ← LOWEST(q, c0, c1, r)
  5. 4if zlo ≠ none and zlo < H[i][j] then
  6. 5H[i][j] ← max(zlo, z_bottom)
  7. LOWEST(q, c0, c1, r) ▷ lowest z of the swept tool on the line at q
  8. 6a ← c0.xy − q; b ← c1.xy − c0.xy; s ← c1.z − c0.z
  9. 7A ← a·a; k ← a·b; B ← b·b; R ← r² − A
  10. 8if B = 0 then ▷ a vertical move, or no move
  11. 9if R < 0 then return none
  12. 10t ← 0 if s ≥ 0 else 1; return c0.z + t s − √R
  13. 11D ← k² + B R
  14. 12if D < 0 then return none ▷ the line misses the cylinder
  15. 13lo ← max(0, (−k − √D)/B); hi ← min(1, (−k + √D)/B)
  16. 14if lo > hi then return none ▷ the line misses the end balls too
  17. 15t* ← (−k − s √(D/(B + s²)))/B ▷ the zero of f'
  18. 16t ← min(max(t*, lo), hi)
  19. 17return c0.z + t s − √(r² − |a + t b|²)

Line L1 limits the work to the grid points that the tool can reach. Lines L6 and L7 write the squared horizontal distance as g(t)=A+2kt+Bt2g(t) = A + 2kt + Bt^2. Lines L11 to L14 find the interval of tt where g(t)≤r2g(t) \le r^2, the times at which the tool is over qq. Line L15 is the zero of the derivative of ff, which lies inside that interval. Since ff is convex, line L16 clamps it to [0,1][0, 1], and line L17 evaluates ff there.

Numbers. The heights are measured quantities, so the code uses floating point. The only branches on float values are at lines L9, L12 and L14. They decide whether the tool touches the column at all, and a wrong answer there happens only when the tool is tangent to the line, where the lowest point is the equator of the ball at the height of the center. So a rounding error changes a height by a rounding error, not more. The tests compare each height with an exact rational test of membership in the swept volume, one part in 10910^9 above and below it.

Example

Take a ball-end mill of radius r=2r = 2, a grid with h=1h = 1, a block with top 33 and bottom −2-2, and one move of the ball center from c0=(1,1,3)c_0 = (1, 1, 3) to c1=(5,1,1)c_1 = (5, 1, 1). The tool goes down a slope of m=−1/2m = -1/2. Along the row y=1y = 1, the path is right above the grid points.

column qq case zloz_{lo} new HH
(0,1)(0, 1) behind the start: t=0t = 0, d=1d = 1 3−3≈1.2683 - \sqrt 3 \approx 1.268 1.2681.268
(1,1)(1, 1) on the cylinder: axis height 33 3−5≈0.7643 - \sqrt 5 \approx 0.764 0.7640.764
(2,1)(2, 1) axis height 2.52.5 2.5−5≈0.2642.5 - \sqrt 5 \approx 0.264 0.2640.264
(3,1)(3, 1) axis height 22 2−5≈−0.2362 - \sqrt 5 \approx -0.236 −0.236-0.236
(4,1)(4, 1) axis height 1.51.5 1.5−5≈−0.7361.5 - \sqrt 5 \approx -0.736 −0.736-0.736
(5,1)(5, 1) the end ball, t=1t = 1, d=0d = 0 1−2=−11 - 2 = -1 −1-1
(6,1)(6, 1) after the end, t=1t = 1, d=1d = 1 1−3≈−0.7321 - \sqrt 3 \approx -0.732 −0.732-0.732
(7,1)(7, 1) d=2d = 2: the equator of the end ball 11 11
(3,3)(3, 3) d=2d = 2 from the path line 22 22
(3,3.5)(3, 3.5) not on the grid, but d>rd > r there none unchanged

On the cylinder part, the cut is r1+m2=5≈2.236r\sqrt{1 + m^2} = \sqrt 5 \approx 2.236 below the axis, not r=2r = 2. A tilted cylinder of radius rr meets a vertical line in a longer chord than a vertical one. At (5,1)(5, 1) the cylinder would reach 1−51 - \sqrt 5, but the move ends there, and the end ball reaches only −1-1. The column at (1,1)(1, 1) is cut to 0.7640.764, below the bottom of the ball when its center was over that column, which is 11. The lowest point comes later, when the ball is past qq and lower.

Correctness

On a vertical line, a ball position at horizontal distance d≤rd \le r meets the line in a segment, and the shank above it covers the rest of the line upward. So each position removes a ray [f(t),∞)[f(t), \infty), and the move removes the union of these rays, which is the ray from min⁡f\min f. The distance d(t)2d(t)^2 is a convex quadratic, so the set of tt where the tool is over the line is an interval. On it ff is convex as a linear term plus a convex nondecreasing function of a convex function. Writing u=k+tBu = k + tB gives r2−g(t)=(D−u2)/Br^2 - g(t) = (D - u^2)/B with D=k2+BRD = k^2 + BR. This gives the interval of line L13, and shows that the derivative of ff is zero at t∗t^* of line L15. A convex function is smallest at the point of the interval nearest to its stationary point, which is line L16. Grid points outside the box of line L1 are more than rr from the path in xx or yy, so the tool misses them. The full proof is in proofs/correctness.md.

Proof: A z-map cut sets each column to the lowest point of the swept ball-end toolfull

Setting. The tool is a ball-end mill of radius r>0r > 0 with its axis parallel to zz. With the ball center at cc, the tool is the set T(c)T(c) = the closed ball of radius rr about cc, together with the half-infinite cylinder {p:(px−cx)2+(py−cy)2≤r2, pz≥cz}\{p : (p_x - c_x)^2 + (p_y - c_y)^2 \le r^2,\ p_z \ge c_z\}. A linear move takes the center along c(t)=c0+t(c1−c0)c(t) = c_0 + t(c_1 - c_0) for t∈[0,1]t \in [0, 1], and the swept volume is S=⋃t∈[0,1]T(c(t))S = \bigcup_{t \in [0,1]} T(c(t)). Fix a column point q=(qx,qy)q = (q_x, q_y) and write d(t)d(t) for the horizontal distance from qq to (cx(t),cy(t))(c_x(t), c_y(t)).

Claim. Let Θ={t∈[0,1]:d(t)≤r}\Theta = \{t \in [0, 1] : d(t) \le r\} and f(t)=cz(t)−r2−d(t)2f(t) = c_z(t) - \sqrt{r^2 - d(t)^2} on Θ\Theta. Then:

  1. S∩({q}×R)S \cap (\{q\} \times \mathbb{R}) is empty if Θ\Theta is empty, and otherwise it is {q}×[zlo,∞)\{q\} \times [z_{lo}, \infty) with zlo=min⁡Θfz_{lo} = \min_\Theta f;
  2. LOWEST of lines L6 to L17 returns None exactly when Θ\Theta is empty, and otherwise returns zloz_{lo};
  3. after CUT, each column height is min⁡(Hold,zlo)\min(H_{\text{old}}, z_{lo}), clamped at the stock bottom, and a column outside the box of line L1 has Θ\Theta empty.

All real numbers are exact in the proof. The code computes the same formulas in floating point.

Step 1 (one position). Fix tt. If d(t)>rd(t) > r, neither the ball nor the cylinder meets the vertical line at qq. If d(t)≤rd(t) \le r, let w=r2−d(t)2w = \sqrt{r^2 - d(t)^2}. The ball meets the line in [cz−w,cz+w][c_z - w, c_z + w] and the cylinder meets it in [cz,∞)[c_z, \infty). Their union is [cz−w,∞)=[f(t),∞)[c_z - w, \infty) = [f(t), \infty), since w≥0w \ge 0.

Step 2 (all positions). So the line meets SS in ⋃t∈Θ[f(t),∞)\bigcup_{t \in \Theta} [f(t), \infty). The function d(t)2d(t)^2 is a convex quadratic in tt, so Θ\Theta is a closed interval or empty. On Θ\Theta, ff is continuous, so it has a minimum zloz_{lo}, and the union is [zlo,∞)[z_{lo}, \infty). This proves part 1.

Step 3 (convexity). Write a=(c0x−qx,c0y−qy)a = (c_{0x} - q_x, c_{0y} - q_y), b=(c1x−c0x,c1y−c0y)b = (c_{1x} - c_{0x}, c_{1y} - c_{0y}), s=c1z−c0zs = c_{1z} - c_{0z}, A=a⋅aA = a \cdot a, k=a⋅bk = a \cdot b, B=b⋅bB = b \cdot b, and R=r2−AR = r^2 - A, as in lines L6 and L7. Then d(t)2=g(t)=A+2kt+Bt2d(t)^2 = g(t) = A + 2kt + Bt^2. The map φ(u)=−r2−u\varphi(u) = -\sqrt{r^2 - u} is convex and nondecreasing on (−∞,r2](-\infty, r^2], and gg is convex, so φ∘g\varphi \circ g is convex. Adding the linear term c0z+tsc_{0z} + ts keeps it convex. So ff is convex on Θ\Theta.

Step 4 (no horizontal motion). If B=0B = 0 (line L8), then g(t)=Ag(t) = A for all tt. If A>r2A > r^2, Θ\Theta is empty, and line L9 returns None. Otherwise Θ=[0,1]\Theta = [0, 1] and f(t)=c0z+ts−Rf(t) = c_{0z} + ts - \sqrt{R} is linear with slope ss, so its minimum is at t=0t = 0 when s≥0s \ge 0 and at t=1t = 1 when s<0s < 0, as in line L10.

Step 5 (the closed form). Let B>0B > 0 and put u=k+tBu = k + tB. Then g(t)=A+(u2−k2)/Bg(t) = A + (u^2 - k^2)/B, so

r2−g(t)=D−u2B,D=k2+BR.r^2 - g(t) = \frac{D - u^2}{B}, \qquad D = k^2 + BR.

Hence g(t)≤r2g(t) \le r^2 if and only if u2≤Du^2 \le D. If D<0D < 0, no real tt has g(t)≤r2g(t) \le r^2, and line L12 returns None. If D≥0D \ge 0, the real tt with g(t)≤r2g(t) \le r^2 form [ta,tb][t_a, t_b] with ta,b=(−k∓D)/Bt_{a,b} = (-k \mp \sqrt D)/B, and Θ=[ta,tb]∩[0,1]=[lo,hi]\Theta = [t_a, t_b] \cap [0, 1] = [lo, hi] of line L13. If lo>hilo > hi, Θ\Theta is empty and line L14 returns None. This proves the None cases of part 2.

Now let Θ=[lo,hi]\Theta = [lo, hi] be non-empty. Put t∗=(−k−sD/(B+s2))/Bt^* = (-k - s\sqrt{D/(B + s^2)})/B, as in line L15, so u∗=k+t∗B=−sD/(B+s2)u^* = k + t^*B = -s\sqrt{D/(B + s^2)}. If D=0D = 0 then ta=tb=t∗=−k/Bt_a = t_b = t^* = -k/B, and Θ\Theta is the single point t∗t^*, so the clamp of line L16 returns it. Let D>0D > 0. Then u∗2=s2D/(B+s2)<Du^{*2} = s^2 D/(B + s^2) < D, because B>0B > 0, so t∗t^* lies in the open interval (ta,tb)(t_a, t_b), where ff is differentiable with

f′(t)=s+g′(t)2r2−g(t)=s+uBD−u2.f'(t) = s + \frac{g'(t)}{2\sqrt{r^2 - g(t)}} = s + \frac{u\sqrt B}{\sqrt{D - u^2}}.

At t∗t^*, D−u∗2=DB/(B+s2)D - u^{*2} = DB/(B + s^2), so B/D−u∗2=B+s2/D\sqrt B/\sqrt{D - u^{*2}} = \sqrt{B + s^2}/\sqrt D, and the second term is −sD/(B+s2)⋅B+s2/D=−s-s\sqrt{D/(B + s^2)} \cdot \sqrt{B + s^2}/\sqrt D = -s. So f′(t∗)=0f'(t^*) = 0. A convex function with zero derivative at an interior point has its minimum over [ta,tb][t_a, t_b] there, and it is nonincreasing to the left of t∗t^* and nondecreasing to the right. So its minimum over the subinterval [lo,hi][lo, hi] is at the point of [lo,hi][lo, hi] nearest to t∗t^*, which is the clamp of line L16. Line L17 evaluates ff there. This proves part 2.

Step 6 (the cut). If Θ\Theta is not empty, there is a tt with d(t)≤rd(t) \le r, so ∣qx−cx(t)∣≤r|q_x - c_x(t)| \le r and ∣qy−cy(t)∣≤r|q_y - c_y(t)| \le r. Since cx(t)c_x(t) lies between c0xc_{0x} and c1xc_{1x}, qxq_x lies in [min⁡(c0x,c1x)−r,max⁡(c0x,c1x)+r][\min(c_{0x}, c_{1x}) - r, \max(c_{0x}, c_{1x}) + r], and the same holds for yy. So the columns that line L1 skips have Θ\Theta empty, and the tool does not touch them. For each other column, by part 1 the stock that remains on the line is the old interval [zbottom,Hold][z_{\text{bottom}}, H_{\text{old}}] minus [zlo,∞)[z_{lo}, \infty), whose top is min⁡(Hold,zlo)\min(H_{\text{old}}, z_{lo}), or nothing if zloz_{lo} is below the bottom. Lines L4 and L5 store exactly this, with the empty column stored as height zbottomz_{\text{bottom}}. This proves part 3.

Termination. CUT visits a finite box of columns and does a constant amount of work per column. ■\blacksquare

Remark (what the z-map does not represent). Part 1 holds because the tool has a shank that goes up forever. For a tool without a shank, or a tool that is not parallel to zz, the line can meet the swept volume in a bounded interval, and the stock left on the line is two intervals. A z-map cannot store that. The dexel representation can.

Complexity

A move whose ball centers span LxL_x by LyL_y in plan touches c=(⌊(Lx+2r)/h⌋+1)(⌊(Ly+2r)/h⌋+1)c = (\lfloor (L_x + 2r)/h \rfloor + 1)(\lfloor (L_y + 2r)/h \rfloor + 1) grid points, and LOWEST takes O(1)O(1) time on each, so a move costs O(c)O(c). A toolpath with mm moves costs O(∑c)O(\sum c). For a diagonal move the box holds many columns that the tool does not touch. A walk over the band of width 2r2r around the path, row by row, cuts this to the columns within rr of the path. A height query is O(1)O(1), and the model takes NN numbers of space. The error does not depend on the toolpath: between grid points the model knows nothing, so a feature narrower than hh can be missed, and halving hh multiplies NN and the cost of every cut by 4. Drysdale, Jerard, Schaudt and Hauck (1989) analyse how the grid spacing bounds the size of the errors that a point sample simulation can find.

Variants

  • Other tools. A flat-end mill of radius rr sweeps a different volume. On a line at horizontal distance d(t)≤rd(t) \le r from the axis, the lowest point is the tip height cz(t)c_z(t). A bull-nose (toroidal) mill gives a quartic, and many codes then sample the move at small steps and take the minimum of exact single-position heights.
  • Error maps. Store, beside each height, the height of the design surface on the same line. The difference is the stock left. A negative difference is a gouge, and a large positive one is missed material. See gouge detection.
  • Extended z-map. Some systems store more than one sample per cell, for example points on the cell edges, so that steep walls are drawn better. The model still has one interval per line.
  • Normal vectors. Jerard and coauthors (1989) cut short vectors that stand on the design surface along its normals, instead of vertical lines. This handles steep walls, which a z-map samples badly, but it needs the design surface in advance.
  • Dexels. Keep a sorted list of intervals per line, not one height. The cut becomes an interval subtraction, and undercuts are allowed. See dexel representation.
  • Voxels. A 3D grid of cells is the spatial occupancy enumeration of the stock. It allows any shape, at a cost of n3n^3 cells in place of n2n^2 heights.

When to use it

Use a z-map for 3-axis milling with a tool along zz, for roughing and finishing of dies, molds and other parts that are a function of (x,y)(x, y). It is fast, easy to draw as a height field, and easy to compare with the design surface. Do not use it for 5-axis machining, for turning, for parts with undercuts, or when the tool can come in from the side. Do not use it when the walls are steep and their position matters, because the grid samples a vertical wall at only one column.

Pitfalls

  • Ball bottom under the center. Lowering each column to cz−rc_z - r when the center passes over it is wrong for a tilted move. In the example it gives 00 at (3,1)(3, 1), but the true value is 2−52 - \sqrt 5. Use the lowest point over the whole move.
  • Sampling the move. Cutting only at the ball positions at fixed steps along a move misses the material between them, so the simulation shows ridges that the real tool removes.
  • No shank. A tool model with only the ball can leave material above the ball inside the cut. Real tools have a shank. In a z-map, model it, or the columns become two intervals that the model cannot hold.
  • Grid aliasing. A slot narrower than hh can fall between columns. Choose hh from the smallest feature to find, not from the screen.
  • Tolerances. A height that is lower than the design height by a rounding error is not a gouge. Compare with a tolerance stated in the units of the part.
  • Undercuts. A z-map cannot show them. A part that has them looks solid in the simulation.

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.

z_map_model.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/z-map-model/. The authors are listed in prov/5REJ5X.jsonl.

"""A z-map stock model for 3-axis milling with a ball-end mill.

The stock is a grid of vertical columns. Column (i, j) stands at the point
(x0 + i h, y0 + j h) and holds one number, the height of the top of the stock
there. A ball-end mill of radius r with its shank pointing up (+z) moves on a
straight line, its ball center going from c0 to c1. The tool removes, on each
vertical line, every point at or above the lowest point of the swept tool, so
a cut sets H[i][j] to min(H[i][j], zlo), where zlo is that lowest point.

zlo comes in closed form. For the column at q, the ball center at time t is
c(t) = c0 + t (c1 - c0), its horizontal distance to q is d(t), and the lowest
point of the ball on the line is f(t) = cz(t) - sqrt(r^2 - d(t)^2), defined
where d(t) <= r. f is convex, so its minimum on the interval is its
stationary point, clamped to the interval.

Heights are floats: they are measured quantities. The tests check them
against an exact Fraction membership test, to a tolerance of 1e-9.
"""

from math import ceil, floor, sqrt


def lowest_point(q, c0, c1, r):
    """Lowest z of the ball-end tool swept from c0 to c1 on the vertical line at q.

    q is (x, y); c0 and c1 are ball centers (x, y, z). Returns None if the
    line misses the swept tool.
    """
    ax, ay = c0[0] - q[0], c0[1] - q[1]  # @line L6
    bx, by = c1[0] - c0[0], c1[1] - c0[1]  # @line L6
    s = c1[2] - c0[2]  # @line L6
    a2, k, b2 = ax * ax + ay * ay, ax * bx + ay * by, bx * bx + by * by  # @line L7
    r2 = r * r - a2  # @line L7
    if b2 == 0:  # @line L8
        if r2 < 0:  # @line L9
            return None  # @line L9
        t = 0 if s >= 0 else 1  # @line L10
        return c0[2] + t * s - sqrt(r2)  # @line L10
    disc = k * k + b2 * r2  # @line L11
    if disc < 0:  # @line L12
        return None  # @line L12
    root = sqrt(disc)
    lo, hi = max(0.0, (-k - root) / b2), min(1.0, (-k + root) / b2)  # @line L13
    if lo > hi:  # @line L14
        return None  # @line L14
    t = (-k - s * sqrt(disc / (b2 + s * s))) / b2  # @line L15
    t = min(max(t, lo), hi)  # @line L16
    dx, dy = ax + t * bx, ay + t * by
    return c0[2] + t * s - sqrt(max(0.0, r * r - dx * dx - dy * dy))  # @line L17


class ZMap:
    """Heights on an nx by ny grid with spacing h and lower-left point (x0, y0)."""

    def __init__(self, nx, ny, h, top, x0=0.0, y0=0.0, bottom=0.0):
        self.nx, self.ny, self.h = nx, ny, h
        self.x0, self.y0, self.bottom = x0, y0, bottom
        self.H = [[top] * ny for _ in range(nx)]

    def point(self, i, j):
        return (self.x0 + i * self.h, self.y0 + j * self.h)

    def cut_ball_move(self, c0, c1, r):
        """Remove the volume swept by a ball-end mill moving from c0 to c1."""
        xs = (min(c0[0], c1[0]) - r, max(c0[0], c1[0]) + r)  # @line L1
        ys = (min(c0[1], c1[1]) - r, max(c0[1], c1[1]) + r)
        i0, i1 = max(0, ceil((xs[0] - self.x0) / self.h)), min(self.nx - 1, floor((xs[1] - self.x0) / self.h))
        j0, j1 = max(0, ceil((ys[0] - self.y0) / self.h)), min(self.ny - 1, floor((ys[1] - self.y0) / self.h))
        for i in range(i0, i1 + 1):  # @line L2
            for j in range(j0, j1 + 1):  # @line L2
                z = lowest_point(self.point(i, j), c0, c1, r)  # @line L3
                if z is not None and z < self.H[i][j]:  # @line L4
                    self.H[i][j] = max(z, self.bottom)  # @line L5

    def cut_path(self, centers, r):
        """Cut a polyline toolpath given by its ball centers."""
        for c0, c1 in zip(centers, centers[1:]):
            self.cut_ball_move(c0, c1, r)

    def inside(self, i, j, z):
        """True when the point at column (i, j) and height z is stock."""
        return self.bottom <= z <= self.H[i][j]

    def volume(self):
        """Volume by the column rule: each column stands for an h by h cell."""
        return sum(H - self.bottom for col in self.H for H in col) * self.h * self.h
test_z_map_model.py 129 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/z-map-model/. The authors are listed in prov/5REJ5X.jsonl.

import random
from fractions import Fraction as F

from z_map_model import ZMap, lowest_point

EPS = 1e-9


def min_quadratic(a, b, lo, hi):
    """Least value of |a + t b|^2 for t in [lo, hi], exact (a, b are tuples of Fraction)."""
    bb = sum(x * x for x in b)
    t = lo if bb == 0 else min(max(-sum(x * y for x, y in zip(a, b)) / bb, lo), hi)
    return sum((x + t * y) ** 2 for x, y in zip(a, b))


def removed(p, c0, c1, r):
    """Exact test: is the point p in the volume swept by the ball-end tool?

    The tool is the ball of radius r about c(t) plus the half-infinite
    cylinder of radius r above c(t). All numbers are Fractions.
    """
    v = tuple(c1[i] - c0[i] for i in range(3))
    w = tuple(c0[i] - p[i] for i in range(3))
    if min_quadratic(w, v, F(0), F(1)) <= r * r:  # the ball
        return True
    s, dz = v[2], p[2] - c0[2]  # the shank needs c_z(t) <= p_z
    if s == 0:
        if dz < 0:
            return False
        lo, hi = F(0), F(1)
    elif s > 0:
        lo, hi = F(0), min(F(1), dz / s)
    else:
        lo, hi = max(F(0), dz / s), F(1)
    if lo > hi:
        return False
    return min_quadratic(w[:2], v[:2], lo, hi) <= r * r


def check_column(q, c0, c1, r):
    """Compare lowest_point with the exact membership test on the line at q."""
    z = lowest_point(tuple(map(float, q)), tuple(map(float, c0)), tuple(map(float, c1)), float(r))
    if z is None:
        assert not removed((q[0], q[1], F(10 ** 6)), c0, c1, r)
        return
    assert removed((q[0], q[1], F(z + EPS)), c0, c1, r)
    assert not removed((q[0], q[1], F(z - EPS)), c0, c1, r)


def rand_point(rng, lo, hi, den=4):
    return tuple(F(rng.randint(lo * den, hi * den), den) for _ in range(3))


def test_example():
    c0, c1, r = (1.0, 1.0, 3.0), (5.0, 1.0, 1.0), 2.0
    # on the path line the cut is sqrt(1 + m^2) r = sqrt(5) below the axis (slope m = -1/2)
    for x, axis in ((1.0, 3.0), (2.0, 2.5), (3.0, 2.0), (4.0, 1.5)):
        assert abs(lowest_point((x, 1.0), c0, c1, r) - (axis - 5 ** 0.5)) < 1e-12
    # under the end center: the bottom of the end ball
    assert abs(lowest_point((5.0, 1.0), c0, c1, r) - (-1.0)) < 1e-12
    # behind the start and after the end: the end balls
    assert abs(lowest_point((0.0, 1.0), c0, c1, r) - (3.0 - 3 ** 0.5)) < 1e-12
    assert abs(lowest_point((6.0, 1.0), c0, c1, r) - (1.0 - 3 ** 0.5)) < 1e-12
    # a column 2 away from the path line only touches the ball equator
    assert abs(lowest_point((3.0, 3.0), c0, c1, r) - 2.0) < 1e-12
    assert lowest_point((3.0, 3.5), c0, c1, r) is None


def test_lowest_point_against_exact_membership():
    rng = random.Random(5)
    for _ in range(400):
        c0, c1 = rand_point(rng, -3, 3), rand_point(rng, -3, 3)
        if rng.random() < 0.2:
            c1 = (c0[0], c0[1], c1[2])  # a vertical plunge or retract
        if rng.random() < 0.1:
            c1 = (c1[0], c1[1], c0[2])  # a horizontal move
        r = F(rng.randint(2, 8), 4)
        for _ in range(8):
            q = tuple(F(rng.randint(-20, 20), 4) for _ in range(2))
            check_column(q, c0, c1, r)


def test_zmap_cut_against_exact_membership():
    rng = random.Random(17)
    for _ in range(6):
        zm = ZMap(13, 9, 0.5, 3.0, bottom=-4.0)
        moves = [rand_point(rng, 0, 6) for _ in range(4)]
        r = F(rng.randint(2, 6), 4)
        zm.cut_path([tuple(map(float, c)) for c in moves], float(r))
        for i in range(zm.nx):
            for j in range(zm.ny):
                q = (F(i, 2), F(j, 2))
                H = zm.H[i][j]
                def gone(z):
                    p = (q[0], q[1], F(z))
                    return any(removed(p, a, b, r) for a, b in zip(moves, moves[1:]))
                # every point of the column below H is stock, the top is cut or the original top
                if H < 3.0 - EPS:
                    assert gone(H + EPS)
                    if H > -4.0 + EPS:
                        assert not gone(H - EPS)
                else:
                    assert not gone(3.0 - EPS)


def test_volume_and_inside():
    zm = ZMap(4, 3, 1.0, 2.0)
    assert zm.volume() == 4 * 3 * 2.0
    zm.cut_ball_move((0.0, 0.0, 1.5), (3.0, 0.0, 1.5), 0.5)
    assert all(abs(zm.H[i][0] - 1.0) < 1e-12 for i in range(4))
    assert all(zm.H[i][j] == 2.0 for i in range(4) for j in (1, 2))
    assert zm.inside(0, 0, 0.5) and not zm.inside(0, 0, 1.5)
    assert abs(zm.volume() - (24.0 - 4.0)) < 1e-12


def test_cut_is_monotone_and_order_free():
    rng = random.Random(23)
    for _ in range(10):
        moves = [tuple(float(x) for x in rand_point(rng, 0, 5)) for _ in range(5)]
        a, b = ZMap(11, 11, 0.5, 4.0, bottom=-5.0), ZMap(11, 11, 0.5, 4.0, bottom=-5.0)
        a.cut_path(moves, 1.0)
        pairs = list(zip(moves, moves[1:]))
        rng.shuffle(pairs)
        for c0, c1 in pairs:
            b.cut_ball_move(c0, c1, 1.0)
        assert a.H == b.H

History

Anderson (1978) modelled the stock and the tool as heights over a grid to find collisions in NC programs, and later work on NC verification refers to this grid of heights as the z-map. In the 1980s the same idea served for fast shaded displays of milling, close to the z-buffer of graphics. In 1986 van Hook stored lists of depth intervals per pixel, the dexels, which allow more than one interval per line. Jerard, Drysdale, Hauck, Schaudt and Magewick (1989) compared height grids with vectors along the surface normals, and Drysdale, Jerard, Schaudt and Hauck (1989) analysed the cost and the accuracy of such discrete simulation. Choi and Jerard (1998) present the z-map as the standard model for 3-axis NC verification.

References

  1. Robert O. Anderson, Detecting and eliminating collisions in NC machining, Computer-Aided Design 10(4), 1978, 231 to 237, the stock and the tool as heights over a grid, and the collision test on it
  2. Robert B. Jerard, Robert L. Drysdale, Kenneth Hauck, Barry Schaudt and John Magewick, Methods for detecting errors in numerically controlled machining of sculptured surfaces, IEEE Computer Graphics and Applications 9(1), 1989, 26 to 39, simulation with vectors along the surface normals and with height grids, and the errors each one finds
  3. Robert L. Drysdale, Robert B. Jerard, Barry Schaudt and Ken Hauck, Discrete simulation of NC machining, Algorithmica 4(1), 1989, 33 to 60, the cost and the accuracy of point-sample simulation as a function of the grid spacing
  4. Byoung K. Choi and Robert B. Jerard, Sculptured Surface Machining, Theory and Applications, Kluwer, 1998, the part on controlling accuracy and quality, on the z-map model and NC verification

Where this leads

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.cut
  • a full proof of time.query
  • 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)
WritingW4 complete
  • a review of the text: no review record reviews/5REJ5X/text.yaml