brokkr_kitbash.ram: zones by the bodies a pin joins, record version 2, Soul s4's Lows (cut kit-ram-lows) #38

Open
eureka wants to merge 11 commits from nibu/kit-ram-lows into main
6 changed files with 577 additions and 146 deletions

View file

@ -24,13 +24,19 @@ the coupler bar at c's, the ram at a's plus each of `offsets`.
search(kind, hinge, ram, seats, ...) the best of a seat grid, or the tally and the nearest miss
record(m, ram), from_record the JSON record a rig or runtime drives from
swept(fit, body, ...) points of the swept ram's surface in a body's rest frame
Signed(shells, cap) the distance oracle over closed meshes, signed by three rays
winding(vertices, triangles, points) the generalized winding number of a triangle soup about points
inside(vertices, triangles, points) whether points are inside it: the number is 0.5 or more
solids(part, vertices, faces) the closed, outward wound solids of a part, or the refusal
Signed(shells, cap) the distance oracle over meshes, signed by the winding number
Clearance. The record names the mechanism's `parts`, each a piece of one body (part -> the body whose rest frame
it turns with: a thigh's core, the bracket that carries the rocker's pivot, a link's plates, a pin), and `touch`:
for each member of MEMBERS[kind], zones (part, pin, radius, depth). Every member meets every part. A zone lowers
what the member's samples keep from one part, and only within `radius` of the axis of `pin`, one of the member's
own (RIDES), measured across the hinge axis: there a sample may come as near the part as -depth and no nearer.
The part is one of a body that pin joins (JOINS: a the parent; the rocker's pivot the parent and the rocker; p the
rocker and the coupler; c the coupler and the child; b the child; d the rocker), or the record is refused: what a
member meets at a pin is of the bodies pinned there, and a part of any other body is never let near it.
depth is 0 for what is stacked beside the member on the pin (a plate, the bracket or horn the pin stands in: the
member's axis stays outside it, so a pin whose place along the axis is inside the part it claims to stand beside
is refused), the pin's radius for the pin through the member's eye, half the thickness for the member's own plate
@ -68,13 +74,14 @@ MEMBERS = {"direct": ("barrel", "rod"), "four_bar": ("barrel", "rod", "rocker",
EYE = {"direct": "b", "four_bar": "d", "bell_crank": "d"} # the pin the rod's eye rides
RIDES = {kind: {"barrel": ("a", EYE[kind]), "rod": ("a", EYE[kind]), "rocker": ("rocker", "p"), "coupler": ("p", "c"), "rocker arm": ("rocker", "d")}
for kind in KINDS} # member -> the pins at its start and its end
JOINS = {kind: {"a": ("parent",), "b": ("child",)} if kind == "direct" else
{"a": ("parent",), "rocker": ("parent", "rocker"), "p": ("rocker", "coupler"), "c": ("coupler", "child"), "d": ("rocker",)}
for kind in KINDS} # pin -> the bodies it joins: only their parts are zoned about it
GATES = ("assembly", "stroke", "toggle", "arm", "load", "clash")
SCHEMA, VERSION = "brokkr.ram", 1
SCHEMA, VERSION = "brokkr.ram", 2
ZONE = ("part", "pin", "radius", "depth") # a zone of `touch`, as the record writes it
COMPLIANCE = ("stiffness", "damping", "travel") # reserved: a load-path ram's settle, solved by a later version
BAND = 1e-9 # the loop is refused within this of a dead centre of the rocker and coupler
FINE = 64 # in a zone a segment between samples is halved down to spacing / FINE
RAYS = ((0.5377, 0.6211, 0.5701), (-0.7071, 0.2903, 0.6447), (0.1873, -0.8011, -0.5684)) # Signed's, in order
class RamError(ValueError):
@ -216,6 +223,9 @@ class Mechanism:
radius, depth = _number(self.kind, f"{member} {part} radius", radius, 0.0), _number(self.kind, f"{member} {part} depth", depth)
if depth < 0.0:
raise RamError(self.kind, "record", f"a depth of 0 or more, got {depth!r}", pin=f"{member} {part} depth")
if self.parts[part] not in JOINS[self.kind][pin]:
raise RamError(self.kind, "record", f"{member} may touch about {pin} a part of a body the pin joins ({', '.join(JOINS[self.kind][pin])}); "
f"{part!r} turns with {self.parts[part]}", pin=f"{member} {part} pin")
span = _span(self, member)
for name, value in (("radius", radius), ("depth", depth)):
if value > span:
@ -661,21 +671,20 @@ def search(kind, hinge, ram, seats, world=None, limit=20000, steps=25, spacing=N
def record(m, ram):
"""The mechanism record: plain JSON types, everything a rig or runtime needs to drive the ram from the hinge
angle (from_record, then length or extension). It holds what is authored and nothing derived from it: barrel,
closed length and link lengths come from the pins and the ram. `compliance` is reserved for a load-path ram's
settle (COMPLIANCE: stiffness, damping, travel); version 1 writes it null and solves none."""
closed length and link lengths come from the pins and the ram."""
return {"schema": SCHEMA, "version": VERSION, "kind": m.kind,
"hinge": {"pivot": m.pivot.tolist(), "axis": m.axis.tolist(), "lo": m.lo, "hi": m.hi},
"pins": {name: getattr(m, name).tolist() for name in PINS[m.kind]}, "offsets": list(m.offsets),
"ram": {f.name: getattr(ram, f.name) for f in fields(Ram)},
"parts": dict(m.parts), "compliance": None,
"parts": dict(m.parts),
"touch": {member: [dict(zip(ZONE, zone)) for zone in zones] for member, zones in m.touch.items()}}
def from_record(data):
"""(Mechanism, Ram) of a record. A record of another schema or version (the integer 1: not 1.0, not true), with
a key this version does not know or without one it does, with a compliance block, or with a value that is not
its field's type (a finite number, three of them, a name), or with a zone wider or deeper than its member is
refused whole, as a RamError naming the field: nothing is read past and dropped."""
"""(Mechanism, Ram) of a record. A record of another schema or version (the integer 2: not 2.0, not true), with
a key this version does not know or without one it does, or with a value that is not its field's type (a finite
number, three of them, a name), or with a zone of a body its pin does not join, or wider or deeper than its
member, is refused whole, as a RamError naming the field: nothing is read past and dropped."""
if not isinstance(data, dict):
raise RamError("None", "record", f"a record is an object, got {type(data).__name__}")
kind, version = str(data.get("kind")), data.get("version")
@ -695,13 +704,11 @@ def from_record(data):
raise RamError(kind, "record", f"three finite numbers, got {value!r}", pin=name)
return [_number(kind, name, x) for x in value]
keys("record", data, ("schema", "version", "kind", "hinge", "pins", "offsets", "ram", "parts", "touch", "compliance"))
keys("record", data, ("schema", "version", "kind", "hinge", "pins", "offsets", "ram", "parts", "touch"))
hinge, pins, ram = data["hinge"], data["pins"], data["ram"]
keys("hinge", hinge, ("pivot", "axis", "lo", "hi"))
keys("pins", pins, PINS[kind])
keys("ram", ram, [f.name for f in fields(Ram)])
if data["compliance"] is not None:
raise RamError(kind, "record", f"a compliance block ({', '.join(COMPLIANCE)}) is a later version's: version {VERSION} solves none and will not drop it")
for name, value in ram.items():
_number(kind, name, value, 0.0 if name == "bore" else None)
if not isinstance(data["offsets"], list):
@ -744,47 +751,118 @@ def swept(f, body, margin=0.0, steps=13, around=8):
return _into(m, p, body, np.concatenate(pts, axis=1)).reshape(-1, 3)
class Signed:
"""The distance oracle over closed meshes: distance(part, points) is the nearest face's distance, negative
where the point is inside one of the part's shells (its depth below the nearest face), capped at `cap` outside
only. shells: part -> [(vertices (N, 3), faces)], each shell closed, in the rest frame of the part's body.
Inside is the crossing parity of `rays` of RAYS, by majority: one ray that runs through an edge or a vertex
miscounts, and a sample then reads inside a plate it stands clear of. An unknown part raises. Needs Blender's
mathutils (BVHTree)."""
def winding(vertices, triangles, points):
"""The generalized winding number of a triangle soup about each of `points` (Jacobson, Kavan and Sorkine-Hornung
2013): the triangles' signed solid angles, summed, over 4 pi. A triangle counts positive from the side its normal
points away from (counterclockwise seen from outside). About a closed mesh it is the whole number of times the
surface wraps the point: 0 outside, 1 inside, 2 where two solids of one mesh overlap, whether they share vertices
or cut through one another. About an open mesh it is a fraction that falls off toward the hole (the closed
mesh's number less the missing faces' share of the sphere about the point), and about a mesh wound inside out
it is the negative: neither has an inside to read, and Signed refuses both. The plain sum: a point costs every
triangle. The corners' offsets from the point are taken in double precision and the angles in single (2.4 times
the pace): the number is good to 1e-5 a millimetre off a face and to 1e-2 at 1e-7 off it, and nearer than that
its side of the face is not held."""
v, t, pts = np.asarray(vertices, dtype=float).reshape(-1, 3), np.asarray(triangles, dtype=int).reshape(-1, 3), np.asarray(points, dtype=float).reshape(-1, 3)
A, B, C = (np.ascontiguousarray(v[t[:, k]].T) for k in range(3)) # each (3, F): a corner of every triangle
out, step = np.zeros(len(pts)), max(1, 32768 // max(len(t), 1)) # a block of pairs that stays in cache: 3.1 times the pace of 400,000
for k in range(0, len(pts), step):
p = pts[k:k + step].T[:, :, None]
(ax, ay, az), (bx, by, bz), (cx, cy, cz) = ((corner[:, None, :] - p).astype(np.float32) for corner in (A, B, C))
la, lb, lc = np.sqrt(ax * ax + ay * ay + az * az), np.sqrt(bx * bx + by * by + bz * bz), np.sqrt(cx * cx + cy * cy + cz * cz)
volume = ax * (by * cz - bz * cy) + ay * (bz * cx - bx * cz) + az * (bx * cy - by * cx)
out[k:k + step] = np.arctan2(volume, la * lb * lc + (ax * bx + ay * by + az * bz) * lc + (bx * cx + by * cy + bz * cz) * la + (cx * ax + cy * ay + cz * az) * lb).sum(axis=1, dtype=float)
return out / (2.0 * math.pi)
def __init__(self, shells, cap=None, rays=3):
def inside(vertices, triangles, points):
"""Whether each of `points` is inside the triangle soup: its winding number is 0.5 or more. About the closed,
outward wound solids `solids` passes the number is whole and any bound over 0 and up to 1 reads the same; 0.5
is the bound because it is the middle, the farthest from both whole numbers the single-precision sum rounds
about."""
return winding(vertices, triangles, points) >= 0.5
def solids(part, vertices, faces):
"""The solid each face of a part belongs to (faces joined across an edge are one solid), or a RamError where
the part has no inside to sign: a solid with an edge no face runs the other way (a boundary edge, or two faces
wound against each other across it) is open, and a closed solid of negative volume is wound inside out.
Nothing is repaired. A cavity cut as its own inward shell is such a solid and is refused with the rest."""
v = np.asarray(vertices, dtype=float).reshape(-1, 3)
owner, edges = list(range(len(faces))), {}
def root(k):
while owner[k] != k:
owner[k] = k = owner[owner[k]]
return k
for k, face in enumerate(faces):
for i, j in zip(face, tuple(face[1:]) + tuple(face[:1])):
there = edges.setdefault((min(i, j), max(i, j)), [k, 0])
there[1] += 1 if i < j else -1
owner[root(k)] = root(there[0])
of = np.array([root(k) for k in range(len(faces))], dtype=int)
names = {r: n for n, r in enumerate(dict.fromkeys(of.tolist()))} # solids numbered in the order of their first faces
unmatched = {}
for first, balance in edges.values():
if balance:
unmatched[names[of[first]]] = unmatched.get(names[of[first]], 0) + 1
for n, count in sorted(unmatched.items()):
raise RamError("mesh", "signed", f"part {part!r} is open: solid {n} of {len(names)} has {count} edge{'s' if count > 1 else ''} no face runs the other way")
of = np.array([names[r] for r in of.tolist()], dtype=int)
fan = np.array([(k, face[0], face[n], face[n + 1]) for k, face in enumerate(faces) for n in range(1, len(face) - 1)], dtype=int).reshape(-1, 4)
volume = np.bincount(of[fan[:, 0]], (v[fan[:, 1]] * np.cross(v[fan[:, 2]], v[fan[:, 3]])).sum(axis=1) / 6.0, len(names))
for n in np.flatnonzero(volume < 0.0):
raise RamError("mesh", "signed", f"part {part!r} is wound inside out: solid {n} of {len(names)} ({int((of == n).sum())} faces from face {int(np.flatnonzero(of == n)[0])}) has volume {volume[n]:.3g}")
return of
class Signed:
"""The distance oracle over meshes: distance(part, points) is the distance to the part's surface, negative
where the point is inside the part (its depth), capped at `cap` outside only. shells: part -> [(vertices
(N, 3), faces)], in the rest frame of the part's body. Every solid of a part (`solids`) is closed and wound
counterclockwise seen from outside: a part with an open or an inside-out solid is refused when the oracle is
made, by a RamError that names the part, the solid and the edge count or the volume. Inside is where `inside`
says, by the winding number of all the part's faces (a face of more than three corners as a fan): solids that
overlap, in one mesh or several, welded or not, read inside wherever any is. The depth is to the nearest
exposed face: one whose centroid, set 1e-6 of the part's extent off the face along its normal, is not inside
the part. A face buried in another solid is not the part's surface and is left out. A face that crosses
another solid is taken whole by where its centroid is: left out, the depth by it reads greater than it is;
kept, a point by its buried stretch reads shallower than the part's surface is. Outside, the distance is to
the nearest face of all. An unknown part raises. Needs Blender's mathutils (BVHTree) for the nearest face."""
def __init__(self, shells, cap=None):
from mathutils import Vector
from mathutils.bvhtree import BVHTree
self.cap, self.asked, self.vector = cap, 0, Vector
self.rays = [Vector(ray).normalized() for ray in RAYS[:rays]]
self.trees = {part: [(BVHTree.FromPolygons(np.asarray(v, dtype=float).tolist(), [tuple(face) for face in f], epsilon=0.0),
np.min(v, axis=0), np.max(v, axis=0)) for v, f in made] for part, made in shells.items()}
@staticmethod
def crossings(tree, v, ray):
count, o = 0, v
for _ in range(64):
loc = tree.ray_cast(o, ray)[0]
if loc is None:
break
count, o = count + 1, loc + ray * 1e-6
return count
def inside(self, tree, v):
return 2 * sum(self.crossings(tree, v, ray) % 2 for ray in self.rays) > len(self.rays)
self.cap, self.asked, self.vector, self.parts = cap, 0, Vector, {}
for part, made in shells.items():
verts, faces, at = [], [], 0
for v, f in made:
v = np.asarray(v, dtype=float).reshape(-1, 3)
verts.append(v)
faces += [tuple(at + int(i) for i in face) for face in f]
at += len(v)
verts = np.concatenate(verts)
solids(part, verts, faces)
fan = np.array([(face[0], face[k], face[k + 1]) for face in faces for k in range(1, len(face) - 1)], dtype=int)
normal = np.zeros((len(faces), 3))
np.add.at(normal, np.repeat(np.arange(len(faces)), [len(face) - 2 for face in faces]), np.cross(verts[fan[:, 1]] - verts[fan[:, 0]], verts[fan[:, 2]] - verts[fan[:, 0]]))
size = np.linalg.norm(normal, axis=1)
flat = np.flatnonzero(size > 0.0) # a face of no area has no side to be exposed on
off = np.array([verts[list(faces[k])].mean(axis=0) for k in flat]) + 1e-6 * np.linalg.norm(np.ptp(verts, axis=0)) * normal[flat] / size[flat, None]
exposed = [faces[k] for k in flat[~inside(verts, fan, off)]]
if not exposed:
raise RamError("mesh", "signed", f"part {part!r} has no exposed face")
self.parts[part] = (BVHTree.FromPolygons(verts.tolist(), faces, epsilon=0.0), BVHTree.FromPolygons(verts.tolist(), exposed, epsilon=0.0), verts, fan)
def __call__(self, part, pts):
pts = np.asarray(pts, dtype=float)
pts = np.asarray(pts, dtype=float).reshape(-1, 3)
self.asked += len(pts)
tree, surface, verts, fan = self.parts[part]
out = np.full(len(pts), math.inf if self.cap is None else self.cap)
for tree, lo, hi in self.trees[part]:
boxed = ((pts >= lo) & (pts <= hi)).all(axis=1)
for i, p in enumerate(pts):
v = self.vector(p)
if boxed[i] and self.inside(tree, v):
out[i] = min(out[i], -tree.find_nearest(v)[3])
continue
hit = tree.find_nearest(v, self.cap) if self.cap else tree.find_nearest(v)
if hit[0] is not None and hit[3] < out[i]:
out[i] = hit[3]
for i in np.flatnonzero(inside(verts, fan, pts)):
out[i] = -surface.find_nearest(self.vector(pts[i]))[3]
for i in np.flatnonzero(out >= 0):
hit = tree.find_nearest(self.vector(pts[i]), self.cap) if self.cap else tree.find_nearest(self.vector(pts[i]))
if hit[0] is not None:
out[i] = hit[3]
return out

View file

@ -944,7 +944,10 @@ body whose rest frame it turns with), and `touch`: for each member (`barrel`, `r
bell crank's `rocker arm`), zones `(part, pin, radius, depth)`. Every member meets every part. A zone changes what
the member's samples keep from one part, and only within `radius` of the axis of `pin`, measured across the hinge
axis; the pin is one the member rides (the ram `a` and its eye, the rocker its pivot and `p`, the coupler `p` and
`c`, the arm the pivot and `d`). Inside the zone a sample may come as near the part as `-depth`; beyond it the
`c`, the arm the pivot and `d`), and the part is one of a body that pin joins: `a` the parent; the rocker's pivot
the parent and the rocker; `p` the rocker and the coupler; `c` the coupler and the child; a direct ram's `b` the
child; `d` the rocker (`JOINS`). A zone naming a part of any other body is refused by the record, whatever its
radius and depth. Inside the zone a sample may come as near the part as `-depth`; beyond it the
pair is checked like any other. Nothing is exempt by a name, by a length cut from a member's end, or by the
member's own body: the barrel runs from its back end, the rod to the eye, a bar from pin to pin. Every body of the
kind owns at least one part, or the gate refuses the record.
@ -964,7 +967,9 @@ to pin: a bar's length between its pins, and for the barrel and the rod the base
the centre the eye turns about, added. A `Mechanism` refuses a zone past that from its pins alone. Its depth is
also no more than the member's eye on that pin (`Ram.eye`: `e_a` at the base, `e_b` at the rod's eye, `link_r` on
a bar), which `from_record` and the gate refuse, so a world's answer is held to it as well. The record holds no
plate widths, so the radius has no tighter bound than the length.
plate widths, so the radius has no tighter bound than the length, and two zones of half a member's length about
its two pins cover it whole. What the record does hold is which body a part turns with: a member is let near only
what is pinned where it is pinned.
Between two samples of which either is in a zone the gate does not rely on the spacing. A distance changes by no
more than the way between two points, so along a segment it is at least (g(a) + g(b) - length) / 2. Where that
@ -975,7 +980,12 @@ samples' readings stand, so a burial is read to spacing / 128. This asks of the
than the true distance.
What it gives up: inside a zone the gate holds only the member's axis `depth` from the part, not its surface a
gap from it, so a link may graze the plate it scissors with anywhere within the stated radius. The members are
gap from it, so a link may graze the plate it scissors with anywhere within the stated radius. Among the parts of
the bodies a pin joins the gate still cannot tell a member's own plate from another: a zone over the whole member
lets its axis `depth` into any of them. A part of a third body is never zoned, so a plate stacked on a pin from a
body the pin does not join is refused where it stands; it is stated as a part of a body the pin joins. A four-bar's
eye rides `d`, which joins the rocker alone, though it stands on `p`: the ram is let near the coupler's plates
there by no zone. The members are
round bars; a plate's flat sides are not modelled, which is why stacked plates need a zone at all. The proof
between samples costs oracle calls: a depth stated with no slack over the burial (a bar's own plates at `link_r`)
is halved to the floor along the whole zone. And it is along the axis at each checked angle; between two angles
@ -996,20 +1006,20 @@ about R, and `d` about R for a bell crank, the eye standing at `a`'s place along
least arm; a miss returns the tally by gate and the nearest miss. Clearance takes `world(m) -> (parts, touch,
distance)`: a linkage's brackets and links are the candidate's own, so each candidate that reaches the gate is met
with the parts its own pins place. What `world` returns is read as a record's: anything but the three, a part on
no body of the kind, a zone that is not a part, a pin the member rides, a radius and a depth, or a zone wider or
deeper than its member is refused.
no body of the kind, a zone that is not a part, a pin the member rides, a radius and a depth, a zone of a body
its pin does not join, or a zone wider or deeper than its member is refused.
`swept` gives the ram's swept surface in any body's frame, for a recess.
### The record
`record` and `from_record` carry a mechanism as JSON: `schema` (`brokkr.ram`), `version` (1), `kind`, `hinge`,
`pins`, `offsets`, `ram`, `parts`, `touch` (member -> zones, each `{part, pin, radius, depth}`), and `compliance`.
It holds what is authored; barrel, closed length and link lengths are derived by the reader. `compliance` is
reserved for a load-path ram's settle (stiffness, damping, travel); version 1 writes it null and solves none. A
record of another schema or version (the integer 1: 1.0 and true are not it), with a key version 1 does not know or
without one it does (at the top, in `ram`, `hinge`, `pins` or a zone), with a compliance block, or with a value
that is not its field's (a finite number, the bore over 0, three numbers for a point), or with a zone wider or
deeper than its member is refused whole, as a
`record` and `from_record` carry a mechanism as JSON: `schema` (`brokkr.ram`), `version` (2), `kind`, `hinge`,
`pins`, `offsets`, `ram`, `parts` and `touch` (member -> zones, each `{part, pin, radius, depth}`).
It holds what is authored; barrel, closed length and link lengths are derived by the reader. It holds nothing of
how a load-path cylinder settles: that is a slide joint's, in the joint's own record. A
record of another schema or version (the integer 2: 2.0 and true are not it), with a key version 2 does not know or
without one it does (at the top, in `ram`, `hinge`, `pins` or a zone), or with a value
that is not its field's (a finite number, the bore over 0, three numbers for a point), or with a zone of a body
its pin does not join, or wider or deeper than its member, is refused whole, as a
`RamError` that names the field: a reader never reads past what it cannot solve. A `Ram` built by hand refuses the
same numbers.
@ -1020,11 +1030,34 @@ Bore 0.042, range 0..-125. The kinematic rows are tests/test_ram.py's. The clear
test generates (thigh with its front plate, shin with caps and armour, the bracket that carries R, the horn that
carries `c`, twin link plates stacked 5 mm apart at x 0.31..0.345 and 0.35..0.385, pins through the knee's width,
collars at the eye and a base clevis whose foot runs 0.01 into the thigh; 12 parts) and the package's signed BVH
oracle, `ram.Signed(shells, cap)`: the nearest face for the depth, the crossing parity of three rays, by majority,
for the side. One ray that runs through an edge or a vertex miscounts and signs a sample inside a plate it stands
clear of. `tests/fixtures/ram_rays.json` holds the ray count: the rocker plates as the joint library builds them
and 24 points between the plates, each on the first ray short of an edge or a vertex. One ray signs all 24
inside; three sign none. Three rays are not a proof: of 146 such points one ray missigned, two rays missigned 16.
oracle, `ram.Signed(shells, cap)`: the nearest face for the depth, the generalized winding number for the side
(Jacobson, Kavan and Sorkine-Hornung 2013). `ram.winding` sums the signed solid angle of every triangle of the part
about the point, over 4 pi: about a closed mesh the whole number of times the surface wraps the point, 0 outside, 1
inside, 2 where two solids overlap. A point is inside the part at 0.5 or more. The joint library's plates are one
mesh of four bars, a side's two overlapping about the pivot (`tests/fixtures/ram_plates.json`, with 29 points
inside them, 13 inside two bars): each reads inside, as does the overlap of two boxes welded at a corner and a
staircase prism a line crosses six times.
`Signed` checks what the winding number needs before it answers, and refuses a part by its reason when the oracle is
made (`ram.solids`, a `RamError` at gate `signed`). A part's faces fall into solids, the faces joined across an
edge. Every solid is closed: each edge one face runs is run the other way by another, and a solid with an edge
that is not (a boundary edge, or two faces wound against each other) is refused with the count of such edges. Every
solid is wound counterclockwise seen from outside: one of negative volume is refused with its number, its first
face and its volume, a turned-over bar beside a whole cube included, whose volume in all is positive. Nothing is
repaired or guessed. The shipped plates are four closed solids of 84 faces each, and the 12 parts of both R-3 knees
pass. What it gives up: a part exported open is capped before it is given, a part mirrored by a negative scale has
its faces turned back, and a cavity cut as its own inward shell is refused with the inside-out solids.
With every solid closed the number is whole, so `ram.inside` reads the same at any bound over 0 and up to 1; 0.5 is
pinned in the unit suite on a test-only open cube, where the number is 0.527 under the hole and 0.473 over it.
Outside, the distance is to the nearest face of all. Inside, the depth is to the nearest exposed face: one whose
centroid, set 1e-6 of the part's extent off the face along its normal, is not inside the part. A face buried in
another of the part's solids is left out, so a pin sunk 0.056 into a slab with a thin sheet buried along it reads
0.056 and is refused by a zone of depth 0.01. A face that crosses another solid is kept or left whole by where its
centroid is, not split: left out, the depth by it reads greater than it is, which the gate takes as a refusal;
kept, a point by its buried stretch reads shallower than the union's surface is (a boss through a wall: 0.500 for
0.502 and 0.539 for 0.583 in the live readings).
| drive | reading |
| --- | --- |
@ -1039,8 +1072,14 @@ Cost on Starfire, Python 3.13, 100 repetitions paired and interleaved: one candi
49 steps took 0.79 ms median on the bell crank; its clearance against the analytic parts (50 pairs) took 42 ms
(5th to 95th percentile 38 to 57) over 97,875 points, of which 23,520 are the samples and the rest the halving in
zones (the own plates, stated with no slack, to the floor); the samples alone took 11 ms. A search without a world ran 1.6 to 1.8 ms a candidate over 3,456, so `limit`
(20,000) is 30 to 40 s. On the meshes the bell crank's 60 pairs at 49 steps took 1.95 to 2.12 s capped (two runs), in a
Python loop of BVH queries with three rays a sample, and the 13,824-candidate search with its 22 worlds 43 s (one run).
(20,000) is 30 to 40 s. On the meshes the bell crank's 60 pairs at 49 steps took 0.80 to 1.00 s capped (two runs), the
winding number as the plain sum over a part's 124 to 408 triangles in numpy (single precision over double offsets,
blocks of 32,768 pairs) and the depth a Python loop of BVH queries, and the 13,824-candidate search with its 22
worlds 34.5 and 38.5 s (two runs) on a quiet machine. With the angles in double precision the search took 47.7 to
47.9 s (three runs). The live result reports the search's seconds as a reading and no check holds it: beside other
agents' Blenders at full load the same search took 61 to 94 s. With the refusals and
the exposed faces found as each of its 22 worlds is made it took 66.8 s, run after 59.3 s for the oracle before
them under that load (one pair); finding the solids of a 336-face part takes 1.6 ms.
## The actions

File diff suppressed because one or more lines are too long

View file

@ -9,9 +9,11 @@ Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USE
without them). <out> is an absolute path; writes <out>.result.json and <out>.r3_<angle>.png (the bell crank at 0,
-62.5 and -125) and exits 1 when a check failed.
The oracle is ram.Signed, three rays by majority. Its ray count is held by tests/fixtures/ram_rays.json: the rocker
plates as Imagination's jointlib builds them and points between the plates that stand on the first ray short of an
edge or a vertex. One ray reads them inside a plate they stand clear of; the oracle as it is made reads none inside.
The oracle is ram.Signed: a point is inside a part where the winding number of the part's faces about it is 0.5 or
more. tests/fixtures/ram_plates.json holds the rocker plates as Imagination's jointlib builds them, four closed bars
joined into one mesh, a side's two overlapping, and 29 points inside them: none reads outside. Nor does a point where
two welded boxes overlap. A part that is open or wound inside out is refused when the oracle is made, and the depth
is to the part's surface: a face buried in another of the part's solids is not read.
A clearance verdict is a sign, the gate's own. FLAT follows lodur:ruling:deterministic-bound-margin. The checks run
inside one try: an uncaught error is a failed check that names its section, and the result file is always written.
@ -304,32 +306,74 @@ try:
# plates and none is inside; where the plate is under the point the reading is the 0.0225
ys, zs = np.meshgrid(np.linspace(0.1, 0.9, 96), np.linspace(0.1, 0.7, 72))
plane = np.stack([np.full(ys.size, X_C), ys.ravel(), zs.ravel()], axis=1)
three, one = Signed(shells)("rocker.plate", plane), Signed(shells, rays=1)("rocker.plate", plane)
off_plates = Signed(shells)("rocker.plate", plane)
def off(a, b): # each grid point's distance from the segment a -> b, across the axis
a, b = np.array(a), np.array(b)
t = np.clip(((plane[:, 1:] - a) @ (b - a)) / ((b - a) @ (b - a)), 0.0, 1.0)
return np.linalg.norm(plane[:, 1:] - a - t[:, None] * (b - a), axis=1)
under = (off(CRANK["rocker"], CRANK["p"]) < W_ROCKER - 0.005) | (off(CRANK["rocker"], CRANK["d"]) < W_ARM - 0.005)
RES["readings"]["FLAT"] = float(np.abs(three[under] - (SLAB_R[0] - X_C)).max())
RES["readings"]["one ray: samples signed inside, of %d" % len(plane)] = int((one < 0).sum())
check("three-rays: on a plane 0.0225 off the rocker plates no sample reads inside or nearer, and under a plate each reads the 0.0225",
(three >= SLAB_R[0] - X_C - FLAT).all() and under.sum() > 500 and RES["readings"]["FLAT"] < FLAT, [float(three.min()), int(under.sum()), RES["readings"]["FLAT"]])
# against shells whose inside is known in closed form: a box and a disc, random points, each ray's edges and vertices among them
RES["readings"]["FLAT"] = float(np.abs(off_plates[under] - (SLAB_R[0] - X_C)).max())
check("off-the-plates: on a plane 0.0225 off the rocker plates no sample reads inside or nearer, and under a plate each reads the 0.0225",
(off_plates >= SLAB_R[0] - X_C - FLAT).all() and under.sum() > 500 and RES["readings"]["FLAT"] < FLAT, [float(off_plates.min()), int(under.sum()), RES["readings"]["FLAT"]])
# against a shell whose inside is known in closed form: a box, random points
rng = np.random.default_rng(7)
cloud = rng.uniform((-0.2, -0.2, 0.2), (0.2, 0.2, 1.25), (4000, 3))
core = Signed({"core": [box((0, 0, 0.725), (0.26, 0.28, 0.85))]})("core", cloud)
exact = np.maximum.reduce([np.abs(cloud[:, 0]) - 0.13, np.abs(cloud[:, 1]) - 0.14, np.abs(cloud[:, 2] - 0.725) - 0.425])
check("three-rays: 4000 random points about a box are signed as the box signs them", ((core < 0) == (exact < 0)).all(), int(((core < 0) != (exact < 0)).sum()))
check("box: 4000 random points about a box are signed as the box signs them", ((core < 0) == (exact < 0)).all(), int(((core < 0) != (exact < 0)).sum()))
# the ray count: the jointlib rocker plates, and points between them aimed along the first ray at an edge or a vertex
fixture = json.loads((SURFACE / "tests" / "fixtures" / "ram_rays.json").read_text(encoding="utf-8"))
plates, aimed = {"plates": [(np.array(fixture["verts"]), fixture["faces"])]}, np.array(fixture["points"])
made, single = Signed(plates)("plates", aimed), Signed(plates, rays=1)("plates", aimed)
RES["readings"]["jointlib plates: points one ray signs inside, of %d" % len(aimed)] = int((single < 0).sum())
RES["readings"]["jointlib plates: points the oracle signs inside"] = int((made < 0).sum())
# one ray reads all 24 inside; the oracle as made reads none. The bound on one ray's count is the geometric mean of 1 and 24
check("ray-count: between the jointlib rocker plates, points on the first ray short of an edge or a vertex read outside by the oracle as it is made, inside by one ray",
(np.abs(aimed[:, 0]) < 0.349).all() and (made > 0).all() and (single < 0).sum() >= 5, [int((made < 0).sum()), int((single < 0).sum())])
# what the gate's proof between samples leans on: no point inside a part reads outside. The jointlib rocker plates
# are four closed bars in one mesh, a side's two overlapping about the pivot (crossing parity read the overlap
# outside); the fixture's 29 points are 0.001 or more inside a bar, 13 of them inside two. A count of points
fixture = json.loads((SURFACE / "tests" / "fixtures" / "ram_plates.json").read_text(encoding="utf-8"))
plates = Signed({"plates": [(np.array(fixture["verts"]), fixture["faces"])]})("plates", np.array(fixture["inside"]))
# two boxes cut through one another and welded at the corner they share
def wound(lo, hi):
verts = np.array([[x, y, z] for x in (lo[0], hi[0]) for y in (lo[1], hi[1]) for z in (lo[2], hi[2])], float)
return verts, [(0, 1, 3, 2), (4, 6, 7, 5), (0, 4, 5, 1), (2, 3, 7, 6), (0, 2, 6, 4), (1, 5, 7, 3)]
(v1, f1), (v2, f2) = wound((0, 0, 0), (1, 1, 1)), wound((0, 0, 0), (2, 0.5, 0.5))
welded = (np.concatenate([v1, v2[1:]]), f1 + [tuple(i + 7 if i else 0 for i in face) for face in f2])
cloud = rng.uniform(-0.2, 2.2, (6000, 3))
truth = ((cloud >= 0) & (cloud <= 1)).all(axis=1) | ((cloud >= 0) & (cloud <= (2, 0.5, 0.5))).all(axis=1)
both = ((cloud >= 0) & (cloud <= (1, 0.5, 0.5))).all(axis=1)
got = Signed({"welded": [welded]})("welded", cloud) < 0
RES["readings"]["jointlib plates: inside points read outside, of %d" % len(plates)] = int((plates >= 0).sum())
RES["readings"]["welded boxes: points missigned, of %d (%d in the overlap)" % (len(cloud), int(both.sum()))] = int((got != truth).sum())
check("inside-reads-inside: no point inside the jointlib rocker plates' bars or in two welded boxes' overlap reads outside, and none outside the boxes reads inside",
len(plates) == 29 and int((plates >= 0).sum()) == 0 and int(both.sum()) > 50 and int((got != truth).sum()) == 0,
[int((plates >= 0).sum()), int(both.sum()), int((got != truth).sum())])
# a part with no inside to sign is refused when the oracle is made, by its reason: a cube with its top off, or
# two adjacent faces off, is open; a cube turned over, mirrored, or a turned-over bar beside a whole cube (a
# positive volume in all) is wound inside out. Every part of both knees made here passed the same two checks
turned = [face[::-1] for face in f1]
said = {}
for name, made in (("top off", [(v1, [face for face in f1 if face != (1, 5, 7, 3)])]), ("two faces off", [(v1, [face for face in f1 if face not in ((1, 5, 7, 3), (2, 3, 7, 6))])]),
("turned over", [(v1, turned)]), ("mirrored", [(v1 * (-1, 1, 1), f1)]), ("a turned-over bar beside a cube", [(v1, f1), (v2 + (0, 2, 0), [face[::-1] for face in f2])])):
try:
Signed({"cube": made})
said[name] = None
except R.RamError as error:
said[name] = str(error)
RES["refusals"] = said
want = {"top off": "is open: solid 0 of 1 has 4 edges", "two faces off": "is open: solid 0 of 1 has 6 edges", "turned over": "is wound inside out: solid 0 of 1 (6 faces from face 0) has volume -1",
"mirrored": "is wound inside out: solid 0 of 1 (6 faces from face 0) has volume -1", "a turned-over bar beside a cube": "is wound inside out: solid 1 of 2 (6 faces from face 6) has volume -0.5"}
check("no-inside-is-refused: an open part is refused by its solid and edge count, an inside-out one by its solid and volume, a turned-over bar beside a whole cube included",
all(said[name] is not None and "part 'cube' " + text in said[name] for name, text in want.items()), said)
# the depth is to the part's surface, not to a face buried in another of its solids: a cube of half side 1 with a
# box of side 0.2 buried about (0.5, 0.5, 0.5) reads its own depth by the box and at its centre (the nearest face
# of all is the buried box's: 0.05 and 0.693). A boss through a wall is read, not checked: its side faces cross the
# wall and are kept whole by their centroids, so in the wall by the boss the depth reads to their buried stretch
cube, small = wound((-1, -1, -1), (1, 1, 1)), wound((0.4, 0.4, 0.4), (0.6, 0.6, 0.6))
boss = wound((0.9, -0.5, -0.5), (1.5, 0.5, 0.5))
at = np.array([(0.5, 0.5, 0.55), (0.0, 0.0, 0.0), (0.5, 0.5, 0.95), (0.5, 0.5, 0.5), (1.2, 0.0, 0.0)])
alone, buried, bossed = Signed({"p": [cube]})("p", at), Signed({"p": [cube, small]})("p", at), Signed({"p": [cube, boss]})("p", np.array([(0.95, 0.0, 0.0), (0.7, 0.0, 0.0), (1.2, 0.0, 0.0), (1.6, 0.0, 0.0)]))
RES["readings"]["buried box: depth by it, at the cube's centre, under the cube's face, at the box's centre; outside"] = buried.tolist()
RES["readings"]["boss through a wall (faces that cross a solid are kept or left whole): in both (the surface is 0.502 off), in the wall (0.583), in the boss (0.2), off it (0.1)"] = bossed.tolist()
check("depth-is-to-the-surface: a face buried in another solid of the part is not read: by a buried box the cube reads as the cube alone",
float(np.abs(buried - (-0.45, -1.0, -0.05, -0.5, 0.2)).max()) < FLAT and float(np.abs(buried - alone).max()) < FLAT,
[buried.tolist(), alone.tolist()])
SECTION[0] = "seat"
seat = np.concatenate([v for v, _ in shells["parent.seat"]])

View file

@ -7,17 +7,27 @@
"detail": null
},
{
"name": "three-rays: on a plane 0.0225 off the rocker plates no sample reads inside or nearer, and under a plate each reads the 0.0225",
"name": "off-the-plates: on a plane 0.0225 off the rocker plates no sample reads inside or nearer, and under a plate each reads the 0.0225",
"ok": true,
"detail": null
},
{
"name": "three-rays: 4000 random points about a box are signed as the box signs them",
"name": "box: 4000 random points about a box are signed as the box signs them",
"ok": true,
"detail": null
},
{
"name": "ray-count: between the jointlib rocker plates, points on the first ray short of an edge or a vertex read outside by the oracle as it is made, inside by one ray",
"name": "inside-reads-inside: no point inside the jointlib rocker plates' bars or in two welded boxes' overlap reads outside, and none outside the boxes reads inside",
"ok": true,
"detail": null
},
{
"name": "no-inside-is-refused: an open part is refused by its solid and edge count, an inside-out one by its solid and volume, a turned-over bar beside a whole cube included",
"ok": true,
"detail": null
},
{
"name": "depth-is-to-the-surface: a face buried in another solid of the part is not read: by a buried box the cube reads as the cube alone",
"ok": true,
"detail": null
},
@ -108,21 +118,40 @@
"bell crank: least margin of a zoned pair, 251 steps uncapped": 0.000118,
"bell crank: pairs": 60,
"bell crank: pairs refused with nothing let": 19,
"bell crank: seconds, 49 steps capped": 2.12,
"bell crank: seconds, 49 steps capped": 1.34,
"bell crank: zoned pairs": 20,
"boss through a wall (faces that cross a solid are kept or left whole): in both (the surface is 0.502 off), in the wall (0.583), in the boss (0.2), off it (0.1)": [
-0.5,
-0.5385164618492126,
-0.2999999523162842,
0.10000002384185791
],
"buried box: depth by it, at the cube's centre, under the cube's face, at the box's centre; outside": [
-0.44999998807907104,
-1.0,
-0.050000011920928955,
-0.5,
0.20000004768371582
],
"four bar: barrel inside the shin's clearance": -0.122,
"jointlib plates: points one ray signs inside, of 24": 24,
"jointlib plates: points the oracle signs inside": 0,
"jointlib plates: inside points read outside, of 29": 0,
"moved x: both": -0.0543,
"moved x: the coupler at x 0.25, inside the horn's 0.23..0.31": -0.02,
"moved x: the rocker at x 0.25, inside the bracket's 0.13..0.35": -0.0543,
"one ray: samples signed inside, of 6912": 0,
"search: candidates": 13824,
"search: pass the gates before clearance": 78,
"search: refused on their own parts": 21,
"search: seconds": 43.3,
"search: seconds": 66.8,
"search: worlds built": 22,
"the base clevis's foot inside the thigh": -0.01
"the base clevis's foot inside the thigh": -0.01,
"welded boxes: points missigned, of 6000 (91 in the overlap)": 0
},
"refusals": {
"top off": "mesh ram: signed: part 'cube' is open: solid 0 of 1 has 4 edges no face runs the other way",
"two faces off": "mesh ram: signed: part 'cube' is open: solid 0 of 1 has 6 edges no face runs the other way",
"turned over": "mesh ram: signed: part 'cube' is wound inside out: solid 0 of 1 (6 faces from face 0) has volume -1",
"mirrored": "mesh ram: signed: part 'cube' is wound inside out: solid 0 of 1 (6 faces from face 0) has volume -1",
"a turned-over bar beside a cube": "mesh ram: signed: part 'cube' is wound inside out: solid 1 of 2 (6 faces from face 6) has volume -0.5"
},
"zones": {
"barrel[0] | parent.seat": {
@ -496,9 +525,9 @@
}
},
"renders": [
"F:/aeth-wt/fable-ramcore/scratch/h4/out/live_h4.r3_0.png",
"F:/aeth-wt/fable-ramcore/scratch/h4/out/live_h4.r3_62p5.png",
"F:/aeth-wt/fable-ramcore/scratch/h4/out/live_h4.r3_125.png"
"F:/aeth-wt/fable-ramlows/scratch/out/live_h4b.r3_0.png",
"F:/aeth-wt/fable-ramlows/scratch/out/live_h4b.r3_62p5.png",
"F:/aeth-wt/fable-ramlows/scratch/out/live_h4b.r3_125.png"
],
"ok": true
}

View file

@ -83,6 +83,40 @@ def yz(p, x=0.0):
return (x, float(p[0]), float(p[1]))
def block(lo, hi):
"""A box as a mesh: 8 vertices and 12 triangles wound counterclockwise seen from outside."""
lo, hi = np.asarray(lo, float), np.asarray(hi, float)
verts = np.array([[x, y, z] for x in (lo[0], hi[0]) for y in (lo[1], hi[1]) for z in (lo[2], hi[2])])
quads = ((0, 1, 3, 2), (4, 6, 7, 5), (0, 4, 5, 1), (2, 3, 7, 6), (0, 2, 6, 4), (1, 5, 7, 3))
return verts, np.array([t for a, b, c, d in quads for t in ((a, b, c), (a, c, d))])
def joined(first, second, weld):
"""Two meshes as one; with `weld`, vertices of the second that stand on one of the first take its index."""
(v1, t1), (v2, t2) = first, second
verts, index = [tuple(p) for p in v1], []
for p in map(tuple, v2):
if weld and p in verts:
index.append(verts.index(p))
else:
index.append(len(verts))
verts.append(p)
return np.array(verts), np.concatenate([t1, np.array(index)[t2]])
def staircase():
"""A prism of three steps along y from 0 to 1: under z = 1 for x in 0..1, z = 2 for 1..2, z = 3 for 2..3."""
profile = ((0, 0), (3, 0), (3, 3), (2, 3), (2, 2), (1, 2), (1, 1), (0, 1)) # (x, z)
verts = np.array([(x, y, z) for y in (0.0, 1.0) for x, z in profile], float)
tris = []
for k in range(8):
n = (k + 1) % 8
tris += [(k, n + 8, n), (k, k + 8, n + 8)]
for a, b, c in ((0, 1, 6), (0, 6, 7), (1, 4, 5), (1, 5, 6), (1, 2, 3), (1, 3, 4)): # the cap at y = 0, and at y = 1 turned over
tris += [(a, b, c), (a + 8, c + 8, b + 8)]
return verts, np.array(tris)
def grid(lo, hi, counts):
lo, hi = np.asarray(lo, float), np.asarray(hi, float)
axes = [np.linspace(lo[k], hi[k], n) if n > 1 else np.array([(lo[k] + hi[k]) / 2]) for k, n in enumerate(counts)]
@ -499,6 +533,16 @@ SWING_BOUND = 0.81
TOGGLE_ARM = 0.0386
# The clearance gate's zones on the R-3 bell crank. A reading a hand value states is bounded by its deviation from it;
# a shipped deviation of 0 counts as half an ulp of the value (lodur:ruling:deterministic-bound-zero-reading).
ZONED = 2.2e-10 # a rocker sample against its own plates: shipped 0 (half an ulp of link_r, 1.7e-18), W1..W3 (a zone's edge strict, the first zone only, the last zone overriding) 0.0294 and 0.0914 off, separation 1.3e8 each side
BESIDE = 1.2e-10 # a wall 0.02 beside the coupler, read at the nearest sample: shipped 0 (half an ulp of 0.0242, 1.7e-18), B1 (the proof by the nearer end's reading less the span, which halves and reads beside the wall) 0.00423 off, separation 4.9e7 each side
FLOOR_UNDER = 0.319 # how near the axis a wall held outside reads as touched, in spacing / 64: shipped under 0.451, FINE 128 under 0.2255, separation 1.41 each side
FLOOR_OVER = 0.638 # shipped under 0.451, FINE 32 under 0.902, separation 1.41 each side
WHOLE = 3.8e-4 # a winding number against the count or share a hand value states: shipped 6.3e-6 at most (the plates; the angles are single precision), W1 (the denominator's a.b term without the third length) 0.0224 off on the open cube's axis, separation 60 each side
SPAN_RAM = 0.848 # the ram's span with its base 0.1 from the rocker's pivot: shipped 0.5390 (about that pivot), the span about the knee's pivot 1.3347, separation 1.57 each side
@unittest.skipIf(np is None, "numpy is not installed")
class DeepKnee(unittest.TestCase):
"""The R-3 knee over 0..-125 (probes P1 to P3)."""
@ -562,8 +606,9 @@ class DeepKnee(unittest.TestCase):
def test_a_part_in_the_rams_way_on_each_link(self):
# a lug on the rocker, then on the coupler, on the rod's axis 0.12 from the eye at -60: refused naming the part
# and its body. A zone about the eye lets the rod and the barrel by it only if it reaches the lug and is as
# deep as the lug; a zone of another member's changes nothing
# and its body. A zone about the eye lets the rod and the barrel by the rocker's only if it reaches the lug and
# is as deep as the lug; a zone of another member's changes nothing. The coupler's lug is let by no zone of
# the ram's: the eye's pin does not join the coupler
m, ram = r3("bell_crank", CRANK), R.Ram(BORE)
at = R.pose(m, -60.0)
on_rod = (at.eye - 0.12 * at.u)[:, None, :]
@ -574,13 +619,20 @@ class DeepKnee(unittest.TestCase):
def zones(radius, depth, members=("rod", "barrel")):
return {**touch, **{member: touch[member] + [("lug", "d" if member != "coupler" else "p", radius, depth)] for member in members}}
for label, given in (("nothing let", touch), ("the coupler's zone", zones(0.4, 0.02, ("coupler",))), ("a zone short of the lug", zones(0.1, 0.02)),
("a zone too shallow", zones(0.4, 0.01))):
if body == "coupler": # d joins the rocker alone: no zone of the ram's names a part of the coupler
with self.assertRaises(R.RamError) as caught:
dressed(m, bodies, zones(0.4, 0.02))
self.assertEqual((caught.exception.gate, caught.exception.pin), ("record", "barrel lug pin"))
self.assertIn("a body the pin joins (rocker); 'lug' turns with coupler", str(caught.exception))
for label, given in (("nothing let", touch), ("the coupler's zone", zones(0.4, 0.02, ("coupler",))),
*((("a zone short of the lug", zones(0.1, 0.02)), ("a zone too shallow", zones(0.4, 0.01))) if body == "rocker" else ())):
with self.assertRaises(R.RamError) as caught:
R.fit(dressed(m, bodies, given), ram, steps=49, distance=bodies)
self.assertEqual((caught.exception.gate, caught.exception.fit.clear_at[2]), ("clash", "lug"), (body, label))
self.assertIn(caught.exception.fit.clear_at[1], ("rod[0]", "barrel[0]"))
self.assertIn(f"part 'lug' ({body})", str(caught.exception))
if body == "coupler":
continue
f = R.fit(dressed(m, bodies, zones(0.4, 0.02)), ram, steps=49, distance=bodies)
self.assertIn(("rod[0]", "lug"), f.allowed)
self.assertNotIn(("rocker arm", "lug"), f.allowed)
@ -645,16 +697,26 @@ class DeepKnee(unittest.TestCase):
self.assertAlmostEqual(R._span(m, "rocker arm"), 0.24, places=9)
self.assertGreaterEqual(R._span(m, "rod"), float(R.pose(m, np.linspace(-125.0, 0.0, 126)).L.max()))
self.assertEqual([ram.eye(*of) for of in (("barrel", "a"), ("rod", "a"), ("rod", "d"), ("coupler", "c"))], [ram.e_a, ram.e_a, ram.e_b, ram.link_r])
for member, pin in (("barrel", "a"), ("rod", "d"), ("rocker", "p"), ("coupler", "c"), ("rocker arm", "rocker")):
# a linkage's ram spans from the rocker's pivot, which its eye turns about, not the knee's: a base seated 0.1
# from the rocker's pivot makes a ram of 0.539 at the most, and a zone between that and the 1.335 the knee's
# pivot would give is refused
seated = replace(m, a=m.rocker + (0.0, 0.0, 0.1), parts=bodies.parts)
self.assertAlmostEqual(R._span(seated, "rod"), 0.1 + math.hypot(X_ROCKER, 0.24), places=12)
for member in ("barrel", "rod"):
replace(seated, touch={member: [("thigh", "a", 0.53, 0.0)]})
with self.assertRaises(R.RamError) as caught:
replace(seated, touch={member: [("thigh", "a", SPAN_RAM, 0.0)]})
self.assertEqual((caught.exception.gate, caught.exception.pin), ("record", f"{member} thigh radius"))
for member, pin, part in (("barrel", "a", "thigh"), ("rod", "d", "pin d"), ("rocker", "p", "coupler plates"), ("coupler", "c", "horn"), ("rocker arm", "rocker", "bracket")):
span, eye = R._span(m, member), ram.eye(member, pin)
def zoned(radius, depth):
return dressed(m, bodies, {member: [("thigh", pin, radius, depth)]})
return dressed(m, bodies, {member: [(part, pin, radius, depth)]})
zoned(span, 0.0)
for radius, depth, field in ((1.2 * span, 0.0, "radius"), (1e308, 0.0, "radius"), (1e9, 1e9, "radius"), (0.1, 1.2 * span, "depth"), (0.1, 1e308, "depth")):
with self.assertRaises(R.RamError) as caught:
zoned(radius, depth)
self.assertEqual((caught.exception.gate, caught.exception.pin), ("record", f"{member} thigh {field}"))
self.assertEqual((caught.exception.gate, caught.exception.pin), ("record", f"{member} {part} {field}"))
self.assertIn(f"{member} is at most {span:.4f} from pin to pin", str(caught.exception))
R.clearance(zoned(0.1, eye), ram, [-60.0], bodies)
wrote = R.record(zoned(0.1, eye), ram)
@ -664,19 +726,66 @@ class DeepKnee(unittest.TestCase):
lambda: R.from_record(wrote)):
with self.assertRaises(R.RamError) as caught:
read()
self.assertEqual((caught.exception.gate, caught.exception.pin), ("record", f"{member} thigh depth"))
self.assertEqual((caught.exception.gate, caught.exception.pin), ("record", f"{member} {part} depth"))
self.assertIn(f"{member}'s on {pin} is {eye:.4f}", str(caught.exception))
def test_a_zone_names_a_part_of_a_body_its_pin_joins(self):
# Soul's whole-member zones: two of 0.51 of its length about p and c covered the coupler and let its axis
# 0.0294 into a capsule of the thigh. No bound on a radius stops that; the record says which bodies a pin
# joins, and a part of any other is zoned about it by no member, whatever the radius and depth
joins = {"a": ("parent",), "b": ("child",), "rocker": ("parent", "rocker"), "p": ("rocker", "coupler"), "c": ("coupler", "child"), "d": ("rocker",)}
for m in (R.Mechanism("direct", O, X, -62, 0, a=(0.05, -0.3, 0.8), b=(0.05, -0.3, -0.6)), r3("four_bar", DEEP), r3("bell_crank", CRANK)):
parts = {"of " + body: body for body in R.BODIES[m.kind]}
for member in R.MEMBERS[m.kind]:
for pin in R.RIDES[m.kind][member]:
for part, body in parts.items():
zone = {member: [(part, pin, 0.01, 0.0)]}
if body in joins[pin]:
self.assertEqual(replace(m, parts=parts, touch=zone).touch[member], ((part, pin, 0.01, 0.0),))
continue
with self.assertRaises(R.RamError) as caught:
replace(m, parts=parts, touch=zone)
self.assertEqual((caught.exception.gate, caught.exception.pin), ("record", f"{member} {part} pin"), (m.kind, member, pin, body))
self.assertIn(f"{member} may touch about {pin} a part of a body the pin joins ({', '.join(joins[pin])}); "
f"'{part}' turns with {body}", str(caught.exception))
# Soul's capsule of the parent under the coupler, zoned as the probe zoned it: refused by the record, by
# from_record and as a world's answer; the shipped zones, each a part of a body its pin joins, are read
m, ram = r3("bell_crank", CRANK), R.Ram(BORE)
bodies, touch = r3_bodies(m, ram)
wire = json.loads(json.dumps(R.record(dressed(m, bodies, touch), ram)))
self.assertEqual(R.from_record(wire)[0].touch, dressed(m, bodies, touch).touch)
bodies.parts["under"], bodies.shapes["under"] = "parent", [("capsule", (X_COUPLER, 0.5, 0.2), (X_COUPLER, 0.6, 0.3), 0.08)]
halves = [("under", "p", 0.51 * m.lc, ram.link_r), ("under", "c", 0.51 * m.lc, ram.link_r)]
wire["parts"]["under"] = "parent"
for k, zone in enumerate(halves):
given = {**touch, "coupler": touch["coupler"] + halves[k:]}
wrote = {**wire, "touch": {**wire["touch"], "coupler": wire["touch"]["coupler"] + [dict(zip(R.ZONE, zone))]}}
hinge, seat = {"pivot": O, "axis": X, "lo": -125, "hi": 0}, {name: [getattr(m, name)] for name in ("a", "rocker", "c")}
for read in (lambda: dressed(m, bodies, given), lambda: R.from_record(wrote),
lambda: R.search("bell_crank", hinge, ram, {**seat, "link": (m.lr, m.lr, 1), "d": (0.24, 0.24, 1)}, world=lambda made: (bodies.parts, given, bodies))):
with self.assertRaises(R.RamError) as caught:
read()
self.assertEqual((caught.exception.gate, caught.exception.pin), ("record", "coupler under pin"))
self.assertIn(f"about {zone[1]} a part of a body the pin joins", str(caught.exception))
# the body is refused before the zone is measured: a zone both foreign and wider than its member names the pin
with self.assertRaises(R.RamError) as caught:
dressed(m, bodies, {"coupler": [("under", "p", 1e9, 0.0)]})
self.assertEqual(caught.exception.pin, "coupler under pin")
def test_a_wall_the_axis_crosses_in_a_zone_is_read_whatever_its_thickness(self):
# Soul's tunnel: a wall of the thigh across the coupler, midway between two of its samples, inside a zone
# about p of depth 0. Every sample stands outside it; the segment between them is what crosses
# Soul's tunnel: a wall of the rocker across the coupler, midway between two of its samples, inside a zone
# about p of depth 0. Every sample stands outside it; the segment between them is what crosses. The wall is
# the rocker's, which p joins, and stands in the rocker's frame, where the coupler's samples at -60 are `samples`
m, ram = r3("bell_crank", CRANK), R.Ram(BORE)
at = R.pose(m, -60.0)
start = at.P[0] - np.array(X) * ((at.P[0] - at.C[0]) @ np.array(X))
count = int(math.ceil(m.lc / ram.spacing())) + 1
samples = start + (at.C[0] - start) * np.linspace(0.0, 1.0, count)[:, None]
def seen(n, body="rocker"):
return R._into(m, at, body, (start + (at.C[0] - start) * np.linspace(0.0, 1.0, n)[:, None])[None])[0]
samples = seen(count)
spot = 0.5 * (samples[2] + samples[3])
along = (at.C[0] - start) / m.lc
along = (samples[-1] - samples[0]) / m.lc
k = 1 if abs(along[1]) > abs(along[2]) else 2
def reading(half, shift=0.0):
@ -684,26 +793,41 @@ class DeepKnee(unittest.TestCase):
lo[k], hi[k] = spot[k] - half, spot[k] + half
lo[0], hi[0] = X_COUPLER - 0.05 + shift, X_COUPLER + 0.05 + shift
bodies = r3_parts(m, ram)
bodies.parts["wall"], bodies.shapes["wall"] = "parent", [("box", lo, hi)]
self.assertGreater(float(bodies("wall", samples).min()), 0.0)
bodies.parts["wall"], bodies.shapes["wall"] = "rocker", [("box", lo, hi)]
reading.sampled = float(bodies("wall", samples).min())
self.assertGreater(reading.sampled, 0.0)
return R.clearance(dressed(m, bodies, {"coupler": [("wall", "p", 0.28, 0.0)]}), ram, [-60.0], bodies).pairs[("coupler", "wall")][0]
for half in (0.01, 0.003, 1e-4, 1e-7, 1e-10):
self.assertLess(reading(half), 0.0, half)
# the same walls beside the axis, 0.02 off along the hinge axis: held outside, and let
# the same walls beside the axis, 0.02 off along the hinge axis: held outside, and let. The samples either
# side prove the segment, so the reading is the nearer sample's (0.0242: 0.02 across, 0.0137 along), not the
# 0.02 a point between them would read
for half in (0.01, 1e-7):
self.assertGreaterEqual(reading(half, 0.07), 0.02)
# nearer the axis than the floor of the halving, a part the axis is held outside reads as touched
self.assertLess(reading(0.01, 0.05 + 0.2 * ram.spacing() / R.FINE), 0.0)
self.assertGreaterEqual(reading(0.01, 0.05 + 1.2 * ram.spacing() / R.FINE), 0.0)
self.assertLess(abs(reading(half, 0.07) - reading.sampled), BESIDE, half)
self.assertGreater(reading.sampled, 0.024)
# nearer the axis than the floor of the halving, a part the axis is held outside reads as touched. The floor is
# the spacing over 64, written here as the number: the doc's, and what the gate's cost was measured at
self.assertEqual(R.FINE, 64)
self.assertLess(reading(0.01, 0.05 + FLOOR_UNDER * ram.spacing() / 64), 0.0)
self.assertGreaterEqual(reading(0.01, 0.05 + FLOOR_OVER * ram.spacing() / 64), 0.0)
# a segment with one end in the zone is proved as well. Sampled 0.3 apart, the sample beyond the zone keeps its
# 0.186 from a bead on the axis 0.008 past the last sample in the zone; the bead is read all the same
wide = start + (at.C[0] - start) * np.linspace(0.0, 1.0, 3)[:, None]
wide = seen(3)
bodies, spot = r3_parts(m, ram), wide[1] + 0.012 * along
bodies.parts["bead"], bodies.shapes["bead"] = "parent", [("capsule", spot, spot, 0.004)]
bodies.parts["bead"], bodies.shapes["bead"] = "rocker", [("capsule", spot, spot, 0.004)]
self.assertGreater(float(bodies("bead", wide[:2]).min()), 0.0)
self.assertGreaterEqual(float(bodies("bead", wide[2:])[0]), near(ram, "coupler", 0.3))
got = R.clearance(dressed(m, bodies, {"coupler": [("bead", "p", 0.25, 0.0)]}), ram, [-60.0], bodies, spacing=0.3)
self.assertLess(got.pairs[("coupler", "bead")][0], 0.0)
# and so is the segment whose far end alone is in the zone: a bead of the shin 0.008 short of the first sample
# in a zone about c, the sample before it out of the zone and keeping its 0.186
wide = seen(3, "child")
bodies, spot = r3_parts(m, ram), wide[1] - 0.012 * (wide[2] - wide[0]) / m.lc
bodies.parts["bead"], bodies.shapes["bead"] = "child", [("capsule", spot, spot, 0.004)]
self.assertGreater(float(bodies("bead", wide[1:]).min()), 0.0)
self.assertGreaterEqual(float(bodies("bead", wide[:1])[0]), near(ram, "coupler", 0.3))
got = R.clearance(dressed(m, bodies, {"coupler": [("bead", "c", 0.25, 0.0)]}), ram, [-60.0], bodies, spacing=0.3)
self.assertLess(got.pairs[("coupler", "bead")][0], 0.0)
def test_two_zones_of_one_pair_and_a_sample_at_a_zones_radius(self):
# Soul's W1..W3. A pair zoned twice: a sample both reach is let the deeper, in either order, and each zone
@ -718,8 +842,11 @@ class DeepKnee(unittest.TestCase):
self.assertAlmostEqual(reading(deep, beside, far), 0.0, places=12)
self.assertAlmostEqual(reading(beside, deep, far), 0.0, places=12)
self.assertAlmostEqual(reading(far, beside, deep), 0.0, places=12)
for short in ((beside, beside, far), (deep, beside), (far, deep[:2] + (0.3 * m.lr, ram.link_r))):
self.assertLess(reading(*short), -0.9 * ram.link_r, short)
# short of that the sample reads what it is: link_r inside its own plate where the zone holds it outside, and
# where no zone reaches it link_r inside and all it keeps short
own = ram.link_r + near(ram, "rocker")
for short, reads in (((beside, beside, far), -ram.link_r), ((deep, beside), -own), ((far, deep[:2] + (0.3 * m.lr, ram.link_r)), -own)):
self.assertLess(abs(reading(*short) - reads), ZONED, short)
at = R.pose(m, [-60.0])
end = at.P - np.array(X) * ((at.P - m.rocker) @ np.array(X))[:, None]
count = int(math.ceil(m.lr / ram.spacing())) + 1
@ -727,7 +854,7 @@ class DeepKnee(unittest.TestCase):
across = np.linalg.norm(R._flat(pts - m.rocker, np.array(X)), axis=2)[0]
edge, beyond = float(across[3]), m.lr - 0.5 * float(across[3] + across[4])
self.assertAlmostEqual(reading(("rocker plates", "rocker", edge, ram.link_r), ("rocker plates", "p", beyond, ram.link_r), degrees=[-60.0]), 0.0, places=12)
self.assertLess(reading(("rocker plates", "rocker", float(np.nextafter(edge, 0.0)), ram.link_r), ("rocker plates", "p", beyond, ram.link_r), degrees=[-60.0]), -0.9 * ram.link_r)
self.assertLess(abs(reading(("rocker plates", "rocker", float(np.nextafter(edge, 0.0)), ram.link_r), ("rocker plates", "p", beyond, ram.link_r), degrees=[-60.0]) + own), ZONED)
def test_a_pin_stood_inside_what_it_stands_beside_is_refused(self):
# Soul's moved-x probes: the rocker's x moved from its plate's place (0.3675) into the bracket's 0.13..0.35,
@ -843,8 +970,13 @@ class OracleRule(unittest.TestCase):
lugged = two(a=seats.shapes["a"] and ("parent", seats.shapes["a"]), b=("child", seats.shapes["b"]), **{"b.lug": ("child", seats.shapes["b"])})
got = R.clearance(dressed(m, lugged, zones), ram, 0.0, lugged)
self.assertEqual({pair: round(reading[0], 9) for pair, reading in got.pairs.items() if reading[0] < 0.0}, {("rod[0]", "b.lug"): round(-0.03 - near(ram, "rod"), 9)})
for crossed in ({"barrel": [("b", "b", 0.2, 0.03)], "rod": [("a", "a", 0.2, 0.03)]}, {"barrel": [("a", "b", 0.2, 0.03)], "rod": [("b", "a", 0.2, 0.03)]}):
self.assertLess(float(R.clearance(dressed(m, seats, crossed), ram, 0.0, seats).margin[0]), 0.0)
crossed = {"barrel": [("b", "b", 0.2, 0.03)], "rod": [("a", "a", 0.2, 0.03)]}
self.assertLess(float(R.clearance(dressed(m, seats, crossed), ram, 0.0, seats).margin[0]), 0.0)
# and a part zoned about the pin at the member's other end, which does not join its body, is no zone at all
for crossed, pin in (({"barrel": [("a", "b", 0.2, 0.03)]}, "barrel a pin"), ({"rod": [("b", "a", 0.2, 0.03)]}, "rod b pin")):
with self.assertRaises(R.RamError) as caught:
dressed(m, seats, crossed)
self.assertEqual((caught.exception.gate, caught.exception.pin), ("record", pin))
def test_every_body_owns_a_part(self):
ball = Bodies({"ball": ("parent", [("capsule", (0, 0, 0), (0, 0, 0), 0.1)])})
@ -942,19 +1074,20 @@ class SearchBestFirst(unittest.TestCase):
((ball.parts, {}, None), "search", "world(m) returns"), ((ball.parts, {"rod": ["parent"]}, ball), "record", "zone is (part, pin, radius, depth)"),
((ball.parts, {"rod": [("parent", "c", 1.0, 0.0)]}, ball), "record", "a pin it rides (a, b)"),
((ball.parts, {"rod": [("thigh", "b", 1.0, 0.0)]}, ball), "record", "no part of the record"),
((ball.parts, {"rod": [("parent", "b", 1e308, 0.0)]}, ball), "record", "rod is at most"),
((ball.parts, {"rod": [("parent", "b", 0.5, 1e308)]}, ball), "record", "rod is at most"),
((ball.parts, {"rod": [("parent", "b", 1e9, 1e9)]}, ball), "record", "rod is at most"),
((ball.parts, {"rod": [("parent", "b", float("inf"), 0.0)]}, ball), "record", "a finite number"),
((ball.parts, {"rod": [("parent", "b", 0.5, float("nan"))]}, ball), "record", "a finite number"),
((ball.parts, {"rod": [("parent", "b", 0.5, 1.2 * ram.e_b)]}, ball), "record", "rod's on b is 0.0850"),
((ball.parts, {"rod": [("child", "b", 1e308, 0.0)]}, ball), "record", "rod is at most"),
((ball.parts, {"rod": [("parent", "b", 0.5, 0.0)]}, ball), "record", "a body the pin joins (child); 'parent' turns with parent"),
((ball.parts, {"rod": [("child", "b", 0.5, 1e308)]}, ball), "record", "rod is at most"),
((ball.parts, {"rod": [("child", "b", 1e9, 1e9)]}, ball), "record", "rod is at most"),
((ball.parts, {"rod": [("child", "b", float("inf"), 0.0)]}, ball), "record", "a finite number"),
((ball.parts, {"rod": [("child", "b", 0.5, float("nan"))]}, ball), "record", "a finite number"),
((ball.parts, {"rod": [("child", "b", 0.5, 1.2 * ram.e_b)]}, ball), "record", "rod's on b is 0.0850"),
(({"ball": "rocker"}, {}, ball), "record", "turns with 'rocker'"), (({"ball": "parent"}, {}, ball), "record", "no part turns with body child")):
with self.assertRaises(R.RamError) as caught:
R.search("direct", self.HINGE, ram, seats, world=lambda m: made)
self.assertEqual(caught.exception.gate, gate, said)
self.assertIn(said, str(caught.exception))
self.assertTrue(R.search("direct", self.HINGE, ram, seats, world=lambda m: (ball.parts, {}, ball)).found)
self.assertTrue(R.search("direct", self.HINGE, ram, seats, world=lambda m: (ball.parts, {"rod": [("parent", "b", 0.5, ram.e_b)]}, ball)).found)
self.assertTrue(R.search("direct", self.HINGE, ram, seats, world=lambda m: (ball.parts, {"rod": [("child", "b", 0.5, ram.e_b)]}, ball)).found)
def test_the_limit_is_refused_naming_the_count(self):
seats = {"a": grid((0, -0.5, 0.4), (0, -0.2, 1.2), (1, 3, 5)), "b": grid((0, -0.5, -1.2), (0, -0.2, -0.4), (1, 3, 5))}
@ -1021,8 +1154,8 @@ class RecordDrives(unittest.TestCase):
data = R.record(m, ram)
wire = json.loads(json.dumps(data))
self.assertEqual(wire, data)
self.assertEqual(sorted(data), ["compliance", "hinge", "kind", "offsets", "parts", "pins", "ram", "schema", "touch", "version"])
self.assertEqual((data["schema"], data["version"], data["compliance"]), ("brokkr.ram", 1, None))
self.assertEqual(sorted(data), ["hinge", "kind", "offsets", "parts", "pins", "ram", "schema", "touch", "version"])
self.assertEqual((data["schema"], data["version"]), ("brokkr.ram", 2))
again, ram2 = R.from_record(wire)
self.assertEqual(R.record(again, ram2), data)
self.assertEqual((again.parts, again.touch), (m.parts, m.touch))
@ -1053,18 +1186,18 @@ class RecordDrives(unittest.TestCase):
def test_a_record_this_version_cannot_read_is_refused_whole(self):
data = R.record(R.Mechanism("direct", O, X, -62, 0, a=(0.05, -0.3, 0.8), b=(0.05, -0.3, -0.6)), R.Ram(BORE))
settle = {"stiffness": 2.0e6, "damping": 4.0e3, "travel": 0.02}
self.assertEqual(tuple(settle), R.COMPLIANCE)
ram = dict(data["ram"], stiffness=2.0e6)
short = {k: v for k, v in data.items() if k != "touch"}
for change, said in (({"version": 2}, "version 2"), ({"version": 2, "compliance": settle}, "version 2"), ({"compliance": settle}, "compliance block"),
for change, said in (({"version": 1}, "reads brokkr.ram version 2; the record is brokkr.ram version 1"), ({"version": 3}, "version 3"), ({"version": 1, "settle": settle}, "version 1"),
({"schema": "brokkr.kit"}, "brokkr.kit"), ({"settle": settle}, "unknown ['settle']"), ({"ram": ram}, "unknown ['stiffness']"),
({"hinge": dict(data["hinge"], rate=1.0)}, "unknown ['rate']"),
# a block that is falsy is a block (S23); the version is the integer 1
({"compliance": {}}, "compliance block"), ({"compliance": 0}, "compliance block"), ({"compliance": False}, "compliance block"),
({"version": 1.0}, "version 1.0"), ({"version": True}, "version True"), ({"version": "1"}, "version '1'"),
# a key the record does not know is refused whatever it holds, null and falsy included (S23): a ram
# record carries no settle. The version is the integer 2
({"settle": None}, "unknown ['settle']"), ({"settle": {}}, "unknown ['settle']"), ({"settle": False}, "unknown ['settle']"),
({"version": 2.0}, "version 2.0"), ({"version": True}, "version True"), ({"version": "2"}, "version '2'"),
({"kind": "scissor"}, "kind is one of"),
# a pin this kind has not, or a key that is no pin, is refused by name; so is one missing
({"pins": dict(data["pins"], q=[0.0, 0.0, 0.0])}, "the pins's keys are not version 1's: unknown ['q']"),
({"pins": dict(data["pins"], q=[0.0, 0.0, 0.0])}, "the pins's keys are not version 2's: unknown ['q']"),
({"pins": dict(data["pins"], parts={})}, "unknown ['parts']"), ({"pins": {"a": data["pins"]["a"]}}, "missing ['b']"),
({"pins": [1, 2]}, "(pin pins): an object, got list"), ({"ram": None}, "(pin ram): an object, got NoneType"),
# every number is a finite number, the bore over 0; three of them make a point
@ -1082,7 +1215,8 @@ class RecordDrives(unittest.TestCase):
({"parts": {"knee": "parent"}, "touch": {"rod": "knee"}}, "rod's zones are a list"),
({"parts": {"knee": "parent"}, "touch": {"rod": [{"part": "knee", "pin": "b", "radius": 0.1}]}}, "missing ['depth']"),
({"parts": {"knee": "parent"}, "touch": {"rod": [{"part": "knee", "pin": "b", "radius": 0.1, "depth": 0.0, "whole": True}]}}, "unknown ['whole']"),
({"parts": {"knee": "parent"}, "touch": {"rod": [{"part": "knee", "pin": "b", "radius": None, "depth": 0.0}]}}, "(pin rod knee radius)")):
({"parts": {"knee": "parent"}, "touch": {"rod": [{"part": "knee", "pin": "b", "radius": None, "depth": 0.0}]}}, "(pin rod knee radius)"),
({"parts": {"knee": "parent"}, "touch": {"rod": [{"part": "knee", "pin": "b", "radius": 0.1, "depth": 0.0}]}}, "(pin rod knee pin): rod may touch about b a part of a body the pin joins (child)")):
with self.assertRaises(R.RamError) as caught:
R.from_record({**data, **change})
self.assertEqual(caught.exception.gate, "record", change)
@ -1090,7 +1224,7 @@ class RecordDrives(unittest.TestCase):
with self.assertRaises(R.RamError) as caught:
R.from_record([data])
self.assertIn("a record is an object, got list", str(caught.exception))
zoned = R.from_record({**data, "parts": {"knee": "parent"}, "touch": {"rod": [{"part": "knee", "pin": "b", "radius": 0.1, "depth": 0}]}})[0]
zoned = R.from_record({**data, "parts": {"knee": "child"}, "touch": {"rod": [{"part": "knee", "pin": "b", "radius": 0.1, "depth": 0}]}})[0]
self.assertEqual(zoned.touch, {"rod": (("knee", "b", 0.1, 0.0),)})
# a ram refuses the same numbers when built by hand
for bad in ({"bore": -0.05}, {"bore": 0.0}, {"bore": None}, {"bore": True}, {"bore": 0.05, "gap": float("nan")}, {"bore": 0.05, "tail": float("inf")}, {"bore": 0.05, "rod": "0.02"}):
@ -1144,6 +1278,8 @@ class Refusals(unittest.TestCase):
self.refused("record", "rod knee radius", **knee, touch={"rod": [("knee", "d", "0.1", 0.0)]})
self.refused("record", "rod knee depth", **knee, touch={"rod": [("knee", "d", 0.1, -0.01)]})
self.refused("record", "rod knee depth", **knee, touch={"rod": [("knee", "d", 0.1, float("nan"))]})
self.assertIn("a body the pin joins (rocker); 'knee' turns with parent", str(self.refused("record", "rod knee pin", **knee, touch={"rod": [("knee", "d", 0.1, 0.0)]})))
self.assertEqual(R.Mechanism("four_bar", O, X, -125, 0, **{name: yz(DEEP[name]) for name in DEEP}, **knee, touch={"rod": [("knee", "a", 0.1, 0.0)]}).touch["rod"], (("knee", "a", 0.1, 0.0),))
self.refused("record", "a", a=(0, 1))
self.refused("record", "c", c=(0, float("nan"), 1))
self.refused("record", "b", b=(0, 0, -1)) # a four-bar has no b
@ -1167,6 +1303,111 @@ class Refusals(unittest.TestCase):
self.assertEqual((caught.exception.gate, caught.exception.pin), ("arm", "b"))
self.assertIn(f"arm at {caught.exception.angle:g} deg (pin b)", str(caught.exception))
def test_overlapping_solids_wind_by_their_count(self):
# two boxes that cut through one another in one mesh, each with its own vertices, then sharing the one index
# at the corner they have in common (all a merge by distance welds): the winding number is the count of
# boxes about the point, 2 in the overlap, where crossing parity read outside
big, small = block((0, 0, 0), (1, 1, 1)), block((0, 0, 0), (2, 0.5, 0.5))
pts = np.random.default_rng(1).uniform(-0.2, 2.2, (6000, 3))
count = sum(((pts >= lo) & (pts <= hi)).all(axis=1).astype(int) for lo, hi in (((0, 0, 0), (1, 1, 1)), ((0, 0, 0), (2, 0.5, 0.5))))
self.assertGreater(int((count == 2).sum()), 50)
for weld in (False, True):
verts, tris = joined(big, small, weld)
self.assertEqual(len(verts), 15 if weld else 16)
self.assertLess(float(np.abs(R.winding(verts, tris, pts) - count).max()), WHOLE, weld)
def test_the_plates_overlapping_bars_wind_by_their_count(self):
# the jointlib rocker plates: four closed bars in one mesh, a side's two overlapping. Every inside point of
# the fixture winds 1, or 2 where two bars overlap
fixture = json.loads((SURFACE / "tests" / "fixtures" / "ram_plates.json").read_text(encoding="utf-8"))
w = R.winding(fixture["verts"], fixture["faces"], fixture["inside"])
self.assertLess(float(np.abs(w - np.round(w)).max()), WHOLE)
self.assertEqual((int((np.round(w) == 1).sum()), int((np.round(w) == 2).sum())), (16, 13))
def test_a_staircase_winds_whole(self):
# a nonconvex prism of three steps, which a line crosses up to six times: 1 inside, 0 outside
verts, tris = staircase()
g = np.arange(-0.375, 3.5, 0.25)
pts = np.array([(x, y, z) for x in g for y in (-0.25, 0.125, 0.5, 0.875, 1.25) for z in g])
truth = (pts[:, 1] > 0) & (pts[:, 1] < 1) & (pts[:, 0] > 0) & (pts[:, 0] < 3) & (pts[:, 2] > 0) & (pts[:, 2] < np.ceil(pts[:, 0]))
self.assertGreater(min(int(truth.sum()), int((~truth).sum())), 200)
self.assertLess(float(np.abs(R.winding(verts, tris, pts) - truth).max()), WHOLE)
def test_an_open_cube_winds_by_what_its_hole_takes(self):
# a unit cube less its top face: about a point on the hole's axis the winding number is 1 less the hole's
# share of the sphere inside, and that share outside, 4 asin(a^2 / (a^2 + h^2)) of 4 pi for a square of half
# side a seen from h off its centre. So it is over 0.5 everywhere inside and under 0.5 over the hole, and
# passes through 0.5 on the hole's plane, where no face is. Less one triangle of the top it is the same
verts, tris = block((0, 0, 0), (1, 1, 1))
top = [k for k, t in enumerate(tris) if (verts[t][:, 2] == 1.0).all()]
self.assertEqual(len(top), 2)
z = np.array((0.5, 0.9, 0.999, 1.001, 1.1, 1.5))
share = np.arcsin(0.25 / (0.25 + (1.0 - z) ** 2)) / math.pi
w = R.winding(verts, np.delete(tris, top, axis=0), np.stack([np.full(6, 0.5), np.full(6, 0.5), z], axis=1))
self.assertLess(float(np.abs(w - np.where(z < 1, 1.0 - share, share)).max()), WHOLE)
self.assertTrue((w[:3] > 0.5).all() and (w[3:] < 0.5).all(), w.tolist()) # 0.001 under the plane 0.5009, 0.001 over it 0.4991
# no point inside either open cube, down to 0.001 from its faces and its hole, winds under 0.5: a count
inner = np.random.default_rng(3).uniform(0.001, 0.999, (4000, 3))
for gone in (top, top[:1]):
self.assertEqual(int((R.winding(verts, np.delete(tris, gone, axis=0), inner) < 0.5).sum()), 0)
def test_inside_is_half_a_winding_or_more(self):
# the bound, on a mesh only a test may read: a unit cube less its top winds 0.527 on the hole's axis 0.03
# under the hole's plane and 0.473 as far over it (1 less, and plainly, asin(0.25 / 0.2509) / pi). A bound
# of 0.45 reads the point over the hole inside and one of 0.55 the point under it outside: 0.473 and 0.527
# stand at the geometric means of 0.5 and those two, 1.06 from each, all the room there is between them
verts, tris = block((0, 0, 0), (1, 1, 1))
opened = np.delete(tris, [k for k, t in enumerate(tris) if (verts[t][:, 2] == 1.0).all()], axis=0)
pts = np.array([(0.5, 0.5, 0.97), (0.5, 0.5, 1.03)])
w = R.winding(verts, opened, pts)
self.assertLess(float(np.abs(w - (0.5270, 0.4730)).max()), 1e-4)
self.assertEqual(R.inside(verts, opened, pts).tolist(), [True, False])
# about closed solids the number is whole, so there the bound reads as any over 0 and up to 1 would
cloud = np.random.default_rng(5).uniform(-0.2, 1.2, (500, 3))
self.assertEqual(R.inside(verts, tris, cloud).tolist(), ((cloud > 0) & (cloud < 1)).all(axis=1).tolist())
def test_solids_are_the_closed_pieces_of_a_part(self):
# the jointlib rocker plates are four closed bars, each wound outward: none is refused. Two boxes that cut
# through one another are two solids, sharing a corner's index or not
fixture = json.loads((SURFACE / "tests" / "fixtures" / "ram_plates.json").read_text(encoding="utf-8"))
self.assertEqual(np.bincount(R.solids("plates", fixture["verts"], fixture["faces"])).tolist(), [84, 84, 84, 84])
for weld in (False, True):
verts, tris = joined(block((0, 0, 0), (1, 1, 1)), block((0, 0, 0), (2, 0.5, 0.5)), weld)
self.assertEqual(R.solids("boxes", verts, tris).tolist(), [0] * 12 + [1] * 12)
self.assertEqual(R.solids("stairs", *staircase()).tolist(), [0] * 28)
def test_an_open_part_is_refused_by_its_edge_count(self):
# a cube less a triangle has 3 edges no face runs back along, less its top 4, less two adjacent faces 6
# (the edge between them is gone with both); one triangle turned over leaves its 3 edges run twice one way
verts, tris = block((0, 0, 0), (1, 1, 1))
top = [k for k, t in enumerate(tris) if (verts[t][:, 2] == 1.0).all()]
side = [k for k, t in enumerate(tris) if (verts[t][:, 1] == 1.0).all()]
turned_over = tris.copy()
turned_over[0] = tris[0][::-1]
less = lambda gone: (verts, np.delete(tris, gone, axis=0))
for name, mesh, count, solid in (("a triangle off", less(top[:1]), 3, "solid 0 of 1"), ("the top off", less(top), 4, "solid 0 of 1"), ("two faces off", less(top + side), 6, "solid 0 of 1"),
("a triangle turned over", (verts, turned_over), 3, "solid 0 of 1"), ("the second of two open", joined(block((2, 0, 0), (3, 1, 1)), less(top), False), 4, "solid 1 of 2")):
with self.assertRaises(R.RamError, msg=name) as caught:
R.solids("cube", *mesh)
self.assertEqual(caught.exception.gate, "signed", name)
self.assertIn(f"part 'cube' is open: {solid} has {count} edges no face runs the other way", str(caught.exception), name)
def test_an_inside_out_solid_is_refused_by_name(self):
# a cube with every face turned over, or mirrored with its winding kept, has volume -1. A cube with a bar
# of half its volume turned over beside it has a positive volume in all: the bar is refused as its solid
verts, tris = block((0, 0, 0), (1, 1, 1))
for name, v, t in (("turned over", verts, tris[:, ::-1]), ("mirrored", verts * (-1, 1, 1), tris)):
with self.assertRaises(R.RamError, msg=name) as caught:
R.solids("cube", v, t)
self.assertIn("part 'cube' is wound inside out: solid 0 of 1 (12 faces from face 0) has volume -1", str(caught.exception), name)
bar_v, bar_t = block((2, 0, 0), (3, 1, 0.5))
mixed = joined((verts, tris), (bar_v, bar_t[:, ::-1]), False)
self.assertAlmostEqual(sum(float(mixed[0][a] @ np.cross(mixed[0][b], mixed[0][c])) / 6.0 for a, b, c in mixed[1]), 0.5, places=12)
with self.assertRaises(R.RamError) as caught:
R.solids("pair", *mixed)
self.assertIn("part 'pair' is wound inside out: solid 1 of 2 (12 faces from face 12) has volume -0.5", str(caught.exception))
self.assertEqual(R.solids("pair", *joined((bar_v, bar_t), (verts, tris), False)).tolist(), [0] * 12 + [1] * 12)
def test_no_blender(self):
source = (SURFACE / "brokkr_kitbash" / "ram.py").read_text(encoding="utf-8")
for word in ("bpy", "np.gradient"):