rotoki 0.2.0__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.
rotoki/loader.py ADDED
@@ -0,0 +1,81 @@
1
+ """Load robots as MuJoCo models for simulation or as URDFs for viewing."""
2
+
3
+ from importlib import import_module
4
+ from typing import Literal
5
+
6
+ import mujoco
7
+ import mujoco_menagerie as mm
8
+ import yourdfpy
9
+ from robot_descriptions import DESCRIPTIONS
10
+ from robot_descriptions.loaders import mujoco as rd_mujoco
11
+ from robot_descriptions.loaders import yourdfpy as rd_yourdfpy
12
+
13
+ RobotSource = Literal["menagerie", "robot_descriptions"]
14
+
15
+
16
+ def get_mjcf_names(source: RobotSource = "menagerie") -> list[str]:
17
+ """List robots that load_mjcf can load from a source."""
18
+ if source == "menagerie":
19
+ return mm.names()
20
+ if source == "robot_descriptions":
21
+ return sorted(name for name, d in DESCRIPTIONS.items() if d.has_mjcf)
22
+ raise ValueError(f"Unknown robot source: {source}")
23
+
24
+
25
+ def get_urdf_names() -> list[str]:
26
+ """List robot_descriptions robots that load_urdf can load."""
27
+ return sorted(name for name, d in DESCRIPTIONS.items() if d.has_urdf)
28
+
29
+
30
+ def load_mjcf(
31
+ robot_name: str | None = None,
32
+ xml_path: str | None = None,
33
+ source: RobotSource = "menagerie",
34
+ ) -> tuple[mujoco.MjModel, mujoco.MjData]:
35
+ """Load a MuJoCo robot by name from a source or an MJCF file."""
36
+ if (robot_name is None) == (xml_path is None):
37
+ raise ValueError("Provide exactly one of robot_name or xml_path")
38
+ if robot_name is None:
39
+ model = mujoco.MjModel.from_xml_path(str(xml_path))
40
+ elif source == "menagerie":
41
+ model = mm.load(robot_name)
42
+ elif source == "robot_descriptions":
43
+ model = rd_mujoco.load_robot_description(robot_name)
44
+ else:
45
+ raise ValueError(f"Unknown robot source: {source}")
46
+ data = mujoco.MjData(model)
47
+ if model.nkey > 0:
48
+ mujoco.mj_resetDataKeyframe(model, data, 0)
49
+ return model, data
50
+
51
+
52
+ def load_mjcf_spec(
53
+ robot_name: str | None = None,
54
+ xml_path: str | None = None,
55
+ source: RobotSource = "menagerie",
56
+ ) -> mujoco.MjSpec:
57
+ """Load an editable MuJoCo robot without its scene, by name from a source or from an MJCF file, for add_sim_robot."""
58
+ if (robot_name is None) == (xml_path is None):
59
+ raise ValueError("Provide exactly one of robot_name or xml_path")
60
+ if robot_name is None:
61
+ return mujoco.MjSpec.from_file(str(xml_path))
62
+ if source == "menagerie":
63
+ robot = mm.get(robot_name)
64
+ return robot.spec(robot.default_model)
65
+ if source == "robot_descriptions":
66
+ module = import_module(f"robot_descriptions.{robot_name}")
67
+ if not hasattr(module, "MJCF_PATH"):
68
+ raise ValueError(f"{robot_name} is not an MJCF description")
69
+ return mujoco.MjSpec.from_file(module.MJCF_PATH)
70
+ raise ValueError(f"Unknown robot source: {source}")
71
+
72
+
73
+ def load_urdf(
74
+ robot_name: str | None = None, urdf_path: str | None = None
75
+ ) -> yourdfpy.URDF:
76
+ """Load a URDF robot by name from robot_descriptions or a URDF file."""
77
+ if (robot_name is None) == (urdf_path is None):
78
+ raise ValueError("Provide exactly one of robot_name or urdf_path")
79
+ if robot_name is None:
80
+ return yourdfpy.URDF.load(str(urdf_path))
81
+ return rd_yourdfpy.load_robot_description(robot_name)
rotoki/message.py ADDED
@@ -0,0 +1,176 @@
1
+ """Common robotics message definitions and functions."""
2
+
3
+ from datetime import datetime
4
+ from typing import Self
5
+
6
+ import msgspec
7
+ import numpy as np
8
+ import zenoh
9
+
10
+
11
+ class Message(msgspec.Struct):
12
+ """Base class for all messages."""
13
+
14
+ def encode(self) -> bytes:
15
+ return msgspec.msgpack.encode(self)
16
+
17
+ @classmethod
18
+ def decode(cls, sample: zenoh.Sample) -> Self:
19
+ return msgspec.msgpack.decode(
20
+ sample.payload.to_bytes(),
21
+ type=cls,
22
+ )
23
+
24
+ @classmethod
25
+ def timestamp(cls, sample: zenoh.Sample) -> datetime | None:
26
+ if sample.timestamp is None:
27
+ return None
28
+ return sample.timestamp.get_time()
29
+
30
+ @classmethod
31
+ def channel(cls, sample: zenoh.Sample) -> zenoh.KeyExpr:
32
+ return sample.key_expr
33
+
34
+
35
+ class Position(Message):
36
+ x: float
37
+ y: float
38
+ z: float
39
+
40
+
41
+ class Orientation(Message):
42
+ """A quaternion orientation."""
43
+
44
+ w: float
45
+ x: float
46
+ y: float
47
+ z: float
48
+
49
+ @classmethod
50
+ def from_rpy(cls, roll: float, pitch: float, yaw: float) -> Self:
51
+ """Create an orientation from roll, pitch, and yaw in radians, applied about fixed x, y, then z axes as in URDF."""
52
+ cr, sr = np.cos(roll / 2), np.sin(roll / 2)
53
+ cp, sp = np.cos(pitch / 2), np.sin(pitch / 2)
54
+ cy, sy = np.cos(yaw / 2), np.sin(yaw / 2)
55
+ return cls(
56
+ float(cr * cp * cy + sr * sp * sy),
57
+ float(sr * cp * cy - cr * sp * sy),
58
+ float(cr * sp * cy + sr * cp * sy),
59
+ float(cr * cp * sy - sr * sp * cy),
60
+ )
61
+
62
+ def to_array(self) -> np.ndarray:
63
+ """Return the quaternion as a wxyz array."""
64
+ return np.array([self.w, self.x, self.y, self.z])
65
+
66
+
67
+ class Pose(Message):
68
+ position: Position
69
+ orientation: Orientation | None = None
70
+
71
+ @classmethod
72
+ def from_xyz(cls, x: float, y: float, z: float) -> Self:
73
+ """Create a pose from an xyz position."""
74
+ return cls(Position(x, y, z))
75
+
76
+
77
+ class Path(Message):
78
+ poses: list[Pose]
79
+
80
+
81
+ class JointState(Message):
82
+ positions: list[float]
83
+ velocities: list[float] | None = None
84
+ efforts: list[float] | None = None
85
+ names: list[str] | None = None
86
+
87
+
88
+ class Trajectory(Message):
89
+ """Joint states, the time in seconds to reach each one, and the names of the joints they position."""
90
+
91
+ states: list[JointState]
92
+ times: list[float]
93
+ joint_names: list[str] | None = None
94
+
95
+
96
+ class Velocity(Message):
97
+ x: float
98
+ y: float
99
+ z: float
100
+
101
+
102
+ class Twist(Message):
103
+ linear: Velocity
104
+ angular: Velocity
105
+
106
+
107
+ class Effort(Message):
108
+ """A force or torque."""
109
+
110
+ x: float
111
+ y: float
112
+ z: float
113
+
114
+
115
+ class Wrench(Message):
116
+ force: Effort
117
+ torque: Effort
118
+
119
+
120
+ IMAGE_ENCODINGS: dict[str, tuple[type[np.generic], int]] = {
121
+ "mono8": (np.uint8, 1),
122
+ "mono16": (np.uint16, 1),
123
+ "rgb8": (np.uint8, 3),
124
+ "bgr8": (np.uint8, 3),
125
+ "rgba8": (np.uint8, 4),
126
+ "bgra8": (np.uint8, 4),
127
+ }
128
+
129
+
130
+ class Image(Message):
131
+ width: int
132
+ height: int
133
+ encoding: str
134
+ data: bytes
135
+
136
+ @classmethod
137
+ def from_array(cls, pixels: np.ndarray, encoding: str = "rgb8") -> Self:
138
+ """Create an image from a (height, width) or (height, width, channels) array."""
139
+ dtype, channels = IMAGE_ENCODINGS[encoding]
140
+ shape = pixels.shape[:2] if channels == 1 else (*pixels.shape[:2], channels)
141
+ if pixels.shape != shape:
142
+ raise ValueError(f"{encoding} expects shape {shape}, got {pixels.shape}")
143
+ height, width = shape[:2]
144
+ return cls(width, height, encoding, pixels.astype(dtype, copy=False).tobytes())
145
+
146
+ def to_array(self) -> np.ndarray:
147
+ """Return the pixels as a read-only (height, width) or (height, width, channels) array."""
148
+ dtype, channels = IMAGE_ENCODINGS[self.encoding]
149
+ shape = (
150
+ (self.height, self.width)
151
+ if channels == 1
152
+ else (self.height, self.width, channels)
153
+ )
154
+ return np.frombuffer(self.data, dtype).reshape(shape)
155
+
156
+
157
+ class PointCloud(Message):
158
+ fields: list[str]
159
+ count: int
160
+ data: bytes
161
+
162
+ @classmethod
163
+ def from_array(cls, points: np.ndarray, fields: list[str] | None = None) -> Self:
164
+ """Create a point cloud from a (count, len(fields)) array, with fields defaulting to x, y, z."""
165
+ fields = fields if fields is not None else ["x", "y", "z"]
166
+ if points.ndim != 2 or points.shape[1] != len(fields):
167
+ raise ValueError(
168
+ f"{fields} expects shape (count, {len(fields)}), got {points.shape}"
169
+ )
170
+ return cls(fields, len(points), points.astype(np.float32, copy=False).tobytes())
171
+
172
+ def to_array(self) -> np.ndarray:
173
+ """Return the points as a read-only (count, len(fields)) float32 array."""
174
+ return np.frombuffer(self.data, np.float32).reshape(
175
+ self.count, len(self.fields)
176
+ )
rotoki/navigation.py ADDED
@@ -0,0 +1,412 @@
1
+ """Navigation for wheeled mobile bases using OMPL for collision-free routes in the plane."""
2
+
3
+ import copy
4
+ from dataclasses import dataclass, field
5
+ from typing import Literal, cast
6
+
7
+ import mujoco
8
+ import numpy as np
9
+ import numpy.typing as npt
10
+ from ompl import base as ob
11
+ from ompl import geometric as og
12
+ from ompl import util as ou
13
+
14
+ from .message import Orientation, Pose, Trajectory
15
+ from .planning import PlanningError, sample_path, time_path
16
+
17
+
18
+ @dataclass
19
+ class WheeledBase:
20
+ """A mobile base found by get_wheeled_base, and how to read and drive its pose of x, y, and yaw."""
21
+
22
+ kind: Literal["planar", "differential"]
23
+ body_id: int
24
+ robot_body_ids: set[int]
25
+ joint_ids: list[int]
26
+ qpos_ids: npt.NDArray[np.intp]
27
+ actuator_ids: npt.NDArray[np.intp]
28
+ start_qpos: npt.NDArray[np.float64]
29
+ start_pose: npt.NDArray[np.float64]
30
+ center: npt.NDArray[np.float64] = field(default_factory=lambda: np.zeros(3))
31
+ axes: npt.NDArray[np.float64] = field(default_factory=lambda: np.eye(2))
32
+ wheel_offsets: npt.NDArray[np.float64] = field(default_factory=lambda: np.zeros(0))
33
+ wheel_scales: npt.NDArray[np.float64] = field(default_factory=lambda: np.zeros(0))
34
+ max_speed: float = np.inf
35
+
36
+
37
+ def get_wheeled_base(
38
+ model: mujoco.MjModel, data: mujoco.MjData, robot: str | None = None
39
+ ) -> WheeledBase:
40
+ """Find a robot's wheeled base, named robot/... by add_sim_robot, or the only one, in its current pose."""
41
+ joints = [
42
+ j
43
+ for j in range(model.njnt)
44
+ if robot is None or model.body(model.jnt_bodyid[j]).name.startswith(f"{robot}/")
45
+ ]
46
+ free = [j for j in joints if model.jnt_type[j] == mujoco.mjtJoint.mjJNT_FREE]
47
+ if free:
48
+ return _differential_base(model, data, joints, free[0])
49
+ return _planar_base(model, data, joints)
50
+
51
+
52
+ def get_base_pose(base: WheeledBase, data: mujoco.MjData) -> npt.NDArray[np.float64]:
53
+ """Return the base's x, y, and yaw in the world at its center."""
54
+ rotation = data.xmat[base.body_id].reshape(3, 3)
55
+ center = data.xpos[base.body_id] + rotation @ base.center
56
+ return np.array([center[0], center[1], np.arctan2(rotation[1, 0], rotation[0, 0])])
57
+
58
+
59
+ def set_base_pose(base: WheeledBase, data: mujoco.MjData, pose: npt.ArrayLike) -> None:
60
+ """Write the joint positions that put the base's center at x, y, and yaw in the world."""
61
+ x, y, yaw = np.asarray(pose, dtype=np.float64)
62
+ turn = yaw - base.start_pose[2]
63
+ if base.kind == "planar":
64
+ offset = np.array([x, y]) - base.start_pose[:2]
65
+ data.qpos[base.qpos_ids] = base.start_qpos + [*(base.axes @ offset), turn]
66
+ return
67
+ start_quat = base.start_qpos[3:]
68
+ quat = np.zeros(4)
69
+ mujoco.mju_mulQuat(quat, Orientation.from_rpy(0, 0, turn).to_array(), start_quat)
70
+ rotation = np.zeros(9)
71
+ mujoco.mju_quat2Mat(rotation, quat)
72
+ center = rotation.reshape(3, 3) @ base.center
73
+ position = [x - center[0], y - center[1], base.start_qpos[2]]
74
+ data.qpos[base.qpos_ids] = [*position, *quat]
75
+
76
+
77
+ def is_base_collision_free(
78
+ model: mujoco.MjModel,
79
+ data: mujoco.MjData,
80
+ base: WheeledBase,
81
+ pose: npt.ArrayLike,
82
+ clearance: float = 0.0,
83
+ ) -> bool:
84
+ """Return whether the base at a pose is at least clearance meters from everything but the floor and itself.
85
+
86
+ Near misses are only found within the geoms' margins, which plan_route raises to its clearance.
87
+ """
88
+ set_base_pose(base, data, pose)
89
+ mujoco.mj_kinematics(model, data)
90
+ mujoco.mj_collision(model, data)
91
+ geoms = data.contact.geom[: data.ncon]
92
+ touching = data.contact.dist[: data.ncon] > clearance - 1e-4
93
+ floor = np.any(model.geom_type[geoms] == mujoco.mjtGeom.mjGEOM_PLANE, axis=1)
94
+ on_robot = np.isin(model.geom_bodyid[geoms], list(base.robot_body_ids))
95
+ # Only contacts between the robot and something else, ignoring itself and other robots' own contacts
96
+ between = on_robot.sum(axis=1) == 1
97
+ return bool(np.all(touching | floor | ~between))
98
+
99
+
100
+ def plan_route(
101
+ model: mujoco.MjModel,
102
+ data: mujoco.MjData,
103
+ base: WheeledBase,
104
+ goal_pose: Pose,
105
+ max_velocity: float = 0.5,
106
+ max_angular_velocity: float = 1.0,
107
+ timeout: float = 1.0,
108
+ seed: int | None = None,
109
+ clearance: float = 0.05,
110
+ search_margin: float = 2.0,
111
+ ) -> Trajectory:
112
+ """Plan a collision-free route for the base from its current pose to a goal, as a trajectory of x, y, and yaw."""
113
+ # A copy whose geoms report contacts within the clearance
114
+ planning_model = copy.copy(model)
115
+ planning_model.geom_margin[:] = np.maximum(planning_model.geom_margin, clearance)
116
+ scratch = mujoco.MjData(planning_model)
117
+ scratch.qpos[:] = data.qpos
118
+ start = get_base_pose(base, data)
119
+ goal = np.array([goal_pose.position.x, goal_pose.position.y, start[2]])
120
+ differential = base.kind == "differential"
121
+ if differential:
122
+ # Leave headroom below the wheels' top speed for correcting errors
123
+ max_velocity = min(max_velocity, 0.8 * base.max_speed)
124
+ max_angular_velocity = min(
125
+ max_angular_velocity,
126
+ 0.8 * base.max_speed / np.abs(base.wheel_offsets).max(),
127
+ )
128
+ if goal_pose.orientation is not None:
129
+ goal[2] = _yaw(goal_pose.orientation)
130
+ elif differential:
131
+ goal[2] = np.arctan2(goal[1] - start[1], goal[0] - start[0])
132
+
133
+ for name, pose in (("start", start), ("goal", goal)):
134
+ if not is_base_collision_free(planning_model, scratch, base, pose, clearance):
135
+ raise PlanningError(
136
+ f"The base's {name} is in collision or within {clearance} m of an obstacle"
137
+ )
138
+
139
+ if seed is not None:
140
+ log_level = ou.getLogLevel()
141
+ ou.setLogLevel(ou.LogLevel.LOG_NONE)
142
+ ou.RNG.setSeed(seed)
143
+ ou.setLogLevel(log_level)
144
+
145
+ space = ob.ReedsSheppStateSpace(0.05) if differential else ob.SE2StateSpace()
146
+ bounds = ob.RealVectorBounds(2)
147
+ bounds.low = (np.minimum(start[:2], goal[:2]) - search_margin).tolist()
148
+ bounds.high = (np.maximum(start[:2], goal[:2]) + search_margin).tolist()
149
+ space.setBounds(bounds)
150
+
151
+ def to_pose(state: ob.State) -> list[float]:
152
+ state = cast(ob.SE2StateType, state)
153
+ return [state.getX(), state.getY(), state.getYaw()]
154
+
155
+ def is_valid(state: ob.State) -> bool:
156
+ return is_base_collision_free(
157
+ planning_model, scratch, base, to_pose(state), clearance
158
+ )
159
+
160
+ setup = og.SimpleSetup(space)
161
+ setup.setStateValidityChecker(is_valid)
162
+ start_state = cast(ob.SE2StateType, space.allocState())
163
+ start_state.setXY(start[0], start[1])
164
+ start_state.setYaw(start[2])
165
+ goal_state = cast(ob.SE2StateType, space.allocState())
166
+ goal_state.setXY(goal[0], goal[1])
167
+ goal_state.setYaw(goal[2])
168
+ setup.setStartAndGoalStates(start_state, goal_state)
169
+ setup.getSpaceInformation().setStateValidityCheckingResolution(0.002)
170
+ setup.setPlanner(og.RRTConnect(setup.getSpaceInformation()))
171
+
172
+ for _ in range(5):
173
+ setup.clear()
174
+ setup.solve(timeout)
175
+ if not setup.haveExactSolutionPath():
176
+ continue
177
+ setup.simplifySolution()
178
+ path = np.array([to_pose(s) for s in setup.getSolutionPath().getStates()])
179
+ if differential:
180
+ path = _turn_and_drive(path, keep_yaw=goal_pose.orientation is not None)
181
+ path[:, 2] = start[2] + np.cumsum(_wrap(np.diff(path[:, 2], prepend=start[2])))
182
+ if _is_path_collision_free(planning_model, scratch, base, path, clearance):
183
+ limits = [max_velocity, max_velocity, max_angular_velocity]
184
+ return time_path(path, limits, np.multiply(limits, 2), data.time)
185
+ raise PlanningError(f"No route found within {timeout} seconds")
186
+
187
+
188
+ def drive_route(base: WheeledBase, data: mujoco.MjData, route: Trajectory) -> None:
189
+ """Write the base's actuator controls to follow a route from plan_route at the current time."""
190
+ reference = sample_path(route, data.time)
191
+ if base.kind == "planar":
192
+ offset = reference[:2] - base.start_pose[:2]
193
+ turn = reference[2] - base.start_pose[2]
194
+ data.ctrl[base.actuator_ids] = base.start_qpos + [*(base.axes @ offset), turn]
195
+ return
196
+
197
+ step = 0.05
198
+ ahead = sample_path(route, data.time + step)
199
+ x, y, yaw = get_base_pose(base, data)
200
+ forward = np.array([np.cos(yaw), np.sin(yaw)])
201
+ left = np.array([-forward[1], forward[0]])
202
+ error = reference[:2] - [x, y]
203
+ error_x, error_y = error @ forward, error @ left
204
+ error_yaw = _wrap(reference[2] - yaw)
205
+ reference_heading = np.array([np.cos(reference[2]), np.sin(reference[2])])
206
+ reference_velocity = (ahead[:2] - reference[:2]) @ reference_heading / step
207
+ reference_turn = (ahead[2] - reference[2]) / step
208
+ velocity = reference_velocity * np.cos(error_yaw) + 2.0 * error_x
209
+ turn = reference_turn + reference_velocity * 8.0 * error_y + 4.0 * np.sin(error_yaw)
210
+ wheel_speeds = velocity - turn * base.wheel_offsets
211
+ data.ctrl[base.actuator_ids] = wheel_speeds / base.wheel_scales
212
+
213
+
214
+ def get_route_path(route: Trajectory, height: float = 0.02) -> npt.NDArray[np.float64]:
215
+ """Returns the world positions the base's center passes through along a route from plan_route, at a height."""
216
+ path = np.array([state.positions for state in route.states])
217
+ return np.column_stack([path[:, :2], np.full(len(path), height)])
218
+
219
+
220
+ def _differential_base(
221
+ model: mujoco.MjModel, data: mujoco.MjData, joints: list[int], free: int
222
+ ) -> WheeledBase:
223
+ body = int(model.jnt_bodyid[free])
224
+ rotation = data.xmat[body].reshape(3, 3)
225
+ wheels, actuators, positions, scales = [], [], [], []
226
+ for actuator in range(model.nu):
227
+ joint = int(model.actuator_trnid[actuator, 0])
228
+ if (
229
+ model.actuator_trntype[actuator] != mujoco.mjtTrn.mjTRN_JOINT
230
+ or joint not in joints
231
+ or model.jnt_type[joint] != mujoco.mjtJoint.mjJNT_HINGE
232
+ or not _is_velocity_actuator(model, actuator)
233
+ ):
234
+ continue
235
+ axis = rotation.T @ data.xaxis[joint]
236
+ if abs(axis[1]) < 0.9: # Not a wheel along the side
237
+ continue
238
+ wheel_body = int(model.jnt_bodyid[joint])
239
+ radius = _wheel_radius(model, wheel_body)
240
+ gear = model.actuator_gear[actuator, 0]
241
+ wheels.append(joint)
242
+ actuators.append(actuator)
243
+ positions.append(rotation.T @ (data.xpos[wheel_body] - data.xpos[body]))
244
+ # A wheel spinning about axis rolls its center along axis × up
245
+ scales.append(radius * np.cross(axis, [0, 0, 1])[0] / gear)
246
+ positions = np.array(positions).reshape(-1, 3)
247
+ if not (np.any(positions[:, 1] > 0) and np.any(positions[:, 1] < 0)):
248
+ raise ValueError(
249
+ "No wheeled base found: a free-floating base needs velocity actuators on wheels on both sides"
250
+ )
251
+ center = positions.mean(axis=0)
252
+ center[2] = 0.0
253
+ adr = model.jnt_qposadr[free]
254
+ base = WheeledBase(
255
+ kind="differential",
256
+ body_id=body,
257
+ robot_body_ids=_subtree(model, body),
258
+ joint_ids=[free, *wheels],
259
+ qpos_ids=np.arange(adr, adr + 7),
260
+ actuator_ids=np.array(actuators, dtype=np.intp),
261
+ start_qpos=data.qpos[adr : adr + 7].copy(),
262
+ start_pose=np.zeros(3),
263
+ center=center,
264
+ wheel_offsets=positions[:, 1] - center[1],
265
+ wheel_scales=np.array(scales),
266
+ )
267
+ limited = model.actuator_ctrllimited[base.actuator_ids].astype(bool)
268
+ top_controls = np.abs(model.actuator_ctrlrange[base.actuator_ids]).min(axis=1)
269
+ speeds = np.where(limited, top_controls * np.abs(base.wheel_scales), np.inf)
270
+ base.max_speed = float(speeds.min())
271
+ base.start_pose = get_base_pose(base, data)
272
+ return base
273
+
274
+
275
+ def _planar_base(
276
+ model: mujoco.MjModel, data: mujoco.MjData, joints: list[int]
277
+ ) -> WheeledBase:
278
+ def find(joint_type: mujoco.mjtJoint, axis: int) -> int | None:
279
+ for joint in joints:
280
+ if (
281
+ model.jnt_type[joint] == joint_type
282
+ and abs(data.xaxis[joint][axis]) > 0.99
283
+ ):
284
+ return joint
285
+ return None
286
+
287
+ planar = [
288
+ find(mujoco.mjtJoint.mjJNT_SLIDE, 0),
289
+ find(mujoco.mjtJoint.mjJNT_SLIDE, 1),
290
+ find(mujoco.mjtJoint.mjJNT_HINGE, 2),
291
+ ]
292
+ actuators = [
293
+ next(
294
+ (
295
+ a
296
+ for a in range(model.nu)
297
+ if model.actuator_trntype[a] == mujoco.mjtTrn.mjTRN_JOINT
298
+ and model.actuator_trnid[a, 0] == joint
299
+ and model.actuator_biasprm[a, 1] < 0 # Position actuator
300
+ ),
301
+ None,
302
+ )
303
+ for joint in planar
304
+ ]
305
+ if None in planar or None in actuators:
306
+ raise ValueError(
307
+ "No wheeled base found: needs a free joint with wheels, or x, y, and yaw joints with position actuators"
308
+ )
309
+ planar_joints = cast(list[int], planar)
310
+ body = int(model.jnt_bodyid[planar_joints[2]])
311
+ qpos_ids = model.jnt_qposadr[planar_joints]
312
+ yaw_sign = np.sign(data.xaxis[planar_joints[2]][2])
313
+ base = WheeledBase(
314
+ kind="planar",
315
+ body_id=body,
316
+ robot_body_ids=_subtree(model, int(model.jnt_bodyid[planar_joints[0]])),
317
+ joint_ids=planar_joints,
318
+ qpos_ids=qpos_ids,
319
+ actuator_ids=np.array(actuators, dtype=np.intp),
320
+ start_qpos=data.qpos[qpos_ids].copy(),
321
+ start_pose=np.zeros(3),
322
+ center=data.xmat[body].reshape(3, 3).T
323
+ @ (data.xanchor[planar_joints[2]] - data.xpos[body]),
324
+ axes=np.array([data.xaxis[j][:2] for j in planar_joints[:2]]),
325
+ )
326
+ base.start_pose = get_base_pose(base, data)
327
+ if yaw_sign < 0:
328
+ raise ValueError("The base's yaw joint must turn counterclockwise")
329
+ return base
330
+
331
+
332
+ def _is_velocity_actuator(model: mujoco.MjModel, actuator: int) -> bool:
333
+ """An actuator whose control is a target velocity: force = kv * (control - velocity)."""
334
+ gain, bias = model.actuator_gainprm[actuator], model.actuator_biasprm[actuator]
335
+ return bool(gain[0] > 0 and bias[0] == 0 and bias[1] == 0 and bias[2] == -gain[0])
336
+
337
+
338
+ def _wheel_radius(model: mujoco.MjModel, body: int) -> float:
339
+ """The largest half extent of the wheel's colliding geoms."""
340
+ geoms = [
341
+ g
342
+ for g in range(model.ngeom)
343
+ if model.geom_bodyid[g] == body
344
+ and (model.geom_contype[g] or model.geom_conaffinity[g])
345
+ ]
346
+ if not geoms:
347
+ raise ValueError(f"Wheel {model.body(body).name} has no colliding geoms")
348
+ return float(max(model.geom_aabb[g, 3:].max() for g in geoms))
349
+
350
+
351
+ def _subtree(model: mujoco.MjModel, root: int) -> set[int]:
352
+ bodies = {root}
353
+ for body in range(root + 1, model.nbody):
354
+ if model.body_parentid[body] in bodies:
355
+ bodies.add(body)
356
+ return bodies
357
+
358
+
359
+ def _turn_and_drive(
360
+ path: npt.NDArray[np.float64], keep_yaw: bool
361
+ ) -> npt.NDArray[np.float64]:
362
+ """Replace each step of a path with turning in place to face it, forward or in reverse, then driving straight."""
363
+ poses = [path[0]]
364
+ for end in path[1:]:
365
+ x, y, yaw = poses[-1]
366
+ dx, dy = end[0] - x, end[1] - y
367
+ if np.hypot(dx, dy) > 1e-6:
368
+ heading = np.arctan2(dy, dx)
369
+ if abs(_wrap(heading - yaw)) > np.pi / 2:
370
+ heading += np.pi # Reverse
371
+ poses.append(np.array([x, y, heading]))
372
+ poses.append(np.array([end[0], end[1], heading]))
373
+ if keep_yaw:
374
+ poses.append(np.array([path[-1][0], path[-1][1], path[-1][2]]))
375
+ unique = [poses[0]]
376
+ for pose in poses[1:]:
377
+ if np.any(np.abs(pose - unique[-1]) > 1e-9):
378
+ unique.append(pose)
379
+ return np.array(unique)
380
+
381
+
382
+ def _is_path_collision_free(
383
+ model: mujoco.MjModel,
384
+ data: mujoco.MjData,
385
+ base: WheeledBase,
386
+ path: npt.NDArray[np.float64],
387
+ clearance: float,
388
+ ) -> bool:
389
+ """Check poses along each straight or turning step, every 2 cm or 2 degrees."""
390
+ for row in range(len(path) - 1):
391
+ start, end = path[row], path[row + 1]
392
+ steps = int(
393
+ max(
394
+ np.hypot(*(end[:2] - start[:2])) / 0.02,
395
+ abs(end[2] - start[2]) / np.radians(2),
396
+ 1,
397
+ )
398
+ )
399
+ for fraction in np.linspace(0, 1, steps + 1):
400
+ pose = start + fraction * (end - start)
401
+ if not is_base_collision_free(model, data, base, pose, clearance):
402
+ return False
403
+ return True
404
+
405
+
406
+ def _wrap(angle: npt.ArrayLike) -> npt.NDArray[np.float64]:
407
+ return (np.asarray(angle) + np.pi) % (2 * np.pi) - np.pi
408
+
409
+
410
+ def _yaw(orientation: Orientation) -> float:
411
+ w, x, y, z = orientation.to_array()
412
+ return float(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z)))