Skip to content

Commit 728450e

Browse files
authored
fix: support hfield in warp lidar (#17)
* fix: support hfield in warp lidar * test: update go2 benchmark scenes * chore: refresh lockfile from pypi * ci: test only python 3.12
1 parent a1c30b6 commit 728450e

20 files changed

Lines changed: 1412 additions & 1302 deletions

‎.github/workflows/ci.yml‎

Lines changed: 7 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -11,39 +11,24 @@ jobs:
1111
steps:
1212
- uses: actions/checkout@v4
1313
- uses: astral-sh/setup-uv@v4
14-
- run: uv sync --extra dev
15-
- run: uv run ruff check .
16-
- run: uv run ruff format --check .
14+
- run: uv sync --python 3.12 --extra dev
15+
- run: uv run python -m ruff check .
16+
- run: uv run python -m ruff format --check .
1717

1818
test-cpu:
1919
needs: lint
2020
runs-on: ubuntu-latest
21-
strategy:
22-
matrix:
23-
python-version: ['3.10', '3.11', '3.12', '3.13']
2421
steps:
2522
- uses: actions/checkout@v4
2623
- uses: astral-sh/setup-uv@v4
27-
- run: uv sync --python ${{ matrix.python-version }} --extra dev
28-
- run: uv run pytest tests/test_core.py tests/test_cpu_backend.py tests/test_scan_gen.py -v
24+
- run: uv sync --python 3.12 --extra dev
25+
- run: uv run python -m pytest tests/test_core.py tests/test_cpu_backend.py tests/test_scan_gen.py -v
2926

3027
test-backends:
3128
needs: lint
3229
runs-on: ubuntu-latest
3330
steps:
3431
- uses: actions/checkout@v4
3532
- uses: astral-sh/setup-uv@v4
36-
- run: uv sync --extra taichi --extra jax --extra dev
37-
- run: uv run pytest tests/test_integration.py -v
38-
39-
benchmark:
40-
needs: test-cpu
41-
runs-on: ubuntu-latest
42-
steps:
43-
- uses: actions/checkout@v4
44-
with:
45-
fetch-depth: 0
46-
- uses: astral-sh/setup-uv@v4
47-
- run: uv sync
48-
- run: uv run python benchmarks/benchmark_core.py
49-
- run: uv run python benchmarks/check_regression.py
33+
- run: uv sync --python 3.12 --extra taichi --extra jax --extra dev
34+
- run: uv run python -m pytest tests/test_integration.py -v

‎benchmarks/benchmark_core.py‎

Lines changed: 90 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,17 @@
11
import time
2+
from pathlib import Path
23

34
import mujoco
45
import numpy as np
56

67
from mujoco_lidar import MjLidarWrapper, scan_gen
78

8-
9-
def create_benchmark_scene():
10-
"""创建基准测试场景"""
11-
xml = """
12-
<mujoco>
13-
<worldbody>
14-
<body name="box1" pos="2 0 0.5">
15-
<geom type="box" size="0.5 0.5 0.5"/>
16-
</body>
17-
<body name="box2" pos="0 2 0.5">
18-
<geom type="box" size="0.5 0.5 0.5"/>
19-
</body>
20-
<body name="sphere" pos="-2 0 0.5">
21-
<geom type="sphere" size="0.5"/>
22-
</body>
23-
<site name="lidar_site" pos="0 0 1"/>
24-
</worldbody>
25-
</mujoco>
26-
"""
27-
return mujoco.MjModel.from_xml_string(xml)
9+
_ROOT = Path(__file__).resolve().parent.parent
10+
_MODELS_DIR = _ROOT / "models"
11+
_TRACE_SCENES = {
12+
"go2": "scene_go2.xml",
13+
"go2_stairs": "scene_go2_stairs_terrain.xml",
14+
}
2815

2916

3017
def benchmark_ray_generation(n_runs=10):
@@ -49,52 +36,121 @@ def benchmark_ray_generation(n_runs=10):
4936
"mean_ms": np.mean(times) * 1000,
5037
"std_ms": np.std(times) * 1000,
5138
"n_rays": len(theta),
39+
"m_rays_per_sec": len(theta) / np.mean(times) / 1e6,
5240
}
5341

5442
return results
5543

5644

57-
def benchmark_trace_rays(backend="cpu", n_runs=10):
45+
def load_model(filename):
46+
return mujoco.MjModel.from_xml_path((_MODELS_DIR / filename).as_posix())
47+
48+
49+
def benchmark_trace_rays(scene_name, scene_file, backend="cpu", n_runs=10):
5850
"""基准测试:射线追踪速度"""
59-
model = create_benchmark_scene()
51+
model = load_model(scene_file)
6052
data = mujoco.MjData(model)
53+
mujoco.mj_resetDataKeyframe(model, data, 0)
54+
mujoco.mj_forward(model, data)
55+
56+
geomgroup = np.ones((mujoco.mjNGROUP,), dtype=np.ubyte)
57+
geomgroup[3:] = 0
6158

6259
try:
63-
lidar = MjLidarWrapper(model, site_name="lidar_site", backend=backend)
60+
lidar = MjLidarWrapper(
61+
model,
62+
site_name="lidar",
63+
backend=backend,
64+
args={"bodyexclude": model.body("base").id, "geomgroup": geomgroup},
65+
)
6466
except ImportError:
6567
return None
6668

67-
theta, phi = scan_gen.generate_HDL64()
69+
theta, phi = scan_gen.LivoxGenerator("mid360").sample_ray_angles()
70+
theta = np.ascontiguousarray(theta).astype(np.float32)
71+
phi = np.ascontiguousarray(phi).astype(np.float32)
6872

6973
# Warmup
70-
lidar.trace_rays(data, theta, phi)
74+
ranges = lidar.trace_rays(data, theta, phi)
75+
if hasattr(ranges, "block_until_ready"):
76+
ranges.block_until_ready()
7177

7278
times = []
7379
for _ in range(n_runs):
7480
start = time.perf_counter()
75-
lidar.trace_rays(data, theta, phi)
81+
ranges = lidar.trace_rays(data, theta, phi)
82+
if hasattr(ranges, "block_until_ready"):
83+
ranges.block_until_ready()
7684
elapsed = time.perf_counter() - start
7785
times.append(elapsed)
7886

7987
return {
88+
"scene": scene_name,
8089
"backend": backend,
8190
"mean_ms": np.mean(times) * 1000,
8291
"std_ms": np.std(times) * 1000,
8392
"n_rays": len(theta),
84-
"rays_per_sec": len(theta) / np.mean(times),
93+
"m_rays_per_sec": len(theta) / np.mean(times) / 1e6,
8594
}
8695

8796

97+
def print_table(headers, rows):
98+
widths = [len(header) for header in headers]
99+
for row in rows:
100+
for i, value in enumerate(row):
101+
widths[i] = max(widths[i], len(value))
102+
103+
fmt = " ".join(f"{{:<{width}}}" for width in widths)
104+
print(fmt.format(*headers))
105+
print(fmt.format(*["-" * width for width in widths]))
106+
for row in rows:
107+
print(fmt.format(*row))
108+
109+
88110
if __name__ == "__main__":
111+
generation_rows = []
112+
tracing_rows = []
113+
89114
print("=== Ray Generation Benchmark ===")
90115
gen_results = benchmark_ray_generation()
91116
for name, result in gen_results.items():
92-
print(f"{name}: {result['mean_ms']:.2f}±{result['std_ms']:.2f}ms ({result['n_rays']} rays)")
117+
print(
118+
f"{name}: {result['mean_ms']:.2f}±{result['std_ms']:.2f}ms "
119+
f"({result['m_rays_per_sec']:.3f} M rays/s)"
120+
)
121+
generation_rows.append(
122+
[
123+
name,
124+
str(result["n_rays"]),
125+
f"{result['mean_ms']:.2f}",
126+
f"{result['std_ms']:.2f}",
127+
f"{result['m_rays_per_sec']:.3f} M rays/s",
128+
]
129+
)
93130

94131
print("\n=== Ray Tracing Benchmark ===")
95-
for backend in ["cpu", "taichi", "jax", "warp"]:
96-
result = benchmark_trace_rays(backend)
97-
if result:
98-
print(
99-
f"{backend}: {result['mean_ms']:.2f}±{result['std_ms']:.2f}ms ({result['rays_per_sec']:.0f} rays/s)"
100-
)
132+
for scene_name, scene_file in _TRACE_SCENES.items():
133+
print(f"\n--- {scene_name} ({scene_file}) ---")
134+
for backend in ["cpu", "taichi", "jax", "warp"]:
135+
result = benchmark_trace_rays(scene_name, scene_file, backend)
136+
if result:
137+
print(
138+
f"{backend}: {result['mean_ms']:.2f}±{result['std_ms']:.2f}ms "
139+
f"({result['m_rays_per_sec']:.3f} M rays/s)"
140+
)
141+
tracing_rows.append(
142+
[
143+
scene_name,
144+
backend,
145+
str(result["n_rays"]),
146+
f"{result['mean_ms']:.2f}",
147+
f"{result['std_ms']:.2f}",
148+
f"{result['m_rays_per_sec']:.3f} M rays/s",
149+
]
150+
)
151+
152+
print("\n=== Ray Generation Summary ===")
153+
print_table(["Name", "Rays", "Mean ms", "Std ms", "Throughput"], generation_rows)
154+
155+
print("\n=== Ray Tracing Summary ===")
156+
print_table(["Scene", "Backend", "Rays", "Mean ms", "Std ms", "Throughput"], tracing_rows)

‎benchmarks/check_regression.py‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import sys
33
from pathlib import Path
44

5-
from benchmark_core import benchmark_trace_rays
5+
from benchmark_core import _TRACE_SCENES, benchmark_trace_rays
66

77
BASELINE_FILE = Path(__file__).parent / "baselines" / "baseline.json"
88
REGRESSION_THRESHOLD = 0.05 # 5% 性能下降阈值
@@ -25,7 +25,10 @@ def check_regression():
2525
baseline = load_baseline()
2626

2727
# 运行当前基准测试
28-
current = {"cpu": benchmark_trace_rays("cpu")}
28+
current = {
29+
f"{scene_name}/cpu": benchmark_trace_rays(scene_name, scene_file, backend="cpu")
30+
for scene_name, scene_file in _TRACE_SCENES.items()
31+
}
2932

3033
if baseline is None:
3134
print("No baseline found, saving current results as baseline")

‎examples/unitree_go2.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ def get_control(self, model: mujoco.MjModel, data: mujoco.MjData) -> None:
131131
policy = OnnxController(
132132
mj_model,
133133
policy_path=(_ONNX_DIR / "go2_policy.onnx").as_posix(),
134-
default_angles=np.array(mj_model.keyframe("home").qpos[7 : 7 + _JOINT_NUM]),
134+
default_angles=np.array(mj_model.key_qpos[0, 7 : 7 + _JOINT_NUM]),
135135
n_substeps=int(round(ctrl_dt / mj_model.opt.timestep)),
136136
action_scale=0.5,
137137
lidar_type=args.lidar,

‎examples/unitree_go2_ros2.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,7 @@ def load_callback(model=None, data=None):
169169
policy = OnnxControllerRos2(
170170
model,
171171
policy_path=(_ONNX_DIR / "go2_policy.onnx").as_posix(),
172-
default_angles=np.array(model.keyframe("home").qpos[7 : 7 + _JOINT_NUM]),
172+
default_angles=np.array(model.key_qpos[0, 7 : 7 + _JOINT_NUM]),
173173
n_substeps=n_substeps,
174174
action_scale=0.5,
175175
lidar_type=args.lidar,

‎models/scene_go2_stairs_terrain.xml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
<keyframe>
1313
<key name="home"
1414
qpos="
15-
7.47569 -0.507727 -0.119553
15+
0 0 2
1616
1 0 0 0
1717
0.1 0.9 -1.8
1818
-0.1 0.9 -1.8

‎pyproject.toml‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ dependencies = [
2323
"scipy",
2424
"pynput",
2525
"matplotlib",
26-
"zhplot",
2726
]
2827

2928
[project.optional-dependencies]

‎src/mujoco_lidar/core_cpu/mjlidar_cpu.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,10 +61,10 @@ def trace_rays(self, pose_4x4: np.ndarray, ray_theta: np.ndarray, ray_phi: np.nd
6161
cutoff=self.cutoff_dist,
6262
)
6363
# Calculate the point's position in local frame from vec + dist
64-
self._dist[_geomid == -1] = 0
64+
self._dist[_geomid == -1] = -1
6565

6666
# Update the pcl frame with local frame data
67-
self._hit_points = local_vecs * self._dist[:, np.newaxis]
67+
self._hit_points = local_vecs * np.maximum(self._dist, 0)[:, np.newaxis]
6868

6969
def get_hit_points(self) -> np.ndarray | None:
7070
return self._hit_points

‎src/mujoco_lidar/core_jax/mjlidar_jax.py‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -298,8 +298,7 @@ def scan_fn(carry, x):
298298
)
299299
min_dist = jnp.minimum(min_dist, d_hfields)
300300

301-
# Replace inf with 0.0 (no hit)
302-
distance = jnp.where(jnp.isinf(min_dist), 0.0, min_dist)
301+
distance = jnp.where(jnp.isinf(min_dist), -1.0, min_dist)
303302

304303
return distance
305304

‎src/mujoco_lidar/core_ti/mjlidar_ti.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -458,7 +458,7 @@ def _trace_kernel(
458458
[best_t * dir_local.x, best_t * dir_local.y, best_t * dir_local.z]
459459
)
460460
else:
461-
distances[i] = 0.0
461+
distances[i] = -1.0
462462
hit_pts[i] = ti.Vector([0.0, 0.0, 0.0])
463463

464464
def trace_rays_batch(self, sensor_pos, sensor_rot, theta, phi):
@@ -556,7 +556,7 @@ def _trace_rays_batch_kernel(
556556
hit_pts[ib, ir, 1] = best_t * dir_local.y
557557
hit_pts[ib, ir, 2] = best_t * dir_local.z
558558
else:
559-
distances[ib, ir] = 0.0
559+
distances[ib, ir] = -1.0
560560
hit_pts[ib, ir, 0] = 0.0
561561
hit_pts[ib, ir, 1] = 0.0
562562
hit_pts[ib, ir, 2] = 0.0

0 commit comments

Comments
 (0)