mink 0.0.9__py3-none-any.whl → 0.0.11__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
mink/__init__.py CHANGED
@@ -9,11 +9,19 @@ from .constants import (
9
9
  SUPPORTED_FRAMES,
10
10
  )
11
11
  from .exceptions import (
12
+ IntegrationTimestepNotSet,
13
+ InvalidConstraint,
14
+ InvalidDamping,
12
15
  InvalidFrame,
16
+ InvalidGain,
13
17
  InvalidKeyframe,
14
18
  InvalidMocapBody,
19
+ InvalidTarget,
20
+ LimitDefinitionError,
15
21
  MinkError,
16
22
  NotWithinConfigurationLimits,
23
+ TargetNotSet,
24
+ TaskDefinitionError,
17
25
  UnsupportedFrame,
18
26
  )
19
27
  from .lie import SE3, SO3, MatrixLieGroup
@@ -30,10 +38,10 @@ from .tasks import (
30
38
  DampingTask,
31
39
  EqualityConstraintTask,
32
40
  FrameTask,
41
+ KineticEnergyRegularizationTask,
33
42
  Objective,
34
43
  PostureTask,
35
44
  RelativeFrameTask,
36
- TargetNotSet,
37
45
  Task,
38
46
  )
39
47
  from .utils import (
@@ -55,6 +63,7 @@ __all__ = (
55
63
  "RelativeFrameTask",
56
64
  "PostureTask",
57
65
  "Task",
66
+ "KineticEnergyRegularizationTask",
58
67
  "EqualityConstraintTask",
59
68
  "Objective",
60
69
  "ConfigurationLimit",
@@ -72,6 +81,13 @@ __all__ = (
72
81
  "NotWithinConfigurationLimits",
73
82
  "TargetNotSet",
74
83
  "InvalidMocapBody",
84
+ "InvalidConstraint",
85
+ "InvalidDamping",
86
+ "InvalidGain",
87
+ "InvalidTarget",
88
+ "LimitDefinitionError",
89
+ "TaskDefinitionError",
90
+ "IntegrationTimestepNotSet",
75
91
  "SUPPORTED_FRAMES",
76
92
  "FRAME_TO_ENUM",
77
93
  "FRAME_TO_JAC_FUNC",
mink/configuration.py CHANGED
@@ -237,6 +237,21 @@ class Configuration:
237
237
  mujoco.mj_integratePos(self.model, self.data.qpos, velocity, dt)
238
238
  self.update()
239
239
 
240
+ def get_inertia_matrix(self) -> np.ndarray:
241
+ r"""Return the joint-space inertia matrix at the current configuration.
242
+
243
+ Returns:
244
+ The joint-space inertia matrix :math:`M(\mathbf{q})`.
245
+ """
246
+ # Run the composite rigid body inertia (CRB) algorithm to populate the joint
247
+ # space inertia matrix data.qM.
248
+ mujoco.mj_crb(self.model, self.data)
249
+ # data.qM is stored in a custom sparse format and can be converted to dense
250
+ # format using mujoco.mj_fullM.
251
+ M = np.empty((self.nv, self.nv), dtype=np.float64)
252
+ mujoco.mj_fullM(self.model, M, self.data.qM)
253
+ return M
254
+
240
255
  # Aliases.
241
256
 
242
257
  @property
mink/exceptions.py CHANGED
@@ -96,3 +96,43 @@ class NotWithinConfigurationLimits(MinkError):
96
96
  f"{lower} <= {value} <= {upper}"
97
97
  )
98
98
  super().__init__(message)
99
+
100
+
101
+ class TaskDefinitionError(MinkError):
102
+ """Exception raised when a task definition is ill-formed."""
103
+
104
+
105
+ class IntegrationTimestepNotSet(MinkError):
106
+ """Exception raised when the integration timestep is not set."""
107
+
108
+ def __init__(self, cls_name: str):
109
+ message = f"No integration timestep set for {cls_name}"
110
+ super().__init__(message)
111
+
112
+
113
+ class TargetNotSet(MinkError):
114
+ """Exception raised when attempting to use a task with an unset target."""
115
+
116
+ def __init__(self, cls_name: str):
117
+ message = f"No target set for {cls_name}"
118
+ super().__init__(message)
119
+
120
+
121
+ class InvalidTarget(MinkError):
122
+ """Exception raised when the target is invalid."""
123
+
124
+
125
+ class InvalidGain(MinkError):
126
+ """Exception raised when the gain is outside the valid range."""
127
+
128
+
129
+ class InvalidDamping(MinkError):
130
+ """Exception raised when the damping is outside the valid range."""
131
+
132
+
133
+ class InvalidConstraint(MinkError):
134
+ """Exception raised when a constraint is invalid."""
135
+
136
+
137
+ class LimitDefinitionError(MinkError):
138
+ """Exception raised when a limit definition is ill-formed."""
mink/lie/so3.py CHANGED
@@ -85,6 +85,7 @@ class SO3(MatrixLieGroup):
85
85
  assert matrix.shape == (SO3.matrix_dim, SO3.matrix_dim)
86
86
  wxyz = np.empty(SO3.parameters_dim, dtype=np.float64)
87
87
  mujoco.mju_mat2Quat(wxyz, matrix.ravel())
88
+ # NOTE mju_mat2Quat normalizes the quaternion.
88
89
  return SO3(wxyz=wxyz)
89
90
 
90
91
  @classmethod
@@ -163,20 +164,22 @@ class SO3(MatrixLieGroup):
163
164
  def exp(cls, tangent: np.ndarray) -> SO3:
164
165
  axis = np.array(tangent)
165
166
  theta = mujoco.mju_normalize3(axis)
166
- wxyz = np.zeros(4)
167
+ wxyz = np.empty(4, dtype=np.float64)
168
+ # NOTE mju_axisAngle2Quat does not normalize the quaternion but is guaranteed
169
+ # to return a unit quaternion when axis is a unit vector. In our case,
170
+ # mju_normalize3 ensures that axis is a unit vector.
167
171
  mujoco.mju_axisAngle2Quat(wxyz, axis, theta)
168
172
  return SO3(wxyz=wxyz)
169
173
 
170
174
  # Eq. 133.
171
175
  def log(self) -> np.ndarray:
172
- if self.wxyz[0] < 0.0:
173
- theta = 2.0 * np.arccos(-self.wxyz[0])
174
- axis = -1.0 * np.array(self.wxyz[1:])
175
- else:
176
- theta = 2.0 * np.arccos(self.wxyz[0])
177
- axis = np.array(self.wxyz[1:])
178
- mujoco.mju_normalize3(axis)
179
- return theta * axis
176
+ q = np.array(self.wxyz)
177
+ q *= np.sign(q[0])
178
+ w, v = q[0], q[1:]
179
+ norm = mujoco.mju_normalize3(v)
180
+ if norm < get_epsilon(v.dtype):
181
+ return np.zeros_like(v)
182
+ return 2 * np.arctan2(norm, w) * v
180
183
 
181
184
  # Eq. 139.
182
185
  def adjoint(self) -> np.ndarray:
mink/limits/__init__.py CHANGED
@@ -2,7 +2,6 @@
2
2
 
3
3
  from .collision_avoidance_limit import CollisionAvoidanceLimit
4
4
  from .configuration_limit import ConfigurationLimit
5
- from .exceptions import LimitDefinitionError
6
5
  from .limit import Constraint, Limit
7
6
  from .velocity_limit import VelocityLimit
8
7
 
@@ -12,5 +11,4 @@ __all__ = (
12
11
  "Constraint",
13
12
  "Limit",
14
13
  "VelocityLimit",
15
- "LimitDefinitionError",
16
14
  )
@@ -7,7 +7,7 @@ import numpy as np
7
7
 
8
8
  from ..configuration import Configuration
9
9
  from ..constants import dof_width, qpos_width
10
- from .exceptions import LimitDefinitionError
10
+ from ..exceptions import LimitDefinitionError
11
11
  from .limit import Constraint, Limit
12
12
 
13
13
 
@@ -98,7 +98,7 @@ class ConfigurationLimit(Limit):
98
98
  return Constraint()
99
99
 
100
100
  # Upper.
101
- delta_q_max = np.zeros((self.model.nv,))
101
+ delta_q_max = np.empty((self.model.nv,))
102
102
  mujoco.mj_differentiatePos(
103
103
  m=self.model,
104
104
  qvel=delta_q_max,
@@ -108,7 +108,7 @@ class ConfigurationLimit(Limit):
108
108
  )
109
109
 
110
110
  # Lower.
111
- delta_q_min = np.zeros((self.model.nv,))
111
+ delta_q_min = np.empty((self.model.nv,))
112
112
  mujoco.mj_differentiatePos(
113
113
  m=self.model,
114
114
  qvel=delta_q_min,
@@ -8,7 +8,7 @@ import numpy.typing as npt
8
8
 
9
9
  from ..configuration import Configuration
10
10
  from ..constants import dof_width
11
- from .exceptions import LimitDefinitionError
11
+ from ..exceptions import LimitDefinitionError
12
12
  from .limit import Constraint, Limit
13
13
 
14
14
 
mink/solve_ik.py CHANGED
@@ -7,11 +7,11 @@ import qpsolvers
7
7
 
8
8
  from .configuration import Configuration
9
9
  from .limits import ConfigurationLimit, Limit
10
- from .tasks import Objective, Task
10
+ from .tasks import BaseTask, Objective
11
11
 
12
12
 
13
13
  def _compute_qp_objective(
14
- configuration: Configuration, tasks: Sequence[Task], damping: float
14
+ configuration: Configuration, tasks: Sequence[BaseTask], damping: float
15
15
  ) -> Objective:
16
16
  H = np.eye(configuration.model.nv) * damping
17
17
  c = np.zeros(configuration.model.nv)
@@ -42,7 +42,7 @@ def _compute_qp_inequalities(
42
42
 
43
43
  def build_ik(
44
44
  configuration: Configuration,
45
- tasks: Sequence[Task],
45
+ tasks: Sequence[BaseTask],
46
46
  dt: float,
47
47
  damping: float = 1e-12,
48
48
  limits: Optional[Sequence[Limit]] = None,
@@ -53,7 +53,9 @@ def build_ik(
53
53
  configuration: Robot configuration.
54
54
  tasks: List of kinematic tasks.
55
55
  dt: Integration timestep in [s].
56
- damping: Levenberg-Marquardt damping.
56
+ damping: Levenberg-Marquardt damping. Higher values improve numerical
57
+ stability but slow down task convergence. This value applies to all
58
+ dofs, including floating-base coordinates.
57
59
  limits: List of limits to enforce. Set to empty list to disable. If None,
58
60
  defaults to a configuration limit.
59
61
 
@@ -67,7 +69,7 @@ def build_ik(
67
69
 
68
70
  def solve_ik(
69
71
  configuration: Configuration,
70
- tasks: Sequence[Task],
72
+ tasks: Sequence[BaseTask],
71
73
  dt: float,
72
74
  solver: str,
73
75
  damping: float = 1e-12,
@@ -85,7 +87,9 @@ def solve_ik(
85
87
  tasks: List of kinematic tasks.
86
88
  dt: Integration timestep in [s].
87
89
  solver: Backend quadratic programming (QP) solver.
88
- damping: Levenberg-Marquardt damping.
90
+ damping: Levenberg-Marquardt damping applied to all tasks. Higher values
91
+ improve numerical stability but slow down task convergence. This
92
+ value applies to all dofs, including floating-base coordinates.
89
93
  safety_break: If True, stop execution and raise an exception if
90
94
  the current configuration is outside limits. If False, print a
91
95
  warning and continue execution.
mink/tasks/__init__.py CHANGED
@@ -3,20 +3,14 @@
3
3
  from .com_task import ComTask
4
4
  from .damping_task import DampingTask
5
5
  from .equality_constraint_task import EqualityConstraintTask
6
- from .exceptions import (
7
- InvalidConstraint,
8
- InvalidDamping,
9
- InvalidGain,
10
- InvalidTarget,
11
- TargetNotSet,
12
- TaskDefinitionError,
13
- )
14
6
  from .frame_task import FrameTask
7
+ from .kinetic_energy_regularization_task import KineticEnergyRegularizationTask
15
8
  from .posture_task import PostureTask
16
9
  from .relative_frame_task import RelativeFrameTask
17
- from .task import Objective, Task
10
+ from .task import BaseTask, Objective, Task
18
11
 
19
12
  __all__ = (
13
+ "BaseTask",
20
14
  "ComTask",
21
15
  "FrameTask",
22
16
  "Objective",
@@ -24,11 +18,6 @@ __all__ = (
24
18
  "PostureTask",
25
19
  "RelativeFrameTask",
26
20
  "Task",
27
- "TargetNotSet",
28
- "InvalidTarget",
29
- "TaskDefinitionError",
30
- "InvalidConstraint",
31
- "InvalidGain",
32
- "InvalidDamping",
33
21
  "EqualityConstraintTask",
22
+ "KineticEnergyRegularizationTask",
34
23
  )
mink/tasks/com_task.py CHANGED
@@ -9,7 +9,7 @@ import numpy as np
9
9
  import numpy.typing as npt
10
10
 
11
11
  from ..configuration import Configuration
12
- from .exceptions import InvalidTarget, TargetNotSet, TaskDefinitionError
12
+ from ..exceptions import InvalidTarget, TargetNotSet, TaskDefinitionError
13
13
  from .task import Task
14
14
 
15
15
 
@@ -18,6 +18,20 @@ class ComTask(Task):
18
18
 
19
19
  Attributes:
20
20
  target_com: Target position of the CoM.
21
+
22
+ Example:
23
+
24
+ .. code-block:: python
25
+
26
+ com_task = ComTask(model, cost=1.0)
27
+
28
+ # Update the target CoM directly.
29
+ com_desired = np.zeros(3)
30
+ com_task.set_target(com_desired)
31
+
32
+ # Or from a keyframe defined in the model.
33
+ configuration.update_from_keyframe("home")
34
+ com_task.set_target_from_configuration(configuration)
21
35
  """
22
36
 
23
37
  k: int = 3
@@ -69,7 +83,21 @@ class ComTask(Task):
69
83
  self.set_target(configuration.data.subtree_com[1])
70
84
 
71
85
  def compute_error(self, configuration: Configuration) -> np.ndarray:
72
- """Compute the CoM task error.
86
+ r"""Compute the CoM task error.
87
+
88
+ The center of mass :math:`c(q)` for a collection of bodies :math:`\mathcal{B}`
89
+ is the mass-weighted average of their individual centers of mass. After running
90
+ forward kinematics, in particular after calling ``mj_comPos``, MuJoCo stores
91
+ the CoM of each subtree in ``data.subtree_com``. This task uses the CoM of the
92
+ subtree starting from body 1, which is the entire robot excluding the world
93
+ body (body 0).
94
+
95
+ The task error :math:`e(q)` is the difference between the current CoM
96
+ :math:`c(q)` and the target CoM :math:`c^*`:
97
+
98
+ .. math::
99
+
100
+ e(q) = c(q) - c^*
73
101
 
74
102
  Args:
75
103
  configuration: Robot configuration :math:`q`.
@@ -79,19 +107,46 @@ class ComTask(Task):
79
107
  """
80
108
  if self.target_com is None:
81
109
  raise TargetNotSet(self.__class__.__name__)
110
+ # Note: body 0 is the world body, so we start from body 1 (the robot).
111
+ # TODO(kevin): Don't hardcode subtree index.
82
112
  return configuration.data.subtree_com[1] - self.target_com
83
113
 
84
114
  def compute_jacobian(self, configuration: Configuration) -> np.ndarray:
85
- """Compute the CoM task Jacobian.
115
+ r"""Compute the Jacobian of the CoM task error :math:`e(q)`.
116
+
117
+ The Jacobian is the derivative of this error with respect to the
118
+ generalized coordinates :math:`q`. Since the target :math:`c^*` is
119
+ constant, the Jacobian of the error simplifies to the Jacobian of the
120
+ CoM position :math:`c(q)`:
121
+
122
+ .. math::
123
+
124
+ J(q) = \frac{\partial e(q)}{\partial q} = \frac{\partial c(q)}{\partial q}
125
+
126
+ MuJoCo's ``mj_jacSubtreeCom`` function computes this Jacobian using the
127
+ formula:
128
+
129
+ .. math::
130
+
131
+ \frac{\partial c(q)}{\partial q} =
132
+ \frac{1}{M} \sum_{i \in \mathcal{B}} m_i \frac{\partial p_i(q)}{\partial q}
133
+ = \frac{1}{M} \sum_{i \in \mathcal{B}} m_i J_i(q)
134
+
135
+ where :math:`M = \sum_{i \in \mathcal{B}} m_i` is the total mass of the subtree,
136
+ :math:`m_i` is the mass of body :math:`i`, :math:`p_i(q)` is the position
137
+ of the origin of body frame :math:`i` in the world frame, :math:`J_i(q) =
138
+ \frac{\partial p_i(q)}{\partial q}` is the Jacobian mapping joint velocities to
139
+ the linear velocity of the origin of body frame :math:`i`, and the sum is over
140
+ all bodies :math:`\mathcal{B}` in the specified subtree (body 1 and its
141
+ descendants).
86
142
 
87
143
  Args:
88
144
  configuration: Robot configuration :math:`q`.
89
145
 
90
146
  Returns:
91
- Center-of-mass task jacobian :math:`J(q)`.
147
+ Jacobian of the center-of-mass task error :math:`J(q)`.
92
148
  """
93
- if self.target_com is None:
94
- raise TargetNotSet(self.__class__.__name__)
149
+ # NOTE: We don't need a target CoM to compute this Jacobian.
95
150
  jac = np.empty((self.k, configuration.nv))
96
151
  mujoco.mj_jacSubtreeCom(configuration.model, configuration.data, jac, 1)
97
152
  return jac
@@ -1,20 +1,66 @@
1
1
  """Damping task implementation."""
2
2
 
3
- from __future__ import annotations
4
-
5
3
  import mujoco
4
+ import numpy as np
6
5
  import numpy.typing as npt
7
6
 
7
+ from ..configuration import Configuration
8
8
  from .posture_task import PostureTask
9
9
 
10
10
 
11
11
  class DampingTask(PostureTask):
12
- """Minimize joint velocities.
12
+ r"""L2-regularization on joint velocities (a.k.a. *velocity damping*).
13
+
14
+ This low-priority task adds a Tikhonov/Levenberg-Marquardt term to the
15
+ quadratic program, making the Hessian strictly positive-definite and
16
+ selecting the **minimum-norm joint velocity** in any redundant or
17
+ near-singular situation. Formally it contributes:
18
+
19
+ .. math::
20
+ \frac{1}{2}\,\Delta \mathbf{q}^\top \Lambda\,\Delta \mathbf{q},
21
+
22
+ where :math:`\Delta \mathbf{q}\in\mathbb{R}^{n_v}` is the vector of joint
23
+ displacements and :math:`\Lambda = \mathrm{diag}(\lambda_1, \ldots, \lambda_{n_v})`
24
+ is a diagonal matrix of per-DoF weights provided by ``cost``. A larger
25
+ :math:`\lambda_i` reduces motion in DoF :math:`i`; with no other active
26
+ tasks the robot remains at rest.
27
+
28
+ This task does not favor a particular posture—only small instantaneous
29
+ motion. If you need a posture bias, use an explicit :class:`~.PostureTask`.
30
+
31
+ .. note::
32
+
33
+ Floating-base coordinates are not affected by this task.
34
+
35
+ Example:
13
36
 
14
- This task is implemented as a special case of the PostureTask where the gain and
15
- target configuration are set to 0 and qpos0 respectively.
37
+ .. code-block:: python
38
+
39
+ # Uniform damping across all degrees of freedom.
40
+ damping_task = DampingTask(model, cost=1.0)
41
+
42
+ # Custom damping.
43
+ cost = np.zeros(model.nv)
44
+ cost[:3] = 1.0 # High damping for the first 3 joints.
45
+ cost[3:] = 0.1 # Lower damping for the remaining joints.
46
+ damping_task = DampingTask(model, cost)
16
47
  """
17
48
 
18
49
  def __init__(self, model: mujoco.MjModel, cost: npt.ArrayLike):
19
- super().__init__(model=model, cost=cost, gain=0.0, lm_damping=0.0)
20
- self.target_q = model.qpos0
50
+ super().__init__(model, cost, gain=0.0, lm_damping=0.0)
51
+
52
+ def compute_error(self, configuration: Configuration) -> np.ndarray:
53
+ r"""Compute the damping task error.
54
+
55
+ The damping task does not chase a reference; its desired joint velocity
56
+ is identically **zero**, so the error vector is always
57
+
58
+ .. math:: e = \mathbf 0 \in \mathbb R^{n_v}.
59
+
60
+ Args:
61
+ configuration: Robot configuration :math:`q`.
62
+
63
+ Returns:
64
+ Zero vector of length :math:`n_v`.
65
+ """
66
+ return np.zeros(configuration.nv)
@@ -10,7 +10,7 @@ import numpy as np
10
10
  import numpy.typing as npt
11
11
 
12
12
  from ..configuration import Configuration
13
- from .exceptions import InvalidConstraint, TaskDefinitionError
13
+ from ..exceptions import InvalidConstraint, TaskDefinitionError
14
14
  from .task import Task
15
15
 
16
16
 
@@ -24,20 +24,54 @@ def _get_constraint_dim(constraint: int) -> int:
24
24
  }[constraint]
25
25
 
26
26
 
27
+ def _sparse2dense_fallback(
28
+ res: np.ndarray,
29
+ mat: np.ndarray,
30
+ rownnz: np.ndarray,
31
+ rowadr: np.ndarray,
32
+ colind: np.ndarray,
33
+ ) -> None:
34
+ """Fallback implementation of mujoco.mju_sparse2dense for Python 3.8.
35
+
36
+ This is a fallback implementation of mujoco.mju_sparse2dense for Python 3.8.
37
+ It is used when the version of MuJoCo is less than 3.2.5. This is because
38
+ mujoco.mju_sparse2dense was added Oct 23, 2024 which corresponds to 3.2.5+ and
39
+ Python 3.8 was dropped in 3.2.4.
40
+ """
41
+ # Ref: https://github.com/google-deepmind/mujoco/blob/178fb49c2b2ff48f59653515ab09b9cafca31b7a/src/engine/engine_util_sparse.c#L135
42
+ for r in range(res.shape[0]):
43
+ for i in range(rownnz[r]):
44
+ res[r, colind[rowadr[r] + i]] = mat[rowadr[r] + i]
45
+
46
+
27
47
  def _get_dense_constraint_jacobian(
28
48
  model: mujoco.MjModel, data: mujoco.MjData
29
49
  ) -> np.ndarray:
30
50
  """Return the dense constraint Jacobian for a model."""
31
- if mujoco.mj_isSparse(model):
32
- efc_J = np.empty((data.nefc, model.nv))
33
- mujoco.mju_sparse2dense(
34
- efc_J,
35
- data.efc_J,
36
- data.efc_J_rownnz,
37
- data.efc_J_rowadr,
38
- data.efc_J_colind,
39
- )
51
+
52
+ def _sparse2dense(data: mujoco.MjData) -> np.ndarray:
53
+ if mujoco.__version__ < "3.2.5":
54
+ efc_J = np.zeros((data.nefc, model.nv)) # Important to zero out here.
55
+ _sparse2dense_fallback(
56
+ efc_J,
57
+ data.efc_J,
58
+ data.efc_J_rownnz,
59
+ data.efc_J_rowadr,
60
+ data.efc_J_colind,
61
+ )
62
+ else:
63
+ efc_J = np.empty((data.nefc, model.nv))
64
+ mujoco.mju_sparse2dense(
65
+ efc_J,
66
+ data.efc_J,
67
+ data.efc_J_rownnz,
68
+ data.efc_J_rowadr,
69
+ data.efc_J_colind,
70
+ )
40
71
  return efc_J
72
+
73
+ if mujoco.mj_isSparse(model):
74
+ return _sparse2dense(data)
41
75
  return data.efc_J.reshape((data.nefc, model.nv)).copy()
42
76
 
43
77
 
@@ -53,9 +87,18 @@ class EqualityConstraintTask(Task):
53
87
  * ``mjEQ_JOINT``: Couple the values of two scalar joints.
54
88
  * ``mjEQ_TENDON``: Couple the values of two tendons.
55
89
 
56
- This task can regulate all equality constraints in a model or a specific subset
90
+ This task can regulate all equality constraints in the model or a specific subset
57
91
  identified by name or ID.
58
92
 
93
+ .. note::
94
+
95
+ MuJoCo computes the constraint residual and its Jacobian and stores them in
96
+ ``data.efc_pos`` and ``data.efc_J`` (potentially in sparse format), respectively.
97
+ The :func:`compute_error` and :func:`compute_jacobian` methods simply extract the
98
+ rows corresponding to the active equality constraints specified for this task
99
+ from ``data.efc_pos`` and ``data.efc_J``. More information on MuJoCo's constraint
100
+ model can be found in [MuJoCoEqualityConstraints]_.
101
+
59
102
  Attributes:
60
103
  equalities: ID or name of the equality constraints to regulate. If not provided,
61
104
  the task will regulate all equality constraints in the model.
@@ -126,32 +169,25 @@ class EqualityConstraintTask(Task):
126
169
  self.cost = np.repeat(self._cost, repeats)
127
170
 
128
171
  def compute_error(self, configuration: Configuration) -> np.ndarray:
129
- """Compute the equality constraint task error.
172
+ """Compute the task error (constraint residual) :math:`e(q) = r(q)`.
130
173
 
131
174
  Args:
132
175
  configuration: Robot configuration :math:`q`.
133
176
 
134
177
  Returns:
135
- Equality constraint task error vector :math:`e(q)`. The shape of the
136
- error vector is ``(neq_active * constraint_dim,)``, where ``neq_active``
137
- is the number of active equality constraints, and ``constraint_dim``
138
- depends on the type of equality constraint.
178
+ Task error vector :math:`e(q)` for the active equality constraints.
139
179
  """
140
180
  self._update_active_constraints(configuration)
141
181
  return configuration.data.efc_pos[self._mask]
142
182
 
143
183
  def compute_jacobian(self, configuration: Configuration) -> np.ndarray:
144
- """Compute the task Jacobian at a given configuration.
184
+ """Compute the task Jacobian (constraint Jacobian) :math:`J(q) = J_r(q)`.
145
185
 
146
186
  Args:
147
187
  configuration: Robot configuration :math:`q`.
148
188
 
149
189
  Returns:
150
- Equality constraint task jacobian :math:`J(q)`. The shape of the Jacobian
151
- is ``(neq_active * constraint_dim, nv)``, where ``neq_active`` is the
152
- number of active equality constraints, ``constraint_dim`` depends on the
153
- type of equality constraint, and ``nv`` is the dimension of the tangent
154
- space.
190
+ Task jacobian :math:`J(q)` for the active equality constraints.
155
191
  """
156
192
  self._update_active_constraints(configuration)
157
193
  efc_J = _get_dense_constraint_jacobian(configuration.model, configuration.data)
mink/tasks/frame_task.py CHANGED
@@ -8,19 +8,38 @@ import numpy as np
8
8
  import numpy.typing as npt
9
9
 
10
10
  from ..configuration import Configuration
11
+ from ..exceptions import TargetNotSet, TaskDefinitionError
11
12
  from ..lie import SE3
12
- from .exceptions import TargetNotSet, TaskDefinitionError
13
13
  from .task import Task
14
14
 
15
15
 
16
16
  class FrameTask(Task):
17
- """Regulate the pose of a frame expressed in the world frame.
17
+ """Regulate the position and orientation of a frame expressed in the world frame.
18
18
 
19
19
  Attributes:
20
20
  frame_name: Name of the frame to regulate, typically the name of body, geom
21
21
  or site in the robot model.
22
22
  frame_type: The frame type: `body`, `geom` or `site`.
23
23
  transform_frame_to_world: Target pose of the frame.
24
+
25
+ Example:
26
+
27
+ .. code-block:: python
28
+
29
+ frame_task = FrameTask(
30
+ frame_name="target",
31
+ frame_type="site",
32
+ position_cost=1.0,
33
+ orientation_cost=1.0,
34
+ )
35
+
36
+ # Update the target pose directly.
37
+ transform_target_to_world = SE3.from_translation(np.random.rand(3))
38
+ frame_task.set_target(transform_target_to_world)
39
+
40
+ # Or from the current configuration. This will automatically compute the
41
+ # target pose from the current configuration and update the task target.
42
+ frame_task.set_target_from_configuration(configuration)
24
43
  """
25
44
 
26
45
  k: int = 6
@@ -0,0 +1,74 @@
1
+ """Kinetic energy regularization task implementation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Optional, SupportsFloat
6
+
7
+ import numpy as np
8
+
9
+ from ..configuration import Configuration
10
+ from ..exceptions import IntegrationTimestepNotSet, TaskDefinitionError
11
+ from .task import BaseTask, Objective
12
+
13
+
14
+ class KineticEnergyRegularizationTask(BaseTask):
15
+ r"""Kinetic-energy regularization task.
16
+
17
+ This low-priority task adds a configuration-dependent quadratic term to the
18
+ QP objective that penalizes the system's kinetic energy. Formally, it contributes:
19
+
20
+ .. math::
21
+ \frac{1}{2}\, \lambda\, \Delta \mathbf{q}^\top M(\mathbf{q})\,\Delta \mathbf{q},
22
+
23
+ where :math:`\Delta \mathbf{q}\in\mathbb{R}^{n_v}` is the vector of joint
24
+ displacements, :math:`M(\mathbf{q})` is the joint-space inertia matrix
25
+ (dependent on the current configuration), and :math:`\lambda` is the scalar
26
+ strength of the regularization.
27
+
28
+ .. note::
29
+
30
+ This task penalizes DoFs in proportion to their joint-space inertia, so
31
+ higher-inertia (i.e., heavier) links will move less. This is in contrast to
32
+ :class:`~.L2RegularizationTask`, which uniformly damps all DoFs.
33
+
34
+ .. warning::
35
+
36
+ The timestep :math:`\Delta t` must be set via :meth:`set_dt` before use.
37
+ This task penalizes velocity via displacement, and omitting `dt` will raise
38
+ a runtime error.
39
+
40
+ Example:
41
+
42
+ .. code-block:: python
43
+
44
+ task = KineticEnergyRegularizationTask(cost=1e-4)
45
+ task.set_dt(0.02)
46
+ """
47
+
48
+ def __init__(self, cost: SupportsFloat):
49
+ cost = float(cost)
50
+ if cost < 0:
51
+ raise TaskDefinitionError(f"{self.__class__.__name__} cost should be >= 0")
52
+ self.cost: float = cost
53
+
54
+ # Kinetic energy is defined as T = ½ * q̇ᵀ * M * q̇. Since q̇ ≈ Δq / dt, we
55
+ # substitute: T ≈ ½ * (Δq / dt)ᵀ * M * (Δq / dt) = ½ * Δqᵀ * (M / dt²) * Δq.
56
+ # Therefore, we scale the inertia matrix by 1 / dt² to penalize energy in
57
+ # terms of joint displacements Δq.
58
+ self.inv_dt_sq: Optional[float] = None
59
+
60
+ def set_dt(self, dt: float) -> None:
61
+ """Set the integration timestep.
62
+
63
+ Args:
64
+ dt: Integration timestep in [s].
65
+ """
66
+ self.inv_dt_sq = 1.0 / dt**2
67
+
68
+ def compute_qp_objective(self, configuration: Configuration) -> Objective:
69
+ if self.inv_dt_sq is None:
70
+ raise IntegrationTimestepNotSet(self.__class__.__name__)
71
+ M = configuration.get_inertia_matrix()
72
+ H = self.cost * self.inv_dt_sq * M
73
+ c = np.zeros(configuration.nv)
74
+ return Objective(H, c)
@@ -9,19 +9,36 @@ import numpy as np
9
9
  import numpy.typing as npt
10
10
 
11
11
  from ..configuration import Configuration
12
+ from ..exceptions import InvalidTarget, TargetNotSet, TaskDefinitionError
12
13
  from ..utils import get_freejoint_dims
13
- from .exceptions import InvalidTarget, TargetNotSet, TaskDefinitionError
14
14
  from .task import Task
15
15
 
16
16
 
17
17
  class PostureTask(Task):
18
18
  """Regulate the joint angles of the robot towards a desired posture.
19
19
 
20
- A posture is a vector of actuated joint angles. Floating-base coordinates are not
21
- affected by this task.
20
+ Using this task with a low cost value is useful as a regularizer when the problem
21
+ is under-constrained.
22
22
 
23
23
  Attributes:
24
- target_q: Target configuration.
24
+ target_q: Target configuration :math:`q^*`, of shape :math:`(n_q,)`. Units are
25
+ radians for revolute joints and meters for prismatic joints. Note that
26
+ floating-base coordinates are not affected by this task but should be
27
+ included in the target configuration.
28
+
29
+ Example:
30
+
31
+ .. code-block:: python
32
+
33
+ posture_task = PostureTask(model, cost=1e-3)
34
+
35
+ # Update the target posture directly.
36
+ q_desired = ...
37
+ posture_task.set_target(q_desired)
38
+
39
+ # Or from a keyframe defined in the model.
40
+ configuration.update_from_keyframe("home")
41
+ posture_task.set_target_from_configuration(configuration)
25
42
  """
26
43
 
27
44
  target_q: Optional[np.ndarray]
@@ -108,8 +125,8 @@ class PostureTask(Task):
108
125
  m=configuration.model,
109
126
  qvel=qvel,
110
127
  dt=1.0,
111
- qpos1=configuration.q,
112
- qpos2=self.target_q,
128
+ qpos1=self.target_q,
129
+ qpos2=configuration.q,
113
130
  )
114
131
 
115
132
  if self._v_ids is not None:
@@ -132,11 +149,7 @@ class PostureTask(Task):
132
149
  Returns:
133
150
  Posture task jacobian :math:`J(q)`.
134
151
  """
135
- if self.target_q is None:
136
- raise TargetNotSet(self.__class__.__name__)
137
-
138
- jac = -np.eye(configuration.nv)
152
+ jac = np.eye(configuration.nv)
139
153
  if self._v_ids is not None:
140
154
  jac[:, self._v_ids] = 0.0
141
-
142
155
  return jac
@@ -8,8 +8,8 @@ import numpy as np
8
8
  import numpy.typing as npt
9
9
 
10
10
  from ..configuration import Configuration
11
+ from ..exceptions import TargetNotSet, TaskDefinitionError
11
12
  from ..lie import SE3
12
- from .exceptions import TargetNotSet, TaskDefinitionError
13
13
  from .task import Task
14
14
 
15
15
 
mink/tasks/task.py CHANGED
@@ -6,23 +6,41 @@ from typing import NamedTuple
6
6
  import numpy as np
7
7
 
8
8
  from ..configuration import Configuration
9
- from .exceptions import InvalidDamping, InvalidGain
9
+ from ..exceptions import InvalidDamping, InvalidGain
10
10
 
11
11
 
12
12
  class Objective(NamedTuple):
13
- r"""Quadratic objective of the form :math:`\frac{1}{2} x^T H x + c^T x`."""
13
+ r"""Quadratic objective of the form
14
+ :math:`\frac{1}{2} \Delta q^T H \Delta q + c^T \Delta q`.
15
+ """
14
16
 
15
17
  H: np.ndarray
16
- """Hessian matrix, of shape (n_v, n_v)"""
18
+ r"""Hessian matrix, of shape (:math:`n_v`, :math:`n_v`)."""
17
19
  c: np.ndarray
18
- """Linear vector, of shape (n_v,)."""
20
+ r"""Linear vector, of shape (:math:`n_v`,)."""
19
21
 
20
22
  def value(self, x: np.ndarray) -> float:
21
23
  """Returns the value of the objective at the input vector."""
22
24
  return x.T @ self.H @ x + self.c @ x
23
25
 
24
26
 
25
- class Task(abc.ABC):
27
+ class BaseTask(abc.ABC):
28
+ """Base class for all tasks."""
29
+
30
+ @abc.abstractmethod
31
+ def compute_qp_objective(self, configuration: Configuration) -> Objective:
32
+ r"""Compute the matrix-vector pair :math:`(H, c)` of the QP objective.
33
+
34
+ Args:
35
+ configuration: Robot configuration :math:`q`.
36
+
37
+ Returns:
38
+ Pair :math:`(H(q), c(q))`.
39
+ """
40
+ raise NotImplementedError
41
+
42
+
43
+ class Task(BaseTask):
26
44
  r"""Abstract base class for kinematic tasks.
27
45
 
28
46
  Subclasses must implement the configuration-dependent task error
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mink
3
- Version: 0.0.9
3
+ Version: 0.0.11
4
4
  Summary: mink: MuJoCo inverse kinematics.
5
5
  Keywords: inverse,kinematics,mujoco
6
6
  Author-email: Kevin Zakka <zakka@berkeley.edu>
@@ -16,6 +16,7 @@ Classifier: Programming Language :: Python :: 3.9
16
16
  Classifier: Programming Language :: Python :: 3.10
17
17
  Classifier: Programming Language :: Python :: 3.11
18
18
  Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
19
20
  Classifier: Topic :: Scientific/Engineering
20
21
  License-File: LICENSE
21
22
  Requires-Dist: mujoco >= 3.1.6
@@ -27,7 +28,6 @@ Requires-Dist: black ; extra == "dev"
27
28
  Requires-Dist: mink[test] ; extra == "dev"
28
29
  Requires-Dist: mypy ; extra == "dev"
29
30
  Requires-Dist: ruff ; extra == "dev"
30
- Requires-Dist: dm_control >= 1.0.20 ; extra == "examples"
31
31
  Requires-Dist: loop-rate-limiters >= 0.1.0 ; extra == "examples"
32
32
  Requires-Dist: qpsolvers[daqp] >= 4.3.1 ; extra == "examples"
33
33
  Requires-Dist: osqp >=0.6.2,<1 ; extra == "examples"
@@ -66,14 +66,14 @@ For usage and API reference, see the [documentation](https://kevinzakka.github.i
66
66
  If you use mink in your research, please cite it as follows:
67
67
 
68
68
  ```bibtex
69
- @software{Zakka_Mink_Python_inverse_2024,
69
+ @software{Zakka_Mink_Python_inverse_2025,
70
70
  author = {Zakka, Kevin},
71
- license = {Apache-2.0},
72
- month = jul,
73
71
  title = {{Mink: Python inverse kinematics based on MuJoCo}},
72
+ year = {2025},
73
+ month = may,
74
+ version = {0.0.11},
74
75
  url = {https://github.com/kevinzakka/mink},
75
- version = {0.0.4},
76
- year = {2024}
76
+ license = {Apache-2.0}
77
77
  }
78
78
  ```
79
79
 
@@ -1,9 +1,9 @@
1
- mink/__init__.py,sha256=g-eOZoPMgO3l4PtP7RK4ercpo1lyLnIcOT6Tb78T968,1829
2
- mink/configuration.py,sha256=wbP2ab-Zn5pH844Czk5w8mgDXP44AosMOdNxqwyCSik,9199
1
+ mink/__init__.py,sha256=q1A7zX73664z9YJXcW7m2xMhtuZSWMf_eBtjD-NUCDI,2241
2
+ mink/configuration.py,sha256=kYKXS7yuLhXHtJgksrDhaWyyYw8mKoB_tYPijedXHiU,9847
3
3
  mink/constants.py,sha256=hcWy4zM4hGI7vvJrTmCjJgs2WtOxKJ1IVtYHucWbOAI,813
4
- mink/exceptions.py,sha256=tmExo-ydn_mu9Mny5sP0Ehr7hfo3d79fM8HvvxZBKYM,2931
4
+ mink/exceptions.py,sha256=Y8xrcEXtijXaUaf1H02aoIGmRQ7W05cxRKaqxcDp10M,4024
5
5
  mink/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
- mink/solve_ik.py,sha256=VzPYpfxkJ-JxUZIpwN7-WVOw0Oi2YiIvDZcwB5ROeug,3591
6
+ mink/solve_ik.py,sha256=m_p_woj4InctpkA-JLlAHKQp8Ei9RorR9E9elTNFZYI,3962
7
7
  mink/utils.py,sha256=Eok-pr8xR4LjmjEDEOtD7pvZPDCk53K9gWGdth8TxOA,5329
8
8
  mink/.mypy_cache/.gitignore,sha256=amnaZw0RUw038PDP3HvtMLeOpkNOJPenMgi5guKdMiw,34
9
9
  mink/.mypy_cache/CACHEDIR.TAG,sha256=8cE6_FVTWMkDOw8fMKqhd_6IvaQPS4okWYQA1UeHatw,190
@@ -334,24 +334,23 @@ mink/contrib/keyboard_teleop/teleop_mocap.py,sha256=2cuauiBHsQb6IVruRbGtCumdHQaz
334
334
  mink/lie/__init__.py,sha256=7tm3ZFnF3o1SDd9MOFO1In13lHMQJHO0FB-ejI6tsgE,202
335
335
  mink/lie/base.py,sha256=8TGWWEWRvmoBsJP-9y1YXQHkTC-TFfI8JDvBFKxxP-A,4865
336
336
  mink/lie/se3.py,sha256=cEzAzKEfBAQcbHhbZbhW8QZA8WpfRRaeZ0YGdSmhOx8,8634
337
- mink/lie/so3.py,sha256=0KgvflDlUJHd_Ruy2pDlgyR7ZC1HkJz4HVxWcCLo5EY,8182
337
+ mink/lie/so3.py,sha256=Goipwo7PRxNecYRNBmueWCiO2D51D7qHlzs2gQiXO-Q,8423
338
338
  mink/lie/utils.py,sha256=DuEl3pj84daLvMKN84-YBvkXnJfqvc5vpvJ9J-pJ11U,403
339
- mink/limits/__init__.py,sha256=hX5Dgpri9AE6YtUCkW79AXMBuNAuBhniR9kQ6Rxwv3Y,416
339
+ mink/limits/__init__.py,sha256=-ijdhSGfMRVE1o1pJ-3qTSsSNIIVxhdk2Z511_UzjzU,343
340
340
  mink/limits/collision_avoidance_limit.py,sha256=MJXesSjvm_2O6RUEz2e4D8uTVOHyTsH9j4UxkPemcn8,11918
341
- mink/limits/configuration_limit.py,sha256=WspxM4W3-VFIKVo8FLg68x7T9EMmfRmzefiWmi4qrZY,4376
342
- mink/limits/exceptions.py,sha256=EnVKgFhUJFM6rNVCtdngb-XMu66PWKMFSDy-XkdKzr8,178
341
+ mink/limits/configuration_limit.py,sha256=y_1mWbEeuprjcuAgJnFOKdWNI-KqxTPA9X0pW9MF9zQ,4377
343
342
  mink/limits/limit.py,sha256=65K4clGFCPxa3TScGaLhYe1rVYgmJnkMnsFg6DCGjI4,1529
344
- mink/limits/velocity_limit.py,sha256=2i1Jsh6Y4_qw6CR5_hNxQr-X1YkfJtfeLqlsuqj2b8k,3744
345
- mink/tasks/__init__.py,sha256=rTx9Ab8XPSohhSa1RUD7lNggTzVi02LOaPzPZFMFvuI,763
346
- mink/tasks/com_task.py,sha256=ch6w7pwa5E0GVo2DCAuEF-c8TCN1iMk-ySY9A4B6yoQ,3121
347
- mink/tasks/damping_task.py,sha256=SwSfUvMHzoNYNsloQRD1qlPLd4kfoDIWZlTDU9LuKM4,556
348
- mink/tasks/equality_constraint_task.py,sha256=Ou8jBSC1SsZCi_WbzkgdYog4-rXsUF2uMmwGpFSlBZU,8196
349
- mink/tasks/exceptions.py,sha256=d2P9q_CWaHUXxgSwFjcu-ml87mLuXJYxrVLUwrJp6w8,803
350
- mink/tasks/frame_task.py,sha256=DeNg-bEJxqnrRI0FaJK4UHyb8CyF4A7uPF9G-CdN0sg,5307
351
- mink/tasks/posture_task.py,sha256=sVDZyalCh5DP8zmCuX5kYuZxiMxRut_mTZUjv5y3b5M,3998
352
- mink/tasks/relative_frame_task.py,sha256=9rIiYocI1eEESt0bLZZpQR7K6ggVRZH8iEhdhzkfZa0,5119
353
- mink/tasks/task.py,sha256=F16YZT1L9ueNOcKoOhbCyEnZw0DOgrmjqADl0jahVQI,4838
354
- mink-0.0.9.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
355
- mink-0.0.9.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82
356
- mink-0.0.9.dist-info/METADATA,sha256=PbX9fwluNc1-M5fB8cuJnPD33Flma45GzAU5yd6myfg,5606
357
- mink-0.0.9.dist-info/RECORD,,
343
+ mink/limits/velocity_limit.py,sha256=drb5tyOymUb_erlghfH7pAZEzfirfvsII1IPrUahSS4,3745
344
+ mink/tasks/__init__.py,sha256=W-wUUrjbnUO17YQpP8Bodm-8p5GJfwTCALS58AroH5Y,624
345
+ mink/tasks/com_task.py,sha256=9QMoUSAt4hUtC2_nWvzK1ZYVWki5P0ttMQp07HW4SKo,5494
346
+ mink/tasks/damping_task.py,sha256=CvUIHeKp0b-YwwzsH7Xr-ctQAQKQMJbmkRIUwbaixio,2279
347
+ mink/tasks/equality_constraint_task.py,sha256=ICC_vN2LB6Sv3T3QxCmbVwQNvhmjtDVaB7-a-PYUNS4,9509
348
+ mink/tasks/frame_task.py,sha256=Y4Jq58cdkpMOs322yQaMgYGBo0CKlQ-W0_wkJmCDKi0,5946
349
+ mink/tasks/kinetic_energy_regularization_task.py,sha256=iCYM8-zYZwu2tNC4jWFBWJyXfIyuCwvqXmFK-X8lMFE,2660
350
+ mink/tasks/posture_task.py,sha256=OPJgjF61QPuU7OqlTT_ThJv0YFs8uJlxcUD8mpZTdt0,4546
351
+ mink/tasks/relative_frame_task.py,sha256=Bu9vBBqzhLKZyBPj1Xc0b69dAa1twkzeLknZDVcRmoA,5120
352
+ mink/tasks/task.py,sha256=BXz17rL_KXiGBrS_5ITqMj2dQXzoQMUUN3xXfGGtJRA,5319
353
+ mink-0.0.11.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
354
+ mink-0.0.11.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82
355
+ mink-0.0.11.dist-info/METADATA,sha256=BW8wC5vCqRsYktgopCYsOQ_QuZv3oJe_iaVuD6NvoTA,5601
356
+ mink-0.0.11.dist-info/RECORD,,
mink/limits/exceptions.py DELETED
@@ -1,7 +0,0 @@
1
- """Exceptions raised by limits."""
2
-
3
- from ..exceptions import MinkError
4
-
5
-
6
- class LimitDefinitionError(MinkError):
7
- """Exception raised when a limit definition is ill-formed."""
mink/tasks/exceptions.py DELETED
@@ -1,31 +0,0 @@
1
- """Exceptions raised by tasks."""
2
-
3
- from ..exceptions import MinkError
4
-
5
-
6
- class TaskDefinitionError(MinkError):
7
- """Exception raised when a task definition is ill-formed."""
8
-
9
-
10
- class TargetNotSet(MinkError):
11
- """Exception raised when attempting to use a task with an unset target."""
12
-
13
- def __init__(self, cls_name: str):
14
- message = f"No target set for {cls_name}"
15
- super().__init__(message)
16
-
17
-
18
- class InvalidTarget(MinkError):
19
- """Exception raised when the target is invalid."""
20
-
21
-
22
- class InvalidGain(MinkError):
23
- """Exception raised when the gain is outside the valid range."""
24
-
25
-
26
- class InvalidDamping(MinkError):
27
- """Exception raised when the damping is outside the valid range."""
28
-
29
-
30
- class InvalidConstraint(MinkError):
31
- """Exception raised when a constraint is invalid."""
File without changes