Skip to content

Commit 6f00ede

Browse files
committed
finalize docs, clean code, improve testing
1 parent 8fc0737 commit 6f00ede

17 files changed

Lines changed: 705 additions & 778 deletions

File tree

‎autodata_domain_randomization/camera.py‎

Lines changed: 39 additions & 79 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,11 @@
55

66
from __future__ import annotations
77

8-
import math
98
import torch
109
from typing import TYPE_CHECKING, Any
1110

11+
from autodata_utils import pose_math
12+
1213
if TYPE_CHECKING:
1314
from isaaclab.envs import ManagerBasedEnv
1415
from isaaclab.managers import SceneEntityCfg
@@ -90,24 +91,33 @@ def _randomize_extrinsics(
9091
from isaaclab.sim.utils import standardize_xform_ops
9192

9293
offset = sensor.cfg.offset
93-
nominal_position = tuple(float(component) for component in offset.pos)
94-
nominal_rotation = _convert_rotation(tuple(offset.rot), offset.convention, "ros")
94+
nominal_position = torch.tensor(offset.pos, dtype=torch.float64)
95+
nominal_rotation = pose_math.convert_camera_frame_orientation_convention(
96+
torch.tensor(offset.rot, dtype=torch.float64), offset.convention, "ros"
97+
)
9598
camera_prims = _find_camera_prims_by_env(env, env_ids, sensor)
9699

97100
applied = {}
98101
for env_id in env_ids:
99-
position_offset = _sample_uniform_vector(position_xyz_min, position_xyz_max, env.device)
100-
rotation_offset_deg = _sample_uniform_vector(rotation_rpy_min_deg, rotation_rpy_max_deg, env.device)
101-
position = tuple(nominal + sampled for nominal, sampled in zip(nominal_position, position_offset))
102-
rotation = _quat_multiply(nominal_rotation, _quat_from_rpy_deg(rotation_offset_deg))
102+
position_offset = pose_math.sample_uniform_vector(position_xyz_min, position_xyz_max, env.device)
103+
rotation_offset_deg = pose_math.sample_uniform_vector(rotation_rpy_min_deg, rotation_rpy_max_deg, env.device)
104+
position = nominal_position + position_offset
105+
rotation = pose_math.quat_mul(
106+
nominal_rotation, pose_math.quat_from_euler_xyz(torch.deg2rad(rotation_offset_deg))
107+
)
108+
position_xyz = tuple(position.tolist())
103109
standardize_xform_ops(
104110
camera_prims[env_id],
105-
translation=position,
106-
orientation=_convert_rotation(rotation, "ros", "opengl"),
111+
translation=position_xyz,
112+
orientation=tuple(
113+
pose_math.convert_camera_frame_orientation_convention(rotation, "ros", "opengl").tolist()
114+
),
107115
)
108116
applied[env_id] = {
109-
"position_xyz": position,
110-
"rotation_xyzw": _convert_rotation(rotation, "ros", offset.convention),
117+
"position_xyz": position_xyz,
118+
"rotation_xyzw": tuple(
119+
pose_math.convert_camera_frame_orientation_convention(rotation, "ros", offset.convention).tolist()
120+
),
111121
}
112122
return applied
113123

@@ -129,7 +139,7 @@ def _randomize_intrinsics(
129139
height, width = sensor.image_shape
130140
nominal_focal_length_px = width * focal_length / horizontal_aperture
131141
scales = torch.tensor(
132-
[_sample_uniform(focal_length_scale_range, env.device) for _ in env_ids],
142+
[pose_math.sample_uniform_scalar(focal_length_scale_range, env.device) for _ in env_ids],
133143
dtype=torch.float32,
134144
device=env.device,
135145
)
@@ -140,23 +150,26 @@ def _randomize_intrinsics(
140150
matrices[:, 0, 2] = 0.5 * width
141151
matrices[:, 1, 2] = 0.5 * height
142152
matrices[:, 2, 2] = 1.0
143-
prims = _find_camera_prims_by_env(env, env_ids, sensor)
144-
nominal = [prims[env_id].GetCustomDataByKey("isaaclab_arena:nominal_opencv_intrinsics") for env_id in env_ids]
145-
if any(value is not None for value in nominal):
146-
assert all(value is not None for value in nominal), "Camera clones must share the same lens model"
153+
distortion = getattr(spawn_cfg, "distortion", None)
154+
if distortion is not None:
155+
assert distortion.model == "opencvPinhole", "Camera DR supports OpenCV pinhole calibration only."
156+
prims = _find_camera_prims_by_env(env, env_ids, sensor)
147157
for index, env_id in enumerate(env_ids):
148-
fx, fy, cx, cy = nominal[index]
158+
fx, fy, cx, cy = distortion.fx, distortion.fy, distortion.cx, distortion.cy
149159
scale = float(scales[index])
150160
matrices[index, 0, 0], matrices[index, 1, 1] = fx * scale, fy * scale
151161
matrices[index, 0, 2], matrices[index, 1, 2] = cx, cy
152162
prim = prims[env_id]
163+
assert (
164+
prim.GetAttribute("omni:lensdistortion:model").Get() == "opencvPinhole"
165+
), "Camera DR requires the renderer to author the configured OpenCV pinhole lens model."
153166
prefix = "omni:lensdistortion:opencvPinhole:"
154-
prim.GetAttribute(prefix + "fx").Set(fx * scale)
155-
prim.GetAttribute(prefix + "fy").Set(fy * scale)
167+
for name, value in (("fx", fx * scale), ("fy", fy * scale), ("cx", cx), ("cy", cy)):
168+
prim.GetAttribute(prefix + name).Set(value)
156169
prim.GetAttribute("focalLength").Set(focal_length * scale)
157-
# set_intrinsic_matrices would discard cx/cy and average fx/fy. RTX reads
158-
# the native lens attributes; publish the same K in the sensor metadata.
159-
sensor._data.intrinsic_matrices.torch[env_ids] = matrices
170+
# Lab's setter skips cameras with an authored OpenCV model. Edit the lens
171+
# attributes and use its readback to keep the sensor calibration consistent.
172+
sensor._update_intrinsic_matrices(env_ids)
160173
else:
161174
sensor.set_intrinsic_matrices(matrices, focal_length=focal_length, env_ids=env_ids)
162175
return {env_id: float(matrices[index, 0, 0]) for index, env_id in enumerate(env_ids)}
@@ -172,16 +185,17 @@ def _sync_camera_mounts_to_fabric(env: ManagerBasedEnv, env_ids: list[int], sens
172185
import usdrt
173186
from isaaclab.sim.utils.stage import get_current_stage_id
174187
from pxr import UsdGeom
188+
from usdrt import hierarchy
175189

176190
stage = usdrt.Usd.Stage.Attach(get_current_stage_id())
177-
hierarchy = usdrt.hierarchy.IFabricHierarchy().get_fabric_hierarchy(
191+
fabric_hierarchy = hierarchy.IFabricHierarchy().get_fabric_hierarchy(
178192
stage.GetFabricId(), stage.GetStageIdAsStageId()
179193
)
180194
for prim in _find_camera_prims_by_env(env, env_ids, sensor).values():
181195
local = UsdGeom.Xformable(prim).GetLocalTransformation()
182196
matrix = usdrt.Gf.Matrix4d(*[value for row in local for value in row])
183-
hierarchy.set_local_xform(usdrt.Sdf.Path(str(prim.GetPath())), matrix)
184-
hierarchy.update_world_xforms()
197+
fabric_hierarchy.set_local_xform(usdrt.Sdf.Path(str(prim.GetPath())), matrix)
198+
fabric_hierarchy.update_world_xforms()
185199

186200

187201
def _find_camera_prims_by_env(env: ManagerBasedEnv, env_ids: list[int], sensor: Camera) -> dict[int, Any]:
@@ -198,57 +212,3 @@ def _find_camera_prims_by_env(env: ManagerBasedEnv, env_ids: list[int], sensor:
198212
), f"Expected exactly one camera prim under {env_path!r} for {sensor.cfg.prim_path!r}, found {len(matches)}."
199213
prims_by_env[env_id] = matches[0]
200214
return prims_by_env
201-
202-
203-
def _convert_rotation(
204-
rotation_xyzw: tuple[float, float, float, float],
205-
origin: str,
206-
target: str,
207-
) -> tuple[float, float, float, float]:
208-
"""Convert camera orientation conventions without changing the physical mount."""
209-
from isaaclab.utils.math import convert_camera_frame_orientation_convention
210-
211-
rotation = torch.tensor([rotation_xyzw], dtype=torch.float32)
212-
converted = convert_camera_frame_orientation_convention(rotation, origin=origin, target=target)
213-
return tuple(float(component) for component in converted[0])
214-
215-
216-
def _quat_from_rpy_deg(rpy_deg: tuple[float, float, float]) -> tuple[float, float, float, float]:
217-
"""Build an (x, y, z, w) quaternion from intrinsic x-y-z rotations [deg]."""
218-
quat = (0.0, 0.0, 0.0, 1.0)
219-
for axis, angle_deg in enumerate(rpy_deg):
220-
half_angle = 0.5 * math.radians(angle_deg)
221-
axis_quat = [0.0, 0.0, 0.0, math.cos(half_angle)]
222-
axis_quat[axis] = math.sin(half_angle)
223-
quat = _quat_multiply(quat, tuple(axis_quat))
224-
return quat
225-
226-
227-
def _quat_multiply(
228-
first_xyzw: tuple[float, float, float, float],
229-
second_xyzw: tuple[float, float, float, float],
230-
) -> tuple[float, float, float, float]:
231-
"""Compose two (x, y, z, w) quaternions, applying ``second_xyzw`` in the body frame."""
232-
x_1, y_1, z_1, w_1 = first_xyzw
233-
x_2, y_2, z_2, w_2 = second_xyzw
234-
return (
235-
w_1 * x_2 + x_1 * w_2 + y_1 * z_2 - z_1 * y_2,
236-
w_1 * y_2 - x_1 * z_2 + y_1 * w_2 + z_1 * x_2,
237-
w_1 * z_2 + x_1 * y_2 - y_1 * x_2 + z_1 * w_2,
238-
w_1 * w_2 - x_1 * x_2 - y_1 * y_2 - z_1 * z_2,
239-
)
240-
241-
242-
def _sample_uniform_vector(
243-
minimum: tuple[float, float, float],
244-
maximum: tuple[float, float, float],
245-
device: str,
246-
) -> tuple[float, float, float]:
247-
return tuple(_sample_uniform((low, high), device) for low, high in zip(minimum, maximum))
248-
249-
250-
def _sample_uniform(value_range: tuple[float, float], device: str) -> float:
251-
low, high = value_range
252-
if low == high:
253-
return float(low)
254-
return float(low + (high - low) * torch.rand((), device=device).item())

‎autodata_domain_randomization/configs.py‎

Lines changed: 10 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -12,22 +12,19 @@
1212

1313
@dataclass(kw_only=True)
1414
class LightingRandomizationCfg:
15-
"""Randomization settings for existing per-environment, non-dome lights.
15+
"""Randomization settings for existing lights.
1616
1717
Attributes:
18-
enabled: Whether lighting is randomized.
19-
asset_name: Scene-asset name of the per-environment light.
18+
asset_name: Scene-asset name of the light. Global and dome lights require one environment.
2019
intensity_range: Uniform USD emitter intensity range.
2120
color_temperature_range: Uniform color-temperature range [K].
2221
"""
2322

24-
enabled: bool = True
2523
asset_name: str = "light"
2624
intensity_range: tuple[float, float] = (250.0, 750.0)
2725
color_temperature_range: tuple[float, float] = (3000.0, 8000.0)
2826

2927
def __post_init__(self) -> None:
30-
assert isinstance(self.enabled, bool), "Lighting enabled must be a boolean."
3128
assert self.asset_name, "Lighting randomization requires a non-empty scene asset name."
3229
self.intensity_range = tuple(self.intensity_range)
3330
self.color_temperature_range = tuple(self.color_temperature_range)
@@ -49,21 +46,18 @@ class MaterialColorRandomizationCfg:
4946
to brighten a dark source texture.
5047
5148
Attributes:
52-
enabled: Whether this material color is randomized.
5349
asset_name: Scene-asset name containing the target prims.
5450
prim_name_markers: Substrings that identify target visual prim names.
5551
shader_input: Material shader input that receives the sampled color.
5652
color_palette: RGB multiplier anchors defining the sampled color gradient.
5753
"""
5854

59-
enabled: bool = True
6055
asset_name: str
6156
prim_name_markers: tuple[str, ...]
6257
shader_input: str
6358
color_palette: tuple[tuple[float, float, float], ...]
6459

6560
def __post_init__(self) -> None:
66-
assert isinstance(self.enabled, bool), "Material color enabled must be a boolean."
6761
assert not isinstance(self.prim_name_markers, str), "Material color prim name markers must be a sequence."
6862
self.prim_name_markers = tuple(self.prim_name_markers)
6963
self.color_palette = tuple(tuple(color) for color in self.color_palette)
@@ -89,21 +83,18 @@ class MaterialScalarRandomizationCfg:
8983
a fixed value for matching a known material.
9084
9185
Attributes:
92-
enabled: Whether this material scalar is applied.
9386
asset_name: Scene-asset name containing the target prims.
9487
prim_name_markers: Substrings that identify target visual prim names.
9588
shader_input: Material shader input that receives the sampled value.
9689
value_range: Uniform sampling range for the scalar.
9790
"""
9891

99-
enabled: bool = True
10092
asset_name: str
10193
prim_name_markers: tuple[str, ...]
10294
shader_input: str
10395
value_range: tuple[float, float]
10496

10597
def __post_init__(self) -> None:
106-
assert isinstance(self.enabled, bool), "Material scalar enabled must be a boolean."
10798
assert not isinstance(self.prim_name_markers, str), "Material scalar prim name markers must be a sequence."
10899
self.prim_name_markers = tuple(self.prim_name_markers)
109100
self.value_range = tuple(self.value_range)
@@ -125,7 +116,6 @@ class CameraRandomizationCfg:
125116
the calibration error being modelled and never accumulate across resets.
126117
127118
Attributes:
128-
enabled: Whether this camera is randomized.
129119
asset_name: Scene-asset name of the camera sensor.
130120
focal_length_scale_range: Uniform multiplier range applied to the nominal focal length.
131121
The native pinhole sensor uses square pixels and a centered principal point.
@@ -136,7 +126,6 @@ class CameraRandomizationCfg:
136126
rotation_rpy_max_deg: Upper bound of the rotation offset [deg] about the same axes.
137127
"""
138128

139-
enabled: bool = True
140129
asset_name: str
141130
focal_length_scale_range: tuple[float, float] = (1.0, 1.0)
142131
position_xyz_min: tuple[float, float, float] = (0.0, 0.0, 0.0)
@@ -145,7 +134,6 @@ class CameraRandomizationCfg:
145134
rotation_rpy_max_deg: tuple[float, float, float] = (0.0, 0.0, 0.0)
146135

147136
def __post_init__(self) -> None:
148-
assert isinstance(self.enabled, bool), "Camera enabled must be a boolean."
149137
assert self.asset_name, "Camera randomization requires a non-empty scene asset name."
150138
self.focal_length_scale_range = tuple(self.focal_length_scale_range)
151139
assert all(
@@ -172,23 +160,20 @@ class PoseRandomizationCfg:
172160
"""Pose range applied through an existing Isaac Lab reset event.
173161
174162
Attributes:
175-
enabled: Whether to override this reset event's pose range.
176163
event_name: Existing reset event accepting a ``pose_range`` parameter.
177164
position_xyz_min: Lower position bounds [m], in the event's reference frame.
178165
position_xyz_max: Upper position bounds [m], in the event's reference frame.
179166
rpy_min: Lower roll/pitch/yaw bounds [rad].
180167
rpy_max: Upper roll/pitch/yaw bounds [rad].
181168
"""
182169

183-
enabled: bool = True
184170
event_name: str
185171
position_xyz_min: tuple[float, float, float]
186172
position_xyz_max: tuple[float, float, float]
187173
rpy_min: tuple[float, float, float] = (0.0, 0.0, 0.0)
188174
rpy_max: tuple[float, float, float] = (0.0, 0.0, 0.0)
189175

190176
def __post_init__(self) -> None:
191-
assert isinstance(self.enabled, bool), "Pose enabled must be a boolean."
192177
assert self.event_name, "Pose randomization requires a reset event name."
193178
self.position_xyz_min = tuple(self.position_xyz_min)
194179
self.position_xyz_max = tuple(self.position_xyz_max)
@@ -220,13 +205,11 @@ def as_pose_range(self) -> dict[str, tuple[float, float]]:
220205
class RobotRootRandomizationCfg:
221206
"""Independent uniform offsets from the default robot root, in world axes."""
222207

223-
enabled: bool = True
224208
x_range_m: tuple[float, float] = (0.0, 0.0)
225209
y_range_m: tuple[float, float] = (0.0, 0.0)
226210
yaw_range_deg: tuple[float, float] = (0.0, 0.0)
227211

228212
def __post_init__(self) -> None:
229-
assert isinstance(self.enabled, bool), "Robot root enabled must be a boolean."
230213
for name in ("x_range_m", "y_range_m", "yaw_range_deg"):
231214
bounds = tuple(getattr(self, name))
232215
assert len(bounds) == 2 and all(
@@ -248,18 +231,16 @@ def as_pose_range(self) -> dict[str, tuple[float, float]]:
248231
class RobotJointRandomizationCfg:
249232
"""Independent uniform joint offsets from the nominal reset position."""
250233

251-
enabled: bool = True
252234
joint_names: tuple[str, ...] = ()
253235
delta_range_deg: tuple[float, float] = (0.0, 0.0)
254236

255237
def __post_init__(self) -> None:
256-
assert isinstance(self.enabled, bool), "Robot joints enabled must be a boolean."
257238
assert not isinstance(self.joint_names, str), "Robot joint_names must be a sequence of names or regex patterns."
258239
self.joint_names = tuple(self.joint_names)
259240
assert all(
260241
isinstance(name, str) and name for name in self.joint_names
261242
), "Joint names must be non-empty strings."
262-
assert not self.enabled or self.joint_names, "Enabled robot joint DR requires joint_names."
243+
assert self.joint_names, "Robot joint DR requires joint_names."
263244
self.delta_range_deg = tuple(self.delta_range_deg)
264245
assert len(self.delta_range_deg) == 2 and all(
265246
math.isfinite(value) for value in self.delta_range_deg
@@ -278,7 +259,7 @@ class DomainRandomizationCfg:
278259
Only sections present in the profile are applied. Settings are sampled once per episode reset.
279260
280261
Attributes:
281-
lighting: Optional non-dome lighting settings.
262+
lighting: Optional lighting settings.
282263
robot_root: Optional robot root offsets.
283264
robot_joints: Optional robot joint offsets.
284265
poses: Pose ranges for existing reset events.
@@ -339,12 +320,17 @@ def from_dict(cls, data: dict[str, Any]) -> DomainRandomizationCfg:
339320
return cls(**kwargs)
340321

341322
def validate_runtime(self, num_envs: int) -> None:
342-
"""Validate the environment count before creation.
323+
"""Validate the environment count and single-environment intrinsics restriction.
343324
344325
Args:
345326
num_envs: Number of parallel environments in the process.
346327
"""
347328
assert num_envs > 0, "num_envs must be positive."
329+
for camera in self.cameras:
330+
assert num_envs == 1 or camera.focal_length_scale_range == (1.0, 1.0), (
331+
"Camera intrinsics DR requires num_envs=1. For multi-environment extrinsics DR, "
332+
"keep focal_length_scale_range at [1.0, 1.0]."
333+
)
348334

349335

350336
def _validate_keys(data: Any, name: str, allowed_keys: set[str]) -> None:

0 commit comments

Comments
 (0)