A Gentle Introduction To PythonTeX

Transcription

page.1A GentleIntroduction toPythonTEXAndrew Mertz,William SloughOverviewA Question of PrimesIntroduction toPythonTEXA Gentle Introduction to PythonTEXMathematics withSympyPlots with matplotlibAndrew MertzWilliam SloughWeb ServicesConclusionsExtra ExamplesMathematics and Computer Science DepartmentEastern Illinois UniversityOctober 23, 2013

page.2A GentleIntroduction toPythonTEXAndrew Mertz,William SloughOverviewA Question of PrimesIntroduction toPythonTEXMathematics withSympyPlots with matplotlibWeb ServicesConclusionsExtra ExamplesTEX

page.3Python OverviewA GentleIntroduction toPythonTEXAndrew Mertz,William SloughOverviewA Question of PrimesIntroduction toPythonTEXMathematics withIGeneral purpose, high-level programming languageIMulti-paradigm: object-oriented, imperative, functionalIComprehensive standard libraryIOrigins from late 1989IFree and open-sourceSympyPlots with matplotlibWeb ServicesConclusionsExtra Examples

page.4Python Scientific ComputingA GentleIntroduction toPythonTEXAndrew Mertz,William SloughOverviewA Question of PrimesIntroduction toPythonTEXMathematics withSympyPlots with matplotlibWeb ServicesConclusionsExtra Examples

page.5A Recent Question on TEX Stack ExchangeA GentleIntroduction toPythonTEXAndrew Mertz,William SloughOverviewA Question of PrimesIntroduction toPythonTEXMathematics withSympyPlots with matplotlib“I would like to write a LATEX script that produces all the primenumbers between the numbers n and m, where n m. How can I dothis? I feel it should not be that hard, but I cannot seem to programit.”— Kevin†Web ServicesConclusionsExtra Examples† uce-a-list-of-prime-numbers-in-latex/134366#134366

page.6From The TEXBook, Page 218 (1984)A GentleIntroduction toPythonTEXAndrew Mertz,William SloughOverviewA Question of PrimesIntroduction toPythonTEXMathematics withSympyPlots with matplotlibThe first 30 prime numbers 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. You may not find this fact very startling; but you maybe surprised to learn that the previous sentence was typeset by sayingThe first thirty prime numbers are \primes{30}.Web ServicesConclusionsExtra ExamplesTEX did all the calculation by expanding the primes macro, so theauthor is pretty sure that the list of prime numbers given above isquite free of typographic errors.

page.7Knuth’s Code, -worthyA GentleIntroduction toPythonTEXAndrew Mertz,William SloughOverviewA Question of PrimesIntroduction toPythonTEXMathematics withSympyPlots with matplotlibWeb ServicesConclusionsExtra Examples\newif\ifprime \newif\ifunknown % boolean variables\newcount\n \newcount\p \newcount\d \newcount\a % integer variables\def\primes#1{2, 3% assume that #1 is at least 3\n #1 \advance\n by-2 % n more to go\p 5 % odd primes starting with p\loop\ifnum\n 0 \printifprime\advance\p by2 \repeat}\def\printp{, % we will invoke \printp if p is prime\ifnum\n 1 and \fi % and precedes the last value\number\p \advance\n by -1 }\def\printifprime{\testprimality \ifprime\printp\fi}\def\testprimality{{\d 3 \global\primetrue\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.8David Carlisle’s ResponseA GentleIntroduction toPythonTEXAndrew Mertz,William SloughOverviewA Question of PrimesIntroduction toPythonTEXMathematics withSympyPlots with matplotlibWeb ServicesConclusionsExtra \def\comma{, ndafter\ifx\csname p-\the\count@\endcsname\relax\ifnum\@tempcntb \count@\else\ifnum\count@ ndafter\let\csname p-\the\@tempcnta\endcsname\@ne\ifnum\@tempcnta \@tempcntb\repeat\ifnum\@tempcntb \count@\expandafter\@primes\fi}\makeatother

page.9Karl Koeller’s ResponseA GentleIntroduction toPythonTEXAndrew Mertz,William SloughA solution using the \pgfmathisprime macro provided by AlainMatthes’ tkz-euclide package:OverviewA Question of PrimesIntroduction toPythonTEX\usepackage{tkz-euclide}Mathematics withSympy\newif\ifcommaPlots with matplotlibWeb ServicesConclusionsExtra ach\numb in sult 1\ifcomma, \numb\else\numb\global\commatrue\fi%\fi%}%}

page.10Can PythonTEX Make This Simpler?A GentleIntroduction toPythonTEXAndrew Mertz,William SloughOverviewA Question of PrimesIntroduction toPythonTEXMathematics withSympyPlots with matplotlibWeb ServicesConclusionsExtra ExamplesYes. . .

page.11Evaluating Expressions With \pyA GentleIntroduction toPythonTEXAndrew Mertz,William SloughOverviewA Question of PrimesThe macro \py{expression} evaluates a Python expression andtypesets its value.Introduction toPythonTEXMathematics withSympyPlots with matplotlibWeb ServicesDid you know that 2 {65} \py{2**65} ?ConclusionsExtra ExamplesDid you know that 265 36893488147419103232?

page.12Evaluating Expressions With \pycA GentleIntroduction toPythonTEXAndrew Mertz,William SloughOverviewThe macro \pyc{expression} evaluates a Python expression andtypesets anything that it prints.A Question of PrimesIntroduction toPythonTEXMathematics withSympyDid you know that 2 {65} \pyc{print(2**65)} ?Plots with matplotlibWeb ServicesConclusionsDid you know that 265 36893488147419103232?Extra ExamplesWhile “printing” adds little in this case, it is important for morecomplex examples.

page.13A More Complex Example Using \pycA GentleIntroduction toPythonTEXAndrew Mertz,William SloughOverviewA Question of PrimesIntroduction toPythonTEXMathematics withSympyPlots with matplotlibWeb ServicesConclusionsExtra Examples\pyc{showGoogleMap("Tokyo", 11)}

page.14Charleston, Illinois USAA GentleIntroduction toPythonTEXAndrew Mertz,William SloughOverviewA Question of PrimesIntroduction toPythonTEXMathematics withSympyPlots with matplotlibWeb ServicesConclusionsExtra Examples\pyc{showGoogleMap("600 Lincoln,Charleston,IL", 14)}

page.15Generating Tables With pycodeA GentleIntroduction toPythonTEXAndrew Mertz,William SloughOverviewA Question of PrimesIntroduction toPythonTEXMathematics withSympyPlots with matplotlibWeb Services\begin{pycode}print(r"\begin{tabular}{c c}")print(r" m & 2 m \\ \hline")print(r"%d & %d \\" % (1, 2**1))print(r"%d & %d \\" % (2, 2**2))print(r"%d & %d \\" % (3, 2**3))print(r"%d & %d \\" % (4, nsExtra Examples\begin{tabular}{c c} m & 2 m \\ \hline1 & 2 \\2 & 4 \\3 & 8 \\4 & 16 \\\end{tabular}

page.16Generating Tables With pycodeA GentleIntroduction toPythonTEXAndrew Mertz,William SloughOverviewA Question of PrimesIntroduction toPythonTEXMathematics withSympyPlots with matplotlibWeb Services\begin{pycode}print(r"\begin{tabular}{c c}")print(r" m & 2 m \\ \hline")print(r"%d & %d \\" % (1, 2**1))print(r"%d & %d \\" % (2, 2**2))print(r"%d & %d \\" % (3, 2**3))print(r"%d & %d \\" % (4, nsExtra Examplesm12342m24816

page.17Generating Tables With a LoopA GentleIntroduction toPythonTEXAndrew Mertz,William SloughOverviewA Question of PrimesIntroduction toPythonTEXMathematics withSympyPlots with matplotlib\begin{pycode}lo, hi 1, 6print(r"\begin{tabular}{c c}")print(r" m & 2 m \\ \hline")for m in range(lo, hi 1):print(r"%d & %d \\" % (m, 2**m))print(r"\end{tabular}")\end{pycode}Web ServicesConclusionsExtra Examplesm1234562m248163264

page.18Defining a FunctionA GentleIntroduction toPythonTEXAndrew Mertz,William SloughOverviewA Question of PrimesIntroduction toPythonTEXMathematics withSympyPlots with matplotlibWeb Services\begin{pycode}def fib(n):# nth Fibonacci valuea, b 0, 1for i in range(n):a, b b, a breturn a\end{pycode}ConclusionsExtra ExamplesDid you know that F {10} \py{fib(10)} ?Did you know that F10 55?

page.19SessionsA GentleIntroduction toPythonTEXAndrew Mertz,William Sloughpy, pyc, and pycode all have an optional session argument.OverviewA Question of PrimesIntroduction toPythonTEXMathematics withSympyThis argument determines the name of the Python session in whichthe code is executed.Plots with matplotlibWeb ServicesConclusionsExtra ExamplesSessions with different names may be executed in parallel providing aspeedup.If a session is not specified, then the default session is used.

page.20Introducing pythontexcustomcodeA GentleIntroduction toPythonTEXAndrew Mertz,William SloughOverviewA Question of PrimesIntroduction toPythonTEXMathematics withSympyPlots with matplotlib\begin{pythontexcustomcode}{py}def makeTable(lo, hi):print(r"\begin{tabular}{c c}")print(r" m & 2 m \\ \hline")for m in range(lo, hi 1):print(r"%d & %d \\" % (m, ode}Web ServicesConclusionsExtra ExamplesThe pythontexcustomcode environment evaluates the code blockat the start of each “session” – which makes it a great place todefine well-tested functions.\begin{pythontexcustomcode}{py}python code block\end{pythontexcustomcode}

page.21Generating Tables in Multiple SessionsA GentleIntroduction to\pyc[table1]{makeTable(1, 4)}PythonTEXAndrew Mertz,William SloughOverviewA Question of PrimesIntroduction toPythonTEXm12342m24816Mathematics withSympyPlots with matplotlib\pyc[table2]{makeTable(4, 10)}Web ServicesConclusionsExtra Examplesm456789102m1632641282565121024

page.22Generating Tables From a FunctionA GentleIntroduction toPythonTEXAndrew Mertz,William SloughOverviewA Question of PrimesIntroduction toPythonTEXMathematics withSympyPlots with matplotlib\begin{pythontexcustomcode}{py}def makeTableFromFunction(lo, hi, funct, label):print(r"\begin{tabular}{c c}")print(r" m & %s \\ \hline" % label)for m in range(lo, hi 1):print(r"%d & %d \\" % (m, tomcode}Web ServicesConclusions\pyc{makeTableFromFunction(7, 11, fib, " F {m} ")}Extra Examplesm7891011Fm1321345589

page.23Generating Tables From a Library FunctionA GentleIntroduction toPythonTEXAndrew Mertz,William SloughOverviewPython excels in the quantity and quality of its modules.Modules make additional functions available. To use them, thecorresponding module needs to be imported.A Question of PrimesIntroduction toPythonTEXMathematics withSympy\begin{pythontexcustomcode}{py}import math\end{pythontexcustomcode}Plots with matplotlibWeb ServicesConclusions\pyc{makeTableFromFunction(30, 33, math.factorial, " m! ")}Extra 280000000

page.24Generating Tables From a Library FunctionA GentleIntroduction toPythonTEXAndrew Mertz,William SloughWith the import statement the module name is needed each time amember of the module is used.To avoid this, a from import statement can be used.OverviewA Question of PrimesIntroduction toPythonTEXMathematics withSympyPlots with matplotlibThis can shadow other functions and should be used with care.\begin{pythontexcustomcode}{py}from math import factorial\end{pythontexcustomcode}Web ServicesConclusions\pyc{makeTableFromFunction(30, 33, factorial, " m! ")}Extra 280000000

page.25Remember Kevin?A GentleIntroduction toPythonTEXAndrew Mertz,William SloughOverview\begin{pythontexcustomcode}{py}from sympy import primeA Question of PrimesIntroduction toPythonTEXMathematics withSympyPlots with matplotlibWeb Servicesdef generatePrimes(n):# Assume n 3for i in range(1, n):print("%d, " % prime(i))print("and %d%%" % prime(n))\end{pythontexcustomcode}ConclusionsExtra ExamplesThe 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, and113.

page.26Processing PythonTEX FilesA GentleIntroduction toPythonTEXAndrew Mertz,William Sloughmy.texOverviewA Question of PrimesIntroduction toPythonTEXMathematics withSympyPlots with matplotlibWeb Services1. pdfLATEX2. xtra Examples3. pdfLATEXmy.pdf

page.27Symbolic Mathematics With SympyA GentleIntroduction toPythonTEXAndrew Mertz,William SloughOverviewA Question of Primes from sympy import * var("x, y")(x, y)# Define symbolic variablesIntroduction toPythonTEXMathematics with z (x y)**3 # Define an expressionSympyPlots with matplotlibWeb ServicesConclusions z(x y)**3# Display zExtra Examples expand(z)# Display the expansion of zx**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.28Expanding BinomialsA GentleIntroduction toPythonTEXAndrew Mertz,William Slough\begin{pycode}from sympy import *var("x, y")OverviewA Question of PrimesIntroduction toPythonTEXbinomials []for m in range(3, 6):binomials.append((x y)**m)Mathematics withSympyPlots with matplotlibWeb ServicesConclusionsExtra Examplesprint(r"\begin{align*}")for expr in binomials:print(r"%s & %s\\" % (latex(expr), code}3(x y ) x 3 3x 2 y 3xy 2 y 34(x y ) x 4 4x 3 y 6x 2 y 2 4xy 3 y 45(x y ) x 5 5x 4 y 10x 3 y 2 10x 2 y 3 5xy 4 y 5

page.29A Little Bit of CalculusA GentleIntroduction toPythonTEXAndrew Mertz,William SloughOverviewA Question of PrimesIntroduction toPythonTEXMathematics withSympy\begin{pycode}functions [sin(x), cos(x), tan(x)]print(r"\begin{align*}")for f in functions:d Derivative(f, x)print(latex(d) "& " latex(d.doit()) r"\\")print(r"\end{align*}")\end{pycode}Plots with matplotlibWeb ServicesConclusionsExtra Examplesdsin (x) cos (x)dxdcos (x) sin (x)dxdtan (x) tan2 (x) 1dx

page.30A Little Bit MoreA GentleIntroduction toPythonTEXAndrew Mertz,William SloughOverviewA Question of PrimesIntroduction toPythonTEXMathematics withSympy\begin{pycode}functions [sin(x), cos(x), tan(x)]print(r"\begin{align*}")for f in functions:i Integral(f, x)print(latex(i) "& " latex(i.doit()) r"\\")print(r"\end{align*}")\end{pycode}Plots with matplotlibWeb ServicesZConclusionsExtra Examplessin (x) dx cos (x)Zcos (x) dx sin (x)Z 1tan (x) dx log sin2 (x) 12

page.31Stirling’s TriangleA GentleIntroduction toPythonTEXAndrew Mertz,William SloughOverviewn n0 n101234567810000000011111111A Question of PrimesIntroduction toPythonTEXMathematics withSympyPlots with matplotlibWeb ServicesConclusionsExtra ExamplesStirling’s Triangle for Subsets 401050121266 n7 n81281

page.32Stirling’s Triangle (code excerpt)A GentleIntroduction toPythonTEXAndrew Mertz,William SloughOverviewA Question of PrimesIntroduction toPythonTEXMathematics withSympyPlots with matplotlibWeb ServicesConclusionsExtra Examplesfrom sympy.functions.combinatorial.numbers import *for n in range(numberOfRightHandColumns):print("%d" % n)for k in range(n 1):print("& %d" % stirling(n, k))print(r"\\")

page.33Plotting With MatplotlibA GentleIntroduction toPythonTEXAndrew Mertz,William Slough0.8A Question of Primes0.6Introduction toPythonTEX0.4SympyPlots with matplotlibWeb ServicesConclusionsExtra Examplesvoltage (mV)OverviewMathematics withDamped exponential decay1.00.2y cos(2πt)e t0.0 0.2 0.4 0.6 0.801234time (s)Inspired by a plot from matplotlib.org/1.3.1/gallery.html5

page.34Plot Details, Part 1A GentleIntroduction toPythonTEXAndrew Mertz,William Slough\begin{pycode}from pylab import *OverviewA Question of PrimesIntroduction toPythonTEX# Define f(t), the desired function to plotdef f(t):return cos(2 * pi * t) * exp(-t)Mathematics withSympyPlots with matplotlibWeb ServicesConclusions# Generate the points (t i, y i) to plott linspace(0, 5, 500)y f(t)Extra Examples# Begin with an empty plot, 5 x 3 inchesclf()figure(figsize (5, 3))# Use TeX fontsrc("text", usetex True)

page.35Plot Details, Part 2A GentleIntroduction toPythonTEXAndrew Mertz,William SloughOverviewA Question of PrimesIntroduction toPythonTEXMathematics with# Generate the plot with annotationsplot(t, y)title("Damped exponential decay")text(3, 0.15, r" y \cos(2 \pi t) e {-t} ")xlabel("time (s)")ylabel("voltage (mV)")SympyPlots with matplotlibWeb Services# Save the plot as a PDF filesavefig("myplot.pdf", bbox inches "tight")ConclusionsExtra Examples# Include the plot in the current LaTeX aphics[width )\end{pycode}

page.36Simple Access of a Web ServiceA GentleIntroduction toPythonTEXAndrew Mertz,William SloughMany powerful and freely available web services can be accessedthough the libraries of Python.OverviewA Question of PrimesIntroduction toPythonTEXPython has excellent JSON, XML and networking libraries.Mathematics withSympyPlots with matplotlibThe first web service we will use is Google’s Geocoding API.Web ServicesConclusionsExtra ExamplesGeocoding is the process of converting an address into geographiccoordinates such as latitude and longitude.Reverse geocoding is the process of converting geographiccoordinates into a human-readable address.

page.37Using Google’s Geocoding ServiceA GentleIntroduction toPythonTEXAndrew Mertz,William Sloughfrom urllib2 import urlopenfrom urllib import urlencodeimport jsonOverviewA Question of PrimesIntroduction toPythonTEXMathematics withSympyPlots with matplotlibWeb Servicesdef findLatlong(address):# Build the data needed to call the Goggle APIquery {"address": address, "sensor": "false"}data urlencode(query)url "url dataConclusionsExtra Examples# Fetch and parseresult 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.38Executing a SubprocessA GentleIntroduction toPythonTEXAndrew Mertz,William SloughOverviewA Question of PrimesPython can run other programs and use their output.Here we use webkit2png to render a web page as an image that isincluded in the document.Introduction toPythonTEXMathematics withSympyimport subprocessPlots with matplotlibWeb ServicesConclusionsExtra Examplesdef showWebpage(url, filename):subprocess.call(["webkit2png", "-o", filename,"-F", "javascript","-w", raphics{%s}" % filename)print(r"\end{center}")

page.39How the Maps Were Made (pseudocode)A GentleIntroduction toPythonTEXAndrew Mertz,William SloughOverviewA Question of PrimesIntroduction toPythonTEXdef showGoogleMap(address, zoomlevel):# Find the latitude and longitude of the addressMathematics withSympyPlots with matplotlib# Build a web page with the JavaScript needed to load# a Google Map at the given location and zoom levelWeb ServicesConclusions# Save the web page to a temporary fileExtra Examples# Use showWebpage to display the map

page.40IssuesA GentleIntroduction toPythonTEXIPythonTEX adds significant processing timeAppropriate use of sessions can reduce this time, butthere is still a large overhead.IDebugging Python code within TEX is difficultTest complex Python code outside of TEX firstITEX macros that have arguments generated by Python fail onfirst processing stepAdd such TEX macros from within PythonIUse parentheses for print statements: print(x).Be clear of the differences between \py and \pyc.When using Beamer use the frame optionfragile singleslide if able.Be skeptical of SymPy results.If all else fails delete the pythontex-files folder.Andrew Mertz,William SloughOverviewA Question of PrimesIntroduction toPythonTEXMathematics withSympyPlots with matplotlibWeb ServicesConclusionsExtra ExamplesIIII

page.41A GentleIntroduction toPythonTEXAndrew Mertz,William SloughOverviewA Question of PrimesIntroduction toPythonTEXMathematics withSympyPlots with matplotlibWeb ServicesConclusionsExtra ExamplesQuestions?

page.42ReferencesA GentleIntroduction toPythonTEXAndrew Mertz,William SloughPython: python.orgOverviewA Question of PrimesIntroduction toPythonTEXSciPy: scipy.orgMathematics withSympyPlots with matplotlibWeb ServicesPythonTEX(Geoffrey Poore): www.ctan.org/pkg/pythontexConclusionsExtra ExamplesAnaconda(Python distribution): store.continuum.io/cshop/anacondawebkit2png: github.com/adamn/python-webkit2png

page.43How to Shorten a Long URLA GentleIntroduction toPythonTEXAndrew Mertz,William SloughOverviewA Question of PrimesIntroduction toPythonTEXMathematics withSympyfrom urllib2 import Requestdef shortenURL(longURL):# Build the data needed to call the Goggle APIurl ery {"longUrl": longURL, "key": googleAPIKey}data json.dumps(query)request Request(url, data,{"Content-Type": "application/json"})Plots with matplotlibWeb ServicesConclusionsExtra Examples# Fetch and parseresult json.load(urlopen(request))shortURL result["id"]print(r"\url{%s}%%" % shortURL)Here is a short url cros/latex/contrib/pythontex/pythontex.pdf")}Here is a short url http://goo.gl/sfT8S5.

page.44Mail MergeA GentleIntroduction toPythonTEXAndrew Mertz,William SloughOverviewA Question of PrimesAddress: to fieldHello name field, I just wanted to say hello.Introduction toPythonTEXMathematics withSympyPlots with matplotlibWeb ServicesConclusionsExtra Examplesto,namejs@example.com,John Smithmw@example.com,Mike Whitetb@example.com,Tom Blue

page.45Mail MergeA GentleIntroduction toPythonTEXAndrew Mertz,William SloughOverviewA Question of PrimesIntroduction toPythonTEXMathematics withSympy\begin{pythontexcustomcode}{py}import csvdef mailMerge(filename, texcommand):csvFile open(filename, "r")csvReader csv.DictReader(csvFile)for row in csvReader:setCommand r"\def\mail%s{%s}"Plots with matplotlibWeb ServicesConclusionsfor keyValuePair in row.items():print(setCommand % keyValuePair)Extra Examplesprint(r"%s\vfill" % ailBody}{Address: \mailto\\Hello \mailname, I just wanted to say hello.}

page.46Mail MergeA GentleIntroduction toPythonTEXAndrew Mertz,William Slough\pyc{mailMerge("./data.csv", r"\mailBody")}OverviewA Question of PrimesIntroduction toPythonTEXAddress: js@example.comHello John Smith, I just wanted to say hello.Mathematics withSympyPlots with matplotlibWeb ServicesConclusionsAddress: mw@example.comHello Mike White, I just wanted to say hello.Extra ExamplesAddress: tb@example.comHello Tom Blue, I just wanted to say hello.

Python Overview I General purpose, high-level programming language I Multi-paradigm: object-oriented, imperative, functional I Comprehensive standard library I Origins from late 1989 I Free and open-source. page.4 A Gentle Introduction to PythonTEX Andrew Mertz, Wil