Skip to main content
\( \newcommand{\lt}{<} \newcommand{\gt}{>} \newcommand{\amp}{&} \)

Section9SageMath content

Subsection9.1SageMathCells

Including computational SageMath cells is pretty easy with sage, input, and output. The last tag is useful for producing a PDF that includes the result of the code's execution.

<sage>
    <input>
        2+2
    </input>
    <output>
        4
    </output>
</sage>
Listing9.1SageMath cell

The code in Listing 9.1 produces the following output:

SageMathCells on a single HTML page are automatically linked so that a cell can use the results of computations done in earlier cells on the same page.

Subsection9.2sageplot

Sometimes you don't want to provide an interactive SageMath environment in the middle of your book (or a chunk of code) but you would like to produce a figure to include in your project by using SageMath. The cleanest way to do this his to put the SageMath code right in your PreTeXt project and use the mbx script to produce the image files required for your chosen output formats. This is accomplished by using sageplot and the mbx script that we discussed in Subsection 7.3. (In particular, see the aside in that subsection about the additional packages that must be installed and configured to use the mbx script.)

<figure xml:id="fig-sage-cubic">
    <caption>A cubic plotted by SageMath on <m>[-3,2]</m></caption>
    <image xml:id="sageplot-cubic" width="50%">
        <description>A cubic function on the interval [-3,2]</description>
        <sageplot>
            f(x) = (x-1)*(x+1)*(x-2)
            plot(f, (x, -3, 2), color='blue', thickness=3)
        </sageplot>
    </image>
</figure>
Listing9.2sageplot to produce a graphic

We need to run the mbx script to actually make the image files required. If you want to make both HTML and PDF via , you'll need to run it twice. The first command below (again, enter on one line) makes the SVG to use on the web, and the second makes what you need for . There is an all option that can be passed after -f instead of svg or pdf, but that is more likely to raise errors because some source code cannot produce certain output formats. It's best to stay away from error-producing steps until you're comfortable with debugging your system.

[path to mathbook]/script/mbx -c sageplot -f svg
                -d ./images [path to PTX source file]
[path to mathbook]/script/mbx -c sageplot -f pdf
                -d ./images [path to PTX source file]

The code in Listing 9.2 produces the following output.

A cubic function on the interval [-3,2]
Figure9.3A cubic plotted by SageMath on \([-3,2]\)