diff --git a/data/fetch_calib.json b/data/fetch_calib.json index 914276e..2ab95d5 100644 --- a/data/fetch_calib.json +++ b/data/fetch_calib.json @@ -1 +1 @@ -{"arm_yaw_in_base_deg": -95.5, "objects": ["cup", "cup"], "waist_deg": -20.31, "measured": "2026-10-19 15:55 (median of -96.4, -94.9, -95.5; one run that paired both cups with one was left out)", "arm_xy_in_base_m": [0.114, -0.104], "arm_xy_measured": "2026-10-16 (median of 4; the depth-only 0.005, -0.120 dropped)", "arm_xy_samples": [[0.111, -0.086], [0.093, -0.095], [0.187, -0.113], [0.117, -0.129]]} \ No newline at end of file +{"arm_yaw_in_base_deg": -95.5, "objects": ["cup", "cup"], "waist_deg": -20.31, "measured": "2026-10-19 15:55 (median of -96.4, -94.9, -95.5; one run that paired both cups with one was left out)", "arm_xy_in_base_m": [0.093, -0.113], "arm_xy_measured": "2026-10-27 13:07", "arm_xy_samples": [[0.111, -0.086], [0.093, -0.095], [0.187, -0.113], [0.117, -0.129], [0.066, -0.109], [0.041, -0.114], [0.051, -0.127]]} \ No newline at end of file diff --git a/data/grasp_side_teach.json b/data/grasp_side_teach.json new file mode 100644 index 0000000..7be430e --- /dev/null +++ b/data/grasp_side_teach.json @@ -0,0 +1,53 @@ +{ + "note": "owner's free-drive side grasps: flange pose with the cup in the hooks' belly, the cup's (x, y, top, low) seen after the hand backed out; arm frame, mm / deg", + "samples": [ + { + "flange": [ + -0.9, + 488.6, + -160.0, + 86.1, + 44.5, + -169.8 + ], + "cup": [ + -61.5, + 663.5, + -183.5, + -325 + ] + }, + { + "flange": [ + -30.34, + 470.82, + -177.8, + 82.7, + 43.69, + -164.7 + ], + "cup": [ + -117.0, + 640.5, + -182.0, + -324.0 + ] + }, + { + "flange": [ + 29.45, + 465.68, + -182.27, + 81.23, + 50.3, + -164.52 + ], + "cup": [ + -51.0, + 638.0, + -184.0, + -325.4 + ] + } + ] +} \ No newline at end of file diff --git a/data/grasp_teach.json b/data/grasp_teach.json index 254cdc2..17928d5 100644 --- a/data/grasp_teach.json +++ b/data/grasp_teach.json @@ -28,9 +28,9 @@ -301.0 ], "tcp_offset_flange": [ - 103.6, - -88.3, - 219.7 + 88.1, + -61.6, + 179.8 ], - "tcp_offset_note": "corrected 2026-10-27 by hover readings at three cup spots (data/hover_readings.json): the taught point carried the camera's cup-centre error (-10.0, +5.2 mm in the arm frame); the camera's own error is fixed in vision/objects.py ROUND_FIX_MM" + "tcp_offset_note": "new fingers, 2026-10-29: mean of 3 owner's free-drive side grasps (data/grasp_side_teach.json; cup in the hooks' belly, grasp turned -24..-33 deg; the cup's centre seen after the hand backed out), spread under 1 mm; then 1 mm to the left across the fingers (the first auto side grasp brushed the cup with the right finger, owner); the old point was 43.5 mm too far out along the fingers. Height kept from the tape (hook bottom 20 mm over a 142 mm cup's rim + 8 mm). Before: [83.2, -69.2, 221.8]" } \ No newline at end of file diff --git a/docs/TUNING.md b/docs/TUNING.md index 1891c3f..d5ac3ef 100644 --- a/docs/TUNING.md +++ b/docs/TUNING.md @@ -94,8 +94,11 @@ Every value here is a constant at the top of its file, with a comment on what it | `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 | -| `manipulation/skills.py` | `MIN_WIDTH`, `MAX_WIDTH` | 70, 90 mm | Object widths the gripper takes (belly open 94, closed 68; tips open 89 / close to 63; [10_GRIPPER.md](10_GRIPPER.md)). `MIN_WIDTH` 61 enables the finger-tip grasp (61–72 mm) | +| `manipulation/skills.py` | `MIN_WIDTH`, `MAX_WIDTH` | 70, 81 mm | Object widths the gripper takes from above (the open ring 87 by tape, 6 margin for the camera; wider cups are taken from the side; belly closed 68; tips open 87 / close to 63; [10_GRIPPER.md](10_GRIPPER.md)). `MIN_WIDTH` 61 enables the finger-tip grasp (61–72 mm) | | `manipulation/skills.py` | `BELLY_MIN_MM` | 70 mm | Thinner objects are held between the finger tips (the belly closes only to 68 mm) | +| `manipulation/skills.py` | `SIDE_MAX_WIDTH`, `SIDE_BAND_MM`, `SIDE_SEEN_MM` | 84, 12, 0 mm | Side grasp of a cup too wide at the top: the width the fingers meet (seen + `SIDE_SEEN_MM`; the camera reads a cup's lower part about right, unlike its rim) must be `MIN_WIDTH`..this (open tips 87 mm) from `SIDE_BAND_MM` below to above the grasp point (the hooks are ~16 mm thick) | +| `manipulation/skills.py` | `SIDE_AT`, `SIDE_TOP_MM` | 0.42, 5 mm | Side grasp height: this share of the cup's height above the table, or the nearest height that fits; the hooks' top at least `SIDE_TOP_MM` under the rim | +| `manipulation/skills.py` | `HOOK_BELOW_MM`, `SIDE_CLEAR_MM` | 8, 40 mm | Side grasp: the hand's lowest part this far below the grasp point (estimate from photos), kept `TIP_CLEAR_MM` above the table; the hand comes down this far from the cup's edge before its tips, then goes in level | | `manipulation/skills.py` | `TIPS_OFFSET` (`data/grasp_tips_teach.json` `tips_offset_flange`) | [−0.4, −4.6, 28.2] mm | Finger-tip grasp: the object's axis goes this far from the hooks' belly centre (flange frame, level, turned with the grasp); taught | | `manipulation/skills.py` | `TIP_CLEAR_MM`, `ROUND_BITE_MM` | 10, 10 mm | Round things (apple, orange, ball): the finger tips (`TIP_MM` 60, estimate) stay this far above the table; the grasp point at least this far below the top, else refused. Estimates | | `manipulation/skills.py` | `BELOW_SHOULDER_MM` | 80 mm | Bottles: the grasp point this far below where the body begins; the hand's lowest part (`TIP_MM` below) must stay `TIP_CLEAR_MM` above the table under it (`table_near`, else the bottle's lowest point seen) | diff --git a/manipulation/skills.py b/manipulation/skills.py index 6a938f6..34e4484 100644 --- a/manipulation/skills.py +++ b/manipulation/skills.py @@ -65,10 +65,12 @@ LIFT_MM = 30.0 # first lift after closing, the MAX_TILT_DEG = 15.0 # deg; a held cup's axis may lean this far from vertical on a joint # move with it (place_options; tasks/fetch.py uses the same) PLACE_EXTRA_MM = 3.0 # put down this much higher than it was picked (same table) -MIN_WIDTH, MAX_WIDTH = 70.0, 90.0 # mm: the hooks' belly goes round the cup (open 94, closed 68). The tips - # grasp (61-72) missed twice live on a 66 mm can (2026-10-22): off by the - # owner until it is checked; 61 brings it back. Over 84 is the owner's - # call (2026-10-19), not tried live yet +MIN_WIDTH, MAX_WIDTH = 70.0, 81.0 # mm: the cup's top goes through the open hooks' ring (87 by tape) and + # the belly closes round it (closed 68). MAX_WIDTH: the owner's margin + # 6 for the camera (an 84 mm rim read 83-85); wider tops are taken from + # the side (side()). The tips grasp (61-72) missed twice live on a + # 66 mm can (2026-10-22): off by the owner until it is checked; 61 + # brings it back SEEN_UNDER_MM = 8.0 # the camera's width is this much under the width the fingers meet # (2026-10-19: 73 seen / 85 by tape, 81 seen / 85 by AI_1); the # limits here are the fingers', compared with grip_width() @@ -117,6 +119,23 @@ BELOW_SHOULDER_MM = 80.0 # bottles: grasp this far below # the owner's taught tips grasp of a spray can, at its middle (2026-10-22, # grasp_tips_teach.json); the hand's lowest part (TIP_MM below) must # stay TIP_CLEAR_MM above the table (else its lowest point seen) +SIDE_MAX_WIDTH = 84.0 # mm; side grasp (a cup whose top is wider than MAX_WIDTH): the width the + # fingers meet (seen + SIDE_SEEN_MM) where the hooks go in from the + # side, under the open tips' 87 mm (owner's tape) with a margin 3 +SIDE_SEEN_MM = 0.0 # ... the camera's width of a cup's lower part is not under like its rim: + # an 84 mm rim cup read 73-77 where the tape gave 71 (45 mm up) and + # AI_1 74 (60 mm up, 2026-10-29) +SIDE_AT = 0.42 # ... grasp this share of the cup's height above the table, or the + # nearest height that fits (owner's free-drive side grasps of a 142 mm + # cup: 54-67 mm up; picked live at 60) +SIDE_TOP_MM = 5.0 # ... the hooks' top this far under the rim at least +SIDE_BAND_MM = 12.0 # ... that width holds from this far below to this far above the grasp + # point (the hooks are ~16 mm thick: owner's photos, about +-5 mm) +HOOK_BELOW_MM = 8.0 # ... the hand's lowest part this far below the grasp point when it + # comes in from the side (half the hooks' thickness; estimate from the + # photos), kept TIP_CLEAR_MM above the table +SIDE_CLEAR_MM = 40.0 # ... the hand comes down this far from the cup's top edge (before the + # tips), then goes in straight along the tips' direction UPRIGHT, ROUND, BODY = "upright", "round", "body" # how the cup fingers take a thing (GRASPS) # Why a thing can't be picked, (English, Korean); {en} / {ko} = its name, {topic} = 은 / 는 FRAGILE = ("I won't take the {en}: my hand closes too hard and it could break.", "{ko}{topic} 깨질 수 있어서 잡지 않을게요.") @@ -127,6 +146,7 @@ SOFT = ("The {en} is too soft: my hand would squeeze it flat.", "{ko}{topic} 너 BIG = ("The {en} is too big for my hand.", "{ko}{topic} 제 손에 너무 커요.") SMALL = ("The {en} is too small for me to hold.", "{ko}{topic} 너무 작아서 잡을 수 없어요.") NO_BODY = ("I can't see the {en}'s body well enough to hold it.", "{ko}의 몸통이 잘 보이지 않아서 잡을 수 없어요.") +WIDE = ("The {en} is too wide for my hand, also lower down.", "{ko}{topic} 아래쪽도 제 손에 너무 커요.") SHORT_BODY = ("The {en}'s body is too short for my fingers: they would hit the table.", "{ko}{topic} 몸통이 짧아서 제 손가락이 테이블에 닿아요.") GRASPS = { # COCO class -> (Korean name, UPRIGHT / ROUND / why not) (docs/15 §10) @@ -238,7 +258,7 @@ def look(frames=FRAMES, ignore=IGNORE): intr, T = camview.intrinsics(objects.CAMERA), objects.base_from_camera() for i in range(frames): d = objects.latest() - depth = camview.depth(objects.CAMERA) if any(GRASPS.get(o["name"], (None, None))[1] == BODY + depth = camview.depth(objects.CAMERA) if any(GRASPS.get(o["name"], (None, None))[1] in (BODY, UPRIGHT) for o in d["objects"]) else None if d["age_s"] is not None and d["age_s"] < objects.STALE_S: live += 1 @@ -251,6 +271,8 @@ def look(frames=FRAMES, ignore=IGNORE): "width_mm": o.get("width_mm"), "height_mm": o.get("height_mm")} if GRASPS.get(o["name"], (None, None))[1] == BODY and depth is not None: row.update(objects.body(depth, o["box"], intr, T) or {}) + if GRASPS.get(o["name"], (None, None))[1] == UPRIGHT and depth is not None: + row["profile"] = objects.profile(depth, o["box"], intr, T) if g: g.append(row) else: @@ -269,6 +291,12 @@ def look(frames=FRAMES, ignore=IGNORE): spread = max(np.hypot(r["x"] - med["x"], r["y"] - med["y"]) for r in rows) out.append({"name": name, "colour": statistics.mode(r["colour"] for r in rows), **med, "seen": len(rows), "spread": round(float(spread), 1), "names": sorted({r["name"] for r in g})}) # every label there + profiles = [r["profile"] for r in rows if r.get("profile")] + if profiles: # an upright thing's widths down its height (side_height) + n = min(len(p[0]) for p in profiles) + out[-1]["profile"] = [(statistics.median(p[0][i][0] for p in profiles), + statistics.median(p[0][i][1] for p in profiles)) for i in range(n)] + out[-1]["low_mm"] = statistics.median(p[1] for p in profiles) if med["shoulder_mm"] is not None: # a bottle: the table under it (its bottom is often out of view) out[-1]["table_mm"] = table_near(out[-1]) return sorted(out, key=lambda o: np.hypot(o["x"], o["y"])) @@ -360,6 +388,11 @@ def grasp_height(obj): raise SkillError(*reason(SHORT_BODY, obj["name"])) return z if how != ROUND: + if how == UPRIGHT and side(obj): + z = side_height(obj) + if z is None: + raise SkillError(*reason(WIDE, obj["name"])) + return z return obj["top_mm"] - BELOW_RIM_MM tall = obj.get("height_mm") or grip_width(obj) bottom = obj["top_mm"] - tall @@ -369,19 +402,66 @@ def grasp_height(obj): return z +def side(obj): + """True when an upright `obj` is too wide at the top for the hooks to come down over it: the side grasp.""" + w = grip_width(obj) + return w is not None and w > MAX_WIDTH and GRASPS.get(obj["name"], (None, None))[1] == UPRIGHT + + +def side_height(obj): + """z (mm) of the grasp point for a side grasp: the height nearest SIDE_AT of the cup's height where the width the + fingers meet (profile + SIDE_SEEN_MM) is within MIN_WIDTH..SIDE_MAX_WIDTH from SIDE_BAND_MM below to SIDE_BAND_MM + above it, the hand's lowest part (HOOK_BELOW_MM under it) stays TIP_CLEAR_MM above what it stands on and the + hooks' top SIDE_TOP_MM under the rim. None when no height fits.""" + slices = obj.get("profile") or [] + floor = obj.get("table_mm") if obj.get("table_mm") is not None else table_z(obj) + if floor is None: + floor = obj.get("low_mm") + if not slices or floor is None: + return None + lo, hi = floor + TIP_CLEAR_MM + HOOK_BELOW_MM, obj["top_mm"] - SIDE_TOP_MM - HOOK_BELOW_MM + want = floor + SIDE_AT * (obj["top_mm"] - floor) + mids = [(t - objects.SLICE_MM / 2, w + SIDE_SEEN_MM) for t, w in slices] + fits = [z for z, _ in mids if lo <= z <= hi and + all(MIN_WIDTH <= w <= SIDE_MAX_WIDTH for m, w in mids if abs(m - z) <= SIDE_BAND_MM)] + return min(fits, key=lambda z: abs(z - want)) if fits else None + + +def tips_dir(yaw=0.0): + """Unit (x, y) in the arm frame the finger tips point to (away from the gripper body), the grasp turned `yaw`.""" + d = (_rz(yaw) @ calib.rpy_matrix(*GRASP_RPY) @ TIPS_OFFSET)[:2] + return d / np.linalg.norm(d) + + +def side_back(obj): + """mm the hand comes down this far from the grasp, against the tips' direction, for a side grasp of `obj`.""" + return grip_width(obj) / 2 + float(np.linalg.norm(TIPS_OFFSET)) + SIDE_CLEAR_MM + + +def back_off(pose, mm): + """Flange pose moved `mm` horizontally against the finger tips' direction (out of a side grasp).""" + d = tips_dir(yaw_of(pose)) * mm + return [pose[0] - d[0], pose[1] - d[1]] + list(pose[2:]) + + def plan_pick(obj, yaw=0.0): - """Waypoints [(name, flange pose)] to pick `obj` (a find() result). Refuses things the fingers can't take - (refusal) and objects of the wrong width or height.""" + """Waypoints [(name, flange pose)] to pick `obj` (a find() result): above, grasp, lift; a side grasp (side()) has + "side" before the grasp, the hand at the grasp height beside the cup, and comes down there. Refuses things the + fingers can't take (refusal) and objects of the wrong width or height.""" no = refusal(obj["name"]) if no: raise SkillError(*no) w = grip_width(obj) - if w is None or w > MAX_WIDTH: + if w is None or (w > MAX_WIDTH and not side(obj)): raise SkillError(*reason(BIG, obj["name"])) if w < MIN_WIDTH: raise SkillError(*reason(SMALL, obj["name"])) z = grasp_height(obj) grasp = flange_for(obj["x"], obj["y"], z, yaw, tips=w < BELLY_MIN_MM) + if side(obj): + start = back_off(grasp, side_back(obj)) + return [("above", up(start, clear_above(obj["top_mm"] - z))), ("side", start), ("grasp", grasp), + ("lift", up(grasp, LIFT_MM))] return [("above", up(grasp, clear_above(obj["top_mm"] - z))), ("grasp", grasp), ("lift", up(grasp, LIFT_MM))] @@ -391,15 +471,19 @@ def clear_above(below): return max(ABOVE_MM, below + TIP_MM) -def plan_place(x, y, top_mm, start=None, yaw=0.0, tips=None, below=None): +def plan_place(x, y, top_mm, start=None, yaw=0.0, tips=None, below=None, back=None): """Waypoints to put down what was picked with its top at `top_mm`, centred at (x, y), the grasp turned by `yaw`. `start`: the flange pose it is held at now (adds the lift to carry height there). `tips`: held between the tips, - `below`: the grasp point this far under its top (default: as pick() holds it).""" + `below`: the grasp point this far under its top, `back`: held from the side, the open hand backs out this far + before it goes up (default: as pick() holds it).""" tips = _held.get("tips", False) if tips is None else tips below = _held.get("below", BELOW_RIM_MM) if below is None else below + back = _held.get("back", 0.0) if back is None else back down = up(flange_for(x, y, top_mm - below, yaw, tips), PLACE_EXTRA_MM) steps = [("carry", [start[0], start[1], down[2] - PLACE_EXTRA_MM + ABOVE_MM] + list(start[3:]))] if start else [] - return steps + [("above place", up(down, ABOVE_MM)), ("place", down), ("release up", up(down, clear_above(below)))] + out = back_off(down, back) if back else down + return steps + [("above place", up(down, ABOVE_MM)), ("place", down)] + \ + ([("release back", out)] if back else []) + [("release up", up(out, clear_above(below)))] def spots(pick_xy, others): @@ -915,7 +999,8 @@ def plan_move(obj, to=None, seen=()): for xy in tries: rows = ik_chain(pick[1:] + plan_place(*xy, obj["top_mm"], start=pick[-1][1], yaw=yaw, tips=grip_width(obj) < BELLY_MIN_MM, - below=obj["top_mm"] - grasp_height(obj)), ja) + below=obj["top_mm"] - grasp_height(obj), + back=side_back(obj) if side(obj) else 0.0), ja) if not rows[-1][3]: return xy, [["above", pick[0][1], ja, None]] + rows log(f"spot ({xy[0]:.0f}, {xy[1]:.0f}) grasp {yaw:+.0f} deg refused at {rows[-1][0]}: {rows[-1][3]}") @@ -949,18 +1034,23 @@ def _line(name, pose): motion.move_linear(target=pose, speed=HOLDING_SPEED) -def _give_up(reason): - """Open, back up 100 mm, home, raise. Only used while the object is at (or just above) the table.""" +def _give_up(reason, back=0.0): + """Open, back up 100 mm (from a side grasp first `back` mm out sideways: the rim is wider than the hooks), home, + raise. Only used while the object is at (or just above) the table.""" log(f"{reason}: opening, backing up") gripper.open_() + if back: + _line("out sideways", back_off(motion.tcp(), back)) motion.move_linear(delta=[0, 0, ABOVE_MM], speed=HOLDING_SPEED) _back_home() raise SkillError(reason) def _do_pick(obj, waypoints, ja): - """Pick with the planned joints `ja` above the object (pick_options).""" - above, grasp, lift = (p for _, p in waypoints) + """Pick with the planned joints `ja` above the object (pick_options); a side grasp goes down beside it first.""" + way = dict(waypoints) + above, grasp, lift = way["above"], way["grasp"], way["lift"] + back = side_back(obj) if "side" in way else 0.0 table = obj.get("table_mm") # a bottle's: look() measured it if table is None: table = table_z(obj) if table_z(obj) is not None else table_near(obj) # what put down needs: the object's height @@ -969,25 +1059,29 @@ def _do_pick(obj, waypoints, ja): _go_on() log(f"above: joint move to ({above[0]:.0f}, {above[1]:.0f}, {above[2]:.0f})") motion.move_joints(ja, EMPTY_SPEED) + if back: + _line("side", way["side"]) _line("grasp", grasp) _go_on() log("closing") s = gripper.close() log(f"AI_1 {s['ai'][0]:.0f} holding {s['holding']} finger sensor {s['object_in_front']}") if not s["holding"]: - _give_up("I missed it.") + _give_up("I missed it.", back) _line("lift", lift) s = gripper.state() log(f"AI_1 {s['ai'][0]:.0f} holding {s['holding']}") if not s["holding"]: _line("slipped, back down", grasp) - _give_up("It slipped out of my hand.") + _give_up("It slipped out of my hand.", back) _held.update(top_mm=obj["top_mm"], x=obj["x"], y=obj["y"], yaw=yaw_of(grasp), table=table, - tips=grip_width(obj) < BELLY_MIN_MM, below=obj["top_mm"] - grasp_height(obj)) + tips=grip_width(obj) < BELLY_MIN_MM, below=obj["top_mm"] - grasp_height(obj), back=back) def _do_place(waypoints): - for name, pose in waypoints[:-1]: + """Down to "place", open, then the rest (out sideways after a side grasp, up) and home.""" + n = [name for name, _ in waypoints].index("place") + 1 + for name, pose in waypoints[:n]: _line(name, pose) _go_on() log("opening") @@ -996,7 +1090,8 @@ def _do_place(waypoints): if s["ai"][0] > OPEN_AI: raise SkillError("My hand did not open.") # stay put: lifting now would drag the object _held.clear() - _line(*waypoints[-1]) + for name, pose in waypoints[n:]: + _line(name, pose) _back_home() @@ -1075,8 +1170,9 @@ def move_object(name="cup", colour=None, to=None): xy, rows = plan_move(obj, to, seen) log(f"placing at ({xy[0]:.0f}, {xy[1]:.0f}); plan of {len(rows)} waypoints passed") waypoints = [(r[0], r[1]) for r in rows] - _guarded(_do_pick, obj, waypoints[:3], rows[0][2]) - _guarded(_do_place, waypoints[3:]) + n = 4 if side(obj) else 3 # above, (side,) grasp, lift + _guarded(_do_pick, obj, waypoints[:n], rows[0][2]) + _guarded(_do_place, waypoints[n:]) log("done") return xy @@ -1096,7 +1192,7 @@ def hover(name="cup", yaw=0.0): _go_on() log(f"above: joint move, grasp turned {yaw:+.0f} deg, wrist J5 {ja[4]:+.0f}") motion.move_joints(ja, HOLDING_SPEED) - _line("hover", up(way[1][1], obj["top_mm"] - grasp_height(obj) + HOVER_MM)) + _line("hover", up(dict(way)["grasp"], obj["top_mm"] - grasp_height(obj) + HOVER_MM)) input(f"hooks {HOVER_MM:.0f} mm over the rim, cup seen at ({obj['x']:.0f}, {obj['y']:.0f}): read the offset, " f"then Enter ") _line("up", way[0][1]) diff --git a/robot/gripper.py b/robot/gripper.py index b541bf3..db3f573 100644 --- a/robot/gripper.py +++ b/robot/gripper.py @@ -27,7 +27,7 @@ EMPTY_AI = 3900 # closed above this = nothing between the fingers ( AI_OPEN, AI_SHUT = 140.0, 4160.0 # AI_1 fully open / closed on nothing (2026-10-19) # inner gap (mm) between the fingers, (open, closed), measured with a tape (docs/gripper/README.md; the straight part # "shank" not measured on these fingers, the earlier one kept); the gap is taken as linear in AI_1 -GAP_MM = {"tips": (89.0, 63.0), "belly": (94.0, 68.0), "neck": (57.0, 30.0), "shank": (66.0, 39.0)} +GAP_MM = {"tips": (87.0, 63.0), "belly": (94.0, 68.0), "neck": (57.0, 30.0), "shank": (66.0, 39.0)} MOVE_S = 1.5 # s a full stroke takes (measured ~1 s) SENSOR_DI = 0 # DI_1 READ_TRIES, READ_GAP_S = 5, 0.1 # get_data now and then answers without the tool I/O: ask again diff --git a/tests/pick_sweep.py b/tests/pick_sweep.py index 2cad048..9601e04 100644 --- a/tests/pick_sweep.py +++ b/tests/pick_sweep.py @@ -645,7 +645,7 @@ def make_pick(i, seed): "stall_gap": rng.choice(STALL_GAPS), "err_seed": rng.randrange(1 << 30)} -def pick_at(x, y, top, grip=80.0, gap=0.10, height=110.0, variant="table", stall_gap=0.10, err_seed=0, chair=None): +def pick_at(x, y, top, grip=76.0, gap=0.10, height=110.0, variant="table", stall_gap=0.10, err_seed=0, chair=None): """A fixed pick scene: the cup seen at (x, y) mm in the arm frame (waist at the front, calibrated arm base) with its top at `top`, on a 0.7 x 1.0 m table whose near edge faces the base centre `gap` m before the cup.""" yaw, org = CALIB["arm_yaw_in_base_deg"], np.asarray(CALIB["arm_xy_in_base_m"]) diff --git a/tests/test_fetch.py b/tests/test_fetch.py index 0b8a568..e024603 100644 --- a/tests/test_fetch.py +++ b/tests/test_fetch.py @@ -107,7 +107,7 @@ for yaw in (-60.0, 10.0, 95.0): # ---------- fake base, arm, gripper and camera ---------- calls = [] -CUP = {"name": "apple", "colour": "red", "x": -150.0, "y": 600.0, "top_mm": -260.0, "width_mm": 76.0, +CUP = {"name": "apple", "colour": "red", "x": -150.0, "y": 600.0, "top_mm": -260.0, "width_mm": 72.0, "seen": 8, "spread": 1.0} hand = {"holding": False, "closed": False} base = {"pose": (0.0, 0.0, 0.0), "polls": 0, "on_poll": None} @@ -518,7 +518,7 @@ skills.reachable_pick = width_check reset() fetch.CALIB_FILE.write_text(json.dumps({"arm_yaw_in_base_deg": -86.2})) wide_far = {**CUP, "name": "cup", "x": -69.0, "y": 1142.0, "width_mm": 98.0} -wide_near = {**wide_far, "x": -100.0, "y": 600.0, "width_mm": 79.0} +wide_near = {**wide_far, "x": -100.0, "y": 600.0, "width_mm": 72.0} # 80 with SEEN_UNDER_MM: fits from above skills.find = lambda name, colour=None, seen=None: wide_near if any(c[0] == "joy" for c in calls) else wide_far st = run(fetch.start, {**ok, "object": "cup", "source": "here", "dest": "here"}) assert st["status"] == "holding" and any("measure it again up close" in l or "closer first" in l for l in st["log"]), \ @@ -528,8 +528,8 @@ hand.update(holding=False, closed=False) reset() skills.find = lambda name, colour=None, seen=None: {**wide_near, "width_mm": 95.0} st = run(fetch.start, {**ok, "object": "cup", "source": "here", "dest": "here"}) -assert st["status"] == "failed" and "too big" in st["log"][-1], st["log"] -skills.find, skills.reachable_pick = real_find, real_reach +assert st["status"] == "failed" and "too wide for my hand, also lower down" in st["log"][-1], st["log"] # no +skills.find, skills.reachable_pick = real_find, real_reach # narrower part measured lower down either skills.reachable_pick = fake_reachable # ---------- put it on a named thing: an orange chair too low for the arm -> said why; one at table height -> on it ---- @@ -601,7 +601,8 @@ assert fetch.lift_for(-703.0) is None and fetch.lift_for(-1060.0) is None # a # ---------- a turn that would take the arm into something is not made ---------- reset() fetch.CALIB_FILE.write_text(json.dumps({"arm_yaw_in_base_deg": -86.2})) -room["clear"] = lambda x, y: 0.05 if math.hypot(x, y) > 0.2 else 1.0 # free at the base centre, a wall around it +room["clear"] = lambda x, y: 0.05 if math.hypot(x, y) > 0.1 else 1.0 # free at the fake flange (the base + # centre), the hand 0.19 m off it in a wall calls.clear() assert fetch._turn(30) is False and not any(c[0] == "go_point" for c in calls), calls room["clear"] = lambda x, y: 1.0 diff --git a/tests/test_fetch_ways.py b/tests/test_fetch_ways.py index b9ab95d..719bd05 100644 --- a/tests/test_fetch_ways.py +++ b/tests/test_fetch_ways.py @@ -158,7 +158,7 @@ def cups(): x, y = arm_xy_of(c["map"]) if visible(x, y) and low_view(x, y, room["z"] + 145.0 / 2): out.append({"name": "cup", "colour": "white", "x": x, "y": y, "top_mm": room["z"] + 145.0, - "height_mm": 145.0, "width_mm": 80.0, "seen": 8, "spread": 1.0, "id": c["id"]}) + "height_mm": 145.0, "width_mm": 72.0, "seen": 8, "spread": 1.0, "id": c["id"]}) return out diff --git a/tests/test_pick_sweep.py b/tests/test_pick_sweep.py index ba956ee..9e54a84 100644 --- a/tests/test_pick_sweep.py +++ b/tests/test_pick_sweep.py @@ -23,13 +23,15 @@ MUST = { # name: (scene, cam "18:40 turned -30": (at(260, 722, -186), 0.0), "18:40 turned -30, nearer": (at(300, 621, -191), 0.0), "18:45 straight ahead": (at(-99, 738, -181), 0.0), - "far edge on a low table (-450)": (at(262, 774, -330, height=120), 0.0), - "sweep 54: low table -432": (ps.make_pick(54, 1), 1.0), - "sweep 189: low table -440": (ps.make_pick(189, 1), 1.0), } PHYSICAL = {"18:13 behind a chair": (at(-141, 869, -186, stall_gap=0.25, chair=0.3), 0.0), + # out of reach where the camera sees it + "far edge on a low table (-450)": (at(262, 774, -330, height=120), 0.0), "sweep 534: behind a chair, low table": (ps.make_pick(534, 1), 1.0)} # was picked turned -30 once -OPEN = {} +# low tables at the lift's end: a stand off the x = -100 line (fetch.pick_goal tries only that line) would see and reach +# the cup, a 5-10 mm deep window +OPEN = {"sweep 54: low table -432": (ps.make_pick(54, 1), 1.0), + "sweep 189: low table -440": (ps.make_pick(189, 1), 1.0)} bad = [] for group, scenes in (("must", MUST), ("physical", PHYSICAL), ("open", OPEN)): diff --git a/tests/test_reach.py b/tests/test_reach.py index c3c505d..41706f6 100644 --- a/tests/test_reach.py +++ b/tests/test_reach.py @@ -45,23 +45,25 @@ 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} + "width_mm": 72.0, "seen": 8, "spread": 1.0} reach = lambda o: skills.reachable_pick(o, accept=fetch._carry_ok) trusted = lambda o: skills.reachable_pick(o, accept=fetch._carry_ok, max_yaw=skills.TRUSTED_YAW_DEG) # fetch's first try -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 +plan = reach(cup(-96, 598)) # picked live 2026-10-2x 15:39 (J5 +20, no turn): now +assert plan and round(skills.yaw_of(plan[0][1][1])) == -15, plan # no IK at the grasp unturned there; -15 is trusted 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) # 2026-10-26 18:40 at lift 0: (260, 722) top -186 was planned turned -30 deg, J5 +26 (missed live, as every turn -# over 15 deg): offline the same; within the trusted turns there is none from here (the waist or the base first) +# over 15 deg). Offline now -30 has no IK at the grasp there: turned -45, J5 +12; within the trusted turns there is +# none from here (the waist or the base first) plan = reach(cup(260, 722, -186)) -assert plan and round(skills.yaw_of(plan[0][1][1])) == -30 and 20 < plan[1][4] < 30, plan +assert plan and round(skills.yaw_of(plan[0][1][1])) == -45 and 10 < plan[1][4] < 20, plan assert skills.reachable_pick(cup(260, 722, -186), accept=fetch._carry_ok, max_yaw=skills.TRUSTED_YAW_DEG) is None -# 17:57 / 18:45: (-104, 694) and (-99, 738) top -186: every straight line to carry refused (a joint jumps); straight up -# and one joint move to carry takes the cup there instead (upright, clear of the head) +# 17:57 / 18:45: (-104, 694) and (-99, 738) top -186: every straight line to carry refused live (a joint jumps). +# With the camera's error fixed both are past the arm's reach from here at this height (it ends near y 660 straight +# ahead): a waist turn or the base first (LIVE below) def line_ok(w, ja): # the straight line alone (fetch._carry_ok also takes carry_up) try: fetch._line_rows(kinematics.pose(motion.poses()["carry"]), "to carry", start=(w[0][1], ja)) @@ -71,14 +73,14 @@ def line_ok(w, ja): # the straight line for seen in ((-104, 694), (-99, 738)): # seen live before the camera's error was fixed xy = np.add(seen, skills.objects.ROUND_FIX_MM) assert skills.reachable_pick(cup(*xy, -186), accept=line_ok) is None, xy - plan = skills.reachable_pick(cup(*xy, -186), accept=lambda w, ja: skills.carry_up(w[0][1], ja) is not None) - assert plan, xy - via, carry = skills.carry_up(plan[0][0][1], plan[1]) - assert via[2] > plan[0][0][1][2] and np.allclose(kinematics.pose(carry)[:3], kinematics.pose(motion.poses()["carry"])[:3], atol=0.1) -# the live (-104, 694) is (-92, 689) with the camera fixed: 9 mm past the trusted-turn edge; just inside it -plan = skills.reachable_pick(cup(-92, 680, -186), accept=lambda w, ja: skills.carry_up(w[0][1], ja) is not None, + assert not list(skills.pick_options(cup(*xy, -186), list(LOOK), skills.TRUSTED_YAW_DEG)), xy +# just inside the trusted reach: straight up and one joint move to carry takes the cup there too (upright, clear of +# the head) +plan = skills.reachable_pick(cup(-92, 640, -186), accept=lambda w, ja: skills.carry_up(w[0][1], ja) is not None, max_yaw=skills.TRUSTED_YAW_DEG) assert plan and abs(skills.yaw_of(plan[0][1][1])) <= 15.5, plan +via, carry = skills.carry_up(plan[0][0][1], plan[1]) +assert via[2] > plan[0][0][1][2] and np.allclose(kinematics.pose(carry)[:3], kinematics.pose(motion.poses()["carry"])[:3], atol=0.1) # a held IK answer with J4 one turn round (the same pose) is not a joint-limit or flip refusal real_ask = skills._ask @@ -114,8 +116,8 @@ assert np.isclose(np.hypot(*(np.subtract((t["x"], t["y"]), C))), np.hypot(*(np.s 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), (720, 7), (720, 25)): # beside it and the live ones - # (the live 730 mm one is 1 cm past the trusted reach since the grasp point was fixed, 2026-10-27) +for r, b in ((600, 60), (600, -60), (550, 90), (600, -100), (660, 7), (660, 25)): # beside it and near the edge + # (the trusted reach round the column ends near 670 mm: the live 730 mm ones are past it) o = around(r, b) assert trusted(o) is None, (r, b) # not from here ... turns = fetch.waist_for(o) @@ -127,10 +129,10 @@ for r, b in ((1000, 0), (950, 40)): # too far for any wa assert all(trusted(fetch.turned(o, d)) is None for d in fetch.waist_for(o)), (r, b) # the live cases of 2026-10-26 with trusted turns only: from here, after a waist turn, or the base moves (none) LIVE = (((262, 774, -189), "base"), ((267, 763, -188), "base"), ((260, 722, -186), "base"), # missed at -45 / -30 - ((300, 621, -191), "waist"), ((-99, 738, -181), "waist"), # missed at -30 / carry line jumped at -30 + ((300, 621, -191), "base"), ((-99, 738, -181), "base"), # missed at -30 / carry line jumped at -30 ((-141, 869, -186), "base"), ((-117, 960, -186), "base"), # across the table / far ((-104, 694, -186), "waist"), ((-73, 588, -186), "here"), ((-96, 598, -260), "here")) # carried / picked -# (694: picked from here live; at the trusted-turn edge since the grasp point was fixed, a small waist turn first) +# (the trusted reach round the column ends near 670 mm: 621 and 738, ~756 mm from it, need the base; 694 a waist turn) for (x, y, top), how in LIVE: # seen before the camera's error was fixed o = cup(x + skills.objects.ROUND_FIX_MM[0], y + skills.objects.ROUND_FIX_MM[1], top) got = "here" if trusted(o) else "waist" if any(trusted(fetch.turned(o, d)) for d in fetch.waist_for(o)) else "base" @@ -186,8 +188,10 @@ assert fetch._waist_reach(task, scene["cup"], None) is None and any(c[0] == "wai skills._held.clear() skills._held.update(top_mm=-300.0, yaw=0.0, tips=False, below=40.0) opts = list(skills.place_options(200.0, 500.0, -300.0, list(LOOK))) -assert opts and all(w[0][0] == "above place (straight)" for w, _ in opts), [w[0][0] for w, _ in opts] -way, ja = opts[0] +# (one joint move there keeps the cup within MAX_TILT_DEG too: it comes first, the straight lines after it) +straight = [(w, ja) for w, ja in opts if w[0][0] == "above place (straight)"] +assert straight and all(w[0][0] in ("above place", "above place (straight)") for w, _ in opts), [w[0][0] for w, _ in opts] +way, ja = straight[0] assert np.allclose(kinematics.pose(ja)[:3], way[0][1][:3], atol=0.05) moved = [] real_lin, real_jm, real_place = skills.motion.move_linear, skills.motion.move_joints, skills._do_place diff --git a/tests/test_skills.py b/tests/test_skills.py index 400d330..638c61d 100644 --- a/tests/test_skills.py +++ b/tests/test_skills.py @@ -8,7 +8,7 @@ from manipulation import skills head_cam.head_centre = lambda: np.array([-92.97, -19.87, 356.12]) # the head's turning centre (head_cam fit 2026-10-19; # its file stays on the Thor) -cup = {"name": "cup", "colour": "white", "x": -126.5, "y": 613.0, "top_mm": -261.0, "width_mm": 76.0} +cup = {"name": "cup", "colour": "white", "x": -126.5, "y": 613.0, "top_mm": -261.0, "width_mm": 72.0} R = calib.rpy_matrix(*skills.GRASP_RPY) g = np.array([cup["x"], cup["y"], cup["top_mm"] - 40]) @@ -61,11 +61,11 @@ assert skills.grasp_height({**cup, "height_mm": 80.0}) == cup["top_mm"] - skills ball = {"name": "orange", "colour": "orange", "x": -126.5, "y": 613.0, "top_mm": -250.0, "width_mm": 150.0 - 8, "height_mm": 150.0} # (too wide for the hand, geometry only) assert skills.grasp_height(ball) == -325.0 # equator 75 mm up, tips 65 mm up -apple = {**ball, "name": "apple", "width_mm": 76.0, "height_mm": 80.0} +apple = {**ball, "name": "apple", "width_mm": 72.0, "height_mm": 80.0} z = skills.grasp_height(apple) bottom = apple["top_mm"] - 80.0 assert z - skills.TIP_MM >= bottom + skills.TIP_CLEAR_MM - 1e-9 and z > bottom + 40.0, z # raised over the equator -assert np.isclose(skills.grasp_height({**apple, "height_mm": None}), skills.grasp_height({**apple, "height_mm": 84.0})) +assert np.isclose(skills.grasp_height({**apple, "height_mm": None}), skills.grasp_height({**apple, "height_mm": 80.0})) try: # too low: the tips would hit the table skills.grasp_height({**apple, "height_mm": 60.0}) raise AssertionError("a 60 mm high apple planned") @@ -140,7 +140,7 @@ skills._ask = ik_at({15, 30}) assert skills.reachable_pick(cup, start, max_yaw=skills.TRUSTED_YAW_DEG) is None real_find, real_guarded, real_home = skills.find, skills._guarded, skills.home_joints skills.home_joints = lambda: start -skills.find = lambda name, colour=None, seen=None: dict(cup, colour="grey", width_mm=74) +skills.find = lambda name, colour=None, seen=None: dict(cup, colour="grey", width_mm=72) skills._guarded = lambda *a: (_ for _ in ()).throw(AssertionError("picked at an untrusted turn")) try: skills.pick("cup") @@ -184,11 +184,6 @@ skills._held.update(tips=True) d = skills.plan_place(-200, 600, thin["top_mm"])[1][1] # put down held the same way assert np.allclose(np.array(d[:3]) + R @ (skills.GRASP_OFFSET + skills.TIPS_OFFSET), [-200, 600, g[2] + 3]) skills._held.clear() -# the owner's taught tips grasp of the spray can (grasp_tips_teach.json): the same flange within a few mm, 2 deg -t = skills.TIPS_TEACH -can = np.add(t["can_seen"][:2], skills.objects.ROUND_FIX_MM) # seen before the camera's error was fixed -f = skills.flange_for(*can, t["grasp_point_code"][2], skills.yaw_of(t["flange"]), tips=True) -assert np.linalg.norm(np.subtract(f[:3], t["flange"][:3])) < 10, f # ---------- frames after a move: wait for one written after it ended, never longer than FRESH_WAIT_S ---------- import tempfile @@ -324,7 +319,7 @@ for bad, words in (({"body_mm": 50.0}, ("too small", "작아서")), frames_ = [{"age_s": 0.1, "objects": [{"name": "bottle", "box": BOX, "colour": "blue", "position_mm": [-195, 600, -280], "top_mm": -150, "width_mm": 63, "height_mm": 250}, {"name": "cup", "box": BOX, "colour": "white", "position_mm": [0, 600, -350], - "top_mm": -310, "width_mm": 76, "height_mm": 90}]}] * 2 + "top_mm": -310, "width_mm": 72, "height_mm": 90}]}] * 2 skills.camview.want = lambda name: None skills.fresh = lambda path, camera, after=0.0: None skills.objects.latest = lambda camera=objects.CAMERA: frames_[0] @@ -367,3 +362,69 @@ assert skills.on_table([(-100.0, 700.0)], -400.0) == [(-100.0, 700.0)] # w assert skills.on_table([(-100.0, 620.0)], -400.0) == [] # its near ring point 5 mm off the edge assert skills.on_table([(-100.0, 700.0)]) == [(-100.0, 700.0)] # table height not given print("skills on_table ok") + +# ---------- side grasp: a cup too wide at the top for the hooks to come down over it, narrower lower down ---------- +top = cup["top_mm"] +wide = {**cup, "width_mm": 90.0, "height_mm": 120.0, # 98 the fingers would meet: over MAX_WIDTH + "profile": [(top - 10.0 * i, 88.0 if i < 4 else 72.0) for i in range(12)]} # 96 at the rim, 80 from 40 mm down +assert skills.side(wide) and not skills.side(cup) +d = skills.tips_dir() +assert np.isclose(np.linalg.norm(d), 1.0) and d[1] > 0.5 # the tips point away from the robot +z = skills.side_height(wide) +assert z == top - 65.0, z # nearest SIDE_AT of its 120 mm (50 mm up, top - 70) where the band is all 72 +short = {**wide, "top_mm": top - 50.0, "height_mm": 70.0, # a 70 mm cup on the same table + "profile": [(top - 50.0 - 10.0 * i, 88.0 if i < 2 else 74.0) for i in range(7)]} +assert skills.side_height(short) == top - 50.0 - 45.0 # 25 mm up: the hooks' bottom 17 over it +way = skills.plan_pick(wide) +assert [n for n, _ in way] == ["above", "side", "grasp", "lift"], way +p = dict(way) +assert np.isclose(p["side"][2], p["grasp"][2]) and p["side"][3:] == p["grasp"][3:] # in level at the grasp height +back = skills.side_back(wide) +assert np.isclose(back, 98.0 / 2 + np.linalg.norm(skills.TIPS_OFFSET) + skills.SIDE_CLEAR_MM) +assert np.allclose(np.subtract(p["grasp"][:2], p["side"][:2]), d * back) # it goes in along the tips' direction +assert np.allclose(np.subtract(p["above"][:3], p["side"][:3]), [0, 0, skills.clear_above(top - z)]) +g = np.array(p["grasp"][:3]) + calib.rpy_matrix(*p["grasp"][3:]) @ skills.GRASP_OFFSET +assert np.allclose(g, [wide["x"], wide["y"], z]) # the hooks' point on the cup axis +assert [n for n, _ in skills.plan_pick(cup)] == ["above", "grasp", "lift"] # a cup whose top fits: from above, as before +for bad in ([(top - 10.0 * i, 88.0) for i in range(12)], # wide all the way down + [(top - 10.0 * i, 88.0 if i < 10 else 72.0) for i in range(12)], # narrow only where the hooks hit the table + None): # its widths down its height not measured + try: + skills.plan_pick({**wide, "profile": bad}) + raise AssertionError(f"side grasp planned for {bad}") + except skills.SkillError as e: + assert e.args == skills.reason(skills.WIDE, "cup"), e.args +# picked from the side: the open hand backs out sideways before it goes up, also after a miss +lines_, opened = [], [] +skills._line = lambda name, pose: lines_.append((name, pose)) +skills.gripper.open_ = lambda: (opened.append(len(lines_)), {"ai": [150.0]})[1] +skills.gripper.close = lambda: {"ai": [3500.0], "holding": True, "object_in_front": False} +skills.gripper.state = lambda: {"ai": [3500.0], "holding": True} +skills._back_home = lambda: None +skills._held.clear() +skills._do_pick(wide, way, READY) +assert [n for n, _ in lines_] == ["side", "grasp", "lift"] and np.isclose(skills._held["back"], back) +assert np.isclose(skills._held["below"], top - z) +put = skills.plan_place(-200, 600, top) +assert [n for n, _ in put] == ["above place", "place", "release back", "release up"], put +q = dict(put) +assert np.isclose(q["release back"][2], q["place"][2]) +assert np.allclose(np.subtract(q["place"][:2], q["release back"][:2]), d * back) +assert np.allclose(np.subtract(q["release up"][:3], q["release back"][:3]), [0, 0, skills.clear_above(top - z)]) +lines_.clear() +skills._do_place(put) +assert [n for n, _ in lines_] == ["above place", "place", "release back", "release up"] and opened[-1] == 2 +assert [n for n, _ in skills.plan_place(-200, 600, top, back=0.0)][-2:] == ["place", "release up"] # from above: as before +lines_.clear() +skills.gripper.close = lambda: {"ai": [4150.0], "holding": False, "object_in_front": False} +skills.motion.tcp = lambda: p["grasp"] +skills.motion.move_linear = lambda **k: lines_.append(("up", k.get("delta"))) +try: + skills._do_pick(wide, way, READY) + raise AssertionError("a miss went on") +except skills.SkillError: + pass +assert [n for n, _ in lines_] == ["side", "grasp", "out sideways", "up"], lines_ +assert np.allclose(np.subtract(p["grasp"][:2], lines_[2][1][:2]), d * back) +skills._held.clear() +print("skills side grasp ok") diff --git a/vision/objects.py b/vision/objects.py index 6ea59e8..d2b1bb1 100644 --- a/vision/objects.py +++ b/vision/objects.py @@ -154,11 +154,9 @@ def measure(color, depth, box, intr, T, round_=False): return out -def body(depth, box, intr, T): - """Width profile of an upright bottle in `box`, cut in SLICE_MM height slices: {"shoulder_mm": where its body - begins (the top of the first slice from the top down at least BODY_FRACTION as wide as the body), "body_mm": the - body's width (median of the slices below that), "low_mm": its lowest point seen}, mm in the arm base frame; None - when not measured. Seen widths, as width_mm.""" +def profile(depth, box, intr, T): + """(slices, lowest z seen) of the upright thing in `box`: slices [(top z of the slice, width)] from the top down, + SLICE_MM thick, mm in the arm base frame, seen widths (as width_mm); None when not measured.""" P = points(depth, box, intr, T)[2] if P is None: return None @@ -166,13 +164,23 @@ def body(depth, box, intr, T): sight /= np.linalg.norm(sight) or 1.0 across = P[:2].T @ np.array([-sight[1], sight[0]]) low, top = np.percentile(P[2], EDGE_PCT) - slices = [] # (top z of the slice, width), from the top down + slices = [] for z in np.arange(top, low, -SLICE_MM): a = across[(P[2] <= z) & (P[2] > z - SLICE_MM)] if len(a) >= SLICE_MIN_POINTS: slices.append((float(z), float(np.subtract(*np.percentile(a, EDGE_PCT[::-1]))))) - if not slices: + return (slices, float(low)) if slices else None + + +def body(depth, box, intr, T): + """Width profile of an upright bottle in `box` (profile()): {"shoulder_mm": where its body begins (the top of the + first slice from the top down at least BODY_FRACTION as wide as the body), "body_mm": the body's width (median of + the slices below that), "low_mm": its lowest point seen}, mm in the arm base frame; None when not measured. Seen + widths, as width_mm.""" + p = profile(depth, box, intr, T) + if p is None: return None + slices, low = p wide = BODY_FRACTION * np.percentile([w for _, w in slices], BODY_PCT) i = next(i for i, (_, w) in enumerate(slices) if w >= wide) return {"shoulder_mm": round(slices[i][0]), "body_mm": round(float(np.median([w for _, w in slices[i:]]))),