Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion docs/changelog.rst
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
Changelog
=========

Pre-Release v1.4.0a4 (2026-11-27)
Pre-Release v1.4.0a5 (2026-11-27)
---------------------------------

General
Expand All @@ -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
^^^^^^^^^
Expand Down
1 change: 1 addition & 0 deletions docs/examples_tutorials.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 <https://github.com/ubi-coro/MagBotSim/blob/main/magbotsim/envs_without_rl_api/object_manipulation/panda_box_env.py>`_.
Expand Down
48 changes: 48 additions & 0 deletions docs/examples_tutorials/rotation_limits.rst
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 1 addition & 1 deletion magbotsim/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
__version__ = '1.4.0a4'
__version__ = '1.4.0a5'

from gymnasium.envs.registration import register

Expand Down
110 changes: 110 additions & 0 deletions magbotsim/basic_magbot_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand All @@ -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()
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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 #
###################################################
Expand Down
7 changes: 7 additions & 0 deletions magbotsim/rl_envs/basic_multi_agent_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__(
Expand All @@ -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,
Expand All @@ -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
Expand Down
7 changes: 7 additions & 0 deletions magbotsim/rl_envs/basic_single_agent_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__(
Expand All @@ -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,
Expand All @@ -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
Expand Down
Loading
Loading