Skip to content

Commit 71f9086

Browse files
committed
finalized PR cleanup still need ot move branch over to open source
1 parent 01a2833 commit 71f9086

File tree

4 files changed

+97
-32
lines changed

4 files changed

+97
-32
lines changed

source/extensions/omni.isaac.lab/omni/isaac/lab/envs/direct_marl_env.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
1+
# Copyright (c) 2022-2025, The Isaac Lab Project Developers.
22
# All rights reserved.
33
#
44
# SPDX-License-Identifier: BSD-3-Clause
@@ -576,12 +576,15 @@ def _apply_scene_randomization(self):
576576
the operations of the event manager to apply the scene-level randomization.
577577
578578
It must be called only before the simulation/physics is started.
579+
580+
Note: A duplicate function exists in manager_based_env.py please make sure to carry over
581+
any changes made to this function.
579582
"""
580583
# check if scene randomization is enabled
581584
applied_scene_randomization = False
582585
# iterate over all event terms
583586
for term_name, term_cfg in self.cfg.events.__dict__.items():
584-
# check for non config
587+
# check for none config
585588
if term_cfg is None:
586589
continue
587590
# call event terms corresponding to the scene-level randomization

source/extensions/omni.isaac.lab/omni/isaac/lab/envs/manager_based_env.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
1+
# Copyright (c) 2022-2025, The Isaac Lab Project Developers.
22
# All rights reserved.
33
#
44
# SPDX-License-Identifier: BSD-3-Clause
@@ -117,6 +117,7 @@ def __init__(self, cfg: ManagerBasedEnvCfg):
117117
print("[INFO]: Scene manager: ", self.scene)
118118

119119
# randomization at scene level
120+
# note: this must happened after the scene is constructed because it involves modifying Xform attributes
120121
with Timer("[INFO]: Time taken for scene randomization", "scene_randomization"):
121122
self._apply_scene_randomization()
122123

@@ -358,6 +359,9 @@ def _apply_scene_randomization(self):
358359
the operations of the event manager to apply the scene-level randomization.
359360
360361
It must be called only before the simulation/physics is started.
362+
363+
Note: A duplicate function exists in direct_marl_env.py please make sure to carry over
364+
any changes made to this function.
361365
"""
362366
# check if scene randomization is enabled
363367
applied_scene_randomization = False

source/extensions/omni.isaac.lab/omni/isaac/lab/envs/mdp/events.py

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
1+
# Copyright (c) 2022-2025, The Isaac Lab Project Developers.
22
# All rights reserved.
33
#
44
# SPDX-License-Identifier: BSD-3-Clause
@@ -63,6 +63,10 @@ def randomize_shape_color(env: ManagerBasedEnv, env_ids: torch.Tensor | None, as
6363
# spawn single instance
6464
prim_spec = Sdf.CreatePrimInLayer(stage.GetRootLayer(), prim_paths[env_id])
6565

66+
# check to make sure input:diffuseColor attribute exists
67+
if not prim_spec.GetAttributeAtPath(prim_paths[env_id] + "/geometry/material/Shader.inputs:diffuseColor"):
68+
raise ValueError("inputs:diffuseColor not a valid attribute. Please set to an existing attribute.")
69+
6670
# get the attribute to randomize
6771
color_spec = prim_spec.GetAttributeAtPath(
6872
prim_paths[env_id] + "/geometry/material/Shader.inputs:diffuseColor"
@@ -100,11 +104,17 @@ def randomize_scale(
100104
# extract the used quantities (to enable type-hinting)
101105
asset: RigidObject | Articulation = env.scene[asset_cfg.name]
102106

107+
# check to make sure scale randomization is not triggered while simulation is running
108+
if env.sim.is_playing():
109+
raise ValueError(
110+
"Unable to randomize scale while scene is running."
111+
" Assure scale randomization called prior to simulation start."
112+
)
113+
103114
# check to make sure replicate_physics is set to False, else raise warning
104115
if env.cfg.scene.replicate_physics:
105116
raise ValueError(
106-
"Unable to randomize scale - ensure InteractiveSceneCfg's replicate_physics parameter"
107-
" is set to False."
117+
"Unable to randomize scale - ensure InteractiveSceneCfg's replicate_physics parameter is set to False."
108118
)
109119

110120
# resolve environment ids
@@ -133,6 +143,10 @@ def randomize_scale(
133143
# spawn single instance
134144
prim_spec = Sdf.CreatePrimInLayer(stage.GetRootLayer(), prim_paths[env_id])
135145

146+
# check to make sure xformOp:scale attribute exists
147+
if not prim_spec.GetAttributeAtPath(prim_paths[env_id] + ".xformOp:scale"):
148+
raise ValueError("xforOp:scale not a valid attribute. Please set to an existing attribute.")
149+
136150
# get the attribute to randomize
137151
scale_spec = prim_spec.GetAttributeAtPath(prim_paths[env_id] + ".xformOp:scale")
138152
scale_spec.default = Gf.Vec3f(*rand_samples[i])

source/extensions/omni.isaac.lab/test/envs/test_scale_randomization.py

Lines changed: 70 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
1+
# Copyright (c) 2022-2025, The Isaac Lab Project Developers.
22
# All rights reserved.
33
#
44
# SPDX-License-Identifier: BSD-3-Clause
@@ -24,7 +24,7 @@
2424
from omni.isaac.lab.app import AppLauncher, run_tests
2525

2626
# Can set this to False to see the GUI for debugging
27-
HEADLESS = False
27+
HEADLESS = True
2828

2929
# launch omniverse app
3030
app_launcher = AppLauncher(headless=HEADLESS, enable_cameras=True)
@@ -35,6 +35,9 @@
3535
import torch
3636
import unittest
3737

38+
import omni.usd
39+
from pxr import Sdf
40+
3841
import omni.isaac.lab.envs.mdp as mdp
3942
import omni.isaac.lab.sim as sim_utils
4043
from omni.isaac.lab.assets import AssetBaseCfg, RigidObject, RigidObjectCfg
@@ -159,9 +162,22 @@ class MySceneCfg(InteractiveSceneCfg):
159162
# add terrain
160163
terrain = TerrainImporterCfg(prim_path="/World/ground", terrain_type="plane", debug_vis=False)
161164

162-
# add cube
163-
cube: RigidObjectCfg = RigidObjectCfg(
164-
prim_path="{ENV_REGEX_NS}/cube",
165+
# add cube for scale randomization
166+
cube1: RigidObjectCfg = RigidObjectCfg(
167+
prim_path="{ENV_REGEX_NS}/cube1",
168+
spawn=sim_utils.CuboidCfg(
169+
size=(0.2, 0.2, 0.2),
170+
rigid_props=sim_utils.RigidBodyPropertiesCfg(max_depenetration_velocity=1.0, disable_gravity=True),
171+
mass_props=sim_utils.MassPropertiesCfg(mass=1.0),
172+
physics_material=sim_utils.RigidBodyMaterialCfg(),
173+
visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 0.0, 0.0)),
174+
),
175+
init_state=RigidObjectCfg.InitialStateCfg(pos=(0.0, 0.0, 5)),
176+
)
177+
178+
# add cube for static scale values
179+
cube2: RigidObjectCfg = RigidObjectCfg(
180+
prim_path="{ENV_REGEX_NS}/cube2",
165181
spawn=sim_utils.CuboidCfg(
166182
size=(0.2, 0.2, 0.2),
167183
rigid_props=sim_utils.RigidBodyPropertiesCfg(max_depenetration_velocity=1.0, disable_gravity=True),
@@ -188,7 +204,7 @@ class MySceneCfg(InteractiveSceneCfg):
188204
class ActionsCfg:
189205
"""Action specifications for the MDP."""
190206

191-
joint_pos = CubeActionTermCfg(asset_name="cube")
207+
joint_pos = CubeActionTermCfg(asset_name="cube1")
192208

193209

194210
@configclass
@@ -200,7 +216,7 @@ class PolicyCfg(ObsGroup):
200216
"""Observations for policy group."""
201217

202218
# cube velocity
203-
position = ObsTerm(func=base_position, params={"asset_cfg": SceneEntityCfg("cube")})
219+
position = ObsTerm(func=base_position, params={"asset_cfg": SceneEntityCfg("cube1")})
204220

205221
def __post_init__(self):
206222
self.enable_corruption = True
@@ -224,16 +240,27 @@ class EventCfg:
224240
"y": (-0.5, 0.5),
225241
"z": (-0.5, 0.5),
226242
},
227-
"asset_cfg": SceneEntityCfg("cube"),
243+
"asset_cfg": SceneEntityCfg("cube1"),
228244
},
229245
)
230246

231-
randomize_scale = EventTerm(
247+
# Scale randomization as intended
248+
randomize_scale1 = EventTerm(
232249
func=mdp.randomize_scale,
233250
mode="scene",
234251
params={
235252
"scale_range": {"x": (0.5, 1.5), "y": (0.5, 1.5), "z": (0.5, 1.5)},
236-
"asset_cfg": SceneEntityCfg("cube"),
253+
"asset_cfg": SceneEntityCfg("cube1"),
254+
},
255+
)
256+
257+
# Static scale values
258+
randomize_scale2 = EventTerm(
259+
func=mdp.randomize_scale,
260+
mode="scene",
261+
params={
262+
"scale_range": {"x": (1.0, 1.0), "y": (1.0, 1.0), "z": (1.0, 1.0)},
263+
"asset_cfg": SceneEntityCfg("cube2"),
237264
},
238265
)
239266

@@ -248,7 +275,7 @@ class CubeEnvCfg(ManagerBasedEnvCfg):
248275
"""Configuration for the locomotion velocity-tracking environment."""
249276

250277
# Scene settings
251-
scene: MySceneCfg = MySceneCfg(num_envs=64, env_spacing=2.5, replicate_physics=False)
278+
scene: MySceneCfg = MySceneCfg(num_envs=10, env_spacing=2.5, replicate_physics=False)
252279
# Basic settings
253280
observations: ObservationsCfg = ObservationsCfg()
254281
actions: ActionsCfg = ActionsCfg()
@@ -281,29 +308,46 @@ def test_scale_randomization(self):
281308
# offset all targets so that they move to the world origin
282309
target_position -= env.scene.env_origins
283310

311+
stage = omni.usd.get_context().get_stage()
312+
313+
# Test to make sure randomized values are truly random
314+
applied_scaling_randomization = set()
315+
prim_paths = sim_utils.find_matching_prim_paths("/World/envs/env_.*/cube1")
316+
for i in range(3):
317+
prim_spec = Sdf.CreatePrimInLayer(stage.GetRootLayer(), prim_paths[i])
318+
scale_spec = prim_spec.GetAttributeAtPath(prim_paths[i] + ".xformOp:scale")
319+
if scale_spec.default in applied_scaling_randomization:
320+
raise ValueError(
321+
"Detected repeat in applied scale values - indication scaling randomizatio is not working."
322+
)
323+
applied_scaling_randomization.add(scale_spec.default)
324+
325+
# Test to make sure that fixed values are assigned correctly
326+
prim_paths = sim_utils.find_matching_prim_paths("/World/envs/env_.*/cube2")
327+
for i in range(3):
328+
prim_spec = Sdf.CreatePrimInLayer(stage.GetRootLayer(), prim_paths[i])
329+
scale_spec = prim_spec.GetAttributeAtPath(prim_paths[i] + ".xformOp:scale")
330+
torch.testing.assert_close(tuple(scale_spec.default), (1.0, 1.0, 1.0))
331+
284332
# simulate physics
285333
count = 0
286-
obs, _ = env.reset()
287334
while simulation_app.is_running():
288335
with torch.inference_mode():
289336
# reset
290-
if count % 300 == 0:
291-
count = 0
292-
obs, _ = env.reset()
293-
print("-" * 80)
294-
print("[INFO]: Resetting environment...")
295-
# step env
296-
obs, _ = env.step(target_position)
297-
# print mean squared position error between target and current position
298-
error = torch.norm(obs["policy"] - target_position).mean().item()
299-
print(f"[Step: {count:04d}]: Mean position error: {error:.4f}")
337+
if count % 100 == 0:
338+
env.reset()
339+
340+
# step the environment
341+
env.step(target_position)
342+
300343
# update counter
301344
count += 1
302345

346+
# After 2 iterations finish the test and close env
347+
if count >= 200:
348+
env.close()
349+
break
350+
303351

304352
if __name__ == "__main__":
305353
run_tests()
306-
# # run the main function
307-
# main()
308-
# # close sim app
309-
# simulation_app.close()

0 commit comments

Comments
 (0)