% Document Type: LaTeX

\chapter{The \resquan\ Library}

The \resquan\ library provides some basic facilities for working with
restricted quantifications. It consists of a single theory \verb|res_quan.th|,
which contains a number of theorems about the properties of some
restricted quantifiers, and a set of ML functions for dealing with
these quantifiers. It also contains some conditional
rewriting tools which can be loaded as a separate library part.

The description in this chapter begins with a brief introduction to
the syntax for restricted quantification. This is followed by an
overview of the ML functions available in the library and a
description of the theory \verb|res_quan.th|. A complete reference
manual for all ML functions appears in Chapter~2. The last chapter
lists all theorems in the \verb|res_quan.th|.

\section{Syntax for restricted quantification}

Since Version 2.0, \HOL\ provides parser and pretty printer support
for restricted quantification. This notation allows terms of the form
\[
\con{Q}\,x ::P.\, t[x],
\]
where \con{Q} is a quantifier and
if $x:\alpha$ then $P$ can be any term of type $\alpha\fun\bool$; this
denotes the quantification of $x$ over those values satisfying $P$.
The qualifier {\small\verb|::|} can be used with {\small\verb|\|} and any
binder, including user defined ones. The appropriate meanings are
predefined for {\small\verb|\|} and the built-in binders
{\small\verb|!|}, {\small\verb|?|} and {\small\verb|@|}.
This syntax automatically translates as follows:

\begin{hol}
{\small\verb%   \%}$v${\small\verb%::%}$P${\small\verb%.%}$tm${\small\verb%    <---->   %}\con{RES\_ABSTRACT}\ $P${\small\verb% (\%}$v${\small\verb%.%}$tm${\small\verb%)%}\\
{\small\verb%   !%}$v${\small\verb%::%}$P${\small\verb%.%}$tm${\small\verb%    <---->   %}\con{RES\_FORALL}\ \ \ $P${\small\verb% (\%}$v${\small\verb%.%}$tm${\small\verb%)%}\\
{\small\verb%   ?%}$v${\small\verb%::%}$P${\small\verb%.%}$tm${\small\verb%    <---->   %}\con{RES\_EXISTS}\ \ \ $P${\small\verb% (\%}$v${\small\verb%.%}$tm${\small\verb%)%}\\
{\small\verb%   @%}$v${\small\verb%::%}$P${\small\verb%.%}$tm${\small\verb%    <---->   %}\con{RES\_SELECT}\ \ \ $P${\small\verb% (\%}$v${\small\verb%.%}$tm${\small\verb%)%}
\end{hol}

The constants \con{RES\_ABSTRACT}, \con{RES\_FORALL}, \con{RES\_EXISTS} and
\con{RES\_SELECT} are defined in the theory \ml{bool} to provide
semantics for these restricted quantifiers as follows:

\begin{hol}\begin{verbatim}
   RES_ABSTRACT P tm  =  \x:*. (P x => tm x | ARB:**)

   RES_FORALL   P tm  =  !x:*. P x ==> tm x

   RES_EXISTS   P tm  =  ?x:*. P x /\ tm x

   RES_SELECT   P tm  =  @x:*. P x /\ tm x
\end{verbatim}\end{hol}

\noindent where the constant \con{ARB} is defined in the theory \ml{bool} by:

\begin{hol}\begin{verbatim}
   ARB  =  @x:*. T
\end{verbatim}\end{hol}

User-defined binders can also have restricted forms, which are set up
with the function:

\begin{holboxed}\index{associate_restriction@\ml{associate\_restriction}}
\begin{verbatim}
   associate_restriction : (string # string) -> *
\end{verbatim}\end{holboxed}

\noindent If \m{B} is the name
of a binder and \ml{RES\_}$B$ is the name of a suitable constant (which
must be explicitly defined), then executing:

\begin{hol}
{\small\verb%   associate_restriction(`%}\m{B}{\small\verb%`, `RES_%}\m{B}{\small\verb%`)%}
\end{hol}

\noindent will cause the parser and pretty-printer to support:

\begin{hol}
{\small\verb%   %}$B$ $v${\small\verb%::%}$P${\small\verb%. %}$tm${\small\verb%    <---->   RES_%}$B$ $P${\small\verb% (\%}$v${\small\verb%. %}$tm${\small\verb%)%}
\end{hol}

\noindent Note that associations between user defined binders and their
restrictions are not stored in theory files, so they have to be set up
for each \HOL\ session (e.g. with a {\small\verb%hol-init.ml%} initialization file).

The flag \ml{print\_restrict} has default \ml{true}, but if set to
\ml{false} will
disable the pretty printing. This is useful for seeing what the
semantics of particular restricted abstractions are.
Here is an example session:

\setcounter{sessioncount}{1}
\begin{session}\begin{verbatim}
#"!x y::P. x<y";;
"!x y :: P. x < y" : term

#set_flag(`print_restrict`, false);;
true : bool

#"!x y::P. x<y";;
"RES_FORALL P(\x. RES_FORALL P(\y. x < y))" : term

#"?(x,y) p::(\(m,n).m<n). p=(x,y)";;
"RES_EXISTS
 (\(m,n). m < n)
 (\(x,y). RES_EXISTS(\(m,n). m < n)(\p. p = x,y))"
: term

#"\x y z::P.[0;x;y;z]";;
"RES_ABSTRACT P(\x. RES_ABSTRACT P(\y. RES_ABSTRACT P(\z. [0;x;y;z])))"
: term
\end{verbatim}\end{session}

The syntax for restricted quantification provides a method of
simulating subtypes and dependent types; the qualifying predicate $P$ can be
an arbitrary term containing parameters. For example:
{\small\verb|!|}$w${\small\verb|::|}$\con{Word}(n)${\small\verb|. |}$t[w]$,
for a suitable constant \con{Word}, simulates a quantification over the
`type' of $n$-bit words.\footnote{This approach is used in the library
{\tt word} to model bit vectors.}

\section{The theory {\tt res\_quan.{}th}}

This theory contains a small number of theorems about the restricted
universal quantifier and restricted existential quantifier.
The following four theorems state the distributivity property of these
quantifiers across conjunction and disjunction.
\begin{verbatim}
 RESQ_FORALL_CONJ_DIST
  |- !P Q R.
     (!(i:*) :: P. (Q i /\ R i)) = (!i :: P. Q i) /\ (!i :: P. R i)

 RESQ_FORALL_DISJ_DIST
  |- !P Q R.
     (!(i:*) :: \i. P i \/ Q i. R i) = (!i :: P. R i) /\ (!i :: Q. R i)

 RESQ_EXISTS_DISJ_DIST
  |- !P Q R.
     (?(i:*) :: P. (Q i \/ R i)) = (?i :: P. Q i) \/ (?i :: P. R i)

 RESQ_DISJ_EXISTS_DIST
  |- !P Q R.
     (?(i:*) :: \i. P i \/ Q i. R i) = (?i :: P. R i) \/ (?i :: Q. R i)
\end{verbatim}

The theorems \ml{RESQ\_FORALL\_REORDER} and \ml{RESQ\_EXISTS\_REORDER}
state the reordering property of these quantifiers.
\begin{verbatim}
 RESQ_FORALL_REORDER
  |- !(P:*->bool) (Q:**->bool) (R:*->**->bool).
      (!i :: P. !j :: Q. R i j) = (!j :: Q. !i :: P. R i j)

 RESQ_EXISTS_REORDER
  |- !(P:*->bool) (Q:**->bool) (R:*->**->bool).
      (?i :: P. ?j :: Q. R i j) = (?j :: Q. ?i :: P. R i j)
\end{verbatim}
The theorem \ml{RESQ\_FORALL\_FORALL} states the reordering property of
the restricted universal quantifier and the ordinary universal
quantifier.
\begin{verbatim}
 RESQ_FORALL_FORALL
  |- !(P:*->bool) (R:*->**->bool) x.
      (!x. !i :: P. R i x) = (!i :: P. !x. R i x)
\end{verbatim}

\section{ML functions}

The ML functions available when this library is loaded can be divided
into six groups: conditional rewriting tools, syntax functions,
derived rules, conversions, tactics, and constant definitions. They
will be described in separate subsections.

\subsection{Conditional rewriting tools}

The conditional rewriting tools are not specific for restricted
quantifiers. They are available as a separate part of the library
which can be loaded into \HOL\ without loading other functions in this
library. This is done by the command
\begin{verbatim}
 load_library `res_quan:cond_rewrite`;;
\end{verbatim}

The conditional rewriting tools consists of a simple tactic which is
for use in goal-directed proof and a simple conversion which is
usually used in forward proof.

\subsubsection{Conditional theorems}

Both the conditional rewriting tactic and conversion require a theorem
to do the rewriting. This theorem should be an implication whose
consequence is an equation, i.e., it should be of the following form:
\begin{equation}
   A \vdash \forall\,x_1 \ldots x_n\DOT P_1 \IMP \ldots P_m \IMP
 (Q[x_1,\ldots,x_n] = R[x_1,\ldots,x_n]) \label{eq-cond-thm}
\end{equation}
where $x_1, \ldots, x_n$ are the only variables that occur free in the
left-hand side of the conclusion of the theorem but do not occur free
in the assumptions. Futhermore, none of the antecedents
$P_1,\ldots,P_n$ should be
conjunctions. The idea of  conditional rewriting is that the
antecedents of this input theorem are treated as conditions which have
to be satisfied before the equation $Q[x_1,\ldots,x_n] = R[x_1,\ldots,x_n]$
can be used to rewrite a term.

The ML function \ml{COND\_REWR\_CANON} transforms a theorem
into the canonical form in~\ref{eq-cond-thm}. The antecedents of the
input theorem to \ml{COND\_REWR\_CANON} may contain conjunctions and
quantification. For example, suppose that {\tt th} is the theorem
\begin{equation}
   A \vdash \forall\,x\DOT P_1\,x \IMP  \forall y\,z.(P_2\,y \AND P_3\,z) \IMP
 (\forall t. Q[x,y,z,t] = R[x,y,z,t]) \label{eq-cond-thm2}
\end{equation}
then \verb|COND_REWR_CANON th| returns the theorem
\[
   A \vdash \forall\,x\,y\,z\,t\DOT P_1\,x \IMP P_2\,y \IMP P_3\,z \IMP
 (Q[x,y,z,t] = R[x,y,z,t])
\]
That is all universal quantifications are moved to the outer most level
and conjunctions in the antecedents are converted to implication.

\subsubsection{Conditional rewriting tactic}

The basic conditional rewriting tactic is
\begin{holboxed}
\begin{verbatim}
   COND_REWRITE1_TAC : thm_tactic
\end{verbatim}
\end{holboxed}
Suppose {\tt th} is the theorem in~\ref{eq-cond-thm2},
the effects of applying the tactic $\ml{COND\_REWRITE1\_TAC}\;th$ to the
goal $(asm,gl)$ is that
\begin{itemize}
\item  all instances of $Q$ in the goal $gl$ are
	replaced by corresponding instances of $R$, and
\item the instances of the antecedents $P_i$ which do not appear in
	the assumption $asm$ become new subgoals.
\end{itemize}

This tactic is implemented using a lower level tactic \ml{COND\_REWR\_TAC}.
The theorem $th$ supplied to \ml{COND\_REWRITE1\_TAC} is processed by
\ml{COND\_REWR\_CANON} first. The resulting theorem is passed to the low
level conditional rewriting tactic \ml{COND\_REWR\_TAC} together with a
search function \ml{search\_top\_down}. This function determines how to
find the instantiations. By calling \ml{COND\_REWR\_TAC} with different
search function, other conditional rewriting strategy can be
implemented. The details of the tactics and search functions can be
found in the reference entries in Chapter~2.
Note that the {\tt 1} in the name of the tactic indicates that it
takes only a single theorem as its argument.

\subsubsection{Conditional rewriting conversion}

The basic conditional rewriting conversion is
\begin{holboxed}
\begin{verbatim}
   COND_REWRITE1_CONV : (thm list -> thm -> conv)
\end{verbatim}
\end{holboxed}
which performs conversion in a way similar to the conditional
rewriting tactics. The difference is that the instances of the
antecedents are added to the list of assumptions of the resulting theorem. The
extra argument to this conversion is a list of theorems which are
used to eliminate instances of the antecedents from the assumptions.

\subsection{Syntax functions}

There are term constructors, term destructors and term testers for the
four built-in restricted quantifiers. There are also iterative
constructors and destructors for the restricted universal and
existential quantifiers. Their names and types are:
\begin{holboxed}
\begin{verbatim}
mk_resq_forall = - : ((term # term # term) -> term)
mk_resq_exists = - : ((term # term # term) -> term)
mk_resq_select = - : ((term # term # term) -> term)
mk_resq_abstract = - : ((term # term # term) -> term)
list_mk_resq_forall = - : (((term # term) list # term) -> term)
list_mk_resq_exists = - : (((term # term) list # term) -> term)

dest_resq_forall = - : (term -> (term # term # term))
dest_resq_exists = - : (term -> (term # term # term))
dest_resq_select = - : (term -> (term # term # term))
dest_resq_abstract = - : (term -> (term # term # term))
strip_resq_forall = - : (term -> ((term # term) list # term))
strip_resq_exists = - : (term -> ((term # term) list # term))

is_resq_forall = - : (term -> bool)
is_resq_exists = - : (term -> bool)
is_resq_select = - : (term -> bool)
is_resq_abstract = - : (term -> bool)
\end{verbatim}
\end{holboxed}

\subsection{Derived rules}

The introduction and elimination rules for the restricted universal
quantifier are \ml{RESQ\_SPEC} and \ml{RESQ\_GEN} which are in analogy
to the rules for the universal quantifier. The specification of these
rules are:
\[
\frac{\Gamma \THM \forall x :: P. t[x]}{\Gamma,P\,x'\THM t[x'/x]}
\quad\mbox{{\tt RESQ\_SPEC "x'"}}
\]
\[
\frac{\Gamma,P\,x\THM t[x]}{\Gamma \THM \forall x :: P. t[x]}
\quad\mbox{{\tt RESQ\_GEN "x" "P"}}
\]
There is an extra rule \ml{RESQ\_HALF\_SPEC} which transform a
restricted universal quantification into its underlying semantic
representation, namely an implication.
\[
\frac{\Gamma \THM \forall x :: P. t[x]}{\Gamma \THM\forall x. P\,x\IMP t[x]}
\quad\mbox{{\tt RESQ\_HALF\_SPEC}}
\]

There are iterative versions of the introduction and elimination rules:
\begin{holboxed}
\begin{verbatim}
RESQ_SPECL = - : (term list -> thm -> thm)
RESQ_SPEC_ALL = - : (thm -> thm)

RESQ_GENL = - : (term list -> thm -> thm)
RESQ_GEN_ALL = - : (thm -> thm)
\end{verbatim}
\end{holboxed}

Since instantiation of a theorem is a very common operation, for
convenience, the following ML functions are provided to instantiate a
theorem with a mixture of ordinary and restricted universal quantifiers:
\begin{holboxed}
\begin{verbatim}
GQSPEC = - : tm -> thm -> thm
GQSPECL : term list -> thm -> thm
GQSPEC_ALL : thm -> thm
\end{verbatim}
\end{holboxed}

The rule for eliminating restricted existential quantification is
\ml{RESQ\_HALF\_EXISTS} whose specification is:
\[
\frac{\Gamma \THM \exists x:: P. t[x]}{\Gamma \THM \exists x. P\,x
\AND t[x]}\quad\mbox{{\tt RESQ\_HALF\_EXISTS}}
\]
This function only transforms the restricted existential quantifier to
an ordinary existential quantifier.

The function \ml{RESQ\_MATCH\_MP} eliminates a restricted universal
quantifier using an instance of the condition. Its specification is:
\[
\frac{\Gamma_1 \THM \forall x::P. t[x]\qquad\Gamma_2\THM P\,x'}
{\Gamma_1 \cup \Gamma_2 \THM t[x'/x]}\quad\mbox{{\tt RESQ\_MATCH\_MP}}
\]

\subsection{Conversions}

There are a number of conversions for manipulating restricted
universal quantification. The conversion \ml{RESQ\_FORALL\_CONV}
converts a restricted universal quantification to its underlying
semantic representation, namely an implication. For example,
evaluating the ML expression
\verb|RESQ_FORALL_CONV "!x :: P. t[x]"| returns the following theorem:
\[
\THM \forall x :: P. t[x] = \forall x. P x \IMP t[x]
\]
The ML function
\ml{IMP\_RESQ\_FORALL\_CONV} performs the reverse conversion. The ML
function \ml{LIST\_RESQ\_FORALL\_CONV} is an iterative version of
\ml{RESQ\_FORALL\_CONV} which converts a term having multiple
restricted universal quantifiers at the outer level.

The conversions \ml{RESQ\_FORALL\_AND\_CONV} and
\ml{AND\_RESQ\_FORALL\_CONV} move the restricted universal
quantification in and out of a conjunction, respectively.
The conversion \linebreak\ml{RESQ\_FORALL\_SWAP\_CONV} changes the order of two
restricted universal quantifications. For instance, evaluating the
following ML expression
\begin{verbatim}
   RESQ_FORALL_SWAP_CONV "!i :: P. !j :: Q. R"
\end{verbatim}
returns the theorem:
\[
\THM (\forall i :: P. \forall j :: Q. R) = (\forall j :: Q. \forall i :: P. R)
\]
providing that $i$ does not occur free in $Q$ and $j$ does not occur
free in $P$.

The conversion \ml{RESQ\_EXISTS\_CONV} transforms a restricted
existential quantification to its underlying semantic representation.
For instance, \verb|RESQ_EXISTS_CONV "?x::P. t"| returns the theorem
\[
\THM \exists x::P. t = \exists x. P x \AND t[x]
\]

A rewriting conversion \ml{RESQ\_REWRITE1\_CONV} uses a restricted
universal quantified equation to rewrite a term. For instance, if {\tt
th} is a theorem of the following form:
\[
\THM \forall x::P. u[x] = v[x]
\]
and {\tt tm} is a term containing some instances of $u$,
then \verb|RESQ_REWRITE1_CONV ths th tm| will return the theorem
\[
\Gamma \THM tm = tm'
\]
where $tm'$ is obtained by replacing all instances of $u$ by
corresponding instances of $v$ and $\Gamma$ contains instances of $P$
which cannot be eliminated by the theorems in the list {\tt ths}. This
conversion is implemented using the conditional rewriting conversion
\ml{COND\_REWRITE1\_CONV}.

\subsection{Tactics}

The simple tactics \ml{RESQ\_GEN\_TAC} and \ml{RESQ\_EXISTS\_TAC} are
provided for stripping of a restricted universal or existential
quantifier, respectively. They reduce a restricted quantified goal to
a goal in the underlying semantic representation. They are in analogy
to \ml{GEN\_TAC} and \ml{EXISTS\_TAC}.

The resolution tactics and tactical listed below are in analogy to
\ml{RES\_TAC}, \ml{IMP\_RES\_TAC}, \ml{RES\_THEN} and
\ml{IMP\_RES\_THEN}.
\begin{holboxed}
\begin{verbatim}
RESQ_RES_THEN : (thm_tactic -> tactic)
RESQ_IMP_RES_THEN : thm_tactical
RESQ_RES_TAC : tactic
RESQ_IMP_RES_TAC : thm_tactic
\end{verbatim}
\end{holboxed}
The theorem-tactic \ml{RESQ\_IMP\_RES\_TAC} uses a restricted universally
quantified theorem as if it is an implication to perform resolution.
Similarly, the tactic \ml{RESQ\_RES\_TAC} uses a restricted universally
quantified assumption as if it is an implication to
perform resolution against other assumptions.

The theorem-tactic \ml{RESQ\_REWRITE1\_TAC} uses a restricted universally
quantified theorem to perform conditional rewriting.
For instance, if {\tt th} is the following theorem
\[
\THM \forall x::P. u[x] = v[x]
\]
then applying the tactic \verb|RESQ_REWRITE1_TAC th| to a goal {\tt
gl} will reduce it to one or more subgoals {\tt gl0}, \ldots, {\tt
gln}. The main subgoal {\tt gl0} is obtained by replacing instances of
$u$ in {\tt gl} with corresponding instances of $v$. The new subgoals
are the instances of $P$ which do not occur in the assumption of $gl$.

\subsection{Constant definitions}

This library provides support for defining constants whose arguments
can be restricted quantified variables. For example, one can defined a constant
\con{C} by the following equation:
\begin{eqnarray*}
\lefteqn{\forall x_1::P_1. \ldots \forall x_n::P_n.} \\
 & &  \mbox{{\sf C}}\, y\, x_1 \ldots x_n\, z = t[y,x_1,\ldots,x_n,z]
\end{eqnarray*}
The constant \con{C} may be an ordinary constant, or it may have
either `infix' or `binder' status. The ML functions for defining
restricted quantified constants are:
\begin{holboxed}
\begin{verbatim}
new_resq_definition        : (string # term) -> thm
new_infix_resq_definition  : (string # term) -> thm
new_binder_resq_definition : (string # term) -> thm
\end{verbatim}
\end{holboxed}
Suppose {\tt tm} is the term shown above, evaluating the ML expression
\begin{verbatim}
   new_resq_definition(`C_DEF`,tm)
\end{verbatim}
will store the definition under
the name \verb|C_DEF| in the current theory. The definition is
returned as the value of the expression.


\section{Generalised Method of Moments (GMM)}


\section*{Typing}

Expressions evaluate to numbers, boolean values, strings or function values.

Only function values can be applied using the syntax:

\begin{eqnarray*}
 \textit{expression}
                                   & ::=   &  \textit{name}
                                               \texttt{\textbf{(}}\  \textit{expressions} \
                                               \texttt{\textbf{)}}\\
\end{eqnarray*}

The following table specifies what arguments Source's operators
take and what results they return.

\begin{center}
\begin{tabular}{c|c|c|c}
operator & argument 1 & argument 2 & result\\ \hline
\texttt{\textbf{+}} & number   & number     & number\\
\texttt{\textbf{+}} & string   & string     & string\\
\texttt{\textbf{-}} & number   & number     & number\\
\texttt{\textbf{*}} & number   & number     & number\\
\texttt{\textbf{/}} & number   & number     & number\\
\texttt{\textbf{\%}} & number   & number     & number\\
\texttt{\textbf{===}} & any   & any     & bool\\
\texttt{\textbf{!==}} & any   & any     & bool\\
\texttt{\textbf{>}} & number   & number     & bool\\
\texttt{\textbf{>}} & string   & string     & bool\\
\texttt{\textbf{<}} & number   & number     & bool\\
\texttt{\textbf{<}} & string   & string     & bool\\
\texttt{\textbf{>=}} & number   & number     & bool\\
\texttt{\textbf{>=}} & string   & string     & bool\\
\texttt{\textbf{<=}}    & number   & number     & bool\\
\texttt{\textbf{<=}} & string   & string     & bool\\
\texttt{\textbf{\&\&}} & bool & any & any\\
\texttt{\textbf{||}}   & bool & any & any\\
\texttt{\textbf{!}}    & bool &      & bool\\
\texttt{\textbf{-}}    & number &    & number
\end{tabular}
\end{center}

Preceding \texttt{\textbf{?}} and following \texttt{\textbf{if}}, Source only allows
boolean expressions.


\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{url}
\usepackage[margin=0.75in]{geometry}

\setlength{\parskip}{0.7em}
\setlength{\parindent}{0em}

\begin{document}
	\begin{center}

		% MAKE SURE YOU TAKE OUT THE SQUARE BRACKETS
		\LARGE{\textbf{CSE 6730, Group Proposal}} \\
		\vspace{1em}
		\Large{Project 2: Complex Simulation} \\

	\end{center}
	\begin{normalsize}

		\section{Project Title}

		Simulation of Predator-Prey Population Dynamics

		\section{Team Members}

		\begin{enumerate}
			\item D. Aaron Hillegass (GTID 901988533)
			\item Siawpeng Er (GTID 903413430)
			\item Xiaotong Mu (GTID 903529807)
		\end{enumerate}

		\section{Problem Description and Purpose}
		The predator and prey relationship is an important ecological system. Their populations rise and fall over time as they interact and impact one another. These interactions are the prime movers of energy through food chains. Both prey and predators are affecting each other. In simplest interaction, predators depend on the prey as the food source. However, any abuse of the food source may result in decease in population of the prey, and subsequently decrease the number of the predators due to lack of food. Because of such interaction, the population of the predators and the prey may oscillate, and inversely proportional to each others.  \\

		Predator prey releationship is important for us to understand the impact of the relationship on the ecological system in one area. Such relationship is always complicated. Without predators, prey (normally herbivors) will cause detrimental impact on the plants in that area. However, overkill by the predators may also impact the balance of the nature. Besides, there are effects from human intervention on such relationship (eg: hunting and destroy of the habitat). Furthermore, predator-prey model can be used to describe many fundamental characteristics of ecological systems and can even be extended to other ideas like military response \cite{derrik}.\\

		One of the mathematical models that simulates predator and prey interactions is the Lotka-Volterra model proposed by Alfred Lotka and Vito Volterra. Lotka helped develop the logistic equation to explain autocatalytic chemical reactions. Volterra interconnected the logistic equation to two separate populations in competition to explain predator and prey relationships. We hope to use this intuitive model in our complex system simulation,  so that we could gain more understanding on the relationship, as well as the impact of our activities on such relationship.

		\section{Data Source}
		For this project, we plan to obtain some data from the National Park. However, it is also possible from literature review we could obtained some of the data source used by the their simulation and use it as our data source.

		\section{Methodology}
		Our simulation will first simulate predators and prey entering and exiting a predefined area. Then through interactions, their population may affecting each others.

		Traditionally, there is the nonlinear Lotka-Volterra Model of the predator-prey dynamic system \cite{inproceedings, 1102729}. LVM approach is a simplified model and suitable for detailed stability analysis. However, it is also very limited model and lack of flexibility for complex interaction. Hence, we also hope to incorporate the Agent-Based Model \cite{Hodzic} in this project to increase the completeness of our analysis.

		In our project, some of the ideas that we wish to investigate include:
		\begin{enumerate}
			\item Long-term population interaction among predators and prey.
			\item Introduction of the uncertainties like diseases.
			\item Introduction of the third parties interaction: human activity, natural disasters etc.
		\end{enumerate}

		\section{Development Platform}
		The programming language is Python 3. We will provide a Jupyter notebook for user interaction.
		In the Jupyter notebook, we will allow the user to change some of the probability and the simulation parameters to see different result of the simulation.

		\section{Division of Labor}
		As we move forward on our project, we plan to work concurrently. The timeline is as below:

		\begin{center}
			\begin{tabular}{ |c|c|c| }
				\hline
				Task & Duration  \\
				\hline
				Data collection & 2 weeks \\
				Modeling design and implementaion & 4 weeks \\
				Modeling revised & 4 weeks \\
				\hline
			\end{tabular}
		\end{center}

		\bibliographystyle{plain}
		\bibliography{reference}
	\end{normalsize}

\end{document}


\section{Deep Learning}
\label{sec:deep_learning}

\subsection{Why Machine Learning}

Machine learning methods try to model either the joint or the marginal distribution of some covariates and some target. In statistics a model is usually explicitly formulated. A typical example could be linear regression. The covariates is decided on, and transformed such that they fit the desired model. The linear regression will yield a parameter vector which can then be interpreted. This interpretation is usually the focus; parameter inference. Example: Does an increase in the minimum salary have a negative effect on BNP per capita. Machine Learning focuses on prediction. That is, the objective is to predict some target conditional on some covariates. The specific model is not necessarily important, instead the focus is on Out-Of-Sample error. These predictive methods lend themselves well where causal inference is not needed. Example: What is the expected consumption on a monthly basis by person with a given set of characteristics. When formulating a traditional econometric method, e.g., OLS, there are standard ways to infer if the model is well specified. In general machine learning does not have the same asymptotic results regarding regularization of a model. Usually sample splitting will be used instead. Take a data set, split the data into two partitions a test set and a training set. First the hyper parameters of the machine learning algorithm is tuned, usually by finding which set of hyper parameters that yield the best performance on the training data. Cross validation is the go-to procedure to optimize the hyper parameters. The final algorithm is only used on the test data set once yielding the out-of-sample performance. Machine learning methods, as mentioned before usually has associated hyper parameters. These are parameters of the model, which is not fitted by training on the data, rather these are specifications of the algorithm before training the model. Much of machine learning is about finding the right hyper parameters and regularizing the model in an intelligent way \parencite{friedman_elements_2001}. Now why is this paper concerned with ML methods? This is due to the fact, that when estimating the value function, or the policy function, one cannot be sure that this follows a linear function. In fact value functions and policy functions might be highly non-linear, which is where machine learning methods shine. Considering that the value function is a conditional expectation: $ \E[Y \mid X=x]$, where $Y$ is the expected cumulative discounted rewards and $X$ is the state implies, that machine learning methods is the appropriate choice for value function approximation. Also, in this case, causal interpretation of the influence of a specific state on the value function is not of interest, rather it's the accuracy of the expected value function\footnote{Obviously, intelligent agents usually do causal inference on their actions. They might not do a certain action exactly because they have some causal notion of how the environment will evolve conditional on their action.}. Deep neural networks has been the standard way to implement reinforcement algorithms, however other machine learning methods can also be used. The reason for deep Learning methods being the standard implementation is the convenient property of online updating of the networks weights. In other words, as more data comes in, the neural network can be incrementally fitted to the new data.

\subsection{Deep Neural Networks}

Deep learning (feed forward networks), which is used in this paper, is in fact just layered non-linear functions. Figure \ref{fig:feedforwardnetwork} illustrates the architecture of a deep neural network\footnote{Figure found at \url{https://upload.wikimedia.org/wikipedia/commons/thumb/c/c2/MultiLayerNeuralNetworkBigger_english.png/381px-MultiLayerNeuralNetworkBigger_english.png}}.

\begin{figure}[ht]
    \centering
    \includegraphics[scale=0.6]{figures/feedforwardnetworkillustration.png}
    \caption{Illustration of Feed Forward Neural Network}
    \label{fig:feedforwardnetwork}
\end{figure}

The network can be described as having an \textit{input layer}, that takes the covariates, $\textbf{x}$. The \textit{hidden layer} makes a transformation of the previous layer. This also implies that a hidden layer, can be followed by an arbitrary number of other hidden layers. Lastly an \textit{output layer} maps the representation of the last hidden layer into the desired output. For classification that could be a one-hot encoding of the classes, and for regression a single real valued scalar.

As illustrated in figure \ref{fig:feedforwardnetwork}, each layer is broken down into smaller cells. The number of cells in each layer corresponds to the width of the layer. The wider the layer the more flexible representation the given layer is capable of doing. The hidden cells work as mentioned by creating a non-linear transformation of the input from last layer:

\begin{equation}
    z_i^{+} = g(\textbf{z}; \theta) = g(\textbf{w}^T \cdot \textbf{z} + b)
\end{equation}

The output of cell \textit{i} is the real valued scalar $z_i^+$. $g$ is the activation function that maps the input into the output. $\textbf{w}$ is the weights of dot product, $\textbf{z}$ is a vector of the outputs from the last layer, and $b$ is bias or the constant in the activation. In that sense the activation looks like a linear regression squashed through an activation function $g$. Multiple different activation functions has been proposed. Originally the logistic function was preferred, but in later years the rectified linear unit activation function has been popular \parencite{goodfellow_deep_2016}:

\begin{equation}
    \textbf{Rectified Linear Unit: }  \max \lcp 0, \textbf{w}^T \cdot \textbf{z} + b \rcp
\end{equation}

The neural network can in other words be considered a function $f$, that takes an input $\textbf{x}$ and maps it to some output $y$, parameterized by $\theta$, which is a collection of all the weights and biases associated with each individual cell.

\subsection{Stochastic Gradient Descent and Optimization}

The neural network is estimated (or trained) by using stochastic gradient descent. This is possible due to the fact, that a neural network can be represented as a set of nested functions, such that the chain rule can be applied. The loss function can in other words be differentiated with respect to the parameter vector $\theta$ as shown below:

\begin{equation}\label{eq:loss_function}
    \frac{\partial}{\partial\theta} \Loss (\textbf{X}, \textbf{Y}, \theta) = \frac{\partial}{\partial\theta} \lp \sum \ell_i \rp = \frac{\partial}{\partial\theta} \lp \sum \lp \hat{Y}_i  - Y_i \rp^2 \rp = \frac{\partial}{\partial\theta} \lp \sum \lp f^{\theta}(X_i)  - Y_i \rp^2 \rp
\end{equation}

In equation \eqref{eq:loss_function} the loss function $\Loss$ is assumed be a mean squared error loss function, in other words a regression problem. The optimization works by minimizing the loss with respect to the parameters $\theta$. In modern neural network architectures it is not unusual to see neural networks have in the excess of a million parameters. The objective function of the optimization cannot be assumed to be convex due to the non-linearity of the activation functions. For this reason deep neural networks is not solved analytically. Instead, gradient descent is used for estimating the parameters of the network. The update rule of the parameters can be described as \parencite{goodfellow_deep_2016}:

\begin{equation}
    \theta \la \theta - \alpha \nabla_{\theta} \Loss(\textbf{X}, \textbf{Y}, \theta)
\end{equation}

So for each step in the algorithm the derivative of the loss function with respect to the parameters can be calculated, and the parameters can be updated by taking a small step in parameter space of size $\alpha$ in the direction that reduces the loss. Stochastic gradient is a response to the fact that it can be computationally expensive to calculate the gradient for the entire data set in each update step. This is important for deep neural networks, since the training period of a large network, even on optimized hardware, can take a very long time, so any speed up for the training is important. In practice this implies that the training data is split into mini batches usually of size 32 to 128. The optimization is then performed on each of the small batches, taking a small step of size $\alpha$ for each step.


\subsubsection{\lst{GroupElement.getEncoded} method (Code 7.2)}
\label{sec:type:GroupElement:getEncoded}
\noindent
\begin{tabularx}{\textwidth}{| l | X |}
   \hline
   \bf{Description} & Get an encoding of the point value. \\

  \hline
  \bf{Parameters} &
      \(\begin{array}{l l l}

      \end{array}\) \\

  \hline
  \bf{Result} & \lst{Coll[Byte]} \\
  \hline

  \bf{Serialized as} & \hyperref[sec:serialization:operation:PropertyCall]{\lst{PropertyCall}} \\
  \hline

\end{tabularx}

\subsubsection{\lst{GroupElement.exp} method (Code 7.3)}
\label{sec:type:GroupElement:exp}
\noindent
\begin{tabularx}{\textwidth}{| l | X |}
   \hline
   \bf{Description} & Exponentiate this \lst{GroupElement} to the given number. Returns this to the power of k \\

  \hline
  \bf{Parameters} &
      \(\begin{array}{l l l}
         \lst{k} & \lst{: BigInt} & \text{// The power} \\
      \end{array}\) \\

  \hline
  \bf{Result} & \lst{GroupElement} \\
  \hline

  \bf{Serialized as} & \hyperref[sec:serialization:operation:Exponentiate]{\lst{Exponentiate}} \\
  \hline

\end{tabularx}

\subsubsection{\lst{GroupElement.multiply} method (Code 7.4)}
\label{sec:type:GroupElement:multiply}
\noindent
\begin{tabularx}{\textwidth}{| l | X |}
   \hline
   \bf{Description} & Group operation. \\

  \hline
  \bf{Parameters} &
      \(\begin{array}{l l l}
         \lst{other} & \lst{: GroupElement} & \text{// other element of the group} \\
      \end{array}\) \\

  \hline
  \bf{Result} & \lst{GroupElement} \\
  \hline

  \bf{Serialized as} & \hyperref[sec:serialization:operation:MultiplyGroup]{\lst{MultiplyGroup}} \\
  \hline

\end{tabularx}

\subsubsection{\lst{GroupElement.negate} method (Code 7.5)}
\label{sec:type:GroupElement:negate}
\noindent
\begin{tabularx}{\textwidth}{| l | X |}
   \hline
   \bf{Description} & Inverse element of the group. \\

  \hline
  \bf{Parameters} &
      \(\begin{array}{l l l}

      \end{array}\) \\

  \hline
  \bf{Result} & \lst{GroupElement} \\
  \hline

  \bf{Serialized as} & \hyperref[sec:serialization:operation:PropertyCall]{\lst{PropertyCall}} \\
  \hline

\end{tabularx}


\documentclass[10pt]{beamer}

\usetheme[progressbar=frametitle]{metropolis}
\usepackage{mathtools}
\usepackage{booktabs}
\usepackage{setspace}
\usepackage{listings}

%\usepackage{pgfplots}
%\usepgfplotslibrary{dateplot}

\usepackage{xspace}
\newcommand{\order}[1]{\mathcal{O}(#1)}

%color definitions
\definecolor{ourgreen}{rgb}{0,0.6,0}
\definecolor{ourgray}{rgb}{0.5,0.5,0.5}
\definecolor{ourmauve}{rgb}{0.58,0,0.82}

%code style
\lstset{
firstnumber=1,
language=python, % choose the language of the code
numbers=left,
stepnumber=1,% the step between two line-numbers. If it is 1 each line will be numbered
numbersep=5pt, % how far the line-numbers are from the code
frame=single,% adds a frame around the code
commentstyle=\color{ourgreen},    % comment style
keywordstyle=\color{blue},       % keyword style
stringstyle=\color{ourmauve},     % string literal style
breaklines=true, % sets automatic line breaking
basicstyle=\tiny,
}

\title{Generating Trapdoor Primes}
\subtitle{A short take on generating SNFS primes}
% \date{\today}
\date{}
\author{Nikolai Rozanov}
\institute{UCL - Computer Science}
% \titlegraphic{\hfill\includegraphics[height=1.5cm]{logo.pdf}}

\begin{document}

\maketitle

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TOC and Introduction
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{frame}{Table of contents - Introduction}
  \setbeamertemplate{section in toc}[sections numbered]
  \tableofcontents[hideallsubsections]
\end{frame}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Importance
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Importance}
\begin{frame}[fragile]{Importance}

\begin{itemize}
\item Look Up
\item Benchmarking
\item Deliberate Weakening
\end{itemize}

\end{frame}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Method and Code
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Method and Code}

\begin{frame}[fragile]{Algorithm}
\begin{enumerate}[\textbf{Step} 1.]
\item Generating the prime q of the corresponding size.
\item Generating the coefficients for polynomials f and g, according to the size suggestions in \cite{Paper}
\item Setting up a new polynomial G, which is the resultant of f and g and the variable is the leading coefficient of g.
\item Finding roots of G-1 modulo q, if there are no roots then going back to Step 1.
\item Then letting p=$|G|$, and checking if p is prime, (an addition is to check whether q divides p-1).
\end{enumerate}
\end{frame}
\begin{frame}[fragile]{Main Script}
\textbf{Main Script}
\begin{lstlisting}
# Generating required Rings
X.<x>     = ZZ['x']
G.<x,g1>  = ZZ['x,g1']
# Main Loop
    #generating prime and Associated Field
    q = get_prime(bits_q)
    T.<g2>    = Integers(q)['g2']
	##while loop
        f_poly,norm_f = get_f(X,degree_f,bits_q)
        g_poly,g0 = get_g(g1,x,bits_p,degree_f, norm_f)
        G_poly = get_G(f_poly,g_poly)
        temp = list(G_poly.coefficients())
        temp.reverse()
        T2 = T(temp)
    r    = T2.roots()
    root = r[0][0]
    rt   = int(root)
#    while(rt<int(2^(bits_p/degree_f)/norm_f)):
#        rt+=q
    p    = X([G_poly(1,rt)+1])
\end{lstlisting}
\end{frame}

\begin{frame}[fragile]{Helper Functions}
\begin{alertblock}{Helper Functions}\end{alertblock}
\textbf{Prime Generation}
\begin{lstlisting}
def get_prime(bits_q):
    q = random_prime(2^bits_q-1,False,2^(bits_q-1))
    while(not is_prime(q)):
        q = random_prime(2^bits_q-1,False,2^(bits_q-1))
    return q
 \end{lstlisting}
 \textbf{Poly f}
 \begin{lstlisting}
def get_f(X,degree_f, bits_q):
    flag_irreducible = False
    while (not flag_irreducible):
        #f_vec = [ZZ.random_element(-int(2^(10)-1),int(2^(10)-1)) for _ in range(degree_f+1)]
        f_vec = [ZZ.random_element(-int(2^(bits_q/(2*(degree_f+1)))),int(2^(bits_q/(2*(degree_f+1))))) for _ in range(degree_f+1)]
        #f_vec = [ZZ.random_element(1,int(2^(bits_q/(2*(degree_f+1))))) for _ in range(degree_f+1)]

        norm_f = max(map(abs,f_vec))
        f_poly = X(list(f_vec))
        if f_poly.is_irreducible():
            flag_irreducible = True
    return f_poly,norm_f
        \end{lstlisting}
\end{frame}

\begin{frame}[fragile]{Helper Functions}
\textbf{Poly g}
 \begin{lstlisting}
def get_g(g1,x,bits_p,degree_f,norm_f):
    g0 = ZZ.random_element(-int(2^(bits_p/degree_f)/norm_f),int(2^(bits_p/degree_f)/norm_f))
    #g0 = ZZ.random_element(1,int(2^(bits_p/degree_f)/norm_f))
    g_poly = g1*x+g0
    return g_poly,g0
        \end{lstlisting}
\textbf{Poly G}
\begin{lstlisting}
def get_G(f_poly,g_poly):
    G_temp = f_poly.sylvester_matrix(g_poly,variable=x)
    G_poly = G_temp.determinant()-1
    return G_poly
\end{lstlisting}
\end{frame}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Main Results
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Some Analysis}

\begin{frame}[fragile]{Plots}
\textbf{Running Time Data}
\begin{figure}[H]
\minipage{0.9\textwidth}
  \includegraphics[width=\linewidth]{Data.png}
\endminipage
\end{figure}
\end{frame}

\begin{frame}[fragile]{Plots}
\textbf{Running Time Plot}
\begin{figure}[H]
\minipage{0.9\textwidth}
  \includegraphics[width=\linewidth]{together.png}
\endminipage
\end{figure}
\end{frame}

\begin{frame}[allowframebreaks]{References}

  \bibliography{bibliography}
  \bibliographystyle{abbrv}

\end{frame}

\end{document}


\subsection{Asymptotic normality of the MLE}


% !TeX spellcheck = en_GB
% !TeX root = memoco-report.tex

\section{Introduction}
\label{chap:introduction}

\subsection{Description of the problem}
The task of the exercise was to develop two algorithms capable of solving the Travelling Salesman Problem (TSP), specialized to the domain of drilling holes in electric panels. Given a sequence of holes to be drilled in an electric panel, the algorithms should be used to find a sequence of holes that minimizes the cost of drilling the whole panel, where the costs are given by the euclidean distances between holes. For simplicity it is assumed that the cost of drilling every hole can be ignored.\\
The first algorithm implements an exact methods using the IBM CPLEX optimization suite. The second algorithm is an approximated heuristic, inspired by the Lin-Kernighan algorithm \cite{LinK73}. Some implementation details has been taken from \cite{ImplemLK}. \\
Both algorithms have been tested on synthetic instances produced taking into account the applicative domain. The two algorithms are described in the following pages, and tests and results are reported in the last sections.

\subsection{Description of provided material}
%\minitoc
The delivered material includes all the produced code and everything necessary to run the program.
The provided archive comes with the following structure:
\renewcommand*\DTstylecomment{\rmfamily\color{blue}\textit}
\dirtree{%
	.1 /.
	.2 bin/\DTcomment{Binary files folder (after compiling)}.
	.2 build/\DTcomment{Build files folder (after compiling)}.
	.2 files/\DTcomment{Logs folder (after running)}.
	.2 instances/\DTcomment{Contains csv files to load}.
	.2 plots/.
	.2 src/.
	.3 utils/.
	.4 cpxmacro.hpp.
	.4 params.hpp.
	.4 python\_adapter.hpp\DTcomment{Wrapper class for Python embedding}.
	.4 variadic\_table.hpp\DTcomment{Library to print tables}.
	.4 yaml\_parser.hpp\DTcomment{Parser for the configuration file}.
	.3 calibrate.cpp\DTcomment{Calibration script}.
	.3 config.yml.
	.3 CPLEX.cpp.
	.3 CPLEX.hpp.
	.3 LK.cpp.
	.3 LK.hpp.
	.3 main.cpp\DTcomment{Program main}.
	.3 Pair.cpp.
	.3 Pair.hpp.
	.3 plot\_script.py\DTcomment{Script to plot with Python}.
	.3 test.cpp\DTcomment{Test script}.
	.3 Tour.cpp.
	.3 Tour.hpp.
	.3 TSPinstance.cpp.
	.3 TSPinstance.hpp.
	.3 TSPsolution.cpp.
	.3 TSPsolution.hpp.
	.3 utilities.cpp.
	.3 utilities.hpp.
}

\subsubsection{How to run}
The program has the following dependencies:
\begin{itemize}
	\setlength\itemsep{0.03em}
	\item \texttt{g++ 7} or higher;
	\item \texttt{IBM ILOG CPLEX Optimization Studio 12.8} or higher;
	\item \texttt{Python 2.7}.
\end{itemize}

To test the program, some instances should be generated or imported by placing them in the \texttt{instances/} folder. Some files are already provided in this folder to launch some tests. To generate new instances set \texttt{generate\_instances: true} in the \texttt{config.yml} file, and the other parameters as desired. If \texttt{N\_min = 20, N\_incr = 5, N\_max = 30}, three \texttt{csv} files containing the coordinates of every point will be generated, with size 20, 25 and 30 respectively, and will be placed in the instances folder. After that it is possible to run the exact method or the heuristic on these instances. To do that, add to the list in \texttt{instances\_to\_read} the filename (without extension) of the files that should be read and set \texttt{solve\_heur} and \texttt{solve\_cplex} as desired. Some reasonable parameters for the heuristic are already set, but it is possible to change them if necessary. A description of these specific parameters is provided in \cref{ssec:hyperpar}.
The script can then be run from a Linux environment with \texttt{make \&\& ./bin/main}. The algorithm writes its output in file \texttt{solLK.txt} and \texttt{solCPLEX.txt} under the \texttt{files/} folder. When solving more than one problem, these files can also be checked while the program is running to monitor its execution. Additionally running the heuristic also produces an image of the final solution and places it in folder \texttt{plots/}. Furthermore, running both CPLEX and the heuristic together will produce plots with a comparison of the execution times and error values in the same folder. \\

\subsection{Development environment}
The specifics of the machine used for development, calibration and test of the program are listed in \cref{tab:maspecs}.
\begin{table}[H]
	\caption{Hardware and software specifics}
	\label{tab:maspecs}
	\centering
	\begin{tabular}[t]{ll}
		\rowcolor[HTML]{EFEFEF}
		\textbf{Specific} & \textbf{Value} \\
		OS       & Ubuntu 18.04.4 LTS 64 bit	   \\
		Processor & Intel Core i7-7500U 2.70GHz $\times$ 4     \\
		Main memory  & 16 GB
	\end{tabular}
\end{table}

\section{Dataset generation}
\label{sec:datasetgen}
In order to test the two algorithms, a procedure to build a synthetic dataset of different sizes has been provided.\\
The procedure to generate the TSP instances receives as an input a number $N$ of points (which symbolises holes) and generates $N$ pairs representing the coordinates in space of the points on a $N\times N$ square canvas. These points are distributed in a way to resemble the regularity usually found in the disposition of holes in electric panels.\\
To do this the procedure draws some regular polygons with up to $10$ sides. Each polygon is generated independently and may overlap with the others, creating not perfectly regular shapes, but neither a completely random point distribution. An example of such an instance is shown in \cref{fig:dataexample}. All this operations, as well as the function to load already generated instances from \texttt{csv} files, are implemented in \texttt{TSPinstance.cpp}.

\begin{figure}[h]
	\centering
	\includegraphics[width=13cm]{path_100}
	\caption{A generated instance of with size N = 100}
	\label{fig:dataexample}
\end{figure}


\documentclass[12pt]{article}
\usepackage[pdftex]{graphicx}
\newcommand{\kg}{\mathrm{kg}}
\newcommand{\m}{\mathrm{m}}
\newcommand{\cm}{\mathrm{cm}}
\newcommand{\s}{\mathrm{s}}
\newcommand{\ms}{\mathrm{ms}}
\newcommand{\N}{\mathrm{N}}
\newcommand{\vs}{\emph{vs}}
\newcounter{problem}
\stepcounter{problem}
\newcounter{answer}[problem]
\newenvironment{problem}{\noindent\begin{minipage}{\textwidth}\sloppy\sloppypar\raggedright\textbf{\theproblem.}\refstepcounter{problem}\stepcounter{answer}---}{\end{minipage}\vspace{2ex}}
\newcommand{\source}[1]{[{#1}]}
\newenvironment{answers}{\\}{}
\newcommand{\answer}[1]{\textbf{\Alph{answer}:}\refstepcounter{answer}~\mbox{#1}\hspace{3ex}}
\begin{document}

\section*{NYU General Physics 1---Term Exam 1}

\begin{problem}
  \source{from lecture 2011-09-06} Roughly what is the mass of a cube
  of rock of side length $10\,\m$?
  \begin{answers}
    \answer{$600\,\kg$}
    \answer{$60,000\,\kg$}
    \answer{$6,000,000\,\kg$}
    \answer{$600,000,000\,\kg$}
  \end{answers}
\end{problem}

\begin{problem}
  \source{from lecture 2011-09-08} How long does it take a heavy
  object to fall (from rest) about $5\,\m$?
  \begin{answers}
    \answer{much less than $0.01\,\s$}
    \answer{about $0.01\,\s$}
    \answer{about $0.1\,\s$}
    \answer{about $1\,\s$}
    \answer{much more than $1\,\s$}
  \end{answers}
\end{problem}

\begin{problem}
  \source{from lecture 2011-09-13} We spoke of a girl throwing a
  stone.  When the stone is precisely at the \emph{highest} point on
  its trajectory (at the apex), and ignoring air resistance, the
  acceleration of the stone:
  \begin{answers}
    \answer{is zero}
    \answer{is downwards at $9.8\,\m\,\s^{-2}$}
    \answer{depends on the velocity}
    \answer{is none of the above}
  \end{answers}
\end{problem}

\begin{problem}
  \source{from lecture 2011-09-15} Which of the following position
  \vs\ time graphs is a possible path for a car undergoing normal
  kinds of acceleration and deceleration?
  \\\includegraphics{../py/x_vs_t_options.pdf}
\end{problem}

\begin{problem}
  \source{from lecture 2011-09-20} What is the magnitude $|\vec{N}|$
  of the normal force for a block on a frictionless plane inclined at
  an angle $\theta$ to the horizontal?
  \begin{answers}
    \answer{$|\vec{N}| = m\,|\vec{g}|\,\cos\theta$}
    \answer{$|\vec{N}| = m\,|\vec{g}|\,\sin\theta$}
    \answer{$|\vec{N}| = |\vec{g}|\,\cos\theta$}
    \answer{$|\vec{N}| = |\vec{g}|\,\sin\theta$}
    \answer{$|\vec{N}| = m\,|\vec{g}|$}
  \end{answers}
\end{problem}

\begin{problem}
  \source{from lecture 2011-09-20} For the block on the inclined
  plane, by what method did we figure out the \emph{direction} of the
  acceleration?
  \begin{answers}
    \answer{Acceleration is always perpendicular to gravity.}
    \answer{Acceleration is always perpendicular to a normal force.}
    \answer{We used $\vec{F}=m\,\vec{a}$.}
    \answer{We used common sense and/or physical intuition.}
    \answer{We used none of the above.}
  \end{answers}
\end{problem}

\begin{problem}
  \source{from lecture 2011-09-22} We considered a machine that had
  two blocks, one $2\,\kg$, one $4\,\kg$, attached by a light string
  with tension $T_4$ in the string.  The $T_4$ string was draped over
  a light, fixed, frictionless pulley.  What is true of this tension
  $T_4$ (if we set $g=10\,\m\,\s^{-2}$)?
  \begin{answers}
    \answer{$T_4 = 20\,\N$}
    \answer{$20 < T_4 < 30\,\N$}
    \answer{$30 \leq T_4 < 40\,\N$}
    \answer{$T_4 = 40\,\N$}
    \answer{$T_4 > 40\,\N$}
  \end{answers}
\end{problem}

\begin{problem}
  \source{from lecture 2011-09-27} A plane is flying in a circular
  path at speed $v$.  The circle has radius $R$.  If the plane flies
  for a short time $t$, by what angle $\theta$ does its direction
  change during that time?
  \begin{answers}
    \answer{$\displaystyle\theta = \frac{R\,t}{v}$}
    \answer{$\displaystyle\theta = \frac{v}{R\,t}$}
    \answer{$\displaystyle\theta = \frac{R}{v\,t}$}
    \answer{$\displaystyle\theta = \frac{v\,t}{R}$}
    \answer{none of the above}
  \end{answers}
\end{problem}

\begin{problem}
  \source{from lecture 2011-09-29} A textbook of mass $m$ slams into a
  hard surface.  Before the collision, the textbook is moving at speed
  $v$.  The textbook stops in a time $\Delta t$.  After the collision,
  the textbook is at rest.  The magnitude of the force of impact is
  roughly
  \begin{answers}
    \answer{$\displaystyle m\,\frac{v}{\Delta t}$}
    \answer{$\displaystyle \frac{v}{\Delta t}$}
    \answer{$\displaystyle m\,\frac{\Delta t}{v}$}
    \answer{$\displaystyle \frac{\Delta t}{v}$}
  \end{answers}
\end{problem}

\begin{problem}
  \source{from problem set 1, problem 1} At 1500 dollars per ounce
  (29\,g), roughly what is the mass of $100$ million dollars worth of
  gold?
  \begin{answers}
    \answer{much less than $20\,\kg$}
    \answer{$20\,\kg$}
    \answer{$2,000\,\kg$}
    \answer{$200,000\,\kg$}
    \answer{much more than $200,000\,\kg$}
  \end{answers}
\end{problem}

\begin{problem}
  \source{from problem set 1, problem 2} What combination of length $L$,
  density $\rho$, and speed $v$ have dimensions of force?
  \begin{answers}
    \answer{$\rho\,L\,v$}
    \answer{$\rho\,L\,v^2$}
    \answer{$\rho\,L^2\,v$}
    \answer{$\rho\,L^2\,v^2$}
    \answer{none of the above}
  \end{answers}
\end{problem}

\begin{problem}
  \source{from problem set 1, problem 3} The dynamic viscosity $\mu$
  has dimensions of mass per length per time (units of
  $\kg\,\m^{-1}\,\s^{-1}$).  What combination of dynamic viscosity
  $\mu$, length $L$, and speed $v$ have units of force?
  \begin{answers}
    \answer{$\mu\,L\,v$}
    \answer{$\mu\,L\,v^2$}
    \answer{$\mu\,L^2\,v$}
    \answer{$\mu\,L^2\,v^2$}
    \answer{none of the above}
  \end{answers}
\end{problem}

\begin{problem}
  \source{from problem set 2, problem 1} A dragster travels 0.25\,mi
  in 5.5\,s, starting from rest.  Under the assumption of constant
  acceleration, what is the time it takes the dragster to go half-way;
  that is, how many seconds does it take to go the first 0.125\,mi?
  \begin{answers}
    \answer{substantially less than $1.38\,\s$}
    \answer{$1.38\,\s$}
    \answer{$2.75\,\s$}
    \answer{$3.9\,\s$}
    \answer{substantially more than $3.9\,\s$}
  \end{answers}
\end{problem}

\begin{problem}
  \source{from problem set 2, problem 1} Again, the dragster: Two cars
  start from rest and accelerate at constant acceleration over a
  distance $X$.  If car $F$ goes at twice the acceleration of car $S$,
  by what factor is car $S$ slower?  That is, what is the ratio of the
  time $t_S$ taken by car $S$ to the time taken by car $F$?
  \begin{answers}
    \answer{$1$}
    \answer{$\sqrt{2}$}
    \answer{$2$}
    \answer{$4$}
  \end{answers}
\end{problem}

\begin{problem}
  \source{from problem set 2, problem 2} Which of the following graphs
  is a possible graph of the velocity as a function of time for an
  object thrown upwards at $3\,\m\,\s^{-1}$ at $t=0$ and then falling
  freely?
  \\\includegraphics{../py/vy_vs_t_options.pdf}
\end{problem}

\begin{problem}
  \source{from problem set 2, problem 3} Below is a graph of velocity
  $v_x$ in the $x$ direction as a function of time for an automobile.
  \\\includegraphics{../py/vx_vs_t.pdf}\\
  How far does the automobile travel between $t=0$ and $t=35\,\s$?
  \begin{answers}
    \answer{$5\,\m$}
    \answer{$175\,\m$}
    \answer{$425\,\m$}
    \answer{$525\,\m$}
    \answer{much more than $525\,\m$}
  \end{answers}
\end{problem}

\begin{problem}
  \source{from problem set 3, problem 1} If $g$ is the acceleration
  due to gravity and $R$ is the radius of the Earth, what, roughly, is
  the orbital period of the Space Station?
  \begin{answers}
    \answer{$\displaystyle 2\pi\,\sqrt{\frac{R}{g}}$}
    \answer{$\displaystyle 2\pi\,\sqrt{\frac{g}{R}}$}
    \answer{$\displaystyle 2\pi\,\sqrt{R\,g}$}
    \answer{$\displaystyle 2\pi\,\sqrt{\frac{1}{R\,g}}$}
    \answer{none of the above}
  \end{answers}
\end{problem}

\begin{problem}
  \source{from problem set 3, problem 2} What is the tension T in this
  problem?\\\includegraphics{../py/stringblocks.pdf}
  \begin{answers}
    \answer{$\displaystyle F\,\frac{m_1}{m_1+m_2}$}
    \answer{$\displaystyle F\,\frac{m_2}{m_1+m_2}$}
    \answer{$\displaystyle F$}
    \answer{$\displaystyle m_1\,g$}
    \answer{$\displaystyle m_2\,g$}
  \end{answers}
\end{problem}

\begin{problem}
  \source{from problem set 3, problem 3} A block of mass $m=9\,\kg$
  lies on a horizontal table.  It is stationary relative to the table.
  Now imagine that the table is accelerating upwards with an
  acceleration of magnitude $0.5\,\m\,\s^{-2}$.  What is the magnitude
  of the force on the block from the table?  For ease of calculation,
  take $g=10\,\m\,\s^{-2}$.
  \begin{answers}
    \answer{$4.5\,\N$}
    \answer{$85.5\,\N$}
    \answer{$90.0\,\N$}
    \answer{$94.5\,\N$}
    \answer{much more than $94.5\,\N$}
  \end{answers}
\end{problem}

\begin{problem}
  \source{from problem set 4, problem 1} A block of mass $m$ sits on a
  plane inclined at an angle of $\theta=20\,\deg$ to the horizontal.
  There is a coefficient of friction $\mu=0.9$ between the block and
  the plane.  What is the magnitude of the frictional force?
  \begin{answers}
    \answer{$m\,g\,\cos\theta$}
    \answer{$m\,g\,\sin\theta$}
    \answer{$\mu\,m\,g\,\cos\theta$}
    \answer{$\mu\,m\,g\,\sin\theta$}
    \answer{$\mu\,m\,g\,\tan\theta$}
  \end{answers}
\end{problem}

\begin{problem}
  \source{from problem set 4, problem 2} At the lowest point in its
  swing, a mass swinging like a pendulum at the end of a light,
  inextensible string is
  \begin{answers}
    \answer{not accelerating}
    \answer{accelerating upwards}
    \answer{accelerating downwards}
    \answer{accelerating in the direction of the velocity}
    \answer{accelerating in the direction opposite to the velocity}
  \end{answers}
\end{problem}

\begin{problem}
  \source{from problem set 4, problem 3} A ball of mass $m$ and radius
  $R$ drops from a height $h$ onto a flat surface.  It bounces.  In
  which of these situations will the contact force (during the bounce)
  be largest?
  \begin{answers}
    \answer{rubber ball on rubber surface}
    \answer{rubber ball on marble surface}
    \answer{steel ball on rubber surface}
    \answer{steel ball on marble surface}
  \end{answers}
\end{problem}

\begin{problem}
  \source{from \textit{Motion 1} lab} The motion sensor measured the
  position of your notebook by making use of
  \begin{answers}
    \answer{the volume of reflected sound pulses}
    \answer{the brightness of reflected light pulses}
    \answer{the arrival times of reflected sound pulses}
    \answer{the arrival times of reflected light pulses}
    \answer{none of the above}
  \end{answers}
\end{problem}

\begin{problem}
  \source{from \textit{Motion 2} lab} Take the second derivative with respect
  to time $t$ of the expression $$x_0 + v_0\,t +
  \frac{1}{2}\,a\,t^2$$.  What do you get?
  \begin{answers}
    \answer{$\displaystyle x_0 + v_0\,t + \frac{1}{2}\,a\,t^2$}
    \answer{$\displaystyle x_0 + v_0\,t$}
    \answer{$\displaystyle x_0$}
    \answer{$\displaystyle v_0 + a\,t$}
    \answer{$\displaystyle a$}
  \end{answers}
\end{problem}

\begin{problem}
  WRONG ANSWERS \source{from \textit{Equilibrium of a Particle} lab} Imagine that
  there are three forces $\vec{A}$, $\vec{B}$ and $\vec{C}$ acting on
  a particle such that the particle is in equilibrium.  Now imagine
  that forces $\vec{B}$ and $\vec{C}$ point in opposite directions from one another.
  What is true of the force magnitudes?
  \begin{answers}
    \answer{$|\vec{A}|^2 = |\vec{B}|^2 + |\vec{C}|^2$}
    \answer{$|\vec{A}|^2 = |\vec{B}|^2 + |\vec{C}|^2 - |\vec{B}|\,|\vec{C}|\,\cos{\theta}$}
    \answer{$|\vec{A}| = 0$ and $|\vec{B}| = |\vec{C}|$}
    \answer{All forces must have zero magnitude.}
    \answer{None of the above.}
  \end{answers}
\end{problem}

\end{document}


\documentclass{classrep}
\usepackage[utf8]{inputenc}
\frenchspacing

\usepackage{graphicx}
\usepackage[usenames,dvipsnames]{color}
\usepackage[hidelinks]{hyperref}
\usepackage{lmodern}
\usepackage{placeins}
\usepackage{url}
\usepackage{amsmath, amssymb, mathtools}
\usepackage{listings}
\usepackage{fancyhdr, lastpage}
\usepackage{subfiles}
\usepackage{ifthen}

\pagestyle{fancyplain}
\fancyhf{}
\renewcommand{\headrulewidth}{0pt}
\cfoot{\thepage\ / \pageref*{LastPage}}

% In order to change person, change value of variable
\newboolean{is_karwowski}
\setboolean{is_karwowski}{true}

%--------------------------------------------------------------------------------------%
\studycycle{Applied Information Technology, 2 cycle}
\coursesemester{II}

\coursename{Soft Computing Laboratory}
\courseyear{2021/2022}

\courseteacher{dr inż. Kamil Stokfiszewski}
\coursegroup{Wednesday, 8:30}

\author{%
    \ifthenelse{\boolean{is_karwowski}}
    {\studentinfo[239671@edu.p.lodz.pl]{Jan Karwowski}{239671}\\}
    {\studentinfo[239676@edu.p.lodz.pl]{Kamil Kowalewski}{239676}\\}
}

\title{Assignment 5.: Kohonen Network for image compression}

\begin{document}
    \maketitle
    \thispagestyle{fancyplain}

    \tableofcontents
    \newpage

    \section{Main goal} \label{main_goal} {
        The main goal of this task is to prepare implementation of Kohonen network for
        image compression. The images themselves should use 8-bit grayscale.
    }

    \section{Theoretical background} \label{theory} {
        Kohonen Network is a kind of self organizing map, where neurons and input values represent
        points (vectors) in N-dimensional space. The purpose of this model is to represent or
        reproduce shape and distribution of input values using much more lower number of points. I.e
        this algorithm groups input values into clusters (clusterize).

        Kohonen Network consists of a single layer of neurons. It is trained in unsupervised manner
        (without labels), and the training is based on simple rule \emph{winner takes all}.  This
        means, that for each input pattern only the most activated neuron's weights are modified.
        Purpose of this weights change is to make the winner neuron closer (in some sens, e.g.
        euclidean) to the input pattern.

        Getting down to the possible implementation details, neuron's activation should depends on
        \emph{distance} to input pattern. If input patterns and weights are normalized, this
        distance (or rather similarity) could be calculated as a simple dot product. If there is no
        normalization then euclidean distance could be used. After finding the nearest neuron
        (winner) for the particular pattern, neuron's weights are modified according to the
        following equation:
        \begin{equation}
            w_{i} = w_{i} + \eta (x_{i} - w_{i})
        \end{equation}
        where $w_{i}$ and $x_{i}$ are the i-th element of weight and input vectors respectively,
        $\eta$ is a learning rate.

        To compress an image using described algorithm, it should be divided to a sequence of
        random, relatively small crops (e.g. 4x4 or 16x16). Such a sequence constructs training set,
        and as a result of training Kohonen Network these crops are grouped into clusters.  To
        compress an image it should be divided to chunks and these chunks should be treated as input
        patterns and replaced by weights of the most activated neuron. When the network was trained
        without normalization this substitution is enough. When weights and input
        patterns are normalized, then pixel intensity information is lost and should be
        remembered for each chunk during compression.
    }

    \section{Implementation} \label{implementation} {
        Created program consists of two main modules. The first one is a pure Kohonen Network
        implementation, the second one is responsible for an image compression. Ours Kohonen Network
        can work in two modes - with and without normalization, which implies small differences in
        implementation. When the network is created its weights are initialized and all the input
        patterns are remembered for further training. If in \emph{normalize} mode, these two
        matrices are normalized. To train a network its \emph{train\_step} method should be called
        iteratively. Within this function single training step is proceed - for each input pattern
        winner neuron is found and its weights are updated. Winner selection depends on the running
        mode. If in \emph{normalize} mode, then dot product is calculated and the most activated
        neuron is a winner. If not in \emph{normalize} mode, then euclidean distance to each neuron
        is calculated and the nearest one is a winner. After that, dead neurons, which are not
        modified for all the input patterns in a single training step, are randomly initialized.
        Number of dead neurons and max winner weight's modification are remembered to defined stop
        constraint. Our algorithm stops if there is no dead neurons and maximum winner weight's
        modification is lower then $0.00001$ part of input patterns' min-max values range.
        Optionally, if in \emph{normalize} mode, after each training step neurons' weights are
        normalized.

        To compress an image it is read into memory in a grayscale mode. Then given number of
        random crops in given shape are extracted from the image. These random crops build dataset,
        which Kohonen Network is trained on. After training process, given number of neurons is
        available to use. Image is splitted into crops and each crop is replaced by weights of
        neuron, which is the most activated in response to the image crop. This is how decompressed
        image view is simulated. Additionally PSNR value and compression ratio are calculated.
    }

    \section{Experiments and results} \label{results} {
        \ifthenelse{\boolean{is_karwowski}}
        {\subfile{section/karwowski_results.tex}}
        {\subfile{section/kowalewski_results.tex}}
    }

    \section{Summary and conclusions} \label{summary} {
        \ifthenelse{\boolean{is_karwowski}}
        {\subfile{section/karwowski_summary.tex}}
        {\subfile{section/kowalewski_summary.tex}}
    }

    \begin{thebibliography}{0}
        % @formatter:off
        \bibitem{instruction}{Labolatory instruction, URL: https://ftims.edu.p.lodz.pl/pluginfile.php/75444/\\mod\_resource/content/1/soft\_comp\_lab\_05\_KOHONEN.pdf}
        % @formatter:on
    \end{thebibliography}

\end{document}


%\subsubsection{ESMF\_RegridDistrb}
%
%{\sf DESCRIPTION:\\}
%Regrid options for Field data motion supported by ESMF.
%
%Valid values are:
%\begin{description}
%   \item [ESMF\_REGRIDDISTRB\_BOTH]
%         Redistribute both source and destination Fields.
%   \item [ESMF\_REGRIDDISTRB\_DEST]
%         Redistribute destination Field.
%   \item [ESMF\_REGRIDDISTRB\_NONE]
%         No data motion required or undefined.
%   \item [ESMF\_REGRIDDISTRB\_SOURCE]
%         Redistribute source Field.
%\end{description}

\subsubsection{ESMF\_REGRIDMETHOD}

{\sf DESCRIPTION:\\}
General Regrid methods supported by ESMF.

Valid values are:
\begin{description}
%  \item [ESMF\_REGRID\_METHOD\_ADJOINT]
%        Create adjoint of existing regrid
%  \item[ESMF\_REGRID\_METHOD\_BICUBIC ]

\item [ESMF\_REGRIDMETHOD\_BILINEAR]
     Bilinear regridding using a local bilinear approximation to interpolate
     to a point in a quadrilateral grid.  For more details, please see
     Section~\ref{sec:BilinearRegrid}.  NOTE: This is applicable only for
     logically-rectangular or block-structured logically-rectangular grids.

%\item[ESMF\_REGRID\_METHOD\_CONSERV1 and ESMF\_REGRID\_METHOD\_CONSERV2]
\item[ESMF\_REGRIDMETHOD\_CONSERV1]
     First-order conservative remapping.  For algorithm details, please see
     Section~\ref{sec:ConserveRegrid}.

%  \item [ESMF\_REGRID\_METHOD\_FILE]
%        Read a regrid from a file
%  \item [ESMF\_REGRID\_METHOD\_FOURIER]
%        Fourier transform.
%  \item [ESMF\_REGRID\_METHOD\_INDEX]
%        Index-space regrid (shift, stencil).
%  \item [ESMF\_REGRID\_METHOD\_LEGENDRE]
%        Legendre transform.
\item[ESMF\_REGRIDMETHOD\_LINEAR  ]
     This is a standard linear regridding algorithm for 1-d grids only.  In ESMF,
     it is used to regrid between vertical grids.

%  \item [ESMF\_REGRID\_METHOD\_NEARNBR]
%        Nearest-neighbor dist-weighted avg
\item [ESMF\_REGRIDMETHOD\_NONE]
     No regridding or undefined regrid.
%  \item [ESMF\_REGRID\_METHOD\_RASTER]
%        Regrid by rasterizing domain.
%  \item [ESMF\_REGRID\_METHOD\_REGRIDCOPY]
%        Copy existing regrid
%  \item [ESMF\_REGRID\_METHOD\_SHIFT]
%        Shift addresses of existing regrid
%  \item [ESMF\_REGRID\_METHOD\_SPLINE]
%        Cubic spline for 1-d regridding
%  \item [ESMF\_REGRID\_METHOD\_USER]
%        User-supplied method
\end{description}

\subsubsection{ESMF\_RegridNormOpt}

{\sf DESCRIPTION:\\}
Regrid normalization options supported by ESMF, for conservative regridding only.

Valid values are:
\begin{description}
   \item [ESMF\_REGRID\_NORM\_DSTAREA]
         The Regrid weights are normalized by the destination area of each cell.
   \item [ESMF\_REGRID\_NORM\_FRACAREA]
         The Regrid weights are normalized by the area of the source grid
         overlapped by each cell (default).
   \item [ESMF\_REGRID\_NORM\_NONE]
         No normalization applied to Regrid weights.
   \item [ESMF\_REGRID\_NORM\_UNKNOWN]
         Unknown or undefined normalization.
\end{description}


\documentclass{article}
\usepackage{amsmath}
\usepackage{amssymb}
\title{Specialization Store Working}
\author{Mark Cox}

\newcommand{\true}{\textrm{true}}
\newcommand{\false}{\textrm{false}}

\begin{document}
\maketitle

TODO
\begin{enumerate}
\item Improve the terminology. Precedence, applicability, most
  applicable.
\item Add proofs.
\end{enumerate}

\section{Introduction}

The specialization store system defines a new style of generic
function which can i) dispatch according to optional, keyword or rest
arguments and ii) the operation is determined using argument types
rather than classes.

This document outlines an ordering of specializations for a given set
of input types and that there exists a set of projections which
partition a set of specializations in to disjoint regions.

The operators used in this document are defined as follows
\begin{itemize}
\item $ x \preceq y $ denotes that the set $x$ is a subset of the set $y$.
\item $ x \prec y$ denotes that the set $x$ is a strict subset of the set $y$.
\item $\lnot x $ is logical negation operator.
\item $x \lor y$ is an operator performing the \emph{or} operation.
\item $x \land y$ is an operator performing the \emph{and} operation.
\item $\Pi_{i=1}^n x_i $ is equivalent to $ x_i \land \dots \land x_n $.
\end{itemize}
The standard numerical operators $=$, $<$, $>$, $\leq$ and $\geq$ are
also used.

A symbol $x$ may refer to a tuple containing an arbitrary number of
values, written $x = (x_1, \dots, x_n)$, or may represent a type. The
context of the symbol should make it clear what it represents. Note
that \emph{none} of the above operators are defined for tuples.

The operators defined for tuples are
\begin{itemize}
\item $|x|$ is the number of elements in the typle. e.g. $|x| = n$
  when $ x = ( x_i, \dots, x_n ) $ .
\end{itemize}

\section{Specializations}
There are two different types of specializations defined in
specialization store.
\begin{description}
\item[Fixed arity] These are specializations which can be added to
  store functions which accept a fixed number of required arguments
  and possibly optional arguments and/or keyword
  arguments. Specializations belonging to these functions are
  represented by $ t \equiv (t_1, \dots, t_n) $.
\item[Variable arity] These specialization belong to store functions
  which define a \texttt{\&rest} argument without using
  \texttt{\&key}. These specializations are represented by
  $ x \equiv (t_{1}, \dots, t_{n_x}, \sigma_x, \mu_x) $ where $n_x$
  represents the number of required arguments for the specialization,
  $\sigma_x$ is a non negative integer indicating how many other
  arguments the specialization accepts and $\mu_x$ is the type of each
  of the other $\sigma_x$ arguments. In the context of argument types
  $t$, the value $\sigma_t = |t| - n_x$ is the number of non required
  arguments in the tuple $t$ and $\mu_t$ is the most specific type for
  which each non required argument.
\end{description}

\section{Ordering}
\label{sec:ordering}
\subsection{Fixed arity}
In this section we show how a specialization is selected for an
invocation with the argument types $t \equiv (t_1, \dots, t_n)$.

A specialization is selected by sorting the specializations using a
predicate $h(x,y;t)$ where $x$ and $y$ denote a specialization tuple
and $t$ is the tuple containing the argument types. The function $h$
is true if $x$ is applicable to the argument types $t$ and is a more
suitable specialization than $y$. Its definition is as follows
\begin{align}
  h(x,y;t) &\equiv g(x;t) \land (\lnot g(y;t) \lor f(x,y) )
\end{align}
where $g$ is the applicability function
\begin{align}
  g(x;t) &\equiv \Pi_{i=1}^n (t_i \preceq x_i)
\end{align}
and $f$ is the precedence function
\begin{align}
  f(x,y) &\equiv \Pi_{i=1}^n (x_i \preceq y_i)
\end{align}

\subsection{Variable arity}
The functions $g$, $f$ and $h$ for specializations with variable arity
are
\begin{align}
  g(x;t) &\equiv (n_x \leq |t| \leq n_x + \sigma_x)
                 \land \Pi_{i=1}^{n_x} (t_i \preceq x_i)
                 \land ( \mu_t \preceq \mu_x ) \\
  f(x,y) &\equiv (n_x \geq n_y)
                 \land \Pi_{i=1}^{n_y}(x_i \preceq y_i)
                 \land ( \mu_x \preceq \mu_y )\\
  h(x,y;t) &\equiv g(x;t) \land (\lnot g(y;t) \lor f(x,y) )
\end{align}

\section{Dispatch Tree}
An applicability function $g$ and a discrimination function $f$
provide a method of selecting a specialization from a set $Z$ which
has the highest precedence for a set of arguments. This method of
selection is not very efficient as it requires sorting the set of
specializations.

In this section we seek to find a function $d : t \rightarrow x$ which
computes a specialization $x \in Z$ which has the highest precedence
for input arguments of type $t$.

The key property of the function $d$ is that its computational
complexity is no greater than the $\max_i |x_i|$ where $x_i \in Z$.

\subsection{Criteria}
The following cases need to proven in order to show that the function
$d$ is equivalent to the sorting method.
\begin{align}
  \begin{cases}
    g(d(t); t) \equiv \true & h(d(t),y;t) \equiv \true \;\; \forall y \in Z \\
    g(d(t); t) \equiv \false & g(y;t) \equiv \false \;\; \forall y \in Z
  \end{cases}
\end{align}

\noindent The sorting function $h(x,y;t)$ is defined as
\begin{align}
  h(x,y;t) &\equiv g(x;t) \land (\lnot g(y;t) \lor f(x,y) )
\end{align}
which has the following truth table

\begin{table}[h]
\centering
\begin{tabular}{|c|c|c||c|}
\hline
$g(x;t)$ & $g(y;t)$ & $f(x,y)$ & $h(x,y;t)$ \\
\hline
F & F & F & F \\
F & F & T & F \\
F & T & F & F \\
F & T & T & F \\
T & F & F & T \\
T & F & T & T \\
T & T & F & F \\
T & T & T & T \\
\hline
\end{tabular}
\end{table}

The precedence function for the fixed arity and variable arity case
both share the term
\begin{align}
  \Pi_{i=1}^{\min(n_x,n_y)} x_i \preceq y_i
\end{align}
which, according to the function $h$, requires an input argument type
$t_i$ to satisfy
\begin{align}
  (t_i \preceq x_i) \land [\lnot (t_i \preceq y_i) \lor (x_i \preceq y_i)].
\end{align}

\subsection{Fixed Arity}
Assume that we have a set of specializations $Z$ for an arity $n$
store function which are partially applicable.
\begin{align}
  x_1 & \equiv (x_{11}, \dots, x_{1n}) \nonumber \\
  x_2 & \equiv (x_{21}, \dots, x_{2n}) \nonumber \\
  \vdots & \vdots                     \nonumber \\
  x_k & \equiv (x_{k1}, \dots, x_{kn}) \nonumber
\end{align}
It is assumed that no two specializations are the same.

Partial applicability is defined by the set $P$ which represents
knowledge about any of the input argument types $t_j$. Specifically
\begin{align}
  (p_j \in P) \rightarrow (t_j \preceq p_j)
.
\end{align}

A specialization $x_i$ is said to be partially applicable if
\begin{align}
  \exists_j \left[(p_j \preceq x_{ij}) \land (p_j \in P) \right]
.
\end{align}

A specialization $x_i$ is said to be applicable if
\begin{align}
  \forall_j \left[(p_j \preceq x_{ij}) \land (p_j \in P) \right]
\end{align}

The function $d$ created for the fixed arity case is a decision tree
which involves selecting a type $p_j$ to use as a test for a specific
input argument type $t_j$.

The type $p_j$ is selected from the $x_{ij}$ such that
\begin{enumerate}
\item $\exists_i (p_j \equiv x_{ij})$
\item $\{ x_{ij} | x_{ij} \prec p_j \} \equiv \emptyset$
\item $p_j \notin P$
\end{enumerate}

The type $p_j$ is then used to partition the specializations $Z$ in to
a set $X$ and $Y$ such that
\begin{align}
  X & \equiv \{ x_i | p_j \preceq x_{ij} \} & Y & \equiv (Z - X) \cup \{ x_i | p_j \prec x_{ij} \}
\end{align}

This process continues by splitting the set $X$ with
$P = P \cup \{ p_j \}$ and splitting the set $Y$ with $P =
P$. Splitting stops when no $p_j$ can be obtained.

There may be more than one specialization in $X$ when $P$ is full
e.g. the tuples $x_1 = (\alpha)$ and $x_2 = (\alpha \lor \beta)$. This
can be resolved by sorting the specializations using $h()$.

\subsection{Variable Arity}
The tree building process for the variable arity case proceeds by
partitioning the specializations using the first $\min_i n_{x_i}$
arguments as if it were a fixed arity problem.

A leaf in the resulting tree will contain a set of specializations
$Z$. These specializations can be split in to two categories, those
which can be invoked with $c$ arguments and those that can be invoked
with more than $c$
\begin{align}
  X & = \{ x_i | n_{x_i} \leq c \leq n_{x_i} + \sigma_{x_i} \} & Y &= \{ x_i | c < n_{x_i} + \sigma_{x_i} \}
\end{align}
where $c$ is defined as
\begin{align}
  c = \min_i n_{x_i} \textrm{ s.t. } x_i \in Z
\end{align}

The set $X$ represents a fixed arity problem and thus can be
partitioned using the strategy outlined in the previous section. The
above process is recursively applied to set $Y$.

\end{document}

%%% Local Variables:
%%% mode: LaTeX
%%% mode: TeX-PDF
%%% End:


\documentclass[jou]{apa6}

\usepackage[american]{babel}

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

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

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

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

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

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

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

\leftheader{Discrete Sample Quiz 8}

\abstract{%
}

%\keywords{}

\setlength\parindent{0pt}

\begin{document}

%\thispagestyle{empty}

\twocolumn
\section{Quiz 11: Graphs}

\vspace{4pt}
{\bf Question 1.}
Let $G = (V,E)$ be a graph, where $V$ is the set of all positive divisors of $144$ (including
$1$ and $144$ itself). Two different vertices $d_1,d_2$ are connected by an edge iff one of the
numbers divides another ($d_1\,\mid\,d_2$ or $d_2\,\mid\,d_1$).
Find the number of vertices $|V|$ and the number of edges $|E|$ in this graph.

Write two comma-separated integers.

\vspace{10pt}
{\bf Question 2.}
How long is the longest simple circuit in $W_{20}$?
(A simple circuit is a circular path that may visit vertices multiple times,
but does not contain any edge more than once.)

Write a positive integer.

\vspace{10pt}
{\bf Question 3.}
Let $G$ be a planar connected graph with $60$ vertices, each vertex has degree $3$.
How many regions are there in $G$?

Write a positive integer.

\vspace{10pt}
{\bf Question 4.} This is an adjacency matrix for some graph:
{\footnotesize
$$M_G = \left(
\begin{array}{ccccccccc}
0 & 1 & 0 & 1 & 0 & 0 & 0 & 0 & 1 \\
1 & 0 & 1 & 1 & 1 & 0 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 & 1 & 1 & 0 & 0 & 0 \\
1 & 1 & 0 & 0 & 1 & 0 & 1 & 0 & 0 \\
0 & 1 & 1 & 1 & 0 & 1 & 1 & 1 & 0 \\
0 & 0 & 1 & 0 & 1 & 0 & 0 & 1 & 1 \\
0 & 0 & 0 & 1 & 1 & 0 & 0 & 1 & 0 \\
0 & 0 & 0 & 0 & 1 & 1 & 1 & 0 & 1 \\
1 & 0 & 0 & 0 & 0 & 1 & 0 & 1 & 0 \\
\end{array} \right).$$
}

It is known that $G$ is a planar graph. Find the number of vertices $|V|$,
number of edges $|E|$ and the number of regions $|R|$ for this graph.

Write $3$ comma-separated integers.

\vspace{10pt}
{\bf Question 5 (Dudeney2016, Prob.434), ``536 Puzzles''.}

\begin{figure}[!htb]
\center{\includegraphics[width=1.5in]{quiz-11/prison-cells.png}}
\caption{\label{fig:prison-cells} A weighted graph.}
\end{figure}

A prisoner currently is in the cell ``$A$'' (Figure~\ref{fig:prison-cells}). He has to visit each
prison cell no more than once and return
back to the cell ``$A$''. What is the largest number of prison cells that
can be visited in this way?\\
{\em (Visiting each cell once does not contradict with the requirement to return back
to ``$A$'' \textendash{} the prisoner uses a circular path between the rooms:
every room on the path, including ``$A$'', is entered once and left once. We want
to know the maximum length of this path.)}

Write a positive integer.

{\em Note.} You may also want to prove to yourself that the number is the largest possible.

\vspace{10pt}
{\bf Question 6}
There is a bipartite graph $G=(V,E)$ with exactly $|V| = 17$ vertices. (A graph is {\em bipartite}, if
the set of vertices $V$ can be split into two parts $X$, $Y$ so that all edges are between a vertex in $X$ and a vertex in $Y$.)
Find the largest possible number of edges in such a graph.

Write a positive integer.

\vspace{10pt}
{\bf Question 7} Verify, if these statements are true.
A simple undirected graph is called a {\em cubic} graph,
if every vertex has degree $3$.\\
{\bf (A)} There exists a cubic graph with $7$ vertices.\\
{\bf (B)} There exists a cubic graph with $6$ vertices that is not isomorphic to $K_{3,3}$.\\
{\bf (C)} There exists a cubic graph with $8$ edges.

Write a sequence of 3 comma-separated letters (e.g.\ {\tt T,T,T} or {\tt F,F,F}).

\vspace{10pt}
{\bf Question 8.} Verify, if these statements are true:\\
{\bf (A)} There exists a simple directed graph with indegrees $0,1,2,4,5$ and outdegrees $0,3,3,3,3$. (A graph is {\em simple}, if
it is not a {\em multigraph} \textendash{} there is no more than one edge $(u,v)$ for any vertices $u,v$.)\\
{\bf (B)} There exists a connected undirected simple planar graph with $5$ regions and $8$ vertices, each vertex has degree $3$.\\
{\bf (C)} There exists a connected undirected simple planar graph with $8$ regions and $6$ vertices, each region is surrounded
with $3$ edges.

Write a sequence of 3 comma-separated letters (e.g.\ {\tt T,T,T} or {\tt F,F,F}).

\vspace{10pt}
{\bf Question 9.}
Use Dijkstra’s Algorithm to find the shortest paths from the source vertex $s$
to all other vertices $t,x,y,z$ (Figure~\ref{fig:dijkstra}). The length of a path is obtained by adding the
weights of the directed edges.

\begin{figure}[!htb]
\center{\includegraphics[width=1.8in]{quiz-11/dijkstra.png}}
\caption{\label{fig:dijkstra} A weighted graph.}
\end{figure}

Write $4$ comma-separated numbers \textendash{} the shortest paths
to the vertices $t,x,y,z$ respectively.

{\em Note.} Dijkstra's algorithm (Rosen2019, p.747) initializes the set of vertices $S$ that we
know the shortest paths to (initially it only contains the
source vertex $S = \{ s \}$;
the distance from $s$ to itself is $0$; initialize the distances to
all the other vertices to $\infty$). At every step consider all the edges that
go from the set $S$ to $\overline{S}$, i.e. to the vertices where we still
do not know the shortest paths. Update all the shortest paths (if crossing from
the set $S$ to $\overline{S}$ finds a shorter path than $\infty$ or the currently
known minimum length, then decrease the estimate for this vertex).
Finally, add the minimum vertex from $\overline{S}$ to $S$. Repeat the steps
until all vertices are added to $S$ and all the shortest path estimates have
reached their smallest values.

\vspace{10pt}
{\bf Question 10 (Dudeney2016, Prob.423), ``536 Puzzles''.}
A man starting from the town $A$, has to inspect all the roads
shown from town to town (Figure~\ref{fig:path-with-repetitions}).
Their respective lengths, $13$, $12$, and $5$
miles are all shown. What is the shortest possible route he can adopt,
ending his journey wherever he likes?

\begin{figure}[!htb]
\center{\includegraphics[width=2in]{quiz-11/path-with-repetitions.png}}
\caption{\label{fig:path-with-repetitions} Path with repetitions}
\end{figure}

Write an integer \textendash{} the length of the shortest route.

{\em Note.} This graph obviously has no Euler path (since there
are more than $2$ vertices with odd degrees). The problem is to
find a path that is likely {\bf not} simple
(uses the same edge several times),
but that includes every edge shown and the total of weights is minimal.

\vspace{10pt}
{\bf Question 11}\\
Somebody placed $24$ chess rooks on a $8 \times 8$ chessboard as shown in Figure~\ref{fig:rooks}
(each horizontal and each vertical has exactly $3$ rooks).

\begin{figure}[!htb]
\center{\includegraphics[width=1.5in]{quiz-11/rooks.png}}
\caption{\label{fig:rooks} Path with repetitions}
\end{figure}

We imagine that this chess-board defines a bipartite graph between the
set of all verticals $X= \{ A,B,C,D,E,F,G,H \}$ and the set of all
horizontals $Y= \{ 1,2,3,4,5,6,7,8 \}$. Any rook defines an edge between these two sets.
For example, the rook $C8$ defines an edge $(C,8)$.

Find a subset of verticals $V \subseteq X$ such that $|V|=3$, but
the neighbor set has size $|N(V)| = 5$.

Write $3$ comma-separated letters in your answer (the vertices from $V$). It is
sufficient to write just one possible answer, if there are many.

\vspace{10pt}
{\em Note 1.} For example, the answer $\textcolor{blue}{\mathtt{F,G,H}}$ does not work,
since the set of vertices $\{ \mathtt{F},\mathtt{G},\mathtt{H} \} \subseteq X$
is neighboring with a set of six vertices
$\{ 1,3,5,6,7,8 \} \subseteq Y$, i.e. the rooks on these three verticals
attack six horizontals, but not five.

{\em Note 2.} For the condition of the Hall's marriage theorem we need the inequality $|V| \leq |N(V)|$
for {\bf every} $V \subseteq X$. You could prove to yourself that it is always satisfied
(also for all the other placements of $24$ rooks where each horizontal and each
vertical has $3$ rooks).\\
{\em Note 3.} Interpret for yourself what does a ``perfect matching'' between the sets
$X$ and $Y$ mean in this subject-area with a chessboard and rooks.

\newpage

\subsection{Answers}

\vspace{4pt}
{\bf Question 1} Answer: $15,75$\\
Since $144 = 2^4 \cdot 3^2$, number $144$ has $(4+1)(2+1) = 15$ divisors
(the number of ways to pick powers $2^a \cdot 3^b$).
Their Hasse diagram is shown in Figure~\ref{fig:divisibility-144-graph}
(transitive closure has many more arrows that are not shown).

For each vertex $d_1$ we calculate the number of other vertices that
are divisible by $d_1$ (i.e. can be reached by following one or more arrows in the
Hasse diagram). Adding all those numbers gives the number of edges.

\begin{figure}[!htb]
\center{\includegraphics[width=3in]{quiz-11/divisibility-144-graph.png}}
\caption{\label{fig:divisibility-144-graph} Divisibility Hasse diagram.}
\end{figure}

\vspace{10pt}
{\bf Question 2} Answer: $30$\\
All the vertices on the regular $20$-gon have degree equal to $3$.
This means that we have to drop at least $10$ edges before we
get a simple path (because any simple path adds only even number to the degree
of any vertex in a graph). Initially $W_{20}$ has $20 + 20 = 40$ edges.
After deleting $10$ edges (every other edge on the perimeter of the $20$-gon),
we are left with $30$ edges.

\vspace{10pt}
{\bf Question 3} Answer: $32$\\
$60$ vertices (having degree $3$ each would create the sum of all degrees equal to $60 \cdot 3 = 180$.
The number of edges equals one half of that; so $|E| = 90$. The number of regions
can be computed using Euler's formula: $|V| - |E| + |R| = 2$ (in our case
$60 - 90 + |R| = 2$; therefore $|R| = 32$.

One example of such graph is {\em truncated icosahedron}, see \url{https://bit.ly/2WaSW6I},
but there may be many others that are not isomorphic to it. Still, all of them
would have the same number of regions due to Euler's formula.

\vspace{10pt}
{\bf Question 4} Answer: {\tt 9,17,10}\\
Number of vertices equals the size of the matrix $9 \times 9$,
so $|V| = 9$. The number of edges is one half of all the $1$s written
in the adjacency matrix; therefore $|E| = 17$. Since we can assume
that the graph $G$ is planar, it satisfies Euler's formula:
$$|V| - |E| + |R| = 2.$$
Therefore the number of regions $|R| = 10$.

Graph (shown without edge intersections as a planar graph) is visible
on Figure~\ref{fig:question4-graph}. In this picture we can simply count
vertices, edges and regions. But it is usually time-consuming to
create such pictures (and to verify that they match the adjacency matrix).

\begin{figure}[!htb]
\center{\includegraphics[width=1.5in]{quiz-11/question4-graph.png}}
\caption{\label{fig:question4-graph} A planar graph}
\end{figure}

\vspace{10pt}
{\bf Question 5} Answer: $34$\\
It is easy to build a path that visits all rooms except one.
There cannot be a circular path with exactly $35$ steps \textendash{}
one can use checkerboard pattern (color all cells in black and white).
Every step switches the color to the opposite; after exactly $35$ color switches
the color would be opposite \textendash{} the path cannot return back to cell $A$.

\vspace{10pt}
{\bf Question 6} Answer: $72$\\
We know that the sum of two sizes $|X| + |Y| = 17$,
and the maximum number of edges is $|X| \cdot |Y|$.
The greatest possible product of two numbers is
when they are closest to each other:
$8 \cdot 9 = 72$. (We can try out all combinations of two numbers
that add up to $17$ to see that this is the largest one.)

We can write the following algebraic inequalities:
$$|X| \cdot |Y| \leq \left( \frac{|X| + |Y|}{2} \right)^2,$$
$$4 |X| \cdot |Y| \leq \left( |X| + |Y| \right)^2,$$
$$4 |X| \cdot |Y| \leq |X|^2 + |Y|^2 + 2 |X| \cdot |Y|,$$
$$0 \leq |X|^2 + |Y|^2 = 2 |X| \cdot |Y| = (|X| + |Y|)^2.$$

From the first inequality we imply that $|X| \cdot |Y| \leq (17/2)^2 = 72.25$.
Since the number of edges cannot be fractional, $72$ is indeed the largest number.

\vspace{10pt}
{\bf Question 7} Answer: {\tt FTT}\\
{\bf (A)} False. No cubic graph can have odd number of vertices
(the sum of all degrees of all vertices should be even \textendash{} twice the number of edges).\\
{\bf (B)} True. $K_{3,3}$ is bipartite graph (it does not contain any ``triangles'': three vertices
that are all mutually connected). But the graph on Figure~\ref{fig:cubic-graph-6}
is not bipartite (so it is not isomorphic
to $K_{3,3}$.

\begin{figure}[!htb]
\center{\includegraphics[width=1in]{quiz-11/cubic-graph-6.png}}
\caption{\label{fig:cubic-graph-6} Cubic graph with 6 vertices.}
\end{figure}

{\bf (C)} True. You can draw a regular octagon and add all the long diagonals.
Now every vertex is adjacent with three vertices (both neighbors and the opposite one).

\vspace{10pt}
{\bf Question 8} Answer: {\tt FFT}\\
{\bf (A)} False. In a simple directed graph with $5$ vertices, an indegree
$5$ means that all vertices should point arrows to the given vertex (including the vertex itself).
But in this case there cannot be any vertices with outdegree $0$.\\
{\bf (B)} False. A graph with $8$ vertices of degree $3$ means that it has $\frac{8 \cdot 3}{2} = 12$ edges.
According to Euler's formula, the number of regions should be $R = 2 + E - V = 6$. Therefore
such a graph should have $6$ (not $5$) regions.\\
{\bf (C)} True. Such graph exists. For example Octahedron - see \url{https://bit.ly/3f1gnrG}.

\vspace{10pt}
{\bf Question 9} Answer: {\tt 8,9,5,7}

{\footnotesize
\begin{tabular}{|l|l|l|} \hline
Set $S$ & Weights of $\overline{S}$ & Added to $S$ \\ \hline
$\{ s \}$ & $w(t,x,y,z) = (10,\infty,5,\infty)$ & $y$ (min path $5$) \\  \hline
$\{ s,y \}$ & $w(t,x,z) = (8,\infty,7)$ & $z$ (min path $7$) \\ \hline
$\{ s,y,z \}$ & $w(t,x) = (8,9)$ & $t$ (min path $8$) \\ \hline
$\{ s,t,y,z \}$ & $w(x) = 9$ & $x$ (min path $9$) \\ \hline
\end{tabular}
}

\vspace{10pt}
{\bf Question 10} Answer: {\tt 211}\\
There are altogether $6$ vertices with odd degrees (one of them is $A$). If we start our travel in $A$
and end it in any other vertex with odd degree (say, in $G$), then there are
four more vertices with odd degrees. By adding edges $(C,H)$ and $(I,E)$ two times, we can
build the required path (each of these edges has weight $5$). Therefore the full length of the
path is the sum of all weights:
$$3 \cdot (12 + 12 + 12) + 3 \cdot (13 + 13 + 5) + (5 + 5).$$

\begin{figure}[!htb]
\center{\includegraphics[width=1.5in]{quiz-11/path-with-repetitions2.png}}
\caption{\label{fig:path-with-repetitions2} Path with Repetitions (Solved).}
\end{figure}

\vspace{10pt}
{\bf Question 11} Answer: {\tt "A,B,D"}, {\tt "A,B,F"},
{\tt "C,E,H"}, {\tt "C,G,H"}, {\tt "D,E,G"}\\
There are five ways to select the verticals (any one of them is correct).
Since the rooks (as edges linking horizontals with verticals) satisfy the Hall's Marriage theorem,
there exists a perfect matching: One can select $8$ rooks (out of the $24$) so that
each rook has its own horizontal and its own vertical. In other words, they do not attack each other.

We can start searching this perfect matching using ``backtracking'' \textendash{} first
try to pick the minimum possible horizontal in each vertical (avoiding any attacking position).
If this leads in a dead end, then start moving the rooks that have been placed last.
This very quickly leads to a solution (Figure~\ref{fig:rooks2}). There are also many other
perfect matchings.

\begin{figure}[!htb]
\center{\includegraphics[width=1.5in]{quiz-11/rooks2.png}}
\caption{\label{fig:rooks2} 8 selected rooks shown red}
\end{figure}

\end{document}