Debian Codegraph @

texmf-dist/doc/latex/pythontex/pythontex_gallery.tex

raw
1 \documentclass[11pt]{article}
2
3 % Engine-specific settings
4 % Detect pdftex/xetex/luatex, and load appropriate font packages.
5 % This is inspired by the approach in the iftex package.
6 % pdftex:
7 \ifx\pdfmatch\undefined
8 \else
9 \usepackage[T1]{fontenc}
10 \usepackage[utf8]{inputenc}
11 \fi
12 % xetex:
13 \ifx\XeTeXinterchartoks\undefined
14 \else
15 \usepackage{fontspec}
16 \defaultfontfeatures{Ligatures=TeX}
17 \fi
18 % luatex:
19 \ifx\directlua\undefined
20 \else
21 \usepackage{fontspec}
22 \fi
23 % End engine-specific settings
24
25 \usepackage{amsmath,amssymb}
26 \usepackage{fullpage}
27 \usepackage{graphicx}
28 \usepackage[svgnames]{xcolor}
29 \usepackage{url}
30 \urlstyle{same}
31
32 \usepackage[makestderr]{pythontex}
33 \restartpythontexsession{\thesection}
34
35
36 \usepackage[framemethod=TikZ]{mdframed}
37
38 \newcommand{\pytex}{Python\TeX}
39 \renewcommand*{\thefootnote}{\fnsymbol{footnote}}
40
41
42 \title{\pytex\ Gallery}
43 \author{Geoffrey M.\ Poore}
44
45
46 \begin{document}
47
48
49 \maketitle
50
51
52 \begin{abstract}
53 \pytex\ allows you to run Python code from within \LaTeX\ documents and automatically include the output. This document serves as an example of what is possible with \pytex.\footnote{Since \pytex\ runs Python code (and potentially other code) on your computer, documents using \pytex\ have a greater potential for security risks than do standard \LaTeX\ documents. You should only compile \pytex\ documents from sources you trust.}
54 \end{abstract}
55
56
57
58 \section{General Python interaction}
59
60 We can typeset code that is passed to Python, and bring back the results.
61
62 This can be simple. For example, \pyb{print('Python says hi!')} returns the following:
63 \begin{quote}
64 \printpythontex
65 \end{quote}
66
67 Or we could access the printed content verbatim (it might contain special characters):
68 \begin{quote}
69 \printpythontex[verb]
70 \end{quote}
71
72 Python interaction can also be more complex. \pyb{print(str(2**2**2) + r'\endinput')} returns \printpythontex. In this case, the printed result includes \LaTeX\ code, which is correctly interpreted by \LaTeX\ to ensure that there is not an extra space after the 16. Printed output is saved to a file and brought back in via \verb|\input|, and the \verb|\endinput| command stops input immediately, before \LaTeX\ gets to the end of the line and inserts a space character there, after the 16.
73
74 Printing works, but as the last example demonstrates, you have to be careful about spacing if you have text immediately after the printed content. In that case, it's usually best to assemble text within a \pytex\ environment and store the text in a variable. Then you can bring in the text later, using the \pygment{latex}{\py} command. The \pygment{latex}{\py} command brings in a string representation of its argument. First we create the text.
75 \begin{pyblock}
76 mytext = '$1 + 1 = {0}$'.format(1 + 1)
77 \end{pyblock}
78 Then we bring it in: \py{mytext}. The \pygment{latex}{\py} command can even bring in verbatim content.
79
80 We don't have to typeset the code we're executing. It can be hidden.\pyc{mystring=r'\textbf{This is a message from Python}'} And then we can access it later: \py{mystring}.
81
82 It is also possible to perform variable substitution or string interpolation. The earlier result could be recreated: \pys{$1 + 1 = !{1+1}$}.
83
84
85 \section{Pygments highlighting}
86
87 \pytex\ supports syntax highlighting via Pygments. Any language supported by Pygments can be highlighted. Unicode is supported. Consider this snippet copied and pasted from a Python 3 interactive session. (Using random strings of Unicode for variable names is probably not a good idea, but \pytex\ will happily highlight it for you.)
88
89 \begin{pygments}{pycon}
90 >>> âæéöø = 123
91 >>> ßçñðŠ = 456
92 >>> âæéöø + ßçñðŠ
93 579
94 \end{pygments}
95
96 There is also a Pygments command for inline use: \pygment{latex}{\pygment}.
97
98
99 \section{Python console environment}
100
101 \pytex\ includes an environment that emulates a Python interactive session. Commands are entered within the environment, each line is treated as input to an interactive session, and the result is typeset.
102
103 \begin{pyconsole}[][frame=single]
104 x = 123
105 y = 345
106 z = x + y
107 z
108 def f(expr):
109 return(expr**4)
110
111 f(x)
112 print('Python says hi from the console!')
113 \end{pyconsole}
114
115 It is possible to refer to the values of console variables later on in inline contexts, using the \pygment{latex}{\pycon} command. For example, the value of $z$ was \pycon{z}.
116
117
118 \section{Basic SymPy interaction}
119
120 \pytex\ allows us to perform algebraic manipulations with SymPy and then properly typeset the results.
121
122 We create three variables, and define $z$ in terms of the other two.
123
124 \begin{sympyblock}
125 var('x, y, z')
126 z = x + y
127 \end{sympyblock}
128
129 Now we can access what $z$ is equal to:
130
131 \[z=\sympy{z}\]
132
133 Many things are possible, including some very nice calculus.
134
135 \begin{sympyblock}
136 f = x**3 + cos(x)**5
137 g = Integral(f, x)
138 \end{sympyblock}
139
140 \[\sympy{g}=\sympy{g.doit()}\]
141
142 It's easy to use arbitrary symbols in equations.
143
144 \begin{sympyblock}
145 phi = Symbol(r'\phi')
146 h = Integral(exp(-phi**2), (phi, 0, oo))
147 \end{sympyblock}
148
149 \[\sympy{h}=\sympy{h.doit()}\]
150
151
152
153 \section{Plots with matplotlib}
154
155 We can create plots with matplotlib, perfectly matching the plot fonts with the document fonts. No more searching for the code that created a figure!
156
157 It is possible to pass page dimensions and similar contextual information from the \LaTeX\ side to the Python side. If you want your figures to be, for example, a particular fraction of the page width, you can pass the value of \pygment{latex}{\textwidth} to the Python side, and use it in creating your figures. See \pygment{latex}{\setpythontexcontext} in the main documentation for details.
158
159 You may want to use matplotlib's PGF backend when creating plots.
160
161 \begin{pylabblock}
162 rc('text', usetex=True)
163 rc('font', family='serif')
164 rc('font', size=10.0)
165 rc('legend', fontsize=10.0)
166 rc('font', weight='normal')
167 x = linspace(0, 10)
168 figure(figsize=(4, 2.5))
169 plot(x, sin(x), label=r'$\sin(x)$')
170 xlabel(r'$x\mathrm{-axis}$')
171 ylabel(r'$y\mathrm{-axis}$')
172 legend(loc='lower right')
173 savefig('myplot.pdf', bbox_inches='tight')
174 \end{pylabblock}
175
176 \begin{center}
177 \includegraphics{myplot.pdf}
178 \end{center}
179
180
181 \section{Basic pylab interaction}
182
183 \begin{pylabblock}
184 from scipy.integrate import quad
185 myintegral = quad(lambda x: e**-x**2, 0, inf)[0]
186 \end{pylabblock}
187
188 \[ \int_0^\infty e^{-x^2}\,dx = \pylab{myintegral} \]
189
190
191 \section{An automated derivative and integral table}
192
193 \pytex\ allows some amazing document automation, such as this derivative and integral table. Try typing that by hand, fast!
194
195 \begin{sympyblock}[][numbers=left,frame=single,framesep=5mm,label=An Automated Derivative and Integral Table]
196 from re import sub
197
198 var('x')
199
200 # Create a list of functions to include in the table
201 funcs = ['sin(x)', 'cos(x)', 'tan(x)',
202 'sin(x)**2', 'cos(x)**2', 'tan(x)**2',
203 'asin(x)', 'acos(x)', 'atan(x)',
204 'sinh(x)', 'cosh(x)', 'tanh(x)']
205
206 print(r'\begin{align*}')
207
208 for func in funcs:
209 # Put in some vertical space when switching to arc and hyperbolic funcs
210 if func == 'asin(x)' or func == 'sinh(x)':
211 print(r'&\\')
212 myderiv = 'Derivative(' + func + ', x)'
213 myint = 'Integral(' + func + ', x)'
214 print(latex(eval(myderiv)) + '&=' +
215 latex(eval(myderiv + '.doit()')) + r'\quad & \quad')
216 print(latex(eval(myint)) + '&=' +
217 latex(eval(myint+'.doit()')) + r'\\')
218 print(r'\end{align*}')
219 \end{sympyblock}
220
221 \printpythontex
222
223
224 \section{Step-by-step solutions}
225
226 Using SymPy, it is possible to typeset step-by-step solutions. In this particular case, we also use the \verb|mdframed| package to place a colored background behind our code.
227
228 \begin{mdframed}[linecolor=Green,innerrightmargin=30pt,innerleftmargin=30pt,leftmargin=-30pt,rightmargin=-30pt,backgroundcolor=Black!5,skipabove=10pt,skipbelow=10pt,roundcorner=5pt,frametitle={Step-by-Step Integral Evaluation},frametitlealignment=\center,splitbottomskip=6pt,splittopskip=12pt]
229 \begin{sympyblock}[][numbers=left]
230 x, y, z = symbols('x,y,z')
231 f = Symbol('f(x,y,z)')
232
233 # Define limits of integration
234 x_llim = 0
235 x_ulim = 2
236 y_llim = 0
237 y_ulim = 3
238 z_llim = 0
239 z_ulim = 4
240
241 print(r'\begin{align*}')
242
243 # Notice how I define f as a symbol, then later as an actual function
244 left = Integral(f, (x, x_llim, x_ulim), (y, y_llim, y_ulim), (z, z_llim, z_ulim))
245 f = x*y + y*sin(z) + cos(x+y)
246 right = Integral(f, (x, x_llim, x_ulim), (y, y_llim, y_ulim), (z, z_llim, z_ulim))
247 print(latex(left) + '&=' + latex(right) + r'\\')
248
249 # For each step, I move limits from an outer integral to an inner, evaluated
250 # integral until the outer integral is no longer needed
251 right = Integral(Integral(f, (z, z_llim, z_ulim)).doit(), (x, x_llim, x_ulim),
252 (y, y_llim, y_ulim))
253 print('&=' + latex(right) + r'\\')
254
255 right = Integral(Integral(f, (z, z_llim, z_ulim), (y, y_llim, y_ulim)).doit(),
256 (x, x_llim, x_ulim))
257 print('&=' + latex(right) + r'\\')
258
259 right = Integral(f, (z, z_llim, z_ulim), (y, y_llim, y_ulim),
260 (x, x_llim, x_ulim)).doit()
261 print('&=' + latex(right) + r'\\')
262
263 print('&=' + latex(N(right)) + r'\\')
264
265 print(r'\end{align*}')
266 \end{sympyblock}
267 \end{mdframed}
268
269 \printpythontex
270
271
272 \section{Including stderr}
273
274 \pytex\ allows code to be typset next to the stderr it produces. This requires the package option \verb|makestderr|.
275
276 \begin{pyblock}[errorsession][numbers=left]
277 x = 123
278 y = 345
279 z = x + y +
280 \end{pyblock}
281
282 This code causes a syntax error:
283
284 \stderrpythontex[verbatim][frame=single]
285
286 The package option \verb|stderrfilename| allows the file name that appears in the error message to be customized.
287
288
289
290
291 \end{document}