diff --git a/docs/changelog.rst b/docs/changelog.rst index e7c0b71..b63834f 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -1,7 +1,7 @@ Changelog ========= -Pre-Release v1.4.0a4 (2026-11-27) +Pre-Release v1.4.0a5 (2026-11-27) --------------------------------- General @@ -12,6 +12,14 @@ General - Added H-, E-, and O-shaped objects and equilateral triangular prisms with configurable dimensions and mass. - Added random object type selection on reset from a configured list, with explicit reset overrides taking precedence. - Fixed pose reward calculations to use the geometry stored with each transition, independently of the current episode’s object type. +3. Added ``check_mover_rotation()`` and ``full_rotation_possible()`` to ``BasicMagBotEnv`` to check rotation limitations that some + MagLev systems may have: a full 360° rotation is only possible within a tolerance ``tol`` around configurable rotation points + (``rotation_points``). At all other positions, the yaw may deviate at most ``max_yaw_deviation`` (default: ±10°) from the nearest + multiple of 90°. By default, ``get_tile_rotation_points()`` provides one possible variant of such a limitation: the center, + corners, and edge midpoints of a tile, if the mover fully covers existing tiles there, i.e. not at the border of the tile + layout or next to absent tiles. + The rotation points can be specified via the ``rotation_points`` parameter of ``BasicMagBotEnv``, ``BasicMagBotSingleAgentEnv``, + and ``BasicMagBotMultiAgentEnv``. Bug Fixes ^^^^^^^^^ diff --git a/docs/examples_tutorials.rst b/docs/examples_tutorials.rst index 83c47fe..cf3359b 100644 --- a/docs/examples_tutorials.rst +++ b/docs/examples_tutorials.rst @@ -13,6 +13,7 @@ Please use one of our :ref:`environments` as more extensive examples of how to u examples_tutorials/create_env examples_tutorials/customizing_mujoco_model examples_tutorials/applying_controls_and_collision_checking_tutorial + examples_tutorials/rotation_limits examples_tutorials/adding_magbots diff --git a/docs/examples_tutorials/applying_controls_and_collision_checking_tutorial.rst b/docs/examples_tutorials/applying_controls_and_collision_checking_tutorial.rst index 1a039c9..5796c02 100644 --- a/docs/examples_tutorials/applying_controls_and_collision_checking_tutorial.rst +++ b/docs/examples_tutorials/applying_controls_and_collision_checking_tutorial.rst @@ -145,7 +145,7 @@ movers and tiles have simple shapes, such as cuboids or cylinders, which signifi collision checking problem. In addition, safety margins around a mover can be easily changed without requiring building and compiling a new MuJoCo model. The collision shapes, sizes, and additional margins can be configured using the ``collision_params``. Please refer to the :ref:`basic_magbot_env` -documentation for more information about the ``collision_params``, ``check_wall_collision()``, and +documentation for more information about the ``collision_params``, ``check_wall_collision()``, and ``check_mover_collision()`` methods. The complete code for the ``PandaBoxExampleEnv`` can be found `here `_. diff --git a/docs/examples_tutorials/rotation_limits.rst b/docs/examples_tutorials/rotation_limits.rst new file mode 100644 index 0000000..3dbeb03 --- /dev/null +++ b/docs/examples_tutorials/rotation_limits.rst @@ -0,0 +1,48 @@ +.. _rotation_limits_tutorial: + +Rotation Limits +=============== +Some MagLev systems may limit the rotation of a mover around the z-axis (yaw), e.g. a full +360° rotation may only be possible at certain positions. To take such limitations into account, MagBotSim provides the +``check_mover_rotation()`` method in the :ref:`basic_magbot_env`. It models a rotation limitation by a set of rotation points: a full rotation is +possible if the (x,y) distance between the center of a mover and one of the rotation points is at most ``tol``. At all +other positions, the yaw of a mover may only deviate by ``max_yaw_deviation`` (in rad) from the nearest multiple of 90°. +The method returns a numpy array of shape (num_movers,), where an element is True if the rotation limit of the +corresponding mover is violated: + +.. code-block:: python + + rotation_violation = self.check_mover_rotation( + mover_names=self.mover_names, + mover_qpos=None, + add_qpos_noise=True, # would also occur in a real system + tol=0.001, # [m] + max_yaw_deviation=np.deg2rad(10.0), + ).any() + +By default, the rotation points model one possible rotation limitation (see ``get_tile_rotation_points()``): a full +rotation is only possible at the center, the four corners, and the four edge midpoints of a tile, and only if the mover +fully covers existing tiles there, i.e. all tiles touching the point must exist (center: 1 tile, edge midpoint: 2 tiles, +corner: 4 tiles). Thus, a full rotation is not possible at the corners and edge midpoints at the border of the system or +next to missing tiles. + +If your system has a different rotation limitation, you can specify arbitrary rotation points as a numpy array of shape +(num_points,2), either using the ``rotation_points`` parameter of the ``BasicMagBotEnv`` or by assigning the +``rotation_points`` attribute of an existing environment: + +.. code-block:: python + + # full rotation only possible at two specific positions + env.rotation_points = np.array([[0.36, 0.36], [0.6, 0.12]]) + + # default rotation points plus an additional point + env.rotation_points = np.vstack([env.get_tile_rotation_points(), [[0.42, 0.3]]]) + +Limitations that cannot be described by points, e.g. rotation areas, can be modeled by overriding +``full_rotation_possible()``, which is used by ``check_mover_rotation()``. If you only want to know whether a full +rotation is possible at certain positions, e.g. to plan where a mover should rotate, you can also use +``full_rotation_possible()`` directly. It ignores the orientation of the movers. + +.. note:: + Rotation points are always configured in the :ref:`basic_magbot_env`, but the check is only executed, if ``check_mover_rotation()`` + is called in a custom environment. diff --git a/magbotsim/__init__.py b/magbotsim/__init__.py index 8751db5..829126d 100644 --- a/magbotsim/__init__.py +++ b/magbotsim/__init__.py @@ -1,4 +1,4 @@ -__version__ = '1.4.0a4' +__version__ = '1.4.0a5' from gymnasium.envs.registration import register diff --git a/magbotsim/basic_magbot_env.py b/magbotsim/basic_magbot_env.py index 216befa..d36e6ed 100644 --- a/magbotsim/basic_magbot_env.py +++ b/magbotsim/basic_magbot_env.py @@ -164,6 +164,12 @@ class BasicMagBotEnv: profile frame, defaults to False. Profiles stay outside the tile footprints and have a fixed width of 0.05 m and height of 0.10 m. Their top is 0.065 m above the tile surface (world z=0), with the bottom at z=-0.035 m. Rectangular tiles are supported. Raises ValueError if a section is too short or the frame would overlap tiles or other frame sections. + :param rotation_points: a numpy array of shape (num_points,2) containing the (x,y) positions at which a full 360° rotation of a + mover is possible, or None; defaults to None. These points are used by ``check_mover_rotation()`` and ``full_rotation_possible()`` + to model rotation limitations of a MagLev system. If set to None, the rotation points of the + APS4322-0000-0000 (240mm tiles Beckhoff XPlanar) are configured for rotation limit checking. The points can also be changed + later using the ``rotation_points`` attribute. Note that rotation points are always set, but the check is only executed, if + ``check_mover_rotation()`` is called in a custom environment. """ metadata = {'render_modes': ['human', 'rgb_array'], 'render_fps': 60} @@ -187,6 +193,7 @@ def __init__( custom_model_xml_strings: dict[str, str] | None = None, use_mj_passive_viewer: bool = False, use_profile_frame: bool = False, + rotation_points: np.ndarray | None = None, ) -> None: # rng self.rng_noise = np.random.default_rng() @@ -237,6 +244,17 @@ def __init__( self.layout_tiles_wc = np.pad(layout_tiles, ((0, 1), (0, 1)), mode='constant', constant_values=0) # precomputed wall-segment lookup table for qpos_is_valid self.walls_per_tile, self.n_walls_per_tile = self._precompute_wall_segments_fast() + # positions at which a full 360° rotation of a mover is possible (rotation limitations) + if rotation_points is not None: + rotation_points = np.asarray(rotation_points, dtype=np.float64) + if rotation_points.size == 0: + rotation_points = rotation_points.reshape((0, 2)) + assert rotation_points.ndim == 2 and rotation_points.shape[1] == 2, ( + f'rotation_points must be a numpy array of shape (num_points,2), got shape {rotation_points.shape}.' + ) + self.rotation_points = rotation_points + else: + self.rotation_points = self.get_default_tile_rotation_points() # mover configuration self.num_movers = num_movers @@ -614,6 +632,72 @@ def check_wall_collision( return 1 - self.qpos_is_valid(mover_qpos, c_size, add_safety_offset) + def check_mover_rotation( + self, + mover_names: list[str], + mover_qpos: np.ndarray | None = None, + add_qpos_noise: bool = False, + tol: float = 0.001, + max_yaw_deviation: float = np.deg2rad(10.0), + ) -> np.ndarray: + """Check whether the movers specified in ``mover_names`` violate the rotation limits around the z-axis (yaw). Depending on + the MagLev system, a full 360° rotation of a mover may only be possible at certain positions. This method models such + limitations as follows: a full rotation is possible if the mover is within ``tol`` of one of the ``rotation_points`` + (see ``full_rotation_possible()``). At all other positions, the yaw of a mover may deviate at most ``max_yaw_deviation`` + from the nearest multiple of 90°. + + :param mover_names: a list of mover names that should be checked (correspond to the body name of the mover in + the MuJoCo model) + :param mover_qpos: a numpy array of shape (num_movers,7) containing the qpos (x_p,y_p,z_p,w_o,x_o,y_o,z_o) of each mover or + None. If set to None, the current qpos of each mover in the MuJoCo model is used; defaults to None + :param add_qpos_noise: whether to add Gaussian noise to the qpos of the movers, defaults to False. Only used if mover_qpos is + None. + :param tol: the maximum (x,y) distance between the center of a mover and a rotation point at which a full rotation is still + possible, defaults to 0.001 [m] + :param max_yaw_deviation: the maximum deviation of the yaw from the nearest multiple of 90° if the mover is not at a rotation + point, defaults to 10° (in rad) + :return: a numpy array of shape (num_movers,), where an element is True if the rotation limit of the mover is violated, + otherwise False + """ + if mover_qpos is None: + mover_qpos = self.get_mover_qpos(mover_names=mover_names, add_noise=add_qpos_noise) + + assert mover_qpos.shape == (len(mover_names), 7) + + # yaw angle extracted from quaternion stored as (w, qx, qy, qz) at indices 3-6 + w_q = mover_qpos[:, 3] + q_x = mover_qpos[:, 4] + q_y = mover_qpos[:, 5] + q_z = mover_qpos[:, 6] + yaw = np.arctan2(2.0 * (w_q * q_z + q_x * q_y), 1.0 - 2.0 * (q_y * q_y + q_z * q_z)) + # deviation from the nearest multiple of 90° in [-45°, 45°) + yaw_deviation = np.mod(yaw + np.pi / 4, np.pi / 2) - np.pi / 4 + + return ~self.full_rotation_possible(qpos=mover_qpos, tol=tol) & (np.abs(yaw_deviation) > max_yaw_deviation) + + def full_rotation_possible(self, qpos: np.ndarray, tol: float = 0.001) -> np.ndarray: + """Check whether a full 360° rotation around the z-axis is possible at the (x,y) positions specified in ``qpos``, i.e. + whether the (x,y) distance between a position and at least one of the ``rotation_points`` is at most ``tol``. The + rotation points can be arbitrary positions. To model rotation limitations that cannot be described by points, e.g. + rotation areas, this method can be overridden (it is also used by ``check_mover_rotation()``). + + This method allows to check multiple qpos at the same time. The orientation of the mover is ignored. + + :param qpos: a numpy array of shape (num_qpos,7) containing the qpos (x_p,y_p,z_p,w_o,x_o,y_o,z_o) to be checked + :param tol: the maximum (x,y) distance between a position and a rotation point at which a full rotation is still possible, + defaults to 0.001 [m] + :return: a numpy array of shape (num_qpos,), where an element is True if a full rotation is possible, otherwise False + """ + assert len(qpos.shape) == 2 and qpos.shape[1] == 7 + assert tol >= 0.0, 'The tolerance must be non-negative.' + + # squared (x,y) distances between all positions and all rotation points, shape (num_qpos, num_points) + diff = qpos[:, np.newaxis, :2] - self.rotation_points[np.newaxis, :, :] + dist_sq = np.sum(diff * diff, axis=2) + + # without rotation points, np.any over the empty axis returns False for all positions + return np.any(dist_sq <= tol**2, axis=1) + def qpos_is_valid(self, qpos: np.ndarray, c_size: float | np.ndarray, add_safety_offset: bool = False) -> np.ndarray: """Check whether qpos is valid. This method considers the edges as imaginary walls if there is no other tile next to that edge. A position is valid if it is above a tile and the distance to the walls is greater that the required safety margin, @@ -916,6 +1000,32 @@ def _precompute_wall_segments_fast(self) -> tuple[np.ndarray, np.ndarray]: return walls_per_tile, n_walls_per_tile + def get_default_tile_rotation_points(self) -> np.ndarray: + """Return the default rotation points (see ``rotation_points``), which model one possible rotation limitation of a MagLev + system: a full 360° rotation of a mover is only possible at the center, the four corners, and the four edge midpoints of a + tile, and only if the mover fully covers existing tiles there. A rotation point must be surrounded by tiles, i.e. points at + the border of the tile layout or next to an absent tile are no rotation points. + This assumes that the rotating mover does not reach beyond the tiles touching the point, which holds for + movers whose half-diagonal is smaller than half a tile. + + :return: a numpy array of shape (num_points,2) containing the (x,y) positions of the rotation points + """ + # Candidate points form a grid spaced half a tile apart: the point with index (m, n) is located at + # (m * tile_size[0], n * tile_size[1]) relative to the upper left corner of the tile layout, and tile (i, j) touches + # the points with indices m in [2i, 2i+2] and n in [2j, 2j+2]. + mask = np.ones((2 * self.num_tiles_x + 1, 2 * self.num_tiles_y + 1), dtype=bool) + # points at the border of the layout touch tiles outside the layout + mask[[0, -1], :] = False + mask[:, [0, -1]] = False + # points touched by an absent tile + for i, j in zip(*np.nonzero(self.layout_tiles == 0), strict=True): + mask[2 * i : 2 * i + 3, 2 * j : 2 * j + 3] = False + m, n = np.nonzero(mask) + + origin_x = self.x_pos_tiles[0, 0] - self.tile_size[0] + origin_y = self.y_pos_tiles[0, 0] - self.tile_size[1] + return np.stack([origin_x + m * self.tile_size[0], origin_y + n * self.tile_size[1]], axis=1) + ################################################### # MuJoCo # ################################################### diff --git a/magbotsim/rl_envs/basic_multi_agent_env.py b/magbotsim/rl_envs/basic_multi_agent_env.py index 34ce7cb..bc684b6 100644 --- a/magbotsim/rl_envs/basic_multi_agent_env.py +++ b/magbotsim/rl_envs/basic_multi_agent_env.py @@ -58,6 +58,11 @@ class BasicMagBotMultiAgentEnv(BasicMagBotEnv, ParallelEnv): :param use_mj_passive_viewer: whether the MuJoCo passive_viewer should be used, defaults to False. If set to False, the Gymnasium MuJoCo WindowViewer with custom overlays is used. :param use_profile_frame: whether to add the collision-enabled profile frame, defaults to False + :param rotation_points: a numpy array of shape (num_points,2) containing the (x,y) positions at which a full 360° rotation of a + mover is possible, or None; defaults to None. If set to None, the rotation points of the + APS4322-0000-0000 (240mm tiles Beckhoff XPlanar) are configured for rotation limit checking. Note that rotation points are always + set, but the check is only executed, if ``check_mover_rotation()`` is called in a custom environment. + See ``BasicMagBotEnv`` for more information about rotation limitations. """ def __init__( @@ -79,6 +84,7 @@ def __init__( custom_model_xml_strings: dict[str, str] | None = None, use_mj_passive_viewer: bool = False, use_profile_frame: bool = False, + rotation_points: np.ndarray | None = None, ) -> None: super().__init__( layout_tiles=layout_tiles, @@ -98,6 +104,7 @@ def __init__( custom_model_xml_strings=custom_model_xml_strings, use_mj_passive_viewer=use_mj_passive_viewer, use_profile_frame=use_profile_frame, + rotation_points=rotation_points, ) self.agents = self.mover_names diff --git a/magbotsim/rl_envs/basic_single_agent_env.py b/magbotsim/rl_envs/basic_single_agent_env.py index 2467e09..5bb73d9 100644 --- a/magbotsim/rl_envs/basic_single_agent_env.py +++ b/magbotsim/rl_envs/basic_single_agent_env.py @@ -67,6 +67,11 @@ class BasicMagBotSingleAgentEnv(BasicMagBotEnv, gym.Env, ABC): :param use_mj_passive_viewer: whether the MuJoCo passive_viewer should be used, defaults to False. If set to False, the Gymnasium MuJoCo WindowViewer with custom overlays is used. :param use_profile_frame: whether to add the collision-enabled profile frame, defaults to False + :param rotation_points: a numpy array of shape (num_points,2) containing the (x,y) positions at which a full 360° rotation of a + mover is possible, or None; defaults to None. If set to None, the rotation points of the + APS4322-0000-0000 (240mm tiles Beckhoff XPlanar) are configured for rotation limit checking. Note that rotation points are always + set, but the check is only executed, if ``check_mover_rotation()`` is called in a custom environment. + See ``BasicMagBotEnv`` for more information about rotation limitations. """ def __init__( @@ -90,6 +95,7 @@ def __init__( custom_model_xml_strings: dict[str, str] | None = None, use_mj_passive_viewer: bool = False, use_profile_frame: bool = False, + rotation_points: np.ndarray | None = None, ) -> None: super().__init__( layout_tiles=layout_tiles, @@ -109,6 +115,7 @@ def __init__( custom_model_xml_strings=custom_model_xml_strings, use_mj_passive_viewer=use_mj_passive_viewer, use_profile_frame=use_profile_frame, + rotation_points=rotation_points, ) # rendering diff --git a/tests/test_basic_env.py b/tests/test_basic_env.py index 6abbc4e..46b3675 100644 --- a/tests/test_basic_env.py +++ b/tests/test_basic_env.py @@ -9,7 +9,7 @@ from shapely.geometry import box from shapely.ops import unary_union -from magbotsim import BasicMagBotEnv, BasicMagBotMultiAgentEnv +from magbotsim import BasicMagBotEnv, BasicMagBotMultiAgentEnv, BasicMagBotSingleAgentEnv @pytest.mark.parametrize( @@ -2115,6 +2115,211 @@ def test_mover_position_is_valid_check(layout_tiles, qpos, collision_params, add assert (pos_is_valid == expected_result).all() +# 3x3 layout with absent tile (2, 2); tile size 0.24 m -> tile centers at 0.12, 0.36, 0.60 m +ROTATION_TEST_LAYOUT = np.array([[1, 1, 1], [1, 1, 1], [1, 1, 0]]) + + +def _qpos_from_xy_yaw(xy: list, yaw_deg: list | float = 0.0) -> np.ndarray: + """Build qpos of shape (num_qpos, 7) from (x, y) positions and yaw angles in degrees.""" + xy = np.asarray(xy, dtype=np.float64).reshape(-1, 2) + yaw = np.deg2rad(np.broadcast_to(np.asarray(yaw_deg, dtype=np.float64), (xy.shape[0],))) + qpos = np.zeros((xy.shape[0], 7)) + qpos[:, :2] = xy + qpos[:, 3] = np.cos(yaw / 2) + qpos[:, 6] = np.sin(yaw / 2) + return qpos + + +def _sorted_points(points: np.ndarray) -> np.ndarray: + """Sort (x, y) points lexicographically for order-independent comparisons.""" + return points[np.lexsort((points[:, 1], points[:, 0]))] + + +@pytest.mark.parametrize( + 'layout_tiles, expected_indices', + [ + # points at the border of the layout and points touching the absent tile (2, 2) are no rotation points + (ROTATION_TEST_LAYOUT, [(m, n) for m in range(1, 6) for n in range(1, 6) if not (m >= 4 and n >= 4)]), + # complete layout: all points except the ones at the border + (np.ones((2, 3)), [(m, n) for m in range(1, 4) for n in range(1, 6)]), + # single tile: only the center + (np.ones((1, 1)), [(1, 1)]), + ], +) +def test_get_default_tile_rotation_points(layout_tiles, expected_indices): + env = BasicMagBotEnv(layout_tiles=layout_tiles, num_movers=1, render_mode=None) + # candidate points are spaced half a tile (0.12 m) apart + expected = np.array(expected_indices, dtype=np.float64) * 0.12 + + points = env.get_default_tile_rotation_points() + + assert points.shape == (len(expected_indices), 2) + assert np.allclose(_sorted_points(points), _sorted_points(expected)) + # used by default + assert np.allclose(_sorted_points(env.rotation_points), _sorted_points(expected)) + + +def test_custom_rotation_points(): + custom_points = np.array([[0.30, 0.30], [0.4237, 0.1]]) # not on the half-tile grid + + # via constructor + env = BasicMagBotEnv(layout_tiles=ROTATION_TEST_LAYOUT, num_movers=1, render_mode=None, rotation_points=custom_points) + assert np.allclose(env.rotation_points, custom_points) + qpos = _qpos_from_xy_yaw([[0.30, 0.30], [0.4245, 0.1], [0.36, 0.36]], yaw_deg=45.0) + assert (env.full_rotation_possible(qpos=qpos) == np.array([True, True, False])).all() + for qpos_i, expected in zip(qpos, [False, False, True], strict=True): + assert env.check_mover_rotation(mover_names=env.mover_names, mover_qpos=qpos_i[np.newaxis, :])[0] == expected + + # via attribute (e.g. for environments that do not forward the constructor parameter) + env_default = BasicMagBotEnv(layout_tiles=ROTATION_TEST_LAYOUT, num_movers=1, render_mode=None) + assert (env_default.full_rotation_possible(qpos=qpos) == np.array([False, False, True])).all() + env_default.rotation_points = custom_points.tolist() + assert env_default.rotation_points.shape == (2, 2) + assert (env_default.full_rotation_possible(qpos=qpos) == np.array([True, True, False])).all() + + # no rotation points: a full rotation is not possible anywhere + env_default.rotation_points = np.empty((0, 2)) + assert not env_default.full_rotation_possible(qpos=qpos).any() + env_default.rotation_points = [] + assert env_default.rotation_points.shape == (0, 2) + assert env_default.check_mover_rotation(mover_names=env_default.mover_names, mover_qpos=qpos[2:])[0] + + # invalid shapes + with pytest.raises(AssertionError): + env_default.rotation_points = np.array([0.3, 0.3]) + with pytest.raises(AssertionError): + BasicMagBotEnv(layout_tiles=ROTATION_TEST_LAYOUT, num_movers=1, render_mode=None, rotation_points=np.zeros((2, 3))) + + +class _MinimalSingleAgentEnv(BasicMagBotSingleAgentEnv): + """Minimal concrete ``BasicMagBotSingleAgentEnv`` (the abstract methods are not used by the tests).""" + + def _get_obs(self): + return np.zeros(0) + + def _get_info(self, *args, **kwargs): + return {} + + def compute_reward(self, *args, **kwargs): + return 0.0 + + def compute_terminated(self, *args, **kwargs): + return False + + def compute_truncated(self, *args, **kwargs): + return False + + +@pytest.mark.parametrize('env_cls', [_MinimalSingleAgentEnv, BasicMagBotMultiAgentEnv], ids=['single_agent', 'multi_agent']) +def test_rotation_points_forwarded_by_rl_base_envs(env_cls): + custom_points = np.array([[0.30, 0.30], [0.4237, 0.1]]) + + env = env_cls(layout_tiles=ROTATION_TEST_LAYOUT, num_movers=1, render_mode=None, rotation_points=custom_points) + try: + assert np.allclose(env.rotation_points, custom_points) + finally: + env.close() + + # default: tile rotation points + env = env_cls(layout_tiles=ROTATION_TEST_LAYOUT, num_movers=1, render_mode=None) + try: + assert np.allclose(_sorted_points(env.rotation_points), _sorted_points(env.get_default_tile_rotation_points())) + finally: + env.close() + + +@pytest.mark.parametrize( + 'xy, tol, expected', + [ + # nine points of tile (1, 1); corner (0.48, 0.48) touches the absent tile (2, 2) + ( + [[0.36, 0.36], [0.24, 0.24], [0.48, 0.24], [0.24, 0.48], [0.48, 0.48], [0.36, 0.24], [0.36, 0.48], [0.24, 0.36], [0.48, 0.36]], + 0.001, + [True, True, True, True, False, True, True, True, True], + ), + # tile centers at the layout border are rotation points (the mover covers only one tile) + ([[0.12, 0.12], [0.12, 0.60], [0.60, 0.12], [0.60, 0.36]], 0.001, [True] * 4), + # corners and edge midpoints at the layout border are no rotation points (the mover would not fully cover tiles) + ([[0.0, 0.0], [0.72, 0.0], [0.0, 0.12], [0.36, 0.72], [0.0, 0.24]], 0.001, [False] * 5), + # default tolerance (Euclidean distance) + ([[0.3609, 0.36], [0.3611, 0.36], [0.36, 0.3591], [0.3608, 0.3608]], 0.001, [True, False, True, False]), + # custom tolerance + ([[0.363, 0.36], [0.36, 0.366]], 0.005, [True, False]), + # (almost) zero tolerance + ([[0.36, 0.36], [0.3601, 0.36]], 1e-9, [True, False]), + # arbitrary positions on tiles + ([[0.30, 0.30], [0.18, 0.36], [0.12, 0.06]], 0.001, [False] * 3), + # no point touching the absent tile (2, 2) is a rotation point + ( + [[0.60, 0.60], [0.72, 0.60], [0.60, 0.72], [0.72, 0.72], [0.60, 0.48], [0.48, 0.60], [0.48, 0.48], [0.72, 0.48]], + 0.001, + [False] * 8, + ), + # outside the layout + ([[-0.24, 0.12], [0.12, 0.96], [-0.0005, 0.0]], 0.001, [False] * 3), + ], +) +def test_full_rotation_possible(xy, tol, expected): + env = BasicMagBotEnv(layout_tiles=ROTATION_TEST_LAYOUT, num_movers=1, render_mode=None) + qpos = _qpos_from_xy_yaw(xy, yaw_deg=30.0) + + result = env.full_rotation_possible(qpos=qpos, tol=tol) + + assert result.shape == (len(xy),) + assert result.dtype == bool + assert (result == np.array(expected)).all() + + +@pytest.mark.parametrize( + 'xy, yaw_deg, kwargs, expected', + [ + # rotation point: any yaw is allowed + ([0.36, 0.36], [0, 10.5, 45, 135, -170, 359], {}, [False] * 6), + ([0.24, 0.48], [45], {}, [False]), + # no rotation point: yaw must be within 10° of the nearest multiple of 90° + ( + [0.30, 0.30], + [0, 5, -9.9, 10.5, -10.5, 45, 85, 95, -95, 180, 189, 200, 275], + {}, + [False, False, False, True, True, True, False, False, False, False, False, True, False], + ), + # custom yaw limit + ([0.30, 0.30], [5, 15, 25, -25], {'max_yaw_deviation': np.deg2rad(20.0)}, [False, False, True, True]), + # tolerance + ([0.362, 0.36], [45], {}, [True]), + ([0.362, 0.36], [45], {'tol': 0.005}, [False]), + # center of the absent tile, corner next to the absent tile, and edge midpoint at the layout border are no rotation points + ([0.60, 0.60], [45], {}, [True]), + ([0.48, 0.48], [5, 45], {}, [False, True]), + ([0.0, 0.36], [5, 45], {}, [False, True]), + ], +) +def test_check_mover_rotation(xy, yaw_deg, kwargs, expected): + env = BasicMagBotEnv(layout_tiles=ROTATION_TEST_LAYOUT, num_movers=1, render_mode=None) + + for yaw, exp in zip(yaw_deg, expected, strict=True): + mover_qpos = _qpos_from_xy_yaw([xy], yaw_deg=yaw) + result = env.check_mover_rotation(mover_names=env.mover_names, mover_qpos=mover_qpos, **kwargs) + assert result.shape == (1,) + assert result[0] == exp, f'xy={xy}, yaw={yaw}°: expected {exp}, got {result[0]}' + + +def test_check_mover_rotation_current_qpos(): + # movers are placed in the tile centers by default + env = BasicMagBotEnv(layout_tiles=ROTATION_TEST_LAYOUT, num_movers=2, render_mode=None) + result = env.check_mover_rotation(mover_names=env.mover_names) + assert result.shape == (2,) + assert not result.any() + + # move mover 1 off the rotation point and rotate it by 45° -> violation + env.data.qpos[env.mover_qpos_indices[1]] = _qpos_from_xy_yaw([[0.15, 0.36]], yaw_deg=45.0)[0] + np.array( + [0, 0, env.data.qpos[env.mover_qpos_indices[1, 2]], 0, 0, 0, 0] + ) + result = env.check_mover_rotation(mover_names=env.mover_names) + assert (result == np.array([False, True])).all() + assert (env.check_mover_rotation(mover_names=[env.mover_names[1]]) == np.array([True])).all() + + def _frame_geom_bounds(env, prefix): """Return world-space mesh bounds for frame geoms matching a name prefix.""" bounds = []