Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 66 additions & 3 deletions docs/source/arm_backend.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
-------------------

Expand All @@ -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
------------
Expand All @@ -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
Expand Down
9 changes: 9 additions & 0 deletions src/roboticstoolbox/backends/Connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
#
Expand Down
1 change: 1 addition & 0 deletions src/roboticstoolbox/backends/PyPlot/PyPlot.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
43 changes: 6 additions & 37 deletions src/roboticstoolbox/backends/__init__.py
Original file line number Diff line number Diff line change
@@ -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"]
156 changes: 156 additions & 0 deletions src/roboticstoolbox/backends/registry.py
Original file line number Diff line number Diff line change
@@ -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_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__}")
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_backend_name(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_backend_name(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)

Check failure on line 141 in src/roboticstoolbox/backends/registry.py

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

src/roboticstoolbox/backends/registry.py#L141

Untrusted user input in `importlib.import_module()` function allows an attacker to load arbitrary code.
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")
1 change: 1 addition & 0 deletions src/roboticstoolbox/backends/swift/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading