Skip to content
Closed
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
3 changes: 2 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.0a2 (2026-11-10)
Pre-Release v1.4.0a3 (2026-11-10)
---------------------------------

General
Expand All @@ -15,6 +15,7 @@ Bug Fixes
2. Fixed some minor discontinuity issues in edge cases:
- Numerical rounding issue for z_p_min (in ``GripperMagBotsAPM4330Params``)
- Finger distance to angle calculation now became c2 smooth (in ``GripperMagBotsAPM4330``)
3. Fix damping calculation for rotational component together with corresponding env examples (in ``MoverImpedanceController``)

Release v1.3.0 (2026-09-11)
---------------------------
Expand Down
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.0a2'
__version__ = '1.4.0a3'

from gymnasium.envs.registration import register

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,7 @@ def step(self, platform_setposes: np.ndarray, num_cycles: int = 40, render_every
num_cycles = 5
cnt = 0
err_scale_xy_fast = np.array([2.0, 2.0, 1.0, 1.0, 1.0, 1.0])
err_scale_xyc_fast = np.array([2.0, 2.0, 1.0, 1.0, 1.0, 6.0])
err_scale_xyc_fast = np.array([2.0, 2.0, 1.0, 1.0, 1.0, 0.6])
env.impedance_controllers[0].set_pose_err_scale(err_scale_xy_fast)
env.impedance_controllers[1].set_pose_err_scale(err_scale_xy_fast)
e_threshold = 1e-2
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -219,10 +219,10 @@ def step(self, platform_setposes: np.ndarray, num_cycles: int = 40, render_every
platform_setposes[0, 1] = 0.36 + fR * np.sin(fTime)
platform_setposes[0, 2] = 0.03 * np.sin(3.5 * fTime) + 0.24
# wave movement
platform_setposes[1, 3] = np.cos(2.0 * fTime)
platform_setposes[1, 4] = np.sin(2.0 * fTime)
platform_setposes[1, 3] = np.deg2rad(14.0)*np.cos(2.0 * fTime)
platform_setposes[1, 4] = np.deg2rad(14.0)*np.sin(2.0 * fTime)
# env step (integration, collision checking, rendering)
env.step(platform_setposes=platform_setposes, num_cycles=num_cycles, render_every_cycle=False)
env.step(platform_setposes=platform_setposes, num_cycles=num_cycles, render_every_cycle=True)
fTime += 0.001 * num_cycles
except KeyboardInterrupt:
pass
Expand Down
43 changes: 40 additions & 3 deletions magbotsim/utils/impedance_control.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ class MoverImpedanceController:
is specified, the same stiffness value is used for all rotational axes.
:param pose_err_scale: the scaling factors for the pose error, can be either a single float (same values for all error dimensions)
or a numpy array of shape (6,1) or (6,) containing values for each error dimension (order: pos error x,y,z, rot error a,b,c)

The damping matrix is chosen such that all DoFs are critically damped (damping ratio = 1). The translational damping is computed
from the mass of the mover (and an optional additional mass), whereas the rotational damping is computed from the moments of
inertia of the mover body about the axes of the mover frame.
"""

def __init__(
Expand All @@ -53,7 +57,8 @@ def __init__(
self.stiffness[-3:, -3:] = self._init_stiffness_mat(stiffness=rotational_stiffness)
# configure damping matrix (damping ratio = 1)
self.mover_mass = model.body(self.mover_body_id).subtreemass[0]
self.damping = 2 * np.sqrt(self.stiffness * self.mover_mass)
self.mover_inertia = self._get_mover_inertia(model)
self._init_damping()

# enable/disable joints
if joint_mask is None:
Expand Down Expand Up @@ -91,6 +96,37 @@ def _init_stiffness_mat(self, stiffness: np.ndarray | float) -> np.ndarray:
assert stiffness.shape == (3,)
return np.diag(stiffness)

def _get_mover_inertia(self, model: MjModel) -> np.ndarray:
"""Return the moments of inertia of the mover body about the axes of the mover frame. MuJoCo stores the principal moments of
inertia in the principal axes frame (body_iquat), which is not necessarily aligned with the mover frame.

:param model: mjModel of the MuJoCo environment
:return: the diagonal of the inertia tensor in the mover frame, i.e. a numpy array of shape (3,) (order: a, b, c)
"""
rot_mat = np.zeros(9)
mujoco.mju_quat2Mat(rot_mat, model.body_iquat[self.mover_body_id])
rot_mat = rot_mat.reshape((3, 3))
return np.diag(rot_mat @ np.diag(model.body_inertia[self.mover_body_id]) @ rot_mat.T).copy()

def _init_damping(self) -> None:
"""Initialize the damping matrix (damping ratio = 1) based on the current stiffness matrix. The rotational damping is computed
from the inertia of the mover. It is constant and therefore only computed here, i.e. this method must be called again if the
rotational stiffness is changed.
"""
self.damping = np.zeros((6, 6))
self._update_damping()
self.damping[-3:, -3:] = 2 * np.sqrt(self.stiffness[-3:, -3:] * np.diag(self.mover_inertia))

def _update_damping(self, additional_mass: float = 0.0) -> None:
"""Update the mass-dependent (translational) part of the damping matrix (damping ratio = 1) based on the current stiffness
matrix.

:param additional_mass: any additional mass (float), e.g. the mass of an object the mover is transporting, defaults to 0.0
"""
mass = self.mover_mass + additional_mass
# only the translational damping depends on the (additional) mass
self.damping[:3, :3] = 2 * np.sqrt(self.stiffness[:3, :3] * mass)

def set_joint_mask(self, new_joint_mask: np.ndarray):
"""Set a new joint mask to control only specified DoFs of a mover with this controller.

Expand Down Expand Up @@ -136,7 +172,8 @@ def update_cached_mujoco_data(self, model: MjModel) -> None:
self.mover_dofadr = model.body(self.mover_body_id).dofadr[0]
self.mover_dofnum = model.body(self.mover_body_id).dofnum[0]
self.mover_mass = model.body(self.mover_body_id).subtreemass[0]
self.damping = 2 * np.sqrt(self.stiffness * self.mover_mass)
self.mover_inertia = self._get_mover_inertia(model)
self._init_damping()
# actuators
self.actuator_ids = np.zeros((len(self.actuator_names),), dtype=np.int32)
for idx_a, actuator_name in enumerate(self.actuator_names):
Expand Down Expand Up @@ -167,7 +204,7 @@ def update(self, model: MjModel, data: MjData, pos_d: np.ndarray, quat_d: np.nda
quat_d = quat_d.astype(np.float64)

# update damping if required
self.damping = 2 * np.sqrt(self.stiffness * (self.mover_mass + additional_mass))
self._update_damping(additional_mass=additional_mass)

# desired rot mat
xmat_d = np.zeros((9,))
Expand Down
140 changes: 140 additions & 0 deletions tests/test_impedance_control.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
import mujoco
import numpy as np
import pytest

from magbotsim.utils.impedance_control import MoverImpedanceController

MOVER_HALF_HEIGHT = 0.006
MOVER_START_POS = np.array([0.24, 0.24, 0.5])
MOVER_MASS = 1.24
# inertia tensor of the mover in the mover frame (ixx, iyy, izz, ixy, ixz, iyz); the off-diagonal entries ensure that the principal
# axes frame of the mover (body_iquat) is not aligned with the mover frame
MOVER_FULL_INERTIA = np.array([2.5e-3, 3.0e-3, 5.0e-3, 2.0e-4, 1.0e-4, -1.5e-4])
MOVER_INERTIA_DIAG = MOVER_FULL_INERTIA[:3]


def _build_model(actuator_xml_str: str = '') -> mujoco.MjModel:
full_inertia = ' '.join(str(v) for v in MOVER_FULL_INERTIA)
start_pos = ' '.join(str(v) for v in MOVER_START_POS)
xml_str = f"""
<mujoco>
<option gravity="0 0 0" timestep="0.002"/>
<worldbody>
<body name="mover_0" pos="{start_pos}">
<joint name="mover_joint_0" type="free"/>
<inertial pos="0 0 0" mass="{MOVER_MASS}" fullinertia="{full_inertia}"/>
<geom type="box" size="0.0775 0.0775 {MOVER_HALF_HEIGHT}" contype="0" conaffinity="0"/>
</body>
</worldbody>
<actuator>{actuator_xml_str}
</actuator>
</mujoco>
"""
return mujoco.MjModel.from_xml_string(xml_str)


def _setup(**controller_kwargs) -> tuple[mujoco.MjModel, mujoco.MjData, MoverImpedanceController]:
"""Create the controller, add its actuators to the model and update the cached MuJoCo data (same procedure as in the envs)."""
model = _build_model()
controller = MoverImpedanceController(
model=model, mover_joint_name='mover_joint_0', mover_half_height=MOVER_HALF_HEIGHT, **controller_kwargs
)
model = _build_model(controller.generate_actuator_xml_string(idx_mover=0))
controller.update_cached_mujoco_data(model)
data = mujoco.MjData(model)
mujoco.mj_forward(model, data)
return model, data, controller


def _expected_damping(translational_stiffness: np.ndarray, rotational_stiffness: np.ndarray, additional_mass: float = 0.0):
trans = 2 * np.sqrt(translational_stiffness * (MOVER_MASS + additional_mass))
rot = 2 * np.sqrt(rotational_stiffness * MOVER_INERTIA_DIAG)
return np.diag(np.concatenate((trans, rot)))


def _rotate_quat(axis: np.ndarray, angle: float) -> np.ndarray:
quat = np.zeros(4)
mujoco.mju_axisAngle2Quat(quat, axis, angle)
return quat


def _simulate_rotation_step(rotational_stiffness: float, axis_idx: int, init_angle: float, duration: float) -> np.ndarray:
"""Start the mover with an orientation error about one axis of the mover frame and control it back to the identity orientation.

:return: the orientation error (rotation vector in the mover frame) at each time step, i.e. a numpy array of shape (num_steps, 3)
"""
model, data, controller = _setup(translational_stiffness=1000.0, rotational_stiffness=rotational_stiffness)
axis = np.zeros(3)
axis[axis_idx] = 1.0
data.qpos[3:7] = _rotate_quat(axis, init_angle)
mujoco.mj_forward(model, data)

pos_d = MOVER_START_POS - np.array([0.0, 0.0, MOVER_HALF_HEIGHT])
quat_d = np.array([1.0, 0.0, 0.0, 0.0])
errors = []
for _ in range(int(duration / model.opt.timestep)):
controller.update(model, data, pos_d=pos_d, quat_d=quat_d)
mujoco.mj_step(model, data)
err = np.zeros(3)
mujoco.mju_subQuat(err, data.qpos[3:7], quat_d)
errors.append(err)
return np.array(errors)


def test_mover_inertia_in_mover_frame():
_, _, controller = _setup()
assert np.allclose(controller.mover_inertia, MOVER_INERTIA_DIAG)


@pytest.mark.parametrize(
'translational_stiffness, rotational_stiffness',
[
(1.0, 0.1), # default values
(np.array([5000.0, 5000.0, 10.0]), np.array([5.0, 5.0, 0.0])),
(np.array([100.0, 200.0, 300.0]), np.array([1.0, 2.0, 3.0])),
],
)
def test_damping_matrix_critically_damped(translational_stiffness, rotational_stiffness):
"""Translational damping is based on the mover mass, rotational damping on the moments of inertia of the mover."""
_, _, controller = _setup(translational_stiffness=translational_stiffness, rotational_stiffness=rotational_stiffness)
expected = _expected_damping(np.broadcast_to(translational_stiffness, (3,)), np.broadcast_to(rotational_stiffness, (3,)))
assert np.allclose(controller.damping, expected)


@pytest.mark.parametrize('additional_mass', [0.0, 0.5, 2.0])
def test_additional_mass_only_affects_translational_damping(additional_mass):
translational_stiffness = np.array([100.0, 200.0, 300.0])
rotational_stiffness = np.array([1.0, 2.0, 3.0])
model, data, controller = _setup(translational_stiffness=translational_stiffness, rotational_stiffness=rotational_stiffness)

controller.update(model, data, pos_d=MOVER_START_POS.copy(), quat_d=np.array([1.0, 0.0, 0.0, 0.0]), additional_mass=additional_mass)
expected = _expected_damping(translational_stiffness, rotational_stiffness, additional_mass=additional_mass)
assert np.allclose(controller.damping, expected)


@pytest.mark.parametrize('axis_idx', [0, 1, 2])
def test_rotation_converges_without_overshoot(axis_idx):
"""With critical damping, a mover with an initial orientation error converges back to the desired orientation within a few
natural periods and without (significant) overshoot. With a damping that is computed from the mass, the rotational DoFs are
heavily overdamped and the orientation error barely decreases in the same time.
"""
init_angle = 0.1
errors = _simulate_rotation_step(rotational_stiffness=0.1, axis_idx=axis_idx, init_angle=init_angle, duration=1.5)
assert np.all(np.isfinite(errors))
# error about the excited axis decreases to less than 2% of the initial error
assert abs(errors[-1, axis_idx]) < 0.02 * init_angle
# no significant overshoot
assert np.min(errors[:, axis_idx]) > -0.02 * init_angle


@pytest.mark.parametrize('axis_idx', [0, 1])
def test_rotation_stable_for_high_rotational_stiffness(axis_idx):
"""For a high rotational stiffness, a damping that is computed from the mass is several orders of magnitude too large for the small
rotational inertia of the mover, which makes the controller numerically unstable. Critical damping based on the inertia keeps it
stable.
"""
init_angle = 0.1
errors = _simulate_rotation_step(rotational_stiffness=5.0, axis_idx=axis_idx, init_angle=init_angle, duration=0.5)
assert np.all(np.isfinite(errors))
assert np.max(np.abs(errors)) <= init_angle + 1e-6
assert np.max(np.abs(errors[-1])) < 0.02 * init_angle
Loading