Algorithm Search⌘K

Algorithmresearch

Collision-free tool orientation in C-space

Also called tool orientation C-space.

Maps the tool, holder and machine obstacles into the space of tool axis angles at each contact point and picks a smooth path of feasible axes, after Morishige and coauthors.

Time
O(m k n + m k^2) worst
Space
O(m k) extra
Where
k = number of candidate directions per position; m = number of tool positions; n = number of obstacle boxes
Properties
deterministicexactiterative
Origin
Koichi Morishige, Kiwamu Kase, Y. Takeuchi, 1997

Collision-free tool orientation in C-space chooses the tool axis at each point of a five-axis toolpath from a map of the directions that are free of collisions. At each tool position, every obstacle (a wall of the part, a clamp, a block of the fixture) is turned into a region of a plane whose points are tool directions, the C-space of orientations. A direction is free when it lies outside all the regions. The planner then picks one free direction per position so that the axis stays close to a preferred direction, such as the tilt of the principal axis method, and changes little from one position to the next. This is the manufacturing side of mechanical CAD, about the motion of a cutter, not the placement and routing of a circuit. The version here models the tool as a half-line from the tool center and the obstacles as boxes. In the gnomonic chart of directions each box becomes an exact polygonal shadow, the test needs only rational arithmetic, and the smooth choice is a shortest path over the layers of free directions, solved exactly by dynamic programming.

In plain words

Stand where the cutter is and look up. Some directions are open sky, and some are blocked by a wall, a post or a clamp. Draw a map of the sky with the blocked parts shaded. A tool that points into the open sky does not hit anything.

The cutter moves along a path, so you draw one such map at each stop and mark a few candidate directions in the open part. You want a good direction for cutting, but you also want the tool to swing little from stop to stop, because big swings are slow and rough.

So you pick one open direction on each map, and you score the whole choice by how far each pick is from the good direction and how far it moves between stops. The best choice is found by working through the stops one at a time.

The problem

Directions. The tool is a half-line from the tool center pp, the center of the ball of a ball end mill, in a direction dd above the horizon. Write d=(qx,qy,1)d = (q_x, q_y, 1), so the direction is a point qq of the plane. This is the gnomonic chart: q=0q = 0 is the vertical axis, and the tilt from vertical is arctan⁡∣q∣\arctan|q|. Lines through the center of the sphere of directions map to straight lines in this chart.

Obstacles. Closed boxes [x0,x1]×[y0,y1]×[z0,z1][x_0, x_1] \times [y_0, y_1] \times [z_0, z_1]. A box blocks qq at pp when the ray p+t dp + t\, d, t>0t > 0, meets it. A tool of radius rr is handled by growing each box by rr on every side, which is safe but can reject a few free directions near the edges.

Output. Given tool centers p1,…,pmp_1, \dots, p_m, a grid of candidate directions q=hgq = h g with g∈G⊂Z2g \in G \subset \mathbb{Z}^2, preferred grid points πi\pi_i and a weight ww, choose free g1,…,gmg_1, \dots, g_m that minimize

J=w∑i∣gi−πi∣2+∑i≥2∣gi−gi−1∣2.J = w \sum_i |g_i - \pi_i|^2 + \sum_{i \ge 2} |g_i - g_{i-1}|^2 .

The image of a box. With T0=max⁡(z0−pz,0)T_0 = \max(z_0 - p_z, 0), T1=z1−pzT_1 = z_1 - p_z and the rectangle Rˉ=[x0−px,x1−px]×[y0−py,y1−py]\bar R = [x_0 - p_x, x_1 - p_x] \times [y_0 - p_y, y_1 - p_y], the box blocks qq exactly when T1>0T_1 > 0 and the segment from T0qT_0 q to T1qT_1 q meets Rˉ\bar R. For a block that stands on the floor, T0=0T_0 = 0, and the blocked set is the shadow of the rectangle Rˉ/T1\bar R / T_1 seen from the origin: every qq whose segment from 00 meets it.

The algorithm

  1. PLAN-ORIENTATIONS(p[1..m], boxes, G, h, π[1..m], w)
  2. 1for i ← 1 to m do
  3. 2F_i ← {g ∈ G : for every box, the segment from T_0·hg to T_1·hg misses the rectangle}
  4. 3if F_i is empty then fail: no free direction at p_i
  5. 4C_1[g] ← w·|g − π_1|² for g ∈ F_1
  6. 5for i ← 2 to m do
  7. 6for g ∈ F_i: C_i[g] ← w·|g − π_i|² + min over g' ∈ F_{i−1} of (C_{i−1}[g'] + |g − g'|²); keep the best g' as back_i[g]
  8. 7g_m ← argmin C_m; g_{i−1} ← back_i[g_i] for i = m, …, 2
  9. 8return (min C_m, g_1, …, g_m)

Line L2 is the C-space map. The segment test is line clipping of a segment against a rectangle in parameter form, as Liang and Barsky do it, and with rational data it is exact, including directions that graze an edge or a corner. Lines L4 to L7 are a shortest path through the layers F1,…,FmF_1, \dots, F_m, the same recurrence as the Viterbi algorithm.

Example

The tool center moves toward a wall, the box [4,5]×[−10,10]×[0,6][4, 5] \times [-10, 10] \times [0, 6], along pi=(i−1,0,1)p_i = (i - 1, 0, 1) for i=1,…,4i = 1, \dots, 4. The candidates are q=(g/8,0)q = (g/8, 0) for g=−4,…,4g = -4, \dots, 4, and the preferred direction is g=4g = 4, a lead of 26.57°26.57° toward the wall.

For the wall, T0=0T_0 = 0 and T1=5T_1 = 5, so qq is blocked when 5qx≥4−px5 q_x \ge 4 - p_x (and ∣5qy∣≤10|5q_y| \le 10).

position ii pxp_x blocked when qx≥q_x \ge largest free tilt largest free gg
1 0 0.8 below 38.66°38.66° 4
2 1 0.6 below 30.96°30.96° 4
3 2 0.4 below 21.80°21.80° 3
4 3 0.2 below 11.31°11.31° 1

With w=1w = 1 the program returns g=(4,4,3,1)g = (4, 4, 3, 1) with J=(0+0+1+9)+(0+1+4)=15J = (0 + 0 + 1 + 9) + (0 + 1 + 4) = 15: it follows the preference until the wall forces it back, then drops from 20.56°20.56° to 7.13°7.13° in one step. With w=1/4w = 1/4 smoothness counts more, and it returns (3,3,2,1)(3, 3, 2, 1) with J=15/4+2=5.75J = 15/4 + 2 = 5.75: the tool starts to stand up at once, and the largest step is one grid cell. Both answers equal a search over all 949^4 choices.

At the exact grid point q=(0.4,0)q = (0.4, 0) at p3p_3, the ray goes through the top edge of the wall, (4,0,6)(4, 0, 6). The closed box counts this as a hit. A float test can decide such a case either way, and the exact test is the reason the code uses fractions.

Correctness

Theorem. Line L2 marks a grid direction as free exactly when its ray from pip_i misses every box. If every FiF_i is nonempty, the program returns the least JJ over all choices of free grid directions and a choice that attains it. With boxes grown by rr, every point of each chosen ray is more than rr from the original boxes.

The ray p+t dp + t\,d is at height pz+tp_z + t, so it is in the slab of the box for t∈[z0−pz,z1−pz]t \in [z_0 - p_z, z_1 - p_z], and for such tt it is in the box exactly when tq∈Rˉt q \in \bar R. The points tqt q form the segment of line L2, and the end t=0t = 0 does not matter because pp is outside the box. The program is optimal by the usual argument for layered shortest paths: the best choice that ends in gg at layer ii is a best choice ending at some g′g' at layer i−1i - 1, plus the step. The full proof is in the proof file.

What is exact is the test and the optimum over the grid for this cost. The model is not exact: a half-line or a grown box is not a full tool with its holder, and the grid can miss a narrow free gap. The tests compare line L2 with a direct slab test of the 3D ray against each box, in exact fractions, on random boxes and on directions aimed exactly at edges and corners, and compare the program with a search over all choices.

Proof: The shadow test marks exactly the directions whose ray meets a box, and the layered dynamic program returns a cheapest choice of free grid directionsfull

Setting. A box is a closed set B=[x0,x1]×[y0,y1]×[z0,z1]B = [x_0, x_1] \times [y_0, y_1] \times [z_0, z_1]. A tool center is a point pp that lies in no box. A direction above the horizon is written d(q)=(qx,qy,1)d(q) = (q_x, q_y, 1) with q∈R2q \in \mathbb{R}^2, and the box blocks qq at pp when the ray {p+t d(q):t>0}\{p + t\, d(q) : t > 0\} meets BB. Write T0=max⁡(z0−pz,0)T_0 = \max(z_0 - p_z, 0), T1=z1−pzT_1 = z_1 - p_z, and Rˉ=[x0−px,x1−px]×[y0−py,y1−py]\bar R = [x_0 - p_x, x_1 - p_x] \times [y_0 - p_y, y_1 - p_y]. The grid is a finite set G⊂Z2G \subset \mathbb{Z}^2 with a step h>0h > 0, and the grid point gg stands for q=hgq = h g. The planner gets tool centers p1,…,pmp_1, \dots, p_m, boxes B\mathcal{B}, preferred grid points π1,…,πm\pi_1, \dots, \pi_m and a weight w≥0w \ge 0, and minimizes

J(g1,…,gm)=w∑i=1m∣gi−πi∣2+∑i=2m∣gi−gi−1∣2J(g_1, \dots, g_m) = w \sum_{i=1}^m |g_i - \pi_i|^2 + \sum_{i=2}^m |g_i - g_{i-1}|^2

over the choices with gi∈Fig_i \in F_i, the free grid points at pip_i.

Lemma 1 (the C-space image of a box). BB blocks qq at pp if and only if T1>0T_1 > 0 and the closed segment from T0qT_0 q to T1qT_1 q meets Rˉ\bar R.

Proof. The point p+t d(q)p + t\, d(q) has height pz+tp_z + t, so it is in the slab z0≤z≤z1z_0 \le z \le z_1 exactly for t∈[z0−pz,z1−pz]t \in [z_0 - p_z, z_1 - p_z]. With t>0t > 0 this is the set I=[T0,T1]∖{0}I = [T_0, T_1] \setminus \{0\}, which is empty when T1≤0T_1 \le 0. For t∈It \in I, the point is in BB exactly when its horizontal part pxy+tqp_{xy} + t q is in the rectangle, that is when tq∈Rˉt q \in \bar R. So BB blocks qq if and only if tq∈Rˉt q \in \bar R for some t∈It \in I. The points tqt q for t∈[T0,T1]t \in [T_0, T_1] form the segment of the lemma. It remains to see that excluding t=0t = 0 changes nothing. If T0>0T_0 > 0, then 0∉[T0,T1]0 \notin [T_0, T_1]. If T0=0T_0 = 0, then z0≤pzz_0 \le p_z, and T1>0T_1 > 0 gives pz<z1p_z < z_1, so pp lies in the slab; as p∉Bp \notin B, pxyp_{xy} is not in the rectangle, that is 0⋅q=0∉Rˉ0 \cdot q = 0 \notin \bar R, and the point t=0t = 0 of the segment is not in Rˉ\bar R. □\square

The function segment_meets_rect is Liang and Barsky clipping: it intersects the parameter interval [0,1][0, 1] with the closed interval of parameters for which each coordinate lies in its range, and reports a hit when the result is not empty. With rational inputs every step is exact, so the test decides Lemma 1 without rounding.

Lemma 2 (growing boxes is safe). Let BrB_r be BB grown by r≥0r \ge 0 on each side. If BrB_r does not block qq at pp, then every point of the ray is at Euclidean distance more than rr from BB.

Proof. A point xx outside BrB_r has some coordinate more than rr outside the range of BB, so its distance to BB in the maximum norm exceeds rr, and the Euclidean distance is at least the maximum norm distance. □\square

So a cylinder of radius rr about the ray does not meet BB: the test is conservative, and it can reject directions that are in fact free for the cylinder, near the edges of the box.

Lemma 3 (the dynamic program). For i≥1i \ge 1 and g∈Fig \in F_i let

Ci(g)=min⁡{Ji(g1,…,gi):gj∈Fj, gi=g},Ji=w∑j≤i∣gj−πj∣2+∑2≤j≤i∣gj−gj−1∣2.C_i(g) = \min \{ J_i(g_1, \dots, g_i) : g_j \in F_j,\ g_i = g \},\quad J_i = w \sum_{j \le i} |g_j - \pi_j|^2 + \sum_{2 \le j \le i} |g_j - g_{j-1}|^2 .

Then line L4 sets cost to C1C_1, and after the pass of line L6 for layer ii, cost equals CiC_i.

Proof. For i=1i = 1, J1=w∣g1−π1∣2J_1 = w|g_1 - \pi_1|^2, which line L4 computes. Let i≥2i \ge 2 and assume cost =Ci−1= C_{i-1}. Every feasible (g1,…,gi)(g_1, \dots, g_i) with gi=gg_i = g splits as a feasible prefix ending in some h∈Fi−1h \in F_{i-1} and the last step, and Ji=Ji−1(g1,…,gi−1)+w∣g−πi∣2+∣g−h∣2J_i = J_{i-1}(g_1, \dots, g_{i-1}) + w|g - \pi_i|^2 + |g - h|^2. Minimizing first over the prefixes that end in hh gives Ci−1(h)C_{i-1}(h), and then over hh gives Ci(g)=w∣g−πi∣2+min⁡h(Ci−1(h)+∣g−h∣2)C_i(g) = w|g - \pi_i|^2 + \min_h \big(C_{i-1}(h) + |g - h|^2\big), which line L6 computes. □\square

Theorem. If every FiF_i is nonempty, plan_orientations returns min⁡J\min J over all choices of free grid points and a choice that attains it. Every direction of the choice is free at its point, by Lemma 1 exactly for the given boxes, and by Lemma 2 with clearance rr when the boxes were grown by rr. If some FiF_i is empty, line L3 reports it, and no choice exists.

Proof. Line L2 builds FiF_i by Lemma 1. By Lemma 3, after the last layer cost =Cm= C_m, and min⁡J=min⁡gCm(g)\min J = \min_g C_m(g), which line L7 takes. The back pointers record, for each gg in layer ii, an hh that attains the minimum of Lemma 3, so following them from the best gg in layer mm gives a choice (g1,…,gm)(g_1, \dots, g_m) whose cost adds up, step by step, to Cm(gm)C_m(g_m). All FiF_i are finite, so all loops end. ■\blacksquare

Remarks. (1) The optimality is over the grid and for this cost. A finer grid, or another cost, such as a bound on the angle between neighbors or the cost of the rotary axes of a machine, can change the answer. (2) The tool is a half-line, or a cylinder after growing the boxes. The holder, the spindle, and the swept volume between two tool positions are not checked. (3) The tests compare the shadow test with a direct slab test of the ray against each box, with exact fractions, on random boxes and on directions aimed exactly at the edges and corners of boxes, and they compare the dynamic program with a search over all choices.

Complexity

Building the free sets tests each of kk grid directions against each of nn boxes at each of mm positions, O(mkn)O(mkn) time. Line L6 compares every pair of directions in neighboring layers, O(mk2)O(mk^2) time, and the back pointers take O(mk)O(mk) space. A grid of 41×4141 \times 41 directions, 1000 positions and 50 boxes is about 8.4⋅1078.4 \cdot 10^7 box tests and 2.8⋅1092.8 \cdot 10^9 pair steps, so real systems restrict the steps to a window of nearby directions, which brings line L6 down to O(mk s)O(mk\,s) for a window of ss cells, or rasterize the shadows of the boxes on the grid instead of testing every pair.

Properties

  • Exact test. The C-space image of a box is computed with rational arithmetic, with no tolerance.
  • Conservative for thick tools. Growing the boxes by the tool radius never accepts a colliding direction.
  • Optimal on the grid. The dynamic program finds the best choice for the stated cost.
  • Local in space. Each position is tested on its own. Collisions of the tool while it moves between two positions are not tested.
  • Above the horizon. The chart covers directions with a positive vertical part, which is the range of most five-axis machines.

Variants and improvements

  • Angle charts. Morishige, Kase and Takeuchi used two angles of the tool axis as the coordinates of the C-space. The gnomonic chart here makes box shadows polygons. Other obstacles, such as triangles of a mesh, also map to polygons in it.
  • Feasible regions and smoothing. Jun, Cha and Lee (2003) built at each contact point a feasible region bounded by gouge and collision limits and smoothed the orientations by searching forward and backward along the path.
  • Full tool shapes. A tool with a holder is a stack of cylinders and cones. Each part maps to its own C-space region, found by distance tests, by ray casting from many points of the tool, or on graphics hardware.
  • Machine axes. The cost can be measured in the rotary angles of the machine instead of in the chart, which adds the kinematics and the pole singularity of the orientation problem.
  • Accessibility maps. Over a whole region, the intersection of the free sets is an accessibility cone, used to choose fixed axes for 3+2 machining.

When to use it

Use a C-space planner when a five-axis path runs close to walls, between blades of an impeller, or past clamps, and the tool must lean away from them. Use the principal axis method or another local method to get the preferred direction, and the C-space step to make it safe and smooth. On open parts with no nearby obstacles, a local method alone is enough.

Pitfalls

  • Ray instead of tool. A collision test of the axis line alone misses collisions of the body of the tool. Grow the obstacles by the radius, or test the full tool.
  • Float tests at edges. A direction that grazes an edge or a corner of an obstacle is decided by the sign of a rounding error in float code. Use exact arithmetic, or a margin that is applied the same way everywhere.
  • Grid gaps. A narrow free gap between two obstacles can fall between grid directions. A finer grid near the boundary of the free set helps.
  • Moves between positions. Two free positions can be joined by a move that collides, when the tool swings through an obstacle. Check the swept volume of each move.
  • Gouges. Collision-free is not gouge-free. A direction that misses all obstacles can still cut into the part near the contact point. Combine with gouge detection.
  • Too strong a preference. With a large weight on the preferred direction, the path follows it until an obstacle forces a sudden turn, as in the example with w=1w = 1.

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.

collision_free_tool_orientation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/collision-free-tool-orientation/. The authors are listed in prov/E9RNYT.jsonl.

"""Collision-free tool orientation in a two-dimensional C-space of directions.

The tool is a half-line from the tool center p (for a ball end mill, the
center of the ball) in the direction d. Obstacles are closed axis-aligned
boxes (x0, x1, y0, y1, z0, z1): blocks of a terrain, walls, clamps. A tool
of radius r is handled by growing every box by r on each side, which can
only remove free directions.

Directions above the horizon are written in the gnomonic chart
d = (qx, qy, 1), so the C-space at p is the plane of q. A box blocks q at p
when the ray p + t (q, 1), t > 0, meets it. With T0 = max(z0 - pz, 0) and
T1 = z1 - pz, this happens exactly when the segment from T0 q to T1 q in the
plane meets the rectangle [x0 - px, x1 - px] x [y0 - py, y1 - py]. So each box
maps to an exact region of the C-space, the shadow of its rectangle, and
the test uses only rational arithmetic.

The planner takes a grid of candidate directions, keeps the free ones at
each point, and picks one per point by dynamic programming over the layers,
minimizing

    w * sum |g_i - pref_i|^2 + sum |g_i - g_(i-1)|^2

over integer grid points g_i, where the direction of g is q = g * step.
"""

from fractions import Fraction


def segment_meets_rect(a, b, rect):
    """Whether the closed segment from a to b meets the closed rectangle.

    a and b are points (x, y); rect is (x0, x1, y0, y1). Exact with ints or
    Fractions (Liang-Barsky clipping).
    """
    lo, hi = Fraction(0), Fraction(1)
    for k, (m0, m1) in enumerate(((rect[0], rect[1]), (rect[2], rect[3]))):
        s, e = a[k], b[k] - a[k]
        if e == 0:
            if s < m0 or s > m1:
                return False
            continue
        t0, t1 = Fraction(m0 - s) / e, Fraction(m1 - s) / e
        if t0 > t1:
            t0, t1 = t1, t0
        lo, hi = max(lo, t0), min(hi, t1)
        if lo > hi:
            return False
    return True


def box_blocks(p, box, q):
    """Whether the box blocks the direction q = (qx, qy) at the tool center p."""
    x0, x1, y0, y1, z0, z1 = box
    t1 = z1 - p[2]
    if t1 <= 0:
        return False  # the box is below the tool center
    t0 = max(z0 - p[2], 0)
    rect = (x0 - p[0], x1 - p[0], y0 - p[1], y1 - p[1])
    return segment_meets_rect((t0 * q[0], t0 * q[1]), (t1 * q[0], t1 * q[1]), rect)


def grow(box, r):
    """The box grown by r on each side, a conservative stand-in for a tool of radius r."""
    x0, x1, y0, y1, z0, z1 = box
    return (x0 - r, x1 + r, y0 - r, y1 + r, z0 - r, z1 + r)


def free_directions(p, boxes, grid, step):
    """The grid points g whose direction q = g * step no box blocks at p."""
    return [g for g in grid if not any(box_blocks(p, b, (g[0] * step, g[1] * step)) for b in boxes)]


def _d2(g, h):
    return (g[0] - h[0]) ** 2 + (g[1] - h[1]) ** 2


def plan_orientations(points, boxes, grid, step, pref, w=1):
    """One free grid direction per tool center, at least total cost.

    Returns (cost, [g_1, ..., g_m]). Raises ValueError if some point has no
    free direction on the grid.
    """
    free = []
    for i, p in enumerate(points):  # @line L1
        f = free_directions(p, boxes, grid, step)  # @line L2
        if not f:  # @line L3
            raise ValueError("no free direction on the grid at point %d" % i)
        free.append(f)
    cost = {g: w * _d2(g, pref[0]) for g in free[0]}  # @line L4
    back = [None]
    for i in range(1, len(points)):  # @line L5
        new, ptr = {}, {}
        for g in free[i]:  # @line L6
            h = min(cost, key=lambda h: (cost[h] + _d2(g, h), h))
            new[g] = w * _d2(g, pref[i]) + cost[h] + _d2(g, h)
            ptr[g] = h
        cost = new
        back.append(ptr)
    g = min(cost, key=lambda h: (cost[h], h))  # @line L7
    best = cost[g]
    path = [g]
    for i in range(len(points) - 1, 0, -1):
        g = back[i][g]
        path.append(g)
    path.reverse()
    return best, path  # @line L8
test_collision_free_tool_orientation.py 189 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/collision-free-tool-orientation/. The authors are listed in prov/E9RNYT.jsonl.

import itertools
import math
import random
from fractions import Fraction as F

import pytest

from collision_free_tool_orientation import (
    box_blocks,
    free_directions,
    grow,
    plan_orientations,
)


def ray_hits_box(p, d, box):
    """Reference: slab test of the ray p + t d, t > 0, against the closed box, exactly."""
    lo, hi = None, None  # the set of t, as an interval
    for k in range(3):
        m0, m1 = box[2 * k], box[2 * k + 1]
        if d[k] == 0:
            if p[k] < m0 or p[k] > m1:
                return False
            continue
        t0, t1 = F(m0 - p[k]) / d[k], F(m1 - p[k]) / d[k]
        if t0 > t1:
            t0, t1 = t1, t0
        lo = t0 if lo is None else max(lo, t0)
        hi = t1 if hi is None else min(hi, t1)
    if hi is None:
        return True  # d = 0 does not happen here
    return lo <= hi and hi > 0


def inside(p, box):
    return all(box[2 * k] <= p[k] <= box[2 * k + 1] for k in range(3))


def random_box(rng):
    x0, y0 = F(rng.randint(-12, 10), 2), F(rng.randint(-12, 10), 2)
    z0 = F(rng.choice([0, 0, rng.randint(0, 8)]), 2)
    return (x0, x0 + F(rng.randint(1, 6), 2), y0, y0 + F(rng.randint(1, 6), 2), z0, z0 + F(rng.randint(1, 10), 2))


def random_center(rng, boxes):
    while True:
        p = (F(rng.randint(-8, 8), 3), F(rng.randint(-8, 8), 3), F(rng.randint(1, 12), 3))
        if not any(inside(p, b) for b in boxes):
            return p


def test_cspace_test_equals_ray_test_random():
    rng = random.Random(11)
    for _ in range(3000):
        box = random_box(rng)
        p = random_center(rng, [box])
        q = (F(rng.randint(-20, 20), rng.randint(1, 6)), F(rng.randint(-20, 20), rng.randint(1, 6)))
        assert box_blocks(p, box, q) == ray_hits_box(p, (q[0], q[1], 1), box)


def test_cspace_test_equals_ray_test_on_edges_and_corners():
    # Directions aimed exactly at corners and edges of a box, where floats would fail.
    rng = random.Random(12)
    count = 0
    for _ in range(400):
        box = random_box(rng)
        p = random_center(rng, [box])
        for cx in box[0:2]:
            for cy in box[2:4]:
                for cz in box[4:6]:
                    if cz <= p[2]:
                        continue
                    t = cz - p[2]
                    for dx, dy in [(0, 0), (F(1, 1000), 0), (0, F(-1, 1000))]:
                        q = ((cx - p[0]) / t + dx, (cy - p[1]) / t + dy)
                        assert box_blocks(p, box, q) == ray_hits_box(p, (q[0], q[1], 1), box)
                        count += 1
    assert count > 500


def test_wall_and_post_example():
    p = (0, 0, 1)
    wall = (2, 3, -5, 5, 0, 6)
    post = (-3, -2, -1, 1, 0, 4)
    assert box_blocks(p, wall, (F(2, 5), 0))  # exactly at the top edge of the wall
    assert not box_blocks(p, wall, (F(2, 5) - F(1, 1000), 0))
    assert box_blocks(p, post, (F(-2, 3), 0))
    assert not box_blocks(p, post, (F(-2, 3) + F(1, 1000), 0))
    assert math.isclose(math.degrees(math.atan(0.4)), 21.80140948635181)
    assert math.isclose(math.degrees(math.atan(2 / 3)), 33.690067525979785)


def grid_of(k):
    return [(a, b) for a in range(-k, k + 1) for b in range(-k, k + 1)]


def test_free_set_equals_direct_ray_tests():
    rng = random.Random(13)
    grid = grid_of(4)
    step = F(1, 4)
    for _ in range(40):
        boxes = [random_box(rng) for _ in range(5)]
        p = random_center(rng, boxes)
        got = free_directions(p, boxes, grid, step)
        want = [g for g in grid if not any(ray_hits_box(p, (g[0] * step, g[1] * step, 1), b) for b in boxes)]
        assert got == want


def test_grown_boxes_keep_the_tool_clear():
    # A direction that is free for boxes grown by r keeps the whole ray at
    # least r away from the boxes (checked on samples along the ray).
    rng = random.Random(14)
    r = F(1, 2)
    grid = grid_of(4)
    step = F(1, 4)
    for _ in range(20):
        boxes = [random_box(rng) for _ in range(4)]
        grown = [grow(b, r) for b in boxes]
        p = random_center(rng, grown)
        for g in free_directions(p, grown, grid, step):
            d = (float(g[0] * step), float(g[1] * step), 1.0)
            for k in range(1, 200):
                t = k * 0.1
                x = [float(p[i]) + t * d[i] for i in range(3)]
                for b in boxes:
                    dist2 = sum(max(float(b[2 * i]) - x[i], 0.0, x[i] - float(b[2 * i + 1])) ** 2 for i in range(3))
                    assert dist2 >= float(r) ** 2 - 1e-9


def brute_force(points, boxes, grid, step, pref, w):
    free = [free_directions(p, boxes, grid, step) for p in points]
    best = None
    for choice in itertools.product(*free):
        c = sum(w * ((g[0] - pr[0]) ** 2 + (g[1] - pr[1]) ** 2) for g, pr in zip(choice, pref))
        c += sum((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 for a, b in zip(choice, choice[1:]))
        if best is None or c < best:
            best = c
    return best


@pytest.mark.parametrize("seed", range(6))
def test_dynamic_program_equals_brute_force(seed):
    rng = random.Random(100 + seed)
    grid = grid_of(2)
    step = F(1, 2)
    while True:
        boxes = [random_box(rng) for _ in range(4)]
        points = [random_center(rng, boxes) for _ in range(3)]
        if all(free_directions(p, boxes, grid, step) for p in points):
            break
    pref = [(rng.randint(-2, 2), rng.randint(-2, 2)) for _ in points]
    w = rng.choice([1, 2, 5])
    cost, path = plan_orientations(points, boxes, grid, step, pref, w)
    assert cost == brute_force(points, boxes, grid, step, pref, w)
    # the returned path is free and has the returned cost
    for p, g in zip(points, path):
        assert g in free_directions(p, boxes, grid, step)
    c = sum(w * ((g[0] - pr[0]) ** 2 + (g[1] - pr[1]) ** 2) for g, pr in zip(path, pref))
    c += sum((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 for a, b in zip(path, path[1:]))
    assert c == cost


def test_path_along_a_wall():
    # The example of the page: the tool moves toward a wall with a preferred lead q = (1/2, 0).
    wall = (4, 5, -10, 10, 0, 6)
    points = [(0, 0, 1), (1, 0, 1), (2, 0, 1), (3, 0, 1)]
    grid = [(a, 0) for a in range(-4, 5)]
    step = F(1, 8)
    pref = [(4, 0)] * 4
    free = [free_directions(p, [wall], grid, step) for p in points]
    assert [max(g[0] for g in f) for f in free] == [4, 4, 3, 1]
    cost, path = plan_orientations(points, [wall], grid, step, pref, w=1)
    assert path == [(4, 0), (4, 0), (3, 0), (1, 0)]
    assert cost == 0 + 0 + (1 + 1) + (9 + 4)
    # with a smaller weight on the preference, the path tilts back earlier
    cost, path = plan_orientations(points, [wall], grid, step, pref, w=F(1, 4))
    assert path == [(3, 0), (3, 0), (2, 0), (1, 0)]
    assert cost == F(1 + 1 + 4 + 9, 4) + (0 + 1 + 1)
    assert cost == brute_force(points, [wall], grid, step, pref, F(1, 4))


def test_no_free_direction():
    box = (-5, 5, -5, 5, 0, 10)
    with pytest.raises(ValueError):
        plan_orientations([(0, 0, 11)], [(-5, 5, -5, 5, 11, 20)], grid_of(1), F(1), [(0, 0)])
    assert free_directions((0, 0, 11), [box], grid_of(1), F(1)) == grid_of(1)

History

Lozano-Pérez (1983) introduced the configuration space for spatial planning, in which a moving object is a point and the obstacles grow into regions. Morishige, Kase and Takeuchi (1997) applied the idea to five-axis machining with a two-dimensional C-space of tool directions at each point of the path, and Morishige, Takeuchi and Kase (1999) extended it. Jun, Cha and Lee (2003) used feasible regions in a C-space of two angles together with gouge limits, and optimized and smoothed the orientation along the path. The exact shadow test and the layered dynamic program on this page are a compact form of the same scheme.

References

  1. Koichi Morishige, Kiwamu Kase and Y. Takeuchi, Collision-free tool path generation using 2-dimensional C-space for 5-axis control machining, The International Journal of Advanced Manufacturing Technology 13(6), 393-400, 1997, the two-dimensional C-space of tool directions at a contact point and the choice of collision-free directions in it
  2. Cha-Soo Jun, Kyungduck Cha and Yuan-Shin Lee, Optimizing tool orientations for 5-axis machining by configuration-space search method, Computer-Aided Design 35(6), 549-566, 2003, the feasible region of tool orientations in the space of two angles and the smoothing of the orientations along the path in both directions
  3. Tomás Lozano-Pérez, Spatial planning, a configuration space approach, IEEE Transactions on Computers C-32(2), 108-120, 1983, the configuration space and the images of obstacles in it
  4. You-Dong Liang and Brian A. Barsky, A new concept and method for line clipping, ACM Transactions on Graphics 3(1), 1-22, 1984, the parametric clipping of a segment against a rectangle, used for the exact test of a direction against a box

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example