%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Short Sectioned Assignment
% LaTeX Template
% Version 1.0 (5/5/12)
%
% This template has been downloaded from:
% http://www.LaTeXTemplates.com
%
% Original author:
% Frits Wenneker (http://www.howtotex.com)
%
% License:
% CC BY-NC-SA 3.0 (http://creativecommons.org/licenses/by-nc-sa/3.0/)
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%----------------------------------------------------------------------------------------
%	PACKAGES AND OTHER DOCUMENT CONFIGURATIONS
%----------------------------------------------------------------------------------------

\documentclass[paper=a4, fontsize=11pt]{scrartcl} % A4 paper and 11pt font size
\usepackage{amsmath,amsfonts,graphicx}
\usepackage{lastpage}	% Required to determine the last page for the footer
\usepackage{booktabs}
%\usepackage{algpseudocode}
\usepackage{tikz}
\usepackage{algorithm}
\usepackage{algorithmicx}
\usepackage{algpseudocode}
\usepackage[top=2cm, bottom=2cm, left=2cm, right=2cm]{geometry}

\usepackage{listings}
\usepackage{color}
\usepackage{xcolor}
\definecolor{dkgreen}{rgb}{0,0.6,0}
\definecolor{gray}{rgb}{0.5,0.5,0.5}
\definecolor{mauve}{rgb}{0.58,0,0.82}
\lstset{frame=tb,
     %language=Java,
     aboveskip=3mm,
     belowskip=3mm,
     showstringspaces=false,
     columns=flexible,
     basicstyle = \ttfamily\small,
     numbers=none,
     numberstyle=\tiny\color{gray},
     keywordstyle=\color{blue},
     commentstyle=\color{dkgreen},
     stringstyle=\color{mauve},
     breaklines=true,
     breakatwhitespace=true,
     tabsize=3
}

%\usepackage[]{algorithm2e}

\usepackage[T1]{fontenc} % Use 8-bit encoding that has 256 glyphs
\usepackage{fourier} % Use the Adobe Utopia font for the document - comment this line to return to the LaTeX default
\usepackage[english]{babel} % English language/hyphenation
\usepackage{amsmath,amsfonts,amsthm} % Math packages

\usepackage{lipsum} % Used for inserting dummy 'Lorem ipsum' text into the template

\usepackage{sectsty} % Allows customizing section commands
\allsectionsfont{\centering \normalfont\scshape} % Make all sections centered, the default font and small caps

\usepackage{fancyhdr} % Custom headers and footers
    \pagestyle{fancyplain} % Makes all pages in the document conform to the custom headers and footers
    \fancyhead[L]{\textsc{COMP90038 Assignment 2}}
    \fancyhead[R]{\textsc{Student Number: 955986 }} % No page header - if you want one, create it in the same way as the footers below
    \fancyfoot[L]{} % Empty left footer
    \fancyfoot[C]{} % Empty center footer
    \fancyfoot[R]{\textsc{Page} \thepage \textsc{ of} \pageref{LastPage}} % Page numbering for right footer
    \renewcommand{\headrulewidth}{0pt} % Remove header underlines
    \renewcommand{\footrulewidth}{0pt} % Remove footer underlines
    \setlength{\headheight}{13.6pt} % Customize the height of the header

\numberwithin{equation}{section} % Number equations within sections (i.e. 1.1, 1.2, 2.1, 2.2 instead of 1, 2, 3, 4)
\numberwithin{figure}{section} % Number figures within sections (i.e. 1.1, 1.2, 2.1, 2.2 instead of 1, 2, 3, 4)
\numberwithin{table}{section} % Number tables within sections (i.e. 1.1, 1.2, 2.1, 2.2 instead of 1, 2, 3, 4)

\setlength\parindent{0pt} % Removes all indentation from paragraphs - comment this line for an assignment with lots of text

%----------------------------------------------------------------------------------------
%	TITLE SECTION
%----------------------------------------------------------------------------------------

\newcommand{\horrule}[1]{\rule{\linewidth}{#1}} % Create horizontal rule command with 1 argument of height

\title{
\normalfont \normalsize
\textsc{The University of Melbourne } \\ [25pt] % Your university, school and/or department name(s)
\horrule{0.5pt} \\[0.4cm] % Thin top horizontal rule
\huge COMP90038  Algorithms and Complexity SM2, 2018
Assignment 2 \\ % The assignment title
\horrule{2pt} \\[0.5cm] % Thick bottom horizontal rule
}

\author{Peiyong Wang $\,$ 955986 } % Your name

\date{\normalsize\today} % Today's date or a custom date

\begin{document}

\maketitle % Print the title
\thispagestyle{empty}%no head or foot on the first page

\section{Problem One}
See Figure 1.1.

\begin{figure}[htbp!]
		\centering
		\includegraphics[width=0.9\textwidth]{f1.png}
		\caption{Answer for Problem 1}%\label{book}
		\vspace{-1em}
\end{figure}

\section{Problem Two}
\paragraph{a}

See Algorithm 1.

The time complexity of Algorithm 1 should be O($min(mlog_2m+nlog_2m, mlog_2n+nlog_2n)$), where m and n are the size of X and Y, respectively.
\begin{algorithm}
	\caption{Find intersections of two sets with sorting}
	\begin{algorithmic}[1]
		\Require Two sets of integers X and Y
		\Function{FindSetIntersection}{$X, Y$}
            \State I = [] \Comment initialize the intersection as empty
            \If{$X.size \geq Y.size$}
            \State smallArray = \Call{MergeSort}{Y}
            \State largeArray = X
            \Else
            \State smallArray = \Call{MergeSort}{X}
            \State largeArray = Y

            \EndIf

            \For{every element c in largeArray}
            \State searchResult = \Call{BinSearch}{smallArray, smallArray.size,c}
            \State \Comment Call the BinSearch algorithm from lecture 10.
            \If{searchResult is not -1} \Comment If c exists in smallArray
            \State I.append(c) \Comment copy c to I

            \EndIf

            \EndFor
            \State \Return{ I}

		\EndFunction
	\end{algorithmic}

\end{algorithm}

\paragraph{b}
See Algorithm 2.

The time complexity of Algorithm 2 should be $ O(m+n)$, where m and n are the size of X and Y, respectively.

\begin{algorithm}
	\caption{Find intersections of two sets with hashing}
	\begin{algorithmic}[1]
		\Require Two sets of integers X and Y
		\Function{FindSetIntersection}{$X, Y$}
            \State I = [] \Comment initialize the intersection as empty
            \State S = \Call{HashSet}{}()\Comment initialize an empty hash set
            \For{every x in X }
            \State S.add(x)

            \EndFor
            \For{every y in Y }
            \If{S.contains(y)}
            \State I.append(y)

            \EndIf

            \EndFor
            \State \Return{ I}

		\EndFunction
	\end{algorithmic}

\end{algorithm}

\section{Problem Three}
See Algorithm 3.

For a node i with children [1,2,3,...,n], of which childern 1 needs the most time to pass the message to all its childern and childern n needs the least time to pass the message to all its childern. So we can get through mathematical induction that the time that node i needs to pass the message to all its childern T(i) = n + max(T(n), T(n-1)-1, T(n-2)-2,...,T(1)-(n-1))

Time complexity is O($n^2logn$).

\begin{algorithm}
	\caption{ compute the minimumnumber of days required for the decision to be disclosed to all employee}
	\begin{algorithmic}[1]
		\Require Employee tree C[][]
		\Function{MinDays}{C[][]}

            \State \Return{\Call{MinDaysForEmployeeI}{C[][],0}}

        \EndFunction
        \Function{MinDaysForEmployeeI}{C[][], i}
        \If{C[i][0] is 0}
        \State \Return{0}
        \EndIf
        \State childNodes = []\Comment initialize an empty to store child nodes of i
        \If{C[i][0] is not 0 }

        \State m = 1
        \While{C[i][m] is not -1}
        \State childNodes.append(C[i][m])
        \State  m = m+1

        \EndWhile
        \EndIf
        \State days = [\Call{MinDaysForEmployeeI}{C[][], x} for x in childNodes]
        \State days = \Call{QuickSort}{days}
        \For{j from 0 to days.length - 1}
        \State days[j] = days[j] - j

        \EndFor
        \State dayI = C[i][0] + \Call{Max}{days} \Comment function Max() has time complexity O($\frac{3n}{2}$)
        \State \Return{dayI}

        \EndFunction
	\end{algorithmic}

\end{algorithm}

\section{Problem Four}
\paragraph{a} See Algorithm 4. The time complexity should be O(n), where n is the length of input array.

\begin{algorithm}
	\caption{Find the nearest larger element}
	\begin{algorithmic}[1]
		\Require An array of integers A[]
		\Function{NextLarger}{A[]}
            \State res = list(n, -1)\Comment initialize a list of length n and all of its elements are -1
            \State monoStack = stack()\Comment initialize an empty stack
            \For{i from to A.size - 1}
            \While{monoStack is not empty AND A[monoStack.top]<A[i]}
            \State res[monoStack.top] = i
            \State monoStack.pop

            \EndWhile
            \State monoStack.push(i)

            \EndFor
            \State \Return{res}

		\EndFunction
	\end{algorithmic}

\end{algorithm}

\paragraph{b}
See Algorithm 5. The time complexity should be O($2nlog_2n+n$) = O($nlogn$)

\begin{algorithm}
	\caption{For each of the elementA[i], find the minimumA[j] so thatA[j]> A[i] andj > i}
	\begin{algorithmic}[1]
		\Require An array of integers A[]
		\Function{NextSmallestLarger}{A[]}
            \State res = list(n, -1)\Comment initialize a list of length n and all of its elements are -1
            \State B = [][] \Comment initialize B as a 2-D list
            \State B = [[A[i],i] for i from 0 to A.length -1] \Comment store A[i] and i, B = [[A[0],0],\dots,[A[n-1], n-1]]
            \State \Call{MergeSort}{B[$\cdot$][0]}\Comment sort B according to values from A
            \State \Call{MinHeapArray}{B[$\cdot$][0]} \Comment Turn B[$\cdot$][0] into a min heap stored in an array, original index sift with values from A
            \State listOfJ = B[$\cdot$][1] \Comment original index after sorted with elements from A

            \State monoStack = stack()\Comment initialize an empty stack

            \For{j from 0 to n-1}
            \While{monoStack is not empty AND B[monoStack.top][1] < B[j][1] AND B[monoStack.top][0] < B[j][0]}
            \State res[B[monoStack.top][1]] = listOfJ[j]
            \State monoStack.pop

            \EndWhile
            \State monoStack.push(j)

            \EndFor
            \State \Return{res}

		\EndFunction
	\end{algorithmic}

\end{algorithm}

\end{document}

%\begin{align}
%\begin{split}
%(x+y)^3 	&= (x+y)^2(x+y)\\
%&=(x^2+2xy+y^2)(x+y)\\
%&=(x^3+2x^2y+xy^2) + (x^2y+2xy^2+y^3)\\
%&=x^3+3x^2y+3xy^2+y^3
%\end{split}
%\end{align}

%\begin{tabbing}
%\hspace*{.25in} \= \hspace*{.25in} \= \hspace*{.25in} \= \hspace*{.25in} \= \hspace*{.25in} \=\kill
%\>$Euclid(m,n)=$ \\
%\>\> {\bf while} n$ \neq $ 0 \\
%\>\>\> r $ \leftarrow $ $m$ mod $n$  \\
%\>\>\>  m $\leftarrow$n\\
%\>\>{\bf return} m
%\end{tabbing}

%Python code:
%\begin{lstlisting}[language = python]
%def gcd(m,n):
%	while n != 0:
%		r = m % n
%		m = n
%		n = r
%	return m
%\end{lstlisting}

%\paragraph{Heading on level 4 (paragraph)}

%\begin{tabbing}
%	\hspace*{.25in} \= \hspace*{.25in} \= \hspace*{.25in} \= \hspace*{.25in} \= \hspace*{.25in} \=\kill
%	{\bf function} find (A,x,n)\\
%	\> j $\leftarrow$ 0\\
%	\> {\bf while} j < n\\
%	\>\> {\bf if} A[j]=x\\
%	\>\>\>  {\bf return} j  \\
%	\>\> j $\leftarrow$ j+1\\
%	\> {\bf return} -1
%\end{tabbing}

%\begin{figure}[htbp!]
%		\centering
%		\includegraphics[width=0.6\textwidth]{lec26.png}
%		\caption{Linked List}%\label{book}
%		\vspace{-1em}
%\end{figure}

%\begin{align}
%A =
%\begin{bmatrix}
%A_{11} & A_{21} \\
%A_{21} & A_{22}
%\end{bmatrix}
%\end{align}

%\begin{algorithm}
 %       \caption{Count the number of occurrences of a certain integer $x$ in an array $A[]$}
  %      \begin{algorithmic}[1] %每行显示行号
   %         \Require  $Array$ A[],$Length\;of\;the\;array$ n, $Integer$ x
    %        \Ensure   Number of occurrence of integer x
     %       \Function {NumberCount}{$A[], x,n$}
      %
       %     	\State $firstApperence \gets $\Call{FirstOccurrenceSearch}{$A[]$,0,$n-1$,$x$,$n$}

        %    	\If{$firstApperence=-1$}
         %   	\State \Return $firstApperence$
          %  	\EndIf

           % 	\State $lastApperence\gets$ \Call{LastOccurrenceSearch}{$A[],firstApperence,n-1,x,n$}
            %	\State \Return $lastApperence-firstApperence+1$

                %\State $result \gets 0$

                %\If {$high \geqslant low$}
                    %\State $mid \gets (high + low) // 2$   \#"//" means integer division
                    %\State $result \gets result +$ \Call{MergerSort}{$Array, left, middle$}
                    %\State $result \gets result +$ \Call{MergerSort}{$Array, middle, right$}
                    %\State $result \gets result +$ \Call{Merger}{$Array,left,middle,right$}
                %\EndIf
                %\If {$mid = 0 \, OR x > A[mid-1]$}
                %	\State \Return $mid$
                %\Else
                %	\If {$x>A[mid]$}
                %		\State \Return

                 %\Return{$result$}
            %\EndFunction
           %\State
            %\Function{FirstOccurrenceSearch}{$A[],low, high,x,n$}

      %      \If{$high \geqslant low$}
      %      \State $mid\gets(low + high)//2$ \Comment "//" means integer division
      %      \EndIf
      %      \If{$\{mid = 0 \; OR\;  x>A[mid-1]\}\; AND\; \{A[mid]=x\}$}
      %      \State \Return $mid$
      %      \Else
      %      	\If{$x>A[mid]$}
      %      	\State \Return \Call{FirstOccurrenceSearch}{$A[],mid+1,high,x,n$}
      %      	\Else
      %      	\State \Return \Call{FirstOccurrenceSearch}{$A[],low,mid-1,x,n$}
      %      	\EndIf
      %      \EndIf
      %      \State \Return -1
      %
      %      \EndFunction
      %
      %      \State
      %      \Function{LastOccurrenceSearch}{$A[],low,high,x,n$}
      %
      %      \If{$high \geqslant low$}
      %      \State $mid\gets(low + high)//2$ \Comment "//" means integer division
      %      \EndIf
      %      \If{$\{mid = n-1 \; OR\;  x<A[mid-1]\}\; AND\; \{A[mid]=x\}$}
      %      \State \Return $mid$
      %     \Else
       %     	\If{$x<A[mid]$}
        %    	\State \Return \Call{LastOccurrenceSearch}{$A[],low, mid-1, x,n$}
         %   	\Else
          %  	\State \Return \Call{LastOccurrenceSearch}{$A[],mid+1, high,x,n$}
           % 	\EndIf
            %\EndIf
            %\State \Return -1

           % \EndFunction

            %\Function{Merger}{$Array, left, middle, right$}
             %   \State $i\gets left$
              %  \State $j\gets middle$
               % \State $k\gets 0$
               % \State $result \gets 0$
               % \While{$i<middle$ \textbf{and} $j<right$}
                %    \If{$Array[i]<Array[j]$}
                 %       \State $B[k++]\gets Array[i++]$
                  %  \Else
                   %     \State $B[k++] \gets Array[j++]$
                    %    \State $result \gets result + (middle - i)$
                    %\EndIf
                %\EndWhile
                %\While{$i<middle$}
                %    \State $B[k++] \gets Array[i++]$
                %\EndWhile
                %\While{$j<right$}
                %    \State $B[k++] \gets Array[j++]$
                %\EndWhile
                %\For{$i = 0 \to k-1$}
                %    \State $Array[left + i] \gets B[i]$
                %\EndFor
                %\State \Return{$result$}
            %\EndFunction
      %  \end{algorithmic}
    %\end{algorithm}

    %\begin{figure}[htbp]
     %   \centering

      %  \begin{tikzpicture}
       %     [level distance=1.3cm,
%        level 1/.style={sibling distance=8cm, level distance=0.8cm},
%       level 2/.style={sibling distance=4cm, level distance=0.8cm},
%        level 3/.style={sibling distance=2cm, level distance=0.8cm},
%        level 4/.style={sibling distance=1cm, level distance=0.8cm}]
%        \node {A}
%       child{node{B}
%            child{node{\color{blue}D}
%%                child{node{H}
 %                   child{node{\color{red}1}}
%                    child{node{2}}}
%                child{node{I}
%                    child{node{3}}
%                    child{node{4}}}}
%            child{node{E}
%                child{node{\color{blue}J}
%                   child{node{\color{red}5}}
%                    child{node{6}}}
%                child{node{\color{blue}K}
%                    child{node{7}}
%                    child{node{\color{red}8}}}}}
%        child{node{C}
%            child{node{F}
%                child{node{\color{blue}L}
%                    child{node{9}}
%                    child{node{\color{red}10}}}
%                child{node{\color{blue}M}
%                    child{node{\color{red}11}}
%                    child{node{12}}}}
%            child{node{\color{blue}G}
%                child{node{N}
%                    child{node{13}}
%                    child{node{14}}}
%                child{node{O}
%                    child{node{\color{red}15}}
%                    child{node{16}}}}}
%        ;
%
%        \end{tikzpicture}
%        \caption{Adaptive tree walk protocol for solving contention. Red digits are stations which are ready,
%        blue characters are the nodes where the contention is resolved.}
%    \end{figure}


\documentclass{article}

\usepackage[final]{style}
\usepackage[utf8]{inputenc} % allow utf-8 input
\usepackage[T1]{fontenc}    % use 8-bit T1 fonts
\usepackage{hyperref}       % hyperlinks
\usepackage{url}            % simple URL typesetting
\usepackage{booktabs}       % professional-quality tables
\usepackage{amsfonts}       % blackboard math symbols
\usepackage{nicefrac}       % compact symbols for 1/2, etc.
\usepackage{microtype}      % microtypography
\usepackage{verbatim}
\usepackage{graphicx}       % for figures
\usepackage{placeins}
\usepackage{amsmath}
\usepackage{gensymb}

\title{Lecture \#06: Edge Detection}

\author{
  Winston Wang, Antonio Tan-Torres, Hesam Hamledari \\
  Department of Computer Science\\
  Stanford University\\
  Stanford, CA 94305 \\
  \texttt{\{wwang13, tantonio\}@cs.stanford.edu; hesamh@stanford.edu} \\
}

\begin{document}
\maketitle
\section{Introduction}
This lecture covers edge detection, Hough transformations, and RANSAC.
The detection of edges provides meaningful semantic information that facilitate the understanding of an image. This can help analyzing the shape of elements, extracting image features, and understanding changes in the properties of depicted scenes such as discontinuity in depth, type of material, and illumination, to name a few. We will explore the application of Sobel and Canny edge detection techniques.
The next section introduces the Hough transform, used for the detection of parametric models in images;for example, the detection of linear lines, defined by two parameters, is made possible by the Hough transform. Furthermore, this technique can be generalized to detect other shapes (e.g., circles).
However, as we will see, the use of Hough transform is not effective in fitting models with a high number of parameters. To address this model fitting problem, the random sampling consensus (RANSAC) is introduced in the last section; this non-deterministic approach repeatedly samples subsets of data, uses them to fit the model, and classifies the remaining data points as "inliers" or "outliers" depending on how well they can be explained by the fitted model (i.e., their proximity to the model). The result is used for a final selection of data points used in achieving the final model fit. A general comparison of RANSAC and Hough transform is also provided in the last section.

\section{Edge Detection}
\subsection{Motivation for Edge Detection}
Edge detection is extremely relevant for mammalian eyes.  Certain neurons within the brain are adept at recognizing straight lines.  The information from these neurons is put together in the brain for recognition of objects.  In fact, edges are so useful for recognition in humans, line drawings are almost as recognizable as the original image (Fig. 1).We would like to be able to extract information, recognize objects, and recover the geometry and viewpoint of an image.

\includegraphics[width=\textwidth]{line_drawings.png}
\textbf{Fig. 1. Certain areas of the brain react to edges; the line drawings are as recognizable as the original image; image source: \cite{line_drawings}}

\subsection{Edge Basics}
There are four possible sources of edges in an image:  surface normal discontinuity (surface changes direction sharply), depth discontinuity (one surface behind another), surface color discontinuity (single surface changes color), illumination discontinuity (shadows/lighting).  These discontinuities are demonstrated in the Fig.2a; different types of edges can be seen in Fig.2b:
\FloatBarrier
\includegraphics[width=\textwidth]{overall.png}
\FloatBarrier
\textbf{Fig. 2. Different types of edges due to discontinuities in surface color, surface depth, and surface normal (source: lecture notes)}

Edges occur in images when the magnitude of the gradient is high
\subsection{Finding the Gradient}
In order to find the gradient, we must first find the derivatives in both the $x$ and $y$ directions
\subsubsection{Discrete Derivatives}
\begin{align*}
\frac{df(x)}{dx} &= \lim_{\delta x\rightarrow0}\frac{f(x)-f(x-\delta x)}{\delta x} = f'(x)\\
\frac{df(x)}{dx} &= \frac{f(x)-f(x-1}{1} = f'(x)\\
\frac{df(x)}{dx} &= f(x)-f(x-1) = f'(x)
\end{align*}
It is also possible to take the derivative three different ways
\begin{itemize}
\item Backward: $f'(x) = f(x)-f(x-1)$
\item Forward: $f'(x) = f(x+1)-f(x)$
\item Central: $f'(x) = \frac{(x+1)-f(x-1)}{2}$
\end{itemize}
Each of these can also be represented as a filter (convoluting the filter with the image gives the derivative)
\begin{itemize}
\item Backward: $f'(x) = f(x)-f(x-1)\rightarrow[0,1,-1]$
\item Forward: $f'(x) = f(x)-f(x+1)\rightarrow[-1,1,0]$
\item Central: $f'(x) = f(x+1)-f(x-1)\rightarrow[1,0,-1]$
\end{itemize}
The gradient ($\nabla f$) can be calculated as follows:
\begin{align*}
\nabla f(x,y) &= \begin{bmatrix}%
    \frac{\partial f(x,y)}{\partial x}\\
    \frac{\partial f(x,y)}{\partial y}
    \end{bmatrix}\\
    &= \begin{bmatrix}%
    f_x\\
    f_y
    \end{bmatrix}
\end{align*}
We can also calculate the magnitude and the angle of the gradient:
\begin{align*}
|\nabla f(x,y)| &= \sqrt{f_x^2+f_y^2}\\
\theta &= \tan^{-1}\left(f_y/f_x\right)
\end{align*}
\subsection{Reducing noise}
Noise will interfere with the gradient, making it impossible to find edges using the simple method, even though the edges are still detectable to the eye.  The solution is to first smooth the image.
\newline
Let $f$ be the image and $g$ be the smoothing kernel.  Thus, in order to find the smoothed gradient, we must calculate (1D example):
\[
\frac{d}{dx}(f*g)
\]
By the derivative theorem of convolution:
\[
\frac{d}{dx}(f*g) = f*\frac{d}{dx}g
\]
This simplification saves us one operation.  Smoothing removes noise but blurs edges.  Smoothing with different kernel sizes can detect edges at different scales
\subsection{Sobel Noise Detector}
This algorithm utilizes 2 $3\times3$ kernels which, once convolved with the image, approximate the $x$ and $y$ derivatives of the original image.
\begin{align*}
&\mathbf{G}_x = \begin{bmatrix}%
    1 & 0 & -1\\
    2 & 0 & -2\\
    1 & 0 & -1
    \end{bmatrix}
    &\mathbf{G}_y = \begin{bmatrix}%
    1 & 2 & 1\\
    0 & 0 & 0\\
    -1 & -2 & -1
    \end{bmatrix}
\end{align*}
These matrices represent the result of smoothing and differentiation
\[
\mathbf{G}_x = \begin{bmatrix}%
    1 & 0 & -1\\
    2 & 0 & -2\\
    1 & 0 & -1
    \end{bmatrix} = \begin{bmatrix}%
    1\\
    2\\
    1
    \end{bmatrix}\begin{bmatrix}%
    1 & 0 & -1\\
    \end{bmatrix}
\]
The Sobel Filter has many problems, including poor localization.  The Sobel Filter also favors horizontal and vertical edges over oblique edges
\subsection{Canny Edge Detector}
The Canny Edge Detector has five algorithmic steps:
\begin{itemize}
\item Suppress noise
\item Compute gradient magnitude and direction
\item Apply non-maximum suppression
\item Hysteresis thresholding
\item Connectivity analysis to detect edges
\end{itemize}
\subsubsection{Suppress noise}
We can both suppress noise and compute the derivatives in the $x$ and $y$ directions using a method similar to the Sobel filter.
\subsubsection{Compute gradient magnitude and direction}
From above,
\begin{align*}
|\nabla f(x,y)| &= \sqrt{f_x^2+f_y^2}\\
\theta &= \tan^{-1}\left(f_y/f_x\right)
\end{align*}
\subsubsection{Apply non-maximum suppression}
The purpose of this portion of the algorithm is to make sure the edges are specific.  Thus, we assume that the edge occurs when the gradient reaches a maximum.  We suppress any pixels that have a non-maximum gradient.\newline
Basically, if the pixel is not the largest of the three pixels in the direction and opposite the direction of its gradient, it is set to 0.  Furthermore, all gradients are rounded to the nearest 45\degree
\subsubsection{Hysteresis thresholding}
All remaining pixels are subjected to hysteresis thresholding.  This part uses two values, for the high and low thresholds.  Every pixel with a value above the high threshold is marked as a strong edge.  Every pixel below the low threshold is set to 0.  Every pixel between the two thresholds is marked as a weak edge
\subsubsection{Connectivity analysis to detect edges}
The final step is connecting the edges.  All strong edge pixels are edges.  For weak edge pixels, only the weak edge pixels that are linked to strong edge pixels are edges.  The part uses BFS or DFS to find all the edges.

\section{Hough Transforms}
\subsection{Intro to Hough Transform}
Hough Transform is a way to detect particular structures in images, namely lines. However, Hough transform can be used to detect any structure whose paramteric equation is known. It gives a robust detector under noise and partial occlusion.

\subsection{Goal of Hough Transform for detecting lines}
Hough transform can be used to detect lines in images. To do this, we want to locate sets of pixels that make up straight lines in the image. This works to detect lines in an image after an edge detector is applied to get the pixels of just the edges (and thus we find which sets of those pixels make up straight lines).

\subsection{Detecting lines using Hough Transform in a,b space}
Say we have a ${x_i,y_i}$. There are infinite lines that could pass through this point.
We can define a line that passes through this pixel $x_i, y_i$ as $$y_i = a*x_i + b$$. Using this, we can transform each pixel into $a,b$ space by re-writing this equation as:
$$ b = -a*x_i + y_i$$

This equation represents a line in $a,b$ space, and each $a,b$ point on the line represents a possible line passing through our point $x_i,y_i$.

Thus, for each pixel $x_i,y_i$ in our set of edge pixels, we transform it into $a,b$ space to get a line.

\includegraphics[width=\textwidth]{hough_transform.png}
\textbf{Fig. 3. The transformation from the original space to the Hough space; source: lecture slides}

The intersection of lines in $a,b$ space represent the $a,b$ values that compromise a line $y_i = a*x_i + b$ passing through those points. Example:
Say we have two points $x_1,y_1$ = $(1,1)$, and $x_2,y_2$ = $(2,3)$.
We transform these points into $a,b$ space with the lines $b = -a*1 + 1$ and $b = -a*2 + 3$.
Solving for the intersection of these two lines gives us $a=2$ and $b=-1$. This intersection point in $(a,b)$ space gives us the values for the line that goes through both points in $x,y$ space.

\includegraphics[width=\textwidth]{hough_transform2.png}
\textbf{Fig. 4. The lines passing through a point in the original space; source: lecture slides}

\subsection{Accumulator Cells}
In order to get the "best" lines, we quantize the $a,b$ space into cells. For each line in our $a,b$ space, we add a "vote" or a count to each cell that it passes through. We do this for each line, so at the end, the cells with the most "votes" have the most intersections and therefore should correspond to real lines in our image.

The algorithm for Hough transform in $a,b$ space is as follows:

\includegraphics[width=\textwidth]{hough_transform3.png}
\textbf{Fig. 5. The Hough transform algorithm; source: lecture slides}

\subsection{Hough transform in $\rho, \theta$ space}
A problem with using $a,b$ space to represent lines is that they are limited and cannot represent vertical lines.
To solve this, we use polar coordinates to represent lines. For a pixel $x_i, y_i$, we transform it using the equation:
$$ x*\cos\theta + y*\sin\theta = \rho$$
In $\rho, \theta$ space, points are not represented as lines but instead as sine wave-like functions.

\includegraphics[width=\textwidth]{hough_transform4.png}
\textbf{Fig. 6. The Hough transform in $\rho, \theta$ space; source: lecture slides}

The intersection of these functions in $\rho, \theta$ space still correspond to the $\rho, \theta$ that comprise a line passing through those points.

So, for each pixel $x_i, y_i$ we transform it into a function in  $\rho, \theta$ space. We apply the same accumulator cell algorithm to count the most intersections of functions.

In this case, we quantize our $\rho, \theta$ space into cells, and add a "vote" to each cell that our function passes through. The cells with the most votes are the most likely real lines in our image.

\subsection{Concluding Remarks}
Advantages of the Hough Transform is that it is conceptually simple (just transforming and finding intersection in Hough space). It is also fairly easy to implement, and it can handle missing and occluded data well. Another advantage is that it can find other structures other than lines, as long as the structure has a parametric equation.

Some disadvantages include that it gets more computationally complex the more parameters you have. It can also only look for one kind of structure (so not lines and circles together). The length and the position of a line segment can also not be detected by this. It can be fooled by "apparent" lines, and co-linear line segments cannot be separated.
\section{RANSAC}
With the increase in model complexity (i.e., the number of parameters), the Hough transform loses its effectiveness; this section elaborates on the design of the RAndom Sample Consensus (RANSAC) technique \cite{fischler1981random} which provides a computationally efficient means of fitting models in images. We begin with an introduction of the RANSAC's basic idea and then introduce its algorithm.
\subsection{Introduction to RANSAC Basics}
The RANSAC algorithm is used for estimating the parameters of models in images (i.e., model fitting). The basic idea behind RANSAC is to solve the fitting problem many times using randomly selected minimal subsets of the data and choosing the best performing fit. To achieve this, RANSAC tries to iteratively identify the data points that correspond to model we are trying to fit.

Fig. 7a illustrates an example where a linear model (i.e., 2 parameters) is to be fitted to the data; while the majority of data points fit a linear model, the two points in the top right corner can significantly affect the accuracy of overall fit (if they are included in the fit). The RANSAC algorithm aims to address this challenge by identifying the "inliers" and "outliers" in the data.

RANSAC randomly selects samples of the data, with the assumption that if enough samples are chosen, there will be a low probability that at all samples provides a bad fit.

\includegraphics[width=\textwidth]{ransac1.png}
\textbf{Fig. 7. a) the outliers are detected by RANSAC to improve parameter estimation; b) RANSAC application for image stitching; sources(\cite{prince2012computer}and Derek Hoiem)}

\subsection{Applications}
The RANSAC algorithm can be used to estimate parameters of different models; this is proven beneficial in image stitching (Fig. 6b), outlier detection, lane detection (linear model estimation), and stereo camera calculations.

\subsection{The Algorithm}
The RANSAC algorithm iteratively samples nominal subsets of the original data (e.g., 2 points for line estimation); the model is fitted to each sample, and the number of "inliers" corresponding to this fit is calculated; this includes the data points that are close to the fitted model. The points closer than a threshold (e.g., 2 standard deviation, or a pre-determined number of pixels) are considered "inliers". The fitted model is considered good if a big fraction of the data is considered as "inliers" for that fit. In the case of a good fit, the model is re-fitted using all the inliers, and the outliers are discarded. This process is repeated, and model estimates with a big enough fraction of inliers (e.g., bigger than a pre-specified threshold) are compared to choose the best-performing fit. Fig. 8 illustrates this process for a linear model and its three samples. The third sample (Fig. 8c) provides the best fit as it includes the most number of inliers.

\includegraphics[width=\textwidth]{ransac2.png}
\textbf{Fig. 8. The demonstration of the RANSAC algorithm for a linear model estimation and three random samples; source(\cite{prince2012computer})}

\includegraphics[width=0.9\textwidth]{ransac3.png}

\textbf{Fig. 9. The pseudocode for RANSAC; source(\cite{forsyth2011computer})}

The RANSAC is detailed in Fig. 9. The major steps included in the RANSAC loop:

\begin{enumerate}
  \item Randomly select a seed group from data.
  \item Perform parameter estimation using the selected seed group.
  \item Identify the inliers (points close to the estimated model).
  \item (If there exists a sufficiently large number of inliers,)re-estimate the model using all inliers.
  \item repeat steps 1-4 and finally keep the estimate with most inliers and best fit.
\end{enumerate}

\subsection{How Many Samples are Needed?}
The RANSAC is a non-deterministic model fitting approach; this means that the number of samples need to be large enough to provide a high confidence estimate of parameters. The number of required samples depends on 1) the number of fitted parameters and 2) the amount of noise. Fig. 10 lists the minimum number of samples needed based on p=0.99 and variations of sample size (i.e., the number of parameters) and the fraction of outliers (i.e., noise). More samples are needed for estimating bigger models and noisier data.
A large enough number of samples ($k$) need to be chosen such that a low probability of only seeing bad samples (${P_f}$) is guaranteed:
$${P_f}= (1-W^n)^k= 1-p$$
where $W$ and $n$ are respectively the fraction of inliers and the number of points needed for model fitting. The minimum number of samples:
$$k=\frac{log(1-p)}{log(1-W^n)}$$

\includegraphics[width=\textwidth]{ransac4.png}
\textbf{Fig. 10. The number of samples for different choices of noise population and model size; source: David Lowe)}

\subsection{Advantages, Limitations, and Considerations}
The advantages of the RANSAC lie in its simple implementation and wide application range in the model fitting domain. Other advantages include its computational efficiency; the sampling approach provides a better alternative to solving the problem for all possible combinations of features.

In some cases, it'd be more efficient to use the Hough transform instead of the RANSAC:
\begin{enumerate}
  \item The number of parameters are small; for example, linear model estimation (2 parameters) can be achieved efficiently using Hough transform, while image stitching requires a more computationally frugal approach such as RANSAC.
  \item If the noise population is high; as we saw earlier, increase in noise requires a more extensive sampling approach (higher number of samples), increasing computation cost. Increased noise reduces the chances of correct parameter estimation and the accuracy of inlier classification.
\end{enumerate}

The poor performance in highly noisy data is a primary limitation of the RANSAC; this is espcially crucial as real-world problems have high rate of outliers.

% References
\small
\bibliographystyle{plain}
\bibliography{bibliography}

\end{document}


\documentclass[t,usenames,dvipsnames]{beamer}
\usetheme{Copenhagen}
\setbeamertemplate{headline}{} % remove toc from headers
\beamertemplatenavigationsymbolsempty

\usepackage{amsmath, tkz-euclide, tikz, xcolor, pgfplots, array}
\usetkzobj{all}
\pgfplotsset{compat = 1.16}
\usetikzlibrary{arrows.meta, calc, decorations.pathreplacing}
\pgfplotsset{every axis/.append style = {axis lines = middle, axis line style = {<->}}}
\pgfplotsset{every tick label/.append style={font=\scriptsize}}
\everymath{\displaystyle}

\title{Verifying Trig Identities}
\author{}
\date{}

\AtBeginSection[]
{
  \begin{frame}
    \frametitle{Objectives}
    \tableofcontents[currentsection]
  \end{frame}
}

\begin{document}

\begin{frame}
    \maketitle
\end{frame}

\section{Verify trigonometric identities}

\begin{frame}{Identities}
    Recall that an \alert{identity} is an equation that is \underline{always} true. \newline\\

    To verify an identity, we will work with the left and/or right sides of the equation given to show that the equation is true for all values of the variable. \newline\\

    In this section, the identities will involve trig functions.
\end{frame}

\begin{frame}{Quotient Identities}
    The Quotient Identities are
    \[
    \tan \theta = \frac{\sin\theta}{\cos\theta} \quad \text{ and } \quad \cot\theta = \frac{\cos\theta}{\sin\theta}
    \]
\end{frame}

\begin{frame}{Example 1}
Use the triangle to verify $\tan\theta = \frac{\sin\theta}{\cos\theta}$ \\[18pt]
\begin{minipage}{0.3\textwidth}
\begin{tikzpicture}
\tkzDefPoints{0/0/A, 3/0/B, 3/2/C}
\tkzMarkRightAngle(C,B,A)
\tkzDrawPolygon(A,B,C)
\tkzLabelAngle[pos = 0.75](B,A,C){$\theta$}
\tkzLabelSegment[below](A,B){$x$}
\tkzLabelSegment[right](B,C){$y$}
\tkzLabelSegment[above](A,C){$r$}
\end{tikzpicture}
\end{minipage}
\hspace{0.25cm}
\begin{minipage}{0.5\textwidth}
\begin{align*}
\onslide<2->{\frac{\sin\theta}{\cos\theta} &= \dfrac{\left(\dfrac{y}{r}\right)} {\left(\dfrac{x}{r}\right)} }
\onslide<3->{{\color{blue}\left(\dfrac{r}{r}\right)}} \\[12pt]
\onslide<4->{&=\dfrac{y}{x}} \\[12pt]
\onslide<5->{&=\tan\theta}
\end{align*}
\end{minipage}
\end{frame}

\begin{frame}{Example 2}
Verify $\cot\theta = \frac{\cos\theta}{\sin\theta}$ \\[18pt]
\begin{minipage}{0.3\textwidth}
\begin{tikzpicture}
\tkzDefPoints{0/0/A, 3/0/B, 3/2/C}
\tkzMarkRightAngle(C,B,A)
\tkzDrawPolygon(A,B,C)
\tkzLabelAngle[pos = 0.75](B,A,C){$\theta$}
\tkzLabelSegment[below](A,B){$x$}
\tkzLabelSegment[right](B,C){$y$}
\tkzLabelSegment[above](A,C){$r$}
\end{tikzpicture}
\end{minipage}
\hspace{0.25cm}
\begin{minipage}{0.5\textwidth}
\begin{align*}
\onslide<2->{\frac{\cos\theta}{\sin\theta} &= \dfrac{\left(\dfrac{x}{r}\right)} {\left(\dfrac{y}{r}\right)} }
\onslide<3->{{\color{blue}\left(\dfrac{r}{r}\right)}} \\[12pt]
\onslide<4->{&=\dfrac{x}{y}} \\[12pt]
\onslide<5->{&=\cot\theta}
\end{align*}
\end{minipage}
\end{frame}

\begin{frame}[c]{Reciprocal Identities}
\begin{center}
    \begin{tabular}{p{0.3\textwidth}p{0.3\textwidth}}
        $\csc\theta = \dfrac{1}{\sin\theta}$    &   $\sin\theta = \dfrac{1}{\csc\theta}$    \\[22pt]
        $\sec\theta = \dfrac{1}{\cos\theta}$    &   $\cos\theta = \dfrac{1}{\sec\theta}$    \\[22pt]
        $\cot\theta = \dfrac{1}{\tan\theta}$    &   $\tan\theta = \dfrac{1}{\cot\theta}$
    \end{tabular}
\end{center}
\end{frame}

\begin{frame}{Pythagorean Identities}
    These are some of the most important identities in this course. \newline\\

    They are based on the Pythagorean Theorem.
\end{frame}

\begin{frame}{Example 3}
Verify $\cos^2\theta + \sin^2\theta = 1$    \\[12pt]
\begin{minipage}{0.3\textwidth}
\begin{tikzpicture}
\tkzDefPoints{0/0/A, 3/0/B, 3/2/C}
\tkzMarkRightAngle(C,B,A)
\tkzDrawPolygon(A,B,C)
\tkzLabelAngle[pos = 0.75](B,A,C){$\theta$}
\tkzLabelSegment[below](A,B){$x$}
\tkzLabelSegment[right](B,C){$y$}
\tkzLabelSegment[above](A,C){$r$}
\end{tikzpicture}
\end{minipage}
\hspace{0.25cm}
\begin{minipage}{0.5\textwidth}
\begin{align*}
\onslide<2->{x^2 + y^2 &= r^2} \\[12pt]
\onslide<3->{\frac{x^2}{r^2} + \frac{y^2}{r^2} &= \frac{r^2}{r^2}} \\[12pt]
\onslide<4->{\left(\frac{x}{r}\right)^2 + \left(\frac{y}{r}\right)^2 &= 1} \\[12pt]
\onslide<5->{(\cos\theta)^2 + (\sin\theta)^2 &= 1} \\[12pt]
\onslide<6->{\cos^2\theta + \sin^2\theta &= 1}
\end{align*}
\end{minipage}
\end{frame}

\begin{frame}{Example 4}
Verify $1 + \tan^2\theta = \sec^2\theta$    \\[12pt]
\begin{minipage}{0.3\textwidth}
\begin{tikzpicture}
\tkzDefPoints{0/0/A, 3/0/B, 3/2/C}
\tkzMarkRightAngle(C,B,A)
\tkzDrawPolygon(A,B,C)
\tkzLabelAngle[pos = 0.75](B,A,C){$\theta$}
\tkzLabelSegment[below](A,B){$x$}
\tkzLabelSegment[right](B,C){$y$}
\tkzLabelSegment[above](A,C){$r$}
\end{tikzpicture}
\end{minipage}
\hspace{0.25cm}
\begin{minipage}{0.5\textwidth}
\begin{align*}
\onslide<2->{x^2 + y^2 &= r^2} \\[12pt]
\onslide<3->{\frac{x^2}{x^2} + \frac{y^2}{x^2} &= \frac{r^2}{x^2}} \\[12pt]
\onslide<4->{1 + \left(\frac{y}{x}\right)^2 &= \left(\frac{r}{x}\right)^2} \\[12pt]
\onslide<5->{1 + (\tan\theta)^2 &= (\sec\theta)^2} \\[12pt]
\onslide<6->{1 + \tan^2\theta &= \sec^2\theta}
\end{align*}
\end{minipage}
\end{frame}

\begin{frame}{Example 5}
Verify $\cot^2\theta + 1  = \csc^2\theta$    \\[12pt]
\begin{minipage}{0.3\textwidth}
\begin{tikzpicture}
\tkzDefPoints{0/0/A, 3/0/B, 3/2/C}
\tkzMarkRightAngle(C,B,A)
\tkzDrawPolygon(A,B,C)
\tkzLabelAngle[pos = 0.75](B,A,C){$\theta$}
\tkzLabelSegment[below](A,B){$x$}
\tkzLabelSegment[right](B,C){$y$}
\tkzLabelSegment[above](A,C){$r$}
\end{tikzpicture}
\end{minipage}
\hspace{0.25cm}
\begin{minipage}{0.5\textwidth}
\begin{align*}
\onslide<2->{x^2 + y^2 &= r^2} \\[12pt]
\onslide<3->{\frac{x^2}{y^2} + \frac{y^2}{y^2} &= \frac{r^2}{y^2}} \\[12pt]
\onslide<4->{\left(\frac{x}{y}\right)^2 + 1 &= \left(\frac{r}{y}\right)^2} \\[12pt]
\onslide<5->{(\cot\theta)^2 + 1 &= (\csc\theta)^2} \\[12pt]
\onslide<6->{\cot^2\theta + 1 &= \csc^2\theta}
\end{align*}
\end{minipage}
\end{frame}

\begin{frame}{Alternate Forms of Pythagorean Identities}
    \[
    \cos^2\theta + \sin^2\theta = 1
    \]
    \pause
    \begin{itemize}
        \item $1 - \sin^2\theta = \cos^2\theta$ \newline\\  \pause
        \begin{itemize}
            \item $(1-\sin\theta)(1+\sin\theta) = \cos^2\theta$ \newline\\  \pause
        \end{itemize}
        \item $1 - \cos^2\theta = \sin^2\theta$ \newline\\  \pause
        \begin{itemize}
            \item $(1+\cos\theta)(1-\cos\theta) = \sin^2\theta$
        \end{itemize}
    \end{itemize}
\end{frame}

\begin{frame}{Alternate Forms of Pythagorean Identities}
    \[
    1 + \tan^2\theta = \sec^2\theta
    \]
    \pause
    \begin{itemize}
        \item $\sec^2\theta - 1 = \tan^2\theta$ \newline\\  \pause
        \begin{itemize}
            \item $(\sec\theta + 1)(\sec\theta - 1)$ \newline\\  \pause
        \end{itemize}
        \item $1 = \sec^2\theta - \tan^2\theta$ \newline\\  \pause
        \begin{itemize}
            \item $1 = (\sec\theta + \tan\theta)(\sec\theta - \tan\theta)$
        \end{itemize}
    \end{itemize}
\end{frame}

\begin{frame}{Alternate Forms of Pythagorean Identities}
    \[
    1 + \cot^2\theta = \csc^2\theta
    \]
    \pause
    \begin{itemize}
        \item $\csc^2\theta - \cot^2\theta = 1$ \newline\\  \pause
        \begin{itemize}
            \item $(\csc\theta + \cot\theta)(\csc\theta - \cot\theta) = 1$ \newline\\  \pause
        \end{itemize}
        \item $\csc^2 \theta - 1 = \cot^2\theta$ \newline\\  \pause
        \begin{itemize}
            \item $(\csc\theta + 1)(\csc\theta - 1) = \cot^2\theta$
        \end{itemize}
    \end{itemize}
\end{frame}

\begin{frame}{Strategies For Verifying Trig Identities}
    \begin{itemize}
        \item Rewrite other functions in terms of sine and/or cosine.   \newline\\
        \item Work on one or both sides of the equation at the same time. \newline\\
        \item Try working on the more complicated side of the identity. \newline\\
        \item Use Reciprocal and Quotient Identities to write complex fractions that you can then simplify. \newline\\
        \item Obtain common denominators before adding rational expressions. \newline\\
        \item Try Pythagorean Identities, especially if you find trig functions raised to a power.
    \end{itemize}
\end{frame}

\begin{frame}{Example 6}
Verify each.    \newline\\
(a) \quad $\tan\theta = \sin\theta \cdot \sec\theta$
\begin{align*}
    \onslide<2->{\dfrac{\sin\theta}{\cos\theta} &= \sin\theta \left(\dfrac{1}{\cos\theta}\right)} \\[12pt]
    \onslide<3->{\dfrac{\sin\theta}{\cos\theta} &= \dfrac{\sin\theta}{\cos\theta}}
\end{align*}
\end{frame}

\begin{frame}{Example 6}
(b) \quad $(\sec\theta - \tan\theta)(\sec\theta + \tan\theta) = 1$
\begin{align*}
    \onslide<2->{\sec\theta(\sec\theta + \tan\theta) - \tan\theta(\sec\theta + \tan\theta) &= 1} \\[12pt]
    \onslide<3->{\sec^2\theta + \sec\theta\tan\theta - \sec\theta\tan\theta - \tan^2\theta &= 1} \\[12pt]
    \onslide<4->{\sec^2\theta - \tan^2\theta &= 1} \\[12pt]
    \onslide<5->{1 &= 1}
\end{align*}
\end{frame}

\begin{frame}{Example 6}
(c) \quad $\dfrac{\sec\theta}{1-\tan\theta} = \dfrac{1}{\cos\theta - \sin\theta}$
\begin{align*}
    \onslide<2->{\dfrac{\frac{1}{\cos\theta}}{1-\frac{\sin\theta}{\cos\theta}} &= \dfrac{1}{\cos\theta-\sin\theta}} \\[12pt]
    \onslide<3->{\dfrac{\frac{1}{\cos\theta}}{1-\frac{\sin\theta}{\cos\theta}}&} \onslide<4->{\left(\dfrac{\cos\theta}{\cos\theta}\right)}   \\[12pt]
    \onslide<5->{\dfrac{1}{\cos\theta-\sin\theta} &= \dfrac{1}{\cos\theta-\sin\theta}}
\end{align*}
\end{frame}

\begin{frame}{Example 6}
(d) \quad $6\sec\theta\tan\theta = \dfrac{3}{1-\sin\theta} - \dfrac{3}{1+\sin\theta}$   \newline\\
\begin{align*}
    \onslide<2->{6\sec\theta\tan\theta &= 6\left(\dfrac{1}{\cos\theta}\right)\left(\dfrac{\sin\theta}{\cos\theta}\right)} \\[18pt]
    \onslide<3->{&= \dfrac{6\sin\theta}{\cos^2\theta}}
\end{align*}
\end{frame}

\begin{frame}{Example 6 \quad $6\sec\theta\tan\theta = \frac{3}{1-\sin\theta} - \frac{3}{1+\sin\theta}$}
\begin{align*}
    \dfrac{3}{1-\sin\theta} - \dfrac{3}{1+\sin\theta} &= \onslide<2->{\dfrac{3}{1-\sin\theta}\left(\dfrac{1+\sin\theta}{1+\sin\theta}\right) - \dfrac{3}{1+\sin\theta}\left(\dfrac{1-\sin\theta}{1-\sin\theta}\right)} \\[12pt]
    \onslide<3->{&= \dfrac{3+3\sin\theta}{1-\sin^2\theta} - \dfrac{3-3\sin\theta}{1-\sin^2\theta}} \\[12pt]
    \onslide<4->{&= \dfrac{3+3\sin\theta -3+3\sin\theta}{\cos^2\theta}} \\[12pt]
    \onslide<5->{&= \dfrac{6\sin\theta}{\cos^2\theta}}
\end{align*}
\end{frame}

\begin{frame}{Example 6}
(e) \quad $\dfrac{\sin\theta}{1-\cos\theta} = \dfrac{1+\cos\theta}{\sin\theta}$ \quad (Half-Angle Tangent Identity)
\begin{align*}
    \onslide<2->{\dfrac{\sin\theta}{1-\cos\theta} &}
    \onslide<3->{\left(\dfrac{1+\cos\theta}{1+\cos\theta}\right)}   \\[12pt]
    \onslide<4->{\dfrac{\sin\theta(1+\cos\theta)}{1-\cos^2\theta}&} \\[12pt]
    \onslide<5->{\dfrac{\sin\theta(1+\cos\theta)}{\sin^2\theta}&}    \\[12pt]
    \onslide<6->{\dfrac{1+\cos\theta}{\sin\theta}&}
\end{align*}
\end{frame}

\end{document}


%% LaTeX Beamer presentation template (requires beamer package)
%% see http://bitbucket.org/rivanvx/beamer/wiki/Home
%% idea contributed by H. Turgut Uyar
%% template based on a template by Till Tantau
%% this template is still evolving - it might differ in future releases!

\documentclass{beamer}
\mode<presentation>
{
	\usetheme{Singapore}
	\setbeamertemplate{footline}[frame number]
	\usefonttheme{serif}

	\setbeamertemplate{navigation symbols}{}
    \setbeamertemplate{caption}[numbered]
% 	\setbeamercovered{transparent}
}

\usepackage{graphics}

\usepackage{mathtools}
\DeclarePairedDelimiter\ceil{\lceil}{\rceil}
\DeclarePairedDelimiter\floor{\lfloor}{\rfloor}

\title{Tutorial}

%\subtitle{}

%\author{Hengfeng Wei}

% \institute[Universities of]
% {
% 	Institute of Computer Software, NJU
% }

\date{\today}

% If you have a file called "university-logo-filename.xxx", where xxx
% is a graphic format that can be processed by latex or pdflatex,
% resp., then you can add a logo as follows:

% \pgfdeclareimage[height=0.5cm]{university-logo}{university-logo-filename}
% \logo{\pgfuseimage{university-logo}}

% Delete this, if you do not want the table of contents to pop up at
% the beginning of each subsection:
\AtBeginSubsection[]
{
	\begin{frame}<beamer>
		\frametitle{Tutorial}
		\tableofcontents[currentsection]
	\end{frame}
}

\AtBeginSection[]
{
	\begin{frame}<beamer>
		\frametitle{Tutorial}
		\tableofcontents[currentsection]
	\end{frame}
}
% If you wish to uncover everything in a step-wise fashion, uncomment
% the following command:

%\beamerdefaultoverlayspecification{<+->}

\begin{document}

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

\begin{frame}
	\frametitle{Tutorial}
	\tableofcontents
% You might wish to add the option [pausesections]
\end{frame}

%%%%%%%%%%%%%%%
\section{Amortized Analysis}

\begin{frame}
  \frametitle{Basic}
  \begin{quote}
    Amortized analysis is a strategy for analyzing \\
    \textcolor{blue}{a sequence of operations} to show that \\
    \textcolor{blue}{the average cost per operation} is small, \\
    even though a \textcolor{blue}{single operation within the sequence might be
    expensive}.
  \end{quote}

  \vspace{0.30cm}
  Key points:
  \begin{itemize}
    \setlength{\itemsep}{3pt}
    \item $\neq$ average-case analysis; \textcolor{red}{no probability here}\\
    (\textsc{Quick-Sort}, \textsc{HashTable})
    \item worst-case analysis; upper-bound
    \item on operation sequence; not on separate operations
    \item cheap ops (often) vs. expensive ops (occasionally)
  \end{itemize}
\end{frame}

\begin{frame}
  \frametitle{Basic}

  Methods:
  \begin{itemize}
    \setlength{\itemsep}{3pt}
    \item summation method
    \begin{itemize}
      \item the op sequence is known and easy to analyze
      \item sum and then average
    \end{itemize}
    \item accounting method
    \begin{itemize}
      \item impose an extra charge on inexpensive ops and use it to pay
      for expensive ops later on
    \end{itemize}
  \end{itemize}
\end{frame}

\begin{frame}
  \frametitle{Example for Summation Method}

  \begin{example}[Binary Counter]
    \begin{itemize}
      \item start from 0
	  \item \textsc{Increment}
	  \item measure: \emph{bit flip}
      \item cost sequence: $1,2,1,3,1,2,1,4,1,2,1,3,1,2,1,5,\ldots$
      \item think globally about each bit:
        \[
          \sum_{i=0}^{\floor{\log n}} \floor{\frac{n}{2^i}} < n
          \sum_{i=0}^{\infty} \floor{\frac{1}{2^i}} = 2n
        \]
      \item average cost per op: $2$
    \end{itemize}
  \end{example}
\end{frame}

\begin{frame}
  \frametitle{Accounting Method}

  Accounting method: \\
  \emph{amortized cost = actual cost + accounting cost}
  \[
    \hat{c_i} = c_i + a_i, a_i >=< 0.
  \]
  \[
    \forall n, \sum_{i=1}^{n} \hat{c_i} = \sum_{i=1}^{n} c_i + \sum_{i=1}^{n}
    a_i
  \]
  \begin{itemize}
    \item upper bound: the \emph{total amortized cost} of a sequence of ops must
    be an upper bound on the \emph{total actual cost} of the sequence
        \[ \forall n, \sum_{i=1}^{n} \hat{c_i} \geq \sum_{i=1}^{n} c_i
          \Rightarrow \textcolor{red}{\forall n, \sum_{i=1}^{n} a_i \geq 0}
        \]
	\item put the accounting cost on specific objects
  \end{itemize}
\end{frame}

\begin{frame}
  \frametitle{Example for Accounting Method}

  \begin{example}[Binary Counter]
    To show that $\hat{c_i} = 2$:
    \begin{itemize}
      \item low-level bit: $0 \to 1 (c=2 = 1:set+1:accouting)$
      \item put the accounting (1) on the bit 1; number of 1s = sum of
      accounting $\geq 0$
      \item $1 \to 0 (c=0)$
      \item \textsc{Increment} $\hat{c_i} = 2: (0 \to 1) + (1 \to 0)$; \emph{at
      most $0 \to 1$}
    \end{itemize}
  \end{example}

  \begin{block}{Remarks}
    \begin{itemize}
      \item \emph{you cannot say:} cost per operation = 2
      \item \emph{you should say:} average cost per operation over any operation
      sequence $\leq$ 2
      \item constant vs. variable
      \item \textsc{Decrement}? how to support \textsc{Decrement} in $O(1)$?
    \end{itemize}
  \end{block}
\end{frame}

\begin{frame}
  \frametitle{Table Expansion}

  \begin{example}[Table Expansion]
    \begin{itemize}
      \item ``double when it is full''
      \item \textsc{Table-Insert}
      \item measure: \emph{elementary insert}
    \end{itemize}
    \begin{itemize}
      \item Summation Method: \\
        \emph{a sequence of $n$ \textsc{Table-Insert}}
        \begin{itemize}
          \item \begin{displaymath}
					c_i = \left\{ \begin{array}{ll}
					i & \textrm{if $i-1$ is an exact power of 2}\\
					l & \textrm{o.w.}
					\end{array} \right.
				\end{displaymath}
		  \item \[
				  \sum_{i=1}^{n} c_i \leq n + \sum_{j=0}^{\floor{\lg n}} 2^j < n + 2n = 3n.
		  		\]
        \end{itemize}
    \end{itemize}
  \end{example}
\end{frame}

\begin{frame}
  \frametitle{Table Expansion}

  \begin{example}[Table Expansion]
    \begin{itemize}
      \item ``double when it is full''
      \item \textsc{Table-Insert}
      \item measure: \emph{elementary insert}
    \end{itemize}
    \begin{itemize}
      \item Accounting Method: \\
        \emph{why $\hat{c_i} = 3$? why not 2?}
        \begin{itemize}
          \setlength{\itemsep}{3pt}
          \item check $\hat{c_i} = 2 = 1 (insert) + 1 (move)$
		  \item problem: $2 \Rightarrow 4 (\textrm{after expansion}, \sum a_i = 0)
		  \Rightarrow 8$
		  \item so, $\hat{c_i} = 3 = 1 (insert) + 1 (\textrm{move itself}) + 1
		  (\textrm{give a hand})$
		  \item Meta-method: \textcolor{red}{trial and error}
        \end{itemize}
    \end{itemize}
  \end{example}
\end{frame}

\begin{frame}
  \frametitle{Insertion Cost (4.2.7)}

  \begin{example}[Insertion Cost (4.2.7)]
    \begin{itemize}
      \item \textsc{Insert}
      \item measure: create + merge ($2m$)
    \end{itemize}
    Summation Method:

	  \[
		\sum_{i=1}^{n} c_i = \sum_{j=0}^{\lfloor \log n \rfloor} \lfloor \frac{n}{2^j} \rfloor 2^j \le n (\lfloor \log n \rfloor + 1)
	  \]

    Accounting Method:
      \begin{itemize}
        \item $\hat{c_i} = 1 + \lfloor \log n \rfloor$
        \item consider each inserted element
        \item to check $\sum a_i = \sum_{i} (\lg n - D_{a_i}) \geq 0$
      \end{itemize}
  \end{example}
\end{frame}

\begin{frame}
  \frametitle{Union Find}

  \begin{example}[Union Find]
    \begin{itemize}
      \item \textsc{Make-Set}
      \item \textsc{wUnion}
      \item \textsc{cFind}: beautiful code ($P_{289}$, $P_{508}$)
      \item $\hat{c}$ \emph{are different}
      \item worst-case
    \end{itemize}
  \end{example}
\end{frame}
%%%%%%%%%%%%%%%
\section{Adversary Argument}

\begin{frame}
  \frametitle{Basic}

  \begin{itemize}
    \item lower bound
      \[ T(A) = \max_{I} T(A,I) \]
      \[ T(P) = \min_{A} \max_{I} T(A,I) \]
    \item two directions: \uppercase{Sorting}
		\[ n! \Rightarrow n^2 (cards) \Rightarrow n \lg n (\textrm{John von
		Neumann}@1948) \Rightarrow ??? \]
		\[ n \Rightarrow n \lg n \]
    \item adversary argument
      \begin{itemize}
        \setlength{\itemsep}{3pt}
        \item alg vs. adversary
        \item \emph{alg says:} I have a dream
        \item \emph{adversary says:} pay something \textcolor{red}{necessary}
        \item adversary strategy: also an alg; \textcolor{red}{How to construct
        it?}
        \item finding min and max; finding the second largest; \\
        finding median; horse racing; matrix search
      \end{itemize}
  \end{itemize}
\end{frame}

\begin{frame}
  \frametitle{Finding the Median}

  \begin{example}[Finding the Median]
    \begin{itemize}
      \item decision tree
		\begin{itemize}
		  \item tree vs. alg
		  \item path vs. execution on input
		  \item internal node vs. comparison
		  \item leaf vs. output
		\end{itemize}
      \item $\forall$ leaf, $x^{\ast}$: every other keys are comparable to
      $x^{\ast}$. \textcolor{red}{why?}
      \item critical comparison (first): $\forall y, \exists y \textrm{ vs. } z:
      y > z \geq x^{\ast} \textrm{ or } y < z \leq x^{\ast}$
		\begin{itemize}
		  \item path, internal node
		  \item \emph{alg:} how do I know?
		  \item \emph{adversary:} no, you don't know. It is my \emph{private
		  classification}.
		  \item \emph{alg:} so you can cheat!
		  \item \emph{adversary:} no, look at this path; critical, critical,
		  non-critical $\ldots$ (example)
		\end{itemize}
    \end{itemize}
  \end{example}
\end{frame}

\begin{frame}
  \frametitle{Finding the Median}

  \begin{example}[Finding the Median]
    Adversary: \emph{to enfore critical comparisons + non-critical operations as
    many as possible}
    \begin{itemize}
      \item critical: $n-1$
      \item non-critical:
        \begin{itemize}
          \item $L;N;S$
          \item \textsc{Compare}$(x,y)$ until $|L| = \frac{n-1}{2}$ or $|R| =
          \frac{n-1}{2}$
          $$N,N;N,S; S,N;N,L; L,N;$$
          $$L,S; S,L;$$
          $$L,L; S,S \textrm{(\emph{maybe critical}; however no new } L, S)$$
        \end{itemize}
      \item \emph{alg:} do $|L| = \frac{n-1}{2}$ at least; via \textsc{Compare}
      \item \emph{adversary:} $1 L$ per compare at most; all non-critical
      \item \emph{alg:} at least $\frac{n-1}{2}$ non-critical comparisons
    \end{itemize}
  \end{example}
\end{frame}

\begin{frame}
  \frametitle{Horse Racing}

  \begin{example}[Horse Racing]
    \begin{itemize}
      \item 25;5;3
      \item 7 rounds
      \item adversary argument
        \begin{itemize}
          \item $< 5$: \textcolor{red}{why?}
          \item $= 5$: which is the fastest?
          \item $= 6$: to know the fastest, you must run the five first ranked
          \textcolor{red}{why?}
          \item $= 6$: which is the second? ($a_2, b_1$)
        \end{itemize}
    \end{itemize}
  \end{example}
\end{frame}

\begin{frame}
  \frametitle{Matrix Search}

  \begin{example}[Matrix Search ($P_{246}$, 5.24)]
    \begin{itemize}
      \item $M[n][n]$; row; column
      \item $n^2 \Rightarrow T(n) = 3T(\frac{n}{2}) + O(1) = n^{\lg 3}
      \Rightarrow 2n-1$
      \item $2n-1:$ check the below-left corner element
      \item worst case: check the two diagonals $i+j=n-1,i+j=n$
      \item adversary \textsc{Compare$(x, M[i,j])$}:
      \[
        i + j \leq n-1 : x > M[i,j]; i + j > n-1 : x < M[i,j]
      \]
      \item \emph{alg:} at least check every element in two diagonals
      \item \emph{adversary:} eliminates 1 at most per comparison
      \item \emph{alg:} at least $2n-1$ comparisons
    \end{itemize}
  \end{example}
\end{frame}

%%%%%%%%%%%%%%%%%%
\section{Other Problems}

\begin{frame}
  \frametitle{Other Problems}

  \begin{itemize}
    \setlength{\itemsep}{5pt}
    \item 4.2.3: sorted, distinct; $O(\lg n)$; $a_i = i$; binary search; $T(n)
    = T(\frac{n}{2}) + O(1)$
    \item 4.2.5: search for two numbers; $x = a+b$;

    \textcolor{red}{extension: sorted};

    Ex: 1,2,3,5,8,9;2,3,4,6,10,12 \textcolor{red}{[proof or counterexample]}
    \item 4.2.6: closed address hashing
    	\[
    	  Q_k = (\frac{1}{n})^k (1-\frac{1}{n})^{n-k} \binom{n}{k}
    	\]
    \item 4.1.4,4.1.5,4.1.6: binomial tree
    \item 2.1.2: $H \leq N -1$
  \end{itemize}
\end{frame}
%%%%%%%%%%
% \section*{Summary}
% \begin{frame}
%   \frametitle{}
%
% %   \begin{figure}[htp]
% % 	\centering
% % 	  \includegraphics[scale = 0.40]{figure/thankyou.png}
% %   \end{figure}
% \end{frame}
%%%%%%%%%%
\end{document}


\documentclass[12pt]{article}
\usepackage[a4paper, bindingoffset=0.2in, %
							left=0.5in,right=0.5in,top=0.5in,bottom=0.5in,%
							footskip=.25in]{geometry}
\usepackage{graphicx}
\usepackage{listings}
\usepackage{amssymb}
\usepackage{amsmath}
\usepackage{hyperref}

\title{PSet1 Report}
\author{Ali Abolhassanzadeh Mahani}
%\date{Oct. 15}

\begin{document}
	\maketitle
	\section{The Koch Fractal Set}
	I used the \texttt{Turtle} tool in the \texttt{python} library set to draw the \emph{koch fractal set}. I made a class called \texttt{Koch} that takes in the
	\texttt{level} and \texttt{max\_level} as inputs and creates the koch fractal
	recursively. Then,
	there's the \texttt{draw()} method in \texttt{Koch} that gets called recursively to draw the koch fractal.
	I drew it to level 5 and output used a snipping tool to take a sceenshot of it.(Fig\ref{fig:koch})
	\begin{figure}[h!]
		\centering
		\includegraphics[width=.9\linewidth]{../P1/koch.png}
		\label{fig:koch}
		\caption{Koch fractal set, drawn to level 5. The length is reaching the pixel size
			now.}
	\end{figure}
	\section{The Serpinski Fractal Set}
		\subsection{Deterministic}
		I created a class for \texttt{Serpinski} and a module to \texttt{add\_subset}. Then a module to recursively go through the \texttt{sub\_sets} and draws them using \texttt{plt.fill()}. This method is very
		inefficient. A better way is to append the coordinates to a single array recursively and then draw it. This
		way makes it much faster. plt is so damn slow! (:face\_palming).

		The generated set with 8 levels of subsets is shown in Fig\ref{fig:serpDet}.
		\begin{figure}[h!]
			\centering
			\includegraphics[width=.9\linewidth]{../P2/fractalstuff.jpg}
			\label{fig:serpDet}
			\caption{The level 8 serpinski fractal set.}
		\end{figure}
		\subsection{Randomized}
		Here I added a module to the \texttt{Serpinski} class called \texttt{is\_bound()} which takes
		the coordinates of the point and recursively justifies if the point is in the serpinski fractal
		boundary. If yes, then I save the point coordinates. After I successfully find 50000 dots, I
		draw them using \texttt{plt.scatter(x, y, s=0.1)} where \texttt{s=0.1} refers to the markersize
		which is set to 0.1 pt. Now Here's the Simulation for the level 8 fractal from the previous
		subsection. (Fig \ref{fig:serpRAND})
		\begin{figure}[h!]
			\centering
			\includegraphics[width=0.9\linewidth]{../P3/fractalstuff.jpg}
			\label{fig:serpRAND}
			\caption{find 50000 radom particles for the level 8 serpinski fractal from
				Fig\ref{fig:serpDet}}
		\end{figure}
	\section{Random Deposition}
	\subsection{Intro}
	In oder to work with Random Depostion, I made a function that generates the canvas,
	\texttt{n} times. This fucntion calls another function that generates the canvas
	\emph{once}. This, then, calls a function that deploys a particle using the rule that it's been
	given -- e.g. the Ballistic Deposition rule or the Competitve BD rule.

	\textbf{Equations to be used:}\\
	\emph{!! Note: $L$ is the length of the surface, $t$ is time, $w$ is width (roughness)}
	\begin{equation}
		w(L, t) = t^{\beta}, \, t \ll t_s
		\label{eq:beta}
	\end{equation}
	\begin{equation}
		t_s = L^z
		\label{eq:z}
	\end{equation}
	\begin{equation}
		w_s = t_s^\beta = L^{\beta z} = L^\alpha
		\label{eq:alpha}
	\end{equation}

	After generating the graphics once, I shutdown (\texttt{comment out}) the graphics part and do the calculations. I fit the curve using polyfit and reported the value for $\beta$
	\subsection{Random Deposition}
	The graphics to lay 25 layers is shown in Fig \ref{fig:RD25}
	\begin{figure}[h!]
		\centering
		\includegraphics[width=.9\linewidth]{../P4/canvas.jpg}
		\label{fig:RD25}
		\caption{Randomly deposit particles on the surface of length 200 and change  color every 2000 particles you deposit. Do this for 50000 particles}
	\end{figure}
	The value for $\beta$ using eq.\ref{eq:beta} is as follows:
	\begin{equation*}
		\beta = 0.44 \pm 0.02
	\end{equation*}
	And the plot is shown at Fig.\ref{fig:RD25beta}
	\begin{figure}[h!]
				\centering
		\includegraphics[width=.9\linewidth]{../P4/plot_for_beta.jpg}
		\label{fig:RD25beta}
		\caption{Take the stdev of height as roughness ($w(L, t)$) for every layer you deposit.
		do this 10 times and find the error of each layer. Then plot and fit using
		\texttt{plt.errorbar} and \texttt{scipy.optimize.curve\_fit} respectively.}
	\end{figure}
	\subsection{Random Deposition with Surface Relaxation}
	The canvas for this part is shown in Fig\ref{fig:RDSR}.
	\begin{figure}[h!]
		\centering
		\includegraphics[width=.9\linewidth]{../P5/canvas.jpg}
		\label{fig:RDSR}
		\caption{deposit 100000 particles using the RDSR rule and output the data.}
	\end{figure}
	In order to reach saturation we need
	at least about 50000 particles. to make the plot (Fig\ref{fig:RDSRplot}) I ran the simulation 10 times with 800
	layer deposits total. The value for $t_s$ was output by looking at the graph and getting
	the data that was closest to the values we were looking for.
	The value found for beta is:
	\begin{figure}[h!]
		\centering
		\includegraphics[width=0.9\linewidth]{../P5/plot_for_beta.jpg}
		\label{fig:RDSRplot}
		\caption{Plot log-log of roughness over time for RDSR}
	\end{figure}
	\begin{equation*}
		\beta = 1.64 \pm 0.06
	\end{equation*}
	The values for length $L$, saturation width $w_s$ and saturation time $t_s$ is as follows:
	\begin{equation*}
		\begin{aligned}
			L		 &= [10, 50, 100, 150, 200, 250]\\
			t_s		&= [32, 3072, 16384, 49152, 131072, 1048276]\\
			w_s	  &= [0.6, 1.1, 1.678, 2.725, 2.789, 3.558]
		\end{aligned}
	\end{equation*}

	These values are plotted using the file \texttt{plots.py}. Plot fittings also happen there.

	Values found for $beta$ and $z$ are as follows:
	\begin{equation*}
		\beta = 0.18 \pm 0.02, \qquad z = 2.97 \pm 0.24, \qquad \Rightarrow \alpha \simeq 0.547
	\end{equation*}
	plots for $beta$ and $z$ are found in Fig\ref{fig:beta_z}

	The theoretical value for $\beta$ is $0.24$ and alpha, $0.47$ which gives a percentile
	error of $\eta_\beta = 25\%$ and $\eta_\alpha = \%$ respectively
	\begin{figure}[h!]
		\centering
		\includegraphics[width=.4\linewidth]{../P5/beta.jpg}
		\includegraphics[width=.4\linewidth]{../P5/z.jpg}
		\label{fig:beta_z}
		\caption{The left log-log plot is for $w_s$ over $t_s$ and the one on the right is for
		$t_s$ over length$L$. These plots are to measure $beta$, $z$ and $alpha$ in RDSR}
	\end{figure}

	\subsection{Ballistic Deposition}
	The canvas for this part is shown in Fig\ref{fig:BD}.
\begin{figure}[h!]
	\centering
	\includegraphics[width=.9\linewidth]{../P6/canvas.jpg}
	\label{fig:BD}
	\caption{deposit 20000 particles using the BD rule, change colors every 2000 particles and output the data.}
\end{figure}
In order to reach saturation we need
at least about 50000 particles. to make the plot (Fig\ref{fig:BDplot}) I ran the simulation 10 times with 800
layer deposits total. The value for $t_s$ was output by looking at the graph and getting
the data that was closest to the values we were looking for.
The value found for beta is:
\begin{figure}[h!]
	\centering
	\includegraphics[width=0.9\linewidth]{../P6/plot_for_beta.jpg}
	\label{fig:BDplot}
	\caption{Plot log-log of roughness over time for BD with surface length 200 and 1000 layers laid. Data taken for every $2^n$ particles laid}
\end{figure}
\begin{equation*}
	\beta = 0.44 \pm 0.02
\end{equation*}
The values for length $L$, saturation width $w_s$ and saturation time $t_s$ is as follows:
\begin{equation*}
	\begin{aligned}
		L		 &= [10, 50, 100, 150, 200, 250]\\
		t_s		&= [64, 1024, 3072, 4096, 8192, 32768]\\
		w_s	  &= [1.5, 4.40, 5.5, 7.2, 7.5, 9.0]
	\end{aligned}
\end{equation*}

These values are plotted using the file \texttt{plots.py}. Plot fittings also happen there.

Values found for $beta$ and $z$ are as follows:
\begin{equation*}
	\beta = 0.30 \pm 0.04, \quad z = 1.75 \pm 0.17  \Rightarrow \alpha \simeq 0.521
\end{equation*}
plots for $beta$ and $z$ are found in Fig\ref{fig:BDbeta_z}

The theoretical value for $\beta$ is $0.21$ and alpha, $0.48$ which gives a percentile
error of $\eta_\beta = 43\%$ and $\eta_\alpha = 8.5\%$ respectively
\begin{figure}[h!]
	\centering
	\includegraphics[width=.4\linewidth]{../P6/beta.jpg}
	\includegraphics[width=.4\linewidth]{../P6/z.jpg}
	\label{fig:BDbeta_z}
	\caption{The left log-log plot is for $w_s$ over $t_s$ and the one on the right is for
		$t_s$ over length$L$. These plots are to measure $beta$, $z$ and $alpha$ in BD}
\end{figure}

	\subsection{Competitive Ballistic Deposition}
	The dynamics of this system is very similar to that of BD. The canvas plot is shown in Fig\ref{fig:CBD}
	\begin{figure}[h!]
		\includegraphics[width=0.9\linewidth]{../P7/canvas.jpg}
		\label{fig:CBD}
		\caption{The plot for laying  8000 particles using the CBR rules and  initial conditions. Chnage color every 2000 particles.}
		\end{figure}

		The plot for the Distance is available in Fig\ref{fig:CBDdist}. I generated the canvas 10 times and got the mean and sdtev and error for plot.
		\begin{figure}[h!]
			\includegraphics[width=.9\linewidth]{../P7/dist_plot.jpg}
			\label{fig:CBDdist}
			\caption{Distance of the index of the right most and left most part of the canvas that is active. over time. Collect data for every 200 particles laid. I generated the canvas 10 times and got the mean and sdtev and error for plot.}
	\end{figure}

\end{document}


\documentclass{article}

\usepackage[american]{babel}
\usepackage[T1]{fontenc}
\usepackage{xcolor, fullpage, hyperref, listings, enumitem, sectsty}
\usepackage{fullpage}
\usepackage{graphicx}
\graphicspath{ {./Graphics/} }

\sectionfont{\color{blue}}  % sets colour of sections
\subsectionfont{\color{blue}}

\hypersetup{
    colorlinks=true,
    linkcolor=blue,
    filecolor=magenta,
    urlcolor=cyan,
}

\newcommand{\hlite}[1]{%
  \colorbox{yellow!50}{#1} }
\newcommand{\units}{\,\mathrm}

\title{\color{blue}\texttt{problem2tex} \\ \normalsize{version = 0.8.5 (2021-06-15)}}

\author{
David Johns, \\ \texttt{david.johns@icewire.ca}
}
\date{Document Date - 2021-06-15}

\begin{document}

\maketitle
\tableofcontents

\section{The need for problem to tex}

Latex is an excellent way to create educational material such as textbooks, examples, exams, and problem sets.  The purpose of \texttt{problem2tex} creating a .tex file is to allow one to create a numerical example (or problem) .prb file so that parameters can change and have the solution be automatically updated for that choice of parameters.  In addition, \texttt{problem2tex} has an expression solver that is used to quickly write the solution for an example (or problem).

Example usage:\\
\texttt{problem2tex -export=example.tex -random=false -sigDigits=4 example.prb}

\section{Installation and Setup}

For installation/setup of problem2tex, see \href{https://www.icewire.ca}{https://www.icewire.ca}

\section{Running problem2tex}

\subsection{Command Line Options}

The command line options for \texttt{problem2tex} are the following:
\begin{itemize}
\item \texttt{-help}
\begin{itemize}
\item[] Print out help info
\end{itemize}
\item \texttt{-version}
\begin{itemize}
\item[] Print out version info
\end{itemize}
\item \texttt{-export=\textcolor{blue}{path}/filename.tex}
\begin{itemize}
\item[] where the output should be placed
\item[] \textcolor{blue}{path} is the directory path that can include .. or . and subdirectories
\end{itemize}
\item \texttt{-random=\textcolor{blue}{option}}
\begin{itemize}
\item[] where option is one of ... (problem to tex option)
\item[] \textcolor{blue}{true}: Parameters are randomized
\item[] \textcolor{blue}{false}: Parameters are the first values in the sets (default setting)
\item[] \textcolor{blue}{positive integer}: Seed for random number generator
\item[] \textcolor{blue}{min}: All smallest numbers
\item[] \textcolor{blue}{max}: All largest numbers
\item[] \textcolor{blue}{minMax}: Random mix of largest and smallest numbers

\end{itemize}
\item \texttt{-sigDigits=\textcolor{blue}{value}}
\begin{itemize}
\item[] where value is an integer that sets the default number of significant digits in the output (If not specified, then it is set to 4).  RunConfig can also be used to set number of significant digits.
\end{itemize}
\end{itemize}

\subsection{Error Logging}

When running problem2tex, error information is placed as comments at the beginning of the output .tex file.  If things do not work as you expect, check the error log information first as Latex error information can sometimes be misleading.

\subsection{Examples}

problem2tex is a way to make problems have parameters that can change and the solution is re-calculated for that solution.  In addition, the solution is easily written as equations which are then displayed as latex solutions.  For this to work, problem2tex has a built-in expression solver similar to Julia or Matlab.

This example is available at \href{https://www.icewire.ca/examples/testBasic.zip}{testBasic.zip}

In this example, basic01.prb is a user generated problem file and contains the following text:
\begin{lstlisting}
\runParam{x = [2, 3, 4, 5]}
\runParam{y = [6, 7, 8, 9] }
\runParam{k = [8]}
\question Given \val={x}, \val={y}, and \val={k} find $z = x^2+y-k$\\
\textbf{Solution}\\
\run(){z=x^2+y-k}\\
\hlite{\val={z}}
\end{lstlisting}

For the above problem, $x$, $y$ and $k$ are all parameters where $x$ is any one of 2,3,4 or 5 and
y is any one of 6,7,8 or 9 and k is 8.  For the solution, it is simply written as the equation and a built-in expression solver solves the expression and writes it out in correct Latex form.  The solution in this case is written as

\begin{lstlisting}
\run(){z=x^2+y-k}
\end{lstlisting}

and when running with the following command\\
\begin{lstlisting}
problem2tex -export=example.tex example.prb
\end{lstlisting}
the following tex file is created ...
\begin{lstlisting}
% Created with problem2tex: version = (version info)
\question Given \mbox{$x = \mbox{$2 \units{ }$}$}, \mbox{$y = \mbox{$6 \units{ }$}$},
and \mbox{$k = \mbox{$8 \units{ }$}$} find $z = x^2+y-k$\\
\textbf{Solution}\\
\mbox{$z=x^2+y-k  = (2)^2+(6)-(8)$}\\
\hlite{\mbox{$z = \mbox{$2 \units{ }$}$}}
\end{lstlisting}

The command \textbackslash mbox is used so that inline equations can be used either within or outside other inline equations.  The command \textbackslash units is used to improve the font when displaying units (there are no units for this example).

In the same testBasic.zip file, the second example basic01.prb contains the following text:
\begin{lstlisting}
\runParam{V_1 = [2, 3, 4, 5]# \units{V}}
\runParam{R_1 = [6, 7, 8, 9]# \units{k \Omega}}
\question Given \val={V_1} and \val={R_1}, find the current  $I_R = V_1/R_1$\\
\textbf{Solution}\\
\run(){I_R=V_1/R_1}\\
\hlite{\val={I_R}}
\end{lstlisting}

What is interesting here is that units can be assigned to parameters and the expression solver takes into account unit prefixes to generate the correct solution value prefix (i.e, f, p, n, $\mu$, m, k, M, G, etc).

Also related to units, the units for any variable can be set using the \textbackslash units\{\} command.  In addition, a parameter in runConfig called defaultUnits can be used to set the default units depending on the first letter of the variable. (see runConfig)

\textbf{NOTE: micro uses \textbackslash mu (and not the letter u)}

In this example, the above 2 problem files are included in a filed called basic.tex which contains the following text:
\begin{lstlisting}
\documentclass[11pt]{exam}
\usepackage{import,xcolor}
\newcommand{\incProb}[1]{
    \immediate\write18{problem2tex -export=Problems/tmp/#1.tex
    -random=false -sigDigits=4 Problems/#1.prb}
  \import{Problems/tmp/}{#1.tex}
}
\newcommand{\hlite}[1]{%
  \colorbox{yellow!50}{#1} }
\newcommand{\units}{\,\mathrm}

\begin{document}
\begin{questions}

\incProb{basic01}
\incProb{basic02}

\end{questions}
\end{document}
\end{lstlisting}

The tex file is using the exam class (for question numbering) and has 3 commands defined: \textbackslash incProb; \textbackslash hlite; \textbackslash units.

When the above basic.tex is compiled as a text document, the following output is generated:

\begin{itemize}
% Created with problem2tex: version = 0.8.2 (2021-02-09)
\item[1.] Given \mbox{$x = \mbox{$2 \units{ }$}$}, \mbox{$y = \mbox{$6 \units{ }$}$}, and \mbox{$k = \mbox{$8 \units{ }$}$} find $z = x^2+y-k$
\item[] \textbf{Solution}\\
\mbox{$z=x^2+y-k  = (2)^2+(6)-(8)$}\\
\hlite{\mbox{$z = \mbox{$2 \units{ }$}$}}

\vspace{10px}
% Created with problem2tex: version = 0.8.2 (2021-02-09)
\item[2.] Given \mbox{$V_{1} = \mbox{$2 \units{ V}$}$} and \mbox{$R_{1} = \mbox{$6 \units{k \Omega}$}$}, find the current  $I_R = V_1/R_1$
\item[] \textbf{Solution}\\
\mbox{$I_{R}=V_{1}/R_{1}  = (2)/(6e3)$}\\
\hlite{\mbox{$I_{R} = \mbox{$333.3 \units{\mu A}$}$}}
\end{itemize}

In this case, all default parameters are used but it is one line change to obtain random parameters and change the significant number of digits.

\begin{lstlisting}
problem2tex -export=Problems/tmp/#1.tex -random=true -sigDigits=6 Problems/#1.prb
\end{lstlisting}

When run using the above random flag, one example random case is the following:
(each run will be random)

\begin{itemize}
% Created with problem2tex: version = 0.8.2 (2021-02-09)
\item[1.] Given \mbox{$x = \mbox{$5 \units{ }$}$}, \mbox{$y = \mbox{$8 \units{ }$}$}, and \mbox{$k = \mbox{$8 \units{ }$}$} find $z = x^2+y-k$
\item[] \textbf{Solution}\\
\mbox{$z=x^2+y-k  = (5)^2+(8)-(8)$}\\
\hlite{\mbox{$z = \mbox{$25 \units{ }$}$}}

\vspace{10px}
% Created with problem2tex: version = 0.8.2 (2021-02-09)
\item[2.] Given \mbox{$V_{1} = \mbox{$3 \units{ V}$}$} and \mbox{$R_{1} = \mbox{$7 \units{k \Omega}$}$}, find the current  $I_R = V_1/R_1$
\item[] \textbf{Solution}\\
\mbox{$I_{R}=V_{1}/R_{1}  = (3)/(7e3)$}\\
\hlite{\mbox{$I_{R} = \mbox{$428.571 \units{\mu A}$}$}}
\end{itemize}

\subsection{Configuration settings}
Configuration settings can be changed at any time and then they are used going forward until
changed again.  Configuration settings can be changed using the \textbackslash runConfig command.

Example: \textbackslash runConfig\{random = min\}

\begin{itemize}
\item random - choice of false, true, min, max, minMax and positive integer
\begin{itemize}
\item[] - false:  defaults elements chosen
\item[] - true: random elements chosen
\item[] - min: min sized elements chosen
\item[] - max: max sized elements chosen
\item[] - minMax: random choice of min and max sized elements chosen
\item[] - positive integer: seed for random generator so same elements can be chosen
\end{itemize}
\item fmtVal - format of output values for \textbackslash val
\begin{itemize}
\item[] - set as \textbackslash runConfig\{format=X\} where X is one of ...\\
(the number of significant digits can be from 1-9)
\item[] - E4 for engineering format with 4 significant digits
\item[] - S4 for scientific format with 4 significant digits
\item[] - D4 for decimal format with 4 significant digits
\item[] - \$ for dollar format (always has 2 digits after decimal point)
\item[] - U4 for SI format (including units) with 4 significant digits
\item[] - DEFAULT IS U4
\end{itemize}
\item fmtRun= - format of output values after equal in \textbackslash run= or \textbackslash run()= commands
\begin{itemize}
\item[] - Same as format above
\item[] - DEFAULT IS U4
\end{itemize}
\item fmtRun() - format of output values in bracketed numbers in \textbackslash run() or \textbackslash run()= commands
\begin{itemize}
\item[] - Same as format above except U format not allowed
\item[] - DEFAULT IS E4
\end{itemize}
\item KFactor - Used for default set generation if \textbackslash runParam sets var to a nominal number.
\begin{itemize}
\item[] - Set KFactor example: \textbackslash runConfig\{KFactor = 1.5:5\} where 1.5 is the factor and 5 is the number of elements in the set.
\item[] - Factor must be a number greater than 1.
\item[] - The range of the elements are from nominal/factor to nominal*factor and are geometrically spaced.
\end{itemize}
\item defaultUnits - used to set the default units depending on the first letter of a variable
\begin{itemize}
\item[] - example: \textbackslash runConfig\{defaultUnits = [[iI:A][vV:V][R:\textbackslash Omega]]\}
\item[] - above example results in variables starting with the letter i or I having default units of "A"
\item[] - variables starting with letter v or V having default units of "V"
\item[] - variables starting with letter R having default units of "\textbackslash Omega"
\item[] - use of \textbackslash units within a run command will override the default unit setting
\end{itemize}
\item verbose - choice of true or false (default false)
\begin{itemize}
\item[] - prints out the elements sets in commented out lines in the .tex file (useful for debugging)\item[] - Also prints out the configuration settings
\end{itemize}
\end{itemize}

\subsection{Commands for .prb files}

There are 4 main commands for problem to tex:
\begin{itemize}
\item \textbackslash runConfig (discussed above)
\item \textbackslash runParam
\item \textbackslash run
\item \textbackslash val
\end{itemize}

\subsubsection{\textbackslash runParam command}
The command \textbackslash runParam can be used to set configuration parameters (see above) as well as being used for setting the randomly generated parameters.

\begin{itemize}
\item \textbackslash runParam\{var = [x1, x2, x3, ...]\# \textbackslash units\{\textcolor{blue}{units}\} \textbackslash symbol\{\textcolor{blue}{varLatex}\} \}
\begin{itemize}
\item[] - var will be a random selection from the set of x1, x2, x3, ...
\item[] - if random=false, the default value for var is the first element
\item[] - if \textbackslash units\{\textcolor{blue}{units}\} is present, then the units for that variable will be \textcolor{blue}{units}
\item[] - if \textbackslash symbol\{\textcolor{blue}{varLatex}\} is present, then when printing out, var will be replaced with \textcolor{blue}{varLatex}
\end{itemize}
\item \textbackslash runParam\{var = min;max;stepsize\# \textbackslash units\{\textcolor{blue}{units}\} \textbackslash symbol\{\textcolor{blue}{varLatex}\} \}
\begin{itemize}
\item[] - The set for var will be generated from min;max;stepsize
\item[] - The first element will be min so the default will be the min element
\item[] - Otherwise, it is the same as the array generation above
\end{itemize}
\item \textbackslash runParam\{var = nominal\# \textbackslash units\{\textcolor{blue}{units}\} \textbackslash symbol\{\textcolor{blue}{varLatex}\} \}
\begin{itemize}
\item[] - The set for var will be generated from nominal and the KFactor configuration parameter
\item[] - KFactor: factor:numElements... factor is a number greater than 1 and numElements is a positive integer (numElements is the number of elements in the set).
\item[] - Elements range from nominal/factor to nominal*factor and are geometrically spaced
\item[] - Example: if nominal is 10 and factor is 1.5, then the range is from 6.667 to 15
\item[] - The default is nominal which would be 10 in the above example
\item[] - Otherwise, it is the same as the array generation above
\end{itemize}
\end{itemize}
\subsubsection{\textbackslash run commands}

The commands \textbackslash run are used for evaluating expressions and setting new variables.

\textbf{The format for an expression is the same as Matlab or Julia (NOT a latex equation).}

See the Expression Solver section below for more information.

Options are the same as in \textbackslash runParam.

\textbf{In all cases below, the \textcolor{blue}{expr} is evaluated and the result is assigned to \textcolor{blue}{var}}

\begin{itemize}
\item \textbackslash run\{\textcolor{blue}{var} = \textcolor{blue}{expr} \# \textcolor{blue}{options} \}
\begin{itemize}
\item[] - Print out \textcolor{blue}{var} = \textcolor{blue}{expr}.
\item[] - There can be multiple \textcolor{blue}{var} = \textcolor{blue}{expr} separated by ";"
\end{itemize}
\item \textbackslash runSilent\{\textcolor{blue}{var} = \textcolor{blue}{expr} \# \textcolor{blue}{options}\}
\begin{itemize}
\item[] - Do not print anything out
\end{itemize}
\item \textbackslash run()\{\textcolor{blue}{var} = \textcolor{blue}{expr} \# \textcolor{blue}{options}\}
\begin{itemize}
\item[] - Print out \textcolor{blue}{var} = \textcolor{blue}{expr} AND print out intermediate () \textcolor{blue}{expr} for clarity
\end{itemize}
\item \textbackslash run=\{\textcolor{blue}{var} = \textcolor{blue}{expr} \# \textcolor{blue}{options}\}
\begin{itemize}
\item[] - Print out \textcolor{blue}{var} = \textcolor{blue}{expr} AND print out  "= result"
\end{itemize}
\item \textbackslash run()=\{\textcolor{blue}{var} = \textcolor{blue}{expr} \# \textcolor{blue}{options}\}
\begin{itemize}
\item[] - Print out \textcolor{blue}{var} = \textcolor{blue}{expr} AND print out intermediate () \textcolor{blue}{expr} AND print out "= result"
\end{itemize}
\end{itemize}

\subsubsection{\textbackslash val command}
Below is the \textbackslash val command for printing out variable value or an expression value.
\begin{itemize}
\item \textbackslash val\{\textcolor{blue}{expr,format}\}
\begin{itemize}
\item[] - Print out the result of \textcolor{blue}{expr} with format set by \textcolor{blue}{format} (see \textbackslash runConfig)
\item[] - \textcolor{blue}{,format} is optional.  If not present, then the default setting for format is used which was set by \textbackslash runConfig\{format = X\}
\item[] - \textcolor{blue}{expr} in a \textbackslash val command should NOT contain a ","
\item[] - \textcolor{blue}{expr} in a \textbackslash run command may contain ","s
\item[] - \textcolor{blue}{expr} can be a single variable or a full expression
\end{itemize}

\end{itemize}

\subsection{Expression Solver}

Problem to tex makes use of a built in expression solver to solve \textcolor{blue}{expr} within \textbackslash run\{\textcolor{blue}{expr}\}.  Expressions are made similar to Julia or Matlab.

Example valid  \textcolor{blue}{expr} are:
\begin{itemize}
\item \textbackslash run\{A = sqrt(B)*abs(-4)\}
\item \textbackslash run\{R\_4 = parll(R\_1,parll(R\_2,R\_3))\}
\end{itemize}

\subsubsection{Functions}

The functions currently known in problem2tex are:

\begin{itemize}
\item[] abs, asin, asinh, acos, acosh, atan, atanh, ceil, cos, cosh, exp, floor, log, log10, round, sin, sinh, sqrt, tan, tanh
\end{itemize}

the above make use of the math package for golang.

In addition, extra functions are:

\begin{itemize}
\item cosd(x), sind(x), tand(x)
\begin{itemize}
\item[] returns cos(x)/sin(x)/tan(x) but x value is in degrees
\end{itemize}
\item acosd(x), asind(x), atand(x)
\begin{itemize}
\item[] returns acos(x)/asin(x)/atan(x) but returns the value in degrees
\end{itemize}
\item dB(x)
\begin{itemize}
\item[] returns 10*log10(x)
\end{itemize}
\item dbV(x)
\begin{itemize}
\item[] returns 20*log10(x)
\end{itemize}
\item parll(a,b)
\begin{itemize}
\item[] returns the numeric parallel value (returns $(1/a + 1/b)^{-1}$)
\item[] the latex printout of this function is $||$ to make it more readable
\end{itemize}
\end{itemize}

\subsubsection{More on Units}

problem2tex will automatically calculate proper unit prefixes IF SI unit notation is used.  For micro, "\textbackslash mu" must be used instead of "u". In some situations, one might want to use a unit notation that is NOT SI proper.  For example, one might want to use $\units{V/\mu m}$ instead of $\units{MV/m}$.  In this case a way to achieve this is shown with the following example...

\begin{lstlisting}
\runParam{VAprime = [5,3,4,6]# \units{V/\mu m} \symbol{V_A'}}
\runParam{V_A = [6, 7, 8, 9]}
\question Given \val={VAprime} and \val={V_A}, find $L$ \\
\textbf{Solution}\\
\runSilent{VAprime = 1e6*VAprime}
\run()={L=V_A/VAprime#\units{m}}\\
\end{lstlisting}

The use of \textbackslash runSilent corrects the value for VAprime (since $\units{\mu m}$ is in the denominator of a unit) by multiplying the values by 1e6. In this example, "L" would default to units of "H" so it is corrected to meters using \textbackslash units\{m\}.

The output becomes ...

\begin{itemize}
% Created with problem2tex: version = 0.8.2 (2021-02-09)
\item[1.] Given \mbox{$V_A' = \mbox{$5 \units{ V/\mu m}$}$} and \mbox{$V_{A} = \mbox{$6 \units{ V}$}$}, find $L$ \\
\textbf{Solution}\\
\mbox{$L=V_{A}/V_A'  = (6)/(5e6) = \mbox{$1.2 \units{\mu m}$}$}\\
\end{itemize}

\section{License}

\subsection{Files created by problem2tex}

All files created by problem2tex are owned by the creators of the work (that is you) and/or by the original authors of the work in cases you use derivative works.

\subsection{Software License}

Copyright \textcopyright\ 2021 David Johns.

This license applies to problem2tex the program, it's packages, extensions and source code as published or made available through any third party.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

\end{document}


\section{Phenomenology of the MSSM}
As the first step towards  phenomenological access to the relevant parameters of the MSSM, we want to have a look at three hypothetically allowed phenomena in the MSSM, that are relatively well controlled by various experimental constraints. For specific regions of the parameter space we encounter that:

\begin{itemize}
	\item The respective lepton numbers $L_{e}$, $L_{\mu}$ and $L_{\tau}$ are not conserved.
	\item Flavor-changing neutral currents (FCNCs) are not suppressed.
	\item New sources of CP-violation are present.
\end{itemize}

\noindent In the MSSM, the non-diagonal terms in the sfermion mass matrices and in the trilinear coupling matrices can induce FCNCs.  In Figure \ref{fig:fcnc} at the beginning of the next page, an hypothetical example process describing such a FCNC is presented. These kind of phenomena are already present in the Standard Model at higher loop orders, but they are highly suppressed which can be explained for example by the GIM-mechanism \cite{GIM1970}, which relates those processes to the unitarity or the presence of complex phases in the CKM matrix. \\
The understanding of CP-violation and its sources in the SM and beyond is very important. In weak interactions CP-violation has extensive implications for the $V$-$A$ structure of the couplings and the non-trivial quark mixing (CKM matrix). Another source of possible CP-violation in the SM is given by the topological $\theta$-term. The famous Sakharov conditions tell us that we need CP-violation in order to describe baryogenesis in the Early Universe. Experimental tests of CP-violation are usually performed in the context of electric dipole moments of electrons and neutrons as well as studies of the Kaon-system. Those measurements put severe constraints on the beforehand presented sources. To give some explicit values we refer for example to \cite{Fischler1992}, where they found out that for TeV-ish sfermion and gaugino masses the absolute values of the complex phases of the gaugino mass parameters, the trilinear couplings and $\abs{\mu}$  have to be $\leq 10^{-2} - 10^{-3}$.\\
\noindent
In the MSSM the amount of new CP-violating phases has increased drastically. This now gives room for two different explanations: One possibility could be that those phases all are approximately zero (which is usually assumed) or there could be non-trivial cancellations amongst the new phases that might lead to tiny measurable effects. In the end this would be a horrible fine tuning task.

\begin{figure}[t]
\centering
\includegraphics[scale = 0.8]{figures/fcnc_diagram}
\caption{An example diagram for a hypothetical FCNC process ($s \rightarrow d$) in the MSSM involving a Bino and sdown quarks. Such processes can occur if the MSSM squark masses are flavor-violating.}
\label{fig:fcnc}
\end{figure}

\noindent With these general observations at hand we define the \enquote{phenomenological} MSSM (pMSSM) by three basic assumptions \cite{MSSMGroup1998}:

\begin{enumerate}
	\item We do not allow any additional sources of CP-violation. This is implemented by setting all phases in the soft SUSY breaking potential to zero.
	\item We also do not allow processes inducing FCNCs.  This results in a simple, diagonal structure of the sfermion and trilinear coupling matrices.
	\item We assume first and second generation universality, this means we assume that the scalar masses are the same for the first two generations. This is motivated by results on Kaon mixing which put severe constraints on the splitting of the masses. The same we do for the trilinear couplings $A^{u}, A^{d}$ and $A^{\ell}$, usually they are even set to zero since they are not important for phenomenology\footnote{Since they are proportional to the sfermion masses, only the third generation trilinear couplings have phenomenological impact.}.
\end{enumerate}
This already facilitates the general structure of the MSSM a lot! \newpage We summarize the remaining parameters in the pMSSM in the following:

\begin{itemize}
	\item $\tan\beta = v_u/v_d$, the ratio of the VEVs from the two-Higgs doublets.
	\item $m_{A}^2 = 2m_{12}^2  / \operatorname{sin} 2\beta$, the mass of the pseudoscalar Higgs boson.
	\item $M_{1}$, $M_{2}$ and $M_{3}$, the bino, wino and gluino masses.
	\item $\mu$, the Higgs-higgsino mass parameter.
	\item $m_{\tilde{q}}$, $m_{\tilde{u}_R}$, $m_{\tilde{d}_R}$, $m_{\tilde{\ell}}$ and $m_{\tilde{e}_R}$, the first/second generation sfermion masses.
	\item $m_{\tilde{Q}}$, $m_{\tilde{t}_R}$, $m_{\tilde{b}_R}$, $m_{\tilde{L}}$ and $m_{\tilde{\tau}_R}$, the third generation sfermion masses.
	\item $A^{t}$, $A^{b}$ and $A^{\tau}$, the third generation trilinear couplings.
\end{itemize}
This still leaves 19 open parameters, which makes comprehensive studies of the pMSSM computationally very expensive. In actual experiments we need to construct even more simplified models with only two or three parameters to be able to test any predictions. One possible way to construct such a \enquote{simpler} model, may be to study possible connections to gravity at high energy scales which might render the underlying structure of the theory relatively simple in the high energy regime. This idea is known as mSUGRA und we will present the general concept behind it in the next section. \\
To conclude this section we need to discuss SUSY-breaking. A key problem of the MSSM is, that it fails to give a natural explanation of the fundamental origin of the SUSY breaking parameters. In the last talks we learned about gauge- and gravity mediated SUSY breaking which might provide a way around this problem. We won't go into details here, but for a visualization of the general idea of these concepts, have a look at Figure \ref{fig:susy_breaking}.
\begin{figure}[H]
\centering
\includegraphics[scale = 1]{figures/susy_breaking}
\caption{Visualization of the idea of gravity-mediated SUSY breaking.}
\label{fig:susy_breaking}
\end{figure}
\noindent
The general idea is that the SUSY-breaking occurs in the hidden sector and is mediated at some messenger scale $M_{\mathrm{mess}}$ via fundamental interactions to the MSSM. The understanding of how SUSY breaking is \enquote{naturally} encoded in this framework might also help to facilitate phenomenological access to the MSSM.