13 · ピック&プレース¶
目標: シミュレーション上の TurtleBot3 Lime を、すべてそろった状態で動かします。チュートリアル 06〜12 のすべてのセンサーとグラフに加えて、MoveIt 2、Nav2、YOLO を同時に動かします。そのうえで、バナナを見つけて拾い上げ、ボウルに入れてから駐車するという仕事を与えます。2D の検出が 3D の位置になり、ロボットがそこまで正確に走り、アームがそれを把持する、という各部分のつながりがわかります。
システム全体¶
flowchart LR
subgraph ISAAC["Isaac Sim · isaac/13_all_together.py"]
direction TB
g06[clock + drive<br/>06]
g07[odom + TF + joint states<br/>07 / 12]
g08[camera: RGB + depth<br/>08]
g09[LiDAR + IMU<br/>09]
g12[joint commands<br/>12]
end
subgraph ROS["ROS 2 · lime_full.launch.py"]
direction TB
rc[ros2_control + MoveIt 2<br/>lime_isaac_moveit]
nav[Nav2<br/>map, AMCL, planner, controller]
yolo[YOLO<br/>lime_yolo]
mission[mission<br/>lime_isaac_bringup]
end
g06 -- "/clock" --> ROS
nav -- "/cmd_vel" --> g06
mission -- "/cmd_vel (last centimetres)" --> g06
g07 -- "/odom /tf /isaac_joint_states" --> rc & nav & mission
rc -- "/isaac_joint_commands" --> g12
g08 -- "color/image_raw" --> yolo
g08 -- "aligned_depth_to_color, camera_info" --> mission
g09 -- "/scan" --> nav
yolo -- "/detections" --> mission
mission -- "MoveGroup, GripperCommand" --> rc
mission -- NavigateToPose --> nav
robot_state_publisher は 1 つだけ
lime_full.launch.py は lime_isaac_moveit/moveit.launch.py をインクルードし、これが唯一の robot_state_publisher を起動します。その URDF には ros2_control のブロックも含まれています。Nav2 の bringup は navigation.launch.py を介さずに直接インクルードしているので、2 つ目の robot_state_publisher が起動することはありません。/joint_states は joint_state_broadcaster からしか来ません(チュートリアル 12 を参照)。
拾い上げられる物体¶
チュートリアル 08〜10 では、床の上の物体はカメラに映る絵にすぎず、コライダーも質量もありませんでした。ここでは物体が実体を持ちます (add_object_physics)。コライダーと質量があるので、ロボットは物体をすり抜けられず、ロボットがぶつかれば物体は倒れます。物体を拾い上げるには、さらに 2 つのものが必要です。バナナが入るボウルと、滑りにくい指です。
| 物体 | 物理設定 | 理由 |
|---|---|---|
| バナナ | 剛体、66 g、convex decomposition(凸分解)のコライダー | 落ちたり、押されたり、持ち上げられたりする必要がある。凸包 1 つだと、曲がったバナナが幅 7 cm の塊になり、グリッパーで挟むには幅が広すぎる |
| マグカップ、マスタードのボトル | 剛体、118 g と 603 g。マグカップは convex decomposition、ボトルは convex hull(凸包) | ロボットがぶつかれば倒れる。デフォルトの凸包では、マグカップが 5 s で床の上を勝手に 16 cm 動いた。凸分解にすると静止したままになる |
| ボウル | 静的なコライダー、none(三角形メッシュそのもの)。このチュートリアルでは 1.5 倍の大きさ | くぼみの中にバナナを収める必要がある。19 cm のバナナは、元の 16 cm のボウルには入らない |
| 指 + バナナ | 物理マテリアル、摩擦 1.0(このチュートリアルで設定) | ゴムのようなパッドにして、10 N で挟めばバナナを保持できるようにする |
assets/scenes/lime_room.usda を開き、Property パネルの + Add ボタンを使います。
/World/LimeRoom/Objects/Bananaを選びます。+ Add ▸ Physics ▸ Rigid Body with Colliders Preset を選び、続いて + Add ▸ Physics ▸ Mass を選んで、Mass を 0.066 にします。Mug(0.118) とBottle(0.603) にも同じことをします。ボトルは Convex Hull のままでかまいません。マグカップのメッシュにも Convex Decomposition を設定します(手順 2)。-
Stage パネルでバナナを展開し、そのメッシュを選びます。プリセットによって Convex Hull のコライダーが付いています。Approximation を Convex Decomposition に変更します。

-
ボウルを選びます。Scale を 1.5、Translate Z を 0.044 にして、床の上に立ったままになるようにします。次に + Add ▸ Physics ▸ Colliders Preset を選びます。これで近似が None(三角形メッシュそのもの)の静的なコライダーになります。決して動かない物体なら、これを使ってかまいません。
- Create ▸ Physics ▸ Physics Material を選び、Rigid Body Material にチェックを入れて Ok をクリックします。その静止摩擦と動摩擦を 1.0 にします。バナナのメッシュをもう一度選び、その Physics materials on selected models セクションで新しいマテリアルを選びます(このセクションはコライダーのプリムにしか表示されません)。
指にも同じマテリアルが必要ですが、ロボットの指のコライダー gripper_left_palm と gripper_right_palm はインスタンス化されています。つまり、共有された読み取り専用のコピーなので、GUI からは変更できません。Python 版では、1 つ上の階層の gripper_left_link と gripper_right_link にマテリアルをバインドしています。このバインドは、その下にあるすべてのコライダーに適用されます。
{ .full }
Play を押し、Shift + マウスの左ボタンでバナナをドラッグします。バナナが落ちて転がるようになりました。
作業内容を残すには、Stop ■ を押し、File ▸ Save As で my_stages/13_pick_and_place.usd として保存します。lime_room.usda には上書きしないでください。チュートリアル 08 と 11 の GUI タブがこのファイルを開きます。
13_all_together.py は、object_physics=True を指定して lime_room を作ります。
add_object_physics():すべての物体にコライダーと質量を与える
def add_object_physics(stage, root: str = "/World/LimeRoom"):
"""Make the objects real: colliders and mass, so the robot cannot drive through them (tutorial 13).
Without this (tutorials 08-10) they are only pictures for the camera. With it:
* banana, mug, bottle: rigid bodies with their real (YCB) masses: they fall, can be pushed, knocked over
and lifted. Colliders: a convex decomposition for the banana (a single convex hull would make the
curved banana a 7 cm wide blob, too wide for the gripper) and for the mug (with a convex hull it crept
across the floor by itself); a convex hull for the bottle.
* bowl: a static collider (it never moves) that keeps its exact, hollow shape ("none" = the triangle mesh
itself, which PhysX allows for static objects only)
"""
from pxr import PhysxSchema, Usd, UsdGeom, UsdPhysics
def colliders(prim, approximation):
for p in Usd.PrimRange(prim):
if p.IsA(UsdGeom.Mesh):
UsdPhysics.CollisionAPI.Apply(p)
UsdPhysics.MeshCollisionAPI.Apply(p).CreateApproximationAttr(approximation)
for name, mass, approximation in (
("Banana", 0.066, "convexDecomposition"),
("Mug", 0.118, "convexDecomposition"),
("Bottle", 0.603, "convexHull"),
):
prim = stage.GetPrimAtPath(f"{root}/Objects/{name}")
UsdPhysics.RigidBodyAPI.Apply(prim)
UsdPhysics.MassAPI.Apply(prim).CreateMassAttr(mass) # kg
colliders(prim, approximation)
# a banana squeezed between two fingers (tutorial 13) needs more solver iterations
banana = stage.GetPrimAtPath(f"{root}/Objects/Banana")
PhysxSchema.PhysxRigidBodyAPI.Apply(banana).CreateSolverPositionIterationCountAttr(32)
colliders(stage.GetPrimAtPath(f"{root}/Objects/Bowl"), "none")
そのあと、ボウルと指のための関数を 1 つ追加で呼び出します。
BOWL_SCALE = 1.5 # tutorial 13: the 19 cm banana fits into a 24 cm bowl, not into the 16 cm original
def setup_pick_and_place(stage, robot_path: str, root: str = "/World/LimeRoom"):
"""Tutorial 13, on top of add_object_physics(): a bowl the banana fits into, and grippy fingers.
* bowl: 1.5x bigger (its static collider scales with it)
* fingers and banana: rubber-like friction 1.0, so a 10 N squeeze holds the banana
"""
from isaacsim.core.experimental.prims import XformPrim
from pxr import Usd, UsdPhysics, UsdShade
_name, _asset, x, y, _yaw, half_height, _up, _coco = next(o for o in OBJECTS if o[0] == "Bowl")
bowl = XformPrim(f"{root}/Objects/Bowl")
bowl.set_local_scales([[BOWL_SCALE] * 3])
_position, orientation = bowl.get_world_poses()
bowl.set_world_poses(positions=[[x, y, BOWL_SCALE * half_height + 0.002]], orientations=orientation)
rubber = UsdShade.Material.Define(stage, f"{root}/PhysicsMaterials/rubber")
api = UsdPhysics.MaterialAPI.Apply(rubber.GetPrim())
api.CreateStaticFrictionAttr(1.0)
api.CreateDynamicFrictionAttr(1.0)
banana = stage.GetPrimAtPath(f"{root}/Objects/Banana")
fingers = [p for p in Usd.PrimRange(stage.GetPrimAtPath(robot_path)) if p.GetName() in ("gripper_left_link", "gripper_right_link")]
for prim in [banana, *fingers]:
UsdShade.MaterialBindingAPI.Apply(prim).Bind(rubber, UsdShade.Tokens.weakerThanDescendants, "physics")
実行してみる¶
ターミナル 1 で Isaac Sim を起動します。
ターミナル 2 で ROS 2 のスタックと RViz を起動します(「Managed nodes are active」と「You can start planning now!」が表示されるまで待ちます。RViz なしで起動するには rviz:=false を付けます)。
ターミナル 3 でミッションを実行します(初回の起動時には、ターミナル 2 で約 40 MB の yolo11m.pt がダウンロードされます)。
YOLO: banana (0.88) at (0.75, -0.11), bowl (0.70) at (0.96, 0.41)
YOLO: banana (0.92) at (0.792, -0.123), pointing 19 deg
MoveIt: above the banana: done
MoveIt: down to the banana: done
MoveIt: lift: done
MoveIt: carry: done
YOLO: bowl (0.67) at (0.998, 0.377), radius 9 cm
MoveIt: above the bowl: done
MoveIt: arm folded: done
Nav2: parking at (2.8, -1.8)
mission complete: the banana is in the bowl
シミュレーションでのバナナの実際の位置は (0.800, −0.121)、向きは 20° で、ボウルは (1.0, 0.4) にあります。スタート地点からの 1 回目の観測は、5 cm 手前にずれています。横からの 2 回目の観測は誤差 1 cm 以内で、把持するには十分な精度です。

ミッションのしくみ¶
flowchart LR
a["1 · YOLO + depth<br/>find banana and bowl"] --> b["2 · look again<br/>from the side"] --> c["3 · drive to 16 cm"]
c --> d["4 · MoveIt<br/>pick"] --> e["5 · drive round the mug<br/>to the bowl"] --> f["6 · MoveIt<br/>place, fold"] --> g["7 · into the open<br/>Nav2 parks"]
ミッションの主要部分:lime_isaac_bringup/scripts/mission.py
# 1. Find the banana and the bowl from where we are (the banana is small and far: collect a few seconds).
found, found_bowl = lime.locate("banana", seconds=6.0), lime.locate("bowl", seconds=2.0)
if found is None or found_bowl is None:
fail("YOLO: I need to see both the banana and the bowl")
banana, _ = long_object(found)
bowl, _ = round_object(found_bowl)
log.info(f"YOLO: banana ({found['score']:.2f}) at ({banana[0]:.2f}, {banana[1]:.2f}), bowl ({found_bowl['score']:.2f}) at ({bowl[0]:.2f}, {bowl[1]:.2f})")
# 2. From here we see the banana almost end-on: its far half hides behind its near half. Look again from
# 45 cm away and 55 deg further round (the side away from the mug): now the whole banana is visible.
x, y, _ = lime.pose()
look = math.atan2(banana[1] - y, banana[0] - x) + math.radians(55)
toward = np.array([math.cos(look), math.sin(look)])
lime.drive_to(*(banana - 0.45 * toward))
lime.turn_to(look)
found = lime.locate("banana")
if found is None:
fail("YOLO: lost the banana")
banana, banana_yaw = long_object(found)
log.info(f"YOLO: banana ({found['score']:.2f}) at ({banana[0]:.3f}, {banana[1]:.3f}), pointing {math.degrees(banana_yaw) % 180:.0f} deg")
# 3. Stop with the banana 16 cm in front of the robot: inside the arm's reach for a top-down grasp.
lime.drive_to(*(banana - 0.16 * toward))
lime.turn_to(look)
# 4. Pick it up.
lime.gripper(GRIPPER_OPEN)
bx, by = lime.to_base(*banana)
yaw = wrap(banana_yaw - lime.pose()[2]) # the banana's direction as seen from the robot
above, grasp, lifted = (top_down_ik(bx, by, z, yaw) for z in (0.10, 0.03, 0.15))
if None in (above, grasp, lifted):
fail(f"the banana at ({bx:.3f}, {by:.3f}) in the robot frame is out of reach")
if not (lime.move_arm(above, "above the banana") and lime.move_arm(grasp, "down to the banana")):
fail("MoveIt: grasp failed")
lime.gripper(GRIPPER_CLOSED) # stops when the fingers touch the banana, and keeps squeezing
if not (lime.move_arm(lifted, "lift") and lime.move_arm(CARRY, "carry")):
fail("MoveIt: lift failed")
# 5. Back to the bowl. The mug stands between the banana and the bowl, so go round: approach the bowl
# from its open side (from -y, 42 cm away), look again, and drive up until the bowl is 20 cm in front.
lime.drive_to(bowl[0], bowl[1] - 0.42)
lime.turn_to(math.pi / 2)
found = lime.locate("bowl")
if found is None:
fail("YOLO: lost the bowl")
bowl, radius = round_object(found)
log.info(f"YOLO: bowl ({found['score']:.2f}) at ({bowl[0]:.3f}, {bowl[1]:.3f}), radius {radius * 100:.0f} cm")
lime.drive_to(bowl[0], bowl[1] - 0.20)
lime.turn_to(math.pi / 2)
# 6. Put the banana in: above the bowl's centre, or as close to it as the arm reaches; banana across the robot.
bx, by = lime.to_base(*bowl)
release = next((q for x in np.arange(bx, 0.10, -0.005) if (q := top_down_ik(x, by, 0.13, math.pi / 2))), None)
if release is None or not lime.move_arm(release, "above the bowl"):
fail("MoveIt: could not reach the bowl")
lime.gripper(GRIPPER_OPEN)
lime.spin_for(1.0)
lime.move_arm(HOME, "arm folded")
# 7. Back away from the bowl and drive into the open middle of the room, then let Nav2 park the robot.
# (Started right next to the bottle, Nav2 would steer the robot straight through it.)
x, y, yaw = lime.pose()
lime.drive_to(x - 0.12 * math.cos(yaw), y - 0.12 * math.sin(yaw), backwards=True)
lime.drive_to(bowl[0] + 0.6, bowl[1] - 0.45)
log.info(f"Nav2: parking at ({PARK[0]}, {PARK[1]})")
goal = PoseStamped()
goal.header.frame_id = "map"
goal.pose.position.x, goal.pose.position.y = PARK[0], PARK[1]
goal.pose.orientation.w = 1.0
lime.nav.goToPose(goal)
while not lime.nav.isTaskComplete():
time.sleep(0.2)
if lime.nav.getResult() != TaskResult.SUCCEEDED:
fail(f"Nav2: could not park: {lime.nav.getResult()}")
1. 2D のボックスから 3D の点へ¶
より大きな YOLO
lime_full.launch.py は、チュートリアル 10 の yolo11n.pt (nano) ではなく yolo11m.pt (medium) を実行します。低い位置にあるカメラから見ると、バナナは平たい黄色の三日月形です。nano モデルはこれを frisbee (0.44) と判定し、small モデルは 0.46 でバナナ、medium モデルは 0.88 でバナナと判定します(チュートリアル 10 では、nano モデルでも 0.40 でバナナを見つけられます。ここではバナナに物理が設定されていて数ミリメートル違う姿勢で静止するので、nano モデルの答えが frisbee に変わってしまいます)。medium モデルは CPU で 1 枚あたり約 75 ミリ秒かかりますが、毎秒 5 枚なら問題ありません。モデルは yolo_model:=... で選べます。
YOLO の答えは「バナナ、0.9、このボックスの中」で、単位はメートルではなくピクセルです。位置合わせ済みの深度画像(チュートリアル 08)には、各ピクセル \((u, v)\) について、カメラの光軸方向の距離 \(z\) が入っています。camera_info のカメラモデルを使うと、これをカメラの光学フレームでの 3D の点に変換できます。
次に TF で、点を camera_color_optical_frame から odom フレームに移します。このとき、画像が撮影された瞬間の変換を使います(検出のタイムスタンプ)。ロボットはそのあと動いているかもしれません。床の上の点 (\(z \approx 0\)) は捨てます。残るのは、その物体の小さな点群です。
Lime.locate()
def locate(self, name, seconds=4.0):
"""Find object `name` with YOLO and measure where it is: a 3D point cloud of the object, in the odom frame.
2D box (YOLO) + depth image + camera model -> 3D points in the camera frame
+ TF odom <- camera at the image's time stamp -> 3D points in the odom frame
"""
self.detections.clear()
self.spin_for(seconds) # collect a few seconds of detections, keep the most confident one
best = None
for msg, depth_msg in self.detections:
for d in msg.detections:
h = d.results[0].hypothesis
if h.class_id == name and (best is None or h.score > best[0]):
best = (h.score, d, msg.header, depth_msg)
if best is None or self.K is None:
return None
score, det, header, depth_msg = best
pts, camera = self.points(det, header, depth_msg)
return None if pts is None else {"score": score, "points": pts, "camera": camera}
def points(self, det, header, depth_msg):
"""The 3D points (odom frame) of one detection's box, and where the camera was. (None, None) if too few."""
depth = np.frombuffer(depth_msg.data, dtype=np.float32).reshape(depth_msg.height, depth_msg.width)
cx, cy = det.bbox.center.position.x, det.bbox.center.position.y
w, h = det.bbox.size_x, det.bbox.size_y
u0, u1 = int(max(cx - w / 2, 0)), int(min(cx + w / 2, depth_msg.width - 1))
v0, v1 = int(max(cy - h / 2, 0)), int(min(cy + h / 2, depth_msg.height - 1))
v, u = np.mgrid[v0:v1 + 1, u0:u1 + 1]
z = depth[v0:v1 + 1, u0:u1 + 1]
ok = np.isfinite(z) & (z > 0.05) & (z < 3.0)
fx, fy, px, py = self.K[0, 0], self.K[1, 1], self.K[0, 2], self.K[1, 2]
cam = np.stack([(u[ok] - px) * z[ok] / fx, (v[ok] - py) * z[ok] / fy, z[ok]], axis=1) # optical frame
tf = self.tf.lookup_transform("odom", header.frame_id, header.stamp, timeout=rclpy.duration.Duration(seconds=1.0))
t, q = tf.transform.translation, tf.transform.rotation
R = quat_to_matrix(q.x, q.y, q.z, q.w)
pts = cam @ R.T + np.array([t.x, t.y, t.z])
pts = pts[(pts[:, 2] > 0.006) & (pts[:, 2] < 0.40)] # drop the floor (z = 0) around the object
if len(pts) < 20:
return None, None
middle = np.median(pts[:, :2], axis=0)
pts = pts[np.linalg.norm(pts[:, :2] - middle, axis=1) < 0.25] # drop the background inside the box
return pts, np.array([t.x, t.y])
2. 正確にはどこにあるか¶
カメラには物体の手前側しか見えないので、形ごとに小さなルールを用意します。
- バナナ(細長い物体): バナナの向きは点群の主軸(主成分分析)で求め、グリッパーはバナナを横切る向きに閉じます。把持点は長さの中央、つまり両端のちょうど中間です。単純な点の平均ではありません。カメラに近い側の端のほうが深度ピクセルが多く、平均をそちらに引き寄せてしまうからです。
- ボウル(丸い物体): 中心は、見えている点の真ん中にはありません。見えている点はすべて手前側にあるからです。中心は視線の方向に半径 1 つ分だけ奥にあり、半径は見えている幅の半分です。
long_object() と round_object()
def long_object(found):
"""A lying object (the banana): its direction = the main axis of its points (PCA); the grasp point = the
middle of its length. Not simply the average point: the end nearer the camera gets more depth pixels."""
xy = found["points"][:, :2]
mean = xy.mean(axis=0)
eigenvalues, eigenvectors = np.linalg.eigh(np.cov((xy - mean).T))
axis = eigenvectors[:, np.argmax(eigenvalues)]
normal = np.array([-axis[1], axis[0]])
along, across = (xy - mean) @ axis, (xy - mean) @ normal
middle = (np.percentile(along, 2) + np.percentile(along, 98)) / 2 # halfway between the two ends
at_middle = np.abs(along - middle) < 0.02 # the slice of the object there (a banana is curved)
centre = mean + middle * axis + np.median(across[at_middle]) * normal
return centre, math.atan2(axis[1], axis[0])
def round_object(found):
"""A round object (the bowl): the camera sees only its front, so centre = front surface + one radius
further along the line of sight; the radius is half the width the camera sees."""
xy = found["points"][:, :2]
ray = np.median(xy, axis=0) - found["camera"]
ray /= np.linalg.norm(ray)
side = np.array([-ray[1], ray[0]])
along, across = (xy - found["camera"]) @ ray, (xy - found["camera"]) @ side
radius = (np.percentile(across, 98) - np.percentile(across, 2)) / 2
front = np.percentile(along, 5)
middle = (np.percentile(across, 98) + np.percentile(across, 2)) / 2
return found["camera"] + (front + radius) * ray + middle * side, radius
3. 最後の数センチ:オドメトリで走る¶
真下を向いた状態でアームが床に届くのは、base_footprint の前方約 12〜20 cm の範囲だけです。Nav2 はゴールの許容誤差 25 cm 以内で停止します。駐車にはこれで十分ですが、把持には粗すぎます。そこで短い移動では、ミッションが自分でロボットを走らせます。目標のほうを向き、まっすぐ走り、1 cm 以内の誤差で止まります。/cmd_vel をパブリッシュし、姿勢は TF(odom → base_footprint、Isaac Sim のオドメトリ)から読み取ります。ロボットがバナナを運んでいることもあるので、速度はゆっくり変えます。
2 つのルールで、これを単純に保っています。
- 横から見て、あとは見ずに走る: スタート地点からは、カメラにはバナナがほぼ端の方向から見えるので、奥の半分が手前の半分に隠れてしまいます(推定値は 5 cm 手前にずれました)。そこでロボットは、45 cm 離れ、55° 回り込んだ位置からもう一度見ます。そのあと、最後の 30 cm は見ずに走ります。近づくと、低い位置のカメラではバナナがきちんと見えなくなります(16 cm では画像の下端でバナナが切れます)。また、チュートリアル 07 では、0.8 m 走ったあとの Isaac Sim のオドメトリの誤差は 3 mm 以内でした。
- 物体は自分で回り込む: これらの短い走行では Nav2 を使わないので、マグカップを回り込む経路を計画してくれるものはありません。そこでミッションは、ボウルのふさがっていない側から近づきます。
- 開けた場所で Nav2 に引き継ぐ: バナナを落としたあと、ロボットはマスタードのボトルのすぐ隣にいます。Nav2 にはボトルが見えていますが、このミッションの最初のバージョンでは、これほど近くから出発したために、ボトルを突き抜けてまっすぐ走ってしまいました。そこでミッションは、ボウルから後退し、部屋の中央の開けた場所へ 60 cm 走ってから Nav2 に引き継ぎます。
turn_to()、drive_to()、to_base()
def pose(self):
"""Robot pose (x, y, yaw) in the odom frame - Isaac Sim's odometry, through TF."""
tf = self.tf.lookup_transform("odom", "base_footprint", rclpy.time.Time(), timeout=rclpy.duration.Duration(seconds=1.0))
t, q = tf.transform.translation, tf.transform.rotation
return t.x, t.y, math.atan2(2 * (q.w * q.z + q.x * q.y), 1 - 2 * (q.y * q.y + q.z * q.z))
def send(self, v, w):
msg = Twist()
msg.linear.x, msg.angular.z = float(v), float(w)
self.cmd.publish(msg)
def turn_to(self, yaw):
w, end = 0.0, time.time() + 30.0
while time.time() < end:
error = wrap(yaw - self.pose()[2])
if abs(error) < 0.01:
break
target = math.copysign(min(0.5, max(0.08, 1.5 * abs(error))), error)
w += max(-0.03, min(0.03, target - w)) # gentle acceleration: the robot carries things
self.send(0.0, w)
time.sleep(0.05)
self.send(0.0, 0.0)
time.sleep(0.5)
def drive_to(self, x, y, backwards=False):
"""Turn towards (x, y) [odom frame], drive there in a straight line, stop within a centimetre."""
px, py, _ = self.pose()
heading = math.atan2(y - py, x - px) + (math.pi if backwards else 0.0)
self.turn_to(heading)
v, sign, end = 0.0, -1.0 if backwards else 1.0, time.time() + 60.0
while time.time() < end:
px, py, yaw = self.pose()
ahead = (x - px) * math.cos(yaw) + (y - py) * math.sin(yaw) # distance left along the heading
if sign * ahead < 0.008:
break
target = min(0.12, max(0.02, 0.8 * abs(ahead)))
v += max(-0.01, min(0.01, target - v))
side = -(x - px) * math.sin(yaw) + (y - py) * math.cos(yaw)
self.send(sign * v, max(-0.3, min(0.3, 2.0 * side * sign)) if abs(ahead) > 0.05 else 0.0)
time.sleep(0.05)
self.send(0.0, 0.0)
time.sleep(0.5)
def to_base(self, x, y):
"""odom-frame point -> base_footprint frame (where the arm works)."""
px, py, yaw = self.pose()
dx, dy = x - px, y - py
return dx * math.cos(yaw) + dy * math.sin(yaw), -dx * math.sin(yaw) + dy * math.cos(yaw)
4. 真上からの把持:紙の上で解く逆運動学¶
真上から把持する場合、Lime の 6 ジョイントのアームは単純になります。
joint1は物体のほうを向きます。joint2(肩)とjoint3(肘)は、長さ \(L_1 = 12.4\) cm と \(L_2 = 10.45\) cm の平面 2 リンクアームになります。手首はend_effector_linkの \(L_3 = 16.25\) cm 上に来ます(指先はさらに 2 cm 下まで届きます)。joint5は 3 つの傾きの合計を 180° にして、グリッパーが真下を向くようにします。joint6は、指がバナナを横切る向きになるように回します。
\(r\) を水平距離、\(d_z\) を肩から見た手首の高さとすると、余弦定理から肘の角度が求まります。
ミッションはこれらのジョイント角を計算し、ジョイントのゴールとして MoveIt に渡します。計画は引き続き MoveIt が行い、ジョイントの制限を守った、衝突のないなめらかな軌道を作ります(ミッションは最初に、MoveIt のプランニングシーンに床を追加します)。把持では、end_effector_link を床から 10 cm の高さに置き、次に 3 cm まで下げ(このとき指先は床から約 1 cm 上にあります)、グリッパーを閉じて、15 cm まで持ち上げます。

バナナの上へ、下げて閉じる、持ち上げる。曲がったバナナを 2 本の指でつまむと、そこが蝶番のように働くので、アームが動くとバナナが揺れることがあります(動画を見てください)。それでも、バナナはしっかり保持されています。
top_down_ik()
# The arm in the base_footprint frame (from the URDF): joint1 turns about a vertical axis at x = -0.024;
# joint2, joint3 and joint5 tilt the arm forward; joint4 and joint6 roll. Looking straight down, the arm is
# a planar 2-link arm (upper arm L1, forearm L2) plus L3 from the wrist to end_effector_link (the fingertips
# reach 2 cm further down).
SHOULDER_X, SHOULDER_Z = -0.024, 0.2065
L1, L2, L3 = 0.124, 0.1045, 0.1625
def top_down_ik(x, y, z, object_yaw):
"""Joint angles that put end_effector_link at (x, y, z) [base_footprint frame], pointing straight down,
with the fingers closing across an object whose long axis points along object_yaw. None = out of reach."""
j1 = math.atan2(y, x - SHOULDER_X)
r = math.hypot(x - SHOULDER_X, y) # horizontal distance from joint1's axis
dz = z + L3 - SHOULDER_Z # the wrist is L3 above end_effector_link
c3 = (r * r + dz * dz - L1 * L1 - L2 * L2) / (2 * L1 * L2) # law of cosines
if abs(c3) > 1.0:
return None
j3 = math.acos(c3) # elbow up
j2 = math.atan2(r, dz) - math.atan2(L2 * math.sin(j3), L1 + L2 * math.cos(j3))
j5 = math.pi - j2 - j3 # the three tilts add up to 180 deg: pointing down
j6 = (j1 - object_yaw + math.pi / 2) % math.pi - math.pi / 2 # fingers across the object (either way round)
joints = [j1, j2, j3, 0.0, j5, j6]
limits = [(-2.82, 2.82), (-1.69, 1.76), (-1.75, 1.85), (-1.57, 1.57), (-1.66, 1.78), (-2.82, 2.82)]
return joints if all(lo <= j <= hi for j, (lo, hi) in zip(joints, limits)) else None
なぜ姿勢のゴールを使わないのか
MoveIt は逆運動学を自分で解くこともできます (kinematics.yaml, KDL)。しかし Lime の MoveIt の設定は position_only_ik: True を使っていて、これはグリッパーの向きを無視するため、「真下を向く」という姿勢のゴールは守られません。真上からの把持なら、上の解析解は正確で、すぐに求まり、確かめるのも簡単です。
5. つかみ続ける¶
グリッパーには完全に閉じた位置 (−1 cm) を指令し、指がバナナに触れたところでグリッパーは止まります。GripperActionController は閉じた位置を指令し続けるので、位置ドライブ(チュートリアル 03:剛性 1000 N/m、最大 10 N)は、アームが持ち上げている間もロボットが走っている間も、バナナを挟み続けます。
コントローラーは、ストール(指の速度がほぼ 0 の状態が 2 秒続くこと)を検出すると、ゴールを完了させるはずです(チュートリアル 12 の ros2_controllers.yaml にある allow_stalling: true)。しかしシミュレーションでは、物体を押している指は、位置が変わらないのに速度(ここでは約 0.3 m/s)を報告するので、ストールが検出されることはありません。そこでミッションは、グリッパーを最大 3 秒だけ待ってから先に進みます。ゴールはアクティブのまま残り、次のグリッパーへの指令(ボウルの上で開く)がそれを置き換えます。
自動チェック¶
python isaac/13_all_together.py --headless --test は、シミュレーションの正解(ground truth)を使ってミッションの進み具合を追跡します。
[13] ground truth: banana at [ 0.8 -0.121], bowl at [1. 0.4]
[13] banana lifted (10 cm above the floor) at t = 47 s
[13] banana in the bowl, 4.9 cm from its centre at t = 71 s
[13] arm folded at t = 73 s
[13] robot parked in the far corner at t = 98 s
[13][check] ok banana picked up (more than 10 cm above the floor)
[13][check] ok banana put into the bowl (within 7 cm of its centre)
[13][check] ok arm folded afterwards
[13][check] ok robot parked in the far corner (within 0.3 m)
[13][check] ok banana still in the bowl at the end (4.9 cm from its centre)
[13][check] ok mug not bumped into (moved 0.0 cm)
[13][check] ok bottle not bumped into (moved 0.0 cm)
[13][test] PASS
バナナはボウルの中心から約 5 cm 手前に落ちます。伸ばしたアームは、その高さではロボットの前方 18 cm までしか届かないからです(joint5 の制限)。ボウルの半径は 12 cm です。
作成中にうまくいかなかったこと(とその対処)¶
11 の問題とその対処
| 症状 | 原因 | 対処 |
|---|---|---|
| 把持が 2 cm ずれ、ロボットの向きが 6° 変わっていた | アームの目標値が 1 ステップで跳び、その衝撃でロボットが回転した | アームは常になめらかに動かす(MoveIt の軌道ならそうなる) |
| 持ち上げたときにバナナが滑り落ちた | デフォルトの摩擦が 0.5 で、しかもバナナを中心から外れた位置で把持していた | ゴムのような摩擦 1.0 にし、点群の中央で把持する |
| 指がバナナを囲むように閉じられなかった | convexHull によって、曲がったバナナが 7 cm の塊になっていた |
convexDecomposition |
| バナナがボウルの縁に乗ってしまった | 19 cm のバナナに 16 cm のボウル | 1.5 倍のボウルにし、バナナをロボットに対して横向きにして放す |
| YOLO:バナナではなく frisbee | 床から 5.8 cm の高さから見た、平たい三日月形 | medium モデルの yolo11m.pt |
| バナナの推定位置が 5 cm 手前にずれた | 端の方向から見ると、奥の半分が手前の半分に隠れる | 横からもう一度見る。長さの中央を使う |
| グリッパーを閉じたあと、ミッションが止まった | 挟んでいる指が速度を報告するので、コントローラーがストールを検出しない | グリッパーは最大 3 s だけ待つ |
| マグカップが勝手に床の上を動いた | 凸包(convex hull)のコライダー(マグカップのメッシュは底が平らなので、原因はモデルではなく凸包) | マグカップに convexDecomposition |
| 駐車に向かう途中で、ロボットがマスタードのボトルを突き抜けた | ボトルにコライダーがなく、しかも Nav2 がボトルのすぐ隣から出発した | マグカップとボトルにコライダーを付け、Nav2 に引き継ぐ前に開けた場所まで走る |
走行後に MoveIt:Start state out of bounds … joint3 |
折りたたみ姿勢 (joint3 = 1.85) が垂れ下がり、ジョイントの制限 (1.8567) に達した |
joint3 = 1.80 で折りたたむ(チュートリアル 03 の初期姿勢と SRDF の値) |
| ときどき、開始直後に「amcl/get_state service not available, waiting...」と出たあと、ミッションが止まった | サービスが現れた直後は、DDS がまだ両側をマッチングしていないことがあり、最初のリクエストが失われる。すると BasicNavigator.waitUntilNav2Active() は応答をいつまでも待ち続ける |
mission.py の wait_until_nav2_active():同じ処理を、リクエストごとの 2 s のタイムアウトとリトライ付きで行う |
この先へ¶
- ほかの物体:
locate()は、YOLO の 80 クラスのどれにでも使えます。バナナと同じように物体に物理を設定し、その形に合った把持のルールを選んでください。 - 横から把持する: ボトルのような背の高い物体には、水平向きのグリッパーが必要です。条件 \(\theta_2 + \theta_3 + \theta_5 = \pi\) を \(\pi/2\) に変え、手首 \(L_3\) を把持点の上ではなく手前に置きます。
- 自分の検出器を学習させる: Isaac Sim の Replicator を使えば、lime_room のラベル付き画像を何千枚もレンダリングできます。
- 実機: ROS 側は実機の Lime と同じトピック名とフレーム名を使っているので、実機への移行は、おもにシミュレーションを実機のドライバーに置き換えるだけで済みます(
JointStateTopicSystemの代わりに Lime 自身の ros2_control ハードウェアを使い、さらに RealSense と LDS のドライバーを使います)。これは実機の Lime ではテストしていません。
launch ファイル:lime_isaac_bringup/launch/lime_full.launch.py
# SPDX-FileCopyrightText: 2026 An (an-robotics)
# SPDX-License-Identifier: Apache-2.0
"""Tutorial 13: everything at once - MoveIt 2 + ros2_control, Nav2, YOLO and RViz.
ros2 launch lime_isaac_bringup lime_full.launch.py
ros2 run lime_isaac_bringup mission # the pick-and-place mission (YOLO + MoveIt + Nav2)
Only ONE robot_state_publisher runs (the one in lime_isaac_moveit/moveit.launch.py, whose URDF also
contains the ros2_control block). /joint_states comes from joint_state_broadcaster.
"""
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument, GroupAction, IncludeLaunchDescription
from launch.conditions import IfCondition
from launch.substitutions import LaunchConfiguration, PathJoinSubstitution
from launch_ros.actions import Node
from launch_ros.substitutions import FindPackageShare
def generate_launch_description():
pkg = FindPackageShare("lime_isaac_bringup")
return LaunchDescription(
[
DeclareLaunchArgument("rviz", default_value="true"),
DeclareLaunchArgument("params_file", default_value=PathJoinSubstitution([pkg, "config", "nav2_params.yaml"])),
# MoveIt 2 + ros2_control (+ robot_state_publisher). In a scoped group: otherwise its rviz:=false
# would leak out and switch off the RViz below as well.
GroupAction(
[
IncludeLaunchDescription(
PathJoinSubstitution([FindPackageShare("lime_isaac_moveit"), "launch", "moveit.launch.py"]),
launch_arguments={"rviz": "false"}.items(),
)
],
scoped=True,
),
# Nav2 (map_server, AMCL, planner, controller, ...)
IncludeLaunchDescription(
PathJoinSubstitution([FindPackageShare("nav2_bringup"), "launch", "bringup_launch.py"]),
launch_arguments={
"map": PathJoinSubstitution([pkg, "maps", "lime_room.yaml"]),
"params_file": LaunchConfiguration("params_file"),
"use_sim_time": "true",
"autostart": "true",
}.items(),
),
# YOLO - the medium model: from the low camera the nano model (tutorial 10) calls the banana a "frisbee"
DeclareLaunchArgument("yolo_model", default_value="yolo11m.pt"),
IncludeLaunchDescription(
PathJoinSubstitution([FindPackageShare("lime_yolo"), "launch", "yolo.launch.py"]),
launch_arguments={"model": LaunchConfiguration("yolo_model")}.items(),
),
Node(
package="rviz2",
executable="rviz2",
arguments=["-d", PathJoinSubstitution([pkg, "rviz", "navigation.rviz"])],
parameters=[{"use_sim_time": True}],
condition=IfCondition(LaunchConfiguration("rviz")),
output="screen",
),
]
)
Isaac Sim 側:isaac/13_all_together.py
# SPDX-FileCopyrightText: 2026 An (an-robotics)
# SPDX-License-Identifier: Apache-2.0
"""Tutorial 13 - Putting it all together: the complete simulated TurtleBot3 Lime.
source scripts/isaac_env.sh
python isaac/13_all_together.py
# ROS 2 container: MoveIt 2 + ros2_control, Nav2, YOLO, RViz - then the mission
./docker/run_ros.sh ros2 launch lime_isaac_bringup lime_full.launch.py
./docker/run_ros.sh ros2 run lime_isaac_bringup mission
Everything from tutorials 06-12 in one scene:
/clock /cmd_vel /odom /tf /isaac_joint_states /isaac_joint_commands
/camera/camera/... /scan /imu
New here: the objects are real (rigid bodies, colliders, masses): the gripper can pick up the banana, the bowl
holds it, and the mug and the bottle would be knocked over (common/scene.py: setup_pick_and_place).
"""
import sys
from common.cli import parse_args
args = parse_args(__doc__.splitlines()[0])
from isaacsim import SimulationApp
simulation_app = SimulationApp({"headless": args.headless, "width": 1280, "height": 720})
import isaacsim.core.experimental.utils.app as app_utils
import isaacsim.core.experimental.utils.stage as stage_utils
import numpy as np
from common import graphs, lime, sensors
from common.scene import OBJECTS, build_lime_room, setup_pick_and_place
from isaacsim.core.experimental.prims import Articulation, XformPrim
from isaacsim.core.simulation_manager import SimulationManager
graphs.enable_ros2_realtime(simulation_app)
stage = stage_utils.create_new_stage(template="empty")
build_lime_room(stage, object_physics=True) # real objects: colliders and mass, so they can be picked up
while stage_utils.is_stage_loading():
simulation_app.update()
robot_path = "/World/turtlebot3_lime"
articulation_root = lime.add_lime(robot_path)
setup_pick_and_place(stage, robot_path) # a bigger bowl, grippy fingers
graphs.create_clock_graph() # 06
graphs.create_drive_graph(articulation_root) # 06 /cmd_vel <- Nav2
graphs.create_odom_tf_joint_states_graph(articulation_root, joint_states_topic="/isaac_joint_states") # 07 + 12
graphs.create_joint_command_graph(articulation_root) # 12 /isaac_joint_commands <- ros2_control <- MoveIt
graphs.create_camera_graph(sensors.add_d435_camera(robot_path)) # 08 camera -> YOLO
graphs.create_lidar_graph(sensors.add_lds_lidar(robot_path)) # 09 /scan -> Nav2
graphs.create_imu_graph(sensors.add_imu(robot_path)) # 09 /imu
recorder = None
if args.record:
from common.recorder import Recorder
CLOSE_UP = ((1.75, -1.05, 0.85), (0.85, 0.12, 0.05)) # pick and place
OVERVIEW = ((0.9, -4.4, 3.6), (1.0, -0.4, 0.0)) # parking
recorder = Recorder(args.record, eye=CLOSE_UP[0], target=CLOSE_UP[1], every_n=8, fps=24)
SimulationManager.setup_simulation(dt=1.0 / 60.0)
app_utils.play()
simulation_app.update()
robot = Articulation(articulation_root)
arm = robot.get_dof_indices(lime.ARM_JOINTS)
print("[13] ready: ros2 launch lime_isaac_bringup lime_full.launch.py, then ros2 run lime_isaac_bringup mission", flush=True)
# --test: follow the mission from the simulation's point of view (ground truth)
banana = XformPrim("/World/LimeRoom/Objects/Banana")
others = {name: XformPrim(f"/World/LimeRoom/Objects/{name}") for name in ("Mug", "Bottle")} # must not be touched
start = {} # where they rest after settling (recorded 1 s into the simulation)
BOWL = np.array(next(o for o in OBJECTS if o[0] == "Bowl")[2:4])
CORNER = np.array([2.8, -1.8])
events, steps, still_since, view_blend, still_frame = {}, 0, None, 0.0, -1
if args.test or args.record:
print(f"[13] ground truth: banana at {np.round(banana.get_world_poses()[0].numpy()[0, :2], 3)}, bowl at {BOWL}", flush=True)
def event(name, text):
events[name] = steps / 60
print(f"[13] {text} at t = {events[name]:.0f} s", flush=True)
while simulation_app.is_running():
simulation_app.update()
steps += 1
if recorder:
if "folded" in events and view_blend < 1.0: # glide from the close-up to the overview for the parking
view_blend = min(1.0, view_blend + 1 / 180)
a = 0.5 - 0.5 * np.cos(np.pi * view_blend)
recorder.look_at(*[(1 - a) * np.array(c) + a * np.array(o) for c, o in zip(CLOSE_UP, OVERVIEW)])
recorder.capture()
if args.test or args.record:
if steps == 60:
start = {name: prim.get_world_poses()[0].numpy()[0].copy() for name, prim in others.items()}
xy = robot.get_world_poses()[0].numpy()[0, :2]
q = robot.get_dof_positions(dof_indices=arm).numpy()[0]
for name, prim in others.items(): # report the moment the robot bumps into the mug or the bottle
if start and f"bumped {name}" not in events and np.linalg.norm(prim.get_world_poses()[0].numpy()[0] - start[name]) > 0.005:
event(f"bumped {name}", f"{name.lower()} bumped (robot at {np.round(xy, 2)})")
b = banana.get_world_poses()[0].numpy()[0]
if "lifted" not in events and b[2] > 0.10:
event("lifted", f"banana lifted ({b[2] * 100:.0f} cm above the floor)")
in_bowl = np.linalg.norm(b[:2] - BOWL) < 0.07 and b[2] < 0.10
still_since = (still_since or steps) if in_bowl else None
if "lifted" in events and "in_bowl" not in events and still_since and steps - still_since > 60:
event("in_bowl", f"banana in the bowl, {np.linalg.norm(b[:2] - BOWL) * 100:.1f} cm from its centre")
if "in_bowl" in events and "folded" not in events and np.max(np.abs(q - np.array(lime.ARM_HOME))) < 0.05:
event("folded", "arm folded")
still_frame = len(recorder.frames) - 1 if recorder else -1 # the picture for the docs: banana in the bowl
if "folded" in events and "parked" not in events and np.linalg.norm(xy - CORNER) < 0.3:
event("parked", "robot parked in the far corner")
if ("parked" in events and steps / 60 > events["parked"] + 5) or steps > 500 * 60:
break # (5 s more, so the mission can finish cleanly)
ok = True
if args.test:
b = banana.get_world_poses()[0].numpy()[0]
checks = {
"banana picked up (more than 10 cm above the floor)": "lifted" in events,
"banana put into the bowl (within 7 cm of its centre)": "in_bowl" in events,
"arm folded afterwards": "folded" in events,
"robot parked in the far corner (within 0.3 m)": "parked" in events,
f"banana still in the bowl at the end ({np.linalg.norm(b[:2] - BOWL) * 100:.1f} cm from its centre)": np.linalg.norm(b[:2] - BOWL) < 0.07,
}
for name, prim in others.items():
moved = np.linalg.norm(prim.get_world_poses()[0].numpy()[0] - start[name])
checks[f"{name.lower()} not bumped into (moved {moved * 100:.1f} cm)"] = moved < 0.01
for text, passed in checks.items():
print(f"[13][check] {'ok ' if passed else 'FAIL'} {text}")
ok = all(checks.values())
print(f"[13][test] {'PASS' if ok else 'FAIL'}")
if recorder:
recorder.save(still_index=still_frame)
app_utils.stop()
simulation_app.close(exit_code=0 if ok else 1)
sys.exit(0 if ok else 1)
ミッション全体:lime_isaac_bringup/scripts/mission.py
#!/usr/bin/env python3
# SPDX-FileCopyrightText: 2026 An (an-robotics)
# SPDX-License-Identifier: Apache-2.0
"""Tutorial 13 mission: tidy up the lime_room - put the banana into the bowl, then park.
ros2 run lime_isaac_bringup mission
1. YOLO + depth find the banana: a 2D box + the depth image + TF -> a 3D position and direction
2. drive drive up to it, centimetre-accurate, with odometry
3. MoveIt pick it up: top-down grasp, fingers across the banana
4. YOLO + depth find the bowl, drive up to it
5. MoveIt put the banana into the bowl, fold the arm
6. Nav2 park in the far corner of the room
"""
import math
import sys
import threading
import time
import numpy as np
import rclpy
import tf2_ros
from control_msgs.action import GripperCommand
from geometry_msgs.msg import Pose, PoseStamped, Twist
from moveit_msgs.action import MoveGroup
from moveit_msgs.msg import CollisionObject, Constraints, JointConstraint, MoveItErrorCodes, PlanningScene
from moveit_msgs.srv import ApplyPlanningScene
from nav2_simple_commander.robot_navigator import BasicNavigator, TaskResult
from rclpy.action import ActionClient
from rclpy.executors import SingleThreadedExecutor
from rclpy.parameter import Parameter
from sensor_msgs.msg import CameraInfo, Image
from shape_msgs.msg import SolidPrimitive
from vision_msgs.msg import Detection2DArray
ARM_JOINTS = [f"joint{i}" for i in range(1, 7)]
HOME = [0.0, -1.10, 1.80, 0.0, 0.98, 0.0] # folded (the SRDF "home" pose)
CARRY = [0.0, -0.3, 1.2, 0.0, 1.0, 0.0] # banana held high above the robot, out of the camera's view
GRIPPER_OPEN, GRIPPER_CLOSED = 0.019, -0.010
CAMERA = "/camera/camera"
PARK = (2.8, -1.8, 0.0)
def wrap(a):
return (a + math.pi) % (2 * math.pi) - math.pi
# The arm in the base_footprint frame (from the URDF): joint1 turns about a vertical axis at x = -0.024;
# joint2, joint3 and joint5 tilt the arm forward; joint4 and joint6 roll. Looking straight down, the arm is
# a planar 2-link arm (upper arm L1, forearm L2) plus L3 from the wrist to end_effector_link (the fingertips
# reach 2 cm further down).
SHOULDER_X, SHOULDER_Z = -0.024, 0.2065
L1, L2, L3 = 0.124, 0.1045, 0.1625
def top_down_ik(x, y, z, object_yaw):
"""Joint angles that put end_effector_link at (x, y, z) [base_footprint frame], pointing straight down,
with the fingers closing across an object whose long axis points along object_yaw. None = out of reach."""
j1 = math.atan2(y, x - SHOULDER_X)
r = math.hypot(x - SHOULDER_X, y) # horizontal distance from joint1's axis
dz = z + L3 - SHOULDER_Z # the wrist is L3 above end_effector_link
c3 = (r * r + dz * dz - L1 * L1 - L2 * L2) / (2 * L1 * L2) # law of cosines
if abs(c3) > 1.0:
return None
j3 = math.acos(c3) # elbow up
j2 = math.atan2(r, dz) - math.atan2(L2 * math.sin(j3), L1 + L2 * math.cos(j3))
j5 = math.pi - j2 - j3 # the three tilts add up to 180 deg: pointing down
j6 = (j1 - object_yaw + math.pi / 2) % math.pi - math.pi / 2 # fingers across the object (either way round)
joints = [j1, j2, j3, 0.0, j5, j6]
limits = [(-2.82, 2.82), (-1.69, 1.76), (-1.75, 1.85), (-1.57, 1.57), (-1.66, 1.78), (-2.82, 2.82)]
return joints if all(lo <= j <= hi for j, (lo, hi) in zip(joints, limits)) else None
class Lime:
"""Everything the mission needs: perception, the base, the arm. Nav2 is the BasicNavigator node."""
def __init__(self):
self.nav = BasicNavigator("lime_mission")
self.nav.set_parameters([Parameter("use_sim_time", Parameter.Type.BOOL, True)])
self.log = self.nav.get_logger()
# TF on its own node + thread, so lookups work while the main node waits for actions
self.tf_node = rclpy.create_node("lime_mission_tf", parameter_overrides=[Parameter("use_sim_time", Parameter.Type.BOOL, True)])
self.tf = tf2_ros.Buffer()
tf2_ros.TransformListener(self.tf, self.tf_node)
self.executor = SingleThreadedExecutor()
self.executor.add_node(self.tf_node)
self.tf_thread = threading.Thread(target=self.executor.spin, daemon=True)
self.tf_thread.start()
n = self.nav
self.detections, self.depth, self.K = [], {}, None
n.create_subscription(Detection2DArray, "/detections", self.on_detections, 10)
n.create_subscription(Image, f"{CAMERA}/aligned_depth_to_color/image_raw", self.on_depth, 5)
n.create_subscription(CameraInfo, f"{CAMERA}/color/camera_info", lambda m: setattr(self, "K", np.array(m.k).reshape(3, 3)), 1)
self.cmd = n.create_publisher(Twist, "/cmd_vel", 10)
self.arm = ActionClient(n, MoveGroup, "/move_action")
self.grip = ActionClient(n, GripperCommand, "/gripper_controller/gripper_cmd")
self.scene = n.create_client(ApplyPlanningScene, "/apply_planning_scene")
def close(self):
"""Stop the TF thread and the nodes before exiting (otherwise Python aborts at exit)."""
self.send(0.0, 0.0)
self.executor.shutdown()
self.tf_thread.join(timeout=2.0)
self.tf_node.destroy_node()
self.nav.destroy_node()
rclpy.try_shutdown()
def on_depth(self, msg):
self.depth[(msg.header.stamp.sec, msg.header.stamp.nanosec)] = msg
while len(self.depth) > 60:
self.depth.pop(next(iter(self.depth)))
def on_detections(self, msg):
"""Keep each detection together with the depth image taken at the same moment (same time stamp)."""
depth = self.depth.get((msg.header.stamp.sec, msg.header.stamp.nanosec))
if depth is not None:
self.detections.append((msg, depth))
del self.detections[:-60] # the last 60 only (each holds a depth image)
def spin_for(self, seconds):
end = time.time() + seconds
while time.time() < end:
rclpy.spin_once(self.nav, timeout_sec=0.05)
def wait(self, future):
rclpy.spin_until_future_complete(self.nav, future)
return future.result()
def locate(self, name, seconds=4.0):
"""Find object `name` with YOLO and measure where it is: a 3D point cloud of the object, in the odom frame.
2D box (YOLO) + depth image + camera model -> 3D points in the camera frame
+ TF odom <- camera at the image's time stamp -> 3D points in the odom frame
"""
self.detections.clear()
self.spin_for(seconds) # collect a few seconds of detections, keep the most confident one
best = None
for msg, depth_msg in self.detections:
for d in msg.detections:
h = d.results[0].hypothesis
if h.class_id == name and (best is None or h.score > best[0]):
best = (h.score, d, msg.header, depth_msg)
if best is None or self.K is None:
return None
score, det, header, depth_msg = best
pts, camera = self.points(det, header, depth_msg)
return None if pts is None else {"score": score, "points": pts, "camera": camera}
def points(self, det, header, depth_msg):
"""The 3D points (odom frame) of one detection's box, and where the camera was. (None, None) if too few."""
depth = np.frombuffer(depth_msg.data, dtype=np.float32).reshape(depth_msg.height, depth_msg.width)
cx, cy = det.bbox.center.position.x, det.bbox.center.position.y
w, h = det.bbox.size_x, det.bbox.size_y
u0, u1 = int(max(cx - w / 2, 0)), int(min(cx + w / 2, depth_msg.width - 1))
v0, v1 = int(max(cy - h / 2, 0)), int(min(cy + h / 2, depth_msg.height - 1))
v, u = np.mgrid[v0:v1 + 1, u0:u1 + 1]
z = depth[v0:v1 + 1, u0:u1 + 1]
ok = np.isfinite(z) & (z > 0.05) & (z < 3.0)
fx, fy, px, py = self.K[0, 0], self.K[1, 1], self.K[0, 2], self.K[1, 2]
cam = np.stack([(u[ok] - px) * z[ok] / fx, (v[ok] - py) * z[ok] / fy, z[ok]], axis=1) # optical frame
tf = self.tf.lookup_transform("odom", header.frame_id, header.stamp, timeout=rclpy.duration.Duration(seconds=1.0))
t, q = tf.transform.translation, tf.transform.rotation
R = quat_to_matrix(q.x, q.y, q.z, q.w)
pts = cam @ R.T + np.array([t.x, t.y, t.z])
pts = pts[(pts[:, 2] > 0.006) & (pts[:, 2] < 0.40)] # drop the floor (z = 0) around the object
if len(pts) < 20:
return None, None
middle = np.median(pts[:, :2], axis=0)
pts = pts[np.linalg.norm(pts[:, :2] - middle, axis=1) < 0.25] # drop the background inside the box
return pts, np.array([t.x, t.y])
def pose(self):
"""Robot pose (x, y, yaw) in the odom frame - Isaac Sim's odometry, through TF."""
tf = self.tf.lookup_transform("odom", "base_footprint", rclpy.time.Time(), timeout=rclpy.duration.Duration(seconds=1.0))
t, q = tf.transform.translation, tf.transform.rotation
return t.x, t.y, math.atan2(2 * (q.w * q.z + q.x * q.y), 1 - 2 * (q.y * q.y + q.z * q.z))
def send(self, v, w):
msg = Twist()
msg.linear.x, msg.angular.z = float(v), float(w)
self.cmd.publish(msg)
def turn_to(self, yaw):
w, end = 0.0, time.time() + 30.0
while time.time() < end:
error = wrap(yaw - self.pose()[2])
if abs(error) < 0.01:
break
target = math.copysign(min(0.5, max(0.08, 1.5 * abs(error))), error)
w += max(-0.03, min(0.03, target - w)) # gentle acceleration: the robot carries things
self.send(0.0, w)
time.sleep(0.05)
self.send(0.0, 0.0)
time.sleep(0.5)
def drive_to(self, x, y, backwards=False):
"""Turn towards (x, y) [odom frame], drive there in a straight line, stop within a centimetre."""
px, py, _ = self.pose()
heading = math.atan2(y - py, x - px) + (math.pi if backwards else 0.0)
self.turn_to(heading)
v, sign, end = 0.0, -1.0 if backwards else 1.0, time.time() + 60.0
while time.time() < end:
px, py, yaw = self.pose()
ahead = (x - px) * math.cos(yaw) + (y - py) * math.sin(yaw) # distance left along the heading
if sign * ahead < 0.008:
break
target = min(0.12, max(0.02, 0.8 * abs(ahead)))
v += max(-0.01, min(0.01, target - v))
side = -(x - px) * math.sin(yaw) + (y - py) * math.cos(yaw)
self.send(sign * v, max(-0.3, min(0.3, 2.0 * side * sign)) if abs(ahead) > 0.05 else 0.0)
time.sleep(0.05)
self.send(0.0, 0.0)
time.sleep(0.5)
def to_base(self, x, y):
"""odom-frame point -> base_footprint frame (where the arm works)."""
px, py, yaw = self.pose()
dx, dy = x - px, y - py
return dx * math.cos(yaw) + dy * math.sin(yaw), -dx * math.sin(yaw) + dy * math.cos(yaw)
# --- the arm (MoveIt 2) and the gripper (ros2_control) ---
def move_arm(self, joints, what):
goal = MoveGroup.Goal()
goal.request.group_name = "arm"
goal.request.num_planning_attempts = 5
goal.request.allowed_planning_time = 5.0
goal.request.max_velocity_scaling_factor = 0.3
goal.request.max_acceleration_scaling_factor = 0.3
goal.request.goal_constraints = [
Constraints(
joint_constraints=[
JointConstraint(joint_name=n, position=p, tolerance_above=0.01, tolerance_below=0.01, weight=1.0)
for n, p in zip(ARM_JOINTS, joints)
]
)
]
handle = self.wait(self.arm.send_goal_async(goal))
ok = handle.accepted and self.wait(handle.get_result_async()).result.error_code.val == MoveItErrorCodes.SUCCESS
self.log.info(f"MoveIt: {what}: {'done' if ok else 'FAILED'}")
return ok
def gripper(self, position, seconds=3.0):
"""Open / close the gripper. Closing on the banana, the fingers stop at the banana. The controller would
call that a "stall" once the finger velocity is ~0, but in simulation the squeezing finger reports a
velocity (about 0.3 m/s) although it does not move, so the goal never finishes. Wait at most `seconds`:
the goal stays active, and the controller keeps commanding the closed position, so the fingers keep
squeezing."""
goal = GripperCommand.Goal()
goal.command.position, goal.command.max_effort = position, 10.0
handle = self.wait(self.grip.send_goal_async(goal))
result = handle.get_result_async()
rclpy.spin_until_future_complete(self.nav, result, timeout_sec=seconds)
return handle.accepted
def add_floor(self):
"""Tell MoveIt about the floor, so no planned arm motion goes through it."""
floor = CollisionObject(id="floor", operation=CollisionObject.ADD)
floor.header.frame_id = "base_footprint"
floor.primitives = [SolidPrimitive(type=SolidPrimitive.BOX, dimensions=[3.0, 3.0, 0.02])]
floor.primitive_poses = [Pose()]
floor.primitive_poses[0].position.z = -0.02 # top at -1 cm: below the wheels, above nothing else
floor.primitive_poses[0].orientation.w = 1.0
request = ApplyPlanningScene.Request(scene=PlanningScene(is_diff=True))
request.scene.world.collision_objects = [floor]
self.scene.wait_for_service(timeout_sec=30.0)
return self.wait(self.scene.call_async(request)).success
def wait_until_nav2_active(nav):
"""BasicNavigator.waitUntilNav2Active(), but with a timeout on every service call, and retries.
Right after a service appears, DDS may not have finished matching both sides, and the first request can get
lost. The original then waits for its answer forever (it happened twice in about 25 runs)."""
from lifecycle_msgs.srv import GetState
for node in ("amcl", "bt_navigator"):
client = nav.create_client(GetState, f"{node}/get_state")
while True:
if not client.wait_for_service(timeout_sec=1.0):
nav.info(f"{node}/get_state service not available, waiting...")
continue
future = client.call_async(GetState.Request())
rclpy.spin_until_future_complete(nav, future, timeout_sec=2.0)
if future.done() and future.result() is not None and future.result().current_state.label == "active":
break
time.sleep(1.0) # not active yet, or the answer got lost: ask again
nav.destroy_client(client)
if node == "amcl":
nav._waitForInitialPose() # BasicNavigator's own: (re)publish the initial pose until AMCL has it
nav.info("Nav2 is ready for use!")
def quat_to_matrix(x, y, z, w):
return np.array(
[
[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
[2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
[2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)],
]
)
def long_object(found):
"""A lying object (the banana): its direction = the main axis of its points (PCA); the grasp point = the
middle of its length. Not simply the average point: the end nearer the camera gets more depth pixels."""
xy = found["points"][:, :2]
mean = xy.mean(axis=0)
eigenvalues, eigenvectors = np.linalg.eigh(np.cov((xy - mean).T))
axis = eigenvectors[:, np.argmax(eigenvalues)]
normal = np.array([-axis[1], axis[0]])
along, across = (xy - mean) @ axis, (xy - mean) @ normal
middle = (np.percentile(along, 2) + np.percentile(along, 98)) / 2 # halfway between the two ends
at_middle = np.abs(along - middle) < 0.02 # the slice of the object there (a banana is curved)
centre = mean + middle * axis + np.median(across[at_middle]) * normal
return centre, math.atan2(axis[1], axis[0])
def round_object(found):
"""A round object (the bowl): the camera sees only its front, so centre = front surface + one radius
further along the line of sight; the radius is half the width the camera sees."""
xy = found["points"][:, :2]
ray = np.median(xy, axis=0) - found["camera"]
ray /= np.linalg.norm(ray)
side = np.array([-ray[1], ray[0]])
along, across = (xy - found["camera"]) @ ray, (xy - found["camera"]) @ side
radius = (np.percentile(across, 98) - np.percentile(across, 2)) / 2
front = np.percentile(along, 5)
middle = (np.percentile(across, 98) + np.percentile(across, 2)) / 2
return found["camera"] + (front + radius) * ray + middle * side, radius
def main():
rclpy.init()
lime = Lime()
log = lime.log
def fail(text):
log.error(text)
lime.close()
sys.exit(1)
p = PoseStamped()
p.header.frame_id = "map"
p.header.stamp = lime.nav.get_clock().now().to_msg()
p.pose.orientation.w = 1.0
lime.nav.setInitialPose(p) # the robot starts at the map origin
wait_until_nav2_active(lime.nav)
if not (lime.arm.wait_for_server(timeout_sec=60.0) and lime.grip.wait_for_server(timeout_sec=60.0)):
fail("MoveIt / gripper action servers not available")
lime.add_floor()
lime.spin_for(1.0)
# 1. Find the banana and the bowl from where we are (the banana is small and far: collect a few seconds).
found, found_bowl = lime.locate("banana", seconds=6.0), lime.locate("bowl", seconds=2.0)
if found is None or found_bowl is None:
fail("YOLO: I need to see both the banana and the bowl")
banana, _ = long_object(found)
bowl, _ = round_object(found_bowl)
log.info(f"YOLO: banana ({found['score']:.2f}) at ({banana[0]:.2f}, {banana[1]:.2f}), bowl ({found_bowl['score']:.2f}) at ({bowl[0]:.2f}, {bowl[1]:.2f})")
# 2. From here we see the banana almost end-on: its far half hides behind its near half. Look again from
# 45 cm away and 55 deg further round (the side away from the mug): now the whole banana is visible.
x, y, _ = lime.pose()
look = math.atan2(banana[1] - y, banana[0] - x) + math.radians(55)
toward = np.array([math.cos(look), math.sin(look)])
lime.drive_to(*(banana - 0.45 * toward))
lime.turn_to(look)
found = lime.locate("banana")
if found is None:
fail("YOLO: lost the banana")
banana, banana_yaw = long_object(found)
log.info(f"YOLO: banana ({found['score']:.2f}) at ({banana[0]:.3f}, {banana[1]:.3f}), pointing {math.degrees(banana_yaw) % 180:.0f} deg")
# 3. Stop with the banana 16 cm in front of the robot: inside the arm's reach for a top-down grasp.
lime.drive_to(*(banana - 0.16 * toward))
lime.turn_to(look)
# 4. Pick it up.
lime.gripper(GRIPPER_OPEN)
bx, by = lime.to_base(*banana)
yaw = wrap(banana_yaw - lime.pose()[2]) # the banana's direction as seen from the robot
above, grasp, lifted = (top_down_ik(bx, by, z, yaw) for z in (0.10, 0.03, 0.15))
if None in (above, grasp, lifted):
fail(f"the banana at ({bx:.3f}, {by:.3f}) in the robot frame is out of reach")
if not (lime.move_arm(above, "above the banana") and lime.move_arm(grasp, "down to the banana")):
fail("MoveIt: grasp failed")
lime.gripper(GRIPPER_CLOSED) # stops when the fingers touch the banana, and keeps squeezing
if not (lime.move_arm(lifted, "lift") and lime.move_arm(CARRY, "carry")):
fail("MoveIt: lift failed")
# 5. Back to the bowl. The mug stands between the banana and the bowl, so go round: approach the bowl
# from its open side (from -y, 42 cm away), look again, and drive up until the bowl is 20 cm in front.
lime.drive_to(bowl[0], bowl[1] - 0.42)
lime.turn_to(math.pi / 2)
found = lime.locate("bowl")
if found is None:
fail("YOLO: lost the bowl")
bowl, radius = round_object(found)
log.info(f"YOLO: bowl ({found['score']:.2f}) at ({bowl[0]:.3f}, {bowl[1]:.3f}), radius {radius * 100:.0f} cm")
lime.drive_to(bowl[0], bowl[1] - 0.20)
lime.turn_to(math.pi / 2)
# 6. Put the banana in: above the bowl's centre, or as close to it as the arm reaches; banana across the robot.
bx, by = lime.to_base(*bowl)
release = next((q for x in np.arange(bx, 0.10, -0.005) if (q := top_down_ik(x, by, 0.13, math.pi / 2))), None)
if release is None or not lime.move_arm(release, "above the bowl"):
fail("MoveIt: could not reach the bowl")
lime.gripper(GRIPPER_OPEN)
lime.spin_for(1.0)
lime.move_arm(HOME, "arm folded")
# 7. Back away from the bowl and drive into the open middle of the room, then let Nav2 park the robot.
# (Started right next to the bottle, Nav2 would steer the robot straight through it.)
x, y, yaw = lime.pose()
lime.drive_to(x - 0.12 * math.cos(yaw), y - 0.12 * math.sin(yaw), backwards=True)
lime.drive_to(bowl[0] + 0.6, bowl[1] - 0.45)
log.info(f"Nav2: parking at ({PARK[0]}, {PARK[1]})")
goal = PoseStamped()
goal.header.frame_id = "map"
goal.pose.position.x, goal.pose.position.y = PARK[0], PARK[1]
goal.pose.orientation.w = 1.0
lime.nav.goToPose(goal)
while not lime.nav.isTaskComplete():
time.sleep(0.2)
if lime.nav.getResult() != TaskResult.SUCCEEDED:
fail(f"Nav2: could not park: {lime.nav.getResult()}")
log.info("mission complete: the banana is in the bowl")
lime.close()
if __name__ == "__main__":
main()
次へ: 14 · SLAM で自分の地図を作る。チュートリアル 16 はこのチュートリアルの続きです。ロボットはまず 3 本のバナナを探し出さなければならず、全体がビヘイビアツリーで動きます。