From 1dbc376fc96d06eb6dea0192a247f3f475dd13b9 Mon Sep 17 00:00:00 2001 From: Marco Grabowski Date: Tue, 10 Nov 2026 14:52:28 +0100 Subject: [PATCH 1/5] MoverImpedanceController: compute rotational damping from inertia The rotational damping was computed from the mover mass, which is several orders of magnitude too large for the small rotational inertia of a mover. This makes the rotational response heavily overdamped and numerically unstable for higher rotational stiffness values. The rotational DoFs are now critically damped based on the moments of inertia of the mover body about the axes of the mover frame. The translational damping is still computed from the mover mass plus the optional additional mass. Add unit tests for the damping matrix and the closed-loop rotational response. --- magbotsim/utils/impedance_control.py | 43 +++++++- tests/test_impedance_control.py | 140 +++++++++++++++++++++++++++ 2 files changed, 180 insertions(+), 3 deletions(-) create mode 100644 tests/test_impedance_control.py diff --git a/magbotsim/utils/impedance_control.py b/magbotsim/utils/impedance_control.py index bc4e1d4..c03f58c 100644 --- a/magbotsim/utils/impedance_control.py +++ b/magbotsim/utils/impedance_control.py @@ -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__( @@ -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: @@ -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. @@ -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): @@ -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,)) diff --git a/tests/test_impedance_control.py b/tests/test_impedance_control.py new file mode 100644 index 0000000..da63a30 --- /dev/null +++ b/tests/test_impedance_control.py @@ -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""" + + + """ + 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 From 208356b863f1e0a7c9bc35bc2770951a23a59b08 Mon Sep 17 00:00:00 2001 From: Marco Grabowski Date: Tue, 10 Nov 2026 15:33:27 +0100 Subject: [PATCH 2/5] Fix magbot env examples --- .../magbots/sixD_platform_application_example_env.py | 2 +- .../magbots/sixD_platform_example_env.py | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/magbotsim/envs_without_rl_api/magbots/sixD_platform_application_example_env.py b/magbotsim/envs_without_rl_api/magbots/sixD_platform_application_example_env.py index cc10ab7..ce5a50f 100644 --- a/magbotsim/envs_without_rl_api/magbots/sixD_platform_application_example_env.py +++ b/magbotsim/envs_without_rl_api/magbots/sixD_platform_application_example_env.py @@ -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 diff --git a/magbotsim/envs_without_rl_api/magbots/sixD_platform_example_env.py b/magbotsim/envs_without_rl_api/magbots/sixD_platform_example_env.py index 5b49463..210b78a 100644 --- a/magbotsim/envs_without_rl_api/magbots/sixD_platform_example_env.py +++ b/magbotsim/envs_without_rl_api/magbots/sixD_platform_example_env.py @@ -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 From 09c2a17d1e77a1992a683058d63b9c4757512824 Mon Sep 17 00:00:00 2001 From: Marco Grabowski Date: Tue, 10 Nov 2026 15:38:04 +0100 Subject: [PATCH 3/5] v1.4.0a4: Fix MoverImpedanceController damping calculation for rotational component --- docs/changelog.rst | 3 ++- magbotsim/__init__.py | 2 +- .../magbots/sixD_platform_example_env.py | 6 +++--- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 408d741..805b6a5 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -1,7 +1,7 @@ Changelog ========= -Pre-Release v1.4.0a3 (2026-11-11) +Pre-Release v1.4.0a4 (2026-11-12) --------------------------------- General @@ -20,6 +20,7 @@ Bug Fixes - Numerical rounding issue for z_p_min (in ``GripperMagBotsAPM4330Params``) - Finger distance to angle calculation now became c2 smooth (in ``GripperMagBotsAPM4330``) 3. Fixed stale rendering resources in ``MujocoViewerCollection`` after model reloads, which could +4. Fix damping calculation for rotational component together with corresponding env examples (in ``MoverImpedanceController``) cause missing objects or incorrectly displayed meshes. Release v1.3.0 (2026-09-11) diff --git a/magbotsim/__init__.py b/magbotsim/__init__.py index 212566f..8751db5 100644 --- a/magbotsim/__init__.py +++ b/magbotsim/__init__.py @@ -1,4 +1,4 @@ -__version__ = '1.4.0a3' +__version__ = '1.4.0a4' from gymnasium.envs.registration import register diff --git a/magbotsim/envs_without_rl_api/magbots/sixD_platform_example_env.py b/magbotsim/envs_without_rl_api/magbots/sixD_platform_example_env.py index 210b78a..8e947cb 100644 --- a/magbotsim/envs_without_rl_api/magbots/sixD_platform_example_env.py +++ b/magbotsim/envs_without_rl_api/magbots/sixD_platform_example_env.py @@ -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.deg2rad(14.0)*np.cos(2.0 * fTime) - platform_setposes[1, 4] = np.deg2rad(14.0)*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=True) + env.step(platform_setposes=platform_setposes, num_cycles=num_cycles, render_every_cycle=False) fTime += 0.001 * num_cycles except KeyboardInterrupt: pass From 51c49636c9f16b2b31d54c5f53a9d3d3bef13586 Mon Sep 17 00:00:00 2001 From: Marco Grabowski Date: Tue, 17 Nov 2026 11:30:06 +0100 Subject: [PATCH 4/5] Fix order of bug fix entries in changelog --- docs/changelog.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index 805b6a5..ece769b 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -19,9 +19,9 @@ 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. Fixed stale rendering resources in ``MujocoViewerCollection`` after model reloads, which could -4. Fix damping calculation for rotational component together with corresponding env examples (in ``MoverImpedanceController``) +3. Fixed stale rendering resources in ``MujocoViewerCollection`` after model reloads, which could cause missing objects or incorrectly displayed meshes. +4. Fix damping calculation for rotational component together with corresponding env examples (in ``MoverImpedanceController``) Release v1.3.0 (2026-09-11) --------------------------- From 3402164aa85dca296175d48bbc8f14c97bcb360f Mon Sep 17 00:00:00 2001 From: Lara Bergmann Date: Fri, 27 Nov 2026 10:12:11 +0100 Subject: [PATCH 5/5] rename _update_damping to _update_translational_damping in MoverImpedanceController --- docs/changelog.rst | 2 +- magbotsim/utils/impedance_control.py | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/changelog.rst b/docs/changelog.rst index ece769b..e7c0b71 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -1,7 +1,7 @@ Changelog ========= -Pre-Release v1.4.0a4 (2026-11-12) +Pre-Release v1.4.0a4 (2026-11-27) --------------------------------- General diff --git a/magbotsim/utils/impedance_control.py b/magbotsim/utils/impedance_control.py index c03f58c..aea0c7a 100644 --- a/magbotsim/utils/impedance_control.py +++ b/magbotsim/utils/impedance_control.py @@ -114,10 +114,10 @@ def _init_damping(self) -> None: rotational stiffness is changed. """ self.damping = np.zeros((6, 6)) - self._update_damping() + self._update_translational_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: + def _update_translational_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. @@ -204,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._update_damping(additional_mass=additional_mass) + self._update_translational_damping(additional_mass=additional_mass) # desired rot mat xmat_d = np.zeros((9,))