diff --git a/docs/changelog.rst b/docs/changelog.rst index 408d741..e7c0b71 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-27) --------------------------------- General @@ -19,8 +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 +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) --------------------------- 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_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..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,8 +219,8 @@ 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) fTime += 0.001 * num_cycles diff --git a/magbotsim/utils/impedance_control.py b/magbotsim/utils/impedance_control.py index bc4e1d4..aea0c7a 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_translational_damping() + self.damping[-3:, -3:] = 2 * np.sqrt(self.stiffness[-3:, -3:] * np.diag(self.mover_inertia)) + + 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. + + :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_translational_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