forked from gpoore/pythontex
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpythontex_gallery.html
More file actions
224 lines (212 loc) · 17 KB
/
pythontex_gallery.html
File metadata and controls
224 lines (212 loc) · 17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<meta name="generator" content="pandoc" />
<meta name="author" content="Geoffrey M. Poore" />
<title>PythonTeX Gallery</title>
<style type="text/css">code{white-space: pre;}</style>
<style type="text/css">
table.sourceCode, tr.sourceCode, td.lineNumbers, td.sourceCode {
margin: 0; padding: 0; vertical-align: baseline; border: none; }
table.sourceCode { width: 100%; line-height: 100%; }
td.lineNumbers { text-align: right; padding-right: 4px; padding-left: 4px; color: #aaaaaa; border-right: 1px solid #aaaaaa; }
td.sourceCode { padding-left: 5px; }
code > span.kw { color: #007020; font-weight: bold; }
code > span.dt { color: #902000; }
code > span.dv { color: #40a070; }
code > span.bn { color: #40a070; }
code > span.fl { color: #40a070; }
code > span.ch { color: #4070a0; }
code > span.st { color: #4070a0; }
code > span.co { color: #60a0b0; font-style: italic; }
code > span.ot { color: #007020; }
code > span.al { color: #ff0000; font-weight: bold; }
code > span.fu { color: #06287e; }
code > span.er { color: #ff0000; font-weight: bold; }
</style>
<script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML" type="text/javascript"></script>
</head>
<body>
<div id="header">
<h1 class="title">PythonTeX Gallery</h1>
<h2 class="author">Geoffrey M. Poore</h2>
</div>
<p>PythonTeX 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 PythonTeX.<sup><a href="#fn1" class="footnoteRef" id="fnref1">1</a></sup></p>
<h1>General Python interaction</h1>
<p>We can typeset code that is passed to Python, and bring back the results.</p>
<p>This can be simple. For example, <code>print('Python says hi!')</code> returns the following:</p>
<blockquote>
<p>Python says hi!</p>
</blockquote>
<p>Or we could access the printed content verbatim (it might contain special characters):</p>
<blockquote>
<p><code>Python says hi!</code></p>
</blockquote>
<p>Python interaction can also be more complex. <code>print(str(2**2**2) + r'\endinput')</code> returns 16. In this case, the printed results include 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 <code>\input</code>, and the <code>\endinput</code> command stops input immediately, before LaTeX gets to the end of the line and inserts a space character there, after the 16.</p>
<p>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 PythonTeX environment and store the text in a variable. Then you can bring in the text later, using the <code>\py</code> command. The <code>\py</code> command brings in a string representation of its argument. First we create the text.</p>
<pre class="sourceCode python"><code class="sourceCode python">mytext = <span class="st">'$1 + 1 = {0}$'</span>.<span class="dt">format</span>(<span class="dv">1</span> + <span class="dv">1</span>)</code></pre>
<p>Then we bring it in: <span class="math">\(1 + 1 = 2\)</span>. The <code>\py</code> command can even bring in verbatim content, as long as you are using the pdfTeX or XeTeX engines. (Unfortunately, verbatim does not work with LuaTeX, due to a bug.<sup><a href="#fn2" class="footnoteRef" id="fnref2">2</a></sup>)</p>
<p>We don’t have to typeset the code we’re executing. It can be hidden. And then we can access it later: <strong>This is a message from Python</strong>.</p>
<h1>Pygments highlighting</h1>
<p>PythonTeX 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 PythonTeX will happily highlight it for you.)</p>
<pre class="pycon"><code>>>> âæéöø = 123
>>> ßçñðŠ = 456
>>> âæéöø + ßçñðŠ
579</code></pre>
<p>There is also a Pygments command for inline use: <code>\pygment</code>.</p>
<h1>Python console environment</h1>
<p>PythonTeX 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.</p>
<pre class="pycon"><code>>>> x = 123
>>> y = 345
>>> z = x + y
>>> z
468
>>> def f(expr):
... return(expr**4)
...
>>> f(x)
228886641
>>> print('Python says hi from the console!')
Python says hi from the console!</code></pre>
<p>It is possible to refer to the values of console variables later on in inline contexts, using the <code>\pycon</code> command. For example, the value of <span class="math">\(z\)</span> was <code>468</code>.</p>
<h1>Basic SymPy interaction</h1>
<p>PythonTeX allows us to perform algebraic manipulations with SymPy and then properly typeset the results.</p>
<p>We create three variables, and define <span class="math">\(z\)</span> in terms of the other two.</p>
<pre class="sourceCode python"><code class="sourceCode python">var(<span class="st">'x, y, z'</span>)
z = x + y</code></pre>
<p>Now we can access what <span class="math">\(z\)</span> is equal to:</p>
<p><span class="math">\[z=x + y\]</span></p>
<p>Many things are possible, including some very nice calculus.</p>
<pre class="sourceCode python"><code class="sourceCode python">f = x**<span class="dv">3</span> + cos(x)**<span class="dv">5</span>
g = Integral(f, x)</code></pre>
<p><span class="math">\[\int x^{3} + \cos^{5}{\left (x \right )}\, dx=\frac{1}{4} x^{4} + \frac{1}{5} \sin^{5}{\left (x \right )} - \frac{2}{3} \sin^{3}{\left (x \right )} + \sin{\left (x \right )}\]</span></p>
<p>It’s easy to use arbitrary symbols in equations.</p>
<pre class="sourceCode python"><code class="sourceCode python">phi = Symbol(<span class="st">r'\phi'</span>)
h = Integral(exp(-phi**<span class="dv">2</span>), (phi, <span class="dv">0</span>, oo))</code></pre>
<p><span class="math">\[\int_{0}^{\infty} e^{- \phi^{2}}\, d\phi=\frac{1}{2} \sqrt{\pi}\]</span></p>
<h1>Plots with matplotlib</h1>
<p>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!</p>
<p>You may want to use matplotlib’s PGF backend when creating plots.</p>
<pre class="sourceCode python"><code class="sourceCode python">rc(<span class="st">'text'</span>, usetex=<span class="ot">True</span>)
rc(<span class="st">'font'</span>, family=<span class="st">'serif'</span>)
rc(<span class="st">'font'</span>, size=<span class="fl">10.0</span>)
rc(<span class="st">'legend'</span>, fontsize=<span class="fl">10.0</span>)
rc(<span class="st">'font'</span>, weight=<span class="st">'normal'</span>)
x = linspace(<span class="dv">0</span>, <span class="dv">10</span>)
figure(figsize=(<span class="dv">4</span>, <span class="fl">2.5</span>))
plot(x, sin(x), label=<span class="st">'$\sin(x)$'</span>)
xlabel(<span class="st">r'$x\mathrm{-axis}$'</span>)
ylabel(<span class="st">r'$y\mathrm{-axis}$'</span>)
legend(loc=<span class="st">'lower right'</span>)
savefig(<span class="st">'myplot.png'</span>, bbox_inches=<span class="st">'tight'</span>)</code></pre>
<p><img src="myplot.png" alt="image" /></p>
<h1>Basic pylab interaction</h1>
<pre class="sourceCode python"><code class="sourceCode python"><span class="ch">from</span> scipy.integrate <span class="ch">import</span> quad
myintegral = quad(<span class="kw">lambda</span> x: e**-x**<span class="dv">2</span>, <span class="dv">0</span>, inf)[<span class="dv">0</span>]</code></pre>
<p><span class="math">\[\int_0^\infty e^{-x^2}\,dx = 0.886226925453\]</span></p>
<h1>An automated derivative and integral table</h1>
<p>PythonTeX allows some amazing document automation, such as this derivative and integral table. Try typing that by hand, fast!</p>
<pre class="sourceCode python" linenos="" startFrom="1"><code class="sourceCode python"><span class="ch">from</span> re <span class="ch">import</span> sub
var(<span class="st">'x'</span>)
<span class="co"># Create a list of functions to include in the table</span>
funcs = [<span class="st">'sin(x)'</span>, <span class="st">'cos(x)'</span>, <span class="st">'tan(x)'</span>,
<span class="co">'sin(x)**2'</span>, <span class="st">'cos(x)**2'</span>, <span class="st">'tan(x)**2'</span>,
<span class="co">'asin(x)'</span>, <span class="st">'acos(x)'</span>, <span class="st">'atan(x)'</span>,
<span class="co">'sinh(x)'</span>, <span class="st">'cosh(x)'</span>, <span class="st">'tanh(x)'</span>]
<span class="kw">print</span>(<span class="st">r'\begin{align*}'</span>)
<span class="kw">for</span> func in funcs:
<span class="co"># Put in some vertical space when switching to arc and hyperbolic funcs</span>
<span class="kw">if</span> func == <span class="st">'asin(x)'</span> or func == <span class="st">'sinh(x)'</span>:
<span class="kw">print</span>(<span class="st">r'&\\'</span>)
myderiv = <span class="st">'Derivative('</span> + func + <span class="st">', x)'</span>
myint = <span class="st">'Integral('</span> + func + <span class="st">', x)'</span>
<span class="kw">print</span>(latex(<span class="dt">eval</span>(myderiv)) + <span class="st">'&='</span> +
latex(<span class="dt">eval</span>(myderiv + <span class="st">'.doit()'</span>)) + <span class="st">r'\quad & \quad'</span>)
<span class="kw">print</span>(latex(<span class="dt">eval</span>(myint)) + <span class="st">'&='</span> +
latex(<span class="dt">eval</span>(myint+<span class="st">'.doit()'</span>)) + <span class="st">r'\\'</span>)
<span class="kw">print</span>(<span class="st">r'\end{align*}'</span>)</code></pre>
<p><span class="math">\[\begin{aligned}
\frac{\partial}{\partial x} \sin{\left (x \right )}&=\cos{\left (x \right )}\quad & \quad
\int \sin{\left (x \right )}\, dx&=- \cos{\left (x \right )}\\
\frac{\partial}{\partial x} \cos{\left (x \right )}&=- \sin{\left (x \right )}\quad & \quad
\int \cos{\left (x \right )}\, dx&=\sin{\left (x \right )}\\
\frac{\partial}{\partial x} \tan{\left (x \right )}&=\tan^{2}{\left (x \right )} + 1\quad & \quad
\int \tan{\left (x \right )}\, dx&=- \frac{1}{2} \log{\left (\sin^{2}{\left (x \right )} -1 \right )}\\
\frac{\partial}{\partial x} \sin^{2}{\left (x \right )}&=2 \sin{\left (x \right )} \cos{\left (x \right )}\quad & \quad
\int \sin^{2}{\left (x \right )}\, dx&=\frac{1}{2} x - \frac{1}{2} \sin{\left (x \right )} \cos{\left (x \right )}\\
\frac{\partial}{\partial x} \cos^{2}{\left (x \right )}&=- 2 \sin{\left (x \right )} \cos{\left (x \right )}\quad & \quad
\int \cos^{2}{\left (x \right )}\, dx&=\frac{1}{2} x + \frac{1}{2} \sin{\left (x \right )} \cos{\left (x \right )}\\
\frac{\partial}{\partial x} \tan^{2}{\left (x \right )}&=\left(2 \tan^{2}{\left (x \right )} + 2\right) \tan{\left (x \right )}\quad & \quad
\int \tan^{2}{\left (x \right )}\, dx&=- x + \frac{\sin{\left (x \right )}}{\cos{\left (x \right )}}\\
&\\
\frac{\partial}{\partial x} \operatorname{asin}{\left (x \right )}&=\frac{1}{\sqrt{- x^{2} + 1}}\quad & \quad
\int \operatorname{asin}{\left (x \right )}\, dx&=x \operatorname{asin}{\left (x \right )} + \sqrt{- x^{2} + 1}\\
\frac{\partial}{\partial x} \operatorname{acos}{\left (x \right )}&=- \frac{1}{\sqrt{- x^{2} + 1}}\quad & \quad
\int \operatorname{acos}{\left (x \right )}\, dx&=x \operatorname{acos}{\left (x \right )} - \sqrt{- x^{2} + 1}\\
\frac{\partial}{\partial x} \operatorname{atan}{\left (x \right )}&=\frac{1}{x^{2} + 1}\quad & \quad
\int \operatorname{atan}{\left (x \right )}\, dx&=x \operatorname{atan}{\left (x \right )} - \frac{1}{2} \log{\left (x^{2} + 1 \right )}\\
&\\
\frac{\partial}{\partial x} \sinh{\left (x \right )}&=\cosh{\left (x \right )}\quad & \quad
\int \sinh{\left (x \right )}\, dx&=\cosh{\left (x \right )}\\
\frac{\partial}{\partial x} \cosh{\left (x \right )}&=\sinh{\left (x \right )}\quad & \quad
\int \cosh{\left (x \right )}\, dx&=\sinh{\left (x \right )}\\
\frac{\partial}{\partial x} \tanh{\left (x \right )}&=- \tanh^{2}{\left (x \right )} + 1\quad & \quad
\int \tanh{\left (x \right )}\, dx&=- x - \log{\left (\tanh{\left (x \right )} -1 \right )}\\\end{aligned}\]</span></p>
<h1>Step-by-step solutions</h1>
<p>Using SymPy, it is possible to typeset step-by-step solutions. In this particular case, we also use the <code>mdframed</code> package to place a colored background behind our code.</p>
<pre class="sourceCode python" linenos="" startFrom="1"><code class="sourceCode python">x, y, z = symbols(<span class="st">'x,y,z'</span>)
f = Symbol(<span class="st">'f(x,y,z)'</span>)
<span class="co"># Define limits of integration</span>
x_llim = <span class="dv">0</span>
x_ulim = <span class="dv">2</span>
y_llim = <span class="dv">0</span>
y_ulim = <span class="dv">3</span>
z_llim = <span class="dv">0</span>
z_ulim = <span class="dv">4</span>
<span class="kw">print</span>(<span class="st">r'\begin{align*}'</span>)
<span class="co"># Notice how I define f as a symbol, then later as an actual function</span>
left = Integral(f, (x, x_llim, x_ulim), (y, y_llim, y_ulim), (z, z_llim, z_ulim))
f = x*y + y*sin(z) + cos(x+y)
right = Integral(f, (x, x_llim, x_ulim), (y, y_llim, y_ulim), (z, z_llim, z_ulim))
<span class="kw">print</span>(latex(left) + <span class="st">'&='</span> + latex(right) + <span class="st">r'\\'</span>)
<span class="co"># For each step, I move limits from an outer integral to an inner, evaluated </span>
<span class="co"># integral until the outer integral is no longer needed</span>
right = Integral(Integral(f, (z, z_llim, z_ulim)).doit(), (x, x_llim, x_ulim),
(y, y_llim, y_ulim))
<span class="kw">print</span>(<span class="st">'&='</span> + latex(right) + <span class="st">r'\\'</span>)
right = Integral(Integral(f, (z, z_llim, z_ulim), (y, y_llim, y_ulim)).doit(),
(x, x_llim, x_ulim))
<span class="kw">print</span>(<span class="st">'&='</span> + latex(right) + <span class="st">r'\\'</span>)
right = Integral(f, (z, z_llim, z_ulim), (y, y_llim, y_ulim),
(x, x_llim, x_ulim)).doit()
<span class="kw">print</span>(<span class="st">'&='</span> + latex(right) + <span class="st">r'\\'</span>)
<span class="kw">print</span>(<span class="st">'&='</span> + latex(N(right)) + <span class="st">r'\\'</span>)
<span class="kw">print</span>(<span class="st">r'\end{align*}'</span>)</code></pre>
<p><span class="math">\[\begin{aligned}
\int_{0}^{4}\int_{0}^{3}\int_{0}^{2} f(x,y,z)\, dx\, dy\, dz&=\int_{0}^{4}\int_{0}^{3}\int_{0}^{2} x y + y \sin{\left (z \right )} + \cos{\left (x + y \right )}\, dx\, dy\, dz\\
&=\int_{0}^{3}\int_{0}^{2} 4 x y - y \cos{\left (4 \right )} + y + 4 \cos{\left (x + y \right )}\, dx\, dy\\
&=\int_{0}^{2} 18 x - 4 \sin{\left (x \right )} + 4 \sin{\left (x + 3 \right )} - \frac{9}{2} \cos{\left (4 \right )} + \frac{9}{2}\, dx\\
&=4 \cos{\left (3 \right )} + 4 \cos{\left (2 \right )} - 4 \cos{\left (5 \right )} - 9 \cos{\left (4 \right )} + 41\\
&=40.1235865133293\\\end{aligned}\]</span></p>
<h1>Including stderr</h1>
<p>PythonTeX allows code to be typset next to the stderr it produces. This requires the package option <code>makestderr</code>.</p>
<pre class="sourceCode python" linenos="" startFrom="1"><code class="sourceCode python">x = <span class="dv">123</span>
y = <span class="dv">345</span>
z = x + y +</code></pre>
<p>This code causes a syntax error:</p>
<pre><code> File "py_errorsession_9.py", line 3
z = x + y +
^
SyntaxError: invalid syntax</code></pre>
<p>The package option <code>stderrfilename</code> allows the file name that appears in the error message to be customized.</p>
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p>Since PythonTeX runs Python code (and potentially other code) on your computer, documents using PythonTeX have a greater potential for security risks than do standard LaTeX documents. You should only compile PythonTeX documents from sources you trust.<a href="#fnref1">↩</a></p></li>
<li id="fn2"><p><a href="http://tracker.luatex.org/view.php?id=733">http://tracker.luatex.org/view.php?id=733</a><a href="#fnref2">↩</a></p></li>
</ol>
</div>
</body>
</html>