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
17 changes: 15 additions & 2 deletions docs/lite/wasm_check/check_pyodide_install.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -104,14 +104,27 @@ class _Matplotlib:
module.matplotlib = _Matplotlib()

frames = []
module._ipy_display = lambda frame, display_id=None: frames.append(frame.data)
widgets = []

def _display(frame, display_id=None):
# an inline frame is an image; a widget figure is displayed as its canvas
if hasattr(frame, "data"):
frames.append(frame.data)
else:
widgets.append(frame)

module._ipy_display = _display
module._ipy_clear_output = lambda wait=False: None

robot = rtb.models.DH.Puma560()
env = robot.plot(rtb.jtraj(robot.qz, robot.qn, 8).q, dt=0.0)
assert env.render_mode == "notebook-inline", env.render_mode
assert len(set(frames)) >= 8, f"{len(set(frames))} different frames pushed for 8 steps"
assert robot.plot(robot.qn).render_mode == "notebook-widget"
assert not widgets, "an animation displayed a widget"
static = robot.plot(robot.qn)
assert static.render_mode == "notebook-widget"
# a static plot is one live figure, displayed once and not before it is drawn
assert widgets == [static.fig.canvas], f"{len(widgets)} widgets displayed"
print(f"plot of a trajectory: {env.render_mode}, {len(set(frames))} different frames")
print("import roboticstoolbox: OK")
`;
Expand Down
9 changes: 8 additions & 1 deletion docs/notebooks/_rtb_nb_bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,17 @@ async def ensure_installed(extras: tuple[str, ...] | list[str] = ()) -> bool:
requirement = "roboticstoolbox-python"
if extras:
requirement += "[" + ",".join(extras) + "]"
# Colab does not ship ipympl, which the notebooks select with
# %matplotlib ipympl; matplotlib rejects the backend if it is missing.
subprocess.run(
[sys.executable, "-m", "pip", "install", "-q", requirement],
[sys.executable, "-m", "pip", "install", "-q", requirement, "ipympl"],
check=True,
)
# ipympl figures need Colab's custom widget manager, enabled before the
# first figure is created.
from google.colab import output

output.enable_custom_widget_manager()
where, colab = "on Colab", True

import roboticstoolbox
Expand Down
4 changes: 3 additions & 1 deletion docs/notebooks/branched-robot.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,9 @@
" requirement = 'roboticstoolbox-python'\n",
" if extras:\n",
" requirement += '[' + ','.join(extras) + ']'\n",
" subprocess.run([sys.executable, '-m', 'pip', 'install', '-q', requirement], check=True)\n",
" subprocess.run([sys.executable, '-m', 'pip', 'install', '-q', requirement, 'ipympl'], check=True)\n",
" from google.colab import output\n",
" output.enable_custom_widget_manager()\n",
" where, colab = ('on Colab', True)\n",
" import roboticstoolbox\n",
" version = getattr(roboticstoolbox, '__version__', 'unknown')\n",
Expand Down
4 changes: 3 additions & 1 deletion docs/notebooks/dynamics.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,9 @@
" requirement = 'roboticstoolbox-python'\n",
" if extras:\n",
" requirement += '[' + ','.join(extras) + ']'\n",
" subprocess.run([sys.executable, '-m', 'pip', 'install', '-q', requirement], check=True)\n",
" subprocess.run([sys.executable, '-m', 'pip', 'install', '-q', requirement, 'ipympl'], check=True)\n",
" from google.colab import output\n",
" output.enable_custom_widget_manager()\n",
" where, colab = ('on Colab', True)\n",
" import roboticstoolbox\n",
" version = getattr(roboticstoolbox, '__version__', 'unknown')\n",
Expand Down
4 changes: 3 additions & 1 deletion docs/notebooks/ets.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,9 @@
" requirement = 'roboticstoolbox-python'\n",
" if extras:\n",
" requirement += '[' + ','.join(extras) + ']'\n",
" subprocess.run([sys.executable, '-m', 'pip', 'install', '-q', requirement], check=True)\n",
" subprocess.run([sys.executable, '-m', 'pip', 'install', '-q', requirement, 'ipympl'], check=True)\n",
" from google.colab import output\n",
" output.enable_custom_widget_manager()\n",
" where, colab = ('on Colab', True)\n",
" import roboticstoolbox\n",
" version = getattr(roboticstoolbox, '__version__', 'unknown')\n",
Expand Down
4 changes: 3 additions & 1 deletion docs/notebooks/graphics-test.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,9 @@
" requirement = 'roboticstoolbox-python'\n",
" if extras:\n",
" requirement += '[' + ','.join(extras) + ']'\n",
" subprocess.run([sys.executable, '-m', 'pip', 'install', '-q', requirement], check=True)\n",
" subprocess.run([sys.executable, '-m', 'pip', 'install', '-q', requirement, 'ipympl'], check=True)\n",
" from google.colab import output\n",
" output.enable_custom_widget_manager()\n",
" where, colab = ('on Colab', True)\n",
" import roboticstoolbox\n",
" version = getattr(roboticstoolbox, '__version__', 'unknown')\n",
Expand Down
4 changes: 3 additions & 1 deletion docs/notebooks/icra2021.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,9 @@
" requirement = 'roboticstoolbox-python'\n",
" if extras:\n",
" requirement += '[' + ','.join(extras) + ']'\n",
" subprocess.run([sys.executable, '-m', 'pip', 'install', '-q', requirement], check=True)\n",
" subprocess.run([sys.executable, '-m', 'pip', 'install', '-q', requirement, 'ipympl'], check=True)\n",
" from google.colab import output\n",
" output.enable_custom_widget_manager()\n",
" where, colab = ('on Colab', True)\n",
" import roboticstoolbox\n",
" version = getattr(roboticstoolbox, '__version__', 'unknown')\n",
Expand Down
4 changes: 3 additions & 1 deletion docs/notebooks/icra2026.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,9 @@
" requirement = 'roboticstoolbox-python'\n",
" if extras:\n",
" requirement += '[' + ','.join(extras) + ']'\n",
" subprocess.run([sys.executable, '-m', 'pip', 'install', '-q', requirement], check=True)\n",
" subprocess.run([sys.executable, '-m', 'pip', 'install', '-q', requirement, 'ipympl'], check=True)\n",
" from google.colab import output\n",
" output.enable_custom_widget_manager()\n",
" where, colab = ('on Colab', True)\n",
" import roboticstoolbox\n",
" version = getattr(roboticstoolbox, '__version__', 'unknown')\n",
Expand Down
4 changes: 3 additions & 1 deletion docs/notebooks/ik-symbolic.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,9 @@
" requirement = 'roboticstoolbox-python'\n",
" if extras:\n",
" requirement += '[' + ','.join(extras) + ']'\n",
" subprocess.run([sys.executable, '-m', 'pip', 'install', '-q', requirement], check=True)\n",
" subprocess.run([sys.executable, '-m', 'pip', 'install', '-q', requirement, 'ipympl'], check=True)\n",
" from google.colab import output\n",
" output.enable_custom_widget_manager()\n",
" where, colab = ('on Colab', True)\n",
" import roboticstoolbox\n",
" version = getattr(roboticstoolbox, '__version__', 'unknown')\n",
Expand Down
4 changes: 3 additions & 1 deletion docs/notebooks/iros2020.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,9 @@
" requirement = 'roboticstoolbox-python'\n",
" if extras:\n",
" requirement += '[' + ','.join(extras) + ']'\n",
" subprocess.run([sys.executable, '-m', 'pip', 'install', '-q', requirement], check=True)\n",
" subprocess.run([sys.executable, '-m', 'pip', 'install', '-q', requirement, 'ipympl'], check=True)\n",
" from google.colab import output\n",
" output.enable_custom_widget_manager()\n",
" where, colab = ('on Colab', True)\n",
" import roboticstoolbox\n",
" version = getattr(roboticstoolbox, '__version__', 'unknown')\n",
Expand Down
4 changes: 3 additions & 1 deletion docs/notebooks/kinematics.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,9 @@
" requirement = 'roboticstoolbox-python'\n",
" if extras:\n",
" requirement += '[' + ','.join(extras) + ']'\n",
" subprocess.run([sys.executable, '-m', 'pip', 'install', '-q', requirement], check=True)\n",
" subprocess.run([sys.executable, '-m', 'pip', 'install', '-q', requirement, 'ipympl'], check=True)\n",
" from google.colab import output\n",
" output.enable_custom_widget_manager()\n",
" where, colab = ('on Colab', True)\n",
" import roboticstoolbox\n",
" version = getattr(roboticstoolbox, '__version__', 'unknown')\n",
Expand Down
4 changes: 3 additions & 1 deletion docs/notebooks/symbolic.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,9 @@
" requirement = 'roboticstoolbox-python'\n",
" if extras:\n",
" requirement += '[' + ','.join(extras) + ']'\n",
" subprocess.run([sys.executable, '-m', 'pip', 'install', '-q', requirement], check=True)\n",
" subprocess.run([sys.executable, '-m', 'pip', 'install', '-q', requirement, 'ipympl'], check=True)\n",
" from google.colab import output\n",
" output.enable_custom_widget_manager()\n",
" where, colab = ('on Colab', True)\n",
" import roboticstoolbox\n",
" version = getattr(roboticstoolbox, '__version__', 'unknown')\n",
Expand Down
4 changes: 3 additions & 1 deletion docs/notebooks/two-link-dynamics.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,9 @@
" requirement = 'roboticstoolbox-python'\n",
" if extras:\n",
" requirement += '[' + ','.join(extras) + ']'\n",
" subprocess.run([sys.executable, '-m', 'pip', 'install', '-q', requirement], check=True)\n",
" subprocess.run([sys.executable, '-m', 'pip', 'install', '-q', requirement, 'ipympl'], check=True)\n",
" from google.colab import output\n",
" output.enable_custom_widget_manager()\n",
" where, colab = ('on Colab', True)\n",
" import roboticstoolbox\n",
" version = getattr(roboticstoolbox, '__version__', 'unknown')\n",
Expand Down
37 changes: 34 additions & 3 deletions src/roboticstoolbox/backends/PyPlot/PyPlot.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,13 @@ def launch(
self.inline_dpi = inline_dpi
self._inline_step_count = 0
self._inline_display_handle = None
self._inline_is_jl = sys.platform == "emscripten"
self._widget_owned = False
self._widget_pending = False
# JupyterLite and Colab do not update a display handle in place, so each
# frame must replace the last one by clearing the cell output
self._inline_is_jl = (
sys.platform == "emscripten" or "google.colab" in sys.modules
)

self.limits = limits
if limits is not None:
Expand All @@ -209,7 +215,18 @@ def launch(
self.fig = ax.figure
else:
if fig is None:
self.fig = plt.figure(name)
if self.render_mode == "notebook-widget":
# With interactive mode on, ipympl displays the figure as soon as
# it is created, while still empty, and plt.show() displays it
# again; frontends differ in what that does (a blank figure in
# VS Code, three copies in Colab). Create it quietly and display
# the finished canvas once, in add().
with plt.ioff():
self.fig = plt.figure(name)
self._widget_owned = True
self._widget_pending = True
else:
self.fig = plt.figure(name)
else:
self.fig = fig
set_window_title(self.fig, name)
Expand Down Expand Up @@ -515,6 +532,15 @@ def add(
# In inline/JupyterLite mode, push a frame immediately so static
# plots (eg. plot_vellipse/plot_fellipse) are visible without step().
self._push_inline_frame()
elif self._widget_owned and _ipy_display is not None:
# a widget figure that launch() created: show it once, when first drawn,
# and after that only redraw it
if self._widget_pending:
self.fig.canvas.draw()
_ipy_display(self.fig.canvas)
self._widget_pending = False
else:
self.fig.canvas.draw_idle()
else:
plt.draw() # matplotlib refresh
plt.show(block=False)
Expand Down Expand Up @@ -826,7 +852,8 @@ def _isnotebook() -> bool:
"""
Determine if code is being run from a Jupyter notebook or JupyterLite

``_isnotebook`` is True if running Jupyter notebook, JupyterLite, or similar, else False
``_isnotebook`` is True if running Jupyter notebook, JupyterLite, Google Colab, or
similar, else False

:references:

Expand All @@ -839,6 +866,10 @@ def _isnotebook() -> bool:
if sys.platform == "emscripten":
return True

# Colab's shell is google.colab._shell.Shell, not a ZMQInteractiveShell
if "google.colab" in sys.modules:
return True

# Fall back to checking IPython shell type
try:
shell = get_ipython().__class__.__name__ # type: ignore[name-defined]
Expand Down
38 changes: 38 additions & 0 deletions tests/test_notebook_bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -354,3 +354,41 @@ def test_the_browser_install_goes_through_piplite():

assert "import piplite" in template
assert '"/pypi"' not in template


def test_the_colab_install_includes_ipympl_and_the_widget_manager(monkeypatch):
# Colab does not ship ipympl, and matplotlib rejects "%matplotlib ipympl" without
# it. The Colab branch is run here with a fake google.colab and no real pip, so
# this checks the command and the widget-manager call, not a real Colab install.
import asyncio
import types

bootstrap = _load_module("_rtb_nb_bootstrap", NOTEBOOKS_DIR / "_rtb_nb_bootstrap.py")

calls = []
enabled = []
output = types.SimpleNamespace(
enable_custom_widget_manager=lambda: enabled.append(True)
)
colab = types.ModuleType("google.colab")
colab.output = output
google = types.ModuleType("google")
google.colab = colab
monkeypatch.setitem(sys.modules, "google", google)
monkeypatch.setitem(sys.modules, "google.colab", colab)

def fake_run(cmd, **kw):
# subprocess.run is global, so anything else that uses it must still work
if "pip" in cmd:
calls.append(cmd)
return types.SimpleNamespace(returncode=0, stdout=b"", stderr=b"")

monkeypatch.setattr(bootstrap.subprocess, "run", fake_run)
monkeypatch.setattr(bootstrap.sys, "platform", "linux")

assert asyncio.run(bootstrap.ensure_installed(["ik"])) is True

assert len(calls) == 1
assert "roboticstoolbox-python[ik]" in calls[0]
assert "ipympl" in calls[0]
assert enabled == [True]
86 changes: 86 additions & 0 deletions tests/test_render_mode.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,3 +100,89 @@ def test_plot_leaves_an_explicit_render_mode_alone():
except Exception:
pass
assert launch.call_args.kwargs["render_mode"] == "notebook-widget"


# --- display in a notebook ---------------------------------------------------
# These run on the Agg backend with the display function replaced, so they check
# what is asked of IPython and when, not how a real frontend (VS Code, Colab,
# JupyterLab) draws it.


@pytest.fixture
def displayed(monkeypatch):
import matplotlib.pyplot as plt

shown = []
monkeypatch.setattr(pyplot_module, "_ipy_display", shown.append)
plt.close("all")
yield shown
plt.close("all")


def test_a_widget_figure_is_displayed_once_when_it_is_drawn(displayed):
import matplotlib.pyplot as plt

robot = rtb.models.DH.Puma560()
env = PyPlot()
env.launch(render_mode="notebook-widget")

# created quietly: nothing shown while the figure is empty
assert displayed == []

env.add(robot, q=robot.qn, readonly=True)
assert displayed == [env.fig.canvas]

# a second robot is drawn into the figure already on show
env.add(robot, q=robot.qr, readonly=True)
assert displayed == [env.fig.canvas]
plt.close(env.fig)


def test_a_figure_supplied_by_the_caller_is_not_displayed_by_launch(displayed):
import matplotlib.pyplot as plt

fig = plt.figure()
env = PyPlot()
env.launch(fig=fig, render_mode="notebook-widget")
env.add(rtb.models.DH.Puma560(), q=[0, 0, 0, 0, 0, 0], readonly=True)

assert displayed == []
plt.close(fig)


def test_colab_replaces_inline_frames_like_jupyterlite(monkeypatch, displayed):
import types

monkeypatch.setitem(sys.modules, "google.colab", types.ModuleType("google.colab"))
env = PyPlot()
env.launch(render_mode="notebook-inline")

assert env._inline_is_jl is True


def test_other_environments_update_one_inline_display(displayed):
env = PyPlot()
env.launch(render_mode="notebook-inline")

assert env._inline_is_jl is False


def test_colab_is_a_notebook(monkeypatch):
# Colab's IPython shell is not a ZMQInteractiveShell, so it is recognised by
# its module; otherwise it gets a window and the same figure is displayed
# several times
import types

monkeypatch.setitem(sys.modules, "google.colab", types.ModuleType("google.colab"))

assert pyplot_module._isnotebook() is True


def test_colab_with_ipympl_is_a_widget_for_a_static_plot(monkeypatch):
import types

monkeypatch.setitem(sys.modules, "google.colab", types.ModuleType("google.colab"))
monkeypatch.setattr(matplotlib, "get_backend", lambda: IPYMPL)

assert _resolve_render_mode(None) == "notebook-widget"
assert _resolve_render_mode(None, animation=True) == "notebook-inline"
Loading