16 · 総仕上げ:部屋を片付ける¶
目標: チュートリアル 06〜15 のすべてを一度に使って、Lime に本物の仕事をさせます。lime_room のあちこちに 3 本のバナナが置かれていますが、ロボットはその場所を知りません。ロボットはすべてのバナナを見つけて拾い上げ、フルーツボウルに入れて、ホームに戻る必要があります。Nav2 が見回り地点から見回り地点へロボットを走らせ、深度カメラが床の上の物を見つけ、YOLO がそれが何かを判定し、MoveIt がピック&プレースを行い、ビヘイビアツリー(チュートリアル 15)が次に何をするかを決めます。

最後のフルーツボウル:3 本のバナナがすべて入っています。
仕事の内容¶
チュートリアル 13 では、スタート地点のロボットから見えるバナナを 1 本拾いました。このチュートリアルでは次のようになります。
| チュートリアル 13 | チュートリアル 16 | |
|---|---|---|
| バナナ | 1 本、ロボットの前 | 3 本:1 本は前、1 本は柱の陰、1 本は仕切りの陰 |
| 置き場所 | スタート時点で YOLO に見えている | 不明:ロボットが探す必要がある |
| マグカップとボトル | バナナのすぐ隣にあり、邪魔になる | 邪魔にならないよう隅のほうに置く:見つけて、チェックして、そのままにしておく物 |
| 走行 | オドメトリ。Nav2 は駐車のときだけ | すべての場所の間は Nav2、センチメートル単位の移動はオドメトリ |
| ミッション | スクリプト:ステップ 1、ステップ 2、... | ビヘイビアツリー:探す、チェックする、やり直す、そのままにする |
ロボットが知っているのは、地図(チュートリアル 11)と 3 つの見回り地点です。見回り地点とは、部屋の大部分を見渡せる場所です。
考え方¶
物を見つける:地図にないもの¶
「バナナはどこ?」に答えるなら、YOLO を使うのが当然に思えます。しかし、床から 5.8 cm の高さにある Lime のカメラから見ると、横たわったバナナは細い黄色の線にすぎません。1 本のバナナをさまざまな距離と角度から見たときに、YOLO (yolo11m.pt) が出す答えは次のとおりです。
| 距離 | 端から(end-on) | 30° | 60° | 真横から(side-on) |
|---|---|---|---|---|
| 0.5 m | banana 0.89 | banana 0.93 | banana 0.92 | banana 0.90 |
| 0.75 m | sports ball 0.68 | banana 0.85 | frisbee 0.48 | frisbee 0.83 |
| 1.0 m | sports ball 0.75 | tennis racket 0.47 | tennis racket 0.26 | frisbee 0.36 |
| 1.5 m | sports ball 0.69 | sports ball 0.25 | frisbee 0.27 | frisbee 0.33 |
| 2.0 m | sports ball 0.62 | — | frisbee 0.34 | frisbee 0.50 |
そこで、探索には代わりに深度カメラを使い、YOLO は近くからだけ使います。
- 見つける(見回り地点から):深度画像の各ピクセルを 3D の点にします(チュートリアル 13 のカメラモデルと TF)。床を取り除き、地図にすでにあるもの、つまり壁、柱、箱、仕切りもすべて取り除きます。残ったものは新しいもの、つまり床の上の物です。隣り合う点をまとめて、それぞれ 1 つの物にします。
- チェックする(近くから):Nav2 がそれぞれの物から 55 cm の位置までロボットを走らせ、YOLO がそれが何かを判定します。
- 行動する:バナナならボウルに入れます。それ以外はその場に残します。
ここでもチュートリアル 11 のルールが当てはまります。地図には動かないものを載せる。地図にないものは、障害物か仕事のどちらかです。
Nav2 は LiDAR より低いものも見る¶
チュートリアル 11 では、Nav2 のコストマップは障害物を LiDAR から得ていました。LiDAR は床から 16 cm の高さをスキャンします。バナナ (4 cm)、マグカップ (8 cm)、ボウル (8 cm) は LiDAR には見えないので、Nav2 はその上をそのまま走ってしまいます。実際のロボットは深度カメラもコストマップに加えます。このチュートリアルでも同じようにします。
- Isaac Sim は、深度カメラから小さな点群をパブリッシュします。同じカメラの 2 つ目のレンダープロダクト(render product)で、160 × 120 ピクセル、毎秒 10 回です(
create_depth_cloud_graph、graphs.pyに新しく追加)。 - Nav2 (
config/nav2_params_tidy.yaml) では、両方のコストマップにレイヤーdepth_layerを 1 つ追加します。
isaac/common/graphs.py の create_depth_cloud_graph()
def create_depth_cloud_graph(
camera_path: str,
width: int = 160,
height: int = 120,
every_nth_frame: int = 6,
graph_path: str = "/World/ROS2_DepthCloud",
topic: str = "/camera/camera/depth/color/points", # realsense2_camera's topic name
frame_id: str = "camera_color_optical_frame",
):
"""Tutorial 16: the depth camera as a point cloud (sensor_msgs/PointCloud2), for Nav2's costmaps.
A second, small render product of the same camera (160 x 120 = 19,200 points instead of 307,200),
published on every 6th frame (10 Hz): plenty for a costmap with 5 cm cells, light for DDS.
"""
import usdrt.Sdf
og = _og()
keys = og.Controller.Keys
og.Controller.edit(
{"graph_path": graph_path, "evaluator_name": "execution"},
{
keys.CREATE_NODES: [
("OnPlaybackTick", "omni.graph.action.OnPlaybackTick"),
("RenderProduct", "isaacsim.core.nodes.IsaacCreateRenderProduct"),
("PublishCloud", "isaacsim.ros2.bridge.ROS2CameraHelper"),
],
keys.SET_VALUES: [
("RenderProduct.inputs:cameraPrim", [usdrt.Sdf.Path(camera_path)]),
("RenderProduct.inputs:width", width),
("RenderProduct.inputs:height", height),
("PublishCloud.inputs:type", "depth_pcl"),
("PublishCloud.inputs:topicName", topic),
("PublishCloud.inputs:frameId", frame_id),
("PublishCloud.inputs:frameSkipCount", every_nth_frame - 1),
],
keys.CONNECT: [
("OnPlaybackTick.outputs:tick", "RenderProduct.inputs:execIn"),
("RenderProduct.outputs:execOut", "PublishCloud.inputs:execIn"),
("RenderProduct.outputs:renderProductPath", "PublishCloud.inputs:renderProductPath"),
],
},
)
depth_layer:
plugin: nav2_costmap_2d::VoxelLayer
enabled: true
publish_voxel_map: false
origin_z: 0.0
z_resolution: 0.05
z_voxels: 10
max_obstacle_height: 0.5
mark_threshold: 0
observation_sources: depth
depth: {topic: /camera/camera/depth/color/points, data_type: PointCloud2, marking: true, clearing: true,
min_obstacle_height: 0.015, max_obstacle_height: 0.5, obstacle_min_range: 0.35, obstacle_max_range: 2.5,
raytrace_min_range: 0.35, raytrace_max_range: 2.5}
| パラメーター | 理由 |
|---|---|
| 専用のレイヤー | LiDAR のレイヤーは、ビームが通過したすべてのセルをクリアします。ビームはバナナの上を通過するので、レイヤーを共有すると、カメラがマークしたものが消されてしまいます |
VoxelLayer、5 cm のボクセル 10 個 |
3D:マグカップの奥の壁に向かうカメラの光線は、マグカップの上を通過し、実際に通過したボクセルだけをクリアします。平面 (2D) のレイヤーでは、マグカップの向こうを見るたびにマグカップが消され、最後に見えた側面だけが残ります |
min_obstacle_height: 0.015 |
床から 1.5 cm 以上の高さにあるものはすべて障害物です。床そのものは障害物ではありません |
obstacle_min_range、raytrace_min_range: 0.35 |
35 cm より近い範囲では、カメラはマークせず(そこに見えるのは、把持するときのロボット自身のアームとグリッパーです)、クリアもしません(もっと遠くから見たものが残ります) |
obstacle_max_range、raytrace_max_range: 2.5 |
同じ値にします。カメラがクリアできる範囲では、マークもできます |
ロボットが知っていることは Nav2 に伝える: カメラに見えるのは、いつも物の手前側だけです。このチュートリアルの最初のバージョン(シーンを参照)では、ロボットはマグカップを西側から見つけたので、コストマップにはマグカップの西側だけが入り、東側から通りかかった Nav2 はマグカップの残りの部分に突っ込みました。しかし、ミッションはマグカップ全体を知っています。マグカップは物のリストに入っているからです。そこでミッションは、知っているすべての物を円として 2 つ目の地図 /known_things(/map と同じ大きさ)に描き込み、両方のコストマップがそれをもう 1 つのレイヤーとして読み込みます(things_layer、StaticLayer、最大値で結合)。バナナを拾うと、その円は消えます。マグカップとボトルの円は残ります。ここでもチュートリアル 11 のルールです。/map には動かないものを、/known_things にはロボットが床の上で見つけたものを入れます。
things_layer: {plugin: 'nav2_costmap_2d::StaticLayer', map_topic: /known_things, map_subscribe_transient_local: true, use_maximum: true}
RViz (tidy.launch.py) の、最初の見回りのあとのグローバルコストマップ:
- ロボット:バナナをチェックするために近づいているところです。
- 1 本目のバナナ:円(マゼンタ)とそのインフレーションです。
- ボウルも同じです。
- 隅にあるマグカップも同じです。ここからでは Nav2 のセンサーが届く範囲をはるかに超えています。コストマップに入っているのは、ミッションが Nav2 に知らせたからです。
- 地図:壁、仕切り、箱(ここ)、柱です。
Lime の形に合わせた衝突チェック: MPPI の CostCritic は通常、base_footprint を中心とする円で衝突をチェックします (consider_footprint: false)。Lime の base_footprint は車輪の間、つまり前寄りにあります。台車は前方には 7.5 cm しか張り出していませんが、後方には 20.5 cm 張り出しています。最初のバージョンでは、マグカップの横で旋回したときに、ロボットの後部がマグカップにぶつかりました。さらに、何かがロボットに触れると、それは LiDAR の最小距離 12 cm よりも、カメラの 35 cm よりも近くなります。もう何もそれをマークしないので、Nav2 はボトルを部屋の中で 1.8 m も押していきました。consider_footprint: true にすると、MPPI はフットプリント全体をチェックします。
インフレーション半径はフットプリントより大きくする
フットプリントのチェックが機能するのは、inflation_radius (0.30 m) がフットプリントの外接円の半径より大きい場合だけです。Lime の外接円の半径は、標準の 1 cm の footprint_padding で 0.28 m です。最初のバージョンでは、フットプリントに 5 cm のパディングを付けていました (0.33 m)。すると Nav2 は「The inflation radius (0.300000) is smaller than the circumscribed radius (0.333542)」というログを毎秒 20 回出しながら、ひっそりと円によるチェックに戻っていました。代わりにインフレーションを 0.45 m に上げると、最初のバージョンの散らかった隅からバナナを運び出す動きが、のろのろになるか失敗するようになりました。MPPI はほとんど動かなかったのです(よくても 45 秒で 1.1 m)。そこでパディングは標準に戻し、マグカップとボトルのまわりの余裕は、本来あるべきところ、つまり /known_things に描いたそれぞれの円から取るようにしました。
nav2_params_tidy.yaml
チュートリアル 11 の nav2_params.yaml に、ちょうど 3 つの変更を加えたものです。両方のコストマップの depth_layer と things_layer、そして MPPI の consider_footprint です。tidy.launch.py は、チュートリアル 13 の lime_full.launch.py でこのパラメーターファイルを使うようにしたものです。
シーン¶
16_tidy_room.py は、チュートリアル 13 の部屋に置いたチュートリアル 13 のロボットです(実体のある物体、1.5 倍の大きさのボウル、滑りにくい指)。変更点は 3 つです。マグカップとボトルを邪魔にならないよう隅のほうへ移したこと、バナナを 2 本追加したこと、そして深度の点群です。
最初のバージョンでは、マグカップとボトルをチュートリアル 13 と同じ場所、つまり 1 本目のバナナから 30 cm のところに置いていました。この 2 つがバナナを囲い込んでしまい、把持できる方向は 1 方向しか残らず、Nav2 はボウルへ運ぶたびに 2 つの間をすり抜けなければなりませんでした。うまくいかなかったことの問題のほとんどは、ここから来ています。実際の家でも、ロボットに拾わせたいバナナのすぐ隣にカップを置いたりはしないでしょう。今ではこの 2 つはおとりです。ロボットは探索中にこれらを見つけ、YOLO でチェックし、そのままにしておきます。
isaac/common/scene.py の setup_tidy_room()
def setup_tidy_room(stage, root: str = "/World/LimeRoom") -> list[str]:
"""Tutorial 16: move the mug and the bottle out of the way (TIDY_MOVES), and add two more bananas, real
ones like the first (66 g, convex decomposition, rubber-like friction). Call it after setup_pick_and_place(),
which makes the rubber material. Returns the paths of all three bananas."""
from isaacsim.core.experimental.prims import XformPrim
from pxr import PhysxSchema, Usd, UsdGeom, UsdPhysics, UsdShade
for name, (x, y) in TIDY_MOVES.items():
prim = XformPrim(f"{root}/Objects/{name}")
position, orientation = prim.get_world_poses()
prim.set_world_poses(positions=[[x, y, float(position.numpy()[0, 2])]], orientations=orientation)
_name, rel, _x, _y, _yaw, half_height, up, _coco = next(o for o in OBJECTS if o[0] == "Banana")
rubber = UsdShade.Material(stage.GetPrimAtPath(f"{root}/PhysicsMaterials/rubber"))
paths = [f"{root}/Objects/Banana"]
for name, x, y, yaw in MORE_BANANAS:
path = f"{root}/Objects/{name}"
_place_ycb(path, rel, x, y, yaw, half_height, up)
prim = stage.GetPrimAtPath(path)
UsdPhysics.RigidBodyAPI.Apply(prim)
UsdPhysics.MassAPI.Apply(prim).CreateMassAttr(0.066) # kg
for p in Usd.PrimRange(prim):
if p.IsA(UsdGeom.Mesh):
UsdPhysics.CollisionAPI.Apply(p)
UsdPhysics.MeshCollisionAPI.Apply(p).CreateApproximationAttr("convexDecomposition")
PhysxSchema.PhysxRigidBodyAPI.Apply(prim).CreateSolverPositionIterationCountAttr(32)
UsdShade.MaterialBindingAPI.Apply(prim).Bind(rubber, UsdShade.Tokens.weakerThanDescendants, "physics")
paths.append(path)
return paths
ツリー¶
flowchart TD
root["→ Tidy the room"] --> bowl(["Find the fruit bowl<br/>YOLO"])
root --> each{{"◇ Every lookout<br/>(ForEach)"}} --> at["→ At the lookout"]
root --> home(["Go home<br/>Nav2"])
at --> get["? Get there"]
get --> retry1{{"◇ Up to 2 tries"}} --> go(["Go to the lookout<br/>Nav2"])
get --> skip(["Skip it"])
at --> look(["Look around<br/>depth camera"])
at --> until{{"◇ Until nothing is left<br/>(Repeat)"}} --> check["→ Check the next thing"]
check --> next(["Next thing to check<br/>FAILURE when none"])
check --> sel["? Tidy it or leave it"]
sel --> golook["→ Go and look"]
sel --> leave(["Leave it"])
golook --> choose(["Choose where to look from"])
golook --> drive(["Drive up to it<br/>Nav2"])
golook --> what(["What is it?<br/>YOLO"])
golook --> tidy["→ Tidy the banana"]
tidy --> isb(["Is it a banana?"])
tidy --> retry2{{"◇ Up to 3 tries"}} --> pick(["Pick it up<br/>MoveIt"])
tidy --> side(["Choose a side of the bowl"])
tidy --> carry(["Carry it to the bowl<br/>Nav2"])
tidy --> put(["Put it in the bowl<br/>MoveIt"])
チュートリアル 15 の各パターンが、ここでそれぞれの役割を果たします。
- ForEach は見回り地点を順にたどります。各地点で、Look around が見つけたものを物のリストに追加します。
- Repeat until nothing is left:Next thing to check は、まだチェックしていない物のうち一番近いものを選び、1 つもなければ失敗します。この失敗でループが終わり(FailureIsSuccess)、ツリーは次の見回り地点に進みます。
- Tidy it or leave it は Selector です。Go and look の中で何かが失敗すると(バナナではなかった、把持に 3 回失敗した、Nav2 がそこに行けない)、Leave it がその物をチェック済みにします。そのため、ロボットが 1 つの物から先に進めなくなることはありません。
- Retry:把持に失敗したら、新たに見直してからもう一度試します(全部で 3 回まで)。把持に失敗するとたいていバナナが少し動くので、次の試行ではバナナが違って見えます。
- Skip it:Nav2 がたどり着けない見回り地点は飛ばします。
def build_tree(lime, world):
blackboard = py_trees.blackboard.Client(name="tidy")
blackboard.register_key(key="lookouts", access=Access.WRITE)
blackboard.lookouts = LOOKOUTS
Seq, Sel = py_trees.composites.Sequence, py_trees.composites.Selector
tidy_banana = Seq("Tidy the banana", memory=True, children=[
IsBanana(),
py_trees.decorators.Retry("Up to 3 tries", PickUp(lime, world), num_failures=3),
ChooseBowlSide(lime, world),
NavigateTo("Carry it to the bowl", lime, key="goal"),
PutInBowl(lime, world),
])
check_thing = Seq("Check the next thing", memory=True, children=[
NextThing(lime, world), # FAILURE when nothing is left: ends the loop below
Sel("Tidy it or leave it", memory=True, children=[
Seq("Go and look", memory=True, children=[
ChooseViewpoint(lime, world),
NavigateTo("Drive up to it", lime, key="goal"),
WhatIsIt(lime, world),
tidy_banana,
]),
LeaveIt(lime, world),
]),
])
at_lookout = Seq("At the lookout", memory=True, children=[
Sel("Get there", memory=True, children=[
py_trees.decorators.Retry("Up to 2 tries", NavigateTo("Go to the lookout", lime, key="lookout"), num_failures=2),
py_trees.behaviours.Success("Skip it"),
]),
LookAround(lime, world),
py_trees.decorators.FailureIsSuccess("Until nothing is left", py_trees.decorators.Repeat("Repeat", check_thing, num_success=-1)),
])
return Seq("Tidy the room", memory=True, children=[
FindBowl(lime, world),
py_trees.decorators.ForEach("Every lookout", at_lookout, source_key="lookouts", target_key="lookout"),
NavigateTo("Go home", lime, pose=HOME_POSE),
])
葉(リーフ)は、チュートリアル 13 の Lime を呼び出す Action(チュートリアル 15)です:locate()、drive_to()、turn_to()、move_arm()、gripper()、top_down_ik()、long_object()、round_object()。新しいスキルは床のスキャンだけです。
ロボットが知っていること¶
World は、地図(Nav2 と同じく /map から)、ボウル、そして物を保持します。物はそれぞれ、位置(チュートリアル 13 と同じく odom フレーム)、YOLO が判定した種類、状態(new:新規、tidied:片付け済み、left:そのまま)を持ちます。free() は「ロボットはここに立てるか?」に答えます。Lime のフットプリントが、地図とも、既知のどの物とも重なっていてはいけません。ツリーはこれを使って、どこから見るか、どちら側から把持するか、ボウルのところでどこに立つかを選びます。
lime_isaac_bringup/scripts/tidy.py の Thing と World
class Thing:
"""Something on the floor that is not in the map. Positions are in the odom frame, like in tutorial 13."""
def __init__(self, xy, points):
self.xy, self.points, self.what, self.state = np.array(xy), points, None, "new" # new / tidied / left
def __repr__(self):
return f"{self.what or 'thing'} at ({self.xy[0]:.2f}, {self.xy[1]:.2f})"
def describe(self):
return f"{self!r} ({self.points} points)"
class World:
"""What the mission knows: the map (walls etc.), the things on the floor, and the bowl."""
def __init__(self, lime):
self.lime, self.things, self.bowl, self.map = lime, [], None, None
self.gripper = None
qos = QoSProfile(depth=1, durability=DurabilityPolicy.TRANSIENT_LOCAL, reliability=ReliabilityPolicy.RELIABLE)
lime.nav.create_subscription(OccupancyGrid, "/map", self.on_map, qos)
lime.nav.create_subscription(JointState, "/joint_states", self.on_joints, 10)
self.known = lime.nav.create_publisher(OccupancyGrid, "/known_things", qos) # for Nav2: see tell_nav2()
def on_map(self, msg):
occupied = np.array(msg.data, dtype=np.int16).reshape(msg.info.height, msg.info.width) >= 65
self.map = {"occupied": occupied, "near": grow(occupied, 3), "res": msg.info.resolution,
"origin": np.array([msg.info.origin.position.x, msg.info.origin.position.y]), "info": msg.info}
def tell_nav2(self):
"""Draw every thing the robot knows about into a second map, /known_things, the size of /map. Nav2 reads
it as one more costmap layer. The camera marks only the sides of a thing it has seen; this map has the
whole thing, and forgets a banana as soon as it is picked up."""
info = self.map["info"]
grid = np.zeros((info.height, info.width), dtype=np.int8) # 0 = free: this layer never frees anything
y, x = np.mgrid[0:info.height, 0:info.width]
cx, cy = info.origin.position.x + (x + 0.5) * info.resolution, info.origin.position.y + (y + 0.5) * info.resolution
known = [(t.xy, t.what) for t in self.things if t.state in ("new", "left")] # YOLO "unknown": still something
for xy, what in known + ([(self.bowl, "bowl")] if self.bowl is not None else []):
mx, my, _ = self.to_map(*xy, 0.0)
grid[np.hypot(cx - mx, cy - my) < RADIUS.get(what, 0.12)] = 100
msg = OccupancyGrid(info=info)
msg.header.frame_id = "map"
msg.header.stamp = self.lime.nav.get_clock().now().to_msg()
msg.data = grid.ravel().tolist()
self.known.publish(msg)
def on_joints(self, msg):
if "gripper_left_joint" in msg.name:
self.gripper = msg.position[msg.name.index("gripper_left_joint")]
def map_from_odom(self):
"""(R, t) of the map <- odom transform, in 2D (AMCL keeps it up to date; in simulation it is almost zero)."""
tf = self.lime.tf.lookup_transform("map", "odom", rclpy.time.Time(), timeout=rclpy.duration.Duration(seconds=1.0))
q, t = tf.transform.rotation, tf.transform.translation
yaw = math.atan2(2 * (q.w * q.z + q.x * q.y), 1 - 2 * (q.y * q.y + q.z * q.z))
return np.array([[math.cos(yaw), -math.sin(yaw)], [math.sin(yaw), math.cos(yaw)]]), np.array([t.x, t.y]), yaw
def to_map(self, x, y, yaw):
"""A pose in the odom frame -> the map frame (for Nav2 goals)."""
R, t, dyaw = self.map_from_odom()
mx, my = R @ np.array([x, y]) + t
return float(mx), float(my), wrap(yaw + dyaw)
def in_map(self, xy, layer="occupied"):
"""For points in the odom frame: does the map have something there? (outside the map counts as yes)"""
R, t, _ = self.map_from_odom()
cells = np.floor(((np.atleast_2d(xy) @ R.T + t) - self.map["origin"]) / self.map["res"]).astype(int)
h, w = self.map[layer].shape
inside = (cells[:, 0] >= 0) & (cells[:, 0] < w) & (cells[:, 1] >= 0) & (cells[:, 1] < h)
hit = np.ones(len(cells), dtype=bool)
hit[inside] = self.map[layer][cells[inside, 1], cells[inside, 0]]
return hit
def note(self, xy, points):
"""A thing seen on the floor: a new one, or one we know already (within 25 cm)."""
if self.bowl is not None and np.linalg.norm(xy - self.bowl) < 0.25:
return # the bowl itself, and the bananas in it
for thing in self.things:
if np.linalg.norm(thing.xy - xy) < 0.25:
if thing.state == "new" and points > thing.points: # keep the best (closest) look
thing.xy, thing.points = np.array(xy), points
return
self.things.append(Thing(xy, points))
def free(self, x, y, yaw, ignore=None, margin=0.05):
"""Is the robot's footprint at (x, y, yaw) [odom] clear of the map and of every known thing?"""
back, front, half = FOOTPRINT
c, s = math.cos(yaw), math.sin(yaw)
for thing in self.things:
if thing is ignore:
continue
dx, dy = thing.xy[0] - x, thing.xy[1] - y
fx, fy = dx * c + dy * s, -dx * s + dy * c # the thing in the robot's frame
r = margin + 0.07 # a thing is about 14 cm across
if back - r < fx < front + r and abs(fy) < half + r:
return False
if self.bowl is not None and ignore != "bowl":
dx, dy = self.bowl[0] - x, self.bowl[1] - y
fx, fy = dx * c + dy * s, -dx * s + dy * c
if back - margin - 0.13 < fx < front + margin + 0.13 and abs(fy) < half + margin + 0.13:
return False
fx, fy = np.meshgrid(np.arange(back - margin, front + margin + 0.01, 0.05), np.arange(-half - margin, half + margin + 0.01, 0.05))
pts = np.stack([x + fx.ravel() * c - fy.ravel() * s, y + fx.ravel() * s + fy.ravel() * c], axis=1)
return not self.in_map(pts).any()
def grow(mask, cells):
"""Grow the occupied cells of a grid by `cells` in every direction."""
out = mask.copy()
padded = np.pad(mask, cells)
h, w = mask.shape
for dy in range(-cells, cells + 1):
for dx in range(-cells, cells + 1):
if dx * dx + dy * dy <= cells * cells:
out |= padded[cells + dy:cells + dy + h, cells + dx:cells + dx + w]
return out
見回す:床のスキャン¶
def floor_scan(lime, world, step=2):
"""One look with the depth camera: every thing on the floor that is not in the map.
depth image -> 3D points (camera model + TF, like tutorial 13's locate())
-> drop the floor (lower than 1.2 cm) and what the map has (walls, pillar, crate, divider)
-> group the rest into things (neighbouring 5 cm cells belong together)
"""
msg = lime.depth[max(lime.depth)] # the newest depth image
depth = np.frombuffer(msg.data, dtype=np.float32).reshape(msg.height, msg.width)[::step, ::step]
v, u = np.mgrid[0:msg.height:step, 0:msg.width:step]
ok = np.isfinite(depth) & (depth > 0.3) & (depth < 2.0) # closer than 30 cm: maybe the robot's own arm
fx, fy, px, py = lime.K[0, 0], lime.K[1, 1], lime.K[0, 2], lime.K[1, 2]
z = depth[ok]
cam = np.stack([(u[ok] - px) * z / fx, (v[ok] - py) * z / fy, z], axis=1)
tf = lime.tf.lookup_transform("odom", msg.header.frame_id, msg.header.stamp, timeout=rclpy.duration.Duration(seconds=1.0))
t, q = tf.transform.translation, tf.transform.rotation
pts = cam @ quat_to_matrix(q.x, q.y, q.z, q.w).T + np.array([t.x, t.y, t.z])
pts = pts[(pts[:, 2] > 0.012) & (pts[:, 2] < 0.30)] # not the floor
pts = pts[~world.in_map(pts[:, :2], layer="near")] # not the walls, the pillar, ... (or within 15 cm of them)
cells = {}
for i, cell in enumerate(map(tuple, np.floor(pts[:, :2] / 0.05).astype(int))):
cells.setdefault(cell, []).append(i)
things, todo = [], set(cells)
while todo: # flood fill: one group of touching cells = one thing
group, stack = [], [todo.pop()]
while stack:
cx, cy = stack.pop()
group += cells[(cx, cy)]
for n in ((cx + a, cy + b) for a in (-1, 0, 1) for b in (-1, 0, 1)):
if n in todo:
todo.remove(n)
stack.append(n)
if len(group) >= 40: # a banana 1.4 m away gives about 120; fewer: noise at the edge of a wall or pillar
things.append((pts[group, :2].mean(axis=0), len(group)))
return things
LookAround:60° ずつ向きを変えて 6 回見る
class LookAround(Action):
"""Turn round once, in six steps of 60 deg (the camera sees 69 deg), and scan the floor at each."""
def __init__(self, lime, world):
super().__init__("Look around")
self.lime, self.world = lime, world
def run(self):
_, _, yaw = self.lime.pose()
for k in range(6):
if self.stop_requested:
return False
self.lime.turn_to(wrap(yaw + k * math.pi / 3))
self.lime.spin_for(0.6) # a fresh depth image
for xy, points in floor_scan(self.lime, self.world):
self.world.note(xy, points)
new = [t for t in self.world.things if t.state == "new"]
self.lime.log.info(f"things to check: {', '.join(t.describe() for t in new) or 'none'}")
self.world.tell_nav2()
return True
物をチェックする¶
Choose where to look from は、物のまわりの 24 方向を、ロボットに近い側から順に試し、物から 55 cm 離れていてロボットが収まる最初の場所を選びます。Nav2 がそこまで走り(Nav2 はゴールから 25 cm 以内で止まるので、最後の部分はオドメトリで動きます)、What is it? が 3 秒分の YOLO の検出結果を集めます。検出の 3D の点(チュートリアル 13 の points())が物から 15 cm 以内にあれば、その検出はその物のものとみなします。
YOLO がいつも答えを出せるとは限りません。隅にあって、すぐ後ろに壁があるマグカップは、ほとんどの場合まったく認識されません(ロボットの側からの 12 通りのテスト視点のうち、cup が 0.5 を超えたのは 1 つだけでした)。その場合、物は unknown になります。それで問題ありません。Is it a banana? が失敗し、ロボットが確信を持てないものには、安全なデフォルトである Leave it が使われます。
NextThing、ChooseViewpoint、WhatIsIt、IsBanana、LeaveIt
class NextThing(py_trees.behaviour.Behaviour):
"""Choose the nearest thing that has not been checked yet. FAILURE when there is none left."""
def __init__(self, lime, world):
super().__init__("Next thing to check")
self.lime, self.world = lime, world
self.blackboard = self.attach_blackboard_client(name=self.name)
self.blackboard.register_key(key="thing", access=Access.WRITE)
def update(self):
new = [t for t in self.world.things if t.state == "new"]
if not new:
return Status.FAILURE
x, y, _ = self.lime.pose()
self.blackboard.thing = min(new, key=lambda t: np.hypot(t.xy[0] - x, t.xy[1] - y))
self.feedback_message = str(self.blackboard.thing)
return Status.SUCCESS
class ChooseViewpoint(py_trees.behaviour.Behaviour):
"""A free spot VIEW metres from the thing, facing it, on the side the robot comes from -> blackboard 'goal'."""
def __init__(self, lime, world):
super().__init__("Choose where to look from")
self.lime, self.world = lime, world
self.blackboard = self.attach_blackboard_client(name=self.name)
self.blackboard.register_key(key="thing", access=Access.READ)
self.blackboard.register_key(key="goal", access=Access.WRITE)
def update(self):
thing = self.blackboard.thing
x, y, _ = self.lime.pose()
here = math.atan2(y - thing.xy[1], x - thing.xy[0]) # the robot's direction, seen from the thing
for a in sorted((k * math.pi / 12 for k in range(24)), key=lambda a: abs(wrap(a - here))):
vx, vy = thing.xy + VIEW * np.array([math.cos(a), math.sin(a)])
if self.world.free(vx, vy, a + math.pi, margin=NAV2_ROOM):
self.blackboard.goal = self.world.to_map(vx, vy, a + math.pi)
self.feedback_message = f"({vx:.2f}, {vy:.2f})"
return Status.SUCCESS
thing.state = "left"
self.feedback_message = f"no free spot to look at the {thing} from"
return Status.FAILURE
class WhatIsIt(Action):
"""Face the thing and ask YOLO: the most confident detection whose 3D points lie on the thing."""
def __init__(self, lime, world):
super().__init__("What is it?")
self.lime, self.world = lime, world
self.blackboard = self.attach_blackboard_client(name=self.name)
self.blackboard.register_key(key="thing", access=Access.READ)
def run(self):
thing, lime = self.blackboard.thing, self.lime
x, y, _ = lime.pose()
away = np.array([x, y]) - thing.xy
if np.linalg.norm(away) > VIEW + 0.08: # Nav2 stops within 25 cm of its goal: the last bit by odometry
lime.drive_to(*(thing.xy + VIEW * away / np.linalg.norm(away)))
x, y, _ = lime.pose()
lime.turn_to(math.atan2(thing.xy[1] - y, thing.xy[0] - x))
lime.detections.clear()
lime.spin_for(3.0)
best = None
for msg, depth_msg in lime.detections:
for d in msg.detections:
h = d.results[0].hypothesis
pts, _camera = lime.points(d, msg.header, depth_msg)
if pts is not None and np.linalg.norm(np.median(pts[:, :2], axis=0) - thing.xy) < 0.15:
if best is None or h.score > best[0]:
best = (h.score, h.class_id)
thing.what = best[1] if best else "unknown"
lime.log.info(f"YOLO: {thing}" + (f" ({best[0]:.2f})" if best else ""))
self.world.tell_nav2()
return True
class IsBanana(py_trees.behaviour.Behaviour):
def __init__(self):
super().__init__("Is it a banana?")
self.blackboard = self.attach_blackboard_client(name=self.name)
self.blackboard.register_key(key="thing", access=Access.READ)
def update(self):
return Status.SUCCESS if self.blackboard.thing.what == "banana" else Status.FAILURE
class LeaveIt(Action):
"""The fallback: it is not a banana, or something went wrong - remember it as checked and carry on.
(Still holding it? Then put it down first.)"""
def __init__(self, lime, world):
super().__init__("Leave it")
self.lime, self.world = lime, world
self.blackboard = self.attach_blackboard_client(name=self.name)
self.blackboard.register_key(key="thing", access=Access.READ)
def run(self):
thing = self.blackboard.thing
if thing.state == "carried":
self.lime.gripper(GRIPPER_OPEN)
self.lime.move_arm(HOME, "arm folded")
thing.state = "left"
self.lime.log.info(f"leave the {thing}")
self.world.tell_nav2()
return True
拾い上げる¶
チュートリアル 13 の把持ですが、視点は固定ではなく選びます。チュートリアル 13 は、いつも 55° 回り込んだ位置からもう一度見ていました。それが合っていたのは、あの 1 本のバナナをあの 1 つのスタート地点から拾う場合だけです。
- 1 回目の観察:Nav2 がロボットを運んできた場所(55 cm 離れた位置)から見ます。
- 2 回目の観察は、45〜135° 回り込んだ位置から行います(90° が最適です)。1 回の観察ではバナナの手前側しか見えません。ほぼ端から見ると、曲がったバナナの向きは約 25° ずれて求まり、その後のすべての判断がその誤差の上に積み重なってしまいます。
long_object()は、すべての観察の点をまとめて受け取ります。 - 把持する側を選ぶ:バナナの長軸からできるだけ離れた方向、最低でも 24° 離れた方向を選びます。それより端寄りだと、バナナの手前の端がロボットの前部の下に入ってしまいます。ロボットは 60 cm の位置から把持位置まで、何にも触れずにまっすぐ進入できなければなりません。Nav2 は 60 cm の地点に 10 cm の余裕を必要とします。把持のあと、そこから Nav2 が引き継ぐからです。その側が新しい場所なら、ロボットはそこからもう一度見ます。
- 把持はチュートリアル 13 とまったく同じです。そのあと、来た道をそのまま後退して 60 cm の位置まで戻ります。マグカップのすぐ隣から Nav2 で動き出したときは、Nav2 がロボットの後部をマグカップにぶつけてしまいました。
(チュートリアル 13 のようにマグカップとボトルが 1 本目のバナナから 30 cm のところにあると、使える良い側は、チュートリアル 13 が使った約 225° の側しか残りませんでした。)
PickUp
class PickUp(Action):
"""Tutorial 13's grasp, from wherever the robot stands: look from two sides, drive up blind, grasp, lift."""
def __init__(self, lime, world):
super().__init__("Pick it up")
self.lime, self.world = lime, world
self.blackboard = self.attach_blackboard_client(name=self.name)
self.blackboard.register_key(key="thing", access=Access.READ)
def run(self):
lime, world, thing = self.lime, self.world, self.blackboard.thing
# 1. First look, from where Nav2 brought the robot.
looks = [self.look()]
if looks[0] is None:
return self.fail("YOLO: lost the banana")
centre, first_axis = long_object(looks[0])
thing.xy = centre # YOLO's points are better than the floor scan's
first = math.atan2(*(looks[0]["camera"] - centre)[::-1]) # where the first look came from
# 2. Second look, from 45 to 135 deg further round (90 is best). One look sees only the banana's near
# side, and seen nearly end-on, its direction comes out 25 deg wrong. Together they see all of it.
def second_look_cost(a): # how far from 90 deg round from the first look; None: not 45..135 deg
round_by = abs(wrap(a - first))
return abs(round_by - math.pi / 2) if math.pi / 4 < round_by < 3 * math.pi / 4 else None
second = self.spot(centre, second_look_cost)
if second is not None and self.go(centre, second):
looks.append(self.look())
centre, axis = long_object(merge(looks))
lime.log.info(f"banana pointing {math.degrees(axis) % 180:.0f} deg from {len(looks)} looks "
f"(the first alone: {math.degrees(first_axis) % 180:.0f} deg)")
# 3. The grasp side: as far off the banana's axis as possible, and at least 24 deg (closer to end-on, the
# banana's near end would be under the robot's front; tutorial 13 grasped from 26 deg). The robot must
# be able to drive straight up to the grasp position, and Nav2 takes over from there afterwards.
x, y, _ = lime.pose()
here = math.atan2(y - centre[1], x - centre[0])
def grasp_cost(a): # the more across the banana the better, and the nearer the robot's own side
across = abs(math.sin(a - axis)) # 1 = from the side, 0 = end-on
return -across + abs(wrap(a - here)) / math.pi if across > 0.4 else None
side = self.spot(centre, grasp_cost, grasp=True)
if side is None:
return self.fail("no free side to grasp the banana from")
if abs(wrap(side - here)) > math.radians(5):
if not self.go(centre, side):
return self.fail("could not get to the side of the banana")
looks.append(self.look())
centre, banana_yaw = long_object(merge(looks))
lime.log.info(f"YOLO: banana at ({centre[0]:.3f}, {centre[1]:.3f}), pointing {math.degrees(banana_yaw) % 180:.0f} deg "
f"from {len(looks)} looks; grasp from {math.degrees(side):.0f} deg")
# 4. Drive up blind until the banana is GRASP m in front, then tutorial 13's grasp.
look = side + math.pi
toward = np.array([math.cos(look), math.sin(look)])
lime.drive_to(*(centre - GRASP * toward))
lime.turn_to(look)
lime.gripper(GRIPPER_OPEN)
bx, by = lime.to_base(*centre)
yaw = wrap(banana_yaw - lime.pose()[2])
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):
return self.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")):
return self.fail("MoveIt: could not reach down")
lime.gripper(GRIPPER_CLOSED)
if not (lime.move_arm(lifted, "lift") and lime.move_arm(CARRY, "carry")):
return self.fail("MoveIt: could not lift")
lime.spin_for(0.5)
if world.gripper is None or world.gripper < GRIPPER_CLOSED + 0.004: # the fingers closed on nothing
return self.fail(f"missed the banana (gripper at {world.gripper})")
thing.state = "carried"
world.tell_nav2() # it is not on the floor any more
lime.log.info(f"holding the banana (gripper at {world.gripper * 1000:.1f} mm)")
# 5. Leave the way you came: back out to BACK_OUT. Nav2 then starts in the open, not right next to
# whatever stands near the banana (started that close, it can sweep the robot's back into it).
lime.drive_to(*(centre - BACK_OUT * toward), backwards=True)
return True
def look(self):
"""Face the banana and locate it (tutorial 13)."""
x, y, _ = self.lime.pose()
thing = self.blackboard.thing
self.lime.turn_to(math.atan2(thing.xy[1] - y, thing.xy[0] - x))
return self.lime.locate("banana", seconds=3.0)
def spot(self, centre, cost, grasp=False):
"""The direction a (from the banana) of the best free spot SIDE m away; cost(a) = None: not allowed.
For the grasp, the whole straight line from BACK_OUT to the grasp position must be free too, and Nav2
needs more room at BACK_OUT (it takes over from there after the grasp)."""
return best_spot(self.world, self.blackboard.thing, centre, cost, grasp)
def go(self, centre, a):
"""To the spot SIDE m from the banana in direction a, facing it: a straight drive if the way is free
(the banana counts as in the way, too), else Nav2."""
lime, world = self.lime, self.world
x, y, _ = lime.pose()
spot = centre + SIDE * np.array([math.cos(a), math.sin(a)])
heading = math.atan2(spot[1] - y, spot[0] - x)
if not all(world.free(*p, heading) for p in np.linspace([x, y], spot, 10)):
if not navigate(lime, world.to_map(*spot, a + math.pi), stop=lambda: self.stop_requested):
return False
lime.drive_to(*spot)
lime.turn_to(a + math.pi)
return True
def fail(self, why):
"""Let go, fold the arm and back off, so that the next try (or the next thing) starts clean."""
self.feedback_message = why
self.lime.gripper(GRIPPER_OPEN)
self.lime.move_arm(HOME, "arm folded")
x, y, yaw = self.lime.pose()
self.lime.drive_to(x - 0.15 * math.cos(yaw), y - 0.15 * math.sin(yaw), backwards=True)
return False
ボウルに入れる¶
ボウルは最初に一度だけ見つけます(チュートリアル 13 と同じく、スタート地点から YOLO に見えます)。バナナごとに、Choose a side of the bowl が、ほかのどの物とも 30 cm の余裕がある空いた側のうち最も近い側を選び、Nav2 がバナナをそこまで運びます。Put it in the bowl はチュートリアル 13 のリリースと同じです。ボウルに向きを合わせ、バナナをロボットに対して横向きにして、ボウルの中心の上(またはアームが届くできるだけ近い位置)でグリッパーを開き、アームを折りたたんで後退します。
ボウルには 3 本のバナナがすべて入ります。バナナは積み重なり、3 本目はほかの 2 本の上に載ります。
FindBowl、ChooseBowlSide、PutInBowl
class FindBowl(Action):
"""At the start: where is the fruit bowl? (YOLO + depth, tutorial 13)"""
def __init__(self, lime, world):
super().__init__("Find the fruit bowl")
self.lime, self.world = lime, world
def run(self):
found = self.lime.locate("bowl", seconds=3.0)
if found is None:
return False
self.world.bowl, _radius = round_object(found)
self.lime.log.info(f"YOLO: bowl ({found['score']:.2f}) at ({self.world.bowl[0]:.2f}, {self.world.bowl[1]:.2f})")
self.world.tell_nav2()
return True
class ChooseBowlSide(py_trees.behaviour.Behaviour):
"""The nearest free spot BOWL_APPROACH m from the bowl with room around it (30 cm to any thing), or else
the one with the most room -> blackboard 'goal'."""
def __init__(self, lime, world):
super().__init__("Choose a side of the bowl")
self.lime, self.world = lime, world
self.blackboard = self.attach_blackboard_client(name=self.name)
self.blackboard.register_key(key="goal", access=Access.WRITE)
self.blackboard.register_key(key="bowl_side", access=Access.WRITE)
def update(self):
bowl, sides = self.world.bowl, []
x, y, _ = self.lime.pose()
for a in (k * math.pi / 8 for k in range(16)):
p = bowl + BOWL_APPROACH * np.array([math.cos(a), math.sin(a)])
if self.world.free(*p, a + math.pi, ignore="bowl", margin=NAV2_ROOM):
room = min([np.linalg.norm(t.xy - p) for t in self.world.things if t.state != "carried"] + [9.0])
sides.append((room, np.hypot(p[0] - x, p[1] - y), a))
if not sides:
return Status.FAILURE
roomy = [s for s in sides if s[0] > 0.30]
a = min(roomy, key=lambda s: s[1])[2] if roomy else max(sides)[2]
self.feedback_message = f"{math.degrees(a):.0f} deg"
self.blackboard.bowl_side = a
self.blackboard.goal = self.world.to_map(*(bowl + BOWL_APPROACH * np.array([math.cos(a), math.sin(a)])), a + math.pi)
return Status.SUCCESS
class PutInBowl(Action):
"""Tutorial 13's release: line up with the bowl, banana across the robot, above the bowl's centre, open."""
def __init__(self, lime, world):
super().__init__("Put it in the bowl")
self.lime, self.world = lime, world
self.blackboard = self.attach_blackboard_client(name=self.name)
self.blackboard.register_key(key="thing", access=Access.READ)
self.blackboard.register_key(key="bowl_side", access=Access.READ)
def run(self):
lime, world, a = self.lime, self.world, self.blackboard.bowl_side
out = np.array([math.cos(a), math.sin(a)]) # from the bowl towards the robot
lime.drive_to(*(world.bowl + BOWL_APPROACH * out))
lime.turn_to(a + math.pi)
found = lime.locate("bowl")
bowl = round_object(found)[0] if found else world.bowl
lime.drive_to(*(bowl + BOWL_RELEASE * out))
lime.turn_to(a + math.pi)
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.14, math.pi / 2))), None)
if release is None or not lime.move_arm(release, "above the bowl"):
return False
lime.gripper(GRIPPER_OPEN)
lime.spin_for(1.0)
lime.move_arm(HOME, "arm folded")
lime.drive_to(*(bowl + BOWL_APPROACH * out), backwards=True) # leave the way you came
self.blackboard.thing.state = "tidied"
lime.log.info(f"tidied: the {self.blackboard.thing}")
return True
実行してみる¶
ターミナル 1 では Isaac Sim を実行します。
ターミナル 2 では ROS 2 スタックを実行します。チュートリアル 13 の lime_full.launch.py を nav2_params_tidy.yaml で起動するものです(「Managed nodes are active」と「You can start planning now!」が表示されるまで待ちます)。
./scripts/build_ws.sh lime_isaac_bringup
./docker/run_ros.sh ros2 launch lime_isaac_bringup tidy.launch.py
ターミナル 3 ではミッションを実行します。
ミッションは、見つけたものを表示し、ツリーのビヘイビアが成功 (ok) または失敗 (FAIL) するたびに、その名前とかかった時間を表示します(時間は実時間の秒数です。テスト用 PC では、シミュレーションは実時間の約半分の速さで動きました)。1 本目のバナナを含む、最初の部分です。
YOLO: bowl (0.67) at (0.99, 0.40)
[bt] ok Find the fruit bowl (3 s)
[bt] ok Go to the lookout
things to check: thing at (0.75, -0.12) (331 points), thing at (-1.18, -1.37) (111 points)
[bt] ok Look around (34 s)
[bt] ok Next thing to check: thing at (0.75, -0.12)
[bt] ok Choose where to look from: (0.22, 0.02)
[bt] ok Drive up to it (4 s)
YOLO: banana at (0.75, -0.12) (0.87)
[bt] ok What is it? (14 s)
[bt] ok Is it a banana?
banana pointing 16 deg from 2 looks (the first alone: 47 deg)
YOLO: banana at (0.798, -0.121), pointing 17 deg from 3 looks; grasp from 270 deg
holding the banana (gripper at -0.5 mm)
[bt] ok Pick it up (112 s)
[bt] ok Choose a side of the bowl: 292 deg
[bt] ok Carry it to the bowl (16 s)
tidied: the banana at (0.74, -0.11)
[bt] ok Put it in the bowl (59 s)
[bt] ok Drive up to it (23 s)
YOLO: unknown at (-1.18, -1.37)
[bt] ok What is it? (13 s)
[bt] FAIL Is it a banana?
leave the unknown at (-1.18, -1.37)
[bt] ok Leave it
[bt] FAIL Next thing to check
一番近いので、まずバナナ、次にマグカップです。マグカップは、ここからでは YOLO が認識しません (unknown)。バナナではないので、そのまま残します。Next thing to check が失敗し、ここにはもう何も残っていないので、ツリーは次の見回り地点に進みます。
[bt] ok Go to the lookout (32 s)
things to check: thing at (3.39, 0.88) (304 points), thing at (2.69, -1.66) (171 points)
...
YOLO: banana at (2.731, -1.693), pointing 113 deg from 3 looks; grasp from 0 deg
...
tidied: the banana at (2.71, -1.66)
[bt] ok Put it in the bowl (54 s)
[bt] ok Drive up to it (21 s)
YOLO: bottle at (3.39, 0.88) (0.85)
[bt] ok What is it? (7 s)
[bt] FAIL Is it a banana?
leave the bottle at (3.39, 0.88)
[bt] FAIL Next thing to check
[bt] ok Go to the lookout (22 s)
things to check: thing at (1.60, 2.04) (136 points)
...
tidied: the banana at (1.60, 2.05)
[bt] FAIL Next thing to check
[bt] ok Go home (28 s)
room tidy: 3 bananas in the bowl, 898 s
1 本目のバナナの実際の位置は (0.80, −0.12) で、向きは 20° です。最初の場所からだけ、ほぼ端から見たときは、向きが 47° と求まりました。約 90° 回り込んだ位置からの 2 回目の観察を加えると、16° になりました。
自動チェック¶
python isaac/16_tidy_room.py --headless --test は、シミュレーションの正解(ground truth)を使ってミッションを追跡します。各バナナが持ち上げられた時刻とボウルの中で静止した時刻、ロボットがホームに戻ったかどうか、マグカップやボトルに触れたかどうかを調べます。バナナは、その中心がボウルの中心から 10 cm 以内にあり(縁は 12 cm のところです)、そこで静止していれば、ボウルに入ったとみなします。tools/run_all_checks.sh 16 は tidy.launch.py とミッションを起動します。
[16] ground truth: banana at (0.80, -0.12), pointing 20 deg
[16] ground truth: banana2 at (2.70, -1.70), pointing 120 deg
[16] ground truth: banana3 at (1.60, 2.05), pointing 10 deg
[16] banana lifted at t = 86 s
[16] banana in the bowl, 3.7 cm from its centre at t = 121 s
[16] banana2 lifted at t = 243 s
[16] banana2 in the bowl, 1.6 cm from its centre at t = 279 s
[16] banana3 lifted at t = 399 s
[16] banana3 in the bowl, 6.9 cm from its centre at t = 435 s
[16] robot back home, arm folded at t = 453 s
[16][check] ok banana in the bowl at the end (3.6 cm from its centre)
[16][check] ok banana2 in the bowl at the end (1.5 cm from its centre)
[16][check] ok banana3 in the bowl at the end (6.9 cm from its centre)
[16][check] ok robot back home with the arm folded (within 0.3 m)
[16][check] ok mug not bumped into (moved 0.0 cm)
[16][check] ok bottle not bumped into (moved 0.0 cm)
[16][test] PASS
仕事全体には、シミュレーション時間で約 7 分半かかります。
Isaac Sim 側:isaac/16_tidy_room.py
# SPDX-FileCopyrightText: 2026 An (an-robotics)
# SPDX-License-Identifier: Apache-2.0
"""Tutorial 16 - All together: tidy the room. Three bananas lie around the lime_room; the Lime finds them all.
source scripts/isaac_env.sh
python isaac/16_tidy_room.py
# ROS 2 container: MoveIt 2 + ros2_control, Nav2 (+ the depth camera in the costmaps), YOLO, RViz
./docker/run_ros.sh ros2 launch lime_isaac_bringup tidy.launch.py
./docker/run_ros.sh ros2 run lime_isaac_bringup tidy # the mission: a behavior tree
The robot of tutorial 13 (every sensor and graph from tutorials 06-12) in tutorial 13's lime_room, plus:
* the mug and the bottle moved out of the way, towards the corners: things to find and leave alone
* two more bananas, where the robot cannot see them from its start (common/scene.py: setup_tidy_room)
* a small point cloud from the depth camera, so Nav2 sees what is lower than the LiDAR (graphs.create_depth_cloud_graph)
"""
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, setup_tidy_room
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) # tutorial 13's room: real objects
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
bananas = setup_tidy_room(stage) # the mug and the bottle out of the way; two more bananas, hidden from the start
while stage_utils.is_stage_loading():
simulation_app.update()
graphs.create_clock_graph() # 06
graphs.create_drive_graph(articulation_root) # 06 /cmd_vel <- Nav2, mission
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
camera = sensors.add_d435_camera(robot_path)
graphs.create_camera_graph(camera) # 08 camera -> YOLO, mission
graphs.create_depth_cloud_graph(camera) # 16 depth point cloud -> Nav2's costmaps
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
CHASE = np.array([-0.9, -1.7, 1.5]) # the camera follows the robot from behind and above (south-west)
recorder = Recorder(args.record, eye=CHASE, target=(0.0, 0.0, 0.1), every_n=20, fps=24)
follow = np.zeros(2)
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("[16] ready: ros2 launch lime_isaac_bringup tidy.launch.py, then ros2 run lime_isaac_bringup tidy", flush=True)
# --test: follow the mission from the simulation's point of view (ground truth)
prims = {path.rsplit("/", 1)[1]: XformPrim(path) for path in bananas}
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])
HOME = np.array([0.0, 0.0])
events, steps, still_since = {}, 0, {}
if args.test or args.record:
for name, prim in prims.items():
(x, y, _), (w, qx, qy, qz) = prim.get_world_poses()[0].numpy()[0], prim.get_world_poses()[1].numpy()[0]
axis = np.degrees(np.arctan2(2 * (qx * qy + w * qz), 1 - 2 * (qy * qy + qz * qz))) % 180 # its long axis (local x)
print(f"[16] ground truth: {name.lower()} at ({x:.2f}, {y:.2f}), pointing {axis:.0f} deg", flush=True)
def event(name, text):
events[name] = steps / 60
print(f"[16] {text} at t = {events[name]:.0f} s", flush=True)
def in_bowl(p): # its centre inside the bowl (rim radius 12 cm, 1.5 x the YCB bowl), resting, not held above it
return np.linalg.norm(p[:2] - BOWL) < 0.10 and p[2] < 0.15
while simulation_app.is_running():
simulation_app.update()
steps += 1
if recorder:
follow += 0.01 * (robot.get_world_poses()[0].numpy()[0, :2] - follow) # smooth, so the view does not jerk
target = np.array([follow[0], follow[1], 0.1])
recorder.look_at(target + CHASE, target)
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]
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)})")
for name, prim in prims.items():
b = prim.get_world_poses()[0].numpy()[0]
if f"{name} lifted" not in events and b[2] > 0.10:
event(f"{name} lifted", f"{name.lower()} lifted")
still_since[name] = (still_since.get(name) or steps) if in_bowl(b) else None
if f"{name} lifted" in events and f"{name} in bowl" not in events and still_since[name] and steps - still_since[name] > 60:
event(f"{name} in bowl", f"{name.lower()} in the bowl, {np.linalg.norm(b[:2] - BOWL) * 100:.1f} cm from its centre")
tidied = all(f"{name} in bowl" in events for name in prims)
q = robot.get_dof_positions(dof_indices=arm).numpy()[0]
if tidied and "home" not in events and np.linalg.norm(xy - HOME) < 0.3 and np.max(np.abs(q - np.array(lime.ARM_HOME))) < 0.05:
event("home", "robot back home, arm folded")
if ("home" in events and steps / 60 > events["home"] + 5) or steps > 1800 * 60:
break # (5 s more, so the mission can finish cleanly)
ok = True
if args.test:
checks = {}
for name, prim in prims.items():
b = prim.get_world_poses()[0].numpy()[0]
checks[f"{name.lower()} in the bowl at the end ({np.linalg.norm(b[:2] - BOWL) * 100:.1f} cm from its centre)"] = in_bowl(b)
checks["robot back home with the arm folded (within 0.3 m)"] = "home" in events
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"[16][check] {'ok ' if passed else 'FAIL'} {text}")
ok = all(checks.values())
print(f"[16][test] {'PASS' if ok else 'FAIL'}")
if recorder: # the picture for the docs: a close-up of the full bowl
recorder.look_at((BOWL[0] - 0.35, BOWL[1] - 0.45, 0.45), (BOWL[0], BOWL[1], 0.04))
for _ in range(30):
simulation_app.update()
for _ in range(72): # 3 s at the end of the video
simulation_app.update()
recorder.capture(force=True)
recorder.save()
app_utils.stop()
simulation_app.close(exit_code=0 if ok else 1)
sys.exit(0 if ok else 1)
launch ファイル:lime_isaac_bringup/launch/tidy.launch.py
# SPDX-FileCopyrightText: 2026 An (an-robotics)
# SPDX-License-Identifier: Apache-2.0
"""Tutorial 16: tutorial 13's complete stack (MoveIt 2, Nav2, YOLO, RViz), with Nav2 also seeing the depth camera.
ros2 launch lime_isaac_bringup tidy.launch.py
ros2 run lime_isaac_bringup tidy # the mission: tidy the room (a behavior tree)
The only difference to lime_full.launch.py is Nav2's parameter file: config/nav2_params_tidy.yaml adds a
costmap layer for the depth camera's point cloud, so Nav2 drives round the bananas, the mug and the bowl.
"""
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument, IncludeLaunchDescription
from launch.substitutions import LaunchConfiguration, PathJoinSubstitution
from launch_ros.substitutions import FindPackageShare
def generate_launch_description():
pkg = FindPackageShare("lime_isaac_bringup")
return LaunchDescription(
[
DeclareLaunchArgument("rviz", default_value="true"),
IncludeLaunchDescription(
PathJoinSubstitution([pkg, "launch", "lime_full.launch.py"]),
launch_arguments={
"rviz": LaunchConfiguration("rviz"),
"params_file": PathJoinSubstitution([pkg, "config", "nav2_params_tidy.yaml"]),
}.items(),
),
]
)
ミッション全体:lime_isaac_bringup/scripts/tidy.py
#!/usr/bin/env python3
# SPDX-FileCopyrightText: 2026 An (an-robotics)
# SPDX-License-Identifier: Apache-2.0
"""Tutorial 16 mission: tidy the room - a behavior tree (py_trees) on top of Nav2, the depth camera, YOLO and MoveIt.
ros2 run lime_isaac_bringup tidy
ros2 run lime_isaac_bringup tidy --render DIR # only draw the tree (DIR/tidy.png), no robot needed
Bananas lie around the lime_room; the robot does not know where. Put every one into the fruit bowl, then go home.
1. Find the fruit bowl: YOLO, from the start (tutorial 13).
2. At each lookout (Nav2): turn round once. The depth camera finds every thing on the floor that is not in
the map (tutorial 11: the map holds only what stays put).
3. Check each thing: Nav2 drives up to it, and YOLO says what it is. (YOLO knows a lying banana only from
up close: from the low camera, a banana 1 m away is a thin yellow line.)
4. A banana: pick it up (tutorial 13), Nav2 carries it to the bowl, put it in. Anything else: leave it.
5. Go home.
"""
import argparse
import math
import os
import sys
import time
import numpy as np
import py_trees
import rclpy
from geometry_msgs.msg import PoseStamped
from nav_msgs.msg import OccupancyGrid
from py_trees.common import Access, Status
from rclpy.qos import DurabilityPolicy, QoSProfile, ReliabilityPolicy
from sensor_msgs.msg import JointState
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__))) # tutorial 13's mission.py, lime_bt.py
from lime_bt import Action, NavigateTo, run_tree # noqa: E402
LOOKOUTS = [(0.0, 0.0, 0.0), (2.9, -0.5, 0.0), (1.9, 0.7, math.pi / 2)] # where the robot looks round (map frame)
HOME_POSE = (0.0, 0.0, 0.0)
VIEW = 0.55 # m: look at a thing from this far (YOLO's banana range from the low camera)
SIDE = 0.45 # m: look at a banana from its side, from this far, before grasping it (tutorial 13)
BACK_OUT = 0.60 # m: after the grasp, back out to this far from where the banana was; Nav2 takes over there
GRASP = 0.16 # m: a banana this far in front of base_footprint is in the arm's reach (tutorial 13)
BOWL_APPROACH, BOWL_RELEASE = 0.42, 0.20 # m from the bowl's centre (tutorial 13)
FOOTPRINT = (-0.205, 0.075, 0.165) # back, front, half width (m): the Lime's base in Nav2 (tutorial 11)
# How big to draw each kind of thing for Nav2 (m): its radius, plus a few cm because the camera saw only its near
# side (its centre may be that much off), plus 3 cm to keep Nav2 off it
RADIUS = {"cup": 0.12, "bottle": 0.11, "banana": 0.14, "bowl": 0.16}
NAV2_ROOM = 0.10 # m round the footprint where Nav2 starts or stops: room to turn, and one 5 cm costmap cell
def wrap(a):
return (a + math.pi) % (2 * math.pi) - math.pi
def merge(looks):
"""The points of several looks at one object, as if they were one look (for long_object())."""
looks = [f for f in looks if f is not None]
return {"points": np.vstack([f["points"] for f in looks]), "camera": looks[-1]["camera"]}
class Thing:
"""Something on the floor that is not in the map. Positions are in the odom frame, like in tutorial 13."""
def __init__(self, xy, points):
self.xy, self.points, self.what, self.state = np.array(xy), points, None, "new" # new / tidied / left
def __repr__(self):
return f"{self.what or 'thing'} at ({self.xy[0]:.2f}, {self.xy[1]:.2f})"
def describe(self):
return f"{self!r} ({self.points} points)"
class World:
"""What the mission knows: the map (walls etc.), the things on the floor, and the bowl."""
def __init__(self, lime):
self.lime, self.things, self.bowl, self.map = lime, [], None, None
self.gripper = None
qos = QoSProfile(depth=1, durability=DurabilityPolicy.TRANSIENT_LOCAL, reliability=ReliabilityPolicy.RELIABLE)
lime.nav.create_subscription(OccupancyGrid, "/map", self.on_map, qos)
lime.nav.create_subscription(JointState, "/joint_states", self.on_joints, 10)
self.known = lime.nav.create_publisher(OccupancyGrid, "/known_things", qos) # for Nav2: see tell_nav2()
def on_map(self, msg):
occupied = np.array(msg.data, dtype=np.int16).reshape(msg.info.height, msg.info.width) >= 65
self.map = {"occupied": occupied, "near": grow(occupied, 3), "res": msg.info.resolution,
"origin": np.array([msg.info.origin.position.x, msg.info.origin.position.y]), "info": msg.info}
def tell_nav2(self):
"""Draw every thing the robot knows about into a second map, /known_things, the size of /map. Nav2 reads
it as one more costmap layer. The camera marks only the sides of a thing it has seen; this map has the
whole thing, and forgets a banana as soon as it is picked up."""
info = self.map["info"]
grid = np.zeros((info.height, info.width), dtype=np.int8) # 0 = free: this layer never frees anything
y, x = np.mgrid[0:info.height, 0:info.width]
cx, cy = info.origin.position.x + (x + 0.5) * info.resolution, info.origin.position.y + (y + 0.5) * info.resolution
known = [(t.xy, t.what) for t in self.things if t.state in ("new", "left")] # YOLO "unknown": still something
for xy, what in known + ([(self.bowl, "bowl")] if self.bowl is not None else []):
mx, my, _ = self.to_map(*xy, 0.0)
grid[np.hypot(cx - mx, cy - my) < RADIUS.get(what, 0.12)] = 100
msg = OccupancyGrid(info=info)
msg.header.frame_id = "map"
msg.header.stamp = self.lime.nav.get_clock().now().to_msg()
msg.data = grid.ravel().tolist()
self.known.publish(msg)
def on_joints(self, msg):
if "gripper_left_joint" in msg.name:
self.gripper = msg.position[msg.name.index("gripper_left_joint")]
def map_from_odom(self):
"""(R, t) of the map <- odom transform, in 2D (AMCL keeps it up to date; in simulation it is almost zero)."""
tf = self.lime.tf.lookup_transform("map", "odom", rclpy.time.Time(), timeout=rclpy.duration.Duration(seconds=1.0))
q, t = tf.transform.rotation, tf.transform.translation
yaw = math.atan2(2 * (q.w * q.z + q.x * q.y), 1 - 2 * (q.y * q.y + q.z * q.z))
return np.array([[math.cos(yaw), -math.sin(yaw)], [math.sin(yaw), math.cos(yaw)]]), np.array([t.x, t.y]), yaw
def to_map(self, x, y, yaw):
"""A pose in the odom frame -> the map frame (for Nav2 goals)."""
R, t, dyaw = self.map_from_odom()
mx, my = R @ np.array([x, y]) + t
return float(mx), float(my), wrap(yaw + dyaw)
def in_map(self, xy, layer="occupied"):
"""For points in the odom frame: does the map have something there? (outside the map counts as yes)"""
R, t, _ = self.map_from_odom()
cells = np.floor(((np.atleast_2d(xy) @ R.T + t) - self.map["origin"]) / self.map["res"]).astype(int)
h, w = self.map[layer].shape
inside = (cells[:, 0] >= 0) & (cells[:, 0] < w) & (cells[:, 1] >= 0) & (cells[:, 1] < h)
hit = np.ones(len(cells), dtype=bool)
hit[inside] = self.map[layer][cells[inside, 1], cells[inside, 0]]
return hit
def note(self, xy, points):
"""A thing seen on the floor: a new one, or one we know already (within 25 cm)."""
if self.bowl is not None and np.linalg.norm(xy - self.bowl) < 0.25:
return # the bowl itself, and the bananas in it
for thing in self.things:
if np.linalg.norm(thing.xy - xy) < 0.25:
if thing.state == "new" and points > thing.points: # keep the best (closest) look
thing.xy, thing.points = np.array(xy), points
return
self.things.append(Thing(xy, points))
def free(self, x, y, yaw, ignore=None, margin=0.05):
"""Is the robot's footprint at (x, y, yaw) [odom] clear of the map and of every known thing?"""
back, front, half = FOOTPRINT
c, s = math.cos(yaw), math.sin(yaw)
for thing in self.things:
if thing is ignore:
continue
dx, dy = thing.xy[0] - x, thing.xy[1] - y
fx, fy = dx * c + dy * s, -dx * s + dy * c # the thing in the robot's frame
r = margin + 0.07 # a thing is about 14 cm across
if back - r < fx < front + r and abs(fy) < half + r:
return False
if self.bowl is not None and ignore != "bowl":
dx, dy = self.bowl[0] - x, self.bowl[1] - y
fx, fy = dx * c + dy * s, -dx * s + dy * c
if back - margin - 0.13 < fx < front + margin + 0.13 and abs(fy) < half + margin + 0.13:
return False
fx, fy = np.meshgrid(np.arange(back - margin, front + margin + 0.01, 0.05), np.arange(-half - margin, half + margin + 0.01, 0.05))
pts = np.stack([x + fx.ravel() * c - fy.ravel() * s, y + fx.ravel() * s + fy.ravel() * c], axis=1)
return not self.in_map(pts).any()
def grow(mask, cells):
"""Grow the occupied cells of a grid by `cells` in every direction."""
out = mask.copy()
padded = np.pad(mask, cells)
h, w = mask.shape
for dy in range(-cells, cells + 1):
for dx in range(-cells, cells + 1):
if dx * dx + dy * dy <= cells * cells:
out |= padded[cells + dy:cells + dy + h, cells + dx:cells + dx + w]
return out
def floor_scan(lime, world, step=2):
"""One look with the depth camera: every thing on the floor that is not in the map.
depth image -> 3D points (camera model + TF, like tutorial 13's locate())
-> drop the floor (lower than 1.2 cm) and what the map has (walls, pillar, crate, divider)
-> group the rest into things (neighbouring 5 cm cells belong together)
"""
msg = lime.depth[max(lime.depth)] # the newest depth image
depth = np.frombuffer(msg.data, dtype=np.float32).reshape(msg.height, msg.width)[::step, ::step]
v, u = np.mgrid[0:msg.height:step, 0:msg.width:step]
ok = np.isfinite(depth) & (depth > 0.3) & (depth < 2.0) # closer than 30 cm: maybe the robot's own arm
fx, fy, px, py = lime.K[0, 0], lime.K[1, 1], lime.K[0, 2], lime.K[1, 2]
z = depth[ok]
cam = np.stack([(u[ok] - px) * z / fx, (v[ok] - py) * z / fy, z], axis=1)
tf = lime.tf.lookup_transform("odom", msg.header.frame_id, msg.header.stamp, timeout=rclpy.duration.Duration(seconds=1.0))
t, q = tf.transform.translation, tf.transform.rotation
pts = cam @ quat_to_matrix(q.x, q.y, q.z, q.w).T + np.array([t.x, t.y, t.z])
pts = pts[(pts[:, 2] > 0.012) & (pts[:, 2] < 0.30)] # not the floor
pts = pts[~world.in_map(pts[:, :2], layer="near")] # not the walls, the pillar, ... (or within 15 cm of them)
cells = {}
for i, cell in enumerate(map(tuple, np.floor(pts[:, :2] / 0.05).astype(int))):
cells.setdefault(cell, []).append(i)
things, todo = [], set(cells)
while todo: # flood fill: one group of touching cells = one thing
group, stack = [], [todo.pop()]
while stack:
cx, cy = stack.pop()
group += cells[(cx, cy)]
for n in ((cx + a, cy + b) for a in (-1, 0, 1) for b in (-1, 0, 1)):
if n in todo:
todo.remove(n)
stack.append(n)
if len(group) >= 40: # a banana 1.4 m away gives about 120; fewer: noise at the edge of a wall or pillar
things.append((pts[group, :2].mean(axis=0), len(group)))
return things
class LookAround(Action):
"""Turn round once, in six steps of 60 deg (the camera sees 69 deg), and scan the floor at each."""
def __init__(self, lime, world):
super().__init__("Look around")
self.lime, self.world = lime, world
def run(self):
_, _, yaw = self.lime.pose()
for k in range(6):
if self.stop_requested:
return False
self.lime.turn_to(wrap(yaw + k * math.pi / 3))
self.lime.spin_for(0.6) # a fresh depth image
for xy, points in floor_scan(self.lime, self.world):
self.world.note(xy, points)
new = [t for t in self.world.things if t.state == "new"]
self.lime.log.info(f"things to check: {', '.join(t.describe() for t in new) or 'none'}")
self.world.tell_nav2()
return True
class NextThing(py_trees.behaviour.Behaviour):
"""Choose the nearest thing that has not been checked yet. FAILURE when there is none left."""
def __init__(self, lime, world):
super().__init__("Next thing to check")
self.lime, self.world = lime, world
self.blackboard = self.attach_blackboard_client(name=self.name)
self.blackboard.register_key(key="thing", access=Access.WRITE)
def update(self):
new = [t for t in self.world.things if t.state == "new"]
if not new:
return Status.FAILURE
x, y, _ = self.lime.pose()
self.blackboard.thing = min(new, key=lambda t: np.hypot(t.xy[0] - x, t.xy[1] - y))
self.feedback_message = str(self.blackboard.thing)
return Status.SUCCESS
class ChooseViewpoint(py_trees.behaviour.Behaviour):
"""A free spot VIEW metres from the thing, facing it, on the side the robot comes from -> blackboard 'goal'."""
def __init__(self, lime, world):
super().__init__("Choose where to look from")
self.lime, self.world = lime, world
self.blackboard = self.attach_blackboard_client(name=self.name)
self.blackboard.register_key(key="thing", access=Access.READ)
self.blackboard.register_key(key="goal", access=Access.WRITE)
def update(self):
thing = self.blackboard.thing
x, y, _ = self.lime.pose()
here = math.atan2(y - thing.xy[1], x - thing.xy[0]) # the robot's direction, seen from the thing
for a in sorted((k * math.pi / 12 for k in range(24)), key=lambda a: abs(wrap(a - here))):
vx, vy = thing.xy + VIEW * np.array([math.cos(a), math.sin(a)])
if self.world.free(vx, vy, a + math.pi, margin=NAV2_ROOM):
self.blackboard.goal = self.world.to_map(vx, vy, a + math.pi)
self.feedback_message = f"({vx:.2f}, {vy:.2f})"
return Status.SUCCESS
thing.state = "left"
self.feedback_message = f"no free spot to look at the {thing} from"
return Status.FAILURE
class WhatIsIt(Action):
"""Face the thing and ask YOLO: the most confident detection whose 3D points lie on the thing."""
def __init__(self, lime, world):
super().__init__("What is it?")
self.lime, self.world = lime, world
self.blackboard = self.attach_blackboard_client(name=self.name)
self.blackboard.register_key(key="thing", access=Access.READ)
def run(self):
thing, lime = self.blackboard.thing, self.lime
x, y, _ = lime.pose()
away = np.array([x, y]) - thing.xy
if np.linalg.norm(away) > VIEW + 0.08: # Nav2 stops within 25 cm of its goal: the last bit by odometry
lime.drive_to(*(thing.xy + VIEW * away / np.linalg.norm(away)))
x, y, _ = lime.pose()
lime.turn_to(math.atan2(thing.xy[1] - y, thing.xy[0] - x))
lime.detections.clear()
lime.spin_for(3.0)
best = None
for msg, depth_msg in lime.detections:
for d in msg.detections:
h = d.results[0].hypothesis
pts, _camera = lime.points(d, msg.header, depth_msg)
if pts is not None and np.linalg.norm(np.median(pts[:, :2], axis=0) - thing.xy) < 0.15:
if best is None or h.score > best[0]:
best = (h.score, h.class_id)
thing.what = best[1] if best else "unknown"
lime.log.info(f"YOLO: {thing}" + (f" ({best[0]:.2f})" if best else ""))
self.world.tell_nav2()
return True
class IsBanana(py_trees.behaviour.Behaviour):
def __init__(self):
super().__init__("Is it a banana?")
self.blackboard = self.attach_blackboard_client(name=self.name)
self.blackboard.register_key(key="thing", access=Access.READ)
def update(self):
return Status.SUCCESS if self.blackboard.thing.what == "banana" else Status.FAILURE
class LeaveIt(Action):
"""The fallback: it is not a banana, or something went wrong - remember it as checked and carry on.
(Still holding it? Then put it down first.)"""
def __init__(self, lime, world):
super().__init__("Leave it")
self.lime, self.world = lime, world
self.blackboard = self.attach_blackboard_client(name=self.name)
self.blackboard.register_key(key="thing", access=Access.READ)
def run(self):
thing = self.blackboard.thing
if thing.state == "carried":
self.lime.gripper(GRIPPER_OPEN)
self.lime.move_arm(HOME, "arm folded")
thing.state = "left"
self.lime.log.info(f"leave the {thing}")
self.world.tell_nav2()
return True
class PickUp(Action):
"""Tutorial 13's grasp, from wherever the robot stands: look from two sides, drive up blind, grasp, lift."""
def __init__(self, lime, world):
super().__init__("Pick it up")
self.lime, self.world = lime, world
self.blackboard = self.attach_blackboard_client(name=self.name)
self.blackboard.register_key(key="thing", access=Access.READ)
def run(self):
lime, world, thing = self.lime, self.world, self.blackboard.thing
# 1. First look, from where Nav2 brought the robot.
looks = [self.look()]
if looks[0] is None:
return self.fail("YOLO: lost the banana")
centre, first_axis = long_object(looks[0])
thing.xy = centre # YOLO's points are better than the floor scan's
first = math.atan2(*(looks[0]["camera"] - centre)[::-1]) # where the first look came from
# 2. Second look, from 45 to 135 deg further round (90 is best). One look sees only the banana's near
# side, and seen nearly end-on, its direction comes out 25 deg wrong. Together they see all of it.
def second_look_cost(a): # how far from 90 deg round from the first look; None: not 45..135 deg
round_by = abs(wrap(a - first))
return abs(round_by - math.pi / 2) if math.pi / 4 < round_by < 3 * math.pi / 4 else None
second = self.spot(centre, second_look_cost)
if second is not None and self.go(centre, second):
looks.append(self.look())
centre, axis = long_object(merge(looks))
lime.log.info(f"banana pointing {math.degrees(axis) % 180:.0f} deg from {len(looks)} looks "
f"(the first alone: {math.degrees(first_axis) % 180:.0f} deg)")
# 3. The grasp side: as far off the banana's axis as possible, and at least 24 deg (closer to end-on, the
# banana's near end would be under the robot's front; tutorial 13 grasped from 26 deg). The robot must
# be able to drive straight up to the grasp position, and Nav2 takes over from there afterwards.
x, y, _ = lime.pose()
here = math.atan2(y - centre[1], x - centre[0])
def grasp_cost(a): # the more across the banana the better, and the nearer the robot's own side
across = abs(math.sin(a - axis)) # 1 = from the side, 0 = end-on
return -across + abs(wrap(a - here)) / math.pi if across > 0.4 else None
side = self.spot(centre, grasp_cost, grasp=True)
if side is None:
return self.fail("no free side to grasp the banana from")
if abs(wrap(side - here)) > math.radians(5):
if not self.go(centre, side):
return self.fail("could not get to the side of the banana")
looks.append(self.look())
centre, banana_yaw = long_object(merge(looks))
lime.log.info(f"YOLO: banana at ({centre[0]:.3f}, {centre[1]:.3f}), pointing {math.degrees(banana_yaw) % 180:.0f} deg "
f"from {len(looks)} looks; grasp from {math.degrees(side):.0f} deg")
# 4. Drive up blind until the banana is GRASP m in front, then tutorial 13's grasp.
look = side + math.pi
toward = np.array([math.cos(look), math.sin(look)])
lime.drive_to(*(centre - GRASP * toward))
lime.turn_to(look)
lime.gripper(GRIPPER_OPEN)
bx, by = lime.to_base(*centre)
yaw = wrap(banana_yaw - lime.pose()[2])
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):
return self.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")):
return self.fail("MoveIt: could not reach down")
lime.gripper(GRIPPER_CLOSED)
if not (lime.move_arm(lifted, "lift") and lime.move_arm(CARRY, "carry")):
return self.fail("MoveIt: could not lift")
lime.spin_for(0.5)
if world.gripper is None or world.gripper < GRIPPER_CLOSED + 0.004: # the fingers closed on nothing
return self.fail(f"missed the banana (gripper at {world.gripper})")
thing.state = "carried"
world.tell_nav2() # it is not on the floor any more
lime.log.info(f"holding the banana (gripper at {world.gripper * 1000:.1f} mm)")
# 5. Leave the way you came: back out to BACK_OUT. Nav2 then starts in the open, not right next to
# whatever stands near the banana (started that close, it can sweep the robot's back into it).
lime.drive_to(*(centre - BACK_OUT * toward), backwards=True)
return True
def look(self):
"""Face the banana and locate it (tutorial 13)."""
x, y, _ = self.lime.pose()
thing = self.blackboard.thing
self.lime.turn_to(math.atan2(thing.xy[1] - y, thing.xy[0] - x))
return self.lime.locate("banana", seconds=3.0)
def spot(self, centre, cost, grasp=False):
"""The direction a (from the banana) of the best free spot SIDE m away; cost(a) = None: not allowed.
For the grasp, the whole straight line from BACK_OUT to the grasp position must be free too, and Nav2
needs more room at BACK_OUT (it takes over from there after the grasp)."""
return best_spot(self.world, self.blackboard.thing, centre, cost, grasp)
def go(self, centre, a):
"""To the spot SIDE m from the banana in direction a, facing it: a straight drive if the way is free
(the banana counts as in the way, too), else Nav2."""
lime, world = self.lime, self.world
x, y, _ = lime.pose()
spot = centre + SIDE * np.array([math.cos(a), math.sin(a)])
heading = math.atan2(spot[1] - y, spot[0] - x)
if not all(world.free(*p, heading) for p in np.linspace([x, y], spot, 10)):
if not navigate(lime, world.to_map(*spot, a + math.pi), stop=lambda: self.stop_requested):
return False
lime.drive_to(*spot)
lime.turn_to(a + math.pi)
return True
def fail(self, why):
"""Let go, fold the arm and back off, so that the next try (or the next thing) starts clean."""
self.feedback_message = why
self.lime.gripper(GRIPPER_OPEN)
self.lime.move_arm(HOME, "arm folded")
x, y, yaw = self.lime.pose()
self.lime.drive_to(x - 0.15 * math.cos(yaw), y - 0.15 * math.sin(yaw), backwards=True)
return False
class FindBowl(Action):
"""At the start: where is the fruit bowl? (YOLO + depth, tutorial 13)"""
def __init__(self, lime, world):
super().__init__("Find the fruit bowl")
self.lime, self.world = lime, world
def run(self):
found = self.lime.locate("bowl", seconds=3.0)
if found is None:
return False
self.world.bowl, _radius = round_object(found)
self.lime.log.info(f"YOLO: bowl ({found['score']:.2f}) at ({self.world.bowl[0]:.2f}, {self.world.bowl[1]:.2f})")
self.world.tell_nav2()
return True
class ChooseBowlSide(py_trees.behaviour.Behaviour):
"""The nearest free spot BOWL_APPROACH m from the bowl with room around it (30 cm to any thing), or else
the one with the most room -> blackboard 'goal'."""
def __init__(self, lime, world):
super().__init__("Choose a side of the bowl")
self.lime, self.world = lime, world
self.blackboard = self.attach_blackboard_client(name=self.name)
self.blackboard.register_key(key="goal", access=Access.WRITE)
self.blackboard.register_key(key="bowl_side", access=Access.WRITE)
def update(self):
bowl, sides = self.world.bowl, []
x, y, _ = self.lime.pose()
for a in (k * math.pi / 8 for k in range(16)):
p = bowl + BOWL_APPROACH * np.array([math.cos(a), math.sin(a)])
if self.world.free(*p, a + math.pi, ignore="bowl", margin=NAV2_ROOM):
room = min([np.linalg.norm(t.xy - p) for t in self.world.things if t.state != "carried"] + [9.0])
sides.append((room, np.hypot(p[0] - x, p[1] - y), a))
if not sides:
return Status.FAILURE
roomy = [s for s in sides if s[0] > 0.30]
a = min(roomy, key=lambda s: s[1])[2] if roomy else max(sides)[2]
self.feedback_message = f"{math.degrees(a):.0f} deg"
self.blackboard.bowl_side = a
self.blackboard.goal = self.world.to_map(*(bowl + BOWL_APPROACH * np.array([math.cos(a), math.sin(a)])), a + math.pi)
return Status.SUCCESS
class PutInBowl(Action):
"""Tutorial 13's release: line up with the bowl, banana across the robot, above the bowl's centre, open."""
def __init__(self, lime, world):
super().__init__("Put it in the bowl")
self.lime, self.world = lime, world
self.blackboard = self.attach_blackboard_client(name=self.name)
self.blackboard.register_key(key="thing", access=Access.READ)
self.blackboard.register_key(key="bowl_side", access=Access.READ)
def run(self):
lime, world, a = self.lime, self.world, self.blackboard.bowl_side
out = np.array([math.cos(a), math.sin(a)]) # from the bowl towards the robot
lime.drive_to(*(world.bowl + BOWL_APPROACH * out))
lime.turn_to(a + math.pi)
found = lime.locate("bowl")
bowl = round_object(found)[0] if found else world.bowl
lime.drive_to(*(bowl + BOWL_RELEASE * out))
lime.turn_to(a + math.pi)
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.14, math.pi / 2))), None)
if release is None or not lime.move_arm(release, "above the bowl"):
return False
lime.gripper(GRIPPER_OPEN)
lime.spin_for(1.0)
lime.move_arm(HOME, "arm folded")
lime.drive_to(*(bowl + BOWL_APPROACH * out), backwards=True) # leave the way you came
self.blackboard.thing.state = "tidied"
lime.log.info(f"tidied: the {self.blackboard.thing}")
return True
def best_spot(world, thing, centre, cost, grasp=False):
"""PickUp.spot() (a function, so that it can be tried without a robot)."""
best = None
for a in (k * math.pi / 12 for k in range(24)):
c = cost(a)
if c is None:
continue
d = np.array([math.cos(a), math.sin(a)])
line = np.arange(BACK_OUT, GRASP - 0.001, -0.05) if grasp else [SIDE]
if grasp and not world.free(*(centre + BACK_OUT * d), a + math.pi, ignore=thing, margin=NAV2_ROOM):
continue
# the last drive, from SIDE up to the banana, is slow and centimetre-accurate (odometry): 2 cm margin is enough
if all(world.free(*(centre + r * d), a + math.pi, ignore=thing, margin=0.02 if grasp and r < SIDE + 0.01 else 0.05) for r in line) and (
best is None or c < best[0]
):
best = (c, a)
return None if best is None else best[1]
def navigate(lime, goal, stop=lambda: False):
"""Nav2 to a map-frame pose, from inside an Action."""
x, y, yaw = goal
pose = PoseStamped()
pose.header.frame_id = "map"
pose.header.stamp = lime.nav.get_clock().now().to_msg()
pose.pose.position.x, pose.pose.position.y = x, y
pose.pose.orientation.z, pose.pose.orientation.w = math.sin(yaw / 2), math.cos(yaw / 2)
if not lime.nav.goToPose(pose):
return False
while not lime.nav.isTaskComplete():
if stop():
lime.nav.cancelTask()
return False
from nav2_simple_commander.robot_navigator import TaskResult
return lime.nav.getResult() == TaskResult.SUCCEEDED
def build_tree(lime, world):
blackboard = py_trees.blackboard.Client(name="tidy")
blackboard.register_key(key="lookouts", access=Access.WRITE)
blackboard.lookouts = LOOKOUTS
Seq, Sel = py_trees.composites.Sequence, py_trees.composites.Selector
tidy_banana = Seq("Tidy the banana", memory=True, children=[
IsBanana(),
py_trees.decorators.Retry("Up to 3 tries", PickUp(lime, world), num_failures=3),
ChooseBowlSide(lime, world),
NavigateTo("Carry it to the bowl", lime, key="goal"),
PutInBowl(lime, world),
])
check_thing = Seq("Check the next thing", memory=True, children=[
NextThing(lime, world), # FAILURE when nothing is left: ends the loop below
Sel("Tidy it or leave it", memory=True, children=[
Seq("Go and look", memory=True, children=[
ChooseViewpoint(lime, world),
NavigateTo("Drive up to it", lime, key="goal"),
WhatIsIt(lime, world),
tidy_banana,
]),
LeaveIt(lime, world),
]),
])
at_lookout = Seq("At the lookout", memory=True, children=[
Sel("Get there", memory=True, children=[
py_trees.decorators.Retry("Up to 2 tries", NavigateTo("Go to the lookout", lime, key="lookout"), num_failures=2),
py_trees.behaviours.Success("Skip it"),
]),
LookAround(lime, world),
py_trees.decorators.FailureIsSuccess("Until nothing is left", py_trees.decorators.Repeat("Repeat", check_thing, num_success=-1)),
])
return Seq("Tidy the room", memory=True, children=[
FindBowl(lime, world),
py_trees.decorators.ForEach("Every lookout", at_lookout, source_key="lookouts", target_key="lookout"),
NavigateTo("Go home", lime, pose=HOME_POSE),
])
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--render", metavar="DIR", help="only draw the tree into DIR (tidy.png / .svg / .dot)")
args, _ros = parser.parse_known_args()
if args.render:
py_trees.display.render_dot_tree(build_tree(None, None), target_directory=args.render, name="tidy")
return
rclpy.init()
lime = Lime()
world = World(lime)
start = PoseStamped()
start.header.frame_id = "map"
start.header.stamp = lime.nav.get_clock().now().to_msg()
start.pose.orientation.w = 1.0
lime.nav.setInitialPose(start) # 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)):
lime.log.error("MoveIt / gripper action servers not available")
lime.close()
sys.exit(1)
lime.add_floor()
while world.map is None or lime.K is None or not lime.depth:
lime.spin_for(0.5)
t0 = time.time()
status = run_tree(build_tree(lime, world), lime.log)
tidied = [t for t in world.things if t.state == "tidied"]
lime.log.info(f"{'room tidy' if status == Status.SUCCESS else 'FAILED'}: {len(tidied)} bananas in the bowl, {time.time() - t0:.0f} s")
lime.close()
sys.exit(0 if status == Status.SUCCESS else 1)
from mission import CARRY, GRIPPER_CLOSED, GRIPPER_OPEN, HOME, Lime, long_object, quat_to_matrix, round_object, top_down_ik, wait_until_nav2_active # noqa: E402
if __name__ == "__main__":
main()
作る過程でうまくいかなかったこと(とその対処)¶
これらのほとんどは、マグカップとボトルが 1 本目のバナナから 30 cm のところにあった最初のバージョンで起きました。対処はそのまま残してあります。物が近くに集まっている場所ではどこでも、これらの対処がロボットを慎重にしてくれます。
11 個の問題とその対処
| 症状 | 原因 | 対処 |
|---|---|---|
| YOLO が 1 m 先のバナナを frisbee や sports ball と判定した | 床から 5.8 cm の高さから見ると、横たわったバナナは細い黄色の線にすぎない | 深度カメラで物を見つけ、YOLO は 55 cm の距離からチェックする |
| Nav2 が各ゴールに向かってのろのろ進み、最後に諦めた:「Failed to make progress」 | ゴールの許容誤差が 10 cm だった。MPPI が最後の数センチメートルをゆっくり進むため、進捗チェッカー(10 s で 0.5 m)に引っかかった | Jazzy の 25 cm にする。最後の数センチメートルはミッション自身がオドメトリで動く |
| 把持の直後、ロボットがマグカップを小突いた | マグカップのすぐ隣で Nav2 に引き継いだ | 来た道を後退してから Nav2 に任せる |
| Nav2 がボトルを部屋の中で 1.8 m 押していった | MPPI は base_footprint を中心とする円しかチェックしていなかった。一度触れると、ボトルは LiDAR (12 cm) にもカメラ (35 cm) にも近すぎた |
consider_footprint: true、そして余裕として /known_things に物の円を描く |
| ロボットがボウルにバックでぶつかり、動けなくなった | カメラは 35 cm 以内のセルをクリアした(壁に向かう光線は、2D ではボウルの上を通過する)が、マークはしなかったので、ボウルがコストマップから消えた | raytrace_min_range: 0.35 も設定する。カメラの近くではマークもクリアもしない |
| それでも Nav2 は、カメラが一度も見ていない側から来てマグカップをかすめた | カメラは物の見えた側しかマークしない | ミッションが知っている物を、コストマップのレイヤーである /known_things に描き込む |
| ミッションが選んだ場所から Nav2 が出られなかった | ミッションが選んだ場所は、素のフットプリントなら空いていたが、Nav2 にとっては狭すぎた | Nav2 が出発または停止するすべての場所のまわりに 10 cm の余裕を取る |
| 散らかった隅からバナナを運び出すとき、Nav2 がほとんど動かず、諦めた | 5 cm のフットプリントのパディングには 0.45 m のインフレーション半径が必要で、それがその隅のほとんどにコストを載せた。MPPI はのろのろ進む(よくても 45 s で 1.1 m)か、止まった | パディングとインフレーションは標準に戻し、余裕は /known_things から取る。最終的には、マグカップとボトルを邪魔にならない場所に移した(運び出しは 14〜27 s になった) |
| 柱の角に「物」が見つかった | 柱の縁にある少数の深度の点 | 2 m 先までしか見ない。また、1 つの物と認めるには深度の点が 40 個以上必要 |
| バナナがグリッパーから滑り落ちた、または指が何もないところで閉じた | 2 回目の観察が 1 回目とほぼ同じ方向からだった。端から見ると、バナナの向きが 25° ずれて求まり(20° ではなく 41°)、把持が斜めになった | 45〜135° 回り込んだ位置から 2 回目の観察を行い、すべての観察の点をまとめて使う (18°)。最大 3 回試す |
| ミッションのメモリが 1.1 GB まで増えた | チュートリアル 13 の Lime が、すべての検出結果を深度画像ごと保持していた |
最新の 60 個だけを保持する |
この先へ¶
- もっと多くの種類の物:
WhatIsItはすでにボトルとバナナを見分けています。クラスごとに置き場所を決めましょう。ボトルはリサイクルへ、おもちゃはおもちゃ箱へ。ツリーには Selector が 1 つ増えます:「これはどの仕事か?」 - ツリーをリアルタイムで見る: py_trees 自身のものではなく
py_trees_ros.trees.BehaviourTreeでツリーを tick します(py_trees_rosはコンテナに入っています)。これはツリーをパブリッシュするので、ミッションの実行中にpy-trees-tree-watcherコマンドで、すべてのステータスとともにツリーを表示できます。 - 巡回ではなく探索する: 見回り地点は固定です。実際のロボットなら、まだ見ていない場所をもとに次の見回り地点を選ぶでしょう(フロンティア探索)。
- SLAM: 先にチュートリアル 14 で地図を作り、チュートリアル 11 の地図の代わりに Nav2 に渡します(
lime_full.launch.pyの Nav2 の include のmap引数)。