8.5 Embed SageMath
R Markdown does not support SageMath. So, we actually embed SageMath in HTML,9 which is supported by R Markdown. SageMath is an open source program with
- Powerful symbolic calculation.
- Simple syntax that draws pretty 3D interactive graphs.
- Interactive component for building widgets.
Plus, there is a free server called SageMathCells that can render all the calculations online with reasonable speed. Let’s see how to take the advantage of all these three aspects.
- Create a blank sageHeader.html file, then paste the following HTML codes and save the file1011. The purposes of the codes are
- Send all interactive calcuation to the SageMathCells server.
- Defines two HTML classes:
- The class sage_all has a Sage code editor, an evaluation button and the output panel.
- The class sage_simple only displays the result panel.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script src="https://sagecell.sagemath.org/static/embedded_sagecell.js"></script>
<script>$(function () {
sagecell.makeSagecell({inputLocation: 'div.sage_all',
linked: 'false',
autoeval: 'false',
evalButtonText: 'Evaluate'});
sagecell.makeSagecell({inputLocation: 'div.sage_simple',
autoeval: 'true',
hide: ['editor','evalButton', 'permalink']});
});
</script>
</head>
</html>
- Create a R Markdown file and Source the sageHeader.html file in a R chunk using the htmltools package. Suppose the R Markdown file and the html file are in the same folder:
```{r eval=TRUE, echo=FALSE}
htmltools::includeHTML("sageHeader.html")
```
- If we’d like the audience to type/modify the Sage codes, use the sage_all class. Insert the following code chunk in R Markdown to output a Sage editor and an evaluation buttonin. (There is a button in the far right of the editor, which makes the editor full screen for easy editing.)
```{block, type="sage_all"}
<script type="text/x-sage">
diff(sin(x)^2, x)
</script>
```
Then it shows the derivative of \(\sin^2(x)\) from the code chunk we typed in. Next, we can modify the editor and evaluate the modified codes.
- If we only want to display a dynamic output (e.g., a 3D graph),, use the sage_simple class. The following HTML codes in the R Markdown document will only display a hypobolic paraboloid. (It may take a while for the 3D image to show up. Refresh the browser might help.)
```{block, type="sage_simple"}
<script type="text/x-sage">
# Declare variables
var('u,v')
# Choose the jet colormap.
color_map = colormaps.jet
# c is the color function, whose range must be normalized (converted to between 0 and 1).
def c(u,v): return ((u^2-v^2)+1)/2
# 3d plot and settings
surf = parametric_plot3d( [u, v, u^2-v^2], (u, -1, 1), (v, -1, 1), color = (c, color_map))
show(surf, viewer='threejs', frame=False)
</script>
```
- Finally, don’t forget the wonderful interactive components of Sage.12 Below is an example of volume by revolution (cylindrical shells).