Ticket #11583: example.tex

File example.tex, 13.3 KB (added by mderickx, 10 years ago)
Line
1 % General example LaTeX file for including Sage calculations and plots
2% Build with:
3%
4%   (pdf)latex example.tex; sage example.sage; pdflatex example.tex
5%
8
9\documentclass{article}
10\title{Examples of embedding Sage in \LaTeX{} with \textsf{Sage\TeX}}
11\author{Dan Drake and others}
12\usepackage{hyperref}
13\usepackage{verbatim}
14% if you want to show the section: "Plotting (combinatorial) graphs with TikZ"
15% remove the \begin{commen} and \end{comment} below and
16% then uncomment the following line
17%\usepackage{tkz-berge}
18
19\usepackage{sagetex}
20%
21% If you want SageTeX to use Imagemagick's convert' utility to make eps
22% files from png files when generating a dvi file, add the "imagemagick"
23% option above:
24%
25%    \usepackage[imagemagick]{sagetex}
26
27\setlength{\sagetexindent}{10ex}
28
29\begin{document}
30\maketitle
31
32\section{Inline Sage, code blocks}
33
34This is an example $2+2=\sage{2+2}$. If you raise the current year mod
35$100$ (which equals $\sage{mod(\the\year, 100)}$) to the power of the
36current day ($\the\day$), you get $\sage{Integer(mod(\the\year, 37100))^\the\day}$. Also, $\the\year$ modulo $42$ is $\sage{\the\year 38\percent 42}$.
39
40Code block which uses a variable \texttt{s} to store the solutions:
41\begin{sageblock}
42 1+1
43 var('a,b,c')
44 eqn = [a+b*c==1, b-a*c==0, a+b==5]
45 s = solve(eqn, a,b,c)
46\end{sageblock}
47
48Solutions of $\mbox{eqn}=\sage{eqn}$:
49$50\sage{s[0]} 51$
52$53\sage{s[1]} 54$
55
56Now 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't
61know how to typeset the output of such a thing. So you have to use a
62code block. The elliptic curve $E$ given by $\sage{E}$ has discriminant
63$\sage{E.discriminant()}$.
64
65You can do anything in a code block that you can do in Sage and/or
66Python. Here we save an elliptic curve into a file.
67\begin{sageblock}
68try:
70except IOError:
71    E = EllipticCurve([1,2,3,4,5])
72    E.anlist(100000)
73    E.save('E2')
74\end{sageblock}
75
76The 9999th Fourier coefficient of $\sage{E}$ is
77$\sage{E.anlist(100000)[9999]}$.
78
79The following code block doesn't appear in the typeset file\dots
80\begin{sagesilent}
81  e = 2
82  e = 3*e + 1
83\end{sagesilent}
84but we can refer to whatever we did in that code block: $e=\sage{e}$.
85
86\begin{sageblock}
87  var('x')
88  f(x) = log(sin(x)/x)
89\end{sageblock}
90The Taylor Series of $f$ begins: $\sage{ f.taylor(x, 0, 10) }$.
91
92\section{Plotting}
93
94Here's a plot of the elliptic curve $E$.
95
96\sageplot{E.plot(-3,3)}
97
98\begin{sagesilent}
99  # the var line is unecessary unless you've defined x to be something
100  # other than a symbolic variable
101  var('x')
102  f(x) = -x^3+3*x^2+7*x-4
103\end{sagesilent}
104
105You can use variables to hold plot objects and do stuff with them.
106\begin{sageblock}
107  p = plot(f, x, -5, 5)
108\end{sageblock}
109
110Here's a small plot of $f$ from $-5$ to $5$, which I've centered:
111
112\begin{center} \sageplot[scale=.2]{p} \end{center}
113
114On second thought, use the default size of $3/4$ the \verb|\textwidth|
115and don't use axes:
116
117\sageplot{p, axes=False}
118
119Remember, you're using Sage, and can therefore call upon any of the
120software 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 object
128  plot1 = plot(g.sage(),x,-1,2*pi)
129\end{sagesilent}
130
131You can specify a file format and options for \verb|includegraphics|.
132The default is for EPS and PDF files, which are the best choice in
133almost all situations. (Although see the section on 3D plotting.)
134
135\sageplot[angle=45, width=.5\textwidth][png]{plot1}
136
137If 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.
140
141When using \verb|\sageplot|, you can pass in just about anything that
142Sage can call \verb|.save()| on to produce a graphics file:
143
144\begin{center}
145\sageplot{plot1 + plot(f.sage(),x,-1,2*pi,rgbcolor=hue(0.4)), figsize=[1,2]}
146\end{center}
147
148To fiddle with aspect ratio, first save the plot object:
149
150\begin{sageblock}
151  p = plot(x, 0, 1) + circle((0,0), 1)
152  p.set_aspect_ratio(1)
153\end{sageblock}
154
155Now plot it and see the circular circle and nice 45 degree angle:
156
157\sageplot[scale=.33]{p}
158
159Indentation and so on works fine.
160\begin{sageblock}
161 s     = 7
162 s2    = 2^s
163 P.<x> = GF(2)[]
164 M     = matrix(parent(x),s2)
165 for i in range(s2):
166    p  = (1+x)^i
167    pc = p.coeffs()
168    a  = pc.count(1)
169    for j in range(a):
170        idx        = pc.index(1)
171        M[i,idx+j] = pc.pop(idx)
172
173 matrixprogram = matrix_plot(M,cmap='Greys')
174\end{sageblock}
175And here's the picture:
176
177\sageplot{matrixprogram}
178
179Reset \texttt{x} in Sage so that it's not a generator for the polynomial
180ring: \sage{var('x')}
181
182
183\subsection{Plotting (combinatorial) graphs with TikZ}
184
185This example depends on the tkz-berge package. This package wich is not part of sagetex can be a lot harder to get to work then sagetex and hence is the example depending on this package is not enabled by default. If you have tkz-berge package installed correctly you can remove the \begin{verbatim}\begin{comment}\end{verbatim} and \begin{verbatim}\end{comment}\end{verbatim} lines below and uncomment the \begin{verbatim}\usepackage{tkz-berge}\end{verbatim}, at the top of this file to show this example.
186
187\begin{comment}
188\label{sec:plotting-graphs-with}
189
190Sage now includes some nice support for plotting graphs using
191\href{http://www.texample.net/tikz/}{TikZ}. Here, we mean things with
192vertices and edges, not graphs of a function of one or two variables.
193
194First define our graph:
195
196\begin{sageblock}
197  g = graphs.PetersenGraph()
198  g.set_latex_options(tkz_style='Art')
199\end{sageblock}
200
201Now just do \verb|\sage{}| on it to plot it. You'll need to use the
202\href{http://altermundus.com/pages/graphtheory.html}{\texttt{tkz-berge}}
203package for this to work; that package in turn depends on
204\href{http://altermundus.com/pages/graph.html}{\texttt{tkz-graph}} and
205TikZ. See
206\href{http://sagemath.org/doc/reference/sage/graphs/graph_latex.html}{\LaTeX{}
207  Options for Graphs''} in the Sage reference manual for more details.
208
209\begin{center}
210  \sage{g}
211\end{center}
212
213The above command just outputs a \texttt{tikzpicture} environment, and
214you can control that environment using anything supported by
215TikZ---although the output of \verb|\sage{g}| explicitly hard-codes a
216lot of things and cannot be flexibly controlled in its current form.
217
218\tikzstyle{every picture}=[rotate=45, scale=1/2]
219
220\begin{center}
221  \sage{g}
222\end{center}
223
224Here's some more graphs, plotted using the usual plot routines.
225
226\sageplot[scale=.5]{graphs.FlowerSnark().plot()}
227
228\begin{sageblock}
229G4 = DiGraph({1:[2,2,3,5], 2:[3,4], 3:[4], 4:[5,7], 5:[6]},\
230             multiedges=True)
231G4plot = G4.plot(layout='circular')
232\end{sageblock}
233
234\sageplot[scale=.5]{G4plot, axes=False}
235\end{comment}
236
237\subsection{3D plotting}
238
2393D plotting right now (Sage version 4.3.4) is problematic because
240there's no convenient way to produce vector graphics. We can make PNGs,
241though, so if you pass \verb|sageplot| a graphics object that cannot be
242saved to EPS or PDF format, we will automatically save to a PNG file,
243which can be used when typesetting a PDF file, but not when creating a
244DVI file. However, you can specify the \texttt{imagemagick}'' option,
245which will use the Imagemagick \texttt{convert} utility to make EPS
246files. See the documentation for details.
247
248% FIXME: not sure this works with remote sagetex
249
250\begin{sagesilent}
251  x, y = var('x y')
252\end{sagesilent}
253
254Here's a 3D plot whose format we do not specify; it will automatically
255get saved as a PNG file and won't work when using \texttt{latex} to make
256a DVI file.
257
258\sageplot[scale=.5]{plot3d(sin(pi*(x^2+y^2))/2,(x,-1,1),(y,-1,1))}
259
260Here's the (perhaps-not-so-) famous Sage cube graph in 3D.
261
262\begin{sageblock}
263  G = graphs.CubeGraph(5)
264\end{sageblock}
265
266% need empty [] so sageplot knows you want png format, and aren't
267% passing an option to includegraphics
268\sageplot[][png]{G.plot3d()}
269
270\section{Pausing Sage\TeX}
271\label{sec:pausing-sagetex}
272
273Sometimes you want to pause'' for a bit while writing your document if
274you have embedded a long calculation or just want to concentrate on the
275\LaTeX{} and ignore any Sage stuff. You can use the \verb|\sagetexpause|
276and \verb|\sagetexunpause| macros to do that.
277
278\sagetexpause
279
280A calculation: $\sage{factor(2^325 + 1)}$ and a code environment that
281simulates a time-consuming calculation. While paused, this will get
282skipped over.
283\begin{sageblock}
284  import time
285  time.sleep(15)
286\end{sageblock}
287
288Graphics are also skipped: \sageplot{plot(2*sin(x^2) + x^2, (x, 0, 5))}
289
290\sagetexunpause
291
292\section{Make Sage write your \LaTeX{} for you}
293
294With \textsf{Sage\TeX}, you can not only have Sage do your math for you,
295it can write parts of your \LaTeX{} document for you! For example, I
296hate writing \texttt{tabular} environments; there's too many fiddly
297little bits of punctuation and whatnot\ldots and what if you want to add
298a column? It's a pain---or rather, it \emph{was} a pain. Just write a
299Sage/Python function that outputs a string of \LaTeX{} code, and use
300\verb|\sagestr|. Here's how to make Pascal's triangle.
301
302\begin{sageblock}
303def pascals_triangle(n):
304    # start of the table
305    s  = [r"\begin{tabular}{cc|" + "r" * (n+1) + "}"]
306    s.append(r"  & & $k$: & \\")
307    # second row, with k values:
308    s.append(r"  & ")
309    for k in [0..n]:
310        s.append("& {0} ".format(k))
311    s.append(r"\\")
312    # the n = 0 row:
313    s.append(r"\hline" + "\n" + r"$n$: & 0 & 1 & \\")
314    # now the rest of the rows
315    for r in [1..n]:
316        s.append(" & {0} ".format(r))
317        for k in [0..r]:
318            s.append("& {0} ".format(binomial(r, k)))
319        s.append(r"\\")
320    # add the last line and return
321    s.append(r"\end{tabular}")
322    return ''.join(s)
323
324# how big should the table be?
325n = 8
326\end{sageblock}
327
328Okay, now here's the table. To change the size, edit \texttt{n} above.
329If you have several tables, you can use this to get them all the same
330size, while changing only one thing.
331
332
333
334\begin{center}
335  \sagestr{pascals_triangle(n)}
336\end{center}
337
338\section{Include doctest-like examples in your document}
339
340Here are some examples of using the \texttt{sageexample} environment:
341
342\begin{sageexample}
343  sage: 1+1
344  2
345  sage: factor(x^2 + 2*x + 1)
346  (x + 1)^2
347\end{sageexample}
348
349If you want to see the plain-text output as well as the typeset output,
350renew the \texttt{sageexampleincludetextoutput} command to True:
351\begin{verbatim}
352  \renewcommand{\sageexampleincludetextoutput}{True}
353\end{verbatim}
354\renewcommand{\sageexampleincludetextoutput}{True}
355This can be useful to check that the two outputs are consistent.
356
357When this environment is near the bottom of the page, it may look like
358the page number is the output of a command, when in fact the real output
359is on the next page. If the output of a command below looks like
360\thepage, don't worry, that's just the page number.
361
362
363\begin{sageexample}
364  sage: 1+1
365  2
366  sage: factor(x^2 + 2*x + 1)
367  (x + 1)^2
368\end{sageexample}
369
370Multiline statements are supported, as are triple-quoted strings
371delimited by single quotes:
372\renewcommand{\sageexampleincludetextoutput}{False}
373\begin{sageexample}
374  sage: def f(a):
375  ...       '''This function is really quite nice,
376  ...       although perhaps not very useful.'''
377  ...       print "f called with a = ", a
378  ...       y = integrate(SR(cyclotomic_polynomial(10)) + a, x)
379  ...       return y + 1
380  sage: f(x)
381  f called with a =  x
382  1/5*x^5 - 1/4*x^4 + 1/3*x^3 + x + 1
383\end{sageexample}
384
385Note that the $f$ called with\ldots'' stuff doesn't get typeset, since
386when running Sage on \texttt{example.sage}, that gets printed to the
387terminal.
388
389When typesetting your document, the validity of the outputs is not
390checked. In fact, the provided outputs are completely ignored:
391\renewcommand{\sageexampleincludetextoutput}{True}
392\begin{sageexample}
393  sage: is_prime(57)
394  toothpaste
395\end{sageexample}
396\renewcommand{\sageexampleincludetextoutput}{False}
397
398However, typesetting your document produces a file named
399\texttt{example\_doctest.sage} containing all the doctest-like examples,
400and you can have Sage check them for you with:
401\begin{verbatim}
402  $sage -t example_doctest.sage 403\end{verbatim} 404You should get one doctest failure from the `toothpaste'' line above. 405 406Please look into this file for the original line numbers. 407 408Beware that \texttt{sage -t} does not handle well file names with 409special characters in them, particularly dashes, dots, and spaces---this 410ultimately comes from the way Python interprets \texttt{import} 411statements. Also, running doctests on files outside the main Sage 412library does not always work, so contact \texttt{sage-support} if you 413run into troubles. 414 415Some more examples. This environment is implemented a little bit 416differently than the other environments, so it's good to make sure that 417definitions are preserved across multiple uses. This will correctly 418define$a$, but not print its output because the statement is made up of 419a sequence of expressions. 420\begin{sageexample} 421 sage: 1; 2; a=4; 3; a 422 1 423 2 424 3 425 4 426\end{sageexample} 427 428After that, Sage should remember that %$a = \sage{a}\$ and be able to use
429that in future \texttt{sageexample} blocks:
430\begin{sageexample}
431  sage: f(a)
432  f called with a =  4
433  1/5*x^5 - 1/4*x^4 + 1/3*x^3 - 1/2*x^2 + 5*x + 1
434\end{sageexample}
435
436\end{document}