mujoco-robot 0.2.0__tar.gz → 0.3.1__tar.gz

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.
Files changed (30) hide show
  1. {mujoco_robot-0.2.0 → mujoco_robot-0.3.1}/PKG-INFO +12 -6
  2. {mujoco_robot-0.2.0 → mujoco_robot-0.3.1}/README.md +9 -5
  3. {mujoco_robot-0.2.0 → mujoco_robot-0.3.1}/mujoco_robot/ik.py +10 -4
  4. mujoco_robot-0.3.1/mujoco_robot/mujoco_object.py +405 -0
  5. {mujoco_robot-0.2.0 → mujoco_robot-0.3.1}/mujoco_robot/mujoco_robot.py +275 -627
  6. mujoco_robot-0.3.1/mujoco_robot/types.py +142 -0
  7. {mujoco_robot-0.2.0 → mujoco_robot-0.3.1}/mujoco_robot/utils/robot_loader_utils.py +2 -6
  8. {mujoco_robot-0.2.0 → mujoco_robot-0.3.1}/mujoco_robot.egg-info/PKG-INFO +12 -6
  9. {mujoco_robot-0.2.0 → mujoco_robot-0.3.1}/mujoco_robot.egg-info/SOURCES.txt +2 -0
  10. {mujoco_robot-0.2.0 → mujoco_robot-0.3.1}/pyproject.toml +3 -1
  11. {mujoco_robot-0.2.0 → mujoco_robot-0.3.1}/tests/test_control.py +33 -3
  12. {mujoco_robot-0.2.0 → mujoco_robot-0.3.1}/tests/test_cosmetics.py +9 -8
  13. mujoco_robot-0.3.1/tests/test_getters.py +316 -0
  14. {mujoco_robot-0.2.0 → mujoco_robot-0.3.1}/tests/test_ik.py +50 -0
  15. {mujoco_robot-0.2.0 → mujoco_robot-0.3.1}/tests/test_wrapping.py +26 -3
  16. mujoco_robot-0.2.0/tests/test_getters.py +0 -178
  17. {mujoco_robot-0.2.0 → mujoco_robot-0.3.1}/LICENSE +0 -0
  18. {mujoco_robot-0.2.0 → mujoco_robot-0.3.1}/mujoco_robot/__init__.py +0 -0
  19. {mujoco_robot-0.2.0 → mujoco_robot-0.3.1}/mujoco_robot/py.typed +0 -0
  20. {mujoco_robot-0.2.0 → mujoco_robot-0.3.1}/mujoco_robot/utils/__init__.py +0 -0
  21. {mujoco_robot-0.2.0 → mujoco_robot-0.3.1}/mujoco_robot/utils/model_builder.py +0 -0
  22. {mujoco_robot-0.2.0 → mujoco_robot-0.3.1}/mujoco_robot/viewer_utils.py +0 -0
  23. {mujoco_robot-0.2.0 → mujoco_robot-0.3.1}/mujoco_robot.egg-info/dependency_links.txt +0 -0
  24. {mujoco_robot-0.2.0 → mujoco_robot-0.3.1}/mujoco_robot.egg-info/requires.txt +0 -0
  25. {mujoco_robot-0.2.0 → mujoco_robot-0.3.1}/mujoco_robot.egg-info/top_level.txt +0 -0
  26. {mujoco_robot-0.2.0 → mujoco_robot-0.3.1}/setup.cfg +0 -0
  27. {mujoco_robot-0.2.0 → mujoco_robot-0.3.1}/tests/test_contacts.py +0 -0
  28. {mujoco_robot-0.2.0 → mujoco_robot-0.3.1}/tests/test_lifecycle.py +0 -0
  29. {mujoco_robot-0.2.0 → mujoco_robot-0.3.1}/tests/test_object.py +0 -0
  30. {mujoco_robot-0.2.0 → mujoco_robot-0.3.1}/tests/test_smoke.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mujoco_robot
3
- Version: 0.2.0
3
+ Version: 0.3.1
4
4
  Summary: A general Python interface class for robot simulations using MuJoCo.
5
5
  Author-email: Saif Sidhik <mail@saifsidhik.page>
6
6
  License-Expression: MIT
@@ -20,6 +20,8 @@ Classifier: Programming Language :: Python :: 3 :: Only
20
20
  Classifier: Programming Language :: Python :: 3.10
21
21
  Classifier: Programming Language :: Python :: 3.11
22
22
  Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Programming Language :: Python :: 3.13
24
+ Classifier: Programming Language :: Python :: 3.14
23
25
  Requires-Python: >=3.10
24
26
  Description-Content-Type: text/markdown
25
27
  License-File: LICENSE
@@ -83,8 +85,8 @@ from mujoco_robot.utils.robot_loader_utils import get_mjcf_from_awesome_robot_de
83
85
  robot = MujocoRobot(
84
86
  mjcf_path=get_mjcf_from_awesome_robot_descriptions("panda_mj_description"),
85
87
  ee_names=["hand"],
86
- run_async=False, # step manually
87
- render=True, # launch the passive viewer (needs a display)
88
+ run_async=False, # step manually
89
+ render=True, # launch the passive viewer (needs a display)
88
90
  )
89
91
  robot.set_position_control_mode()
90
92
 
@@ -102,9 +104,13 @@ stepped by its host (other actuated joints, other free bodies, the host's own pr
102
104
  scope `MujocoRobot` to the robot's joints:
103
105
 
104
106
  ```python
105
- robot = MujocoRobot(model=sim.model, data=sim.data,
106
- joint_names=[f"arm/{j}" for j in AUBO_JOINTS],
107
- ee_sites=["arm/tcp"], run_async=False)
107
+ robot = MujocoRobot(
108
+ model=sim.model,
109
+ data=sim.data,
110
+ joint_names=[f"arm/{j}" for j in AUBO_JOINTS],
111
+ ee_sites=["arm/tcp"],
112
+ run_async=False,
113
+ )
108
114
  # host steps: sim.step(); robot only reads and writes ctrl / qfrc_applied for its joints
109
115
  ```
110
116
 
@@ -41,8 +41,8 @@ from mujoco_robot.utils.robot_loader_utils import get_mjcf_from_awesome_robot_de
41
41
  robot = MujocoRobot(
42
42
  mjcf_path=get_mjcf_from_awesome_robot_descriptions("panda_mj_description"),
43
43
  ee_names=["hand"],
44
- run_async=False, # step manually
45
- render=True, # launch the passive viewer (needs a display)
44
+ run_async=False, # step manually
45
+ render=True, # launch the passive viewer (needs a display)
46
46
  )
47
47
  robot.set_position_control_mode()
48
48
 
@@ -60,9 +60,13 @@ stepped by its host (other actuated joints, other free bodies, the host's own pr
60
60
  scope `MujocoRobot` to the robot's joints:
61
61
 
62
62
  ```python
63
- robot = MujocoRobot(model=sim.model, data=sim.data,
64
- joint_names=[f"arm/{j}" for j in AUBO_JOINTS],
65
- ee_sites=["arm/tcp"], run_async=False)
63
+ robot = MujocoRobot(
64
+ model=sim.model,
65
+ data=sim.data,
66
+ joint_names=[f"arm/{j}" for j in AUBO_JOINTS],
67
+ ee_sites=["arm/tcp"],
68
+ run_async=False,
69
+ )
66
70
  # host steps: sim.step(); robot only reads and writes ctrl / qfrc_applied for its joints
67
71
  ```
68
72
 
@@ -15,7 +15,7 @@ from typing import Sequence
15
15
  import numpy as np
16
16
  import mujoco
17
17
 
18
- from .mujoco_robot import xyzw_to_wxyz
18
+ from .types import xyzw_to_wxyz
19
19
 
20
20
  _FREE = int(mujoco.mjtJoint.mjJNT_FREE)
21
21
  _HINGE = int(mujoco.mjtJoint.mjJNT_HINGE)
@@ -64,7 +64,7 @@ def differential_ik(
64
64
  Solves on a COPY of ``data`` (the live simulation is never mutated) for joint positions that
65
65
  place the named site at ``target_pos`` and, if given, ``target_quat`` (otherwise the target is
66
66
  position-only). Iterates ``dq = Jᵀ (J Jᵀ + damping² I)⁻¹ e`` with a per-step norm clamp, then
67
- integrates and clamps to joint limits.
67
+ integrates and clamps to joint limits. No global MuJoCo callback runs.
68
68
 
69
69
  Args:
70
70
  model (mujoco.MjModel): The model.
@@ -106,7 +106,12 @@ def differential_ik(
106
106
  # Work on a copy so the live sim is untouched.
107
107
  scratch = mujoco.MjData(model)
108
108
  scratch.qpos[:] = data.qpos
109
- mujoco.mj_forward(model, scratch)
109
+ scratch.mocap_pos[:] = data.mocap_pos
110
+ scratch.mocap_quat[:] = data.mocap_quat
111
+ # Only the stages that site poses and mj_jacSite read: mj_forward would run the global
112
+ # callbacks.
113
+ mujoco.mj_kinematics(model, scratch)
114
+ mujoco.mj_comPos(model, scratch)
110
115
 
111
116
  target_pos = np.asarray(target_pos, dtype=float)
112
117
  track_rot = target_quat is not None
@@ -151,7 +156,8 @@ def differential_ik(
151
156
  dq = dq_full
152
157
  mujoco.mj_integratePos(model, scratch.qpos, dq, 1.0)
153
158
  _clamp_to_limits(model, scratch.qpos, joint_ids)
154
- mujoco.mj_forward(model, scratch)
159
+ mujoco.mj_kinematics(model, scratch)
160
+ mujoco.mj_comPos(model, scratch)
155
161
 
156
162
  if joint_ids is not None:
157
163
  return np.array([float(scratch.qpos[int(model.jnt_qposadr[j])]) for j in joint_ids])
@@ -0,0 +1,405 @@
1
+ """Model structure for mujoco_robot: name<->id maps and joint/link/dof bookkeeping."""
2
+
3
+ from typing import Dict, List, Mapping, Optional, Sequence
4
+
5
+ import numpy as np
6
+ import mujoco
7
+
8
+ from .types import Frame, MujocoJointInfo
9
+
10
+ # qpos / dof widths per joint type. free=7/6, ball=4/3, slide=1/1, hinge=1/1.
11
+ _QPOS_DIM: Dict[int, int] = {
12
+ int(mujoco.mjtJoint.mjJNT_FREE): 7,
13
+ int(mujoco.mjtJoint.mjJNT_BALL): 4,
14
+ int(mujoco.mjtJoint.mjJNT_SLIDE): 1,
15
+ int(mujoco.mjtJoint.mjJNT_HINGE): 1,
16
+ }
17
+ _DOF_DIM: Dict[int, int] = {
18
+ int(mujoco.mjtJoint.mjJNT_FREE): 6,
19
+ int(mujoco.mjtJoint.mjJNT_BALL): 3,
20
+ int(mujoco.mjtJoint.mjJNT_SLIDE): 1,
21
+ int(mujoco.mjtJoint.mjJNT_HINGE): 1,
22
+ }
23
+
24
+
25
+ def _id_name_maps(model: mujoco.MjModel, obj_type: int, n: int):
26
+ """Build (names, name->id, id->name) for a MuJoCo element kind. Unnamed elements map to ''."""
27
+ names: List[str] = []
28
+ name_to_id: Dict[str, int] = {}
29
+ id_to_name: Dict[int, str] = {}
30
+ for i in range(n):
31
+ name = mujoco.mj_id2name(model, obj_type, i)
32
+ name = name if name is not None else ""
33
+ names.append(name)
34
+ id_to_name[i] = name
35
+ if name:
36
+ name_to_id[name] = i
37
+ return names, name_to_id, id_to_name
38
+
39
+
40
+ class MujocoObject:
41
+ """Static information about a MuJoCo object: name<->id maps and joint/link/dof bookkeeping.
42
+
43
+ Built from an existing ``MjModel``. No physics is performed here; this only reads the model's
44
+ structure (equivalent role to reading a loaded body's joint/link tables).
45
+
46
+ By default the whole model is the object: every non-free joint is an actuated joint, every
47
+ body is a link, and the root is the first child of the world. Passing ``joint_names`` scopes
48
+ the object to one robot inside a larger world: only those joints are actuated, and the links
49
+ are the subtree under the root body. Everything else in the model is foreign.
50
+ """
51
+
52
+ def __init__(
53
+ self,
54
+ model: mujoco.MjModel,
55
+ joint_names: Optional[Sequence[str]] = None,
56
+ root_body: Optional[str] = None,
57
+ ):
58
+ """Read all addressing/structure information from a compiled model.
59
+
60
+ Args:
61
+ model (mujoco.MjModel): A compiled MuJoCo model.
62
+ joint_names (Sequence[str], optional): Scope the object to exactly these 1-dof (hinge
63
+ or slide) joints, in this order. Defaults to None (the whole model).
64
+ root_body (str, optional): Name of the robot's root body. Base pose and velocity are
65
+ read from it, and the base is floating iff it carries a free joint. Defaults to
66
+ the first child of the world, or, when ``joint_names`` is given, the deepest body
67
+ that is an ancestor of every scoped joint.
68
+ """
69
+ self.model = model
70
+ self.is_scoped: bool = joint_names is not None
71
+ """Whether this object covers only the given ``joint_names`` (not the whole model)."""
72
+
73
+ obj = mujoco.mjtObj
74
+ self.body_names, self.body_name_to_id, self.body_id_to_name = _id_name_maps(
75
+ model, obj.mjOBJ_BODY, model.nbody
76
+ )
77
+ self.joint_names, self.joint_name_to_id, self.joint_id_to_name = _id_name_maps(
78
+ model, obj.mjOBJ_JOINT, model.njnt
79
+ )
80
+ self.actuator_names, self.actuator_name_to_id, self.actuator_id_to_name = _id_name_maps(
81
+ model, obj.mjOBJ_ACTUATOR, model.nu
82
+ )
83
+ self.site_names, self.site_name_to_id, self.site_id_to_name = _id_name_maps(
84
+ model, obj.mjOBJ_SITE, model.nsite
85
+ )
86
+ self.geom_names, self.geom_name_to_id, self.geom_id_to_name = _id_name_maps(
87
+ model, obj.mjOBJ_GEOM, model.ngeom
88
+ )
89
+ self.sensor_names, self.sensor_name_to_id, self.sensor_id_to_name = _id_name_maps(
90
+ model, obj.mjOBJ_SENSOR, model.nsensor
91
+ )
92
+
93
+ scoped_joint_ids = self._resolve_scoped_joints(joint_names) if self.is_scoped else None
94
+
95
+ # Base = root body: the given one, else the common ancestor of the scoped joints, else
96
+ # the first body whose parent is the world.
97
+ if root_body is not None:
98
+ if root_body not in self.body_name_to_id or self.body_name_to_id[root_body] == 0:
99
+ raise ValueError(f"'{root_body}' is not a body that can be a robot root.")
100
+ self.base_id: int = self.body_name_to_id[root_body]
101
+ elif self.is_scoped:
102
+ self.base_id = self._infer_root_body(scoped_joint_ids)
103
+ else:
104
+ self.base_id = next(
105
+ (i for i in range(1, model.nbody) if int(model.body_parentid[i]) == 0), 1
106
+ )
107
+ self.base_name: str = self.body_id_to_name.get(self.base_id, "")
108
+ self.name: str = self.base_name
109
+ """Name of the robot (its base/root link name)."""
110
+
111
+ # Links are bodies, excluding the world body (id 0). Scoped: the subtree under the root.
112
+ if self.is_scoped:
113
+ self.link_ids: List[int] = self._subtree_body_ids(self.base_id)
114
+ else:
115
+ self.link_ids = list(range(1, model.nbody))
116
+ self.link_names: List[str] = [self.body_id_to_name[i] for i in self.link_ids]
117
+ self.link_name_to_id: Dict[str, int] = {
118
+ n: i for n, i in zip(self.link_names, self.link_ids) if n
119
+ }
120
+ self.link_id_to_name: Dict[int, str] = dict(zip(self.link_ids, self.link_names))
121
+
122
+ # Geoms belonging to the robot's links (for transparency / collision toggling).
123
+ link_id_set = set(self.link_ids)
124
+ self.robot_geom_ids: List[int] = [
125
+ g for g in range(model.ngeom) if int(model.geom_bodyid[g]) in link_id_set
126
+ ]
127
+
128
+ # Map each joint-transmission actuator to the joint it drives (matched by transmission
129
+ # target, so actuator names need not match joint names).
130
+ joint_trn = (int(mujoco.mjtTrn.mjTRN_JOINT), int(mujoco.mjtTrn.mjTRN_JOINTINPARENT))
131
+ self.joint_id_to_actuator_id: Dict[int, int] = {}
132
+ joint_actuators: Dict[int, List[int]] = {}
133
+ for a in range(model.nu):
134
+ if int(model.actuator_trntype[a]) in joint_trn:
135
+ jid = int(model.actuator_trnid[a, 0])
136
+ self.joint_id_to_actuator_id[jid] = a
137
+ joint_actuators.setdefault(jid, []).append(a)
138
+ if self.is_scoped:
139
+ self.robot_actuator_ids: List[int] = sorted(
140
+ a for j in scoped_joint_ids for a in joint_actuators.get(j, [])
141
+ )
142
+ """Ids of the actuators driving this robot's actuated joints."""
143
+ self.has_actuators: bool = len(self.robot_actuator_ids) > 0
144
+ else:
145
+ self.robot_actuator_ids = list(range(model.nu))
146
+ self.has_actuators = model.nu > 0
147
+
148
+ # Total mass. Per-body dynamics (mass/inertia/com) are cheap direct lookups on the
149
+ # model's ``body_*`` arrays, so there is no per-link info struct; see get_link_mass.
150
+ self.mass: float = float(sum(model.body_mass[i] for i in self.link_ids))
151
+ """Total mass of this object."""
152
+
153
+ self._build_joint_info(scoped_joint_ids)
154
+
155
+ def _resolve_scoped_joints(self, joint_names: Sequence[str]) -> List[int]:
156
+ """Validate the scoped joint names and return their ids, in the given order."""
157
+ one_dof = (int(mujoco.mjtJoint.mjJNT_HINGE), int(mujoco.mjtJoint.mjJNT_SLIDE))
158
+ joint_names = list(joint_names)
159
+ if not joint_names:
160
+ raise ValueError("joint_names must name at least one joint.")
161
+ if len(set(joint_names)) != len(joint_names):
162
+ raise ValueError(f"joint_names contains duplicates: {joint_names}")
163
+ ids = []
164
+ for name in joint_names:
165
+ if name not in self.joint_name_to_id:
166
+ raise ValueError(f"No joint named '{name}' in the model.")
167
+ jid = self.joint_name_to_id[name]
168
+ if int(self.model.jnt_type[jid]) not in one_dof:
169
+ raise ValueError(f"Joint '{name}' is not a hinge or slide joint.")
170
+ ids.append(jid)
171
+ return ids
172
+
173
+ def _ancestors(self, body_id: int) -> List[int]:
174
+ """The body and its ancestors, nearest first, ending at the world body (id 0)."""
175
+ chain = [body_id]
176
+ while chain[-1] != 0:
177
+ chain.append(int(self.model.body_parentid[chain[-1]]))
178
+ return chain
179
+
180
+ def _common_ancestor(self, body_ids: List[int]) -> int:
181
+ """Deepest body that is an ancestor of (or equal to) every body in ``body_ids``."""
182
+ common = self._ancestors(body_ids[0])
183
+ for b in body_ids[1:]:
184
+ ancestors = set(self._ancestors(b))
185
+ common = [c for c in common if c in ancestors]
186
+ return common[0]
187
+
188
+ def _infer_root_body(self, joint_ids: List[int]) -> int:
189
+ """Root of a scoped robot: the deepest body that the scoped joints all move relative to.
190
+
191
+ That is the common ancestor of the joints' parent bodies (the arm base for a serial
192
+ chain, the hand for a pair of fingers). If that is the world, fall back to the common
193
+ ancestor of the joint bodies themselves.
194
+ """
195
+ joint_bodies = [int(self.model.jnt_bodyid[j]) for j in joint_ids]
196
+ root = self._common_ancestor([int(self.model.body_parentid[b]) for b in joint_bodies])
197
+ if root == 0:
198
+ root = self._common_ancestor(joint_bodies)
199
+ if root == 0:
200
+ raise ValueError(
201
+ "The given joints share no common body other than the world; pass root_body."
202
+ )
203
+ return root
204
+
205
+ def _subtree_body_ids(self, root_id: int) -> List[int]:
206
+ """Ids of ``root_id`` and all of its descendants (MuJoCo orders parents before children)."""
207
+ subtree = {root_id}
208
+ for b in range(root_id + 1, self.model.nbody):
209
+ if int(self.model.body_parentid[b]) in subtree:
210
+ subtree.add(b)
211
+ return sorted(subtree)
212
+
213
+ def _build_joint_info(self, scoped_joint_ids: Optional[List[int]] = None):
214
+ model = self.model
215
+ free_type = int(mujoco.mjtJoint.mjJNT_FREE)
216
+ hinge_type = int(mujoco.mjtJoint.mjJNT_HINGE)
217
+
218
+ self.joint_name_to_info: Mapping[str, MujocoJointInfo] = {}
219
+ # Keyed by id as well, since unnamed joints all share the name "".
220
+ self._joint_info_by_id: Dict[int, MujocoJointInfo] = {}
221
+ self.actuated_joint_names: List[str] = []
222
+ self.actuated_joint_ids: List[int] = []
223
+ self.actuated_joint_lower_limits: List[float] = []
224
+ self.actuated_joint_upper_limits: List[float] = []
225
+ self.actuated_joint_qpos_adrs: List[int] = []
226
+ self.actuated_joint_dof_adrs: List[int] = []
227
+ self.continuous_joint_names: List[str] = []
228
+ self.continuous_joint_ids: List[int] = []
229
+ self.free_joint_id: Optional[int] = None
230
+
231
+ for j in range(model.njnt):
232
+ jtype = int(model.jnt_type[j])
233
+ name = self.joint_id_to_name[j]
234
+ qadr = int(model.jnt_qposadr[j])
235
+ dadr = int(model.jnt_dofadr[j])
236
+ limited = bool(model.jnt_limited[j])
237
+ lower, upper = (float(x) for x in model.jnt_range[j])
238
+ dof_dim = _DOF_DIM[jtype]
239
+
240
+ info = MujocoJointInfo(
241
+ joint_id=j,
242
+ joint_name=name,
243
+ joint_type=jtype,
244
+ qpos_adr=qadr,
245
+ qpos_dim=_QPOS_DIM[jtype],
246
+ dof_adr=dadr,
247
+ dof_dim=dof_dim,
248
+ body_id=int(model.jnt_bodyid[j]),
249
+ body_name=self.body_id_to_name[int(model.jnt_bodyid[j])],
250
+ lower_limit=lower,
251
+ upper_limit=upper,
252
+ limited=limited,
253
+ axis=np.array(model.jnt_axis[j]),
254
+ damping=float(model.dof_damping[dadr]) if dof_dim == 1 else float("nan"),
255
+ actuator_id=self.joint_id_to_actuator_id.get(j),
256
+ )
257
+ self.joint_name_to_info[name] = info
258
+ self._joint_info_by_id[j] = info
259
+
260
+ # A free joint on the root body is the floating base. Free joints elsewhere belong to
261
+ # other bodies in the world. Neither is an actuated joint.
262
+ if jtype == free_type:
263
+ if int(model.jnt_bodyid[j]) == self.base_id:
264
+ self.free_joint_id = j
265
+ continue
266
+
267
+ if scoped_joint_ids is None:
268
+ scoped_joint_ids = [j for j in range(model.njnt) if int(model.jnt_type[j]) != free_type]
269
+ else:
270
+ subtree = set(self.link_ids)
271
+ outside = [
272
+ self.joint_id_to_name[j]
273
+ for j in scoped_joint_ids
274
+ if int(model.jnt_bodyid[j]) not in subtree
275
+ ]
276
+ if outside:
277
+ raise ValueError(f"Joints {outside} are not under root body '{self.base_name}'.")
278
+
279
+ for j in scoped_joint_ids:
280
+ info = self._joint_info_by_id[j]
281
+ self.actuated_joint_ids.append(j)
282
+ self.actuated_joint_names.append(info.joint_name)
283
+ self.actuated_joint_lower_limits.append(info.lower_limit)
284
+ self.actuated_joint_upper_limits.append(info.upper_limit)
285
+ self.actuated_joint_qpos_adrs.append(info.qpos_adr)
286
+ self.actuated_joint_dof_adrs.append(info.dof_adr)
287
+
288
+ # A revolute joint with no limits is a continuous joint.
289
+ if info.joint_type == hinge_type and not info.limited:
290
+ self.continuous_joint_names.append(info.joint_name)
291
+ self.continuous_joint_ids.append(j)
292
+
293
+ self.num_actuated_joints: int = len(self.actuated_joint_ids)
294
+ self.has_floating_base: bool = self.free_joint_id is not None
295
+ self.has_continuous_joints: bool = len(self.continuous_joint_ids) > 0
296
+
297
+ # --- convenience loaders ------------------------------------------------
298
+
299
+ @classmethod
300
+ def from_mjcf_path(cls, mjcf_path: str) -> "MujocoObject":
301
+ """Compile a model from an MJCF (or URDF) file and read its structure.
302
+
303
+ Args:
304
+ mjcf_path (str): Path to an MJCF/URDF file.
305
+
306
+ Returns:
307
+ MujocoObject: Structure information for the compiled model.
308
+ """
309
+ return cls(mujoco.MjModel.from_xml_path(mjcf_path))
310
+
311
+ # --- name <-> id accessors ---------------------------------------------
312
+
313
+ def get_joint_id(self, joint_name: str) -> int:
314
+ """Get the id of the specified joint."""
315
+ return self.joint_name_to_id[joint_name]
316
+
317
+ def get_joint_name(self, joint_id: int) -> str:
318
+ """Get the name of the joint with the given id."""
319
+ return self.joint_id_to_name[joint_id]
320
+
321
+ def get_joint_ids(self, joint_names: List[str]) -> List[int]:
322
+ """Get the ids of the specified joints, in the given order."""
323
+ return [self.joint_name_to_id[name] for name in joint_names]
324
+
325
+ def get_link_id(self, link_name: str) -> int:
326
+ """Get the body id of the specified link."""
327
+ return self.link_name_to_id[link_name]
328
+
329
+ def get_link_name(self, link_id: int) -> str:
330
+ """Get the name of the link (body) with the given id."""
331
+ return self.link_id_to_name[link_id]
332
+
333
+ def get_link_mass(self, link_name: int | str) -> float:
334
+ """Get the mass of the specified link (body), given by name or id."""
335
+ return float(self.model.body_mass[self._resolve_link_id(link_name)])
336
+
337
+ def get_actuator_id(self, actuator_name: str) -> int:
338
+ """Get the id of the specified actuator."""
339
+ return self.actuator_name_to_id[actuator_name]
340
+
341
+ def get_site_id(self, site_name: str) -> int:
342
+ """Get the id of the specified site."""
343
+ return self.site_name_to_id[site_name]
344
+
345
+ # --- name-or-id resolution ----------------------------------------------
346
+ #
347
+ # Methods bound to one kind of element take a name or that kind's id. Numpy integers count as
348
+ # ids (ids read from model arrays are numpy types). Unknown names and invalid ids raise
349
+ # KeyError. Links resolve only to this object's own links, by name or by id. Names are looked
350
+ # up in the name->id maps, which leave out unnamed elements, so "" never resolves.
351
+
352
+ @staticmethod
353
+ def _is_id(x) -> bool:
354
+ return isinstance(x, (int, np.integer)) and not isinstance(x, bool)
355
+
356
+ @staticmethod
357
+ def _checked_id(x, n: int, kind: str) -> int:
358
+ i = int(x)
359
+ if not 0 <= i < n:
360
+ raise KeyError(f"No {kind} with id {i}.")
361
+ return i
362
+
363
+ def _resolve_link_id(self, link: int | str) -> int:
364
+ if not self._is_id(link):
365
+ return self.link_name_to_id[link]
366
+ if int(link) not in self.link_id_to_name:
367
+ raise KeyError(f"Body id {int(link)} is not a link of this robot.")
368
+ return int(link)
369
+
370
+ def _resolve_site_id(self, site: int | str) -> int:
371
+ if self._is_id(site):
372
+ return self._checked_id(site, self.model.nsite, "site")
373
+ return self.site_name_to_id[site]
374
+
375
+ def _resolve_geom_id(self, geom: int | str) -> int:
376
+ if self._is_id(geom):
377
+ return self._checked_id(geom, self.model.ngeom, "geom")
378
+ return self.geom_name_to_id[geom]
379
+
380
+ def _joint_info(self, joint: int | str) -> MujocoJointInfo:
381
+ if self._is_id(joint):
382
+ return self._joint_info_by_id[int(joint)]
383
+ return self._joint_info_by_id[self.joint_name_to_id[joint]]
384
+
385
+ def _resolve_joint_ids(self, joints) -> List[int]:
386
+ return [self._joint_info(j).joint_id for j in joints]
387
+
388
+ def frame(self, name: str) -> Frame:
389
+ """Resolve a link or site name to a typed :class:`Frame` handle.
390
+
391
+ Use it to cache a frame for methods that accept any frame (e.g. ``get_jacobian``), such as
392
+ a tool frame that is a body in one description and a site in another. A link name takes
393
+ precedence over a site with the same name.
394
+
395
+ Args:
396
+ name (str): Link (body) or site name.
397
+
398
+ Returns:
399
+ Frame: The resolved frame.
400
+ """
401
+ if name in self.link_name_to_id:
402
+ return Frame("link", self.link_name_to_id[name], name)
403
+ if name in self.site_name_to_id:
404
+ return Frame("site", self.site_name_to_id[name], name)
405
+ raise KeyError(f"No link or site named '{name}'.")