Examples of using latex in cocalc
% General example LaTeX file for including Sage calculations and plots1% Build with:2%3% (pdf)latex example.tex; sage example.sagetex.sage; pdflatex example.tex4%5% Please read README and the documentation of the SageTeX package for6% more information!7%89\documentclass{article}10\title{Examples of embedding Sage in \LaTeX{} with \textsf{Sage\TeX}}11\author{Dan Drake and others}12\usepackage{hyperref}13% If you want to see the examples in the section "Plotting14% (combinatorial) graphs with TikZ" remove the \begin{comment}15% and \end{comment} in that section and uncomment the following line.16%\usepackage{tkz-berge}171819\usepackage{sagetex}20%21% If you want SageTeX to use Imagemagick's `convert' utility to make eps22% files from png files when generating a dvi file, add the "imagemagick"23% option above:24%25% \usepackage[imagemagick]{sagetex}2627\setlength{\sagetexindent}{10ex}2829\begin{document}30\maketitle3132\section{Inline Sage, code blocks}3334This is an example $2+2=\sage{2+2}$. If you raise the current year mod35$100$ (which equals $\sage{mod(\the\year, 100)}$) to the power of the36current day ($\the\day$), you get $\sage{Integer(mod(\the\year,37100))^\the\day}$. Also, $\the\year$ modulo $42$ is $\sage{\the\year38\percent 42}$.3940Code block which uses a variable \texttt{s} to store the solutions:41\begin{sageblock}421+143var('a,b,c')44eqn = [a+b*c==1, b-a*c==0, a+b==5]45s = solve(eqn, a,b,c)46\end{sageblock}4748Solutions of $\mbox{eqn}=\sage{eqn}$:49\[50\sage{s[0]}51\]52\[53\sage{s[1]}54\]5556Now we evaluate the following block:57\begin{sageblock}58E = EllipticCurve("37a")59\end{sageblock}60You can't do assignment inside \verb|\sage| macros, since Sage doesn't61know how to typeset the output of such a thing. So you have to use a62code block. The elliptic curve $E$ given by $\sage{E}$ has discriminant63$\sage{E.discriminant()}$.6465You can do anything in a code block that you can do in Sage and/or66Python. Here we save an elliptic curve into a file.67\begin{sageblock}68try:69E = load('E2')70except IOError:71E = EllipticCurve([1,2,3,4,5])72E.anlist(100000)73E.save('E2')74\end{sageblock}7576The 9999th Fourier coefficient of $\sage{E}$ is77$\sage{E.anlist(100000)[9999]}$.7879The following code block doesn't appear in the typeset file\dots80\begin{sagesilent}81e = 282e = 3*e + 183\end{sagesilent}84but we can refer to whatever we did in that code block: $e=\sage{e}$.8586\begin{sageblock}87var('x')88f(x) = log(sin(x)/x)89\end{sageblock}90The Taylor Series of $f$ begins: $\sage{ f.taylor(x, 0, 10) }$.9192\section{Plotting}9394Here's a very large plot of the elliptic curve $E$.9596\sageplot{E.plot(-3,3)}9798\begin{sagesilent}99# the var line is unecessary unless you've defined x to be something100# other than a symbolic variable101var('x')102f(x) = -x^3+3*x^2+7*x-4103\end{sagesilent}104105You can use variables to hold plot objects and do stuff with them.106\begin{sageblock}107p = plot(f, x, -5, 5)108\end{sageblock}109110Here's a small plot of $f$ from $-5$ to $5$, which I've centered:111112\begin{center} \sageplot[scale=.2]{p} \end{center}113114On second thought, use a size of $3/4$ the \verb|\textwidth| and don't115use axes:116117\sageplot[width=.75\textwidth]{p, axes=False}118119Remember, you're using Sage, and can therefore call upon any of the120software packages Sage is built out of.121\begin{sageblock}122f = maxima('sin(x)^2*exp(x)')123g = f.integrate('x')124\end{sageblock}125Plot $g(x)$, but don't typeset it.126\begin{sagesilent}127# g is a Maxima thingy, it needs to get converted into a Sage object128plot1 = plot(g.sage(),x,-1,2*pi)129\end{sagesilent}130131You can specify a file format and options for \verb|includegraphics|.132The default is for EPS and PDF files, which are the best choice in133almost all situations. (Although see the section on 3D plotting.)134135\sageplot[angle=45, width=.5\textwidth][png]{plot1}136137If you use regular \verb|latex| to make a DVI file, you'll see a box,138because DVI files can't include PNG files. If you use \verb|pdflatex|139that will work. See the documentation for details.140141When using \verb|\sageplot|, you can pass in just about anything that142Sage can call \verb|.save()| on to produce a graphics file:143144\begin{center}145\sageplot{plot1 + plot(f.sage(),x,-1,2*pi,rgbcolor=hue(0.4)), figsize=[1,2]}146\end{center}147148To fiddle with aspect ratio, first save the plot object:149150\begin{sageblock}151p = plot(x, 0, 1) + circle((0,0), 1)152p.set_aspect_ratio(1)153\end{sageblock}154155Now plot it and see the circular circle and nice 45 degree angle:156157\sageplot[scale=.33]{p}158159Indentation and so on works fine.160\begin{sageblock}161s = 7162s2 = 2^s163P.<x> = GF(2)[]164M = matrix(parent(x),s2)165for i in range(s2):166p = (1+x)^i167pc = p.coefficients(sparse=False)168a = pc.count(1)169for j in range(a):170idx = pc.index(1)171M[i,idx+j] = pc.pop(idx)172173matrixprogram = matrix_plot(M,cmap='Greys')174\end{sageblock}175And here's the picture:176177\sageplot[scale=.5]{matrixprogram}178179Reset \texttt{x} in Sage so that it's not a generator for the polynomial180ring: \sage{var('x')}181182183\subsection{Plotting (combinatorial) graphs with TikZ}184\label{sec:plotting-graphs-with}185186Sage now includes some nice support for plotting graphs using187\href{http://www.texample.net/tikz/}{TikZ}. Here, we mean things with188vertices and edges, not graphs of a function of one or two variables.189190The graphics in this section depends on the \texttt{tkz-berge} package,191which is generally only available in newer \TeX{} distributions (for192example, \TeX Live 2011 and newer). That package depends in turn on193TikZ 2.0, which is also only available in newer \TeX{} distributions.194Installing both of those is in some cases nontrivial, so this section is195disabled by default.196197If you have TikZ and \texttt{tkz-berge} and friends, remove the198\texttt{comment} environments below.199200\begin{comment}201202First define our graph:203204\begin{sageblock}205g = graphs.PetersenGraph()206g.set_latex_options(tkz_style='Art')207\end{sageblock}208209Now just do \verb|\sage{}| on it to plot it. You'll need to use the210\texttt{tkz-berge} package for this to work; that package in turn211depends on \texttt{tkz-graph} and TikZ. See212\href{http://altermundus.fr/pages/tkz.html}{\texttt{altermundus.fr/pages/tkz.html}};213if you're using a recent version of \TeX Live, you can use its package214manager to install those packages, or get them from CTAN:215\href{http://www.ctan.org/pkg/tkz-berge}{\texttt{www.ctan.org/pkg/tkz-berge}}.216See217\href{http://doc.sagemath.org/html/en/reference/sage/graphs/graph_latex.html}{``\LaTeX{}218Options for Graphs''} in the Sage reference manual for more details.219220\begin{center}221\sage{g}222\end{center}223224The above command just outputs a \texttt{tikzpicture} environment, and225you can control that environment using anything supported by226TikZ---although the output of \verb|\sage{g}| explicitly hard-codes a227lot of things and cannot be flexibly controlled in its current form.228229\tikzstyle{every picture}=[rotate=45, scale=1/2]230231\begin{center}232\sage{g}233\end{center}234235\tikzstyle{every picture}=[]236237Here's some more graphs, plotted using the usual plot routines.238239\sageplot[scale=.5]{graphs.FlowerSnark().plot()}240241\begin{sageblock}242G4 = DiGraph({1:[2,2,3,5], 2:[3,4], 3:[4], 4:[5,7], 5:[6]},\243multiedges=True)244G4plot = G4.plot(layout='circular')245\end{sageblock}246247\sageplot[scale=.5]{G4plot, axes=False}248249\end{comment}250251Reset \texttt{x} in Sage so that it's not a generator for the polynomial252ring: \sage{var('x')}253254255\subsection{Plotting (combinatorial) graphs with TikZ}256\label{sec:plotting-graphs-with}257258Sage now includes some nice support for plotting graphs using259\href{http://www.texample.net/tikz/}{TikZ}. Here, we mean things with260vertices and edges, not graphs of a function of one or two variables.261262The graphics in this section depends on the \texttt{tkz-berge} package,263which is generally only available in newer \TeX{} distributions (for264example, \TeX Live 2011 and newer). That package depends in turn on265TikZ 2.0, which is also only available in newer \TeX{} distributions.266Installing both of those is in some cases nontrivial, so this section is267disabled by default.268269If you have TikZ and \texttt{tkz-berge} and friends, remove the270\texttt{comment} environments below.271272\begin{comment}273274First define our graph:275276\begin{sageblock}277g = graphs.PetersenGraph()278g.set_latex_options(tkz_style='Art')279\end{sageblock}280281Now just do \verb|\sage{}| on it to plot it. You'll need to use the282\texttt{tkz-berge} package for this to work; that package in turn283depends on \texttt{tkz-graph} and TikZ. See284\href{http://altermundus.fr/pages/tkz.html}{\texttt{altermundus.fr/pages/tkz.html}};285if you're using a recent version of \TeX Live, you can use its package286manager to install those packages, or get them from CTAN:287\href{http://www.ctan.org/pkg/tkz-berge}{\texttt{www.ctan.org/pkg/tkz-berge}}.288See289\href{http://doc.sagemath.org/html/en/reference/sage/graphs/graph_latex.html}{``\LaTeX{}290Options for Graphs''} in the Sage reference manual for more details.291292\begin{center}293\sage{g}294\end{center}295296The above command just outputs a \texttt{tikzpicture} environment, and297you can control that environment using anything supported by298TikZ---although the output of \verb|\sage{g}| explicitly hard-codes a299lot of things and cannot be flexibly controlled in its current form.300301\tikzstyle{every picture}=[rotate=45, scale=1/2]302303\begin{center}304\sage{g}305\end{center}306307\tikzstyle{every picture}=[]308309Here's some more graphs, plotted using the usual plot routines.310311\sageplot[scale=.5]{graphs.FlowerSnark().plot()}312313\begin{sageblock}314G4 = DiGraph({1:[2,2,3,5], 2:[3,4], 3:[4], 4:[5,7], 5:[6]},\315multiedges=True)316G4plot = G4.plot(layout='circular')317\end{sageblock}318319\sageplot[scale=.5]{G4plot, axes=False}320321\end{comment}322323\subsection{3D plotting}3243253D plotting right now (Sage version 4.3.4) is problematic because326there's no convenient way to produce vector graphics. We can make PNGs,327though, so if you pass \verb|sageplot| a graphics object that cannot be328saved to EPS or PDF format, we will automatically save to a PNG file,329which can be used when typesetting a PDF file, but not when creating a330DVI file. However, you can specify the ``\texttt{imagemagick}'' option,331which will use the Imagemagick \texttt{convert} utility to make EPS332files. See the documentation for details.333334% FIXME: not sure this works with remote sagetex335336\begin{sagesilent}337x, y = var('x y')338\end{sagesilent}339340Here's a 3D plot whose format we do not specify; it will automatically341get saved as a PNG file and won't work when using \texttt{latex} to make342a DVI file.343344\sageplot[scale=.5]{plot3d(sin(pi*(x^2+y^2))/2,(x,-1,1),(y,-1,1))}345346Here's the (perhaps-not-so-) famous Sage cube graph in 3D.347348\begin{sageblock}349G = graphs.CubeGraph(5)350\end{sageblock}351352% need empty [] so sageplot knows you want png format, and aren't353% passing an option to includegraphics354\sageplot[][png]{G.plot3d()}355356\section{Pausing Sage\TeX}357\label{sec:pausing-sagetex}358359Sometimes you want to ``pause'' for a bit while writing your document if360you have embedded a long calculation or just want to concentrate on the361\LaTeX{} and ignore any Sage stuff. You can use the \verb|\sagetexpause|362and \verb|\sagetexunpause| macros to do that.363364\sagetexpause365366A calculation: $\sage{factor(2^325 + 1)}$ and a code environment that367simulates a time-consuming calculation. While paused, this will get368skipped over.369\begin{sageblock}370import time371time.sleep(15)372\end{sageblock}373374Graphics are also skipped: \sageplot{plot(2*sin(x^2) + x^2, (x, 0, 5))}375376\sagetexunpause377378\section{Make Sage write your \LaTeX{} for you}379380With \textsf{Sage\TeX}, you can not only have Sage do your math for you,381it can write parts of your \LaTeX{} document for you! For example, I382hate writing \texttt{tabular} environments; there's too many fiddly383little bits of punctuation and whatnot\ldots and what if you want to add384a column? It's a pain---or rather, it \emph{was} a pain. Just write a385Sage/Python function that outputs a string of \LaTeX{} code, and use386\verb|\sagestr|. Here's how to make Pascal's triangle.387388\begin{sageblock}389def pascals_triangle(n):390# start of the table391s = [r"\begin{tabular}{cc|" + "r" * (n+1) + "}"]392s.append(r" & & $k$: & \\")393# second row, with k values:394s.append(r" & ")395for k in [0..n]:396s.append("& {0} ".format(k))397s.append(r"\\")398# the n = 0 row:399s.append(r"\hline" + "\n" + r"$n$: & 0 & 1 & \\")400# now the rest of the rows401for r in [1..n]:402s.append(" & {0} ".format(r))403for k in [0..r]:404s.append("& {0} ".format(binomial(r, k)))405s.append(r"\\")406# add the last line and return407s.append(r"\end{tabular}")408return ''.join(s)409410# how big should the table be?411n = 8412\end{sageblock}413414Okay, now here's the table. To change the size, edit \texttt{n} above.415If you have several tables, you can use this to get them all the same416size, while changing only one thing.417418\begin{center}419\sagestr{pascals_triangle(n)}420\end{center}421422\section{Include doctest-like examples in your document}423424Here are some examples of using the \texttt{sageexample} environment:425\begin{sageexample}426sage: 2+24274428sage: print 'middle'429middle430sage: factor(x^2 + 2*x + 1)431(x + 1)^2432\end{sageexample}433Note above that no output from the \texttt{print} statement appears.434That is because we have to use Python's \texttt{exec} to execute that435statement (and not \texttt{eval()}), and we can't get the output from436that.437438That said, if you want to see the plain-text output you put into your439\verb|.tex| file as well as the Sage-computed typeset output, renew the440\texttt{sageexampleincludetextoutput} command to True:441\begin{verbatim}442\renewcommand{\sageexampleincludetextoutput}{True}443\end{verbatim}444\renewcommand{\sageexampleincludetextoutput}{True}445This can be useful to check that the two outputs are consistent. Here's446the print statement with text output included:447\begin{sageexample}448sage: print 'middle'449middle450\end{sageexample}451When typesetting your document, the validity of the outputs is not452checked. In fact, the provided outputs are completely ignored:453\renewcommand{\sageexampleincludetextoutput}{True}454\begin{sageexample}455sage: is_prime(57)456toothpaste457\end{sageexample}458\renewcommand{\sageexampleincludetextoutput}{False}%459Multiline statements with the ``\verb|....:|'' continuation marks are460supported, as are triple-quoted strings delimited by single quotes461(double quotes won't work):462\begin{sageexample}463sage: gcd([5656565656,464....: 4747474747,465....: 123456789])4661467sage: mystr = '''my468....: string469....: has470....: several471....: lines.'''472sage: len(mystr)47328474sage: def f(a):475....: '''This function is really quite nice,476....: although perhaps not very useful.'''477....: print "f called with a = ", a478....: y = integrate(SR(cyclotomic_polynomial(10)) + a, x)479....: return y + 1480sage: f(x)481f called with a = x4821/5*x^5 - 1/4*x^4 + 1/3*x^3 + x + 1483\end{sageexample}484Note that the ``$f$ called with\ldots'' stuff doesn't get typeset, since485when running Sage on \texttt{example.sagetex.sage}, that gets printed to the486terminal.487488Typesetting your document produces a file named489\texttt{example\_doctest.sage} containing all the doctest-like examples,490and you can have Sage check them for you with:491\begin{verbatim}492$ sage -t example_doctest.sage493\end{verbatim}494You should get a doctest failure from the ``toothpaste'' line above. The495line numbers from \texttt{sage -t} refer to the ``\verb|_doctest.sage|''496file.497498Beware that \texttt{sage -t} does not really handle file names with499special characters in them, particularly dashes, dots, and spaces---this500ultimately comes from the way Python interprets \texttt{import}501statements. Also, running doctests on files outside the main Sage502library does not always work, so contact \texttt{sage-support} if you503run into troubles.504505Some more examples. This environment is implemented a little bit506differently than the other environments, so it's good to make sure that507definitions are preserved across multiple uses. This will correctly508define $a$, but not print its output because the statement is made up of509a sequence of expressions and we can't use Python's \texttt{eval()}; we510have to use \texttt{exec} and we can't capture the output from that.511\begin{sageexample}512sage: 1; 2; a=4; 3; a5131514251535164517\end{sageexample}518However, after that, Sage should remember that $a = \sage{a}$ and be519able to use that in future \texttt{sageexample} blocks:520\begin{sageexample}521sage: f(a)522f called with a = 45231/5*x^5 - 1/4*x^4 + 1/3*x^3 - 1/2*x^2 + 5*x + 1524\end{sageexample}525526\section{Plotting functions in Ti\emph{k}Z with Sage\TeX}527528(The code in this section should work with any reasonable version of529Ti\emph{k}Z, which means it should work with all but the most terribly530out-of-date \TeX{} installations---but to make sure we can accomodate531everyone, the code here is commented out. You can almost certainly532uncomment and run them. Make sure you do \verb|\usepackage{tikz}| in the533preamble.)534535\begin{comment}536537The wonderful graphics package TikZ has the ability to plot functions by538reading in a sequence of points from an external file---see chapter 18,539page 193 of the TikZ manual. This facility is designed around files540produced by Gnuplot, but the file format is so simple that it's very541easy to use Sage\TeX{} to generate them. First you need a function that542will evaluate functions and write the results into a file:543544545% set up plotting stuff546\begin{sageblock}547def gnuplot(x, y, tvals_, fn):548"""549Write out a gnuplot-style file of points x(t), y(t).550"""551tvals = list(tvals_)552lines = ['#This is a gnuplot-style file written by SageTeX.',553'#x: {0}'.format(x),554'#y: {0}'.format(y),555'#Curve 0, {0} points'.format(len(tvals)),556'#x y type']557fmt = lambda _: _.n().str(no_sci=2)558for t in tvals:559try:560lines.append('{0} {1} i'.format(fmt(x(t)), fmt(y(t))))561except ValueError, ZeroDivisonError:562pass563with open(fn, 'w') as f:564f.write('\n'.join(lines) + '\n')565\end{sageblock}566567There probably should be some more exceptions in that list, and the568above code doesn't check to make sure it's writing real values, but then569again, this is just a file of examples!570571Then you define callable functions x and y and pass them in, along with572a sequence of values and a file name. Here's a plot that I used on a573calculus exam:574575\begin{sageblock}576r(t) = 1 - 2*sin(3*t)577x(t) = r(t)*cos(t)578y(t) = r(t)*sin(t)579gnuplot(x, y, srange(0, 2*pi + .05, .05), 'example-tikz1.table')580\end{sageblock}581582(Usually you would do that in sagesilent environments, I guess.)583584Then you call TikZ with your plot.585586\begin{tikzpicture}587\draw[very thin,->] (-3.25,0) -- (3.25,0);588\draw[very thin,->] (0,-3.25) -- (0,3.25);589\draw[smooth] plot file {example-tikz1.table};590\end{tikzpicture}591592For regular Cartesian plots, just pass in the identity function for x:593594\begin{sageblock}595x = lambda t: t596y(t) = t*sin(1/t)597gnuplot(x, y, [0.01, 0.02..(0.5)] + [0.55, 0.6..2], 'example-tikz2.table')598\end{sageblock}599600\begin{tikzpicture}601\draw[very thin,->] (-0.25,0) -- (2,0);602\draw[very thin,->] (0,-1/3) -- (0,1);603\draw[smooth, red] plot file {example-tikz2.table};604\end{tikzpicture}605606This style of plotting will become even more useful and powerful when607the new TikZ Data Visualization library is available---you will be able608to feed TikZ a bunch of data points, and it automatically make a very609nice plot for you, including axes, labels, and so on.610611\end{comment}612613\section{The \texttt{sagecommandline} environment}614615When writing a \TeX{} document about Sage, you may want to show some616examples of commands and their output. But naturally, you are lazy and617don't want to cut and paste the output into your document. ``Why should618I have to do anything? Why can't Sage and \TeX{} cooperate and do it for619me?'' you may cry. Well, they \emph{can} cooperate:620621\begin{sagecommandline}622sage: 1+1623sage: is_prime(57)624sage: if is_prime(57):625....: print 'prime'626....: else:627....: print 'composite'628\end{sagecommandline}629630Note that the output of the commands is not included in the source file,631but are included in the typeset output.632633Because of the way the environment is implemented, not everything is634exactly like using Sage in a terminal: the two commands below (and the635``if is prime'' one above, did you notice that?) would produce some636output, but don't here:637638\begin{sagecommandline}639sage: x = 2010; len(x.divisors())640sage: print 'Hola, mundo!'641\end{sagecommandline}642643The difference lies in the Python distinction between statements and644expressions; we can use \texttt{eval()} for an expression and get its645output, but we must use \texttt{exec} for a statement and can't get the646output, if any.647648One nice thing is that you can set labels by using an @ sign:649650\begin{sagecommandline}651sage: l = matrix([[1,0,0],[3/5,1,0],[-2/5,-2,1]])652sage: d = diagonal_matrix([15, -1, 4]) #@\label{diagonal}653sage: u = matrix([[1,0,1/3],[0,1,2],[0,0,1]]) #@\label{anotherlabel} \# foo654sage: l*d*u # this is a comment655\end{sagecommandline}656657And then refer to that label: it was on line \ref{diagonal}, which is on658page \pageref{diagonal}. Note that the other text after the hash mark on659that line does not get typeset as a comment, and that you cannot have660any space between the hash mark and the~@. You will also need to typeset661your document \emph{twice}662663You can also typeset the output by changing the value of664\verb|\sagecommandlinetextoutput| to False:665\renewcommand{\sagecommandlinetextoutput}{False}666\begin{sagecommandline}667sage: l*d*u668sage: x = var('x')669sage: (1-cos(x)^2).trig_simplify()670\end{sagecommandline}671672\renewcommand{\sagecommandlinetextoutput}{True}673674The Sage input and output is typeset using the \texttt{listings} package675with the styles \texttt{SageInput} and \texttt{SageOutput},676respectively. If you don't like the defaults you can change them. It is677recommended to derive from \texttt{DefaultSageInput} and678\texttt{DefaultSageOutput}, for example\ldots679\lstdefinestyle{SageInput}{style=DefaultSageInput,basicstyle={\color{red}}}680\lstdefinestyle{SageOutput}{style=DefaultSageOutput,basicstyle={\color{green}}}681makes things overly colorful:682\begin{sagecommandline}683sage: pi.n(100)684\end{sagecommandline}685\lstdefinestyle{SageInput}{style=DefaultSageInput}686\lstdefinestyle{SageOutput}{style=DefaultSageOutput}687688Plotting things doesn't automatically pull in the plot, just the text689representation of the plot (the equivalent of applying \texttt{str()} to690it):691692\begin{sagecommandline}693sage: plot(sin(x), (x, 0, 2*pi))694\end{sagecommandline}695696You can include output, but it will be ignored. This is useful for697doctesting, as all the \texttt{sagecommandline} environment things get698put into the ``\texttt{\_doctest.sage}'' file. However, note that if you699don't include any output, then the corresponding doctest will fail if700the command produces output. The doctest output from this file will have701lots of failures because not many of the commands have output included702in the source \texttt{.tex} file.703704The command below has incorrect output included in the \texttt{.tex}705file; in the PDF, you see the correct Sage-computed answer, but if you706do \texttt{sage -t example\_doctest.sage} you will get a genuine doctest707failure.708\begin{sagecommandline}709sage: factor(x^2 + 2*x + 1)710(x + 999)^2711\end{sagecommandline}712713\end{document}714715