From 3d00c6f17af3b168b82fbda666e7b4361adaf86c Mon Sep 17 00:00:00 2001 From: Peter Corke Date: Tue, 3 Nov 2026 09:37:37 +1000 Subject: [PATCH 1/4] feat(backends): a registry of backends by name load_backend() was an if/elif over three names. The names are now entries in a registry, and register_backend() adds more: a lazy "module:Class" string, which is imported only when the backend is chosen, or a callable that returns one. Names are not case sensitive. An unknown name lists the registered ones, and a missing package names the pip extra. This is groundwork for #886, so a backend can be developed and used outside the Toolbox. Part of #902. No change to what the built-in backends do. Co-Authored-By: Claude Sonnet 5.5 --- src/roboticstoolbox/backends/__init__.py | 43 +----- src/roboticstoolbox/backends/registry.py | 156 +++++++++++++++++++++ tests/test_backend_registry.py | 170 +++++++++++++++++++++++ 3 files changed, 332 insertions(+), 37 deletions(-) create mode 100644 src/roboticstoolbox/backends/registry.py create mode 100644 tests/test_backend_registry.py diff --git a/src/roboticstoolbox/backends/__init__.py b/src/roboticstoolbox/backends/__init__.py index c92f3dd8c..8679415ee 100644 --- a/src/roboticstoolbox/backends/__init__.py +++ b/src/roboticstoolbox/backends/__init__.py @@ -1,39 +1,8 @@ from roboticstoolbox.backends.Connector import Connector +from roboticstoolbox.backends.registry import ( + load_backend, + register_backend, + registered_backends, +) - -def load_backend(name: str) -> Connector: - """ - Instantiate a graphical backend by name. - - Parameters - ---------- - name - Backend identifier: ``'swift'``, ``'pyplot'``, or ``'pyplot2'``. - - Returns - ------- - Connector - An instantiated backend ready for ``.launch()``. - - Raises - ------ - ModuleNotFoundError - If the requested backend's package is not installed (e.g. ``swift`` - when ``swift-sim`` is not present). - ValueError - If ``name`` is not a known backend. - """ - if name == "swift": - from roboticstoolbox.backends.swift import Swift # optional dep - - return Swift() - elif name == "pyplot": - from roboticstoolbox.backends.PyPlot import PyPlot - - return PyPlot() - elif name == "pyplot2": - from roboticstoolbox.backends.PyPlot import PyPlot2 - - return PyPlot2() - else: - raise ValueError(f"Unknown graphical backend: {name!r}") +__all__ = ["Connector", "load_backend", "register_backend", "registered_backends"] diff --git a/src/roboticstoolbox/backends/registry.py b/src/roboticstoolbox/backends/registry.py new file mode 100644 index 000000000..e3ce4b354 --- /dev/null +++ b/src/roboticstoolbox/backends/registry.py @@ -0,0 +1,156 @@ +""" +The registry of graphical backends: the names a backend can be asked for by, and +how to make each one. + +``robot.plot(q, backend="swift")`` looks the name up here. A backend that ships +with the Toolbox is an entry in the table below; a backend from anywhere else is +added with :func:`register_backend`. +""" + +from __future__ import annotations + +import importlib +from collections.abc import Callable +from dataclasses import dataclass +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from roboticstoolbox.backends.Connector import Connector + + +@dataclass(frozen=True) +class _Entry: + #: ``"module:Class"``, imported only when the backend is chosen, or a callable + #: that returns a backend + target: str | Callable[[], Connector] + #: the pip extra that provides the backend's package, or None + extra: str | None = None + + +_registry: dict[str, _Entry] = {} + + +def _normalise(name: str) -> str: + """Backend names are not case sensitive, and surrounding spaces do not count.""" + if not isinstance(name, str): + raise TypeError(f"a backend name is a string, not {type(name).__name__}") + return name.strip().lower() + + +def register_backend( + name: str, + target: str | Callable[[], Connector], + *, + replace: bool = False, + extra: str | None = None, +) -> None: + """ + Make a graphical backend available by name + + ``register_backend("mine", "my_package.module:MyBackend")`` lets + ``robot.plot(q, backend="mine")`` use it. The registration lasts for this + process, so call it before ``plot()``. It is how a backend can be developed, + tested and used outside the Toolbox, and how one that cannot live in it (a + licence, a GPU) can be kept as a package of its own. + + :param name: name to give the backend, which is not case sensitive + :param target: either a string ``"module:Class"``, which is imported only when + the backend is chosen, so registering it costs nothing and the package need + not be installed; or a callable, such as a class or a function, that returns + a backend each time it is called + :param replace: replace the backend if the name is already registered + :param extra: the pip extra of ``roboticstoolbox-python`` that installs the + backend's package, used to say so if the package is missing + :raises ValueError: the name is empty, ``target`` is a string that is not of the + form ``"module:Class"``, or the name is registered and ``replace`` is False + :raises TypeError: ``name`` is not a string, or ``target`` is neither a string + nor callable + + .. seealso:: :func:`load_backend`, :func:`registered_backends` + + .. versionadded:: 1.5.1 + """ + key = _normalise(name) + if not key: + raise ValueError("a backend needs a name") + + if isinstance(target, str): + module, _, attribute = target.partition(":") + if not module or not attribute or ":" in attribute: + raise ValueError( + f"the target of backend {name!r} is {target!r}, which is not of " + 'the form "module:Class"' + ) + elif not callable(target): + raise TypeError( + f"the target of backend {name!r} is a string such as " + f'"module:Class" or a callable, not {type(target).__name__}' + ) + + if key in _registry and not replace: + raise ValueError( + f"backend {key!r} is already registered, use replace=True to replace it" + ) + _registry[key] = _Entry(target, extra) + + +def registered_backends() -> list[str]: + """ + The names of the registered graphical backends + + :returns: the names, in alphabetical order + + .. seealso:: :func:`register_backend` + + .. versionadded:: 1.5.1 + """ + return sorted(_registry) + + +def load_backend(name: str) -> Connector: + """ + Make a graphical backend from its name + + The name is not case sensitive. A backend given as ``"module:Class"`` is + imported now, not when it was registered. + + :param name: a registered backend, such as ``"swift"``, ``"pyplot"`` or + ``"pyplot2"``, see :func:`registered_backends` + :returns: a backend, ready for ``launch()`` + :raises ValueError: ``name`` is not registered + :raises ModuleNotFoundError: the package that provides the backend is not + installed, such as ``swift-sim`` for ``"swift"``; the message names the pip + extra if there is one + + .. seealso:: :func:`register_backend` + """ + key = _normalise(name) + try: + entry = _registry[key] + except KeyError: + raise ValueError( + f"Unknown graphical backend: {name!r}. " + f"The registered backends are: {', '.join(registered_backends())}" + ) from None + + if callable(entry.target): + return entry.target() + + module_name, _, attribute = entry.target.partition(":") + try: + module = importlib.import_module(module_name) + except ModuleNotFoundError as err: + if entry.extra is None: + raise + raise ModuleNotFoundError( + f"the {key!r} backend needs a package that is not installed ({err}): " + f"pip install roboticstoolbox-python[{entry.extra}]", + name=err.name, + ) from err + return getattr(module, attribute)() + + +# the backends that come with the Toolbox +register_backend("swift", "roboticstoolbox.backends.swift:Swift", extra="swift") +register_backend("pyplot", "roboticstoolbox.backends.PyPlot:PyPlot") +register_backend("pyplot2", "roboticstoolbox.backends.PyPlot:PyPlot2") diff --git a/tests/test_backend_registry.py b/tests/test_backend_registry.py new file mode 100644 index 000000000..5ea294040 --- /dev/null +++ b/tests/test_backend_registry.py @@ -0,0 +1,170 @@ +"""The registry of graphical backends: lookup, registration and the errors""" + +from collections import OrderedDict + +import pytest + +from roboticstoolbox.backends import ( + load_backend, + register_backend, + registered_backends, + registry, +) + + +class FakeBackend: + """Stands in for a backend: the registry only makes one, it does not use it.""" + + +@pytest.fixture(autouse=True) +def private_registry(monkeypatch): + """Registrations made by a test are gone when it ends.""" + monkeypatch.setattr(registry, "_registry", dict(registry._registry)) + + +# --------------------------------------------------------------------------- +# the built-in backends +# --------------------------------------------------------------------------- + + +def test_the_builtin_backends_are_registered() -> None: + assert {"pyplot", "pyplot2", "swift"} <= set(registered_backends()) + + +def test_registered_backends_are_sorted() -> None: + names = registered_backends() + assert names == sorted(names) + + +@pytest.mark.parametrize("name", ["pyplot", "PyPlot", " PYPLOT "]) +def test_a_builtin_is_found_whatever_its_case(name) -> None: + from roboticstoolbox.backends.PyPlot import PyPlot + + assert isinstance(load_backend(name), PyPlot) + + +def test_pyplot2_is_a_different_backend() -> None: + from roboticstoolbox.backends.PyPlot import PyPlot2 + + assert isinstance(load_backend("pyplot2"), PyPlot2) + + +# --------------------------------------------------------------------------- +# errors in lookup +# --------------------------------------------------------------------------- + + +def test_an_unknown_name_lists_the_registered_ones() -> None: + with pytest.raises(ValueError, match="Unknown graphical backend: 'nope'") as info: + load_backend("nope") + for name in registered_backends(): + assert name in str(info.value) + + +def test_a_name_that_is_not_a_string_is_a_type_error() -> None: + with pytest.raises(TypeError, match="not int"): + load_backend(3) # type: ignore[arg-type] + + +def test_a_missing_package_names_the_pip_extra() -> None: + register_backend("lost", "no_such_package_xyz:Thing", extra="lost-extra") + with pytest.raises( + ModuleNotFoundError, match=r"roboticstoolbox-python\[lost-extra\]" + ): + load_backend("lost") + + +def test_a_missing_package_with_no_extra_is_the_import_error_itself() -> None: + register_backend("lost", "no_such_package_xyz:Thing") + with pytest.raises(ModuleNotFoundError, match="no_such_package_xyz") as info: + load_backend("lost") + assert "pip install" not in str(info.value) + + +# --------------------------------------------------------------------------- +# register_backend +# --------------------------------------------------------------------------- + + +def test_a_string_target_is_not_imported_until_it_is_chosen() -> None: + # registering a package that is not installed is fine: nothing is imported + register_backend("later", "no_such_package_xyz:Thing") + assert "later" in registered_backends() + + +def test_a_string_target_is_imported_when_chosen() -> None: + register_backend("od", "collections:OrderedDict") + assert isinstance(load_backend("od"), OrderedDict) + + +def test_a_class_target() -> None: + register_backend("fake", FakeBackend) + assert isinstance(load_backend("fake"), FakeBackend) + + +def test_a_function_target_is_called_for_each_backend() -> None: + register_backend("fake", lambda: FakeBackend()) # type: ignore[arg-type, return-value] + assert load_backend("fake") is not load_backend("fake") + + +def test_a_registered_name_is_found_whatever_its_case() -> None: + register_backend("MyBackend", FakeBackend) + assert "mybackend" in registered_backends() + assert isinstance(load_backend("MYBACKEND"), FakeBackend) + + +def test_a_name_registered_twice_is_an_error() -> None: + register_backend("fake", FakeBackend) + with pytest.raises(ValueError, match="already registered"): + register_backend("fake", FakeBackend) + + +def test_the_duplicate_check_ignores_case() -> None: + register_backend("fake", FakeBackend) + with pytest.raises(ValueError, match="already registered"): + register_backend("FAKE", FakeBackend) + + +def test_a_builtin_cannot_be_replaced_by_accident() -> None: + with pytest.raises(ValueError, match="already registered"): + register_backend("pyplot", FakeBackend) + + +def test_replace_true_replaces_the_backend() -> None: + register_backend("fake", "collections:OrderedDict") + register_backend("fake", FakeBackend, replace=True) + assert isinstance(load_backend("fake"), FakeBackend) + + +def test_replace_true_can_replace_a_builtin() -> None: + register_backend("pyplot", FakeBackend, replace=True) + assert isinstance(load_backend("pyplot"), FakeBackend) + + +@pytest.mark.parametrize("name", ["", " "]) +def test_an_empty_name_is_an_error(name) -> None: + with pytest.raises(ValueError, match="needs a name"): + register_backend(name, FakeBackend) + + +def test_a_name_that_is_not_a_string_cannot_be_registered() -> None: + with pytest.raises(TypeError): + register_backend(3, FakeBackend) # type: ignore[arg-type] + + +@pytest.mark.parametrize("target", ["nocolon", ":Class", "module:", "a:b:c", ""]) +def test_a_string_target_must_be_module_colon_class(target) -> None: + with pytest.raises(ValueError, match="module:Class"): + register_backend("fake", target) + + +def test_a_target_that_is_neither_string_nor_callable() -> None: + with pytest.raises(TypeError, match="not int"): + register_backend("fake", 42) # type: ignore[arg-type] + + +def test_a_failed_registration_leaves_the_registry_alone() -> None: + before = registered_backends() + with pytest.raises(ValueError): + register_backend("fake", "nocolon") + assert registered_backends() == before From 29eee9417aa6f3f9a81a8871ac5843ea08a3f5a8 Mon Sep 17 00:00:00 2001 From: Peter Corke Date: Tue, 3 Nov 2026 09:38:38 +1000 Subject: [PATCH 2/4] refactor(robot): backend names are not case sensitive, and are plain strings robot.default_backend = "Swift" was kept as given and failed with ValueError at plot time. The name is now normalised where it is set (default_backend and set_default_backend) and where it is given (plot and teach), by one function in the registry. A name that is not a string is a TypeError where it is set. The backend argument of plot() and teach() was Literal["swift", "pyplot", "pyplot2"], which would reject a registered backend; it is now str, checked at runtime against the registry. Part of #902. Supersedes the lower-casing in #904. Co-Authored-By: Claude Sonnet 5.5 --- src/roboticstoolbox/backends/registry.py | 6 +-- src/roboticstoolbox/robot/BaseRobot.py | 32 +++++++------ tests/test_default_backend.py | 60 ++++++++++++++++++++++++ 3 files changed, 81 insertions(+), 17 deletions(-) diff --git a/src/roboticstoolbox/backends/registry.py b/src/roboticstoolbox/backends/registry.py index e3ce4b354..e946054cf 100644 --- a/src/roboticstoolbox/backends/registry.py +++ b/src/roboticstoolbox/backends/registry.py @@ -30,7 +30,7 @@ class _Entry: _registry: dict[str, _Entry] = {} -def _normalise(name: str) -> str: +def normalise_backend_name(name: str) -> str: """Backend names are not case sensitive, and surrounding spaces do not count.""" if not isinstance(name, str): raise TypeError(f"a backend name is a string, not {type(name).__name__}") @@ -70,7 +70,7 @@ def register_backend( .. versionadded:: 1.5.1 """ - key = _normalise(name) + key = normalise_backend_name(name) if not key: raise ValueError("a backend needs a name") @@ -124,7 +124,7 @@ def load_backend(name: str) -> Connector: .. seealso:: :func:`register_backend` """ - key = _normalise(name) + key = normalise_backend_name(name) try: entry = _registry[key] except KeyError: diff --git a/src/roboticstoolbox/robot/BaseRobot.py b/src/roboticstoolbox/robot/BaseRobot.py index 9a9f0f7d0..16650b2fa 100644 --- a/src/roboticstoolbox/robot/BaseRobot.py +++ b/src/roboticstoolbox/robot/BaseRobot.py @@ -37,6 +37,7 @@ import roboticstoolbox as rtb from roboticstoolbox.backends.Connector import Connector +from roboticstoolbox.backends.registry import normalise_backend_name from roboticstoolbox.ets.ET import ET from roboticstoolbox.ets.ETS import ETS from roboticstoolbox.ets.fknm import Robot_link_T @@ -85,7 +86,7 @@ class BaseRobot(SceneNode, DynamicsMixin, RobotPlottingMPLMixin, ABC, Generic[Li #: default graphical backend for every robot of this class, used when the #: robot has not been given its own, see :meth:`set_default_backend` - _class_default_backend: Any = None + _class_default_backend: str | None = None def __init__( self, @@ -218,7 +219,7 @@ def __init__( # SceneNode, set a reference to the first link self.scene_children = [self.links[0]] - self._default_backend = None + self._default_backend: str | None = None self._active_plot_env: Any = None # --------------------------------------------------------------------- # @@ -866,7 +867,7 @@ def hascollision(self) -> Any: return self._hascollision @property - def default_backend(self) -> Any: + def default_backend(self) -> str | None: """ Get default graphical backend @@ -877,6 +878,7 @@ def default_backend(self) -> Any: - ``robot.default_backend = ...`` Set the default graphical backend, used when no explicit backend is passed to ``Robot.plot``. The default set here will be overridden if the particular ``Robot`` subclass cannot support it. + The name is not case sensitive. :returns: backend name """ @@ -885,15 +887,16 @@ def default_backend(self) -> Any: return self._class_default_backend @default_backend.setter - def default_backend(self, be: Any) -> None: - self._default_backend = be + def default_backend(self, be: str | None) -> None: + self._default_backend = None if be is None else normalise_backend_name(be) @classmethod - def set_default_backend(cls, be: Any) -> None: + def set_default_backend(cls, be: str | None) -> None: """ Set the default graphical backend for all robots - :param be: backend name, for example ``"swift"``, or ``None`` to clear + :param be: backend name, for example ``"swift"``, which is not case + sensitive, or ``None`` to clear ``Robot.set_default_backend("swift")`` sets the backend used by :meth:`plot` for every robot, existing or created later, that has not @@ -902,7 +905,7 @@ def set_default_backend(cls, be: Any) -> None: .. seealso:: :attr:`default_backend` """ - cls._class_default_backend = be + cls._class_default_backend = None if be is None else normalise_backend_name(be) @property def gravity(self) -> NDArray: @@ -1983,15 +1986,16 @@ def get_link_scene_node() -> Any: def _get_graphical_backend( self, - backend: L["swift", "pyplot", "pyplot2"] | None = None, + backend: str | None = None, ) -> Connector: import sys from roboticstoolbox.backends import load_backend # Resolve which backend name to use + using_backend: str | None if backend is not None: - using_backend = backend.lower() + using_backend = normalise_backend_name(backend) else: # In JupyterLite/Pyodide, only pyplot/pyplot2 are available if sys.platform == "emscripten": @@ -2034,7 +2038,7 @@ def _get_graphical_backend( def plot( self, q: ArrayLike, - backend: L["swift", "pyplot", "pyplot2"] | None = None, + backend: str | None = None, block: bool = False, dt: float = 0.05, limits: ArrayLike | None = None, @@ -2062,7 +2066,7 @@ def plot( animation with a pause of ``dt`` seconds between each frame. :param q: The joint configuration of the robot. - :param backend: The graphical backend to use, currently 'swift' and 'pyplot' are implemented. Defaults to 'swift' of a ``Robot`` and 'pyplot` for a ``DHRobot`` + :param backend: The graphical backend to use, by name: 'swift', 'pyplot' or 'pyplot2', or one added by :func:`~roboticstoolbox.backends.register_backend`, see :func:`~roboticstoolbox.backends.registered_backends`. The name is not case sensitive. Defaults to 'swift' of a ``Robot`` and 'pyplot` for a ``DHRobot`` :param block: ``True`` waits until the window is closed; the PyPlot backend has already shown the figure, so ``False`` and ``None`` return at once, defaults to False @@ -2319,7 +2323,7 @@ def teach( limits: ArrayLike | None = None, vellipse: bool = False, fellipse: bool = False, - backend: L["swift", "pyplot", "pyplot2"] | None = None, + backend: str | None = None, view: str | None = None, ) -> Connector: """ @@ -2346,7 +2350,7 @@ def teach( :param fellipse: (Plot Option) Plot the force ellipse at the end-effector (this option is for 'pyplot' only) :param backend: The graphical backend to use -- 'swift', 'pyplot', - or 'pyplot2'. Defaults to whatever :meth:`plot` would pick for + 'pyplot2' or a registered name. Defaults to whatever :meth:`plot` would pick for this robot (see its own ``backend`` for the resolution rule). :param view: ``"xy"``, ``"xz"`` or ``"yz"`` to start with a flat view of that plane, the first axis to the right and the second up, or ``None`` diff --git a/tests/test_default_backend.py b/tests/test_default_backend.py index af84cee9b..bda4aed31 100644 --- a/tests/test_default_backend.py +++ b/tests/test_default_backend.py @@ -43,3 +43,63 @@ def test_class_default_can_be_cleared(restore_class_default) -> None: Robot.set_default_backend("swift") Robot.set_default_backend(None) assert rtb.models.DH.Puma560().default_backend is None + + +# the names are not case sensitive, wherever they are given + + +def test_the_robot_default_is_stored_in_lower_case() -> None: + robot = rtb.models.DH.Puma560() + robot.default_backend = "Swift" + assert robot.default_backend == "swift" + + +def test_the_class_default_is_stored_in_lower_case(restore_class_default) -> None: + Robot.set_default_backend("PyPlot2") + assert rtb.models.DH.Puma560().default_backend == "pyplot2" + + +def test_a_default_given_in_upper_case_selects_the_backend( + restore_class_default, +) -> None: + from roboticstoolbox.backends.PyPlot import PyPlot2 + + Robot.set_default_backend("PYPLOT2") + assert isinstance(rtb.models.DH.Puma560()._get_graphical_backend(), PyPlot2) + + +def test_an_explicit_backend_in_upper_case() -> None: + from roboticstoolbox.backends.PyPlot import PyPlot + + robot = rtb.models.DH.Puma560() + assert isinstance(robot._get_graphical_backend("PyPlot"), PyPlot) + + +def test_the_default_can_be_cleared_on_a_robot() -> None: + robot = rtb.models.DH.Puma560() + robot.default_backend = "pyplot2" + robot.default_backend = None + assert robot.default_backend is None + + +def test_a_default_that_is_not_a_name_is_a_type_error(restore_class_default) -> None: + robot = rtb.models.DH.Puma560() + with pytest.raises(TypeError): + robot.default_backend = 3 # type: ignore[assignment] + with pytest.raises(TypeError): + Robot.set_default_backend(3) # type: ignore[arg-type] + + +def test_a_registered_backend_can_be_the_default( + restore_class_default, monkeypatch +) -> None: + from roboticstoolbox.backends import register_backend, registry + + class Fake: + pass + + monkeypatch.setattr(registry, "_registry", dict(registry._registry)) + register_backend("Fake", Fake) + robot = rtb.models.DH.Puma560() + robot.default_backend = "FAKE" + assert isinstance(robot._get_graphical_backend(), Fake) From c98f5c864ddadecfea3836bc182a097dd6317442 Mon Sep 17 00:00:00 2001 From: Peter Corke Date: Tue, 3 Nov 2026 09:39:52 +1000 Subject: [PATCH 3/4] refactor(robot): plot() asks a backend what it can do, not what class it is plot() recognised Swift by type(env).__name__ == "Swift" and PyPlot by isinstance, so a new backend could not be a web page shown in a notebook, or make a movie, without being named or derived like one of them. Two flags on Connector, both False by default, replace the checks: - embeds_in_notebook: the backend is a web page that can be shown in the cell of a notebook (set by Swift), which plot() asks for in a notebook, and paces an animation in real time - supports_movie: the backend has getframe() (set by PyPlot) They are read with getattr, as supports_teach and supports_ellipse are, so a backend that does not inherit from Connector, as Swift does not, need not define them. Behaviour of the built-in backends is unchanged. Part of #902. Co-Authored-By: Claude Sonnet 5.5 --- src/roboticstoolbox/backends/Connector.py | 9 ++ src/roboticstoolbox/backends/PyPlot/PyPlot.py | 1 + .../backends/swift/__init__.py | 1 + src/roboticstoolbox/robot/BaseRobot.py | 16 ++-- tests/test_backend_flags.py | 96 +++++++++++++++++++ tests/test_swift_plot_options.py | 4 +- 6 files changed, 117 insertions(+), 10 deletions(-) create mode 100644 tests/test_backend_flags.py diff --git a/src/roboticstoolbox/backends/Connector.py b/src/roboticstoolbox/backends/Connector.py index 1f457760d..b304731a0 100644 --- a/src/roboticstoolbox/backends/Connector.py +++ b/src/roboticstoolbox/backends/Connector.py @@ -28,6 +28,15 @@ class Connector(ABC): #: True if the backend can render EllipsePlot objects. supports_ellipse: bool = False + #: True if the backend is a web page that can be shown in the output of a + #: notebook cell, as well as in a browser window of its own. ``plot`` then + #: asks for that in a notebook, and paces an animation in real time. + embeds_in_notebook: bool = False + + #: True if the backend can give back a picture of the scene as ``getframe()``, + #: so that ``plot`` can save an animation as a movie. + supports_movie: bool = False + # # Basic methods to do with the state of the external program # diff --git a/src/roboticstoolbox/backends/PyPlot/PyPlot.py b/src/roboticstoolbox/backends/PyPlot/PyPlot.py index 9cfc33bb6..d4aa97b94 100644 --- a/src/roboticstoolbox/backends/PyPlot/PyPlot.py +++ b/src/roboticstoolbox/backends/PyPlot/PyPlot.py @@ -88,6 +88,7 @@ class PyPlot(Connector): """ supports_ellipse: bool = True + supports_movie: bool = True ax: Any # the 3D Matplotlib axes, set by launch() fig: Any # the Matplotlib figure, set by launch() diff --git a/src/roboticstoolbox/backends/swift/__init__.py b/src/roboticstoolbox/backends/swift/__init__.py index 0a39fc738..2ee663d8f 100644 --- a/src/roboticstoolbox/backends/swift/__init__.py +++ b/src/roboticstoolbox/backends/swift/__init__.py @@ -23,6 +23,7 @@ class Swift(_SwiftBase, Connector): supports_teach: bool = True supports_ellipse: bool = False + embeds_in_notebook: bool = True def _add_teach_panel( self, robot: Any, q: Any, handle: Any = None, block: bool = True diff --git a/src/roboticstoolbox/robot/BaseRobot.py b/src/roboticstoolbox/robot/BaseRobot.py index 16650b2fa..3fce73960 100644 --- a/src/roboticstoolbox/robot/BaseRobot.py +++ b/src/roboticstoolbox/robot/BaseRobot.py @@ -2149,9 +2149,6 @@ def plot( elif ax is not None: raise ValueError("ax and env cannot both be given: the scene has axes") - if movie is not None: - from roboticstoolbox.backends.PyPlot import PyPlot - launch_kwargs: dict[str, Any] = {} for key in ( "render_mode", @@ -2204,9 +2201,9 @@ def plot( # frame of the cell, not in a browser window of its own. An animation is paced # in real time, one step to each dt: unpaced, Swift draws at most 60 frames # per second and skips the steps that come sooner, so the whole trajectory runs - # in a few milliseconds and only its first frame is ever drawn. - is_swift = type(env).__name__ == "Swift" - if is_swift and not adding: + # in a few milliseconds and only its first frame is ever drawn. A backend that + # is a web page says so with embeds_in_notebook. + if getattr(env, "embeds_in_notebook", False) and not adding: from roboticstoolbox.backends.PyPlot.PyPlot import _isnotebook if launch_kwargs.get("browser") == "notebook": @@ -2292,8 +2289,11 @@ def plot( fell.q = qk env.step(dt) - if movie is not None and isinstance(env, PyPlot): # pragma nocover - images.append(env.getframe()) + if movie is not None and getattr( + env, "supports_movie", False + ): # pragma nocover + # getframe is not part of the Connector interface (#676) + images.append(env.getframe()) # type: ignore[attr-defined] if movie is not None: # pragma nocover # save it as an animated GIF diff --git a/tests/test_backend_flags.py b/tests/test_backend_flags.py new file mode 100644 index 000000000..6fdba03ec --- /dev/null +++ b/tests/test_backend_flags.py @@ -0,0 +1,96 @@ +"""The capability flags plot() reads from a backend, instead of checking its class""" + +import importlib +import types + +import pytest + +import roboticstoolbox as rtb +from roboticstoolbox.backends.Connector import Connector +from roboticstoolbox.backends.PyPlot import PyPlot, PyPlot2 + +# the package also exports a class called PyPlot, so ask for the module by name +pyplot_module = importlib.import_module("roboticstoolbox.backends.PyPlot.PyPlot") + + +# --- the flags and their defaults ------------------------------------------------------ + + +@pytest.mark.parametrize("flag", ["embeds_in_notebook", "supports_movie"]) +def test_a_backend_has_neither_ability_unless_it_says_so(flag) -> None: + assert getattr(Connector, flag) is False + + +def test_pyplot_can_make_a_movie() -> None: + assert PyPlot.supports_movie is True + + +def test_pyplot2_cannot_make_a_movie() -> None: + # it has no getframe(), so plot() never offered it a movie + assert PyPlot2.supports_movie is False + + +@pytest.mark.parametrize("backend", [PyPlot, PyPlot2]) +def test_the_pyplot_backends_are_not_web_pages(backend) -> None: + assert backend.embeds_in_notebook is False + + +def test_swift_is_a_web_page_that_can_be_shown_in_a_notebook() -> None: + pytest.importorskip("swift") + from roboticstoolbox.backends.swift import Swift + + assert Swift.embeds_in_notebook is True + + +# --- plot() reads the flag, not the name of the class ---------------------------------- + + +class WebPage: + """A stand-in for a backend that is a web page, with a name that is not Swift.""" + + embeds_in_notebook = True + + def __init__(self): + self.launched_with = None + + def launch(self, notebook=False, **kwargs): + self.launched_with = dict(kwargs, **({"notebook": True} if notebook else {})) + + def add(self, robot, **kwargs): + return types.SimpleNamespace(q=None) + + def step(self, dt=0.05): + pass + + +def _plot_with(backend, monkeypatch, q): + robot = rtb.models.DH.Puma560() + monkeypatch.setattr(pyplot_module, "_isnotebook", lambda: True) + monkeypatch.setattr( + type(robot), "_get_graphical_backend", lambda self, name=None: backend + ) + robot.plot(q) + return backend.launched_with + + +def test_a_web_page_backend_is_shown_in_the_cell_whatever_it_is_called( + monkeypatch, +) -> None: + assert type(WebPage()).__name__ != "Swift" + + launched = _plot_with(WebPage(), monkeypatch, rtb.models.DH.Puma560().qn) + + assert launched["notebook"] is True + assert launched["realtime"] is False + + +def test_a_backend_called_swift_that_is_not_a_web_page_gets_no_swift_options( + monkeypatch, +) -> None: + # the name used to decide this + NotAWebPage = type("Swift", (WebPage,), {"embeds_in_notebook": False}) + + launched = _plot_with(NotAWebPage(), monkeypatch, rtb.models.DH.Puma560().qn) + + assert "notebook" not in launched + assert "realtime" not in launched diff --git a/tests/test_swift_plot_options.py b/tests/test_swift_plot_options.py index 443a66d04..36aa03aae 100644 --- a/tests/test_swift_plot_options.py +++ b/tests/test_swift_plot_options.py @@ -25,6 +25,8 @@ class Swift: """A stand-in for Swift 2.1, which has launch(notebook=...).""" + embeds_in_notebook = True + def __init__(self): self.launched_with = None self.steps = 0 @@ -52,8 +54,6 @@ def launch(self, **kwargs): def robot(request, monkeypatch): robot = rtb.models.DH.Puma560() backend = request.param() - # the class is named Swift, as plot() recognises the backend by it - type(backend).__name__ = "Swift" monkeypatch.setattr( type(robot), "_get_graphical_backend", lambda self, backend_name=None: backend ) From d9b9e77fac7c549045f465971854420710f8be6d Mon Sep 17 00:00:00 2001 From: Peter Corke Date: Tue, 3 Nov 2026 15:40:22 +1000 Subject: [PATCH 4/4] docs(backends): document the backend registry and the capability flags Co-Authored-By: Claude Sonnet 5.5 --- docs/source/arm_backend.rst | 69 ++++++++++++++++++++++++-- src/roboticstoolbox/robot/BaseRobot.py | 2 +- 2 files changed, 67 insertions(+), 4 deletions(-) diff --git a/docs/source/arm_backend.rst b/docs/source/arm_backend.rst index 8c32a5184..6af0e26d8 100644 --- a/docs/source/arm_backend.rst +++ b/docs/source/arm_backend.rst @@ -30,10 +30,37 @@ A *backend* is what draws a robot, and animates it. The Toolbox talks to a back "Teach pendant" in this context means a set of joint configuration sliders that allow you to control the configuration of the displayed robot using the robot's :meth:`~roboticstoolbox.robot.Robot.Robot.teach` method. +What each can do is declared by four flags, see :ref:`backend-contract`: + +.. list-table:: + :header-rows: 1 + :widths: 16 21 21 21 21 + + * - Name + - ``supports_teach`` + - ``supports_ellipse`` + - ``embeds_in_notebook`` + - ``supports_movie`` + * - ``"pyplot"`` + - yes + - yes + - no + - yes + * - ``"pyplot2"`` + - yes + - yes + - no + - no + * - ``"swift"`` + - yes + - no + - yes + - no + Using a backend --------------- -Most of the time you don't use a backend directly: ``robot.plot(q)`` makes one, adds the robot to it and steps it. Name the backend to choose one, or set the default for a robot or for all robots. +Most of the time you don't use a backend directly: ``robot.plot(q)`` makes one, adds the robot to it and steps it. Name the backend to choose one, or set the default for a robot or for all robots. The name is not case sensitive. .. code-block:: python @@ -58,6 +85,35 @@ With no explicit choice the robot's own default is used, then the default for al backend.step() # update the display backend.hold() # keep the window open +Registering a backend +--------------------- + +The backends above are entries in a *registry*, a table of names and of how to make the backend for each. :func:`~roboticstoolbox.backends.registry.registered_backends` lists the names, and :func:`~roboticstoolbox.backends.registry.register_backend` adds one, so that a backend from anywhere can be chosen by name, as ``robot.plot(q, backend="mysim")`` does. + +.. code-block:: python + + from roboticstoolbox.backends import register_backend, registered_backends + + registered_backends() # ['pyplot', 'pyplot2', 'swift'] + + register_backend("mysim", "my_package.mysim:MySim") + robot.plot(q, backend="mysim") # my_package is imported now + + register_backend("mysim", MySim, replace=True) # or give the class itself + +The second argument is either a string ``"module:Class"``, which is imported only when the backend is chosen, so registering it costs nothing and the package need not be installed; or a callable, such as a class or a function, that returns a backend. A name can be registered once, unless ``replace=True`` is given. The registration lasts for the process, so make it before calling ``plot``. + +This is also how a backend can be developed, tested and used outside the Toolbox, and how one that cannot be part of it, because of its licence or because it needs a particular GPU, can be a package of its own. + +.. autofunction:: roboticstoolbox.backends.registry.register_backend + +.. autofunction:: roboticstoolbox.backends.registry.registered_backends + +.. autofunction:: roboticstoolbox.backends.registry.load_backend + +.. versionadded:: 1.5.1 + ``register_backend`` and ``registered_backends``. The name of a backend is no longer case sensitive. + What a backend does ------------------- @@ -67,7 +123,14 @@ The backend holds a *scene*: the robots and other objects that it has been asked - **The scene.** ``add(obj)`` puts an object in the scene and returns an identifier, and ``remove(id)`` takes it out. The object must be of a class that the backend knows how to draw, such as a robot, or an ellipsoid if the backend supports them. - **Time.** ``step(dt)`` advances the scene by ``dt`` seconds, which makes each robot act according to its control type (position, velocity, acceleration or torque) and updates the display. - **Waiting.** ``hold`` keeps the backend running after the script has finished, for as long as the window is open. -- **Optional features**, which a backend declares with two flags: ``supports_teach`` is true if it can show the interactive teach pendant of :meth:`~roboticstoolbox.robot.Robot.Robot.teach`, and ``supports_ellipse`` is true if it can draw the ellipsoids made by :meth:`~roboticstoolbox.robot.Robot.Robot.plot_ellipse`. +- **Optional features**, which a backend declares with four flags, all false unless it says otherwise: + + - ``supports_teach`` is true if it can show the interactive teach pendant of :meth:`~roboticstoolbox.robot.Robot.Robot.teach` + - ``supports_ellipse`` is true if it can draw the ellipsoids made by :meth:`~roboticstoolbox.robot.Robot.Robot.plot_ellipse` + - ``embeds_in_notebook`` is true if it is a web page that can be shown in the output of a notebook cell, as well as in a browser window of its own. :meth:`~roboticstoolbox.robot.Robot.Robot.plot` then asks for that in a notebook, and animates a trajectory in real time + - ``supports_movie`` is true if it has ``getframe()``, which gives a picture of the scene, so that :meth:`~roboticstoolbox.robot.Robot.Robot.plot` can save an animation as a movie + +.. _backend-contract: The contract ------------ @@ -87,7 +150,7 @@ This is written down as the :py:class:`~roboticstoolbox.backends.Connector.Conne ~roboticstoolbox.backends.Connector.Connector.hold .. autoclass:: roboticstoolbox.backends.Connector.Connector - :members: launch, close, reset, restart, add, remove, step, hold, supports_teach, supports_ellipse + :members: launch, close, reset, restart, add, remove, step, hold, supports_teach, supports_ellipse, embeds_in_notebook, supports_movie :member-order: bysource The backends diff --git a/src/roboticstoolbox/robot/BaseRobot.py b/src/roboticstoolbox/robot/BaseRobot.py index 3fce73960..4eea5076c 100644 --- a/src/roboticstoolbox/robot/BaseRobot.py +++ b/src/roboticstoolbox/robot/BaseRobot.py @@ -2066,7 +2066,7 @@ def plot( animation with a pause of ``dt`` seconds between each frame. :param q: The joint configuration of the robot. - :param backend: The graphical backend to use, by name: 'swift', 'pyplot' or 'pyplot2', or one added by :func:`~roboticstoolbox.backends.register_backend`, see :func:`~roboticstoolbox.backends.registered_backends`. The name is not case sensitive. Defaults to 'swift' of a ``Robot`` and 'pyplot` for a ``DHRobot`` + :param backend: The graphical backend to use, by name: 'swift', 'pyplot' or 'pyplot2', or one added by :func:`~roboticstoolbox.backends.registry.register_backend`, see :func:`~roboticstoolbox.backends.registry.registered_backends`. The name is not case sensitive. Defaults to 'swift' of a ``Robot`` and 'pyplot` for a ``DHRobot`` :param block: ``True`` waits until the window is closed; the PyPlot backend has already shown the figure, so ``False`` and ``None`` return at once, defaults to False