Swift in notebooks
Swift runs in a Jupyter notebook, showing its viewer in the output of the cell that launched it. Swift supports three very different notebook execution environments:
a local Jupyter: JupyterLab, the classic notebook, or the Jupyter extension of VS Code;
Google Colab;
JupyterLite, which runs Python in your browser, so there is nothing to install and no server: Swift’s own Try it now site is one.
The example notebooks in docs/notebooks run in all three (one needs a library that is
not available in the browser, and says so), and the setup cell below
is how a notebook of your own does the same.
Where Swift runs
Environment |
What to install |
How the viewer is shown |
|---|---|---|
Local Jupyter, VS Code |
|
Swift runs its web server on your computer, as in a script, and shows the page in
a frame in the output of the cell where you launch with |
Google Colab |
|
Colab cannot reach a web server on its virtual machine, so Swift sends the viewer’s files to the browser through the notebook’s own connection and builds the page there. This needs the anywidget package, and Swift turns on Colab’s custom widget manager for you. |
JupyterLite |
|
The same as Colab. Python is running in your browser, which cannot start a server at all. |
swift-sim 2.2.0 or later is needed on Colab and in JupyterLite. launch() handles the complexity of the different environments, so the code of a notebook is the same in every environment. A notebook that
passes notebook=True to launch() for the local case can leave it in when it runs on Colab or
in JupyterLite, where it is not needed and is ignored.
A setup cell for any notebook
Put this in the first cell of a notebook, and add await ensure_installed(...) at its end. It
installs what is missing in the environment the notebook finds itself in, downloads any example
files the notebook needs, and says what it found:
Running colab using Swift v2.2.0
It returns "local", "colab" or "jupyterlite", which a notebook can use if
it must behave differently in one of them.
The example notebooks start with a copy of this cell, folded away, because Colab opens a single
.ipynb file and cannot see any other file. The source is also in the repository as
docs/notebooks/_swift_nb_bootstrap.py,
which is a template to copy.
1"""Environment bootstrap for Swift's Jupyter notebooks.
2
3Makes Swift ready to use in each of the places a notebook might run: a local
4Jupyter, JupyterLab or VS Code, Google Colab, and JupyterLite (Pyodide, in the
5browser). It installs what is missing, fetches any example files the notebook
6needs, and says what it found.
7
8This file is the single source of truth for that logic. Each notebook's
9bootstrap cell is a generated copy of it (``sync_bootstrap.py``), because
10Colab fetches only the one ``.ipynb`` it is opened from. It is also the
11template to copy into your own notebook; see ``docs/source/notebook.rst``.
12"""
13
14import subprocess
15import sys
16
17# swift-sim 2.2.0 is the first release that can show its viewer on Colab and in
18# JupyterLite; an older one installs but cannot show it.
19SWIFT = "swift-sim>=2.2.0"
20
21# Where the example files (meshes, textures) come from.
22ASSETS_URL = "https://raw.githubusercontent.com/jhavl/swift/main/examples/assets/"
23
24
25async def ensure_installed(
26 extras: tuple[str, ...] | list[str] = (),
27 assets: tuple[str, ...] | list[str] = (),
28) -> str:
29 """Install Swift if needed, fetch example files, and report the environment.
30
31 :param extras: other packages the notebook needs, for example
32 ``["roboticstoolbox-python"]``. They are set per notebook in its
33 metadata (``swift_bootstrap.extras``) and passed here by the generated
34 cell.
35 :param assets: files from Swift's ``examples/assets`` folder to download into
36 ``assets/`` next to the notebook, for example ``["robot.glb"]``. They
37 are set per notebook in its metadata (``swift_bootstrap.assets``).
38 :returns: ``"colab"``, ``"jupyterlite"`` or ``"local"``.
39 """
40 if sys.platform == "emscripten":
41 where = "jupyterlite"
42 # spatialmath-python's docstrings have "\m" in strings that are not raw;
43 # Python complains when it compiles them the first time, which in the
44 # browser is on install, and shows as a red box that looks like an error.
45 import warnings
46
47 warnings.filterwarnings("ignore", category=SyntaxWarning)
48 # In JupyterLite, piplite looks in this site's own package index first,
49 # so Swift is the wheel that was built with the site. micropip alone
50 # cannot see that index and would install the last release from PyPI.
51 # Outside JupyterLite (for example a test under Node) there is no piplite.
52 try:
53 import piplite
54
55 install = piplite.install
56 except ImportError:
57 import micropip
58
59 install = micropip.install
60
61 # spatialmath-python 1.1.19 is the first release that does not list
62 # pre-commit (a dev tool) as a runtime dependency, which conflicted with
63 # the packaging built into Pyodide (rai-opensource/spatialmath-python#250).
64 # Naming it here makes the install fail early, and clearly, if a site's
65 # package index only has an older one.
66 await install("spatialmath-python>=1.1.19")
67 # The widget that shows the viewer in the page; Swift needs it here
68 # because a browser kernel cannot run a web server.
69 await install("anywidget")
70 await install(SWIFT)
71 for package in extras:
72 await install(package)
73 else:
74 try:
75 from google.colab import output # noqa: F401
76
77 where = "colab"
78 except ImportError:
79 where = "local"
80
81 if where == "colab":
82 # Colab shows the viewer with the anywidget package, and has no
83 # web server to reach, so Swift needs it there. Locally Swift
84 # serves the viewer itself and the widget is not needed.
85 requirements = [SWIFT, "anywidget", *extras]
86 else:
87 requirements = [SWIFT, *extras]
88 print("Installing", ", ".join(requirements), "...")
89 subprocess.run(
90 [sys.executable, "-m", "pip", "install", "-q", *requirements],
91 check=True,
92 )
93
94 if assets:
95 await _fetch_assets(assets, where)
96
97 import swift
98
99 print(f"Running {where} using Swift v{swift.__version__}")
100 return where
101
102
103async def _fetch_assets(names: tuple[str, ...] | list[str], where: str) -> None:
104 """Download example files into ``assets/``, skipping those already there."""
105 from pathlib import Path
106
107 folder = Path("assets")
108 folder.mkdir(exist_ok=True)
109 for name in names:
110 target = folder / name
111 if target.exists():
112 continue
113 url = ASSETS_URL + name
114 if where == "jupyterlite":
115 from pyodide.http import pyfetch
116
117 response = await pyfetch(url)
118 if not response.ok:
119 raise RuntimeError(f"Could not download {url}: {response.status}")
120 target.write_bytes(await response.bytes())
121 else:
122 from urllib.request import urlopen
123
124 with urlopen(url) as response:
125 target.write_bytes(response.read())
Finish the cell with one of:
ENV = await ensure_installed()
ENV = await ensure_installed(extras=["roboticstoolbox-python"])
ENV = await ensure_installed(assets=["robot.glb", "gravel.jpg"])
extras are other packages the notebook needs. assets are files from Swift’s
examples/assets folder, downloaded
into an assets folder next to the notebook; give a mesh to Swift with an absolute path
(Path("assets").resolve() / "robot.glb"). On Colab and locally the cell
runs pip; in JupyterLite it uses piplite, which looks first in the site’s own package
index, so a site always runs the Swift that was built with it.
Notebooks that need only Swift can use one line on Colab, %pip install swift-sim anywidget.
The example notebooks
Each notebook has an Open in Colab and an Open in JupyterLite badge in its first cell. The index lists them:
box1: the simplest scene, one cubebox2: a cube standing on a tiled ground planebox_orbit: animating a shape with a callback function of timebusy_scene: shapes, 3D models and a textured groundcollision: collision detection (Colab and local only)two_link_arm_assembly: an assembly moved by joint anglespanda: a Franka-Emika Panda robot from the Robotics Toolbox
What you see, and when
In a notebook the viewer is already on screen while a cell runs, and Python’s messages to it are delivered at once, so what you add appears without waiting for the cell to end.
add_shape() shows the shape straight away, in its pose, even before the first
step().add_robot() shows the robot’s links straight away too, but in a pile at the robot’s base: the pose is sent by
step(), not byadd_robot(). Settinghandle.qchanges the robot’s joint angles in Python only, and the viewer shows the new pose after the nextstep()(orrun(), which calls it). So followhandle.q = ...withenv.step().step() and run() send the poses of everything that moves, and advance the clock at top right. A shape whose pose a callback computes, or a robot or assembly whose joint angles do, moves only while one of them is running.
hold(seconds) waits that long, in one-second steps, and then carries on, leaving the scene where it is, which you can still orbit and zoom with the mouse. You do not need
hold()to keep the viewer on screen: it stays in the output after the cell ends. A notebook cannot tell that the viewer has gone, sohold()with no duration waits until you interrupt the kernel, and that interrupt closes the session.
What to expect
The first run is slow in JupyterLite: it downloads Python and the packages into the browser, which takes from a few seconds to a minute. Later runs are faster.
Sliders and buttons do not steer a running loop. The kernel hears the viewer’s controls only between cells, never while a cell is running. An animation can be driven by a function of time, as the examples are; to change something with a slider, run the next cell. For sliders that act at once, run Swift on your own computer.
Animation runs while a cell runs. Python’s messages to the viewer are delivered during a cell, so
env.run()and astep()loop animate as they do on the desktop.Collision detection is not available in the browser (JupyterLite): it needs the
coallibrary, which does not exist for it. It works on Colab and locally.Performance. Swift’s C++ extension, which speeds up computing poses, is not available in the browser, so JupyterLite uses a pure-Python wheel of Swift. Colab and JupyterLite are for convenience and trying things out, not for large simulations.
Browsers. The JupyterLite site is tested in Chromium. Its Python kernel needs WebAssembly JSPI, which Chrome and Edge have had for some time, Firefox has from version 153 and Safari from version 27. A browser without it is told so by a banner, instead of showing a spinner that never ends.
When it does not start
Swift says what is wrong rather than showing an empty frame:
ImportError: ... pip install anywidget: theanywidgetpackage is missing; run the setup cell, or install it.RuntimeError: The Swift viewer did not start within 10 s(Colab): restart the runtime (Runtime then Restart session) and run the notebook again.In JupyterLite the kernel cannot hear the viewer until the cell ends, so a viewer that did not start is reported by the next call to Swift, rather than by
launch().
How it works
Building a JupyterLite site with Swift
docs/lite/build_site.py builds Swift’s own site, and is the model for another toolbox that
wants Swift in its site (the Robotics Toolbox has one). What matters:
build a pure-Python wheel of Swift (
SWIFT_PURE_WHEEL=1 python -m build --wheel; it is also published on PyPI with each release), because Pyodide cannot install a wheel compiled for CPython;install
anywidgetin the environment that builds the site, so that its JupyterLab extension is bundled; without it the viewer cannot show, with aNo version of module anywidget is registerederror in the browser’s console;build with the
jupyterlite-coreof that environment, and make sure that no other environment’s JupyterLab extensions are on the path, which can break the whole site;use
jupyterlite-pyodide-kernel>=0.8.7, as the toolboxes do, and add the banner for browsers without JSPI (docs/lite/inject_jspi_check.py, whichbuild_site.pyruns).
docs/lite/browser_check/check_lite_in_browser.py runs every notebook of a built site in
a headless browser, as the Docs workflow does.