Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download

Examples of using latex in cocalc

Views: 1132
1
% General example LaTeX file for including Sage calculations and plots
2
% Build with:
3
%
4
% (pdf)latex example.tex; sage example.sagetex.sage; pdflatex example.tex
5
%
6
% Please read README and the documentation of the SageTeX package for
7
% more information!
8
%
9
10
\documentclass{article}
11
\title{Examples of embedding Sage in \LaTeX{} with \textsf{Sage\TeX}}
12
\author{Dan Drake and others}
13
\usepackage{hyperref}
14
% If you want to see the examples in the section "Plotting
15
% (combinatorial) graphs with TikZ" remove the \begin{comment}
16
% and \end{comment} in that section and uncomment the following line.
17
%\usepackage{tkz-berge}
18
19
20
\usepackage{sagetex}
21
%
22
% If you want SageTeX to use Imagemagick's `convert' utility to make eps
23
% files from png files when generating a dvi file, add the "imagemagick"
24
% option above:
25
%
26
% \usepackage[imagemagick]{sagetex}
27
28
\setlength{\sagetexindent}{10ex}
29
30
\begin{document}
31
\maketitle
32
33
\section{Inline Sage, code blocks}
34
35
This is an example $2+2=\sage{2+2}$. If you raise the current year mod
36
$100$ (which equals $\sage{mod(\the\year, 100)}$) to the power of the
37
current day ($\the\day$), you get $\sage{Integer(mod(\the\year,
38
100))^\the\day}$. Also, $\the\year$ modulo $42$ is $\sage{\the\year
39
\percent 42}$.
40
41
Code block which uses a variable \texttt{s} to store the solutions:
42
\begin{sageblock}
43
1+1
44
var('a,b,c')
45
eqn = [a+b*c==1, b-a*c==0, a+b==5]
46
s = solve(eqn, a,b,c)
47
\end{sageblock}
48
49
Solutions of $\mbox{eqn}=\sage{eqn}$:
50
\[
51
\sage{s[0]}
52
\]
53
\[
54
\sage{s[1]}
55
\]
56
57
Now we evaluate the following block:
58
\begin{sageblock}
59
E = EllipticCurve("37a")
60
\end{sageblock}
61
You can't do assignment inside \verb|\sage| macros, since Sage doesn't
62
know how to typeset the output of such a thing. So you have to use a
63
code block. The elliptic curve $E$ given by $\sage{E}$ has discriminant
64
$\sage{E.discriminant()}$.
65
66
You can do anything in a code block that you can do in Sage and/or
67
Python. Here we save an elliptic curve into a file.
68
\begin{sageblock}
69
try:
70
E = load('E2')
71
except IOError:
72
E = EllipticCurve([1,2,3,4,5])
73
E.anlist(100000)
74
E.save('E2')
75
\end{sageblock}
76
77
The 9999th Fourier coefficient of $\sage{E}$ is
78
$\sage{E.anlist(100000)[9999]}$.
79
80
The following code block doesn't appear in the typeset file\dots
81
\begin{sagesilent}
82
e = 2
83
e = 3*e + 1
84
\end{sagesilent}
85
but we can refer to whatever we did in that code block: $e=\sage{e}$.
86
87
\begin{sageblock}
88
var('x')
89
f(x) = log(sin(x)/x)
90
\end{sageblock}
91
The Taylor Series of $f$ begins: $\sage{ f.taylor(x, 0, 10) }$.
92
93
\section{Plotting}
94
95
Here's a very large plot of the elliptic curve $E$.
96
97
\sageplot{E.plot(-3,3)}
98
99
\begin{sagesilent}
100
# the var line is unecessary unless you've defined x to be something
101
# other than a symbolic variable
102
var('x')
103
f(x) = -x^3+3*x^2+7*x-4
104
\end{sagesilent}
105
106
You can use variables to hold plot objects and do stuff with them.
107
\begin{sageblock}
108
p = plot(f, x, -5, 5)
109
\end{sageblock}
110
111
Here's a small plot of $f$ from $-5$ to $5$, which I've centered:
112
113
\begin{center} \sageplot[scale=.2]{p} \end{center}
114
115
On second thought, use a size of $3/4$ the \verb|\textwidth| and don't
116
use axes:
117
118
\sageplot[width=.75\textwidth]{p, axes=False}
119
120
Remember, you're using Sage, and can therefore call upon any of the
121
software packages Sage is built out of.
122
\begin{sageblock}
123
f = maxima('sin(x)^2*exp(x)')
124
g = f.integrate('x')
125
\end{sageblock}
126
Plot $g(x)$, but don't typeset it.
127
\begin{sagesilent}
128
# g is a Maxima thingy, it needs to get converted into a Sage object
129
plot1 = plot(g.sage(),x,-1,2*pi)
130
\end{sagesilent}
131
132
You can specify a file format and options for \verb|includegraphics|.
133
The default is for EPS and PDF files, which are the best choice in
134
almost all situations. (Although see the section on 3D plotting.)
135
136
\sageplot[angle=45, width=.5\textwidth][png]{plot1}
137
138
If you use regular \verb|latex| to make a DVI file, you'll see a box,
139
because DVI files can't include PNG files. If you use \verb|pdflatex|
140
that will work. See the documentation for details.
141
142
When using \verb|\sageplot|, you can pass in just about anything that
143
Sage can call \verb|.save()| on to produce a graphics file:
144
145
\begin{center}
146
\sageplot{plot1 + plot(f.sage(),x,-1,2*pi,rgbcolor=hue(0.4)), figsize=[1,2]}
147
\end{center}
148
149
To fiddle with aspect ratio, first save the plot object:
150
151
\begin{sageblock}
152
p = plot(x, 0, 1) + circle((0,0), 1)
153
p.set_aspect_ratio(1)
154
\end{sageblock}
155
156
Now plot it and see the circular circle and nice 45 degree angle:
157
158
\sageplot[scale=.33]{p}
159
160
Indentation and so on works fine.
161
\begin{sageblock}
162
s = 7
163
s2 = 2^s
164
P.<x> = GF(2)[]
165
M = matrix(parent(x),s2)
166
for i in range(s2):
167
p = (1+x)^i
168
pc = p.coefficients(sparse=False)
169
a = pc.count(1)
170
for j in range(a):
171
idx = pc.index(1)
172
M[i,idx+j] = pc.pop(idx)
173
174
matrixprogram = matrix_plot(M,cmap='Greys')
175
\end{sageblock}
176
And here's the picture:
177
178
\sageplot[scale=.5]{matrixprogram}
179
180
Reset \texttt{x} in Sage so that it's not a generator for the polynomial
181
ring: \sage{var('x')}
182
183
184
\subsection{Plotting (combinatorial) graphs with TikZ}
185
\label{sec:plotting-graphs-with}
186
187
Sage now includes some nice support for plotting graphs using
188
\href{http://www.texample.net/tikz/}{TikZ}. Here, we mean things with
189
vertices and edges, not graphs of a function of one or two variables.
190
191
The graphics in this section depends on the \texttt{tkz-berge} package,
192
which is generally only available in newer \TeX{} distributions (for
193
example, \TeX Live 2011 and newer). That package depends in turn on
194
TikZ 2.0, which is also only available in newer \TeX{} distributions.
195
Installing both of those is in some cases nontrivial, so this section is
196
disabled by default.
197
198
If you have TikZ and \texttt{tkz-berge} and friends, remove the
199
\texttt{comment} environments below.
200
201
\begin{comment}
202
203
First define our graph:
204
205
\begin{sageblock}
206
g = graphs.PetersenGraph()
207
g.set_latex_options(tkz_style='Art')
208
\end{sageblock}
209
210
Now just do \verb|\sage{}| on it to plot it. You'll need to use the
211
\texttt{tkz-berge} package for this to work; that package in turn
212
depends on \texttt{tkz-graph} and TikZ. See
213
\href{http://altermundus.fr/pages/tkz.html}{\texttt{altermundus.fr/pages/tkz.html}};
214
if you're using a recent version of \TeX Live, you can use its package
215
manager to install those packages, or get them from CTAN:
216
\href{http://www.ctan.org/pkg/tkz-berge}{\texttt{www.ctan.org/pkg/tkz-berge}}.
217
See
218
\href{http://doc.sagemath.org/html/en/reference/sage/graphs/graph_latex.html}{``\LaTeX{}
219
Options for Graphs''} in the Sage reference manual for more details.
220
221
\begin{center}
222
\sage{g}
223
\end{center}
224
225
The above command just outputs a \texttt{tikzpicture} environment, and
226
you can control that environment using anything supported by
227
TikZ---although the output of \verb|\sage{g}| explicitly hard-codes a
228
lot of things and cannot be flexibly controlled in its current form.
229
230
\tikzstyle{every picture}=[rotate=45, scale=1/2]
231
232
\begin{center}
233
\sage{g}
234
\end{center}
235
236
\tikzstyle{every picture}=[]
237
238
Here's some more graphs, plotted using the usual plot routines.
239
240
\sageplot[scale=.5]{graphs.FlowerSnark().plot()}
241
242
\begin{sageblock}
243
G4 = DiGraph({1:[2,2,3,5], 2:[3,4], 3:[4], 4:[5,7], 5:[6]},\
244
multiedges=True)
245
G4plot = G4.plot(layout='circular')
246
\end{sageblock}
247
248
\sageplot[scale=.5]{G4plot, axes=False}
249
250
\end{comment}
251
252
Reset \texttt{x} in Sage so that it's not a generator for the polynomial
253
ring: \sage{var('x')}
254
255
256
\subsection{Plotting (combinatorial) graphs with TikZ}
257
\label{sec:plotting-graphs-with}
258
259
Sage now includes some nice support for plotting graphs using
260
\href{http://www.texample.net/tikz/}{TikZ}. Here, we mean things with
261
vertices and edges, not graphs of a function of one or two variables.
262
263
The graphics in this section depends on the \texttt{tkz-berge} package,
264
which is generally only available in newer \TeX{} distributions (for
265
example, \TeX Live 2011 and newer). That package depends in turn on
266
TikZ 2.0, which is also only available in newer \TeX{} distributions.
267
Installing both of those is in some cases nontrivial, so this section is
268
disabled by default.
269
270
If you have TikZ and \texttt{tkz-berge} and friends, remove the
271
\texttt{comment} environments below.
272
273
\begin{comment}
274
275
First define our graph:
276
277
\begin{sageblock}
278
g = graphs.PetersenGraph()
279
g.set_latex_options(tkz_style='Art')
280
\end{sageblock}
281
282
Now just do \verb|\sage{}| on it to plot it. You'll need to use the
283
\texttt{tkz-berge} package for this to work; that package in turn
284
depends on \texttt{tkz-graph} and TikZ. See
285
\href{http://altermundus.fr/pages/tkz.html}{\texttt{altermundus.fr/pages/tkz.html}};
286
if you're using a recent version of \TeX Live, you can use its package
287
manager to install those packages, or get them from CTAN:
288
\href{http://www.ctan.org/pkg/tkz-berge}{\texttt{www.ctan.org/pkg/tkz-berge}}.
289
See
290
\href{http://doc.sagemath.org/html/en/reference/sage/graphs/graph_latex.html}{``\LaTeX{}
291
Options for Graphs''} in the Sage reference manual for more details.
292
293
\begin{center}
294
\sage{g}
295
\end{center}
296
297
The above command just outputs a \texttt{tikzpicture} environment, and
298
you can control that environment using anything supported by
299
TikZ---although the output of \verb|\sage{g}| explicitly hard-codes a
300
lot of things and cannot be flexibly controlled in its current form.
301
302
\tikzstyle{every picture}=[rotate=45, scale=1/2]
303
304
\begin{center}
305
\sage{g}
306
\end{center}
307
308
\tikzstyle{every picture}=[]
309
310
Here's some more graphs, plotted using the usual plot routines.
311
312
\sageplot[scale=.5]{graphs.FlowerSnark().plot()}
313
314
\begin{sageblock}
315
G4 = DiGraph({1:[2,2,3,5], 2:[3,4], 3:[4], 4:[5,7], 5:[6]},\
316
multiedges=True)
317
G4plot = G4.plot(layout='circular')
318
\end{sageblock}
319
320
\sageplot[scale=.5]{G4plot, axes=False}
321
322
\end{comment}
323
324
\subsection{3D plotting}
325
326
3D plotting right now (Sage version 4.3.4) is problematic because
327
there's no convenient way to produce vector graphics. We can make PNGs,
328
though, so if you pass \verb|sageplot| a graphics object that cannot be
329
saved to EPS or PDF format, we will automatically save to a PNG file,
330
which can be used when typesetting a PDF file, but not when creating a
331
DVI file. However, you can specify the ``\texttt{imagemagick}'' option,
332
which will use the Imagemagick \texttt{convert} utility to make EPS
333
files. See the documentation for details.
334
335
% FIXME: not sure this works with remote sagetex
336
337
\begin{sagesilent}
338
x, y = var('x y')
339
\end{sagesilent}
340
341
Here's a 3D plot whose format we do not specify; it will automatically
342
get saved as a PNG file and won't work when using \texttt{latex} to make
343
a DVI file.
344
345
\sageplot[scale=.5]{plot3d(sin(pi*(x^2+y^2))/2,(x,-1,1),(y,-1,1))}
346
347
Here's the (perhaps-not-so-) famous Sage cube graph in 3D.
348
349
\begin{sageblock}
350
G = graphs.CubeGraph(5)
351
\end{sageblock}
352
353
% need empty [] so sageplot knows you want png format, and aren't
354
% passing an option to includegraphics
355
\sageplot[][png]{G.plot3d()}
356
357
\section{Pausing Sage\TeX}
358
\label{sec:pausing-sagetex}
359
360
Sometimes you want to ``pause'' for a bit while writing your document if
361
you have embedded a long calculation or just want to concentrate on the
362
\LaTeX{} and ignore any Sage stuff. You can use the \verb|\sagetexpause|
363
and \verb|\sagetexunpause| macros to do that.
364
365
\sagetexpause
366
367
A calculation: $\sage{factor(2^325 + 1)}$ and a code environment that
368
simulates a time-consuming calculation. While paused, this will get
369
skipped over.
370
\begin{sageblock}
371
import time
372
time.sleep(15)
373
\end{sageblock}
374
375
Graphics are also skipped: \sageplot{plot(2*sin(x^2) + x^2, (x, 0, 5))}
376
377
\sagetexunpause
378
379
\section{Make Sage write your \LaTeX{} for you}
380
381
With \textsf{Sage\TeX}, you can not only have Sage do your math for you,
382
it can write parts of your \LaTeX{} document for you! For example, I
383
hate writing \texttt{tabular} environments; there's too many fiddly
384
little bits of punctuation and whatnot\ldots and what if you want to add
385
a column? It's a pain---or rather, it \emph{was} a pain. Just write a
386
Sage/Python function that outputs a string of \LaTeX{} code, and use
387
\verb|\sagestr|. Here's how to make Pascal's triangle.
388
389
\begin{sageblock}
390
def pascals_triangle(n):
391
# start of the table
392
s = [r"\begin{tabular}{cc|" + "r" * (n+1) + "}"]
393
s.append(r" & & $k$: & \\")
394
# second row, with k values:
395
s.append(r" & ")
396
for k in [0..n]:
397
s.append("& {0} ".format(k))
398
s.append(r"\\")
399
# the n = 0 row:
400
s.append(r"\hline" + "\n" + r"$n$: & 0 & 1 & \\")
401
# now the rest of the rows
402
for r in [1..n]:
403
s.append(" & {0} ".format(r))
404
for k in [0..r]:
405
s.append("& {0} ".format(binomial(r, k)))
406
s.append(r"\\")
407
# add the last line and return
408
s.append(r"\end{tabular}")
409
return ''.join(s)
410
411
# how big should the table be?
412
n = 8
413
\end{sageblock}
414
415
Okay, now here's the table. To change the size, edit \texttt{n} above.
416
If you have several tables, you can use this to get them all the same
417
size, while changing only one thing.
418
419
\begin{center}
420
\sagestr{pascals_triangle(n)}
421
\end{center}
422
423
\section{Include doctest-like examples in your document}
424
425
Here are some examples of using the \texttt{sageexample} environment:
426
\begin{sageexample}
427
sage: 2+2
428
4
429
sage: print 'middle'
430
middle
431
sage: factor(x^2 + 2*x + 1)
432
(x + 1)^2
433
\end{sageexample}
434
Note above that no output from the \texttt{print} statement appears.
435
That is because we have to use Python's \texttt{exec} to execute that
436
statement (and not \texttt{eval()}), and we can't get the output from
437
that.
438
439
That said, if you want to see the plain-text output you put into your
440
\verb|.tex| file as well as the Sage-computed typeset output, renew the
441
\texttt{sageexampleincludetextoutput} command to True:
442
\begin{verbatim}
443
\renewcommand{\sageexampleincludetextoutput}{True}
444
\end{verbatim}
445
\renewcommand{\sageexampleincludetextoutput}{True}
446
This can be useful to check that the two outputs are consistent. Here's
447
the print statement with text output included:
448
\begin{sageexample}
449
sage: print 'middle'
450
middle
451
\end{sageexample}
452
When typesetting your document, the validity of the outputs is not
453
checked. In fact, the provided outputs are completely ignored:
454
\renewcommand{\sageexampleincludetextoutput}{True}
455
\begin{sageexample}
456
sage: is_prime(57)
457
toothpaste
458
\end{sageexample}
459
\renewcommand{\sageexampleincludetextoutput}{False}%
460
Multiline statements with the ``\verb|....:|'' continuation marks are
461
supported, as are triple-quoted strings delimited by single quotes
462
(double quotes won't work):
463
\begin{sageexample}
464
sage: gcd([5656565656,
465
....: 4747474747,
466
....: 123456789])
467
1
468
sage: mystr = '''my
469
....: string
470
....: has
471
....: several
472
....: lines.'''
473
sage: len(mystr)
474
28
475
sage: def f(a):
476
....: '''This function is really quite nice,
477
....: although perhaps not very useful.'''
478
....: print "f called with a = ", a
479
....: y = integrate(SR(cyclotomic_polynomial(10)) + a, x)
480
....: return y + 1
481
sage: f(x)
482
f called with a = x
483
1/5*x^5 - 1/4*x^4 + 1/3*x^3 + x + 1
484
\end{sageexample}
485
Note that the ``$f$ called with\ldots'' stuff doesn't get typeset, since
486
when running Sage on \texttt{example.sagetex.sage}, that gets printed to the
487
terminal.
488
489
Typesetting your document produces a file named
490
\texttt{example\_doctest.sage} containing all the doctest-like examples,
491
and you can have Sage check them for you with:
492
\begin{verbatim}
493
$ sage -t example_doctest.sage
494
\end{verbatim}
495
You should get a doctest failure from the ``toothpaste'' line above. The
496
line numbers from \texttt{sage -t} refer to the ``\verb|_doctest.sage|''
497
file.
498
499
Beware that \texttt{sage -t} does not really handle file names with
500
special characters in them, particularly dashes, dots, and spaces---this
501
ultimately comes from the way Python interprets \texttt{import}
502
statements. Also, running doctests on files outside the main Sage
503
library does not always work, so contact \texttt{sage-support} if you
504
run into troubles.
505
506
Some more examples. This environment is implemented a little bit
507
differently than the other environments, so it's good to make sure that
508
definitions are preserved across multiple uses. This will correctly
509
define $a$, but not print its output because the statement is made up of
510
a sequence of expressions and we can't use Python's \texttt{eval()}; we
511
have to use \texttt{exec} and we can't capture the output from that.
512
\begin{sageexample}
513
sage: 1; 2; a=4; 3; a
514
1
515
2
516
3
517
4
518
\end{sageexample}
519
However, after that, Sage should remember that $a = \sage{a}$ and be
520
able to use that in future \texttt{sageexample} blocks:
521
\begin{sageexample}
522
sage: f(a)
523
f called with a = 4
524
1/5*x^5 - 1/4*x^4 + 1/3*x^3 - 1/2*x^2 + 5*x + 1
525
\end{sageexample}
526
527
\section{Plotting functions in Ti\emph{k}Z with Sage\TeX}
528
529
(The code in this section should work with any reasonable version of
530
Ti\emph{k}Z, which means it should work with all but the most terribly
531
out-of-date \TeX{} installations---but to make sure we can accomodate
532
everyone, the code here is commented out. You can almost certainly
533
uncomment and run them. Make sure you do \verb|\usepackage{tikz}| in the
534
preamble.)
535
536
\begin{comment}
537
538
The wonderful graphics package TikZ has the ability to plot functions by
539
reading in a sequence of points from an external file---see chapter 18,
540
page 193 of the TikZ manual. This facility is designed around files
541
produced by Gnuplot, but the file format is so simple that it's very
542
easy to use Sage\TeX{} to generate them. First you need a function that
543
will evaluate functions and write the results into a file:
544
545
546
% set up plotting stuff
547
\begin{sageblock}
548
def gnuplot(x, y, tvals_, fn):
549
"""
550
Write out a gnuplot-style file of points x(t), y(t).
551
"""
552
tvals = list(tvals_)
553
lines = ['#This is a gnuplot-style file written by SageTeX.',
554
'#x: {0}'.format(x),
555
'#y: {0}'.format(y),
556
'#Curve 0, {0} points'.format(len(tvals)),
557
'#x y type']
558
fmt = lambda _: _.n().str(no_sci=2)
559
for t in tvals:
560
try:
561
lines.append('{0} {1} i'.format(fmt(x(t)), fmt(y(t))))
562
except ValueError, ZeroDivisonError:
563
pass
564
with open(fn, 'w') as f:
565
f.write('\n'.join(lines) + '\n')
566
\end{sageblock}
567
568
There probably should be some more exceptions in that list, and the
569
above code doesn't check to make sure it's writing real values, but then
570
again, this is just a file of examples!
571
572
Then you define callable functions x and y and pass them in, along with
573
a sequence of values and a file name. Here's a plot that I used on a
574
calculus exam:
575
576
\begin{sageblock}
577
r(t) = 1 - 2*sin(3*t)
578
x(t) = r(t)*cos(t)
579
y(t) = r(t)*sin(t)
580
gnuplot(x, y, srange(0, 2*pi + .05, .05), 'example-tikz1.table')
581
\end{sageblock}
582
583
(Usually you would do that in sagesilent environments, I guess.)
584
585
Then you call TikZ with your plot.
586
587
\begin{tikzpicture}
588
\draw[very thin,->] (-3.25,0) -- (3.25,0);
589
\draw[very thin,->] (0,-3.25) -- (0,3.25);
590
\draw[smooth] plot file {example-tikz1.table};
591
\end{tikzpicture}
592
593
For regular Cartesian plots, just pass in the identity function for x:
594
595
\begin{sageblock}
596
x = lambda t: t
597
y(t) = t*sin(1/t)
598
gnuplot(x, y, [0.01, 0.02..(0.5)] + [0.55, 0.6..2], 'example-tikz2.table')
599
\end{sageblock}
600
601
\begin{tikzpicture}
602
\draw[very thin,->] (-0.25,0) -- (2,0);
603
\draw[very thin,->] (0,-1/3) -- (0,1);
604
\draw[smooth, red] plot file {example-tikz2.table};
605
\end{tikzpicture}
606
607
This style of plotting will become even more useful and powerful when
608
the new TikZ Data Visualization library is available---you will be able
609
to feed TikZ a bunch of data points, and it automatically make a very
610
nice plot for you, including axes, labels, and so on.
611
612
\end{comment}
613
614
\section{The \texttt{sagecommandline} environment}
615
616
When writing a \TeX{} document about Sage, you may want to show some
617
examples of commands and their output. But naturally, you are lazy and
618
don't want to cut and paste the output into your document. ``Why should
619
I have to do anything? Why can't Sage and \TeX{} cooperate and do it for
620
me?'' you may cry. Well, they \emph{can} cooperate:
621
622
\begin{sagecommandline}
623
sage: 1+1
624
sage: is_prime(57)
625
sage: if is_prime(57):
626
....: print 'prime'
627
....: else:
628
....: print 'composite'
629
\end{sagecommandline}
630
631
Note that the output of the commands is not included in the source file,
632
but are included in the typeset output.
633
634
Because of the way the environment is implemented, not everything is
635
exactly like using Sage in a terminal: the two commands below (and the
636
``if is prime'' one above, did you notice that?) would produce some
637
output, but don't here:
638
639
\begin{sagecommandline}
640
sage: x = 2010; len(x.divisors())
641
sage: print 'Hola, mundo!'
642
\end{sagecommandline}
643
644
The difference lies in the Python distinction between statements and
645
expressions; we can use \texttt{eval()} for an expression and get its
646
output, but we must use \texttt{exec} for a statement and can't get the
647
output, if any.
648
649
One nice thing is that you can set labels by using an @ sign:
650
651
\begin{sagecommandline}
652
sage: l = matrix([[1,0,0],[3/5,1,0],[-2/5,-2,1]])
653
sage: d = diagonal_matrix([15, -1, 4]) #@\label{diagonal}
654
sage: u = matrix([[1,0,1/3],[0,1,2],[0,0,1]]) #@\label{anotherlabel} \# foo
655
sage: l*d*u # this is a comment
656
\end{sagecommandline}
657
658
And then refer to that label: it was on line \ref{diagonal}, which is on
659
page \pageref{diagonal}. Note that the other text after the hash mark on
660
that line does not get typeset as a comment, and that you cannot have
661
any space between the hash mark and the~@. You will also need to typeset
662
your document \emph{twice}
663
664
You can also typeset the output by changing the value of
665
\verb|\sagecommandlinetextoutput| to False:
666
\renewcommand{\sagecommandlinetextoutput}{False}
667
\begin{sagecommandline}
668
sage: l*d*u
669
sage: x = var('x')
670
sage: (1-cos(x)^2).trig_simplify()
671
\end{sagecommandline}
672
673
\renewcommand{\sagecommandlinetextoutput}{True}
674
675
The Sage input and output is typeset using the \texttt{listings} package
676
with the styles \texttt{SageInput} and \texttt{SageOutput},
677
respectively. If you don't like the defaults you can change them. It is
678
recommended to derive from \texttt{DefaultSageInput} and
679
\texttt{DefaultSageOutput}, for example\ldots
680
\lstdefinestyle{SageInput}{style=DefaultSageInput,basicstyle={\color{red}}}
681
\lstdefinestyle{SageOutput}{style=DefaultSageOutput,basicstyle={\color{green}}}
682
makes things overly colorful:
683
\begin{sagecommandline}
684
sage: pi.n(100)
685
\end{sagecommandline}
686
\lstdefinestyle{SageInput}{style=DefaultSageInput}
687
\lstdefinestyle{SageOutput}{style=DefaultSageOutput}
688
689
Plotting things doesn't automatically pull in the plot, just the text
690
representation of the plot (the equivalent of applying \texttt{str()} to
691
it):
692
693
\begin{sagecommandline}
694
sage: plot(sin(x), (x, 0, 2*pi))
695
\end{sagecommandline}
696
697
You can include output, but it will be ignored. This is useful for
698
doctesting, as all the \texttt{sagecommandline} environment things get
699
put into the ``\texttt{\_doctest.sage}'' file. However, note that if you
700
don't include any output, then the corresponding doctest will fail if
701
the command produces output. The doctest output from this file will have
702
lots of failures because not many of the commands have output included
703
in the source \texttt{.tex} file.
704
705
The command below has incorrect output included in the \texttt{.tex}
706
file; in the PDF, you see the correct Sage-computed answer, but if you
707
do \texttt{sage -t example\_doctest.sage} you will get a genuine doctest
708
failure.
709
\begin{sagecommandline}
710
sage: factor(x^2 + 2*x + 1)
711
(x + 999)^2
712
\end{sagecommandline}
713
714
\end{document}
715