SageMath in Quarto

SageMath (or just Sage) is free, open-source mathematical software built on top of Python. You might think of it as Python plus a huge number of open source libraries built in.

Sage is a great resource for teaching at the university level, in part because it is so easily and freely available. One amazing tool that you could never implement in a commercial product is the Sage Cell Server. This webpage describes how I use the Sage Cell Server to embed Sage in webpages for use in my classes.

Example

Suppose I’m interested in the system \[ \begin{aligned} x^2 - 3xy &= 1 \\ y^2 - 3xy &= 1. \end{aligned} \]

I’d like to solve the system for real values of \(x\) and \(y\) and illustrate the solutions with a plot.

Here’s the solution set:

And here’s the plot:

Note that the cells are linked in the sense that there’s memory of the results from one in the other. Order of execution does matter.

The setup

The Sage Cell server provides some Javascript tools that make it easy to embed it these cells in a webpage. To use it, simply place the following three lines in the <head> of your HTML:

<script src="https://sagecell.sagemath.org/static/embedded_sagecell.js"></script>
<script>sagecell.makeSagecell({"inputLocation": ".sage", linked: true});</script>
<link rel="stylesheet" type="text/css" href="https://sagecell.sagemath.org/static/sagecell_embed.css">

If, like me, you do this with Quarto, you’d put this in your YAML header like so:

format:
    html:
        include-in-header: 
            text: |
                <script src="https://sagecell.sagemath.org/static/embedded_sagecell.js"></script>
                <script>sagecell.makeSagecell({"inputLocation": ".sage", linked: true});</script>
                <link rel="stylesheet" type="text/css" href="https://sagecell.sagemath.org/static/sagecell_embed.css">

There are a number of options, as described here. I like to use the linked: true option when I’ve got a longer document with interdependent code.

The cell code

Once the Sage Cell scripts are imported, you can place Sage code directly in your webpage, as long as long as it’s properly scoped within a script within a div like so:

<div class="sage">
  <script type="text/x-sage">
x,y = var('x,y')
eqs = [x^2-3*x*y==1, y^2-3*x*y==1]
sols = solve(eqs, [x,y])
sols = [tuple([s.rhs() for s in sol]) for sol in sols
    if all(eq.rhs().is_real() for eq in sol)]
sols
  </script>
</div>

Converting Sage notebooks

For more complicated documents, it’s typically more convenient to author Sage code and prose with a Jupyter notebook. I’ve got a ipynb-to-sagecell-qmd.py script to automate the procedure of converting the notebook to Quarto. You can use it like so:

python -B ./ipynb-to-sagecell-qmd.py ./MyNotebook.ipynb -o ./MyPage/index.qmd --css ./styles.cs