|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +# Copyright 2025 The HuggingFace Inc. team. All rights reserved. |
| 4 | +# |
| 5 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | +# you may not use this file except in compliance with the License. |
| 7 | +# You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +# limitations under the License. |
| 16 | + |
| 17 | +import logging |
| 18 | +import time |
| 19 | +from functools import cached_property |
| 20 | +from typing import Any |
| 21 | + |
| 22 | +from lerobot.common.cameras.utils import make_cameras_from_configs |
| 23 | +from lerobot.common.robots.utils import make_robot_from_config |
| 24 | + |
| 25 | +from ..robot import Robot |
| 26 | +from .config_multi_arm_follower import MultiArmFollowerConfig |
| 27 | + |
| 28 | +logger = logging.getLogger(__name__) |
| 29 | + |
| 30 | + |
| 31 | +class MultiArmFollower(Robot): |
| 32 | + """ |
| 33 | + Multiple Arms Follower. |
| 34 | + """ |
| 35 | + |
| 36 | + config_class = MultiArmFollowerConfig |
| 37 | + name = "multi_arm_follower" |
| 38 | + |
| 39 | + def __init__(self, config: MultiArmFollowerConfig): |
| 40 | + super().__init__(config) |
| 41 | + self.config = config |
| 42 | + |
| 43 | + self.arms = [make_robot_from_config(arm_config) for arm_config in config.arms] |
| 44 | + |
| 45 | + self.cameras = make_cameras_from_configs(config.cameras) |
| 46 | + |
| 47 | + def _encode_arm_index(self, key: str, index: int) -> str: |
| 48 | + return f"arm{index}__{key}" |
| 49 | + |
| 50 | + def _decode_arm_index(self, key: str) -> int: |
| 51 | + arm_id, *remaining = key.split("__") |
| 52 | + assert arm_id.startswith("arm"), (arm_id, key) |
| 53 | + return int(arm_id[len("arm") :]), "__".join(remaining) |
| 54 | + |
| 55 | + @cached_property |
| 56 | + def observation_features(self) -> dict[str, type | tuple]: |
| 57 | + # Get quickly all observation_features |
| 58 | + # assuming minimal latency due the loop |
| 59 | + all_observations = [arm.observation_features for arm in self.arms] |
| 60 | + # Post-process the results: |
| 61 | + all_observations = [ |
| 62 | + {self._encode_arm_index(key, i): value for key, value in obs.items()} |
| 63 | + for i, obs in enumerate(all_observations) |
| 64 | + ] |
| 65 | + return {k: v for obs_ft in all_observations for k, v in obs_ft.items()} |
| 66 | + |
| 67 | + @cached_property |
| 68 | + def action_features(self) -> dict[str, type]: |
| 69 | + # Get quickly all action_features |
| 70 | + # assuming minimal latency due the loop |
| 71 | + all_actions = [arm.action_features for arm in self.arms] |
| 72 | + # Post-process the results: |
| 73 | + all_actions = [ |
| 74 | + {self._encode_arm_index(key, i): value for key, value in actions.items()} |
| 75 | + for i, actions in enumerate(all_actions) |
| 76 | + ] |
| 77 | + return {k: v for actions in all_actions for k, v in actions.items()} |
| 78 | + |
| 79 | + @property |
| 80 | + def is_connected(self) -> bool: |
| 81 | + all_arms_connected = all(arm.is_connected for arm in self.arms) |
| 82 | + return all_arms_connected and all(cam.is_connected for cam in self.cameras.values()) |
| 83 | + |
| 84 | + def connect(self, calibrate: bool = True) -> None: |
| 85 | + """ |
| 86 | + We assume that at connection time, arms are in a rest position, |
| 87 | + and torque can be safely disabled to run calibration. |
| 88 | + """ |
| 89 | + for arm in self.arms: |
| 90 | + arm.connect(calibrate=calibrate) |
| 91 | + |
| 92 | + for cam in self.cameras.values(): |
| 93 | + cam.connect() |
| 94 | + |
| 95 | + logger.info(f"{self} connected.") |
| 96 | + |
| 97 | + @property |
| 98 | + def is_calibrated(self) -> bool: |
| 99 | + return all(arm.is_calibrated for arm in self.arms) |
| 100 | + |
| 101 | + def calibrate(self) -> None: |
| 102 | + logger.info(f"\nRunning calibration of {self}") |
| 103 | + for arm in self.arms: |
| 104 | + arm.calibrate() |
| 105 | + |
| 106 | + def configure(self) -> None: |
| 107 | + for arm in self.arms: |
| 108 | + arm.configure() |
| 109 | + |
| 110 | + def setup_motors(self) -> None: |
| 111 | + for arm in self.arms: |
| 112 | + arm.setup_motors() |
| 113 | + |
| 114 | + def get_observation(self) -> dict[str, Any]: |
| 115 | + # Get quickly all observations |
| 116 | + # assuming minimal latency due the loop |
| 117 | + all_observations = [arm.get_observation() for arm in self.arms] |
| 118 | + # Post-process the results: |
| 119 | + all_observations = [ |
| 120 | + {self._encode_arm_index(key, i): value for key, value in obs.items()} |
| 121 | + for i, obs in enumerate(all_observations) |
| 122 | + ] |
| 123 | + obs_dict = {k: v for obs in all_observations for k, v in obs.items()} |
| 124 | + |
| 125 | + # Capture images from cameras |
| 126 | + for cam_key, cam in self.cameras.items(): |
| 127 | + start = time.perf_counter() |
| 128 | + obs_dict[cam_key] = cam.async_read() |
| 129 | + dt_ms = (time.perf_counter() - start) * 1e3 |
| 130 | + logger.debug(f"{self} read {cam_key}: {dt_ms:.1f}ms") |
| 131 | + |
| 132 | + return obs_dict |
| 133 | + |
| 134 | + def send_action(self, action: dict[str, Any]) -> dict[str, Any]: |
| 135 | + """Command arm to move to a target joint configuration. |
| 136 | +
|
| 137 | + The relative action magnitude may be clipped depending on the configuration parameter |
| 138 | + `max_relative_target`. In this case, the action sent differs from original action. |
| 139 | + Thus, this function always returns the action actually sent. |
| 140 | +
|
| 141 | + Raises: |
| 142 | + RobotDeviceNotConnectedError: if robot is not connected. |
| 143 | +
|
| 144 | + Returns: |
| 145 | + the action sent to the motors, potentially clipped. |
| 146 | + """ |
| 147 | + action_per_arm = [None] * len(self.arms) |
| 148 | + for key in action: |
| 149 | + index, base_key = self._decode_arm_index(key) |
| 150 | + if action_per_arm[index] is None: |
| 151 | + action_per_arm[index] = {base_key: action[key]} |
| 152 | + else: |
| 153 | + action_per_arm[index][base_key] = action[key] |
| 154 | + |
| 155 | + output = [ |
| 156 | + arm.send_action(action_per_arm) |
| 157 | + for arm, action_per_arm in zip(self.arms, action_per_arm, strict=False) |
| 158 | + ] |
| 159 | + output = [ |
| 160 | + {self._encode_arm_index(key, i): value for key, value in action.items()} |
| 161 | + for i, action in enumerate(output) |
| 162 | + ] |
| 163 | + return {k: v for action in output for k, v in action.items()} |
| 164 | + |
| 165 | + def disconnect(self): |
| 166 | + for arm in self.arms: |
| 167 | + arm.disconnect() |
| 168 | + |
| 169 | + for cam in self.cameras.values(): |
| 170 | + cam.disconnect() |
| 171 | + |
| 172 | + logger.info(f"{self} disconnected.") |
0 commit comments