OpenGHz's picture
Add fair-comparison/flow-v1
0a3f650 verified
Raw History Blame Contribute Delete
4.48 kB
"""Out-of-distribution StackCube variants for evaluation only.
`StackCubeOOD-v1` is StackCube-v1 with two optional changes:
- `ood_position`: both cubes start in a ring outside the training placement
box (x in [-0.2, 0.2], y in [-0.3, 0.3]) but inside x in [-0.25, 0.25],
y in [-0.35, 0.35] and within `reach_m` of the robot base; draws come from
the episode seed, independent of the native sampler.
- `cube_scale`: both cube edge lengths scaled; spacing and the success
tolerance follow the scaled size exactly as the native task defines them.
Everything else (robot, cameras, rotations, success rule) is unchanged.
"""
import numpy as np
import sapien
import torch
from mani_skill.envs.tasks.tabletop.stack_cube import StackCubeEnv
from mani_skill.envs.utils import randomization
from mani_skill.utils import common
from mani_skill.utils.building import actors
from mani_skill.utils.registration import register_env
from mani_skill.utils.scene_builder.table import TableSceneBuilder
from mani_skill.utils.structs.pose import Pose
INNER = ((-0.2, 0.2), (-0.3, 0.3))
OUTER = ((-0.25, 0.25), (-0.35, 0.35))
BASE_XY = np.array([-0.615, 0.0])
def ring_positions(seed, spacing, reach_m=0.8):
"""Two cube xy positions in the OOD ring, at least `spacing` apart."""
rng = np.random.default_rng([20261005, seed])
chosen = []
while len(chosen) < 2:
xy = np.array([rng.uniform(*OUTER[0]), rng.uniform(*OUTER[1])])
inside = INNER[0][0] <= xy[0] <= INNER[0][1] and INNER[1][0] <= xy[1] <= INNER[1][1]
if inside or np.linalg.norm(xy - BASE_XY) > reach_m:
continue
if chosen and np.linalg.norm(xy - chosen[0]) <= spacing:
continue
chosen.append(xy)
return np.stack(chosen)
@register_env("StackCubeOOD-v1", max_episode_steps=50)
class StackCubeOODEnv(StackCubeEnv):
def __init__(self, *args, ood_position=False, cube_scale=1.0, **kwargs):
self.ood_position = ood_position
self.cube_scale = float(cube_scale)
self.ood_seed = None
super().__init__(*args, **kwargs)
def reset(self, seed=None, options=None):
self.ood_seed = seed
return super().reset(seed=seed, options=options)
def _load_scene(self, options: dict):
half = 0.02 * self.cube_scale
self.cube_half_size = common.to_tensor([half] * 3, device=self.device)
self.table_scene = TableSceneBuilder(
env=self, robot_init_qpos_noise=self.robot_init_qpos_noise
)
self.table_scene.build()
self.cubeA = actors.build_cube(self.scene, half_size=half, color=[1, 0, 0, 1],
name="cubeA", initial_pose=sapien.Pose(p=[0, 0, 0.1]))
self.cubeB = actors.build_cube(self.scene, half_size=half, color=[0, 1, 0, 1],
name="cubeB", initial_pose=sapien.Pose(p=[1, 0, 0.1]))
def _initialize_episode(self, env_idx: torch.Tensor, options: dict):
with torch.device(self.device):
b = len(env_idx)
self.table_scene.initialize(env_idx)
half = 0.02 * self.cube_scale
radius = torch.linalg.norm(torch.tensor([half, half])) + 0.001
xyz = torch.zeros((b, 3))
xyz[:, 2] = half
# Construction resets once without a seed; every evaluated episode
# passes its scene seed, which then fixes the OOD placement.
if self.ood_position and self.ood_seed is not None:
if b != 1:
raise ValueError("OOD placement draws one scene per episode seed")
placed = torch.as_tensor(ring_positions(self.ood_seed, 2 * float(radius)),
dtype=torch.float32)
cubeA_xy, cubeB_xy = placed[:1], placed[1:]
else:
xy = torch.rand((b, 2)) * 0.2 - 0.1
sampler = randomization.UniformPlacementSampler(
bounds=[[-0.1, -0.2], [0.1, 0.2]], batch_size=b, device=self.device
)
cubeA_xy = xy + sampler.sample(radius, 100)
cubeB_xy = xy + sampler.sample(radius, 100, verbose=False)
for actor, cube_xy in ((self.cubeA, cubeA_xy), (self.cubeB, cubeB_xy)):
xyz[:, :2] = cube_xy
qs = randomization.random_quaternions(b, lock_x=True, lock_y=True, lock_z=False)
actor.set_pose(Pose.create_from_pq(p=xyz.clone(), q=qs))