mathsoftware

A course about LaTeX and SageMath
git clone https://git.tronto.net/mathsoftware
Download | Log | Files | Refs | README | LICENSE

9-SageLatex.ipynb (10977B)


      1 {
      2  "cells": [
      3   {
      4    "cell_type": "markdown",
      5    "metadata": {},
      6    "source": [
      7     "It can happen that you need to include the results of your Sage computations and/or Sage code inside a LaTeX document. Luckily Sage provides some functions to translate its objects into LaTeX, and the listings package for LaTeX can be used to include any code (Sage, Python or any other language) in a LaTeX document.\n",
      8     "\n",
      9     "In this document we will describe some of these interactions between LaTeX and Sage."
     10    ]
     11   },
     12   {
     13    "cell_type": "markdown",
     14    "metadata": {},
     15    "source": [
     16     "# The `show()` command\n",
     17     "**Reference:** [[1](https://doc.sagemath.org/html/en/reference/repl/sage/repl/display/pretty_print.html)] (`show()` is just an alternative name for `pretty_print()`).\n",
     18     "\n",
     19     "With this command Sage will generate a picture displaying the object. The result depends on the object itself: most of them will be typeset in Latex, but for example graphics primitives (such as plots) will be displayed as pictures.\n",
     20     "\n",
     21     "You can see it as an alternative to `print()`."
     22    ]
     23   },
     24   {
     25    "cell_type": "code",
     26    "execution_count": 4,
     27    "metadata": {},
     28    "outputs": [
     29     {
     30      "name": "stdout",
     31      "output_type": "stream",
     32      "text": [
     33       "1 + 1*x + 1/2*x^2 + 1/6*x^3 + Order(x^4)\n"
     34      ]
     35     },
     36     {
     37      "data": {
     38       "text/html": [
     39        "<html><script type=\"math/tex; mode=display\">\\newcommand{\\Bold}[1]{\\mathbf{#1}}1 + 1 x + \\frac{1}{2} x^{2} + \\frac{1}{6} x^{3} + \\mathcal{O}\\left(x^{4}\\right)</script></html>"
     40       ],
     41       "text/latex": [
     42        "\\begin{math}\n",
     43        "\\newcommand{\\Bold}[1]{\\mathbf{#1}}1 + 1 x + \\frac{1}{2} x^{2} + \\frac{1}{6} x^{3} + \\mathcal{O}\\left(x^{4}\\right)\n",
     44        "\\end{math}"
     45       ],
     46       "text/plain": [
     47        "1 + 1*x + 1/2*x^2 + 1/6*x^3 + Order(x^4)"
     48       ]
     49      },
     50      "metadata": {},
     51      "output_type": "display_data"
     52     },
     53     {
     54      "name": "stdout",
     55      "output_type": "stream",
     56      "text": [
     57       "[ 1  2  3]\n",
     58       "[ 4  5  6]\n",
     59       "[ 8  9 10]\n"
     60      ]
     61     },
     62     {
     63      "data": {
     64       "text/html": [
     65        "<html><script type=\"math/tex; mode=display\">\\newcommand{\\Bold}[1]{\\mathbf{#1}}\\left(\\begin{array}{rrr}\n",
     66        "1 & 2 & 3 \\\\\n",
     67        "4 & 5 & 6 \\\\\n",
     68        "8 & 9 & 10\n",
     69        "\\end{array}\\right)</script></html>"
     70       ],
     71       "text/latex": [
     72        "\\begin{math}\n",
     73        "\\newcommand{\\Bold}[1]{\\mathbf{#1}}\\left(\\begin{array}{rrr}\n",
     74        "1 & 2 & 3 \\\\\n",
     75        "4 & 5 & 6 \\\\\n",
     76        "8 & 9 & 10\n",
     77        "\\end{array}\\right)\n",
     78        "\\end{math}"
     79       ],
     80       "text/plain": [
     81        "[ 1  2  3]\n",
     82        "[ 4  5  6]\n",
     83        "[ 8  9 10]"
     84       ]
     85      },
     86      "metadata": {},
     87      "output_type": "display_data"
     88     },
     89     {
     90      "name": "stdout",
     91      "output_type": "stream",
     92      "text": [
     93       "pi\n"
     94      ]
     95     },
     96     {
     97      "data": {
     98       "text/html": [
     99        "<html><script type=\"math/tex; mode=display\">\\newcommand{\\Bold}[1]{\\mathbf{#1}}\\pi</script></html>"
    100       ],
    101       "text/latex": [
    102        "\\begin{math}\n",
    103        "\\newcommand{\\Bold}[1]{\\mathbf{#1}}\\pi\n",
    104        "\\end{math}"
    105       ],
    106       "text/plain": [
    107        "pi"
    108       ]
    109      },
    110      "metadata": {},
    111      "output_type": "display_data"
    112     }
    113    ],
    114    "source": [
    115     "s = (e^x).series(x==0, 4)\n",
    116     "M = matrix([[1,2,3],[4,5,6],[8,9,10]])\n",
    117     "print(s)\n",
    118     "show(s)\n",
    119     "print(M)\n",
    120     "show(M)\n",
    121     "print(pi)\n",
    122     "show(pi)"
    123    ]
    124   },
    125   {
    126    "cell_type": "markdown",
    127    "metadata": {},
    128    "source": [
    129     "In a Jupyter notebook, the results above are displayed using [MathJax](https://www.mathjax.org/).\n",
    130     "\n",
    131     "If you are running this code in an interactive console (terminal) instead of a Jupyter notebook, you will get the Latex source code for those objects. You can force this behavior by using the `latex()` command."
    132    ]
    133   },
    134   {
    135    "cell_type": "markdown",
    136    "metadata": {},
    137    "source": [
    138     "# The `latex()` command\n",
    139     "**Reference:** [[2](https://doc.sagemath.org/html/en/reference/misc/sage/misc/latex.html)]\n",
    140     "\n",
    141     "This command is potentially very useful if you need to include the results of Sage computations in a Latex file, especially with complex objects like matrices or very large polynomials.\n",
    142     "\n",
    143     "Technically, this is a function that returns a string, so you need to `print()` it to see the result."
    144    ]
    145   },
    146   {
    147    "cell_type": "code",
    148    "execution_count": 5,
    149    "metadata": {},
    150    "outputs": [
    151     {
    152      "name": "stdout",
    153      "output_type": "stream",
    154      "text": [
    155       "1 + 1 x + \\frac{1}{2} x^{2} + \\frac{1}{6} x^{3} + \\mathcal{O}\\left(x^{4}\\right)\n",
    156       "\n",
    157       "\n",
    158       "\\left(\\begin{array}{rrr}\n",
    159       "1 & 2 & 3 \\\\\n",
    160       "4 & 5 & 6 \\\\\n",
    161       "8 & 9 & 10\n",
    162       "\\end{array}\\right)\n"
    163      ]
    164     }
    165    ],
    166    "source": [
    167     "print(latex(s))\n",
    168     "print(\"\\n\")\n",
    169     "print(latex(M))"
    170    ]
    171   },
    172   {
    173    "cell_type": "markdown",
    174    "metadata": {},
    175    "source": [
    176     "Interestingly, Sage can use matplotlib's PGF backend to generate Latex code for a plot. (PGF is the graphics language underlying TikZ, like TeX is the language underlying Latex)."
    177    ]
    178   },
    179   {
    180    "cell_type": "code",
    181    "execution_count": 15,
    182    "metadata": {},
    183    "outputs": [],
    184    "source": [
    185     "#latex(plot(x^2)) # The output is more than 20 pages long"
    186    ]
    187   },
    188   {
    189    "cell_type": "markdown",
    190    "metadata": {},
    191    "source": [
    192     "It is probably easier to just generate the picture and include that in your Latex document with `\\includegraphics`."
    193    ]
    194   },
    195   {
    196    "cell_type": "markdown",
    197    "metadata": {},
    198    "source": [
    199     "## A Latex name for your variables\n",
    200     "**Reference:** [[3](https://doc.sagemath.org/html/en/reference/calculus/sage/calculus/var.html)]\n",
    201     "\n",
    202     "Sometimes you might want to use variables and functions that have, for example, a Greek letter as a name. You can tell Sage that you want them displayed this way when you declare them:"
    203    ]
    204   },
    205   {
    206    "cell_type": "code",
    207    "execution_count": 16,
    208    "metadata": {},
    209    "outputs": [
    210     {
    211      "name": "stdout",
    212      "output_type": "stream",
    213      "text": [
    214       "phi1(epsilon)\n"
    215      ]
    216     },
    217     {
    218      "data": {
    219       "text/html": [
    220        "<html><script type=\"math/tex; mode=display\">\\newcommand{\\Bold}[1]{\\mathbf{#1}}e^{{\\varepsilon}} + \\phi_1\\left({\\varepsilon}\\right)</script></html>"
    221       ],
    222       "text/latex": [
    223        "\\begin{math}\n",
    224        "\\newcommand{\\Bold}[1]{\\mathbf{#1}}e^{{\\varepsilon}} + \\phi_1\\left({\\varepsilon}\\right)\n",
    225        "\\end{math}"
    226       ],
    227       "text/plain": [
    228        "e^epsilon + phi1(epsilon)"
    229       ]
    230      },
    231      "metadata": {},
    232      "output_type": "display_data"
    233     },
    234     {
    235      "data": {
    236       "text/plain": [
    237        "e^{{\\varepsilon}} + \\phi_1\\left({\\varepsilon}\\right)"
    238       ]
    239      },
    240      "execution_count": 16,
    241      "metadata": {},
    242      "output_type": "execute_result"
    243     }
    244    ],
    245    "source": [
    246     "var('epsilon', latex_name=\"\\\\varepsilon\")\n",
    247     "function('phi1', latex_name=\"\\\\phi_1\")\n",
    248     "\n",
    249     "print(phi1(epsilon))\n",
    250     "show(phi1(epsilon) + e^epsilon)\n",
    251     "latex(phi1(epsilon) + e^epsilon)"
    252    ]
    253   },
    254   {
    255    "cell_type": "markdown",
    256    "metadata": {},
    257    "source": [
    258     "**Warning:** You need to use two backspaces `\\\\`. The reason is that in Python (like in many other programming languages) the backslash symbol inside a string is used to print special characters, such as a newline `\\n`."
    259    ]
    260   },
    261   {
    262    "cell_type": "markdown",
    263    "metadata": {},
    264    "source": [
    265     "# From Jupyter to Latex\n",
    266     "**Reference:** [[4](https://nbconvert.readthedocs.io/en/latest/)]\n",
    267     "\n",
    268     "From the Jupyter menu `File > Download as` you can choose to download your work in many formats, among which there are also Latex and pdf. Personally I prefer downloading the .tex file, so then I can change the title, add an author name and make any other change I like before compiling it into a pdf file.\n",
    269     "\n",
    270     "If you choose to download the pdf file, you might need to install some extra packages. For example I had to install [`pandoc`](https://pandoc.org/), `texlive-XeTeX` and `texlive-Xdvi`, but this depends on your operating system and Latex distribution."
    271    ]
    272   },
    273   {
    274    "cell_type": "markdown",
    275    "metadata": {},
    276    "source": [
    277     "# SageTex\n",
    278     "**Reference:** [[5](https://doc.sagemath.org/html/en/tutorial/sagetex.html)]\n",
    279     "\n",
    280     "With SageTex it is possible to run Sage commands directly inside Latex, using the `\\sage{}` command. In this way you don't need to run your Sage code first and then copy the results in Latex. It can be useful especially for short Sage commands.\n",
    281     "\n",
    282     "You might need to take some extra steps to make this work on your system, see the link above."
    283    ]
    284   },
    285   {
    286    "cell_type": "markdown",
    287    "metadata": {},
    288    "source": [
    289     "# The Latex `listings` package\n",
    290     "**References:** [[6](https://en.wikibooks.org/wiki/LaTeX/Source_Code_Listings)] and [[7](https://ftp.snt.utwente.nl/pub/software/tex/macros/latex/contrib/listings/listings.pdf)]\n",
    291     "\n",
    292     "If you want to include some code (Sage, Python or anything else) in a Latex document you can use the listings package.\n",
    293     "\n",
    294     "```\n",
    295     "\\usepackage{listings}\n",
    296     "\n",
    297     "...\n",
    298     "\n",
    299     "\\begin{lstlisting}[language=Python]\n",
    300     "for i in range(0,100):\n",
    301     "    if i%5 == 0:\n",
    302     "        print(\"Multiple of 5!\")\n",
    303     "\\end{lstlisting}\n",
    304     "```\n",
    305     "\n",
    306     "You need to specify the language you are using with the `language=` option. This option can also be set at the beginning of the document using the `\\lstset{language=Python}` command.\n",
    307     "\n",
    308     "As an alternative, you can include a file directly without copying the code into the tex file, like you would do for a picture:\n",
    309     "\n",
    310     "```\n",
    311     "\\lstinputlisting[language=Python]{file.py}\n",
    312     "```\n",
    313     "\n",
    314     "It is technically possible to include Latex listings in a markdown cell of the Jupyter notebook using [this package](https://jupyter-contrib-nbextensions.readthedocs.io/en/latest/nbextensions/latex_envs/README.html), but it does not make much sense. So we will move to a Latex editor for the examples."
    315    ]
    316   },
    317   {
    318    "cell_type": "code",
    319    "execution_count": null,
    320    "metadata": {},
    321    "outputs": [],
    322    "source": []
    323   }
    324  ],
    325  "metadata": {
    326   "kernelspec": {
    327    "display_name": "SageMath 9.2",
    328    "language": "sage",
    329    "name": "sagemath"
    330   },
    331   "language_info": {
    332    "codemirror_mode": {
    333     "name": "ipython",
    334     "version": 3
    335    },
    336    "file_extension": ".py",
    337    "mimetype": "text/x-python",
    338    "name": "python",
    339    "nbconvert_exporter": "python",
    340    "pygments_lexer": "ipython3",
    341    "version": "3.8.5"
    342   }
    343  },
    344  "nbformat": 4,
    345  "nbformat_minor": 4
    346 }