\documentclass[mathserif,9pt]{beamer}
\parindent=0pt \parskip=8pt

\beamertemplatenavigationsymbolsempty
\beamertemplateballtoc

\usepackage{beamerthemeCambridgeUS} 
\usepackage{pgf,pgfarrows,pgfnodes,pgfautomata,pgfheaps,pgfshade}
\usepackage{amsmath,amssymb}
\usepackage[mathscr]{eucal}
\usepackage[latin1]{inputenc}
%\usepackage{colortbl}
\usepackage[english]{babel}
\setlength{\parindent}{0cm}
\usepackage{graphicx}
\usepackage{psfrag}

%\usepackage{times}

\input{slidesyms}
%\input{syms}

\newcommand{\hatvecx}{\hat{\mathbf{x}}}
\newcommand{\hatvecy}{\hat{\mathbf{y}}}
\newcommand{\hatvecz}{\hat{\mathbf{z}}}

%% ================================================================
\title
	{Python for the working (or aspiring) mathematician}
\author[J.\ Kerl]{John Kerl}
\institute[Arizona]{Department of Mathematics, University of Arizona\\
Software Interest Group}
\date{October 26, 2009}

\begin{document}

\begin{frame}
\titlepage
\end{frame}

%% ----------------------------------------------------------------
\begin{frame}
\frametitle{Abstract}

\begin{itemize}

\item {\emcol Why} people use Python.

\vspace*{0.2in}

\item The {\emcol minimum} you need to know to write and run simple
Python programs, even if you haven't used such languages before.

\vspace*{0.2in}

\item {\emcol Numerics}.

\vspace*{0.2in}

\item {\emcol Formatted I/O}.

\vspace*{0.2in}

\item The \texttt{pylab} module, which offers Matlab-like {\emcol plotting}
functionality.

\end{itemize}

\end{frame}

%% ----------------------------------------------------------------
\begin{frame}
\frametitle{Why Python?  What can one more language do for you?}

\begin{itemize}

\item Python programs are {\emcol fast to develop}:  no compilation phase.
Python syntax is clean, clear, and intuitive:  it looks as simple as
pseudocode.

\item Unlike monolithic programs such as Matlab, Mathematica, etc., it's easy
to connect ({\emcol pipe}) Python scripts to other programs.

\item Python has {\emcol built-in support} for text manipulation, flexible
lists, and complex arithmetic.

\item It {\emcol works the same} on Unix/Linux or Windows.

\item It's good for doing math, as well as other quick-and-dirty programs.
Python is a {\emcol general-purpose language}: which you can use to automate
all sorts of miscellaneous tedious time-consuming tasks --- times when you
think \emph{I am really sick and tired of this miscellaneous tedious
time-consuming task which is keeping me from what I'd rather be doing} ---
grade calcuations, turning data into nicely formatting LaTeX output, making
bulk changes to many files at once, making a nice index for LaTeX documents,
etc.  etc.

\end{itemize}

\end{frame}

%% ----------------------------------------------------------------
\begin{frame}
\frametitle{Reading proficiency}

The department has a {\emcol foreign language} requirement for PhD students.
Why?  Well, not all important results are published in your native language!

By the same token, if you're doing compuational work of any sort, you may find
that your collaborators' favorite programming languages aren't the same as
yours.

If you're going to be doing numerical work, learn some Python, C, Fortran,
Matlab, R.

\end{frame}

%% ----------------------------------------------------------------
\begin{frame}
\frametitle{Magic}

There are many pre-existing software tools.  In this presentation, I'll give
examples of an ODE solver and a data formatter.  Matlab et al. already do these
things for you.  Why should you listen to me reinventing the wheel?

\begin{itemize}

\item Python is freely available; Matlab is not.

\item Pre-existing packages don't always have what you want --- be ready to
roll your own when necessary.

\item Computers appear to be magical.  When you learn to program, you learn to
create your own wizardry and find out how things really work.  Python is a good
starter language.

\end{itemize}

\end{frame}

%% ----------------------------------------------------------------
% Beamer lore:  mark the frame fragile if it contains verbatim.
\begin{frame}[fragile]
\frametitle{Installation and on-line help}

Installation:

\begin{itemize}

\item Unix/Linux:  It's already there.

\item Mac:  It's there too --- Python is included in Mac OS X.

\item Windows:  Download it from the web.

\end{itemize}

On-line help example (we'll talk about \texttt{re.sub} in a few slides):

\begin{verbatim}
[shell prompt]$ python
>>> import re
>>> help(re.sub)
>>> exit()
\end{verbatim}

\end{frame}

%% ----------------------------------------------------------------
% Beamer lore:  mark the frame fragile if it contains verbatim.
\begin{frame}[fragile]
\frametitle{Running Python programs}

Put the following text in a file, say \texttt{hello.py}:

\begin{verbatim}
print 'Hello, world!'
\end{verbatim}

Then at the command prompt, type:

\begin{verbatim}
[shell prompt]$ python hello.py
\end{verbatim}

You should see:

\begin{verbatim}
Hello, world!
\end{verbatim}

\end{frame}

%% ----------------------------------------------------------------
\begin{frame}
\frametitle{More about running Python programs}

For simplicity of presentation, I suggested typing \texttt{python hello.py}.

You can also just type \texttt{hello.py}, if you first do the following:

\begin{itemize}

\item On Unix/Linux:   The first line of \texttt{hello.py} should be
{\emcol \texttt{\#!/usr/bin/python}}.  Then, at the command line,
{\emcol \texttt{chmod u+x hello.py}}.
(The \texttt{.py} extension isn't necessary.)

\item On Windows:  You must use a \texttt{.py} extension.  Also, set up an
association to open such programs using \texttt{python}.

\item I can give you more info about this topic but it's a technical detail.

\end{itemize}

\end{frame}

%% ----------------------------------------------------------------
\begin{frame}
\frametitle{Numerics by example}

Here is a naive Euler (first-order) integrator for the Lorenz equations.  (Feel
free to implement higher-order techniques such as Runge-Kutta --- it would
simply occupy another slide or two.)

Derivation of Euler scheme:
\begin{eqnarray*}
	x &=& x(t) \\
	x' &\approx& \frac{x(t+h) - x(t)}{h} \\
	x(t+h) &\approx& x(t) + h x' \\
	x_{k+1} &:=& x_k + h x'
\end{eqnarray*}
Let's turn that into instructions for a computer to carry out,
using the Lorenz equations.

\end{frame}

%% ----------------------------------------------------------------
\begin{frame}
\frametitle{Lorenz equations}

System of non-linear ODEs:
\begin{eqnarray*}
	x' &=& s(y-x) \\
	y' &=& rx - y - xz \\
	z' &=& xy -bz. \\
\end{eqnarray*}
Constants:
$$
	s = 10.0, \qquad
	r = 28.0, \qquad
	b = 2.6666667.
$$
Initial conditions:
$$
	x_0 = 10, \qquad
	y_0 =  0, \qquad
	z_0 = 10.
$$

\end{frame}

%% ----------------------------------------------------------------
% Beamer lore:  mark the frame fragile if it contains verbatim.
\begin{frame}[fragile]
\frametitle{Numerical script}

\begin{verbatim}
tmax = 10.0; h = 0.002; N = int(tmax/h) # 10 seconds with 0.002-sec step
s    = 10.0; r = 28.0;  b = 2.666667    # Constants
t    = 0;    x = 10;    y = 0; z = 10   # Initial conditions
while t < tmax:
    print '%11.8f %11.8f %11.8f' % (x, y, z)
    xp = s * (y - x);      # Cheesy Euler integrator.
    yp = r * x - y - x * z
    zp = x * y - b * z
    x = x + h * xp; y = y + h * yp; z = z + h * zp; t += h
\end{verbatim}

\begin{itemize}

\item Variable assignments, arithmetic expressions, etc.  are
about what you'd expect.

\item Multiple statements on a single line are separated by semicolons.

\item Control structures (for, if, while, etc.) are delimited
using tab stops.

\item The \texttt{print} syntax is a lot like in C or Perl.

\end{itemize}

\end{frame}

%% ----------------------------------------------------------------
% Beamer lore:  mark the frame fragile if it contains verbatim.
\begin{frame}[fragile]
\frametitle{Output of numerical script}

\begin{verbatim}
[shell prompt]$ python lorenz.py
10.00000000  0.00000000 10.00000000
 9.80000000  0.36000000  9.94666666
 9.61120000  0.71312533  9.90067376
 9.43323851  1.05961157  9.86157814
 9.26576597  1.39970047  9.82897419
 9.10844466  1.73363801  9.80249158
 8.96094853  2.06167273  9.78179311
 ...         ...         ...
\end{verbatim}

OK, so we're seeing the estimated $x$'s, $y$'s, and $z$'s.  But how to plot
three variables on a two-dimensional screen?

\end{frame}

%% ----------------------------------------------------------------
\begin{frame}
\frametitle{Data manipulation by example}

Answer:  Projection from 3D to 2D is just a linear transformation.  Write down
a 2x3 matrix $P$ whose columns are where you want $\hatvecx$, $\hatvecy$, and
$\hatvecz$ to go.  Pre-multiply each data
triple by that:
$$
	\begin{bmatrix}
	u \\ v
	\end{bmatrix}
	=
	\begin{bmatrix}
	(P\hatvecx)_0 & (P\hatvecy)_0 & (P\hatvecz)_0 \\
	(P\hatvecx)_1 & (P\hatvecy)_1 & (P\hatvecz)_1 \\
	\end{bmatrix}
	\begin{bmatrix}
	x \\ y \\ z
	\end{bmatrix}
$$
Then plot $(u,v)$ pairs on the two-dimensional display.

\setlength{\unitlength}{1.0in}
\begin{picture}(6,1.5)
%\put(0.0,0.0){\framebox(6.0,1.5)}
\thicklines
\put(0.2,0.35){\vector(1,0){1.0}}
\put(0.2,0.35){\vector(0,1){1.0}}
\put(0.2,0.35){\vector(-1,-1){0.25}}
\put(1.4,0.35){$\hatvecy$ looks like $(1,0)$ in 2D}
\put(0.4,1.00){$\hatvecz$ looks like $(0,1)$ in 2D}
\put(0.2,0.00){$\hatvecx$ looks like $(-0.25,-0.25)$ in 2D}
\put(3.2,1.00){$P=\begin{bmatrix} -0.25 & 1 & 0 \\ -0.25 & 0 & 1 \\\end{bmatrix}$}
\thinlines
\end{picture}

\end{frame}

%% ----------------------------------------------------------------
\begin{frame}
\frametitle{Outline of projection script}

We'll make a separate (re-usable!) script that simply reads three-column data
--- from our Lorenz integrator \emph{or anything else} --- and writes
two-column data, modified as described above:

\begin{itemize}

\item {\emcol Read} lines of input (triples of numbers,
delimited by whitespace) one line at a time, splitting the line into
three numbers $x$, $y$, and $z$.

\item For each triple $x$, $y$, $z$, {\emcol compute}
$u$ and $v$.

\item {\emcol Write} $u$ and $v$.

\end{itemize}

\end{frame}

%% ----------------------------------------------------------------
% Beamer lore:  mark the frame fragile if it contains verbatim.
\begin{frame}[fragile]
\frametitle{Subroutines}

Here's the computation part.  I'll use this as an example of subroutines.
Assume we've already read in a triple of $x$, $y$, and $z$.  We'll call this
routine to find what $u$ and $v$ are.

\begin{verbatim}
Pxhat = [-0.25, -0.25]; Pyhat = [1, 0]; Pzhat = [0, 1]

def project_3D_to_2D_triple(x, y, z, Pxhat, Pyhat, Pzhat):
    u = Pxhat[0] * x + Pyhat[0] * y + Pzhat[0] * z
    v = Pxhat[1] * x + Pyhat[1] * y + Pzhat[1] * z
    return [u, v]
\end{verbatim}

\begin{itemize}

\item Subroutines start with the \texttt{def} keyword, and they return values
(scalars, lists, etc.) using the \texttt{return} keyword.

\item You can have a list of scalars on the left-hand side of an assignment.
E.g. the caller can do
%\texttt{[u,v] = do\_triple(x, y, z, Pxhat, Pyhat, Pzhat)}.
\begin{verbatim}
[u,v] = project_3D_to_2D_triple(x, y, z, Pxhat, Pyhat, Pzhat)
\end{verbatim}

\item Arrays are indexed (from zero up, math folks!) using square brackets.

\end{itemize}

\end{frame}

%% ----------------------------------------------------------------
% Beamer lore:  mark the frame fragile if it contains verbatim.
\begin{frame}[fragile]
\frametitle{Data I/O}

We need a routine to read files like this:
\begin{small}
\begin{verbatim}
10.00000000  0.00000000 10.00000000
 9.80000000  0.36000000  9.94666666
 9.61120000  0.71312533  9.90067376
 9.26576597  1.39970047  9.82897419
 ...
\end{verbatim}
\end{small}
columnwise into Python arrays such as
\begin{small}
\begin{verbatim}
xs = [10.00000000, 9.80000000, 9.61120000, 9.26576597, ...]
ys = [ 0.00000000, 0.36000000, 0.71312533, 1.39970047, ...]
zs = [10.00000000, 9.94666666, 9.90067376, 9.82897419, ...]
\end{verbatim}
\end{small}
and, vice versa, a routine to write such arrays to files.

I wrote a Python {\emcol module} called {\emcol tabutil.py} which does these
things.  For the sake of time, I won't show the details today.
Our script can simply import the module, and call its subroutines.

\end{frame}

%% ----------------------------------------------------------------
% Beamer lore:  mark the frame fragile if it contains verbatim.
\begin{frame}[fragile]
\frametitle{Projection script}

\begin{verbatim}
import tabutil

def project_3D_to_2D_triple(x, y, z, Pxhat, Pyhat, Pzhat):
    u = Pxhat[0] * x + Pyhat[0] * y + Pzhat[0] * z
    v = Pxhat[1] * x + Pyhat[1] * y + Pzhat[1] * z
    return [u, v]

Pxhat = [-0.25, -0.25]; Pyhat = [1, 0]; Pzhat = [0, 1]
[xs, ys, zs] = tabutil.float_columns_from_file('xyzdata.txt')
for i in range(0, len(xs)):
    x = xs[i]; y = ys[i]; z = zs[i]
    [u, v] = project_3D_to_2D_triple(x, y, z, Pxhat, Pyhat, Pzhat)
    print '%11.7f %11.7f' % (u, v)
\end{verbatim}

\end{frame}

%% ----------------------------------------------------------------
\begin{frame}[fragile]
\frametitle{Output of numerical and projection scripts}

\begin{verbatim}
[shell prompt]$ python lorenz.py | python projdown.py
 -2.5000000   7.5000000
 -2.0900000   7.4966667
 -1.6896747   7.4978738
 -1.2986981   7.5032685
 -0.9167410   7.5125327
 ...          ...
\end{verbatim}
Or:
\begin{verbatim}
[shell prompt]$ python lorenz.py > xyz.txt
[shell prompt]$ python projdown.py < xyz.txt > uv.txt
\end{verbatim}

Now one would like to see a picture!

\end{frame}

%% ----------------------------------------------------------------
\begin{frame}[fragile]
\frametitle{Plotter script}

The \texttt{pylab} module intentionally mimics Matlab.  The basic piece to make
a plot is
\begin{verbatim}
import pylab
... compute the us and vs arrays as above ...
pylab.figure()
pylab.plot(us, vs)
pylab.show()
\end{verbatim}

Inside a computational script, you can simply call these subroutines.
Alternatively, we can create a separate, reusable script which can plot
\emph{any} two-column data file.  Here is my script \texttt{plot2.py}:

\begin{verbatim}
#!/usr/bin/python -Wall
import sys, tabutil, pylab
input_file_name = '-' # Read from standard input
if len(sys.argv) == 2: input_file_name = sys.argv[1] # Read from file
[us, vs] = tabutil.float_columns_from_file(input_file_name)
pylab.figure()
pylab.plot(us,vs)
pylab.show()
\end{verbatim}

\end{frame}

%% ----------------------------------------------------------------
\begin{frame}[fragile]
\frametitle{Output of plotter script}

Now we can pipe all three of our programs together:
\begin{verbatim}
python lorenz.py | python projdown.py | python plot2.py
\end{verbatim}

On the screen, we see the following:

\begin{center}
\includegraphics[scale=0.6]{figures/plot-screenshot.eps}
\end{center}

\end{frame}

%% ----------------------------------------------------------------
\begin{frame}[fragile]
\frametitle{Output of plotter script}

More plot options:

\begin{verbatim}
pylab.figure(1, figsize=(8, 3)) # Specify figure width/height in inches
pylab.plot(xs,ys,'ro-', markersize=8, label='legend label here')
   # 'ro-' means large red dots, with lines connecting the dots.
pylab.errorbar(xs, ys, y_errors)
pylab.bar(xs, ys, width=x[1]-x[0])
pylab.xlabel('Horizontal axis label'); pylab.ylabel('Vertical axis label')
pylab.title('Title text')
pylab.legend() # Make the above legend labels appear
if I_want_an_EPS_file:
    pylab.savefig('myfile.eps', dpi=150) # To disk
else:
    pylab.show()                         # To screen
\end{verbatim}

For more information, do the following:
\begin{verbatim}
[shell prompt]$ python
>>> import pylab
>>> help(pylab.plot)
\end{verbatim}

\end{frame}

%% ----------------------------------------------------------------
\begin{frame}[fragile]
\frametitle{Sample plot outputs}

I am using \texttt{pylab} exclusively for presentation graphics in my
dissertation.  Here are some examples of \texttt{pylab} plots, made using
options such as those on the previous slide:

\begin{center}
\includegraphics[scale=0.35]{pgr-figures/histo.eps}
\quad
%\includegraphics[scale=0.35]{pgr-figures/bridge.eps}
\includegraphics[scale=0.35]{pgr-figures/etadot.eps}

\includegraphics[scale=0.35]{pgr-figures/eta.eps}
\quad
\includegraphics[scale=0.35]{pgr-figures/fs.eps}

\end{center}

\end{frame}

%% ----------------------------------------------------------------
\begin{frame}[fragile]
\frametitle{Downloading the sample scripts}

Code used in this presentation is available in the directory

\texttt{http://math.arizona.edu/{\textasciitilde}kerl/doc/python-talk/}

These include:

\begin{verbatim}
hello.py
lorenz.py
plot2.py
projdown.py
tabutil.py
\end{verbatim}

Also, \texttt{all-in-one.py} skips the file I/O and the pipes: it does the
numerical integration, projection from 3D down to 2D, and the plotting all in
one script.

\end{frame}

%% ----------------------------------------------------------------
\begin{frame}
\frametitle{Modules and references}

There are a bajillion modules out there.  In particular, you might web-search
for \texttt{Scipy} and \texttt{Numpy}.  These include numerical linear algebra
(e.g.  LAPACK/BLAS), database interfaces, etc. etc.

For more information:

\begin{itemize}

\item
\emph{Learning Python}, by Mark Lutz, published by O'Reilly.

\item
\texttt{www.python.org}

\item
\texttt{docs.python.org/tutorial}

\item \begin{tiny}\texttt{http://www.aero.iitb.ac.in/{\textasciitilde}prabhu/tmp/python\_cep07/course\_handouts/science.pdf}\end{tiny}  (Whew!)

\end{itemize}

\end{frame}

%% ----------------------------------------------------------------
\begin{frame}

\begin{center}
{\emcol Thanks for attending!}
\end{center}

\end{frame}

%%% ================================================================

\end{document}
