154 lines
6.0 KiB
Python
154 lines
6.0 KiB
Python
"""Resolve MuJoCo joints and their controls by name."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass
|
|
from numbers import Real
|
|
|
|
import mujoco
|
|
import numpy as np
|
|
|
|
_SCALAR = (mujoco.mjtJoint.mjJNT_HINGE, mujoco.mjtJoint.mjJNT_SLIDE)
|
|
_JOINT = mujoco.mjtTrn.mjTRN_JOINT
|
|
|
|
|
|
def object_id(model: mujoco.MjModel, kind: mujoco.mjtObj, name: str) -> int:
|
|
index = mujoco.mj_name2id(model, kind, name)
|
|
if index < 0:
|
|
raise ValueError(f"Model has no {kind.name.removeprefix('mjOBJ_').lower()} {name!r}")
|
|
return index
|
|
|
|
|
|
def joint_ids(model: mujoco.MjModel, names: list[str]) -> np.ndarray:
|
|
if (
|
|
not isinstance(names, list)
|
|
or not names
|
|
or not all(isinstance(name, str) and name for name in names)
|
|
or len(set(names)) != len(names)
|
|
):
|
|
raise ValueError("joints must be a nonempty list of unique names")
|
|
ids = np.array([object_id(model, mujoco.mjtObj.mjOBJ_JOINT, name) for name in names])
|
|
if any(model.jnt_type[j] not in _SCALAR for j in ids):
|
|
raise ValueError("Controlled joints must be hinges or slides")
|
|
return ids
|
|
|
|
|
|
def joint_actuators(model: mujoco.MjModel, ids: np.ndarray) -> list[np.ndarray]:
|
|
return [
|
|
np.flatnonzero((model.actuator_trntype == _JOINT) & (model.actuator_trnid[:, 0] == joint))
|
|
for joint in ids
|
|
]
|
|
|
|
|
|
def finite(value, field: str, *, positive: bool = False) -> float:
|
|
if not isinstance(value, Real) or isinstance(value, bool) or not np.isfinite(value):
|
|
raise ValueError(f"{field} must be a finite number")
|
|
if positive and value <= 0:
|
|
raise ValueError(f"{field} must be positive")
|
|
return float(value)
|
|
|
|
|
|
def vector(value, size: int, field: str) -> np.ndarray:
|
|
if not isinstance(value, (list, tuple, np.ndarray)) or len(value) != size:
|
|
raise ValueError(f"{field} must contain {size} numbers")
|
|
return np.array([finite(v, field) for v in value], dtype=np.float64)
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class JointControl:
|
|
names: tuple[str, ...]
|
|
ctrl: np.ndarray
|
|
pos: np.ndarray
|
|
vel: np.ndarray
|
|
lo: np.ndarray
|
|
hi: np.ndarray
|
|
|
|
@classmethod
|
|
def bind(cls, model: mujoco.MjModel, names: list[str], kind: str) -> JointControl:
|
|
ids = joint_ids(model, names)
|
|
actuators = joint_actuators(model, ids)
|
|
if any(len(group) != 1 for group in actuators):
|
|
raise ValueError("Each controlled joint must have one joint actuator. Run setup first")
|
|
ctrl = np.array([group[0] for group in actuators])
|
|
if not np.allclose(model.actuator_gear[ctrl], [1, 0, 0, 0, 0, 0], rtol=0, atol=1e-12):
|
|
raise ValueError("Controller needs unit actuator gear. Run setup first")
|
|
if np.any(model.actuator_dyntype[ctrl] != mujoco.mjtDyn.mjDYN_NONE) or np.any(
|
|
model.actuator_delay[ctrl] != 0
|
|
):
|
|
raise ValueError("Controller needs stateless actuators. Run setup first")
|
|
if np.any(model.actuator_gaintype[ctrl] != mujoco.mjtGain.mjGAIN_FIXED):
|
|
raise ValueError("Controller needs fixed-gain actuators. Run setup first")
|
|
gain = model.actuator_gainprm[ctrl, 0]
|
|
bias = model.actuator_biasprm[ctrl, :3]
|
|
bias_type = model.actuator_biastype[ctrl]
|
|
if kind == "motor":
|
|
valid = (bias_type == mujoco.mjtBias.mjBIAS_NONE) & np.isclose(gain, 1)
|
|
elif kind == "velocity":
|
|
valid = (
|
|
(bias_type == mujoco.mjtBias.mjBIAS_AFFINE)
|
|
& (gain > 0)
|
|
& np.isclose(bias[:, 0], 0)
|
|
& np.isclose(bias[:, 1], 0)
|
|
& np.isclose(bias[:, 2], -gain)
|
|
)
|
|
else:
|
|
valid = (
|
|
(bias_type == mujoco.mjtBias.mjBIAS_AFFINE)
|
|
& (gain > 0)
|
|
& np.isclose(bias[:, 0], 0)
|
|
& np.isclose(bias[:, 1], -gain)
|
|
& (bias[:, 2] <= 0)
|
|
)
|
|
if not np.all(valid):
|
|
raise ValueError(f"Controller needs {kind} actuators. Run setup first")
|
|
ranges = model.jnt_range[ids]
|
|
limited = model.jnt_limited[ids]
|
|
lo = np.where(limited, ranges[:, 0], -np.inf)
|
|
hi = np.where(limited, ranges[:, 1], np.inf)
|
|
if kind == "position":
|
|
has_ctrl_range = model.actuator_ctrllimited[ctrl]
|
|
ctrl_range = model.actuator_ctrlrange[ctrl]
|
|
lo = np.maximum(lo, np.where(has_ctrl_range, ctrl_range[:, 0], -np.inf))
|
|
hi = np.minimum(hi, np.where(has_ctrl_range, ctrl_range[:, 1], np.inf))
|
|
if np.any(lo >= hi):
|
|
raise ValueError("Actuator and joint position ranges do not overlap")
|
|
return cls(tuple(names), ctrl, model.jnt_qposadr[ids], model.jnt_dofadr[ids], lo, hi)
|
|
|
|
|
|
def normalize_actuators(
|
|
spec: mujoco.MjSpec,
|
|
model: mujoco.MjModel,
|
|
names: list[str],
|
|
kind: str,
|
|
*,
|
|
kp: float,
|
|
kd: float,
|
|
effort: float,
|
|
speed: float,
|
|
) -> None:
|
|
ids = joint_ids(model, names)
|
|
for joint, name, existing in zip(ids, names, joint_actuators(model, ids), strict=True):
|
|
if len(existing) > 1:
|
|
raise ValueError(f"Joint {name!r} has multiple actuators")
|
|
if len(existing):
|
|
actuator = spec.actuators[int(existing[0])]
|
|
if actuator.plugin.active:
|
|
raise ValueError(f"Joint {name!r} uses an actuator plugin")
|
|
else:
|
|
actuator = spec.add_actuator(name=f"mjrl_{name}", target=name, trntype=_JOINT)
|
|
actuator.gear = [1, 0, 0, 0, 0, 0]
|
|
actuator.delay = 0
|
|
if kind == "motor":
|
|
actuator.set_to_motor()
|
|
limits = [-effort, effort]
|
|
elif kind == "velocity":
|
|
actuator.set_to_velocity(kd)
|
|
limits = [-speed, speed]
|
|
else:
|
|
actuator.set_to_position(kp, kv=kd)
|
|
limits = model.jnt_range[joint] if model.jnt_limited[joint] else None
|
|
actuator.ctrllimited = int(limits is not None)
|
|
actuator.ctrlrange = limits if limits is not None else [0, 0]
|
|
actuator.forcelimited = 1
|
|
actuator.forcerange = [-effort, effort]
|