nepyope commited on
Commit
cac8468
·
verified ·
1 Parent(s): 448ecc8

Asimov 1 MuJoCo sim: the G1 sim with Asimov's model and an Asimov Edge emulation

Browse files
.gitattributes CHANGED
@@ -1,35 +1,3 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
1
+ *.png filter=lfs diff=lfs merge=lfs -text
2
+ *.STL filter=lfs diff=lfs merge=lfs -text
3
+ *.stl filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.gitignore ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ __pycache__/
2
+ .pytest_cache/
3
+ *.pyc
4
+ MUJOCO_LOG.TXT
README.md ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ tags:
3
+ - lerobot
4
+ - mujoco
5
+ - asimov
6
+ - humanoid
7
+ ---
8
+
9
+ # Asimov 1 MuJoCo simulation for LeRobot
10
+
11
+ ![Asimov 1 in the sim](preview/asimov_front.png)
12
+
13
+ Menlo's [Asimov 1](https://github.com/menloresearch/asimov-1) in MuJoCo, built like
14
+ [`lerobot/unitree-g1-mujoco`](https://huggingface.co/lerobot/unitree-g1-mujoco): the
15
+ same simulator loop, elastic band, viewer, ZMQ camera publisher and `make_env()`
16
+ entry point, with the Asimov model in place of the G1.
17
+
18
+ Where the G1 sim speaks Unitree's DDS, this one speaks the robot's own protocol: it
19
+ emulates **Asimov Edge**, the onboard service the Menlo SDK talks to. LeRobot's
20
+ `Asimov` driver therefore connects to the sim exactly as to the real robot, with
21
+ `host=127.0.0.1`.
22
+
23
+ ## Run it
24
+
25
+ ```bash
26
+ pip install -r requirements.txt
27
+ python run_sim.py
28
+ ```
29
+
30
+ The robot starts in STAND, held up by the elastic band with its feet just off the
31
+ floor. In the viewer, **9** releases the band, **7** / **8** lower and raise it.
32
+
33
+ Then, from a LeRobot checkout with the Asimov driver, walk it with LeRobot's
34
+ locomotion controller:
35
+
36
+ ```bash
37
+ python run_locomotion.py
38
+ ```
39
+
40
+ which is
41
+
42
+ ```python
43
+ from lerobot.robots.asimov import Asimov, AsimovConfig
44
+
45
+ robot = Asimov(AsimovConfig(host="127.0.0.1", control_mode="whole_body", robot_supported=True))
46
+ robot.connect()
47
+ robot.send_action({"x.vel": 0.3, "y.vel": 0.0, "theta.vel": 0.0}) # m/s, m/s, deg/s
48
+ ```
49
+
50
+ Release the band once the policy has taken over (about 2 s after connecting). On a
51
+ Wayland desktop, start the sim with `MUJOCO_GL=egl` so its camera renderers do not
52
+ share the viewer's GLFW context.
53
+
54
+ ## Asimov Edge emulation
55
+
56
+ | | |
57
+ | --- | --- |
58
+ | Commands | `asimov.io.RobotCommand` on UDP `127.0.0.1:8850` |
59
+ | State | `asimov.io.RobotState` pushed to UDP `127.0.0.1:8851`, every physics step (200 Hz) |
60
+ | Target facts | `GET http://127.0.0.1:3000/api/version` → `{"robot_model": "asimov_1", "robot_os_version": "0.2.0"}` |
61
+ | Modes | starts in STAND holding the stance; a trajectory switches to MOVE; DAMP 2 s after the last trajectory, as Edge does; STAND and DAMP mode requests |
62
+
63
+ Joint vectors use the firmware's 25 slots. Trajectories carry ankles as pitch/roll;
64
+ state reports them as the A/B motors, through the same coupling as the firmware.
65
+ The IMU (gyro, projected gravity, quaternion) is the pelvis site. Velocity commands
66
+ are accepted but do not move the robot: the sim has no onboard walking policy, so
67
+ use LeRobot's `control_mode=whole_body`, which runs the policy itself and streams
68
+ trajectories. Ports and timings are in `config.yaml`.
69
+
70
+ ## Cameras
71
+
72
+ Like the G1 sim, three streams on **`tcp://127.0.0.1:5555`**, 640 × 480 at about 30 Hz:
73
+
74
+ | Stream name | Mount |
75
+ | --- | --- |
76
+ | `head_camera` | head (`neck_pitch_link`), 90° vertical field of view |
77
+ | `left_wrist_cam` | left wrist (`left_wrist_yaw_link`), 95° |
78
+ | `right_wrist_cam` | right wrist (`right_wrist_yaw_link`), 95° |
79
+
80
+ The message format is the G1 sim's, so `view_cameras_live.py` and LeRobot's ZMQ
81
+ cameras work unchanged; `lerobot_cameras.json` holds the client configuration.
82
+ `make_env(cameras=["head_camera"])` selects a subset, `publish_images=False`
83
+ disables publishing and `onscreen=False` the viewer.
84
+
85
+ ## The model
86
+
87
+ The robot is not bundled. On startup `sim/robot_model.py` downloads it from the
88
+ [`lerobot/robot-urdfs`](https://huggingface.co/datasets/lerobot/robot-urdfs/tree/main/asimov)
89
+ dataset, at the revision pinned in `config.yaml`: Menlo's MJCF and meshes in Menlo's
90
+ black and orange livery. It then removes the standalone world, adds one torque motor
91
+ per joint (limited to the joint's `actuatorfrcrange`) and the three cameras, and
92
+ loads it into `assets/scene_25dof.xml`, the world (floor, sky, lights, `global_view`).
93
+
94
+ Physics are Menlo's: 200 Hz, the policy's training timestep. Joint PD runs in the sim
95
+ from the gains each trajectory carries.
96
+
97
+ ## Checks
98
+
99
+ ```bash
100
+ MUJOCO_GL=egl python -m unittest discover -s tests -v # model, Edge protocol, band
101
+ MUJOCO_GL=egl python tests/smoke_live.py # LeRobot's driver walks it
102
+ ```
103
+
104
+ `smoke_live.py` needs a LeRobot checkout with the Asimov driver.
105
+
106
+ ## TODO
107
+
108
+ - **Unify with the G1 sim.** This repository is the G1 sim with the robot swapped:
109
+ `sim/base_sim.py`, the band, viewer, image publisher, `env.py` and `run_sim.py` are
110
+ shared code. What differs per robot is the model, `config.yaml` and the protocol
111
+ bridge (`sim/asimov_edge_bridge.py` here, `sim/unitree_sdk2py_bridge.py` there). One
112
+ humanoid sim with a robot profile (model, config, bridge) per robot would replace
113
+ both, the way the G1 sim already selects end effectors.
114
+
115
+ ## Licenses
116
+
117
+ - The Asimov 1 model is Menlo Research's, under CERN-OHL-S-2.0
118
+ ([`lerobot/robot-urdfs/asimov`](https://huggingface.co/datasets/lerobot/robot-urdfs/tree/main/asimov)).
119
+ - The sim code is adapted from [`lerobot/unitree-g1-mujoco`](https://huggingface.co/lerobot/unitree-g1-mujoco).
assets/scene_25dof.xml ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <mujoco model="asimov_1_25dof scene">
2
+ <include file="asimov_1_25dof.xml"/>
3
+
4
+ <statistic center="0 0 0.4" extent="1.6"/>
5
+
6
+ <visual>
7
+ <headlight diffuse="0.6 0.6 0.6" ambient="0.3 0.3 0.3" specular="0 0 0"/>
8
+ <rgba haze="0.15 0.25 0.35 1"/>
9
+ <global azimuth="-130" elevation="-20" offwidth="1920" offheight="1080"/>
10
+ </visual>
11
+
12
+ <asset>
13
+ <texture type="skybox" builtin="gradient" rgb1="0.3 0.5 0.7" rgb2="0 0 0" width="512" height="3072"/>
14
+ <texture type="2d" name="groundplane" builtin="checker" mark="edge" rgb1="0.2 0.3 0.4" rgb2="0.1 0.2 0.3"
15
+ markrgb="0.8 0.8 0.8" width="300" height="300"/>
16
+ <material name="groundplane" texture="groundplane" texuniform="true" texrepeat="5 5" reflectance="0.2"/>
17
+ </asset>
18
+
19
+ <worldbody>
20
+ <light pos="0 0 1.5" dir="0 0 -1" directional="true"/>
21
+ <geom name="floor" size="0 0 0.05" type="plane" material="groundplane" friction="1.2 0.5 0.1" condim="3"/>
22
+ <camera name="global_view" pos="2.2 -3.8 2.9" xyaxes="0.866 0.500 0.000 -0.250 0.433 0.866"/>
23
+ </worldbody>
24
+ </mujoco>
config.yaml ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Robot Configuration
2
+ ROBOT_TYPE: 'asimov_1_25dof'
3
+ ROBOT_SCENE: "assets/scene_25dof.xml" # The world; it includes the robot built by sim/robot_model.py
4
+ # Where the robot comes from: Menlo's model in Menlo's livery, pinned.
5
+ ROBOT_MODEL_REPO: "lerobot/robot-urdfs" # Hugging Face dataset
6
+ ROBOT_MODEL_REVISION: "1b184a0e9ea822b8f8bfd1382f3ae0b28e1bfad3"
7
+ ROBOT_MODEL_PATH: "asimov/asimov_1_25dof"
8
+
9
+ # Asimov Edge emulation. The real robot speaks UDP on these ports, so the Menlo SDK
10
+ # and LeRobot's Asimov driver connect to the sim with host=127.0.0.1.
11
+ EDGE_HOST: "127.0.0.1" # where commands are accepted
12
+ COMMAND_PORT: 8850 # asimov.io.RobotCommand in
13
+ STATE_HOST: "127.0.0.1" # Edge's udp-state-host: where RobotState is pushed
14
+ STATE_PORT: 8851 # asimov.io.RobotState out
15
+ VERSION_PORT: 3000 # GET /api/version
16
+ ROBOT_MODEL: "asimov_1"
17
+ ROBOT_OS_VERSION: "0.2.0"
18
+ SETPOINT_TIMEOUT_S: 2.0 # Edge DAMPs a trajectory this long after the last setpoint
19
+ SIMULATOR: "mujoco"
20
+
21
+ # Simulation Settings
22
+ FREE_BASE: False
23
+ ENABLE_ELASTIC_BAND: True
24
+ BAND_LINK: "pelvis_link"
25
+ BAND_HEIGHT: 0.68 # metres. Band anchor; the pelvis hangs ~4 cm below with feet just off the floor. 7/8 lower/raise it, 9 releases
26
+
27
+ # Timing
28
+ SIMULATE_DT: 0.005 # 200Hz physics, the policy's training sim_dt
29
+ VIEWER_DT: 0.02 # 50Hz viewer update
30
+ IMAGE_DT: 0.033333 # ~30Hz camera
31
+
32
+ # Rendering
33
+ ENABLE_ONSCREEN: true
34
+ ENABLE_OFFSCREEN: false
35
+ MP_START_METHOD: "spawn"
36
+ CAMERAS: ["head_camera", "left_wrist_cam", "right_wrist_cam"]
37
+
38
+ # Sensors
39
+ PRINT_SCENE_INFORMATION: True
40
+
41
+ # Robot Dimensions
42
+ NUM_MOTORS: 25
43
+ NUM_JOINTS: 25
44
+
45
+ # MuJoCo joints in firmware order (menlo-sdk ASIMOV_1_BIPED_JOINTS). Each ankle's two
46
+ # slots are its pitch and roll here; RobotState reports them as the A/B motors.
47
+ JOINT_NAMES: [
48
+ left_hip_pitch_joint, left_hip_roll_joint, left_hip_yaw_joint, left_knee_joint,
49
+ left_ankle_pitch_joint, left_ankle_roll_joint,
50
+ right_hip_pitch_joint, right_hip_roll_joint, right_hip_yaw_joint, right_knee_joint,
51
+ right_ankle_pitch_joint, right_ankle_roll_joint,
52
+ left_shoulder_pitch_joint, left_shoulder_roll_joint, left_shoulder_yaw_joint,
53
+ left_elbow_joint, left_wrist_yaw_joint,
54
+ right_shoulder_pitch_joint, right_shoulder_roll_joint, right_shoulder_yaw_joint,
55
+ right_elbow_joint, right_wrist_yaw_joint,
56
+ waist_yaw_joint, neck_yaw_joint, neck_pitch_joint,
57
+ ]
58
+
59
+ # What Edge holds in STAND before any trajectory: Menlo's bent-knee stance, with a
60
+ # stand-in for Edge's own gain table. Same order as JOINT_NAMES.
61
+ STAND_POSE: [
62
+ -0.15, 0.0, 0.0, 0.45, -0.3, 0.0,
63
+ 0.15, 0.0, 0.0, -0.45, 0.3, 0.0,
64
+ -0.25, -0.05, 0.0, 0.4, 0.0,
65
+ 0.25, 0.05, 0.0, -0.4, 0.0,
66
+ 0.0, 0.0, 0.0,
67
+ ]
68
+ STAND_KP: [
69
+ 150.0, 150.0, 150.0, 150.0, 224.42, 35.2,
70
+ 150.0, 150.0, 150.0, 150.0, 224.42, 35.2,
71
+ 60.0, 60.0, 60.0, 60.0, 60.0,
72
+ 60.0, 60.0, 60.0, 60.0, 60.0,
73
+ 65.0, 60.0, 60.0,
74
+ ]
75
+ STAND_KD: [
76
+ 5.0, 5.0, 5.0, 5.0, 10.2, 1.6,
77
+ 5.0, 5.0, 5.0, 5.0, 10.2, 1.6,
78
+ 3.0, 3.0, 3.0, 3.0, 3.0,
79
+ 3.0, 3.0, 3.0, 3.0, 3.0,
80
+ 5.0, 3.0, 3.0,
81
+ ]
82
+ DAMP_KD: 2.0
env.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ import sys
3
+ import gymnasium as gym
4
+ from gymnasium import spaces
5
+ import numpy as np
6
+ from huggingface_hub import snapshot_download
7
+ import yaml
8
+ # LeRobot initially fetches only env.py. Hydrate its matching Hub snapshot;
9
+ # a complete local checkout can also be used without another network request.
10
+ _repo_dir = Path(__file__).parent
11
+ if not (_repo_dir / "assets/scene_25dof.xml").is_file():
12
+ _revision = _repo_dir.name if _repo_dir.parent.name == "snapshots" else None
13
+ snapshot_download("lerobot/asimov-mujoco", revision=_revision)
14
+
15
+ # Ensure sim module is importable
16
+ sys.path.insert(0, str(Path(__file__).parent))
17
+
18
+ from sim.simulator_factory import SimulatorFactory
19
+
20
+
21
+ def make_env(n_envs=1, use_async_envs=False, **kwargs):
22
+ """Create an Asimov simulation environment.
23
+
24
+ Args:
25
+ n_envs: Number of environments (currently only 1 supported)
26
+ use_async_envs: Whether to use async envs (not implemented)
27
+ cfg: LeRobot's env config, when called through lerobot.envs.make_env.
28
+ Any of the options below that it carries are read off it; keywords win.
29
+ **kwargs: Additional arguments passed to simulator
30
+ - publish_images: bool, whether to publish camera images via ZMQ
31
+ - camera_port: int, ZMQ port for camera images
32
+ - cameras: list of camera names
33
+ - onscreen: bool, override the interactive viewer setting
34
+ """
35
+ repo_dir = Path(__file__).parent
36
+ cfg = kwargs.get("cfg")
37
+
38
+ def option(name, default=None):
39
+ """An option as given by keyword, else as carried by cfg, else the default.
40
+
41
+ None means "not set", so a cfg field can leave the choice to config.yaml.
42
+ """
43
+ for value in (kwargs.get(name), getattr(cfg, name, None)):
44
+ if value is not None:
45
+ return value
46
+ return default
47
+
48
+ # Load config
49
+ config_path = repo_dir / "config.yaml"
50
+ with open(config_path) as f:
51
+ config = yaml.safe_load(f)
52
+
53
+ # Configure cameras if requested
54
+ publish_images = option("publish_images", True)
55
+ camera_port = option("camera_port", 5555)
56
+ cameras = option("cameras")
57
+ if cameras is None:
58
+ cameras = config["CAMERAS"]
59
+
60
+ enable_offscreen = publish_images or config.get("ENABLE_OFFSCREEN", False)
61
+ camera_configs = {}
62
+ if enable_offscreen:
63
+ for cam_name in cameras:
64
+ camera_configs[cam_name] = {"height": 480, "width": 640}
65
+
66
+ # Create simulator (runs in same process)
67
+ simulator = SimulatorFactory.create_simulator(
68
+ config=config,
69
+ env_name="default",
70
+ onscreen=option("onscreen", config.get("ENABLE_ONSCREEN", True)),
71
+ offscreen=enable_offscreen,
72
+ camera_configs=camera_configs,
73
+ )
74
+
75
+ class AsimovEnv(gym.Env):
76
+ """Gymnasium environment wrapper for Asimov MuJoCo simulation."""
77
+
78
+ metadata = {"render_modes": ["human"]}
79
+
80
+ def __init__(self, sim, cam_configs, pub_images, cam_port):
81
+ super().__init__()
82
+ self.simulator = sim
83
+ self.sim_env = sim.sim_env
84
+ self.step_count = 0
85
+ self.camera_configs = cam_configs
86
+ self.camera_names = tuple(cam_configs)
87
+ self.camera_port = cam_port
88
+ self.metadata = {"render_modes": ["human"], "cameras": self.camera_names}
89
+
90
+ # Get timing from config
91
+ self.sim_dt = config["SIMULATE_DT"]
92
+ self.viewer_dt = config.get("VIEWER_DT", 0.02)
93
+ self.image_dt = config.get("IMAGE_DT", 0.033333)
94
+
95
+ # Start image publishing subprocess if requested
96
+ if pub_images and len(cam_configs) > 0:
97
+ sim.start_image_publish_subprocess(
98
+ start_method=config.get("MP_START_METHOD", "spawn"),
99
+ camera_port=cam_port
100
+ )
101
+ print(f"Camera images publishing on tcp://localhost:{cam_port}: {', '.join(self.camera_names)}")
102
+
103
+ # Define spaces
104
+ num_joints = config.get("NUM_MOTORS", 25)
105
+ self.action_space = spaces.Box(-np.pi, np.pi, shape=(num_joints,), dtype=np.float32)
106
+ self.observation_space = spaces.Box(-np.inf, np.inf, shape=(num_joints * 3 + 10,), dtype=np.float32)
107
+
108
+ def reset(self, seed=None, options=None):
109
+ """Reset the simulation."""
110
+ super().reset(seed=seed, options=options)
111
+ self.simulator.reset()
112
+ self.step_count = 0
113
+ obs = self._get_obs()
114
+ return obs, {}
115
+
116
+ def step(self, action=None):
117
+ """Execute one simulation step. Caller handles timing."""
118
+ # Run physics step
119
+ self.sim_env.sim_step()
120
+
121
+ # Update viewer at viewer rate
122
+ if self.step_count % int(self.viewer_dt / self.sim_dt) == 0:
123
+ self.sim_env.update_viewer()
124
+
125
+ # Update render caches at image rate (for ZMQ publishing)
126
+ if self.step_count % int(self.image_dt / self.sim_dt) == 0:
127
+ self.sim_env.update_render_caches()
128
+
129
+ self.step_count += 1
130
+
131
+ obs = self._get_obs()
132
+ reward = 0.0
133
+ terminated = False
134
+ truncated = False
135
+ info = {}
136
+ return obs, reward, terminated, truncated, info
137
+
138
+ def _get_obs(self):
139
+ """Get current observation from simulation."""
140
+ obs_dict = self.sim_env.prepare_obs()
141
+ obs = np.concatenate([
142
+ obs_dict.get("body_q", np.zeros(25)),
143
+ obs_dict.get("body_dq", np.zeros(25)),
144
+ obs_dict.get("body_tau_est", np.zeros(25)),
145
+ obs_dict.get("floating_base_pose", np.zeros(7))[:4],
146
+ obs_dict.get("floating_base_vel", np.zeros(6))[:3],
147
+ obs_dict.get("floating_base_acc", np.zeros(3))[:3],
148
+ ]).astype(np.float32)
149
+ return obs
150
+
151
+ def close(self):
152
+ """Close the simulation."""
153
+ print("++++closing simulator ++++")
154
+ self.simulator.close()
155
+
156
+ return AsimovEnv(simulator, camera_configs, publish_images, camera_port)
lerobot_cameras.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "head_camera": {
3
+ "type": "zmq",
4
+ "server_address": "127.0.0.1",
5
+ "port": 5555,
6
+ "camera_name": "head_camera",
7
+ "width": 640,
8
+ "height": 480,
9
+ "fps": 30
10
+ },
11
+ "left_wrist_cam": {
12
+ "type": "zmq",
13
+ "server_address": "127.0.0.1",
14
+ "port": 5555,
15
+ "camera_name": "left_wrist_cam",
16
+ "width": 640,
17
+ "height": 480,
18
+ "fps": 30
19
+ },
20
+ "right_wrist_cam": {
21
+ "type": "zmq",
22
+ "server_address": "127.0.0.1",
23
+ "port": 5555,
24
+ "camera_name": "right_wrist_cam",
25
+ "width": 640,
26
+ "height": 480,
27
+ "fps": 30
28
+ }
29
+ }
preview/asimov_back.png ADDED

Git LFS Details

  • SHA256: e9669ed001a4571f056c9aeedf85f72e544ab9af5378f8606a65226579f76294
  • Pointer size: 131 Bytes
  • Size of remote file: 308 kB
preview/asimov_front.png ADDED

Git LFS Details

  • SHA256: 0fa27c2e03ba78f12c199d7abf07205f0450735bcfe43084469880cf6b5c61b8
  • Pointer size: 131 Bytes
  • Size of remote file: 244 kB
preview/asimov_side.png ADDED

Git LFS Details

  • SHA256: 6dd493e129f0b67533892ab546de3c38631f812d8799542cf58b26516a82e0de
  • Pointer size: 131 Bytes
  • Size of remote file: 292 kB
requirements.txt ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ mujoco>=3.3.0
2
+ numpy>=1.24.0
3
+ pyyaml>=6.0
4
+ asimov-protocol>=1.2.1rc1,<2
5
+ protobuf>=5.29.3
6
+ gymnasium>=1.0.0
7
+ huggingface_hub>=0.25.0
8
+ glfw>=2.5.0
9
+ termcolor>=2.0.0
10
+
11
+ # Camera publishing dependencies
12
+ opencv-python>=4.8.0
13
+ pyzmq>=25.0.0
14
+ matplotlib>=3.5.0 # For live camera viewer
run_locomotion.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Walk the simulated Asimov with LeRobot's locomotion controller.
3
+
4
+ Start the sim first (python run_sim.py), then, in a LeRobot checkout with the Asimov
5
+ driver, run:
6
+
7
+ python run_locomotion.py
8
+
9
+ The driver connects to the emulated Edge on 127.0.0.1 exactly as it would to a real
10
+ robot. Press 9 in the viewer to drop the band once the policy has taken over.
11
+ """
12
+
13
+ import argparse
14
+ import time
15
+
16
+ from lerobot.robots.asimov import Asimov, AsimovConfig
17
+
18
+ # (seconds, forward m/s, yaw deg/s)
19
+ ROUTINE = [(6, 0.0, 0), (6, 0.3, 0), (5, 0.0, 30), (6, 0.3, 0), (5, 0.0, -30), (4, 0.0, 0)]
20
+
21
+
22
+ def main() -> None:
23
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
24
+ parser.add_argument("--host", default="127.0.0.1")
25
+ parser.add_argument("--loops", type=int, default=0, help="routine repetitions, 0 = forever")
26
+ args = parser.parse_args()
27
+
28
+ robot = Asimov(AsimovConfig(host=args.host, control_mode="whole_body", robot_supported=True))
29
+ robot.connect()
30
+ print("Connected. Press 9 in the viewer to release the band.")
31
+ loop = 0
32
+ try:
33
+ while args.loops == 0 or loop < args.loops:
34
+ for seconds, vx, wz in ROUTINE:
35
+ print(f"vx={vx:+.1f} m/s yaw={wz:+d} deg/s for {seconds} s")
36
+ end = time.monotonic() + seconds
37
+ while time.monotonic() < end:
38
+ robot.send_action({"x.vel": vx, "y.vel": 0.0, "theta.vel": float(wz)})
39
+ time.sleep(1 / 30)
40
+ loop += 1
41
+ except KeyboardInterrupt:
42
+ pass
43
+ finally:
44
+ robot.disconnect()
45
+
46
+
47
+ if __name__ == "__main__":
48
+ main()
run_sim.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import sys
3
+ from pathlib import Path
4
+ import time
5
+ # Add sim module to path
6
+ sys.path.insert(0, str(Path(__file__).parent))
7
+
8
+ import yaml
9
+ from sim.simulator_factory import SimulatorFactory
10
+
11
+ def main(n_envs=1, use_async_envs: bool = False,
12
+ publish_images=True, camera_port=5555, cameras=None, **kwargs):
13
+
14
+ # Load config
15
+ config_path = Path(__file__).parent / "config.yaml"
16
+ with open(config_path) as f:
17
+ config = yaml.safe_load(f)
18
+
19
+ # Override config with default values
20
+ enable_offscreen = publish_images or config.get("ENABLE_OFFSCREEN", False)
21
+
22
+ # Configure cameras if requested
23
+ camera_configs = {}
24
+ if enable_offscreen:
25
+ camera_list = config["CAMERAS"] if cameras is None else cameras
26
+ for cam_name in camera_list:
27
+ camera_configs[cam_name] = {"height": 480, "width": 640}
28
+ print(f"📷 Cameras: {', '.join(camera_list)} → ZMQ port {camera_port}")
29
+
30
+ print("="*60)
31
+
32
+ # Create simulator
33
+ sim = SimulatorFactory.create_simulator(
34
+ config=config,
35
+ env_name="default",
36
+ onscreen=kwargs.get("onscreen", config.get("ENABLE_ONSCREEN", True)),
37
+ offscreen=enable_offscreen,
38
+ camera_configs=camera_configs,
39
+ )
40
+
41
+ # Start simulator
42
+ print("\nSimulator running. Press Ctrl+C to exit.")
43
+ if enable_offscreen and publish_images:
44
+ print(f"Camera images publishing on tcp://localhost:{camera_port}")
45
+ try:
46
+ if publish_images:
47
+ sim.start_image_publish_subprocess(
48
+ start_method="spawn",
49
+ camera_port=camera_port,
50
+ )
51
+ time.sleep(1)
52
+ sim.start()
53
+ except KeyboardInterrupt:
54
+ print("+++++Simulator interrupted by user.")
55
+ except Exception as e:
56
+ print(f"++++error in simulator: {e} ++++")
57
+ finally:
58
+ print("++++closing simulator ++++")
59
+ sim.close()
60
+
61
+ if __name__ == "__main__":
62
+ main()
sim/__init__.py ADDED
File without changes
sim/asimov_edge_bridge.py ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import socket
3
+ import threading
4
+ import time
5
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
6
+ from typing import Dict, Tuple
7
+
8
+ import glfw
9
+ import mujoco
10
+ import numpy as np
11
+ from asimov_protocol.v1 import asimov_command_pb2, asimov_common_pb2, asimov_state_pb2
12
+ from termcolor import colored
13
+
14
+ # menlo-sdk robots.py: the ankle linkage. Motor A/B <-> ankle pitch/roll.
15
+ ANKLE_K_PITCH = 2.02
16
+ ANKLE_K_ROLL = 0.8
17
+ ANKLE_SLOTS = ((4, 5), (10, 11))
18
+ PROTOCOL_VERSION = 1
19
+
20
+ MODE_DAMP = asimov_common_pb2.CONTROL_MODE_DAMP
21
+ MODE_STAND = asimov_common_pb2.CONTROL_MODE_STAND
22
+ MODE_MOVE = asimov_common_pb2.CONTROL_MODE_MOVE
23
+
24
+
25
+ def joints_to_motors(values: np.ndarray) -> np.ndarray:
26
+ """Ankle (pitch, roll) slots -> (A, B) motors, as RobotState reports them."""
27
+ out = np.array(values, dtype=np.float64)
28
+ for a, b in ANKLE_SLOTS:
29
+ pitch, roll = out[a], out[b]
30
+ out[a] = ANKLE_K_PITCH * pitch - ANKLE_K_ROLL * roll
31
+ out[b] = -ANKLE_K_PITCH * pitch - ANKLE_K_ROLL * roll
32
+ return out
33
+
34
+
35
+ class AsimovEdgeBridge:
36
+ """
37
+ Bridge between the Asimov Edge UDP protocol and the MuJoCo simulation.
38
+ Answers what Asimov Edge answers to an external client (menlo-sdk ``udp`` mode):
39
+ RobotCommand in on COMMAND_PORT, RobotState out to STATE_HOST:STATE_PORT, and
40
+ the target facts on VERSION_PORT. Like Edge, it starts in STAND holding the stance,
41
+ follows trajectories, and DAMPs SETPOINT_TIMEOUT_S after the last one.
42
+ """
43
+
44
+ def __init__(self, config):
45
+ self.config = config
46
+ self.num_body_motor = config["NUM_MOTORS"]
47
+ self.stand_pose = np.array(config["STAND_POSE"], dtype=np.float64)
48
+ self.stand_kp = np.array(config["STAND_KP"], dtype=np.float64)
49
+ self.stand_kd = np.array(config["STAND_KD"], dtype=np.float64)
50
+ self.setpoint_timeout = float(config["SETPOINT_TIMEOUT_S"])
51
+ self.state_addr = (config["STATE_HOST"], int(config["STATE_PORT"]))
52
+
53
+ self.low_cmd_lock = threading.Lock()
54
+ self._stop = threading.Event()
55
+ self._sequence = 0
56
+ self._last_cmd_sequence = 0
57
+ self._warned_velocity = False
58
+
59
+ self.command_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
60
+ self.command_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
61
+ self.command_sock.bind((config["EDGE_HOST"], int(config["COMMAND_PORT"])))
62
+ self.command_sock.settimeout(0.2)
63
+ self.state_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
64
+ self.command_thread = threading.Thread(target=self._read_commands, name="asimov-edge-commands", daemon=True)
65
+ self.command_thread.start()
66
+
67
+ facts = json.dumps(
68
+ {"robot_model": config["ROBOT_MODEL"], "robot_os_version": config["ROBOT_OS_VERSION"]}
69
+ ).encode()
70
+
71
+ class VersionHandler(BaseHTTPRequestHandler):
72
+ def do_GET(self):
73
+ if self.path != "/api/version":
74
+ self.send_error(404)
75
+ return
76
+ self.send_response(200)
77
+ self.send_header("Content-Type", "application/json")
78
+ self.send_header("Content-Length", str(len(facts)))
79
+ self.end_headers()
80
+ self.wfile.write(facts)
81
+
82
+ def log_message(self, *args):
83
+ pass
84
+
85
+ self.version_server = ThreadingHTTPServer((config["EDGE_HOST"], int(config["VERSION_PORT"])), VersionHandler)
86
+ self.version_thread = threading.Thread(
87
+ target=self.version_server.serve_forever, name="asimov-edge-version", daemon=True
88
+ )
89
+ self.version_thread.start()
90
+ print(
91
+ f"Asimov Edge emulated on {config['EDGE_HOST']}: commands :{config['COMMAND_PORT']}, "
92
+ f"state -> {self.state_addr[0]}:{self.state_addr[1]}, version :{config['VERSION_PORT']}"
93
+ )
94
+
95
+ self.reset()
96
+
97
+ def reset(self):
98
+ with self.low_cmd_lock:
99
+ self.mode = MODE_STAND
100
+ self.targets = self.stand_pose.copy()
101
+ self.kp = self.stand_kp.copy()
102
+ self.kd = self.stand_kd.copy()
103
+ self.last_setpoint = float("-inf")
104
+ self.low_cmd_received = False
105
+
106
+ def close(self):
107
+ self._stop.set()
108
+ self.version_server.shutdown()
109
+ self.version_server.server_close()
110
+ self.command_thread.join(timeout=1.0)
111
+ self.command_sock.close()
112
+ self.state_sock.close()
113
+
114
+ def _read_commands(self):
115
+ while not self._stop.is_set():
116
+ try:
117
+ data, _ = self.command_sock.recvfrom(65535)
118
+ except (TimeoutError, socket.timeout):
119
+ continue
120
+ except OSError:
121
+ return
122
+ msg = asimov_command_pb2.RobotCommand()
123
+ try:
124
+ msg.ParseFromString(data)
125
+ except Exception:
126
+ continue
127
+ self.LowCmdHandler(msg)
128
+
129
+ def LowCmdHandler(self, msg):
130
+ with self.low_cmd_lock:
131
+ self._last_cmd_sequence = msg.sequence
132
+ if msg.HasField("all_trajectory"):
133
+ if self.mode not in (MODE_STAND, MODE_MOVE):
134
+ return # Edge ignores joint commands while damped.
135
+ traj = msg.all_trajectory
136
+ if len(traj.positions) != self.num_body_motor:
137
+ return
138
+ self.targets = np.array(traj.positions, dtype=np.float64)
139
+ if len(traj.kp) == self.num_body_motor and len(traj.kd) == self.num_body_motor:
140
+ self.kp = np.array(traj.kp, dtype=np.float64)
141
+ self.kd = np.array(traj.kd, dtype=np.float64)
142
+ else:
143
+ self.kp, self.kd = self.stand_kp.copy(), self.stand_kd.copy()
144
+ self.mode = MODE_MOVE
145
+ self.last_setpoint = time.monotonic()
146
+ self.low_cmd_received = True
147
+ elif msg.HasField("policy"):
148
+ moving = msg.policy.vx or msg.policy.vy or msg.policy.vyaw
149
+ if moving and not self._warned_velocity:
150
+ self._warned_velocity = True
151
+ print("Velocity command ignored: the sim has no onboard walking policy. "
152
+ "Use LeRobot's control_mode=whole_body.")
153
+ elif msg.mode == MODE_DAMP:
154
+ self.mode = MODE_DAMP
155
+ elif msg.mode == MODE_STAND:
156
+ self.mode = MODE_STAND
157
+ self.targets = self.stand_pose.copy()
158
+ self.kp, self.kd = self.stand_kp.copy(), self.stand_kd.copy()
159
+ self.last_setpoint = float("-inf")
160
+
161
+ def cmd_received(self):
162
+ with self.low_cmd_lock:
163
+ return self.low_cmd_received
164
+
165
+ def GetAction(self) -> Tuple[np.ndarray, np.ndarray, np.ndarray, bool]:
166
+ """Targets (joint space), kp, kd, and whether the joints are damped."""
167
+ with self.low_cmd_lock:
168
+ since = time.monotonic() - self.last_setpoint
169
+ if self.mode == MODE_MOVE and since > self.setpoint_timeout:
170
+ print(f"No setpoint for {self.setpoint_timeout:.0f} s: damping, as Asimov Edge does.")
171
+ self.mode = MODE_DAMP
172
+ damped = self.mode not in (MODE_STAND, MODE_MOVE)
173
+ return self.targets.copy(), self.kp.copy(), self.kd.copy(), damped
174
+
175
+ def PublishLowState(self, obs: Dict[str, any]):
176
+ with self.low_cmd_lock:
177
+ mode = self.mode
178
+ last_cmd = self._last_cmd_sequence
179
+ self._sequence = (self._sequence + 1) & 0xFFFFFFFF
180
+ msg = asimov_state_pb2.RobotState(
181
+ timestamp_us=int(obs["time"] * 1e6),
182
+ sequence=self._sequence,
183
+ current_mode=mode,
184
+ last_cmd_sequence=last_cmd,
185
+ protocol_version=PROTOCOL_VERSION,
186
+ )
187
+ msg.joint_pos.extend(joints_to_motors(obs["body_q"]).tolist())
188
+ msg.joint_vel.extend(joints_to_motors(obs["body_dq"]).tolist())
189
+ msg.base_ang_vel.extend(np.asarray(obs["imu_gyro"], dtype=np.float64).tolist())
190
+ msg.projected_gravity.extend(np.asarray(obs["imu_gravity"], dtype=np.float64).tolist())
191
+ msg.base_quat.extend(np.asarray(obs["imu_quat"], dtype=np.float64).tolist())
192
+ try:
193
+ self.state_sock.sendto(msg.SerializeToString(), self.state_addr)
194
+ except OSError:
195
+ pass
196
+
197
+ def PrintSceneInformation(self, mj_model):
198
+ print(" ")
199
+ print(colored("<<------------- Link ------------->>", "green"))
200
+ for i in range(mj_model.nbody):
201
+ name = mujoco.mj_id2name(mj_model, mujoco.mjtObj.mjOBJ_BODY, i)
202
+ if name:
203
+ print(f"link_index: {i}, name: {name}")
204
+ print(" ")
205
+ print(colored("<<------------- Joint ------------->>", "green"))
206
+ for i in range(mj_model.njnt):
207
+ name = mujoco.mj_id2name(mj_model, mujoco.mjtObj.mjOBJ_JOINT, i)
208
+ if name:
209
+ print(f"joint_index: {i}, name: {name}")
210
+ print(" ")
211
+ print(colored("<<------------- Actuator ------------->>", "green"))
212
+ for i in range(mj_model.nu):
213
+ name = mujoco.mj_id2name(mj_model, mujoco.mjtObj.mjOBJ_ACTUATOR, i)
214
+ if name:
215
+ print(f"actuator_index: {i}, name: {name}")
216
+ print(" ")
217
+ print(colored("<<------------- Sensor ------------->>", "green"))
218
+ index = 0
219
+ for i in range(mj_model.nsensor):
220
+ name = mujoco.mj_id2name(mj_model, mujoco.mjtObj.mjOBJ_SENSOR, i)
221
+ if name:
222
+ print(f"sensor_index: {index}, name: {name}, dim: {mj_model.sensor_dim[i]}")
223
+ index = index + mj_model.sensor_dim[i]
224
+ print(" ")
225
+
226
+
227
+ class ElasticBand:
228
+ """
229
+ ref: https://github.com/unitreerobotics/unitree_mujoco
230
+ """
231
+
232
+ def __init__(self, height=1.0):
233
+ self.kp_pos = 10000
234
+ self.kd_pos = 1000
235
+ self.kp_ang = 1000
236
+ self.kd_ang = 10
237
+ self.point = np.array([0, 0, height])
238
+ self.length = 0
239
+ self.enable = True
240
+
241
+ def Advance(self, pose):
242
+ """
243
+ Args:
244
+ pose: 13D array containing:
245
+ - pose[0:3]: position in world frame
246
+ - pose[3:7]: quaternion [w,x,y,z] in world frame
247
+ - pose[7:10]: linear velocity in world frame
248
+ - pose[10:13]: angular velocity in world frame
249
+ Returns:
250
+ np.ndarray: 6D vector [fx, fy, fz, tx, ty, tz]
251
+ """
252
+ pos = pose[0:3]
253
+ quat = pose[3:7]
254
+ lin_vel = pose[7:10]
255
+ ang_vel = pose[10:13]
256
+
257
+ δx = self.point - pos
258
+ f = self.kp_pos * (δx + np.array([0, 0, self.length])) + self.kd_pos * (0 - lin_vel)
259
+
260
+ # --- Orientation PD control for torque ---
261
+ rotvec = np.zeros(3) # axis-angle error
262
+ mujoco.mju_quat2Vel(rotvec, np.asarray(quat, dtype=np.float64), 1.0)
263
+ torque = -self.kp_ang * rotvec - self.kd_ang * ang_vel
264
+
265
+ return np.concatenate([f, torque])
266
+
267
+ def MujuocoKeyCallback(self, key):
268
+ if key == glfw.KEY_7:
269
+ self.length -= 0.1
270
+ if key == glfw.KEY_8:
271
+ self.length += 0.1
272
+ if key == glfw.KEY_9:
273
+ self.enable = not self.enable
274
+
275
+ def handle_keyboard_button(self, key):
276
+ if key == "9":
277
+ self.enable = not self.enable
sim/base_sim.py ADDED
@@ -0,0 +1,506 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ from pathlib import Path
3
+ import shutil
4
+ import threading
5
+ from threading import Thread
6
+ from typing import Dict
7
+
8
+ import mujoco
9
+ import mujoco.viewer
10
+ import numpy as np
11
+ import yaml
12
+
13
+ from .asimov_edge_bridge import AsimovEdgeBridge, ElasticBand
14
+ from .image_publish_utils import ImagePublishProcess
15
+ from .metric_utils import check_contact
16
+ from .robot_model import scene_path
17
+ from .sim_utils import get_subtree_body_names
18
+
19
+ ASIMOV_ROOT = Path(__file__).resolve().parent.parent # Points to asimov-mujoco/
20
+
21
+
22
+ class DefaultEnv:
23
+ """Base environment class that handles simulation environment setup and step"""
24
+
25
+ def __init__(
26
+ self,
27
+ config: Dict[str, any],
28
+ env_name: str = "default",
29
+ camera_configs: Dict[str, any] = None,
30
+ onscreen: bool = False,
31
+ offscreen: bool = False,
32
+ ):
33
+ # Avoid mutable default argument gotcha
34
+ if camera_configs is None:
35
+ camera_configs = {}
36
+
37
+ self.config = config
38
+ self.env_name = env_name
39
+ self.num_body_dof = self.config["NUM_JOINTS"]
40
+ self.sim_dt = self.config["SIMULATE_DT"]
41
+ self.obs = None
42
+ self.camera_configs = camera_configs
43
+ self.damp_kd = float(self.config.get("DAMP_KD", 2.0))
44
+
45
+ # Debug: print camera config
46
+ if len(camera_configs) > 0:
47
+ print(f"✓ DefaultEnv initialized with {len(camera_configs)} camera(s): {list(camera_configs.keys())}")
48
+
49
+ # Asimov Edge bridge will be initialized by the simulator
50
+ self.edge_bridge = None
51
+ self.elastic_band = None
52
+
53
+ # Store display mode
54
+ self.onscreen = onscreen
55
+
56
+ # Initialize scene (defined in subclasses)
57
+ self.init_scene()
58
+
59
+ # Setup offscreen rendering if needed (lazy init - renderers created on first use)
60
+ self.offscreen = offscreen
61
+ self.renderers = {} # Will be lazily initialized
62
+ self._renderers_initialized = False
63
+ self.image_dt = self.config.get("IMAGE_DT", 0.033333)
64
+
65
+ # Image publishing subprocess (initialized separately)
66
+ self.image_publish_process = None
67
+
68
+ def init_scene(self):
69
+ """Initialize the default robot scene"""
70
+ scene = scene_path(self.config)
71
+ try:
72
+ self.mj_model = mujoco.MjModel.from_xml_path(str(scene))
73
+ finally:
74
+ shutil.rmtree(scene.parent, ignore_errors=True)
75
+ self.mj_data = mujoco.MjData(self.mj_model)
76
+ self.mj_model.opt.timestep = self.sim_dt
77
+ self.torso_index = self.mj_model.body("waist_yaw_link").id
78
+ self.root_body = "pelvis_link"
79
+ self.imu_site = self.mj_model.site("imu_in_pelvis").id
80
+ # Enable the elastic band
81
+ if self.config["ENABLE_ELASTIC_BAND"]:
82
+ self.elastic_band = ElasticBand(height=self.config.get("BAND_HEIGHT", 1.0))
83
+ self.band_attached_link = self.mj_model.body(self.config.get("BAND_LINK", "pelvis_link")).id
84
+ if self.onscreen:
85
+ self.viewer = mujoco.viewer.launch_passive(
86
+ self.mj_model,
87
+ self.mj_data,
88
+ key_callback=self.elastic_band.MujuocoKeyCallback,
89
+ show_left_ui=False,
90
+ show_right_ui=False,
91
+ )
92
+ else:
93
+ mujoco.mj_forward(self.mj_model, self.mj_data)
94
+ self.viewer = None
95
+ else:
96
+ if self.onscreen:
97
+ self.viewer = mujoco.viewer.launch_passive(
98
+ self.mj_model, self.mj_data, show_left_ui=False, show_right_ui=False
99
+ )
100
+ else:
101
+ mujoco.mj_forward(self.mj_model, self.mj_data)
102
+ self.viewer = None
103
+
104
+ if self.viewer:
105
+ # viewer camera
106
+ self.viewer.cam.azimuth = 120 # Horizontal rotation in degrees
107
+ self.viewer.cam.elevation = -30 # Vertical tilt in degrees
108
+ self.viewer.cam.distance = 2.0 # Distance from camera to target
109
+ self.viewer.cam.lookat = np.array([0, 0, 0.4]) # Point the camera is looking at
110
+
111
+ # The MJCF orders joints by kinematic tree, not as the firmware does, so map each
112
+ # firmware slot to its joint by name.
113
+ names = self.config["JOINT_NAMES"]
114
+ if len(names) != self.config["NUM_JOINTS"]:
115
+ raise ValueError(f"Expected {self.config['NUM_JOINTS']} JOINT_NAMES, got {len(names)}")
116
+ self.body_joint_index = np.array([self.mj_model.joint(name).id for name in names], dtype=int)
117
+ self.body_qpos_index = self.mj_model.jnt_qposadr[self.body_joint_index]
118
+ self.body_dof_index = self.mj_model.jnt_dofadr[self.body_joint_index]
119
+ actuator_ids = []
120
+ for joint_id in self.body_joint_index:
121
+ matches = np.flatnonzero(
122
+ (self.mj_model.actuator_trntype == mujoco.mjtTrn.mjTRN_JOINT)
123
+ & (self.mj_model.actuator_trnid[:, 0] == joint_id)
124
+ )
125
+ if len(matches) != 1:
126
+ raise ValueError(f"Expected one actuator for {self.mj_model.joint(joint_id).name}, got {len(matches)}")
127
+ actuator_ids.append(matches[0])
128
+ self.body_actuator_index = np.asarray(actuator_ids, dtype=int)
129
+ self.torques = np.zeros(self.mj_model.nu)
130
+ self.torque_limit = self.mj_model.actuator_ctrlrange[self.body_actuator_index]
131
+ self.stand_pose = np.array(self.config["STAND_POSE"], dtype=np.float64)
132
+ for name in self.camera_configs:
133
+ if mujoco.mj_name2id(self.mj_model, mujoco.mjtObj.mjOBJ_CAMERA, name) < 0:
134
+ raise ValueError(f"Camera {name!r} does not exist in {self.config['ROBOT_SCENE']}")
135
+ self.reset()
136
+
137
+ def init_renderers(self):
138
+ # Initialize camera renderers
139
+ self.renderers = {}
140
+ for camera_name, camera_config in self.camera_configs.items():
141
+ renderer = mujoco.Renderer(
142
+ self.mj_model, height=camera_config["height"], width=camera_config["width"]
143
+ )
144
+ self.renderers[camera_name] = renderer
145
+
146
+ def start_image_publish_subprocess(self, start_method: str = "spawn", camera_port: int = 5555):
147
+ """Start image publishing subprocess using ZMQ"""
148
+ # Use spawn method for better GIL isolation, or configured method
149
+ if len(self.camera_configs) == 0:
150
+ print(
151
+ "Warning: No camera configs provided, image publishing subprocess will not be started"
152
+ )
153
+ return
154
+ start_method = self.config.get("MP_START_METHOD", "spawn")
155
+ self.image_publish_process = ImagePublishProcess(
156
+ camera_configs=self.camera_configs,
157
+ image_dt=self.image_dt,
158
+ zmq_port=camera_port,
159
+ start_method=start_method,
160
+ verbose=self.config.get("verbose", False),
161
+ )
162
+ self.image_publish_process.start_process()
163
+ print(f"✓ Started image publishing subprocess on ZMQ port {camera_port}")
164
+
165
+ def compute_body_torques(self) -> np.ndarray:
166
+ """Compute body torques from the latest Edge command and the current robot state"""
167
+ q = self.mj_data.qpos[self.body_qpos_index]
168
+ dq = self.mj_data.qvel[self.body_dof_index]
169
+ if self.edge_bridge is None:
170
+ return np.zeros(self.num_body_dof)
171
+ targets, kp, kd, damped = self.edge_bridge.GetAction()
172
+ if damped:
173
+ return -self.damp_kd * dq
174
+ return kp * (targets - q) - kd * dq
175
+
176
+ def prepare_obs(self) -> Dict[str, any]:
177
+ """Prepare observation dictionary from the current robot state"""
178
+ obs = {}
179
+ obs["floating_base_pose"] = self.mj_data.qpos[:7]
180
+ obs["floating_base_vel"] = self.mj_data.qvel[:6]
181
+ obs["floating_base_acc"] = self.mj_data.qacc[:6]
182
+ obs["secondary_imu_quat"] = self.mj_data.xquat[self.torso_index]
183
+ obs["secondary_imu_vel"] = self.mj_data.cvel[self.torso_index]
184
+ obs["body_q"] = self.mj_data.qpos[self.body_qpos_index]
185
+ obs["body_dq"] = self.mj_data.qvel[self.body_dof_index]
186
+ obs["body_ddq"] = self.mj_data.qacc[self.body_dof_index]
187
+ obs["body_tau_est"] = self.mj_data.actuator_force[self.body_actuator_index]
188
+ # The firmware's IMU sits in the pelvis and reports in its own frame.
189
+ rot = self.mj_data.site_xmat[self.imu_site].reshape(3, 3)
190
+ vel = np.zeros(6)
191
+ mujoco.mj_objectVelocity(self.mj_model, self.mj_data, mujoco.mjtObj.mjOBJ_SITE, self.imu_site, vel, 0)
192
+ quat = np.empty(4)
193
+ mujoco.mju_mat2Quat(quat, self.mj_data.site_xmat[self.imu_site])
194
+ obs["imu_gyro"] = rot.T @ vel[:3]
195
+ obs["imu_gravity"] = rot.T @ np.array([0.0, 0.0, -1.0])
196
+ obs["imu_quat"] = quat
197
+ obs["time"] = self.mj_data.time
198
+ return obs
199
+
200
+ def sim_step(self):
201
+ self.obs = self.prepare_obs()
202
+ self.edge_bridge.PublishLowState(self.obs)
203
+ if self.config["ENABLE_ELASTIC_BAND"]:
204
+ if self.elastic_band.enable:
205
+ # Get Cartesian pose and velocity of the band_attached_link
206
+ pose = np.concatenate(
207
+ [
208
+ self.mj_data.xpos[self.band_attached_link], # link position in world
209
+ self.mj_data.xquat[
210
+ self.band_attached_link
211
+ ], # link quaternion in world [w,x,y,z]
212
+ np.zeros(6), # placeholder for velocity
213
+ ]
214
+ )
215
+
216
+ # Get velocity in world frame
217
+ mujoco.mj_objectVelocity(
218
+ self.mj_model,
219
+ self.mj_data,
220
+ mujoco.mjtObj.mjOBJ_BODY,
221
+ self.band_attached_link,
222
+ pose[7:13],
223
+ 0, # 0 for world frame
224
+ )
225
+
226
+ # Reorder velocity from [ang, lin] to [lin, ang]
227
+ pose[7:10], pose[10:13] = pose[10:13], pose[7:10].copy()
228
+ self.mj_data.xfrc_applied[self.band_attached_link] = self.elastic_band.Advance(pose)
229
+ else:
230
+ # explicitly resetting the force when the band is not enabled
231
+ self.mj_data.xfrc_applied[self.band_attached_link] = np.zeros(6)
232
+ self.torques[self.body_actuator_index] = self.compute_body_torques()
233
+ self.torques[self.body_actuator_index] = np.clip(
234
+ self.torques[self.body_actuator_index], self.torque_limit[:, 0], self.torque_limit[:, 1]
235
+ )
236
+
237
+ self.mj_data.ctrl[:] = self.torques
238
+ mujoco.mj_step(self.mj_model, self.mj_data)
239
+ # self.check_self_collision()
240
+
241
+ def apply_perturbation(self, key):
242
+ """Apply perturbation to the robot"""
243
+ # Add velocity perturbations in body frame
244
+ perturbation_x_body = 0.0 # forward/backward in body frame
245
+ perturbation_y_body = 0.0 # left/right in body frame
246
+ if key == "up":
247
+ perturbation_x_body = 1.0 # forward
248
+ elif key == "down":
249
+ perturbation_x_body = -1.0 # backward
250
+ elif key == "left":
251
+ perturbation_y_body = 1.0 # left
252
+ elif key == "right":
253
+ perturbation_y_body = -1.0 # right
254
+
255
+ # Transform body frame velocity to world frame using MuJoCo's rotation
256
+ vel_body = np.array([perturbation_x_body, perturbation_y_body, 0.0])
257
+ vel_world = np.zeros(3)
258
+ base_quat = self.mj_data.qpos[3:7] # [w, x, y, z] quaternion
259
+
260
+ # Use MuJoCo's robust quaternion rotation (handles invalid quaternions automatically)
261
+ mujoco.mju_rotVecQuat(vel_world, vel_body, base_quat)
262
+
263
+ # Apply to base linear velocity in world frame
264
+ self.mj_data.qvel[0] += vel_world[0] # world X velocity
265
+ self.mj_data.qvel[1] += vel_world[1] # world Y velocity
266
+
267
+ # Update dynamics after velocity change
268
+ mujoco.mj_forward(self.mj_model, self.mj_data)
269
+
270
+ def update_viewer(self):
271
+ if self.viewer is not None:
272
+ self.viewer.sync()
273
+
274
+ def update_viewer_camera(self):
275
+ if self.viewer is not None:
276
+ if self.viewer.cam.type == mujoco.mjtCamera.mjCAMERA_TRACKING:
277
+ self.viewer.cam.type = mujoco.mjtCamera.mjCAMERA_FREE
278
+ else:
279
+ self.viewer.cam.type = mujoco.mjtCamera.mjCAMERA_TRACKING
280
+
281
+ def set_edge_bridge(self, edge_bridge):
282
+ """Set the Asimov Edge bridge from the simulator"""
283
+ self.edge_bridge = edge_bridge
284
+
285
+ def get_privileged_obs(self):
286
+ """Get privileged observation. Should be implemented by subclasses."""
287
+ return {}
288
+
289
+ def update_render_caches(self):
290
+ """Update render cache and shared memory for subprocess."""
291
+ # Lazy init renderers on first call (creates OpenGL context in calling thread)
292
+ if not self._renderers_initialized and self.offscreen:
293
+ self.init_renderers()
294
+ self._renderers_initialized = True
295
+ print(f"✓ Renderers initialized lazily in thread {threading.current_thread().name}")
296
+
297
+ render_caches = {}
298
+ for camera_name, camera_config in self.camera_configs.items():
299
+ renderer = self.renderers.get(camera_name)
300
+ if renderer is None:
301
+ continue
302
+ if "params" in camera_config:
303
+ renderer.update_scene(self.mj_data, camera=camera_config["params"])
304
+ else:
305
+ renderer.update_scene(self.mj_data, camera=camera_name)
306
+ render_caches[camera_name + "_image"] = renderer.render()
307
+
308
+ # Update shared memory if image publishing process is available
309
+ if self.image_publish_process is not None:
310
+ self.image_publish_process.update_shared_memory(render_caches)
311
+
312
+ return render_caches
313
+
314
+ def handle_keyboard_button(self, key):
315
+ if self.elastic_band is not None:
316
+ self.elastic_band.handle_keyboard_button(key)
317
+
318
+ if key == "backspace":
319
+ self.reset()
320
+ if key == "v":
321
+ self.update_viewer_camera()
322
+ if key in ["up", "down", "left", "right"]:
323
+ self.apply_perturbation(key)
324
+
325
+ def check_fall(self):
326
+ """Check if the robot has fallen"""
327
+ self.fall = False
328
+ if self.mj_data.qpos[2] < 0.2:
329
+ self.fall = True
330
+ print(f"Warning: Robot has fallen, height: {self.mj_data.qpos[2]:.3f} m")
331
+
332
+ if self.fall:
333
+ self.reset()
334
+
335
+ def check_self_collision(self):
336
+ """Check for self-collision of the robot"""
337
+ robot_bodies = get_subtree_body_names(self.mj_model, self.mj_model.body(self.root_body).id)
338
+ self_collision, contact_bodies = check_contact(
339
+ self.mj_model, self.mj_data, robot_bodies, robot_bodies, return_all_contact_bodies=True
340
+ )
341
+ if self_collision:
342
+ print(f"Warning: Self-collision detected: {contact_bodies}")
343
+ return self_collision
344
+
345
+ def reset(self):
346
+ mujoco.mj_resetData(self.mj_model, self.mj_data)
347
+ # Hang in the stance Edge holds in STAND, with the pelvis at the band's height.
348
+ self.mj_data.qpos[3:7] = [1.0, 0.0, 0.0, 0.0]
349
+ self.mj_data.qpos[2] = self.config.get("BAND_HEIGHT", self.mj_data.qpos[2])
350
+ self.mj_data.qpos[self.body_qpos_index] = self.stand_pose
351
+ if self.elastic_band is not None:
352
+ self.elastic_band.length = 0
353
+ # Propagate qpos to derived quantities (xquat, xpos, etc.)
354
+ mujoco.mj_forward(self.mj_model, self.mj_data)
355
+
356
+
357
+ class BaseSimulator:
358
+ """Base simulator class that handles initialization and running of simulations"""
359
+
360
+ def __init__(self, config: Dict[str, any], env_name: str = "default", **kwargs):
361
+ self.config = config
362
+ self.env_name = env_name
363
+ self.node = None
364
+ self.thread = None
365
+
366
+ # Set update frequencies
367
+ self.sim_dt = self.config["SIMULATE_DT"]
368
+ self.image_dt = self.config.get("IMAGE_DT", 0.033333)
369
+ self.viewer_dt = self.config.get("VIEWER_DT", 0.02)
370
+
371
+ # Create the environment
372
+ self.sim_env = DefaultEnv(config, env_name, **kwargs)
373
+
374
+ # Initialize the Asimov Edge bridge and pass it to the environment
375
+ self.init_edge_bridge()
376
+ self.sim_env.set_edge_bridge(self.edge_bridge)
377
+ if self.config.get("PRINT_SCENE_INFORMATION", False):
378
+ self.edge_bridge.PrintSceneInformation(self.sim_env.mj_model)
379
+
380
+ # Initialize additional components
381
+ self.init_subscriber()
382
+ self.init_publisher()
383
+
384
+ self.sim_thread = None
385
+ self._stop = threading.Event()
386
+
387
+ def start_as_thread(self):
388
+ # Create simulation thread
389
+ self.sim_thread = Thread(target=self.start)
390
+ self.sim_thread.start()
391
+
392
+ def start_image_publish_subprocess(self, start_method: str = "spawn", camera_port: int = 5555):
393
+ """Start the image publish subprocess"""
394
+ self.sim_env.start_image_publish_subprocess(start_method, camera_port)
395
+
396
+ def init_subscriber(self):
397
+ """Initialize subscribers. Can be overridden by subclasses."""
398
+ pass
399
+
400
+ def init_publisher(self):
401
+ """Initialize publishers. Can be overridden by subclasses."""
402
+ pass
403
+
404
+ def init_edge_bridge(self):
405
+ """Initialize the Asimov Edge bridge."""
406
+ self.edge_bridge = AsimovEdgeBridge(self.config)
407
+
408
+ def start(self):
409
+ """Main simulation loop"""
410
+ import time
411
+ sim_cnt = 0
412
+ last_time = time.time()
413
+
414
+ print(f"Starting simulation loop. Viewer: {self.sim_env.viewer is not None}")
415
+
416
+ try:
417
+ while not self._stop.is_set() and (
418
+ (self.sim_env.viewer and self.sim_env.viewer.is_running()) or self.sim_env.viewer is None
419
+ ):
420
+ # Run simulation step
421
+ self.sim_env.sim_step()
422
+
423
+ # Update viewer at viewer rate
424
+ if sim_cnt % int(self.viewer_dt / self.sim_dt) == 0:
425
+ self.sim_env.update_viewer()
426
+
427
+ # Update render caches at image rate
428
+ if sim_cnt % int(self.image_dt / self.sim_dt) == 0:
429
+ self.sim_env.update_render_caches()
430
+
431
+ # Sleep to maintain correct rate (simple timing without ROS)
432
+ elapsed = time.time() - last_time
433
+ sleep_time = max(0, self.sim_dt - elapsed)
434
+ if sleep_time > 0:
435
+ time.sleep(sleep_time)
436
+ last_time = time.time()
437
+
438
+ sim_cnt += 1
439
+
440
+ print(f"Loop exited. Viewer running: {self.sim_env.viewer.is_running() if self.sim_env.viewer else 'No viewer'}")
441
+ except KeyboardInterrupt:
442
+ # User pressed Ctrl+C - exit cleanly
443
+ print("Keyboard interrupt received")
444
+ pass
445
+ except Exception as e:
446
+ print(f"Exception in simulation loop: {e}")
447
+ import traceback
448
+ traceback.print_exc()
449
+ self.close()
450
+
451
+ def __del__(self):
452
+ """Clean up resources when simulator is deleted"""
453
+ self.close()
454
+
455
+ def reset(self):
456
+ """Reset the simulation. Can be overridden by subclasses."""
457
+ self.edge_bridge.reset()
458
+ self.sim_env.reset()
459
+
460
+ def close(self):
461
+ """Close the simulation. Can be overridden by subclasses."""
462
+ try:
463
+ self._stop.set()
464
+ if self.sim_thread is not None and self.sim_thread is not threading.current_thread():
465
+ self.sim_thread.join(timeout=2.0)
466
+
467
+ # Stop image publishing subprocess
468
+ if hasattr(self.sim_env, "image_publish_process") and self.sim_env.image_publish_process is not None:
469
+ self.sim_env.image_publish_process.stop()
470
+ self.sim_env.image_publish_process = None
471
+
472
+ # Close viewer
473
+ if hasattr(self.sim_env, "viewer") and self.sim_env.viewer is not None:
474
+ self.sim_env.viewer.close()
475
+
476
+ for renderer in self.sim_env.renderers.values():
477
+ renderer.close()
478
+ self.sim_env.renderers.clear()
479
+ self.sim_env._renderers_initialized = False
480
+
481
+ if getattr(self, "edge_bridge", None) is not None:
482
+ self.edge_bridge.close()
483
+ self.edge_bridge = None
484
+ except Exception as e:
485
+ print(f"Warning during close: {e}")
486
+
487
+ def get_privileged_obs(self):
488
+ obs = self.sim_env.get_privileged_obs()
489
+ return obs
490
+
491
+ def handle_keyboard_button(self, key):
492
+ # Only handles keyboard buttons for default env.
493
+ if self.env_name == "default":
494
+ self.sim_env.handle_keyboard_button(key)
495
+
496
+
497
+ if __name__ == "__main__":
498
+ parser = argparse.ArgumentParser(description="Robot")
499
+ parser.add_argument("--config", type=str, default=str(ASIMOV_ROOT / "config.yaml"), help="config file")
500
+ args = parser.parse_args()
501
+
502
+ with open(args.config, "r") as file:
503
+ config = yaml.load(file, Loader=yaml.FullLoader)
504
+
505
+ simulation = BaseSimulator(config)
506
+ simulation.start_as_thread()
sim/image_publish_utils.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import multiprocessing as mp
2
+ from multiprocessing import shared_memory
3
+ import time
4
+ from typing import Any, Dict
5
+
6
+ import numpy as np
7
+
8
+
9
+ def get_multiprocessing_info(verbose: bool = True):
10
+ """Get information about multiprocessing start methods"""
11
+
12
+ if verbose:
13
+ print(f"Available start methods: {mp.get_all_start_methods()}")
14
+ return mp.get_start_method()
15
+
16
+
17
+ class ImagePublishProcess:
18
+ """Subprocess for publishing images using shared memory and ZMQ"""
19
+
20
+ def __init__(
21
+ self,
22
+ camera_configs: Dict[str, Any],
23
+ image_dt: float,
24
+ zmq_port: int = 5555,
25
+ start_method: str = "spawn",
26
+ verbose: bool = False,
27
+ ):
28
+ self.camera_configs = camera_configs
29
+ self.image_dt = image_dt
30
+ self.zmq_port = zmq_port
31
+ self.verbose = verbose
32
+ self.shared_memory_blocks = {}
33
+ self.shared_memory_info = {}
34
+ self.process = None
35
+
36
+ # Use specific context to avoid global state pollution
37
+ self.mp_context = mp.get_context(start_method)
38
+ if self.verbose:
39
+ print(f"Using multiprocessing context: {start_method}")
40
+
41
+ self.stop_event = self.mp_context.Event()
42
+ self.data_ready_event = self.mp_context.Event()
43
+
44
+ # Ensure events start in correct state
45
+ self.stop_event.clear()
46
+ self.data_ready_event.clear()
47
+
48
+ if self.verbose:
49
+ print(f"Initial stop_event state: {self.stop_event.is_set()}")
50
+ print(f"Initial data_ready_event state: {self.data_ready_event.is_set()}")
51
+
52
+ # Calculate shared memory requirements for each camera
53
+ for camera_name, camera_config in camera_configs.items():
54
+ height = camera_config["height"]
55
+ width = camera_config["width"]
56
+ # RGB image: height * width * 3 (uint8)
57
+ size = height * width * 3
58
+
59
+ # Create shared memory block
60
+ shm = shared_memory.SharedMemory(create=True, size=size)
61
+ self.shared_memory_blocks[camera_name] = shm
62
+ self.shared_memory_info[camera_name] = {
63
+ "name": shm.name,
64
+ "size": size,
65
+ "shape": (height, width, 3),
66
+ "dtype": np.uint8,
67
+ }
68
+
69
+ def start_process(self):
70
+ """Start the image publishing subprocess"""
71
+ if self.verbose:
72
+ print(f"Starting subprocess with stop_event state: {self.stop_event.is_set()}")
73
+ self.process = self.mp_context.Process(
74
+ target=self._image_publish_worker,
75
+ args=(
76
+ self.shared_memory_info,
77
+ self.image_dt,
78
+ self.zmq_port,
79
+ self.stop_event,
80
+ self.data_ready_event,
81
+ self.verbose,
82
+ ),
83
+ )
84
+ self.process.start()
85
+ if self.verbose:
86
+ print(f"Subprocess started, PID: {self.process.pid}")
87
+
88
+ def update_shared_memory(self, render_caches: Dict[str, np.ndarray]):
89
+ """Update shared memory with new rendered images"""
90
+ images_updated = 0
91
+ for camera_name in self.camera_configs.keys():
92
+ image_key = f"{camera_name}_image"
93
+ if image_key in render_caches:
94
+ image = render_caches[image_key]
95
+
96
+ # Ensure image is uint8 and has correct shape
97
+ if image.dtype != np.uint8:
98
+ image = (image * 255).astype(np.uint8)
99
+
100
+ # Get shared memory array
101
+ shm = self.shared_memory_blocks[camera_name]
102
+ shared_array = np.ndarray(
103
+ self.shared_memory_info[camera_name]["shape"],
104
+ dtype=self.shared_memory_info[camera_name]["dtype"],
105
+ buffer=shm.buf,
106
+ )
107
+
108
+ # Copy image data to shared memory atomically
109
+ np.copyto(shared_array, image)
110
+ images_updated += 1
111
+
112
+ # Signal that new data is ready only after all images are written
113
+ if images_updated > 0:
114
+ if self.verbose:
115
+ print(f"Main process: Updated {images_updated} images, setting data_ready_event")
116
+ self.data_ready_event.set()
117
+ elif self.verbose:
118
+ print(
119
+ "Main process: No images to update. "
120
+ "please check if camera configs are provided and the renderer is properly initialized"
121
+ )
122
+
123
+ def stop(self):
124
+ """Stop the image publishing subprocess"""
125
+ if self.verbose:
126
+ print("Stopping image publishing subprocess...")
127
+ self.stop_event.set()
128
+
129
+ if self.process and self.process.is_alive():
130
+ # Give the process time to clean up gracefully
131
+ self.process.join(timeout=5)
132
+ if self.process.is_alive():
133
+ if self.verbose:
134
+ print("Subprocess didn't stop gracefully, terminating...")
135
+ self.process.terminate()
136
+ self.process.join(timeout=2)
137
+ if self.process.is_alive():
138
+ if self.verbose:
139
+ print("Force killing subprocess...")
140
+ self.process.kill()
141
+ self.process.join()
142
+
143
+ # Clean up shared memory
144
+ for camera_name, shm in self.shared_memory_blocks.items():
145
+ try:
146
+ shm.close()
147
+ shm.unlink()
148
+ if self.verbose:
149
+ print(f"Cleaned up shared memory for {camera_name}")
150
+ except Exception as e:
151
+ if self.verbose:
152
+ print(f"Warning: Failed to cleanup shared memory for {camera_name}: {e}")
153
+
154
+ self.shared_memory_blocks.clear()
155
+ if self.verbose:
156
+ print("Image publishing subprocess stopped and cleaned up")
157
+
158
+ @staticmethod
159
+ def _image_publish_worker(
160
+ shared_memory_info, image_dt, zmq_port, stop_event, data_ready_event, verbose
161
+ ):
162
+ """Worker function that runs in the subprocess"""
163
+ # Import dependencies within worker (needed for multiprocessing spawn mode)
164
+ from .sensor_utils import ImageMessageSchema, ImageUtils, SensorServer
165
+
166
+ if verbose:
167
+ print(f"Worker started! PID: {__import__('os').getpid()}")
168
+ print(f"Worker stop_event state at start: {stop_event.is_set()}")
169
+ print(f"Worker data_ready_event state at start: {data_ready_event.is_set()}")
170
+
171
+ try:
172
+ # Initialize ZMQ sensor server
173
+ sensor_server = SensorServer()
174
+ sensor_server.start_server(port=zmq_port)
175
+
176
+ # Connect to shared memory blocks
177
+ shared_arrays = {}
178
+ shm_blocks = {}
179
+ for camera_name, info in shared_memory_info.items():
180
+ shm = shared_memory.SharedMemory(name=info["name"])
181
+ shm_blocks[camera_name] = shm
182
+ shared_arrays[camera_name] = np.ndarray(
183
+ info["shape"], dtype=info["dtype"], buffer=shm.buf
184
+ )
185
+
186
+ print(
187
+ f"Image publishing subprocess started with {len(shared_arrays)} cameras on ZMQ port {zmq_port}"
188
+ )
189
+
190
+ loop_count = 0
191
+ last_data_time = time.time()
192
+
193
+ while not stop_event.is_set():
194
+ loop_count += 1
195
+
196
+ # Wait for new data with shorter timeout for better responsiveness
197
+ timeout = min(image_dt, 0.1) # Max 100ms timeout
198
+ data_available = data_ready_event.wait(timeout=timeout)
199
+
200
+ current_time = time.time()
201
+
202
+ if data_available:
203
+ data_ready_event.clear()
204
+ if loop_count % 50 == 0:
205
+ print("Image publish frequency: ", 1 / (current_time - last_data_time))
206
+ last_data_time = current_time
207
+
208
+ # Collect all camera images and serialize them
209
+ try:
210
+ # Copy all images atomically at once
211
+ image_copies = {name: arr.copy() for name, arr in shared_arrays.items()}
212
+
213
+ # Create message with all camera images
214
+ message_dict = {
215
+ "images": image_copies,
216
+ "timestamps": {name: current_time for name in image_copies.keys()},
217
+ }
218
+
219
+ # Create ImageMessageSchema and serialize
220
+ image_msg = ImageMessageSchema(
221
+ timestamps=message_dict.get("timestamps"),
222
+ images=message_dict.get("images", None),
223
+ )
224
+
225
+ # Serialize and send via ZMQ
226
+ serialized_data = image_msg.serialize()
227
+
228
+ # Add individual camera images to the message
229
+ for camera_name, image_copy in image_copies.items():
230
+ serialized_data[f"{camera_name}"] = ImageUtils.encode_image(image_copy)
231
+
232
+ sensor_server.send_message(serialized_data)
233
+
234
+ except Exception as e:
235
+ print(f"Error publishing images: {e}")
236
+
237
+ elif verbose and loop_count % 10 == 0:
238
+ print(f"Subprocess: Still waiting for data... (iteration {loop_count})")
239
+
240
+ # Small sleep to prevent busy waiting when no data
241
+ if not data_available:
242
+ time.sleep(0.001)
243
+
244
+ except KeyboardInterrupt:
245
+ print("Image publisher interrupted by user")
246
+ finally:
247
+ # Clean up
248
+ try:
249
+ for shm in shm_blocks.values():
250
+ shm.close()
251
+ sensor_server.stop_server()
252
+ except Exception as e:
253
+ print(f"Error during subprocess cleanup: {e}")
254
+ if verbose:
255
+ print("Image publish subprocess stopped")
sim/metric_utils.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Tuple
2
+
3
+ import mujoco
4
+
5
+ from .sim_utils import get_body_geom_ids
6
+
7
+
8
+ def check_contact(
9
+ mj_model: mujoco.MjModel,
10
+ mj_data: mujoco.MjData,
11
+ bodies_1: List[str] | str,
12
+ bodies_2: List[str] | str,
13
+ return_all_contact_bodies: bool = False,
14
+ ) -> Tuple[bool, List[Tuple[str, str]]] | bool:
15
+ """
16
+ Finds contact between two body groups. Any geom in the body is considered to be in contact.
17
+ Args:
18
+ mj_model (MujocoModel): Current simulation object
19
+ mj_data (MjData): Current simulation data
20
+ bodies_1 (str or list of int): an individual body name or list of body names.
21
+ bodies_2 (str or list of int): another individual body name or list of body names.
22
+ Returns:
23
+ bool: True if any body in @bodies_1 is in contact with any body in @bodies_2.
24
+ """
25
+ if isinstance(bodies_1, str):
26
+ bodies_1 = [bodies_1]
27
+ if isinstance(bodies_2, str):
28
+ bodies_2 = [bodies_2]
29
+
30
+ geoms_1 = [get_body_geom_ids(mj_model, mj_model.body(g).id) for g in bodies_1]
31
+ geoms_1 = [g for geom_list in geoms_1 for g in geom_list]
32
+ geoms_2 = [get_body_geom_ids(mj_model, mj_model.body(g).id) for g in bodies_2]
33
+ geoms_2 = [g for geom_list in geoms_2 for g in geom_list]
34
+ contact_bodies = []
35
+ for i in range(mj_data.ncon):
36
+ contact = mj_data.contact[i]
37
+ # check contact geom in geoms
38
+ c1_in_g1 = contact.geom1 in geoms_1
39
+ c2_in_g2 = contact.geom2 in geoms_2 if geoms_2 is not None else True
40
+ # check contact geom in geoms (flipped)
41
+ c2_in_g1 = contact.geom2 in geoms_1
42
+ c1_in_g2 = contact.geom1 in geoms_2 if geoms_2 is not None else True
43
+ if (c1_in_g1 and c2_in_g2) or (c1_in_g2 and c2_in_g1):
44
+ contact_bodies.append(
45
+ (
46
+ mj_model.body(mj_model.geom(contact.geom1).bodyid).name,
47
+ mj_model.body(mj_model.geom(contact.geom2).bodyid).name,
48
+ )
49
+ )
50
+ if not return_all_contact_bodies:
51
+ break
52
+ if return_all_contact_bodies:
53
+ return len(contact_bodies) > 0, set(contact_bodies)
54
+ else:
55
+ return len(contact_bodies) > 0
56
+
57
+
58
+ def check_height(
59
+ mj_model: mujoco.MjModel,
60
+ mj_data: mujoco.MjData,
61
+ geom_name: str,
62
+ lower_bound: float = -float("inf"),
63
+ upper_bound: float = float("inf"),
64
+ ):
65
+ """
66
+ Checks if the height of a geom is greater than a given height.
67
+ """
68
+ geom_id = mj_model.geom(geom_name).id
69
+ return (
70
+ mj_data.geom_xpos[geom_id][2] < upper_bound and mj_data.geom_xpos[geom_id][2] > lower_bound
71
+ )
sim/robot_model.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The simulated robot: Asimov 1 from the lerobot/robot-urdfs dataset, adapted for this sim.
2
+
3
+ The dataset holds Menlo's MJCF in Menlo's livery as a standalone viewer scene: its own
4
+ floor, lights and skyboxes, and no actuators (training adds them in Python). This
5
+ writes the robot alone, as the G1 robot files are, next to a copy of the scene in
6
+ ``assets/``, which adds the world:
7
+
8
+ * meshes resolve from the downloaded dataset
9
+ * floor, lights, skyboxes and ground textures removed
10
+ * one torque motor per joint, in firmware order, limited to the joint's actuatorfrcrange
11
+ * head and wrist cameras, the names the G1 sim publishes
12
+ """
13
+
14
+ import shutil
15
+ import tempfile
16
+ import xml.etree.ElementTree as ET # nosec B405
17
+ from pathlib import Path
18
+
19
+ from huggingface_hub import snapshot_download
20
+
21
+ ROOT = Path(__file__).resolve().parent.parent
22
+
23
+ # Camera looks along its local -Z. right = -Y, up = +Z looks along the parent +X.
24
+ LOOK_FORWARD = "0 -1 0 0 0 1"
25
+ CAMERAS = (
26
+ # name, parent body, position in the parent, vertical field of view
27
+ ("head_camera", "neck_pitch_link", "0.09 0 0.06", "90"),
28
+ ("left_wrist_cam", "left_wrist_yaw_link", "0.09 0 0", "95"),
29
+ ("right_wrist_cam", "right_wrist_yaw_link", "0.09 0 0", "95"),
30
+ )
31
+ WORLD_TEXTURES = {"groundplane", "texplane", ""}
32
+ WORLD_MATERIALS = {"groundplane"}
33
+
34
+
35
+ def download_robot(config: dict) -> Path:
36
+ """The robot's folder (xml/, meshes/) at the pinned dataset revision, from the Hub cache."""
37
+ folder = config["ROBOT_MODEL_PATH"]
38
+ root = snapshot_download(
39
+ config["ROBOT_MODEL_REPO"],
40
+ repo_type="dataset",
41
+ revision=config["ROBOT_MODEL_REVISION"],
42
+ allow_patterns=[f"{folder}/xml/*", f"{folder}/meshes/*"],
43
+ )
44
+ return Path(root) / folder
45
+
46
+
47
+ def robot_mjcf(config: dict, robot_dir: Path) -> ET.ElementTree:
48
+ tree = ET.parse(robot_dir / "xml" / f"{config['ROBOT_TYPE']}.xml") # nosec B314
49
+ root = tree.getroot()
50
+ root.set("name", config["ROBOT_TYPE"])
51
+
52
+ root.find("compiler").set("meshdir", str(robot_dir / "meshes"))
53
+ for visual in root.findall("visual"):
54
+ root.remove(visual)
55
+
56
+ asset = root.find("asset")
57
+ for texture in asset.findall("texture"):
58
+ if texture.get("type") == "skybox" or texture.get("name", "") in WORLD_TEXTURES:
59
+ asset.remove(texture)
60
+ for material in asset.findall("material"):
61
+ if material.get("name") in WORLD_MATERIALS:
62
+ asset.remove(material)
63
+
64
+ worldbody = root.find("worldbody")
65
+ for child in list(worldbody):
66
+ if child.tag in ("light", "geom"):
67
+ worldbody.remove(child)
68
+
69
+ bodies = {body.get("name"): body for body in root.iter("body")}
70
+ for name, parent, pos, fovy in CAMERAS:
71
+ ET.SubElement(bodies[parent], "camera", name=name, pos=pos, xyaxes=LOOK_FORWARD, fovy=fovy)
72
+
73
+ joints = {joint.get("name"): joint for joint in root.iter("joint")}
74
+ actuator = ET.SubElement(root, "actuator")
75
+ for name in config["JOINT_NAMES"]:
76
+ low, high = joints[name].get("actuatorfrcrange").split()
77
+ ET.SubElement(actuator, "motor", name=name.removesuffix("_joint"), joint=name, ctrlrange=f"{low} {high}")
78
+ return tree
79
+
80
+
81
+ def scene_path(config: dict) -> Path:
82
+ """Write the sim's robot MJCF beside a copy of ROBOT_SCENE and return that scene."""
83
+ robot_dir = download_robot(config)
84
+ scene = ROOT / config["ROBOT_SCENE"]
85
+ out = Path(tempfile.mkdtemp(prefix="asimov-mujoco-"))
86
+ shutil.copy(scene, out / scene.name)
87
+ robot_mjcf(config, robot_dir).write(out / f"{config['ROBOT_TYPE']}.xml", encoding="unicode")
88
+ return out / scene.name
sim/sensor_utils.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Standalone sensor utilities for camera image publishing via ZMQ"""
2
+ import base64
3
+ import json
4
+ from dataclasses import dataclass
5
+ from typing import Any, Dict
6
+
7
+ import cv2
8
+ import numpy as np
9
+ import zmq
10
+
11
+
12
+ @dataclass
13
+ class ImageMessageSchema:
14
+ """
15
+ Standardized message schema for image data.
16
+ Used to serialize/deserialize image data for network transmission.
17
+ """
18
+
19
+ timestamps: Dict[str, float]
20
+ """Dictionary of timestamps, keyed by image identifier (e.g., {"ego_view": 123.45})"""
21
+ images: Dict[str, np.ndarray]
22
+ """Dictionary of images, keyed by image identifier (e.g., {"ego_view": array})"""
23
+
24
+ def serialize(self) -> Dict[str, Any]:
25
+ """Serialize the message for transmission."""
26
+ serialized_msg = {"timestamps": self.timestamps, "images": {}}
27
+ for key, image in self.images.items():
28
+ serialized_msg["images"][key] = ImageUtils.encode_image(image)
29
+ return serialized_msg
30
+
31
+ @staticmethod
32
+ def deserialize(data: Dict[str, Any]) -> "ImageMessageSchema":
33
+ """Deserialize received message data."""
34
+ timestamps = data.get("timestamps", {})
35
+ images = {}
36
+ for key, value in data.get("images", {}).items():
37
+ if isinstance(value, str):
38
+ images[key] = ImageUtils.decode_image(value)
39
+ else:
40
+ images[key] = value
41
+ return ImageMessageSchema(timestamps=timestamps, images=images)
42
+
43
+ def asdict(self) -> Dict[str, Any]:
44
+ """Convert to dictionary format."""
45
+ return {"timestamps": self.timestamps, "images": self.images}
46
+
47
+
48
+ class SensorServer:
49
+ """ZMQ-based sensor server for publishing camera images"""
50
+
51
+ def start_server(self, port: int):
52
+ self.context = zmq.Context()
53
+ self.socket = self.context.socket(zmq.PUB)
54
+ self.socket.setsockopt(zmq.SNDHWM, 20) # high water mark
55
+ self.socket.setsockopt(zmq.LINGER, 0)
56
+ self.socket.bind(f"tcp://*:{port}")
57
+ print(f"Sensor server running at tcp://*:{port}")
58
+
59
+ self.message_sent = 0
60
+ self.message_dropped = 0
61
+
62
+ def stop_server(self):
63
+ self.socket.close()
64
+ self.context.term()
65
+
66
+ def send_message(self, data: Dict[str, Any]):
67
+ try:
68
+ json_str = json.dumps(data)
69
+ self.socket.send_string(json_str, flags=zmq.NOBLOCK)
70
+ except zmq.Again:
71
+ self.message_dropped += 1
72
+ print(f"[Warning] message dropped: {self.message_dropped}")
73
+ self.message_sent += 1
74
+
75
+ if self.message_sent % 100 == 0:
76
+ print(
77
+ f"[Sensor server] Message sent: {self.message_sent}, message dropped: {self.message_dropped}"
78
+ )
79
+
80
+
81
+ class SensorClient:
82
+ """ZMQ-based sensor client for subscribing to camera images"""
83
+
84
+ def start_client(self, server_ip: str, port: int):
85
+ self.context = zmq.Context()
86
+ self.socket = self.context.socket(zmq.SUB)
87
+ self.socket.setsockopt_string(zmq.SUBSCRIBE, "")
88
+ self.socket.setsockopt(zmq.CONFLATE, True) # last msg only.
89
+ self.socket.setsockopt(zmq.RCVHWM, 3) # queue size 3 for receive buffer
90
+ self.socket.connect(f"tcp://{server_ip}:{port}")
91
+
92
+ def stop_client(self):
93
+ self.socket.close()
94
+ self.context.term()
95
+
96
+ def receive_message(self):
97
+ json_str = self.socket.recv_string()
98
+ return json.loads(json_str)
99
+
100
+
101
+ class ImageUtils:
102
+ """Utilities for encoding/decoding images for network transmission"""
103
+
104
+ @staticmethod
105
+ def encode_image(image: np.ndarray) -> str:
106
+ """Encode numpy image to base64-encoded JPEG string"""
107
+ _, color_buffer = cv2.imencode(".jpg", image, [int(cv2.IMWRITE_JPEG_QUALITY), 80])
108
+ return base64.b64encode(color_buffer).decode("utf-8")
109
+
110
+ @staticmethod
111
+ def encode_depth_image(image: np.ndarray) -> str:
112
+ """Encode depth image to base64-encoded PNG string"""
113
+ depth_compressed = cv2.imencode(".png", image)[1].tobytes()
114
+ return base64.b64encode(depth_compressed).decode("utf-8")
115
+
116
+ @staticmethod
117
+ def decode_image(image: str) -> np.ndarray:
118
+ """Decode base64-encoded JPEG string to numpy image"""
119
+ color_data = base64.b64decode(image)
120
+ color_array = np.frombuffer(color_data, dtype=np.uint8)
121
+ return cv2.imdecode(color_array, cv2.IMREAD_COLOR)
122
+
123
+ @staticmethod
124
+ def decode_depth_image(image: str) -> np.ndarray:
125
+ """Decode base64-encoded PNG string to depth image"""
126
+ depth_data = base64.b64decode(image)
127
+ depth_array = np.frombuffer(depth_data, dtype=np.uint8)
128
+ return cv2.imdecode(depth_array, cv2.IMREAD_UNCHANGED)
129
+
sim/sim_utils.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Utility functions for working with Mujoco models.
3
+ copied from https://github.com/kevinzakka/mink/blob/main/mink/utils.py
4
+ """
5
+
6
+ from typing import List
7
+
8
+ import mujoco
9
+
10
+
11
+ def get_body_body_ids(model: mujoco.MjModel, body_id: int) -> List[int]:
12
+ """Get immediate children bodies belonging to a given body.
13
+
14
+ Args:
15
+ model: Mujoco model.
16
+ body_id: ID of body.
17
+
18
+ Returns:
19
+ A List containing all child body ids.
20
+ """
21
+ return [
22
+ i
23
+ for i in range(model.nbody)
24
+ if model.body_parentid[i] == body_id and body_id != i # Exclude the body itself.
25
+ ]
26
+
27
+
28
+ def get_subtree_body_ids(model: mujoco.MjModel, body_id: int) -> List[int]:
29
+ """Get all bodies belonging to subtree starting at a given body.
30
+
31
+ Args:
32
+ model: Mujoco model.
33
+ body_id: ID of body where subtree starts.
34
+
35
+ Returns:
36
+ A List containing all subtree body ids.
37
+ """
38
+ body_ids: List[int] = []
39
+ stack = [body_id]
40
+ while stack:
41
+ body_id = stack.pop()
42
+ body_ids.append(body_id)
43
+ stack += get_body_body_ids(model, body_id)
44
+ return body_ids
45
+
46
+
47
+ def get_subtree_body_names(model: mujoco.MjModel, body_id: int) -> List[str]:
48
+ """Get all bodies belonging to subtree starting at a given body.
49
+ Args:
50
+ model: Mujoco model.
51
+ body_id: ID of body where subtree starts.
52
+
53
+ Returns:
54
+ A List containing all subtree body names.
55
+ """
56
+ return [model.body(i).name for i in get_subtree_body_ids(model, body_id)]
57
+
58
+
59
+ def get_body_geom_ids(model: mujoco.MjModel, body_id: int) -> List[int]:
60
+ """Get immediate geoms belonging to a given body.
61
+
62
+ Here, immediate geoms are those directly attached to the body and not its
63
+ descendants.
64
+
65
+ Args:
66
+ model: Mujoco model.
67
+ body_id: ID of body.
68
+
69
+ Returns:
70
+ A list containing all body geom ids.
71
+ """
72
+ geom_start = model.body_geomadr[body_id]
73
+ geom_end = geom_start + model.body_geomnum[body_id]
74
+ return list(range(geom_start, geom_end))
75
+
76
+
77
+ def get_subtree_geom_ids(model: mujoco.MjModel, body_id: int) -> List[int]:
78
+ """Get all geoms belonging to subtree starting at a given body
79
+
80
+ Here, a subtree is defined as the kinematic tree starting at the body and including
81
+ all its descendants.
82
+
83
+ Args:
84
+ model: Mujoco model.
85
+ body_id: ID of body where subtree starts.
86
+
87
+ Returns:
88
+ A list containing all subtree geom ids.
89
+ """
90
+ geom_ids: List[int] = []
91
+ stack = [body_id]
92
+ while stack:
93
+ body_id = stack.pop()
94
+ geom_ids.extend(get_body_geom_ids(model, body_id))
95
+ stack += get_body_body_ids(model, body_id)
96
+ return geom_ids
sim/simulator_factory.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict
2
+
3
+ from .base_sim import BaseSimulator
4
+
5
+
6
+ class SimulatorFactory:
7
+ """Factory class for creating different types of simulators."""
8
+
9
+ @staticmethod
10
+ def create_simulator(config: Dict[str, Any], env_name: str = "default", **kwargs):
11
+ """
12
+ Create a simulator based on the configuration.
13
+
14
+ Args:
15
+ config: Configuration dictionary containing SIMULATOR type
16
+ env_name: Environment name
17
+ **kwargs: Additional keyword arguments for specific simulators
18
+ """
19
+ simulator_type = config.get("SIMULATOR", "mujoco")
20
+ if simulator_type == "mujoco":
21
+ return SimulatorFactory._create_mujoco_simulator(config, env_name, **kwargs)
22
+ else:
23
+ print(
24
+ f"Warning: Invalid simulator type: {simulator_type}. "
25
+ "If you are using run_sim_loop, please ignore this warning."
26
+ )
27
+ return None
28
+
29
+ @staticmethod
30
+ def _create_mujoco_simulator(config: Dict[str, Any], env_name: str = "default", **kwargs):
31
+ """Create a MuJoCo simulator instance."""
32
+ camera_configs = kwargs.pop("camera_configs", {})
33
+ if len(camera_configs) > 0:
34
+ print(f"Debug: SimulatorFactory received {len(camera_configs)} camera config(s)")
35
+
36
+ env_kwargs = dict(
37
+ onscreen=kwargs.pop("onscreen", True),
38
+ offscreen=kwargs.pop("offscreen", False),
39
+ camera_configs=camera_configs,
40
+ )
41
+ return BaseSimulator(config=config, env_name=env_name, **env_kwargs)
tests/smoke_live.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """End to end: LeRobot's Asimov driver walks the sim with its locomotion controller.
3
+
4
+ Runs the sim headless in this process on the default Edge ports, connects
5
+ ``lerobot.robots.asimov.Asimov`` to it as to a real robot (control_mode=whole_body),
6
+ drops the band, then stands, walks, turns and stops, printing the pelvis pose.
7
+ Needs a LeRobot checkout with the Asimov driver and its ``asimov`` extra.
8
+
9
+ MUJOCO_GL=egl python tests/smoke_live.py
10
+ """
11
+
12
+ import os
13
+ import sys
14
+ import time
15
+ from pathlib import Path
16
+
17
+ import numpy as np
18
+ import yaml
19
+
20
+ ROOT = Path(__file__).resolve().parent.parent
21
+ sys.path.insert(0, str(ROOT))
22
+ os.environ.setdefault("MUJOCO_GL", "egl")
23
+
24
+ from lerobot.robots.asimov import Asimov, AsimovConfig # noqa: E402
25
+
26
+ from sim.simulator_factory import SimulatorFactory # noqa: E402
27
+
28
+
29
+ def main() -> None:
30
+ config = yaml.safe_load((ROOT / "config.yaml").read_text())
31
+ config["PRINT_SCENE_INFORMATION"] = False
32
+ sim = SimulatorFactory.create_simulator(config=config, onscreen=False, offscreen=False, camera_configs={})
33
+ sim.start_as_thread()
34
+ env = sim.sim_env
35
+ robot = Asimov(AsimovConfig(host="127.0.0.1", control_mode="whole_body", robot_supported=True))
36
+
37
+ def report(tag: str) -> None:
38
+ q = env.mj_data.qpos
39
+ w, x, y, z = q[3:7]
40
+ yaw = np.degrees(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z)))
41
+ print(f"{tag:22s} pelvis z={q[2]:.3f} xy=({q[0]:+.2f},{q[1]:+.2f}) yaw={yaw:+.0f}")
42
+
43
+ def drive(seconds: float, vx: float = 0.0, yaw_deg: float = 0.0) -> None:
44
+ end = time.monotonic() + seconds
45
+ while time.monotonic() < end:
46
+ robot.send_action({"x.vel": vx, "y.vel": 0.0, "theta.vel": yaw_deg})
47
+ time.sleep(1 / 30)
48
+
49
+ try:
50
+ robot.connect()
51
+ drive(3.0)
52
+ report("on the band")
53
+ env.elastic_band.enable = False
54
+ drive(3.0)
55
+ report("standing")
56
+ assert env.mj_data.qpos[2] > 0.55, "fell after the band was released"
57
+ start = env.mj_data.qpos[0]
58
+ drive(5.0, vx=0.3)
59
+ report("walked 5 s at 0.3 m/s")
60
+ assert env.mj_data.qpos[0] - start > 0.8, "did not walk forward"
61
+ drive(4.0, yaw_deg=25.0)
62
+ report("turned 4 s at 25 deg/s")
63
+ drive(3.0)
64
+ report("stopped")
65
+ assert env.mj_data.qpos[2] > 0.55, "fell"
66
+ print("OK")
67
+ finally:
68
+ if robot.is_connected:
69
+ robot.disconnect()
70
+ sim.close()
71
+
72
+
73
+ if __name__ == "__main__":
74
+ main()
tests/test_sim.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The sim against the real MuJoCo and the Edge protocol, headless and on spare ports.
2
+
3
+ MUJOCO_GL=egl python -m unittest discover -s tests -v
4
+ """
5
+
6
+ import json
7
+ import socket
8
+ import sys
9
+ import time
10
+ import unittest
11
+ import urllib.request
12
+ from pathlib import Path
13
+
14
+ import mujoco
15
+ import numpy as np
16
+ import yaml
17
+ from asimov_protocol.v1 import asimov_command_pb2, asimov_common_pb2, asimov_state_pb2
18
+
19
+ ROOT = Path(__file__).resolve().parent.parent
20
+ sys.path.insert(0, str(ROOT))
21
+
22
+ from sim.asimov_edge_bridge import joints_to_motors # noqa: E402
23
+ from sim.simulator_factory import SimulatorFactory # noqa: E402
24
+
25
+ PORTS = {"COMMAND_PORT": 18850, "STATE_PORT": 18851, "VERSION_PORT": 13000}
26
+
27
+
28
+ def wait_for(predicate, timeout=3.0):
29
+ end = time.monotonic() + timeout
30
+ while time.monotonic() < end:
31
+ if predicate():
32
+ return True
33
+ time.sleep(0.02)
34
+ return False
35
+
36
+
37
+ class AsimovSimTest(unittest.TestCase):
38
+ @classmethod
39
+ def setUpClass(cls):
40
+ config = yaml.safe_load((ROOT / "config.yaml").read_text())
41
+ config.update(PORTS, PRINT_SCENE_INFORMATION=False, SETPOINT_TIMEOUT_S=0.5)
42
+ cls.config = config
43
+ cls.state_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
44
+ cls.state_sock.bind(("127.0.0.1", PORTS["STATE_PORT"]))
45
+ cls.state_sock.settimeout(1.0)
46
+ cls.command_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
47
+ cls.sim = SimulatorFactory.create_simulator(config=config, onscreen=False, offscreen=False, camera_configs={})
48
+ cls.env = cls.sim.sim_env
49
+ cls.model = cls.env.mj_model
50
+ cls.sim.start_as_thread()
51
+
52
+ @classmethod
53
+ def tearDownClass(cls):
54
+ cls.sim.close()
55
+ cls.state_sock.close()
56
+ cls.command_sock.close()
57
+
58
+ def latest_state(self) -> asimov_state_pb2.RobotState:
59
+ self.state_sock.setblocking(False)
60
+ msg = None
61
+ try:
62
+ while True:
63
+ msg = self.state_sock.recv(65535)
64
+ except BlockingIOError:
65
+ pass
66
+ finally:
67
+ self.state_sock.settimeout(1.0)
68
+ if msg is None:
69
+ msg = self.state_sock.recv(65535)
70
+ state = asimov_state_pb2.RobotState()
71
+ state.ParseFromString(msg)
72
+ return state
73
+
74
+ def send(self, command: asimov_command_pb2.RobotCommand):
75
+ self.command_sock.sendto(command.SerializeToString(), ("127.0.0.1", PORTS["COMMAND_PORT"]))
76
+
77
+ def test_model_matches_config(self):
78
+ self.assertEqual(self.model.nu, len(self.config["JOINT_NAMES"]))
79
+ joints = [self.model.joint(self.model.actuator_trnid[i, 0]).name for i in range(self.model.nu)]
80
+ self.assertEqual(joints, self.config["JOINT_NAMES"])
81
+ for name in ("head_camera", "left_wrist_cam", "right_wrist_cam", "global_view"):
82
+ self.assertGreaterEqual(mujoco.mj_name2id(self.model, mujoco.mjtObj.mjOBJ_CAMERA, name), 0, name)
83
+
84
+ def test_robot_in_menlo_livery(self):
85
+ torso = self.model.body("waist_yaw_link").id
86
+ materials = {
87
+ self.model.material(self.model.geom_matid[g]).name
88
+ for g in range(self.model.ngeom)
89
+ if self.model.geom_bodyid[g] == torso and self.model.geom_type[g] == mujoco.mjtGeom.mjGEOM_MESH
90
+ }
91
+ self.assertEqual(materials, {"asimov_orange", "asimov_black"})
92
+
93
+ def test_version_endpoint(self):
94
+ url = f"http://127.0.0.1:{PORTS['VERSION_PORT']}/api/version"
95
+ facts = json.loads(urllib.request.urlopen(url, timeout=2).read())
96
+ self.assertEqual(facts, {"robot_model": "asimov_1", "robot_os_version": self.config["ROBOT_OS_VERSION"]})
97
+
98
+ def test_state_and_trajectory_then_damp(self):
99
+ state = self.latest_state()
100
+ self.assertEqual(len(state.joint_pos), 25)
101
+ self.assertEqual(state.current_mode, asimov_common_pb2.CONTROL_MODE_STAND)
102
+ np.testing.assert_allclose(state.projected_gravity, [0, 0, -1], atol=0.1)
103
+ np.testing.assert_allclose(
104
+ state.joint_pos, joints_to_motors(self.config["STAND_POSE"]), atol=0.15
105
+ )
106
+
107
+ command = asimov_command_pb2.RobotCommand(sequence=7, protocol_version=1)
108
+ command.all_trajectory.positions.extend(self.config["STAND_POSE"])
109
+ command.all_trajectory.kp.extend(self.config["STAND_KP"])
110
+ command.all_trajectory.kd.extend(self.config["STAND_KD"])
111
+ self.send(command)
112
+ self.assertTrue(
113
+ wait_for(lambda: self.latest_state().current_mode == asimov_common_pb2.CONTROL_MODE_MOVE)
114
+ )
115
+ self.assertEqual(self.latest_state().last_cmd_sequence, 7)
116
+ self.assertTrue(
117
+ wait_for(lambda: self.latest_state().current_mode == asimov_common_pb2.CONTROL_MODE_DAMP, timeout=2.0)
118
+ )
119
+
120
+ self.send(asimov_command_pb2.RobotCommand(mode=asimov_common_pb2.CONTROL_MODE_STAND, sequence=8))
121
+ self.assertTrue(
122
+ wait_for(lambda: self.latest_state().current_mode == asimov_common_pb2.CONTROL_MODE_STAND)
123
+ )
124
+
125
+ def test_band_holds_the_robot(self):
126
+ self.assertTrue(self.env.elastic_band.enable)
127
+ time.sleep(1.0)
128
+ height = self.env.mj_data.qpos[2]
129
+ self.assertGreater(height, 0.6)
130
+ self.assertLess(height, self.config["BAND_HEIGHT"] - 0.01)
131
+
132
+
133
+ class AnkleCouplingTest(unittest.TestCase):
134
+ def test_pitch_and_roll_to_motors(self):
135
+ joints = np.zeros(25)
136
+ joints[4], joints[5] = 0.1, 0.0
137
+ motors = joints_to_motors(joints)
138
+ self.assertAlmostEqual(motors[4], 0.202)
139
+ self.assertAlmostEqual(motors[5], -0.202)
140
+ joints[4], joints[5] = 0.0, 0.1
141
+ motors = joints_to_motors(joints)
142
+ self.assertAlmostEqual(motors[4], -0.08)
143
+ self.assertAlmostEqual(motors[5], -0.08)
144
+
145
+
146
+ if __name__ == "__main__":
147
+ unittest.main()
view_cameras_live.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Live camera viewer for MuJoCo simulator using matplotlib
4
+ Works without X11/GTK - suitable for SSH sessions with X forwarding
5
+ """
6
+ import argparse
7
+ import sys
8
+ import time
9
+ from pathlib import Path
10
+
11
+ # Add sim module to path
12
+ sys.path.insert(0, str(Path(__file__).parent))
13
+
14
+ import cv2
15
+ import numpy as np
16
+ import matplotlib.pyplot as plt
17
+ from matplotlib.animation import FuncAnimation
18
+ from sim.sensor_utils import SensorClient, ImageUtils
19
+
20
+
21
+ class CameraViewer:
22
+ def __init__(self, host, port):
23
+ self.client = SensorClient()
24
+ self.client.start_client(server_ip=host, port=port)
25
+
26
+ self.fig = None
27
+ self.axes = {}
28
+ self.images = {}
29
+ self.text_objs = {}
30
+
31
+ self.frame_count = 0
32
+ self.last_time = time.time()
33
+ self.fps = 0
34
+
35
+ def init_plot(self):
36
+ """Initialize matplotlib figure and axes"""
37
+ # Wait for first frame to know how many cameras we have
38
+ print("Waiting for first frame to detect cameras...")
39
+ data = self.client.receive_message()
40
+
41
+ # Parse camera names - handle nested 'images' dict
42
+ camera_names = []
43
+ if "images" in data and isinstance(data["images"], dict):
44
+ # Nested structure: data["images"]["camera_name"]
45
+ camera_names = list(data["images"].keys())
46
+ else:
47
+ # Flat structure: data["camera_name"] directly
48
+ camera_names = [k for k in data.keys() if k not in ["timestamps", "images"]]
49
+
50
+ num_cameras = len(camera_names)
51
+
52
+ if num_cameras == 0:
53
+ print("No cameras found in stream!")
54
+ return False
55
+
56
+ print(f"Found {num_cameras} camera(s): {', '.join(camera_names)}")
57
+
58
+ # Create subplots
59
+ if num_cameras == 1:
60
+ self.fig, ax = plt.subplots(1, 1, figsize=(10, 8))
61
+ axes_list = [ax]
62
+ elif num_cameras == 2:
63
+ self.fig, axes_list = plt.subplots(1, 2, figsize=(16, 6))
64
+ else:
65
+ rows = (num_cameras + 1) // 2
66
+ self.fig, axes_list = plt.subplots(rows, 2, figsize=(16, 6 * rows))
67
+ axes_list = axes_list.flatten()
68
+
69
+ # Initialize each camera subplot
70
+ for i, cam_name in enumerate(camera_names):
71
+ ax = axes_list[i]
72
+ ax.set_title(f"{cam_name}", fontsize=12, fontweight='bold')
73
+ ax.axis('off')
74
+
75
+ # Get image data from nested or flat structure
76
+ if "images" in data and cam_name in data["images"]:
77
+ img_data = data["images"][cam_name]
78
+ elif cam_name in data:
79
+ img_data = data[cam_name]
80
+ else:
81
+ img_data = cam_name # Use the actual data if it's the value
82
+
83
+ # Decode first image
84
+ if isinstance(img_data, str):
85
+ img = ImageUtils.decode_image(img_data)
86
+ elif isinstance(img_data, np.ndarray):
87
+ img = img_data
88
+ else:
89
+ print(f"Warning: Unknown image format for {cam_name}: {type(img_data)}")
90
+ continue
91
+
92
+ # Check if image is valid
93
+ if img is None or not isinstance(img, np.ndarray):
94
+ print(f"Warning: Invalid image data for {cam_name}")
95
+ continue
96
+
97
+ # Convert BGR to RGB for matplotlib
98
+ img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
99
+
100
+ # Display image
101
+ im = ax.imshow(img_rgb)
102
+ self.images[cam_name] = im
103
+ self.axes[cam_name] = ax
104
+
105
+ # Add FPS text
106
+ text = ax.text(0.02, 0.98, 'FPS: 0.0',
107
+ transform=ax.transAxes,
108
+ fontsize=10,
109
+ verticalalignment='top',
110
+ bbox=dict(boxstyle='round', facecolor='black', alpha=0.7),
111
+ color='lime',
112
+ fontweight='bold')
113
+ self.text_objs[cam_name] = text
114
+
115
+ # Hide unused subplots
116
+ if num_cameras < len(axes_list):
117
+ for i in range(num_cameras, len(axes_list)):
118
+ axes_list[i].axis('off')
119
+
120
+ self.fig.tight_layout()
121
+ return True
122
+
123
+ def update_frame(self, frame_num):
124
+ """Update function for animation"""
125
+ try:
126
+ # Receive new frame
127
+ data = self.client.receive_message()
128
+
129
+ # Calculate FPS
130
+ self.frame_count += 1
131
+ current_time = time.time()
132
+ if current_time - self.last_time >= 1.0:
133
+ self.fps = self.frame_count / (current_time - self.last_time)
134
+ self.frame_count = 0
135
+ self.last_time = current_time
136
+
137
+ # Update each camera
138
+ for cam_name in self.images.keys():
139
+ # Get image data from nested or flat structure
140
+ if "images" in data and cam_name in data["images"]:
141
+ img_data = data["images"][cam_name]
142
+ elif cam_name in data:
143
+ img_data = data[cam_name]
144
+ else:
145
+ continue
146
+
147
+ # Decode image
148
+ if isinstance(img_data, str):
149
+ img = ImageUtils.decode_image(img_data)
150
+ elif isinstance(img_data, np.ndarray):
151
+ img = img_data
152
+ else:
153
+ continue
154
+
155
+ # Check if image is valid
156
+ if img is None or not isinstance(img, np.ndarray):
157
+ continue
158
+
159
+ # Convert BGR to RGB for matplotlib
160
+ img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
161
+
162
+ # Update image
163
+ self.images[cam_name].set_data(img_rgb)
164
+
165
+ # Update FPS text
166
+ self.text_objs[cam_name].set_text(f'FPS: {self.fps:.1f}')
167
+
168
+ except Exception as e:
169
+ print(f"Error updating frame: {e}")
170
+
171
+ return list(self.images.values()) + list(self.text_objs.values())
172
+
173
+ def start(self, interval=33):
174
+ """Start the live viewer"""
175
+ if not self.init_plot():
176
+ return
177
+
178
+ print(f"\n{'='*60}")
179
+ print("📹 Live camera viewer started!")
180
+ print("Close the window or press Ctrl+C to exit")
181
+ print(f"{'='*60}\n")
182
+
183
+ # Create animation
184
+ anim = FuncAnimation(
185
+ self.fig,
186
+ self.update_frame,
187
+ interval=interval, # ms between frames
188
+ blit=True,
189
+ cache_frame_data=False
190
+ )
191
+
192
+ try:
193
+ plt.show()
194
+ except KeyboardInterrupt:
195
+ print("\nStopping viewer...")
196
+ finally:
197
+ self.client.stop_client()
198
+ plt.close('all')
199
+
200
+
201
+ def main():
202
+ parser = argparse.ArgumentParser(description="Live camera viewer for MuJoCo simulator")
203
+ parser.add_argument("--host", type=str, default="localhost",
204
+ help="Simulator host address (default: localhost)")
205
+ parser.add_argument("--port", type=int, default=5554,
206
+ help="ZMQ port (default: 5555)")
207
+ parser.add_argument("--interval", type=int, default=33,
208
+ help="Update interval in ms (default: 33 = ~30fps)")
209
+ args = parser.parse_args()
210
+
211
+ print("="*60)
212
+ print("📷 MuJoCo Live Camera Viewer (matplotlib)")
213
+ print("="*60)
214
+ print(f"🌐 Connecting to: tcp://{args.host}:{args.port}")
215
+ print(f"⏱️ Update interval: {args.interval}ms (~{1000/args.interval:.0f} fps)")
216
+ print("="*60)
217
+
218
+ viewer = CameraViewer(host=args.host, port=args.port)
219
+ viewer.start(interval=args.interval)
220
+
221
+
222
+ if __name__ == "__main__":
223
+ main()
224
+