Sharedlatex-tests / example.texOpen in CoCalc
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%
6% Please read README and the documentation of the SageTeX package for
8
9\documentclass{article}
10\title{Examples of embedding Sage in \LaTeX{} with \textsf{Sage\TeX}}
11\author{Drake and others}
12\usepackage{amsmath}
13\usepackage{sagetex}
14%
15% If you want SageTeX to use Imagemagick's convert' utility to make eps
16% files from png files when generating a dvi file, add the "imagemagick"
17% option above:
18%
19%    \usepackage[imagemagick]{sagetex}
20
21\setlength{\sagetexindent}{10ex}
22
23\begin{document}
24\maketitle
25
26\section{Inline SageMath, code blocks}
27
28This is an example $2+2=\sage{2+2}$. If you raise the current year mod
29$100$ (which equals $\sage{mod(\the\year, 100)}$) to the power of the
30current day ($\the\day$), you get
31$\sage{Integer(mod(\the\year, 100))^\the\day}$.
32Also, $\the\year$ modulo $42$ is $\sage{\the\year\percent 42}$.
33
34Code block, which uses a variable \texttt{s} to store the solutions:
35
36\begin{sageblock}
37  1+1
38  var('a,b,c,d')
39  eqn = [a+b*c==1, b-a*c==0, a+b==5]
40  s = solve(eqn, a,b,c)
41\end{sageblock}
42
43Solutions of $\mbox{eqn}=\sage{eqn}$:
44$45 \sage{s[0]} 46$
47$48 \sage{s[1]} 49$
50
51Now we evaluate the following block:
52
53\begin{sageblock}
54  E = EllipticCurve("37a")
55\end{sageblock}
56
57You can't do assignment inside \verb|\sage| macros, since Sage doesn't
58know how to typeset the output of such a thing. So you have to use a
59code block. The elliptic curve $E$ given by $\sage{E}$ has discriminant
60$\sage{E.discriminant()}$.
61
62You can do anything in a code block that you can do in Sage and/or
63Python. Here we save an elliptic curve into a file.
64\begin{sageblock}
65try:
66  E = load('E2')
67except IOError:
68  E = EllipticCurve([1,2,7,4,5])
69  E.anlist(100000)
70  E.save('E2')
71\end{sageblock}
72
73The 9999th Fourier coefficient of $\sage{E}$ is $\sage{E.anlist(100000)[9999]}$.
74
75The following code block doesn't appear in the typeset file\dots
76\begin{sagesilent}
77  e = 2
78  e = 3*e + 1
79\end{sagesilent}
80but we can refer to whatever we did in that code block: $e=\sage{e}$.
81
82\begin{sageblock}
83  var('x')
84  f(x) = log(sin(x)/x)
85\end{sageblock}
86The Taylor Series of $f$ begins: $\sage{ f.taylor(x, 0, 10) }$.
87
88\section{Plotting}
89
90Here's a plot of the elliptic curve $E$.
91
92\sageplot[scale=.4]{E.plot(-3,3)}
93
94\begin{sagesilent}
95  # the var line is unecessary unless you've defined x to be something
96  # other than a symbolic variable
97  var('x')
98  f(x) = -x^3+4*x^2+7*x-4
99\end{sagesilent}
100
101You can use variables to hold plot objects and do stuff with them.
102\begin{sageblock}
103  p = plot(f, x, -5, 8)
104\end{sageblock}
105
106Here's a small plot of $f$ from $-5$ to $5$, which I've centered:
107
108\begin{center} \sageplot[scale=.2]{p} \end{center}
109
110On second thought, use the default size of $3/4$ the \verb|\textwidth|
111and don't use axes:
112
113\sageplot[scale=.4]{p, axes=False}
114
115Remember, you're using Sage, and can therefore call upon any of the
116software packages Sage is built out of.
117\begin{sageblock}
118  f = maxima('sin(.4 * x)^3*cos(x)')
119  g = f.integrate('x')
120\end{sageblock}
121Plot $g(x)$, but don't typeset it.
122\begin{sagesilent}
123  # g is a Maxima thingy, it needs to get converted into a Sage object
124  plot1 = plot(g.sage(),x,-1,2*pi)
125\end{sagesilent}
126
127You can specify a file format and options for \verb|includegraphics|.
128The default is for EPS and PDF files, which are the best choice in
129almost all situations. (Although see the section on 3D plotting.)
130
131\sageplot[angle=45, width=.5\textwidth][png]{plot1}
132
133If you use regular \verb|latex| to make a DVI file, you'll see a box,
134because DVI files can't include PNG files. If you use \verb|pdflatex|
135that will work. See the documentation for details.
136
137When using \verb|\sageplot|, you can pass in just about anything that
138Sage can call \verb|.save()| on to produce a graphics file:
139
140\begin{center}
141  \sageplot{plot1 + plot(f.sage(),x,-1,2*pi,rgbcolor=hue(0.4)), figsize=[1,2]}
142\end{center}
143
144\sageplot{graphs.FlowerSnark().plot()}
145
146\begin{sageblock}
147  G4 = DiGraph({1:[2,2,3,5], 2:[3,4], 3:[4], 4:[5,7], 5:[6]},\
148  multiedges=True)
149  G4plot = G4.plot(layout='circular')
150\end{sageblock}
151
152\sageplot{G4plot, axes=False}
153
154Indentation and so on works fine.
155\begin{sageblock}
156  s     = 7
157  s2    = 2^s
158  P.<x> = GF(2)[]
159  M     = matrix(parent(x),s2)
160  for i in range(s2):
161    p  = (1+x)^i
162    pc = p.coeffs()
163    a  = pc.count(1)
164    for j in range(a):
165      idx        = pc.index(1)
166      M[i,idx+j] = pc.pop(idx)
167
168  matrixprogram = matrix_plot(M,cmap='Greys')
169\end{sageblock}
170And here's the picture:
171
172\sageplot{matrixprogram}
173
174Reset \texttt{x} in Sage so that it's not a generator for the polynomial
175ring: \sage{var('x')}
176
177\subsection{3D plotting}
178
1793D plotting right now is problematic because there's no convenient way
180to produce vector graphics. We can make PNGs, though, and since the
181\verb|sageplot| command defaults to EPS and PDF, \emph{you must specify
182a valid format for 3D plotting}. Sage right now (version 3.4.2) can't
183produce EPS or PDF files from plot3d objects, so if you don't specify a
184valid format, things will go badly. You can specify the
185\texttt{imagemagick}'' option, which will use the Imagemagick
186\texttt{convert} utility to make EPS files. See the documentation for
187details.
188
189Here's the famous Sage cube graph:
190
191\begin{sageblock}
192  G = graphs.CubeGraph(5)
193\end{sageblock}
194
195% need empty [] so sageplot knows you want png format, and aren't
196% passing an option to includegraphics
197\sageplot[][png]{G.plot3d(engine='tachyon')}
198
199\section{Pausing Sage\TeX}
200\label{sec:pausing-sagetex}
201
202Sometimes you want to pause'' for a bit while writing your document if
203you have embedded a long calculation or just want to concentrate on the
204\LaTeX{} and ignore any Sage stuff. You can use the \verb|\sagetexpause|
205and \verb|\sagetexunpause| macros to do that.
206
207\sagetexpause
208
209A calculation: $\sage{factor(2^325 + 1)}$ and a code environment that
210simulates a time-consuming calculation. While paused, this will get
211skipped over.
212\begin{sageblock}
213  import time
214  time.sleep(15)
215\end{sageblock}
216
217Graphics are also skipped: \sageplot{plot(2*sin(x^2) + x^2, (x, 0, 5))}
218
219\sagetexunpause
220
221\section{Make Sage write your \LaTeX{} for you}
222
223With \textsf{Sage\TeX}, you can not only have Sage do your math for you,
224it can write parts of your \LaTeX{} document for you! For example, I
225hate writing \texttt{tabular} environments; there's too many fiddly
226little bits of punctuation and whatnot\ldots and what if you want to add
227a column? It's a pain---or rather, it \emph{was} a pain. Here's how to
228make Pascal's triangle. It requires the \texttt{amsmath} package because
229of what Sage does when producing a \LaTeX{} representation of a string.
230(It puts it inside a \verb|\text| macro.)
231
232%\begin{sageblock}
233%def pascals_triangle(n):
234%  # start of the table
235%  s  = r"\begin{tabular}{cc|" + "r" * (n+1) + "}"
236%  s += r"  & & $k$: & \\"
237%  # second row, with k values:
238%  s += r"  & "
239%  for k in [0..n]:
240%    s += "& %d " % k
241%    s += r"\\"
242%    # the n = 0 row:
243%    s += r"\hline" + "\n" + r"$n$: & 0 & 1 & \\"
244%  # now the rest of the rows
245%  for r in [1..n]:
246%    s += " & %d " % r
247%  for k in [0..r]:
248%    s += "& %d " % binomial(r, k)
249%    s += r"\\"
250%    # add the last line and return
251%    s += r"\end{tabular}"
252%  return s
253%
254%  # how big should the table be?
255%  n = 8
256%\end{sageblock}
257
258Okay, now here's the table. To change the size, edit \texttt{n} above.
259If you have several tables, you can use this to get them all the same
260size, while changing only one thing.
261
262%\begin{center}
263%$\sage{pascals_triangle(n)}$
264%\end{center}
265
266$\sage{version()}$
267
268\end{document}
269
`