%%
%% Automatically generated file from DocOnce source
%% (https://github.com/hplgit/doconce/)
%%
%%

%-------------------- begin preamble ----------------------

\documentclass[%
oneside,                 % oneside: electronic viewing, twoside: printing
final,                   % draft: marks overfull hboxes, figures with paths
10pt]{article}

\listfiles               %  print all files needed to compile this document

\usepackage{relsize,makeidx,color,setspace,amsmath,amsfonts,amssymb}
\usepackage[table]{xcolor}
\usepackage{bm,ltablex,microtype}

\usepackage[pdftex]{graphicx}

\usepackage[T1]{fontenc}
%\usepackage[latin1]{inputenc}
\usepackage{ucs}
\usepackage[utf8x]{inputenc}

\usepackage{lmodern}         % Latin Modern fonts derived from Computer Modern

% Hyperlinks in PDF:
\definecolor{linkcolor}{rgb}{0,0,0.4}
\usepackage{hyperref}
\hypersetup{
    breaklinks=true,
    colorlinks=true,
    linkcolor=linkcolor,
    urlcolor=linkcolor,
    citecolor=black,
    filecolor=black,
    %filecolor=blue,
    pdfmenubar=true,
    pdftoolbar=true,
    bookmarksdepth=3   % Uncomment (and tweak) for PDF bookmarks with more levels than the TOC
    }
%\hyperbaseurl{}   % hyperlinks are relative to this root

\setcounter{tocdepth}{2}  % levels in table of contents

% prevent orhpans and widows
\clubpenalty = 10000
\widowpenalty = 10000

% --- end of standard preamble for documents ---

% insert custom LaTeX commands...

\raggedbottom
\makeindex
\usepackage[totoc]{idxlayout}   % for index in the toc
\usepackage[nottoc]{tocbibind}  % for references/bibliography in the toc

%-------------------- end preamble ----------------------

\begin{document}

% matching end for #ifdef PREAMBLE

\newcommand{\exercisesection}[1]{\subsection*{#1}}

% ------------------- main content ----------------------

% ----------------- title -------------------------

\thispagestyle{empty}

\begin{center}
{\LARGE\bf
\begin{spacing}{1.25}
Project 4, deadline  April 30
\end{spacing}
}
\end{center}

% ----------------- author(s) -------------------------

\begin{center}
{\bf Stock Market model${}^{}$} \\ [0mm]
\end{center}

\begin{center}
% List of all institutions:
\end{center}

% ----------------- end author(s) -------------------------

% --- begin date ---
\begin{center}
Spring semester 2017
\end{center}
% --- end date ---

\vspace{1cm}

\subsection*{Theoretical background and description of the system}

The aim of this project is to simulate financial transactions among financial agents
using Monte Carlo methods. The final goal is to extract a distribution of income  as function
of the income $m$.   From Pareto's work (\href{{http://www.institutcoppet.org/2012/05/08/cours-deconomie-politique-1896-de-vilfredo-pareto}}{V.~Pareto, 1897}) it is known from empirical studies
that the higher end of the distribution of money follows a distribution
\[
w_m\propto m^{-1-\alpha},
\]
with $\alpha\in [1,2]$. We will here follow the analysis made by \href{{http://www.sciencedirect.com/science/article/pii/S0378437104004327}}{Patriarca and collaborators}.

Here we will study numerically the relation between the micro-dynamic relations among financial
agents and the  resulting macroscopic money distribution.

We assume we have $N$ agents that exchange money in pairs $(i,j)$. We assume also that all agents
start with the same amount of money $m_0 > 0$. At a given 'time step', we choose randomly a pair
of agents $(i,j)$ and let a transaction take place. This means that agent $i$'s money $m_i$ changes
to $m_i'$ and similarly we have $m_j\rightarrow m_j'$.
Money is conserved during a transaction, meaning that
\begin{equation}
  m_i+m_j=m_i'+m_j'.
  \label{eq:conserve}
\end{equation}
The change is done via a random reassignement (a random number) $\epsilon$, meaning that

\begin{equation*}
m_i' = \epsilon(m_i+m_j),
\end{equation*}
leading to

\begin{equation*}
m_j'= (1-\epsilon)(m_i+m_j).
\end{equation*}
The number $\epsilon$ is extracted from a uniform distribution.
In this simple model, no agents are left with a debt, that is $m\ge 0$.
Due to the conservation law above, one can show that the system relaxes toward an equilibrium
state given by a Gibbs distribution

\begin{equation*}
w_m=\beta \exp{(-\beta m)},
\end{equation*}
with

\begin{equation*}
\beta = \frac{1}{\langle m\rangle},
\end{equation*}
and $\langle m\rangle=\sum_i m_i/N=m_0$, the average money.
It means that after equilibrium has been reached that the majority of agents is left with a small
number of money, while the number of richest agents, those with $m$ larger than a specific value $m'$,
exponentially decreases with $m'$.

We assume that we have $N=500$ agents.   In each simulation, we need a sufficiently large number of transactions, say $10^7$. Our aim is find the final equilibrium distribution $w_m$. In order to do that we would need
several runs of the above simulations, at least $10^3-10^4$ runs (experiments).

\paragraph{Project 4a): Simulation of Transactions.}
Your task is to first set up an algorithm which simulates the above transactions with an initial
  amount $m_0$.
  The challenge here is to figure out a Monte Carlo  simulation  based on the
  above equations.
  You will in particular need to make an algorithm which sets up a histogram as function of $m$.
  This histogram contains the number of times a value $m$ is registered and represents
  $w_m\Delta m$. You will need to set up a value for the interval $\Delta m$  (typically $0.01-0.05$).
  That means you need to account for the number of times you register an income in the interval
  $m,m+\Delta m$. The number of times you register this income, represents the value that enters the histogram.
  You will also need to find a criterion for when the equilibrium situation has been reached.

\paragraph{Project 4b): Recognizing the distribution.}
Make thereafter a plot of  $\log{(w_m)}$ as function of $m$
  and see if you get a straight line.
  Comment the result.

\paragraph{Project 4c): Transactions and savings.}
We can then change our model to allow for a saving criterion, meaning that the agents save
  a fraction $\lambda$ of the money they have before the transaction is made. The final distribution will then no longer be given by Gibbs distribution. It could also include a taxation on financial transactions.

  The conservation law of Eq. (\ref{eq:conserve}) holds, but the money to be shared in a transaction between
  agent $i$ and agent $j$ is now $(1-\lambda)(m_i+m_j)$. This means that we have

\begin{equation*}
  m_i' = \lambda m_i+\epsilon(1-\lambda)(m_i+m_j),
  \end{equation*}
  and

\begin{equation*}
  m_j' = \lambda m_j+(1-\epsilon)(1-\lambda)(m_i+m_j),
  \end{equation*}
  which can be written as

\begin{equation*}
  m_i'=m_i+\delta m
  \end{equation*}
  and

\begin{equation*}
  m_j'=m_j-\delta m,
  \end{equation*}
  with

\begin{equation*}
  \delta m=(1-\lambda)(\epsilon m_j-(1-\epsilon)m_i),
  \end{equation*}
  showing how money is conserved during a transaction.
  Select values of $\lambda =0.25,0.5$ and $\lambda=0.9$ and try to extract the corresponding
  equilibrium distributions and compare these with the Gibbs distribution. Comment your results.
Extract a parametrization of the above curves, see for example \href{{http://www.sciencedirect.com/science/article/pii/S0378437104004327}}{Patriarca and collaborators} and see if you can parametrize the high-end tails of the distributions in terms of power laws. Comment your results.

\paragraph{Project 4d): Nearest neighbor interactions.}
In the rest of this project we will follow the work of \href{{http://www.sciencedirect.com/science/article/pii/S0378437114006967}}{Goswami and Sen}.
In the studies above the agents were selected randomly, irrespective of whether we allowed for
saving or not during a transaction. What is often observed is that various agents tend to make preferences for for whom to interact with. We will now study the evolution of the distribution of wealth $w_m$ by assuming that there is a likelihood
\[
p_{ij} \propto \vert m_i-m_j\vert^{-\alpha},
\]
for an interaction between agents $i$ and $j$ with respective wealths $m_i$ and $m_j$. The parameter  $\alpha >  0$. For $\alpha=0$ we recover our model from part 5a).
Perform the same analysis as previously with $N=500$ as well as with $N=1000$ agents and study the distribution of wealth for $\alpha =0.5$, $\alpha =1.0$, $\alpha =1.5$ and $\alpha =2.0$.
You should try to reproduce Figure 1 of \href{{http://www.sciencedirect.com/science/article/pii/S0378437114006967}}{Goswami and Sen}.
Extract the tail of the distribution and see if it follows a Pareto distribution
\[
w_m\propto m^{-1-\alpha}.
\]
What happens if $\alpha \gg 1$?

Perform the analysis with and without a saving $\lambda$ on each transaction and comment your results.
\paragraph{Project 4e): Nearest neighbors and former  transactions.}
We add to the previous probability the possibility that two agents who interact have performed similar transactions earlier. That is, in addition to being financially close, we assume that the likelihood for interacting increases if two agents have interacted earlier.
We add this feature by modifying the previous likelihood to
\[
p_{ij} \propto \vert m_i-m_j\vert^{-\alpha}\left(c_{ij}+1\right)^{\gamma},
\]
where $c_{ij}$ represents the number of  previous interactions that have taken place between $i$ and $j$. The factor $1$ is added in order to ensure that if they have not interacted earlier they can still interact.  Perform similar studies as above with $N=1000$, $\alpha=1.0$ and $\alpha=2.0$ using $\gamma = 0.0, 1.0, 2.0, 3.0$ and $4.0$. Plot the wealth distributions for these cases and try to extract eventual power law tails with and without a saving $\lambda$ in each transaction. Comment your results and compare them with figures 5 and 6 of \href{{http://www.sciencedirect.com/science/article/pii/S0378437114006967}}{Goswami and Sen}.

Finally, (this part is optional) if you have time, which features would you add to these models in order to make them even more realistic?

\subsection*{Background literature}

\begin{itemize}
  \item \href{{http://www.institutcoppet.org/2012/05/08/cours-deconomie-politique-1896-de-vilfredo-pareto}}{V. Pareto, Cours d'economie politique, Lausanne, 1897}.

  \item \href{{http://www.sciencedirect.com/science/article/pii/S0378437104004327}}{M. Patriarca, A. Chakraborti, K. Kaski, Physica A \textbf{340}, 334 (2004)}.

  \item \href{{http://www.sciencedirect.com/science/article/pii/S0378437114006967}}{S. Goswami and P. Sen, Physica A \textbf{415}, 514 (2014)}.
\end{itemize}

\noindent
\subsection*{Introduction to numerical projects}

Here follows a brief recipe and recommendation on how to write a report for each
project.

\begin{itemize}
  \item Give a short description of the nature of the problem and the eventual  numerical methods you have used.

  \item Describe the algorithm you have used and/or developed. Here you may find it convenient to use pseudocoding. In many cases you can describe the algorithm in the program itself.

  \item Include the source code of your program. Comment your program properly.

  \item If possible, try to find analytic solutions, or known limits in order to test your program when developing the code.

  \item Include your results either in figure form or in a table. Remember to        label your results. All tables and figures should have relevant captions        and labels on the axes.

  \item Try to evaluate the reliabilty and numerical stability/precision of your results. If possible, include a qualitative and/or quantitative discussion of the numerical stability, eventual loss of precision etc.

  \item Try to give an interpretation of you results in your answers to  the problems.

  \item Critique: if possible include your comments and reflections about the  exercise, whether you felt you learnt something, ideas for improvements and  other thoughts you've made when solving the exercise. We wish to keep this course at the interactive level and your comments can help us improve it.

  \item Try to establish a practice where you log your work at the  computerlab. You may find such a logbook very handy at later stages in your work, especially when you don't properly remember  what a previous test version  of your program did. Here you could also record  the time spent on solving the exercise, various algorithms you may have tested or other topics which you feel worthy of mentioning.
\end{itemize}

\noindent
\subsection*{Format for electronic delivery of report and programs}

The preferred format for the report is a PDF file. You can also use DOC or postscript formats or as an ipython notebook file.  As programming language we prefer that you choose between C/C++, Fortran2008 or Python. The following prescription should be followed when preparing the report:

\begin{itemize}
  \item Use your github repository to upload your report. Indicate where the report is by creating for example a \textbf{Report} folder. Please send us as soon as possible your github username.

  \item Place your programs in a folder called for example \textbf{Programs} or \textbf{src}, in order to indicate where your programs are. You can use a README file to tell us how your github folders are organized.

  \item In your git repository, please include a folder which contains selected results. These can be in the form of output from your code for a selected set of runs and input parameters.

  \item In this and all later projects, you should include tests (for example unit tests) of your code(s).

  \item Comments  from us on your projects, with score and detailed feedback will be emailed to you.
\end{itemize}

\noindent
Finally,
we encourage you to work two and two together. Optimal working groups consist of
2-3 students. You can then hand in a common report.

% ------------------- end of main content ---------------

\end{document}


\documentclass{beamer}
\usetheme{Copenhagen}

\title{Introduction to Python}
\usepackage{listings}
\subtitle{Iterables, Iterators and Generators}
\date{13 November 2015}

\begin{document}
\definecolor{keywords}{RGB}{255,0,90}
\definecolor{comments}{RGB}{0,0,113}
\definecolor{red}{RGB}{160,0,0}
\definecolor{green}{RGB}{0,150,0}
\lstset{language=Python,
        basicstyle=\ttfamily\small,
        keywordstyle=\color{keywords},
        commentstyle=\color{comments},
        stringstyle=\color{red},
        showstringspaces=false,
        identifierstyle=\color{green},
        procnamekeys={def,class}}
\begin{frame}
  \titlepage
\end{frame}

\section{Iterables}
\begin{frame}[fragile]{Examples 1}
  \begin{itemize}
	\item {We have already seen that loops in Python are pretty flexible:
	\pause
  \begin{block}{}
\begin{lstlisting}{frame=single}
for i in [1,2,3]:
    print i # prints elements
for	i in "123":
    print i # prints characterwise
\end{lstlisting}
\end{block}
	}
  \end{itemize}
\end{frame}
\begin{frame}[fragile]{Examples 2}
  \begin{itemize}
	\item {We have already seen that loops in Python are pretty flexible (excuse lack of indentation):
  \begin{block}{}
\begin{lstlisting}{frame=single}
for i in xrange(4):
    print i #prints the range without storing
for i in enumerate([1,2,3]):
    print i # gives me indices as well as elements
\end{lstlisting}
\end{block}
	}
	\pause
	\item{ Hopefully you see this and think how do I do that in my code!}
  \end{itemize}
\end{frame}
\begin{frame}[fragile]{Definition}
  \begin{itemize}
	\item { An \textbf{iterable} is any object that responds to the function iter(obj)
	}
	\pause
	\item{ Python likes to hide this!
  \begin{block}{}
  \begin{lstlisting}{frame=single}
	for i in x:
	    # Do loop stuff
  \end{lstlisting}
\end{block}
}
\item Call iter(x) and assign to some name that is never used in the code.
\pause
\item iter(x) returns an object that can do one thing and one thing alone - respond to \_\_next\_\_()
\pause
\item Assign i to the response to \_\_next\_\_() each time round until it throws StopIteration exception (sort of an error) and then move on.
\end{itemize}
\end{frame}
\begin{frame}[fragile]{Definition}
  \begin{itemize}
  \begin{block}{}
  \begin{lstlisting}{frame=single}
	for i in x:
	    # Do loop stuff
  \end{lstlisting}
\end{block}
	\item{ This is equivalent to:
  \begin{block}{}
  \begin{lstlisting}{frame=single}
  randomName = iter(x)
  while(True):
      try:
          i = randomName.__next__()
          # Do loop stuff
      except StopIteration:
           break
  \end{lstlisting}
\end{block}
}
\end{itemize}
\end{frame}

\begin{frame}[fragile]{Uses for Iterables}
  \begin{itemize}
	\item{ Iterables can be used all over the place!
  \begin{block}{}
  \begin{lstlisting}{frame=single}
  new_list = list(iterable)
  total = sum(iterable)
  smallest = min(iterable)
  largest = max(iterable)
  combined = ''.join(iterable)
  result = [f(x) for x in iterable]
 \end{lstlisting}
\end{block}
}

\end{itemize}
\end{frame}
\section{Generators}
\begin{frame}[fragile]{Make your own iterables}
  \begin{itemize}
  \item{ To make an object and iterable you only need to define the \_\_iter\_\_() hook.}
  \item{\textbf{Generators} are a great way to create your own iterables that are extremely flexible}
  \pause
  \item{You define generators in a similar way to function but using the keyword \textbf{yield}
  \begin{block}{}
\begin{lstlisting}{frame=single}
def myXRange(n):
    i = 0
    while( i < n):
        yield i
        i += 1
\end{lstlisting}
\end{block}
}
\pause
\item This responds to the \emph{next} call by running until it hits yield and then stopping and waiting.
\pause
\item Demo Time!
\end{itemize}
\end{frame}

\begin{frame}[fragile]{Make your own iterables 2}
  \begin{itemize}
\item No reason to make our iterable only finite!
\item{ Lets have all of the positive even numbers
\begin{block}{}
\begin{lstlisting}{frame=single}
def evens():
    i = 2
    while True:
        yield i
        i += 2
\end{lstlisting}
\end{block}
}
\pause
\item Be careful when using these! Don't try to make a list out of this one...
\end{itemize}
\end{frame}

\begin{frame}[fragile]{Make your own iterables 3}
\begin{itemize}
\item{ Perhaps most importantly, we can make iterables that depend on other iterables.
\pause
\begin{block}{}
\begin{lstlisting}{frame=single}
def myEnumerate(iterable):
    index = 0
    for i in iterable:
        yield (index,i)
        index += 1
\end{lstlisting}
\end{block}
}
\item Demo Time!
\end{itemize}
\end{frame}

\begin{frame}[fragile]{Fin}
\begin{itemize}
\item Suggested watching: Loop Like A Native, Ned Batchelder
\item Suggested Library: itertools (This probably has what you need!)
\end{itemize}
\end{frame}

\end{document}


%-------------------------------------------------------------------------------
\section{Pre-fit and post-fit event yields in the $\Htautau$ search}
\label{sec:prepostfit_yields_Htautau_appendix}
%-------------------------------------------------------------------------------

Table~\ref{tab:Htautau_Prefit_Yields_Unblind} presents the observed and predicted yields in each of the analysis regions
for the search before the fit to data.
Tables~\ref{tab:Htautau_Postfit_Yields_Unblind_Hc} and~\ref{tab:Htautau_Postfit_Yields_Unblind_Hu} present the observed and predicted yields
in each of the analysis regions after the fit to the data under the signal-plus-background hypothesis, assuming
$tHc$ and $tHu$ as signal, respectively.

%%%%%%%%%%%%%%%%%%%%%%%%
\begin{table}[htbp]
\caption{
Predicted and observed yields in each of the analysis regions considered.
The prediction is shown before the fit to data. Also shown are the signal expectations for
$\Hc$ and $\Hu$ assuming $\BR(t\to Hc)=0.1\%$ and $\BR(t\to Hu)=0.1\%$ respectively.
The contributions with real $\had$ candidates from $\ttbar$ and  $Z\to \ell^+\ell^-$ ($\ell = e, \mu$), diboson, $\ttbar V$, $\ttbar H$, single-top-quark, and other small backgrounds are combined into
a single background source referred to as ``Other MC'' in the leptonic channels , whereas single-top-quark and the small contributions are combined into ``Rare'' in the hadronic channels.
The quoted uncertainties are the sum in quadrature of statistical and systematic uncertainties of the yields.}
\small
\centering
\begin{tabular}{|c|c|c|c|c|c|}
\hline
 & $t_{l}\tau_{had}-1j$ & $t_{l}\tau_{had}-2j$ & $t_{h}\tau_{lep}\tau_{had}-3j$ & $t_{h}\tau_{lep}\tau_{had}-2j$ & $t_{l}\tau_{had}\tau_{had}$\\\hline
  QCD Fake lep  & $916.84 \pm 469.22$ & $434.65 \pm 218.77$ & $233.82 \pm 155.13$ & $416.75 \pm 232.61$ & $0 \pm 0$ \\
  W-jet fake $\tau$   & $839.60 \pm 257.79$ & $963.47 \pm 297.97$ & $2934.6 \pm 2722.5$ & $3434.22 \pm 3525.35$ & $4.96 \pm 2.80$ \\
  Other Fake $\tau$   & $2918.71 \pm 315.44$ & $2625.87 \pm 196.24$ & $1767.93 \pm 721.15$ & $1635.44 \pm 910.48$ & $138.86 \pm 23.10$ \\
  b Fake $\tau$   & $811.72 \pm 149.76$ & $1015.84 \pm 244.27$ & $522.39 \pm 236.07$ & $573.09 \pm 171.86$ & $68.10 \pm 14.20$ \\
  %tuH   & 71.0825 \pm 8.98689 & 62.9807 \pm 4.44175 & 123.517 \pm 14.72 & 87.6489 \pm 6.581 & 93.0677 \pm 3.83729 \\
  Lep fake $\tau$    & $221.68 \pm 31.75$ & $87.81 \pm 10.74$ & $307.45 \pm 102.87$ & $563.25 \pm 84.76$ & $0.88 \pm 0.36$ \\
  Double Fake $\tau$    & $0 \pm 0$ & $0 \pm 0$ & $0 \pm 0$ & $0 \pm 0$ & $89.74 \pm 37.20$ \\
  $\bar{t}t$   & $280.14 \pm 20.08$ & $178.8 \pm 42.01$ & $7081.53 \pm 2237.99$ & $11610.1 \pm 1263.95$ & $5.10 \pm 4.28$ \\
  Other MC   & $84.62 \pm 8.00$ & $83.30 \pm 3.31$ & $880.00 \pm 233.62$ & $1591.41 \pm 254.97$ & $40.79 \pm 2.02$ \\\hline
  Total B & $6073 \pm 488$ & $5390 \pm 291$ & $13728 \pm 1192$ & $19824 \pm 2091$ & $348 \pm 42$ \\ \hline
  Data & $6353\pm80$ & $5390 \pm 291$ & $35942\pm190$ & $50412\pm225$ & $351\pm19$\\\hline
  $\bar{t}t\to bWcH$ & $57.59\pm0.61$ &$52.80\pm0.58$ & $133.14\pm1.19$ &$102.58\pm0.97$ & $66.43\pm0.65$\\
$cg\to tH$ & $2.23\pm0.04$ & $1.38\pm0.03$  & $4.47\pm0.08$ & $5.66\pm0.08$ & $5.10\pm0.06$\\
tcH~merged & $59.82\pm0.61$ & $54.19\pm0.58$ & $137.61\pm1.19$ & $108.24\pm0.98$ & $71.53\pm0.65$\\\hline
$\bar{t}t\to bWuH$ & $59.72\pm7.52$ & $55.47\pm3.91$ & $139.67\pm16.65$ & $105.62\pm7.93$ & $69.10\pm2.85$\\
$ug\to tH$ & $11.36\pm1.43$ &$7.51\pm0.53$ & $24.78\pm3.00$ &$28.60\pm2.15$ & $24.00\pm1.00$\\
tuH~merged & $71.08\pm9.00$ & $62.98\pm4.44$ & $164.45\pm19.60$ & $134.22\pm10.10$ & $93.10\pm3.84$\\\hline
 % Total  & 6144.39 \pm 487.946 & 5452.72 \pm 291.302 & 13851.2 \pm 1191.74 & 19911.9 \pm 2091.1 & 441.49 \pm 41.7833 \\
\hline
\end{tabular}
\begin{tabular}{|c|c|c|}
\hline
 & $t_{h}\tau_{had}\tau_{had}-2j$ & $t_{h}\tau_{had}\tau_{had}-3j$\\
\hline
  only $\tau_{sub}$ real   & $64.23 \pm 70.07$ & $84.46 \pm 100.98$ \\
  %tcH   & 31.4803 \pm 6.36964 & 84.4383 \pm 10.5275 \\
  %tuH   & 45.6609 \pm 6.76374 & 105.38 \pm 10.798 \\
  Diboson   & $8.40 \pm 1.65$ & $10.75 \pm 1.25$ \\
  Fake $\tau$ MC   & $277.11 \pm 148.41$ & $332.76 \pm 153.96$ \\
  $\bar{t}t$   & $225.85 \pm 34.02$ & $209.75 \pm 50.43$ \\
  $Z\rightarrow\tau\tau$   & $485.70 \pm 53.51$ & $406.02 \pm 64.48$ \\
  $\bar{t}tV$   & $0.75 \pm 0.44$ & $5.46 \pm 1.13$ \\
  Rare   & $17.84 \pm 2.96$ & $10.05 \pm 2.72$ \\
  SM Higgs   & $17.29 \pm 2.18$ & $25.88 \pm 2.55$ \\
\hline
Total B  & $1097 \pm 197$ & $1085 \pm 230$ \\ \hline
data                  & $1033\pm32$                   & $1052\pm32$  \\\hline
$\bar{t}t\to bWcH$    & $28.13\pm5.70$        & $80.14\pm9.94$     \\
$cg\to tH$            & $3.35\pm0.67$                 & $4.30\pm0.53$      \\
tcH~merged            & $31.48\pm6.37$                & $84.44\pm10.53$     \\\hline
$\bar{t}t\to bWuH$    & $28.37\pm4.26$        & $83.75\pm8.40$     \\
$ug\to tH$            & $17.29\pm2.59$                & $21.63\pm2.40$     \\
tuH~merged            & $45.66\pm6.76$                & $105.38\pm10.80$    \\\hline
\end{tabular}
%\input{\FCNCTables/tthML/showFake/faketau/postfit/NOMINAL_SROnly/yield_chart}
%\input{\FCNCTables/xTFW/showFake/NOMINAL/yield_chart}
%\begin{center}
%\begin{tabular}{l*{4}{c}}
%\hline\hline
% & $\lephad$, 3j & $\lephad$, $\geq$4j & $\hadhad$, 3j &  $\hadhad$, $\geq$4j \\
%\hline
%$\Hc$  &   $ 89 \pm 14 $ &   $ 226 \pm 43 $ &   $ 46 \pm 14 $ &   $ 122 \pm 32 $ \\
%$\Hu$  &   $ 100 \pm 17 $ &   $ 237 \pm 47 $ &   $ 32 \pm 10 $ &   $ 114 \pm 28 $ \\
%\hline
%Fake $\had$  &   $ 2828 \pm 78 $ &   $ 3200 \pm 100 $ &   $ 710 \pm 110 $ &   $ 500 \pm 62 $ \\
%Top (real $\had$)  &   $ 3840 \pm 720 $ &   $ 3160 \pm 890 $ &   $ 113 \pm 72 $ &   $ 117 \pm 35 $ \\
%$Z \to \tau\tau$  &   $ 420 \pm 140 $ &   $ 320 \pm 120 $ &   $ 283 \pm 99 $ &   $ 267 \pm 96 $ \\
%Other  &   $ 168 \pm 56 $ &   $ 103 \pm 33 $ &   $ 8.9 \pm 2.5 $ &   $ 11.2 \pm 2.5 $ \\
%\hline
%Total background  &   $ 7260 \pm 730 $ &   $ 6770 \pm 880 $ &   $ 1120 \pm 120 $ &   $ 900 \pm 120 $ \\
%\hline
%Data  & 7259  & 6768  & 1119  & 894  \\
%\hline\hline
%\end{tabular}
%%\\
%\vspace{0.2cm}
%
%\end{center}
%\vspace{-0.5cm}
\label{tab:Htautau_Prefit_Yields_Unblind}
\end{table}
%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%
\begin{table}[htbp]
\caption{
Predicted and observed yields in each of the analysis regions considered.
The background prediction is shown after the fit to asimov data under the signal-plus-background hypothesis
(assuming $\Hc$ as signal).
The contributions with real $\had$ candidates from $\ttbar$ and  $Z\to \ell^+\ell^-$ ($\ell = e, \mu$), diboson, $\ttbar V$, $\ttbar H$, single-top-quark, and other small backgrounds are combined into
a single background source referred to as ``Other MC'' in the leptonic channels , whereas single-top-quark and the small contributions are combined into ``Rare'' in the hadronic channels.
The quoted uncertainties are the sum in quadrature of statistical and systematic uncertainties of the yields,
computed taking into account correlations among nuisance parameters and among processes.}
\small
\centering
\begin{tabular}{|c|c|c|c|c|c|}\hline
  & $t_{l}\tau_{had}-1j$ & $t_{l}\tau_{had}2j$ & $t_{h}\tau_{lep}\tau_{had}-3j$ & $t_{h}\tau_{lep}\tau_{had}-2j$ & $t_{l}\tau_{had}\tau_{had}$\\\hline
  QCD Fake lep   & $916.84 \pm 213.23$ & $434.65 \pm 98.21$ & $233.82 \pm 77.52$ & $416.75 \pm 107.82$ & $0 \pm 0$ \\
  W-jet fake $\tau$  & $839.60 \pm 176.84$ & $963.47 \pm 211.11$ & $2934.6 \pm 602.46$ & $3434.22 \pm 820.85$ & $4.96 \pm 1.58$ \\
  Other Fake $\tau$  & $2918.71 \pm 217.11$ & $2625.87 \pm 161.15$ & $1767.93 \pm 455.10$ & $1635.44 \pm 784.74$ & $138.86 \pm 14.05$ \\
  b Fake $\tau$  & $811.72 \pm 109.86$ & $1015.84 \pm 158.82$ & $522.39 \pm 69.31$ & $573.09 \pm 75.11$ & $68.10 \pm 8.32$ \\
    tcH   & $59.82 \pm xxx$ & $54.19 \pm xxx$ & $137.61 \pm xxx$ & $108.24 \pm xxx$ & $71.53 \pm xxx$ \\
  Lep fake $\tau$  & $221.68 \pm 29.45$ & $87.81 \pm 9.62$ & $307.45 \pm 33.81$ & $563.25 \pm 60.64$ & $0.88 \pm 0.34$ \\
  Double Fake $\tau$  & $0 \pm 0$ & $0 \pm 0$ & $0 \pm 0$ & $0 \pm 0$ & $89.74 \pm 23.31$ \\
  $\bar{t}t$   & $280.14 \pm 15.02$ & $178.8 \pm 26.84$ & $7081.53 \pm 363.91$ & $11610.1 \pm 475.80$ & $5.10 \pm 2.69$ \\
  Other MC   & $84.62 \pm 7.34$ & $83.30 \pm 3.10$ & $880.00 \pm 67.57$ & $1591.41 \pm 84.97$ & $40.79 \pm 1.75$ \\
\hline
  Total  & $6144 \pm 170$ & $5453 \pm 94$ & $13851 \pm 138$ & $19912 \pm 164$ & $441 \pm 29$ \\ \hline
\end{tabular}
\begin{tabular}{|c|c|c|}
\hline
 & $t_{h}\tau_{had}\tau_{had}-2j$ & $t_{h}\tau_{had}\tau_{had}-3j$\\
\hline
  only $\tau_{sub}$ real   & $64.23 \pm 49.64$ & $84.46 \pm 66.13$ \\
  tcH   & $31.48 \pm 9.43$ & $84.44 \pm 22.34$ \\
%  tuH   & $45.66 \pm 13.02$ & $105.38 \pm 27.65$ \\
  Diboson   & $8.40 \pm 1.59$ & $10.75 \pm 1.10$ \\
  Fake $\tau$ MC   & $277.11 \pm 87.45$ & $332.77 \pm 93.32$ \\
  $\bar{t}t$   & $225.85 \pm 26.18$ & $209.75 \pm 31.01$ \\
  $Z\rightarrow\tau\tau$   & $485.70 \pm 43.14$ & $406.02 \pm 51.63$ \\
  $\bar{t}tV$   & $0.76 \pm 0.43$ & $5.46 \pm 1.03$ \\
  Rare   & $17.84 \pm 2.76$ & $10.05 \pm 2.53$ \\
  SM Higgs   & $17.30 \pm 1.90$ & $25.88 \pm 2.05$ \\ \hline
  Total background  & $1097 \pm 38$ & $1085 \pm 45$ \\
\hline
\end{tabular}
%\begin{center}
%\begin{tabular}{l*{4}{c}}
%\hline\hline
% & $\lephad$, 3j & $\lephad$, $\geq$4j & $\hadhad$, 3j &  $\hadhad$, $\geq$4j \\
%\hline
%$\Hc$  &   $ -4.2 \pm 8.2 $ &   $ -11 \pm 21 $ &   $ -2.4 \pm 4.3 $ &   $ -10 \pm 11 $ \\
%\hline
%Fake $\had$  &   $ 2290 \pm 680 $ &   $ 2640 \pm 880 $ &   $ 640 \pm 110 $ &   $ 440 \pm 100 $ \\
%Top (real $\had$)  &   $ 4300 \pm 670 $ &   $ 3660 \pm 860 $ &   $ 147 \pm 84 $ &   $ 139 \pm 35 $ \\
%$Z \to \tau\tau$  &   $ 500 \pm 100 $ &   $ 359 \pm 90 $ &   $ 320 \pm 79 $ &   $ 306 \pm 76 $ \\
%Other  &   $ 178 \pm 45 $ &   $ 112 \pm 28 $ &   $ 9.6 \pm 2.6 $ &   $ 12.5 \pm 2.6 $ \\
%\hline
%Total  &   $ 7230 \pm 160 $ &   $ 6760 \pm 170 $ &   $ 1117 \pm 65 $ &   $ 893 \pm 45 $ \\
%\hline
%Data & 7259  & 6768  & 1119  & 894 \\
%\hline\hline
%\end{tabular}
%%\\
%\vspace{0.2cm}
%
%\end{center}
%\vspace{-0.5cm}
\label{tab:Htautau_Postfit_Yields_Unblind_Hc}
\end{table}
%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%
\begin{table}[htbp]
\caption{
Predicted and observed yields in each of the analysis regions considered.
The background prediction is shown after the fit to the asimov data under the signal-plus-background hypothesis
(assuming $\Hu$ as signal).
The contributions with real $\had$ candidates from $\ttbar$ and  $Z\to \ell^+\ell^-$ ($\ell = e, \mu$), diboson, $\ttbar V$, $\ttbar H$, single-top-quark, and other small backgrounds are combined into
a single background source referred to as ``Other MC'' in the leptonic channels , whereas single-top-quark and the small contributions are combined into ``Rare'' in the hadronic channels.
The quoted uncertainties are the sum in quadrature of statistical and systematic uncertainties of the yields,
computed taking into account correlations among nuisance parameters and among processes.
}
\small
\centering
\begin{tabular}{|c|c|c|c|c|c|}
  \hline
 & $t_{l}\tau_{had}-1j$ & $t_{l}\tau_{had}2j$ & $t_{h}\tau_{lep}\tau_{had}-3j$ & $t_{h}\tau_{lep}\tau_{had}-2j$ & $t_{l}\tau_{had}\tau_{had}$\\
\hline
  QCD Fake lep   & $916.84 \pm 213.23$ & $434.65 \pm 98.21$ & $233.82 \pm 77.52$ & $416.75 \pm 107.82$ & $0 \pm 0$ \\
  W-jet fake $\tau$  & $839.60 \pm 176.84$ & $963.47 \pm 211.11$ & $2934.6 \pm 602.46$ & $3434.22 \pm 820.85$ & $4.96 \pm 1.58$ \\
  Other Fake $\tau$  & $2918.71 \pm 217.11$ & $2625.87 \pm 161.15$ & $1767.93 \pm 455.10$ & $1635.44 \pm 784.74$ & $138.86 \pm 14.05$ \\
  b Fake $\tau$  & $811.72 \pm 109.86$ & $1015.84 \pm 158.82$ & $522.39 \pm 69.31$ & $573.09 \pm 75.11$ & $68.10 \pm 8.32$ \\
  tuH   & $71.08 \pm 14.95$ & $62.98 \pm 11.26$ & $123.52 \pm 20.39$ & $87.65 \pm 13.75$ & $93.07 \pm 14.64$ \\
  Lep fake $\tau$  & $221.68 \pm 29.45$ & $87.81 \pm 9.62$ & $307.45 \pm 33.81$ & $563.25 \pm 60.64$ & $0.88 \pm 0.34$ \\
  Double Fake $\tau$  & $0 \pm 0$ & $0 \pm 0$ & $0 \pm 0$ & $0 \pm 0$ & $89.74 \pm 23.31$ \\
  $\bar{t}t$   & $280.14 \pm 15.02$ & $178.8 \pm 26.84$ & $7081.53 \pm 363.91$ & $11610.1 \pm 475.80$ & $5.10 \pm 2.69$ \\
  Other MC   & $84.62 \pm 7.34$ & $83.30 \pm 3.10$ & $880.00 \pm 67.57$ & $1591.41 \pm 84.97$ & $40.79 \pm 1.75$ \\
\hline
  Total  & $6144 \pm 170$ & $5453 \pm 94$ & $13851 \pm 138$ & $19912 \pm 164$ & $441 \pm 29$ \\ \hline
\end{tabular}
\begin{tabular}{|c|c|c|}
\hline
 & $t_{h}\tau_{had}\tau_{had}-2j$ & $t_{h}\tau_{had}\tau_{had}-3j$\\
\hline
  only $\tau_{sub}$ real   & $64.23 \pm 49.64$ & $84.46 \pm 66.13$ \\
  %  tcH   & $31.48 \pm 9.43$ & $84.44 \pm 22.34$ \\
  tuH   & $45.66 \pm 13.02$ & $105.38 \pm 27.65$ \\
  Diboson   & $8.40 \pm 1.59$ & $10.75 \pm 1.10$ \\
  Fake $\tau$ MC   & $277.11 \pm 87.45$ & $332.77 \pm 93.32$ \\
  $\bar{t}t$   & $225.85 \pm 26.18$ & $209.75 \pm 31.01$ \\
  $Z\rightarrow\tau\tau$   & $485.70 \pm 43.14$ & $406.02 \pm 51.63$ \\
  $\bar{t}tV$   & $0.76 \pm 0.43$ & $5.46 \pm 1.03$ \\
  Rare   & $17.84 \pm 2.76$ & $10.05 \pm 2.53$ \\
  SM Higgs   & $17.30 \pm 1.90$ & $25.88 \pm 2.05$ \\ \hline
  Total background  & $1097 \pm 38$ & $1085 \pm 45$ \\
\hline
\end{tabular}
%\begin{center}
%\begin{tabular}{l*{4}{c}}
%\hline\hline
% & $\lephad$, 3j & $\lephad$, $\geq$4j & $\hadhad$, 3j &  $\hadhad$, $\geq$4j \\
%\hline
%$\Hu$  &   $ -5.7 \pm 8.6 $ &   $ -14 \pm 21 $ &   $ -2,0 \pm 2.8 $ &   $ -7.1 \pm 9.8 $ \\
%\hline
%Fake $\had$  &   $ 2270 \pm 680 $ &   $ 2620 \pm 880 $ &   $ 640 \pm 110 $ &   $ 440 \pm 100 $ \\
%Top (real $\had$)  &   $ 4320 \pm 660 $ &   $ 3680 \pm 860 $ &   $ 148 \pm 84 $ &   $ 140 \pm 35 $ \\
%$Z \to \tau\tau$  &   $ 470 \pm 100 $ &   $ 359 \pm 89 $ &   $ 321 \pm 79 $ &   $ 308 \pm 77 $ \\
%Other  &   $ 177 \pm 44 $ &   $ 111 \pm 27 $ &   $ 9.7 \pm 2.6 $ &   $ 12.5 \pm 2.6 $ \\
%\hline
%Total  &   $ 7230 \pm 160 $ &   $ 6760 \pm 160 $ &   $ 1118 \pm 66 $ &   $ 892 \pm 45 $ \\
%\hline
%Data  & 7259  & 6768  & 1119  & 894  \\
%\hline\hline
%\end{tabular}
%%\\
%\vspace{0.2cm}
%
%\end{center}
%\vspace{-0.5cm}
\label{tab:Htautau_Postfit_Yields_Unblind_Hu}
\end{table}
%%%%%%%%%%%%%%%%%%%%%%%%


\usepackage{amsfonts, amsmath, amsthm, amssymb} % For math fonts, symbols and environments
\usepackage{graphicx} % Required for including images
\usepackage{booktabs} % Top and bottom rules for table
\usepackage{wrapfig} % Allows in-line images
\usepackage[labelfont=bf]{caption} % Make figure numbering in captions bold
\usepackage[top=0.5in,bottom=0.5in,left=0.5in,right=0.5in]{geometry} % Reduce the size of the margin
\pagestyle{empty} % Remove page numbers
\hyphenation{ionto-pho-re-tic iso-tro-pic fortran}
\usepackage[scaled]{helvet} % Helvetica font (equivalent to Arial)
\renewcommand*\familydefault{\sfdefault} % Helvetica font
\usepackage[T1]{fontenc}
\usepackage{ulem}
\usepackage{xcolor}
\usepackage{cite}
\usepackage{sectsty}
\usepackage{siunitx}
\usepackage{xfrac}
\usepackage[colorlinks,linkcolor=blue,anchorcolor=blue,citecolor=blue]{hyperref}
\sectionfont{\color{blue}}
\usepackage[compact]{titlesec}
\usepackage{subfig}
\captionsetup{belowskip=0pt,aboveskip=0pt}
\titlespacing\section{0pt}{0pt plus 0pt minus 0pt}{0pt plus 0pt minus 0pt}
\titlespacing\subsection{0pt}{0pt plus 0pt minus 0pt}{0pt plus 0pt minus 0pt}
\titlespacing\subsubsection{0pt}{0pt plus 0pt minus 0pt}{0pt plus 0pt minus 0pt}
\usepackage[labelformat=empty]{caption} % remove automatic figure numbers
\usepackage{enumitem} % list spacing
\setlist{nolistsep} % no separation between items in a list
\usepackage{etoolbox}
\patchcmd{\thebibliography}{\section*{\refname}}{}{}{}
\usepackage[parfill]{parskip}
\usepackage{pdfpages} % use this to add on other pdfs, e.g. Letters of Support
\usepackage{fancyhdr}
\fancyhf{} % sets both header and footer to nothing
\renewcommand{\headrulewidth}{0pt}
% page numbering and header
%\pagestyle{fancy}
%\pagenumbering{arabic}
% \rhead{\thepage}
% \lhead{Principle Investigator (Hill David, Richard)}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% CS624: Analysis of Algorithms
% Copyright 2015 Pejman Ghorbanzade <pejman@ghorbanzade.com>
% Creative Commons Attribution-ShareAlike 4.0 International License
% More info: https://github.com/ghorbanzade/beacon
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\section*{Question 5}

Show how depth-first search works on the graph of Figure \ref{fig51}.
Assume that the \textbf{for} loop of lines 5-7 of the \textsc{DFS} procedure considers the vertices in alphabetical order, and assume that each adjacency list is ordered alphabetically.
Show the discovery and finishing times for each vertex, and show the classification of each edge.

\begin{figure}[H]\centering
\tikzstyle{every path}=[draw,->]
\tikzstyle{vertex}=[circle,draw,minimum size=0.7cm]
\tikzstyle{not visited}=[]
\tikzstyle{visited}=[fill=gray!50]
\tikzstyle{in queue}=[fill=gray!20]
\tikzstyle{label}=[]
\tikzstyle{ultra thick}=[line width=0.6mm]
  \begin{tikzpicture}
    \node[vertex] (1) {q};
    \node[vertex] (3) [left = 1cm of 1] {s};
    \node[vertex] (9) [right = 1cm of 1] {y};
    \node[vertex] (6) [left = 1cm of 3] {v};
    \node[vertex] (7) [below = 1cm of 6] {w};
    \node[vertex] (4) [below = 1cm of 9] {t};
    \node[vertex] (2) [right = 1cm of 9] {r};
    \node[vertex] (5) [below = 1cm of 2] {u};
    \node[vertex] (8) [below = 1cm of 1] {x};
    \node[vertex] (10)[left = 1cm of 8] {z};
%    \node[label]  (9) [above = 0.1cm of 1] {r};
%    \node[label]  (10) [above = 0.1cm of 2] {s};
%    \node[label]  (11) [above = 0.1cm of 3] {t};
%    \node[label]  (12) [above = 0.1cm of 4] {u};
%    \node[label]  (13) [below = 0.1cm of 5] {v};
%    \node[label]  (14) [below = 0.1cm of 6] {w};
%    \node[label]  (15) [below = 0.1cm of 7] {x};
%    \node[label]  (16) [below = 0.1cm of 8] {y};

    \path[thick]
      (1) edge (4)
      (1) edge (3)
      (1) edge (7)
      (3) edge (6)
      (6) edge (7)
      (7) edge (3)
      (4) edge (8)
      (8) edge (10)
      (10) edge [bend left = 30] (8)
      (4) edge (9)
      (9) edge (1)
      (2) edge (9)
      (5) edge (9)
      (2) edge (5)
      ;
    \path[ultra thick]
      ;
  \end{tikzpicture}
\caption{Directed graph $G$}\label{fig51}
\end{figure}

\subsection*{Solution}

Final tree constructed by applying the depth-first search algorithm to graph $G$ starting from source vertex $q$ and continuing alphabetically, is shown in Figure \ref{fig52}.
As can be seen, starting and finishing time of each node is written next to it.

\begin{figure}[H]\centering
\tikzstyle{every path}=[draw,->]
\tikzstyle{vertex}=[circle,draw,minimum size=0.7cm]
\tikzstyle{not visited}=[]
\tikzstyle{visited}=[fill=gray!50]
\tikzstyle{in queue}=[fill=gray!20]
\tikzstyle{label}=[]
\tikzstyle{ultra thick}=[line width=0.6mm]
  \begin{tikzpicture}
    \node[vertex,visited] (1) {q};
    \node[vertex,visited] (3) [left = 1cm of 1] {s};
    \node[vertex,visited] (9) [right = 1cm of 1] {y};
    \node[vertex,visited] (6) [left = 1cm of 3] {v};
    \node[vertex,visited] (7) [below = 1cm of 6] {w};
    \node[vertex,visited] (4) [below = 1cm of 9] {t};
    \node[vertex,visited] (2) [right = 1cm of 9] {r};
    \node[vertex,visited] (5) [below = 1cm of 2] {u};
    \node[vertex,visited] (8) [below = 1cm of 1] {x};
    \node[vertex,visited] (10)[left = 1cm of 8] {z};
    \node[label]  (11) [above = 0.1cm of 6] {3/6};
    \node[label]  (12) [above = 0.1cm of 3] {2/7};
    \node[label]  (13) [above = 0.1cm of 1] {1/16};
    \node[label]  (14) [above = 0.1cm of 9] {13/14};
    \node[label]  (15) [above = 0.1cm of 2] {17/20};
    \node[label]  (16) [below = 0.1cm of 7] {4/5};
    \node[label]  (17) [below = 0.1cm of 10]{10/11};
    \node[label]  (18) [below = 0.1cm of 8] {9/12};
    \node[label]  (19) [below = 0.1cm of 4] {8/15};
    \node[label]  (20) [below = 0.1cm of 5] {18/19};

    \path[thick]
      (1) edge (7)
      (7) edge (3)
      (10) edge [bend left = 30] (8)
      (4) edge (9)
      (9) edge (1)
      (2) edge (9)
      (5) edge (9)
      ;
    \path[ultra thick]
      (1) edge (3)
      (3) edge (6)
      (6) edge (7)
      (1) edge (4)
      (4) edge (8)
      (8) edge (10)
      (2) edge (5)
      ;
  \end{tikzpicture}
\caption{Graph $G$ after implementation of DFS algorithm starting from node $q$}\label{fig52}
\end{figure}

A brief explanation of how the algorithm works is as follows.
First, node $q$ is visited.
Then, due to the alphabetical order, node $s$ will be discovered and visited as the child of $q$.
Since node $s$ is connected to $v$, the algorithm continues by visiting $v$ and $w$.
Once $w$ is visited, since nodes connected to $w$ are already visited, the algorithm will continue with the second child of $q$.
$t$ itself will be discovered and visited.
Since $x$ alphabetically proceeds $y$, the algorithm continues with discovering the subtree $t \rightarrow x \rightarrow z$.
After this step, as second child of $t$ will be visited.
Since $y$ is not connected to any unvisited node, the algorithm will mark it as visited and continues with discovering a new node $r$ and eventually visiting the last node $u$.

Using the DFS algorithm on graph $G$ will lead to a set of tree edges that is as follows.
$E = \{(q,s), (s,v), (v,w), (q,t), (t,x), (x,z), (r,u)\}$.
At the same time, set of forward edges will have only one element $(q,w)$ and set of back edges will include $\{(w,x), (z,x), (y,q)\}$.
Noteworthy that $(r,y)$ and $(u,y)$ are neither in set of forward nor back edges.


\documentclass{article}

\usepackage{fancyhdr}
\usepackage{extramarks}
\usepackage{amsmath}
\usepackage{amsthm}
\usepackage{amsfonts}
\usepackage{tikz}
\usepackage[plain]{algorithm}
\usepackage{algpseudocode}

\usetikzlibrary{automata,positioning}

%
% Basic Document Settings
%

\topmargin=-0.45in
\evensidemargin=0in
\oddsidemargin=0in
\textwidth=6.5in
\textheight=9.0in
\headsep=0.25in

\linespread{1.1}

\pagestyle{fancy}
\lhead{\hmwkAuthorName}
\chead{\hmwkClass\ (\hmwkClassInstructor\ \hmwkClassTime): \hmwkTitle}
\rhead{\firstxmark}
\lfoot{\lastxmark}
\cfoot{\thepage}

\renewcommand\headrulewidth{0.4pt}
\renewcommand\footrulewidth{0.4pt}

\setlength\parindent{0pt}

%
% Create Problem Sections
%

\newcommand{\enterProblemHeader}[1]{
    \nobreak\extramarks{}{Problem \arabic{#1} continued on next page\ldots}\nobreak{}
    \nobreak\extramarks{Problem \arabic{#1} (continued)}{Problem \arabic{#1} continued on next page\ldots}\nobreak{}
}

\newcommand{\exitProblemHeader}[1]{
    \nobreak\extramarks{Problem \arabic{#1} (continued)}{Problem \arabic{#1} continued on next page\ldots}\nobreak{}
    \stepcounter{#1}
    \nobreak\extramarks{Problem \arabic{#1}}{}\nobreak{}
}

\setcounter{secnumdepth}{0}
\newcounter{partCounter}
\newcounter{homeworkProblemCounter}
\setcounter{homeworkProblemCounter}{1}
\nobreak\extramarks{Problem \arabic{homeworkProblemCounter}}{}\nobreak{}

%
% Homework Problem Environment
%
% This environment takes an optional argument. When given, it will adjust the
% problem counter. This is useful for when the problems given for your
% assignment aren't sequential. See the last 3 problems of this template for an
% example.
%
\newenvironment{homeworkProblem}[1][-1]{
    \ifnum#1>0
        \setcounter{homeworkProblemCounter}{#1}
    \fi
    \section{Problem \arabic{homeworkProblemCounter}}
    \setcounter{partCounter}{1}
    \enterProblemHeader{homeworkProblemCounter}
}{
    \exitProblemHeader{homeworkProblemCounter}
}

%
% Homework Details
%   - Title
%   - Due date
%   - Class
%   - Section/Time
%   - Instructor
%   - Author
%

\newcommand{\hmwkTitle}{Homework\ \#2}
\newcommand{\hmwkDueDate}{January 24th, 2017}
\newcommand{\hmwkClass}{Elements of Algebra I}
\newcommand{\hmwkClassTime}{Section 161}
\newcommand{\hmwkClassInstructor}{Professor Deepam Patel}
\newcommand{\hmwkAuthorName}{Yao Xiao}

%
% Title Page
%

\title{
    \vspace{2in}
    \textmd{\textbf{\hmwkClass:\ \hmwkTitle}}\\
    \normalsize\vspace{0.1in}\small{Due\ on\ \hmwkDueDate\  }\\
    \vspace{0.1in}\large{\textit{\hmwkClassInstructor\ \hmwkClassTime}}
    \vspace{3in}
}

\author{\textbf{\hmwkAuthorName}}
\date{}

\renewcommand{\part}[1]{\textbf{\large Part \Alph{partCounter}}\stepcounter{partCounter}\\}

%
% Various Helper Commands
%

% Useful for algorithms
\newcommand{\alg}[1]{\textsc{\bfseries \footnotesize #1}}

% For derivatives
\newcommand{\deriv}[1]{\frac{\mathrm{d}}{\mathrm{d}x} (#1)}

% For partial derivatives
\newcommand{\pderiv}[2]{\frac{\partial}{\partial #1} (#2)}

% Integral dx
\newcommand{\dx}{\mathrm{d}x}

% Alias for the Solution section header
\newcommand{\solution}{\textbf{\large Solution}}

% Probability commands: Expectation, Variance, Covariance, Bias
\newcommand{\E}{\mathrm{E}}
\newcommand{\Var}{\mathrm{Var}}
\newcommand{\Cov}{\mathrm{Cov}}
\newcommand{\Bias}{\mathrm{Bias}}

\begin{document}

\maketitle

\pagebreak

\begin{homeworkProblem}
Proof by induction \\
When n=1,
\[
\begin{split}
1=\frac{n(n+1)(2n+1)}{6}=\frac{1*2*3}{6}
\end{split}
\]
Suppose n=k
\[
\begin{split}
1+2^2+3^2+...+k^2=\frac{k(k+1)(2k+1)}{6}\\
1+2^2+3^2+...+k^2+(k+1)^2&=\frac{k(k+1)(2k+1)}{6}+(k+1)^2\\
&=\frac{6(k+1)^2+k(k+1)(2k+1)}{6}\\
&=\frac{(k+1)(6(k+1)+(2k+1)k)}{6}\\
&=\frac{(k+1)(6k+6+2k^2+k)}{6}\\
&=\frac{(k+1)(2k^2+7k+6)}{6}\\
&=\frac{(k+1)(2k+3)(k+2)}{6}\\
&=\frac{(k+1)(2(k+1)+1)((k+1)+1)}{6}\\
\end{split}
\]
So the equation holds for n=k+1. Therefore, the inequalities hold for all positive integers n > 1 by induction

\end{homeworkProblem}

\begin{homeworkProblem}
Proof by induction \\
When n=2 \\
We have \(1<8/3<5\), so the inequalities hold when n=2

When n is greater than 2, \[
\begin{split}
1+2^2+3^2+...+(n-1)^2+n^2&<\frac{n^3}{3}+n^2\\
&=\frac{n^3+3n^2}{3}\\
&<\frac{n^3+3n^2+3n+1}{3}\\
&=\frac{(n+1)^3}{3}
\end{split}
\]
So the left inequality holds
\[
\begin{split}
1+2^2+3^2+...n^2+(n+1)^2&>\frac{n^3}{3}+(n+1)^2\\
&=\frac{n^3+3(n+1)^2}{3}\\
&=\frac{n^3+3n^2+6n+3}{3}\\
&>\frac{n^3+3n^2+3n+1}{3}\\
&=\frac{(n+1)^3}{3}
\end{split}
\]
So the right inequality holds as well
\end{homeworkProblem}
\begin{homeworkProblem}
\begin{enumerate}
\item Let a be the integer, (a-a)=0. 0 mod anything is 0. So it holds
\item Let a and b be integers. Suppose that a $\equiv$ b (mod n), aka a-b = kn. b-a=-(a-b)=(-k)n. So it holds
\item Let a,b,c be integers. a-b=nk, b-c=nj, let the first one plus the second one a-b+b-c=nk+nj, a-c=n(k+j) so a-c=nk' as well
\end{enumerate}
\end{homeworkProblem}
\begin{homeworkProblem}
\( a \rightarrow b \) is true iff \( \neg b \rightarrow \neg a \) is true.
So we assume a is even, and the product of the two even number is \(2k*2k=2(2k)\) and it's even too.
\end{homeworkProblem}
\begin{homeworkProblem}
Let rotate be function R, so that \[R(1)=2\ R(2)=3\ R(3)=4\ R(4)=1 \]
Let flip be function F, so that \[F(1)=2\ F(2)=1\ F(3)=4\ F(4)=3 \]
When you rotate the square once, twice and three times. It will become (2,3,4,1),(3,4,1,2),(4,1,2,3), respectively. So when you do \(R^3*R\). it will become (1,2,3,4) which is I. So any rotation could be one of the I,\(R,R^2,R^3\)
\end{homeworkProblem}
\begin{homeworkProblem}
Assume we are starting from (1,2,3,4)
\[
\begin{split}
F=(2,1,4,3)\\
FR=R(2,1,4,3)=(3,2,1,4)\\
FR^2=R^2(2,1,4,3)=(4,3,2,1)\\
FR^3=R^3(2,1,4,3)=(1,4,3,2)
\end{split}
\]
\end{homeworkProblem}
\begin{homeworkProblem}
Since \(F^2=I\) and \(R^4=I\), there will be all the symmetric flips. Also it's obvious that you rotate first and flip later
\[RF=F(2,3,4,1)=(3,2,1,4)=FR\]
\end{homeworkProblem}
\begin{homeworkProblem}
The inverse of R is \(R^3\)\\
The inverse of \(R^2\) is \(R^2\)\\
The inverse of \(R^3\) is \(R\)
\end{homeworkProblem}

\end{document}


\subsubsection{Maul}\label{weapon:maul}
Weapon, Blunt, Two-Handed, Regular, Melee\\
Size: L\\
Cost: 200 Gold

\textbf{Bash}\\
6 AP, ST to hit, \passus{1} Reach\\
2d10 + ST Blunt Damage\\
When reducing a creature to 0 Health with this Attack, you can choose to knock them out instead of killing them.

\textbf{Block}\\
ST to block\\
2d4 + \sfrac{1}{3}\texttimes ST Cutting Damage


% This is a XeLaTeX document. To process and view it use the following command:
% xelatex Torch_for_Matlab_users.tex && open Torch_for_Matlab_users.pdf

% Also, I avoided using equations to make the document compatible to automatic conversion to markdown. Here is the command for that:
% pandoc -r latex -w markdown_github -o Torch_for_Matlab_users.md Torch_for_Matlab_users.tex
% To view the Github markdown locally, you can use grip package:
% grip Torch_for_Matlab_users.md

\documentclass[letter]{article}
\usepackage[margin=.7in]{geometry}

\usepackage{hyperref}

\usepackage{fontspec}
\setmainfont{Palatino Linotype}
\newfontfamily{\maintext}{Palatino Linotype}
\newfontfamily{\stressed}{Helvetica}
\newfontfamily{\exotic}{Code2000}
\newfontfamily{\math}{Asana Math}
\pagenumbering{gobble}

\newcommand{\frstClmnWidth}{.43in}
\newcommand{\scndClmnWidth}{6.37in}

\title{Torch for Matlab\textsuperscript{\textregistered}{\let\thefootnote\relax\footnote{Matlab\textsuperscript{\textregistered} is a registered trademark of The MathWorks, Inc.}} Users}
\author{Ata Mahjoubfar\\
\href{mailto:ata.m@ucla.edu}{ata.m@ucla.edu}}

\begin{document}
\maketitle
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section*{General Commands}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Get help for a specific function:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!help sqrt! \\ \hline
\textbf{Torch} & \verb!help(torch.sqrt)! \\ \hline
\end{tabular}
\\

\noindent Documentation of \verb!sqrt! function is shown.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Scalar operations:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!testVar1 = (4*5-1+10.1)/3^2;! \\ \hline
\textbf{Torch} & \verb!testVar1 = (4*5-1+10.1)/3^2;! \\ \hline
\end{tabular}
\\

\noindent The resultant value (3.2333) is assigned to variable \verb!testVar1!.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Scalar assignment:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!testVar2 = testVar1;! or \verb!testVar2 = testVar1! \\ \hline
\textbf{Torch} & \verb!testVar2 = testVar1;! or \verb!testVar2 = testVar1! \\ \hline
\end{tabular}
\\

\noindent The value of variable \verb!testVar1! (3.2333) is assigned to variable \verb!testVar2!.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Display strings and numbers:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!disp(['The distance is ', num2str(100), ' meters.'])! \\ \hline
\textbf{Torch} & \verb!print('The distance is ' .. 100 .. ' meters.')! \\ \hline
\end{tabular}
\\

\noindent This prints \verb!The distance is 100 meters.! in the output.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Determine type:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!class('Hi')! \\ \hline
\textbf{Torch} & \verb!torch.type('Hi')! \\ \hline
\end{tabular}
\\

\noindent For this example, Matlab returns \verb!char!, and Torch returns \verb!string!.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section*{Matrices and Tensors}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Create a two-dimensional tensor or matrix:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!m = [9, 6, 3, 4; 7, 2, 8, 1]! \\ \hline
\textbf{Torch} & \verb!m = torch.Tensor({{9, 6, 3, 4}, {7, 2, 8, 1}})! \\ \hline
\end{tabular}
\\

\noindent A 2×4 two-dimensional tensor (matrix) with specified elements is formed and assigned to \verb!m!.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Number of dimensions of a tensor:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!ndims(m)! \\ \hline
\textbf{Torch} & \verb!m:dim()! \\ \hline
\end{tabular}
\\

\noindent For example here, for the previously defined two-dimensional tensor (matrix) \verb!m!, the returned number is 2.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Size of a tensor in all dimensions:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!size(m)! \\ \hline
\textbf{Torch} & \verb!m:size()! or \verb!#m! \\ \hline
\end{tabular}
\\

\noindent For example here, for the previously defined two-dimensional tensor (matrix) \verb!m!, the returned numbers are 2 and 4, which are the numbers of rows and columns, respectively.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Size of a tensor in a specific dimension:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!size(m,2)! \\ \hline
\textbf{Torch} & \verb!m:size(2)! or \verb!(#m)[2]! \\ \hline
\end{tabular}
\\

\noindent For example here, for the previously defined two-dimensional tensor (matrix) \verb!m!, the returned number is 4, which is the size of the second dimension (number of columns).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Number of elements in a tensor:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!numel(m)! \\ \hline
\textbf{Torch} & \verb!m:numel()! \\ \hline
\end{tabular}
\\

\noindent For example here, for the previously defined two-dimensional tensor (matrix) \verb!m!, the returned number is 8.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Create a row vector:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!v = [9, 7, 6, 8]! or \verb!v = [9 7 6 8]! \\ \hline
\textbf{Torch} & \verb!v = torch.Tensor({{9, 7, 6, 8}})! \\ \hline
\end{tabular}
\\

\noindent Unlike Matlab, this is not used as a vector in Torch because it is a two-dimensional Tensor.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Create a column vector:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!v = [9; 7; 6; 8]! \\ \hline
\textbf{Torch} & \verb!v = torch.Tensor({{9}, {7}, {6}, {8}})! \\ \hline
\end{tabular}
\\

\noindent Again unlike Matlab, this is not used as a vector in Torch because it is still a two-dimensional Tensor.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Create a one-dimensional tensor:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \textit{Not available} \\ \hline
\textbf{Torch} & \verb!t = torch.Tensor({9, 7, 6, 8})! \\ \hline
\end{tabular}
\\

\noindent Matlab does not have \textit{one-dimensional tensors}; this can be verified by running \verb!ndims([9, 7, 6, 8])!. On the other hand, for many operations that Matlab uses row or column vectors, Torch uses one-dimensional tensors.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Access an element in a vector or one-dimensional tensor:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!v(2)! \\ \hline
\textbf{Torch} & \verb!t[2]! \\ \hline
\end{tabular}
\\

\noindent Second element of the vector is accessed.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Access an element from the end of a vector or one-dimensional tensor:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!v(end-1)! \\ \hline
\textbf{Torch} & \verb!t[-2]! \\ \hline
\end{tabular}
\\

\noindent Second element from the end of the vector is accessed.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Access a range of elements in a vector or one-dimensional tensor:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!v(2:4)! \\ \hline
\textbf{Torch} & \verb!t[{{2,4}}]! \\ \hline
\end{tabular}
\\

\noindent Second to fourth elements of the vector are accessed.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Access an element in a matrix:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!m(2, 3)! \\ \hline
\textbf{Torch} & \verb!m[{2, 3}]! or \verb!m[2][3]! \\ \hline
\end{tabular}
\\

\noindent Second row, third column element is accessed. Accessing in the form of \verb!m[2][3]! is not recommended, because it causes an \verb!out of memory! error for large tensors.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Access a row in a matrix as a two-dimensional tensor:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!m(2, :)! \\ \hline
\textbf{Torch} & \verb!m[{{2}, {}}]! \\ \hline
\end{tabular}
\\

\noindent The returned row is a two-dimensional tensor.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Access a row in a matrix as a one-dimensional tensor:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \textit{Not available} \\ \hline
\textbf{Torch} & \verb!m[{2, {}}]! or \verb!m[2]! \\ \hline
\end{tabular}
\\

\noindent The returned row is a one-dimensional tensor.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Access a column in a matrix as a two-dimensional tensor:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!m(:, 2)! \\ \hline
\textbf{Torch} & \verb!m[{{}, {2}}]! \\ \hline
\end{tabular}
\\

\noindent The returned column is a two-dimensional tensor.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Access a column in a matrix as a one-dimensional tensor:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \textit{Not available} \\ \hline
\textbf{Torch} & \verb!m[{{}, 2}]! \\ \hline
\end{tabular}
\\

\noindent The returned column is a one-dimensional tensor.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Access a range of elements in a matrix:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!m(2, 2:4)! \\ \hline
\textbf{Torch} & \verb!m[{{2}, {2,4}}] or m[{2, {2,4}}]! \\ \hline
\end{tabular}
\\

\noindent The second to fourth columns of the second row are returned. In Torch, there is a slight difference between using \verb!index! (e.g. \verb!2!) or \verb!{index}! (e.g. \verb!{2}!) for pointing to a singleton dimension. For \verb!{index}!, the dimension of the returned tensor is same as the original tensor (e.g. tensor~\verb!m!). For \verb!index!, the singleton dimension is removed, and the dimension of the returned tensor is one less than the original tensor (e.g. tensor~\verb!m!). Also, \verb!{}! refers to all elements in that dimension. Finally, \verb!-index! (e.g. \verb!-4!) means \verb!index!-th (e.g. fourth) element from the end.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section*{Forming Basic Tensors}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Create a vector over a range of values with unit step:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!3:8! \\ \hline
\textbf{Torch} & \verb!torch.range(3, 8)! \\ \hline
\end{tabular}
\\

\noindent Torch's result is a one-dimensional tensor with elements spaced \verb!1! strating at \verb!3!.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Create a vector over a range of values with an arbitrary step:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!3:-1.9:-4.2! \\ \hline
\textbf{Torch} & \verb!torch.range(3, -4.2, -1.9)! \\ \hline
\end{tabular}
\\

\noindent Torch's result is a one-dimensional tensor with elements spaced \verb!-1.9! strating at \verb!3!.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Create a vector with linearly-located elements:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!linspace(3, 8, 50)! \\ \hline
\textbf{Torch} & \verb!torch.linspace(3, 8, 50)! \\ \hline
\end{tabular}
\\

\noindent Torch's result is a one-dimensional tensor with \verb!50! equally-spaced elements strating at \verb!3! and ending at \verb!8!.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Create a vector with logarithmically-located elements:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!logspace(3, 8, 50)! \\ \hline
\textbf{Torch} & \verb!torch.logspace(3, 8, 50)! \\ \hline
\end{tabular}
\\

\noindent Torch's result is a one-dimensional tensor with \verb!50! exponentially-spaced elements strating at 10\textsuperscript{3} and ending at 10\textsuperscript{8}.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Create an all zeros vector or one-dimensional tensor:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!zeros(1,4)! or \verb!zeros(4,1)! \\ \hline
\textbf{Torch} & \verb!torch.zeros(4)! \\ \hline
\end{tabular}
\\

\noindent Torch's result is a one-dimensional tensor with \verb!4! zero elements.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Create an all zeros matrix:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!zeros(5,3)! \\ \hline
\textbf{Torch} & \verb!torch.zeros(5,3)! \\ \hline
\end{tabular}
\\

\noindent 5×3 matrix of zeros is generated.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Create an all ones vector or one-dimensional tensor:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!ones(1,4)! or \verb!ones(4,1)! \\ \hline
\textbf{Torch} & \verb!torch.ones(4)! \\ \hline
\end{tabular}
\\

\noindent Torch's result is a one-dimensional tensor with \verb!4! one elements.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Create an all ones matrix:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!ones(5,3)! \\ \hline
\textbf{Torch} & \verb!torch.ones(5,3)! \\ \hline
\end{tabular}
\\

\noindent 5×3 matrix of ones is generated.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Create an identity matrix:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!eye(5,3)! \\ \hline
\textbf{Torch} & \verb!torch.eye(5,3)! \\ \hline
\end{tabular}
\\

\noindent 5×3 identity matrix is generated.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Create a square identity matrix:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!eye(4)! \\ \hline
\textbf{Torch} & \verb!torch.eye(4)! \\ \hline
\end{tabular}
\\

\noindent 4×4 identity matrix is generated.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Create a uniformly-distributed random vector or one-dimensional tensor:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!rand(1,4)! or \verb!rand(4,1)! \\ \hline
\textbf{Torch} & \verb!torch.rand(4)! \\ \hline
\end{tabular}
\\

\noindent Torch's result is a one-dimensional tensor with \verb!4! random elements from uniform probability distribution.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Create a uniformly-distributed random matrix:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!rand(5,3)! \\ \hline
\textbf{Torch} & \verb!torch.rand(5,3)! \\ \hline
\end{tabular}
\\

\noindent 5×3 matrix of random elements from uniform probability distribution is generated.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Create a normally-distributed random vector or one-dimensional tensor:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!randn(1,4)! or \verb!randn(4,1)! \\ \hline
\textbf{Torch} & \verb!torch.randn(4)! \\ \hline
\end{tabular}
\\

\noindent Torch's result is a one-dimensional tensor with \verb!4! random elements from normal probability distribution.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Create a normally-distributed random matrix:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!randn(5,3)! \\ \hline
\textbf{Torch} & \verb!torch.randn(5,3)! \\ \hline
\end{tabular}
\\

\noindent 5×3 matrix of random elements from normal probability distribution is generated.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section*{Operations}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Tensor assignment without memory copy:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \textit{Not directly available} \\ \hline
\textbf{Torch} & \verb!matOut = matIn! or \verb!matOut = matIn;! \\ \hline
\end{tabular}
\\

\noindent Matlab internally handles memory assignment for a copied array. As soon, as the copied array is modified in Matlab, a copy of the initial array is generated. Whereas, Torch gives this option to have a copied tensor that points to the same location in the memory as the initial tensor. For example, if elements of the \verb!matOut! tensor are modified here, the same changes happen to the elements of the \verb!matIn! tensor.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Tensor assignment with memory copy:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!matOut = matIn! or \verb!matOut = matIn;! \\ \hline
\textbf{Torch} & \verb!matOut = matIn:clone()! or \verb!matOut = matIn:clone();! \\ \hline
\end{tabular}
\\

\noindent Matlab's internal memory handling for array assignment is somewhat closer to this. Here, Torch generates a copy of the tensor content in memory. Any changes in \verb!matOut! elements are independent of the changes in the elements of the \verb!matIn! tensor.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Change type of a tensor:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!uint8(matIn)!, \verb!int8(matIn)!, \verb!int16(matIn)!, \verb!int32(matIn)!, \verb!int64(matIn)!, \verb!single(matIn)!, or \verb!double(matIn)! \\ \hline
\textbf{Torch} & \verb!matIn:byte()!, \verb!matIn:char()!, \verb!matIn:short()!, \verb!matIn:int()!, \verb!matIn:long()!, \verb!matIn:float()!, or \verb!matIn:double()! \\ \hline
\end{tabular}
\\

\noindent By default, double precision is used.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Multiplication of a tensor by a scalar:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!matIn * 17! or \verb!17 * matIn! \\ \hline
\textbf{Torch} & \verb!matIn * 17! \\ \hline
\end{tabular}
\\

\noindent Pay attention that in Torch, the scalar cannot be the first argument of the multiplication.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Matrix multiplication of a tensor by another tensor:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!matA * matB! \\ \hline
\textbf{Torch} & \verb!matA * matB! \\ \hline
\end{tabular}
\\

\noindent Tensor sizes must be appropriate for the multiplication.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Element-wise multiplication of a tensor by another tensor:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!matA .* matB! \\ \hline
\textbf{Torch} & \verb!torch.cmul(matA, matB)! \\ \hline
\end{tabular}
\\

\noindent Tensor sizes must be identical.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Transpose of a two-dimensional tensor (matrix):}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!matIn.'! \\ \hline
\textbf{Torch} & \verb!matIn:t()! \\ \hline
\end{tabular}
\\

\noindent A new tensor, which is the transpose of the input matrix (two-dimensional tensor) is returned.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Vertical tensor concatenation:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb![matTop; matBottom]! \\ \hline
\textbf{Torch} & \verb!torch.cat(matTop, matBottom, 1)! \\ \hline
\end{tabular}
\\

\noindent The number of columns in input tensors must be equal.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Horizontal tensor concatenation:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb![matLeft, matRight]! \\ \hline
\textbf{Torch} & \verb!torch.cat(matLeft, matRight, 2)! \\ \hline
\end{tabular}
\\

\noindent The number of rows in input tensors must be equal.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Square root of elements returned in a new tensor:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!matOut = sqrt(matIn)! \\ \hline
\textbf{Torch} & \verb!matOut = torch.sqrt(matIn)! \\ \hline
\end{tabular}
\\

\noindent Square root of each element is saved in an output tensor with the same size as the input tensor.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Square root of elements returned in the same tensor:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!matIn = sqrt(matIn)! \\ \hline
\textbf{Torch} & \verb!matIn = torch.sqrt(matIn)! or \verb!matIn.sqrt(matIn)! or \verb!matIn:sqrt()! \\ \hline
\end{tabular}
\\

\noindent \verb!matIn:sqrt()! is same as \verb!matIn.sqrt(matIn)!. Generally in Torch, \verb!object:function(p1, p2, ...)! is same as\\ \verb!object.function(object, p1, p2, ...)!, where the function's object (also known as \verb!self!) is passed as the first input to the function.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Element-wise power to a scalar:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!matIn.^5! \\ \hline
\textbf{Torch} & \verb!torch.pow(matIn, 5)! \\ \hline
\end{tabular}
\\

\noindent Each element to the power of 5 is saved in an output tensor with the same size as the input tensor.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Element-wise power to a tensor:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!matIn.^matPow! \\ \hline
\textbf{Torch} & \verb!torch.cpow(matIn, matPow)! \\ \hline
\end{tabular}
\\

\noindent Each element of the \verb!matIn! tensor to the power of the corresponding element of the \verb!matPow! tensor is saved in an output tensor with the same size as the input tensor.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%
\end{document}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection*{Short description here:}

\begin{tabular}{|p{\frstClmnWidth{}}|p{\scndClmnWidth{}}|}
\hline
\textbf{Matlab} & \verb!Matlab code here! \\ \hline
\textbf{Torch} & \verb!Torch code here! \\ \hline
\end{tabular}
\\

\noindent Description of the details here.


%!TEX root = forallxsol.tex
%\part{Interpretations}
%\label{ch.semantics}
%\addtocontents{toc}{\protect\mbox{}\protect\hrulefill\par}

\setcounter{chapter}{27}
\chapter{Truth in FOL}\setcounter{ProbPart}{0}
\problempart
\label{pr.TorF1}
Consider the following interpretation:
	\begin{ebullet}
		\item The domain comprises only Corwin and Benedict
		\item `$Ax$' is to be true of both Corwin and Benedict
		\item `$Bx$' is to be true of Benedict only
		\item `$Nx$' is to be true of no one
		\item `$c$' is to refer to Corwin
	\end{ebullet}
Determine whether each of the following sentences is true or false in that interpretation:
\begin{earg}
\item $Bc$ \hfill \myanswer{False}
\item $Ac \eiff \enot Nc$ \hfill \myanswer{True}
\item $Nc \eif (Ac \eor Bc)$ \hfill \myanswer{True}
\item $\forall x Ax$ \hfill \myanswer{True}
\item $\forall x \enot Bx$ \hfill \myanswer{False}
\item $\exists x(Ax \eand Bx)$ \hfill \myanswer{True}
\item $\exists x(Ax \eif Nx)$ \hfill \myanswer{False}
\item $\forall x(Nx \eor \enot Nx)$ \hfill \myanswer{True}
\item $\exists x Bx \eif \forall x Ax$ \hfill \myanswer{True}
\end{earg}

\problempart
\label{pr.TorF2}
Consider the following interpretation:
	\begin{ebullet}
		\item The domain comprises only Lemmy, Courtney and Eddy
		\item `$Gx$' is to be true of Lemmy, Courtney and Eddy.
		\item `$Hx$' is to be true of and only of Courtney
		\item `$Mx$' is to be true of and only of Lemmy and Eddy
		\item `$c$' is to refer to Courtney
		\item `$e$' is to refer to Eddy
	\end{ebullet}
Determine whether each of the following sentences is true or false in that interpretation:
\begin{earg}
\item $Hc$ \hfill \myanswer{True}
\item $He$\hfill \myanswer{False}
\item $Mc \eor Me$ \hfill \myanswer{True}
\item $Gc \eor \enot Gc$ \hfill \myanswer{True}
\item $Mc \eif Gc$ \hfill \myanswer{True}
\item $\exists x Hx$ \hfill \myanswer{True}
\item $\forall x Hx$ \hfill \myanswer{False}
\item $\exists x \enot Mx$ \hfill \myanswer{True}
\item $\exists x(Hx \eand Gx)$ \hfill \myanswer{True}
\item $\exists x(Mx \eand Gx)$ \hfill \myanswer{True}
\item $\forall x(Hx \eor Mx)$ \hfill \myanswer{True}
\item $\exists x Hx \eand \exists x Mx$ \hfill \myanswer{True}
\item $\forall x(Hx \eiff \enot Mx)$ \hfill \myanswer{True}
\item $\exists x Gx \eand \exists x \enot Gx$ \hfill \myanswer{False}
\item $\forall x\exists y(Gx \eand Hy)$ \hfill \myanswer{True}
\end{earg}

\problempart
\label{pr.TorF3}
Following the diagram conventions introduced at the end of \S23, consider the following interpretation:
\begin{center}
\begin{tikzpicture}
\node (atom1) at (0,2) {1};
\node (atom2) at (2,2) {2};
\node (atom4) at (0,0) {3};
\node (atom5) at (2,0) {4};
\node (atom6) at (4,0) {5};
\draw[->, thick] (atom1)+(-0.15,0.15) arc (-330:-30:.3);
\draw[->, thick] (atom6)+(0.15,-0.15) arc (-150:150:.3);
\draw[->, thick] (atom1) -- (atom2);
\draw[->, thick] (atom1) -- (atom4);
\draw[<->, thick] (atom1) -- (atom5);
\draw[->, thick] (atom1) -- (atom6);
\draw[->, thick] (atom2) -- (atom6);
\end{tikzpicture}
\end{center}
Determine whether each of the following sentences is true or false in that interpretation:
\begin{earg}
\item $\exists x Rxx$ \hfill \myanswer{True}
\item $\forall x Rxx$ \hfill \myanswer{False}
\item $\exists x \forall y Rxy$ \hfill \myanswer{True}
\item $\exists x \forall y Ryx$ \hfill \myanswer{False}
\item $\forall x \forall y \forall z ((Rxy \eand Ryz) \eif Rxz)$ \hfill \myanswer{False}
\item $\forall x \forall y \forall z ((Rxy \eand Rxz) \eif Ryz)$ \hfill \myanswer{False}
\item $\exists x \forall y \enot Rxy$ \hfill \myanswer{True}
\item $\forall x(\exists y Rxy \eif \exists y Ryx)$ \hfill \myanswer{True}
\item $\exists x \exists y (\enot x = y \eand Rxy \eand Ryx)$ \hfill \myanswer{True}
\item $\exists x \forall y(Rxy \eiff x = y)$ \hfill \myanswer{True}
\item $\exists x \forall y(Ryx \eiff x = y)$ \hfill \myanswer{False}
\item $\exists x \exists y(\enot x = y \eand Rxy \eand \forall z(Rzx \eiff y = z))$ \hfill \myanswer{True}
\end{earg}

\setcounter{chapter}{29}
\chapter{Using Interpretations}\setcounter{ProbPart}{0}

\solutions
\problempart
\label{pr.Contingent}
Show that each of the following is neither a logical truth nor a contradiction:
\begin{earg}
\item \leftsolutions\ $Da \eand Db$
\item \leftsolutions\ $\exists x Txh$
\item \leftsolutions\ $Pm \eand \enot\forall x Px$
\item $\forall z Jz \eiff \exists y Jy$
\item $\forall x (Wxmn \eor \exists yLxy)$
\item $\exists x (Gx \eif \forall y My)$
\item $\exists x (x = h \eand x = i)$
\end{earg}

\solutions
\problempart
\label{pr.NotEquiv}
Show that the following pairs of sentences are not logically equivalent.
\begin{earg}
\item $Ja$, $Ka$
\item $\exists x Jx$, $Jm$
\item $\forall x Rxx$, $\exists x Rxx$
\item $\exists x Px \eif Qc$, $\exists x (Px \eif Qc)$
\item $\forall x(Px \eif \enot Qx)$, $\exists x(Px \eand \enot Qx)$
\item $\exists x(Px \eand Qx)$, $\exists x(Px \eif Qx)$
\item $\forall x(Px\eif Qx)$, $\forall x(Px \eand Qx)$
\item $\forall x\exists y Rxy$, $\exists x\forall y Rxy$
\item $\forall x\exists y Rxy$, $\forall x\exists y Ryx$
\end{earg}

\problempart
Show that the following sentences are jointly consistent:
\begin{earg}
\item $Ma, \enot Na, Pa, \enot Qa$
\item $Lee, Leg, \enot Lge, \enot Lgg$
\item $\enot (Ma \eand \exists x Ax), Ma \eor Fa, \forall x(Fx \eif Ax)$
\item $Ma \eor Mb, Ma \eif \forall x \enot Mx$
\item $\forall y Gy, \forall x (Gx \eif Hx), \exists y \enot Iy$
\item $\exists x(Bx \eor Ax), \forall x \enot Cx, \forall x\bigl[(Ax \eand Bx) \eif Cx\bigr]$
\item $\exists x Xx, \exists x Yx, \forall x(Xx \eiff \enot Yx)$
\item $\forall x(Px \eor Qx), \exists x\enot(Qx \eand Px)$
\item $\exists z(Nz \eand Ozz), \forall x\forall y(Oxy \eif Oyx)$
\item $\enot \exists x \forall y Rxy, \forall x \exists y Rxy$
\item $\enot Raa$, $\forall x (x=a \eor Rxa)$
\item $\forall x\forall y\forall z[(x=y \eor y=z )\eor x=z]$, $\exists x\exists y\ \enot x= y$
\item $\exists x\exists y((Zx \eand Zy )\eand x=y)$, $\enot Zd$, $d=e$
\end{earg}

\problempart
Show that the following arguments are invalid:
\begin{earg}
\item $\forall x(Ax \eif Bx) \therefore \exists x Bx$
\item $\forall x(Rx \eif Dx), \forall x(Rx \eif Fx) \therefore \exists x(Dx \eand Fx)$
\item $\exists x(Px\eif Qx) \therefore \exists x Px$
\item $Na \eand Nb \eand Nc \therefore \forall x Nx$
\item $Rde, \exists x Rxd \therefore Red$
\item $\exists x(Ex \eand Fx), \exists x Fx \eif \exists x Gx \therefore \exists x(Ex \eand Gx)$
\item $\forall x Oxc, \forall x Ocx \therefore \forall x Oxx$
\item $\exists x(Jx \eand Kx), \exists x \enot Kx, \exists x \enot Jx \therefore \exists x(\enot Jx \eand \enot Kx)$
\item $Lab \eif \forall x Lxb, \exists x Lxb \therefore Lbb$
\item $\forall x(Dx \eif \exists y Tyx) \therefore \exists y \exists z\ \enot y= z$
\end{earg}


\section{Introduction}

The \textit{Online Encyclopedia of Integer Sequences} \citep{OEIS} is an online
database of sequences of numbers that collects any kind of data regarding them,
available at \url{https://oeis.org/}.  It was founded by N.~J.~A.~Sloane in
$1964$ and since then has been, and continue to be, updated constantly by
contributions of many users. Despite of its powerful searching mechanisms,
shown in Figure \ref{fig:oeis:page} which reports results about the well known
sequence of Fibonacci numbers (see e.g.  \citep{ConcreteMath}), we design a
parallel \textit{suite of software tools} that satisfies the necessities (i)~to
search the OEIS offline by downloading repeated searches, (ii)~to work in the
console to use programming facilities to manipulate contents more effectively
and (iii)~to interface with third-party libraries to visualize networks
encoding connections among sequences.

\begin{figure}
\centering
\includegraphics{OEIS/oeis-page}
\caption{The OEIS search page: the present snapshot shows search
results about the sequence of Fibonacci numbers }
\label{fig:oeis:page}
\end{figure}

Looking for similar approaches in the recent literature,
\citep{Nguyen_miningthe} mines the OEIS for new mathematical identities,
discussing how to store, compare and match integer sequences toward the
formalization of some conjectures; on the other hand, searching the word
"\textit{oeis}" in GitHub returns one hundred repositories, the majority of
them host simple implementations of scripts that download data about a
given sequence, targeting all major programming languages. Moreover,
\citep{weidmann:sequencer} is a project that identifies number sequences given
a list of numbers and gives a formula that generates them.

Our approach complements the former ones because it provides a
\textit{recursive} and \textit{asynchronous} fetching process, vanilla data
storage in JSON files and visualization of sequences' relations; the
description of each tool is addressed in the following sections, respectively.

The present suite of tools had been shown at an open school on
Combinatorial Method in the analysis of Algorithms and Data Structures
in Korea \citep{Nocentini:korea}; moreover, all the sources that
implements the applications can be found online in the repository
\url{https://github.com/massimo-nocentini/oeis-tools}.

\section{The Crawler}

The script \verb|crawling.py| implements a bot that given a sequence identifier
in the form $Axxxxxx$, where $x$s are digits, issues an HTTP request to the
main OEIS server and waits for a response; once it is received, the bot stores
it locally and, looking into the response's \verb|xref| section that contains a
set of other sequences identifiers, repeats its behaviour on each one of them,
recursively.  Such a bot is commonly known as \emph{crawler}.

Our implementation features neither threads nor race conditions nor data sync;
on the contrary, it targets \textit{pure asynchronous computation} by using
\textit{async/await} Python primitives only. The approach is educational and we
strive to create a simple but elegant codebase which boils down to $300$ lines
of Python code; eventually, it allows us to cache portions of the OEIS to speed
up repeated lookups and to restart the fetching process from the cache already
downloaded.

The script presents a help message to explain itself:
\VerbatimInput[fontsize=\small]{OEIS/crawler-help.txt}

\begin{example}
We illustrate a typical session where we start from scratch. First of all, we
want to download the OEIS content about two important and nice sequences,
namely those corresponding to the Fibonacci and Catalan numbers (see e.g.
\citep{ConcreteMath,stanley:2015}), known in the OEIS by identifiers $A000045$ and
$A000108$, respectively:
\VerbatimInput[fontsize=\small]{OEIS/crawler-fetching-command.txt}
After stopping the crawler, we check the content of cache with the commands
\VerbatimInput[fontsize=\small]{OEIS/crawler-status.txt} which tell us that
$30$ sequences had been fetched and stored in the default directory
\verb|./fetched/|.  Moreover, we can restart the crawler from where it was
interrupted with the command
\VerbatimInput[fontsize=\small]{OEIS/crawler-restarting.txt}
and we check that new sequences are actually collected,
\begin{Verbatim}[fontsize=\small]
$ python3.6 crawling.py
50 sequences in cache ./fetched/
354 sequences in fringe for restarting
\end{Verbatim}
as desired.
\end{example}

Having contents stored in JSON files allows us to inspect and manipulate them
using every tool available in our working environment, as the next example
shows.

\begin{example}
Combining the \verb|cat| command with the Python module \verb|json.tool|, that prints JSON files
with respect to indentation, we can visualize data about the sequence of Fibonacci
numbers as follows
\VerbatimInput[fontsize=\small]{OEIS/crawler-A000045-chunk.txt}
\end{example}

Our implementation takes strong inspiration from
\citep{VANROSSUM:DAVIS:async:await} and provides the following main abstractions:

\begin{description}
\item[reader] objects, that have the responsibility to be \textit{asynchronous
iterators}, having to respond to the message \verb|__anext__| where the
computation waits asynchronously for incoming data from the \verb|self.read|
coroutine. The code
\inputminted[fontsize=\small,stripnl=false,firstline=28,lastline=39]
{python}{../src/crawling.py} implements the description precisely.

\item[fetcher] objects have the responsibilities to (i)~create a socket with
OEIS server, (ii)~establish a working connection, (iii)~send an HTTP \verb|GET|
request for the desired sequence, (iv)~wait for the fetching process completes
and (v)~close the socket and signal that the work ends successfully.
\inputminted[fontsize=\small,stripnl=false,firstline=41,lastline=86]
    {python}{../src/crawling.py}

\item[crawler] objects have the responsibilities (i)~to keep a queue of task,
one for each candidate sequence, (ii)~to put each ready task into the
scheduling process and (iii)~to reclaim memory for completed task and,
eventually, (iv)~to deque them.
\inputminted[fontsize=\small,stripnl=false,firstline=89,lastline=117]
    {python}{../src/crawling.py}

\end{description}

\iffalse
Finally, the function \verb|oeis| puts all together and it is the main
interface exported by the \verb|crawling| module:
\inputminted[fontsize=\small,stripnl=false,firstline=195,lastline=221]
    {python}{../src/crawling.py}
\fi

\section{The (Pretty) Printer}

The script \verb|pprinting.py| provides a proxy for searching into the OEIS,
therefore it shows exactly the same contents you see from usual web interface
on \url{http://oeis.org}; additionally, it provides (i)~tabular representations
of \verb|data| sections in \textit{one and two dimensions} using list and
matrix notations, respectively, (ii)~filtering capabilities on most response's
sections and (iii)~interoperability with the crawler tool by taking advantage of
cached sequences.

The script presents a help message to explain itself:
\VerbatimInput[fontsize=\small]{OEIS/pprinting-help.txt} In the next examples
we show how \verb|pprinting|'s facilities can be used to apply filters, to
print data-only visualization and to search by an open query, respectively.

\begin{example} Typing the following command into a shell, it outputs
on the \verb|stdout| the pretty-printed contents about the sequence of
Fibonacci numbers, with two filters applied that show comments made by
prof. Barry and the first $5$ formulae only,
\VerbatimInput[fontsize=\small]{OEIS/pprinting-A000045.txt}
other sections, such as \verb|reference| and \verb|link|, are hidden by
default to provide a cleaner output.
\end{example}

\begin{example}
The following command pretty prints (i)~the first 3 sequences from our current
cache --the result may vary if you try on your own machine--, (ii)~ranking them
according to the most recent access time, (iii)~reporting data only and
(iv)~limiting up to $10$ coefficients for linear sequences:
\VerbatimInput[fontsize=\small]{OEIS/pprinting-data-only.txt}
\end{example}

\begin{example}
The following command pretty prints (i)~response about the open query
"\verb|pascal triangle|", (ii)~using $2$-dimension representation for matrices
in \verb|data| sections and (iii)~reports the first $2$ sequences in the
returned list only,
\VerbatimInput[fontsize=\small]{OEIS/pprinting-pascal-matrix.txt}
\end{example}

In parallel of the textual interface, we develop pretty printing functions that
integrates in Jupyter notebooks. The aim remains the same, namely to present
contents taken from the OEIS targeting a different environment that accepts
their representation; this is the time of a dynamic web interface that allows
us to evaluate Python code on the fly. Using Jupyter's Markdown language to
write textual content, we propose another view of the same data, as shown in
Figures \ref{fig:oeis:notebook:fibonacci}, \ref{fig:oeis:notebook:catalan} and
\ref{fig:oeis:notebook:pascal}; in particular, we take advantage of
(i)~hyper-references to make sequences labels clickable to quickly visit them
in a new tab, (ii)~font styles to emphasize words in italics and
(iii)~bold-face and to render math notations properly such as $2$-dimensional
array representation for matrices.
\vfill

\begin{figure}
\includegraphics{OEIS/notebook-fibonacci}
\caption{This screenshot shows search results about the Fibonacci numbers where
(i)~the section about comments is filtered such that the word "\emph{binomial}"
has to appear in their text and (ii)~the section about formulae is hidden.}
\label{fig:oeis:notebook:fibonacci}
\end{figure}

\begin{figure}
\includegraphics{OEIS/notebook-catalan}
\caption{This screenshot shows search results of a query using a subsequence,
showing \emph{data} sections only.}
\label{fig:oeis:notebook:catalan}
\end{figure}

\begin{figure}
\includegraphics{OEIS/notebook-pascal}
\caption{This screenshot shows search results of an open query using the
"\emph{pascal}" keyword, representing the \emph{data} section as a
$2$-dimensional array.  }
\label{fig:oeis:notebook:pascal}
\end{figure}

\section{The Grapher}

The script \verb|graphing.py| allows us to represent networks where vertices
are sequences and edges are connections among them, according to \verb|xref|
sections in their JSON encodings. It integrates with the crawler tool by
parsing the fetched files and creates \verb|Graph| objects, defined in the
Python module \verb|networkx|, having different layouts according to a set of
drawing algorithms.

It presents a help message to explain itself:
\VerbatimInput[fontsize=\small]{OEIS/graphing-help.txt}

\begin{example}
The following command draws the graph shown in Figure
\ref{fig:oeis:sequences:network}, where the width of each vertex grows
according to the number of its \textit{incoming} connections,
\begin{Verbatim}[fontsize=\small]
$ python3.6 graphing.py --layout FRUCHTERMAN-REINGOLD graph.png
\end{Verbatim}
in order to emphasize most referenced sequences.
\end{example}

\begin{figure}
\includegraphics{OEIS/graph1}
\caption{Sequences network where vertices are emphasized according to the
number of incoming connections.}
\label{fig:oeis:sequences:network}
\end{figure}

Moreover, it can extract essential data from the whole set of JSON files, such
as the list of vertices and edges, to interface with third-party software tools
that provide different visualizations; in particular, libraries using the
\textit{Javascript} programming language are very powerful and the output they
produce are very expressive. For our purposes, we use the \verb|arborjs|
library (freely available at \url{http://arborjs.org/}) to display two
additional graphs described in the next two examples, respectively.

\begin{example}
Figure \ref{fig:oeis:sequences:network:fibonacci:catalan} reports a new
unlabeled graph that shows the underlying structure of sequences connections.
Here, the layout spreads vertices such that the ones having many
\textit{outgoing} connections are centered, while those having poor
connectivity are left on borders.

Under the hood, the Fibonacci and Catalan numbers are the two central sequences
and both of them have an orbit which contains a set of highly connected
sequences.
\end{example}

\begin{figure}
%\begin{sideways}
\includegraphics[width=15cm, height=15cm]{OEIS/points}
\caption{Sequences network abstracting over identifier to spot the underlying
structure.}
%\end{sideways}
\label{fig:oeis:sequences:network:fibonacci:catalan}
\end{figure}

\begin{example}
On the other hand, Figure
\ref{fig:oeis:sequences:network:fibonacci:catalan:labeled} adds labels and
colors to vertices in order to spot their identity and their relevance
according to a combination of their properties. In particular, each color is
represented by an RGB tuple that gets weigths (i)~the number of comments and
formulae for \textit{red}, (ii)~the number of references and links for
\textit{green} and (iii)~the number of incoming and outgoing connections for
\textit{blue}, respectively. Moreover, we get the complement to $255$ of each
component because many sequences have not so many details and this manipulation
allows us to obtain cleaner and more expressive graphs.

For the sake of clarity, the two sequences in evidence are the Fibonacci and
Catalan numbers, the former has the color $(006100)_{16}$ and its complement
$(FFFFFF)_{16}-(006100)_{16}=(FF9EFF)_{16}$ means that it has many comments,
formulae and connections; the latter has the color $(7C00E5)_{16}$ and its
complement $(FFFFFF)_{16}-(7C00E5)_{16}=(83FF1A)_{16}$ means that it has lots
of comments, links and references.
\end{example}

\begin{remark}
Recall that the interpretations given in the previous examples concern a
\textit{subset} of the OEIS only, in particular the one fetched in our session;
finally, the more we crawl, the more graphs are effective and accurate.
\end{remark}

\begin{figure}
\centering
\begin{sideways}
%\includegraphics[width=20cm, height=20cm]{OEIS/labels}
\includegraphics[width=20cm, height=35cm]{OEIS/coloured}
\end{sideways}
\caption{Sequences network with labelel vertices, here we see that the sequence
of \textit{Fibonacci numbers} (\url{https://oeis.org/A000045}) and of
\textit{Catalan numbers} (\url{https://oeis.org/A000108}) are the two central
sequences, respectively.}
\label{fig:oeis:sequences:network:fibonacci:catalan:labeled}
\end{figure}

\begin{example}
Finally, crawling for a while to get more sequences, we represent their
connections in Figure
\ref{fig:oeis:sequences:network:fibonacci:catalan:circular}, arranging them
using a circular layout and we emphasize vertices in the \textit{dominating
set} using the \textit{red} color.
\end{example}

\begin{figure}
\hspace{-2cm}
\includegraphics[width=20cm, height=20cm]{OEIS/circular}
\caption{A bigger sequences network composed of $419$ sequences; here the
sequence of \textit{Fibonacci numbers} is denoted by $\alpha$ and the sequence
of \textit{Catalan numbers} is denoted by $\beta$, respectively.}
\label{fig:oeis:sequences:network:fibonacci:catalan:circular}
\end{figure}

\section*{Conclusions}

This paper presents a suite of tools that interacts with the \textit{Online
Encyclopedia of Integer Sequences}, whose primary goal is to automate simple
and repetitive operations such as (i)~crawling sequences to hold a local copy
stored in JSON files, (ii)~pretty printing data with filtering capabilities,
both in the terminal and in Jupyter (\url{http://jupyter.org/}) notebooks and
(iii)~to visualize connections among sequences using graphs.

In parallel, this suite has been devised to be open to extension
and to interface with the hosting environment, UNIX in particular. For
instance, the printer can be used in pipe with the \verb|less| command to gain
scroll and search features for free or the grapher can be augmented to generate
more detailed graph descriptions to be processed by visualization tools.

An additional work direction is to make graphs interactive, namely to tie
together the crawler and the grapher in a web-browser interface such that a
click on a vertex triggers the execution of the fetching process (unless it has
been downloaded already) and the new connections are added to the network
dynamically.

We wish to point out that the suite of tools presented in this work, the
\textit{grapher} in particular, could be used to mine the graph structures
for study regularities and patterns among sequences which looks an interesting
research activity.

\iffalse

\begin{figure}
\includegraphics{OEIS/fibonacci-catalan}
\caption{Sequences network fetched by commands issued in the discussed session.}
\label{fig:oeis:sequences:network}
\end{figure}

\notbreakable{
    \inputminted[fontsize=\small,stripnl=false,firstline=31,lastline=44]
        {python}{../src/graphing.py}
}

\notbreakable{
    \inputminted[fontsize=\small,stripnl=false,firstline=46,lastline=76]
        {python}{../src/graphing.py}
}

\fi