brokkr_kitbash/route.py: a hose's path from waypoints and a distance oracle (cut kit-hose)

grid, wavefront, pull and leg search a leg; fillet rounds the polyline by each corner's measured room; sag lowers a
span by half its room (ruling hose-slack-and-skinned); passes turns the child's side through a pin's rolls; frames
are rotation minimising. numpy only; tests/test_route.py.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-12-02 16:18:21 +01:00
commit 0db85abd96
2 changed files with 694 additions and 0 deletions

View file

@ -0,0 +1,398 @@
"""The path of a hose: from waypoints and a distance oracle to a curve with frames. numpy only, tested without
Blender (tests/test_route.py); brokkr_kitbash.hose is the bpy around it (docs/kitbash.md, Hoses between sockets).
A `distance` is a callable over (N, 3) points that answers how far each stands from the nearest obstacle; the caller
owns what an obstacle is and may cap the answer. `need` is how far a hose's centre line must stay from every
obstacle: the bundle's half width plus its clearance.
A leg between two waypoints is searched on a voxel grid of the box around them (grid, wavefront), then pulled taut
(pull). A voxel is free when it stands need plus half a voxel's diagonal from every obstacle: distance changes by at
most the distance moved, so every point of a step between two neighbouring free voxels keeps need. The legs joined are
one polyline; fillet rounds its corners, each by the largest arc its measured room allows, and verify measures the
curve. sag lowers the middle of a leg by what its room allows. passes turns the part of a polyline beyond a point on
a pin's axis through the pin's rolls and measures each. frames gives the rotation-minimising ups the tubes are swept
with (Wang, Juettler, Zheng and Liu, "Computation of rotation minimizing frames", ACM TOG 27(1), 2008: the double
reflection method).
Every refusal is a RouteError that names the leg, corner, point or roll.
"""
from __future__ import annotations
import math
from typing import NamedTuple
import numpy as np
class RouteError(ValueError):
"""A route that cannot be made, in words that name where."""
NEIGHBOURS = [(i, j, k) for i in (-1, 0, 1) for j in (-1, 0, 1) for k in (-1, 0, 1) if (i, j, k) != (0, 0, 0)]
REACH = math.sqrt(3.0) / 2.0 # of a voxel: how far a point of a step between two neighbouring voxels can stand from the nearer one
STRAIGHT = 1e-9 # radians: a corner that turns less is no corner
HELD = 1e-9 # metres under need that a reading may stand and hold it
ARC = 24 # arc segments a radian of turn
def spot(point) -> str:
return "[" + ", ".join(f"{float(v):.4g}" for v in point) + "]"
def bundle(count: int, radius: float, spread: float, clearance: float, bend: float) -> dict:
"""The sizes a bundle of `count` hoses of `radius` routes by. spread is centre to centre (0: 2.6 radii). width is
across the bundle; envelope its half; need is how far the centre line stays from obstacles; floor the least
radius of the centre line, bend outside diameters for the innermost hose, which runs half the bundle's spread
inside it; lead the straight a fitting keeps: a ferrule of 5 radii, then 1.5 outside diameters before any bend."""
spread = spread if spread > 0.0 else 2.6 * radius
half = (count - 1) / 2.0 * spread
return {"spread": spread, "width": 2.0 * half + 2.0 * radius, "envelope": half + radius, "need": half + radius + clearance,
"floor": bend * 2.0 * radius + half, "lead": 5.0 * radius + 1.5 * 2.0 * radius}
class Grid(NamedTuple):
"""Voxels of a box: free[i, j, k] is the voxel centred at lo + step * (i, j, k)."""
free: np.ndarray
lo: np.ndarray
step: float
def grid(lo, hi, step: float, distance, need: float, limit: int = 2 ** 19) -> Grid:
"""The voxels of the box lo..hi at `step` that stand at least `need` from every obstacle. Refuses a box of more
than `limit` voxels, naming a step that fits."""
lo, hi = np.asarray(lo, dtype=np.float64), np.asarray(hi, dtype=np.float64)
shape = lambda s: np.maximum(1, np.ceil((hi - lo) / s - 1e-9).astype(np.int64) + 1) # noqa: E731
n = shape(step)
if int(n.prod()) > limit:
fits = step
while int(shape(fits).prod()) > limit:
fits *= 1.05
raise RouteError(f"its search box of {spot(hi - lo)} m is {int(n.prod())} voxels at step {step:g}, over {limit}: a step of {math.ceil(fits * 1e4) / 1e4:g} fits")
axes = [lo[i] + step * np.arange(n[i]) for i in range(3)]
points = np.stack(np.meshgrid(*axes, indexing="ij"), axis=-1).reshape(-1, 3)
return Grid(free=(np.asarray(distance(points)) >= need).reshape(n), lo=lo, step=float(step))
def wavefront(free: np.ndarray, start, goal) -> list:
"""The voxels of a shortest 26-connected way from start to goal through free voxels, both ends included: a
wavefront grown from the goal by array shifts, then walked down from the start, at each step to the neighbour one
wave nearer that stands nearest the goal. Refuses an end that is not free, and a start no wave reaches."""
start, goal, n = tuple(int(v) for v in start), tuple(int(v) for v in goal), free.shape
for name, voxel in (("start", start), ("end", goal)):
if not free[voxel]:
raise RouteError(f"its {name} voxel is not free")
unreached = np.iinfo(np.int32).max
waves = np.full(n, unreached, dtype=np.int32)
waves[goal] = 0
front = np.zeros(n, dtype=bool)
front[goal] = True
wave = 0
while waves[start] == unreached and front.any():
wave += 1
padded, grown = np.pad(front, 1), np.zeros(n, dtype=bool)
for i, j, k in NEIGHBOURS:
grown |= padded[1 + i:1 + i + n[0], 1 + j:1 + j + n[1], 1 + k:1 + k + n[2]]
front = grown & free & (waves == unreached)
waves[front] = wave
if waves[start] == unreached:
raise RouteError("no free way joins its ends: obstacles close every way through its search box")
way, at = [start], start
while waves[at] > 0:
nearer = [(math.dist(m, goal), m) for m in ((at[0] + i, at[1] + j, at[2] + k) for i, j, k in NEIGHBOURS)
if all(0 <= m[axis] < n[axis] for axis in range(3)) and waves[m] == waves[at] - 1]
at = min(nearer)[1]
way.append(at)
return way
def along(a, b, spacing: float) -> np.ndarray:
"""Points from a to b, both included, no further apart than spacing."""
a, b = np.asarray(a, dtype=np.float64), np.asarray(b, dtype=np.float64)
count = max(2, int(math.ceil(float(np.linalg.norm(b - a)) / spacing)) + 1)
return a[None] + (b - a)[None] * np.linspace(0.0, 1.0, count)[:, None]
def clear(a, b, distance, need: float, spacing: float) -> bool:
return bool((np.asarray(distance(along(a, b, spacing))) >= need - HELD).all())
def pull(points, distance, need: float, spacing: float) -> np.ndarray:
"""A polyline pulled taut: from each kept point, the farthest later point in clear sight (need kept at samples no
further apart than spacing); the next point when none is."""
points = np.asarray(points, dtype=np.float64)
kept, i = [points[0]], 0
while i < len(points) - 1:
j = len(points) - 1
while j > i + 1 and not clear(points[i], points[j], distance, need, spacing):
j -= 1
kept.append(points[j])
i = j
return np.array(kept)
def leg(a, b, occupancy, distance, need: float, step: float, margin: float, limit: int, name: str):
"""(the pulled polyline from a to b, the voxels searched): a grid over the two ends' box plus margin, free where
`occupancy` reads need plus REACH of a voxel, a wavefront between the free voxels beside the ends, pulled at need
against `distance`. Refuses, naming the leg: an end nearer an obstacle than need, an end with no free voxel in
sight beside it, a box over the limit, and no way through."""
a, b = np.asarray(a, dtype=np.float64), np.asarray(b, dtype=np.float64)
for label, point in (("start", a), ("end", b)):
reads = float(np.asarray(distance(point[None]))[0])
if reads < need - HELD:
raise RouteError(f"{name}: its {label} {spot(point)} stands {reads:.4g} m from an obstacle, under the {need:.4g} m the bundle needs")
try:
cells = grid(np.minimum(a, b) - margin, np.maximum(a, b) + margin, step, occupancy, need + REACH * step, limit)
except RouteError as error:
raise RouteError(f"{name}: {error}") from None
ends = []
for label, point in (("start", a), ("end", b)):
middle = np.clip(np.round((point - cells.lo) / step).astype(int), 0, np.array(cells.free.shape) - 1)
beside = [tuple(int(v) for v in middle + np.array(d)) for d in [(0, 0, 0)] + NEIGHBOURS]
beside = [m for m in beside if all(0 <= m[axis] < cells.free.shape[axis] for axis in range(3)) and cells.free[m]]
beside.sort(key=lambda m: float(np.linalg.norm(cells.lo + step * np.array(m) - point)))
seen = [m for m in beside if clear(point, cells.lo + step * np.array(m), distance, need, step / 2.0)]
if not seen:
raise RouteError(f"{name}: no free voxel stands in sight of its {label} {spot(point)}: an obstacle is nearer it than {need + REACH * step:.4g} m on every side")
ends.append(seen[0])
try:
way = wavefront(cells.free, ends[0], ends[1])
except RouteError as error:
raise RouteError(f"{name}: {error}") from None
return pull(np.vstack([a[None], cells.lo + step * np.array(way, dtype=np.float64), b[None]]), distance, need, step / 2.0), int(cells.free.size)
def sag(points, depth: float, room, down=(0.0, 0.0, -1.0)):
"""(the polyline, the metres it was lowered): the middle of a leg's longest segment lowered by `depth`, less where
the segment runs along `down` (a hanging span sags, a vertical one does not) and never by more than half the room
`room(a, b)` measures along that segment: both halves then stand within that much of the taut segment, so they keep
need with as much room again for the arc at the middle. A segment shorter than 8 times the drop is left taut."""
points = np.asarray(points, dtype=np.float64)
lengths = np.linalg.norm(np.diff(points, axis=0), axis=1)
i = int(np.argmax(lengths))
a, b = points[i], points[i + 1]
across = np.asarray(down, dtype=np.float64) - (b - a) / lengths[i] * float(np.asarray(down) @ (b - a) / lengths[i])
hang = float(np.linalg.norm(across))
if depth <= 0.0 or hang < 1e-6:
return points, 0.0
drop = min(depth, 0.5 * (math.inf if room is None else float(room(a, b)))) * hang
if drop <= 1e-6 or lengths[i] < 8.0 * drop:
return points, 0.0
return np.vstack([points[:i + 1], ((a + b) / 2.0 + across / hang * drop)[None], points[i + 1:]]), drop
def _turns(points):
steps = np.diff(points, axis=0)
lengths = np.linalg.norm(steps, axis=1)
if (lengths < 1e-9).any():
raise RouteError(f"point {int(np.argmax(lengths < 1e-9))} {spot(points[int(np.argmax(lengths < 1e-9))])}: the segment from it is shorter than 1e-9")
unit = steps / lengths[:, None]
return lengths, unit, np.arccos(np.clip(np.einsum("ij,ij->i", unit[:-1], unit[1:]), -1.0, 1.0))
def _kept(count: int, lead: float, keep) -> np.ndarray:
keep = np.zeros(count) if keep is None else np.array(keep, dtype=np.float64)
keep[0] += lead
keep[-1] += lead
return keep
def _radius(point, before, after, turn: float, cap: float, room) -> float:
"""The largest radius of the arc at a corner whose tangent lengths stay within cap and whose room allows it: the
arc stands within radius x (1 - cos(turn / 2)) of its two tangent segments, so with that much room beyond need
measured along them it keeps need (the triangle inequality). The tangent segments grow with the radius, so the
room can only shrink: the largest radius is found by bisection."""
most = max(cap, 0.0) / math.tan(turn / 2.0)
if room is None:
return most
depth = 1.0 - math.cos(turn / 2.0)
def fits(radius: float) -> bool:
t = radius * math.tan(turn / 2.0)
return radius * depth <= min(room(point - before * t, point), room(point, point + after * t))
if fits(most):
return most
low, high = 0.0, most
for _ in range(24):
middle = (low + high) / 2.0
low, high = (middle, high) if fits(middle) else (low, middle)
return low
def tangents(points, room, lead: float, keep=None, centred=None) -> np.ndarray:
"""The tangent length of the arc at each interior point of a polyline (0 where it runs straight on). Each corner
first gets the largest radius its room allows (_radius) within the straight its two segments have to give: a
segment's length less what it keeps straight (`keep` for each segment, and `lead` more on the first and last), or
half of that at each end of a `centred` segment, whose kept straight stays in its middle. Where two corners'
tangents overlap on a segment both shrink in proportion until they share it."""
points = np.asarray(points, dtype=np.float64)
lengths, unit, turn = _turns(points)
free = np.maximum(lengths - _kept(len(lengths), lead, keep), 0.0)
each = np.where(np.zeros(len(lengths), dtype=bool) if centred is None else np.asarray(centred, dtype=bool), free / 2.0, free)
t = np.zeros(len(turn))
for c in np.flatnonzero(turn >= STRAIGHT):
t[c] = _radius(points[c + 1], unit[c], unit[c + 1], float(turn[c]), float(min(each[c], each[c + 1])), room) * math.tan(turn[c] / 2.0)
share = np.ones(len(lengths))
both = t[:-1] + t[1:] # on segment s, between corners s - 1 and s
share[1:-1] = np.where(both > free[1:-1], free[1:-1] / np.maximum(both, 1e-300), 1.0)
return t * np.minimum(share[:-1], share[1:])
def arcs(points, t):
"""(curve, owner): the polyline with the arc of tangent length t[c] at each interior point c + 1, as points
ARC to the radian, and for each curve point the corner whose arc it is on (-1 on the straights' ends). Every arc
is tangent to both its segments."""
points = np.asarray(points, dtype=np.float64)
_, unit, turn = _turns(points)
curve, owner = [points[0]], [-1]
for c in range(len(turn)):
corner, before, after = points[c + 1], unit[c], unit[c + 1]
if turn[c] < STRAIGHT or t[c] < 1e-9:
curve.append(corner)
owner.append(c)
continue
radius = t[c] / math.tan(turn[c] / 2.0)
inward = after - before * float(before @ after)
inward /= np.linalg.norm(inward)
centre = corner - before * t[c] + inward * radius
for angle in np.linspace(0.0, turn[c], max(2, int(math.ceil(turn[c] * ARC))) + 1):
curve.append(centre + radius * (before * math.sin(angle) - inward * math.cos(angle)))
owner.append(c)
curve.append(points[-1])
owner.append(-1)
curve, owner = np.array(curve), np.array(owner)
keep = np.r_[True, np.linalg.norm(np.diff(curve, axis=0), axis=1) > 1e-9]
return curve[keep], owner[keep]
class Filleted(NamedTuple):
curve: np.ndarray # (N, 3)
owner: np.ndarray # (N,) the corner a curve point's arc belongs to, -1 off the arcs
t: np.ndarray # tangent length at each interior point of the polyline
radii: np.ndarray # radius at each interior point, inf where the polyline runs straight on
def fillet(polyline, room, floor: float, lead: float, keep=None, centred=None) -> Filleted:
"""A polyline with its corners rounded (tangents, arcs). `room(a, b)` is the least obstacle distance along the
segment a..b less need, or None where nothing stands near. Refuses a corner whose radius is under `floor`, naming
the corner, its point, the radius it got and the floor."""
polyline = np.asarray(polyline, dtype=np.float64)
if len(polyline) < 3:
return Filleted(polyline, np.full(len(polyline), -1), np.zeros(0), np.zeros(0))
t = tangents(polyline, room, lead, keep, centred)
turn = _turns(polyline)[2]
radii = np.where(turn >= STRAIGHT, t / np.tan(np.maximum(turn, STRAIGHT) / 2.0), np.inf)
under = np.flatnonzero(radii < floor * (1.0 - 1e-9))
if len(under):
c = int(under[np.argmin(radii[under])])
raise RouteError(f"corner {c + 1} at {spot(polyline[c + 1])} turns {math.degrees(turn[c]):.1f} degrees and gets a bend of radius {radii[c]:.4g} m, under the floor {floor:.4g}: "
"its segments are too short or an obstacle stands too near it")
return Filleted(*arcs(polyline, t), t, radii)
def samples(curve, spacing: float):
"""(points, arc length at each) along a polyline, its own points included, no further apart than spacing."""
curve = np.asarray(curve, dtype=np.float64)
lengths = np.linalg.norm(np.diff(curve, axis=0), axis=1)
starts = np.r_[0.0, np.cumsum(lengths)]
points, s = [curve[:1]], [np.zeros(1)]
for i, length in enumerate(lengths):
count = max(1, int(math.ceil(length / spacing)))
f = np.arange(1, count + 1) / count
points.append(curve[i][None] + (curve[i + 1] - curve[i])[None] * f[:, None])
s.append(starts[i] + length * f)
return np.vstack(points), np.concatenate(s)
def verify(curve, distance, need: float, lead: float, spacing: float, name: str = "the hose") -> float:
"""The least distance the curve stands from an obstacle outside its two leads (the first and last `lead` of its
length, where it leaves its own ports). Refuses a reading under need, naming the point."""
points, s = samples(curve, spacing)
inside = (s >= lead) & (s <= s[-1] - lead)
if not inside.any():
return math.inf
reads = np.asarray(distance(points[inside]))
worst = int(np.argmin(reads))
if reads[worst] < need - HELD:
raise RouteError(f"{name} stands {float(reads[worst]):.4g} m from an obstacle at {spot(points[inside][worst])}, under the {need:.4g} m the bundle needs")
return float(reads[worst])
def frames(curve, up0) -> np.ndarray:
"""An up for each point of a curve, rotation minimising: the first is up0 projected off the tangent, each next the
last reflected twice (Wang et al. 2008), so the ups do not twist about the curve. Tangents are the unit bisectors
core.sweep stands its sections on. Refuses an up0 along the first tangent."""
curve, up = np.asarray(curve, dtype=np.float64), np.asarray(up0, dtype=np.float64)
steps = np.diff(curve, axis=0)
steps = steps / np.linalg.norm(steps, axis=1)[:, None]
tangent = np.vstack([steps[:1], steps[:-1] + steps[1:], steps[-1:]])
tangent /= np.linalg.norm(tangent, axis=1)[:, None]
r = up - tangent[0] * float(up @ tangent[0])
if not np.linalg.norm(r) > 1e-6 * np.linalg.norm(up):
raise RouteError(f"up {spot(up)} runs along the curve's first tangent (or is zero)")
r = r / np.linalg.norm(r)
ups = [r]
for i in range(len(curve) - 1):
v1 = curve[i + 1] - curve[i]
c1 = float(v1 @ v1)
r_left = r - (2.0 / c1) * float(v1 @ r) * v1
t_left = tangent[i] - (2.0 / c1) * float(v1 @ tangent[i]) * v1
v2 = tangent[i + 1] - t_left
c2 = float(v2 @ v2)
r = r_left - (2.0 / c2) * float(v2 @ r_left) * v2 if c2 > 1e-18 else r_left
ups.append(r)
return np.array(ups)
def turned(points, origin, axis, degrees: float) -> np.ndarray:
"""Points turned `degrees` about the line through origin along axis, right-handed."""
axis = np.asarray(axis, dtype=np.float64) / np.linalg.norm(axis)
p = np.asarray(points, dtype=np.float64) - origin
c, s = math.cos(math.radians(degrees)), math.sin(math.radians(degrees))
return origin + p * c + np.cross(axis, p) * s + axis[None] * (p @ axis)[:, None] * (1.0 - c)
def rolls_of(low: float, high: float, step: float) -> list:
"""low, then every step up to high, and high."""
return [float(v) for v in np.arange(low, high - 1e-9, step)] + [float(high)]
def passes(polyline, t, j: int, origin, axis, rolls, current: float, parent, child, need: float, floor: float, lead: float, spacing: float, keep=None) -> dict:
"""A hose through a pin's rolls. `polyline` runs from the parent's side through point j, which stands on the
pin's axis (origin, axis), to the child's side; `t` are its tangent lengths at the roll `current`. At each roll
the points beyond j are turned about the axis by roll - current, as the child's parts are: the straights on each
side move with their own part, and only the corner at j is rounded again, its neighbours' tangents as they were.
The parent's side is then measured against the child's obstacles turned (`child` reads the child's parts where
they stand at `current`, so the samples are turned back), the child's side against the parent's (`parent`), and the
arc at j against both, all outside the leads. Refuses a roll whose bend at the pin is under the floor or whose
reading is under need, naming the roll, the side and the reading. {rolls, worstRoll, least, lengthChange, radius}."""
polyline, origin = np.asarray(polyline, dtype=np.float64), np.asarray(origin, dtype=np.float64)
c, least, lengths, radius = j - 1, (math.inf, None), [], math.inf
kept = _kept(len(polyline) - 1, lead, keep)
for roll in rolls:
posed = np.vstack([polyline[:j + 1], turned(polyline[j + 1:], origin, axis, roll - current)])
back = lambda points, roll=roll: turned(points, origin, axis, current - roll) # noqa: E731
both = lambda points, back=back: np.minimum(np.asarray(parent(points)), np.asarray(child(back(points)))) # noqa: E731
lengths_, unit, turn = _turns(posed)
t_roll = np.array(t, dtype=np.float64)
t_roll[c] = 0.0
if turn[c] >= STRAIGHT:
cap = min(lengths_[c] - kept[c] - (t_roll[c - 1] if c > 0 else 0.0), lengths_[c + 1] - kept[c + 1] - (t_roll[c + 1] if c + 1 < len(t_roll) else 0.0))
bend = _radius(posed[j], unit[c], unit[c + 1], float(turn[c]), float(cap), lambda a, b, both=both: float(both(along(a, b, spacing)).min()) - need)
if bend < floor * (1.0 - 1e-9):
raise RouteError(f"roll {roll:g}: the bend at the pin turns {math.degrees(turn[c]):.1f} degrees and gets radius {bend:.4g} m, under the floor {floor:.4g}")
t_roll[c], radius = bend * math.tan(turn[c] / 2.0), min(radius, bend)
curve, owner = arcs(posed, t_roll)
points, s = samples(curve, spacing)
at = np.r_[0.0, np.cumsum(np.linalg.norm(np.diff(curve, axis=0), axis=1))][owner == c]
inside = (s >= lead) & (s <= s[-1] - lead)
for side, chosen, reads in (("parent's side", inside & (s < at[0]), lambda p, back=back: np.asarray(child(back(p)))),
("child's side", inside & (s > at[-1]), parent),
("bend at the pin", inside & (s >= at[0]) & (s <= at[-1]), both)):
if chosen.any():
reading = float(np.asarray(reads(points[chosen])).min())
if reading < need - HELD:
raise RouteError(f"roll {roll:g}: the hose's {side} stands {reading:.4g} m from the parts on the other side of the pin, under the {need:.4g} m the bundle needs")
least = min(least, (reading, float(roll)))
lengths.append(float(s[-1]))
return {"rolls": len(lengths), "worstRoll": least[1], "least": least[0], "lengthChange": max(lengths) - min(lengths), "radius": radius}

View file

@ -0,0 +1,296 @@
"""Route tests. No Blender: brokkr_kitbash/route.py against analytic distance fields.
Run: python3 -m unittest discover -s surfaces/blender/tests -v (needs numpy; skipped without it)
The hose action is exercised in a real Blender by tests/live/kitbash_hose.py.
Bounds follow lodur:ruling:deterministic-bound-margin: a deterministic reading is exact here, so each assertion is the
rule itself, and each names the mutant it kills (cut kit-hose's H list).
"""
from __future__ import annotations
import importlib.util
import math
import unittest
from pathlib import Path
SURFACE = Path(__file__).resolve().parents[1]
try:
import numpy as np
except ImportError: # pragma: no cover
np = None
if np is not None:
spec = importlib.util.spec_from_file_location("brokkr_kitbash_route", SURFACE / "brokkr_kitbash" / "route.py")
route = importlib.util.module_from_spec(spec)
spec.loader.exec_module(route)
NEED = 0.04
def wall(hole: float):
"""A wall 0.04 thick across x = 1 with a round hole of radius `hole` about the line y = z = 0.2."""
def distance(points):
points = np.asarray(points, dtype=np.float64)
out = np.maximum(np.abs(points[:, 0] - 1.0) - 0.02, 0.0)
inside = hole - np.hypot(points[:, 1] - 0.2, points[:, 2] - 0.2)
return np.where(inside > 0.0, np.hypot(out, inside), out)
return distance
def ball(centre, radius: float):
return lambda points: np.linalg.norm(np.asarray(points, dtype=np.float64) - np.asarray(centre), axis=1) - radius
def nothing(points):
return np.full(len(points), 10.0)
def room_of(distance, need: float, spacing: float = 0.002):
return lambda a, b: float(np.asarray(distance(route.along(a, b, spacing))).min()) - need
def length(points) -> float:
return float(np.linalg.norm(np.diff(np.asarray(points), axis=0), axis=1).sum())
@unittest.skipIf(np is None, "numpy is not installed")
class SearchTests(unittest.TestCase):
def test_a_leg_passes_the_hole_and_every_sight_line_keeps_need(self):
"""wavefront-and-pull. Mutant H12 (occupancy at need less a voxel): a kept point stands under need."""
distance = wall(0.12)
a, b = np.array([0.0, 0.0, 0.0]), np.array([2.0, 0.0, 0.0])
pulled, voxels = route.leg(a, b, distance, distance, NEED, 0.02, 0.3, 2 ** 19, "leg 1")
self.assertEqual(voxels, 131 * 31 * 31)
self.assertTrue(np.allclose(pulled[0], a) and np.allclose(pulled[-1], b))
dense = np.vstack([route.along(p, q, 0.0025) for p, q in zip(pulled[:-1], pulled[1:])]) # a quarter of the spacing pull samples at
self.assertGreaterEqual(float(distance(dense).min()), NEED - 1e-9)
through = dense[np.abs(dense[:, 0] - 1.0) < 0.02]
self.assertTrue(len(through) and (np.hypot(through[:, 1] - 0.2, through[:, 2] - 0.2) < 0.12 - NEED + 1e-9).all())
self.assertLess(length(pulled), 2.0 * math.hypot(1.0, 0.2 * math.sqrt(2.0)) + 0.05) # taut: near the two straights through the hole's middle
def test_two_neighbouring_free_voxels_keep_need_between_them(self):
"""The half diagonal a free voxel stands beyond need is what a step between two of them can lose: beside an
edge (a thin rod) every step between neighbouring free voxels keeps need, and without it some do not."""
rod = lambda points: np.hypot(np.asarray(points)[:, 0], np.asarray(points)[:, 1]) # noqa: E731
for reach, holds in ((route.REACH, True), (0.0, False)):
cells = route.grid([-0.1, -0.1, 0.0], [0.1, 0.1, 0.0], 0.02, rod, 0.043 + reach * 0.02)
free = [np.array(m) for m in zip(*np.nonzero(cells.free))]
least = min(float(rod(route.along(cells.lo + 0.02 * p, cells.lo + 0.02 * q, 0.001)).min())
for p in free for q in free if 0 < np.abs(p - q).max() <= 1)
self.assertEqual(least >= 0.043, holds, least)
def test_a_closed_way_a_buried_end_and_a_box_too_fine_are_refused_by_name(self):
distance = wall(0.03) # a hole narrower than the bundle
ends = (np.array([0.0, 0.0, 0.0]), np.array([2.0, 0.0, 0.0]))
with self.assertRaisesRegex(route.RouteError, r"^leg 2: no free way joins its ends"):
route.leg(*ends, distance, distance, NEED, 0.02, 0.3, 2 ** 19, "leg 2")
with self.assertRaisesRegex(route.RouteError, r"^leg 3: its end \[1, 0, 0\] stands 0 m from an obstacle, under the 0\.04 m"):
route.leg(ends[0], np.array([1.0, 0.0, 0.0]), distance, distance, NEED, 0.02, 0.3, 2 ** 19, "leg 3")
with self.assertRaisesRegex(route.RouteError, r"^leg 4: its search box of \[2\.6, 0\.6, 0\.6\] m is \d+ voxels at step 0\.005, over 524288: a step of 0\.0\d+ fits"):
route.leg(*ends, distance, distance, NEED, 0.005, 0.3, 2 ** 19, "leg 4")
try:
route.leg(*ends, distance, distance, NEED, 0.005, 0.3, 2 ** 19, "leg 4")
except route.RouteError as error:
fits = float(str(error).split("a step of ")[1].split(" ")[0])
self.assertLessEqual(int(np.prod(np.ceil(np.array([2.6, 0.6, 0.6]) / fits - 1e-9) + 1)), 2 ** 19)
with self.assertRaisesRegex(route.RouteError, "its start voxel is not free"):
route.wavefront(np.zeros((2, 2, 2), dtype=bool), (0, 0, 0), (1, 1, 1))
def test_a_wavefront_way_is_a_shortest_one(self):
free = np.ones((9, 9, 1), dtype=bool)
free[4, 1:, 0] = False # a wall with a gap at j = 0
way = route.wavefront(free, (0, 8, 0), (8, 8, 0))
self.assertEqual((way[0], way[-1], len(way)), ((0, 8, 0), (8, 8, 0), 17))
self.assertIn((4, 0, 0), way)
self.assertTrue(all(max(abs(p[i] - q[i]) for i in range(3)) == 1 for p, q in zip(way[:-1], way[1:])))
@unittest.skipIf(np is None, "numpy is not installed")
class FilletTests(unittest.TestCase):
ZIGZAG = np.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 0.3, 0.0], [2.0, 0.3, 0.4], [2.0, 1.5, 0.4]])
def test_every_arc_is_tangent_and_two_corners_share_a_segment(self):
"""fillet-rule. Mutant H2 (arcs not tangent): the first chord of an arc leaves its segment at more than half a
step of the arc. Two corners on the 0.3 segment shrink until their tangents share it."""
made = route.fillet(self.ZIGZAG, None, 0.01, 0.2)
lengths, unit, turn = route._turns(self.ZIGZAG)
self.assertTrue((made.t[:-1] + made.t[1:] <= lengths[1:-1] + 1e-12).all())
self.assertAlmostEqual(float(made.t[0] + made.t[1]), 0.3, places=12)
self.assertAlmostEqual(float(made.t[0] / made.t[1]), min(0.8, 0.3) / min(0.3, float(lengths[2])), places=12) # in proportion to what each had alone
for c in range(3):
arc = made.curve[made.owner == c]
steps = max(2, math.ceil(turn[c] * route.ARC))
self.assertEqual(len(arc), steps + (c != 1)) # arcs 0 and 1 meet on the shared segment: the point where they meet is listed once, as arc 0's
for chord, tangent in ((arc[1] - arc[0], unit[c]), (arc[-1] - arc[-2], unit[c + 1]))[c == 1:]:
self.assertAlmostEqual(math.acos(min(1.0, float(chord @ tangent) / float(np.linalg.norm(chord)))), turn[c] / steps / 2.0, places=9)
self.assertAlmostEqual(float(np.linalg.norm(arc[-1] - self.ZIGZAG[c + 1])), float(made.t[c]), places=12)
self.assertAlmostEqual(float(made.radii[c]), float(made.t[c] / math.tan(turn[c] / 2.0)), places=12)
def test_the_leads_stay_straight(self):
"""Mutant H1 (lead ignored): the first corner's tangent takes the whole first segment and the bend starts at
the ferrule."""
made = route.fillet(np.array([[0.0, 0.0, 0.0], [0.3, 0.0, 0.0], [0.3, 2.0, 0.0], [0.3, 2.0, 0.5]]), None, 0.01, 0.2)
self.assertAlmostEqual(float(made.t[0]), 0.1, places=12)
self.assertAlmostEqual(float(made.t[1]), 0.3, places=12)
self.assertAlmostEqual(float(np.linalg.norm(made.curve[1] - made.curve[0])), 0.2, places=12)
self.assertAlmostEqual(float(np.linalg.norm(made.curve[-1] - made.curve[-2])), 0.2, places=12)
def test_a_kept_straight_stays_in_the_middle_of_a_centred_segment(self):
points = np.array([[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 0.5, 0.0], [3.0, 0.5, 1.0]])
made = route.fillet(points, None, 0.01, 0.0, keep=[0.0, 0.1, 0.0], centred=[False, True, False])
self.assertAlmostEqual(float(made.t[0]), 0.2, places=12)
self.assertAlmostEqual(float(made.t[1]), 0.2, places=12)
def test_a_corner_that_wraps_an_obstacle_gets_the_radius_its_room_allows(self):
"""Mutant H3 (the room cap off: radius by segments only): the arc cuts through the ball."""
distance = ball([-0.25, 0.25, 0.0], 0.17)
points = np.array([[-1.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 0.0]])
room = room_of(distance, 0.05)
made = route.fillet(points, room, 0.05, 0.0)
radius, t = float(made.radii[0]), float(made.t[0])
depth = 1.0 - math.cos(math.pi / 4.0)
measured = min(room(points[1] - np.array([1.0, 0.0, 0.0]) * t, points[1]), room(points[1], points[1] + np.array([0.0, 1.0, 0.0]) * t))
self.assertLessEqual(radius * depth, measured + 1e-12)
self.assertGreater(radius, 0.03 / depth) # more than the room at the segments' nearest points allows: the room is measured along the tangent segments only
self.assertLess(radius, 0.25)
arc = made.curve[made.owner == 0]
self.assertGreaterEqual(float(distance(np.vstack([route.along(p, q, 0.001) for p, q in zip(arc[:-1], arc[1:])])).min()), 0.05)
grown = route.arcs(points, np.array([t * 1.05]))[0] # the largest: 5 percent more breaks the rule
t2 = t * 1.05
self.assertGreater(t2 / math.tan(math.pi / 4.0) * depth, min(room(points[1] - np.array([1.0, 0.0, 0.0]) * t2, points[1]), room(points[1], points[1] + np.array([0.0, 1.0, 0.0]) * t2)))
self.assertEqual(len(grown), len(made.curve))
free = route.fillet(points, None, 0.05, 0.0)
self.assertAlmostEqual(float(free.radii[0]), 1.0, places=12)
self.assertLess(float(distance(free.curve).min()), 0.0)
self.assertGreaterEqual(route.verify(made.curve, distance, 0.05, 0.0, 0.002), 0.05)
with self.assertRaisesRegex(route.RouteError, r"^the hose stands -0\.\d+ m from an obstacle at \[-0\.\d+, 0\.\d+, 0\], under the 0\.05 m"):
route.verify(free.curve, distance, 0.05, 0.0, 0.002)
def test_a_corner_under_the_floor_is_refused_by_name(self):
with self.assertRaisesRegex(route.RouteError, r"^corner 1 at \[1, 0, 0\] turns 90\.0 degrees and gets a bend of radius 0\.15 m, under the floor 0\.5"):
route.fillet(self.ZIGZAG, None, 0.5, 0.2)
with self.assertRaisesRegex(route.RouteError, r"^corner 1 at \[0, 0, 0\] turns 90\.0 degrees and gets a bend of radius 0\.00\d+ m, under the floor 0\.05"):
route.fillet(np.array([[-1.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 0.0]]), room_of(ball([-0.05, 0.05, 0.0], 0.02), 0.05), 0.05, 0.0) # a ball in the corner
def test_the_floor_is_the_innermost_hose_s(self):
"""Mutant H8 (the floor taken at the centre line): the innermost of three hoses bends tighter than bend
outside diameters."""
sizes = route.bundle(3, 0.014, 0.0, 0.01, 4.0)
self.assertAlmostEqual(sizes["spread"], 0.0364, places=12)
self.assertAlmostEqual(sizes["floor"] - sizes["spread"], 4.0 * 0.028, places=12)
self.assertAlmostEqual(sizes["need"], 0.0364 + 0.014 + 0.01, places=12)
self.assertAlmostEqual(sizes["width"], 2 * 0.0364 + 0.028, places=12)
self.assertAlmostEqual(sizes["lead"], 5 * 0.014 + 1.5 * 0.028, places=12)
self.assertEqual(route.bundle(1, 0.01, 0.0, 0.0, 4.0)["floor"], 0.08)
def test_a_span_sags_by_no_more_than_half_its_room(self):
"""ruling hose-slack-and-skinned. Mutant S1 (the sag not bounded by the room): the span hangs into the floor
under it."""
ground = lambda points: np.asarray(points, dtype=np.float64)[:, 2] # noqa: E731
span = np.array([[0.0, 0.0, 0.1], [1.0, 0.0, 0.1]])
hung, drop = route.sag(span, 0.1, room_of(ground, 0.05))
self.assertAlmostEqual(drop, 0.025, places=12)
self.assertTrue(np.allclose(hung[1], [0.5, 0.0, 0.075]))
made = route.fillet(np.vstack([[[0.0, 0.0, 0.5]], hung, [[1.0, 0.0, 0.5]]]), room_of(ground, 0.05), 0.01, 0.1)
self.assertGreaterEqual(route.verify(made.curve, ground, 0.05, 0.1, 0.002), 0.05)
self.assertGreater(float(made.radii[1]), 1.0) # a gentle arc, not a kink
high, drop = route.sag(span + [0.0, 0.0, 1.0], 0.1, room_of(ground, 0.05))
self.assertEqual((drop, len(high)), (0.1, 3))
self.assertEqual(route.sag(np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 1.0]]), 0.1, None)[1], 0.0) # a vertical span does not sag
self.assertEqual(route.sag(span, 0.0, None)[1], 0.0)
leaning, drop = route.sag(np.array([[0.0, 0.0, 1.0], [1.0, 0.0, 2.0]]), 0.1, None) # across the span, by how far it runs from vertical
self.assertAlmostEqual(drop, 0.1 * math.sqrt(0.5), places=12)
self.assertAlmostEqual(float((leaning[1] - [0.5, 0.0, 1.5]) @ [1.0, 0.0, 1.0]), 0.0, places=12)
self.assertEqual(route.sag(np.array([[0.0, 0.0, 1.0], [0.5, 0.0, 1.0]]), 0.1, None)[1], 0.0) # too short for the drop
@unittest.skipIf(np is None, "numpy is not installed")
class FrameTests(unittest.TestCase):
@staticmethod
def reference(curve, tangent, up):
"""The double reflection method as Wang et al. 2008 state it, a point at a time."""
ups = [up]
for i in range(len(curve) - 1):
v1 = [curve[i + 1][k] - curve[i][k] for k in range(3)]
c1 = sum(v * v for v in v1)
dot = lambda a, b: sum(x * y for x, y in zip(a, b)) # noqa: E731
r_left = [ups[-1][k] - 2.0 / c1 * dot(v1, ups[-1]) * v1[k] for k in range(3)]
t_left = [tangent[i][k] - 2.0 / c1 * dot(v1, tangent[i]) * v1[k] for k in range(3)]
v2 = [tangent[i + 1][k] - t_left[k] for k in range(3)]
c2 = dot(v2, v2)
ups.append([r_left[k] - 2.0 / c2 * dot(v2, r_left) * v2[k] for k in range(3)])
return np.array(ups)
@staticmethod
def tangents(curve):
steps = np.diff(curve, axis=0)
steps /= np.linalg.norm(steps, axis=1)[:, None]
tangent = np.vstack([steps[:1], steps[:-1] + steps[1:], steps[-1:]])
return tangent / np.linalg.norm(tangent, axis=1)[:, None]
def test_ups_are_rotation_minimising(self):
"""frames-rmf. Mutant H7 (Frenet frames for ups): on a planar S the up leaves the plane's normal."""
s = np.linspace(0.0, 2.0 * math.pi, 200)
planar = np.stack([s, np.sin(s), np.zeros_like(s)], axis=1)
ups = route.frames(planar, [0.0, 0.0, 1.0])
self.assertLess(float(np.abs(ups - [0.0, 0.0, 1.0]).max()), 1e-12)
helix = np.stack([np.cos(s * 2.0), np.sin(s * 2.0), 0.3 * s], axis=1)
ups, tangent = route.frames(helix, [0.0, 0.0, 1.0]), self.tangents(helix)
self.assertLess(float(np.abs(np.einsum("ij,ij->i", ups, tangent)).max()), 1e-12)
self.assertLess(float(np.abs(np.linalg.norm(ups, axis=1) - 1.0).max()), 1e-12)
first = np.array([0.0, 0.0, 1.0]) - tangent[0] * tangent[0][2]
self.assertLess(float(np.abs(ups - self.reference(helix.tolist(), tangent.tolist(), (first / np.linalg.norm(first)).tolist())).max()), 1e-9)
with self.assertRaisesRegex(route.RouteError, "runs along the curve's first tangent"):
route.frames(planar, planar[1] - planar[0])
@unittest.skipIf(np is None, "numpy is not installed")
class JointTests(unittest.TestCase):
P = np.array([[0.5, 0.0, 1.0], [0.2, 0.0, 0.0], [0.5, 0.0, -1.0]]) # through a point on the x axis
AXIS = (np.zeros(3), np.array([1.0, 0.0, 0.0]))
SIZES = {"need": 0.05, "floor": 0.05, "lead": 0.1, "spacing": 0.01}
def test_a_polyline_through_the_axis_keeps_its_length_at_every_roll(self):
"""joint-passage."""
rolls = route.rolls_of(-120.0, 10.0, 5.0)
self.assertEqual((len(rolls), rolls[0], rolls[-2], rolls[-1]), (27, -120.0, 5.0, 10.0))
self.assertEqual(route.rolls_of(0.0, 12.0, 5.0), [0.0, 5.0, 10.0, 12.0])
for roll in rolls:
posed = np.vstack([self.P[:2], route.turned(self.P[2:], *self.AXIS, roll)])
self.assertAlmostEqual(length(posed), length(self.P), places=12)
self.assertTrue(np.allclose(route.turned(np.array([[0.3, 1.0, 0.0]]), *self.AXIS, 90.0), [[0.3, 0.0, 1.0]])) # right-handed about +x
t = route.fillet(self.P, None, 0.05, 0.1).t
found = route.passes(self.P, t, 1, *self.AXIS, rolls, 0.0, nothing, nothing, **self.SIZES)
self.assertEqual((found["rolls"], found["least"]), (27, 10.0))
self.assertGreater(found["lengthChange"], 0.01) # the bend at the pin is what changes: each roll's is the largest arc its segments give
self.assertLess(found["lengthChange"], length(self.P) * (1.0 - math.pi / 4.0) * 2.0) # no more than every corner's shortcut
def test_a_hairpin_roll_is_refused_by_name(self):
t = route.fillet(self.P, None, 0.05, 0.1).t
with self.assertRaisesRegex(route.RouteError, r"^roll 180: the bend at the pin turns 180\.0 degrees and gets radius \S+e-\d+ m, under the floor 0\.05"):
route.passes(self.P, t, 1, *self.AXIS, [0.0, 90.0, 180.0], 0.0, nothing, nothing, **self.SIZES)
def test_each_side_is_measured_against_the_other_where_the_roll_puts_it(self):
"""Mutants H5 (the child's obstacles not turned with the roll) and H6 (the range checked at its ends only): a
part of the child that the roll carries into the parent's side of the hose, between the ends of the range."""
middle = (self.P[0] + self.P[1]) / 2.0
child = ball(route.turned(middle[None], *self.AXIS, -45.0)[0], 0.05) # where it stands at roll 0
t = route.fillet(self.P, None, 0.05, 0.1).t
for ends in ([-90.0, 90.0], [0.0]):
self.assertEqual(route.passes(self.P, t, 1, *self.AXIS, ends, 0.0, nothing, child, **self.SIZES)["rolls"], len(ends))
with self.assertRaisesRegex(route.RouteError, r"^roll 35: the hose's parent's side stands 0\.0\d+ m from the parts on the other side of the pin, under the 0\.05 m"):
route.passes(self.P, t, 1, *self.AXIS, route.rolls_of(-90.0, 90.0, 5.0), 0.0, nothing, child, **self.SIZES)
seen = []
route.passes(self.P, t, 1, *self.AXIS, [30.0], 10.0, nothing, lambda points: seen.append(np.array(points)) or nothing(points), **self.SIZES)
line = (self.P[1] - self.P[0]) / np.linalg.norm(self.P[1] - self.P[0])
on = [points for points in seen if len(points) > 3 and np.abs(np.cross(route.turned(points, *self.AXIS, 20.0) - self.P[0], line)).max() < 1e-12]
self.assertTrue(on) # the parent's side was read turned back by roll - current: turned forward again it lies on its own segment
self.assertTrue(all(np.abs(np.cross(points - self.P[0], line)).max() > 0.01 for points in on))
parent = ball(route.turned(((self.P[1] + self.P[2]) / 2.0)[None], *self.AXIS, 45.0)[0], 0.05) # a part of the parent the child's side swings into
with self.assertRaisesRegex(route.RouteError, r"^roll 35: the hose's child's side stands"):
route.passes(self.P, t, 1, *self.AXIS, route.rolls_of(-90.0, 90.0, 5.0), 0.0, parent, nothing, **self.SIZES)
if __name__ == "__main__":
unittest.main()