Arm moves only along checked poses; any marker name of the active map

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-21 16:54:22 +09:00
co-authored by Claude Opus 5.5
parent 775b32bc52
commit a50fdc9c0d
19 changed files with 880 additions and 277 deletions
+264
View File
@@ -0,0 +1,264 @@
"""The arm moves between named poses only along a graph of taught poses, every joint move checked before anything
moves.
give - carry - look - wave_start - wave
| \\
ready tuck
`look` is where every arm action starts (picks and puts go out from it and come back to it, skills.py). From any
pose of the graph the arm goes to another along the graph, one joint move per edge. An arm at no pose (after free
drive, after a stop half way) joins the graph only by one checked joint move to the nearest pose, at most JOIN_DEG
on every joint; further away nothing moves and Lumi asks for the arm to be brought near `look` by hand. A task's own
way back from the table (`leaf`: it went out from `look` along a checked plan) goes straight to its target.
Each joint move is checked at PATH_POINTS points (kine_forward): joint limits, no joint turning further than
motion.MAX_TRAVEL, the gripper (flange -> grasp point -> finger tips) at least HEAD_CLEAR_MM from the head's turning
centre (vision/head_cam.py), never more than skills.PATH_SAG_MM below both ends, and with something in the hand the
cup's lean at most skills.MAX_TILT_DEG. Refusals are RouteError with the reason in English and Korean.
Cobo π programs start only from `look` (start_program); hand_shaking.jks never (it hit the head, 2026-10-21).
python manipulation/arm_route.py check [pose] # the route from here to pose (default look), checked; moves nothing
python manipulation/arm_route.py goto <pose> # go there along the route (SPEED; the owner at the STOP)
"""
import collections
import sys
import numpy as np
from manipulation import skills
from robot import arm, gripper, motion
from vision import calib, head_cam
HOME = "look" # every arm action starts here
EDGES = (("give", "carry"), ("carry", "look"), ("look", "wave_start"), ("wave_start", "wave"),
("look", "ready"), ("look", "tuck")) # the only joint moves between named poses (both ways)
SPEED = "slow" # motion.JOINT_SPEED of every move along the graph
AT_POSE_DEG = 3.0 # deg; the arm is at a pose when every joint is this close (where, programs)
EXACT_DEG = 1.0 # deg; further than this from the nearest pose a route first goes to it
JOIN_DEG = 20.0 # deg; an arm at no pose joins the graph only this close to one (every joint)
PATH_POINTS = 21 # points checked (kine_forward) on every joint move
HEAD_CLEAR_MM = 250.0 # mm the gripper keeps from the head's turning centre. Estimate: the head camera
# is 102 mm from it, the head's size is not measured. `look` keeps 327 mm, tuck 266
NEVER_RUN = ("hand_shaking.jks",) # Cobo π programs not started any more
# Why the arm does not move, (English, Korean)
UNKNOWN = ("My arm is in a position I don't know, so I won't move it. Please bring it near its look pose by hand.",
"팔이 모르는 자세라서 움직이지 않을게요. 손으로 팔을 기본 자세 가까이 옮겨 주세요.")
NOT_TAUGHT = ("I haven't learned that arm pose yet.", "그 팔 자세는 아직 배우지 못했어요.")
BLOCKED = ("I can't move my arm there safely.", "팔을 거기로 안전하게 움직일 수 없어요.")
NEAR_HEAD = ("That would bring my hand too close to my head, so I won't move my arm.",
"손이 머리에 너무 가까워져서 팔을 움직이지 않을게요.")
SPILL = ("I can't move my arm there without spilling it.", "쏟지 않고는 팔을 거기로 움직일 수 없어요.")
UNSURE = ("I can't check my arm right now, so I won't move it.", "지금 팔 상태를 확인할 수 없어서 움직이지 않을게요.")
NOT_AT_LOOK = ("My arm has to be in its look pose first.", "먼저 팔이 기본 자세에 있어야 해요.")
RETIRED = ("I don't use that arm program any more.", "그 팔 프로그램은 이제 쓰지 않아요.")
class RouteError(skills.SkillError):
"""args: (English, Korean) reason. Nothing was sent to the arm."""
def log(*a):
skills.log(*a)
def _r(j):
return [round(v, 1) for v in j]
def _deg(now, pose):
"""Largest joint difference (deg) between `now` and `pose` as move_joints would reach it."""
return max(abs(a - b) for a, b in zip(motion.nearest(pose, now), now))
def graph():
"""{pose: joints} of the graph's taught poses."""
p = motion.poses()
return {n: p[n] for e in EDGES for n in e if n in p}
def where(now=None):
"""The graph pose the arm is at (every joint within AT_POSE_DEG), else None."""
now = skills._joints() if now is None else now
d = {n: _deg(now, j) for n, j in graph().items()}
best = min(d, key=lambda n: (d[n], n != HOME), default=None)
return best if best is not None and d[best] <= AT_POSE_DEG else None
def _path(a, b, nodes):
"""Shortest list of poses a .. b along EDGES between `nodes`, None when there is none."""
back, todo = {a: None}, collections.deque([a])
while todo:
n = todo.popleft()
if n == b:
out = []
while n is not None:
out.append(n)
n = back[n]
return out[::-1]
for e in EDGES:
for x, y in (e, e[::-1]):
if x == n and y in nodes and y not in back:
back[y] = n
todo.append(y)
return None
def hops(now, target, leaf=False):
"""The poses the arm goes through from the joints `now` to `target`, in order (not the one it is at). `leaf`: the
arm is out on the task's own checked way from look (above a table): when it is at no pose, straight to target."""
nodes = graph()
if target not in nodes:
log(f"arm route: {target} is not taught (robot/motion.py teach {target})")
raise RouteError(*NOT_TAUGHT)
d = {n: _deg(now, j) for n, j in nodes.items()}
start = min(d, key=lambda n: (d[n], n != HOME))
if d[start] > JOIN_DEG:
if leaf:
return [target]
log(f"arm route: arm at {_r(now)}, {d[start]:.0f} deg from {start}, the nearest pose (joins within "
f"{JOIN_DEG:.0f})")
raise RouteError(*UNKNOWN)
path = _path(start, target, nodes)
if path is None:
log(f"arm route: no way from {start} to {target} among {', '.join(nodes)}")
raise RouteError(*NOT_TAUGHT)
return path if d[start] > EXACT_DEG else path[1:]
def _seg_dist(c, a, b):
"""mm from point c to the segment a-b."""
ab = b - a
t = min(1.0, max(0.0, float((c - a) @ ab) / float(ab @ ab))) if ab @ ab else 0.0
return float(np.linalg.norm(c - (a + t * ab)))
def _gripper(c):
"""Flange, grasp point, finger tips (mm) and the flange rotation of the flange pose c [x, y, z, rx, ry, rz]."""
R, f = calib.rpy_matrix(*c[3:]), np.array(c[:3], float)
g = f + R @ skills.GRASP_OFFSET
return f, g, g + R @ (skills.TIP_MM * skills.FINGER_DIR), R
def flange_clearance(c, centre):
"""Smallest distance (mm) from `centre` to the gripper at the flange pose c."""
f, g, tip, _ = _gripper(c)
return min(_seg_dist(centre, f, g), _seg_dist(centre, g, tip))
def profile(j0, j1, centre):
"""(least gripper distance to `centre` mm, lowest z mm of the gripper at the ends, lowest z on the way, largest
lean deg of a held cup's axis) at PATH_POINTS points of the joint move j0 -> j1 (all joints together, a straight
line in joint space)."""
j0, j1 = np.array(j0, float), np.array(j1, float)
axis = calib.rpy_matrix(*skills.GRASP_RPY).T @ [0.0, 0.0, 1.0] # a held cup's axis in the flange frame
clear, low, tilt = [], [], 0.0
for k in range(PATH_POINTS):
c = skills._ask("kine_forward", jointPosition=[float(v) for v in j0 + (j1 - j0) * k / (PATH_POINTS - 1)])
f, g, tip, R = _gripper(c["cartPosition"])
clear.append(flange_clearance(c["cartPosition"], centre))
low.append(float(min(f[2], g[2], tip[2])))
tilt = max(tilt, float(np.degrees(np.arccos(np.clip((R @ axis)[2], -1.0, 1.0)))))
return min(clear), min(low[0], low[-1]), min(low), tilt
def move_problem(j0, j1, centre, holding=False):
"""Why the joint move j0 -> j1 must not run as (reason, log text), None if it may."""
clear, ends, low, tilt = profile(j0, j1, centre)
if clear < HEAD_CLEAR_MM:
return NEAR_HEAD, f"the gripper comes {clear:.0f} mm from the head (needs {HEAD_CLEAR_MM:.0f})"
if low < ends - skills.PATH_SAG_MM:
return BLOCKED, f"the gripper dips to z {low:.0f} mm"
if holding and tilt > skills.MAX_TILT_DEG:
return SPILL, f"the held cup would lean {tilt:.0f} deg"
return None
def check_moves(now, targets, holding=False):
"""Joint targets of the moves now -> targets[0] -> ..., as move_joints will turn them (J1 / J4 / J6 nearest),
each checked. RouteError when one must not run."""
centre = head_cam.head_centre()
if centre is None:
log("arm route: the head's place is not measured (vision/head_cam.py fit)")
raise RouteError(*UNSURE)
seq, prev, done = [], list(now), {}
for t in targets:
try:
motion.check(t)
except motion.MotionError as e:
log(f"arm route: {e}")
raise RouteError(*BLOCKED) from e
t = motion.nearest(t, prev)
if max(abs(a - b) for a, b in zip(t, prev)) > motion.MAX_TRAVEL:
log(f"arm route: {_r(prev)} -> {_r(t)} turns a joint further than {motion.MAX_TRAVEL:.0f} deg")
raise RouteError(*BLOCKED)
key = frozenset((tuple(np.round(prev, 1)), tuple(np.round(t, 1))))
if key not in done: # a move there and back (a wave's swings): checked once
done[key] = move_problem(prev, t, centre, holding)
if done[key]:
log(f"arm route: {_r(prev)} -> {_r(t)} refused: {done[key][1]}")
raise RouteError(*done[key][0])
seq.append(t)
prev = t
return seq
def plan(target, holding=False, leaf=False, now=None):
"""[(pose, joints)] of the checked way from here to `target` ([] when it is there). RouteError to refuse."""
now = skills._joints() if now is None else now
names = hops(now, target, leaf)
p = motion.poses()
return list(zip(names, check_moves(now, [p[n] for n in names], holding)))
def move(seq, speed=SPEED):
"""Run a plan() along its poses. motion.MotionError when stopped or failed on the way (the arm stays there)."""
for name, _ in seq:
log(f"arm to {name}")
motion.go(name, speed)
def goto(target, holding=False, leaf=False, speed=SPEED):
"""Plan, check and go to pose `target` along the graph. Returns the poses passed."""
seq = plan(target, holding, leaf)
if seq:
log(f"arm route to {target}: {' -> '.join(n for n, _ in seq)}, checked")
move(seq, speed)
return [n for n, _ in seq]
def start_program(name):
"""Start a Cobo π program, only from `look`. It ends wherever it was taught to end: the next move joins the graph
from there (or is refused). RouteError to refuse."""
if name.lower() in NEVER_RUN:
raise RouteError(*RETIRED)
if where() != HOME:
log(f"program {name} refused: the arm is not at {HOME}")
raise RouteError(*NOT_AT_LOOK)
arm.start(name)
if __name__ == "__main__":
a = sys.argv[1:]
try:
if a[:1] == ["check"]:
now = skills._joints()
centre = head_cam.head_centre()
print(f"at {where(now) or 'no pose'}: {_r(now)}")
prev = now
for n, j in plan(a[1] if len(a) > 1 else HOME, gripper.state()["holding"], now=now):
clear, _, low, tilt = profile(prev, j, centre)
print(f" -> {n:10s} {_r(j)} head {clear:.0f} mm, lowest z {low:.0f} mm, cup lean {tilt:.0f} deg")
prev = j
print("checked, nothing moved")
elif a[:1] == ["goto"] and len(a) == 2:
print(goto(a[1], gripper.state()["holding"]))
else:
sys.exit(__doc__)
except RouteError as e:
sys.exit(f"refused: {e.args[0]}")
except motion.MotionError as e:
sys.exit(f"stopped: {e}")
except KeyboardInterrupt:
print(motion.stop())
+6 -7
View File
@@ -709,17 +709,16 @@ def _prepare():
log("opening the gripper")
gripper.open_()
if max(abs(a - b) for a, b in zip(_joints(), home_joints())) > 1.0:
log(f"going to {home()}")
motion.go(home(), EMPTY_SPEED)
from manipulation import arm_route
arm_route.goto(home())
def _back_home():
"""Joint move to the home pose; refused when it would take the gripper lower than where it is now."""
"""From the table (out from home along the checked plan) straight back to the home pose: one joint move, checked
(arm_route: never lower than where it is now, clear of the head)."""
_go_on()
if not joint_move_ok(_joints(), home_joints()):
raise SkillError("I can't get my arm back up safely from here.")
log(f"going to {home()}")
motion.go(home(), EMPTY_SPEED)
from manipulation import arm_route
arm_route.goto(home(), leaf=True)
def _line(name, pose):
+23 -86
View File
@@ -1,15 +1,11 @@
"""Wave the hand when someone asks for it. A greeting never moves the arm.
"""Wave the hand when someone asked for it. A greeting never moves the arm.
The arm waves only from a known start pose (START_POSES: `look`, where the robot stands). It goes through the taught
poses ROUTE (first the hand away from the head, then up), swings one wrist joint about the last of them and comes back
the same way. Before anything moves, every joint move of that sequence is checked: joint limits, no joint turning
further than motion.MAX_TRAVEL, and at PATH_POINTS points along it (kine_forward) the gripper (flange -> grasp point ->
finger tips) stays HEAD_CLEAR_MM from the head's turning centre (vision/head_cam.py). Refused, with the reason in
English and Korean: the arm off or busy, the base driving, a task running, something in the hand, the arm anywhere
else (after free drive, in carry or give), a pose not taught, a move too near the head.
The Cobo π program hand_shaking.jks is not used: it ran from wherever the arm was and hit the head from `look`
(2026-10-21).
The arm goes up along the pose graph (manipulation/arm_route.py: from `look` to `wave_start`, the hand away from the
head, then `wave`, raised), swings one wrist joint there and STAYS at `wave`: the next arm task takes it back down
the same way (wave -> wave_start -> look). Before anything moves, every joint move is checked (arm_route.check_moves:
limits, travel, the gripper clear of the head, no dip). Refused, with the reason in English and Korean: the arm off or
busy, the base driving, a task running, something in the hand, the arm at no known pose (after free drive), a pose not
taught, a move too near the head.
python manipulation/wave.py check # plan and check from where the arm is now; moves nothing
python manipulation/wave.py run # wave (slow; the owner at the STOP)
@@ -18,30 +14,21 @@ Teach the route first, arm moved by hand in Cobo π: python robot/motion.py teac
"""
import sys
import numpy as np
from manipulation import skills
from manipulation import arm_route, skills
from robot import agv, arm, gripper, motion
from vision import calib, head_cam
START_POSES = ("look",) # the wave starts and ends only at one of these (motion.poses())
ROUTE = ("wave_start", "wave") # taught poses from the start: the hand away from the head, then raised
AT_POSE_DEG = 3.0 # deg; the arm is at a pose when every joint is this close
TOP = "wave" # the raised pose (arm_route.EDGES: look - wave_start - wave)
WAVE_JOINT = 4 # joint index swung at the raised pose (4 = J5); check on the first slow run
WAVE_DEG = 15.0 # deg each way from the raised pose
WAVE_SWINGS = 2 # times there and back
WAVE_SPEED = "slow" # motion.JOINT_SPEED; the route and the swings
PATH_POINTS = 21 # points checked (kine_forward) on every joint move
HEAD_CLEAR_MM = 250.0 # mm the gripper keeps from the head's turning centre. Estimate: the head camera
# is 102 mm from it, the head's size is not measured. `look` keeps 327 mm, tuck 266
WAVE_SPEED = arm_route.SPEED # motion.JOINT_SPEED; the route and the swings
# Why Lumi does not wave, (English, Korean)
OFF = ("Please enable my arm first.", "먼저 제 팔을 켜 주세요.")
BUSY = ("I'm busy with my arm right now.", "지금 팔로 하는 일이 있어요.")
DRIVING = ("I can't wave while I'm moving.", "움직이는 동안에는 손을 흔들 수 없어요.")
HOLDING = ("I'm holding something, so I won't wave.", "손에 물건을 들고 있어서 손을 흔들지 않을게요.")
UNKNOWN_POSE = ("My arm isn't in its usual place, so I won't wave. Please put it back first.",
"팔이 평소 자세가 아니어서 손을 흔들지 않을게요. 먼저 팔을 제자리로 해 주세요.")
UNKNOWN_POSE = arm_route.UNKNOWN
NOT_TAUGHT = ("I haven't learned how to wave safely yet.", "아직 안전하게 손 흔드는 법을 배우지 못했어요.")
NEAR_HEAD = ("Waving would bring my hand too close to my head, so I won't.",
"손이 머리에 너무 가까워져서 손을 흔들지 않을게요.")
@@ -70,33 +57,6 @@ def _holding():
return seen == "object" if seen != "unknown" else bool(gripper.state()["holding"])
def _seg_dist(c, a, b):
"""mm from point c to the segment a-b."""
ab = b - a
t = min(1.0, max(0.0, float((c - a) @ ab) / float(ab @ ab))) if ab @ ab else 0.0
return float(np.linalg.norm(c - (a + t * ab)))
def gripper_clearance(j, centre):
"""Smallest distance (mm) from `centre` to the gripper (flange -> grasp point -> finger tips) at joints j."""
c = skills._ask("kine_forward", jointPosition=[float(v) for v in j])["cartPosition"]
R, f = calib.rpy_matrix(*c[3:]), np.array(c[:3], float)
g = f + R @ skills.GRASP_OFFSET
tip = g + R @ (skills.TIP_MM * skills.FINGER_DIR)
return min(_seg_dist(centre, f, g), _seg_dist(centre, g, tip))
def move_clearance(j0, j1, centre):
"""Smallest gripper distance (mm) to `centre` at PATH_POINTS points of the joint move j0 -> j1 (the controller
moves all joints together, in a straight line in joint space)."""
j0, j1 = np.array(j0, float), np.array(j1, float)
return min(gripper_clearance(j0 + (j1 - j0) * k / (PATH_POINTS - 1), centre) for k in range(PATH_POINTS))
def _at(now, pose):
return max(abs(a - b) for a, b in zip(motion.nearest(pose, now), now)) <= AT_POSE_DEG
def plan():
"""Joint targets of the whole wave from here, each move checked. Raises WaveError to refuse."""
from tasks import fetch
@@ -109,45 +69,22 @@ def plan():
raise WaveError(*DRIVING)
if _holding():
raise WaveError(*HOLDING)
now, poses = motion.joints(), motion.poses()
start = next((n for n in START_POSES if n in poses and _at(now, poses[n])), None)
if start is None:
log(f"wave refused: arm at {[round(v, 1) for v in now]}, not at {', '.join(START_POSES)}")
raise WaveError(*UNKNOWN_POSE)
if any(n not in poses for n in ROUTE):
log(f"wave refused: teach {', '.join(n for n in ROUTE if n not in poses)} first (robot/motion.py teach)")
raise WaveError(*NOT_TAUGHT)
route = [list(poses[n]) for n in ROUTE]
top, i = route[-1], WAVE_JOINT
swings = [top[:i] + [top[i] + s * WAVE_DEG] + top[i + 1:] for _ in range(WAVE_SWINGS) for s in (1, -1)]
seq, prev = [], now
for t in route + swings + [top] + route[-2::-1] + [poses[start]]:
motion.check(t)
t = motion.nearest(t, prev) # as move_joints will turn it
if max(abs(a - b) for a, b in zip(t, prev)) > motion.MAX_TRAVEL:
log(f"wave refused: {[round(v, 1) for v in prev]} -> {[round(v, 1) for v in t]} turns a joint too far")
raise WaveError(*NOT_TAUGHT)
seq.append(t)
prev = t
centre = head_cam.head_centre()
if centre is None:
raise WaveError(*UNSURE)
done = set()
for a, b in zip([now] + seq, seq):
key = frozenset((tuple(np.round(a, 1)), tuple(np.round(b, 1))))
if key in done: # the way back and the repeated swings: checked once
continue
done.add(key)
d = move_clearance(a, b, centre)
if d < HEAD_CLEAR_MM:
log(f"wave refused: {[round(v, 1) for v in a]} -> {[round(v, 1) for v in b]} brings the gripper "
f"{d:.0f} mm from the head (needs {HEAD_CLEAR_MM:.0f})")
raise WaveError(*NEAR_HEAD)
now = motion.joints()
try:
route = arm_route.plan(TOP, now=now) # up along the graph ([] when it is up already)
start = route[-1][1] if route else now
top = motion.nearest(motion.poses()[TOP], start)
i = WAVE_JOINT
swings = [top[:i] + [top[i] + s * WAVE_DEG] + top[i + 1:] for _ in range(WAVE_SWINGS) for s in (1, -1)]
seq = [j for _, j in route] + arm_route.check_moves(start, ([] if route else [top]) + swings + [top])
except arm_route.RouteError as e:
raise WaveError(*{arm_route.UNKNOWN: UNKNOWN_POSE, arm_route.NOT_TAUGHT: NOT_TAUGHT,
arm_route.BLOCKED: NOT_TAUGHT, arm_route.NEAR_HEAD: NEAR_HEAD}.get(e.args, UNSURE)) from e
return seq
def wave(on_start=None):
"""Plan, check and wave; back at the start pose at the end. `on_start()` is called once the plan is checked.
"""Plan, check and wave; the arm stays at TOP. `on_start()` is called once the plan is checked.
Raises WaveError (refused) or motion.MotionError (stopped / failed while moving: the arm stays where it stopped)."""
try:
seq = plan()