blocksim 0.1.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.
@@ -0,0 +1,928 @@
1
+ """
2
+ Robot manipulators: URDF import, rigid-body dynamics, and a joint-space block.
3
+
4
+ load_urdf("ur5.urdf") -> RigidBodyTree -> Manipulator block -> a diagram
5
+
6
+ WHAT THIS IS FOR
7
+ blocksim is an ODE and hybrid-event engine, not a contact physics engine,
8
+ so the part of robotics that belongs here is rigid-body dynamics in
9
+ GENERALIZED COORDINATES -- the layer Pinocchio and Drake sit on and that
10
+ Gazebo, MuJoCo and Isaac are built over. There is no collision
11
+ detection, no broadphase and no complementarity solver, and there should
12
+ not be: general multi-contact needs machinery that would define the
13
+ whole project rather than fit inside it. A SINGLE contact -- an end
14
+ stop, a foot touchdown, a gripper closing -- is expressible today as a
15
+ zero-crossing event, and that is the honest boundary.
16
+
17
+ What you get instead of a physics engine is the loop AROUND the arm:
18
+ a torque controller on one clock, an outer position loop on another,
19
+ motor electrical dynamics as continuous states, encoder quantisation,
20
+ joint flexibility, and a bus in between -- all in one diagram, solved
21
+ together. Pinocchio computes M(q) faster than this ever will; it does
22
+ not give you the loop.
23
+
24
+ HOW THE DYNAMICS ARE COMPUTED
25
+ `inverse_dynamics` is the recursive Newton-Euler algorithm in its 3D
26
+ form (Featherstone, *Rigid Body Dynamics Algorithms*; Craig,
27
+ *Introduction to Robotics*), with gravity folded in as a base
28
+ acceleration.
29
+
30
+ `mass_matrix` is then built COLUMN BY COLUMN from that same routine,
31
+ each column being the inverse dynamics of a unit joint acceleration
32
+ with gravity and velocity switched off. That is O(n^3) where the
33
+ composite rigid body algorithm is O(n^2) -- irrelevant below a few tens
34
+ of joints, and worth it: the mass matrix cannot drift out of agreement
35
+ with the inverse dynamics, because it IS the inverse dynamics.
36
+
37
+ WHAT THE URDF READER TAKES
38
+ Links (mass, centre of mass, inertia tensor) and joints (revolute,
39
+ continuous, prismatic and fixed, with axis, origin, limits, damping and
40
+ friction). Mesh, visual and collision paths are recorded but the
41
+ geometry is NOT loaded -- nothing here renders or collides, so it would
42
+ be dead weight. `mimic` joints, `floating` and `planar` joints, and
43
+ xacro macros are refused with an explanatory error rather than silently
44
+ mis-parsed; xacro is a preprocessor, so expand it first.
45
+ """
46
+
47
+ import xml.etree.ElementTree as ET
48
+ from dataclasses import dataclass, field
49
+ from typing import Optional
50
+
51
+ import numpy as np
52
+
53
+ from .core import Block
54
+ from ._logging import get_logger
55
+
56
+ __all__ = [
57
+ "GRAVITY_EARTH",
58
+ "Joint",
59
+ "JointTrajectory",
60
+ "Link",
61
+ "Manipulator",
62
+ "RigidBodyTree",
63
+ "load_urdf",
64
+ "rpy_to_matrix",
65
+ ]
66
+
67
+ log = get_logger("manipulator")
68
+
69
+ #: Reference gravity vector in m/s^2, along negative z.
70
+ GRAVITY_EARTH = np.array([0.0, 0.0, -9.80665])
71
+
72
+ #: joint types the reader understands. `continuous` is a revolute joint
73
+ #: without limits, and behaves identically here.
74
+ REVOLUTE = ("revolute", "continuous")
75
+ SUPPORTED_JOINTS = REVOLUTE + ("prismatic", "fixed")
76
+
77
+
78
+ # ==========================================================================
79
+ # small rotation helpers
80
+ # ==========================================================================
81
+ def rpy_to_matrix(rpy):
82
+ """URDF fixed-axis roll-pitch-yaw to a rotation matrix, R = Rz Ry Rx."""
83
+ roll, pitch, yaw = (float(v) for v in rpy)
84
+ cr, sr = np.cos(roll), np.sin(roll)
85
+ cp, sp = np.cos(pitch), np.sin(pitch)
86
+ cy, sy = np.cos(yaw), np.sin(yaw)
87
+ return np.array(
88
+ [
89
+ [cy * cp, cy * sp * sr - sy * cr, cy * sp * cr + sy * sr],
90
+ [sy * cp, sy * sp * sr + cy * cr, sy * sp * cr - cy * sr],
91
+ [-sp, cp * sr, cp * cr],
92
+ ]
93
+ )
94
+
95
+
96
+ def _axis_rotation(axis, angle):
97
+ """Rodrigues' formula for a rotation of `angle` about a unit `axis`."""
98
+ k = np.asarray(axis, dtype=float)
99
+ K = _skew(k)
100
+ return np.eye(3) + np.sin(angle) * K + (1.0 - np.cos(angle)) * (K @ K)
101
+
102
+
103
+ def _skew(v):
104
+ return np.array([[0.0, -v[2], v[1]], [v[2], 0.0, -v[0]], [-v[1], v[0], 0.0]])
105
+
106
+
107
+ def _homogeneous(R, t):
108
+ T = np.eye(4)
109
+ T[:3, :3] = R
110
+ T[:3, 3] = t
111
+ return T
112
+
113
+
114
+ # ==========================================================================
115
+ # model
116
+ # ==========================================================================
117
+ @dataclass
118
+ class Link:
119
+ """One rigid body.
120
+
121
+ `com` is the centre of mass in the LINK frame, and `inertia` is the
122
+ inertia tensor about the centre of mass, already rotated into the link
123
+ frame (URDF states it in the inertial frame, which may be rotated).
124
+ """
125
+
126
+ name: str
127
+ mass: float = 0.0
128
+ com: np.ndarray = field(default_factory=lambda: np.zeros(3))
129
+ inertia: np.ndarray = field(default_factory=lambda: np.zeros((3, 3)))
130
+ meshes: tuple = () # recorded, never loaded
131
+
132
+ def __post_init__(self):
133
+ self.com = np.asarray(self.com, dtype=float).reshape(3)
134
+ self.inertia = np.asarray(self.inertia, dtype=float).reshape(3, 3)
135
+
136
+
137
+ @dataclass
138
+ class Joint:
139
+ """One joint, connecting `parent` to `child`.
140
+
141
+ `origin_xyz` / `origin_rpy` place the joint frame in the parent link
142
+ frame; `axis` is a unit vector in the joint frame.
143
+ """
144
+
145
+ name: str
146
+ joint_type: str
147
+ parent: str
148
+ child: str
149
+ axis: np.ndarray = field(default_factory=lambda: np.array([0.0, 0.0, 1.0]))
150
+ origin_xyz: np.ndarray = field(default_factory=lambda: np.zeros(3))
151
+ origin_rpy: np.ndarray = field(default_factory=lambda: np.zeros(3))
152
+ lower: float = -np.inf
153
+ upper: float = np.inf
154
+ effort: float = np.inf
155
+ velocity: float = np.inf
156
+ damping: float = 0.0
157
+ friction: float = 0.0
158
+
159
+ def __post_init__(self):
160
+ if self.joint_type not in SUPPORTED_JOINTS:
161
+ raise ValueError(
162
+ f"joint {self.name!r}: type {self.joint_type!r} is not supported; "
163
+ f"this reader handles {', '.join(SUPPORTED_JOINTS)}"
164
+ )
165
+ self.origin_xyz = np.asarray(self.origin_xyz, dtype=float).reshape(3)
166
+ self.origin_rpy = np.asarray(self.origin_rpy, dtype=float).reshape(3)
167
+ axis = np.asarray(self.axis, dtype=float).reshape(3)
168
+ norm = np.linalg.norm(axis)
169
+ if self.joint_type != "fixed":
170
+ if norm < 1e-12:
171
+ raise ValueError(f"joint {self.name!r} has a zero-length axis")
172
+ axis = axis / norm
173
+ self.axis = axis
174
+ self._origin_R = rpy_to_matrix(self.origin_rpy)
175
+
176
+ @property
177
+ def is_fixed(self) -> bool:
178
+ return self.joint_type == "fixed"
179
+
180
+ def transform(self, q: float = 0.0):
181
+ """(R, t) taking a vector from the CHILD frame into the PARENT."""
182
+ if self.joint_type in REVOLUTE:
183
+ return self._origin_R @ _axis_rotation(self.axis, q), self.origin_xyz
184
+ if self.joint_type == "prismatic":
185
+ return self._origin_R, self.origin_xyz + self._origin_R @ (self.axis * q)
186
+ return self._origin_R, self.origin_xyz
187
+
188
+
189
+ class RigidBodyTree:
190
+ """A kinematic tree of rigid bodies, with dynamics.
191
+
192
+ Bodies are held in topological order, so a parent always precedes its
193
+ children and the recursions below are simple loops rather than
194
+ traversals. `q` is the vector of MOVING joint coordinates in that same
195
+ order; fixed joints keep their frames but take no coordinate.
196
+
197
+ Not manipulator-specific despite the module name -- any tree works,
198
+ including legs and grippers. Closed chains are not a tree: model those
199
+ with :class:`~blocksim.mechanics.ConstrainedMechanism`, which already
200
+ carries holonomic loop-closure constraints and their multipliers.
201
+ """
202
+
203
+ def __init__(self, links, joints, name: str = "robot", gravity=None):
204
+ self.name = name
205
+ self.links = {link.name: link for link in links}
206
+ if len(self.links) != len(list(links)):
207
+ raise ValueError("duplicate link names in the model")
208
+ self.joints = list(joints)
209
+ self.gravity = (
210
+ GRAVITY_EARTH if gravity is None else np.asarray(gravity, dtype=float)
211
+ )
212
+ self._build_tree()
213
+
214
+ # ---- topology ----------------------------------------------------------
215
+ def _build_tree(self):
216
+ children = {}
217
+ joint_to_parent = {}
218
+ for joint in self.joints:
219
+ for side in (joint.parent, joint.child):
220
+ if side not in self.links:
221
+ raise ValueError(
222
+ f"joint {joint.name!r} refers to unknown link {side!r}"
223
+ )
224
+ if joint.child in joint_to_parent:
225
+ raise ValueError(
226
+ f"link {joint.child!r} has two parent joints; this is a closed "
227
+ f"chain, not a tree -- use ConstrainedMechanism for loops"
228
+ )
229
+ joint_to_parent[joint.child] = joint
230
+ children.setdefault(joint.parent, []).append(joint)
231
+
232
+ roots = [n for n in self.links if n not in joint_to_parent]
233
+ if len(roots) != 1:
234
+ raise ValueError(
235
+ f"a tree needs exactly one base link, found {len(roots)}: "
236
+ f"{sorted(roots)}"
237
+ )
238
+ self.base = roots[0]
239
+
240
+ # breadth-first from the base gives a valid topological order
241
+ self.body_names = [self.base]
242
+ self.body_joint = [None]
243
+ self.body_parent = [-1]
244
+ cursor = 0
245
+ while cursor < len(self.body_names):
246
+ for joint in children.get(self.body_names[cursor], []):
247
+ self.body_names.append(joint.child)
248
+ self.body_joint.append(joint)
249
+ self.body_parent.append(cursor)
250
+ cursor += 1
251
+
252
+ if len(self.body_names) != len(self.links):
253
+ missing = sorted(set(self.links) - set(self.body_names))
254
+ raise ValueError(
255
+ f"links unreachable from the base {self.base!r}: {missing}"
256
+ )
257
+
258
+ self.index_of = {name: i for i, name in enumerate(self.body_names)}
259
+ #: body index -> coordinate index, or -1 for a fixed joint
260
+ self.body_dof = [-1] * len(self.body_names)
261
+ self.moving_joints = []
262
+ for i, joint in enumerate(self.body_joint):
263
+ if joint is not None and not joint.is_fixed:
264
+ self.body_dof[i] = len(self.moving_joints)
265
+ self.moving_joints.append(joint)
266
+
267
+ @property
268
+ def num_joints(self) -> int:
269
+ """Degrees of freedom, i.e. the length of q."""
270
+ return len(self.moving_joints)
271
+
272
+ @property
273
+ def joint_names(self):
274
+ return [joint.name for joint in self.moving_joints]
275
+
276
+ @property
277
+ def joint_limits(self):
278
+ """(lower, upper) arrays over the moving joints."""
279
+ return (
280
+ np.array([j.lower for j in self.moving_joints]),
281
+ np.array([j.upper for j in self.moving_joints]),
282
+ )
283
+
284
+ @property
285
+ def damping(self):
286
+ return np.array([j.damping for j in self.moving_joints])
287
+
288
+ @property
289
+ def friction(self):
290
+ return np.array([j.friction for j in self.moving_joints])
291
+
292
+ @property
293
+ def total_mass(self) -> float:
294
+ return sum(link.mass for link in self.links.values())
295
+
296
+ def _check_q(self, q, label="q"):
297
+ q = np.atleast_1d(np.asarray(q, dtype=float))
298
+ if q.size != self.num_joints:
299
+ raise ValueError(
300
+ f"{label} has {q.size} entries but the model has "
301
+ f"{self.num_joints} moving joints"
302
+ )
303
+ return q
304
+
305
+ # ---- kinematics --------------------------------------------------------
306
+ def forward_kinematics(self, q):
307
+ """4x4 pose of every body in base coordinates, in body order."""
308
+ q = self._check_q(q)
309
+ poses = [np.eye(4)]
310
+ for i in range(1, len(self.body_names)):
311
+ joint = self.body_joint[i]
312
+ dof = self.body_dof[i]
313
+ R, t = joint.transform(q[dof] if dof >= 0 else 0.0)
314
+ poses.append(poses[self.body_parent[i]] @ _homogeneous(R, t))
315
+ return poses
316
+
317
+ def transform(self, q, body, base=None):
318
+ """Pose of `body` relative to `base` (the model's base by default)."""
319
+ poses = self.forward_kinematics(q)
320
+ target = poses[self._body_index(body)]
321
+ if base is None:
322
+ return target
323
+ source = poses[self._body_index(base)]
324
+ R = source[:3, :3]
325
+ inverse = _homogeneous(R.T, -R.T @ source[:3, 3])
326
+ return inverse @ target
327
+
328
+ def _body_index(self, body):
329
+ if isinstance(body, (int, np.integer)):
330
+ return int(body)
331
+ if body not in self.index_of:
332
+ raise ValueError(f"unknown body {body!r}; have {sorted(self.index_of)}")
333
+ return self.index_of[body]
334
+
335
+ def geometric_jacobian(self, q, body):
336
+ """6 x n Jacobian of `body` in base coordinates.
337
+
338
+ Rows 0-2 are angular and rows 3-5 linear, matching the usual
339
+ convention: ``[omega; v] = J(q) qdot``.
340
+ """
341
+ q = self._check_q(q)
342
+ poses = self.forward_kinematics(q)
343
+ index = self._body_index(body)
344
+ target = poses[index][:3, 3]
345
+
346
+ J = np.zeros((6, self.num_joints))
347
+ node = index
348
+ while node > 0:
349
+ joint = self.body_joint[node]
350
+ dof = self.body_dof[node]
351
+ if dof >= 0:
352
+ # the joint axis lives in the child frame, so use the child pose
353
+ axis_world = poses[node][:3, :3] @ joint.axis
354
+ if joint.joint_type == "prismatic":
355
+ J[3:, dof] = axis_world
356
+ else:
357
+ J[:3, dof] = axis_world
358
+ J[3:, dof] = np.cross(axis_world, target - poses[node][:3, 3])
359
+ node = self.body_parent[node]
360
+ return J
361
+
362
+ def center_of_mass(self, q):
363
+ """Whole-model centre of mass, in base coordinates."""
364
+ poses = self.forward_kinematics(q)
365
+ total = self.total_mass
366
+ if total <= 0.0:
367
+ raise ValueError("the model has no mass")
368
+ weighted = np.zeros(3)
369
+ for i, name in enumerate(self.body_names):
370
+ link = self.links[name]
371
+ if link.mass:
372
+ weighted += link.mass * (poses[i][:3, :3] @ link.com + poses[i][:3, 3])
373
+ return weighted / total
374
+
375
+ # ---- dynamics ----------------------------------------------------------
376
+ def inverse_dynamics(self, q, qd, qdd, gravity=None, external=None):
377
+ """Joint torques for a given motion: the recursive Newton-Euler pass.
378
+
379
+ `gravity` overrides the model's own (pass zeros to get the pure
380
+ inertial terms). `external` is an optional dict mapping a body to a
381
+ 6-vector wrench ``[moment; force]`` applied to it, expressed in base
382
+ coordinates.
383
+
384
+ Returns the generalized force at each moving joint -- torque for a
385
+ revolute joint, force for a prismatic one. Joint damping and
386
+ friction are NOT included; :class:`Manipulator` applies those, so
387
+ that this stays the pure rigid-body map.
388
+ """
389
+ q = self._check_q(q)
390
+ qd = self._check_q(qd, "qd")
391
+ qdd = self._check_q(qdd, "qdd")
392
+ g = self.gravity if gravity is None else np.asarray(gravity, dtype=float)
393
+
394
+ n_bodies = len(self.body_names)
395
+ omega = [np.zeros(3) for _ in range(n_bodies)]
396
+ alpha = [np.zeros(3) for _ in range(n_bodies)]
397
+ # gravity enters as an acceleration of the base, which is why the
398
+ # base starts at -g rather than zero
399
+ accel = [np.zeros(3) for _ in range(n_bodies)]
400
+ accel[0] = -g
401
+ rotations = [np.eye(3) for _ in range(n_bodies)]
402
+ offsets = [np.zeros(3) for _ in range(n_bodies)]
403
+
404
+ forces = [np.zeros(3) for _ in range(n_bodies)]
405
+ moments = [np.zeros(3) for _ in range(n_bodies)]
406
+
407
+ # ---- outward pass: velocities and accelerations -------------------
408
+ for i in range(1, n_bodies):
409
+ joint = self.body_joint[i]
410
+ dof = self.body_dof[i]
411
+ qi = q[dof] if dof >= 0 else 0.0
412
+ R, t = joint.transform(qi)
413
+ rotations[i], offsets[i] = R, t
414
+ parent = self.body_parent[i]
415
+
416
+ # everything is expressed in the body's own frame, so incoming
417
+ # parent quantities are rotated by R^T
418
+ w_p = R.T @ omega[parent]
419
+ a_p = R.T @ alpha[parent]
420
+ linear = R.T @ (
421
+ accel[parent]
422
+ + np.cross(alpha[parent], t)
423
+ + np.cross(omega[parent], np.cross(omega[parent], t))
424
+ )
425
+
426
+ if dof < 0: # fixed joint: pure frame change
427
+ omega[i], alpha[i], accel[i] = w_p, a_p, linear
428
+ elif joint.joint_type == "prismatic":
429
+ omega[i] = w_p
430
+ alpha[i] = a_p
431
+ accel[i] = (
432
+ linear
433
+ + joint.axis * qdd[dof]
434
+ + 2.0 * np.cross(w_p, joint.axis * qd[dof])
435
+ )
436
+ else: # revolute
437
+ omega[i] = w_p + joint.axis * qd[dof]
438
+ alpha[i] = (
439
+ a_p + joint.axis * qdd[dof] + np.cross(w_p, joint.axis * qd[dof])
440
+ )
441
+ accel[i] = linear
442
+
443
+ link = self.links[self.body_names[i]]
444
+ a_com = (
445
+ accel[i]
446
+ + np.cross(alpha[i], link.com)
447
+ + np.cross(omega[i], np.cross(omega[i], link.com))
448
+ )
449
+ forces[i] = link.mass * a_com
450
+ moments[i] = link.inertia @ alpha[i] + np.cross(
451
+ omega[i], link.inertia @ omega[i]
452
+ )
453
+
454
+ # ---- external wrenches, rotated into each body frame --------------
455
+ # They act at the BODY ORIGIN, so they carry no moment arm of their
456
+ # own and must be applied AFTER the centre-of-mass cross product
457
+ # below -- folding them into the inertial force instead would give
458
+ # them the centre of mass as a lever arm, which they do not have.
459
+ applied = {}
460
+ if external:
461
+ poses = self.forward_kinematics(q)
462
+ for body, wrench in external.items():
463
+ index = self._body_index(body)
464
+ wrench = np.asarray(wrench, dtype=float).reshape(6)
465
+ R_world = poses[index][:3, :3]
466
+ applied[index] = (R_world.T @ wrench[:3], R_world.T @ wrench[3:])
467
+
468
+ # ---- inward pass: accumulate forces, read off joint torques -------
469
+ tau = np.zeros(self.num_joints)
470
+ f = [np.array(v) for v in forces]
471
+ n = [np.array(v) for v in moments]
472
+ for i in range(n_bodies - 1, 0, -1):
473
+ link = self.links[self.body_names[i]]
474
+ n[i] = n[i] + np.cross(link.com, forces[i])
475
+ if i in applied:
476
+ moment_ext, force_ext = applied[i]
477
+ f[i] = f[i] - force_ext
478
+ n[i] = n[i] - moment_ext
479
+ parent = self.body_parent[i]
480
+ R, t = rotations[i], offsets[i]
481
+ f[parent] = f[parent] + R @ f[i]
482
+ n[parent] = n[parent] + R @ n[i] + np.cross(t, R @ f[i])
483
+
484
+ dof = self.body_dof[i]
485
+ if dof >= 0:
486
+ joint = self.body_joint[i]
487
+ if joint.joint_type == "prismatic":
488
+ tau[dof] = joint.axis @ f[i]
489
+ else:
490
+ tau[dof] = joint.axis @ n[i]
491
+ return tau
492
+
493
+ def mass_matrix(self, q):
494
+ """Joint-space mass matrix, one inverse-dynamics call per column.
495
+
496
+ Column j is the torque needed for a unit acceleration of joint j
497
+ with nothing else moving and gravity off, which is the definition of
498
+ M. Building it this way costs an extra factor of n over the
499
+ composite rigid body algorithm and buys exact consistency with
500
+ :meth:`inverse_dynamics`.
501
+ """
502
+ q = self._check_q(q)
503
+ n = self.num_joints
504
+ zero = np.zeros(n)
505
+ M = np.zeros((n, n))
506
+ for j in range(n):
507
+ unit = np.zeros(n)
508
+ unit[j] = 1.0
509
+ M[:, j] = self.inverse_dynamics(q, zero, unit, gravity=np.zeros(3))
510
+ # symmetric in exact arithmetic; average away the round-off
511
+ return 0.5 * (M + M.T)
512
+
513
+ def gravity_torque(self, q):
514
+ """Joint torques that hold the model up against gravity."""
515
+ zero = np.zeros(self.num_joints)
516
+ return self.inverse_dynamics(q, zero, zero)
517
+
518
+ def velocity_product(self, q, qd):
519
+ """The Coriolis and centrifugal torques, gravity excluded."""
520
+ return self.inverse_dynamics(
521
+ q, qd, np.zeros(self.num_joints), gravity=np.zeros(3)
522
+ )
523
+
524
+ def forward_dynamics(self, q, qd, tau, external=None):
525
+ """Joint accelerations from applied torques: M(q)^-1 (tau - bias)."""
526
+ tau = self._check_q(tau, "tau")
527
+ bias = self.inverse_dynamics(
528
+ q, qd, np.zeros(self.num_joints), external=external
529
+ )
530
+ return np.linalg.solve(self.mass_matrix(q), tau - bias)
531
+
532
+ # ---- energy, which is what makes a passive model checkable ------------
533
+ def kinetic_energy(self, q, qd) -> float:
534
+ qd = self._check_q(qd, "qd")
535
+ return 0.5 * float(qd @ self.mass_matrix(q) @ qd)
536
+
537
+ def potential_energy(self, q) -> float:
538
+ """Gravitational potential, zero at the base frame origin."""
539
+ poses = self.forward_kinematics(q)
540
+ total = 0.0
541
+ for i, name in enumerate(self.body_names):
542
+ link = self.links[name]
543
+ if link.mass:
544
+ world = poses[i][:3, :3] @ link.com + poses[i][:3, 3]
545
+ total -= link.mass * float(self.gravity @ world)
546
+ return total
547
+
548
+ def total_energy(self, q, qd) -> float:
549
+ return self.kinetic_energy(q, qd) + self.potential_energy(q)
550
+
551
+ # ---- reporting ---------------------------------------------------------
552
+ def describe(self) -> str:
553
+ lines = [
554
+ f"RigidBodyTree {self.name!r}: {len(self.body_names)} bodies, "
555
+ f"{self.num_joints} moving joints, {self.total_mass:.4g} kg",
556
+ f" base: {self.base}",
557
+ ]
558
+ for i in range(1, len(self.body_names)):
559
+ joint = self.body_joint[i]
560
+ dof = self.body_dof[i]
561
+ tag = f"q[{dof}]" if dof >= 0 else "fixed"
562
+ lines.append(
563
+ f" {self.body_names[i]:<20} <- {joint.name:<20} "
564
+ f"{joint.joint_type:<10} {tag:<7} "
565
+ f"m = {self.links[self.body_names[i]].mass:.4g} kg"
566
+ )
567
+ return "\n".join(lines)
568
+
569
+ def __repr__(self):
570
+ return (
571
+ f"<RigidBodyTree {self.name!r}: {len(self.body_names)} bodies, "
572
+ f"{self.num_joints} dof>"
573
+ )
574
+
575
+
576
+ # ==========================================================================
577
+ # URDF
578
+ # ==========================================================================
579
+ def _floats(element, attribute, default):
580
+ if element is None or element.get(attribute) is None:
581
+ return np.asarray(default, dtype=float)
582
+ return np.array([float(v) for v in element.get(attribute).split()])
583
+
584
+
585
+ def _origin(element):
586
+ origin = None if element is None else element.find("origin")
587
+ return _floats(origin, "xyz", (0.0, 0.0, 0.0)), _floats(
588
+ origin, "rpy", (0.0, 0.0, 0.0)
589
+ )
590
+
591
+
592
+ def _parse_link(node) -> Link:
593
+ name = node.get("name")
594
+ if not name:
595
+ raise ValueError("every <link> needs a name")
596
+ meshes = tuple(
597
+ mesh.get("filename")
598
+ for tag in ("visual", "collision")
599
+ for mesh in node.findall(f"{tag}/geometry/mesh")
600
+ if mesh.get("filename")
601
+ )
602
+
603
+ inertial = node.find("inertial")
604
+ if inertial is None:
605
+ return Link(name=name, meshes=meshes)
606
+
607
+ mass_node = inertial.find("mass")
608
+ mass = float(mass_node.get("value")) if mass_node is not None else 0.0
609
+ com, rpy = _origin(inertial)
610
+
611
+ tensor = inertial.find("inertia")
612
+ if tensor is None:
613
+ inertia = np.zeros((3, 3))
614
+ else:
615
+
616
+ def value(key):
617
+ return float(tensor.get(key, 0.0))
618
+
619
+ ixx, iyy, izz = value("ixx"), value("iyy"), value("izz")
620
+ ixy, ixz, iyz = value("ixy"), value("ixz"), value("iyz")
621
+ inertia = np.array([[ixx, ixy, ixz], [ixy, iyy, iyz], [ixz, iyz, izz]])
622
+ # URDF gives the tensor in the inertial frame; the algorithms want
623
+ # it about the same point but along the LINK axes
624
+ R = rpy_to_matrix(rpy)
625
+ inertia = R @ inertia @ R.T
626
+
627
+ return Link(name=name, mass=mass, com=com, inertia=inertia, meshes=meshes)
628
+
629
+
630
+ def _parse_joint(node) -> Joint:
631
+ name = node.get("name")
632
+ joint_type = node.get("type")
633
+ if not name or not joint_type:
634
+ raise ValueError("every <joint> needs a name and a type")
635
+ if node.find("mimic") is not None:
636
+ raise ValueError(
637
+ f"joint {name!r} uses <mimic>, which this reader does not support "
638
+ f"(neither does MATLAB's importrobot); remove it or drive the "
639
+ f"joint explicitly"
640
+ )
641
+ parent = node.find("parent")
642
+ child = node.find("child")
643
+ if parent is None or child is None:
644
+ raise ValueError(f"joint {name!r} needs both <parent> and <child>")
645
+
646
+ xyz, rpy = _origin(node)
647
+ limit = node.find("limit")
648
+ dynamics = node.find("dynamics")
649
+
650
+ def attribute(element, key, default):
651
+ if element is None or element.get(key) is None:
652
+ return default
653
+ return float(element.get(key))
654
+
655
+ return Joint(
656
+ name=name,
657
+ joint_type=joint_type,
658
+ parent=parent.get("link"),
659
+ child=child.get("link"),
660
+ axis=_floats(node.find("axis"), "xyz", (1.0, 0.0, 0.0)),
661
+ origin_xyz=xyz,
662
+ origin_rpy=rpy,
663
+ lower=attribute(limit, "lower", -np.inf),
664
+ upper=attribute(limit, "upper", np.inf),
665
+ effort=attribute(limit, "effort", np.inf),
666
+ velocity=attribute(limit, "velocity", np.inf),
667
+ damping=attribute(dynamics, "damping", 0.0),
668
+ friction=attribute(dynamics, "friction", 0.0),
669
+ )
670
+
671
+
672
+ def load_urdf(source, gravity=None) -> RigidBodyTree:
673
+ """Read a URDF file (or a URDF string) into a :class:`RigidBodyTree`.
674
+
675
+ `source` is a path or the XML itself. Only the inertial and kinematic
676
+ content is used: mesh filenames are recorded on each :class:`Link` for
677
+ reference, but no geometry is loaded, because nothing in blocksim
678
+ renders or collides.
679
+
680
+ Raises rather than guessing on anything it cannot represent -- xacro
681
+ macros, `mimic` joints, and `floating` or `planar` joints.
682
+ """
683
+ text = str(source)
684
+ if "<" not in text: # a path, not a document
685
+ with open(text, "r", encoding="utf-8") as handle:
686
+ text = handle.read()
687
+ if "xacro" in text[:2000] and "<robot" in text:
688
+ if ":" in text.split("<robot", 1)[1].split(">", 1)[0]:
689
+ raise ValueError(
690
+ "this looks like a xacro file, which is a macro preprocessor "
691
+ "rather than a format; expand it first (`xacro model.xacro > "
692
+ "model.urdf`) and load the result"
693
+ )
694
+
695
+ root = ET.fromstring(text)
696
+ if root.tag != "robot":
697
+ raise ValueError(f"expected a <robot> root element, found <{root.tag}>")
698
+
699
+ links = [_parse_link(node) for node in root.findall("link")]
700
+ joints = [_parse_joint(node) for node in root.findall("joint")]
701
+ if not links:
702
+ raise ValueError("the model has no links")
703
+
704
+ tree = RigidBodyTree(links, joints, name=root.get("name", "robot"), gravity=gravity)
705
+ log.debug(
706
+ "loaded %r: %d bodies, %d dof", tree.name, len(tree.body_names), tree.num_joints
707
+ )
708
+ return tree
709
+
710
+
711
+ # ==========================================================================
712
+ # blocks
713
+ # ==========================================================================
714
+ class Manipulator(Block):
715
+ """A :class:`RigidBodyTree` as a block: torques in, motion out.
716
+
717
+ States are ``[q, qd]``. The output is a pure function of them, so this
718
+ composes into a feedback diagram without closing an algebraic loop --
719
+ the same discipline the vehicle chassis follows.
720
+
721
+ Joint damping and viscous friction come from the URDF and are applied
722
+ HERE rather than inside :meth:`RigidBodyTree.inverse_dynamics`, which
723
+ stays the pure rigid-body map. Coulomb friction uses a ``tanh`` around
724
+ zero speed instead of a hard ``sign``, so a joint at rest does not
725
+ chatter; the cost is that true stiction is not modelled.
726
+
727
+ Joint limits are carried on the model but NOT enforced: an end stop is
728
+ a contact, and the natural way to add one here is a zero-crossing event
729
+ on ``q - upper``.
730
+
731
+ Parameters
732
+ ----------
733
+ tree
734
+ the model. `load_urdf` builds one.
735
+ q0, qd0
736
+ initial configuration and joint rates.
737
+ end_effector
738
+ body whose position is published; the last body by
739
+ default.
740
+ damping, friction
741
+ override the URDF values (per joint or scalar).
742
+
743
+ Inputs
744
+ one torque (or force, for a prismatic joint) per moving joint.
745
+ Outputs
746
+ ``q`` (n), ``qd`` (n), then the end-effector position ``x, y, z``
747
+ in base coordinates.
748
+ """
749
+
750
+ def __init__(
751
+ self,
752
+ tree: RigidBodyTree,
753
+ q0=None,
754
+ qd0=None,
755
+ end_effector=None,
756
+ damping=None,
757
+ friction=None,
758
+ omega_eps: float = 1e-3,
759
+ name: Optional[str] = None,
760
+ ):
761
+ if tree.num_joints == 0:
762
+ raise ValueError("the model has no moving joints to actuate")
763
+ self.tree = tree
764
+ self.end_effector = (
765
+ tree.body_names[-1] if end_effector is None else end_effector
766
+ )
767
+ tree._body_index(self.end_effector) # fail now, not mid-simulation
768
+ self.omega_eps = float(omega_eps)
769
+
770
+ n = tree.num_joints
771
+ self.damping = (
772
+ tree.damping
773
+ if damping is None
774
+ else np.broadcast_to(np.asarray(damping, dtype=float), (n,)).copy()
775
+ )
776
+ self.friction = (
777
+ tree.friction
778
+ if friction is None
779
+ else np.broadcast_to(np.asarray(friction, dtype=float), (n,)).copy()
780
+ )
781
+
782
+ labels = [(f"q_{nm}", None) for nm in tree.joint_names]
783
+ super().__init__(
784
+ num_inputs=n,
785
+ num_outputs=2 * n + 3,
786
+ num_states=2 * n,
787
+ name=name or tree.name,
788
+ inputs=[(f"tau_{nm}", "N*m") for nm in tree.joint_names],
789
+ outputs=labels
790
+ + [(f"qd_{nm}", None) for nm in tree.joint_names]
791
+ + [("ee_x", "m"), ("ee_y", "m"), ("ee_z", "m")],
792
+ states=labels + [(f"qd_{nm}", None) for nm in tree.joint_names],
793
+ )
794
+ self.x0 = np.zeros(2 * n)
795
+ if q0 is not None:
796
+ self.x0[:n] = tree._check_q(q0, "q0")
797
+ if qd0 is not None:
798
+ self.x0[n:] = tree._check_q(qd0, "qd0")
799
+
800
+ def _split(self, x):
801
+ n = self.tree.num_joints
802
+ return x[:n], x[n:]
803
+
804
+ def derivative(self, t, x, u):
805
+ q, qd = self._split(x)
806
+ tau = np.asarray(u, dtype=float)
807
+ applied = tau - self.damping * qd - self.friction * np.tanh(qd / self.omega_eps)
808
+ return np.concatenate([qd, self.tree.forward_dynamics(q, qd, applied)])
809
+
810
+ def output(self, t, x):
811
+ q, _ = self._split(x)
812
+ position = self.tree.transform(q, self.end_effector)[:3, 3]
813
+ return np.concatenate([x, position])
814
+
815
+ # ---- convenience for scripts and tests ---------------------------------
816
+ def pose(self, q):
817
+ """Full 4x4 end-effector pose at configuration `q`."""
818
+ return self.tree.transform(q, self.end_effector)
819
+
820
+ def energy(self, x):
821
+ """Total mechanical energy at a state vector, for drift checks."""
822
+ q, qd = self._split(np.asarray(x, dtype=float))
823
+ return self.tree.total_energy(q, qd)
824
+
825
+
826
+ class JointTrajectory(Block):
827
+ """Smooth joint-space trajectory through waypoints.
828
+
829
+ ``quintic`` and ``cubic`` interpolate each segment as a polynomial that
830
+ starts and ends at rest, which is the usual point-to-point behaviour.
831
+ ``trapezoidal`` uses a constant-acceleration / constant-velocity /
832
+ constant-deceleration profile with the acceleration phase taking
833
+ `blend` of the segment.
834
+
835
+ Before the first breakpoint the first waypoint is held, and after the
836
+ last the last -- so the block is safe to leave wired up for the whole
837
+ run.
838
+
839
+ Outputs
840
+ ``q`` (n), ``qd`` (n), ``qdd`` (n).
841
+ """
842
+
843
+ METHODS = ("quintic", "cubic", "trapezoidal")
844
+
845
+ def __init__(
846
+ self,
847
+ waypoints,
848
+ times,
849
+ method: str = "quintic",
850
+ blend: float = 0.25,
851
+ names=None,
852
+ name: Optional[str] = None,
853
+ ):
854
+ if method not in self.METHODS:
855
+ raise ValueError(
856
+ f"unknown method {method!r}; choose from {', '.join(self.METHODS)}"
857
+ )
858
+ self.method = method
859
+ if not 0.0 < blend <= 0.5:
860
+ raise ValueError("blend is the acceleration fraction, in (0, 0.5]")
861
+ self.blend = float(blend)
862
+
863
+ self.waypoints = np.atleast_2d(np.asarray(waypoints, dtype=float))
864
+ self.times = np.atleast_1d(np.asarray(times, dtype=float))
865
+ if self.waypoints.shape[0] != self.times.size:
866
+ raise ValueError(
867
+ f"{self.waypoints.shape[0]} waypoints but {self.times.size} times"
868
+ )
869
+ if self.times.size < 2:
870
+ raise ValueError("a trajectory needs at least two waypoints")
871
+ if np.any(np.diff(self.times) <= 0.0):
872
+ raise ValueError("times must be strictly increasing")
873
+
874
+ n = self.waypoints.shape[1]
875
+ labels = names or [f"j{i}" for i in range(n)]
876
+ if len(labels) != n:
877
+ raise ValueError(f"{len(labels)} names for {n} joints")
878
+ super().__init__(
879
+ num_inputs=0,
880
+ num_outputs=3 * n,
881
+ name=name,
882
+ outputs=[(f"q_{nm}", None) for nm in labels]
883
+ + [(f"qd_{nm}", None) for nm in labels]
884
+ + [(f"qdd_{nm}", None) for nm in labels],
885
+ )
886
+ self.num_joints = n
887
+
888
+ def sample(self, t):
889
+ """(q, qd, qdd) at time `t`."""
890
+ n = self.num_joints
891
+ if t <= self.times[0]:
892
+ return self.waypoints[0].copy(), np.zeros(n), np.zeros(n)
893
+ if t >= self.times[-1]:
894
+ return self.waypoints[-1].copy(), np.zeros(n), np.zeros(n)
895
+
896
+ k = int(np.searchsorted(self.times, t, side="right") - 1)
897
+ duration = self.times[k + 1] - self.times[k]
898
+ s, sd, sdd = self._blend((t - self.times[k]) / duration)
899
+ span = self.waypoints[k + 1] - self.waypoints[k]
900
+ return (
901
+ self.waypoints[k] + span * s,
902
+ span * sd / duration,
903
+ span * sdd / duration**2,
904
+ )
905
+
906
+ def _blend(self, u):
907
+ """Normalised position, velocity and acceleration at u in [0, 1]."""
908
+ if self.method == "cubic":
909
+ return 3 * u**2 - 2 * u**3, 6 * u - 6 * u**2, 6 - 12 * u
910
+ if self.method == "quintic":
911
+ return (
912
+ 10 * u**3 - 15 * u**4 + 6 * u**5,
913
+ 30 * u**2 - 60 * u**3 + 30 * u**4,
914
+ 60 * u - 180 * u**2 + 120 * u**3,
915
+ )
916
+ # trapezoidal: accelerate for `blend`, coast, decelerate
917
+ b = self.blend
918
+ peak = 1.0 / (1.0 - b) # so the areas integrate to exactly 1
919
+ rate = peak / b
920
+ if u < b:
921
+ return 0.5 * rate * u**2, rate * u, rate
922
+ if u <= 1.0 - b:
923
+ return peak * (u - 0.5 * b), peak, 0.0
924
+ w = 1.0 - u
925
+ return 1.0 - 0.5 * rate * w**2, rate * w, -rate
926
+
927
+ def output(self, t):
928
+ return np.concatenate(self.sample(t))