You are on page 1of 46

page.

A Gentle
Introduction to
PythonTEX

Andrew Mertz,
William Slough

Overview

A Question of Primes

Introduction to
A Gentle Introduction to PythonTEX
PythonTEX

Mathematics with
Sympy

Plots with matplotlib Andrew Mertz William Slough


Web Services

Conclusions Mathematics and Computer Science Department


Extra Examples
Eastern Illinois University

October 23, 2013


page.2

A Gentle
Introduction to
PythonTEX

Andrew Mertz,
William Slough

Overview

A Question of Primes

Introduction to
PythonTEX

Mathematics with
Sympy

Plots with matplotlib

Web Services

Conclusions

Extra Examples

TEX
page.3

Python Overview
A Gentle
Introduction to
PythonTEX

Andrew Mertz,
William Slough

Overview

A Question of Primes
I General purpose, high-level programming language
Introduction to
PythonTEX

Mathematics with
I Multi-paradigm: object-oriented, imperative, functional
Sympy

Plots with matplotlib I Comprehensive standard library


Web Services

Conclusions
I Origins from late 1989
Extra Examples
I Free and open-source
page.4

Python + Scientific Computing


A Gentle
Introduction to
PythonTEX

Andrew Mertz,
William Slough

Overview

A Question of Primes

Introduction to
PythonTEX

Mathematics with
Sympy

Plots with matplotlib

Web Services

Conclusions

Extra Examples
page.5

A Recent Question on TEX Stack Exchange


A Gentle
Introduction to
PythonTEX

Andrew Mertz,
William Slough

Overview

A Question of Primes

Introduction to
“I would like to write a LATEX script that produces all the prime
PythonTEX
numbers between the numbers n and m, where n < m. How can I do
Mathematics with
Sympy this? I feel it should not be that hard, but I cannot seem to program
Plots with matplotlib it.”
— Kevin†
Web Services

Conclusions

Extra Examples

† tex.stackexchange.com/questions/134305/how-to-produce-a-list-of-prime-

numbers-in-latex/134366#134366
page.6

From The TEXBook, Page 218 (1984)


A Gentle
Introduction to
PythonTEX

Andrew Mertz,
William Slough

Overview

A Question of Primes The first 30 prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31,
Introduction to 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107,
PythonTEX
109, and 113. You may not find this fact very startling; but you may
Mathematics with
Sympy be surprised to learn that the previous sentence was typeset by saying
Plots with matplotlib
The first thirty prime numbers are \primes{30}.
Web Services

Conclusions TEX did all the calculation by expanding the primes macro, so the
Extra Examples author is pretty sure that the list of prime numbers given above is
quite free of typographic errors.
page.7

Knuth’s Code,  -worthy


A Gentle
Introduction to
PythonTEX

Andrew Mertz,
William Slough
\newif\ifprime \newif\ifunknown % boolean variables
Overview
\newcount\n \newcount\p \newcount\d \newcount\a % integer variables
A Question of Primes \def\primes#1{2,~3% assume that #1 is at least 3
Introduction to
\n=#1 \advance\n by-2 % n more to go
PythonTEX \p=5 % odd primes starting with p
Mathematics with \loop\ifnum\n>0 \printifprime\advance\p by2 \repeat}
Sympy \def\printp{, % we will invoke \printp if p is prime
Plots with matplotlib \ifnum\n=1 and~\fi % and precedes the last value
Web Services
\number\p \advance\n by -1 }
\def\printifprime{\testprimality \ifprime\printp\fi}
Conclusions
\def\testprimality{{\d=3 \global\primetrue
Extra Examples
\loop\trialdivision \ifunknown\advance\d by2 \repeat}}
\def\trialdivision{\a=\p \divide\a by\d
\ifnum\a>\d \unknowntrue\else\unknownfalse\fi
\multiply\a by\d
\ifnum\a=\p \global\primefalse\unknownfalse\fi}
page.8

David Carlisle’s Response


A Gentle
Introduction to
PythonTEX

Andrew Mertz,
William Slough

Overview \makeatletter
A Question of Primes \def\primes#1#2{{%
Introduction to
\def\comma{\def\comma{, }}%
PythonTEX \count@\@ne\@tempcntb#2\relax\@curtab#1\relax
Mathematics with
\@primes}}
Sympy \def\@primes{\loop\advance\count@\@ne
Plots with matplotlib \expandafter\ifx\csname p-\the\count@\endcsname\relax
Web Services
\ifnum\@tempcntb<\count@\else
\ifnum\count@<\@curtab\else\comma\the\count@\fi\fi\else\repeat
Conclusions
\@tempcnta\count@\loop\advance\@tempcnta\count@
Extra Examples \expandafter\let\csname p-\the\@tempcnta\endcsname\@ne
\ifnum\@tempcnta<\@tempcntb\repeat
\ifnum\@tempcntb>\count@\expandafter\@primes\fi}
\makeatother
page.9

Karl Koeller’s Response


A Gentle
Introduction to
PythonTEX

Andrew Mertz,
William Slough
A solution using the \pgfmathisprime macro provided by Alain
Matthes’ tkz-euclide package:
Overview

A Question of Primes

Introduction to
PythonTEX \usepackage{tkz-euclide}
Mathematics with
Sympy \newif\ifcomma
Plots with matplotlib

Web Services
\newcommand{\primes}[2]{%
\commafalse%
Conclusions
\foreach\numb in {#1,...,#2}{%
Extra Examples
\pgfmathisprime{\numb}%
\ifnum\pgfmathresult=1
\ifcomma, \numb\else\numb\global\commatrue\fi%
\fi%
}%
}
page.10

Can PythonTEX Make This Simpler?


A Gentle
Introduction to
PythonTEX

Andrew Mertz,
William Slough

Overview

A Question of Primes

Introduction to
PythonTEX

Yes. . .
Mathematics with
Sympy

Plots with matplotlib

Web Services

Conclusions

Extra Examples
page.11

Evaluating Expressions With \py


A Gentle
Introduction to
PythonTEX

Andrew Mertz,
William Slough

Overview The macro \py{expression} evaluates a Python expression and


A Question of Primes
typesets its value.
Introduction to
PythonTEX

Mathematics with
Sympy

Plots with matplotlib

Web Services
Did you know that $2^{65} = \py{2**65}$?
Conclusions

Extra Examples

Did you know that 265 = 36893488147419103232?


page.12

Evaluating Expressions With \pyc


A Gentle
Introduction to
PythonTEX

Andrew Mertz,
William Slough
The macro \pyc{expression} evaluates a Python expression and
Overview
typesets anything that it prints.
A Question of Primes

Introduction to
PythonTEX

Mathematics with
Sympy
Did you know that $2^{65} = \pyc{print(2**65)}$?
Plots with matplotlib

Web Services

Conclusions Did you know that 265 = 36893488147419103232?


Extra Examples

While “printing” adds little in this case, it is important for more


complex examples.
page.13

A More Complex Example Using \pyc


A Gentle
Introduction to
PythonTEX

Andrew Mertz,
William Slough

Overview

A Question of Primes

Introduction to
PythonTEX

Mathematics with
Sympy

Plots with matplotlib

Web Services

Conclusions

Extra Examples

\pyc{showGoogleMap("Tokyo", 11)}
page.14

Charleston, Illinois USA


A Gentle
Introduction to
PythonTEX

Andrew Mertz,
William Slough

Overview

A Question of Primes

Introduction to
PythonTEX

Mathematics with
Sympy

Plots with matplotlib

Web Services

Conclusions

Extra Examples

\pyc{showGoogleMap("600 Lincoln,Charleston,IL", 14)}


page.15

Generating Tables With pycode


A Gentle
Introduction to
PythonTEX

Andrew Mertz,
\begin{pycode}
William Slough print(r"\begin{tabular}{c|c}")
Overview print(r"$m$ & $2^m$ \\ \hline")
A Question of Primes print(r"%d & %d \\" % (1, 2**1))
Introduction to
PythonTEX
print(r"%d & %d \\" % (2, 2**2))
Mathematics with
print(r"%d & %d \\" % (3, 2**3))
Sympy
print(r"%d & %d \\" % (4, 2**4))
Plots with matplotlib
print(r"\end{tabular}")
Web Services
\end{pycode}
Conclusions

Extra Examples
\begin{tabular}{c|c}
$m$ & $2^m$ \\ \hline
1 & 2 \\
2 & 4 \\
3 & 8 \\
4 & 16 \\
\end{tabular}
page.16

Generating Tables With pycode


A Gentle
Introduction to
PythonTEX

Andrew Mertz,
\begin{pycode}
William Slough print(r"\begin{tabular}{c|c}")
Overview print(r"$m$ & $2^m$ \\ \hline")
A Question of Primes print(r"%d & %d \\" % (1, 2**1))
Introduction to
PythonTEX
print(r"%d & %d \\" % (2, 2**2))
Mathematics with
print(r"%d & %d \\" % (3, 2**3))
Sympy
print(r"%d & %d \\" % (4, 2**4))
Plots with matplotlib
print(r"\end{tabular}")
Web Services
\end{pycode}
Conclusions

Extra Examples

m 2m
1 2
2 4
3 8
4 16
page.17

Generating Tables With a Loop


A Gentle
Introduction to
PythonTEX
\begin{pycode}
Andrew Mertz,
William Slough lo, hi = 1, 6
Overview
print(r"\begin{tabular}{c|c}")
A Question of Primes print(r"$m$ & $2^m$ \\ \hline")
Introduction to for m in range(lo, hi + 1):
PythonTEX
print(r"%d & %d \\" % (m, 2**m))
Mathematics with
Sympy print(r"\end{tabular}")
Plots with matplotlib \end{pycode}
Web Services

Conclusions

Extra Examples m 2m
1 2
2 4
3 8
4 16
5 32
6 64
page.18

Defining a Function
A Gentle
Introduction to
PythonTEX

Andrew Mertz,
William Slough

\begin{pycode}
Overview

A Question of Primes
def fib(n): # nth Fibonacci value
Introduction to
a, b = 0, 1
PythonTEX
for i in range(n):
Mathematics with
Sympy
a, b = b, a + b
Plots with matplotlib
return a
Web Services \end{pycode}
Conclusions

Extra Examples

Did you know that $F_{10} = \py{fib(10)}$?

Did you know that F10 = 55?


page.19

Sessions
A Gentle
Introduction to
PythonTEX

Andrew Mertz,
William Slough
py, pyc, and pycode all have an optional session argument.
Overview

A Question of Primes

Introduction to
PythonTEX This argument determines the name of the Python session in which
Mathematics with
Sympy
the code is executed.
Plots with matplotlib

Web Services

Conclusions Sessions with different names may be executed in parallel providing a


Extra Examples
speedup.

If a session is not specified, then the default session is used.


page.20

Introducing pythontexcustomcode
A Gentle
Introduction to
PythonTEX

Andrew Mertz, \begin{pythontexcustomcode}{py}


William Slough
def makeTable(lo, hi):
Overview
print(r"\begin{tabular}{c|c}")
A Question of Primes
print(r"$m$ & $2^m$ \\ \hline")
Introduction to
PythonTEX for m in range(lo, hi + 1):
Mathematics with print(r"%d & %d \\" % (m, 2**m))
Sympy
print(r"\end{tabular}")
Plots with matplotlib
\end{pythontexcustomcode}
Web Services

Conclusions
The pythontexcustomcode environment evaluates the code block
Extra Examples
at the start of each “session” – which makes it a great place to
define well-tested functions.

\begin{pythontexcustomcode}{py}
python code block
\end{pythontexcustomcode}
page.21

Generating Tables in Multiple Sessions


A Gentle
Introduction to \pyc[table1]{makeTable(1, 4)}
PythonTEX

2m
Andrew Mertz,
William Slough m
Overview
1 2
A Question of Primes 2 4
Introduction to 3 8
PythonTEX
4 16
Mathematics with
Sympy

Plots with matplotlib \pyc[table2]{makeTable(4, 10)}


Web Services

Conclusions
m 2m
Extra Examples 4 16
5 32
6 64
7 128
8 256
9 512
10 1024
page.22

Generating Tables From a Function


A Gentle
Introduction to
PythonTEX
\begin{pythontexcustomcode}{py}
Andrew Mertz,
William Slough def makeTableFromFunction(lo, hi, funct, label):
Overview
print(r"\begin{tabular}{c|c}")
A Question of Primes print(r"$m$ & %s \\ \hline" % label)
Introduction to for m in range(lo, hi + 1):
PythonTEX
print(r"%d & %d \\" % (m, funct(m)))
Mathematics with
Sympy print(r"\end{tabular}")
Plots with matplotlib \end{pythontexcustomcode}
Web Services

Conclusions \pyc{makeTableFromFunction(7, 11, fib, "$F_{m}$")}


Extra Examples

m Fm
7 13
8 21
9 34
10 55
11 89
page.23

Generating Tables From a Library Function


A Gentle
Introduction to
PythonTEX Python excels in the quantity and quality of its modules.
Andrew Mertz,
William Slough Modules make additional functions available. To use them, the
Overview corresponding module needs to be imported.
A Question of Primes

Introduction to
PythonTEX
\begin{pythontexcustomcode}{py}
Mathematics with
import math
Sympy
\end{pythontexcustomcode}
Plots with matplotlib

Web Services

Conclusions
\pyc{makeTableFromFunction(30, 33, math.factorial, "$m!$")}
Extra Examples

m m!
30 265252859812191058636308480000000
31 8222838654177922817725562880000000
32 263130836933693530167218012160000000
33 8683317618811886495518194401280000000
page.24

Generating Tables From a Library Function


A Gentle
Introduction to
PythonTEX
With the import statement the module name is needed each time a
Andrew Mertz, member of the module is used.
William Slough

To avoid this, a from import statement can be used.


Overview

A Question of Primes This can shadow other functions and should be used with care.
Introduction to
PythonTEX
\begin{pythontexcustomcode}{py}
Mathematics with
Sympy from math import factorial
Plots with matplotlib \end{pythontexcustomcode}
Web Services

Conclusions
\pyc{makeTableFromFunction(30, 33, factorial, "$m!$")}
Extra Examples

m m!
30 265252859812191058636308480000000
31 8222838654177922817725562880000000
32 263130836933693530167218012160000000
33 8683317618811886495518194401280000000
page.25

Remember Kevin?
A Gentle
Introduction to
PythonTEX

Andrew Mertz,
William Slough \begin{pythontexcustomcode}{py}
Overview
from sympy import prime
A Question of Primes

Introduction to def generatePrimes(n): # Assume n >= 3


PythonTEX
for i in range(1, n):
Mathematics with
Sympy print("%d, " % prime(i))
Plots with matplotlib print("and %d%%" % prime(n))
Web Services \end{pythontexcustomcode}
Conclusions

Extra Examples

The first 30 primes are \pyc{generatePrimes(30)}.

The first 30 primes are 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,
43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, and
113.
page.26

Processing PythonTEX Files


A Gentle
Introduction to
PythonTEX

Andrew Mertz,
William Slough
my.tex
Overview

A Question of Primes

Introduction to
PythonTEX

Mathematics with
Sympy

Plots with matplotlib

Web Services
1. pdfLATEX 2. pythonTEX 3. pdfLATEX my.pdf

Conclusions

Extra Examples

my.pytxcode pythontex-files-my
page.27

Symbolic Mathematics With Sympy


A Gentle
Introduction to
PythonTEX

Andrew Mertz, >>> from sympy import *


William Slough

Overview
>>> var("x, y") # Define symbolic variables
A Question of Primes
(x, y)
Introduction to
PythonTEX

Mathematics with >>> z = (x + y)**3 # Define an expression


Sympy

Plots with matplotlib

Web Services
>>> z # Display z
Conclusions
(x + y)**3
Extra Examples

>>> expand(z) # Display the expansion of z


x**3 + 3*x**2*y + 3*x*y**2 + y**3

>>> latex(expand(z))
’x^{3} + 3 x^{2} y + 3 x y^{2} + y^{3}’
page.28

Expanding Binomials
A Gentle
Introduction to
PythonTEX
\begin{pycode}
Andrew Mertz, from sympy import *
William Slough
var("x, y")
Overview

A Question of Primes binomials = []


Introduction to for m in range(3, 6):
PythonTEX
binomials.append((x + y)**m)
Mathematics with
Sympy

Plots with matplotlib print(r"\begin{align*}")


Web Services for expr in binomials:
Conclusions print(r"%s &= %s\\" % (latex(expr), latex(expand(expr))))
Extra Examples print(r"\end{align*}")
\end{pycode}

3
(x + y ) = x 3 + 3x 2 y + 3xy 2 + y 3
4
(x + y ) = x 4 + 4x 3 y + 6x 2 y 2 + 4xy 3 + y 4
5
(x + y ) = x 5 + 5x 4 y + 10x 3 y 2 + 10x 2 y 3 + 5xy 4 + y 5
page.29

A Little Bit of Calculus


A Gentle
Introduction to
PythonTEX
\begin{pycode}
Andrew Mertz, functions = [sin(x), cos(x), tan(x)]
William Slough
print(r"\begin{align*}")
Overview for f in functions:
A Question of Primes d = Derivative(f, x)
Introduction to print(latex(d) + "&=" + latex(d.doit()) + r"\\")
PythonTEX
print(r"\end{align*}")
Mathematics with
Sympy \end{pycode}
Plots with matplotlib

Web Services
d
Conclusions
sin (x) = cos (x)
Extra Examples dx
d
cos (x) = − sin (x)
dx
d
tan (x) = tan2 (x) + 1
dx
page.30

A Little Bit More


A Gentle
Introduction to
PythonTEX
\begin{pycode}
Andrew Mertz, functions = [sin(x), cos(x), tan(x)]
William Slough
print(r"\begin{align*}")
Overview for f in functions:
A Question of Primes i = Integral(f, x)
Introduction to print(latex(i) + "&=" + latex(i.doit()) + r"\\")
PythonTEX
print(r"\end{align*}")
Mathematics with
Sympy \end{pycode}
Plots with matplotlib

Web Services Z
Conclusions
sin (x) dx = − cos (x)
Extra Examples

Z
cos (x) dx = sin (x)

Z
1
tan (x) dx = − log sin2 (x) − 1

2
page.31

Stirling’s Triangle
A Gentle
Introduction to
PythonTEX

Andrew Mertz,
William Slough

Overview
Stirling’s Triangle for Subsets
                 
A Question of Primes
n n n n n n n n n
n
Introduction to
PythonTEX
0 1 2 3 4 5 6 7 8
Mathematics with
Sympy
0 1
Plots with matplotlib 1 0 1
Web Services 2 0 1 1
Conclusions 3 0 1 3 1
Extra Examples 4 0 1 7 6 1
5 0 1 15 25 10 1
6 0 1 31 90 65 15 1
7 0 1 63 301 350 140 21 1
8 0 1 127 966 1701 1050 266 28 1
page.32

Stirling’s Triangle (code excerpt)


A Gentle
Introduction to
PythonTEX

Andrew Mertz,
William Slough

Overview

A Question of Primes

Introduction to from sympy.functions.combinatorial.numbers import *


PythonTEX

Mathematics with
Sympy for n in range(numberOfRightHandColumns):
Plots with matplotlib print("%d" % n)
Web Services for k in range(n + 1):
Conclusions print("& %d" % stirling(n, k))
Extra Examples print(r"\\")
page.33

Plotting With Matplotlib


A Gentle
Introduction to
PythonTEX

Andrew Mertz, Damped exponential decay


William Slough 1.0
Overview 0.8
A Question of Primes
0.6
Introduction to
0.4
voltage (mV)

PythonTEX

Mathematics with
Sympy
0.2 y = cos(2πt)e−t
Plots with matplotlib 0.0
Web Services
−0.2
Conclusions
−0.4
Extra Examples
−0.6
−0.8
0 1 2 3 4 5
time (s)

Inspired by a plot from matplotlib.org/1.3.1/gallery.html


page.34

Plot Details, Part 1


A Gentle
Introduction to
PythonTEX

Andrew Mertz, \begin{pycode}


William Slough
from pylab import *
Overview

A Question of Primes # Define f(t), the desired function to plot


Introduction to def f(t):
PythonTEX
return cos(2 * pi * t) * exp(-t)
Mathematics with
Sympy

Plots with matplotlib # Generate the points (t_i, y_i) to plot


Web Services t = linspace(0, 5, 500)
Conclusions y = f(t)
Extra Examples

# Begin with an empty plot, 5 x 3 inches


clf()
figure(figsize=(5, 3))

# Use TeX fonts


rc("text", usetex=True)
page.35

Plot Details, Part 2


A Gentle
Introduction to
PythonTEX

Andrew Mertz,
William Slough # Generate the plot with annotations
plot(t, y)
Overview
title("Damped exponential decay")
A Question of Primes
text(3, 0.15, r"$y = \cos(2 \pi t) e^{-t}$")
Introduction to
PythonTEX xlabel("time (s)")
Mathematics with ylabel("voltage (mV)")
Sympy

Plots with matplotlib


# Save the plot as a PDF file
Web Services
savefig("myplot.pdf", bbox_inches="tight")
Conclusions

Extra Examples
# Include the plot in the current LaTeX document
print(r"\begin{center}")
print(r"\includegraphics[width=0.85\textwidth]{myplot.pdf}")
print(r"\end{center}")
\end{pycode}
page.36

Simple Access of a Web Service


A Gentle
Introduction to
PythonTEX

Andrew Mertz,
William Slough
Many powerful and freely available web services can be accessed
Overview
though the libraries of Python.
A Question of Primes

Introduction to
PythonTEX Python has excellent JSON, XML and networking libraries.
Mathematics with
Sympy

Plots with matplotlib The first web service we will use is Google’s Geocoding API.
Web Services

Conclusions

Extra Examples Geocoding is the process of converting an address into geographic


coordinates such as latitude and longitude.

Reverse geocoding is the process of converting geographic


coordinates into a human-readable address.
page.37

Using Google’s Geocoding Service


A Gentle
Introduction to
PythonTEX from urllib2 import urlopen
Andrew Mertz, from urllib import urlencode
William Slough
import json
Overview

A Question of Primes
def findLatlong(address):
Introduction to
PythonTEX
# Build the data needed to call the Goggle API
Mathematics with
query = {"address": address, "sensor": "false"}
Sympy data = urlencode(query)
Plots with matplotlib url = "http://maps.googleapis.com/maps/api/geocode/json?"
Web Services url += data
Conclusions

Extra Examples # Fetch and parse


result = json.load(urlopen(url))
latlong = result["results"][0]["geometry"]["location"]
return (latlong["lat"], latlong["lng"])

The latitude and longitude of Tokyo is \py{findLatlong("Tokyo")}


The latitude and longitude of Tokyo is (35.6894875, 139.6917064)
page.38

Executing a Subprocess
A Gentle
Introduction to
PythonTEX

Andrew Mertz,
Python can run other programs and use their output.
William Slough

Overview Here we use webkit2png to render a web page as an image that is


A Question of Primes included in the document.
Introduction to
PythonTEX

Mathematics with
Sympy import subprocess
Plots with matplotlib

Web Services def showWebpage(url, filename):


Conclusions subprocess.call(["webkit2png", "-o", filename,
Extra Examples "-F", "javascript",
"-w", "5",
url])
print(r"\begin{center}")
print(r"\includegraphics{%s}" % filename)
print(r"\end{center}")
page.39

How the Maps Were Made (pseudocode)


A Gentle
Introduction to
PythonTEX

Andrew Mertz,
William Slough

Overview

A Question of Primes def showGoogleMap(address, zoomlevel):


Introduction to
PythonTEX
# Find the latitude and longitude of the address
Mathematics with
Sympy # Build a web page with the JavaScript needed to load
Plots with matplotlib # a Google Map at the given location and zoom level
Web Services

Conclusions # Save the web page to a temporary file


Extra Examples

# Use showWebpage to display the map


page.40

Issues
A Gentle
Introduction to
PythonTEX
I PythonTEX adds significant processing time
Andrew Mertz,
William Slough
Appropriate use of sessions can reduce this time, but
there is still a large overhead.
Overview

A Question of Primes
I Debugging Python code within TEX is difficult
Introduction to
PythonTEX Test complex Python code outside of TEX first
Mathematics with
Sympy
I TEX macros that have arguments generated by Python fail on
Plots with matplotlib
first processing step
Web Services

Conclusions
Add such TEX macros from within Python
Extra Examples
I Use parentheses for print statements: print(x).
I Be clear of the differences between \py and \pyc.
I When using Beamer use the frame option
fragile=singleslide if able.
I Be skeptical of SymPy results.
I If all else fails delete the pythontex-files folder.
page.41

A Gentle
Introduction to
PythonTEX

Andrew Mertz,
William Slough

Overview

A Question of Primes

Introduction to
PythonTEX

Mathematics with
Sympy

Plots with matplotlib


Questions?
Web Services

Conclusions

Extra Examples
page.42

References
A Gentle
Introduction to
PythonTEX

Andrew Mertz,
William Slough
Python: python.org
Overview

A Question of Primes

Introduction to
PythonTEX
SciPy: scipy.org
Mathematics with
Sympy

Plots with matplotlib


PythonTEX(Geoffrey Poore): www.ctan.org/pkg/pythontex
Web Services

Conclusions

Extra Examples

Anaconda(Python distribution): store.continuum.io/cshop/anaconda

webkit2png: github.com/adamn/python-webkit2png
page.43

How to Shorten a Long URL


A Gentle
Introduction to
PythonTEX from urllib2 import Request
Andrew Mertz, def shortenURL(longURL):
William Slough
# Build the data needed to call the Goggle API
Overview
url = "https://www.googleapis.com/urlshortener/v1/url"
A Question of Primes
query = {"longUrl": longURL, "key": googleAPIKey}
Introduction to
PythonTEX
data = json.dumps(query)
Mathematics with
request = Request(url, data,
Sympy {"Content-Type": "application/json"})
Plots with matplotlib

Web Services # Fetch and parse


Conclusions result = json.load(urlopen(request))
Extra Examples shortURL = result["id"]
print(r"\url{%s}%%" % shortURL)

Here is a short url \pyc{shortenURL(


"http://mirror.jmu.edu/pub/CTAN/macros/latex/contrib/pythontex/pythontex.pdf")}

Here is a short url http://goo.gl/sfT8S5.


page.44

Mail Merge
A Gentle
Introduction to
PythonTEX

Andrew Mertz,
William Slough

Overview Address: to field


A Question of Primes Hello name field, I just wanted to say hello.
Introduction to
PythonTEX

Mathematics with
Sympy

Plots with matplotlib

Web Services
to,name
Conclusions
js@example.com,John Smith
Extra Examples
mw@example.com,Mike White
tb@example.com,Tom Blue
page.45

Mail Merge
A Gentle
Introduction to
PythonTEX \begin{pythontexcustomcode}{py}
Andrew Mertz, import csv
William Slough

Overview def mailMerge(filename, texcommand):


A Question of Primes csvFile = open(filename, "r")
Introduction to
PythonTEX
csvReader = csv.DictReader(csvFile)
Mathematics with
for row in csvReader:
Sympy setCommand = r"\def\mail%s{%s}"
Plots with matplotlib

Web Services for keyValuePair in row.items():


Conclusions print(setCommand % keyValuePair)
Extra Examples

print(r"%s\vfill" % texcommand)
\end{pythontexcustomcode}

\newcommand{\mailBody}{
Address: \mailto\\
Hello \mailname, I just wanted to say hello.
}
page.46

Mail Merge
A Gentle
Introduction to
PythonTEX

Andrew Mertz,
William Slough \pyc{mailMerge("../data.csv", r"\mailBody")}
Overview

A Question of Primes

Introduction to
Address: js@example.com
PythonTEX Hello John Smith, I just wanted to say hello.
Mathematics with
Sympy

Plots with matplotlib

Web Services
Address: mw@example.com
Conclusions
Hello Mike White, I just wanted to say hello.
Extra Examples

Address: tb@example.com
Hello Tom Blue, I just wanted to say hello.

You might also like