An example Jupyter Notebook#

This notebook is a demonstration of directly-parsing Jupyter Notebooks into Sphinx using the MyST parser.[^download]

Markdown#

Configuration#

https://myst-parser.readthedocs.io/en/latest/using/intro.html#getting-started

To build documentation from this notebook, the following options are set:

myst_enable_extensions = [
    "amsmath",
    "colon_fence",
    "deflist",
    "dollarmath",
    "html_image",
]
myst_url_schemes = ("http", "https", "mailto")

Syntax#

As you can see, markdown is parsed as expected. Embedding images should work as expected. For example, here’s the MyST-NB logo:

![myst-nb logo](../img/unitary_fund_logo.png)

myst-nb logo

By adding "html_image" to the myst_enable_extensions list in the sphinx configuration (see here), you can even add HTML img tags with attributes:

<img src="../img/unitary_fund_logo.png" alt="logo" width="200px" class="shadow mb-2">
logo

Because MyST-NB is using the MyST-markdown parser, you can include rich markdown with Sphinx in your notebook. For example, here’s a note admonition block:

Note

Wow, a note! It was generated with this code (as explained here):

:::{note}
**Wow**, a note!
:::

If you wish to use “bare” LaTeX equations, then you should add "amsmath" to the myst_enable_extensions list in the sphinx configuration. This is explained here, and works as such:

\begin{equation}
\frac {\partial u}{\partial x} + \frac{\partial v}{\partial y} = - \, \frac{\partial w}{\partial z}
\end{equation}

\begin{align*}
2x - 5y &=  8 \\
3x + 9y &=  -12
\end{align*}
(1)#\[\begin{equation} \frac {\partial u}{\partial x} + \frac{\partial v}{\partial y} = - \, \frac{\partial w}{\partial z} \end{equation}\]
\[\begin{align*} 2x - 5y &= 8 \\ 3x + 9y &= -12 \end{align*}\]

Also you can use features like equation numbering and referencing in the notebooks:

$$e^{i\pi} + 1 = 0$$ (euler)
(2)#\[e^{i\pi} + 1 = 0\]

Euler’s identity, equation (2), was elected one of the most beautiful mathematical formulas.

You can see the syntax used for this example here in the MyST documentation.

Code cells and outputs#

You can run cells, and the cell outputs will be captured and inserted into the resulting Sphinx site.

__repr__ and HTML outputs#

For example, here’s some simple Python:

import matplotlib.pyplot as plt
import numpy as np
data = np.random.rand(3, 100) * 100
data[:, :10]
array([[54.42945557, 81.79899209,  4.76113441, 18.32016441, 53.50354678,
        83.52240503, 16.78432573, 93.48276012, 17.95981653,  4.01328644],
       [23.02340991,  4.57754029, 48.34950844, 52.80073414, 27.26750197,
        38.26006148, 46.98896542, 17.18369072, 37.3612231 , 96.45694744],
       [45.9928278 , 50.80933412, 33.7760417 , 21.73929254, 46.53922909,
        88.7081506 , 28.07867196, 82.50645743, 15.93818439, 61.89703489]])

This will also work with HTML outputs

import pandas as pd
df = pd.DataFrame(data.T, columns=['a', 'b', 'c'])
df.head()
a b c
0 54.429456 23.023410 45.992828
1 81.798992 4.577540 50.809334
2 4.761134 48.349508 33.776042
3 18.320164 52.800734 21.739293
4 53.503547 27.267502 46.539229

as well as math outputs

from IPython.display import Math
Math(r"\sum_{i=0}^n i^2 = \frac{(n^2+n)(2n+1)}{6}")
\[\displaystyle \sum_{i=0}^n i^2 = \frac{(n^2+n)(2n+1)}{6}\]

This works for error messages as well:

print("This will be properly printed...")
print(thiswont)
This will be properly printed...
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
/tmp/ipykernel_1031/3073679017.py in <module>
      1 print("This will be properly printed...")
----> 2 print(thiswont)

NameError: name 'thiswont' is not defined

Images#

Images that are generated from your code (e.g., with Matplotlib) will also be embedded.

fig, ax = plt.subplots()
ax.scatter(*data, c=data[2])
<matplotlib.collections.PathCollection at 0x7f494c074150>
../_images/template_9_1.png

Testing#

The following cells setup a test (which won’t be rendered in the notebook), the test code and the test output cell:

SIMULATOR = DensityMatrixSimulator()
# 0.1% depolarizing noise
qbit = LineQubit(0)
circ = Circuit(X(qbit) for _ in range(80))

def simulate_with_noise(circ: Circuit) -> float:
   circuit = circ.with_noise(depolarize(p=0.001))
   rho = SIMULATOR.simulate(circuit).final_density_matrix
   # define the computational basis observable
   obs = np.diag([1, 0])
   expectation = np.real(np.trace(rho @ obs))
   return expectation

unmitigated = simulate_with_noise(circ)
exact = 1
print(f"Error in simulation is {exact - unmitigated:.{3}}")
Error in simulation is 0.0506