*******************
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 :ref:`the setup cell ` below
is how a notebook of your own does the same.
Where Swift runs
================
.. list-table::
:header-rows: 1
:widths: 18 28 54
* - Environment
- What to install
- How the viewer is shown
* - Local Jupyter, VS Code
- ``pip install swift-sim``
- 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 ``notebook=True``. The browser that shows
the notebook must be on the same machine as the kernel.
* - Google Colab
- ``pip install swift-sim anywidget``
- 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
- ``anywidget``, and Swift, from the site's package index
- 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.
.. _notebook-setup-cell:
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.
.. literalinclude:: ../notebooks/_swift_nb_bootstrap.py
:language: python
:linenos:
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 cube
* ``box2``: a cube standing on a tiled ground plane
* ``box_orbit``: animating a shape with a callback function of time
* ``busy_scene``: shapes, 3D models and a textured ground
* ``collision``: collision detection (Colab and local only)
* ``two_link_arm_assembly``: an assembly moved by joint angles
* ``panda``: 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 by ``add_robot()``. Setting ``handle.q`` changes
the robot's joint angles in Python only, and the viewer shows the new pose after the next
``step()`` (or ``run()``, which calls it). So follow ``handle.q = ...`` with ``env.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, so ``hold()`` 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 a ``step()`` loop animate as they do
on the desktop.
* **Collision detection is not available in the browser** (JupyterLite): it needs the ``coal`` library,
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``: the ``anywidget`` package 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
============
See :doc:`internals`, :ref:`notebook-transport`.
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 ``anywidget`` **in the environment that builds the site**, so that its JupyterLab
extension is bundled; without it the viewer cannot show, with a ``No version of module
anywidget is registered`` error in the browser's console;
* build with the ``jupyterlite-core`` of 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``, which ``build_site.py`` runs).
``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.