diff options
author | hardythe1 | 2014-06-12 14:44:39 +0530 |
---|---|---|
committer | hardythe1 | 2014-06-12 14:44:39 +0530 |
commit | f4ff073c0e144546d7c205f6c99df6baed763b04 (patch) | |
tree | 3c6163a3d3aa22362ab9009ece2019e60fc267a6 /slides/advanced_python | |
parent | 2a0aa076b9879a71dba6235ef84efa9cd15fda80 (diff) | |
download | sees-f4ff073c0e144546d7c205f6c99df6baed763b04.tar.gz sees-f4ff073c0e144546d7c205f6c99df6baed763b04.tar.bz2 sees-f4ff073c0e144546d7c205f6c99df6baed763b04.zip |
restructuring and renaming files/directories with underscores instead of spaces & '-'
Diffstat (limited to 'slides/advanced_python')
-rw-r--r-- | slides/advanced_python/advanced_py.tex | 53 | ||||
-rw-r--r-- | slides/advanced_python/more_py.tex | 51 | ||||
-rw-r--r-- | slides/advanced_python/slides/arrays.tex | 341 | ||||
-rw-r--r-- | slides/advanced_python/slides/lambda.tex | 189 | ||||
-rw-r--r-- | slides/advanced_python/slides/modules.tex | 163 | ||||
-rw-r--r-- | slides/advanced_python/slides/oop.tex | 226 | ||||
-rw-r--r-- | slides/advanced_python/slides/plotting.tex | 450 | ||||
-rw-r--r-- | slides/advanced_python/slides/scipy.tex | 273 | ||||
-rw-r--r-- | slides/advanced_python/slides/tmp.tex | 316 |
9 files changed, 2062 insertions, 0 deletions
diff --git a/slides/advanced_python/advanced_py.tex b/slides/advanced_python/advanced_py.tex new file mode 100644 index 0000000..b15419e --- /dev/null +++ b/slides/advanced_python/advanced_py.tex @@ -0,0 +1,53 @@ +\documentclass[12pt,presentation]{beamer} +\usepackage[utf8]{inputenc} +\usepackage[T1]{fontenc} +\usepackage{fixltx2e} +\usepackage{graphicx} +\usepackage{longtable} +\usepackage{float} +\usepackage{wrapfig} +\usepackage{soul} +\usepackage{textcomp} +\usepackage{marvosym} +\usepackage{wasysym} +\usepackage{latexsym} +\usepackage{amssymb} +\usepackage{hyperref} +\tolerance=1000 +\usepackage[english]{babel} \usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} +\usepackage{listings} +\lstset{language=Python, basicstyle=\ttfamily\bfseries, +commentstyle=\color{red}\itshape, stringstyle=\color{green}, +showstringspaces=false, keywordstyle=\color{blue}\bfseries} +\providecommand{\alert}[1]{\textbf{#1}} + +\title{Advanced Python} +\author{FOSSEE} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} + +\AtBeginSection[] +{ + \begin{frame}<beamer> + \frametitle{Outline} + \tableofcontents[currentsection] + \end{frame} +} + +\begin{document} + +\maketitle + +\begin{frame} +\frametitle{Outline} +\setcounter{tocdepth}{3} +\tableofcontents +\end{frame} + +\include{slides/plotting} +\include{slides/arrays} +\include{slides/scipy} +\include{slides/modules} + +\end{document} diff --git a/slides/advanced_python/more_py.tex b/slides/advanced_python/more_py.tex new file mode 100644 index 0000000..8b50ec4 --- /dev/null +++ b/slides/advanced_python/more_py.tex @@ -0,0 +1,51 @@ +\documentclass[12pt,presentation]{beamer} +\usepackage[utf8]{inputenc} +\usepackage[T1]{fontenc} +\usepackage{fixltx2e} +\usepackage{graphicx} +\usepackage{longtable} +\usepackage{float} +\usepackage{wrapfig} +\usepackage{soul} +\usepackage{textcomp} +\usepackage{marvosym} +\usepackage{wasysym} +\usepackage{latexsym} +\usepackage{amssymb} +\usepackage{hyperref} +\tolerance=1000 +\usepackage[english]{babel} \usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} +\usepackage{listings} +\lstset{language=Python, basicstyle=\ttfamily\bfseries, +commentstyle=\color{red}\itshape, stringstyle=\color{green}, +showstringspaces=false, keywordstyle=\color{blue}\bfseries} +\providecommand{\alert}[1]{\textbf{#1}} + +\title{SEES: Advanced Python(2)} +\author{FOSSEE} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} + +\AtBeginSection[] +{ + \begin{frame}<beamer> + \frametitle{Outline} + \tableofcontents[currentsection] + \end{frame} +} + +\begin{document} + +\maketitle + +\begin{frame} +\frametitle{Outline} +\setcounter{tocdepth}{3} +\tableofcontents +\end{frame} + +\include{slides/lambda} +\include{slides/oop} + +\end{document} diff --git a/slides/advanced_python/slides/arrays.tex b/slides/advanced_python/slides/arrays.tex new file mode 100644 index 0000000..e4501c8 --- /dev/null +++ b/slides/advanced_python/slides/arrays.tex @@ -0,0 +1,341 @@ +\section{Arrays} + +\begin{frame}[fragile] + \frametitle{Arrays: Introduction} + \begin{itemize} + \item Similar to lists, but homogeneous + \item Much faster than arrays + \end{itemize} + \begin{lstlisting} + In[]: a1 = array([1,2,3,4]) + In[]: a1 # 1-D + In[]: a2 = array([[1,2,3,4],[5,6,7,8]]) + In[]: a2 # 2-D + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\texttt{arange} and \texttt{shape}} + \begin{lstlisting} + In[]: ar1 = arange(1, 5) + In[]: ar2 = arange(1, 9) + In[]: print ar2 + In[]: ar2.shape = 2, 4 + In[]: print ar2 + \end{lstlisting} + \begin{itemize} + \item \texttt{linspace} and \texttt{loadtxt} also returned arrays + \end{itemize} + \begin{lstlisting} + In[]: ar1.shape + In[]: ar2.shape + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Special methods} + \begin{lstlisting} + In[]: identity(3) + \end{lstlisting} + \begin{itemize} + \item array of shape (3, 3) with diagonals as 1s, rest 0s + \end{itemize} + \begin{lstlisting} + In[]: zeros((4,5)) + \end{lstlisting} + \begin{itemize} + \item array of shape (4, 5) with all 0s + \end{itemize} + \begin{lstlisting} + In[]: a = zeros_like([1.5, 1, 2, 3]) + In[]: print a, a.dtype + \end{lstlisting} + \begin{itemize} + \item An array with all 0s, with similar shape and dtype as argument + \item Homogeneity makes the dtype of a to be float + \item \texttt{ones, ones\_like, empty, empty\_like} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Operations on arrays} + \begin{lstlisting} + In[]: a1 + In[]: a1 * 2 + In[]: a1 + \end{lstlisting} + \begin{itemize} + \item The array is not changed; New array is returned + \end{itemize} + \begin{lstlisting} + In[]: a1 + 3 + In[]: a1 - 7 + In[]: a1 / 2.0 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Operations on arrays \ldots} + \begin{itemize} + \item Like lists, we can assign the new array, the old name + \end{itemize} + \begin{lstlisting} + In[]: a1 = a1 + 2 + In[]: a1 + \end{lstlisting} + \begin{itemize} + \item \alert{Beware of Augmented assignment!} + \end{itemize} + \begin{lstlisting} + In[]: a, b = arange(1, 5), arange(1, 5) + In[]: print a, a.dtype, b, b.dtype + In[]: a = a/2.0 + In[]: b /= 2.0 + In[]: print a, a.dtype, b, b.dtype + \end{lstlisting} + \begin{itemize} + \item Operations on two arrays; element-wise + \end{itemize} + \begin{lstlisting} + In[]: a1 + a1 + In[]: a1 * a2 + \end{lstlisting} +\end{frame} + +\section{Accessing pieces of arrays} + +\begin{frame}[fragile] + \frametitle{Accessing \& changing elements} + \begin{lstlisting} + In[]: A = array([12, 23, 34, 45, 56]) + + In[]: C = array([[11, 12, 13, 14, 15], + [21, 22, 23, 24, 25], + [31, 32, 33, 34, 35], + [41, 42, 43, 44, 45], + [51, 52, 53, 54, 55]]) + + In[]: A[2] + In[]: C[2, 3] + \end{lstlisting} + \begin{itemize} + \item Indexing starts from 0 + \item Assign new values, to change elements + \end{itemize} + \begin{lstlisting} + In[]: A[2] = -34 + In[]: C[2, 3] = -34 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Accessing rows} + \begin{itemize} + \item Indexing works just like with lists + \end{itemize} + \begin{lstlisting} + In[]: C[2] + In[]: C[4] + In[]: C[-1] + \end{lstlisting} + \begin{itemize} + \item Change the last row into all zeros + \end{itemize} + \begin{lstlisting} + In[]: C[-1] = [0, 0, 0, 0, 0] + \end{lstlisting} + OR + \begin{lstlisting} + In[]: C[-1] = 0 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Accessing columns} + \begin{lstlisting} + In[]: C[:, 2] + In[]: C[:, 4] + In[]: C[:, -1] + \end{lstlisting} + \begin{itemize} + \item The first parameter is replaced by a \texttt{:} to specify we + require all elements of that dimension + \end{itemize} + \begin{lstlisting} + In[]: C[:, -1] = 0 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Slicing} + \begin{lstlisting} + In[]: I = imread('squares.png') + In[]: imshow(I) + \end{lstlisting} + \begin{itemize} + \item The image is just an array + \end{itemize} + \begin{lstlisting} + In[]: print I, I.shape + \end{lstlisting} + \begin{enumerate} + \item Get the top left quadrant of the image + \item Obtain the square in the center of the image + \end{enumerate} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Slicing \ldots} + \begin{itemize} + \item Slicing works just like with lists + \end{itemize} + \begin{lstlisting} + In[]: C[0:3, 2] + In[]: C[2, 0:3] + In[]: C[2, :3] + \end{lstlisting} + \begin{lstlisting} + In[]: imshow(I[:150, :150]) + + In[]: imshow(I[75:225, 75:225]) + \end{lstlisting} +\end{frame} + +\begin{frame} +\frametitle{Image after slicing} +\includegraphics[scale=0.45]{../advanced_python/images/slice.png}\\ +\end{frame} + + + +\begin{frame}[fragile] + \frametitle{Striding} + \begin{itemize} + \item Compress the image to a fourth, by dropping alternate rows and + columns + \item We shall use striding + \item The idea is similar to striding in lists + \end{itemize} + \begin{lstlisting} + In[]: C[0:5:2, 0:5:2] + In[]: C[::2, ::2] + In[]: C[1::2, ::2] + \end{lstlisting} + \begin{itemize} + \item Now, the image can be shrunk by + \end{itemize} + \begin{lstlisting} + In[]: imshow(I[::2, ::2]) + \end{lstlisting} +\end{frame} + +\section{Matrix Operations} + +\begin{frame}[fragile] + \frametitle{Matrix Operations using \texttt{arrays}} + We can perform various matrix operations on \texttt{arrays}\\ + A few are listed below. + + \begin{center} + \begin{tabular}{lll} + Operation & How? & Example \\ + \hline + Transpose & \texttt{.T} & \texttt{A.T} \\ + Product & \texttt{dot} & \texttt{dot(A, B)} \\ + Inverse & \texttt{inv} & \texttt{inv(A)} \\ + Determinant & \texttt{det} & \texttt{det(A)} \\ + Sum of all elements & \texttt{sum} & \texttt{sum(A)} \\ + Eigenvalues & \texttt{eigvals} & \texttt{eigvals(A)} \\ + Eigenvalues \& Eigenvectors & \texttt{eig} & \texttt{eig(A)} \\ + Norms & \texttt{norm} & \texttt{norm(A)} \\ + SVD & \texttt{svd} & \texttt{svd(A)} \\ + \end{tabular} + \end{center} +\end{frame} + +\section{Least square fit} + +\begin{frame}[fragile] + \frametitle{Least Square Fit} + \begin{lstlisting} + In[]: L, t = loadtxt("pendulum.txt", + unpack=True) + In[]: L + In[]: t + In[]: tsq = t * t + In[]: plot(L, tsq, 'bo') + In[]: plot(L, tsq, 'r') + \end{lstlisting} + \begin{itemize} + \item Both the plots, aren't what we expect -- linear plot + \item Enter Least square fit! + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Matrix Formulation} + \begin{itemize} + \item We need to fit a line through points for the equation $T^2 = m \cdot L+c$ + \item In matrix form, the equation can be represented as $T_{sq} = A \cdot p$, where $T_{sq}$ is + $\begin{bmatrix} + T^2_1 \\ + T^2_2 \\ + \vdots\\ + T^2_N \\ + \end{bmatrix}$ + , A is + $\begin{bmatrix} + L_1 & 1 \\ + L_2 & 1 \\ + \vdots & \vdots\\ + L_N & 1 \\ + \end{bmatrix}$ + and p is + $\begin{bmatrix} + m\\ + c\\ + \end{bmatrix}$ + \item We need to find $p$ to plot the line + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Least Square Fit Line} + \begin{lstlisting} + In[]: A = array((L, ones_like(L))) + In[]: A.T + In[]: A + \end{lstlisting} + \begin{itemize} + \item We now have \texttt{A} and \texttt{tsq} + \end{itemize} + \begin{lstlisting} + In[]: result = lstsq(A, tsq) + \end{lstlisting} + \begin{itemize} + \item Result has a lot of values along with m and c, that we need + \end{itemize} + \begin{lstlisting} + In[]: m, c = result[0] + In[]: print m, c + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Least Square Fit Line} + \begin{itemize} + \item Now that we have m and c, we use them to generate line and plot + \end{itemize} + \begin{lstlisting} + In[]: tsq_fit = m * L + c + In[]: plot(L, tsq, 'bo') + In[]: plot(L, tsq_fit, 'r') + \end{lstlisting} +\end{frame} + +\begin{frame} +\frametitle{Least Square Fit Line} +\includegraphics[scale=0.45]{../advanced_python/images/lst-sq-fit.png}\\ +\end{frame} + + diff --git a/slides/advanced_python/slides/lambda.tex b/slides/advanced_python/slides/lambda.tex new file mode 100644 index 0000000..25c4f97 --- /dev/null +++ b/slides/advanced_python/slides/lambda.tex @@ -0,0 +1,189 @@ +\section{Functional programming} + +\begin{frame}[fragile] + \frametitle{List Comprehensions} + \begin{itemize} + \item A different style of Programming + \item Functions `emulate' mathematical functions + \item Output depends only on input arguments + \item There is no `state' associated with the program + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{List Comprehensions} + \begin{block}{} + Given a list of weights of people, and we need to + calculate the corresponding weights on the moon. Return a new + list, with each of the values divided by 6.0. + \end{block} + + \begin{itemize} + \item Solution using \texttt{for} loop is shown + \end{itemize} + \begin{lstlisting} + weights = [30, 45.5, 78, 81, 55.5, 62.5] + weights_moon = [] + for w in weights: + weights_moon.append(w/6.0) + print weights_moon + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{List Comprehensions \ldots} + \begin{itemize} + \item List comprehensions are compact and readable + \end{itemize} + \begin{lstlisting} + [ w/6.0 for w in weights ] + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{List Comprehensions \ldots} + \begin{itemize} + \item Return the weight on moon, only if weight on earth > 50 + \end{itemize} + \begin{lstlisting} + weights = [30, 45.5, 78, 81, 55.5, 62.5] + weights_moon = [] + for w in weights: + if w > 50: + weights_moon.append(w/6.0) + + print weights_moon + \end{lstlisting} + \begin{itemize} + \item List comprehension that checks for a condition + \end{itemize} + \begin{lstlisting} + [ w/6.0 for w in weights if w>50 ] + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{List Comprehensions \ldots} + \begin{itemize} + \item if weight > 50, return weight/6.0 + \item else, return weight*3.0 + \end{itemize} + \begin{lstlisting} + weights = [30, 45.5, 78, 81, 55.5, 62.5] + weights_migrate = [] + for w in weights: + if w > 50: + weights_migrate.append(w/6.0) + else: + weights_migrate.append(w * 3.0) + + print weights_migrate + \end{lstlisting} + \begin{itemize} + \item This problem \alert{CANNOT} be solved using list + comprehensions + \item Try \texttt{map} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\texttt{map}} + \begin{itemize} + \item Takes a function and a sequence as arguments + \item Calls function with each element of sequence as argument + \item Returns a sequence with all the results as elements + \item We solve the easier problem first, using \texttt{map} + \end{itemize} + + \begin{lstlisting} + def moonize(weight): + return weight/6.0 + + map(moonize, weights) + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\texttt{map} \ldots} + \begin{lstlisting} + def migrate(weight): + if weight < 50: + return weight*3.0 + else: + return weight/6.0 + \end{lstlisting} + + \begin{itemize} + \item \texttt{migrate} compares weight with 50 and returns the + required value. + \item We can now use \texttt{map} + \end{itemize} + \begin{lstlisting} + map(migrate, weights) + \end{lstlisting} + \begin{itemize} + \item Now, we wish to get away with the function definition + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\texttt{lambda}} + \begin{itemize} + \item Allows function definition, anonymously + \end{itemize} + \begin{lstlisting} + map(lambda x: x/6.0, weights) + \end{lstlisting} + \begin{itemize} + \item \texttt{lambda} actually returns a function which we could in + fact assign to a name and use later. + \end{itemize} + \begin{lstlisting} + l_moonize = lambda x: x/6.0 + map(l_moonize, weights) + \end{lstlisting} + \begin{lstlisting} + l_migrate = lambda x: x*3.0 if x < 50 else x/6.0 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\texttt{filter}} + + \begin{itemize} + \item We avoided discussion of problem of returning new weights only + when actual weight is more than 50. + \item \texttt{filter} can be used to filter out ``bad'' weights + \item Later, we could use \texttt{map} + \end{itemize} + \begin{lstlisting} + filter(lambda x: x > 50, weights) + \end{lstlisting} + \begin{itemize} + \item Takes a function and a sequence + \item Returns a sequence, containing only those elements of the + original sequence, for which the function returned \texttt{True} + \end{itemize} + \begin{lstlisting} + map(lambda x: x/6.0, filter(lambda x: x > 50, weights)) + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\texttt{reduce}} + \begin{itemize} + \item ``reduces'' a sequence + \end{itemize} + \begin{lstlisting} + reduce(lambda x,y: x*y, [1, 2, 3, 4]) + \end{lstlisting} + \begin{itemize} + \item Takes function and sequence as arguments; the function should + take two arguments + \item Passes first two elements of sequence, and continues to move + over the sequence, passing the output in the previous step and the + current element as the arguments + \item The function above essentially calculates $((1*2)*3)*4$ + \end{itemize} +\end{frame} + diff --git a/slides/advanced_python/slides/modules.tex b/slides/advanced_python/slides/modules.tex new file mode 100644 index 0000000..d6de640 --- /dev/null +++ b/slides/advanced_python/slides/modules.tex @@ -0,0 +1,163 @@ +\section{Using Python modules} + +\begin{frame}[fragile] + \frametitle{\texttt{hello.py}} + \begin{itemize} + \item Script to print `hello world' -- \texttt{hello.py} + \end{itemize} + \begin{lstlisting} + print "Hello world!" + \end{lstlisting} + \begin{itemize} + \item We have been running scripts from IPython + \end{itemize} + \begin{lstlisting} + In[]: %run -i hello.py + \end{lstlisting} + \begin{itemize} + \item Now, we run from the shell using python + \end{itemize} + \begin{lstlisting} + $ python hello.py + \end{lstlisting} %$ +\end{frame} + +\begin{frame}[fragile] + \frametitle{Simple plot} + \begin{itemize} + \item Save the following in \texttt{sine\_plot.py} + \end{itemize} + \begin{lstlisting} + x = linspace(-2*pi, 2*pi, 100) + plot(x, sin(x)) + show() + \end{lstlisting} + \begin{itemize} + \item Now, let us run the script + \end{itemize} + \begin{lstlisting} + $ python sine_plot.py + \end{lstlisting} % $ + \begin{itemize} + \item What's wrong? + \end{itemize} +\end{frame} + + +\begin{frame}[fragile] + \frametitle{Importing} + \begin{itemize} + \item \texttt{-pylab} is importing a lot of functionality + \item Add the following to the top of your file + \end{itemize} + \begin{lstlisting} + from scipy import * + \end{lstlisting} + \begin{lstlisting} + $ python sine_plot.py + \end{lstlisting} % $ + \begin{itemize} + \item Now, plot is not found + \item Add the following as the second line of your script + \end{itemize} + \begin{lstlisting} + from pylab import * + \end{lstlisting} + \begin{lstlisting} + $ python sine_plot.py + \end{lstlisting} % $ + \begin{itemize} + \item It works! + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Importing \ldots} + \begin{itemize} + \item \texttt{*} imports everything from \texttt{scipy} and + \texttt{pylab} + \item But, It imports lot of unnecessary stuff + \item And two modules may contain the same name, causing a conflict + \item There are two ways out + \end{itemize} + \begin{lstlisting} + from scipy import linspace, pi, sin + from pylab import plot, show + \end{lstlisting} + \begin{itemize} + \item OR change the imports to following and + \item Replace \texttt{pi} with \texttt{scipy.pi}, etc. + \end{itemize} + \begin{lstlisting} + import scipy + import pylab + \end{lstlisting} +\end{frame} + +\section{Writing modules} + +\begin{frame}[fragile] + \frametitle{GCD script} + \begin{itemize} + \item Function that computes gcd of two numbers + \item Save it as \texttt{gcd\_script.py} + \end{itemize} + \begin{lstlisting} + def gcd(a, b): + while b: + a, b = b, a%b + return a + \end{lstlisting} + \begin{itemize} + \item Also add the tests to the file + \end{itemize} + \begin{lstlisting} + if gcd(40, 12) == 4 and gcd(12, 13) == 1: + print "Everything OK" + else: + print "The GCD function is wrong" + \end{lstlisting} + \begin{lstlisting} + $ python gcd_script.py + \end{lstlisting} % $ +\end{frame} + +\begin{frame}[fragile] + \frametitle{Python path} + \begin{itemize} + \item In IPython type the following + \end{itemize} + \begin{lstlisting} + import sys + sys.path + \end{lstlisting} + \begin{itemize} + \item List of locations where python searches for a module + \item \texttt{import sys} -- searches for file \texttt{sys.py} or + dir \texttt{sys} in all these locations + \item So, our own modules can be in any one of the locations + \item Current working directory is one of the locations + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\texttt{\_\_name\_\_}} + \begin{lstlisting} + import gcd_script + \end{lstlisting} + \begin{itemize} + \item The import is successful + \item But the test code, gets run + \item Add the tests to the following \texttt{if} block + \end{itemize} + \begin{lstlisting} + if __name__ == "__main__": + \end{lstlisting} + \begin{itemize} + \item Now the script runs properly + \item As well as the import works; test code not executed + \item \texttt{\_\_name\_\_} is local to every module and is equal + to \texttt{\_\_main\_\_} only when the file is run as a script. + \end{itemize} +\end{frame} + diff --git a/slides/advanced_python/slides/oop.tex b/slides/advanced_python/slides/oop.tex new file mode 100644 index 0000000..bdb983c --- /dev/null +++ b/slides/advanced_python/slides/oop.tex @@ -0,0 +1,226 @@ +\section{Object Oriented Programming} + +\begin{frame}[fragile] + \frametitle{Objectives} + At the end of this section, you will be able to - + \begin{itemize} + \item Understand the differences between Object Oriented Programming + and Procedural Programming + \item Appreciate the need for Object Oriented Programming + \item Read and understand Object Oriented Programs + \item Write simple Object Oriented Programs + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Example: Managing Talks} + \begin{itemize} + \item A list of talks at a conference + \item We want to manage the details of the talks + \end{itemize} + \begin{lstlisting} + talk = {'Speaker': 'Guido van Rossum', + 'Title': 'The History of Python' + 'Tags': 'python,history,C,advanced'} + + def get_first_name(talk): + return talk['Speaker'].split()[0] + + def get_tags(talk): + return talk['Tags'].split(',') + \end{lstlisting} + \begin{itemize} + \item Not convenient to handle large number of talks + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Objects and Methods} + \begin{itemize} + \item Objects group data with the procedures/functions + \item A single entity called \texttt{object} + \item Everything in Python is an object + \item Strings, Lists, Functions and even Modules + \end{itemize} + \begin{lstlisting} + s = "Hello World" + s.lower() + + l = [1, 2, 3, 4, 5] + l.append(6) + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Objects \ldots} + \begin{itemize} + \item Objects provide a consistent interface + \end{itemize} + \begin{lstlisting} + for element in (1, 2, 3): + print element + for key in {'one':1, 'two':2}: + print key + for char in "123": + print char + for line in open("myfile.txt"): + print line + for line in urllib2.urlopen('http://site.com'): + print line + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Classes} + \begin{itemize} + \item A new string, comes along with methods + \item A template or a blue-print, where these definitions lie + \item This blue print for building objects is called a + \texttt{class} + \item \texttt{s} is an object of the \texttt{str} class + \item An object is an ``instance'' of a class + \end{itemize} + \begin{lstlisting} + s = "Hello World" + type(s) + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Defining Classes} + \begin{itemize} + \item A class equivalent of the talk dictionary + \item Combines data and methods into a single entity + \end{itemize} + \begin{lstlisting} + class Talk: + """A class for the Talks.""" + + def __init__(self, speaker, title, tags): + self.speaker = speaker + self.title = title + self.tags = tags + + def get_speaker_firstname(self): + return self.speaker.split()[0] + + def get_tags(self): + return self.tags.split(',') + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\texttt{class} block} + \begin{itemize} + \item Defined just like a function block + \item \texttt{class} is a keyword + \item \texttt{Talk} is the name of the class + \item Classes also come with doc-strings + \item All the statements of within the class are inside the block + \end{itemize} + \begin{lstlisting} + class Talk: + """A class for the Talks.""" + + def __init__(self, speaker, title, tags): + self.speaker = speaker + self.title = title + self.tags = tags + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\texttt{self}} + \begin{itemize} + \item Every method has an additional first argument, \texttt{self} + \item \texttt{self} is a reference to the object itself, of which + the method is a part of + \item Variables of the class are referred to as \texttt{self.variablename} + \end{itemize} + \begin{lstlisting} + def get_speaker_firstname(self): + return self.speaker.split()[0] + + def get_tags(self): + return self.tags.split(',') + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Instantiating a Class} + \begin{itemize} + \item Creating objects or instances of a class is simple + \item We call the class name, with arguments as required by it's + \texttt{\_\_init\_\_} function. + \end{itemize} + \begin{lstlisting} + bdfl = Talk('Guido van Rossum', + 'The History of Python', + 'python,history,C,advanced') + \end{lstlisting} + \begin{itemize} + \item We can now call the methods of the Class + \end{itemize} + \begin{lstlisting} + bdfl.get_tags() + bdfl.get_speaker_firstname() + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\texttt{\_\_init\_\_} method} + \begin{itemize} + \item A special method + \item Called every time an instance of the class is created + \end{itemize} + \begin{lstlisting} + print bdfl.speaker + print bdfl.tags + print bdfl.title + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile, allowframebreaks] + \frametitle{Inheritance} + \begin{itemize} + \item Suppose, we wish to write a \texttt{Tutorial} class + \item It's almost same as \texttt{Talk} except for minor differences + \item We can ``inherit'' from \texttt{Talk} + \end{itemize} + \begin{lstlisting} + class Tutorial(Talk): + """A class for the tutorials.""" + + def __init__(self, speaker, title, tags, handson=True): + Talk.__init__(self, speaker, title, tags) + self.handson = handson + + def is_handson(self): + return self.handson + \end{lstlisting} + \begin{itemize} + \item Modified \texttt{\_\_init\_\_} method + \item New \texttt{is\_handson} method + \item It also has, \texttt{get\_tags} and + \texttt{get\_speaker\_firstname} + \end{itemize} + \begin{lstlisting} + numpy = Tutorial('Travis Oliphant', + 'Numpy Basics', + 'numpy,python,beginner') + numpy.is_handson() + numpy.get_speaker_firstname() + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Summary} + In this section we have learnt, + \begin{itemize} + \item the fundamental difference in paradigm, between Object Oriented + Programming and Procedural Programming + \item to write our own classes + \item to write new classes that inherit from existing classes + \end{itemize} +\end{frame} + diff --git a/slides/advanced_python/slides/plotting.tex b/slides/advanced_python/slides/plotting.tex new file mode 100644 index 0000000..fbc7aa2 --- /dev/null +++ b/slides/advanced_python/slides/plotting.tex @@ -0,0 +1,450 @@ +\section{Interactive Plotting} + +\begin{frame}[fragile] + \frametitle{First Plot} + \begin{itemize} + \item Start IPython with \texttt{-pylab} + \end{itemize} + \begin{lstlisting} + $ ipython -pylab + \end{lstlisting} % $ + \begin{lstlisting} + In[]: p = linspace(-pi,pi,100) + In[]: plot(p, cos(p)) + \end{lstlisting} +\end{frame} + + +\begin{frame}[fragile] + \frametitle{\texttt{linspace}} + \begin{itemize} + \item \texttt{p} has a hundred points in the range -pi to pi + \begin{lstlisting} + In[]: print p[0], p[-1], len(p) + \end{lstlisting} + \item Look at the doc-string of \texttt{linspace} for more details + \begin{lstlisting} + In[]: linspace? + \end{lstlisting} + \end{itemize} + \begin{itemize} + \item \texttt{plot} simply plots the two arguments with default + properties + \end{itemize} +\end{frame} + +\section{Embellishing Plots} + +\begin{frame}[fragile] + \frametitle{Plot color and thickness} + \begin{lstlisting} + In[]: clf() + In[]: plot(p, sin(p), 'r') + \end{lstlisting} + \begin{itemize} + \item Gives a sine curve in Red. + \end{itemize} + \begin{lstlisting} + In[]: plot(p, cos(p), linewidth=2) + \end{lstlisting} + \begin{itemize} + \item Sets line thickness to 2 + \end{itemize} + \begin{lstlisting} + In[]: clf() + In[]: plot(p, sin(p), '.') + \end{lstlisting} + \begin{itemize} + \item Produces a plot with only points + \end{itemize} + \begin{lstlisting} + In[]: plot? + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\texttt{title}} + \begin{lstlisting} + In[]: x = linspace(-2, 4, 50) + In[]: plot(x, -x*x + 4*x - 5, 'r', + linewidth=2) + In[]: title("Parabolic function -x^2+4x-5") + \end{lstlisting} + \begin{itemize} + \item We can set title using \LaTeX~ + \end{itemize} + \begin{lstlisting} + In[]: title("Parabolic function $-x^2+4x-5$") + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Axes labels} + \begin{lstlisting} + In[]: xlabel("x") + In[]: ylabel("f(x)") + \end{lstlisting} + \begin{itemize} + \item We could, if required use \LaTeX~ + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Annotate} + \begin{lstlisting} + In[]: annotate("local maxima", xy=(2, -1)) + \end{lstlisting} + \begin{itemize} + \item First argument is the annotation text + \item The argument to \texttt{xy} is a tuple that gives the location + of the text. + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Limits of Plot area} + \begin{lstlisting} + In[]: xlim() + In[]: ylim() + \end{lstlisting} + \begin{itemize} + \item With no arguments, \texttt{xlim} \& \texttt{ylim} get the + current limits + \item New limits are set, when arguments are passed to them + \end{itemize} + \begin{lstlisting} + In[]: xlim(-4, 5) + \end{lstlisting} + \begin{lstlisting} + In[]: ylim(-15, 2) + \end{lstlisting} +\end{frame} + +\begin{frame} +\frametitle{Plot} +\includegraphics[scale=0.45]{../advanced_python/images/plot.png}\\ +\end{frame} + + + +\section{Saving to Scripts} + +\begin{frame}[fragile] + \frametitle{Command history} + \begin{itemize} + \item To see the history of commands, we typed + \begin{lstlisting} + In[]: %hist + \end{lstlisting} + \item All commands, valid or invalid, appear in the history + \item \texttt{\%hist} is a magic command, available only in IPython + \end{itemize} + \begin{lstlisting} + In[]: %hist 5 + # last 5 commands + \end{lstlisting} + \begin{lstlisting} + In[]: %hist 5 10 + # commands between 5 and 10 + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Saving to a script} + \begin{itemize} + \item We wish to save commands for reproducing the parabola + \item Look at the history and identify the commands that will + reproduce the parabolic function along with all embellishment + \item \texttt{\%save} magic command to save the commands to a file + \end{itemize} + \begin{lstlisting} + In[]: %save plot_script.py 1 3-6 8 + \end{lstlisting} + \begin{itemize} + \item File name must have a \texttt{.py} extension + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Running the script} + \begin{lstlisting} + In[]: %run -i plot_script.py + \end{lstlisting} + \begin{itemize} + \item There were no errors in the plot, but we don't see it! + \item Running the script means, we are not in interactive mode + \item We need to explicitly ask for the image to be shown + \end{itemize} + \begin{lstlisting} + In[]: show() + \end{lstlisting} + \begin{itemize} + \item \texttt{-i} asks the interpreter to check for names, + unavailable in the script, in the interpreter + \item \texttt{sin}, \texttt{plot}, etc. are taken from the + interpreter + \end{itemize} +\end{frame} + +\section{Saving Plots} + +\begin{frame}[fragile] + \frametitle{\texttt{savefig}} + \begin{lstlisting} + In[]: x = linspace(-3*pi,3*pi,100) + In[]: plot(x,sin(x)) + In[]: savefig('sine.png') + \end{lstlisting} + \begin{itemize} + \item \texttt{savefig} takes one argument + \item The file-type is decided based on the extension + \item \texttt{savefig} can save as png, pdf, ps, eps, svg + \end{itemize} +\end{frame} + +\section{Multiple Plots} + +\begin{frame}[fragile] + \frametitle{Overlaid plots} + \begin{lstlisting} + In[]: x = linspace(0, 50, 10) + In[]: plot(x, sin(x)) + \end{lstlisting} + \begin{itemize} + \item The curve isn't as smooth as we expected + \item We chose too few points in the interval + \end{itemize} + \begin{lstlisting} + In[]: y = linspace(0, 50, 500) + In[]: plot(y, sin(y)) + \end{lstlisting} + \begin{itemize} + \item The plots are overlaid + \item It is the default behaviour of \texttt{pylab} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Legend} + \begin{lstlisting} + In[]: legend(['sine-10 points', + 'sine-500 points']) + \end{lstlisting} + \begin{itemize} + \item Placed in the location, \texttt{pylab} thinks is `best' + \item \texttt{loc} parameter allows to change the location + \end{itemize} + \begin{lstlisting} + In[]: legend(['sine-10 points', + 'sine-500 points'], + loc='center') + \end{lstlisting} +\end{frame} + +\begin{frame} +\frametitle{Overlaid Plots} +\includegraphics[scale=0.45]{../advanced_python/images/overlaid.png}\\ +\end{frame} + + + +\begin{frame}[fragile] + \frametitle{Plotting in separate figures} + \begin{lstlisting} + In[]: clf() + In[]: x = linspace(0, 50, 500) + In[]: figure(1) + In[]: plot(x, sin(x), 'b') + In[]: figure(2) + In[]: plot(x, cos(x), 'g') + \end{lstlisting} + \begin{itemize} + \item \texttt{figure} command allows us to have plots separately + \item It is also used to switch context between the plots + \end{itemize} + \begin{lstlisting} + In[]: savefig('cosine.png') + In[]: figure(1) + In[]: title('sin(y)') + In[]: savefig('sine.png') + In[]: close() + In[]: close() + \end{lstlisting} + \begin{itemize} + \item \texttt{close('all')} closes all the figures + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Subplots} + \begin{lstlisting} + In[]: subplot(2, 1, 1) + \end{lstlisting} + \begin{itemize} + \item number of rows + \item number of columns + \item plot number, in serial order, to access or create + \end{itemize} + \begin{lstlisting} + In[]: subplot(2, 1, 2) + In[]: x = linspace(0, 50, 500) + In[]: plot(x, cos(x)) + + In[]: subplot(2, 1, 1) + In[]: y = linspace(0, 5, 100) + In[]: plot(y, y ** 2) + \end{lstlisting} +\end{frame} + +\begin{frame} +\frametitle{Subplots} +\includegraphics[scale=0.45]{../advanced_python/images/subplot.png}\\ +\end{frame} + + + +\section{Plotting Data} + +\begin{frame}[fragile] + \frametitle{Loading data} + \begin{itemize} + \item \texttt{primes.txt} contains a list of primes listed + column-wise + \item We read the data using \texttt{loadtxt} + \end{itemize} + \begin{lstlisting} + In[]: primes = loadtxt('primes.txt') + In[]: print primes + \end{lstlisting} + \begin{itemize} + \item \texttt{primes} is a sequence of floats + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Reading two column data} + \begin{itemize} + \item \texttt{pendulum.txt} has two columns of data + \item Length of pendulum in the first column + \item Corresponding time period in second column + \item \texttt{loadtxt} requires both columns to be of same length + \end{itemize} + \begin{lstlisting} + In[]: pend = loadtxt('pendulum.txt') + In[]: print pend + \end{lstlisting} + \begin{itemize} + \item \texttt{pend} is not a simple sequence like \texttt{primes} + \end{itemize} +\end{frame} + +\begin{frame}[fragile] + \frametitle{Unpacking with \texttt{loadtxt}} + \begin{lstlisting} + In[]: L, T = loadtxt('pendulum.txt', + unpack=True) + In[]: print L + In[]: print T + \end{lstlisting} + \begin{itemize} + \item We wish to plot L vs. $T^2$ + \item \texttt{square} function gives us the squares + \item (We could instead iterate over T and calculate) + \end{itemize} + \begin{lstlisting} + In[]: Tsq = square(T) + + In[]: plot(L, Tsq, '.') + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] + \frametitle{\texttt{errorbar}} + \begin{itemize} + \item Experimental data always has errors + \item \texttt{pendulum\_error.txt} contains errors in L and T + \item Read the values and make an error bar plot + \end{itemize} + \begin{lstlisting} + In[]: L, T, L_err, T_err = \ + loadtxt('pendulum_error.txt', + unpack=True) + In[]: Tsq = square(T) + + In[]: errorbar(L, Tsq , xerr=L_err, + yerr=T_err, fmt='b.') + \end{lstlisting} +\end{frame} + +\begin{frame} +\frametitle{Errorbar} +\includegraphics[scale=0.45]{../advanced_python/images/L-Tsq.png}\\ +\end{frame} + +\section{Other kinds of Plots} + +\begin{frame}[fragile] + \frametitle{Scatter Plot} + \begin{itemize} + \item The data is displayed as a collection of points + \item Value of one variable determines position along x-axis + \item Value of other variable determines position along y-axis + \item Let's plot the data of profits of a company + \end{itemize} + \begin{lstlisting} + In[]: year, profit = loadtxt( + 'company-a-data.txt', + dtype=type(int())) + + In[]: scatter(year, profit) + \end{lstlisting} + \begin{itemize} + \item \alert{\texttt{dtype=int}; default is float} + \end{itemize} +\end{frame} + +\begin{frame} +\frametitle{Scatter Plot} +\includegraphics[scale=0.45]{../advanced_python/images/scatter.png}\\ +\end{frame} + +\begin{frame}[fragile] + \frametitle{Pie Chart} + \begin{lstlisting} + In[]: pie(profit, labels=year) + \end{lstlisting} +\includegraphics[scale=0.35]{../advanced_python/images/pie.png}\\ +\end{frame} + +\begin{frame}[fragile] + \frametitle{Bar Chart} + \begin{lstlisting} + In[]: bar(year, profit) + \end{lstlisting} +\includegraphics[scale=0.35]{../advanced_python/images/bar.png}\\ +\end{frame} + +\begin{frame}[fragile] + \frametitle{Log-log plot} + \begin{itemize} + \item Plot a \texttt{log-log} chart of $y=5x^3$ for x from 1 to 20 + \end{itemize} + \begin{lstlisting} + In[]: x = linspace(1,20,100) + In[]: y = 5*x**3 + + In[]: loglog(x, y) + In[]: plot(x, y) + \end{lstlisting} + \begin{itemize} + \item Look at \url{http://matplotlib.sourceforge.net/contents.html} + for more! + \end{itemize} +\end{frame} + +\begin{frame} +\frametitle{Log-log plot Plot} +\includegraphics[scale=0.45]{../advanced_python/images/loglog.png}\\ +\end{frame} + + diff --git a/slides/advanced_python/slides/scipy.tex b/slides/advanced_python/slides/scipy.tex new file mode 100644 index 0000000..1116c3d --- /dev/null +++ b/slides/advanced_python/slides/scipy.tex @@ -0,0 +1,273 @@ +\section{Solving Equations} + +\begin{frame}[fragile] +\frametitle{Solution of linear equations} +Consider, + \begin{align*} + 3x + 2y - z & = 1 \\ + 2x - 2y + 4z & = -2 \\ + -x + \frac{1}{2}y -z & = 0 + \end{align*} +Solution: + \begin{align*} + x & = 1 \\ + y & = -2 \\ + z & = -2 + \end{align*} +\end{frame} + +\begin{frame}[fragile] +\frametitle{Solving using Matrices} +Let us now look at how to solve this using \texttt{matrices} + \begin{lstlisting} +In []: A = array([[3,2,-1], + [2,-2,4], + [-1, 0.5, -1]]) +In []: b = array([1, -2, 0]) +In []: x = solve(A, b) + \end{lstlisting} +\end{frame} + +\begin{frame}[fragile] +\frametitle{Solution:} +\begin{lstlisting} +In []: x +Out[]: array([ 1., -2., -2.]) +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] +\frametitle{Let's check!} +\begin{small} +\begin{lstlisting} +In []: Ax = dot(A, x) +In []: Ax +Out[]: array([ 1.00000000e+00, -2.00000000e+00, + -1.11022302e-16]) +\end{lstlisting} +\end{small} +\begin{block}{} +The last term in the matrix is actually \alert{0}!\\ +We can use \texttt{allclose()} to check. +\end{block} +\begin{lstlisting} +In []: allclose(Ax, b) +Out[]: True +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] +\frametitle{\texttt{roots} of polynomials} +\begin{itemize} +\item \texttt{roots} function can find roots of polynomials +\item To calculate the roots of $x^2-5x+6$ +\end{itemize} +\begin{lstlisting} + In []: coeffs = [1, -5, 6] + In []: roots(coeffs) + Out[]: array([3., 2.]) +\end{lstlisting} +\vspace*{-.2in} +\begin{center} +\includegraphics[height=1.6in, interpolate=true]{images/roots} +\end{center} +\end{frame} + +\begin{frame}[fragile] +\frametitle{SciPy: \texttt{fsolve}} +\begin{small} +\begin{lstlisting} + In []: from scipy.optimize import fsolve +\end{lstlisting} +\end{small} +\begin{itemize} +\item Finds the roots of a system of non-linear equations +\item Input arguments - Function and initial estimate +\item Returns the solution +\end{itemize} +\end{frame} + +\begin{frame}[fragile] +\frametitle{\texttt{fsolve} \ldots} +Find the root of $sin(z)+cos^2(z)$ nearest to $0$ +\begin{lstlisting} +In []: def g(z): + ....: return sin(z)+cos(z)*cos(z) + +In []: fsolve(g, 0) +Out[]: -0.66623943249251527 +\end{lstlisting} +\begin{center} +\includegraphics[height=2in, interpolate=true]{images/fsolve} +\end{center} +\end{frame} + +\section{ODEs} + +\begin{frame}[fragile] +\frametitle{Solving ODEs using SciPy} +\begin{itemize} +\item Consider the spread of an epidemic in a population +\item $\frac{dy}{dt} = ky(L-y)$ gives the spread of the disease +\item $L$ is the total population. +\item Use $L = 2.5E5, k = 3E-5, y(0) = 250$ +\item Define a function as below +\end{itemize} +\begin{lstlisting} +In []: from scipy.integrate import odeint +In []: def epid(y, t): + .... k = 3.0e-5 + .... L = 2.5e5 + .... return k*y*(L-y) + .... +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] +\frametitle{Solving ODEs using SciPy \ldots} +\begin{lstlisting} +In []: t = linspace(0, 12, 61) + +In []: y = odeint(epid, 250, t) + +In []: plot(t, y) +\end{lstlisting} +%Insert Plot +\end{frame} + +\begin{frame}[fragile] +\frametitle{Result} +\begin{center} +\includegraphics[height=2in, interpolate=true]{images/epid} +\end{center} +\end{frame} + + +\begin{frame}[fragile] +\frametitle{ODEs - Simple Pendulum} +We shall use the simple ODE of a simple pendulum. +\begin{equation*} +\ddot{\theta} = -\frac{g}{L}sin(\theta) +\end{equation*} +\begin{itemize} +\item This equation can be written as a system of two first order ODEs +\end{itemize} +\begin{align} +\dot{\theta} &= \omega \\ +\dot{\omega} &= -\frac{g}{L}sin(\theta) \\ + \text{At}\ t &= 0 : \nonumber \\ + \theta = \theta_0(10^o)\quad & \&\quad \omega = 0\ (Initial\ values)\nonumber +\end{align} +\end{frame} + +\begin{frame}[fragile] +\frametitle{ODEs - Simple Pendulum \ldots} +\begin{itemize} +\item Use \texttt{odeint} to do the integration +\end{itemize} +\begin{lstlisting} +In []: def pend_int(initial, t): + .... theta = initial[0] + .... omega = initial[1] + .... g = 9.81 + .... L = 0.2 + .... F=[omega, -(g/L)*sin(theta)] + .... return F + .... +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] +\frametitle{ODEs - Simple Pendulum \ldots} +\begin{itemize} +\item \texttt{t} is the time variable \\ +\item \texttt{initial} has the initial values +\end{itemize} +\begin{lstlisting} +In []: t = linspace(0, 20, 101) +In []: initial = [10*2*pi/360, 0] +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] +\frametitle{ODEs - Simple Pendulum \ldots} +%%\begin{small} +\texttt{} +%%\end{small} +\begin{lstlisting} +In []: from scipy.integrate import odeint +In []: pend_sol = odeint(pend_int, + initial,t) +\end{lstlisting} +\end{frame} + +\begin{frame}[fragile] +\frametitle{Result} +\begin{center} +\includegraphics[height=2in, interpolate=true]{images/ode} +\end{center} +\end{frame} + +%% \section{FFTs} + +%% \begin{frame}[fragile] +%% \frametitle{The FFT} +%% \begin{itemize} +%% \item We have a simple signal $y(t)$ +%% \item Find the FFT and plot it +%% \end{itemize} +%% \begin{lstlisting} +%% In []: t = linspace(0, 2*pi, 500) +%% In []: y = sin(4*pi*t) + +%% In []: f = fft(y) +%% In []: freq = fftfreq(500, t[1] - t[0]) + +%% In []: plot(freq[:250], abs(f)[:250]) +%% In []: grid() +%% \end{lstlisting} +%% \end{frame} + +%% \begin{frame}[fragile] +%% \frametitle{FFTs cont\dots} +%% \begin{lstlisting} +%% In []: y1 = ifft(f) # inverse FFT +%% In []: allclose(y, y1) +%% Out[]: True +%% \end{lstlisting} +%% \end{frame} + +%% \begin{frame}[fragile] +%% \frametitle{FFTs cont\dots} +%% Let us add some noise to the signal +%% \begin{lstlisting} +%% In []: yr = y + random(size=500)*0.2 +%% In []: yn = y + normal(size=500)*0.2 + +%% In []: plot(t, yr) +%% In []: figure() +%% In []: plot(freq[:250], +%% ...: abs(fft(yn))[:250]) +%% \end{lstlisting} +%% \begin{itemize} +%% \item \texttt{random}: produces uniform deviates in $[0, 1)$ +%% \item \texttt{normal}: draws random samples from a Gaussian +%% distribution +%% \item Useful to create a random matrix of any shape +%% \end{itemize} +%% \end{frame} + +%% \begin{frame}[fragile] +%% \frametitle{FFTs cont\dots} +%% Filter the noisy signal: +%% \begin{lstlisting} +%% In []: from scipy import signal +%% In []: yc = signal.wiener(yn, 5) +%% In []: clf() +%% In []: plot(t, yc) +%% In []: figure() +%% In []: plot(freq[:250], +%% ...: abs(fft(yc))[:250]) +%% \end{lstlisting} +%% Only scratched the surface here \dots +%% \end{frame} diff --git a/slides/advanced_python/slides/tmp.tex b/slides/advanced_python/slides/tmp.tex new file mode 100644 index 0000000..9913703 --- /dev/null +++ b/slides/advanced_python/slides/tmp.tex @@ -0,0 +1,316 @@ +% Created 2011-04-18 Mon 03:20 +\documentclass[presentation]{beamer} +\usepackage[utf8]{inputenc} +\usepackage[T1]{fontenc} +\usepackage{fixltx2e} +\usepackage{graphicx} +\usepackage{longtable} +\usepackage{float} +\usepackage{wrapfig} +\usepackage{soul} +\usepackage{textcomp} +\usepackage{marvosym} +\usepackage{wasysym} +\usepackage{latexsym} +\usepackage{amssymb} +\usepackage{hyperref} +\tolerance=1000 +\usepackage[english]{babel} \usepackage{ae,aecompl} +\usepackage{mathpazo,courier,euler} \usepackage[scaled=.95]{helvet} +\usepackage{listings} +\lstset{language=Python, basicstyle=\ttfamily\bfseries, +commentstyle=\color{red}\itshape, stringstyle=\color{darkgreen}, +showstringspaces=false, keywordstyle=\color{blue}\bfseries} +\providecommand{\alert}[1]{\textbf{#1}} + +\title{modules.rst.org} +\author{} +\date{\today} + +\usetheme{Warsaw}\usecolortheme{default}\useoutertheme{infolines}\setbeamercovered{transparent} +\begin{document} + +\maketitle + +\begin{frame} +\frametitle{Outline} +\setcounter{tocdepth}{3} +\tableofcontents +\end{frame} + + + + +\section{Using Python modules} +\label{sec-1} + + +We shall, in this section, see how to run Python scripts from the +command line, and more details about importing modules. + +Let us create a simple python script to print hello world. Open your +text editor and type the following, and save the script as \texttt{hello.py}. + +\begin{verbatim} +print "Hello world!" +\end{verbatim} + +Until now we have been running scripts from inside IPython, using + +\begin{verbatim} +%run -i hello.py +\end{verbatim} + +But, as we know, IPython is just an advanced interpreter and it is not +mandatory that every one who wants to run your program has IPython +installed. + +So, the right method to run the script, would be to run it using the +Python interpreter. Open the terminal and navigate to the directory +where \texttt{hello.py} is saved. + +Then run the script by saying, + +\begin{verbatim} +python hello.py +\end{verbatim} + +The script is executed and the string \texttt{Hello World!} has been printed. + +Now let us run a script that plots a simple sine curve in the range -2pi +to 2pi, using Python, instead of running it from within IPython. + +Type the following lines and save it in \texttt{sine\_plot.py} file. + +\begin{verbatim} +x = linspace(-2*pi, 2*pi, 100) +plot(x, sin(x)) +show() +\end{verbatim} + +Now let us run sine\_plot.py as a python script. + +\begin{verbatim} +python sine_plot.py +\end{verbatim} + +Do we get the plot? No! All we get is error messages. Python complains +that \texttt{linspace} isn't defined. What happened? Let us try to run the same +script from within IPython. Start IPython, with the \texttt{-pylab} argument +and run the script. It works! + +What is going on, here? IPython when started with the \texttt{-pylab} option, +is importing a whole set of functionality for us to work with, without +bothering about importing etc. + +Let us now try to fix the problem by importing \texttt{linspace}. + +Let's add the following line as the first line in the script. + +\begin{verbatim} +from scipy import * +\end{verbatim} + +Now let us run the script again, + +\begin{verbatim} +python sine_plot.py +\end{verbatim} + +Now we get an error, that says \texttt{plot} is not defined. Let's edit the +file and import this from pylab. Let's add the following line, as the +second line of our script. + +\begin{verbatim} +from pylab import * +\end{verbatim} + +And run the script, + +\begin{verbatim} +python sine_plot.py +\end{verbatim} + +Yes! it worked. So what did we do? + +We actually imported the required functions and keywords, using +\texttt{import}. By using the *, we are asking python to import everything from +the \texttt{scipy} and \texttt{pylab} modules. This isn't a good practice, as 1. it +imports a lot of unnecessary things 2. the two modules may have +functions with the same name, which would cause a conflict. + +One of the ways out is to import only the stuff that we need, +explicitly. + +Let us modify sine\_plot.py by replacing the import statements with the +following lines. + +\begin{verbatim} +from scipy import linspace, pi, sin +from pylab import plot, show +\end{verbatim} + +Now let us try running the code again as, + +\begin{verbatim} +python show_plot.py +\end{verbatim} + +As expected, this works. But, once the number of functions that you need +to import increases, this is slightly inconvenient. Also, you cannot use +functions with the same name, from different modules. To overcome this, +there's another method. + +We could just import the modules as it is, and use the functions or +other objects as a part of those modules. Change the import lines, to +the following. + +\begin{verbatim} +import scipy +import pylab +\end{verbatim} + +Now, replace \texttt{pi} with \texttt{scipy.pi}. Similarly, for \texttt{sin} and \texttt{linspace}. +Replace \texttt{plot} and \texttt{show} with \texttt{pylab.plot} and \texttt{pylab.show}, +respectively. + +Now, run the file and see that we get the output, as expected. + +We have learned how to import from modules, but what exactly is a +module? How is one written? + +A module is simply a Python script containing the definitions and +statements, which can be imported. So, it is very easy to create your +own modules. You just need to stick in all your definitions into your +python file and put the file in your current directory. + +When importing, Python searches the locations present in a variable +called the Python path. So, our module file should be present in one of +the locations in the Python path. The first location to be searched is +the current directory of the script being run. So, having our module +file in the current working directory, is the simplest way to allow it +to be used as a module and import things from it. + +Python has a very rich standard library of modules. It is very +extensive, offering a wide range of facilities. Some of the standard +modules are, + +for Math: math, random for Internet access: urllib2, smtplib for System, +Command line arguments: sys for Operating system interface: os for +regular expressions: re for compression: gzip, zipfile, tarfile And +there are lot more. + +Find more information at Python Library reference, +\texttt{http://docs.python.org/library/} + +There are a lot of other modules like pylab, scipy, Mayavi, etc which +are not part of the standard Python library. + +This brings us to the end of our discussion on modules and running +scripts from the command line. +\section{Writing modules} +\label{sec-2} + + +In this section we shall look at writing modules, in some more detail. +Often we will have to reuse the code that we have previously written. We +do that by writing functions. Functions can then be put into modules, +and imported as and when required. + +Let us first write a function that computes the gcd of two numbers and +save it in a script. + +\begin{verbatim} +def gcd(a, b): + while b: + a, b = b, a%b + return a +\end{verbatim} + +Now, we shall write a test function in the script that tests the gcd +function, to see if it works. + +\begin{verbatim} +if gcd(40, 12) == 4 and gcd(12, 13) == 1: + print "Everything OK" +else: + print "The GCD function is wrong" +\end{verbatim} + +Let us save the file as gcd\_script.py in \texttt{/home/fossee/gcd\_script.py} +and run it. + +\begin{verbatim} +$ python /home/fossee/gcd_script.py +\end{verbatim} + +We can see that the script is executed and everything is fine. + +What if we want to use the gcd function in some of our other scripts. +This is also possible since every python file can be used as a module. + +But first, we shall understand what happens when you import a module. + +Open IPython and type + +\begin{verbatim} +import sys +sys.path +\end{verbatim} + +This is a list of locations where python searches for a module when it +encounters an import statement. Hence, when we just did \texttt{import sys}, +python searches for a file named \texttt{sys.py} or a folder named \texttt{sys} in all +these locations one by one, until it finds one. We can place our script +in any one of these locations and import it. + +The first item in the list is an empty string which means the current +working directory is also searched. + +Alternatively, we can also import the module if we are working in same +directory where the script exists. + +Since we are in /home/fossee, we can simply do + +\begin{verbatim} +import gcd_script +\end{verbatim} + +We can see that the gcd\_script is imported. But the test code that we +added at the end of the file is also executed. + +But we want the test code to be executed only when the file is run as a +python script and not when it is imported. + +This is possible by using \texttt{\_\_name\_\_} variable. + +Go to the file and add + +\begin{verbatim} +if __name__ == "__main__": +\end{verbatim} + +before the test code and indent the test code. + +Let us first run the code. + +\begin{verbatim} +$ python gcd_script.py +\end{verbatim} + +We can see that the test runs successfully. + +Now we shall import the file + +\begin{verbatim} +import gcd_script +\end{verbatim} + +We see that now the test code is not executed. + +The \texttt{\_\_name\_\_} variable is local to every module and it is equal to +\texttt{\_\_main\_\_} only when the file is run as a script. Hence, all the code +that goes in to the if block, \texttt{if \_\_name\_\_ =} ``__main__'':= is executed +only when the file is run as a python script. + +\end{document} |