diff --git a/data/arm_kinematics.json b/data/arm_kinematics.json new file mode 100644 index 0000000..10db1e1 --- /dev/null +++ b/data/arm_kinematics.json @@ -0,0 +1,195 @@ +{ + "note": "robot/kinematics.py fit: URDF arm chain corrected to the controller", + "base": [ + [ + -0.9965017380653254, + 0.08228504160521556, + -0.01461020057404377, + 26.758436947885883 + ], + [ + -0.08333690024848615, + -0.991500149045653, + 0.09991203881125613, + -3.8920509312702634 + ], + [ + -0.006264749776305157, + 0.10078008915691641, + 0.9948890021202186, + 15.320407874084733 + ], + [ + 0.0, + 0.0, + 0.0, + 1.0 + ] + ], + "joints": [ + [ + [ + 0.014463976063198124, + -0.08227324790396476, + -0.9965048449835936, + -1.8483894263997203 + ], + [ + -5.1188001961846394e-05, + -0.9966091586593242, + 0.08228111725142206, + -5.251298639750065 + ], + [ + -0.9998953899164811, + -0.0011391030184177574, + -0.014419142418387602, + -14.875032380256693 + ], + [ + 0.0, + 0.0, + 0.0, + 1.0 + ] + ], + [ + [ + 0.030884484575492543, + -0.9978833710282825, + 0.057226972991214375, + 0.9358525964723267 + ], + [ + 0.0013439956280143057, + -0.05721277348547816, + -0.9983611031214364, + -16.309063910755572 + ], + [ + 0.9995220569293396, + 0.030910780891630404, + -0.00042583613230320986, + 157.7417814247774 + ], + [ + 0.0, + 0.0, + 0.0, + 1.0 + ] + ], + [ + [ + 0.9999531415363414, + -0.009679216084596333, + -0.00016585412001997012, + 210.09288101857987 + ], + [ + 0.00967924359063766, + 0.9999531412703538, + 0.0001658525394731341, + 4.433966383637138 + ], + [ + 0.0001642410257388599, + -0.00016745011030612464, + 0.9999999724926726, + -28.991609698644602 + ], + [ + 0.0, + 0.0, + 0.0, + 1.0 + ] + ], + [ + [ + 0.003212885588497725, + -6.0758291421003225e-05, + 0.9999948368239835, + 130.26603733667434 + ], + [ + -0.999729317582941, + 0.02304268683206965, + 0.003213432542660397, + 0.4113588374425398 + ], + [ + -0.02304276310129253, + -0.9997344801956113, + 1.3291671223197851e-05, + 18.720077702520747 + ], + [ + 0.0, + 0.0, + 0.0, + 1.0 + ] + ], + [ + [ + 2.4955365061367485e-05, + 0.9988492954906226, + -0.04795919385390744, + -0.002883983208628154 + ], + [ + 6.170048666434476e-07, + -0.04795919388421195, + -0.9988492958007208, + -0.390756453684304 + ], + [ + -0.9999999996884246, + 2.4897057761988666e-05, + -1.8131340677905054e-06, + 80.38847898653269 + ], + [ + 0.0, + 0.0, + 0.0, + 1.0 + ] + ], + [ + [ + -0.0014343747161167885, + 0.0025918095975155683, + -0.9999956125364671, + -159.70089025801343 + ], + [ + -0.480465326246697, + 0.8770087203259357, + 0.002962219931016597, + 0.46558953722369334 + ], + [ + 0.8770125499922043, + 0.48046746715597183, + -1.2684490409824186e-05, + -0.389082276662311 + ], + [ + 0.0, + 0.0, + 0.0, + 1.0 + ] + ] + ], + "offsets_rad": [ + 0.04417165774903003, + 0.009933115945079313, + 0.008148529626565884, + 0.024835648178727746, + 0.0028934426556053924, + 2.071980600720852 + ] +} \ No newline at end of file diff --git a/docs/TUNING.md b/docs/TUNING.md index 678c438..3c91022 100644 --- a/docs/TUNING.md +++ b/docs/TUNING.md @@ -70,6 +70,9 @@ Every value here is a constant at the top of its file, with a comment on what it | `tasks/fetch.py` | `SEARCH_BASE_DEG` | 180°, 90° | Then the base turns towards the busier side, the first of these whose sweep is clear, and all again | | `tasks/fetch.py` | `LIFT_TRIES` | 0, 105 mm (`LIFT_RANGE`) | Nothing found: all of it again at the other end | | `tasks/fetch.py` | `APPROACH_TRIES` | 5 | Base moves to bring an object into reach before asking the person | +| `tasks/fetch.py` | `WAIST_REACH_STEPS` | 0, ±15, ±30° | A pick out of reach: waist turns tried around the one bringing the object to the pick zone's bearing, before a base move | +| `tasks/fetch.py` | `WAIST_FOUND_MM` | 80 mm | After that waist turn the object must be seen this near where it should be | +| `manipulation/skills.py` | `IK_SEEDS` | ready, look, carry, give | Taught poses whose arm configurations (and wrist flips) seed the pick / place IK | | `tasks/fetch.py` | `PICK_ZONE_CENTRE` | (−100, 580) mm | Where a base move brings an object (arm base frame) | | `tasks/fetch.py` | `LOST_BACK_M`, `LOST_TURN_DEG` | 0.15 m, 20° | An object lost after a base move: back off, turn each way, look again | | `tasks/fetch.py` | `WIDTH_NEAR_MM` | 250 mm | A width further than this from the pick zone does not refuse a pick (far widths read ~8 mm too wide); measured again up close | diff --git a/manipulation/skills.py b/manipulation/skills.py index ba4a250..98a86c3 100644 --- a/manipulation/skills.py +++ b/manipulation/skills.py @@ -139,6 +139,11 @@ GRASPS = { # COCO class -> (Korean name, U "handbag": ("핸드백", BIG), "backpack": ("가방", BIG), "umbrella": ("우산", BIG), "suitcase": ("여행가방", BIG), "hair drier": ("드라이기", BIG), "toaster": ("토스터", BIG), # over the tips' open 88 mm, or over the payload } +IK_SEEDS = ("ready", "look", "carry", "give") # taught poses whose arm configurations (and wrist flips) seed the + # pick / place IK: the controller answers the solution nearest the + # seed, so one seed alone misses cups another configuration reaches +WRIST_MIN_DEG = 10.0 # deg; |J5| at least this at above, grasp and lift (estimate: the + # proven picks had J5 +20; near 0 J4 / J6 swing round) RETRIES = 4 # the controller now and then answers with nothing: ask again RETRY_S = 0.2 OPEN_AI = gripper.CLOSED_AI # AI_1 below this after opening = released @@ -589,7 +594,7 @@ def ik_chain(waypoints, start_joints): if r["errorCode"] != "0": rows.append([name, pose, None, "no IK solution"]) return rows - j = r["jointPosition"] + j = motion.nearest(r["jointPosition"], ref) # J1 / J4 / J6 +-360: the same pose, nearest the last one err = None try: motion.check(j) @@ -618,30 +623,38 @@ def wrist_flip(j): return [j[0], j[1], j[2], j[3] + 180.0, -j[4], j[5] + 180.0] -def above_joints(pose, start=None): - """Joint solutions for the approach pose `pose`: from `ready`'s arm configuration (where the picks were proven) - and from it with the wrist flipped. Each is within the joint limits and a joint move from `start` (default: here) - that move_joints accepts (no joint further than motion.MAX_TRAVEL); no duplicates.""" +def above_joints(pose, start=None, seeds=IK_SEEDS): + """Joint solutions for the approach pose `pose`: from the arm configuration of each `seeds` pose (`ready` first, + where the picks were proven) and from it with the wrist flipped. Each is within the joint limits and a joint move + from `start` (default: here) that move_joints accepts (no joint further than motion.MAX_TRAVEL); no duplicates.""" start = _joints() if start is None else start - ready = motion.nearest(motion.poses()["ready"], start) + taught = motion.poses() out = [] - for seed in (ready, wrist_flip(ready)): - r = _ask("kine_inverse", jointPosition=[float(v) for v in seed], cartPosition=list(pose)) - if r["errorCode"] != "0": + for name in seeds: + if name not in taught: continue - j = r["jointPosition"] - try: - motion.check(j) - except motion.MotionError: - continue - near = motion.nearest(j, start) - if max(abs(a - b) for a, b in zip(near, start)) > motion.MAX_TRAVEL: - continue - if all(max(abs(a - b) for a, b in zip(motion.nearest(o, j), j)) > 1.0 for o in out): - out.append(j) + seed = motion.nearest(taught[name], start) + for s in (seed, wrist_flip(seed)): + j = _solve(pose, s, start) + if j is not None and all(max(abs(a - b) for a, b in zip(o, j)) > 1.0 for o in out): + out.append(j) return out +def _solve(pose, seed, start): + """IK of `pose` from `seed`, J1 / J4 / J6 nearest `start`; None when there is none, it is out of the joint limits + or the joint move from `start` turns a joint further than motion.MAX_TRAVEL.""" + r = _ask("kine_inverse", jointPosition=[float(v) for v in seed], cartPosition=list(pose)) + if r["errorCode"] != "0": + return None + j = motion.nearest(r["jointPosition"], start) + try: + motion.check(j) + except motion.MotionError: + return None + return j if max(abs(a - b) for a, b in zip(j, start)) <= motion.MAX_TRAVEL else None + + def path_heights(j0, j1): """Lowest z (mm) of flange, grasp point and finger tips at PATH_POINTS points of the joint move j0 -> j1.""" j0, j1, out = np.array(j0), np.array(motion.nearest(j1, list(j0))), [] @@ -659,6 +672,14 @@ def joint_move_ok(j0, j1): return min(z) >= min(z[0], z[-1]) - PATH_SAG_MM +def move_ok(j0, j1): + """The joint move j0 -> j1 out to a table keeps the gripper HEAD_CLEAR_MM from the head and does not dip + (arm_route.move_problem, the check of every pose-graph move); False when the head's place is not measured.""" + from manipulation import arm_route + centre = arm_route.head_cam.head_centre() + return centre is not None and arm_route.move_problem(j0, j1, centre) is None + + def checked(waypoints, start_joints): rows = ik_chain(waypoints, start_joints) if rows[-1][3]: @@ -671,11 +692,19 @@ def pick_options(obj, start): """(waypoints, joints above) of every grasp turn (GRASP_YAWS) and wrist solution reachable from `start`: a joint move down to above that stays above it, then straight down and up. Objects of the wrong width raise.""" plan_pick(obj) - for yaw in GRASP_YAWS: - waypoints = plan_pick(obj, yaw) - for ja in above_joints(waypoints[0][1], start): - if not ik_chain(waypoints[1:], ja)[-1][3] and joint_move_ok(start, ja): - yield waypoints, ja + for seeds in (IK_SEEDS[:1], IK_SEEDS[1:]): # the proven `ready` configuration at every turn first + for yaw in GRASP_YAWS: + waypoints = plan_pick(obj, yaw) + for ja in above_joints(waypoints[0][1], start, seeds): + rows = ik_chain(waypoints[1:], ja) + if not rows[-1][3] and wrist_ok([ja] + [r[2] for r in rows]) and move_ok(start, ja): + yield waypoints, ja + + +def wrist_ok(joints): + """J5 stays WRIST_MIN_DEG from 0 at every pose of a straight move down and up: near J5 = 0 a straight move may + turn J4 and J6 far round in small steps (motion.move_linear refuses it there, half way through the pick).""" + return all(abs(j[4]) >= WRIST_MIN_DEG for j in joints) def tilt_on(j0, j1): @@ -698,7 +727,9 @@ def place_options(x, y, top_mm, start): for yaw in sorted(GRASP_YAWS, key=lambda a: abs((a - held + 180.0) % 360.0 - 180.0)): way = plan_place(x, y, top_mm, yaw=yaw) for ja in above_joints(way[0][1], start): - if not ik_chain(way[1:], ja)[-1][3] and joint_move_ok(start, ja) and tilt_on(start, ja) <= MAX_TILT_DEG: + rows = ik_chain(way[1:], ja) + if not rows[-1][3] and wrist_ok([ja] + [r[2] for r in rows]) and move_ok(start, ja) and \ + tilt_on(start, ja) <= MAX_TILT_DEG: yield way, ja diff --git a/robot/kinematics.py b/robot/kinematics.py new file mode 100644 index 0000000..ad4b1ac --- /dev/null +++ b/robot/kinematics.py @@ -0,0 +1,200 @@ +"""Offline arm kinematics: forward and inverse, fitted to the controller's own answers, so reach planning can be +checked without the robot (tests, dry runs over many cup positions). The robot itself always plans with the +controller's kine_inverse / kine_forward (manipulation/skills.py); this only stands in for them offline. + +The model is the vendor URDF's arm chain (l_a1 ... l_a6) with every joint's fixed frame and zero corrected by a +least-squares fit to the calibration samples (joints + the flange pose the controller reported). Held-out samples +and the taught grasps agree within 0.2 mm and 0.05 deg. + + python robot/kinematics.py fit # refit data/arm_kinematics.json from data/calib_samples*/ (no robot needed) + python robot/kinematics.py # the fit's error on every sample +""" +import glob +import json +import math +import sys +from pathlib import Path + +import numpy as np + +ROOT = Path(__file__).resolve().parents[1] # the project folder +MODEL_FILE = ROOT / "data" / "arm_kinematics.json" +SAMPLES = ("data/calib_samples/*.json", "data/calib_samples_head/*.json") +URDF_JOINTS = (((0, 0, 0), (3.1416, 1.5708, 0)), # jaka_lumi.urdf l_a1 ... l_a6: origin xyz (m), rpy + ((0, -0.0165, 0.156), (1.5708, -1.5708, 0)), + ((0.21, 0, -0.029), (0, 0, 0)), + ((0.1303, 0, 0.0185), (-1.5708, 0, -1.5708)), + ((0, -0.01805, 0.0802), (1.5708, 1.5708, 0)), + ((-0.1233, 0, 0.01805), (1.5708, 0, -1.5708))) +IK_ITERS = 60 # Newton steps at most +IK_TOL_MM, IK_TOL_RAD = 0.01, 1e-5 # converged when the pose is this close +IK_STEP_DEG = 20.0 # no joint turns more than this in one step (keeps the seed's branch) + + +def _rpy(r, p, y): + """R = Rz(y) Ry(p) Rx(r) (URDF and the controller's convention), radians.""" + cr, sr, cp, sp, cy, sy = math.cos(r), math.sin(r), math.cos(p), math.sin(p), math.cos(y), math.sin(y) + return np.array([[cy * cp, cy * sp * sr - sy * cr, cy * sp * cr + sy * sr], + [sy * cp, sy * sp * sr + cy * cr, sy * sp * cr - cy * sr], + [-sp, cp * sr, cp * cr]]) + + +def _frame(xyz, rpy): + A = np.eye(4) + A[:3, :3], A[:3, 3] = _rpy(*rpy), xyz + return A + + +def _frames(p): + """(base, [joint frames], [zero offsets rad]) of a parameter vector: base xyz rpy, then per joint dxyz drpy dq.""" + joints = [_frame(np.array(xyz) * 1000.0 + p[6 + 7 * i:9 + 7 * i], np.array(rpy) + p[9 + 7 * i:12 + 7 * i]) + for i, (xyz, rpy) in enumerate(URDF_JOINTS)] + return _frame(p[:3], p[3:6]), joints, [p[12 + 7 * i] for i in range(6)] + + +_model = None + + +def _load(): + global _model + if _model is None: + d = json.loads(MODEL_FILE.read_text()) + _model = (np.array(d["base"]), [np.array(f) for f in d["joints"]], d["offsets_rad"]) + return _model + + +def chain(joints, model=None): + """[4x4] of the arm base, then the frame of each joint after its turn (mm); the last one is the flange.""" + base, frames, offsets = model or _load() + T, out = base, [base] + for F, q, off in zip(frames, joints, offsets): + T = T @ F + a = math.radians(q) + off + Rz = np.eye(4) + Rz[:2, :2] = [[math.cos(a), -math.sin(a)], [math.sin(a), math.cos(a)]] + T = T @ Rz + out.append(T) + return out + + +def fk(joints, model=None): + """Flange 4x4 (mm) in the arm base frame, as the controller's kine_forward gives it.""" + return chain(joints, model)[-1] + + +def pose(joints): + """[x, y, z mm, rx, ry, rz deg] of the flange (R = Rz Ry Rx, like the controller).""" + T = fk(joints) + R = T[:3, :3] + return [float(v) for v in T[:3, 3]] + [math.degrees(math.atan2(R[2, 1], R[2, 2])), + math.degrees(math.asin(max(-1.0, min(1.0, -R[2, 0])))), + math.degrees(math.atan2(R[1, 0], R[0, 0]))] + + +def _rotvec(R): + """Rotation vector (rad) of a rotation matrix.""" + a = math.acos(max(-1.0, min(1.0, (np.trace(R) - 1) / 2))) + if a < 1e-9: + return np.zeros(3) + v = np.array([R[2, 1] - R[1, 2], R[0, 2] - R[2, 0], R[1, 0] - R[0, 1]]) + if math.pi - a < 1e-6: # half a turn: the axis from the symmetric part + w = np.sqrt(np.maximum((np.diag(R) + 1) / 2, 0)) + return a * w + return a * v / (2 * math.sin(a)) + + +def ik(target, seed): + """Joints (deg) putting the flange at `target` [x, y, z, rx, ry, rz], found from `seed` by Newton steps (so the + answer is the solution of the seed's arm configuration, like the controller's nearest-to-reference answer); + None when it does not converge (out of reach). Joint limits are not checked here (motion.check does).""" + goal = _frame(target[:3], [math.radians(v) for v in target[3:]]) + q = np.array(seed, float) + for _ in range(IK_ITERS): + frames = chain(q) + T = frames[-1] + e = np.concatenate([goal[:3, 3] - T[:3, 3], T[:3, :3] @ _rotvec(T[:3, :3].T @ goal[:3, :3])]) + if np.linalg.norm(e[:3]) < IK_TOL_MM and np.linalg.norm(e[3:]) < IK_TOL_RAD: + return [float(v) for v in (q + 180.0) % 360.0 - 180.0] # the same pose; within +-180 like a fresh answer + J = np.zeros((6, 6)) + for i in range(6): + z, o = frames[i + 1][:3, 2], frames[i + 1][:3, 3] + J[:3, i], J[3:, i] = np.cross(z, T[:3, 3] - o), z + e[3:] *= 100.0 # 1 rad weighs as 100 mm + J[3:] *= 100.0 + dq = np.degrees(np.linalg.lstsq(J, e, rcond=None)[0]) + q = q + dq * min(1.0, IK_STEP_DEG / max(np.abs(dq).max(), 1e-9)) + return None + + +def ask(name, **args): + """Offline stand-in for skills._ask: kine_forward / kine_inverse answers shaped like the controller's.""" + if name == "kine_forward": + return {"errorCode": "0", "cartPosition": pose(args["jointPosition"])} + if name == "kine_inverse": + j = ik(args["cartPosition"], args["jointPosition"]) + return {"errorCode": "-4"} if j is None else {"errorCode": "0", "jointPosition": j} + raise ValueError(f"offline kinematics has no {name}") + + +# ---------- fitting ---------- +def _samples(): + out = [] + for pattern in SAMPLES: + for f in sorted(glob.glob(str(ROOT / pattern))): + s = json.loads(Path(f).read_text()) + out.append((s["joints"], np.array(s["flange"], float))) + return out + + +def _residual(p, samples): + model = _frames(p) + r = [] + for j, F in samples: + T = fk(j, model) + r += list(T[:3, 3] - F[:3, 3]) + list(100.0 * (T[:3, :3] - F[:3, :3]).ravel()) + return np.array(r) + + +def fit(iters=60): + """Levenberg-Marquardt fit of the corrections to the samples; writes MODEL_FILE. The base starts from a rigid + fit of the plain URDF's flange positions.""" + samples = _samples() + p = np.zeros(6 + 7 * 6) + P = np.array([fk(j, _frames(p))[:3, 3] for j, _ in samples]) + X = np.array([F[:3, 3] for _, F in samples]) + U, _, Vt = np.linalg.svd((P - P.mean(0)).T @ (X - X.mean(0))) + R = Vt.T @ np.diag([1, 1, np.sign(np.linalg.det(Vt.T @ U.T))]) @ U.T + p[:3] = X.mean(0) - R @ P.mean(0) + p[3:6] = [math.atan2(R[2, 1], R[2, 2]), math.asin(-R[2, 0]), math.atan2(R[1, 0], R[0, 0])] + lam = 1e-2 + for _ in range(iters): + r0 = _residual(p, samples) + J = np.stack([(_residual(p + d, samples) - r0) / 1e-4 for d in np.eye(len(p)) * 1e-4], axis=1) + A = J.T @ J + step = np.linalg.solve(A + lam * np.eye(len(p)) + 1e-3 * np.diag(np.diag(A)), -J.T @ r0) + if np.sum(_residual(p + step, samples) ** 2) < np.sum(r0 ** 2): + p, lam = p + step, lam * 0.5 + else: + lam *= 10 + base, frames, offsets = _frames(p) + MODEL_FILE.write_text(json.dumps({"note": "robot/kinematics.py fit: URDF arm chain corrected to the controller", + "base": base.tolist(), "joints": [f.tolist() for f in frames], + "offsets_rad": [float(v) for v in offsets]}, indent=1)) + global _model + _model = None + + +def errors(): + """(largest mm, largest deg) between the model and every sample.""" + mm, deg = [], [] + for j, F in _samples(): + T = fk(j) + mm.append(float(np.linalg.norm(T[:3, 3] - F[:3, 3]))) + deg.append(math.degrees(math.acos(min(1.0, (np.trace(T[:3, :3].T @ F[:3, :3]) - 1) / 2)))) + return max(mm), max(deg) + + +if __name__ == "__main__": + if sys.argv[1:] == ["fit"]: + fit() + print("largest error: %.2f mm, %.3f deg" % errors()) diff --git a/tasks/fetch.py b/tasks/fetch.py index 49bddd4..d158989 100644 --- a/tasks/fetch.py +++ b/tasks/fetch.py @@ -91,6 +91,10 @@ SEARCH_BASE_DEG = (180.0, 90.0) # then the base turns towards that side, th LIFT_TRIES = LIFT_RANGE # mm; nothing found: all of it again at the other end of these SAME_BASE_M = 0.02 # m / rad; the base is still where it picked: the pick spot is still table SAME_BASE_RAD = 0.035 +WAIST_REACH_STEPS = (0.0, 15.0, -15.0, 30.0, -30.0) # deg; a pick out of reach: waist turns tried around the one + # that brings the object to PICK_ZONE_CENTRE's bearing about the column (the waist carries + # the arm round the column: what it reaches beside it, it reaches ahead), before a base move +WAIST_FOUND_MM = 80.0 # mm; after that turn the object is looked for this near where it should be seen APPROACH_TRIES = 5 # base moves to bring an object out of reach to PICK_ZONE_CENTRE before asking the person STRAIGHT_MAX_M = 0.6 # m; a straight drive (after a turn on the spot) at most this long, else navigation STANDOFF_M = 0.4 # m; navigation goes to this far back from the pick pose, then straight in @@ -995,6 +999,61 @@ def _reachable(obj): return None +def turned(obj, deg): + """`obj` (x, y mm, arm frame) as the arm will see it after the waist turns by `deg` (+ left): turned by -deg about + the column (the head's turning centre: the waist and the head turn about the same axis, URDF).""" + c = head_cam.head_centre()[:2] + x, y = c + _rot(-deg) @ (np.array([obj["x"], obj["y"]], float) - c) + return {**obj, "x": float(x), "y": float(y)} + + +def waist_for(obj): + """Waist turns (deg from where it is, + left) to try for an object out of reach: the one that brings it to + PICK_ZONE_CENTRE's bearing about the column, then WAIST_REACH_STEPS around it; inside the body's limits and + WAIST_SCAN_MAX from the front, none smaller than TURN_MIN_DEG. [] when the head's place is not measured.""" + c = head_cam.head_centre() + if c is None: + return [] + bearing = lambda xy: math.degrees(math.atan2(-(xy[0] - c[0]), xy[1] - c[1])) # + left of ahead + d = bearing((obj["x"], obj["y"])) - bearing(PICK_ZONE_CENTRE) + lo, hi = head.AXIS_LIMITS[1] + waist, now, out = head.status()[1], _waist_turn(), [] + for t in ((d + s + 180.0) % 360.0 - 180.0 for s in WAIST_REACH_STEPS): + if abs(t) >= TURN_MIN_DEG and lo <= waist + t <= hi and abs(now + t) <= WAIST_SCAN_MAX and t not in out: + out.append(t) + return out + + +def _waist_reach(task, obj, say): + """(obj, waypoints, joints above) of a pick after a waist turn, for an object the arm doesn't reach from here: the + first turn of waist_for whose pick, planned where the object will be (turned), passes; the waist turns (its sweep + checked), the camera looks again and the pick is planned from what it sees. None when no turn reaches it or the + object is not seen again where it should be (then the base moves).""" + for deg in waist_for(obj): + try: + if not _reachable(turned(obj, deg)): + continue + except skills.SkillError: + return None + _step("turning my waist to reach it", say) + _pose(_look()) + if not _waist_to(_waist_turn() + deg): + return None + want = turned(obj, deg) + hits = [o for o in skills.look() if _is_task(o, task) and o["seen"] >= skills.MIN_SEEN + and o["spread"] <= skills.SPREAD_MM and o["top_mm"] is not None] + o = min(hits, key=lambda o: math.hypot(o["x"] - want["x"], o["y"] - want["y"]), default=None) + if o is None or math.hypot(o["x"] - want["x"], o["y"] - want["y"]) > WAIST_FOUND_MM: + log(f"after the waist turn the {task['object']} is not where it should be ({want['x']:.0f}, " + f"{want['y']:.0f})") + return None + plan = _reachable(o) + log(f"waist turned {deg:+.0f} deg: the {o['name']} at ({o['x']:.0f}, {o['y']:.0f})" + f"{' is in reach' if plan else ', still out of reach'}") + return (o, *plan) if plan else None + return None + + def _head_seen(match): """{"x", "y"} mm (arm frame) of a thing `match(detection)` takes that the head camera saw at least twice in HEAD_READS fresh frames within HEAD_SAME_MM, with "head": True (its depth is not the torso camera's: it only shows @@ -1274,6 +1333,9 @@ def _reach(task, obj, say): other = _other_here(task, obj) if i == 0 else None if other: # the one chosen is out of reach, another one is not return other + got = _waist_reach(task, obj, say) # the waist brings the arm round to it: no base move + if got: + return got if yaw is None or i == APPROACH_TRIES or _charging(): break w = _waist_turn() diff --git a/tests/test_reach.py b/tests/test_reach.py new file mode 100644 index 0000000..4beb6c0 --- /dev/null +++ b/tests/test_reach.py @@ -0,0 +1,130 @@ +"""Self-check of the arm's reach planning with the offline kinematics (robot/kinematics.py), no robot: +python tests/test_reach.py + +Cups the arm reaches from where Lumi stands are planned, from any grasp turn and IK seed; cups beside it are reached +by a waist turn first; cups out of reach of every waist turn still go to the base move / asking. The positions of the +live cases are from logs/api.log (2026-10-2x): the one picked, and the ones refused then.""" +import math + +import numpy as np + +from robot import kinematics, motion +from manipulation import arm_route, skills +from tasks import fetch + +# ---------- the offline kinematics: the controller's own answers ---------- +mm, deg = kinematics.errors() +assert mm < 0.5 and deg < 0.1, (mm, deg) +for name, j in motion.poses().items(): # IK from a seed 8 deg off: the same flange pose + p = kinematics.pose(j) + s = kinematics.ik(p, [a + 8.0 for a in j]) + assert s is not None and np.allclose(kinematics.pose(s)[:3], p[:3], atol=0.05), name +assert kinematics.ask("kine_inverse", jointPosition=[0.0] * 6, cartPosition=[3000.0, 0, 0, 0, 0, 0])["errorCode"] != "0" + +# ---------- picks from look, offline IK, every check fetch uses (carry line, head, joint limits) ---------- +skills._ask = kinematics.ask +LOOK = motion.poses()["look"] +skills._joints = lambda: list(LOOK) +lines = [] +fetch.log = skills.log = arm_route.log = lambda *a: lines.append(" ".join(str(x) for x in a)) +cup = lambda x, y, top=-260.0: {"name": "cup", "colour": "grey", "x": float(x), "y": float(y), "top_mm": top, + "width_mm": 76.0, "seen": 8, "spread": 1.0} +reach = lambda o: skills.reachable_pick(o, accept=fetch._carry_ok) + +plan = reach(cup(-96, 598)) # picked live 2026-10-2x 15:39 (J5 +20, no turn) +assert plan and abs(skills.yaw_of(plan[0][1][1])) < 1, plan +for xy in ((-171, 697), (-395, 629), (-480, 652)): # refused live from where it stood: still out of reach + assert reach(cup(*xy)) is None, xy # of the arm alone at waist 0 (base moved then) + +# a held IK answer with J4 one turn round (the same pose) is not a joint-limit or flip refusal +real_ask = skills._ask +def turned_j4(name, **a): + r = real_ask(name, **a) + if name == "kine_inverse" and r["errorCode"] == "0": + r["jointPosition"][3] += 360.0 if r["jointPosition"][3] < 0 else -360.0 + return r +skills._ask = turned_j4 +assert reach(cup(-96, 598)) +skills._ask = real_ask + +# the joint move out to above the cup is checked against the head: a head on the way refuses it +real_centre = arm_route.head_cam.head_centre +start, ja = list(LOOK), plan[1] +assert skills.move_ok(start, ja) +mid = kinematics.pose([(a + b) / 2 for a, b in zip(start, motion.nearest(ja, start))]) +arm_route.head_cam.head_centre = lambda: np.array(mid[:3]) +assert not skills.move_ok(start, ja) +arm_route.head_cam.head_centre = lambda: None # the head's place unknown: no move +assert not skills.move_ok(start, ja) +arm_route.head_cam.head_centre = real_centre + +# ---------- waist turns: the arm reaches round the column ---------- +C = arm_route.head_cam.head_centre()[:2] +body = {"waist": -20.31} # the waist of measure-axis = the front +fetch.head.status = lambda: [75.0, body["waist"], 0.0, -5.0] +around = lambda r, b: cup(C[0] - r * math.sin(math.radians(b)), C[1] + r * math.cos(math.radians(b))) + +o = cup(-300, 400) +t = fetch.turned(o, 30.0) # turned about the column: same distance from it +assert np.isclose(np.hypot(*(np.subtract((t["x"], t["y"]), C))), np.hypot(*(np.subtract((o["x"], o["y"]), C)))) +assert t["x"] > o["x"] # waist left: a thing on the left comes ahead +assert np.allclose([fetch.turned(t, -30.0)[k] for k in "xy"], [o[k] for k in "xy"]) + +for r, b in ((600, 60), (600, -60), (550, 90), (600, -100), (730, 7), (720, 25)): # beside it and the live ones + o = around(r, b) + assert reach(o) is None, (r, b) # not from here ... + turns = fetch.waist_for(o) + assert turns and any(reach(fetch.turned(o, d)) for d in turns), (r, b, turns) # ... after a waist turn + assert abs(turns[0] - (b - math.degrees(math.atan2(-(fetch.PICK_ZONE_CENTRE[0] - C[0]), + fetch.PICK_ZONE_CENTRE[1] - C[1])))) < 1e-6 +for r, b in ((1000, 0), (950, 40)): # too far for any waist turn: the base has to move + o = around(r, b) + assert all(reach(fetch.turned(o, d)) is None for d in fetch.waist_for(o)), (r, b) +body["waist"] = 100.0 # the waist near its limit (140): no turn past it +assert all(body["waist"] + d <= 140.0 for d in fetch.waist_for(around(600, 80))) +body["waist"] = -20.31 + +# ---------- _reach: a waist turn before any base move; a cup no turn reaches still moves the base ---------- +calls = [] +fetch._step = lambda name, say=None, *a: calls.append(("step", name)) +fetch._pose = lambda name, *a, **k: None +fetch._charging = lambda: False +fetch._other_here = lambda task, obj: None +fetch.arm_yaw = lambda: -95.5 +fetch.remember = lambda obj, yaw: {} +fetch.agv.pose = lambda: (0.0, 0.0, 0.0) +def waist_to(rel): + calls.append(("waist", round(rel))) + body["waist"] = -20.31 + rel + return True +fetch._waist_to = waist_to +scene = {"cup": None} # the cup where it stands, in the arm frame at waist 0 +skills.look = lambda *a, **k: [fetch.turned(scene["cup"], body["waist"] + 20.31)] +class Moved(Exception): + pass +def approach(obj, yaw, tried, **kw): + calls.append(("base",)) + raise Moved() +fetch._approach = approach +task = {"object": "cup", "colour": None} + +scene["cup"] = around(600, 70) # on the left: the waist turns, no base move +got = fetch._reach(task, scene["cup"], None) +assert got and ("base",) not in calls and calls[0] == ("step", "turning my waist to reach it"), calls +assert any(c[0] == "waist" for c in calls) and got[0]["x"] == fetch.turned(scene["cup"], body["waist"] + 20.31)["x"] + +calls.clear() +body["waist"] = -20.31 +scene["cup"] = around(1000, 0) # too far: no waist turn reaches it, the base moves +try: + fetch._reach(task, scene["cup"], None) + raise AssertionError("no base move") +except Moved: + pass +assert ("base",) in calls and not any(c[0] == "waist" for c in calls), calls + +calls.clear() +scene["cup"] = around(600, -70) # the cup was moved away while the waist turned +skills.look = lambda *a, **k: [] +assert fetch._waist_reach(task, scene["cup"], None) is None and any(c[0] == "waist" for c in calls) +print("reach ok")