<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">\documentclass[12pt]{article}
\usepackage{amsmath}
\title{Python Workshop\\Problems and Exercises}
\author{Asokan Pichai\\Prabhu Ramachandran}
\begin{document}
\maketitle

\section{Matrices and Arrays \&amp; 2D Plotting}
\subsection{Matrices and Arrays}
\subsubsection{Basic Numpy}
\begin{verbatim}
# Simple array math example
&gt;&gt;&gt; import numpy as np
&gt;&gt;&gt; a = np.array([1,2,3,4])
&gt;&gt;&gt; b = np.arange(2,6)
&gt;&gt;&gt; b
array([2,3,4,5])
&gt;&gt;&gt; a*2 + b + 1 # Basic math!
array([5, 8, 11, 14])

# Pi and e are defined.
&gt;&gt;&gt; x = np.linspace(0.0, 10.0, 1000)
&gt;&gt;&gt; x *= 2*np.pi/10 # inplace.
# apply functions to array.
&gt;&gt;&gt; y = np.sin(x)
&gt;&gt;&gt; z = np.exp(y)

&gt;&gt;&gt; x = np.array([1., 2, 3, 4])
&gt;&gt;&gt; np.size(x)
4
&gt;&gt;&gt; x.dtype # What is a.dtype?
dtype('float64')
&gt;&gt;&gt; x.shape
(4,)
&gt;&gt;&gt; print np.rank(x), x.itemsize
1 8
&gt;&gt;&gt; x[0] = 10
&gt;&gt;&gt; print x[0], x[-1]
10.0 4.0

&gt;&gt;&gt; a = np.array([[ 0, 1, 2, 3],
...            [10,11,12,13]])
&gt;&gt;&gt; a.shape # (rows, columns)
(2, 4)
# Accessing and setting values
&gt;&gt;&gt; a[1,3] 
13
&gt;&gt;&gt; a[1,3] = -1
&gt;&gt;&gt; a[1] # The second row
array([10,11,12,-1])

&gt;&gt;&gt; b=np.array([[0,2,4,2],[1,2,3,4]])
&gt;&gt;&gt; np.add(a,b,a)
&gt;&gt;&gt; np.sum(x,axis=1)

&gt;&gt;&gt; np.greater(a,4)
&gt;&gt;&gt; np.sqrt(a)
\end{verbatim}

\subsubsection{Array Creation}
\begin{verbatim}
&gt;&gt;&gt; np.array([2,3,4])  
array([2, 3, 4])

&gt;&gt;&gt; np.linspace(0, 2, 4)   
array([0.,0.6666667,1.3333333,2.])

&gt;&gt;&gt;np.ones([2,2])
array([[ 1.,  1.],
     [ 1.,  1.]])

&gt;&gt;&gt;a = np.array([[1,2,3],[4,5,6]])
&gt;&gt;&gt;np.ones_like(a)
array([[1, 1, 1],
       [1, 1, 1]])
\end{verbatim}
\subsubsection{Slicing, Striding Arrays}
\begin{verbatim}
&gt;&gt;&gt; a = np.array([[1,2,3], [4,5,6], 
               [7,8,9]])
&gt;&gt;&gt; a[0,1:3]
array([2, 3])
&gt;&gt;&gt; a[1:,1:]
array([[5, 6],
       [8, 9]])
&gt;&gt;&gt; a[:,2]
array([3, 6, 9])
&gt;&gt;&gt; a[...,2]
array([3, 6, 9])

&gt;&gt;&gt; a[0::2,0::2]
array([[1, 3],
       [7, 9]])
# Slices are references to the 
# same memory!
\end{verbatim}
\subsubsection{Random Numbers}
\begin{verbatim}
&gt;&gt;&gt; np.random.rand(3,2)
array([[ 0.96276665,  0.77174861],
       [ 0.35138557,  0.61462271],
       [ 0.16789255,  0.43848811]])
&gt;&gt;&gt; np.random.randint(1,100)
42
\end{verbatim}

\subsubsection{Problem Set}
\begin{verbatim}
    &gt;&gt;&gt; from scipy import misc
    &gt;&gt;&gt; A=misc.imread(name)
    &gt;&gt;&gt; misc.imshow(A)
\end{verbatim}
\begin{enumerate}
  \item Convert an RGB image to Grayscale. $ Y = 0.5R + 0.25G + 0.25B $.
  \item Scale the image to 50\%.
  \item Introduce some random noise.
  \item Smooth the image using a mean filter.
  \\\small{Each element in the array is replaced by mean of all the neighbouring elements}
  \\\small{How fast does your code run?}
\end{enumerate}

\subsection{2D Plotting}
\subsubsection{Basic 2D Plotting}
\begin{verbatim}
$ ipython -pylab
&gt;&gt;&gt; x = linspace(0, 2*pi, 1000)
&gt;&gt;&gt; plot(x, sin(x)) 
&gt;&gt;&gt; plot(x, sin(x), 'ro')
&gt;&gt;&gt; xlabel(r'$\chi$', color='g')
# LaTeX markup!
&gt;&gt;&gt; ylabel(r'sin($\chi$)', color='r')
&gt;&gt;&gt; title('Simple figure', fontsize=20)
&gt;&gt;&gt; savefig('/tmp/test.eps')
\end{verbatim}
\subsubsection{Tweaking plots}
\begin{verbatim}
# Set properties of objects:
&gt;&gt;&gt; l, = plot(x, sin(x))
# Why "l,"?
&gt;&gt;&gt; setp(l, linewidth=2.0, color='r')
&gt;&gt;&gt; l.set_linewidth(2.0)
&gt;&gt;&gt; draw() # Redraw.
&gt;&gt;&gt; setp(l) # Print properties.
&gt;&gt;&gt; clf() # Clear figure.
&gt;&gt;&gt; close() # Close figure.
\end{verbatim}

\subsubsection{Working with text}
\begin{verbatim}
&gt;&gt;&gt; w = arange(-2,2,.1)
&gt;&gt;&gt; plot(w,exp(-(w*w))*cos)
&gt;&gt;&gt; ylabel('$f(\omega)$')
&gt;&gt;&gt; xlabel('$\omega$')
&gt;&gt;&gt; title(r"$f(\omega)=e^{-\omega^2}
            cos({\omega^2})$")
&gt;&gt;&gt; annotate('maxima',xy=(0, 1), 
             xytext=(1, 0.8), 
             arrowprops=dict(
             facecolor='black', 
             shrink=0.05))
\end{verbatim}

\subsubsection{Legends}
\begin{verbatim}
&gt;&gt;&gt; x = linspace(0, 2*np.pi, 1000)
&gt;&gt;&gt; plot(x, cos(5*x), 'r--', 
         label='cosine')
&gt;&gt;&gt; plot(x, sin(5*x), 'g--', 
         label='sine')
&gt;&gt;&gt; legend() 
# Or use:
&gt;&gt;&gt; legend(['cosine', 'sine'])
\end{verbatim}

\subsubsection{Multiple figures}
\begin{verbatim}
&gt;&gt;&gt; figure(1)
&gt;&gt;&gt; plot(x, sin(x))
&gt;&gt;&gt; figure(2)
&gt;&gt;&gt; plot(x, tanh(x))
&gt;&gt;&gt; figure(1)
&gt;&gt;&gt; title('Easy as 1,2,3')

\end{verbatim}

\subsubsection{Problem Set}
  \begin{enumerate}
    \item Write a function that plots any regular n-gon given n.
    \item Consider the logistic map, $f(x) = kx(1-x)$, plot it for
          $k=2.5, 3.5$ and $4$ in the same plot.

  \item Consider the iteration $x_{n+1} = f(x_n)$ where $f(x) =
        kx(1-x)$.  Plot the successive iterates of this process.
  \item Plot this using a cobweb plot as follows:
  \begin{enumerate}
    \item Start at $(x_0, 0)$
    \item Draw line to $(x_i, f(x_i))$; 
    \item Set $x_{i+1} = f(x_i)$
    \item Draw line to $(x_i, x_i)$
    \item Repeat from 2 for as long as you want 
  \end{enumerate}
\end{enumerate}

\section{Advanced Numpy}

\subsection{Broadcasting}
\begin{verbatim}
&gt;&gt;&gt; a = np.arange(4)
&gt;&gt;&gt; b = np.arange(5)
&gt;&gt;&gt; a+b #Does this work?
&gt;&gt;&gt; a+3
&gt;&gt;&gt; c=np.array([3])
&gt;&gt;&gt; a+c #Works!
&gt;&gt;&gt; b+c #But how?
&gt;&gt;&gt; a.shape, b.shape, c.shape

&gt;&gt;&gt; a = np.arange(4)
&gt;&gt;&gt; a+3
array([3, 4, 5, 6])

&gt;&gt;&gt; x = np.ones((3, 5))
&gt;&gt;&gt; y = np.ones(8)
&gt;&gt;&gt; (x[..., None] + y).shape
(3, 5, 8)

\end{verbatim}

\subsection{Copies \&amp; Views}
\begin{verbatim}
&gt;&gt;&gt; a = np.array([[1,2,3],[4,5,6]])
&gt;&gt;&gt; b = a
&gt;&gt;&gt; b is a
&gt;&gt;&gt; b[0,0]=0; print a
&gt;&gt;&gt; c = a.view()
&gt;&gt;&gt; c is a
&gt;&gt;&gt; c.base is a
&gt;&gt;&gt; c.flags.owndata
&gt;&gt;&gt; d = a.copy()
&gt;&gt;&gt; d.base is a
&gt;&gt;&gt; d.flags.owndata

&gt;&gt;&gt; a = np.arange(1,9)
&gt;&gt;&gt; a.shape=3,3
&gt;&gt;&gt; b = a[0,1:3]
&gt;&gt;&gt; c = a[0::2,0::2]
&gt;&gt;&gt; a.flags.owndata
&gt;&gt;&gt; b.flags.owndata
&gt;&gt;&gt; b.base
&gt;&gt;&gt; c.base is a

&gt;&gt;&gt; b = a[np.array([0,1,2])]
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
&gt;&gt;&gt; b.flags.owndata
&gt;&gt;&gt; abool=np.greater(a,2)
&gt;&gt;&gt; c = a[abool]
&gt;&gt;&gt; c.flags.owndata

\end{verbatim}

\section{Scipy}
\subsection{Linear Algebra}
\begin{verbatim}
&gt;&gt;&gt; import scipy as sp
&gt;&gt;&gt; from scipy import linalg
&gt;&gt;&gt; A=sp.mat(np.arange(1,10))
&gt;&gt;&gt; A.shape=3,3
&gt;&gt;&gt; linalg.inv(A)
&gt;&gt;&gt; linalg.det(A)
&gt;&gt;&gt; linalg.norm(A)
&gt;&gt;&gt; linalg.expm(A) #logm
&gt;&gt;&gt; linalg.sinm(A) #cosm, tanm, ...

&gt;&gt;&gt; A = sp.mat(np.arange(1,10))
&gt;&gt;&gt; A.shape=3,3
&gt;&gt;&gt; linalg.lu(A)
&gt;&gt;&gt; linalg.eig(A)
&gt;&gt;&gt; linalg.eigvals(A)
\end{verbatim}

\subsection{Solving Linear Equations}

\begin{align*}
  3x + 2y - z  &amp; = 1 \\
  2x - 2y + 4z  &amp; = -2 \\
  -x + \frac{1}{2}y -z &amp; = 0
\end{align*}
To Solve this, 
\begin{verbatim}
&gt;&gt;&gt; A = sp.mat([[3,2,-1],[2,-2,4]
              ,[-1,1/2,-1]])
&gt;&gt;&gt; B = sp.mat([[1],[-2],[0]])
&gt;&gt;&gt; linalg.solve(A,B)
\end{verbatim}

\subsection{Integrate}
\subsubsection{Quadrature}
Calculate the area under $(sin(x) + x^2)$ in the range $(0,1)$
\begin{verbatim}
&gt;&gt;&gt; def f(x):
        return np.sin(x)+x**2
&gt;&gt;&gt; integrate.quad(f, 0, 1)
\end{verbatim}

\subsubsection{ODE Integration}
Numerically solve ODEs\\
\begin{align*}
\frac{dx}{dt} &amp;=-e^{-t}x^2\\ 
         x(0) &amp;=2    
\end{align*}
\begin{verbatim}
&gt;&gt;&gt; def dx_dt(x,t):
...     return -np.exp(-t)*x**2
&gt;&gt;&gt; x=integrate.odeint(dx_dt, 2, t)
&gt;&gt;&gt; plt.plot(x,t)
\end{verbatim}

\subsection{Interpolation}
\subsubsection{1D Interpolation}
\begin{verbatim}
&gt;&gt;&gt; from scipy import interpolate
&gt;&gt;&gt; interpolate.interp1d?
&gt;&gt;&gt; x = np.arange(0,2*np.pi,np.pi/4)
&gt;&gt;&gt; y = np.sin(x)
&gt;&gt;&gt; fl = interpolate.interp1d(
            x,y,kind='linear')
&gt;&gt;&gt; fc = interpolate.interp1d(
             x,y,kind='cubic')
&gt;&gt;&gt; fl(np.pi/3)
&gt;&gt;&gt; fc(np.pi/3)
\end{verbatim}

\subsubsection{Splines}
Plot the Cubic Spline of $sin(x)$
\begin{verbatim}
&gt;&gt;&gt; x = np.arange(0,2*np.pi,np.pi/4)
&gt;&gt;&gt; y = np.sin(x)
&gt;&gt;&gt; tck = interpolate.splrep(x,y)
&gt;&gt;&gt; X = np.arange(0,2*np.pi,np.pi/50)
&gt;&gt;&gt; Y = interpolate.splev(X,tck,der=0)
&gt;&gt;&gt; plt.plot(x,y,'o',x,y,X,Y)
&gt;&gt;&gt; plt.show()
\end{verbatim}

\subsection{Signal \&amp; Image Processing}
Applying a simple median filter
\begin{verbatim}
&gt;&gt;&gt; from scipy import signal, ndimage
&gt;&gt;&gt; from scipy import lena
&gt;&gt;&gt; A=lena().astype('float32')
&gt;&gt;&gt; B=signal.medfilt2d(A)
&gt;&gt;&gt; imshow(B)
\end{verbatim}
Zooming an array - uses spline interpolation
\begin{verbatim}
&gt;&gt;&gt; b=ndimage.zoom(A,0.5)
&gt;&gt;&gt; imshow(b)
\end{verbatim}

\section{3D Data Visualization}
\subsection{Using mlab}
\begin{verbatim}
&gt;&gt;&gt; from enthought.mayavi import mlab

&gt;&gt;&gt; mlab.test_&lt;TAB&gt;
&gt;&gt;&gt; mlab.test_contour3d()
&gt;&gt;&gt; mlab.test_contour3d??
\end{verbatim}

\subsubsection{Plotting Functions}
\begin{verbatim}
&gt;&gt;&gt; from numpy import *
&gt;&gt;&gt; t = linspace(0, 2*pi, 50)
&gt;&gt;&gt; u = cos(t)*pi
&gt;&gt;&gt; x, y, z = sin(u), cos(u), sin(t)

&gt;&gt;&gt; x = mgrid[-3:3:100j,-3:3:100j]
&gt;&gt;&gt; z = sin(x*x + y*y)
&gt;&gt;&gt; mlab.surf(x, y, z)
\end{verbatim}

\subsubsection{Large 2D Data}
\begin{verbatim}
&gt;&gt;&gt; mlab.mesh(x, y, z)

&gt;&gt;&gt; phi, theta = numpy.mgrid[0:pi:20j, 
...                         0:2*pi:20j]
&gt;&gt;&gt; x = sin(phi)*cos(theta)
&gt;&gt;&gt; y = sin(phi)*sin(theta)
&gt;&gt;&gt; z = cos(phi)
&gt;&gt;&gt; mlab.mesh(x, y, z, 
...           representation=
...           'wireframe')
\end{verbatim}

\subsubsection{Large 3D Data}
\begin{verbatim}
&gt;&gt;&gt; x, y, z = ogrid[-5:5:64j, 
...                -5:5:64j, 
...                -5:5:64j]
&gt;&gt;&gt; mlab.contour3d(x*x*0.5 + y*y + 
                   z*z*2)

&gt;&gt;&gt; mlab.test_quiver3d()
\end{verbatim}

\subsection{Motivational Problem}
Atmospheric data of temperature over the surface of the earth. Let temperature ($T$) vary linearly with height ($z$)\\
$T = 288.15 - 6.5z$

\begin{verbatim}
lat = linspace(-89, 89, 37)
lon = linspace(0, 360, 37)
z = linspace(0, 100, 11)
\end{verbatim}

\begin{verbatim}
x, y, z = mgrid[0:360:37j,-89:89:37j,
                0:100:11j]
t = 288.15 - 6.5*z
mlab.contour3d(x, y, z, t)
mlab.outline()
mlab.colorbar()
\end{verbatim}

\subsection{Lorenz equation}
\begin{eqnarray*}
\frac{d x}{dt} &amp;=&amp; s (y-x)\\
\frac{d y}{d t} &amp;=&amp; rx -y -xz\\
\frac{d z}{d t} &amp;=&amp; xy - bz\\
\end{eqnarray*}

Let $s=10,$
$r=28,$ 
$b=8./3.$

\begin{verbatim}
x, y, z = mgrid[-50:50:20j,-50:50:20j,
                -10:60:20j]

\end{verbatim}

\end{document}
</pre></body></html>