Skip to content

Robot API

A simulated robot loaded from a URDF or MJCF file.

Provides structured access to all joints and links by name, along with base-link state properties, RL-compatible state/action interfaces, and reset functionality.

Do not instantiate directly — use the :meth:load class method.

Parameters:

Name Type Description Default
body_id int

PyBullet body ID.

required
sim 'Simulation'

The parent :class:~bulletlab.core.simulation.Simulation.

required
name str

Human-readable robot name.

'Robot'
initial_position tuple[float, float, float]

Initial base position.

(0.0, 0.0, 0.0)
initial_orientation tuple[float, float, float, float]

Initial base orientation (quaternion).

(0.0, 0.0, 0.0, 1.0)

Example::

robot = Robot.load("car.urdf", sim=sim, position=(0, 0, 0.5))
robot.joints["steering"].set_position(0.3)
robot.links["chassis"].mass = 10.0
Source code in bulletlab/robot/robot.py
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
class Robot:
    """A simulated robot loaded from a URDF or MJCF file.

    Provides structured access to all joints and links by name, along with
    base-link state properties, RL-compatible state/action interfaces,
    and reset functionality.

    Do not instantiate directly — use the :meth:`load` class method.

    Args:
        body_id: PyBullet body ID.
        sim: The parent :class:`~bulletlab.core.simulation.Simulation`.
        name: Human-readable robot name.
        initial_position: Initial base position.
        initial_orientation: Initial base orientation (quaternion).

    Example::

        robot = Robot.load("car.urdf", sim=sim, position=(0, 0, 0.5))
        robot.joints["steering"].set_position(0.3)
        robot.links["chassis"].mass = 10.0
    """

    def __init__(
        self,
        body_id: int,
        sim: "Simulation",
        name: str = "Robot",
        initial_position: tuple[float, float, float] = (0.0, 0.0, 0.0),
        initial_orientation: tuple[float, float, float, float] = (0.0, 0.0, 0.0, 1.0),
    ) -> None:
        self._body_id = body_id
        self._sim = sim
        self._name = name
        self._initial_position = initial_position
        self._initial_orientation = initial_orientation
        self._joints: dict[str, Joint] = {}
        self._links: dict[str, Link] = {}
        self._joint_indices: list[int] = []  # controllable joint indices

        self._discover_joints_and_links()

    # ------------------------------------------------------------------
    # Factory / classmethod
    # ------------------------------------------------------------------

    @classmethod
    def load(
        cls,
        path: str | Path,
        sim: "Simulation",
        position: tuple[float, float, float] = (0.0, 0.0, 0.0),
        orientation: tuple[float, float, float, float] = (0.0, 0.0, 0.0, 1.0),
        name: str | None = None,
        fixed_base: bool = False,
        scale: float = 1.0,
        flags: int = 0,
        tilt: "tuple[tuple[float, float, float], float] | None" = None,
    ) -> "Robot":
        """Load a robot from a URDF/MJCF file or an Arsenal package.

        Automatically discovers all joints and links and exposes them by name.

        **Local file loading** (unchanged behaviour):

        Args:
            path: Path to the URDF/MJCF file.  Can be an absolute path or a
                filename resolvable from the pybullet_data search path.  To
                load from BulletLab Arsenal prefix the argument with
                ``"arsenal:"`` (see below).
            sim: The :class:`~bulletlab.core.simulation.Simulation` instance.
            position: Initial base position ``(x, y, z)`` in meters.
            orientation: Initial base orientation as a quaternion ``(x, y, z, w)``.
                Applied before ``tilt`` if both are given.
            name: Human-readable robot name.  Defaults to the filename stem.
            fixed_base: If ``True``, the robot's base is fixed to the world.
            scale: Global scale factor for the loaded model.
            flags: Additional PyBullet load flags.
            tilt: Optional ``((ax, ay, az), angle_deg)`` shorthand for a
                single axis-angle rotation applied on top of ``orientation``.
                The axis does not need to be pre-normalised.

        **Arsenal loading** — prefix ``path`` with ``"arsenal:"``:

        The robot is downloaded from the BulletLab Arsenal registry into a
        temporary session cache and loaded transparently.  The cache is
        deleted automatically when the Python process exits.

        Arsenal URI formats::

            "arsenal:reference_bot"           # default model
            "arsenal:reference_bot/BLem1"     # specific model

        Returns:
            A new :class:`Robot` instance.

        Raises:
            FileNotFoundError: If a local URDF/MJCF file cannot be found.
            RuntimeError: If PyBullet fails to load the model.
            bulletlab.arsenal.ArsenalError: If Arsenal resolution or download fails.

        Example::

            # Local file (unchanged)
            robot = Robot.load("kuka_iiwa/model.urdf", sim=sim)

            # Arsenal — default model
            robot = Robot.load("arsenal:reference_bot", sim=sim)

            # Arsenal — specific model with spawn position
            robot = Robot.load(
                "arsenal:reference_bot/BLem1",
                sim=sim,
                position=(0, 0, 0.5),
            )

            # Tilt 30° around the Y axis (works with both local and Arsenal)
            robot = Robot.load("laikago/laikago.urdf", sim=sim,
                               tilt=((0, 1, 0), 30))
        """
        import math as _math

        path_str = str(path)

        # ── Arsenal URI handling ──────────────────────────────────────────────
        if path_str.startswith("arsenal:"):
            arsenal_source = path_str[len("arsenal:"):]
            path_str = cls._load_from_arsenal(arsenal_source)
            if name is None:
                # Derive name from the package portion of the URI
                name = arsenal_source.split("/")[0]

        if not sim.is_connected:
            sim.start()

        robot_name = name or Path(path_str).stem

        # ── Resolve final orientation ─────────────────────────────────────────
        if tilt is not None:
            axis, angle_deg = tilt
            ax, ay, az = axis
            # Normalise
            length = _math.sqrt(ax**2 + ay**2 + az**2)
            if length > 1e-9:
                ax, ay, az = ax / length, ay / length, az / length
            half = _math.radians(angle_deg) / 2.0
            s = _math.sin(half)
            tq = (ax * s, ay * s, az * s, _math.cos(half))   # tilt quaternion

            # Compose: final = tilt * base_orientation
            # q_mul(a, b): (a.xyz cross b.xyz + a.w*b.xyz + b.w*a.xyz, a.w*b.w - a.xyz·b.xyz)
            ax1, ay1, az1, aw1 = tq
            bx, by, bz, bw = orientation
            cx = aw1*bx + ax1*bw + ay1*bz - az1*by
            cy = aw1*by - ax1*bz + ay1*bw + az1*bx
            cz = aw1*bz + ax1*by - ay1*bx + az1*bw
            cw = aw1*bw - ax1*bx - ay1*by - az1*bz
            orientation = (cx, cy, cz, cw)

        path_obj = Path(path_str)
        ext = path_obj.suffix.lower()

        with SuppressOutput():
            if ext in (".urdf",):
                body_id = p.loadURDF(
                    path_str,
                    basePosition=list(position),
                    baseOrientation=list(orientation),
                    useFixedBase=fixed_base,
                    globalScaling=scale,
                    flags=flags,
                    physicsClientId=sim.client_id,
                )
            elif ext in (".xml", ".mjcf"):
                # MJCF: position/orientation not directly supported at load time
                body_ids = p.loadMJCF(
                    path_str,
                    physicsClientId=sim.client_id,
                )
                body_id = body_ids[0] if isinstance(body_ids, (list, tuple)) else body_ids
            else:
                # Try URDF by default
                body_id = p.loadURDF(
                    path_str,
                    basePosition=list(position),
                    baseOrientation=list(orientation),
                    useFixedBase=fixed_base,
                    globalScaling=scale,
                    flags=flags,
                    physicsClientId=sim.client_id,
                )

        robot = cls(
            body_id=body_id,
            sim=sim,
            name=robot_name,
            initial_position=position,
            initial_orientation=orientation,
        )
        sim.add_robot(robot)
        return robot

    @classmethod
    def _load_from_arsenal(cls, source: str) -> str:
        """Resolve an Arsenal source string to a local URDF path.

        Downloads the package's URDF and meshes into the session-scoped
        temporary cache and returns the path to the (rewritten) local URDF.

        Args:
            source: Arsenal source string **without** the ``"arsenal:"``
                prefix, e.g. ``"reference_bot"`` or ``"reference_bot/BLem1"``.

        Returns:
            Absolute path string to the downloaded URDF file.

        Raises:
            bulletlab.arsenal.ArsenalError: If the package or model cannot be
                resolved or downloaded.
        """
        from bulletlab.arsenal.cache import get_session_cache
        from bulletlab.arsenal.downloader import download_package
        from bulletlab.arsenal.resolver import parse_source, resolve_model, resolve_package

        package_name, model_id = parse_source(source)
        resolve_package(package_name)   # validates existence; raises PackageNotFoundError
        model = resolve_model(package_name, model_id)
        entrypoint: str = model["entrypoint"]

        cache_dir = get_session_cache() / package_name
        urdf_path = download_package(package_name, entrypoint, cache_dir)
        return str(urdf_path)

    @classmethod
    def install(
        cls,
        source: str,
        path: "str | Path | None" = None,
    ) -> Path:
        """Permanently install an Arsenal robot package to the local machine.

        Downloads only the URDF and mesh files required by the requested model.
        Installed packages persist across Python sessions and can be loaded
        via a local file path afterwards.

        Use :meth:`load` with an ``"arsenal:"`` prefix for ad-hoc loading
        without permanent installation.

        Args:
            source: One of:

                * ``"package_name"`` — install the default model.
                * ``"package_name/model_id"`` — install a specific model.

            path: Optional local directory to install into.  When omitted,
                installs to ``~/.bulletlab/packages/<package_name>/``.

        Returns:
            :class:`pathlib.Path` to the installed URDF file.

        Raises:
            bulletlab.arsenal.ArsenalError: On any resolution or download failure.

        Example::

            # Install the default model of reference_bot globally
            Robot.install("reference_bot")

            # Install a specific model to a project-local directory
            Robot.install("reference_bot/BLem1", path="robots/")

            # Load the installed robot afterwards
            robot = Robot.load(
                "/home/user/.bulletlab/packages/reference_bot/BLem1.urdf",
                sim=sim,
            )
        """
        from bulletlab.arsenal.installer import install as _install
        return _install(source, path=path)

    # ------------------------------------------------------------------
    # Discovery
    # ------------------------------------------------------------------

    def _discover_joints_and_links(self) -> None:
        """Scan PyBullet body and populate joints and links dictionaries."""
        num_joints = p.getNumJoints(self._body_id, physicsClientId=self._sim.client_id)

        # Base link (index -1)
        base_name = p.getBodyInfo(self._body_id, physicsClientId=self._sim.client_id)
        base_link_name = base_name[0].decode("utf-8") if isinstance(base_name[0], bytes) else str(base_name[0])
        self._links[base_link_name] = Link(
            name=base_link_name,
            index=-1,
            body_id=self._body_id,
            sim=self._sim,
        )
        # Also expose as "base"
        self._links["base"] = self._links[base_link_name]

        for i in range(num_joints):
            info = p.getJointInfo(self._body_id, i, physicsClientId=self._sim.client_id)
            joint_name_raw = info[1]
            link_name_raw = info[12]

            joint_name = joint_name_raw.decode("utf-8") if isinstance(joint_name_raw, bytes) else str(joint_name_raw)
            link_name = link_name_raw.decode("utf-8") if isinstance(link_name_raw, bytes) else str(link_name_raw)
            joint_type = info[2]

            # Build Joint object
            joint = Joint(
                name=joint_name,
                index=i,
                body_id=self._body_id,
                sim=self._sim,
            )
            self._joints[joint_name] = joint

            # Build Link object for this joint's child link
            link = Link(
                name=link_name,
                index=i,
                body_id=self._body_id,
                sim=self._sim,
            )
            self._links[link_name] = link

            # Track controllable joints (non-fixed)
            if joint_type != p.JOINT_FIXED:
                self._joint_indices.append(i)

    # ------------------------------------------------------------------
    # Joints and Links access
    # ------------------------------------------------------------------

    @property
    def joints(self) -> dict[str, Joint]:
        """Dictionary of all joints indexed by name.

        Example::

            robot.joints["wheel_left"].velocity = 10
        """
        return self._joints

    @property
    def links(self) -> dict[str, Link]:
        """Dictionary of all links indexed by name.

        Example::

            robot.links["chassis"].mass = 5.0
        """
        return self._links

    @property
    def controllable_joints(self) -> list[Joint]:
        """List of all non-fixed joints (those that can be actuated)."""
        return [j for j in self._joints.values() if not j.is_fixed]

    # ------------------------------------------------------------------
    # Base state
    # ------------------------------------------------------------------

    @property
    def base_position(self) -> tuple[float, float, float]:
        """World-frame base position ``(x, y, z)`` in meters.

        Example::

            x, y, z = robot.base_position
        """
        pos, _ = p.getBasePositionAndOrientation(
            self._body_id,
            physicsClientId=self._sim.client_id,
        )
        return tuple(float(v) for v in pos)  # type: ignore[return-value]

    @property
    def base_orientation(self) -> tuple[float, float, float, float]:
        """World-frame base orientation as quaternion ``(x, y, z, w)``.

        Example::

            q = robot.base_orientation
        """
        _, orn = p.getBasePositionAndOrientation(
            self._body_id,
            physicsClientId=self._sim.client_id,
        )
        return tuple(float(v) for v in orn)  # type: ignore[return-value]

    @property
    def base_velocity(self) -> tuple[float, float, float]:
        """World-frame linear velocity ``(vx, vy, vz)`` in m/s.

        Example::

            speed = robot.base_velocity[0]
        """
        vel, _ = p.getBaseVelocity(
            self._body_id,
            physicsClientId=self._sim.client_id,
        )
        return tuple(float(v) for v in vel)  # type: ignore[return-value]

    @property
    def base_angular_velocity(self) -> tuple[float, float, float]:
        """World-frame angular velocity ``(wx, wy, wz)`` in rad/s.

        Example::

            wx, wy, wz = robot.base_angular_velocity
        """
        _, avel = p.getBaseVelocity(
            self._body_id,
            physicsClientId=self._sim.client_id,
        )
        return tuple(float(v) for v in avel)  # type: ignore[return-value]

    @property
    def roll(self) -> float:
        """Base roll angle in radians (rotation around X axis).

        Example::

            print(f"Roll: {math.degrees(robot.roll):.1f}°")
        """
        return quaternion_to_euler(self.base_orientation)[0]

    @property
    def pitch(self) -> float:
        """Base pitch angle in radians (rotation around Y axis)."""
        return quaternion_to_euler(self.base_orientation)[1]

    @property
    def yaw(self) -> float:
        """Base yaw angle in radians (rotation around Z axis)."""
        return quaternion_to_euler(self.base_orientation)[2]

    @property
    def speed(self) -> float:
        """Scalar speed (magnitude of base linear velocity) in m/s.

        Example::

            print(f"Speed: {robot.speed:.2f} m/s")
        """
        v = self.base_velocity
        return math.sqrt(v[0] ** 2 + v[1] ** 2 + v[2] ** 2)

    # ------------------------------------------------------------------
    # Reset
    # ------------------------------------------------------------------

    def reset(
        self,
        position: tuple[float, float, float] | None = None,
        orientation: tuple[float, float, float, float] | None = None,
    ) -> None:
        """Reset the robot to its initial (or specified) pose.

        Also resets all joint positions and velocities to zero.

        Args:
            position: Target base position. Defaults to initial load position.
            orientation: Target base orientation. Defaults to initial load orientation.

        Example::

            robot.reset()
            robot.reset(position=(0, 0, 1), orientation=(0, 0, 0, 1))
        """
        pos = position if position is not None else self._initial_position
        orn = orientation if orientation is not None else self._initial_orientation

        p.resetBasePositionAndOrientation(
            self._body_id,
            list(pos),
            list(orn),
            physicsClientId=self._sim.client_id,
        )
        p.resetBaseVelocity(
            self._body_id,
            [0, 0, 0],
            [0, 0, 0],
            physicsClientId=self._sim.client_id,
        )
        for joint in self._joints.values():
            if not joint.is_fixed:
                joint.reset(pos=0.0, vel=0.0)

    def delete(self) -> None:
        """Removes the robot from the simulation.

        Example::

            robot.delete()
        """
        if hasattr(self._sim, "remove_robot"):
            self._sim.remove_robot(self)
        else:
            p.removeBody(self._body_id, physicsClientId=self._sim.client_id)

    def tilt(self, axis: str, degrees: float) -> None:
        """Rotates the robot around 'x', 'y', or 'z' axis.

        Example::

            robot.tilt('z', 90)
        """
        axis = axis.lower()
        if axis not in ('x', 'y', 'z'):
            raise ValueError("axis must be 'x', 'y', or 'z'")

        rads = math.radians(degrees)
        euler = list(self.base_orientation_euler)
        if axis == 'x': euler[0] += rads
        elif axis == 'y': euler[1] += rads
        elif axis == 'z': euler[2] += rads

        from bulletlab.utils.math_utils import euler_to_quaternion
        orn = euler_to_quaternion(*euler)

        p.resetBasePositionAndOrientation(
            self._body_id,
            list(self.base_position),
            list(orn),
            physicsClientId=self._sim.client_id,
        )

    def scale(self, factor: float) -> None:
        """Scale the robot. (Requires re-loading in PyBullet)"""
        raise NotImplementedError("Dynamic scaling of existing robots is not yet supported in PyBullet.")

    # ------------------------------------------------------------------
    # RL interface
    # ------------------------------------------------------------------

    def get_state(self) -> np.ndarray:
        """Return the full observable state as a flat NumPy array.

        State vector layout::

            [base_x, base_y, base_z,       # base position (3)
             base_qx, base_qy, base_qz, base_qw,  # base orientation quaternion (4)
             base_vx, base_vy, base_vz,   # base linear velocity (3)
             base_wx, base_wy, base_wz,   # base angular velocity (3)
             joint_pos_0, ...,            # controllable joint positions (N)
             joint_vel_0, ...]            # controllable joint velocities (N)

        Returns:
            1D NumPy float64 array of shape ``(13 + 2*N,)`` where N is the
            number of controllable joints.

        Example::

            state = robot.get_state()
            action = my_policy(state)
        """
        pos = list(self.base_position)
        orn = list(self.base_orientation)
        vel = list(self.base_velocity)
        avel = list(self.base_angular_velocity)

        joint_positions = []
        joint_velocities = []
        for idx in self._joint_indices:
            js = p.getJointState(self._body_id, idx, physicsClientId=self._sim.client_id)
            joint_positions.append(float(js[0]))
            joint_velocities.append(float(js[1]))

        return np.array(
            pos + orn + vel + avel + joint_positions + joint_velocities,
            dtype=np.float64,
        )

    def apply_action(self, action: np.ndarray) -> None:
        """Apply a NumPy action array to all controllable joints.

        The action array must have the same length as the number of
        controllable joints. Each value is interpreted as a target velocity.

        Args:
            action: 1D NumPy array of target velocities for each controllable joint.

        Raises:
            ValueError: If ``action`` length doesn't match controllable joint count.

        Example::

            action = np.array([10.0, 10.0, -5.0])
            robot.apply_action(action)
        """
        if len(action) != len(self._joint_indices):
            raise ValueError(
                f"Action length {len(action)} does not match "
                f"controllable joint count {len(self._joint_indices)}"
            )
        for idx, act_val in zip(self._joint_indices, action):
            p.setJointMotorControl2(
                self._body_id,
                idx,
                controlMode=p.VELOCITY_CONTROL,
                targetVelocity=float(act_val),
                force=100.0,
                physicsClientId=self._sim.client_id,
            )

    def apply_torques(self, torques: np.ndarray) -> None:
        """Apply torque control to all controllable joints.

        Args:
            torques: 1D NumPy array of torques for each controllable joint (N·m).

        Raises:
            ValueError: If ``torques`` length doesn't match controllable joint count.

        Example::

            robot.apply_torques(np.array([5.0, -5.0, 0.0]))
        """
        if len(torques) != len(self._joint_indices):
            raise ValueError(
                f"Torques length {len(torques)} does not match "
                f"controllable joint count {len(self._joint_indices)}"
            )
        # Disable velocity motors first
        for idx in self._joint_indices:
            p.setJointMotorControl2(
                self._body_id,
                idx,
                controlMode=p.VELOCITY_CONTROL,
                targetVelocity=0,
                force=0,
                physicsClientId=self._sim.client_id,
            )
        for idx, torque_val in zip(self._joint_indices, torques):
            p.setJointMotorControl2(
                self._body_id,
                idx,
                controlMode=p.TORQUE_CONTROL,
                force=float(torque_val),
                physicsClientId=self._sim.client_id,
            )

    # ------------------------------------------------------------------
    # External forces
    # ------------------------------------------------------------------

    def apply_force(
        self,
        force: tuple[float, float, float],
        position: tuple[float, float, float] = (0.0, 0.0, 0.0),
        link: str | None = None,
        frame: str = "world",
    ) -> None:
        """Apply an external force to the robot's base or a named link.

        The force is applied for **one physics step** only (PyBullet clears it
        automatically after each ``stepSimulation`` call), so you must call
        this every step to maintain a continuous force (e.g. thrust).

        Args:
            force: Force vector ``(fx, fy, fz)`` in Newtons.
            position: Point of application in the frame specified by ``frame``.
                Use ``(0, 0, 0)`` to apply at the link's centre of mass.
            link: Name of the link to apply the force to.  ``None`` means the
                robot's base link.
            frame: ``"world"`` (default) for world frame, or ``"local"`` for
                the link's local body frame.

        Example::

            # Simulate upward thrust every step
            robot.apply_force((0, 0, 20.0))

            # Push the arm's end-effector sideways in body frame
            robot.apply_force((5, 0, 0), link="gripper", frame="local")
        """
        cid = self._sim.client_id
        pybullet_frame = p.LINK_FRAME if frame == "local" else p.WORLD_FRAME

        if link is None:
            link_index = -1  # base
        else:
            # Find the joint index of this link (link index == joint index in PyBullet)
            link_index = -1
            for jname, joint in self._joints.items():
                lobj = self._links.get(link)
                if lobj is not None:
                    link_index = lobj.index
                    break
            if link_index == -1 and link not in self._links:
                raise ValueError(f"Link {link!r} not found. Available: {list(self._links.keys())}")

        p.applyExternalForce(
            self._body_id,
            link_index,
            list(force),
            list(position),
            pybullet_frame,
            physicsClientId=cid,
        )

    def apply_torque(
        self,
        torque: tuple[float, float, float],
        link: str | None = None,
        frame: str = "world",
    ) -> None:
        """Apply an external torque to the robot's base or a named link.

        Like :meth:`apply_force`, the torque is cleared after each physics step
        and must be re-applied every step for continuous rotation.

        Args:
            torque: Torque vector ``(tx, ty, tz)`` in Newton-metres.
            link: Name of the link.  ``None`` = base.
            frame: ``"world"`` or ``"local"``.

        Example::

            # Spin the base around the Z axis
            robot.apply_torque((0, 0, 5.0))
        """
        cid = self._sim.client_id
        pybullet_frame = p.LINK_FRAME if frame == "local" else p.WORLD_FRAME

        if link is None:
            link_index = -1
        else:
            lobj = self._links.get(link)
            if lobj is None:
                raise ValueError(f"Link {link!r} not found. Available: {list(self._links.keys())}")
            link_index = lobj.index

        p.applyExternalTorque(
            self._body_id,
            link_index,
            list(torque),
            pybullet_frame,
            physicsClientId=cid,
        )

    # ------------------------------------------------------------------
    # Physics dynamics
    # ------------------------------------------------------------------

    def set_dynamics(
        self,
        link: str | None = None,
        mass: float | None = None,
        lateral_friction: float | None = None,
        spinning_friction: float | None = None,
        rolling_friction: float | None = None,
        restitution: float | None = None,
        linear_damping: float | None = None,
        angular_damping: float | None = None,
        contact_stiffness: float | None = None,
        contact_damping: float | None = None,
    ) -> None:
        """Change physics/dynamics parameters for a link at runtime.

        Only the parameters you pass are changed — unspecified ones are left
        at their current PyBullet values.

        Args:
            link: Link name.  ``None`` = base link.
            mass: New mass in kg.
            lateral_friction: Coulomb friction coefficient.
            spinning_friction: Friction around the contact normal.
            rolling_friction: Rolling friction coefficient.
            restitution: Bounciness ``[0, 1]``.
            linear_damping: Linear velocity damping ``[0, 1]``.
            angular_damping: Angular velocity damping ``[0, 1]``.
            contact_stiffness: Contact ERP stiffness (advanced).
            contact_damping: Contact ERP damping (advanced).

        Example::

            # Make wheels grippier
            robot.set_dynamics("wheel_fl", lateral_friction=1.5)

            # Change body mass on-the-fly
            robot.set_dynamics(mass=3.0)

            # Make everything bouncy
            for name in robot.links:
                robot.set_dynamics(name, restitution=0.8)
        """
        cid = self._sim.client_id

        if link is None:
            link_index = -1
        else:
            lobj = self._links.get(link)
            if lobj is None:
                raise ValueError(f"Link {link!r} not found. Available: {list(self._links.keys())}")
            link_index = lobj.index

        kwargs: dict = {}
        if mass               is not None: kwargs["mass"]              = float(mass)
        if lateral_friction   is not None: kwargs["lateralFriction"]  = float(lateral_friction)
        if spinning_friction  is not None: kwargs["spinningFriction"]  = float(spinning_friction)
        if rolling_friction   is not None: kwargs["rollingFriction"]   = float(rolling_friction)
        if restitution        is not None: kwargs["restitution"]       = float(restitution)
        if linear_damping     is not None: kwargs["linearDamping"]     = float(linear_damping)
        if angular_damping    is not None: kwargs["angularDamping"]    = float(angular_damping)
        if contact_stiffness  is not None: kwargs["contactStiffness"]  = float(contact_stiffness)
        if contact_damping    is not None: kwargs["contactDamping"]    = float(contact_damping)

        if kwargs:
            p.changeDynamics(
                self._body_id,
                link_index,
                physicsClientId=cid,
                **kwargs,
            )



    # ------------------------------------------------------------------
    # Identity
    # ------------------------------------------------------------------

    @property
    def name(self) -> str:
        """Human-readable robot name."""
        return self._name

    @name.setter
    def name(self, value: str) -> None:
        self._name = str(value)

    @property
    def body_id(self) -> int:
        """PyBullet body ID (internal identifier). Prefer using named properties."""
        return self._body_id

    @property
    def num_joints(self) -> int:
        """Total number of joints (including fixed joints)."""
        return len(self._joints)

    @property
    def num_controllable_joints(self) -> int:
        """Number of non-fixed, actuatable joints."""
        return len(self._joint_indices)

    # ------------------------------------------------------------------
    # Repr
    # ------------------------------------------------------------------

    def __repr__(self) -> str:
        return (
            f"Robot({self._name!r}, body_id={self._body_id}, "
            f"joints={len(self._joints)}, links={len(self._links)})"
        )

base_angular_velocity: tuple[float, float, float] property

World-frame angular velocity (wx, wy, wz) in rad/s.

Example::

wx, wy, wz = robot.base_angular_velocity

base_orientation: tuple[float, float, float, float] property

World-frame base orientation as quaternion (x, y, z, w).

Example::

q = robot.base_orientation

base_position: tuple[float, float, float] property

World-frame base position (x, y, z) in meters.

Example::

x, y, z = robot.base_position

base_velocity: tuple[float, float, float] property

World-frame linear velocity (vx, vy, vz) in m/s.

Example::

speed = robot.base_velocity[0]

body_id: int property

PyBullet body ID (internal identifier). Prefer using named properties.

controllable_joints: list[Joint] property

List of all non-fixed joints (those that can be actuated).

joints: dict[str, Joint] property

Dictionary of all joints indexed by name.

Example::

robot.joints["wheel_left"].velocity = 10

Dictionary of all links indexed by name.

Example::

robot.links["chassis"].mass = 5.0

name: str property writable

Human-readable robot name.

num_controllable_joints: int property

Number of non-fixed, actuatable joints.

num_joints: int property

Total number of joints (including fixed joints).

pitch: float property

Base pitch angle in radians (rotation around Y axis).

roll: float property

Base roll angle in radians (rotation around X axis).

Example::

print(f"Roll: {math.degrees(robot.roll):.1f}°")

speed: float property

Scalar speed (magnitude of base linear velocity) in m/s.

Example::

print(f"Speed: {robot.speed:.2f} m/s")

yaw: float property

Base yaw angle in radians (rotation around Z axis).

apply_action(action: np.ndarray) -> None

Apply a NumPy action array to all controllable joints.

The action array must have the same length as the number of controllable joints. Each value is interpreted as a target velocity.

Parameters:

Name Type Description Default
action ndarray

1D NumPy array of target velocities for each controllable joint.

required

Raises:

Type Description
ValueError

If action length doesn't match controllable joint count.

Example::

action = np.array([10.0, 10.0, -5.0])
robot.apply_action(action)
Source code in bulletlab/robot/robot.py
def apply_action(self, action: np.ndarray) -> None:
    """Apply a NumPy action array to all controllable joints.

    The action array must have the same length as the number of
    controllable joints. Each value is interpreted as a target velocity.

    Args:
        action: 1D NumPy array of target velocities for each controllable joint.

    Raises:
        ValueError: If ``action`` length doesn't match controllable joint count.

    Example::

        action = np.array([10.0, 10.0, -5.0])
        robot.apply_action(action)
    """
    if len(action) != len(self._joint_indices):
        raise ValueError(
            f"Action length {len(action)} does not match "
            f"controllable joint count {len(self._joint_indices)}"
        )
    for idx, act_val in zip(self._joint_indices, action):
        p.setJointMotorControl2(
            self._body_id,
            idx,
            controlMode=p.VELOCITY_CONTROL,
            targetVelocity=float(act_val),
            force=100.0,
            physicsClientId=self._sim.client_id,
        )

apply_force(force: tuple[float, float, float], position: tuple[float, float, float] = (0.0, 0.0, 0.0), link: str | None = None, frame: str = 'world') -> None

Apply an external force to the robot's base or a named link.

The force is applied for one physics step only (PyBullet clears it automatically after each stepSimulation call), so you must call this every step to maintain a continuous force (e.g. thrust).

Parameters:

Name Type Description Default
force tuple[float, float, float]

Force vector (fx, fy, fz) in Newtons.

required
position tuple[float, float, float]

Point of application in the frame specified by frame. Use (0, 0, 0) to apply at the link's centre of mass.

(0.0, 0.0, 0.0)
link str | None

Name of the link to apply the force to. None means the robot's base link.

None
frame str

"world" (default) for world frame, or "local" for the link's local body frame.

'world'

Example::

# Simulate upward thrust every step
robot.apply_force((0, 0, 20.0))

# Push the arm's end-effector sideways in body frame
robot.apply_force((5, 0, 0), link="gripper", frame="local")
Source code in bulletlab/robot/robot.py
def apply_force(
    self,
    force: tuple[float, float, float],
    position: tuple[float, float, float] = (0.0, 0.0, 0.0),
    link: str | None = None,
    frame: str = "world",
) -> None:
    """Apply an external force to the robot's base or a named link.

    The force is applied for **one physics step** only (PyBullet clears it
    automatically after each ``stepSimulation`` call), so you must call
    this every step to maintain a continuous force (e.g. thrust).

    Args:
        force: Force vector ``(fx, fy, fz)`` in Newtons.
        position: Point of application in the frame specified by ``frame``.
            Use ``(0, 0, 0)`` to apply at the link's centre of mass.
        link: Name of the link to apply the force to.  ``None`` means the
            robot's base link.
        frame: ``"world"`` (default) for world frame, or ``"local"`` for
            the link's local body frame.

    Example::

        # Simulate upward thrust every step
        robot.apply_force((0, 0, 20.0))

        # Push the arm's end-effector sideways in body frame
        robot.apply_force((5, 0, 0), link="gripper", frame="local")
    """
    cid = self._sim.client_id
    pybullet_frame = p.LINK_FRAME if frame == "local" else p.WORLD_FRAME

    if link is None:
        link_index = -1  # base
    else:
        # Find the joint index of this link (link index == joint index in PyBullet)
        link_index = -1
        for jname, joint in self._joints.items():
            lobj = self._links.get(link)
            if lobj is not None:
                link_index = lobj.index
                break
        if link_index == -1 and link not in self._links:
            raise ValueError(f"Link {link!r} not found. Available: {list(self._links.keys())}")

    p.applyExternalForce(
        self._body_id,
        link_index,
        list(force),
        list(position),
        pybullet_frame,
        physicsClientId=cid,
    )

apply_torque(torque: tuple[float, float, float], link: str | None = None, frame: str = 'world') -> None

Apply an external torque to the robot's base or a named link.

Like :meth:apply_force, the torque is cleared after each physics step and must be re-applied every step for continuous rotation.

Parameters:

Name Type Description Default
torque tuple[float, float, float]

Torque vector (tx, ty, tz) in Newton-metres.

required
link str | None

Name of the link. None = base.

None
frame str

"world" or "local".

'world'

Example::

# Spin the base around the Z axis
robot.apply_torque((0, 0, 5.0))
Source code in bulletlab/robot/robot.py
def apply_torque(
    self,
    torque: tuple[float, float, float],
    link: str | None = None,
    frame: str = "world",
) -> None:
    """Apply an external torque to the robot's base or a named link.

    Like :meth:`apply_force`, the torque is cleared after each physics step
    and must be re-applied every step for continuous rotation.

    Args:
        torque: Torque vector ``(tx, ty, tz)`` in Newton-metres.
        link: Name of the link.  ``None`` = base.
        frame: ``"world"`` or ``"local"``.

    Example::

        # Spin the base around the Z axis
        robot.apply_torque((0, 0, 5.0))
    """
    cid = self._sim.client_id
    pybullet_frame = p.LINK_FRAME if frame == "local" else p.WORLD_FRAME

    if link is None:
        link_index = -1
    else:
        lobj = self._links.get(link)
        if lobj is None:
            raise ValueError(f"Link {link!r} not found. Available: {list(self._links.keys())}")
        link_index = lobj.index

    p.applyExternalTorque(
        self._body_id,
        link_index,
        list(torque),
        pybullet_frame,
        physicsClientId=cid,
    )

apply_torques(torques: np.ndarray) -> None

Apply torque control to all controllable joints.

Parameters:

Name Type Description Default
torques ndarray

1D NumPy array of torques for each controllable joint (N·m).

required

Raises:

Type Description
ValueError

If torques length doesn't match controllable joint count.

Example::

robot.apply_torques(np.array([5.0, -5.0, 0.0]))
Source code in bulletlab/robot/robot.py
def apply_torques(self, torques: np.ndarray) -> None:
    """Apply torque control to all controllable joints.

    Args:
        torques: 1D NumPy array of torques for each controllable joint (N·m).

    Raises:
        ValueError: If ``torques`` length doesn't match controllable joint count.

    Example::

        robot.apply_torques(np.array([5.0, -5.0, 0.0]))
    """
    if len(torques) != len(self._joint_indices):
        raise ValueError(
            f"Torques length {len(torques)} does not match "
            f"controllable joint count {len(self._joint_indices)}"
        )
    # Disable velocity motors first
    for idx in self._joint_indices:
        p.setJointMotorControl2(
            self._body_id,
            idx,
            controlMode=p.VELOCITY_CONTROL,
            targetVelocity=0,
            force=0,
            physicsClientId=self._sim.client_id,
        )
    for idx, torque_val in zip(self._joint_indices, torques):
        p.setJointMotorControl2(
            self._body_id,
            idx,
            controlMode=p.TORQUE_CONTROL,
            force=float(torque_val),
            physicsClientId=self._sim.client_id,
        )

delete() -> None

Removes the robot from the simulation.

Example::

robot.delete()
Source code in bulletlab/robot/robot.py
def delete(self) -> None:
    """Removes the robot from the simulation.

    Example::

        robot.delete()
    """
    if hasattr(self._sim, "remove_robot"):
        self._sim.remove_robot(self)
    else:
        p.removeBody(self._body_id, physicsClientId=self._sim.client_id)

get_state() -> np.ndarray

Return the full observable state as a flat NumPy array.

State vector layout::

[base_x, base_y, base_z,       # base position (3)
 base_qx, base_qy, base_qz, base_qw,  # base orientation quaternion (4)
 base_vx, base_vy, base_vz,   # base linear velocity (3)
 base_wx, base_wy, base_wz,   # base angular velocity (3)
 joint_pos_0, ...,            # controllable joint positions (N)
 joint_vel_0, ...]            # controllable joint velocities (N)

Returns:

Type Description
ndarray

1D NumPy float64 array of shape (13 + 2*N,) where N is the

ndarray

number of controllable joints.

Example::

state = robot.get_state()
action = my_policy(state)
Source code in bulletlab/robot/robot.py
def get_state(self) -> np.ndarray:
    """Return the full observable state as a flat NumPy array.

    State vector layout::

        [base_x, base_y, base_z,       # base position (3)
         base_qx, base_qy, base_qz, base_qw,  # base orientation quaternion (4)
         base_vx, base_vy, base_vz,   # base linear velocity (3)
         base_wx, base_wy, base_wz,   # base angular velocity (3)
         joint_pos_0, ...,            # controllable joint positions (N)
         joint_vel_0, ...]            # controllable joint velocities (N)

    Returns:
        1D NumPy float64 array of shape ``(13 + 2*N,)`` where N is the
        number of controllable joints.

    Example::

        state = robot.get_state()
        action = my_policy(state)
    """
    pos = list(self.base_position)
    orn = list(self.base_orientation)
    vel = list(self.base_velocity)
    avel = list(self.base_angular_velocity)

    joint_positions = []
    joint_velocities = []
    for idx in self._joint_indices:
        js = p.getJointState(self._body_id, idx, physicsClientId=self._sim.client_id)
        joint_positions.append(float(js[0]))
        joint_velocities.append(float(js[1]))

    return np.array(
        pos + orn + vel + avel + joint_positions + joint_velocities,
        dtype=np.float64,
    )

install(source: str, path: 'str | Path | None' = None) -> Path classmethod

Permanently install an Arsenal robot package to the local machine.

Downloads only the URDF and mesh files required by the requested model. Installed packages persist across Python sessions and can be loaded via a local file path afterwards.

Use :meth:load with an "arsenal:" prefix for ad-hoc loading without permanent installation.

Parameters:

Name Type Description Default
source str

One of:

  • "package_name" — install the default model.
  • "package_name/model_id" — install a specific model.
required
path 'str | Path | None'

Optional local directory to install into. When omitted, installs to ~/.bulletlab/packages/<package_name>/.

None

Returns:

Type Description
Path

class:pathlib.Path to the installed URDF file.

Raises:

Type Description
ArsenalError

On any resolution or download failure.

Example::

# Install the default model of reference_bot globally
Robot.install("reference_bot")

# Install a specific model to a project-local directory
Robot.install("reference_bot/BLem1", path="robots/")

# Load the installed robot afterwards
robot = Robot.load(
    "/home/user/.bulletlab/packages/reference_bot/BLem1.urdf",
    sim=sim,
)
Source code in bulletlab/robot/robot.py
@classmethod
def install(
    cls,
    source: str,
    path: "str | Path | None" = None,
) -> Path:
    """Permanently install an Arsenal robot package to the local machine.

    Downloads only the URDF and mesh files required by the requested model.
    Installed packages persist across Python sessions and can be loaded
    via a local file path afterwards.

    Use :meth:`load` with an ``"arsenal:"`` prefix for ad-hoc loading
    without permanent installation.

    Args:
        source: One of:

            * ``"package_name"`` — install the default model.
            * ``"package_name/model_id"`` — install a specific model.

        path: Optional local directory to install into.  When omitted,
            installs to ``~/.bulletlab/packages/<package_name>/``.

    Returns:
        :class:`pathlib.Path` to the installed URDF file.

    Raises:
        bulletlab.arsenal.ArsenalError: On any resolution or download failure.

    Example::

        # Install the default model of reference_bot globally
        Robot.install("reference_bot")

        # Install a specific model to a project-local directory
        Robot.install("reference_bot/BLem1", path="robots/")

        # Load the installed robot afterwards
        robot = Robot.load(
            "/home/user/.bulletlab/packages/reference_bot/BLem1.urdf",
            sim=sim,
        )
    """
    from bulletlab.arsenal.installer import install as _install
    return _install(source, path=path)

load(path: str | Path, sim: 'Simulation', position: tuple[float, float, float] = (0.0, 0.0, 0.0), orientation: tuple[float, float, float, float] = (0.0, 0.0, 0.0, 1.0), name: str | None = None, fixed_base: bool = False, scale: float = 1.0, flags: int = 0, tilt: 'tuple[tuple[float, float, float], float] | None' = None) -> 'Robot' classmethod

Load a robot from a URDF/MJCF file or an Arsenal package.

Automatically discovers all joints and links and exposes them by name.

Local file loading (unchanged behaviour):

Parameters:

Name Type Description Default
path str | Path

Path to the URDF/MJCF file. Can be an absolute path or a filename resolvable from the pybullet_data search path. To load from BulletLab Arsenal prefix the argument with "arsenal:" (see below).

required
sim 'Simulation'

The :class:~bulletlab.core.simulation.Simulation instance.

required
position tuple[float, float, float]

Initial base position (x, y, z) in meters.

(0.0, 0.0, 0.0)
orientation tuple[float, float, float, float]

Initial base orientation as a quaternion (x, y, z, w). Applied before tilt if both are given.

(0.0, 0.0, 0.0, 1.0)
name str | None

Human-readable robot name. Defaults to the filename stem.

None
fixed_base bool

If True, the robot's base is fixed to the world.

False
scale float

Global scale factor for the loaded model.

1.0
flags int

Additional PyBullet load flags.

0
tilt 'tuple[tuple[float, float, float], float] | None'

Optional ((ax, ay, az), angle_deg) shorthand for a single axis-angle rotation applied on top of orientation. The axis does not need to be pre-normalised.

None

Arsenal loading — prefix path with "arsenal:":

The robot is downloaded from the BulletLab Arsenal registry into a temporary session cache and loaded transparently. The cache is deleted automatically when the Python process exits.

Arsenal URI formats::

"arsenal:reference_bot"           # default model
"arsenal:reference_bot/BLem1"     # specific model

Returns:

Type Description
'Robot'

A new :class:Robot instance.

Raises:

Type Description
FileNotFoundError

If a local URDF/MJCF file cannot be found.

RuntimeError

If PyBullet fails to load the model.

ArsenalError

If Arsenal resolution or download fails.

Example::

# Local file (unchanged)
robot = Robot.load("kuka_iiwa/model.urdf", sim=sim)

# Arsenal — default model
robot = Robot.load("arsenal:reference_bot", sim=sim)

# Arsenal — specific model with spawn position
robot = Robot.load(
    "arsenal:reference_bot/BLem1",
    sim=sim,
    position=(0, 0, 0.5),
)

# Tilt 30° around the Y axis (works with both local and Arsenal)
robot = Robot.load("laikago/laikago.urdf", sim=sim,
                   tilt=((0, 1, 0), 30))
Source code in bulletlab/robot/robot.py
@classmethod
def load(
    cls,
    path: str | Path,
    sim: "Simulation",
    position: tuple[float, float, float] = (0.0, 0.0, 0.0),
    orientation: tuple[float, float, float, float] = (0.0, 0.0, 0.0, 1.0),
    name: str | None = None,
    fixed_base: bool = False,
    scale: float = 1.0,
    flags: int = 0,
    tilt: "tuple[tuple[float, float, float], float] | None" = None,
) -> "Robot":
    """Load a robot from a URDF/MJCF file or an Arsenal package.

    Automatically discovers all joints and links and exposes them by name.

    **Local file loading** (unchanged behaviour):

    Args:
        path: Path to the URDF/MJCF file.  Can be an absolute path or a
            filename resolvable from the pybullet_data search path.  To
            load from BulletLab Arsenal prefix the argument with
            ``"arsenal:"`` (see below).
        sim: The :class:`~bulletlab.core.simulation.Simulation` instance.
        position: Initial base position ``(x, y, z)`` in meters.
        orientation: Initial base orientation as a quaternion ``(x, y, z, w)``.
            Applied before ``tilt`` if both are given.
        name: Human-readable robot name.  Defaults to the filename stem.
        fixed_base: If ``True``, the robot's base is fixed to the world.
        scale: Global scale factor for the loaded model.
        flags: Additional PyBullet load flags.
        tilt: Optional ``((ax, ay, az), angle_deg)`` shorthand for a
            single axis-angle rotation applied on top of ``orientation``.
            The axis does not need to be pre-normalised.

    **Arsenal loading** — prefix ``path`` with ``"arsenal:"``:

    The robot is downloaded from the BulletLab Arsenal registry into a
    temporary session cache and loaded transparently.  The cache is
    deleted automatically when the Python process exits.

    Arsenal URI formats::

        "arsenal:reference_bot"           # default model
        "arsenal:reference_bot/BLem1"     # specific model

    Returns:
        A new :class:`Robot` instance.

    Raises:
        FileNotFoundError: If a local URDF/MJCF file cannot be found.
        RuntimeError: If PyBullet fails to load the model.
        bulletlab.arsenal.ArsenalError: If Arsenal resolution or download fails.

    Example::

        # Local file (unchanged)
        robot = Robot.load("kuka_iiwa/model.urdf", sim=sim)

        # Arsenal — default model
        robot = Robot.load("arsenal:reference_bot", sim=sim)

        # Arsenal — specific model with spawn position
        robot = Robot.load(
            "arsenal:reference_bot/BLem1",
            sim=sim,
            position=(0, 0, 0.5),
        )

        # Tilt 30° around the Y axis (works with both local and Arsenal)
        robot = Robot.load("laikago/laikago.urdf", sim=sim,
                           tilt=((0, 1, 0), 30))
    """
    import math as _math

    path_str = str(path)

    # ── Arsenal URI handling ──────────────────────────────────────────────
    if path_str.startswith("arsenal:"):
        arsenal_source = path_str[len("arsenal:"):]
        path_str = cls._load_from_arsenal(arsenal_source)
        if name is None:
            # Derive name from the package portion of the URI
            name = arsenal_source.split("/")[0]

    if not sim.is_connected:
        sim.start()

    robot_name = name or Path(path_str).stem

    # ── Resolve final orientation ─────────────────────────────────────────
    if tilt is not None:
        axis, angle_deg = tilt
        ax, ay, az = axis
        # Normalise
        length = _math.sqrt(ax**2 + ay**2 + az**2)
        if length > 1e-9:
            ax, ay, az = ax / length, ay / length, az / length
        half = _math.radians(angle_deg) / 2.0
        s = _math.sin(half)
        tq = (ax * s, ay * s, az * s, _math.cos(half))   # tilt quaternion

        # Compose: final = tilt * base_orientation
        # q_mul(a, b): (a.xyz cross b.xyz + a.w*b.xyz + b.w*a.xyz, a.w*b.w - a.xyz·b.xyz)
        ax1, ay1, az1, aw1 = tq
        bx, by, bz, bw = orientation
        cx = aw1*bx + ax1*bw + ay1*bz - az1*by
        cy = aw1*by - ax1*bz + ay1*bw + az1*bx
        cz = aw1*bz + ax1*by - ay1*bx + az1*bw
        cw = aw1*bw - ax1*bx - ay1*by - az1*bz
        orientation = (cx, cy, cz, cw)

    path_obj = Path(path_str)
    ext = path_obj.suffix.lower()

    with SuppressOutput():
        if ext in (".urdf",):
            body_id = p.loadURDF(
                path_str,
                basePosition=list(position),
                baseOrientation=list(orientation),
                useFixedBase=fixed_base,
                globalScaling=scale,
                flags=flags,
                physicsClientId=sim.client_id,
            )
        elif ext in (".xml", ".mjcf"):
            # MJCF: position/orientation not directly supported at load time
            body_ids = p.loadMJCF(
                path_str,
                physicsClientId=sim.client_id,
            )
            body_id = body_ids[0] if isinstance(body_ids, (list, tuple)) else body_ids
        else:
            # Try URDF by default
            body_id = p.loadURDF(
                path_str,
                basePosition=list(position),
                baseOrientation=list(orientation),
                useFixedBase=fixed_base,
                globalScaling=scale,
                flags=flags,
                physicsClientId=sim.client_id,
            )

    robot = cls(
        body_id=body_id,
        sim=sim,
        name=robot_name,
        initial_position=position,
        initial_orientation=orientation,
    )
    sim.add_robot(robot)
    return robot

reset(position: tuple[float, float, float] | None = None, orientation: tuple[float, float, float, float] | None = None) -> None

Reset the robot to its initial (or specified) pose.

Also resets all joint positions and velocities to zero.

Parameters:

Name Type Description Default
position tuple[float, float, float] | None

Target base position. Defaults to initial load position.

None
orientation tuple[float, float, float, float] | None

Target base orientation. Defaults to initial load orientation.

None

Example::

robot.reset()
robot.reset(position=(0, 0, 1), orientation=(0, 0, 0, 1))
Source code in bulletlab/robot/robot.py
def reset(
    self,
    position: tuple[float, float, float] | None = None,
    orientation: tuple[float, float, float, float] | None = None,
) -> None:
    """Reset the robot to its initial (or specified) pose.

    Also resets all joint positions and velocities to zero.

    Args:
        position: Target base position. Defaults to initial load position.
        orientation: Target base orientation. Defaults to initial load orientation.

    Example::

        robot.reset()
        robot.reset(position=(0, 0, 1), orientation=(0, 0, 0, 1))
    """
    pos = position if position is not None else self._initial_position
    orn = orientation if orientation is not None else self._initial_orientation

    p.resetBasePositionAndOrientation(
        self._body_id,
        list(pos),
        list(orn),
        physicsClientId=self._sim.client_id,
    )
    p.resetBaseVelocity(
        self._body_id,
        [0, 0, 0],
        [0, 0, 0],
        physicsClientId=self._sim.client_id,
    )
    for joint in self._joints.values():
        if not joint.is_fixed:
            joint.reset(pos=0.0, vel=0.0)

scale(factor: float) -> None

Scale the robot. (Requires re-loading in PyBullet)

Source code in bulletlab/robot/robot.py
def scale(self, factor: float) -> None:
    """Scale the robot. (Requires re-loading in PyBullet)"""
    raise NotImplementedError("Dynamic scaling of existing robots is not yet supported in PyBullet.")

set_dynamics(link: str | None = None, mass: float | None = None, lateral_friction: float | None = None, spinning_friction: float | None = None, rolling_friction: float | None = None, restitution: float | None = None, linear_damping: float | None = None, angular_damping: float | None = None, contact_stiffness: float | None = None, contact_damping: float | None = None) -> None

Change physics/dynamics parameters for a link at runtime.

Only the parameters you pass are changed — unspecified ones are left at their current PyBullet values.

Parameters:

Name Type Description Default
link str | None

Link name. None = base link.

None
mass float | None

New mass in kg.

None
lateral_friction float | None

Coulomb friction coefficient.

None
spinning_friction float | None

Friction around the contact normal.

None
rolling_friction float | None

Rolling friction coefficient.

None
restitution float | None

Bounciness [0, 1].

None
linear_damping float | None

Linear velocity damping [0, 1].

None
angular_damping float | None

Angular velocity damping [0, 1].

None
contact_stiffness float | None

Contact ERP stiffness (advanced).

None
contact_damping float | None

Contact ERP damping (advanced).

None

Example::

# Make wheels grippier
robot.set_dynamics("wheel_fl", lateral_friction=1.5)

# Change body mass on-the-fly
robot.set_dynamics(mass=3.0)

# Make everything bouncy
for name in robot.links:
    robot.set_dynamics(name, restitution=0.8)
Source code in bulletlab/robot/robot.py
def set_dynamics(
    self,
    link: str | None = None,
    mass: float | None = None,
    lateral_friction: float | None = None,
    spinning_friction: float | None = None,
    rolling_friction: float | None = None,
    restitution: float | None = None,
    linear_damping: float | None = None,
    angular_damping: float | None = None,
    contact_stiffness: float | None = None,
    contact_damping: float | None = None,
) -> None:
    """Change physics/dynamics parameters for a link at runtime.

    Only the parameters you pass are changed — unspecified ones are left
    at their current PyBullet values.

    Args:
        link: Link name.  ``None`` = base link.
        mass: New mass in kg.
        lateral_friction: Coulomb friction coefficient.
        spinning_friction: Friction around the contact normal.
        rolling_friction: Rolling friction coefficient.
        restitution: Bounciness ``[0, 1]``.
        linear_damping: Linear velocity damping ``[0, 1]``.
        angular_damping: Angular velocity damping ``[0, 1]``.
        contact_stiffness: Contact ERP stiffness (advanced).
        contact_damping: Contact ERP damping (advanced).

    Example::

        # Make wheels grippier
        robot.set_dynamics("wheel_fl", lateral_friction=1.5)

        # Change body mass on-the-fly
        robot.set_dynamics(mass=3.0)

        # Make everything bouncy
        for name in robot.links:
            robot.set_dynamics(name, restitution=0.8)
    """
    cid = self._sim.client_id

    if link is None:
        link_index = -1
    else:
        lobj = self._links.get(link)
        if lobj is None:
            raise ValueError(f"Link {link!r} not found. Available: {list(self._links.keys())}")
        link_index = lobj.index

    kwargs: dict = {}
    if mass               is not None: kwargs["mass"]              = float(mass)
    if lateral_friction   is not None: kwargs["lateralFriction"]  = float(lateral_friction)
    if spinning_friction  is not None: kwargs["spinningFriction"]  = float(spinning_friction)
    if rolling_friction   is not None: kwargs["rollingFriction"]   = float(rolling_friction)
    if restitution        is not None: kwargs["restitution"]       = float(restitution)
    if linear_damping     is not None: kwargs["linearDamping"]     = float(linear_damping)
    if angular_damping    is not None: kwargs["angularDamping"]    = float(angular_damping)
    if contact_stiffness  is not None: kwargs["contactStiffness"]  = float(contact_stiffness)
    if contact_damping    is not None: kwargs["contactDamping"]    = float(contact_damping)

    if kwargs:
        p.changeDynamics(
            self._body_id,
            link_index,
            physicsClientId=cid,
            **kwargs,
        )

tilt(axis: str, degrees: float) -> None

Rotates the robot around 'x', 'y', or 'z' axis.

Example::

robot.tilt('z', 90)
Source code in bulletlab/robot/robot.py
def tilt(self, axis: str, degrees: float) -> None:
    """Rotates the robot around 'x', 'y', or 'z' axis.

    Example::

        robot.tilt('z', 90)
    """
    axis = axis.lower()
    if axis not in ('x', 'y', 'z'):
        raise ValueError("axis must be 'x', 'y', or 'z'")

    rads = math.radians(degrees)
    euler = list(self.base_orientation_euler)
    if axis == 'x': euler[0] += rads
    elif axis == 'y': euler[1] += rads
    elif axis == 'z': euler[2] += rads

    from bulletlab.utils.math_utils import euler_to_quaternion
    orn = euler_to_quaternion(*euler)

    p.resetBasePositionAndOrientation(
        self._body_id,
        list(self.base_position),
        list(orn),
        physicsClientId=self._sim.client_id,
    )