%========================================================================
% COMPUTATIONAL PHYSICS - PROJECT 2
% STRUCTURE OF WHITE DWARF STARS
%========================================================================

\documentclass[a4paper]{IEEEtran}

\usepackage{amssymb}
\usepackage{moreverb}
\usepackage[cmex10]{amsmath}
\usepackage{cite}
\usepackage{graphicx}
\usepackage[colorlinks=false, hidelinks]{hyperref}

\usepackage{listings}
\usepackage{color}
\usepackage{xcolor}
\usepackage{microtype}
\usepackage{microtype}
\usepackage{inconsolata}
\usepackage[framemethod=TikZ]{mdframed}
\usepackage{alltt}
\usepackage{sverb}
\usepackage{verbatim}
\usepackage{pifont}
\usepackage{alltt}
\usepackage{helvet}

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

%\title{640-364 : Computational Physics -- Project 2 \\
%       Structure of White Dwarf Stars}
\title{Structure of White Dwarf Stars}
\author{Michael Papasimeon\\ August 27, 1997}
\date{August 27, 1997}

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

\newcommand{\R}{\bar{r}}
\newcommand{\M}{\bar{m}}
\newcommand{\Rho}{\bar{\rho}}
\newcommand{\bc}{begin{center}}
\newcommand{\ec}{\end{center}}

%----------------------------------------------------------------------
% CODE LISTING SETTINGS
%----------------------------------------------------------------------

\lstset{language=fortran,
        %basicstyle=\footnotesize\ttfamily,
        basicstyle=\small\ttfamily,
        columns=fullflexible,
        %title=\lstname,
        numbers=left, stringstyle=\texttt,
        numberstyle={\tiny\texttt},
        keywordstyle=\color{blue},
        commentstyle=\color{darkgreen},
        stringstyle=\color{purple} }

\mdfsetup{skipabove=\topskip, skipbelow=\topskip}

\definecolor{codebg}{rgb}{0.99,0.99,0.99}

\global\mdfdefinestyle{code}{%
    frametitlerule=true,%
    frametitlefont=\small\bfseries\ttfamily,%
    frametitlebackgroundcolor=lightgray,%
    backgroundcolor=codebg,%
    linecolor=gray, linewidth=0.5pt,%
    leftmargin=0.5cm, rightmargin=0.5cm,%
    roundcorner=2pt,%
    innerleftmargin=5pt
}

\global\mdfdefinestyle{code2}{%
    topline=false,%
    bottomline=false,%
    leftline=true,%
    rightline=false,%
    backgroundcolor=codebg,%
    linecolor=gray, linewidth=0.5pt,%
    leftmargin=0.0cm, rightmargin=0.0cm,%
    innerleftmargin=1pt
}

\newcommand{\showcode}[1]{\begin{mdframed}[style=code] %
                            \lstinputlisting{#1}%
                          \end{mdframed}%
}

\newcommand{\showsmallcode}[1]{\begin{mdframed}[style=code2] %
        \lstinputlisting[basicstyle=\ttfamily\tiny]{#1}%
                          \end{mdframed}%
}

%----------------------------------------------------------------------
% IEEE SETTINGS
%----------------------------------------------------------------------

\interdisplaylinepenalty=2500
\setlength{\IEEEilabelindent}{\IEEEilabelindentB}

%\markboth{630--364 Computational Physics}{}
\markboth{Structure of White Dwarf Stars. Michael Papasimeon. 1997}{}

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

\begin{document}
\maketitle

\begin{abstract}
This paper was written for an undergradue class in computational physics in 1997.
It focuses on computational/numerical techniques such as Euler's and the Runge-Kutta
method of numerical integration for modelling the mass and density profiles of white
dwarf stars. The stars \emph{Sirius B} and \emph{40 Eri B} are used as case studies.
The code to compute the density profiles was written in \textsc{Fortran77} and is listed
in the paper's appendix.
\end{abstract}

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

\section{Aims}
    The purpose is to write a computer program to numerically
    solve the coupled differential equations~\ref{eq:density}
    and~\ref{eq:mass}, describing the mass profile $\M(\R)$ and density
    profile $\Rho(\R)$ of a white dwarf star.

    \begin{equation}
        \frac{d\Rho}{d\R} = - \frac{\M\Rho}{\gamma(\Rho^{1/3})\R^2}
        \label{eq:density}
    \end{equation}

    \begin{equation}
        \frac{d\M}{d\R} = \R^2\Rho
        \label{eq:mass}
    \end{equation}

    \begin{equation}
        \gamma(x) = \frac{x^2}{3\sqrt{1 + x^2}}
    \end{equation}

    The main aims are:
    \begin{itemize}
        \item Solve the differential equations first using Euler's
              method, and then the using the fourth order Runge-Kutta
              method.
        \item Compare the results of the Euler method with the results
              of the Runge-Kutta method.
        \item Obtain solutions for $\M(\R)$ and $\Rho(\R)$ (and hence
              $\bar{M}$ and $\bar{R}$)
              for different values of the central density $\rho_c$.
        \item Investigate the mass and density profiles for large
              values of the central density.
        \item Solve the differential equations for the white dwarf stars
              Sirius B and 40 Eri B.
    \end{itemize}

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

\section{Background on White Dwarf Stars}
There are two main forces at work in white dwarf stars. The first
is the force of gravity caused by the mass of the star. Most of the star's
mass is due to the mass of all the nuclei of the atoms which make up
the star. Although stars are made primarily of lighter elements such
as Hydrogen and Helium, heavier nuclei such as Carbon ($^{12}$C) and
Iron ($^{56}$Fe) also make a large contribution to the mass of the star.

The other important force present in a white dwarf is that which is
generated by the electron degeneracy pressure. Due to high temperatures
in a star, the electrons are very energetic, are not bound to nuclei
and move around in a Fermi gas. The electron degeneracy pressure
is due to the Pauli exclusion principle.

Therefore, it is when the gravitational force and the force caused
by the electron degeneracy pressure are in equilibrium, that the
white dwarf is stable and does not collapse in on itself.

If $P$ is the electron degeneracy pressure we can equate the corresponding
force $dP/dr$ with Newton's law of gravitation.
\begin{equation}
    -\frac{Gm(r)\rho(r)}{r^2} = \frac{dP}{dr}
\end{equation}
where $G$ is the gravitational constant, $r$ is the radius,
$m(r)$ is the mass profile, and $\rho(r)$ is the density profile.

From this we can differential equations relating the mass and density
with the radius.
\begin{equation}
    \frac{d\rho}{dr} = -\left(\frac{dP}{d\rho}\right)^{-1}\frac{Gm(r)\rho(r)}{r^2}
\end{equation}
\begin{equation}
    \frac{dm}{dr} = 4\pi r^2 \rho(r)
\end{equation}
To find the equation of state for $P$, the electrons in the star can
be treated as a Fermi gas of $N$ electrons. Using statistical mechanics,
we calculate the average occupation number of the electron gas and hence
the total energy (using relativistic calculations because the electrons
are very energetic). The energy is calculated because it allows us to
calculate the pressure, because $P = -dE/dV$.
From this we find that
\begin{equation}
    \frac{dP}{d\rho} = Y_e \frac{m_e}{m_p} \gamma(x)
\end{equation}
where $Y_e$ is the number of electrons per nucleon, $m_e$ is the electron
mass, $m_p$ is the nucleon (proton) mass and $\gamma(x) = x^2/(3\sqrt{1+x^2})$.
Equations 5 and 6 then become the coupled differential equations describing the
mass and density profiles of a white dwarf star which are now given by:
\begin{equation}
    \frac{d\rho}{dr} = -\frac{m_p G}{Y_e m_e} %
                        \frac{m(r)\rho(r)}{r^2 \gamma([ \frac{\rho}{\rho_0}]^{1/3}) }
\end{equation}
\begin{equation}
    \frac{dm}{dr} = 4\pi r^2 \rho(r)
\end{equation}
These equations are scaled to make it easier to solve them by computer.
The corresponding scaled equations which are solved are equations 1 and 2.

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

\section{Method}
    The method followed was:
    \begin{itemize}
        \item Write a FORTRAN program to solve the
              coupled differential equations for a white
              dwarf star using Euler's method.
        \item Modify the program, by adding a subroutine to solve
              the differential equations using the fourth order
              Runge-Kutta method. A flow chart showing a rough outline
              of the algorithm is shown in Figure~\ref{fig:runge-kutta}.
        \item The source code for the program (\texttt{star.f}) is
              in Appendix A.
        \item The code was written so that the program stops if
              the density $\bar{\rho}$ becomes negative. This is
              because an error is generated when the program attempts
              to compute $\bar{\rho}^{1/3}$ when $\bar{\rho} < 0$.
    \end{itemize}

    \begin{figure}
    \caption{Flow Chart for Runge-Kutta Method}
    \label{fig:runge-kutta}
    \begin{center}
        \includegraphics[width=\columnwidth,angle=-90]{figures/flow.eps}
    \end{center}
    \end{figure}

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

%\newpage
\section{Results}

%------------------------------------------------------------------------

    \subsection{Comparing Euler and Runge-Kutta Methods}
    Table~\ref{tbl:euler-runge-kutta} shows the values obtained for $\bar{M}$
    and $\bar{R}$ using Euler's and Runge-Kutta methods for
    a step size, $h = 0.01$ and central density $\rho_c = 10.0$.

    \begin{table}
    \caption{Comparing Euler and Runge-Kutta for $h=0.01$.}
    \label{tbl:euler-runge-kutta}
    \begin{center}
    \begin{tabular}{c|ccc} \hline
    $h$                 & Euler     & Runge-Kutta & Expected\\ \hline
    $\bar{M}$           & 1.550     & 1.580       & 1.58    \\
    $\bar{R}$           & 1.313     & 1.298       & 1.298\\ \hline
    \end{tabular}
    \end{center}
    \end{table}

    We can see from Table~\ref{tbl:euler-runge-kutta}
    that the Runge-Kutta method is more accurate.

    \subsubsection{Mass Profile}
    Figures~\ref{fig:mass-euler} and~\ref{fig:mass-runge-kutta}
    show the mass profile of a white dwarf star
    calculated using Euler's and the Runge-Kutta methods with:
    \begin{itemize}
        \item Step size $h = 0.01$
        \item $\rho_c = 10.0$
    \end{itemize}

    \begin{figure}
    \caption{Plot of $\bar{m}(\bar{r})$ using Euler's method.}
    \label{fig:mass-euler}
    \begin{center}
        \includegraphics[width=\columnwidth]{figures/mass-euler-01}
    \end{center}
    \end{figure}

    \begin{figure}
    \caption{Plot of $\bar{m}(\bar{r})$ using fourth order Runge Kutta.}
    \label{fig:mass-runge-kutta}
    \begin{center}
        \includegraphics[width=\columnwidth]{figures/mass-rk-01}
    \end{center}
    \end{figure}

    \subsubsection{Density Profile}
    Figures~\ref{fig:density-euler} and~\ref{fig:density-runge-kutta}
    show the density profile of a white dwarf star
    calculated using Euler's and the Runge-Kutta methods with:
    \begin{itemize}
        \item Step size $h = 0.01$
        \item $\rho_c$ = 10.0
    \end{itemize}

    \begin{figure}
    \caption{Plot of $\bar{\rho}(\bar{r})$ using Euler's method.}
    \label{fig:density-euler}
    \begin{center}
        \includegraphics[width=\columnwidth]{figures/density-euler-01}
    \end{center}
    \end{figure}

    \begin{figure}
    \caption{Plot of $\bar{\rho}(\bar{r})$ using fourth order Runge Kutta.}
    \label{fig:density-runge-kutta}
    \begin{center}
        \includegraphics[width=\columnwidth]{figures/density-rk-01}
    \end{center}
    \end{figure}

%------------------------------------------------------------------------

    \subsection{Investigating Stability with different step sizes}
    Table~\ref{tbl:R-M-euler} and~\ref{tbl:R-M-runge-kutta}
    show values of $\bar{R}$ and $\bar{M}$, with
    the central density $\rho_c = 10.0$, for different step
    sizes $h$ using both the Euler and the Runge-Kutta methods.

    The first observation is that the Runge-Kutta algorithm reaches
    the answer faster as we increase the step size. This is to
    be expected as we know it provides more accurate results
    than the Euler algorithm.

    By looking at the column for $\bar{M}$, we see that the Runge-Kutta
    algorithm is more stable than the Euler algorithm as we decrease
    the step size.

    \begin{table}
    \caption{$\bar{R}$ and $\bar{M}$ for different values of the
             step size $h$, using Euler's method.}
    \label{tbl:R-M-euler}
    \begin{center}
    \begin{tabular}{r|rr} \hline
    $h$         &   $\bar{R}$   &   $\bar{M}$       \\ \hline
    0.1         &   1.3         &   1.47581763      \\
    0.01        &   1.55        &   1.31320078      \\
    0.001       &   1.587       &   1.29950998      \\
    0.0001      &   1.5911      &   1.29816256      \\
    0.00001     &   1.59157     &   1.29802791      \\
    0.000001    &   1.591623    &   1.29801445      \\ \hline
    \end{tabular}
    \end{center}
    \end{table}

    \begin{table}
    \caption{$\bar{R}$ and $\bar{M}$ for different values of the step
             size $h$, using fourth order Runge-Kutta.}
    \label{tbl:R-M-runge-kutta}
    \begin{center}
    \begin{tabular}{r|rr} \hline
    $h$         &   $\bar{R}$   &   $\bar{M}$       \\ \hline
    0.1         &   1.5         &   1.29518167      \\
    0.01        &   1.58        &   1.29799616      \\
    0.001       &   1.591       &   1.29801293      \\
    0.0001      &   1.5916      &   1.29801295      \\
    0.00001     &   1.59162     &   1.29801295      \\
    0.000001    &   1.591629    &   1.29801295      \\ \hline
    \end{tabular}
    \end{center}
    \end{table}

    \subsection{Investigation of mass and density at large central densities}
    Figure~\ref{fig:mass-profiles} and~\ref{fig:density-profiles}
    plot the mass and density profiles for
    the white dwarf star for a range of values of the central density $\rho_c$,
    (with $Y_e = 1$), using the fourth order Runge-Kutta algorithm with
    a step size of $h = 0.01$.
    These plots are the solutions for $\bar{\rho}(\bar{r})$ and $\bar{m}(\bar{r})$,
    of~\ref{eq:density} and~\ref{eq:mass}.

    Using the solutions to the differential equations we determine
    $\bar{R}$ and $\bar{M}$ for the different values of $\rho_c$.
    These results are shown in Table~\ref{tbl:central-density}.

    \begin{table}
    \caption{$\bar{R}$ and $\bar{M}$ for $h = 0.01$ at different
              values of the central density $\rho_c$.}
    \label{tbl:central-density}
    \begin{center}
    \begin{tabular}{r|rr} \hline
    $\rho_c$&   $\bar{R}$   &   $\bar{M}$       \\ \hline
    0.1     &   2.57        &   0.22178884     \\
    1       &   2.49        &   0.70706357     \\
    10      &   1.58        &   1.29799616     \\
    100     &   0.95        &   1.73552752      \\
    1000    &   0.53        &   1.93285505      \\
    10000   &   0.27        &   1.99681784      \\
    100000  &   0.13        &   2.01300131      \\
    1000000 &   0.05        &   1.76970419      \\ \hline
    \end{tabular}
    \end{center}
    \end{table}

    As the central density increases, the mass of the star increases.
    As the central density increases the radius decreases because there
    is more mass and hence the star is falling in on itself yet there still
    exists the equilibrium between the gravitational force and the electron
    degeneracy pressure. However, a smaller radius increases the gravitational
    field of the star, since we know from Newton's law of gravitation
    the gravitational force proportional to $1/r^2$.

    \begin{equation}
        F_g = -\frac{GmM}{r^2}
    \end{equation}

    Therefore, the greater the mass and the smaller the radius of the
    star the greater the gravitational force of the star, pushing the star
    in on itself.

    For extremely high values of the central density, the resulting radius
    and mass may by be so high it results in an extremely large gravitational
    field which is too strong for it to stay in equilibrium and hence
    the assumptions made about equations~\ref{eq:density} and~\ref{eq:mass}
    no longer hold and the star will collapse in on itself. Then depending on
    the mass of the star it may become a neutron star, or if the mass is
    extremely large, a black hole.

    Figure~\ref{fig:mass-profiles} shows the computed mass profiles for different values of
    $\rho_c$ and Figure~\ref{fig:density-profiles} shows the computed density profiles
    for different values of $\rho_c$.

    %\subsubsection{Mass profiles for different values of $\rho_c$}

    \begin{figure*}
    \caption{Mass profiles for different values of $\rho_c$}
    \label{fig:mass-profiles}
    \begin{center}
    \begin{tabular}{p{7cm}p{7cm}}
        $\rho_c = 0.1$ \newline \includegraphics[width=7cm]{figures/0-1m.eps} &
        $\rho_c = 1.0$ \newline \includegraphics[width=7cm]{figures/1m.eps}
        \\
        $\rho_c = 10.0$ \newline \includegraphics[width=7cm]{figures/10m.eps}  &
        $\rho_c = 10^2$ \newline \includegraphics[width=7cm]{figures/100m.eps}
        \\
        $\rho_c = 10^3$ \newline \includegraphics[width=7cm]{figures/1000m.eps}  &
        $\rho_c = 10^4$ \newline \includegraphics[width=7cm]{figures/10000m.eps}
        \\
        $\rho_c = 10^5$ \newline \includegraphics[width=7cm]{figures/100000m.eps}  &
        $\rho_c = 10^6$ \newline \includegraphics[width=7cm]{figures/1000000m.eps}
        \\
    \end{tabular}
    \end{center}
    \end{figure*}

    %\subsubsection{Density profiles for different values of $\rho_c$}

    \begin{figure*}
    \caption{Density profiles for different values of $\rho_c$}
    \label{fig:density-profiles}
    \begin{center}
    \begin{tabular}{p{7cm}p{7cm}}
        $\rho_c = 0.1$ \newline \includegraphics[width=7cm]{figures/0-1rho.eps} &
        $\rho_c = 1.0$ \newline \includegraphics[width=7cm]{figures/1rho.eps}
        \\
        $\rho_c = 10.0$ \newline \includegraphics[width=7cm]{figures/10rho.eps}  &
        $\rho_c = 10^2$ \newline \includegraphics[width=7cm]{figures/100rho.eps}
        \\
        $\rho_c = 10^3$ \newline \includegraphics[width=7cm]{figures/1000rho.eps}  &
        $\rho_c = 10^4$ \newline \includegraphics[width=7cm]{figures/10000rho.eps}
        \\
        $\rho_c = 10^5$ \newline \includegraphics[width=7cm]{figures/100000rho.eps}  &
        $\rho_c = 10^6$ \newline \includegraphics[width=7cm]{figures/1000000rho.eps}
        \\
    \end{tabular}
    \end{center}
    \end{figure*}

    \section{Calculations for Sirius B and 40 Eri B}

    For values of $Y_e \not= 1$, we have:
    \[ M(Y_e) = Y_{e}^2 \frac{M_0}{M_{sun}} \bar{M}(Y_e = 1)\]
    \[ R(Y_e) = Y_e \frac{R_0}{R_{sun}} \bar{R}(Y_e = 1)\]
    Using values from Koonin~[1] we can calculate:

    \[ \frac{M_0}{M_{sun}} =
        \frac{5.67 \times 10^{33} Y_e^2 gm}{1.98 \times 10^{33} gm} =  2.863636 Y_e^2\]

    \[ \frac{R_0}{R_{sun}} =
        \frac{7.72 \times 10^8 Y_e cm}{6.95 \times 10^{10} cm} = 1.11079 \times 10^{-2} Y_e\]

    \subsection{Sirius B}

    \begin{itemize}
        \item $M = 1.053 \pm 0.028$
        \item $R = 0.0074 \pm 0.0006$
    \end{itemize}

    Table~\ref{tbl:results-sirius-b} shows the results for the radius $R$, for the program
    running for a number of different central densities. Here $R$ is:

    \[ R = Y_e \frac{R_0}{R_{sun}} \bar{R}(Y_e = 1) \]

    \begin{table}
        \caption{Results for Sirius B}
        \label{tbl:results-sirius-b}
        \begin{center}
        \begin{tabular}{r|crr} \hline
        $\rho_c$    &   $\bar{R}(Y_e=1)$   & R ($Y_e = 0.5)$ & R ($Y_e = 0.464$)\\ \hline
        10.0        &   1.58        & 0.00877525071    & 0.00814343218   \\
        15.0        &   1.45        & 0.00877525071    & 0.00814343218   \\
        16.0        &   1.45        & 0.00805323641    & 0.00747340295 \\
        18.0        &   1.40        & 0.00777553860    & 0.00721569940\\
        20.0        &   1.37        & 0.00760891992    & 0.00706107727   \\
        22.0        &   1.34        & 0.00744230123    & 0.00690645514  \\ \hline
        \end{tabular}
        \end{center}
    \end{table}

    We see from Table~\ref{tbl:results-sirius-b} that the central density of Sirius B is:
    \begin{itemize}
        \item $\rho_c = 22.0$ (Solar Units) for $Y_e = 0.5$ (Carbon)
        \item $\rho_c = 16.0$ (Solar Units) for $Y_e = 0.464$ (Iron)
    \end{itemize}

    We see that these results are within error. Sirius B has a mass very similar
    to that of the Sun but a much smaller radius. This implies that the density
    of Sirius B is greater than the Sun, resulting in a smaller radius.
    What this means is that the atoms which make up Sirius B are likely to
    be heavier than those in the Sun. We are more likely to find greater
    amounts of heavy nuclei such as Carbon and Iron.
    Without knowing the exact proportions of Carbon and Iron in Sirius B,
    we can only estimate the the central density of this what dwarf is
    somewhere in the range $16.0 \leq \rho_c \leq 22.0$ in solar units.

    \subsection{40 Eri B}

    \begin{itemize}
        \item $M = 0.48 \pm 0.02 $
        \item $R = 0.0124 \pm 0.0005 $
    \end{itemize}

    Table~\ref{tbl:results-40-eri-b} shows the results for $R$, with the program running
    with different values of the central density.

    \begin{table}
        \caption{Results for 40 Eri B}
        \label{tbl:results-40-eri-b}
        \begin{center}
            \begin{tabular}{r|crr} \hline
            $\rho_c$    &   $\bar{R}(Y_e=1)$   & R ($Y_e = 0.5)$   & R ($Y_e = 0.464$)\\ \hline
            1.0         &   2.49        & 0.0138293508      & 0.0128336368 \\
            1.2         &   2.41        & 0.0133850343      & 0.0124213111 \\
            1.5         &   2.31        & 0.0128296387      & 0.0119059040 \\
            1.7         &   2.25        & 0.0124964013      & 0.0115966597 \\
            2.0         &   2.19        & 0.0121631640       & 0.0112874155 \\
            3.0         &   2.02        & 0.0112189914      & 0.0104112234 \\
            5.0         &   1.83        & 0.0101637397      & 0.0094319499 \\
            6.0         &   1.76        & 0.0097749628     & 0.0090711649 \\ \hline
            \end{tabular}
        \end{center}
    \end{table}

    We see from Table~\ref{tbl:results-40-eri-b} that the central density of 40 Eri B is:
    \begin{itemize}
        \item $\rho_c = 1.7$ (Solar Units) for $Y_e = 0.5$ (Carbon)
        \item $\rho_c = 1.2$ (Solar Units) for $Y_e = 0.464$ (Iron)
    \end{itemize}

    We see that 40 Eri B has mass that is is approximately half that of
    the Sun, and a radius only 1\% that of the Sun's. However we see that
    the central density of 40 Eri B is in the range $1.2 \leq \rho_c \leq 1.7$
    in solar units. If a star half the like the Sun where to have it's radius
    reduced to 1\% of it's original size, it's density would increase
    dramatically because:
        \[ \rho = \frac{M}{V} = \frac{M}{\frac{4}{3} \pi r^3} \]
    This suggests that that the atoms in 40 Eri B are lighter than those
    found in the Sun. It is likely that 40 Eri B consists almost totally
    of Hydrogen and Helium, with only traces of heavier nuclei.

    \section{References}
        \begin{enumerate}
            \item \emph{Computational Physics}, Koonin and Meredith
        \end{enumerate}

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

    \onecolumn
    \appendix[Code Listing: star.f]
    \showcode{src/star.f}

\end{document}

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


\documentclass[12pt,a4paper]{article}
\title{\Huge {Notes}}
\author{Author name}
\date{}

%%%%%%%%%%%%%%Declare PACKAGES%%%%%%%%%%%%%%%%%%

\usepackage{mathtools}  % or use \usepackage{amsmath}
\DeclareMathSizes{12}{12}{8}{8}    %math font sizes
%\DeclareMathSizes{12}{20}{14}{10}  %try for size 12 text

%Uncomment the following for LaTeX helvetica clone
\usepackage[utf8]{inputenc}
\renewcommand{\familydefault}{\sfdefault}
\usepackage{helvet}

%Use XeLatex to render the following
%\usepackage{fontspec}
%\setromanfont[
%BoldFont=HelveticaLTStd-Blk.otf,
%ItalicFont=HelveticaLTStd-Light.otf,
%]{HelveticaLTStd-Roman.otf}

\usepackage[english]{babel}  %for labelling tables, graphics with english text. Use Finnish for finnish labelling
%\usepackage[official]{eurosym}	%euro symbol

%\usepackage{verbatim}      %for commenting huge blocks and dummy text
\usepackage{blindtext}

%Paragraph and Line spacing
\setlength{\parindent}{0pt}	%set paragraph indent to 0 points
\setlength{\parskip}{1em}  %spacing between paragraphs
\renewcommand{\baselinestretch}{1.5}    % set line spacing to 1.5

% Definition of \maketitle
\makeatletter
\def\@maketitle{
\raggedright
%\includegraphics[width = 40mm]{logo.jpg}\\[8ex]
\begin{center}
{\Huge \bfseries \sffamily \@title }\\[4ex]
{\LARGE  \@author}\\[4ex]
{\large\@date}\\[8ex]
%\includegraphics[width=60mm]{metropolia-logo.png}    %logo in the title page
\end{center}}
\makeatother

\usepackage{graphicx}		%for putting pictures
\usepackage{float}            %for putting pictures at specified point

\usepackage{geometry} %Finnish document margins%
\geometry{
 a4paper,
 left=2cm,
 right=1.5cm,      %in reality has to 1cm
 top=1cm,
 bottom=2cm,
 }

\usepackage{fancyhdr}     %package for fancy header and footers
\usepackage{lastpage}     %records the last page number
\pagestyle{fancy}
\fancyhf{} % sets both header and footer to nothing
\renewcommand{\headrulewidth}{0pt}

% your new footer definitions here
\cfoot{}
\lfoot{}
\rfoot{\thepage\ (\pageref{LastPage})}

\usepackage{hyperref}  		%for links
\hypersetup{colorlinks,breaklinks,
            urlcolor=[rgb]{0,0.5,0.5},
            linkcolor=[rgb]{0,0.5,0.5}}    %set link color to Teal

\begin{document}
\maketitle
\tableofcontents
\thispagestyle{empty}      %remove numbering from bottom since pagestyle is empty
%\clearpage
\newpage
%\listoffigures
%\thispagestyle{empty}      %remove numbering from bottom
%\clearpage
%\newpage
\setcounter{page}{1}        % set page counter from this page to 1

\section{Section 1}
\subsection{Subsection 1}
Static friction:
$$
F_{s_{max}} = \mu_s F_N
$$
where $F_{s_{max}}$ is the maximum static friction , $\mu_s$ is the coefficient of static friction and $F_N$ is the normal force perpendicular to the static friction force.

$$F_{s_{max}} = \mu_s F_N$$
$$\mu_s = F_{s_{max}}/F_N$$
$$    = F_{s_{max}}/9.8m $$where m is the mass of the load

$$ =  \frac{5.061 N}{0.7858 kg * 9.8 m/s^2} $$

$$ \mu_s = 0.65 $$

\subsection{Subsection 2}
\begin{figure}[H]
\includegraphics[width=\linewidth]{test}
\caption{\textit{Dark souls}}
\label{Indictment in dark souls}
\end{figure}

\begin{table}[H]
\centering
\begin{tabular}{|c|c|}
\hline
\textbf{Range} & \textbf{Resolution} \\
\hline
$\pm$ 10 N	& 0.01 N \\
\hline
$\pm$ 50 N	& 0.05 N \\
\hline
\end{tabular}
\caption{\textit{Simple table}}
\label{table:Force sensor resolution}
\end{table}

\section{Section 2}
\subsection{Subsection 1}
\paragraph{Definition of terms}
\begin{itemize}
\item Amplitude ($A$) is the difference in height from highest (maximum) to lowest (minimum) point divided by 2 within a single period ($T$). In other words, it is the function of the magnitude of the difference between the variables extreme values.
\item Period ($T$) denotes a single complete cycle of a periodic motion. Second ($s$) is the most common unit used.  $T = \frac{1}{f}$
\item Frequency $f$ describes how many times an event occurs in a single unit of time. In physics, frequency is most often applied to waves. It is denoted in Hertz $(Hz)$.  $f = 1/T$
\item Angular frequency $(\omega)$ measures angular displacement (radians) per unit time (seconds).
\item Kinematics of a periodic harmonic motion
	\begin{itemize}
	\item Displacement $(x), x = A sin(\omega t)$
	\item Velocity $(v), v = A\omega cos(\omega t), v = \pm \omega \sqrt{A^2-x^2}$
	\item Acceleration $(a), a = -A\omega^2 sin(\omega t)$
	\end{itemize}
\end{itemize}

\subsection{Subsection 2}
\blindtext

\end{document}


\documentclass[12pt]{article}

\usepackage[margin=1.1in]{geometry}
\input{../../syllabi/preamble}

%%edit these!!
\newcommand{\coursedept}{Math}
\newcommand{\coursenumber}{369}
\newcommand{\sixhundredsection}{690.03 }
\newcommand{\coursenumbercrosslisted}{/ \sixhundredsection}
\newcommand{\semester}{Fall}
\newcommand{\numcredits}{3}
\newcommand{\lectimeandloc}{Tues and Thurs 5 -- 6:15PM / on zoom}
\newcommand{\requiredlabtimeandloc}{}
\newcommand{\tataofficehourtimeandloc}{TA / TA Office Hours / Loc & Kennly Weerasinghe / see \coursewebpagelink}
\newcommand{\numtheoryhws}{6--9}
\newcommand{\lastdatetimetohandinhomeworks}{Dec 15 at noon}
\newcommand{\midtermonedateandlocation}{Thursday, October 7 on zoom during class time}
\newcommand{\midtermtwodateandlocation}{Thursday, November 11 on zoom during class time}
\newcommand{\finaldateandlocation}{TBD but on zoom}

%%%unchanged
\newcommand{\coursewebpageurl}{https://github.com/kapelner/QC_\coursedept_\coursenumber_\semester_\the\year}
\newcommand{\coursewebpagelink}{\href{\coursewebpageurl}{course homepage}}
\newcommand{\slackurl}{https://QC\coursedept\coursenumber\semester\the\year.slack.com/}
\newcommand{\slacklink}{\href{\slackurl}{slack}}

\input{../../syllabi/_header}

\section*{Course Overview}

MATH 369 is an introduction to the intermediate concepts of mathematical statistics, statistical inference and theory of experimentation. I plan to follow the curriculum when I taught the class previously and the homepage of the previous course can be found \href{https://github.com/kapelner/QC_Math_369_Fall_2020}{here}. Lectures and their topics with time estimates are below:

\input{_lecture_schedule}

\textbf{This is more of a typical mathematics theory course than the rest of the data science series but it is still not like the other math courses you're used to; it will be more philosophical and very high in conceptual density while the mathematics itself is kept deliberately simple.} But we will still attempt to keep our eye on developing ideas and concepts for helping to make decisions in the real world. Thus we may make limited use of computation using the \texttt{R} statistical language.

\subsection*{Prerequisites}

MATH 241 (basic probability), 201 (multivariable calculus) and 231 (linear algebra) or equivalents. I expect a 241 class that covers more or less what I cover in 241. See the course homepage for links under \qu{prerequisite review}. The multivariable calculus and linear algebra we will use I will try to review in class.

\section*{Course Materials}

\paragraph{Textbook:} I will be referencing Larry Wasserman's \emph{All of Statistics: A concise course in statistical inference} which can be purchased on \href{https://www.amazon.com/dp/0387402721}{Amazon} and Casella and Berger's \emph{Statistical Inference} which can be purchased on \href{https://www.amazon.com/dp/8131503941}{Amazon}. There is no excuse not to have these books. They are \textit{required}. However, I will not ususally be teaching \qu{from the book} --- most of the material in the class comes from the lecture notes. The textbooks are a way to get ``another take'' on the material and they will only cover about only half of the material done in class. For the other half, you will have to make use of other resources. I also recommend Rice's \emph{Mathematical Statistics and Data Analysis}, 3rd edition which can be purchased on \href{https://www.amazon.com/dp/0534399428}{Amazon} as well but I will not reference it during class.

\paragraph{Computer Software:} During lectures, there will be demoes using \texttt{R} which is a free, open source statistical programming language and console. You can download it from: \url{http://cran.mirrors.hoobly.com/}. I do not expect you to do \textit{any} programming. If \texttt{R} will be part of the homework, I will give you the code to run and expect you to interpret the results based on concepts explained during the course.

\paragraph{Calculator:} You can use a TI-84, 85, 89 or any calculator which you wish. I strongly suggest you use \href{http://www.wolframalpha.com/}{Wolfram Alpha} and its smartphone app.

\input{../../syllabi/_the650section}

\input{../../syllabi/_use_of_slack}
\input{../../syllabi/_announcements_on_slack}

\input{../../syllabi/_standard_class_meetings}

\input{../../syllabi/_jewish_holiday_reschedule}

\input{../../syllabi/_zoom_policies}

%\input{../../syllabi/_lecture_upload}

\section*{Homework}

\input{../../syllabi/_theory_hws_text}

\input{../../syllabi/_theory_hws_submission_text}
\input{../../syllabi/_philosophy_hws}

\input{../../syllabi/_time_spent_hws}

\input{../../syllabi/_late_hw_policy}

\input{../../syllabi/_latex_hw_bonus_policy}

\input{../../syllabi/_hw_ec_policy}

\section*{Examinations}

\input{../../syllabi/_examination_text}

\input{../../syllabi/_standard_exam_schedule}

\subsection*{Exam Policies and Materials}

\input{../../syllabi/_examination_policies}

\input{../../syllabi/_zoom_examination_policies}

\input{../../syllabi/_standard_cheat_sheet_policy}

\input{../../syllabi/_cheating_on_exams_and_missing_exams}
\input{../../syllabi/_special_services}

\input{../../syllabi/_class_participation}

%\input{../../syllabi/_zoom_attendance}

\input{../../syllabi/_standard_grading_and_grading_policy}

\input{../../syllabi/_advanced_course_grade_distribution}

\input{../../syllabi/_grade_checking_on_gradesly}

\input{../../syllabi/_auditing_policy}

\end{document}


\subsection{Stockpiling}

Let’s consider what happens if Alice tries to save money by producing more fish. If she uses the additional shells from this to buy more goods, she hasn’t saved. If she doesn’t sell them she hasn’t acquired any additional shells.

While building up stockpiles isn’t giving Alice more money now, the economy is producing more that it is consuming, and so this is an investment in the future.


\documentclass{article}
\usepackage{algpseudocode}
\usepackage{algorithm}
\usepackage[english]{babel}
\usepackage[utf8]{inputenc}
\usepackage{fancyhdr}
\usepackage{listings}
\usepackage{graphicx}
\usepackage[section]{placeins}
\usepackage{titlesec}
\usepackage{amssymb}
\usepackage{amsmath}
\usepackage[margin=1in]{geometry}
\pagestyle{fancy}
\fancyhf{}
\rhead{Rahul Shah}
\lhead{Machine Learning: Nanodegree}
\rfoot{\thepage}
\title{2.8 Model Evaluation Metrics}
\begin{document}
\maketitle
\section{Motivation}
How do we evaluate models? What metrics do we use?
\section{Dealing with Training Data}
We need to make sure our models are not overfitting, so we need to take our training data and split it into training data and testing data. Training data will be used to actually train the model, and the test data will be used to verify that the model is accurate. We can tell if the model is accurate if the test data's margin of error and the training data's margin of error are the same. Typically we split 75:25 or 80:20 training:testing.
\section{Confusion matrix}
When evaluatiing effectiveness of a classification algorithm, we can put results in a table.\\
\begin{table}[]
\begin{tabular}{cccc}
 & Guessed Class 1  & ... & Guessed Class N \\
Actual Class 1 &  &  &  \\
... &  &  &  \\
Actual Class N &  &  &
\end{tabular}
\end{table}
\\

Basically we use this to evaluate Type I (False Positive) and Type II (False Negative) error. We measure accurracy via a standard average:\\
$\frac{\Sigma True guesses}{Total}$\\

Depending on your problem, you want to punish false positives or false negatives more, and we can use the following measurements to see what proportion of positive classifications are Type 1 or Type 2 errors:\\
Recall: False positives are fine, false negatives are not: $\frac{True(+)}{True(+) + False(-)}$ (Ex. This metric is useful when testing if someone has a virus that is particularly contagious)
Precision: False negatives are fine, false positives are not: $\frac{True(+}{True(+) + False(+)$ (Ex. This metric is useful when classifying spam emails)\\
\section{The F-beta score}
To put these two measurements together to a single measurement, we use the f-beta score, which tells us a sort of weighted average between the two.\\
$F_{\beta} = (1 + \beta^2)\frac{P * R}{\beta^2 * P + R}$
\\
We choose beta closer to zero when we want to emphasize precision, and we choose beta closer to infinity when we want to emphasize recall, with the middle point being 1. We don't use arithmetic mean because if we have zero for one of the metrics and one hundred for another one of the metrics, the arithmetic mean becomes half, which is inaccurate. We want a low precision or recall to make the entire score low, because ultimately, we want both precision and recall to be high.

\section{Preventing Over/Underfitting}
We want to make sure that our test set is truly for testing accuracy, not for checking which model we want to use. So, we split the data into yet another portion, cross validation, which acts as a sort of test set but for choosing a model. So, to clarify, our data is used in the following ways:\\
Our data sets are the following:
\begin{itemize}
	\item input data coupled with the correct output (used before the final model is determined)
	\item input data with no output (used on the final model after it is determined)
\end{itemize}\\

We are only concerned with the first bullet, obviously. When training the data, we choose multiple different models to see which model represents the data the best. While training each model and trying to figure out which model works best and what weights to use in the model, we do the following:\\
\begin{itemize}
	\item Training phase: We use part of the data from the first bullet of the last list and train each of our potential models (50\%)
	\item Validation phase: We take a different part of the data and use it to test each of our models to see which one is the best model (25\%). We also use this data to estimate model properties. This set also tunes hyperparameters.
	\item Test phase: choose the model that performed best in the validation phase, and check it's accuracy.(25\%)
\end{itemize}

You only need this validation set when you are trying to see which model perform the best. Using the test set as validation is often bad because the test set rror of the final model will underestimate the true testing error, sometimes by a lot.

\subsection{K-Fold Cross Validation}
The method shown above implies that you need even more data to get a good model. Remember the model trains itself by the data we give to it, and the order by which we give the data (training and testing set) changes our final parameters. We use k-fold cross validation to train and test different splits of the data, to get a more accurate model. Basically, we take our data, randomly split it into k equal sized parts, use k-1 of those parts as training data, and 1 part as testing data. Then do that k times. We typically use $k=10$. The splitting can be done in many different ways randomly, but here are a few common methods:
\begin{itemize}
	\item stratified k-fold cross validation: the partitions are selected so the mean response value is approximately equal.
	\item repeated cross validation: split into k partitions several times, and average the performance over several runs
\end{itemize}

\subsection{Grid Search}
Often, we don't know what hyperparameters will help train the model best, so when we pick the model we want, we can use a grid search and basically test each combination of potential hyperparameters against a validation set.

\end{document}

Machine_Learning/Model Evaluation Metrics/Model Evaluation Metrics.tex


\documentclass[12pt]{article}
\usepackage{graphics}
\newcommand{\mi}{\mathrm{mi}}
\newcommand{\m}{\mathrm{m}}
\newcommand{\kg}{\mathrm{kg}}
\newcommand{\rad}{\mathrm{rad}}
\newcommand{\s}{\mathrm{s}}
\newcounter{problem}
\begin{document}
\thispagestyle{empty}

\section*{NYU Physics 1---Problem set 5}

Due Tuesday 2009 October 20 at the beginning of lecture.

\paragraph{Problem~\theproblem:}\refstepcounter{problem}%
\textsl{(a)}~Draw free-body diagrams for all the masses and pulleys in
this mechanism.  Find the tensions in all three strings and the
accelerations of the two blocks.
\\ \rule{0.35\textwidth}{0pt}
\resizebox{0.3\textwidth}{!}{\includegraphics{../mp/tackle_blocks.eps}}
\\
Be careful with your kinematic constraints---the relationships among
the accelerations of the blocks---and treat all the strings and
pulleys as massless and frictionless.

\textsl{(b)}~Now set the mass $m_2$ to the value it must have if the
system is to be perfectly ``balanced''; that is, for there to be no
net acceleration of either block.  In this situation, if block $m_1$
is lowered a distance $h$, what is the net change in potential energy,
accounting for displacements of both blocks?

\paragraph{Problem~\theproblem:}\refstepcounter{problem}%
Consider a simple harmonic oscillator with a mass of $m=0.5\,\kg$, an
angular frequency of $\omega=3.9\,\rad\,\s^{-1}$, and oscillating with
an amplitude of $0.03\,\m$.  Make time-aligned plots of the position
$x$, velocity $v$, potential energy $U$, kinetic energy $K$, and total
energy $U+K$, all as a function of time for the time period
$0<t<3\,\s$.  Clearly label the period, amplitude, and maximum and
minimum values of these plots.  In fact, label anything on your five
plots that could be useful for understanding the system.

\paragraph{Problem~\theproblem:}\refstepcounter{problem}%
Determine the value of $\pi$ by integration!

\textsl{(a)}~Make a spreadsheet with a dimensionless column marked
``$t$'' that goes from 0.0 to 20.0 in units of 0.05.  Now make columns
marked ``$c$'' and ``$s$''.  Integrate the functions $c(t)$ and
$s(t)$ with the properties that:
\begin{eqnarray}\displaystyle
c(0) & = & 1.0 \\
s(0) & = & 0.0 \\
\Delta c & = & -s\,\Delta t \\
\Delta s & = & c\,\Delta t
\end{eqnarray}
Make a graph of $c$ vs $t$ and $s$ vs $t$.  Remind you of anything?

\textsl{(b)}~Make an expanded graph in the region $1.5<t<1.6$ and
look where the curve crosses zero.  Multiply your answer by 2 and you
have an estimate of $\pi$!  Why does that work?

\textsl{(c)}~(Advanced) In part (a) you probably incremented $c$ using
the previous-line value of $s$ and incremented $s$ using the
previous-line value of $c$.  Now switch your spreadsheet to increment
$s$ using the \emph{same-line} value of $c$ (keeping the incrementing
of $c$ the same).  What changed about your graphs and why?  Did your
estimate of $\pi$ get better or worse or stay the same?

\paragraph{Extra Problem (will not be graded for credit):}\refstepcounter{problem}%
\textsl{(a)}~How much energy does it take to raise a 1-ton airplane to
a height of $100\,\mi$ above the Earth's surface?  This feat won an
``X-prize''.

\textsl{(b)}~Compare the answers you get using the standard formula
for distances near the surface of the Earth with the correct formula
taking into account the variation of the force of gravity with
distance.  Is the discrepancy large or small?  Explain the
discrepancy.

\textsl{(c)}~Compute now the orbital speed---the speed required for
the airplane to be in orbit, and not just ``flying''---at an altitude
of $100\,\mi$, using that the orbital centripetal acceleration is
provided by gravity.  Is the corresponding kinetic energy much larger
or much smaller than the energy it took to get from the Earth's
surface to the high altitude?

\end{document}


\documentclass{ecnreport}

\stud{Master 2 CORO-IMARO}
\topic{Task-based control}
\author{O. Kermorgant}

\begin{document}

\inserttitle{Task-based control}

\insertsubtitle{Lab 1: visual servoing}

\section{Goals}

The goal of this lab is to observe the image-space and 3D-space behaviors that are induced when using various visual features.

The ones that are considered are:
\begin{itemize}
 \item Cartesian coordinates of image points
 \item Polar coordinates of image points
 \item $2\frac{1}{2}$ visual servo
 \item 3D translation (either $\Pass{c}{\mathbf{t}}{o}$ or $\Pass{c*}{\mathbf{t}}{c}$)
 \item 3D rotation (either $\Pass{c}{\mathbf{R}}{c*}$ or $\Pass{c*}{\mathbf{R}}{c}$)
\end{itemize}

Several initial / desired poses are available, and some features that lead to a good behavior in some cases may lead to a undesired one in other cases.

\section{Running the lab}

The lab should be done on Ubuntu (either P-robotics room or the Virtual Machine).\\

\subsection{Virtual Machine update}
On the \textbf{virtual machine} you may need to install the \texttt{log2plot} module. If the \texttt{latest\_patch.sh} is in your home directory, just run it through: \texttt{./latest\_patch.sh}. If it is not, run the following lines (it will run it at the end):
\begin{center}\bashstyle
 \begin{lstlisting}
cd ~
git clone https://github.com/CentraleNantesRobotics/ecn_install .ecn_install
ln -s .ecn_install/virtual_machine/latest_patch.sh .
\end{lstlisting}
\end{center}

\subsection{Download and setup}

You can download the lab from github. Navigate to the folder you want to place it and call:
\begin{center}\bashstyle
\begin{lstlisting}
git clone https://github.com/oKermorgant/ecn_visualservo
cd ecn_visualservo
gqt
\end{lstlisting}
\end{center}

This will download the git repository and prepare everything for the compilation.\\
You can then open QtCreator and load the \texttt{CMakeLists.txt} file of this project.

\subsection{Lab files}

Here are the files for this project:

\begin{center}
\begin{minipage}{.4\linewidth}
 \dirtree{%
.1 ecn\_visualservo.
.2 include.
.3 feature\_stack.h.
.3 simulator.h.
.2 src.
.3 feature\_stack.cpp.
.3 simulator.cpp.
.2 CMakeLists.txt.
.2 config.yaml.
.2 main.cpp.
}
\end{minipage}
\begin{minipage}{.55\linewidth}
 Only two files are to be modified:
 \begin{itemize}
  \item \texttt{main.cpp}: to build the feature stack and control law
  \item \texttt{config.yaml}: configuration file to change which features you want to use
 \end{itemize}
\end{minipage}
\end{center}

Feel free to have a look at the other files to see how everything is done under the hood.\\

The simulation runs with the green \texttt{Run} button on the bottom left corner of QtCreator.\\
Of course, as no visual feature are used initially, the camera does not move.

\section{Implementation}

Only a few things are to be implemented in C++ to get a valid simulation: adding features to the stack, and computing the control law.

\subsection{Implement the choice of the features}

In the \texttt{main.cpp} file, a few design variables are loaded from the configuration (\texttt{useXY, usePolar}, etc.).\\

They are used to tell which features we want to use for this simulation. All these features are already available in the ViSP library, and we just have to register them inside a custom feature stack.\\

The first part of this lab is hence to add features to the stack depending on the configuration variables.\\
We assume that:
\begin{itemize}
 \item If \texttt{useXY} is \texttt{true}, we want to stack all points from the simulation with Cartesian coordinates.
 \item If \texttt{usePolar} is \texttt{true}, we want to stack all points from the simulation with polar coordinates.
 \item If \texttt{use2Half} is \texttt{true}, we want to stack:
 \begin{itemize}
  \item the center of gravity of the simulation with Cartesian coordinates
  \item the center of gravity of the simulation with depth coordinate
  \item a 3D rotation (either $\Pass{c}{\mathbf{R}}{c*}$ or $\Pass{c*}{\mathbf{R}}{c}$).\\Use \texttt{stack.setRotation3D("cdRc")} or \texttt{stack.setRotation3D("cRcd")}
 \end{itemize}
 \item The 3D translation and rotation are automatically used if they have a valid value in the configuration file:
 \begin{itemize}
  \item Translation can be \texttt{"cdTc"} ($\Pass{c*}{\mathbf{t}}{c}$) or \texttt{"cTo"} ($\Pass{c}{\mathbf{t}}{o}$)
  \item Rotation can be  \texttt{"cdRc"} ($\Pass{c*}{\mathbf{R}}{c}$) or \texttt{"cRcd"} ($\Pass{c}{\mathbf{R}}{c*}$)
 \end{itemize}
\end{itemize}
Documentation on the \texttt{FeatureStack} class is available in Appendix \ref{app:stack}. It describes how to add new features to the stack.\\

From this point, the stack is able to update the features from a given pose $\cMo$ and give the current features and their interaction matrix.

\subsection{Implement the control law}

In the main control loop, you should retrieve the current feature values \texttt{s} from the stack, and their corresponding interaction matrix \texttt{L}.\\
Then compute \texttt{v} as the classical control $\v = -\lambda\L^+(\s-\ss)$.\\

This velocity twist will be sent to the simulation and a new pose will be computed.

Some gains and parameters are loaded from the configuration: \texttt{lambda, err\_min}, etc.\\
Observe what is their influence on the simulation.

\section{Combining features}

Test that your simulation works for all types of features. \\

Initially it starts from a position tagged as \texttt{cMo\_t} in the configuration file, while the desired position is tagged as \texttt{cdMo}.

Try various combinations of starting / desired poses, together with various choices on the feature set. Typically:
\begin{itemize}
 \item Large translation / rotation error, using XY or Polar
 \item 180 error using XY
 \item Very close poses (\texttt{cMo\_visi})
\end{itemize}

What happens if many features are used at the same time, such as Cartesian + polar coordinates, or 2D + 3D features?

\subsection{On Z-estimation}

The \texttt{z\_estim} keyword of the configuration file allows changing how the Z-depth is estimated in 2D visual servoing.\\
Compare the behavior when using the current depth (negative \texttt{z\_estim}), the one at desired position (set \texttt{z\_estim} to 0) or an arbitrary constant estimation (positive \texttt{z\_estim}).

\subsection{Output files}

All simulations are recorded so you can easily compare them. They are placed in the folder:
\begin{center}
 \texttt{ecn\_visualservo/results/<start>-<end>/<feature set>/}
\end{center}
All files begin with the Z-estimation method and the lambda gain in order to compare the same setup with various gains / estimation methods.

\newpage
\appendix

\section{Class helpers}

Below are details the useful methods of the main classes of the project. Other methods have an explicit name and can be listed from auto-completion.

\subsection{The \texttt{FeatureStack} class}\label{app:stack}

This class is instanciated under the variable \texttt{stack} in the main function. It has the following methods:
\paragraph{Adding feature to the stack}
\begin{itemize}
 \item  \texttt{void addFeaturePoint(vpPoint P, PointDescriptor descriptor)}
 add a point to the stack, where \texttt{descriptor} can be:
 \begin{itemize}
  \item \texttt{PointDescriptor::XY}
  \item \texttt{PointDescriptor::Polar}
  \item \texttt{PointDescriptor::Depth}
 \end{itemize}
  \item  \texttt{void setTranslation3D(std::string descriptor)}: adds the 3D translation feature (cTo, cdTc or none)
  \item  \texttt{void setRotation3D(std::string descriptor)}: adds the 3D rotation feature (cRcd, cdRc or none)
  \item  \texttt{void updateFeatures(vpHomogeneousMatrix cMo)}: updates the features from the passed \texttt{cMo}
\end{itemize}

\paragraph{Stack information}
\begin{itemize}
 \item  \texttt{void summary()}: prints a summary of the added features and their dimensions
 \item  \texttt{vpColVector s()}: returns the current value of the feature vector
  \item  \texttt{vpColVector sd()}: returns the desired value of the feature vector
   \item  \texttt{vpMatrix L()}: returns the current interaction matrix
 \end{itemize}

\subsection{The \texttt{Simulator} class}\label{app:sim}

This class is instanciated under the variable \texttt{sim}. It has the following methods:
\begin{itemize}
 \item \texttt{std::vector<vpPoint> observedPoints()}: returns the list of considered 3D points in the simulation
 \item \texttt{vpPoint cog()}: returns the center of gravity as a 3D point
\end{itemize}

For example, to add all points of the simulation as XY features, plus the depth of the CoG, just write:

\begin{center}\cppstyle
\begin{lstlisting}
for(auto P: sim.observedPoints())
    stack.addFeaturePoint(P, PointDescriptor::XY);

stack.addFeaturePoint(sim.cog(), PointDescriptor::Depth);
\end{lstlisting}
\end{center}

\end{document}


\documentclass[11pt]{article}
\usepackage{amsmath}

\setlength{\textwidth}{7in}
\setlength{\textheight}{9in}
\setlength{\oddsidemargin}{-.2in}
\setlength{\evensidemargin}{-.5in}
\setlength{\topmargin}{-0.8in}

\newcommand{\argmax}{\operatornamewithlimits{argmax}}
\newcommand{\argmin}{\operatornamewithlimits{argmin}}
\renewcommand{\vec}[1]{\ensuremath{\boldsymbol{#1}}}
\renewcommand{\v}[1]{\vec{#1}}
\newcommand{\E}{\ensuremath{\mathbb{E}}}

\begin{document}

\begin{center}
\Large CS6220-03 Data Mining  Techniques -- Fall 2016  \\
\normalfont
\vspace{3mm}
Assignment 1\\
\end{center}
\vspace{1mm}
\framebox{
\parbox{7in}{
\vspace{1mm}
\centering{\bf Submission Instructions}
\begin{itemize}
\item \bf{Your program must run on CCIS machines in WVH 102 lab.}
\vspace{-2mm}
\item \bf{Create a README file with simple, clear instructions on how to compile and run your code.}
\vspace{-2mm}
\item Zip all your files (code, README, written answers, etc.) in a zip file named $\{firstname\}\_\{lastname\}\_CS6220\_HW1.zip$ and upload it to Blackboard.\\

\end{itemize}
}
}

\vspace{4mm}

\section*{Exercise 1: Ridge Regression}

\noindent In this assignment, you are given three artificial datasets (1, 2 and 3) and one real world dataset (4). Each dataset has a training and a test file. Specifically, these files are: \\

\vspace{-3mm}
\indent \indent dataset 1: 	\indent train-100-10.csv \indent \hspace{0.45cm} test-100-10.csv\\
\indent \indent dataset 2: 	\indent train-100-100.csv \hspace{0.85cm} test-100-100.csv\\
\indent \indent dataset 3: 	\indent train-1000-100.csv \hspace{-0.4cm}\indent \indent test-1000-100.csv\\
\indent \indent dataset 4: 	\indent train-wine.csv \hspace{3mm}\indent \indent test-wine.csv\\
\vspace{-3mm}

\noindent In each file, the last column contains the $y$ values and the other columns are the features ($x$'s). \\

\noindent Start the experiment by creating three additional training files from the 1000\_100\_train.csv by taking the first 50, 100, and 150 instances respectively. Call them 50(1000)\_100\_train.csv, 100(1000)\_100\_train.csv and 150(1000)\_100\_train.csv. The corresponding test file for these datasets would be 1000\_100\_test.csv and no modification is needed. Thus, you should have seven datasets in total and each has a training and a test file.\\

\begin{itemize}
\vspace{-5mm}
\item[a.]  Implement $L2$ regularized linear regression algorithm with $\lambda$ range from 0 to 150 (integers only). For each of the seven dataset, plot both the training set MSE and the test set MSE as a function of $\lambda$ (x-axis) in one graph.

\vspace{2mm}
{\bf{Discuss : How does $\lambda$ affect the MSE in general? How does the choice of $\lambda$ depend on the number of features vs. examples?  How does $\lambda$ change with number of examples when the number of features is fixed?}}

%\vspace{-3mm}
\item[b.] Fix $\lambda$ = 1, 46, 150. For each of these values, plot a learning curve for the algorithm using the dataset 1000\_100.csv.\\
Note: a learning curve plots the performance as a function of the size of the training set. To produce the curve, you need to draw random subsets (of increasing sizes) and record performance (MSE) on the corresponding test set when training on these subsets.  In order to get smooth curves, you should repeat the process at least 10 times and average the results.

%\vspace{-3mm}
\item[c.] From the plots in question 1,  we can tell which value of $\lambda$ is best for each dataset once we know the test data and its labels. This is not realistic in real world applications. In this part, we use cross validation to set the value for $\lambda$.
Implement the CV technique given in class. For each dataset, compared the values of $\lambda$ and MSE with the best values in question 1.

\vspace{2mm}
{\bf{Discuss:  How do the values for $\lambda$ and MSE obtained from CV compare to the choice of $\lambda$ and best test set MSE in question 1? What are the drawbacks of CV? What are the factors affecting the performance of CV?}}

\end{itemize}

\section*{Exercise 2: Bayesian Linear Regression}

In this assignment, you will need to derive some identities to express ridge regression and the LASSO as maximum a posteriori (MAP) estimates relative to an appropriate prior, as well as derive confidence intervals on weights in Bayesian linear regression. Please complete this part of the exercise as a PDF file (preferably typed up in LaTeX), and include it in your uploaded zip file named as
\[
    \{firstname\}\_\{lastname\}\_CS6220\_HW1\_exercise2.pdf
\]

\begin{itemize}
\item[a.] Show that ridge regression (i.e. L2-regularized linear regression) and the LASSO are equivalent to a MAP estimation problem in which a prior is placed on the regression weights
\begin{align*}
    \v{w}^*
    &=
    \argmax_{\v{w}}
    p(\v{w} \,|\, \v{y})
    \\
    p(\v{y} \,|\, \v{w})
    &=
    \mathcal{N}(\v{y} ; \v{X} \v{w}, \sigma^2 \v{I})
    \\
    p(\v{w})
    &=
    \mathcal{N}(\v{w} ; \v{0}, s^2 \v{I})
    \qquad
    \text{(L2-regularization)}
    \\
    p(\v{w})
    &=
    \frac{1}{2 b} \exp^{-\frac{|\v{w}|}{b}}
    \qquad
    \text{(L1-regularization)}
\end{align*}
For each case, express the regularization parameter $\l$ in terms of the constants $\sigma$ and $s$, and $b$.

\item[b.] We will now consider the sightly more general case where we place a multivariate Gaussian prior with parameters $\v{m_0}$ and $\v{S_0}$ on the weights
\begin{align*}
    p(\v{w})
    &=
    \mathcal{N}(\v{w} ; \v{m}_0, \v{S}_0)
\end{align*}
Calculate the the posterior mean $\v{m}$ and covariance $\v{S}$ such that
\begin{align*}
    p(\v{w} \,|\, \v{y}, \v{m}_0, \v{S}_0)
    =
    \mathcal{N}(\v{w} ; \v{m}, \v{S})
\end{align*}
Show the steps in the computation (not just the results). \emph{Hint: Expand $\log p(\v{y},\v{w} \,|\, \v{m}_0, \v{S}_0)$ and collect terms that are linear and quadratic in $\v{w}$ (this is known as completing the square).}
\end{itemize}

\end{document}


\documentclass[12pt]{article}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{geometry}
\usepackage{enumerate}
\usepackage{natbib}
\usepackage{float}%稳定图片位置
\usepackage{graphicx}%画图
\usepackage[english]{babel}
\usepackage{a4wide}
\usepackage{indentfirst}%缩进
\usepackage{enumerate}%加序号
\usepackage{multirow}%合并行
\title{\large UM-SJTU JOINT INSTITUTE\\Data Structures and Algorithms\\(VP281)\\\ \\\ \\\ \\\ \\\ \\\ \\\ \\\ \\\ \\\ \\\
Programming Assignment\\\ \\\ Programming Assignment Two\\\  Linear-Time Selection \\\ \\\ \\\ \\\ \\\ }
\author{Name: Pan Chongdan\\ID: 516370910121}
\date{Date: \today}

\begin{document}
\maketitle
\newpage
\section{Introduction}
The programming assignment asks me to implement two linear time selection algorithms including random selection and deterministic algorithm. The goal is clear, to gain experience in implementing these two sorting algorithms to find the n-th small number in a given random array.
\par Second, the assignment asks me to study the performance of these 2 studies by studying their time efficiency. In lecture slides 5, professor gives a summary for the time required to complete the selection.
\begin{figure}[H]
\centering
\includegraphics[scale=0.2]{P1.png}
\caption{Random Selection}
\end{figure}
\begin{figure}[H]
\centering
\includegraphics[scale=0.2]{P2.png}
\caption{Deterministic Selection}
\end{figure}
\par However, we need to test the algorithms' time efficiency by ourselves, so I wrote a cpp file to print out the time required for each algorithm, which is included in appendix part.
\section{Result}
To test time efficiency, I used clock() function to get the time required. To get rid of other disturbing factor, I used to variable start and stop to get the time right before and after the sorting complete, then their difference is the time used. In my analysis, I get 10 set of data ,from which the sorted array' size is 100, 500, 1000, 5000, 10000, 50000, 100000, 1000000.
\begin{table}[H]
\centering
\begin{tabular}{|c|c|c|c|c|c|c|c|c|c|}
\hline
Data Size                 & 100    & 500   & 1000     & 5000    & 10000    & 50000   & 100000   & 1000000  \\ \hline
Random Selection               &8e-6& 2.5e-5& 4e-5 & 2.5e-4 & 4e-4 & 4.6e-3 & 7.5e-3 &5.2e-2      \\ \hline
Deterministic Selection        &1.4e-5& 6.4e-4& 8.6e-4 & 6e-4 & 4.4e-4 & 1.7e-3 & 3.3e-3 &3.3e-1  \\ \hline
Quick Sort (in place)     &1.8e-5& 1.2e-4 & 2.1e-4 & 4.1e-4 & 9.6e-4 & 4.0e-3& 8.3e-3 & 9e-2  \\ \hline
\end{tabular}
\end{table}
\section{Conclusion}
This chart is plot by matlab, showing the time efficiency of each algorithms compared to each other, and it has following characteristics.
\begin{figure}[H]
\centering
\includegraphics[scale=0.2]{P3.png}
\end{figure}
\begin{enumerate}
\item The average time required for each algorithm grows as the array grows bigger.
\item These three algorithm runs in a linear time when the array is big
\item As shown in the graph and lecture slides, deterministic selection requires the more time than the random selection and they're all quicker than quick sort when the array is big. Also these three ways are all Big O complexity.
\end{enumerate}
\section{Appendix}
The appendix shows the cpp code for main project and time comparison.
\begin{figure}[H]
\centering
\includegraphics[scale=0.6]{P4.png}
\end{figure}
\begin{figure}[H]
\centering
\includegraphics[scale=0.6]{P5.png}
\end{figure}
\begin{figure}[H]
\centering
\includegraphics[scale=0.6]{P6.png}
\end{figure}
Then the appendix shows the cpp code for each sort algorithm
\begin{figure}[H]
\centering
\includegraphics[scale=0.6]{P7.png}
\end{figure}
\begin{figure}[H]
\centering
\includegraphics[scale=0.6]{P8.png}
\end{figure}
\begin{figure}[H]
\centering
\includegraphics[scale=0.6]{P8.png}
\end{figure}
\begin{figure}[H]
\centering
\includegraphics[scale=0.6]{P10.png}
\end{figure}
\end{document}


\documentclass[11pt]{amsart}
\usepackage{geometry}                % See geometry.pdf to learn the layout options. There are lots.
\usepackage{graphicx}
\usepackage{amssymb}
\usepackage{epstopdf}
\usepackage{algorithmic}
\usepackage{algorithm}
\usepackage{url}
\usepackage{framed}

\title{Lecture 0  - Introduction }
%\date{}                                           % Activate to display a given date or no date

\begin{document}
\maketitle

\section{Course Introduction}
\begin{itemize}
	\item What is Machine Learning?
	\item Review Syllabus: Course Topics, Grading, Office Hours, etc.
	\item The class website is found on GitHub and Canvas
	\begin{itemize}
		\item Canvas: Grades will be posted here.
		\item GitHub: Course notes, assignments, projects, extra credit, etc.. will be posted here.
	\end{itemize}
	\item This tends to be a challenging course.  Suggestions to help you do well:
	\begin{itemize}
		\item Do the reading in advance and stay on top of your assignments, many topics build on each other
		\item Ask questions when you do not understand. Ask questions in class, during office hours, or using the Canvas discussion page.  Whenever we are asked a question that may be relevant to others, we will post the question and our response to the Canvas discussion page.
		\item Participate in classroom/wiki discussion and activities
		\item You are expected to have a computer available that has git installed, the ability to code and compile in python 3+, and run jupyter notebooks.  If attending class in person, bring this computer to class with you so you can follow along.
	\end{itemize}
	\item Extra Credit: If you find (meaningful) errors or typos in the lecture notes, code, examples, etc posted in the class materials, you can report these using GitHub's ``pull request'' to get some extra credit.  See: \url{https://help.github.com/articles/about-pull-requests/}.  For errors/typos in any PDF file, be sure to correct the associated .tex for my review.
\end{itemize}
\section{Reading Assignment - Due Aug 28 @ 10:40am}
\begin{itemize}
\item Read Introduction to Chapter 1 and Sections 1.1-1.4
\item Review vectors, matrices and the Gaussian distribution. Some (optional) sources for reviewing this material are:
\begin{itemize}
\item Chapters 1 \& 2 of Strang's Introduction to Linear Algebra text
\begin{itemize}
	\item book website: \url{http://math.mit.edu/~gs/linearalgebra/}
	\item associated video lectures: \\\url{https://ocw.mit.edu/courses/mathematics/18-06-linear-algebra-spring-2010/} \end{itemize}
\item Appendix B from Bishop's Pattern Recognition and Machine Learning text.
\end{itemize}
\end{itemize}

\section{Homework 0 - Due Aug 26 @ 11:59pm}
\begin{enumerate}
\item If you do not already have them, install (1) an editor, (2) Python 3+, (3) the NumPy, SciPy, and Matplotlib packages and (4) Jupyter notebooks on the computer(s) you will be bringing to class and using to complete your assignments.
\begin{itemize}
\item You are welcome to use whatever editor you would like.  There are many options. See: \url{https://wiki.python.org/moin/PythonEditors}  Lately, I have been using SublimeText (which is what I will be using in class).
\item An easy way to install Python 3+ and all required packages is to install Anaconda: \url{https://www.anaconda.com/download}

\end{itemize}
\item If you are not familiar with Python 3, go through one (or a few) introductory tutorials:
\begin{itemize}
\item Dive into Python 3: \url{http://www.diveintopython3.net}
\item A list of many beginner tutorials: \url{https://wiki.python.org/moin/BeginnersGuide/Programmers}
\item For those familiar with Matlab, see: \url{https://docs.scipy.org/doc/numpy/user/numpy-for-matlab-users.html}
\end{itemize}
\item If you do not have one, create a github account.
\begin{itemize}
\item Please set up a username that clearly indicates who you are (e.g., my username is alinazare)
\item Check out: \url{https://education.github.com/pack}
\end{itemize}
\item If you are not familiar with git, complete one (or a few) introductory tutorials:
\begin{itemize}
\item Git bootcamp: \url{https://help.github.com/categories/bootcamp/}
\item Tutorials: \url{https://www.atlassian.com/git/tutorials/}
\item Interactive Introduction: \url{https://try.github.io/}
\end{itemize}
\item Follow the assignment link for the Homework00 repository.  After accepting the invitation, clone the repository to your local machine.

\item Code up a python program that prints the following:

\begin{itemize}
\item My name is [your name].
\item I am a [undergraduate/masters/PhD] student majoring in [your major] in the Department of [your department].
\item I have [no/some/extensive] programming experience in general.
\item I have [no/some/extensive] python programming experience.
\item I have [no/some/extensive] experience with using version control software.
\item I have [no/some/extensive] experience with git.
\item I have [no/some/extensive] experience in machine learning.
\item My github username is [username].
\item I am excited to learn the following in this class: [complete with your response]
\end{itemize}
\item Starter code has been provided for you in your homework repository.  You only need to edit, verify that it runs properly, and push back your submission.
\item Submit this through GitHub by pushing your completed code back to the github assignment repository.
\end{enumerate}

\end{document}


\documentclass[12pt]{article}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{geometry}
\usepackage{enumerate}
\usepackage{natbib}
\usepackage{float}%稳定图片位置
\usepackage{graphicx}%画图
\usepackage[english]{babel}
\usepackage{a4wide}
\usepackage{indentfirst}%缩进
\usepackage{enumerate}%加序号
\usepackage{multirow}%合并行
\usepackage{tikz}%图
\title{\large UM-SJTU JOINT INSTITUTE\\DISCRETE MATHEMATICS\\(VE203)\\\ \\\ \\\ \\\ \\\ \\\ \\\ \\\ \\\ \\\ \\\
ASSIGNMENT 9\\\ \\\ \\\ \\\ \\\ \\\ }
\author{Name: Pan Chongdan\\ID: 516370910121}
\date{Date: \today}

\begin{document}
\maketitle
\newpage
\section{Q1}
\begin{enumerate}[(i)]
\item
The sequence is (0,4,9,27,$\cdots$)
\\So the formula
\begin{eqnarray}g(n)=
\begin{cases}
0,n=1\cr 4,n=2 \cr 3^{n-1},n\ge 3\end{cases}
\end{eqnarray}
\item
The sequence is (0,0,3,0,$\frac{9}{2},\cdots$)
\\So the formula
\begin{eqnarray}g(n)=
\begin{cases}
0,n=1\vee n\mathrm{\quad is\quad even} \cr \frac{3^{n-2}}{(n-2)!},n=2k+1,k\in\mathbb{Z^+}\end{cases}
\end{eqnarray}
\item
The sequence is (0,1,-1,0,$\cdots$)
\\So the formula
\begin{eqnarray}g(n)=
\begin{cases}
0,n=3k\cr 1,n=3k+1 \cr -1,n=3k+2,k\in\mathbb{Z}\end{cases}
\end{eqnarray}
\end{enumerate}
\section{Q2}
\begin{figure}[H]
\centering
\includegraphics[scale=0.3]{P1.jpg}
\caption{Petersen Graph}
\end{figure}
Since the degree of all vertex is 3, and we can only get in and out of one vertex once, so every vertex must have exactly two edges in the Hamilton circuit, assume there exists a Hamilton circuit $E_H$ includes all the edges of the Hamilton circuit.
\begin{enumerate}
\item If $\{1,2\}\notin E_H\Rightarrow\{1,5\},\{1,6\},\{2,7\},\{2,3\}\in E_H$
\begin{enumerate}[(a)]
\item Then if $\{3,8\}\in E_H\Rightarrow\{4,9\},\{5,4\}\in E_H\Rightarrow\{10,8\},\{10,7\}\in E_H\Rightarrow\{9,6\}\in E_H.$ So the circuit become $\{1\rightarrow5\rightarrow4\rightarrow9\rightarrow6\rightarrow1\}$, which doesn't pass every vertex.
\item If $\{3,4\}\in E_H\Rightarrow\{8,10\},\{8,6\}\in E_H\Rightarrow\{9,4\},\{9,7\}\in E_H\Rightarrow\{10,5\}\in E_H.$ So the circuit become $\{1\rightarrow5\rightarrow10\rightarrow8\rightarrow6\rightarrow1\}$, which also doesn't pass every vertex.
\end{enumerate}
\item If $\{1,6\}\notin E_H\Rightarrow\{1,5\},\{1,2\},\{6,9\},\{6,8\}\in E_H$
\begin{enumerate}[(a)]
\item Then if $\{5,4\}\in E_H\Rightarrow\{10,8\},\{10,7\}\in E_H\Rightarrow\{3,2\},\{3,4\}\in E_H\Rightarrow\{3,6\}\in E_H.$ So the circuit become $\{1\rightarrow5\rightarrow4\rightarrow3\rightarrow2\rightarrow1\}$, which doesn't pass every vertex.
\item If $\{5,10\}\in E_H\Rightarrow\{4,9\},\{4,3\}\in E_H\Rightarrow\{7,10\},\{7,2\}\in E_H.$ So the circuit become $\{1\rightarrow5\rightarrow10\rightarrow7\rightarrow2\rightarrow1\}$, which also doesn't pass every vertex.
\end{enumerate}
\end{enumerate}
So we can never find a Hamilton circuit passing through vertex 1.
\par If we cut vertex 1 from the Graph then the circuit can be $\{2\rightarrow3\rightarrow4\rightarrow5\rightarrow10\rightarrow8\rightarrow6\rightarrow9\rightarrow7\rightarrow2\}$
\par If we cut vertex 6 from the Graph then the circuit can be $
\{1\rightarrow2\rightarrow7\rightarrow9\rightarrow4\rightarrow3\rightarrow8\rightarrow10\rightarrow5\rightarrow1\}$
\section{Q3}
Yes
\begin{figure}[H]
\centering
\includegraphics[scale=0.3]{P5.jpg}
\caption{The graph doesn't have a Hamilton circuit}
\end{figure}
\section{Q4}
\begin{enumerate}[(i)]
\item
Yes
\begin{figure}[H]
\centering
\includegraphics[scale=0.5]{P2.jpg}
\end{figure}
\item
No, since there are two vertexes whose degrees are 4, then there can't exist a vertex with degree=1
\item
Yes
\begin{figure}[H]
\centering
\includegraphics[scale=0.5]{P3.jpg}
\end{figure}
\item
No, because the sum must be even
\end{enumerate}
\section{Q5}
It's clear that for a graph whose order is $n$ and only has one connected components, it's minimal size is $e\ge n$. If we break it into to connected two components, we must cut off at least one wedge $\therefore e_1\ge e-1\ge n-1$. Similarly, if we break it into $n$ connected components, we must cut off at least $k$ wedge $\therefore e_k\ge e-k\ge n-k\Rightarrow k\ge n-e_k $
\section{Q6}
The least number is 3
\begin{figure}[H]
\centering
\includegraphics[scale=0.5]{P4.jpg}
\end{figure}
\section{Q7}
\begin{enumerate}[(i)]
\item Assume $V=\{v_1,v_2\cdots,v_n\}$ and $\forall e=\{v_a,v_b\}\in E$.
\\Let $X$ be the set of all sets containing two elements of $\mathbb{N}$
\par For example, if $G=(V,E),V=\{1,2,3,4\},E=\{\{1,2\},\{1,3\},\{1,4\},\{2,3\},\{3,4\}\}$
\\$X=\{\{1,2\},\{1,3\},\{1,4\}\cdots\{3,4\}\cdots\}$. According to $G$, we know that vertex 1 is connected to vertex 2,3,4
,so we use $\{\{1,2\},\{1,3\},\{1,4\}\}$ to donate the bijection of vertex 1. Similarly $\{\{1,2\},\{2,3\}\}$ can donate vertex 2. All these donation can form $\chi$ which is a subset of $P(X)$ Then $\{x,y\}=\{\{\{1,2\},\{1,3\},\{1,4\}\},\{\{1,2\},\{2,3\}\}\}\in E_{\chi}$ can donate the wedge. $\therefore H\cong G_{\chi}$
\item In the last example $|X|=3+2+1=6,n=\frac{n(n-1)}{2}=\frac{n^2-n}{2}$
\end{enumerate}
\section{Q8}
\begin{enumerate}[(i)]
\item $$f(n)a_n=g(n)a_{n-1}+h(n)$$
$$Q(n)f(n)a_n=b_{n-1}+Q(n)h(n)$$
$$Q(n)f(n)=\frac{f(1)f(2)\cdots f(n)}{g(1)g(2)\cdots g(n+1)}g(n+1)=g(n+1)Q(n+1)$$
$$\therefore b_n=b_{n+1}+Q(n)h(n)$$
\item
$$b_0=g(1)Q(1)C\Rightarrow b_n=g(1)Q(1)C+\sum_{i=1}^nQ(i)h(i)$$
$$a_n=\frac{b_n}{g(n+1)Q(n+1)},Q(1)=\frac{1}{g(1)}$$
$$\therefore a_n=\frac{C+\sum_{i=1}^nQ(i)h(i)}{g(n+1)Q(n+1)}$$
\item
$$C=1,f(n)=1,h(n)=n,g(n)=n+3$$
$$Q(n)=\frac{6}{(n+3)!}$$
$$a_n=\frac{1+\sum_{i=1}^n\frac{6n}{(n+3)!}}{\frac{6(n+4)}{(n+4)!}}=\frac{(n+3)!+(n+3)!\sum_{i=1}^n\frac{6n}{(n+3)!}}{6}$$
\end{enumerate}
\end{document}


%  -----------------------------------------------------------------------------
%  Author         : Bimalka Piyaruwan Thalagala
%  GitHub         : https://github.com/bimalka98
%  Last Modified  : 14.05.2021
%  -----------------------------------------------------------------------------

\documentclass[a4paper,11pt]{article}%,twocolumn
\input{settings/packages}
\input{settings/page}
\input{settings/macros}
\usepackage{float}
\usepackage{circuitikz}

\begin{document}

\input{content/title_page}

\tableofcontents
\vspace{4cm}
\begin{table}[H]
		\centering
		\begin{tabular}{l c l}
		\textbf{Name} & \textbf{Index} & \textbf{Contribution}\\

	Caldera H. D. J. &  180079X& PLD - Part 1, Part 2\\
	Oshan J. W. P.    & 180437U& PLD - Part 3 \\
	Thalagala B.P. & 180631J & Parasitic effect in Timing analysis \\

		\end{tabular}
		\caption{Contributions of each member}
\end{table}

\pagebreak
\section{Parasitic effect in Timing analysis}
\textbf{Objective}: \textit{Design a 3 stage (3 inverters) ring oscillator. Find the correlation of the parasitic effect in the oscillation period.}

\subsection{System Design}
Ring oscillator is a combination of delay stages arranged in series to form a closed loop chain. It consists of an \textbf{\textit{odd number of identical inverters (NOT gates)}} and it produces a  periodically oscillating output. The period of oscillation($T$) of a ring oscillator can be expressed as follows where $n$ is the number of cascaded NOT gates and $\tau_{d}$ is the propagation delay of a single stage\cite{rosci}. In this case $n = 3$.

\[
T = 2.n.\tau_{d} \hspace{5mm}\Longrightarrow ~ Oscillation~frequency = \frac{1}{2.n.\tau_{d}}
\]
\vspace{5mm}

Following figure illustrates the input output characteristic of an ideal inverter. There, output is changed as soon as the input signal changes. That is no propagation delay.

\begin{figure}[H]
	\centering
	\subfigure[Ideal Inverter Model]
	{ \includegraphics[scale=0.27]{figures/cct1plot5}
	}\hfill
	\subfigure[Ideal inverter Output]
	{ \includegraphics[scale=0.27]{figures/cct1plot6}
	}
\end{figure}

Whereas the below figure illustrates the input output characteristic of a real inverter. It can be observed that finite amount of time is required for output to be valid for a given valid input due to the time taken to charge and discharge the internal parasitic capacitors. This model has  been used to find the parasitic effect on the oscillation period as it is more realistic. For this experiment an NMOS and PMOS models were custom designed and Parameters of those models are as follows.

{\scriptsize
\begin{verbatim}

	.MODEL CMOSP PMOS KP=96u VTO=0.906 LAMBDA=0.01 TOX=21n GAMMA=0.486 CGDO=54p CGSO=54p CGBO=336p
	.MODEL CMOSN NMOS KP=96u VTO=0.786 LAMBDA=0.01 TOX=21n GAMMA=0.586 CGDO=402p CGSO=402p CGBO=362p
\end{verbatim}}

\begin{figure}[H]
	\centering
	\subfigure[Inverter Model with additional delay element]
	{ \includegraphics[scale=0.27]{figures/cct1plot3}
	}\hfill
	\subfigure[Effect of Parasitic Capacitance]
	{ \includegraphics[scale=0.27]{figures/cct1plot4}
	}
\end{figure}

\pagebreak
Basic structure of a ring oscillator can be depicted as follows using logic gates.

\begin{figure}[H]
	\centering
	\begin{circuitikz}
 \draw	 (1,0) node[ieeestd not port] (not1) {}
		 (3,0) node[ieeestd not port] (not2) {}
		 (5,0) node[ieeestd not port] (not3) {}
		 (0,0) -- (not1.in)
		 (not2.in) -- (not1.out)
		 (not3.in) -- (not2.out)
		 (not3.out) -- (6,0)
		 (not1.in) -- (0,0)
		 (6,0) -- (6,-1.5) -- (0,-1.5) -- (0,0)
		 ;
	\end{circuitikz}
	\caption{Basic structure of a 3 stage ring oscillator}
\end{figure}

A genral Ring Oscillator can be implemented using NMOS, PMOS transistors and additional delay elements(capacitors). But as the objective is to find the correlation between parasitic effect and oscillation period, the additional delay elements were not used and only the internal capacitance were taken in to account. Each inverter consists of one PMOS and one NMOS named as CMOSP and CMOSN.

\subsection{Simulation Results and Discussion}

\textit{\textbf{Note 1:} Only the gate-to source  capacitance were considered for the analysis, as it is what matters the most for the propagation delay of a MOSFET. In addition to that when changing the capacitor values, maximum gate-to source  capacitance was set to be 1 $\mu$F only to clearly illustrate the variation in the oscillation period. The real values are in pF range.}\\

\textit{\textbf{Note 2:} gate-to source  capacitance of the PMOS transistors were kept constant and only the NMOS transistors' gate-to source  capacitance were changed as it is sufficient for identifying the effect of parasitic capacitance on the period of oscillation.}\\

Following ring oscillator schematic has been used to simulate the effect of parasitic capacitance on the period of the output waveform. Simulation was run for $2~\mu s$ time intervals({\tt .tran 2u}) for 18 different gate-to source  capacitor values starting form 402 pF to 1 $\mu$F.\\

For the simulation to work an initial pulse is required. This requirement was satisfied through defining an initial condition({\tt .ic V(Vout) = 0}) for the {\tt Vout} node using LTSpice XVII's \textit{Spice Directive} feature. The same feature was used  to sweep\cite{sweeping} through different gate-to source  capacitor values. ({\tt .save V(Vout), .step dec param x 402p 1u 5})

\begin{figure}[H]
	\centering
	\includegraphics[scale=0.6]{figures/cct1plot1}
	\caption{3 stages CMOS Ring Oscillator}
\end{figure}
\pagebreak
When the gate-to source  capacitance is increased, as the plot depicts the period of oscillation increases and hence the frequency decreases. Because as mentioned at the beginning, the period of oscillation($T$) is affected by $\tau_{d}$, the propagation delay of a single stage which depends on the parasitic capacitance.
\[
Oscillation~frequency = \frac{1}{6.\tau_{d}}
\]

\begin{figure}[H]
	\centering
	\includegraphics[scale=0.5]{figures/cct1plot2}
	\caption{Waveform for Voltages of 3 stages CMOS Ring Oscillator}
\end{figure}

\subsection{Cross-section of a MOSFET}

Each MOSFET has 4 terminals called \textit{Body/Substrate (B), Source (S), Gate (G) and Drain (D)}. As following figure depicts the gate terminal is electrically insulated from the substrate semiconductor by a layer of oxide(shown in gray). This Metal-Oxide-Semiconductor structure forms a capacitor which is known as the \textbf{\textit{gate-to source capacitance}} This is what contributes to the propagation delay of the MOSFET \textit{\textbf{the most}} and hence to the period of oscillation of the Ring Oscillator.

\begin{figure}[H]
	\centering
	\includegraphics[scale=0.5]{figures/Cmos_impurity_profile.png}
	\caption{Cross-section of a MOSFET\cite{mosfet}}
\end{figure}

\pagebreak
\section{PLD}
\subsection{Part 1}
\textbf{Objective}: \textit{Design a programmable logic block to configure it as a `NAND' or a `NOR' gate using a single selection bit.}\\

First a truth table is drawn for this part considering a single selection bit (S) with two inputs (A, B) such that S=0 for ‘NAND’ and S=1 for ‘NOR’ operations respectively.
\begin{table}[H]
	\centering
	\begin{tabular}{|c |c| c| c|}
		\hline
		S & A & B & F \\\hline
		0 & 0 & 0 & 1 \\
		0 & 0 & 1 & 1 \\
		0 & 1 & 0 & 1 \\
		0 & 1 & 1 & 0 \\\hline
		1 & 0 & 0 & 1 \\
		1 & 0 & 1 & 0 \\
		1 & 1 & 0 & 0 \\
		1 & 1 & 1 & 0 \\\hline\hline
	\end{tabular}
\caption{The truth table}
\end{table}

Then the relevant logic expression was obtained using a karnaugh map and it was further simplified to obtain the combination of 'NAND' and 'NOR' operations.

\begin{table}[H]
	\centering
	\begin{tabular}{c |c| c| c| c}
		S\textbackslash AB & 00 & 01 & 11 & 10\\\hline
		0 & 1 & 1 & 0 & 1\\\hline
		1 & 1 & 0  &0  & 0
	\end{tabular}
	\caption{Karnough Map for the above truth table}
\end{table}

\[
\begin{split}
	F &= \overline{S}.\overline{A} + \overline{S}.\overline{B} + \overline{A}.\overline{B}\\
	&= \overline{S}.(\overline{A}+\overline{B}) + \overline{A}.\overline{B}\\
	&= \overline{S}.(\overline{A.B}) + \overline{A+B}\\
	&= \overline{S+A.B} + \overline{A+B}\\
	& = \overline{(S + A.B).(A+B)}\\
	& =\overline{(S + \overline{\overline{A.B}}).(\overline{\overline{A+B}})}
\end{split}
\]

So, the resultant combinational logic circuit is as follows. (2 NANDs, 2 NORs, 3 NOTs)

\begin{figure}[H]
	\centering
	\includegraphics[scale=0.5]{figures/PLD_cct.pdf}
	\caption{Resultant Combinational Logic Circuit}
\end{figure}

For the implementation of this circuit; ‘NOT’, ‘NAND’, and 'NOR' gates were designed using 'NMOS' and 'PMOS' transistors. Their schematics in LTspice are depicted below.

\begin{figure}[H]
	\centering
	\subfigure[Schematic of NOT gate]
	{ \includegraphics[scale=0.22]{figures/2part1/NOT.pdf}
	}\hfill
	\subfigure[Schematic of NAND gate]
	{ \includegraphics[scale=0.22]{figures/2part1/NAND.pdf}
	}\hfill
	\subfigure[Schematic of NOR gate]
	{ \includegraphics[scale=0.22]{figures/2part1/NOR.pdf}
	}
\caption{Basic Gates in the CMOS logic}
\end{figure}
%
%
Finally, the PLD block is designed using the above gates and the waveforms were obtained.

\begin{figure}[H]
	\centering
	\includegraphics[scale=0.55]{figures/2part1/cct.pdf}
	\caption{Circuit designed using logic blocks}
\end{figure}

\begin{figure}[H]
	\centering
	\includegraphics[scale=0.5]{figures/2part1/block.pdf}
	\caption{Designed PLD block}
\end{figure}

\begin{figure}[H]
	\centering
	\includegraphics[scale=0.5]{figures/2part1/wave.pdf}
	\caption{Waveforms for inputs and output of PLD }
\end{figure}

\pagebreak
\subsection{Part 2}
\textbf{Objective}: \textit{Design a single switch matrix using six pass transistors.}\\

In this part, the single switch matrix is needed to be designed using six pass transistors. So as the first step, a pass transistor was designed and its performance was checked. Simply an NMOS transistor is fed with a switch could be used for this task.\\

For signal to travel in both directions ( from source to drain and from drain to source ) the NMOS has to be symmetric and to have the switch property, both gate-source and gate-drain of the NMOS should be reverse biased. So body terminal needs to be connected as the lowest voltage in the circuit. So we grounded the body terminal.\\

So when the switch is on, the input signal will be received at the output. But as we are trying to illustrate a real model, the voltage of the output signal will be somewhat reduced compared with the input signal.\\

For this task, an NMOS model was chosen and the defined parameters are as follows\cite{data}.

\begin{verbatim}
L=0.9u W=1.8u
.MODEL N_1u NMOS LEVEL = 3
+ TOX = 200E-10 NSUB = 1E17 GAMMA = 0.5
+ PHI = 0.7 VTO = 0.8 DELTA = 0.1
+ UO = 650 ETA = 3.0E-6 THETA = 0.1
+ KP = 120E-6 VMAX = 1E5 KAPPA = 0.3
+ RSH = 0 NFS = 1E12 TPG = 1
+ XJ = 500E-9 LD = 100E-9
+ CGDO = 200E-12 CGSO = 200E-12 CGBO = 1E-10
+ CJ = 400E-6 PB = 1 MJ = 0.5
+ CJSW = 300E-12 MJSW = 0.5
\end{verbatim}

So the initially designed pass transistor and its results were obtained as follows.
\begin{figure}[H]
	\centering
	\includegraphics[scale=0.5]{figures/2part2/without_res_cct.pdf}
	\caption{Schematic diagram of the first designed pass transistor}
\end{figure}
\begin{figure}[H]
	\centering
	\includegraphics[scale=0.5]{figures/2part2/without_res_wave.pdf}
	\caption{Waveform of the first designed pass transistor}
\end{figure}

But it was observed that there is a leakage voltage when the NMOS is at the high impedance state. So we used a resistor as a load to pull down the output to zero.

\begin{figure}[H]
	\centering
	\includegraphics[scale=0.5]{figures/2part2/small_res_cct.pdf}
	\caption{Schematic diagram of the second designed pass transistor}
\end{figure}
\begin{figure}[H]
	\centering
	\includegraphics[scale=0.5]{figures/2part2/small_res_wave.pdf}
	\caption{Waveform of the second designed pass transistor}
\end{figure}

As observed, the 1 k$\Omega$ load resistance was not enough to satisfy the necessity. So, we used a larger load instead.

\begin{figure}[H]
	\centering
	\includegraphics[scale=0.5]{figures/2part2/pass_ttr.pdf}
	\caption{Schematic diagram of the finalized pass transistor}
\end{figure}
\begin{figure}[H]
	\centering
	\includegraphics[scale=0.5]{figures/2part2/pass_wave.pdf}
	\caption{Waveform of the finalized pass transistor}
\end{figure}

Then using six such transistors, the single switch matrix was designed and the schematic diagram of it is shown below.

\begin{figure}[H]
	\centering
	\includegraphics[scale=0.5]{figures/2part2/switch_mat.pdf}
	\caption{Schematic diagram of the single switch matrix}
\end{figure}
\begin{figure}[H]
	\centering
	\includegraphics[scale=0.5]{figures/2part2/block.pdf}
	\caption{Designed single switch matrix block}
\end{figure}

Finally the functionality of the circuit was checked by giving pulses to left, right, top, and bottom corners separately and switching on the switches at different periods.

\begin{figure}[H]
	\centering
	\includegraphics[scale=0.5]{figures/2part2/top.pdf}
	\caption{Waveforms when the top terminal is fed with a pulse}
\end{figure}

\begin{figure}[H]
	\centering
	\includegraphics[scale=0.5]{figures/2part2/left.pdf}
	\caption{Waveforms when the left terminal is fed with a pulse}
\end{figure}

\begin{figure}[H]
	\centering
	\includegraphics[scale=0.5]{figures/2part2/right.pdf}
	\caption{Waveforms when the right terminal is fed with a pulse}
\end{figure}

\begin{figure}[H]
	\centering
	\includegraphics[scale=0.5]{figures/2part2/bottom.pdf}
	\caption{Waveforms when the bottom terminal is fed with a pulse}
\end{figure}

\pagebreak
\subsection{Part 3}
\textbf{Objective}: \textit{Design a PLD that can be used to design any 3 input
combinational circuit.}\\

The task was to design a PLD circuit capable of implementing any three input combinational circuit. The truth-table of any three input combinational circuits will be as below.\\

\begin{table}[H]
\centering
	\begin{tabular}{|c |c| c| c|}
		\hline
		A&B&C& Output\\\hline
	0 & 0 & 0 & $S_1 $ \\
	0 & 0 & 1 & $S_2$ \\
	0 & 1 & 0 & $S_3$ \\
	0 & 1 & 1 & $S_4$ \\
	1 & 0 & 0 & $S_5$ \\
	1 & 0 & 1 & $S_6$ \\
	1 & 1 & 0 & $S_7$ \\
	1 & 1 & 1 & $S_8$ \\\hline\hline
	\end{tabular}
\caption{The truth-table of any three input combinational circuit}
\end{table}

Outputs $S_1$, $S_2$,...., $S_8$ differ with the combinational circuit. So we can write an expression for the combinational logic circuit using the 8 minterms. Which minterms to be selected differ according to the S1, S2,...., S8. If any $S_i$ is 1 then the corresponding minterm is taken into the sum of products expression. If Si is 0 that corresponding minterm is discarded.\\

So we can build the PLD with a fixed AND plane which has all eight minterms and a programmable OR plane which can be programmed using Si terms. So our PLD becomes a PROM.\\

Before building the PLD the AND plane and OR plane should be created. For the fixed AND plane, we need eight minterms. A minterm is a product of any three of $A$, $\overline{A}$, $B$, $\overline{B}$, $C$ or $\overline{C}$. So we need three input and gate. We configured a three-input AND gate using NAND, NOR, and NOT gates as below for better efficiency.\\

\[ A.B.C = \overline{\overline{A.B.C}} = \overline{\overline{A.B} + \overline{C}} \]

Using this expression we constructed the 3 input AND gates using a minimum number of logic gates.\\

\begin{figure}[H]
	\centering
	\includegraphics[scale=0.7]{figures/Figure332.pdf}
	\caption{Implementing the three-input AND gate using NOR, NAND, and NOT gates.}
\end{figure}

Using seven separate OR gates( 7 NOR gates + 7 NOT gates) to implement the OR plane, increases complexity and the latency of the circuit by a huge factor. Instead, we can simplify the expression and use a minimum number of gates as below.\\

\[
\begin{split}
 & = S_1 + S_2 + S_3 + S_4 + S_5 + S_6 + S_7 + S_8\\
 & = \overline{\overline{S_1 + S_2 + S_3 + S_4 + S_5 + S_6 + S_7 + S_8}}\\
 & = \overline{\overline{\left( S_1 + S_2 + S_3 + S_4 \right)}. \overline{\left( S_5 + S_6 + S_7 + S_8 \right)}}\\
  & = \overline{\overline{\left( S_1 + S_2\right)} .\overline{\left( S_3 + S_4 \right)}. \overline{\left( S_5 + S_6\right)}.  \overline{\left( S_7 + S_8 \right)}}\\
    & = \overline{\overline{\left( S_1 + S_2\right)} .\overline{\left( S_3 + S_4 \right)}}+ \overline{\overline{\left( S_5 + S_6\right)}.  \overline{\left( S_7 + S_8 \right)}}\\
    & = \overline{\overline{ \overline{\overline{\left( S_1 + S_2\right)} .\overline{\left( S_3 + S_4 \right)}}+ \overline{\overline{\left( S_5 + S_6\right)}.  \overline{\left( S_7 + S_8 \right)}} }}
\end{split}
\]

Using this expression we were able to build an OR plane with a minimum number of components as below.\\

\begin{figure}[H]
	\centering
	\includegraphics[scale=0.5]{figures/Figure333.pdf}
	\caption{Implementing the OR plane}
\end{figure}

Instead of using a total of 14 logic gates, now we have implemented it using only 8 logic gates. This reduces the latency and complexity by a huge factor.\\

PROM is constructed as below\\

\begin{figure}[H]
	\centering
	\includegraphics[scale=0.5]{figures/Figure334.pdf}
	\caption{PROM circuit}
\end{figure}

We have used nmos transistors as switches which choose, which minterms are taken into the sum of products.\\

We tested the circuit for different combinational circuits by configuring Si switches. Below we have configured the PROM as a simple NOR gate.\\

\begin{figure}[H]
	\centering
	\includegraphics[scale=0.4]{figures/Figure335.pdf}
	\caption{PROM configured as a NOR gate}
\end{figure}

Results were as below,
\begin{figure}[H]
	\centering
	\includegraphics[scale=0.5]{figures/Figure336.pdf}
	\caption{Results of PROM configured as a NOR gate}
\end{figure}

We can observe that the PROM is functioning correctly.

\subsection{Discussion}

One major problem we encountered when designing the PLD was, configuring the programmability of the OR plane. For the programmability we need configurable switches. Each switch decides the corresponding min-term get added to the final expression or not. Expected characteristics of the switches are,
\begin{enumerate}[\hspace{1cm}1.]
	\item Giving the corresponding signal when the switch is on
	\item Giving binary 0 at the output, when the switch is off.

\end{enumerate}
There are two possible ways for achieving this.
\begin{enumerate}[\hspace{1cm}1.]
	\item Using a 2 input AND gate with corresponding signal and switch bit as two inputs.
	\item NMOS transistor used as a pass transistor with, switch bit given to the gate terminal and corresponding signal given to the source terminal.

\end{enumerate}
Considering the power efficiency and latencies we concluded that using NMOS as a pass transistor is the best way to achieve our goal.
To achieve the second characteristic we expected, giving binary 0 at the output, when the switch is off, we have connected a large load at the output (drain terminal) of the switch as pull
down resistor. So, when transistor is at the high impedance state it will be grounded through the resistor achieving binary 0.\\
\vfill

\hrule
{\scriptsize
\bibliographystyle{plain}
\bibliography{refer}
}
%---------------------------------------------------------------------------
\end{document}


\documentclass[jou]{apa6}

\usepackage[american]{babel}

\usepackage{csquotes}
\usepackage[style=apa,sortcites=true,sorting=nyt,backend=biber]{biblatex}
\DeclareLanguageMapping{american}{american-apa}
\addbibresource{bibliography.bib}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Discrete Structures
%% The start of RBS stuff
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Working internal and external links in PDF
\usepackage{hyperref}
% Extra math symbols in LaTeX
\usepackage{amsmath}
\usepackage{gensymb}
\usepackage{amssymb}
% Enumerations with (a), (b), etc.
\usepackage{enumerate}

\let\OLDitemize\itemize
\renewcommand\itemize{\OLDitemize\addtolength{\itemsep}{-6pt}}

\usepackage{etoolbox}
\makeatletter
\preto{\@verbatim}{\topsep=3pt \partopsep=3pt }
\makeatother

% These sizes redefine APA for A4 paper size
\oddsidemargin 0.0in
\evensidemargin 0.0in
\textwidth 6.27in
\headheight 1.0in
\topmargin -24pt
\headheight 12pt
\headsep 12pt
\textheight 9.19in

\title{Sample Quiz 4}
\author{Discrete Structures, Spring 2020}
\affiliation{RBS}

\leftheader{Discrete Sample Quiz 7}

\abstract{%
}

%\keywords{}

\setlength\parindent{0pt}

\begin{document}

%\thispagestyle{empty}

\twocolumn
\section{Worksheet 7: Counting}

\vspace{10pt}
{\bf Question 1 (Traversing Rubik's Cube).} A tiny ant wants to travel
between two opposite vertices of a $3 \times 3 \times 3$ cube (Figure~\ref{fig:rubiks-cube}). It can crawl
on the surface of the cube (and even inside it);
but any path should consist from exactly $9$ unit-length
steps, where each step is parallel to one of the coordinate axes ($x$, $y$ or $z$).
Find the number of paths that the ant could take as it crawls from the vertex $A$ to the vertex $B$.

\begin{figure}[!htb]
\center{\includegraphics[width=2in]{quiz-sample-07/rubiks-cube.png}}
\caption{\label{fig:rubiks-cube} Rubik's cube.}
\end{figure}

Write your answer as an integer number equal to the number of paths from $A$ to $B$ satisfying the condition.

\vspace{6pt}
{\bf Question 2 (Permutations with Repetition).}\\
{\bf (A)} Find the number of ways (denoted by $N$) one can arrange the letters in the 6-letter word {\tt OLIVIA}.
Both letters "I" are not distinguishable (if they switch places, it is still the same arrangement).\\
{\bf (B)} Assume that somebody writes out all the permutations of the word {\tt OLIVIA}
in the {\em lexicographic ordering} (ordered as in a dictionary: sorted by the 1st letter;
if the 1st letter is the same, then by the 2nd letter, etc.).\\
For example, the first permutation: $w_1 = \mathtt{AIILOV}$ and the last one is $w_N = \mathtt{VOLIIA}$.
Find the permutations $w_{60},w_{61},w_{62},w_{63}$.

Write your answer as a comma-separated list (first the total number of permutations, then the
$60$th,$61$st,$62$nd,$63$rd permutation).\\
$N$,$w_{60},w_{61},w_{62},w_{63}$.

\vspace{6pt}
{\bf Question 3 (Raising to a high power).}
Joe wrote the decimal notation of the following number:
$$X = \left( 10^{10} + 1 \right)^{10}.$$
After that, Joe erased the last $50$ digits of the number $X$, and got the number $Y$.
Finally, Joe erased all the digits of $Y$, except the last ten digits, and got a sequence of digits $Z$.\\
{\bf (A)} Write all the digits of $Z$ (if it has leading zeroes, write them as well).\\
{\bf (B)} Express $Z$ as $C_n^k$ (``$n$ choose $k$''), where $k \leq n$.

Write your answer like this:\\ {\tt dddddddddd,choose(n,k)}.

\vspace{6pt}
{\bf Question 4 (Combinations with Repetition).} You have unlimited number of jellybeans \textendash{}
they can have any of these four colors: red, orange, green, yellow. The jellybeans of each
color are identical. Solve the following: express your answers as a binomial coefficients "$n$ choose $k$",
where $k \leq n$.

{\bf (A)}  How many collections of $20$ jellybeans can you make? (The order of jellybeans in the collection
does not matter. Those jellybean collections that have the same number of each color are considered identical.)\\
{\bf (B)} How many collections of $20$ jellybeans can you make, if there has to be at least one jellybean
of each color.

Write your answer in a form:\\ {\tt choose(n1,k1),choose(n2,k2)}\\
Replace {\tt n1,k1,n2,k2} with appropriate integers.

\vspace{6pt}
{\bf Question 5 (Ordering your combinations).}
Somebody has written out all the combinations, how to choose $k=4$ months out of a set of
$n=12$ months:\\
{\small
$\{ \mathtt{JAN},\mathtt{FEB},\mathtt{MAR},\mathtt{APR},\mathtt{MAY},\mathtt{JUN},
\mathtt{JUL},\mathtt{AUG},\mathtt{SEP},\mathtt{OCT},\mathtt{NOV},\mathtt{DEC} \}.$
}

All these four-month combinations are written in a sorted (so that a month appearing earlier in a year is always
written first), and furthermore \textendash{} all these combinations are arranged in increasing order.
Months are ordered in this way: $\mathtt{JAN} < \mathtt{FEB} < \ldots < \mathtt{DEC}$.\\
The very first combination of months is $\mathtt{JAN},\mathtt{FEB},\mathtt{MAR},\mathtt{APR}$,
the last one is $\mathtt{SEP},\mathtt{OCT},\mathtt{NOV},\mathtt{DEC}$.

Write a comma-separated list of the four-months that is in the $100$th place in this list.

\vspace{6pt}
{\bf Question 6: Pennies and jars.}
Assume that you have $50$ pennies and three jars (these jars are initially labeled $A$, $B$, and $C$).

{\bf (A)} In how many ways can you put the pennies in the jars, assuming that the pennies and the jars are distinguishable?\\
{\bf (B)} In how many ways can you put the pennies in the jars, assuming that the pennies are identical, but jars are distinguishable?\\
{\bf (C)} Assume that we remove the labels ($A$,$B$,$C$) from the jars; and the jars become indistinguishable.
In how many ways can you put the pennies in the jars, assuming that both the pennies and the jars are indistinguishable?

\vspace{6pt}
{\bf Question 7 (Necklace with colored beads).} Assume that we have a circular necklace with
$2012$ equally spaced beads. Exactly $7$ of the beads are red, the remaining ones are white.
How many necklaces there are? (Necklaces that is obtainable from each other by rotating the
circle by some angle $\frac{2\pi}{2012}k$ ($k = 1,\ldots,2011$) are considered identical.)

{\em Note.} A more general question was asked in CGMO (China Girls Mathematical Olympiad),
see Problem 8, \url{https://bit.ly/2TcfHH5}.

\newpage
\subsection{Answers}

\vspace{6pt}
{\bf Question 1} Answer: {\tt 1680}\\
Every unit move of the ant can be expressed by a letter $X,Y,Z$ (depending
on its direction). There are altogether $9!$ ways to arrange
nine letters. Since all three letters $X$ can be mixed in any order, we need
to divide by $3! = 6$. For the same reason we can also mix all three $Y$s and
all three $Z$s. Ultimately,

$$\frac{9!}{3!3!3!} = 1680.$$

\vspace{6pt}
{\bf Question 2} Answer: TBD\\

\vspace{6pt}
{\bf Question 3} Answer: TBD\\

\vspace{6pt}
{\bf Question 4} Answer: TBD\\

\vspace{6pt}
{\bf Question 5} Answer: TBD\\

\vspace{6pt}
{\bf Question 6} Answer: TBD\\

\vspace{6pt}
{\bf Question 7} Answer: TBD\\

\end{document}


\section{Applications}

\begin{outcome}
  \begin{enumerate}
  \item Apply the concepts of vectors in $\R^n$ to applications in
    physics.
  \end{enumerate}
\end{outcome}