Skip to content

16 · All together: tidy the room

⏱ 60 min · Level: advanced · Script: isaac/16_tidy_room.py · ROS: tidy.launch.py, tidy

Goal. A real job for the Lime, with everything from tutorials 06–15 at once. Three bananas lie around the lime_room, and the robot doesn't know where. It must find every one, pick it up, put it into the fruit bowl, and go home. Nav2 drives it from lookout to lookout, the depth camera spots things on the floor, YOLO says what they are, MoveIt picks and places, and a behavior tree (tutorial 15) decides what to do next.

The whole job, about 7½ minutes of simulated time, sped up about 8×. The camera follows the robot: it picks up the first banana and puts it into the bowl, checks the mug in the corner (leave it), finds the banana behind the pillar, checks the bottle (leave it), finds the banana behind the divider, and comes home.

The three bananas in the bowl

The fruit bowl at the end: all three bananas.

The job

Tutorial 13 picked up one banana that the robot could see from its start. Here:

Tutorial 13 Tutorial 16
Bananas one, in front of the robot three: one in front, one behind the pillar, one behind the divider
Where they are YOLO sees it from the start unknown: the robot has to search
The mug and the bottle next to the banana, in the way out of the way, towards the corners: things to find, check and leave alone
Driving odometry; Nav2 only to park Nav2 between all the places, centimetre moves by odometry
The mission a script: step 1, step 2, ... a behavior tree: search, check, retry, leave it

The robot knows the map (tutorial 11) and three lookouts: places from which it can see most of the room.

Concepts

Finding things: what is not in the map

YOLO is the obvious tool for "where is a banana?", but from the Lime's camera, 5.8 cm above the floor, a lying banana is a thin yellow line. This is what YOLO (yolo11m.pt) says about one banana, seen from different distances and angles:

Distance 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

So the search uses the depth camera instead, and YOLO only up close:

  1. Find (from a lookout): every depth pixel becomes a 3D point (tutorial 13's camera model and TF). Drop the floor, and drop everything the map already has: the walls, the pillar, the crate, the divider. What is left is new: things on the floor. Neighbouring points are grouped into one thing each.
  2. Check (up close): Nav2 drives to 55 cm from each thing, and YOLO says what it is.
  3. Act: a banana goes into the bowl; anything else stays where it is.

This is tutorial 11's rule again: the map is for what stays put. Anything that is not in the map is either an obstacle or a job.

In tutorial 11, Nav2's costmaps got their obstacles from the LiDAR, which scans 16 cm above the floor. A banana (4 cm), the mug (8 cm) and the bowl (8 cm) are invisible to it, and Nav2 would drive right over them. A real robot adds its depth camera to the costmaps, and so does this tutorial:

  • Isaac Sim publishes a small point cloud from the depth camera: a second render product of the same camera, 160 × 120 pixels, 10 times a second (create_depth_cloud_graph, new in graphs.py).
  • Nav2 (config/nav2_params_tidy.yaml) gets one more costmap layer, depth_layer, in both costmaps.
create_depth_cloud_graph() in isaac/common/graphs.py
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}
Parameter Why
a layer of its own the LiDAR's layer clears every cell its beams pass through. Its beams pass over a banana, so a shared layer would erase what the camera marked
VoxelLayer, 10 voxels of 5 cm 3D: a camera ray to the wall behind the mug passes over the mug and clears only the voxels it really passes through. In a flat (2D) layer, every look past the mug would erase it, and only the side last seen would remain
min_obstacle_height: 0.015 everything 1.5 cm above the floor or higher is an obstacle; the floor itself is not
obstacle_min_range, raytrace_min_range: 0.35 closer than 35 cm, the camera neither marks (that is the robot's own arm and gripper when it grasps) nor clears (what it saw from further away stays)
obstacle_max_range, raytrace_max_range: 2.5 the same: what the camera clears, it can also mark

What the robot knows, it tells Nav2. The camera only ever sees the near side of a thing. In the first version of this tutorial (see the scene), the robot found the mug from the west, so the costmaps held the mug's west side, and Nav2, coming past from the east, drove into the rest of it. The mission, though, knows the whole mug: it is in its list of things. So it draws every thing it knows about as a disc into a second map, /known_things, the same size as /map, and both costmaps read it as one more layer (things_layer, a StaticLayer, combined by maximum). When a banana is picked up, its disc goes; the mug and the bottle stay. It is tutorial 11's rule once more: /map holds what stays put, /known_things what the robot has found on the floor.

things_layer: {plugin: 'nav2_costmap_2d::StaticLayer', map_topic: /known_things, map_subscribe_transient_local: true, use_maximum: true}

RViz: the global costmap after the first look around

RViz (tidy.launch.py) after the first look around, the global costmap:

  1. The robot, driving up to the banana to check it.
  2. The first banana: a disc (magenta) with its inflation.
  3. The bowl, the same.
  4. The mug in its corner, the same. It is far beyond the reach of Nav2's sensors here: it is in the costmap because the mission told Nav2 about it.
  5. The map: the walls, the divider, the crate (here) and the pillar.

Collision checking for the Lime's shape. MPPI's CostCritic normally checks for collisions with a circle round base_footprint (consider_footprint: false). The Lime's base_footprint sits between its wheels, near the front: its base reaches 7.5 cm forward but 20.5 cm back. In the first version, turning next to the mug, its back swept into it. And once something touches the robot, it is closer than the LiDAR's 12 cm minimum range and the camera's 35 cm: nothing marks it any more, and Nav2 pushed the bottle 1.8 m across the room. With consider_footprint: true, MPPI checks the whole footprint.

Keep the inflation radius larger than the footprint

The footprint check only works if inflation_radius (0.30 m) is larger than the footprint's circumscribed radius: 0.28 m for the Lime with the stock 1 cm footprint_padding. A first version padded the footprint by 5 cm (0.33 m). Nav2 then logged "The inflation radius (0.300000) is smaller than the circumscribed radius (0.333542)" 20 times a second and quietly fell back to the circle. Raising the inflation to 0.45 m instead made the carry out of the first version's cluttered corner crawl or fail: MPPI barely moved (1.1 m in 45 s at best). So the padding is back to stock, and the margin round the mug and the bottle comes from where it belongs: their discs in /known_things.

nav2_params_tidy.yaml

It is tutorial 11's nav2_params.yaml with exactly three changes: the depth_layer and the things_layer in both costmaps, and consider_footprint for MPPI. tidy.launch.py is tutorial 13's lime_full.launch.py with this parameter file.

The scene

16_tidy_room.py is tutorial 13's robot in tutorial 13's room (real objects, the 1.5× bowl, grippy fingers), with three changes: the mug and the bottle move out of the way, towards the corners; two more bananas; and the depth cloud.

The first version kept the mug and the bottle where tutorial 13 has them, 30 cm from the first banana. They boxed the banana in: only one side was left to grasp it from, and Nav2 had to squeeze between them on every trip to the bowl. Most of the problems in Things that went wrong came from there. In a real home you would not leave a cup right next to a banana you want a robot to pick up either. Now they are distractions: the robot finds them on its search, checks them with YOLO, and leaves them.

setup_tidy_room() in isaac/common/scene.py
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

The tree

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"])

Each pattern from tutorial 15 has its job here:

  • ForEach walks the lookouts; at each, Look around adds what it finds to the list of things.
  • Repeat until nothing is left: Next thing to check chooses the nearest unchecked thing, and fails when there is none. That failure ends the loop (FailureIsSuccess), and the tree moves on to the next lookout.
  • Tidy it or leave it is a Selector: if anything in Go and look fails (it is not a banana, the grasp failed three times, Nav2 can't get there), Leave it marks the thing as checked, so the robot never gets stuck on one thing.
  • Retry: a missed grasp is tried again (up to three times in all), from a fresh look. A missed grasp usually nudges the banana, so the next try sees it differently.
  • Skip it: a lookout that Nav2 can't reach is skipped.
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),
    ])

The leaves are Actions (tutorial 15) that call tutorial 13's Lime: locate(), drive_to(), turn_to(), move_arm(), gripper(), top_down_ik(), long_object(), round_object(). The only new skill is the floor scan.

What the robot knows

World keeps the map (from /map, as Nav2 has it), the bowl, and the things: each with its position (odom frame, like tutorial 13), what YOLO said it is, and its state (new, tidied, left). free() answers "can the robot stand here?": the Lime's footprint must be clear of the map and of every known thing. The tree uses it to choose where to look from, from which side to grasp, and where to stand at the bowl.

Thing and World in lime_isaac_bringup/scripts/tidy.py
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

Look around: the floor scan

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: six looks, 60° apart
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

Check a thing

Choose where to look from tries 24 directions round the thing, nearest to the robot's side first, and takes the first spot 55 cm away where the robot fits. Nav2 drives there (it stops within 25 cm of its goal, so the last bit is odometry), and What is it? collects 3 s of YOLO detections. A detection belongs to the thing if its 3D points (tutorial 13's points()) lie within 15 cm of it.

YOLO doesn't always have an answer. In its corner, with the wall close behind it, the mug is mostly not recognised at all (from the robot's side, 1 of 12 test views gave cup with more than 0.5). The thing is then unknown. That is fine: Is it a banana? fails, and Leave it is the safe default for anything the robot is not sure about.

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

Pick it up

Tutorial 13's grasp, with the viewpoints chosen instead of fixed. Tutorial 13 always looked again from 55° further round, which suited that one banana from that one start.

  1. First look, from where Nav2 brought the robot (55 cm away).
  2. Second look, from 45–135° further round (90° is best). One look sees only the banana's near side. Seen nearly end-on, a curved banana's direction comes out about 25° wrong, and every decision after that would build on the error. long_object() gets the points of all looks together.
  3. Choose the grasp side: as far off the banana's long axis as possible, and at least 24°. Any closer to end-on and the banana's near end would be under the robot's front. The robot must be able to drive straight in, from 60 cm to the grasp position, without touching anything. Nav2 needs 10 cm of room at the 60 cm point, because it takes over there after the grasp. If that side is a new place, the robot looks once more from there.
  4. Grasp exactly as in tutorial 13, then back out the way you came, to 60 cm. Started right next to the mug, Nav2 swept the robot's back into it.

(With the mug and the bottle 30 cm from the first banana, as in tutorial 13, the only good side left was the one tutorial 13 used, about 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

Put it in the bowl

The bowl is found once, at the start (YOLO sees it from there, as in tutorial 13). For each banana, Choose a side of the bowl takes the nearest free side with 30 cm of room to any other thing, Nav2 carries the banana there, and Put it in the bowl is tutorial 13's release: line up with the bowl, banana across the robot, open the gripper above the bowl's centre (or as close as the arm reaches), fold the arm, and back out.

The bowl holds all three bananas: they pile up, and the third one rests on the other two.

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

Run it

Terminal 1, Isaac Sim:

source scripts/isaac_env.sh
python isaac/16_tidy_room.py

Terminal 2, the ROS 2 stack: tutorial 13's lime_full.launch.py with nav2_params_tidy.yaml (wait for "Managed nodes are active" and "You can start planning now!"):

./scripts/build_ws.sh lime_isaac_bringup
./docker/run_ros.sh ros2 launch lime_isaac_bringup tidy.launch.py

Terminal 3, the mission:

./docker/run_ros.sh ros2 run lime_isaac_bringup tidy

The mission prints what it finds and every behaviour of the tree that succeeds (ok) or fails (FAIL), with how long it took (wall-clock seconds; on the test PC the simulation ran at about half real time). The start, with the first banana:

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

The banana first, because it is nearest; then the mug, which YOLO doesn't recognise from here (unknown): not a banana, so it stays. Next thing to check fails, nothing is left here, and the tree moves on to the next lookout:

[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

The first banana really is at (0.80, −0.12), pointing 20°. Seen from the first spot alone, nearly end-on, its direction came out as 47°; with the second look from about 90° further round, 16°.

Automatic check

python isaac/16_tidy_room.py --headless --test follows the mission with the simulation's ground truth: when each banana is lifted and when it comes to rest in the bowl, whether the robot comes home, and whether it touched the mug or the bottle. A banana counts as in the bowl if its centre is within 10 cm of the bowl's centre (the rim is at 12 cm) and it rests there. tools/run_all_checks.sh 16 starts tidy.launch.py and the mission:

[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

The whole job takes about 7½ minutes of simulated time.

Isaac Sim side: 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)
The launch file: 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(),
            ),
        ]
    )
The whole mission: 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()

Things that went wrong while building this (and the fixes)

Most of these happened in the first version, with the mug and the bottle 30 cm from the first banana. The fixes stayed: they make the robot careful wherever things stand close together.

Eleven problems and their fixes
Symptom Cause Fix
YOLO called a banana 1 m away a frisbee or a sports ball from 5.8 cm above the floor, a lying banana is a thin yellow line the depth camera finds things, YOLO checks them from 55 cm
Nav2 crept towards each goal and then gave up: "Failed to make progress" a goal tolerance of 10 cm: MPPI's slow last centimetres tripped the progress checker (0.5 m in 10 s) Jazzy's 25 cm; the mission does the last centimetres itself, by odometry
Right after a grasp, the robot nudged the mug Nav2 took over right next to the mug back out the way you came, then Nav2
Nav2 pushed the bottle 1.8 m across the room MPPI checked only a circle round base_footprint; once touching, the bottle was too close for the LiDAR (12 cm) and the camera (35 cm) consider_footprint: true, and the things' discs in /known_things as the margin
The robot backed into the bowl and got stuck the camera cleared the cells within 35 cm (its rays to the walls pass over the bowl, in 2D) but did not mark them, so the bowl vanished from the costmap raytrace_min_range: 0.35 as well: near the camera, neither mark nor clear
Nav2 still brushed the mug, coming from the side the camera had never seen the camera marks only the sides of a thing it has seen the mission draws the things it knows into /known_things, a costmap layer
Nav2 could not leave the spot the mission had chosen the mission's spot was free for the bare footprint, but too tight for Nav2 10 cm of room round every spot where Nav2 starts or stops
Carrying the banana out of the cluttered corner, Nav2 barely moved and gave up a 5 cm footprint padding needed a 0.45 m inflation radius, which put cost on most of that corner; MPPI crept (1.1 m in 45 s at best) or stopped stock padding and inflation, margins from /known_things; in the end, the mug and the bottle out of the way (the carry then took 14–27 s)
A "thing" at the corner of the pillar a few depth points at the pillar's edge look only 2 m far, and a thing needs 40 points
The banana slipped out of the gripper, or the fingers closed on nothing the second look came from nearly the same direction as the first. Seen end-on, the banana's direction came out 25° wrong (41° instead of 20°), so the grasp was crooked a second look from 45–135° further round, with the points of all looks together (18°); up to 3 tries
The mission's memory grew to 1.1 GB tutorial 13's Lime kept every detection, with its depth image keep the last 60

Where to go from here

  • More kinds of things. WhatIsIt already tells bottles from bananas. Give each class its own place: bottles to the recycling, toys into a box. The tree gets one more Selector: which job is this?
  • Watch the tree live. Tick the tree with py_trees_ros.trees.BehaviourTree instead of py_trees' own (py_trees_ros is in the container): it publishes the tree, and the py-trees-tree-watcher command shows it, with every status, while the mission runs.
  • Find instead of patrol. The lookouts are fixed. A real robot would choose the next lookout from what it has not seen yet (frontier exploration).
  • SLAM. Make the map with tutorial 14 first, and give it to Nav2 instead of tutorial 11's map (the map argument of the Nav2 include in lime_full.launch.py).