\documentclass{article}

\title{\sc\LARGE CSCA67 Tutorial, Week 11\\
{\Large Nov. 23rd-Nov. 27th, 2015}}
\date{}
\author{\sc Compiled by {\em G. Singh Cadieux}\\[1ex]
\sc Adapted from\\
A. Bretscher, \href{http://www.utsc.utoronto.ca/~bretscher/a67/lectures/induction_ppt.pdf}{\em CSCA67 Week 10 Lecture Notes},\\
\href{http://youtu.be/NuGDkmwEObM?t=58m50s}{\em Lec 3 \textbar MIT 6.042J Mathematics for Computer Science, Fall 2010} \&\\
V. Hadzilacos, \textit{Course notes for {\em Introduction to the Theory of Computation}} (2007).}

\usepackage{fullpage}
\usepackage{amsmath,amssymb}
%\usepackage{color}
%\usepackage{multicol}
\usepackage{tikz}
\usepackage{hyperref}

\usetikzlibrary{patterns}
\usetikzlibrary{backgrounds}
\tikzstyle{background rectangle}=[draw=none]

\setlength{\parindent}{0pt}

\begin{document}
\maketitle

\section{\sc Review of last week's lecture}
\subsection*{\em Proof by induction}
Proof by induction is a proof technique that is used to prove that a predicate $P(n)$ is true for all natural numbers $n$ larger than $b$, where $b$ is a natural number.\\[1ex]
The natural numbers are the ``counting numbers": the nonnegative integers 0, 1, 2, \ldots (note that, depending upon the context, 0 may or may not be included in the natural numbers). The set of natural numbers is denoted $\mathbb{N}$.\\[1ex]
For example, suppose we have the predicate $P(n): n(n^2+5)$ is divisible by 6.\\
We can demonstrate that $P(n)$ is true or false for a specific value of $n$: for instance, if we choose $n=2$, $2(2^2+5)=18$ is divisible by 6, so $P(6)$ is true.\\
But we cannot demonstrate that $P(n)$ is true for all $n\in\mathbb{N}$ - that is, for all natural numbers $n$ - by successively choosing $n$ to be every natural number, since there are infinitely many natural numbers. We can instead use proof by induction to prove that $P(n)$ is true for all $n\in\mathbb{N}$.\\[1em]
\textsc{Proof Structure:}\\[1ex]
Establish a statement $S(n)$ to prove.\\
Generally, $S(n)$ will take the form ``$P(n)$ is true for all natural numbers $n\geq b$," where $P(n)$ is a predicate such as ``$n(n^2+5)$ is divisible by 6."
\begin{enumerate}
\item \textbf{Base case/basis:} Prove that $P(b)$ is true.
\item \textbf{Induction hypothesis:} Suppose that $P(k)$ is true for all natural numbers $k\geq b$.
\item \textbf{Induction step:} Prove that $P(k)$ implies $P(k+1)$ (i.e., prove that $P(k+1)$ is true if $P(k)$ is true).
\end{enumerate}
Conclude that $P(n)$ is true for all natural numbers $n\geq b$, which is to say that $S(n)$ is true.\\[1em]
\textsc{Intuitively}, this makes sense because, if $P(k)\to P(k+1)$, and $P(b)$ is true, then we reach each natural number with a series of implications starting from $b$:
\begin{equation*}
P(b)\to P(b+1)\to P((b+1)+1)\to P((b+2)+1)\to P((b+3)+1)\to\ldots
\end{equation*}

\textsc{Formally}, we can demonstrate that induction proofs are valid using the \textit{well-ordering principle}.\\[1ex]
\textbf{Well-Ordering Principle:} Any non-empty subset $C$ of $\mathbb{N}$ contains a smallest element.\\[1em]
Suppose that we have completed all 3 steps of a proof by induction in order to prove that $P(n)$ is true for all $n\in\mathbb{N}$ greater than $b$.\\[1ex]
Let $C=\{x\,|\,P(x)\text{ is false},\,x\geq b,\, x\in\mathbb{N}\}$ be the set of all values greater than $b$ for which $P(n)$ is false.\\[1ex]
Suppose that our proof is not valid. Then there must be at least one value for which $P(n)$ is false, so $C$ is non-empty. Then by the well-ordering principle, there exists a smallest element $a\in C$.\\[1ex]
Since our base case proves that $P(b)$ is true, $a\neq b$.\\[1ex]
Since $a>b$ and $b$ is a natural number, $a$ must be a natural number and $(a-1)$ must also be a natural number. But $(a-1)<a$ and $a$ is the smallest element in $C$, so $(a-1)$ must not be in $C$ - that is, $P(a-1)$ must be true.\\[1ex]
However, by the induction hypothesis, if $P(a-1)$ is true, then $P((a-1)+1)=P(a)$ must be true as well. Then $a$ is not in $C$.\\[1ex]
This is a contradiction, demonstrating that our assumption that $C$ is nonempty must be false. Since $C$ \textit{is} empty, there are no values for which $P(n)$ is false if the base case and induction hypothesis hold.\\[1em]
\textsc{Note} that a common misunderstanding of proof by induction is to think that, by using the induction hypothesis, our proof assumes that $P(n)$ is true for all natural numbers. This is \textit{not} the case.\\[1ex]
Rather, we use the induction hypothesis in the induction step to prove that, for any natural number $k$, \textit{if} $P(k)$ is true, then $P(k+1)$ is true as well. Recall that we can prove an implication $p\to q$ true if we prove that, when $p$ is true, $q$ is also true. We are not assuming that $P(n)$ is absolutely true; we are assuming that $P(n)$ is true only to prove that the implication $P(n)\to P(n+1)$ is true.\\[1em]
Q: \textsc{Prove that $P(n): 0+1+2+\ldots+(n-1)+n=\dfrac{n(n+1)}{2}$ is true for all $n\in\mathbb{N}$.}\\[1ex]
Let $S(n)$ be the statement that $P(n)$ holds for all $n\in\mathbb{N}$.\\[1ex]
\textbf{Basis:} $n=0$\\[1ex]
$\dfrac{(0)(0+1)}{2}=0$\\[1ex]
$\Rightarrow P(0)$ holds.\\[1ex]
\textbf{Induction hypothesis:} Suppose that $P(k)$ holds for $k\geq 0$.\\[1ex]
\textbf{Induction step:} $n=k+1$
\begin{align*}
0+1+2+\ldots+k+(k+1)& =(0+1+2+\ldots+k)+(k+1)\\
& =\dfrac{k(k+1)}{2}+(k+1)& \text{[by the induction hypothesis]}\\
& =\dfrac{k(k+1)}{2}+\dfrac{2(k+1)}{2}\\
& =\dfrac{(k+2)(k+1)}{2}\\
& =\dfrac{(k+1)((k+1)+1)}{2}
\end{align*}
$\Rightarrow P(k+1)$ holds if $P(k)$ holds, for $k\geq 0$.\\[1ex]
$\boxed{\Rightarrow S(n)\text{ is true.}}$

\section{\sc Proof by simple induction}

\subsection*{\href{http://www.youtube.com/watch?v=IFqna5F0kW8}{Q: {\em Prove that $4+9+14+19+\ldots+(5n-1)=\dfrac{n}{2}(3+5n)$ for all natural numbers $n$.}}}

Let $P(n)$ be the predicate ``$4+9+14+19+\ldots+(5n-1)=\tfrac{n}{2}(3+5n)$".\\
Let $S(n)$ be the statement that $P(n)$ holds for all $n\in\mathbb{N}$ (note that, here, $0\notin\mathbb{N}$).\\[1ex]
\textbf{Basis:} $n=1$\\[1ex]
$5(1)-1=4$\\[1ex]
$\dfrac{1}{2}(3+5(1))=\dfrac{1}{2}(8)=4$\\[1ex]
$5(1)-1=\dfrac{1}{2}(3+5(1))\Rightarrow P(1)$ holds.\\[1ex]
\textbf{Induction hypothesis:} Suppose that $P(k)$ holds for $k\geq 1$.\\[1ex]
\textbf{Induction step:} $n=k+1$
\begin{align*}
4+9+14+19+\ldots+(5(k)-1)+(5(k+1)-1)& =\dfrac{k}{2}(3+5(k))+(5(k+1)-1)& \text{[by I.H.]}\\
& =\dfrac{5}{2}k^2+\dfrac{13}{2}k+4& \text{[expanded and simplified]}\\
\dfrac{(k+1)}{2}(3+5(k+1))& =\left(\dfrac{k}{2}+\dfrac{1}{2}\right)(3+5k+5)\\
& =(\dfrac{5}{2}k^2+4k)+(\dfrac{5}{2}+4)& \text{[expanded and simplified]}\\
4+9+14+19+\ldots+(5(k)-1)+(5(k+1)-1)& =\dfrac{(k+1)}{2}(3+5(k+1))
\end{align*}
$\Rightarrow P(k+1)$ holds if $P(k)$ holds, for $k\geq 1$.\\[1ex]
$\boxed{\Rightarrow S(n)\text{ is true.}}$

\subsection*{\href{http://www.youtube.com/watch?v=wBvsIyQN4o8}{Q: {\em Prove that $-1+2+5+8+\ldots+(3n-4)=\dfrac{n}{2}(3-5n)$ for all natural numbers $n$.}}}

Let $P(n)$ be the predicate ``$-1+2+5+8+\ldots+(3n-4)=\tfrac{n}{2}(3-5n)$".\\
Let $S(n)$ be the statement that $P(n)$ holds for all $n\in\mathbb{N}$ (note that, here, $0\notin\mathbb{N}$).\\[1ex]
\textbf{Basis:} $n=1$\\[1ex]
$3(1)-4=-1$\\[1ex]
$\dfrac{1}{2}(3-5(1))=\dfrac{1}{2}(-2)=-1$\\[1ex]
$3(1)-4=\dfrac{1}{2}(3-5(1))\Rightarrow P(1)$ holds.\\[1ex]
\textbf{Induction hypothesis:} Suppose that $P(k)$ holds for $k\geq 1$.\\[1ex]
\textbf{Induction step:} $n=k+1$
\begin{align*}
-1+2+5+8+\ldots+(3(k)+4)+(3(k+1)-4)& =\dfrac{k}{2}(3-5(k))+(3(k+1)-4)& \text{[by I.H.]}\\
& =\dfrac{3}{2}k^2+\dfrac{1}{2}k-1& \text{[expanded and simplified]}\\
\dfrac{(k+1)}{2}(3+5(k+1))& =\left(\dfrac{k}{2}+\dfrac{1}{2}\right)(3+5k+5)\\
& =\dfrac{3}{2}k^2+\dfrac{1}{2}k-1& \text{[expanded and simplified]}\\
-1+2+5+8+\ldots+(3(k)+4)+(3(k+1)-4)& =\dfrac{(k+1)}{2}(3+5(k+1))
\end{align*}
$\Rightarrow P(k+1)$ holds if $P(k)$ holds, for $k\geq 1$.\\[1ex]
$\boxed{\Rightarrow S(n)\text{ is true.}}$

\subsection*{\href{http://www.youtube.com/watch?v=uHfwNKWyD20}{Q: {\em Prove that $\dfrac{1}{2}+\dfrac{1}{4}+\dfrac{1}{8}+\ldots+\dfrac{1}{2^n}=\dfrac{2^n-1}{2^n}$ for all natural numbers $n$.}}}

Let $P(n)$ be the predicate ``$\tfrac{1}{2}+\tfrac{1}{4}+\tfrac{1}{8}+\ldots+\tfrac{1}{2^n}=\tfrac{2^n-1}{2^n}$".\\
Let $S(n)$ be the statement that $P(n)$ holds for all $n\in\mathbb{N}$ (note that, here, $0\notin\mathbb{N}$).\\[1ex]
\textbf{Basis:} $n=1$\\[1ex]
$\dfrac{1}{2^{(1)}}=\dfrac{1}{2}$\\[1ex]
$\dfrac{2^{(1)}-1}{2^{(1)}}=\dfrac{1}{2}$\\[1ex]
$\dfrac{1}{2^{(1)}}=\dfrac{2^{(1)}-1}{2^{(1)}}\Rightarrow P(1)$ holds.\\[1ex]
\textbf{Induction hypothesis:} Suppose that $P(k)$ holds for $k\geq 1$.\\[1ex]
\textbf{Induction step:} $n=k+1$
\begin{align*}
\dfrac{1}{2}+\dfrac{1}{4}+\dfrac{1}{8}+\ldots+\dfrac{1}{2^{(k)}}+\dfrac{1}{2^{(k+1)}}& =\dfrac{2^k-1}{2^k}+\dfrac{1}{2^{(k+1)}}& \text{[by I.H.]}\\
& =\dfrac{2(2^k-1)}{2^{(k+1)}}+\dfrac{1}{2^{(k+1)}}\\
& =\dfrac{2^{(k+1)}-2}{2^{(k+1)}}+\dfrac{1}{2^{(k+1)}}\\
& =\dfrac{2^{(k+1)}-1}{2^{(k+1)}}
\end{align*}
$\Rightarrow P(k+1)$ holds if $P(k)$ holds, for $k\geq 1$.\\[1ex]
$\boxed{\Rightarrow S(n)\text{ is true.}}$

\section{\sc Proof by complete induction}
So far, we have been using a type of proof by induction known as ``simple" induction. Another type of proof by induction is \textit{complete} (or \textit{strong}) induction.\\[1ex]
Like simple induction, complete induction is used to prove that a predicate $P(n)$ is true for all natural numbers $n$ larger than $b$, where $b$ is a natural number.\\[1ex]
The difference betwen the two techniques is in the induction hypothesis: rather than assuming only that $P(k)$ is true, we assume that $P(b),\,P(b+1),\,P(b+2),\,\ldots,\,P(k)$ are all true (a ``stronger" induction hypothesis, hence the name of the technique).\\[1ex]
It is easier to use complete induction than simple induction for certain problems, since there are more assumptions that we can use.\\[1em]
\textsc{Proof Structure:}\\[1ex]
Establish a statement $S(n)$ to prove.\\
Generally, $S(n)$ will take the form ``$P(n)$ is true for all natural numbers $n\geq b$," where $P(n)$ is a predicate such as ``$n(n^2+5)$ is divisible by 6."
\begin{enumerate}
\item \textbf{Base case/basis:} Prove that $P(b)$ is true.
\item \textbf{Induction hypothesis:} Suppose that $P(b+1),\,P(b+2),\,\ldots,\,P(k)$ are true for all natural numbers $k\geq b$.
\item \textbf{Induction step:} Prove that $P(b)\wedge P(b+1)\wedge P(b+2)\wedge\ldots\wedge P(k)$ implies $P(k+1)$ (i.e., prove that $P(k+1)$ is true if $P(b),\,P(b+1),\,P(b+2),\,\ldots,\,P(k)$ are true).
\end{enumerate}
Conclude that $P(n)$ is true for all natural numbers $n\geq b$, which is to say that $S(n)$ is true.

\subsection*{\em The Unstacking Game}
Consider a game in which each player starts off with a stack of objects.

\begin{itemize}
\item At his/her turn, each player splits (one of) his/her stack(s) into 2 smaller stacks.
\item The number of points for each turn is the product of the sizes of the 2 stacks.
\item The players continue taking turns and splitting their stacks until all the stacks contain only 1 object each.
\item Each player's total score is the sum of his/her scores for all the turns. The player with the largest total score is the winner.
\end{itemize}
For example, starting with 5 objects, one possible strategy is:\\
\begin{tikzpicture}[framed, inner frame sep=1ex]
\draw (0,0) rectangle (0.75,0.5);
\draw (0,0.5) rectangle (0.75,1);
\draw (0,1) rectangle (0.75,1.5);
\draw (0,1.5) rectangle (0.75,2);
\draw (0,2) rectangle (0.75,2.5);
\end{tikzpicture}
\begin{tikzpicture}[framed, inner frame sep=1ex]
\draw (0,0) rectangle (0.75,0.5);
\draw (0,0.5) rectangle (0.75,1);
\draw (0.85,0) rectangle (1.6,0.5);
\draw (0.85,0.5) rectangle (1.6,1);
\draw (0.85,1) rectangle (1.6,1.5);
\end{tikzpicture}
\begin{tikzpicture}[framed, inner frame sep=1ex]
\draw (0,0) rectangle (0.75,0.5);
\draw (0,0.5) rectangle (0.75,1);
\draw (0.85,0) rectangle (1.6,0.5);
\draw (0.85,0.5) rectangle (1.6,1);
\draw (1.7,0) rectangle (2.45,0.5);
\end{tikzpicture}
\begin{tikzpicture}[framed, inner frame sep=1ex]
\draw (-0.85,0) rectangle (-0.1,0.5);
\draw (0,0) rectangle (0.75,0.5);
\draw (0.85,0) rectangle (1.6,0.5);
\draw (0.85,0.5) rectangle (1.6,1);
\draw (1.7,0) rectangle (2.45,0.5);
\end{tikzpicture}
\begin{tikzpicture}[framed, inner frame sep=1ex]
\draw (0,0) rectangle (0.75,0.5);
\draw (0.85,0) rectangle (1.6,0.5);
\draw (1.7,0) rectangle (2.45,0.5);
\draw (2.55,0) rectangle (3.3,0.5);
\draw (3.4,0) rectangle (4.15,0.5);
\end{tikzpicture}\\
This player will have $(2\times 3)+(2\times 1)+(1\times 1)+(1\times 1)=10$ points in total.\\[1em]
When we play the unstacking game, however, we notice that all strategies appear to result in the same score. For example, here is another strategy when starting with a stack of 5 objects:\\
\begin{tikzpicture}[framed, inner frame sep=1ex]
\draw (0,0) rectangle (0.75,0.5);
\draw (0,0.5) rectangle (0.75,1);
\draw (0,1) rectangle (0.75,1.5);
\draw (0,1.5) rectangle (0.75,2);
\draw (0,2) rectangle (0.75,2.5);
\end{tikzpicture}
\begin{tikzpicture}[framed, inner frame sep=1ex]
\draw (0,0) rectangle (0.75,0.5);
\draw (0.85,0) rectangle (1.6,0.5);
\draw (0.85,0.5) rectangle (1.6,1);
\draw (0.85,1) rectangle (1.6,1.5);
\draw (0.85,1.5) rectangle (1.6,2);
\end{tikzpicture}
\begin{tikzpicture}[framed, inner frame sep=1ex]
\draw (0,0) rectangle (0.75,0.5);
\draw (0.85,0) rectangle (1.6,0.5);
\draw (0.85,0.5) rectangle (1.6,1);
\draw (1.7,0) rectangle (2.45,0.5);
\draw (1.7,0.5) rectangle (2.45,1);
\end{tikzpicture}
\begin{tikzpicture}[framed, inner frame sep=1ex]
\draw (-0.85,0) rectangle (-0.1,0.5);
\draw (0,0) rectangle (0.75,0.5);
\draw (0.85,0) rectangle (1.6,0.5);
\draw (0.85,0.5) rectangle (1.6,1);
\draw (1.7,0) rectangle (2.45,0.5);
\end{tikzpicture}
\begin{tikzpicture}[framed, inner frame sep=1ex]
\draw (0,0) rectangle (0.75,0.5);
\draw (0.85,0) rectangle (1.6,0.5);
\draw (1.7,0) rectangle (2.45,0.5);
\draw (2.55,0) rectangle (3.3,0.5);
\draw (3.4,0) rectangle (4.15,0.5);
\end{tikzpicture}\\
This again produces a total score of $(1\times 4)+(1\times 3)+(2\times 1)+(1\times 1)=10$ points.\\[1em]
\textsc{We can theorize} that, for an inital stack of $n$ objects, any strategy will produce the same score $S(n)$. And since we believe that all strategies produce the same score, let us choose a strategy and calculate the resulting score $S(n)$, which should result from any other strategy as well.\\[1ex]
We know (and have demonstrated above) that the sum of all natural numbers up to $n$ is $\tfrac{n(n+1)}{2}$. If we choose the strategy of splitting each stack of blocks into a stack of 1 block and a stack of all the remaining blocks, then our total score will be $((n-1)\times 1)+(((n-1)-1)\times 1)+\ldots+(1\times 1)=(n-1)+(n-2)+\ldots+1$.\\
For example, when starting with 5 objects, our strategy proceeds as follows:\\
\begin{tikzpicture}[framed, inner frame sep=1ex]
\draw (0,0) rectangle (0.75,0.5);
\draw (0,0.5) rectangle (0.75,1);
\draw (0,1) rectangle (0.75,1.5);
\draw (0,1.5) rectangle (0.75,2);
\draw (0,2) rectangle (0.75,2.5);
\end{tikzpicture}
\begin{tikzpicture}[framed, inner frame sep=1ex]
\draw (0,0) rectangle (0.75,0.5);
\draw (0,0.5) rectangle (0.75,1);
\draw (0,1) rectangle (0.75,1.5);
\draw (0,1.5) rectangle (0.75,2);
\draw (0.85,0) rectangle (1.6,0.5);
\end{tikzpicture}
\begin{tikzpicture}[framed, inner frame sep=1ex]
\draw (0,0) rectangle (0.75,0.5);
\draw (0,0.5) rectangle (0.75,1);
\draw (0,1) rectangle (0.75,1.5);
\draw (0.85,0) rectangle (1.6,0.5);
\draw (1.7,0) rectangle (2.45,0.5);
\end{tikzpicture}
\begin{tikzpicture}[framed, inner frame sep=1ex]
\draw (0,0) rectangle (0.75,0.5);
\draw (0,0.5) rectangle (0.75,1);
\draw (0.85,0) rectangle (1.6,0.5);
\draw (1.7,0) rectangle (2.45,0.5);
\draw (2.55,0) rectangle (3.3,0.5);
\end{tikzpicture}
\begin{tikzpicture}[framed, inner frame sep=1ex]
\draw (0,0) rectangle (0.75,0.5);
\draw (0.85,0) rectangle (1.6,0.5);
\draw (1.7,0) rectangle (2.45,0.5);
\draw (2.55,0) rectangle (3.3,0.5);
\draw (3.4,0) rectangle (4.15,0.5);
\end{tikzpicture}\\
This gives us a score of $(4\times 1)+(3\times 1)+(2\times 1)+(1\times 1)=4+3+2+1$.\\[1ex]
In general, our total score from this strategy will be the sum of all natural numbers up to $(n-1)$, which we know to be $\tfrac{(n-1)((n-1)+1)}{2}=\tfrac{n(n-1)}{2}$.\\[1em]
\textsc{So now} let us use complete induction to prove\\
$Q(n):$ all strategies for the unstacking game produce the same score $S(n)=\dfrac{n(n-1)}{2}$ for all $n\in\mathbb{N}$, where $n$ is the number of objects in the initial stack.\\[1em]
\textbf{Basis:} $n=1$\\[1ex]
$S(1)=\dfrac{(1)((1)-1)}{2}=0$\\[1ex]
Since there are no moves that can be made with a stack of 1 object, all strategies will produce a score of 0. $\Rightarrow$ With $n=1$, all strategies produce the same score $S(1)$.\\[1ex]
\textbf{Induction hypothesis:} Suppose that, with $n=2$, all strategies produce the same score $S(2)$; with $n=3$, all strategies produce the same score $S(3)$; etc. Finally, suppose that, with $n=k\geq 1$, all strategies produce the same score $S(k)$.\\[1ex]
\textbf{Induction step:} $n=k+1$\\[1ex]
For our first turn, we divide the stack of $(k+1)$ objects into a stack of $m$ objects and a stack of $(k+1-m)$ objects (the value of $m$ depends upon our strategy).\\[1ex]
Based on our induction hypothesis, with an initial stack of $m\leq k$ objects, all strategies will produce a score of $S(m)=\tfrac{m(m-1)}{2}$; and with an initial stack of $(k+1-m)$ objects, all strategies will produce a score of $S(k+1-m)=\tfrac{(k+1-m)((k+1-m)-1)}{2}$.\\[1ex]
\textsc{Notice} that these assumptions cannot be used in simple induction.\\[1ex]
Then the total score for the game is the sum of the score for our first turn, and the total score for unstacking $m$ objects, and the total score for unstacking $(k+1-m)$ objects:
\begin{align*}
m(k+1-m)+S(m)+S(k+1-m)& =m(k+1-m)+\dfrac{m(m-1)}{2}+\dfrac{(k+1-m)((k+1-m)-1)}{2}\\
& =(km+m-m^2)+\dfrac{m^2-m}{2}+\dfrac{(k+1-m)(k+m)}{2}\\
& =\dfrac{1}{2}k^2+\dfrac{1}{2}k\qquad\text{[expanded and simplified]}
\end{align*}
Notice that this total score depends only on $k$ and not $m$ - that is, the total score depends only on the inital number of objects and not on our strategy, as we expected.
\begin{align*}
\dfrac{(k+1)((k+1)-1)}{2}& =\dfrac{k(k+1)}{2}\\
& =\dfrac{1}{2}k^2+\dfrac{1}{2}k\qquad\text{[expanded]}\\
m(k+1-m)+S(m)+S(k+1-m)& =\dfrac{(k+1)((k+1)-1)}{2}
\end{align*}
$\Rightarrow$ If all strategies produce the same score $S(2)$ with $n=2$, all strategies produce the same score $S(3)$ with $n=3$, etc., and all strategies produce the same score $S(k)$ with $n=k\geq 1$, then all strategies produce the same score $S(k+1)=\tfrac{(k+1)((k+1)-1)}{2}$ with $n=k+1$.\\[1ex]
$\boxed{\Rightarrow Q(n)\text{ is true.}}$

\section{\sc Additional practice problems}

{\bf Q: Using simple induction, prove that $1+2+4+\ldots+2^n=2^{n+1}-1$ for all natural numbers $n$.}\\[1em]
{\bf Q: Using simple induction, prove that $2^n\geq n^2$ for all natural numbers $n$.}\\[1em]
{\bf Q: Using simple induction, prove that $\sum\limits_{i=0}^n m^i=\dfrac{m^{n+1}-1}{m-1}$ for all integers $m\geq 2,\,n\geq 1$.}\\[1em]
Define the sequence $a_0,\,a_1,\,\ldots$ as\\
$a_i=\begin{cases}
2&\text{if }0\leq i\leq 2\\
a_{i-1}+a_{i-2}+a_{i-3}&\text{if }i>2
\end{cases}$\\[1ex]
{\bf Q: Using complete induction, prove that $a_n<2^n$ for every integer $n\geq 2$.}\\[1em]
{\bf Q: Find the flaw in the following proof by induction (a well-known proof by George P\'{o}lya).}\\[1ex]
$P(n)$: $n$ horses are of the same colour\\[1ex]
$S(n)$: $\forall n \in N$, $P(n)$ holds.\\[1ex]
\underline{Basis:} $n=1$\\[1ex]
$P(1)$ clearly holds as a single horse is the same colour as itself.\\[1ex]
\underline{Induction hypothesis:} Suppose that, within any set of $k$ horses, $k\geq 1$, all horses are of the same colour.\\[1ex]
\underline{Induction step:} $n=k+1$\\[1ex]
Consider a set of $k+1$ horses and number them $\{1,\,2,\,\ldots,\,k+1\}$ so that each horse is distinct. This set contains (among others) the overlapping subsets $\{1,\,2,\,\ldots,\,k\}$ and $\{2,\,3,\,\ldots,\,k+1\}$, each of which has $k$ horses.\\[1ex]
By the inductive hypothesis, the horses in the first subset are all of the same colour, and the horses in the second subset are all of the same colour. Both subsets contain the horses $\{2,\,3,\,\ldots,\,k\}$, meaning that these horses must all be of the same colour, and the horses not contained in both subsets (horse 1 in the first and horse $k+1$ in the second) must also be of the same colour as the rest. Thus, all $k+1$ horses are of the same colour.\\[1ex]
$\Rightarrow P(k+1)$ holds if $P(k)$ holds, for $k\geq 1$.\\[1ex]
$\boxed{\Rightarrow S(n)\text{ is true: all horses are of the same colour!}}$\\[1em]

{\bf Q: Find the flaw in the following proof by induction.}\\[1ex]
$P(n)$: $n=1$.\\[1ex]
$S(n)$: For all natural numbers $n\geq 1$, $P(n)$ holds.\\[1ex]
\underline{Basis:} $n=1$\\[1ex]
Trivial. $\Rightarrow P(1)$ holds.\\[1ex]
\underline{Induction hypothesis:} Suppose that $P(k)$ holds for $k\geq 1$ - that is, suppose that, for any $k\geq 1$, $k=1$.\\[1ex]
\underline{Induction step:} $n=k+1$\\[1ex]
Consider the (as yet unproven) statement $k+1=1$.
\begin{align*}
k+1& =1\\
(k+1)(k-1)& =1(k-1)\\
k^2-1& =k-1\\
k^2& =k\\
1^2& =1\qquad\text{[by I.H.]}
\end{align*}
Since this final statement is true, and is equivalent to the initial statement $k+1=1$, $k+1=1$ must be true as well.\\[1ex]
$\Rightarrow P(k+1)$ holds if $P(k)$ holds, for $k\geq 1$.\\[1ex]
$\boxed{\Rightarrow S(n)\text{ is true.}}$

\end{document}


\lab{F2PY}{F2PY}
\label{lab:f2py}
\objective{Learn how to use F2PY, especially for wrapping Fortran code involving arrays.}

Here we will explore another simple way to access external code from Python.
Various utilities exist to do this, and many are specialized for specific tasks.
F2PY is a utility that can be used to automatically wrap Fortran subroutines so that they are callable from Python.
It is included with NumPy and in most cases does not usually require heavy configuration for use.
The primary requirement for using F2PY is a working Fortran compiler.
If you have access to gfortran, the Fortran equivalent of gcc, it should work well.

\section*{Examples}

F2PY is an interface generator designed to be used primarily to generate Python bindings for array based functions and subroutines from Fortran.
Many simple Fortran files can be compiled \emph{automatically} without any hand-written interfaces between languages.
Windows 64 bit users, if you encounter errors, see the Windows 64 bit install guide.
Here we will wrap a Fortran function that performs a basic tridiagonal solve.
This function is essentially the same as the one wrapped in Lab \ref{lab:cythonwrap}.
In Lab \ref{lab:cythonwrap} the Fortran function had been modified so that it was already callable from C.
F2PY takes care of necessary name and type changes so that pure Fotran functions and subroutines can be wrapped without modification.
We will wrapp the following unmodified version of the algorithm for a tridiagonal solve.
\lstinputlisting[style=fromfile, language=Fortran, name=ftridiag.f90]{./ftridiag/ftridiag.f90}
This subroutine can be wrapped by running the following in the terminal:
\begin{lstlisting}[style=ShellInput]
f2py -c ftridiag.f90 -m ftridiag
\end{lstlisting}
Depending on the way your system is configured, the following command may be needed
\begin{lstlisting}[style=ShellInput]
python f2py.py -c ftridiag.f90 -m ftridiag
\end{lstlisting}
Additional optimization flags can be passed to the compiler using the \li{--opt} flag, as in:
\begin{lstlisting}[style=ShellInput]
f2py -c ftridiag.f90 -m ftridiag --opt="-O3 -march=native"
\end{lstlisting}

Running these commands will create a file called \li{ftridiag.pyd} on a Windows computer or \li{ftridiag.so} on a Linux or Mac based computer.
This file is a Python module that is linked against the compiled Fortran code.
All the details about array type, shape, size, etc. are infered by F2PY.
This wrapper can be tested using a test similar to the one used in Lab \ref{lab:cythonwrap}
\lstinputlisting[style=fromfile, name=ftridiag_test.py]{./ftridiag/test.py}
\begin{info}
This example shows how to compile a single subroutine.
If the subroutine were a part of a Fortran module, F2PY would have created a submodule for the compile module.
For example, if the subroutine were contained in the module \li{tridiag}, after compilation, it would be available in the Python submodule \li{ftridiag.tridiag} as \li{ftridiag.tridiag.ftridiag}.
\end{info}

\begin{info}
In many cases F2PY can automatically infer the correct values for arguments that are used to convey information about array shape.
These arguments are usually included as optional arguments in the calling signature for the Python function.
F2PY also verifies that the shapes of the arrays passed to each subroutine match the shapes of arrays shown in the declaration of the interface for the subroutine.
\end{info}

\begin{warn}
When working with arrays that have more than one dimension, F2PY expects arrays that are Fortran ordered, i.e. arrays that have their columns stored in contiguous blocks.
By default it will raise an error if it receives a C-contiguous array, though it can be configured to silently make a copy instead.
A Fortran ordered array can be made by taking the transpose of a C contiguous array.
This becomes very important when working with arrays with two or more dimensions.
\end{warn}

Again, similar to working with Cython, we can also create a \li{setup.py} file to create our Python extension module.
The following \li{setup.py} file will do the same thing as the terminal command used above.
\lstinputlisting[style=fromfile, name=ftridiag_setup.py]{./ftridiag/setup.py}

\begin{problem}
Included with this lab is a pure-fortran version of the \li{fssor} subroutine that you wrapped in Lab \ref{lab:cythonwrap}.
Wrap it again using f2py.
Write a \li{setup.py} file as shown above.
When wrapping automatically in this way, F2PY was able to infer that \li{m} and \li{n} are the dimensions of the array.
On the other hand, we have not defined default vaues for the tolerance and the maximum number of iterations, so those must still be passed in as arguments.
\end{problem}

\section*{Detailed Compilation Steps}
Though F2PY can be used automatically as shown, it can be used to generate more carefully customized wrappers for Fortran functions and subroutines.
When compiling an extension, F2PY performs two basic steps that are accessible to users:
\begin{itemize}
\item Create a \li{.pyf} signature file defining the interface for the Fortran subroutines
\item Compile the Fortran code and use Python's C API to make an extension module that calls it in the way defined in the signature file.
\end{itemize}
If we want a more specific interface for the Fortran code we are wrapping we can generate the signature file, then modify it so that F2PY will make a Python function with the desired calling signature.

Consider the \li{ftridiag} subroutine used above.
F2PY can be used to generate a signature file based on the contents of the file \li{ftridiag.f90} via the command
\begin{lstlisting}[style=ShellInput]
f2py ftridiag.f90 -m ftridiag -h ftridiag.pyf
\end{lstlisting}
The signature file created by F2PY is
\lstinputlisting[style=fromfile, language=Fortran, name=ftridiag.pyf]{./ftridiag/ftridiag.pyf}
This looks almost like a function signature in Fortran, except that F2PY has accounted for the fact that \li{n} is one more than the dimension of the first array.

Notice that F2PY has automatically recognized that the last argument to the Fortran subroutine can be inferred directly from the length of the arrays given as arguments.
When it detects that an argument can be inferred from array shapes, it includes it as an optional argument in the Python binding.
F2PY also automatically checks that the dimensions of the arrays passed are consistent with the dimensions listed in the subroutine declaration.

A F2PY signature file can, in turn, be used to create a Python extension module that wraps the Fortran subroutines as described in the signature file.
The following command will use the signature file and Fortran source file above to create a Python extension module.
\begin{lstlisting}[style=ShellInput]
f2py -c ftridiag.pyf ftridiag.f90
\end{lstlisting}

Signature files can also be used in \li{setup.py} scripts like this:
\lstinputlisting[style=fromfile, language=Python, name=setup.py]{./ftridiag/setup_with_sig.py}

F2PY's signature files are more useful when working with arrays with more than one dimension.
Consider the following Fortran subroutine that uses a simple iterative method to find an approximate solution to Laplace's equation on a square.
\lstinputlisting[style=fromfile, language=Fortran, name=flaplace.f90]{./flaplace/flaplace.f90}

% Wrap a C function using f2py to teach about signature files.

% Wrap a LAPACK function (dgtsv?), have them do it too.

\begin{warn}
The LAPACK routines available in \li{scipy.linalg.lapack} do not raise errors when passed a C contiguous array.
Instead, the array is copied into Fortran contiguous form before it is passed to the Fortran subroutine.
This means that code is less likely to raise errors, but the implicit copying of arrays may slow a program down unnecessarily.
\end{warn}

% Discuss how memory layout affects performance.

% Discuss programmer time value.


\documentclass[12pt]{article}

\include{preamble}

\title{Math 368 / 621 Fall 2019 \\ Midterm Examination Two}
\author{Professor Adam Kapelner}

\date{November 13, 2019}

\begin{document}
\maketitle

\noindent Full Name \line(1,0){220} Circle Section and Class: A~B~C ~~ 368~621

\thispagestyle{empty}

\section*{Code of Academic Integrity}

\footnotesize
Since the college is an academic community, its fundamental purpose is the pursuit of knowledge. Essential to the success of this educational mission is a commitment to the principles of academic integrity. Every member of the college community is responsible for upholding the highest standards of honesty at all times. Students, as members of the community, are also responsible for adhering to the principles and spirit of the following Code of Academic Integrity.

Activities that have the effect or intention of interfering with education, pursuit of knowledge, or fair evaluation of a student's performance are prohibited. Examples of such activities include but are not limited to the following definitions:

\paragraph{Cheating} Using or attempting to use unauthorized assistance, material, or study aids in examinations or other academic work or preventing, or attempting to prevent, another from using authorized assistance, material, or study aids. Example: using an unauthorized cheat sheet in a quiz or exam, altering a graded exam and resubmitting it for a better grade, etc.
\\

\noindent I acknowledge and agree to uphold this Code of Academic Integrity. \\

\begin{center}
\line(1,0){250} ~~~ \line(1,0){100}\\
~~~~~~~~~~~~~~~~~~~~~signature~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ date
\end{center}

\normalsize

\vspace{-1cm}
\section*{Instructions}

This exam is seventy five minutes and closed-book. You are allowed one page (front and back) of a \qu{cheat sheet.} You may use a graphing calculator of your choice. Please read the questions carefully. If the question reads \qu{compute,} this means the solution will be a number otherwise you can leave the answer in choose, permutation, exponent, factorial or any other notation which could be resolved to a number with a computer. Questions marked \qu{[MA]} are required for those enrolled in 621 and extra credit for those enrolled in 368. If you are enrolled in 368, I advise you to finish the other questions on the exam and only then attempt the extra credit. Questions marked \qu{[Extra Credit]} are extra credit for both 368 and 621 students. I also advise you to use pencil. The exam is 100 points total plus extra credit. Partial credit will be granted for incomplete answers on most of the questions. \fbox{Box} in your final answers. Good luck!

\pagebreak

\problem Below are some theoretical exercises.

\benum

\subquestionwithpoints{6} Let $X \sim \text{Weibull}(k, \lambda)$ and $c$ is a positive constant. Circle the statement(s) that are true.

\begin{enumerate}
\item Let $k = 0.53$. $\prob{X > c} < \cprob{X > 2c}{X > c}$
\item Let $k = 0.53$. $\prob{X > c} > \cprob{X > 2c}{X > c}$
\item Let $k = 1$. $\prob{X > c} < \cprob{X > 2c}{X > c}$
\item Let $k = 1$. $\prob{X > c} > \cprob{X > 2c}{X > c}$
\end{enumerate}

\subquestionwithpoints{6} Let $X \sim \text{ParetoI}(1, \lambda)$ Let $f_X(x)$ denote its density and $F_X(x)$ denote its CDF, both valid for all $x \in \reals$. Set $\lambda$ so that the 80-20 Pareto Principle holds. Circle the statement(s) that are true.

\begin{enumerate}
\item $Q[X, 0.8] = Q[X, 0.2]$
\item $Q[X, 0.8] = f_X(0.8)$
\item $Q[X, 0.8] = F_X(0.8)$
\item $ \frac{\displaystyle\int_{-\infty}^{F^{-1}_X(0.8)} x f_X(x)}{\displaystyle\expe{X}} = 0.2$
\item $\lambda = 0.8$
\end{enumerate}

\subquestionwithpoints{10} Let $X_1, X_2, \ldots \iid \exponential{\lambda}$ and $N \sim \poisson{\lambda}$. Each statement below is either true or false. Circle the statement(s) that are true for all $k \in \naturals$.

\begin{enumerate}
\item $N = X_1 + X_2 + \ldots + X_k$
\item $X_1 + X_2 + \ldots + X_k \sim \text{Gamma}(k, \lambda)$
\item $\prob{X_1 + X_2 + \ldots + X_k < 1} = Q(k, \lambda)$
\item $\prob{X_1 + X_2 + \ldots + X_k < 1} = P(k, \lambda)$
\item $\prob{N < 1} = Q(k, \lambda)$
\item $\prob{N < 1} = P(k, \lambda)$
\item $\prob{N < k} = Q(k, \lambda)$
\item $\prob{N < k} = P(k, \lambda)$
\item $\prob{X_1 + X_2 + \ldots + X_k > 1} = \prob{N < k}$
\end{enumerate}

\subquestionwithpoints{6} Consider a continuous r.v. $X$ with known CDF $F_X$ Let $Y = -X$ and find the CDF of $Y$ in terms of $F_X$.  \spc{1}

\subquestionwithpoints{8} Let $X_1, X_2 \iid \text{Logistic}\parens{0, 1}$. Provide an expression for the $\prob{X_1 + X_2 > a}$ where $a \in \reals$ is a constant. Your answer must consist of just numbers, symbols and no brand name notation e.g. $\int_\reals \oneover{1 + x^2} dx$ but not  $\int_{\support{X_1}} \text{Logistic}\parens{0, 1} dx$. Do NOT simplify! \spc{5}

%\subquestionwithpoints{6} Assume $\Gamma(\half) = \sqrt{\pi}$ and show that $\Gamma(\frac{5}{2}) = \frac{3}{4}\sqrt{\pi}$. \spc{1}

\subquestionwithpoints{6} Let $X \sim \poisson{\lambda}$ and let $Y = g(X) = \sqrt{X}$. Find its PMF $p_Y(y)$ and make sure $p_Y(y)$ is valid $\forall y \in \reals$. Do NOT simplify. \spc{4}

\subquestionwithpoints{4} Let $X \sim \text{BetaPrime}(\alpha, \beta) := \oneover{B(\alpha, \beta)} \frac{x^{\alpha - 1}}{(x + 1)^{\alpha + \beta}} \indic{x \geq 0}$. Decompose the PDF of $X$ into $c \cdot k(x)$ where $k(x)$ is the kernel and $c$ is the normalization constant. \spc{1}
%
%\beqn
%c &=& \\
%&& \\
%&& \\
%k(x) &=& \\
%&&\\
%\eeqn

\subquestionwithpoints{6} Let $X \sim \text{BetaPrime}(\alpha, \beta)$. Prove that $X^{-1} \sim \text{BetaPrime}(\beta, \alpha)$. \spc{10}

%\subquestionwithpoints{6} Let $X \sim \text{Gamma}\parens{\alpha, \beta}$ and let $Y = g(X) = X^{-1}$. Find its PDF $f_Y(y)$ and make sure $f_Y(y)$ is valid $\forall y \in \reals$. \spc{10}

\subquestionwithpoints{8} Consider dependent continuous r.v.'s $X_1, X_2$ with known JDF $f_{X_1, X_2}(x_1, x_2)$ valid for all $x_1, x_2 \in \reals$. Consider the transformation of these r.v.'s of $H = \frac{X_1}{\natlog{X_2}}$. Find a formula that will allow you to compute its PDF $f_H(h)$ in terms of the JDF $f_{X_1, X_2}(x_1, x_2)$. \spc{7}

\subquestionwithpoints{8} Let $X_1, X_2 \iid \text{Laplace}(0,1)$ and let $R = \frac{X_1}{X_2}$. Write a mathematical expression for $f_R(r)$. Do NOT simplify! \spc{4}

\subquestionwithpoints{8} Let $\Xoneton \iid \exponential{\lambda}$. Find the distribution of their minimum. If it is a brand name r.v. we studied, indicate it with the value(s) of its parameters. \spc{5}

\subquestionwithpoints{8} Let $X_1, \ldots, X_{37} \iid \stduniform$. Find $\prob{X_{(17)} \leq \half}$. Express your answer in terms of the regularized incomplete beta function. \spc{8}

\subquestionwithpoints{8} If $X_1, X_2 \iid \text{ExtNegBin}(k, p) := \frac{\Gamma(k + x)}{\Gamma(k)x!} (1 - p)^x p^k \indic{x \in \naturals_0}$ who share the ch.f. $\phi_X(t) = \tothepow{\frac{1-p}{1-pe^{it}}}{k}$, show that $T = X_1 + X_2$ is also distributed as a ExtNegBin and find its parameters. If you use the following properties of ch.f.'s make sure to reference them in your proof by saying \qu{(P1)}, \qu{(P2)}, etc.

\footnotesize
\begin{itemize}
\item[(P0)] $\phi_X(0) = 1$
\item[(P1)] $\phi_X(t) = \phi_Y(t)$ is equivalent to $X \equalsindist Y$
\item[(P2)] If $Y = aX + b$ then $\phi_Y(t) = e^{ibt}\phi_X(at)$
\item[(P3)] If $X_1, X_2 \inddist$ and $T = X_1 + X_2$ then $\phi_T(t) = \phi_{X_1}(t) \phi_{X_2}(t)$ and if $X_1, X_2 \iid$ then $\phi_T(t) = \phi_{X}(t)^2$
\item[(P4)] For any moment that exists, $\expe{X^n} = \phi^{(n)}_X(0) / i^n$
\end{itemize}
\normalsize~\spc{6}

\subquestionwithpoints{8} [MA] If $Y~|~X = x \sim \text{ExtNegBin}(k, x)$ and $X \sim \betanot{\alpha}{\beta}$. Find the PMF of $Y$, a r.v. model you have not seen yet. Simplify \textit{as much as possible}. For those curious, $Y \sim \text{BetaNegBin}(k, \alpha, \beta)$, appropriately named the \qu{beta negative binomial}. \spc{8}

\subquestionwithpoints{6} [Extra Credit] If $Y~|~X = x \sim \binomial{10}{x}$ and $X \sim \betanot{\alpha}{\beta}$ where $Y$ models the number of male births for women who have 10 children and $x$ is the probability of having a male child (assuming each child's gender is an independent and identically distributed process). If Jane had 2 girls, what is the distribution of her $X$? \spc{1}

\eenum

\end{document}


\section{Functions}

\begin{frame}[fragile]
  \frametitle{Abstracting}
  \begin{itemize}
  \item Reduce duplication of code
  \item Fewer lines of code and hence lesser scope for bugs
  \item Re-usability of code, that's already been written
  \item Use functions written by others, without exactly knowing how
    they do, what they are doing
  \item \alert{Enter Functions!}
  \end{itemize}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Defining functions}
  \begin{itemize}
  \item Consider the function \texttt{f(x) = x\textasciicircum{}2}
  \item Let's write a Python function, equivalent to this
  \end{itemize}
  \begin{lstlisting}
   In[]: def f(x):
   ....:     return x*x
   ....:

   In[]: f(1)
   In[]: f(2)
  \end{lstlisting}
  \begin{itemize}
  \item \texttt{def} is a keyword
  \item \texttt{f} is the name of the function
  \item \texttt{x} the parameter of the function
  \item \texttt{return} is a keyword; specifies what should be
    returned
  \end{itemize}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Defining functions \ldots}
  \begin{lstlisting}
  In[]: def greet():
  ....:     print "Hello World!"
  ....:

  In[]: greet()
  \end{lstlisting}
  \begin{itemize}
  \item \texttt{greet} is a function that takes no arguments
  \item Also, it is not returning anything explicitly
  \item But implicitly, Python returns \texttt{None}
  \end{itemize}
  \begin{lstlisting}
  In[]: def avg(a, b):
  ....:     return (a + b)/2
  ....:

  In[]: avg(12, 10)
  \end{lstlisting}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Doc-strings}
  \begin{itemize}
  \item It's highly recommended that all functions have documentation
  \item We write a doc-string along with the function definition
  \end{itemize}
  \begin{lstlisting}
  In[]: def avg(a, b):
        """ avg takes two numbers as input
        and returns their average"""

  ....:     return (a + b)/2
  ....:

  In[]: avg?
  In[]: greet?
  \end{lstlisting}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Returning multiple values}
  \begin{itemize}
  \item Return area and perimeter of circle, given radius
  \item Function needs to return two values
  \end{itemize}
  \begin{lstlisting}
  In[]: def circle(r):
        """returns area and perimeter of a
        circle given, the radius r"""

  ....:     pi = 3.14
  ....:     area = pi * r * r
  ....:     perimeter = 2 * pi * r
  ....:     return area, perimeter
  ....:

  In[]: circle(4)
  In[]: a, p = circle(6)
  In[]: print a
  In[]: print p
  \end{lstlisting}
  \begin{itemize}
  \item Any number of values can be returned
  \end{itemize}
\end{frame}

\begin{frame}[fragile]
  \frametitle{What? -- 1}
  \begin{lstlisting}
  In[]: def what( n ):
  ....:     if n < 0: n = -n
  ....:     while n > 0:
  ....:         if n % 2 == 1:
  ....:             return False
  ....:         n /= 10
  ....:     return True
  ....:
  \end{lstlisting}
\end{frame}

\begin{frame}[fragile]
  \frametitle{What? -- 2}
  \begin{lstlisting}
  In[]: def what( n ):
  ....:     i = 1
  ....:     while i * i < n:
  ....:         i += 1
  ....:     return i * i == n, i
  ....:
  \end{lstlisting}
\end{frame}

\subsection*{Default \& Keyword Arguments}

\begin{frame}[fragile]
  \frametitle{Default arguments}
  \begin{lstlisting}
  In[]: round(2.484)
  In[]: round(2.484, 2)

  In[]: s.split() # split on spaces
  In[]: s.split(';') # split on ';'

  In[]: range(10) # returns numbers from 0 to 9
  In[]: range(1, 10) # returns numbers from 1 to 9
  In[]: range(1, 10, 2) # returns odd numbers from 1 to 9
  \end{lstlisting}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Default arguments \ldots}
  \begin{lstlisting}
  In[]: def welcome(greet, name="World"):
  ....:     print greet, name
  ....:

  In[]: welcome("Hi", "Guido")
  In[]: welcome("Hello")
  \end{lstlisting}
  \begin{itemize}
  \item Arguments with default values, should be placed at the end
  \item The following definition is \alert{WRONG}
  \end{itemize}
  \begin{lstlisting}
  In[]: def welcome(name="World", greet):
  ....:     print greet, name
  ....:
  \end{lstlisting}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Keyword Arguments}
  \begin{lstlisting}
  In[]: def welcome(greet, name="World"):
  ....:     print greet, name
  ....:

  In[]: welcome("Hello", "James")

  In[]: welcome("Hi", name="Guido")

  In[]: welcome(name="Guido", greet="Hey")

  In[]: welcome(name="Guido", "Hey")
  \end{lstlisting}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Built-in functions}
  \begin{itemize}
  \item Variety of built-in functions are available
  \item \texttt{abs, any, all, len, max, min}
  \item \texttt{pow, range, sum, type}
  \item Refer here:
    \url{http://docs.python.org/library/functions.html}
  \end{itemize}
\end{frame}

\subsection*{Variable Scope}

\begin{frame}[fragile]
  \frametitle{Arguments are local}
  \begin{lstlisting}
   In[]: def change(q):
   ....:     q = 10
   ....:     print q
   ....:

   In[]: change(1)
   In[]: print q
  \end{lstlisting}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Variables inside function are local}
  \begin{lstlisting}
  In[]: n = 5
  In[]: def change():
  ....:     n = 10
  ....:     print n
  ....:
  In[]: change()
  In[]: print n
  \end{lstlisting}
\end{frame}

\begin{frame}[fragile]
  \frametitle{global}
 \begin{itemize}
  \item Use the \texttt{global} statement to assign to global variables
  \end{itemize}
  \begin{lstlisting}
  In[]: def change():
  ....:     global n
  ....:     n = 10
  ....:     print n
  ....:
  In[]: change()
  In[]: print n
  \end{lstlisting}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Mutable variables}
  \begin{itemize}
  \item Behavior is different when assigning to a list element/slice
  \item Python looks up for the name, from innermost scope outwards,
    until the name is found
  \end{itemize}
  \begin{lstlisting}
  In[]: name = ['Mr.', 'Steve', 'Gosling']
  In[]: def change_name():
  ....:     name[0] = 'Dr.'
  ....:
  In[]: change_name()
  In[]: print name
  \end{lstlisting}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Passing Arguments \ldots}
  \begin{lstlisting}
  In[]: n = 5
  In[]: def change(n):
  ....:     n = 10
  ....:     print "n = %s inside change " %n
  ....:
  In[]: change(n)
  In[]: print n
  \end{lstlisting}

  \begin{lstlisting}
  In[]: name = ['Mr.', 'Steve', 'Gosling']
  In[]: def change_name(n):
  ....:     n[0] = 'Dr.'
  ....:     print "n = %s inside change_name" %n
  ....:
  In[]: change_name(name)
  In[]: print name
  \end{lstlisting}
\end{frame}


\chapter{Results}
\section{Expected and Measured Yields}
The yield tables for the four analysis regions are shown in Tables \ref{tbl:hvtww_yields} - \ref{tbl:hvwzvbf_yields}. The fitted background normalizations are shown in Tables \ref{tbl:hvtww_norm}-\ref{tbl:hvtwzvbf_norm}. The control region $m_{\ell\nu qq}$ distributions are shown in Figures \ref{fig:hvtww_cr_postfit} - \ref{fig:hvtwz_cr_postfit}. The signal region $m_{\ell\nu qq}$ distributions are shown in Figures \ref{fig:hvtww_sr_postfit} - \ref{fig:hvtwzvbf_tag_sr_postfit}.
% Postfit L1 GGF WCR
\begin{table}
\resizebox{\textwidth}{!}
{\begin{tabular}{|l|c|c|c|}
\hline
	  &	 HP WCR &	 LP WCR &	Resolved WCR \\\hline
	%HVT Z' &	3.91 $\pm$ 9.88 &	7.05 $\pm$ 17.83 &	0.42 $\pm$ 1.06 \\\hline
	Electron Multi-jet &	- &	- &	16500 $\pm$ 2300 \\\hline
	Muon Multi-jet &	- &	- &	20000 $\pm$ 2800 \\\hline
	Diboson &	1800 $\pm$ 180 &	3300 $\pm$ 320 &	9100 $\pm$ 960 \\\hline
	Single-top &	2200 $\pm$ 400 &	3500 $\pm$ 660 &	20000 $\pm$ 3800 \\\hline
	$t\bar{t}$ &	16000 $\pm$ 340 &	24000 $\pm$ 450&	140000 $\pm$ 2000 \\\hline
	$W$+jets &	40000 $\pm$ 360 &	88113.06 $\pm$ 490 &	670000 $\pm$ 4100 \\\hline
	$Z$+jets &	780 $\pm$ 79 &	1800 $\pm$ 180 &	17000 $\pm$ 1700 \\\hline
	Total &	60000 $\pm$ 660 &	120000 $\pm$ 1000 &	890000 $\pm$ 7200 \\\hline
	Data &	60264 &	120852 &	895362 \\\hline
\end{tabular}}

% Postfit L1 GGF TCR
\resizebox{\textwidth}{!}
{\begin{tabular}{|l|c|c|c|}
\hline
	  &	 HP  TCR &	 LP  TCR &	Resolved TCR \\\hline
	%HVT Z' &	1.27 $\pm$ 3.20 &	0.60 $\pm$ 1.50 &	0.12 $\pm$ 0.30 \\\hline
	Electron Multi-jet &	- &	- &	- \\\hline
	Muon Multi-jet &	- &	- &	- \\\hline
	Diboson &	420 $\pm$ 38 &	550 $\pm$ 53 &	1000 $\pm$ 120 \\\hline
	Single-top &	4700 $\pm$ 850 &	3500 $\pm$ 630 &	17000 $\pm$ 3300 \\\hline
	$t\bar{t}$ &	39000 $\pm$ 850 &	34000 $\pm$ 640 &	220000 $\pm$ 3200 \\\hline
	$W$+jets &	2300 $\pm$ 20 &	6600 $\pm$ 36 &	23000 $\pm$ 140 \\\hline
	$Z$+jets &	66 $\pm$ 7 &	210 $\pm$ 21 &	850 $\pm$ 85 \\\hline
	Total &	46000 $\pm$ 1200 &	45000 $\pm$ 900 &	270000 $\pm$ 4600 \\\hline
	Data &	46354 &	44629 &	266443 \\\hline
\end{tabular}}

% Postfit L1 GGF SR
\resizebox{\textwidth}{!}
{\begin{tabular}{|l|c|c|c|}
\hline
	  &	 WW SR &	 LP SR &	Resolved 1-lepton SR \\\hline
	%HVT Z' &	21.59 $\pm$ 54.38 &	10.39 $\pm$ 25.86 &	4.22 $\pm$ 10.58 \\\hline
	Electron Multi-jet &	- &	- &	11000 $\pm$ 1500 \\\hline
	Muon Multi-jet &	- &	- &	16000 $\pm$ 2200 \\\hline
	Diboson &	5000 $\pm$ 400 &	3900 $\pm$ 310 &	17000 $\pm$ 1500 \\\hline
	Single-top &	3000 $\pm$ 600 &	2000 $\pm$ 400 &	20000 $\pm$ 4000 \\\hline
	$t\bar{t}$ &	14000 $\pm$ 300 &	11000 $\pm$ 210&	130000 $\pm$ 1800 \\\hline
	$W$+jets &	25000 $\pm$ 220 &	60080.66 $\pm$ 330 &	440000 $\pm$ 2700 \\\hline
	$Z$+jets &	500 $\pm$ 50 &	1200 $\pm$ 120 &	12000 $\pm$ 1200 \\\hline
	Total &	47000 $\pm$ 780 &	78000 $\pm$ 650 &	650000 $\pm$ 6000 \\\hline
	Data &	47330 &	78380 &	645610 \\\hline
\end{tabular}}
\caption{Expected and Measured for DY $WW$ $W$+jets, $t\bar{t}$ control regions and signal regions.}
\label{tbl:hvtww_yields}
\end{table}

\begin{table}
\resizebox{\textwidth}{!}
% Postfit L1 GGF WCR Untag
{\begin{tabular}{|l|c|c|c|}
\hline
	  &	 HP  Untagged WCR &	 LP Untagged WCR &	Resolved Untagged WCR \\\hline
	%HVT W' &	2.31 $\pm$ 5.75 &	3.63 $\pm$ 9.18 &	0.73 $\pm$ 1.83 \\\hline
	Electron Multi-jet &	- &	- &	15000 $\pm$ 2300 \\\hline
	Muon Multi-jet &	- &	- &	27000 $\pm$ 3000 \\\hline
	Diboson &	1500 $\pm$ 150 &	2800 $\pm$ 280 &	9000 $\pm$ 730 \\\hline
	Single-top &	1800 $\pm$ 310 &	2900 $\pm$ 520 &	21000 $\pm$ 3500 \\\hline
	$t\bar{t}$ &	13000 $\pm$ 240 &	22000 $\pm$ 330 &	140000 $\pm$ 2600 \\\hline
	$W$+jets &	41000 $\pm$ 330 &	88000 $\pm$ 500 &	670000 $\pm$ 4400 \\\hline
	$Z$+jets &	770 $\pm$ 78 &	1800 $\pm$ 180 &	17000 $\pm$ 1700 \\\hline
	Total &	58000 $\pm$ 540 &	120000 $\pm$ 860 &	890000 $\pm$ 7500 \\\hline
	Data &	57699 &	117306 &	895362 \\\hline
\end{tabular}}

% Postfit L1 GGF WCR Tag
\resizebox{\textwidth}{!}
{\begin{tabular}{|l|c|c|c|}
\hline
	  &	 HP Tagged WCR &	 LP Tagged WCR &	Resolved Tagged WCR \\\hline
%	HVT W' &	0.45 $\pm$ 1.12 &	0.86 $\pm$ 2.18 &	0.18 $\pm$ 0.44 \\\hline
	Electron Multi-jet &	- &	- &	400 $\pm$ 60 \\\hline
	Muon Multi-jet &	- &	- &	600 $\pm$ 190 \\\hline
	Diboson &	30 $\pm$ 5 &	50 $\pm$ 80&	260 $\pm$ 28 \\\hline
	Single-top &	300 $\pm$ 60 &	400 $\pm$ 70 &	5800 $\pm$ 1000 \\\hline
	$t\bar{t}$ &	2000 $\pm$ 50&	2041.48 $\pm$ 70 &	58000 $\pm$600 \\\hline
	$W$+jets &	600 $\pm$ 80 &	1100 $\pm$ 90 &	12000 $\pm$ 900 \\\hline
	$Z$+jets &	13 $\pm$ 1 &	23 $\pm$ 2 &	320 $\pm$ 33 \\\hline
	Total &	2600 $\pm$ 100 &	3600 $\pm$ 130 &	78000 $\pm$ 1500 \\\hline
	Data &	2565 &	3546 &	77973 \\\hline
\end{tabular}}

% Postfit L1 GGF TCR Untag
\resizebox{\textwidth}{!}
{\begin{tabular}{|l|c|c|c|}
\hline
	  &	 HP Untagged TCR &	 LP Untagged TCR &	Resolved Untagged TCR \\\hline
%	HVT W' &	0.75 $\pm$ 1.87 &	0.33 $\pm$ 0.81 &	0.10 $\pm$ 0.25 \\\hline
	Electron Multi-jet &	- &	- &	- \\\hline
	Muon Multi-jet &	- &	- &	- \\\hline
	Diboson &	290 $\pm$ 28 &	350 $\pm$ 36 &	700$\pm$ 70 \\\hline
	Single-top &	3100 $\pm$ 540 &	2300 $\pm$ 390 &	9600 $\pm$ 1700\\\hline
	$t\bar{t}$ &	31000 $\pm$ 560 &	30000 $\pm$ 400 &	92000 $\pm$ 1700 \\\hline
	$W$+jets &	2200 $\pm$ 18 &	4900 $\pm$ 28 &	16000 $\pm$ 110 \\\hline
	$Z$+jets &	70 $\pm$ 7 &	160 $\pm$ 16 &	580 $\pm$ 60 \\\hline
	Total &	37000 $\pm$ 780&	35000 $\pm$ 570&	120000 $\pm$ 2400 \\\hline
	Data &	36677 &	34573 &	118928 \\\hline
\end{tabular}}

% Postfit L1 GGF TCR Tag
\resizebox{\textwidth}{!}
{\begin{tabular}{|l|c|c|c|}
\hline
	  &	 HP Tagged TCR &	 LP Tagged TCR &	Resolved Tagged TCR \\\hline
%	HVT W' &	0.12 $\pm$ 0.31 &	0.05 $\pm$ 0.13 &	0.02 $\pm$ 0.04 \\\hline
	Electron Multi-jet &	- &	- &	- \\\hline
	Muon Multi-jet &	- &	- &	- \\\hline
	Diboson &	10 $\pm$ 1 &	9 $\pm$ 1 &	30 $\pm$ 5\\\hline
	Single-top &	110 $\pm$ 21 &	120 $\pm$ 23 &	660 $\pm$ 130 \\\hline
	$t\bar{t}$ &	2000 $\pm$ 50 &	1500 $\pm$ 47 &	18000 $\pm$ 190 \\\hline
	$W$+jets &	30$\pm$ 4 &	90 $\pm$ 7 &	490 $\pm$ 37 \\\hline
	$Z$+jets &	1 $\pm$ 1 &	2 $\pm$ 1 &	19 $\pm$ 2 \\\hline
	Total &	2100 $\pm$ 50 &	1700 $\pm$ 50 &	19000 $\pm$ 230 \\\hline
	Data &	2047 &	1708 &	19143 \\\hline
\end{tabular}}

\caption{Expected and Measured for DY $WZ$ $W$+jets, $t\bar{t}$ tag and untag control regions.}
\label{tbl:hvtwz_yields_cr}
\end{table}

\begin{table}
\resizebox{\textwidth}{!}
% Postfit L1 GGF SR Untag
{\begin{tabular}{|l|c|c|c|}
\hline
	  &	 HP Untagged SR &	 LP Untagged SR &	Resolved Untagged SR \\\hline
%	HVT W' &	13.08 $\pm$ 32.55 &	5.65 $\pm$ 14.09 &	3.73 $\pm$ 9.29 \\\hline
	Electron Multi-jet &	- &	- &	7800 $\pm$ 1200 \\\hline
	Muon Multi-jet &	- &	- &	17004.81 $\pm$ 1834.40 \\\hline
	Diboson &	3000 $\pm$ 270 &	2300 $\pm$ 210 &	15000 $\pm$ 1200 \\\hline
	Single-top &	2100 $\pm$ 370 &	1400 $\pm$ 240 &	18000 $\pm$ 3100\\\hline
	$t\bar{t}$ &	12000 $\pm$ 210 &	8900 $\pm$ 140 &	110000 $\pm$ 2100 \\\hline
	$W$+jets &	23000 $\pm$ 190&	42000 $\pm$ 240 &	340000 $\pm$ 2300 \\\hline
	$Z$+jets &	400 $\pm$ 40 &	800 $\pm$ 90 &	10000 $\pm$ 1000 \\\hline
	Total &	40000 $\pm$ 550 &	55000 $\pm$ 430 &	520000 $\pm$ 5100 \\\hline
	Data &	40193 &	54735 &	521813 \\\hline
\end{tabular}}

% Postfit L1 GGF SR Tag
\resizebox{\textwidth}{!}
{\begin{tabular}{|l|c|c|c|}
\hline
	  &	 HP Tagged SR &	 LP Tagged SR &	Resolved Tagged SR \\\hline
%	HVT W' &	2.20 $\pm$ 5.48 &	1.01 $\pm$ 2.53 &	1.00 $\pm$ 2.48 \\\hline
	Electron Multi-jet &	- &	- &	200 $\pm$ 30 \\\hline
	Muon Multi-jet &	- &	- &	393.43 $\pm$ 124.06 \\\hline
	Diboson &	100 $\pm$ 12 &	65 $\pm$ 8 &	620 $\pm$ 58 \\\hline
	Single-top &	180 $\pm$ 34 &	160$\pm$ 29 &	3500 $\pm$ 620 \\\hline
	$t\bar{t}$ &	1000 $\pm$ 32 &	710 $\pm$ 26 &	38000 $\pm$ 4000 \\\hline
	$W$+jets &	300 $\pm$ 40 &	580 $\pm$ 40 &	6000 $\pm$ 500 \\\hline
	$Z$+jets &	8 $\pm$ 1 &	12 $\pm$ 1 &	180 $\pm$ 19 \\\hline
	Total &	2000 $\pm$ 60 &	2000 $\pm$ 60 &	50000 $\pm$ 900 \\\hline
	Data &	1699 &	1559 &	48919 \\\hline
\end{tabular}}
\caption{Expected and Measured for DY $WZ$ $W$+jets, $t\bar{t}$ tag and untag signal regions.}
\label{tbl:hvtwz_yields_tcr}
\end{table}

\begin{table}
% Postfit L1 VBF WCR
\resizebox{\textwidth}{!}
{\begin{tabular}{|l|c|c|c|}
\hline
	  &	 HP WCR &	 LP WCR &	Resolved WCR \\\hline
	%HVT VBF Z' &	6.05 $\pm$ 2.78 &	12.08 $\pm$ 8.55 &	1.62 $\pm$ 0.72 \\\hline
	Electron Multi-jet &	- &	- &	900 $\pm$ 140 \\\hline
	Muon Multi-jet &	- &	- &	601.46 $\pm$ 182.74 \\\hline
	Diboson &	100 $\pm$ 45 &	170 $\pm$ 68 &	290 $\pm$ 240 \\\hline
	Single-top &	78 $\pm$ 18 &	130 $\pm$ 32 &	880 $\pm$ 220 \\\hline
	$t\bar{t}$ &	400 $\pm$ 28 &	570 $\pm$ 49 &	5100 $\pm$ 160 \\\hline
	$W$+jets &	900 $\pm$ 60 &	1900$\pm$ 90 &	19000 $\pm$ 400 \\\hline
	$Z$+jets &	20 $\pm$ 2 &	47 $\pm$ 5 &	800 $\pm$ 80 \\\hline
	Total &	2000$\pm$ 80 &	2900 $\pm$ 130 &	27000 $\pm$ 60 \\\hline
	Data &	1495 &	2898 &	27120 \\\hline
\end{tabular}}

% Postfit L1 VBF TCR
\resizebox{\textwidth}{!}
{\begin{tabular}{|l|c|c|c|}
\hline
	  &	 HP TCR &	 LP TCR &	Resolved TCR \\\hline
%	HVT VBF Z' &	1.84 $\pm$ 0.72 &	1.15 $\pm$ 0.57 &	0.62 $\pm$ 0.28 \\\hline
	Electron Multi-jet &	- &	- &	- \\\hline
	Muon Multi-jet &	- &	- &	- \\\hline
	Diboson &	10 $\pm$ 7 &	28 $\pm$ 14 &	24 $\pm$ 20\\\hline
	Single-top &	68 $\pm$ 16 &	59 $\pm$ 14 &	300 $\pm$ 70 \\\hline
	$t\bar{t}$ &	500 $\pm$ 30 &	400 $\pm$ 32 &	3800 $\pm$ 100 \\\hline
	$W$+jets &	51 $\pm$ 4 &	140 $\pm$ 8&	450 $\pm$ 12 \\\hline
	$Z$+jets &	1 $\pm$ 1 &	5 $\pm$ 1 &	30 $\pm$ 3 \\\hline
	Total &	600 $\pm$ 40&	637.10 $\pm$ 40 &	5000 $\pm$ 130 \\\hline
	Data &	636 &	634 &	4615 \\\hline
\end{tabular}}

% Postfit L1 VBF SR
\resizebox{\textwidth}{!}
{\begin{tabular}{|l|c|c|c|}
\hline
	  &	 HP SR &	 LP SR &	Resolved SR \\\hline
%	HVT VBF Z' &	38.90 $\pm$ 15.11 &	19.28 $\pm$ 9.38 &	20.33 $\pm$ 8.96 \\\hline
	Electron Multi-jet &	- &	- &	600$\pm$ 90 \\\hline
	Muon Multi-jet &	- &	- &	481.01 $\pm$ 144.48 \\\hline
	Diboson &	150 $\pm$ 49&	180 $\pm$ 67 &	400 $\pm$ 320 \\\hline
	Single-top &	80 $\pm$ 20 &	57 $\pm$ 15 &	780 $\pm$ 190 \\\hline
	$t\bar{t}$ &	340 $\pm$ 24 &	240$\pm$ 21 &	4300 $\pm$ 140 \\\hline
	$W$+jets &	500 $\pm$ 40 &	1300 $\pm$ 65 &	11000 $\pm$ 290 \\\hline
	$Z$+jets &	9$\pm$ 1 &	29 $\pm$ 3 &	570 $\pm$ 58 \\\hline
	Total &	1000 $\pm$ 70 &	2000 $\pm$ 100 &	20000 $\pm$ 500 \\\hline
	Data &	1096 &	1846 &	18530 \\\hline
\end{tabular}}
\caption{Expected and Measured for VBF $WW$ $W$+jets, $t\bar{t}$ control regions and signal regions.}
\label{tbl:hvtwvbf_yields_tcr}
\end{table}

\begin{table}

% Postfit L1 VBF WCR
\resizebox{\textwidth}{!}
{\begin{tabular}{|l|c|c|c|}
\hline
	  &	 HP WCR &	 LP WCR &	Resolved WCR \\\hline
%	HVT VBF W' &	3.57 $\pm$ 2.00 &	5.91 $\pm$ 4.43 &	1.90 $\pm$ 1.07 \\\hline
	Electron Multi-jet &	- &	- &	870 $\pm$ 130\\\hline
	Muon Multi-jet &	- &	- &	620 $\pm$ 200 \\\hline
	Diboson &	93 $\pm$ 42&	150 $\pm$ 64 &	230 $\pm$ 110 \\\hline
	Single-top &	71 $\pm$ 16 &	120 $\pm$ 28 &	1200 $\pm$ 280 \\\hline
	$t\bar{t}$ &	430 $\pm$ 30 &	500 $\pm$ 50 &	6900 $\pm$ 250 \\\hline
	$W$+jets &	870 $\pm$ 64 &	2000 $\pm$ 94 &	19000 $\pm$ 440 \\\hline
	$Z$+jets &	20 $\pm$ 2 &	47 $\pm$ 5 &	800 $\pm$ 80 \\\hline
	Total &	1500 $\pm$ 84 &	2800 $\pm$ 130 &	30000 $\pm$ 600 \\\hline
	Data &	1495 &	2898 &	29755 \\\hline
\end{tabular}}

% Postfit L1 VBF TCR
\resizebox{\textwidth}{!}
{\begin{tabular}{|l|c|c|c|}
\hline
	  &	 HP TCR &	 LP TCR &	Resolved TCR \\\hline
	%HVT VBF W' &	1.42 $\pm$ 0.75 &	0.79 $\pm$ 0.47 &	0.53 $\pm$ 0.30 \\\hline
	Electron Multi-jet &	- &	- &	- \\\hline
	Muon Multi-jet &	- &	- &	- \\\hline
	Diboson &	10 $\pm$ 5 &	13 $\pm$ 7 &	14 $\pm$ 7 \\\hline
	Single-top &	52 $\pm$ 12 &	35 $\pm$ 8 &	170 $\pm$ 45 \\\hline
	$t\bar{t}$ &	470 $\pm$ 29 &	300 $\pm$ 25 &	2400 $\pm$ 75 \\\hline
	$W$+jets &	50 $\pm$ 4 &	110 $\pm$ 6 &	380 $\pm$ 12 \\\hline
	$Z$+jets &	1 $\pm$ 1 &	5 $\pm$ 1 &	18 $\pm$ 2\\\hline
	Total &	580 $\pm$ 32 &	460 $\pm$ 28 &	3000 $\pm$ 90 \\\hline
	Data &	584 &	459 &	3001 \\\hline
\end{tabular}}

% Postfit L1 VBF SR
\resizebox{\textwidth}{!}
{\begin{tabular}{|l|c|c|c|}
\hline
	  &	 HP SR &	 LP SR &	Resolved SR \\\hline
	%HVT VBF W' &	27.77 $\pm$ 14.54 &	12.44 $\pm$ 7.29 &	17.01 $\pm$ 9.36 \\\hline
	Electron Multi-jet &	- &	- &	400 $\pm$ 70\\\hline
	Muon Multi-jet &	- &	- &	400 $\pm$ 130 \\\hline
	Diboson &	100 $\pm$ 40 &	110 $\pm$ 46 &	270 $\pm$ 140 \\\hline
	Single-top &	63$\pm$ 15&	48 $\pm$ 12 &	870 $\pm$ 210 \\\hline
	$t\bar{t}$ &	350 $\pm$ 24 &	190 $\pm$ 18 &	5100 $\pm$ 190 \\\hline
	$W$+jets &	500 $\pm$ 40 &	1000 $\pm$ 50 &	10000 $\pm$ 250 \\\hline
	$Z$+jets &	8 $\pm$ 1 &	24 $\pm$ 2 &	560 $\pm$ 57 \\\hline
	Total &	1000 $\pm$ 60 &	1000 $\pm$ 70 &	20000 $\pm$ 400 \\\hline
	Data &	1018 &	1313 &	17826 \\\hline
\end{tabular}}
\caption{Expected and Measured for VBF $WZ$ $W$+jets, $t\bar{t}$ control regions and signal regions.}
\label{tbl:hvwzvbf_yields}

\end{table}

\begin{table}
\begin{tabular}{|l|c|}
\hline
Background & Fitted Normalization \\\hline
XS\_Top\_LP\_lvqq\_Merg\_binned & $0.91^{+0.017}_{-0.017}$ \\\hline
XS\_Top\_Merg & $0.94^{+0.020}_{-0.020}$ \\\hline
XS\_Top\_Res & $0.96^{+0.013}_{-0.013}$ \\\hline
XS\_Wjets\_LP\_lvqq\_Merg\_binned & $0.88^{+0.0049}_{-0.0049}$ \\\hline
XS\_Wjets\_Merg & $0.9^{+0.008}_{-0.008}$ \\\hline
XS\_Wjets\_Res & $1.0^{+0.006}_{-0.006}$ \\\hline

\end{tabular}
\caption{Fitted background normalizations for $t\bar{t}$ and $W$+jets backgrounds for the DY $WW$ analysis region.}
\label{tbl:hvtww_norm}
\end{table}

\begin{table}
\begin{tabular}{|l|c|}
\hline
Background & Fitted Normalization \\\hline
XS\_Top\_LP\_Tag\_lvqq\_Merg\_binned & $0.97^{+0.033}_{-0.033}$ \\\hline
XS\_Top\_LP\_lvqq\_Merg\_binned & $0.89^{+0.014}_{-0.014}$ \\\hline
XS\_Top\_Merg & $0.89^{+0.016}_{-0.016}$ \\\hline
XS\_Top\_Res & $0.97^{+0.018}_{-0.018}$ \\\hline
XS\_Top\_Tag\_lvqq\_Merg\_binned & $0.95=^{+0.028}_{-0.028}$ \\\hline
XS\_Top\_Tag\_lvqq\_Res\_binned & $0.99^{+0.011}_{-0.011}$ \\\hline
XS\_Wjets\_LP\_Tag\_lvqq\_Merg\_binned & $0.91^{+0.070}_{-0.070}$ \\\hline
XS\_Wjets\_LP\_lvqq\_Merg\_binned & $0.88^{+0.0050}_{-0.0050}$ \\\hline
XS\_Wjets\_Merg & $0.95^{+0.008}_{-0.008}$ \\\hline
XS\_Wjets\_Res & $1.0^{+0.007}_{-0.007}$ \\\hline
XS\_Wjets\_Tag\_lvqq\_Merg\_binned & $0.91^{+0.12}_{-0.12}$ \\\hline
XS\_Wjets\_Tag\_lvqq\_Res\_binned & $1.2^{+0.090}_{-0.090}$ \\\hline
\end{tabular}
\caption{Fitted background normalizations for $t\bar{t}$ and $W$+jets backgrounds for the DY $WZ$ analysis region.}
\label{tbl:hvtwz_norm}
\end{table}

\begin{table}
\begin{tabular}{|l|c|}
\hline
Background & Fitted Normalization \\\hline
XS\_Top\_LP\_lvqq\_Merg\_binned & $0.79^{+0.067}_{-0.067}$ \\\hline
XS\_Top\_Merg & $0.89^{+0.061}_{-0.061}$ \\\hline
XS\_Top\_Res & $1.0^{+0.031}_{-0.031}$ \\\hline
XS\_Wjets\_LP\_lvqq\_Merg\_binned & $0.88^{+0.042}_{-0.042}$ \\\hline
XS\_Wjets\_Merg & $0.881^{+0.068}_{-0.068}$ \\\hline
XS\_Wjets\_Res & $0.93^{+0.020}_{-0.020}$ \\\hline
\end{tabular}
\caption{Fitted background normalizations for $t\bar{t}$ and $W$+jets backgrounds for the VBF $WW$ analysis region.}
\label{tbl:hvtwwvbf_norm}
\end{table}

\begin{table}
\begin{tabular}{|l|c|}
\hline
Background & Fitted Normalization \\\hline
XS\_Top\_LP\_lvqq\_Merg\_binned & $0.71^{+0.064}_{-0.064}$ \\\hline
XS\_Top\_Merg & $0.96^{+0.064}_{-0.064}$ \\\hline
XS\_Top\_Res & $1.0^{+0.04}_{-0.04}$ \\\hline
XS\_Wjets\_LP\_lvqq\_Merg\_binned & $0.9^{+0.044}_{-0.044}$ \\\hline
XS\_Wjets\_Merg & $0.88^{+0.069}_{-0.069}$ \\\hline
XS\_Wjets\_Res & $0.95^{+0.022}_{-0.022}$ \\\hline
\end{tabular}
\caption{Fitted background normalizations for $t\bar{t}$ and $W$+jets backgrounds for the VBF $WZ$ analysis region.}
\label{tbl:hvtwzvbf_norm}
\end{table}

\begin{figure}[h!]
  \centering
  \includegraphics[width=0.48\hsize]{figures/results/HVTWW/PlotyieldTable_postfit.pdf}
    \includegraphics[width=0.48\hsize]{figures/results/HVTWZ/PlotyieldTable_postfit.pdf}
 \caption{The distribution of $m_{\ell\nu qq}$ in the DY $WW(WZ)$ control regions on the left(right).}
  \label{fig:hvtww_cr_postfit}
\end{figure}
\FloatBarrier

\begin{figure}[h!]
  \centering
  \includegraphics[width=0.48\hsize]{figures/results/HVTWWVBF/PlotyieldTable_postfit.pdf}
    \includegraphics[width=0.48\hsize]{figures/results/HVTWZVBF/PlotyieldTable_postfit.pdf}
 \caption{The distribution of $m_{\ell\nu qq}$ in the VBF $WW(WZ)$ control regions.}
  \label{fig:hvtwz_cr_postfit}
\end{figure}
\FloatBarrier

\begin{figure}[h!]
  \centering
  \includegraphics[width=0.3\hsize]{figures/results/HVTWW/L1_MergHP_GGF_WW_SR.pdf}
    \includegraphics[width=0.3\hsize]{figures/results/HVTWW/L1_MergLP_GGF_WW_SR.pdf}
    \includegraphics[width=0.3\hsize]{figures/results/HVTWW/L1_Res_GGF_WW_SR.pdf}
 \caption{The distribution of $m_{\ell\nu qq}$ in the GGF $WW$ signal regions.}
  \label{fig:hvtww_sr_postfit}
\end{figure}
\FloatBarrier

\begin{figure}[h!]
  \centering
  \includegraphics[width=0.3\hsize]{figures/results/HVTWZ/L1_MergHP_GGF_WZ_Untag_SR.pdf}
    \includegraphics[width=0.3\hsize]{figures/results/HVTWZ/L1_MergLP_GGF_WZ_Untag_SR.pdf}
    \includegraphics[width=0.3\hsize]{figures/results/HVTWZ/L1_Res_GGF_WZ_Untag_SR.pdf}
 \caption{The distribution of $m_{\ell\nu qq}$ in the GGF $WZ$ Untag signal regions.}
  \label{fig:hvtwz_untag_sr_postfit}
\end{figure}
\FloatBarrier

\begin{figure}[h!]
  \centering
  \includegraphics[width=0.3\hsize]{figures/results/HVTWZ/L1_MergHP_GGF_WZ_Tag_SR.pdf}
    \includegraphics[width=0.3\hsize]{figures/results/HVTWZ/L1_MergLP_GGF_WZ_Tag_SR.pdf}
    \includegraphics[width=0.3\hsize]{figures/results/HVTWZ/L1_Res_GGF_WZ_Tag_SR.pdf}
 \caption{The distribution of $m_{\ell\nu qq}$ in the GGF $WZ$ Tag signal regions.}
  \label{fig:hvtwz_tag_sr_postfit}
\end{figure}
\FloatBarrier

\begin{figure}[h!]
  \centering
  \includegraphics[width=0.3\hsize]{figures/results/HVTWWVBF/L1_MergHP_VBF_WW_SR.pdf}
    \includegraphics[width=0.3\hsize]{figures/results/HVTWWVBF/L1_MergLP_VBF_WW_SR.pdf}
    \includegraphics[width=0.3\hsize]{figures/results/HVTWWVBF/L1_Res_VBF_WW_SR.pdf}
 \caption{The distribution of $m_{\ell\nu qq}$ in the VBF $WW$ Tag signal regions.}
  \label{fig:hvtwwvbf_tag_sr_postfit}
\end{figure}
\FloatBarrier

\begin{figure}[h!]
  \centering
  \includegraphics[width=0.3\hsize]{figures/results/HVTWZVBF/L1_MergHP_VBF_WZ_SR.pdf}
    \includegraphics[width=0.3\hsize]{figures/results/HVTWZVBF/L1_MergLP_VBF_WZ_SR.pdf}
    \includegraphics[width=0.3\hsize]{figures/results/HVTWZVBF/L1_Res_VBF_WZ_SR.pdf}
 \caption{The distribution of $m_{\ell\nu qq}$ in the VBF $WZ$ Tag signal regions.}
  \label{fig:hvtwzvbf_tag_sr_postfit}
\end{figure}
\FloatBarrier

\section{Systematic Profiling and Correlations}
The ranked systematics, in terms of their impact on $\hat{\mu}$, and their fitted values are shown for the different analysis regions in Figure \ref{fig:hvtww_ranking} and \ref{fig:hvtwz_ranking}. Note that background normalizations for $W$+jets and $t\bar{t}$ are left free to float in the fit. This means the nominal normalization values are one and the uncertainties are not shown in the ranked plots. Overall, systematics are not pulled outside their uncertainties, especially nuisance parameters that affect $\hat{\mu}$ most significantly.

The correlation between systematics are shown in Figure \ref{fig:hvtww_corr}. Correlations between background normalization are expected. The remaining systematic correlations are not very strong or unexpected.
\begin{figure}[h!]
  \centering
  \includegraphics[width=0.48\hsize]{figures/results/HVTWW/ranking_data/nov7_hvtww_2000gev/ranking.pdf}
    \includegraphics[width=0.48\hsize]{figures/results/HVTWWVBF/ranking_data/nov7_hvtwwvbf_1000gev/ranking.pdf}
 \caption{Ranked systematics and their fitted values for $WW$ DY (right) and VBF (left) selections.}
  \label{fig:hvtww_ranking}
\end{figure}
\FloatBarrier

\begin{figure}[h!]
  \centering
  \includegraphics[width=0.48\hsize]{figures/results/HVTWZ/ranking_data/nov7_hvtwz_1000gev/ranking.pdf}
    \includegraphics[width=0.48\hsize]{figures/results/HVTWZVBF/ranking_data/nov7_hvtwzvbf_1000gev/ranking.pdf}
 \caption{Ranked systematics and their fitted values for $WZ$ DY (right) and VBF (left) selections.}
  \label{fig:hvtwz_ranking}
\end{figure}
\FloatBarrier

\begin{figure}[h!]
  \centering
  \includegraphics[width=0.48\hsize]{figures/Results/HVTWW/HVTWW_combined_1nov8_maybeFloatRelevantUncorrXSSingleBinPrunSyst/Plots/CorrMatrix/corr_doAsimov0_doCondtional1_mu0_HighCorr.png}
   \includegraphics[width=0.48\hsize]{figures/Results/HVTWWVBF/HVTWWVBF_combined_1nov8_maybeFloatRelevantUncorrXSSingleBinPrunSyst/Plots/CorrMatrix/corr_doAsimov0_doCondtional1_mu0_HighCorr.pdf}
 \caption{Correlations between systematics for $WW$ DY (right) and VBF (left) selections.}
  \label{fig:hvtww_corr}
\end{figure}
\FloatBarrier

\section{Discovery Tests}
\label{discovery}
To test for the existence of signal in the observed dataset, the discovery tests discussed earlier are used to calculate $p$-values as a function of resonance mass. The results of these tests are shown in Figures \ref{fig:discov_hvtww} - \ref{fig:discov_rsg}. The largest non-VBF excesses are $2.2\sigma$ at 600~GeV and $1.8\sigma$ at 2~TeV for HVT $Z'$. The largest VBF excess is $2.6\sigma$ for HVT $Z'$ 1~TeV resonance.
 \begin{figure}[h!]
  \centering
  \includegraphics[width=0.48\hsize]{figures/results/pvalues/fixed_pvalues/hvtww_pvalue.pdf}
    \includegraphics[width=0.48\hsize]{figures/results/pvalues/fixed_pvalues/hvtwwvbf_pvalue.pdf}
 \caption{These plots show the measured $p_{0}$ value as a function of resonance mass for HVT Z' DY(VBF) production, left(right).}
  \label{fig:discov_hvtww}
\end{figure}
\FloatBarrier

\begin{figure}[h!]
  \centering
  \includegraphics[width=0.48\hsize]{figures/results/pvalues/fixed_pvalues/hvtwz_pvalue.pdf}
    \includegraphics[width=0.48\hsize]{figures/results/pvalues/fixed_pvalues/hvtwzvbf_pvalue.pdf}
 \caption{These plots show the measured $p_{0}$ value as a function of resonance mass for HVT W' DY(VBF) production, left(right).}
  \label{fig:discov_hvtwz}
\end{figure}
\FloatBarrier

\begin{figure}[h!]
  \centering
  \includegraphics[width=0.48\hsize]{figures/results/pvalues/fixed_pvalues/rsg_pvalue.pdf}
 \caption{These plots show the measured $p_{0}$ value as a function of resonance mass for the RS Graviton DY production.}
  \label{fig:discov_rsg}
\end{figure}
\FloatBarrier

\section{Limits}
As the deviations from the background only hypothesis do not constitute discoveries from \ref{discovery}, upper limits on $\mu$ are calculated. Using the exclusion limits tests discussed previously, exclusion limits are set on $\mu$ and consequently signal cross-sections. Exclusion limits for the models considered are shown in Figure \ref{fig:hvtww_limit} - \ref{fig:rsg_limit}. These plots show the theory cross section for a given resonance to decay to $WW/WZ$. An Asimov dataset is used to expected calculate the limits (assuming no new physics contributions) with the associated errors, shown as the black dashed lines with the green and yellow error bands. Finally, the observed limits are shown in black. All signal masses where the theory prediction is less than the observed prediction are excluded. These limits shown exclude HVT Model A W' $< 3.4$ TeV and Z' $< 3.3$ TeV and Model B W' $< 3.7$ TeV and Z'$ < 3.7$ TeV. RS Gravitons are excluded for masses below 1.6~TeV .

\begin{figure}[h!]
  \centering
  \includegraphics[width=0.48\hsize]{figures/results/limits/limits_hvtww.pdf}
  \includegraphics[width=0.48\hsize]{figures/results/limits/limits_hvtwwvbf.pdf}

 \caption{Theory, expected and observed limits for HVT $W'$ DY (left) and VBF (right) production.}
  \label{fig:hvtww_limit}
\end{figure}
\FloatBarrier

\begin{figure}[h!]
  \centering
  \includegraphics[width=0.48\hsize]{figures/results/limits/limits_hvtwz.pdf}
  \includegraphics[width=0.48\hsize]{figures/results/limits/limits_hvtwzvbf.pdf}

 \caption{Theory, expected and observed limits for HVT $Z'$ DY (left) and VBF (right) production.}
  \label{fig:hvtwz_limit}
\end{figure}
\FloatBarrier

\begin{figure}[h!]
  \centering
  \includegraphics[width=0.48\hsize]{figures/results/limits/limits_rsg.pdf}

 \caption{Theory, expected and observed limits for RS Gravitons via gluon-gluon fusion production.}
  \label{fig:rsg_limit}
\end{figure}
\FloatBarrier


\documentclass[12pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{amsthm}
\usepackage[left=2cm,right=2cm,top=2cm,bottom=2cm]{geometry}
\usepackage{enumitem}
\usepackage{tikz}
\usepackage{tikz-cd}
\usepackage{url}

\title{Mathematical software - homework 2}
\author{Sebastiano Tronto}

\newtheorem{thm}{Theorem}
\newtheorem{prop}[thm]{Proposition}

\theoremstyle{definition}
\newtheorem{ex}{Exercise}

\theoremstyle{definition}
\newtheorem*{remark}{Remark}

\newcommand{\bs}{\textbackslash}

\begin{document}

\noindent\hrulefill

\begin{center}
\Huge{\textbf{Mathematical Software - Homework 2}}
\end{center}

\noindent\hrulefill
\begin{center}
\begin{tabular}{lcr}
\texttt{sebastiano.tronto@uni.lu} & \qquad \qquad \qquad \qquad &
\textbf{Deadline: Sunday, April 18th}
\end{tabular}
\end{center}

\vspace{1cm}

\begin{center}
  \emph{\large
    For each of the following exercises submit a .tex and a .pdf file.
  }
\end{center}

\vspace{1cm}

\begin{ex}
  Create a Latex document containing the following pictures:
  \begin{enumerate}[label=(\alph*)]
    \item The regular polygon with $N$-sides centered at the origin of the
          plane (see below).
          The number $N$ of sides must be easy to change at will: you should
          use the \texttt{\textbackslash pgfmathsetmacro} command to set a
          value for $N$ at the beginning, so that changing only that number
          makes the whole picture change accordingly.
      \begin{center}
        \begin{tikzpicture}[scale=1]
        	\pgfmathsetmacro{\N}{6}
        	\pgfmathsetmacro{\an}{360/\N}
        	\pgfmathsetmacro{\r}{4}

        	\draw[lightgray!30,thin] (-6,-6) grid (6,6);
        	\draw[->] (-5,0) -- (5,0);
        	\draw[->] (0,-5) -- (0,5);

        	\filldraw[draw=green,fill=green!30,thick] (0.3*\r,0)
        	  arc[radius=0.3*\r,start angle=0, end angle=\an]
        	  -- node[right] {$\alpha=\an$}(0,0) --  cycle;
        	\draw[thin] (\an:\r) -- (0,0) circle[radius=\r] -- (\r,0);
        	\draw[line width=1.1pt]
        	  (\r,0)  \foreach \x in {1,2,...,\N} { -- (\x*\an:\r) };
        	\foreach \x in {1,...,\N} {
        		\filldraw[red] (\x*\an:\r) circle[radius=0.1];
        	};
        \end{tikzpicture}
      \end{center}
    \item The following commutative diagram:
      \begin{tikzcd}
        0 \ar[r] & A' \ar[r,hook] \ar[d] & A \ar[r,two heads] \ar[d,"\sim"] &
          A'' \ar[r] \ar[d] \ar[l,dashed,"s"',bend right] & 0 \\
        0 \ar[r] & A' \ar[r,hook,"i_{A'}"'] & A'\oplus A''
          \ar[r,two heads,"\pi_{A''}"'] & A'' \ar[r] & 0
      \end{tikzcd}
  \end{enumerate}
\end{ex}

\vspace{0.8cm}

\begin{ex}
  Suppose you have to give a short presentation (10 minutes) on a topic of
  your choice related to your study programme (you will not be asked to
  actually perform this presentation). You can choose to talk about a theorem
  you find important, a result you have seen in class or something else (see
  below for a list of possible topics). For example, if you talk about an
  important theorem you can give the theorem statement, explain why this
  theorem is important and/or possible applications of this result, and
  optionally an idea of the proof; but you can also deviate from this and talk
  for example about the historical background that lead to the development of
  this theorem.

  Your task is to prepare slides for such a presentation using Beamer (Latex).
  Since the time for the (imaginary) presentation is very short, you should
  write 5-8 slides (you can have more if some contain very few or no
  words).

  If you feel like certain slides do not make sense without your explanation
  (for example if you have one slide with just one picture and you plan to
  talk with the picture in background), you can write some comments in the
  .tex file.

  If you can't think of a topic that you like, you can pick one of the
  following:
  \begin{itemize}
    \item The fundamental theorem of arithmetic (about prime numbers)
    \item The central limit theorem (probability theory)
    \item Differential equations (what they are, applications,
          methods to solve them...)
  \end{itemize}
\end{ex}

\newpage
\section*{Grading}

This homework assignment is worth 25\% of your final grade.

\vspace{0.3cm}
\noindent\textbf{Exercise 1 (10 points).}
Part (a) is worth 5 points, divided as follows:
\begin{itemize}
  \item 3 points for obtaining a regular polygon whose number of sides
        can be changed by setting a variable with \texttt{\bs pgfmathsetmacro}
        (or in a similarly easy way).
  \item 1.5 points for other features of the picture (verteces, angle) that
        also change accordingly to the same variable.
  \item 0.5 points for the style of the other elements of the picture. This is
        a matter of personal preference and it does not need to be exactly the
        same as the picture, but some key features should remain (e.g.
        the grid lines should be less visible than the rest of the picture,
        the circle line style should be different from the polygon).
\end{itemize}
Part (b) is worth 5 points, divided as follows:
\begin{itemize}
  \item 3 points if the nodes and arrows of the diagram are correct from a
        mathematical point of view (that is, the arrows point to the correct
        object).
  \item 1 point if the labels of the arrows are placed as shown in the picture
        above.
  \item 1 point for the correct style of the arrows (dashed, curved).
\end{itemize}

\vspace{0.2cm}
\noindent\textbf{Exercise 2 (10 points).}
\begin{itemize}
  \item Producing a presentation that contains at least 4 slides is worth
        5 points (but within reason: for example, the slides must not be empty).
  \item Up to 3 more points are given if the presentation is of a suitable
        length (watch out: both a presentation too short and one too long can
        loose points!).
        Comments in the .tex file can help me understand how long you plan to
        spend on each slide. If you are not sure how long your presentation is
        going to take, try it and write down how long each slide took.
  \item Up to 2 more points will be given if the slides ``look nice'' from
        the audience's perspective (e.g. not too many words on the same slides,
        are there nice pictures, etc).
\end{itemize}

\end{document}


\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{More Basic Python}
\author[FOSSEE] {FOSSEE}
\institute[IIT Bombay] {Department of Aerospace Engineering\\IIT Bombay}
\date []{}

\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}

\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}
  \frametitle{Modules}
  \begin{itemize}
      \item Organize your code
      \item Collect similar functionality
      \item Functions, classes, constants, etc.
  \end{itemize}
\end{frame}

\begin{frame}
  \frametitle{Modules}
  \begin{itemize}
  \item Define variables, functions and classes in a file with a
    \texttt{.py} extension
  \item This file becomes a module!
  \item The \texttt{import} keyword ``loads'' a module
  \item One can also use:
    \mbox{\texttt{from module import name1, name2, name2}}\\
    where \texttt{name1} etc. are names in the module, ``module''
  \item \texttt{from module import *} \ --- imports everything from module,
    \alert{use only in interactive mode}
    \item File name should be valid variable name
  \end{itemize}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Modules: example}
  \begin{lstlisting}
# --- foo.py ---
some_var = 1
def fib(n): # write Fibonacci series up to n
    """Print a Fibonacci series up to n."""
    a, b = 0, 1
    while b < n:
        print b,
        a, b = b, a+b
# EOF
  \end{lstlisting}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Modules: example}
  \begin{lstlisting}
>>> import foo
>>> foo.fib(10)
1 1 2 3 5 8
>>> foo.some_var
1
  \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
  \item Can also set \texttt{PYTHONPATH} env var
  \end{itemize}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Another example: 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{\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}

\begin{frame}[fragile]
  \frametitle{Stand-alone scripts}
Consider a file \texttt{f.py}:
\footnotesize
\begin{lstlisting}
#!/usr/bin/env python
"""Module level documentation."""
# First line tells the shell that it should use Python
# to interpret the code in the file.
def f():
    print "f"

# Check if we are running standalone or as module.
# When imported, __name__ will not be '__main__'
if __name__ == '__main__':
    # This is not executed when f.py is imported.
    f()
\end{lstlisting}
\end{frame}

\section{Exceptions}

\begin{frame}{Motivation}
    \begin{itemize}
        \item How do you signal errors to a user?
    \end{itemize}
\end{frame}

\begin{frame}
  \frametitle{Exceptions}
  \begin{itemize}
  \item Python's way of notifying you of errors
  \item Several standard exceptions: \texttt{SyntaxError}, \texttt{IOError}
    etc.
  \item Users can also \texttt{raise} errors
  \item Users can create their own exceptions
  \item Exceptions can be ``caught'' via \texttt{try/except} blocks
  \end{itemize}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Exception: examples}
\begin{lstlisting}
>>> 10 * (1/0)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ZeroDivisionError: integer division or modulo by zero
>>> 4 + spam*3
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: cannot concatenate 'str' and 'int' objects
\end{lstlisting}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Exception: examples}
\begin{lstlisting}
>>> while True:
...     try:
...         x = int(raw_input("Enter a number: "))
...         break
...     except ValueError:
...         print "Invalid number, try again..."
...
>>> # To raise exceptions
... raise ValueError("your error message")
Traceback (most recent call last):
  File "<stdin>", line 2, in ?
ValueError: your error message
\end{lstlisting}
\end{frame}

\begin{frame}[fragile]
  \frametitle{Exception: try/finally}
\begin{lstlisting}
>>> while True:
...     try:
...         x = open("my_data.txt")
...         lines = x.readlines()
...         # Process the data from the file.
...         value = int(line[0])
...     except ValueError:
...         print "Invalid file!"
...     finally:
...         print "All good!"
...
\end{lstlisting}
\end{frame}

\end{document}