\documentclass[dissertation.tex]{subfiles}
\begin{document}
\chapter{Prerequisites}\label{cha:prerequisites}
\section{Splines and \bss}\label{sec:spline}
A \emph{spline} is a piecewise polynomial function with prescribed
regularity on its domain.

More formally we define a spline \cite{deboor}\cite{farin}\cite{salomon}\cite{bartels}
$$s:[a,b]\subset\mR\rightarrow\mR$$
as follows.
We have a partition of that interval defined by the \emph{breakpoints}
$$\tau = \{\tau_0,\dots,\tau_\ell\}$$
such that $a=\tau_0<\tau_1<\dots<\tau_{\ell-1}<\tau_\ell=b$. Such
breakpoints define $\ell$ intervals
$$
I_i=
\begin{cases}
  [\tau_i,\tau_{i+1}) & \mbox{if } i=0,\dots,\ell-2\\
    [\tau_i,\tau_{i+1}] & \mbox{if } i=\ell-1.\\
\end{cases}
$$
It is possible to define the following spaces:
\paragraph{Piecewise polynomial functions space} $P_{m,\tau}$
is the space of the functions that are polynomials of maximum degree $m$
in each interval $I_i$ of the partition, formally:
\begin{multline*}
  P_{m,\tau}=\{f:[a,b]\rightarrow\mR\ \mid\ \exists p_0\dots
  p_{\ell-1}\in\Pi_m \ \text{such that}\\
  f(t)=p(t),\ \forall t\in I_i,\
  i=0\dots \ell-1\}
\end{multline*}
where $\Pi_m$ is the space of the polynomials of degree $\le m$. The
dimension of $P_{m,\tau}$ is
\begin{equation*}
  dim(P_{m,\tau})=\ell(m+1)
\end{equation*}
because the dimension of $\Pi_m$
is $m+1$.
\paragraph{Classic spline space}\index{Classic splines} $S_{m,\tau}$ is the space of
the piecewise polynomial functions of degree $m$ that have continuity
$C^{m-1}$ in
the junctions of the intervals, formally:
$$
S_{m,\tau}=P_{m,\tau}\cap C^{m-1}[a,b].
$$
The dimension of this space is
\begin{equation}
  \label{eq:dimClassicSpline}
  \ell(m+1)-(\ell-1)\cdot m\,=\,\ell+m.
\end{equation}

\paragraph{Generalized spline space}\index{Generalized splines} $S_{m,\tau,M}$ is the
space of piecewise polynomial functions of degree $m$ with a prescribed
regularity at each breakpoint ranging from $-1$ to $m-1$. The
regularity is prescribed by the multiplicity vector
$$
M=\{m_1,\dots,m_{\ell-1}\},\quad m_i\in\mN,\quad 1\leq m_i\leq m+1
$$
as follows,
\begin{multline*}
  S_{m,\tau,M}=\{f:[a,b]\rightarrow\mR\ \mid\ \exists p_0\dots
  p_{\ell-1}\in\Pi_m \ \text{such that}\\
  f(t)=p(t),\ \forall t\in I_i,\
  i=0\dots \ell-1\ \text{and}\\
  p_{i-1}^{(j)}(\tau_i)=p_{i}^{(j)}(\tau_i),\ j=0,\dots,m-m_i,\ i=1,\dots,\ell-1\}.
\end{multline*}
The dimension of the space is equal to
\begin{equation*}
  dim(S_{m,\tau,M})=\ell(m+1)-\sum_{i=1}^{\ell-1}(m-m_i+1)=m+\mu +1\qquad(\mu=\sum_{i=1}^{\ell-1}m_i)
\end{equation*}

and is true that
$$
\Pi_m\subseteq S_{m,\tau}\subseteq S_{m,\tau,M}\subseteq P_{m,\tau},
$$
in particular:
\begin{itemize}
  \item if $m_i=1$ for all $i=1,\dots,\ell-1$, then
    $S_{m,\tau,M}=S_{m,\tau}$;
  \item if $m_i=m+1$ for all $i=1,\dots,\ell-1$, then
    $S_{m,\tau,M}=P_{m,\tau}$.
\end{itemize}

\subsection{Truncated-powers basis for classic
  splines}\label{sec:truncpow}\index{Classic splines!truncated-powers basis}
A truncated power $(t-\tau_i)_+^m$ is
defined by
$$
(t-\tau_i)_+^m=
\begin{cases}
  0,&\mbox{if}\quad t\leq\tau_i\\
  (t-\tau_i)^m, &\mbox{otherwise}.
\end{cases}
$$
It is possible to demonstrate that the functions
$$
g_i(t)=(t-\tau_i)_+^m)\ \in S_{m,\tau},\quad i=1,\dots,\ell-1
$$
are linearly independents, and that the set
$$
1,t,t^2,\dots,t^m,(t-\tau_1)_+^m,\dots,(t-\tau_{\ell-1})_+^m
$$
forms a basis for the classic spline space \cite{deboor}. Then a
generic element $s\in S_{m,\tau}$ can be expressed as follows,
\begin{equation}\label{eq:classicSplineElement}
  s(t)=\sum_{i=0}^m c_i t^i\, +\, \sum_{j=1}^{\ell-1} d_j
  (t-\tau_j)_+^m\qquad
  \begin{split}
    &c_i\in\mR,\ i=0,\dots,m\\
    &d_j\in\mR,\ j=1,\dots,\ell-1.
  \end{split}
\end{equation}

\subsection{\bss basis for classic
  splines}\label{sec:bsplines}\index{\bss}\index{Classic splines!\bss basis}
\emph{\bss} are a specific basis which can be alternatively used to
represent any generalized spline \cite{deboor}\cite{farin}\cite{salomon}\cite{bartels}. In this
paragraph, however, we consider only their definition to generate the
classic spline space $S_{m,\tau}$. Furthermore in some textbooks, for
notational convenience, the
\emph{order}$=m+1$ is considered.

For defining the \bss \cite{deboor} we need to extend the partition vector
$\tau=\{\tau_0,\cdots,\tau_\ell\}$ with $m$ knots to the left and $m$ to
the right, thus we define a new vector, usually called \emph{extended knot} vector,
$$
T=\{t_0,\dots,t_{m-1},t_{m},\dots,t_{n+1},t_{n+2},\dots,t_{n+m+1}\}
$$
such that
\begin{equation*}
  t_0\leq\dots\leq t_{m-1}\leq \overmath{\equiv\tau_0\equiv a}{t_{m}}<\dots<\overmath{\equiv\tau_\ell\equiv b}{t_{n+1}}\leq t_{n+2}\leq\dots\leq t_{n+m+1}.
\end{equation*}
Since $\tau$ has $\ell+1$ elements, we can calculate the value of
$$
n=\ell+m-1.
$$
Thus the dimension of $S_{m,\tau}$, for
\cref{eq:dimClassicSpline}, is
\begin{equation*}
  dim(S_{m,\tau})=\ell+m=n+1
\end{equation*}

The $n+1$ basis $N_{i,m+1}(t)$ of the \bss of degree $m$ are defined,
for $i=0,\dots,n$, by the recursive formula:
\begin{align*}
  N_{i,1}(t) &=
  \begin{cases}
    1,\quad \mbox{if}\quad t_i\leq t<t_{i+1}\\
    0,\quad \mbox{otherwise}\qquad\qquad\qquad i=0,\dots,n+m
  \end{cases}\\
  N_{i,r}(t) &= \omega_{i,r-1}(t)\cdot N_{i,r-1}(t)\ +\
  (1-\omega_{i+1,r-1}(t))\cdot N_{i+1,r-1}(t)\\
             &\pushright i=0,\dots,n+m+1-3,\ r=2,\dots,m+1
\end{align*}
where
$$
\omega_{i,r}(t) = \begin{cases}
  \frac{t-t_i}{t_{i+r}-t_i},&\mbox{if }t_i\neq t_{i+r}\\
  0, &\mbox{otherwise.}
\end{cases}
$$

Then any function $s\in S_{m,\tau}$ can be expressed also as a linear
combination of \bss,
\begin{equation}\label{eq:bsplineElement}
  s(t)=\sum_{i=0}^nv_i N_{i,m+1}(t)\qquad, v_i\in\mR, i=0,\dots,n.
\end{equation}

\subsection{Spline curves}\index{Spline curves}
A \emph{spline curve} in the affine space $\mE^d$ is the image of a
parametric vector function $\ve{S}:[a,b]\rightarrow\mE^d$ whose
components are all splines belonging to a fixed spline space
$S_{m,\tau}$, for $d=3$
\begin{equation}\label{eq:bsplineCurveComp}
  \ve{S}(u) = \left[
    \begin{array}{c}
      \ve{x}(u)\\
      \ve{y}(u)\\
      \ve{z}(u)
    \end{array}
    \right].
\end{equation}

$\ve{S}(u)$ can be written as follows in the
truncated-powers basis
% A parametric spline \emph{curve} $\ve{S}(t)$ is a curve in a certain
% dimension obtained applying a spline function to a set of points
% in the same dimension
% called \emph{control vertices}. We can apply the control vertices to a
% spline expressed with the truncated powers as in
\cref{eq:classicSplineElement} replacing the coefficients $c_i$ and
$d_i$ with points
\begin{equation}\label{eq:classicSplineCurve}
  \begin{multlined}
  \ve{S}(u)=\sum_{i=0}^m \ve{c_i}\cdot t^i\, +\, \sum_{j=1}^{\ell-1}
  \ve{d_j}\cdot (u-\tau_j)_+^m\qquad,\ve{c_i}\in\mE^d,\
  \ve{d_j}\in\mE^d\\
  i=0,\dots,m;\ j=0,\dots,\ell-1.
  \end{multlined}
\end{equation}

This representation is not practical because
there isn't an intuitive correlation between the points
$\ve{c_i}$, $\ve{d_j}$ and the curve itself. Moreover the
determination of an interpolant to assess argued points in $\mE^d$
is not a well conditioned problem if this form is adopted
\cite{deboor}. To overcome those drawbacks the \emph{\bss
  basis} is adopted (\cref{sec:bsplines}).

We can apply control vertices to a spline expressed with the \bs
basis as in \cref{eq:bsplineElement} replacing the coefficients $v_i$
with points, in this case $\ve{S}(u)$ is represented as follows
\begin{equation}\label{eq:bsplineCurve}
  \ve{S}(u)=\sum_{i=0}^n\ve{v_i}\cdot N_{i,m+1}(u)\qquad
  ,\ve{v_i}\in\mE^d,\ i=0,\dots,n.
\end{equation}
The representation of \cref{eq:bsplineCurve} is more convenient
than the previous one (\cref{eq:classicSplineCurve}) because the curve
$\ve{S}(u)$ roughly
follows the shape given by the points $\ve{v_i}$. Those points are
called \emph{control vertices} because they are used to control the
curve shape. Conformally the polygon they define is called \emph{control polygon}.

\section{\bss curves properties}\label{sec:bsplineProp}\index{\bss!properties}
In this section we describe some properties of \bs curves that we
use for the development of the project.

\subsection{\acf{CHP}}\label{sec:convexHull}\index{\bss!\acf{CHP}}
The \acf{CHP} states that a \bs curve $\ve{S}(u)$ of order $m$,
defined by the control polygon
$\ve{v_0},\ve{v_1},\dots,\ve{v_n}$, is contained inside the union of the
convex hulls composed of $m+1$ vertices of the control polygon
\cite{farin}. If we
call $\conv(\ve{w_0},\ve{w_1},\dots,\ve{w_j})$ the convex hull of the
vertices $\ve{w_0},\ve{w_1},\dots,\ve{w_j}$ then we have
\begin{eqnarray*}
  C_0&=&\conv(\ve{v_0},\ve{v_1},\dots,\ve{v_{m}})\\
  C_1&=&\conv(\ve{v_1},\ve{v_2},\dots,\ve{v_{m+1}})\\
  &\cdots&\\
  C_{n-m}&=&\conv(\ve{v_{n-m}},\ve{v_{n-m+1}},\dots,\ve{v_{n}})\\
\end{eqnarray*}
and the area where $\ve{S}$ is contained is
\begin{equation*}
  C=C_0\cup C_1\cup\dots\cup C_{n-m}
\end{equation*}
or in other words must be true
\begin{equation*}
  \ve{S}(u)\cap C =\ve{S}(u)\qquad \forall u\in[a,b]
\end{equation*}
whatever is the partition vector.

\begin{myfig}{Convex hull containing \bs of degree 2}{fig:convexHull}
  \begin{tikzpicture}
    \coordinate (a) at (0,0);
    \coordinate (b) at (0.5,1.7);
    \coordinate (c) at (2,3);
    \coordinate (d) at (4,3);
    \coordinate (e) at (5.5,1.7);
    \coordinate (f) at (6,0);

    \path[convexHull] (a) -- (b) -- (c) -- (a);
    \path[convexHull] (b) -- (c) -- (d) -- (b);
    \path[convexHull] (c) -- (d) -- (e) -- (c);
    \path[convexHull] (d) -- (e) -- (f) -- (d);

    \draw[convexHullBord] (a) -- (c);
    \draw[convexHullBord] (b) -- (d);
    \draw[convexHullBord] (c) -- (e);
    \draw[convexHullBord] (d) -- (f);

    \draw[controlPoly] (a) -- (b) -- (c) -- (d) -- (e) -- (f);
    \foreach \p in {a,b,c,d,e,f}
    \filldraw[controlVert] (\p) circle (2pt);

    \node[above left] at (a) {$\ve{v_0}$};
    \node[above left] at (b) {$\ve{v_1}$};
    \node[above] at (c) {$\ve{v_2}$};
    \node[above] at (d) {$\ve{v_3}$};
    \node[above right] at (e) {$\ve{v_4}$};
    \node[above right] at (f) {$\ve{v_5}$};
  \end{tikzpicture}
\end{myfig}
In \cref{fig:convexHull} an example of control polygon is visible,
together with the region $C$ (in cyan) where an associated quadratic
\bs curve is located.

Note that the \ac{CHP} holds also in
3-dimensional
space - i.e. a quadratic \bs in 3-dimensional space is contained
inside a flat surface composed by the union of triangles. From degree 3
the area where $\ve{S}$ is contained is not plane anymore
because it is composed by the union of solid polyhedrons.

\subsection{Aligned vertices}\index{\bss!aligned vertices}\label{sec:alignedVertices}
Because control polygons with sequences of
aligned vertices have been adopted in some parts of this project, in
this section their specific
effect on the curve shape is analyzed.

We can have the following situations:
\paragraph{$m$ aligned control vertices}
If $m$ control vertices $v_i,\dots,v_{i+m-1}$ of the control polygon
are on the same line then
the curve $\ve{S}$ touches the segment joining those vertices.

\paragraph{$m+1$ aligned control vertices}
If $m+1$ control vertices $v_i,\dots,v_{i+m}$ of the control polygon
are on the same line then a polynomial arc of the curve $\ve{S}$
lays on the segment joining those vertices.

\subsection{Smoothness}\label{sec:smoothness}\index{Smoothness}\index{\bss!smoothness}
A function is said smooth of class $C^d$ if it is possible to
calculate the $d$-th derivative of it and if such derivative is
continue. A function $f$ that is not continue is said to be of class
$C^{-1}$, a function that is continue until derivative $d$ is said to
be of class $C^d$, a function that is always continue for every
derivative is said to be of class $C^\infty$.

A \bs curve of degree $m$ with $n$ control vertices is composed by
$n-m$ polynomial segments, one for each
interval
\begin{equation*}
[t_i,t_{i+1}]\qquad i=m,\dots,n+1;
\end{equation*}
this means that $\ve{S}(u)$ is $C^\infty$ for
\begin{equation*}
u\in(t_i,t_{i+1})\qquad i=m,\dots,n+1.
\end{equation*}
Note that, if we use generalized \bs curves, an interval
$[t_i,t_{i+1}]$ can also degenerate in just a point if
we have a knot multiplicity $>1$, in
such case there isn't a polynomial segment.
On every breakpoint $\tau_i$ with $i=1,\dots,n+m$ we have that the curve has
smoothness\footnote{If we use generalized \bs curves, it has
  smoothness $C^{m-r}$ where $r$ is the
multiplicity of the knot \cite{farin}.} $C^{m-1}$.

In our project we don't use generalized \bs curves, thus a
curve of degree $m$ has global smoothness
\begin{equation*}
  C^{m-1}.
\end{equation*}

\subsection{End point interpolation}\index{\bss!end point interpolation}\label{sec:clamped}
In general a \bs curve with control vertices
\begin{equation*}
  \ve{v_0}, \dots, \ve{v_n}
\end{equation*}
and extended knot vector
\begin{equation*}
  T=\{t_0,\dots,t_{m-1},t_{m},\dots,t_{n+1},t_{n+2},\dots,t_{n+m+1}\}
\end{equation*}
does not necessarily interpolate any control vertex $v_i$, neither the
first nor the last one. But we are
interested in using \bs for representing paths from one point to
another. Hence, it should be a nice feature to have that the curve defined in
the domain $[a,b]$ is shaped such that
\begin{equation}\label{eq:clamped}
  \begin{cases}
    \ve{S}(u)=\ve{v_0}& \text{for } u=a\\
    \ve{S}(u)=\ve{v_n}& \text{for } u=b.
  \end{cases}
\end{equation}

We can obtain \cite{deboor} the conditions of \cref{eq:clamped} if we
impose
\begin{equation*}
  t_0=\dots= t_{m-1}= \overmath{\equiv a}{t_{m}}<\dots<
\overmath{\equiv b}{t_{n+1}}= t_{n+2}=\dots= t_{n+m+1}
\end{equation*}
on the extended partition vector $T$. In other words
\begin{equation*}
  T=\{\overbrace{a,\dots,a}^m,t_{m+1},\dots,t_{n},\overbrace{b,\dots,b}^m\}.
\end{equation*}

\subsection{Curvature and torsion}\index{Curvature and torsion}\index{\bss!curvature and torsion}
Since we are interested in comparing different curves,
we need to recognize if a certain curve is a \emph{good} or a
\emph{bad} one. One factor that characterizes a certain curve can
be its smoothness (\cref{sec:smoothness}) - i.e. a $C^3$ curve
is better than a $C^2$ curve - but this isn't
enough for comparing curves. Usually
\emph{curvature} and
\emph{torsion} are used for this purpose
\cite{docarmo}\cite{salomon}. Both are scalar quantities defined on
sufficiently smooth
parametric curves for each value of the parameter, and they do not
depend on the selected parametrization.

For a generic parametric curve\footnote{\label{ftn:genericParCur}Thus
  also a \bs curve.} $\ve{S}(u)$ defined for $u\in[a,b]$
given the notation $\wedge$ for the vector product and for \cref{eq:bsplineCurveComp}
\begin{equation*}
  \dot{\ve{S}}(u) = \frac{\md}{\md u} \ve{S}(u)=\left[
    \begin{array}{c}
      \frac{\md}{\md u} \ve{x}(u)\\
      \frac{\md}{\md u} \ve{y}(u)\\
      \frac{\md}{\md u} \ve{z}(u)
    \end{array}
    \right],
\end{equation*}
we define the
curvature $\kappa(u)$ and, in points with non vanishing curvature,
the torsion $\tau(u)$ as
\begin{empheq}[left={=\empheqbiglbrace~}]{align}
  \kappa(u) &= \frac{\norm{\dot{\ve{S}}(u)\wedge\ddot{\ve{S}}(u)}}{{\norm{\dot{\ve{S}}(u)}}^3}  \label{eq:curvature}\\
  \tau(u) &= \frac{\det\left[\dot{\ve{S}}(u),\ddot{\ve{S}}(u),\dddot{\ve{S}}(u)\right]}{\norm{\dot{\ve{S}}(u)\wedge\ddot{\ve{S}}(u)}} = \frac{\left(\dot{\ve{S}}(u)\wedge\ddot{\ve{S}}(u)\right)\cdot\dddot{\ve{S}}(u)}{\norm{\dot{\ve{S}}(u)\wedge\ddot{\ve{S}}(u)}}.  \label{eq:torsion}
\end{empheq}

\Cref{eq:curvature} and \cref{eq:torsion} describe completely the
behavior of $\ve{S}(u)$ locally for each value of $u$. Curvature and
torsion have also a geometric interpretation: for each value $\tilde{u}$ of
the parameter $u$, the inverse $\frac{1}{\kappa(\tilde{u})}$ of the
curvature is the radius of curvature of $\ve{S}$ at
$\ve{S}(\tilde{u})$ - i.e. the radius of the
osculating circle tangent in that point. $\tau(\tilde{u})$ indicates
(if $\kappa(\tilde{u})\neq 0$) how sharply the plane where
the curve lies is rotating.

The value of $\kappa(u)$ can be only non negative, while $\tau(u)$ is
a signed quantity.

Two curves of same smoothness can be compared using the plots of
curvature and torsion, in general curves that have lower peaks of
$\kappa(u)$ and $\tau(u)$ are better than curves with
higher peaks.

\subsection{Arc length}\index{Arc length}\index{\bss!arc length}
Sometimes we are interested in evaluating the length of a generic
parametric curve\footnote{See \cref{ftn:genericParCur}.} $\ve{S}(u)$
defined for $u\in[a,b]$. We can obtain such length, called \emph{arc
  length}, calculating the integral
\begin{equation*}
  \int_a^b\norm{\dot{\ve{S}}(u)}\md u.
\end{equation*}

We can approximate this value using a discrete tabulation of the curve
$\ve{S}(u)$ and an integrating method like the \emph{trapezoidal
  rule} \cite{press}\cite{stoer}.

\section{Voronoi Diagrams}\label{sec:voronoi}\index{\acfp{VD}}
In this section we introduce \acfp{VD}, an important structure used in
the project. \acp{VD} \cite{deberg} provide a method to create a
partition of the
space using distances from a set of input points called
\emph{sites}. Formally we have a set
\begin{equation*}
  S=\{\ve{s_0},\ve{s_1},\dots,\ve{s_n}\} \subset \mE^d
\end{equation*}
of $n$ sites in the euclidean space of dimension $d$, and we build a
set of $n$ Voronoi \emph{cells}\footnote{$2^{\mE^d}$ is the power set of
  $\mE^d$, the set of all the subsets of $\mE^d$.}
\begin{equation*}
  Vor(S)=\{V(\ve{s_0}),\dots,V(\ve{s_n})\}\subset 2^{\mE^d}
\end{equation*}
such that
\begin{equation*}
  V(\ve{\ve{s_i}})=\{\ve{p}\in\mE^d\ :\
  \norm{\ve{p}-\ve{s_i}}<\norm{\ve{p}-\ve{s_j}}\ \forall \ve{s_j}\neq\ve{s_i}\}
\end{equation*}
is the set of the points in $\mE^d$ closer to $\ve{s_i}$ than to any
other site.

\image{voronoi.eps}{Example of a \ac{VD}, dashed lines are infinite edges.}{fig:voronoi}
\Cref{fig:voronoi} is an example of the \ac{VD} built on some random
sites, the dashed lines in the figure are edges that go to infinite.

\image{fortune.png}{Fortune's algorithm execution}{fig:fortune}
\index{Fortune's algorithm}The most important algorithm for
calculating \acp{VD} is the \emph{Fortune's}
\emph{sweeping line} algorithm that builds the diagram in $\bigO(n\log
n)$ and it is optimal. The algorithm involves building $Vor(S)$
incrementally while sweeping the space, see \cref{fig:fortune}. Every
time that the sweeping
line finds a site the algorithm creates a parabola using the site as
focus and the sweeping line as directrix. Such parabolas, or better
the arcs between each intersection of them, constitute
the \emph{beach line}. A parabola disappears from the scene when the
associated
arc vanishes. The evolution of the intersection points on the beach line
constitutes the edges of the \ac{VD}, and each point where an arc of
the beach line disappears constitutes a vertex of the \ac{VD}.
Refer to \cite{deberg} and
\cite{fortune} for details about the Fortune's algorithm.

One property of \acp{VD} is that $V(\ve{s_i})$ can be a closed or an
open area - i.e. the edges of the cells can be infinite - it is important
to keep this in mind if we want to interpret $Vor(S)$ as a graph. In
that case the graph will have edges that go to infinite. We call such
graph $G(Vor(S))$.

Another property is that, if we have $d+1$ sites $\ve{s_0'},\dots,\ve{s_d'}$ that lay on the
surface of a $(d-1)$-sphere\footnote{A circumference in $2$-dimensional
  space, a sphere in $3$-dimensional space, an hypersphere in
  $n$-dimensional space with $n\ge 3$.} that does not have any other site on
the interior, then the center point of the $(d-1)$-sphere is the
vertex shared only between the $d+1$ cells
$V(\ve{s_0'}),\dots,V(\ve{s_d'})$ \cite{deberg}. This is not true for
less than
$d+1$ sites on a
$(d-1)$-sphere because they are not enough to define it univocally,
but is possible to have $n>d+1$ sites on a $(d-1)$-sphere. In that
case, the center of the $(d-1)$-sphere is the shared vertex of the
cells corresponding to the $n$ sites. This is important to reason
about the topography of $G(Vor(S))$ because if we allow more than
$d+1$ sites on a $(d-1)$-sphere then the maximum degree
$\Delta(G(Vor(S)))$ of the graph can be arbitrarily big (up to the
number of vertices). However, the fact that we work with coordinates in
$\mE^d$ legitimizes the restriction\footnote{We can also relax this
  restriction and in case create multiple nodes connected by zero-distance
  edges on the graph.} of not
allowing more than $d+1$ sites on an $(d-1)$-sphere, limiting
$\Delta(G(Vor(S)))$ to $d+1$.

\section{Statistical methods}\label{sec:statisticalMethods}
In this section we briefly introduce the \acf{MCM}
\cite{metropolis}\cite{sobol}\cite{newman} and the \acf{SA} \cite{kirkpatrick}\cite{ho},
two statistical methods to calculate unknown quantities and to find
functions minima. Additionally, we introduce \acf{LR} \cite{benjamin}, a
method to transform a constrained optimization problem in an
unconstrained one by increasing the state space
dimension.
\subsection{Notes on probabilities}
\subsubsection{\ac{PE}}\index{\acf{PE}}
For a random variable $X$ normally distributed with
\begin{itemize}
\item mean $\mu$;
\item variance $\sigma$;
\end{itemize}
for
\begin{equation*}
  r=0.6745\sigma
\end{equation*}
we have that
\begin{equation*}
  \prob{\abs{X-\mu}<r} = \prob{\abs{X-\mu}>r} = 0.5.
\end{equation*}
Thus values of $X$ that deviate from $\mu$ less or more than $r$ have the
same probability, and $r$ identifies the most \ac{PE} in a
normal distribution.
\subsubsection{\acf{PCLT}}\index{\acf{PCLT}}
Consider $N$ independent and \emph{identically-distributed} random variables
$X_1,X_2,\dots,X_N$, with same mean and same variance
\begin{eqnarray*}
  \expected{X_1}=\expected{X_2}=\dots=\expected{X_N}&=&m\\
  \variance{X_1}=\variance{X_2}=\dots=\variance{X_N}&=&b^2.
\end{eqnarray*}

Consider the sum of those random variables:
\begin{equation*}
  Y = X_1+X_2+\cdots+X_N;
\end{equation*}
we have that
\begin{eqnarray*}
  \expected{Y}&=&\expected{X_1+X_2+\cdots+X_N}=Nm\\
  \variance{Y}&=&\variance{X_1+X_2+\cdots+X_N}=Nb^2.
\end{eqnarray*}

Consider a normally distributed random variable $Z$ with
parameters:
\begin{eqnarray*}
  \mu&=&Nm\\
  \sigma&=&b\sqrt{N}
\end{eqnarray*}
with \ac{PDF} $p_Z(x)$.

The \emph{\ac{PCLT}} affirms that, for $N$ big
enough, and for every interval $(x_1,x_2)$, applies:
\begin{equation}\label{eq:tcl}
  \prob{x_1<Y<x_2}\approx\int_{x_1}^{x_2}p_Z(x) \md x.
\end{equation}
Thus, the sum of an elevate number of identically-distributed random
variables is a random variable with normal distribution with mean $Nm$
and variance $Nb^2$, even if
$X_1,X_2,\dots,X_N$ aren't normally distributed.

\subsection{\acf{MCM}}\index{\acf{MCM}}
If we suppose to calculate an unknown quantity $m$, we need
to find a random variable $X$ such that:
\begin{equation*}
  \expected{X} = m.
\end{equation*}
If we have such distribution with variance:
\begin{equation*}
  \variance{X} = b^2
\end{equation*}
it is possible to formalize the following passages.

Consider $N$ random variables $X_1,X_2,\dots,X_N$ that have
distribution identical to the distribution of $X$. For the \ac{PCLT}
\cref{eq:tcl} we have that, for $N$ big enough
\begin{equation*}
  Y=X_1+X_2+\cdots+X_N
\end{equation*}
is normally distributed with parameters
\begin{eqnarray*}
  \mu &=& Nm\\
  \sigma&=&b\sqrt{N}.
\end{eqnarray*}

For the \emph{three sigma rule} \cite{pukelsheim} we have that:
\begin{equation*}
  \prob{\mu-3\sigma < Y <\mu +3\sigma}\approx 0.997
\end{equation*}
that is
\begin{equation*}
  \prob{Nm-3b\sqrt{N} < Y < Nm+3b\sqrt{N}}\approx 0.997
\end{equation*}
dividing by $N$
\begin{equation*}
  \prob{m-\frac{3b}{\sqrt{N}} < \frac{Y}{N} <
    m+\frac{3b}{\sqrt{N}}}\approx 0.997
\end{equation*}
that is
\begin{equation*}
  \prob{\abs{\frac{Y}{N}-m} <\frac{3b}{\sqrt{N}}}\approx 0.997
\end{equation*}
results in
\begin{equation}\label{eq:mc}
  \prob{\abs{\frac{1}{N}\sum_{i=1}^NX_i-m} <\frac{3b}{\sqrt{N}}}\approx 0.997.
\end{equation}

\Cref{eq:mc} asserts that, if we extract a sample for each random
variable $X_i$, the arithmetic mean of those values is approximately
equal to $m$. Moreover, the error of such approximation is equal to
$3b/\sqrt{N}$, that tend to $0$ increasing $N$. It is also possible to
further
reduce the uncertainty ($1-0.997=0.003$) by increasing the number $k$ of
sigma used for the
approximation and evaluating the error $kb/\sqrt{N}$.

In practice, since the random variables $X_i$ have the same
distribution of $X$, it is sufficient to extract $N$ samples from $X$ to
reach the same conclusions.

The \acf{MCM} is constituted by the following procedure, to be adapted
according to the problems:
\begin{enumerate}
\item find the distribution $X$ having desired quantity $m$ as mean
  value and $b^2$ as variance;
\item extract $N$ samples from $X$, with $N$ big enough to have an
  error as small as desired;
\item the arithmetic mean of those $N$ samples is the approximation of
  the desired value $m$.
\end{enumerate}
Essentially, we transforme the problem from \emph{calculating $m$} to
\emph{finding
  the distribution $X$}, or anyway the $N$ samples distributed
accordingly to $X$.

If we want to characterize more in detail the error committed taking
$N$ samples, we can use to \ac{PE}. If we set $k=0.6745$ then we
have that
\begin{equation*}
  \prob{\abs{\frac{1}{N}\sum_{i=1}^NX_i-m} <\frac{0.6745\cdot b}{\sqrt{N}}}\approx 0.5
\end{equation*}
and so
\begin{equation*}
  r_N = \frac{0.6745\cdot b}{\sqrt{N}}
\end{equation*}
indicates how much the value $\frac{1}{N}\sum_{i=1}^NX_i$ deviates
from the desired value $m$. Such value characterize the absolute error
\begin{equation*}
\abs{\frac{1}{N}\sum_{i=1}^NX_i-m}
\end{equation*}
committed taking $N$ samples.

\ac{MCM} is useful to simulate events that have an high degree of
uncertainty in the inputs or an high degree of liberty in the
state: for instance, numerically integrate a function with many
dimensions or \acf{SA} (\cref{sec:simulatedAnnealing}).

\subsection{\acf{SA}}\label{sec:simulatedAnnealing}\index{\acf{SA}}
The \ac{SA} is a method used to find the global maximum or
minimum of a function. It is inspired by a method
used in metallurgy that consists in heating and then cooling slowly a
material to increase the size of the crystals and improving
the chemico-physical properties. The function that must be optimized
can be
defined in a multiple-dimensional space.

\subsubsection{Statistical thermodynamic}
To describe the basic principles of statistical thermodynamic we
consider the following example. In a one-dimensional lattice every point
is a particle with a value of spin that can be \emph{up} or
\emph{down}. If the lattice has $N$ points then the system can be in
$2^N$ different configurations, where each one of those configurations
corresponds to a value of energy, for instance:
\begin{equation*}
  E=B(n_+-n_-)
\end{equation*}
where $B$ is some constant, $n_+$ is the number of particles with spin
\emph{up} and $n_-$ is the number of particles with spin \emph{down}.

The probability $B(\sigma)$ of finding the system in a certain
configuration $\sigma$ is given by the distribution of
\emph{Boltzmann-Gibbs}:
\begin{equation}\label{eq:distBoltz}
  P(\sigma) = C \me^{-E_\sigma/T}
\end{equation}
where $E_\sigma$ is the energy of the configuration, $T$ is the
temperature\footnote{The real Boltzmann-Gibbs distribution is
  $P(\sigma) = C \me^{-E_\sigma/kT}$ where $k$ is the \emph{Boltzmann
    constant} and $T$ is the thermodynamic temperature, but for the
  example the temperature is a parameter not correlated to the
  physical world, thus it is possible to ignore $k$.} and $C$ is a
normalization constant.

The average energy of the system is then:
\begin{eqnarray*}
  \bar{E} &=& \frac{\sum_\sigma E_\sigma P(\sigma)}{\sum_\sigma
    P(\sigma)}\\
  &=& \frac{\sum_\sigma E_\sigma \me^{-E_\sigma/T}}{\sum_\sigma \me^{-E_\sigma/T}}.
\end{eqnarray*}
The computation of the value of $\bar{E}$ can be difficult with an
high number of
states, but it is possible to create a \ac{MCM} simulating the random
fluctuation between the states such that the distribution given by
\cref{eq:distBoltz} is respected. Starting from an arbitrary initial
configuration, after a certain number of \emph{Monte Carlo trials},
the method converges to the equilibrium status $\bar{E}$ and it
continues
to fluctuate around it. \ac{SA} is a method of this kind.

\subsubsection{\acf{SA} algorithm}\index{\acf{SA}!algorithm}
\ac{SA} operates on a system starting from a certain initial state
$s_0$, then it executes a series of iterations where a
neighbour of the state is evaluated and, with a certain distribution
of probability, the system is moved in the new state or not.

A possible algorithm for a \ac{SA} method is \cref{alg:sa}. $s_0$ is
the initial state; $temp$ is the function that assigns a
temperature based on the current iteration number such that for low
$k$ the returned temperature is high and for high $k$ the returned temperature
is low; $neighbour$ is the function that returns a random neighbour of
the current state; $uniform$ returns an uniformly-randomly chosen
number in $[0,1]$; $P_a$ is the distribution of accepting probability
that depends on the energy of the current state, on the energy of the
neighbour, and on the current temperature. In case of acceptance, the
neighbour becomes the current state and the process continues.

\begin{algo}{\acf{SA}}{alg:sa}
  \Function{anneal}{$s_0$}
  \State $s\Ass s_0$
  \For{$k\Ass 0,kMax$}
  \State $T\Ass temp(\frac{k}{kMax})$
  \State $sNew\Ass neighbour(s)$
  \If{$uniform(0,1)<P_a(E(s), E(sNew), T)$}
  \State $s\Ass sNew$
  \EndIf
  \EndFor
  \State\Return $s$
  \EndFunction
\end{algo}
The relation with the statistical thermodynamic is that $P_a$ is chosen
such that
\cref{eq:distBoltz} holds\footnote{A similar distribution is enough.},
moreover $temp$ returns decreasing values of
temperature with the succession of iterations. This explains the
comparison with the metallurgy annealing.

Initially $P_a$ was chosen such that
\begin{equation*}
  P_a(E(s), E(sNew), T)=
  \begin{cases}
    1,& \text{if }E(sNew)<E(s)\\
    \me^{-(E(sNew)-E(s))/T},& \text{otherwise}
  \end{cases}
\end{equation*}
but this isn't strictly necessary to develop a \ac{SA} method.

\subsection{\acf{LR}}\label{sec:lagrangianRelaxation}\index{\acl{LR}}
A general constrained discrete optimization problem can be expressed in
the form:
\begin{equation}\label[problem]{eq:opt}
\begin{aligned}
& \underset{x}{\text{minimize}}
& & f(x) \\
& \text{subject to}
& & g(x)=0
\end{aligned}
\end{equation}
where $x\in X$ is the state of the system in a discrete space $X$, $f(x)$
is the function to
minimize, and $g(x)=0$ is the constraint. The functions can also be
in a multidimensional discrete space, in that case the $x$ is a vector
$\ve{x}=(x_1,\dots,x_n)$ of variables.

To solve this class
of problems a \emph{Lagrange relaxation} method can be used
\cite{bertsekas}: it expands
the variable space $X$ by a \emph{Lagrange multiplier} space
$\Lambda$, equal in dimension to the number of constraints - one in the
\cref{eq:opt}.

The \emph{generalized discrete Lagrangian
  function}, corresponding to the \cref{eq:opt}, is:
\begin{equation}\label{eq:lagrangianFun}
  L_d(x,\lambda)=f(x)+\lambda H(g(x))
\end{equation}
where $\lambda$ is a variable in $\Lambda$; if the dimension of
$\Lambda$ is more than one $\lambda$, it must be transposed in
~\cref{eq:lagrangianFun}. $H(x)$ is a non negative function
with the property that $H(0)=0$ and aimed to transform g in a non
negative function. For instance, it can be  $H(g(x))=|g(x)|$ or
$H(g(x))=g^2(x)$.

Under the previous assumptions, the set of \emph{local minima}
in \cref{eq:opt} - that respect the constraints -  coincides
with the set of \emph{discrete saddle point}
in the augmented space. A point $(x^*,\lambda^*)$ is a discrete saddle
point if:
\begin{equation*}
  L_d(x^*,\lambda)\leq L_d(x^*,\lambda^*)\leq L_d(x,\lambda^*)
\end{equation*}
for all $x\in\mathcal{N}(x^*)$ and for all $\lambda\in\Lambda$, where
$\mathcal{N}(x^*)$ is the set of all $x^*$'s neighbours.

To solve the optimization \cref{eq:opt} it is necessary to calculate,
among the saddle points, the global minimum for $f$. We can use an
optimization method, like \ac{SA}, that descends in $X$ and ascends in
$\Lambda$.

\section{Intersections in space}\label{sec:intersections}\index{3D geometry}
We work in a spatial environment with polyhedral obstacles. Thus, in
order to define admissible paths, first of all we need routines
performing the following three basic geometric tasks:
\begin{enumerate}
\item establish if a point is in or out
  of a convex polyhedron;
\item \label[task]{tsk:segmentTriangle}check if a segment intersects a triangle;
\item establish whether two triangles intersect.
\end{enumerate}

In the project we need to consider three kinds of collision detection
methods in 3-dimension euclidean space.

\subsection{Point inside convex polyhedron in 3D space}\index{3D
  geometry!point inside polyhedron}
To test if a point $\ve{p}$ is inside a convex polyhedron $V$ with
vertices $\ve{v_1},\ve{v_2},\dots,\ve{v_n}$, we use a method that rely
on convex hulls \cite{deberg}\cite{schneider}.

\begin{algo}{Check if point $\ve{p}$ is inside convex polyhedron $V$}{alg:pointInPoly}
  \Function{isPointInPolyhedron}{$\ve{p}$, $V$}
  \State $inside\Ass\True$
  \State $C\Ass convexHullVertices([\ve{p},\ve{v_1},\ve{v_2},\dots,\ve{v_n}])$
  \ForAll{$\ve{c}\in C$}\label{ln:pointInPolyFor}
  \If{$c=p$}
  \State $inside\Ass\False$
  \State \Break
  \EndIf
  \EndFor
  \State\Return $inside$
  \EndFunction
\end{algo}
\Cref{alg:pointInPoly} performs the first task. It first
computes the vertices of the convex hull of all
the vertices of $V$ plus the point $\ve{p}$ and then checks if
$\ve{p}$ is one
of them or not. If $\ve{p}$ is on the convex hull that
means that $\ve{p}$ is external\footnote{Or $\ve{p}$ coincides with a
  vertex of $V$.} to $V$ because we have extended the convex hull
formed by the vertices of $V$. Otherwise this means that $\ve{p}$ is
inside $V$.

The cost of this algorithm is
\begin{equation*}
  \bigO(n\log n)
\end{equation*}
where $n$ is the number of vertices of $V$, because the cost to
construct the convex hull is \cite{deberg} $\bigO(n\log n)$, and
then we have another negligible term $\bigO(n)$ for the cycle on
\cref{ln:pointInPolyFor}.

\subsection{Segment-triangle in 3D space}\label{sec:intersectionST}\index{3D
  geometry!segment-triangle intersection}\index{intersections!segment-triangle}
We need to deal with the intersection between a segment
$S=\overline{\ve{a_2}\ve{b_2}}$ and a triangle
$T=\triangle\ve{a_1}\ve{b_1}\ve{c_1}$. $S$ and $T$ can be in one of
the following cases also summarized in \cref{tab:intersectSegmentTriang}:
\begin{enumerate}[label=\textbf{case \arabic*}]
\item\label[void]{en:ist:nc:ni} $S$ and $T$ do not intersect and the plane containing
  $T$ is not in the sheaf of planes generated by the line
  containing $S$;
\item\label[void]{en:ist:c:ni} $S$ and $T$ do not intersect and the plane containing
  $T$ is in the sheaf of planes generated by the line
  containing $S$;
\item\label[void]{en:ist:nc:i} $S$ and $T$ intersect only at one point and the plane containing
  $T$ is not in the sheaf of planes generated by the line
  containing $S$;
\item\label[void]{en:ist:c:i} $S$ and $T$ intersect in one or infinite points and the plane
  containing $T$ is in the sheaf of planes generated by the line
  containing $S$.
\end{enumerate}
The discriminating factors among the cases are two: the presence of intersection
and coplanarity.
\cref{tab:intersectSegmentTriang}.
\begin{table}
  \centering
  \begin{tabular}{l|cc}
    &not coplanar&coplanar\\
    \hline
    not intersect& \cref{en:ist:nc:ni} & \cref{en:ist:c:ni}\\
    intersect& \cref{en:ist:nc:i} & \cref{en:ist:c:i}\\
  \end{tabular}
  \caption{Relations between $S$ and $T$}
  \label{tab:intersectSegmentTriang}
\end{table}

\begin{myfig}{Example intersection between a segment
    $\overline{\ve{a_2}\ve{b_2}}$ and a triangle $\triangle \ve{a_1}\ve{b_1}\ve{c_1}$.}{fig:segmentTriangleIntersection}
  \begin{tikzpicture}
    \coordinate (A1) at (0,0);
    \coordinate (B1) at (4,5);
    \coordinate (C1) at (8,1);

    \coordinate (cut1) at (barycentric cs:A1=0.8,B1=0.,C1=0.2);
    \coordinate (cut2) at (barycentric cs:A1=0.,B1=0.8,C1=0.2);

    \coordinate (A2) at (2,5);
    \coordinate (B2) at (4.5,1.5);

    \coordinate (X) at (intersection of cut1--cut2 and B2--A2);

    \draw[poly] (A1) -- (C1) -- (B1) -- (A1);
    \draw[poly] (A2) -- (X);
    \draw[polyTract] (B2) -- (X);

    \foreach \p in {A1,B1,C1,A2,B2}
    \filldraw[vertex] (\p) circle (2pt);

    \filldraw[intersection] (X) circle (2pt);

    \node[below=0.5em] at (A1) {$\ve{a_1}$};
    \node[above=0.5em] at (B1) {$\ve{b_1}$};
    \node[below=0.5em] at (C1) {$\ve{c_1}$};
    \node[above=0.5em] at (A2) {$\ve{a_2}$};
    \node[right=0.5em] at (B2) {$\ve{b_2}$};
    \node[right=0.2em] at (X) {$\ve{x}$};
  \end{tikzpicture}
\end{myfig}
In \cref{fig:segmentTriangleIntersection} a
\cref{en:ist:nc:i} situation is shown where there is intersection in
only one
point $\ve{x}$. To establish whether $S$ and $T$ intersect, we need to
solve
four equations in four unknowns \cite{schneider} where we look for a point
$\ve{x}$ being a convex linear
combination of $\ve{a_2}$ and $\ve{b_2}$ and at the same time a convex
linear combination of $\ve{a_1}$,
$\ve{b_1}$ and $\ve{c_1}$. In other words, when there is a collision,
then there is a solution for the unknowns
$\alpha$, $\beta$, $\gamma$, $\delta$, $\zeta$ of the system
\begin{equation}\label[system]{eq:segmentTriangleIntersection1}
  \begin{cases}
    \alpha \ve{a_2} + \beta\ve{b_2}=\gamma\ve{a_1}+\delta\ve{b_1}+\zeta\ve{c_1} \\
    \alpha + \beta = 1\\
    \gamma + \delta +\zeta=1
  \end{cases}
\end{equation}
with the further conditions
\begin{equation}\label[system]{eq:segmentTriangleIntersection1c}
  \begin{cases}
    \alpha \ge 0\\
    \beta \ge 0\\
    \gamma \ge 0\\
    \delta \ge 0\\
    \zeta \ge 0.
  \end{cases}
\end{equation}
Note that the first equation of
\cref{eq:segmentTriangleIntersection1} has vectorial coefficients
$\ve{a_2}$, $\ve{b_2}$, $\ve{a_1}$, $\ve{b_1}$, $\ve{c_1}$, thus we
have a system with five unknowns in five equations. If
\Cref{eq:segmentTriangleIntersection1} has just one solution then we are
in \cref{en:ist:nc:ni} when \cref{eq:segmentTriangleIntersection1c} is
fulfilled or in \cref{en:ist:nc:i} when it is not. If it has
infinite
solutions then we are on \cref{en:ist:c:ni} or \cref{en:ist:c:i},
depending again on the fulfillment of
\cref{eq:segmentTriangleIntersection1c}. Finally, if it has no
solution, then $S$ or $T$ are degenerated.

We are interested in finding only \cref{en:ist:nc:i} collisions because, for
simplicity, we consider the special case of a segment that lays on the
surface of a triangle as nonintersecting with it, and, for coherence, we
restrict the conditions of \cref{eq:segmentTriangleIntersection1c} to
\begin{equation}
  \begin{cases}
    \alpha > 0\\
    \beta > 0\\
    \gamma > 0\\
    \delta > 0\\
    \zeta > 0.
  \end{cases}
\end{equation}

\Cref{eq:segmentTriangleIntersection1} can be simplified in the three
equations
\begin{equation}\label[system]{eq:segmentTriangleIntersection2}
  \begin{cases}
    \alpha \ve{a_2} + (1-\alpha)\ve{b_2}=\gamma\ve{a_1}+\delta\ve{b_1}+(1-(\gamma+\delta))\ve{c_1} \\
  \end{cases}
\end{equation}
in the unknowns $\alpha$, $\gamma$ and $\delta$ with the relative conditions
\begin{equation}\label[system]{eq:segmentTriangleIntersection2c}
  \begin{cases}
    \alpha > 0\\
    \alpha < 1\\
    \gamma > 0\\
    \delta > 0\\
    \gamma+\delta<1.
  \end{cases}
\end{equation}

\begin{algo}{Find intersection between segment $S$ and triangle $T$}{alg:intersectSegmentTriangle}
  \Function{intersect}{$S, T$}
  \State $intersect\Ass\False$
  \State $coordinates\Ass\emptyset$
  \If{$(\alpha,\gamma,\delta)\Ass
    solve($\cref{eq:segmentTriangleIntersection2}$)$}\label{ln:intersectSegmentTriangleIf}
  \If{$satisfy($\cref{eq:segmentTriangleIntersection2c}$)$}
  \State $intersect\Ass\True$
  \State $coordinates\Ass(\gamma, \delta, 1-(\gamma+\delta))$
  \EndIf
  \EndIf
  \State\Return $(intersect, coordinates)$
  \EndFunction
\end{algo}
Thus, \cref{alg:intersectSegmentTriangle} which performs
\cref{tsk:segmentTriangle}
essentially consists in solving
\cref{eq:segmentTriangleIntersection2} with the parameters $\ve{a_2}$,
$\ve{b_2}$, $\ve{a_1}$, $\ve{b_1}$ and $\ve{c_1}$ from $S$ and $T$;
and then in checking if the solution is admissible. The condition of
\cref{ln:intersectSegmentTriangleIf} is $\True$ if
\cref{eq:segmentTriangleIntersection2} has solution and if that
is unique.

We also have the positive secondary effect that from the solution
$(\alpha,\gamma,\delta)$ of \cref{eq:segmentTriangleIntersection2} we
can extract the barycentric coordinates $(\gamma, \delta,
1-(\gamma+\delta))$ of the intersection point $\ve{x}$ on the system of
the vertices $\ve{a_1}$, $\ve{b_1}$, $\ve{c_1}$ of $T$.

\subsection{Triangle-triangle in 3D space}\label{sec:intersectionsTriangleTriangle}\index{3D
  geometry!triangle-triangle intersection}\index{intersections!triangle-triangle}
We are interested in detecting collisions between two triangles
$T_1=\triangle \ve{a_1}\ve{b_1}\ve{c_1}$ and $T_2=\triangle\ve{a_2}\ve{b_2}\ve{c_2}$ in 3-dimensional
space. First of all consider the coplanarity relation between the two
triangles, we have the cases:
\begin{enumerate}[label=\textbf{case \arabic*}]
\item\label[void]{en:itt:c} $T_1$ and $T_2$ are contained by the same plane;
\item\label[void]{en:itt:nc} $T_1$ and $T_2$ are contained by different planes.
\end{enumerate}
To simplify the problem we decide - similarly to the case of
intersection between segment and triangle - that when we are on \cref{en:itt:c}
we consider $T_1$ and $T_2$ not intersecting in any case, even if from a
geometrical point of view they share points. After this premise we can
assert that the possible relation between $T_1$ and $T_2$ can be
exclusively one
of the following types \cite{schneider}:
\begin{enumerate}[label=\textbf{type \arabic*}, start=0]
\item\label[void]{en:itt:i0} $T_1$ and $T_2$ do not intersect;
\item\label[void]{en:itt:i1} two edges of $T_1$ intersect the plane
  section delimited by $T_2$, or vice versa;
\item\label[void]{en:itt:i2} one edge of $T_1$ intersects the plane
  section delimited by $T_2$ and one edge of $T_2$ intersects the
  plane section delimited by $T_1$.
\end{enumerate}

\begin{myfig}{Example of \cref{en:itt:i1} intersection between a triangle $T_1=\triangle \ve{a_1}\ve{b_1}\ve{c_1}$
    and another triangle $T_2=\triangle \ve{a_2}\ve{b_2}\ve{c_2}$.}{fig:trianglesIntersection1}
  \begin{tikzpicture}
    \coordinate (A1) at (0,0);
    \coordinate (B1) at (4,5);
    \coordinate (C1) at (8,1);

    \coordinate (cut1) at (barycentric cs:A1=0.8,B1=0.,C1=0.2);
    \coordinate (cut2) at (barycentric cs:A1=0.,B1=0.8,C1=0.2);

    \coordinate (A2) at (0,3);
    \coordinate (B2) at (2,5);
    \coordinate (C2) at (4.5,1.5);

    \coordinate (Xs1) at (intersection of A1--B1 and C2--A2);
    \coordinate (Xs2) at (intersection of A1--B1 and C2--B2);
    \coordinate (X1) at (intersection of cut1--cut2 and C2--A2);
    \coordinate (X2) at (intersection of cut1--cut2 and C2--B2);

    \draw[poly] (Xs1) -- (A1) -- (C1) -- (B1) -- (Xs2);
    \draw[polyTract] (Xs1) -- (Xs2);
    \draw[poly] (X1) -- (A2) -- (B2) -- (X2);
    \draw[polyTract] (X1) -- (C2) -- (X2);
    \draw[cutting] (X1) -- (X2);

    \foreach \p in {A1,B1,C1,A2,B2,C2}
    \filldraw[vertex] (\p) circle (2pt);

    \filldraw[intersection] (X1) circle (2pt);
    \filldraw[intersection] (X2) circle (2pt);

    \node[below=0.5em] at (A1) {$\ve{a_1}$};
    \node[above=0.5em] at (B1) {$\ve{b_1}$};
    \node[below=0.5em] at (C1) {$\ve{c_1}$};
    \node[left=0.5em] at (A2) {$\ve{a_2}$};
    \node[above=0.5em] at (B2) {$\ve{b_2}$};
    \node[right=0.5em] at (C2) {$\ve{c_2}$};
    \node[below=0.2em] at (X1) {$\ve{x_1}$};
    \node[right=0.2em] at (X2) {$\ve{x_2}$};
  \end{tikzpicture}
\end{myfig}
\begin{myfig}{Example of \cref{en:itt:i2} intersection between a triangle $T_1=\triangle \ve{a_1}\ve{b_1}\ve{c_1}$
    and another triangle $T_2=\triangle \ve{a_2}\ve{b_2}\ve{c_2}$.}{fig:trianglesIntersection2}
  \begin{tikzpicture}
    \coordinate (A1) at (0,0);
    \coordinate (B1) at (4,5);
    \coordinate (C1) at (8,1);

    \coordinate (cut) at (barycentric cs:A1=0.8,B1=0.,C1=0.2);
    \coordinate (X2) at (barycentric cs:A1=0.,B1=0.8,C1=0.2);

    \coordinate (A2) at (0,6);
    \coordinate (B2) at (8,7);
    \coordinate (C2) at (4.5,1.5);

    \coordinate (Xs1) at (intersection of A1--B1 and C2--A2);
    \coordinate (Xs2) at (intersection of C1--B1 and C2--B2);
    \coordinate (X1) at (intersection of cut--X2 and C2--A2);

    \draw[poly] (Xs1) -- (A1) -- (C1) -- (X2);
    \draw[polyTract] (Xs1) -- (B1) -- (X2);
    \draw[poly] (X1) -- (A2) -- (B2) -- (Xs2);
    \draw[polyTract] (X1) -- (C2) -- (Xs2);
    \draw[cutting] (X1) -- (X2);

    \foreach \p in {A1,B1,C1,A2,B2,C2}
    \filldraw[vertex] (\p) circle (2pt);

    \filldraw[intersection] (X1) circle (2pt);
    \filldraw[intersection] (X2) circle (2pt);

    \node[below=0.5em] at (A1) {$\ve{a_1}$};
    \node[above=0.5em] at (B1) {$\ve{b_1}$};
    \node[below=0.5em] at (C1) {$\ve{c_1}$};
    \node[left=0.5em] at (A2) {$\ve{a_2}$};
    \node[above=0.5em] at (B2) {$\ve{b_2}$};
    \node[right=0.5em] at (C2) {$\ve{c_2}$};
    \node[below=0.2em] at (X1) {$\ve{x_1}$};
    \node[right=0.2em] at (X2) {$\ve{x_2}$};
  \end{tikzpicture}
\end{myfig}
\begin{algo}{Find intersection between triangle $T_1$ and triangle $T_2$}{alg:intersectTriangles}
  \Function{intersect}{$T_1=(\ve{a_1},\ve{b_1},\ve{c_1}),\ T_2=(\ve{a_2},\ve{b_2},\ve{c_2})$}
  \ForAll{$S\in \{\overline{\ve{a_1}\ve{b_1}},\ \overline{\ve{b_1}\ve{c_1}},\ \overline{\ve{c_1}\ve{a_1}}\}$}
  \If{$intersect(S,T_2)$}\label{ln:intersectTriangles1}
  \State\Return $\True$
  \EndIf
  \EndFor
  \ForAll{$S\in \{\overline{\ve{a_2}\ve{b_2}},\ \overline{\ve{b_2}\ve{c_2}},\ \overline{\ve{c_2}\ve{a_2}}\}$}
  \If{$intersect(S,T_1)$}\label{ln:intersectTriangles2}
  \State\Return $\True$
  \EndIf
  \EndFor
  \State\Return $\False$
  \EndFunction
\end{algo}
On \cref{fig:trianglesIntersection1} and
\cref{fig:trianglesIntersection2} we can see two examples of
\cref{en:itt:i1} and \cref{en:itt:i2}, respectively. To establish
if $T_1$ and $T_2$
intersect we need to check if every edge of $T_1$ intersects $T_2$
and if every edge of $T_2$ intersects $T_1$. If we find at least one
edge that intersects with one triangle, then $T_1$ and $T_2$
intersect. \Cref{alg:intersectTriangles} executes such check, the function
$intersect$ on \cref{ln:intersectTriangles1} and
\cref{ln:intersectTriangles2} is the intersection check between a segment
and a triangle done by \cref{alg:intersectSegmentTriangle}.

\end{document}

%%% Local Variables:
%%% mode: latex
%%% TeX-master: "../dissertation"
%%% End:


\lesson{4}{Oct 18 2021 Mon (10:55:28)}{Graphing Quadratics}{Unit 2}

\subsubsection*{Parts of a Parabola}

Parabolas consist of a:

\begin{itemize}
    \item Vertex
    \item Axis of Symmetry
    \item Domain
    \item Range
    \item X-Y Intercepts (Sometimes though)
\end{itemize}

\paragraph{Vertex} Here is how you find the vertex of a parabola:

\begin{itemize}
    \item \bf{Step One: $x$-Coordinate} Set the expression inside the parentheses equal to $0$ and solve for the value of $x$
    \item \bf{Step Two: $y$-Coordinate} Substitute the value of $x$ from step one into the original equation and solve for $y$
\end{itemize}

Let's try an example:

\begin{example}[Given the equation $f(x) = -2(x - 5)^2 + 8$, find the $(x,y)$ coordinate of the vertex]
    \begin{align}
        f(x) &= -2(x - 5)^2 + 8 \\
             &= -2([x - 5 = 0])^2 + 8
             &= 5 - 5 = 0 \\
             &= x = 5
    \end{align}

    Now, we're going to solve for the $y$ coordinate

    \begin{align}
        f(x) &= -2(5)(5 - 5)^2 + 8 \\
             &= -2(5 - 5)^2 + 8 \\
             &= -2(0)^2 + 8 \\
             &= -2(0) + 8 \\
             &= y = 8 \\
    \end{align}

    Now, we know that the vertex of the parabola is $(5, 8)$.
\end{example}

\newpage

\subsubsection*{Elements of the Parabola}

\begin{marginfigure}
    \centering
    \incfig{parabola}
    \sidecaption{Here is an example of what a parabola looks like.}
    \label{fig:parabola}
\end{marginfigure}

\paragraph{Line of Symmetry} The \bf{axis of symmetry} is in the line
that divides the parabola into two equal parts where each part is a
mirror reflection of the other.

As you can see, the axis of symmetry is along the line $x = -3$.

To find the equation of the axis of symmetry algebraically, set the expression inside the parentheses equal to $0$ and solve for $x$.

\paragraph{Domain and Range} Any number can be substituted for the variable $x$ to produce a unique $y$ value. Therefore, the domain is \bf{"All Real Numbers}.

This parabola opens up since the value is positive ($+$). Because the parabola opens up, the vertex represents the minimum point on the graph.
All of the $y$ values on the parabola must be above the minimum $y-coordinate$ of $-1$, which makes the range of the parabola this:

\begin{align}
    y \geq -1
\end{align}

\paragraph{Intercepts} Substituting $0$ for $x$ and solving for $y$ will result in the $y-intercept$:

\begin{align}
    f(g) &= (x + 3)^2 - 1 \\
         &= (0 + 3)^2 - 1 \\
         &= (3)^2 - 1 \\
         &= 9 - 1 \\
         &= 8
\end{align}

There you go, you have your $y-intercept$. To determine the $x-intercept$, you just plug in the $y-intercept$:

\begin{align}
    f(9) &= (9 + 3)^2 - 1 \\
         &= (3)^2 - 1 \\
         &= 9 - 1 \\
         &= 8
\end{align}

\subsubsection*{Different Quadratic Equation forms}

While identifying the:

\begin{enumerate}
    \item Vertex
    \item Axis of Symmetry
    \item Domain
    \item Range
    \item Intercepts
\end{enumerate}

is most easily done using the vertex form of a quadratic equation, most of the time, quadratic equations are written in standard form.

Here is the standard form of a quadratic equation:

\begin{align}
    f(x) = ax^2 + bx + c
\end{align}

Now, we can move that into vertex form, here is an example:

\begin{align}
    f(x) &= -2x(x - 5)^2 + 8 \\
         &= -2x(x - 5)(x - 5) + 8 \\
         &= -2x(x^2 - 5x - 5x + 25) + 8 \\
         &= -2x(x^2 - 10x + 25) + 8 \\
         &= -2x^2 + 20x - 50 + 8 \\
         &= -2x^2 + 20x - 42 \\
\end{align}

But, it's not that easy to identify the vertex and axis, so let's us \bf{Axis of Symmetry} equation, which is:

\begin{align}
    f(x) = -\frac{b}{2a}
\end{align}

Now, let's try to convert an equation in the standard form to this form:

\begin{align}
    f(x) &= -2x^2 + 20x - 42 \\
         &= -\frac{20}{2(-2)} \\
         &= -\frac{20}{-4} \\
         &= x = 5
\end{align}

which gives you the axis of symmetry for the $x-axis$. Now, just substitute $5$ for $x$ to find the $y-coordinate$:

\begin{align}
    f(x) &= -2x^2 + 20x - 42 \\
         &= -2(5)^2 + 20(5) - 42 \\
         &= -2(25) + 100 - 42 \\
         &= -50 + 100 - 42 \\
         &= 8 \\
         &= (5, 8)
\end{align}

\subsubsection*{Working our way up}

\begin{marginfigure}
    \centering
    \incfig{parabola}
    \sidecaption{Here is an example of what a parabola looks like.}
    \label{fig:parabola}
\end{marginfigure}

Now, I have discussed how you can find key features within the equation, but let's try and make our equation from the graph.
Taking the image of the parabola, let's try and see if we can create the equation from the graph:

Let's take the vertex $(-3, -1)$ and a random point, $(0, 8)$. Here is how it works:

\begin{align}
    f(x) &= a(x - h)^2 + k \\
         &= a(x + 3)^2 - 1 \\
         &= 8 = a(0 + 3)^2 - 1 \\
    8 &= a(0 + 3)^2 - 1 \\
       &= a(3)^2 - 1 \\
       &= 9a - 1 \\
       &= 9 = 9a \\
       &= \frac{9}{9} = \frac{9}{9a} \\
       &= 1
\end{align}

Now, let's put it all together:

\begin{align}
    a &= 1, h = -3, k = -1 \\
    f(x) &= a(x - h)^2 + k \\
         &= (x + 3)^2 - 1 \\
         &= (x + 3)(x + 3) - 1 \\
         &= (x^2 + 3x + 3x + 9) - 1 \\
         &= (x^2 + 6x + 9) - 1 \\
         &= x^2 + 6x + 8 \\
\end{align}

\newpage


%!TEX root = ../main.tex
\section{Background}
\label{sec:background}

In the following, we explain the fundamental concepts underlying the remaining sections. These concepts include totality in general and productivity in particular, coinductive data, and copatterns.

\subsection{Why Do We Care About Totality?}
In a partial (i.e. non-total) programming setting, a well-typed program results in a value \emph{if} it terminates \emph{and} it does not result in a run-time error, both of which are possible (even for well-typed programs). Non-termination and run-time errors can be eliminated by making a program total.

\emph{Totality} means that for any input, the program always produces an output\,\citep{Turner04totalfunctional}. Consequently, any total program must be defined for all possible cases of its input. Otherwise, some input would exist for which no output would be defined. Stating that a program is total has different implications, depending on whether the output of a program is of inductive or coinductive type.

If a program results in an instance of an inductive type, it is total if it is \emph{terminating}. Since the output is finite by definition, a program is terminating when it has constructed all of its output. Termination is often ensured by showing that all recursive invocations of the program happens on structurally smaller input.

In the case where a program results in a coinductive instance, it is total if it is \emph{productive}. Because coinductive data is potentially infinite, the program cannot be expected to produce all of its output in finite time. Instead, a productive program must continuously be able to produce a finite prefix of its output in finite time. Hence, a total program returning something of coinductive type is said to be productive, since it must be able to produce an output on every invocation.

Making programs total has multiple benefits. First of all, it gives us a guarantee that an output is always produced. Secondly, due to the Curry-Howard correspondence, total programs can be used as proofs, which enables us to establish strong guarantees about program correctness. In Idris, partial functions are not evaluated by the type checker and thus can never consitute part of a proof. The reason for this is not only that the type checker may loop forever, but also because generally recursive functions give rise to an inconsistent logic. A common argument against total programming is that it is impossible to create programs which are not meant to terminate, such as servers and operating systems. But \emph{totality} should not be mistaken for \emph{termination}. It is true that servers and operating systems are not meant to terminate, but they can be \emph{productive}, a notion which is well-suited for systems that need to be responsive. In short, we care about totality because it provides us with a guarantee that our programs always produce an output, which in addition to eliminating a whole class of errors ultimately enables us construct provably correct programs.

% Non-termination is a possibility
% Not used in proof --- not expanded by type checker
% We can write total servers and operating systems!
% termination vs. productivity

\subsection{Codata}
\label{sec:codata}
Coinductive data, or codata (these terms will be used interchangeably), is data defined in terms of \emph{observations}\,\citep{Jacobs97atutorial}. Since its inception, codata has proven to be a useful tool to describe dynamic structures involving some notion of state, such as transition systems and automata\,\citep{Jacobs97atutorial}, and informally we can say that it allows us to model infinite structures. The idea of infinity arises from the fact that we can define codata which can be observed in infinitely many different states.

\subsubsection{The Duality Between Inductive and Coinductive Data} There is a close correlation between inductively defined data and coinductively defined data. In the field of category theory, this correlation is often defined as the duality between initial algebra and final coalgebra\,\citep{Jacobs97atutorial}. For those less acquainted with category theory (which includes the authors), this duality can be described as the distinction between \emph{construction} and \emph{observation}. Inductive data is constructed by the application of a finite set of constructors, whereas coinductive data can be observed in a given state by a finite set of observations. The distinction is perhaps most easily made clear with an example. Consider a the list data structure in Figure~\ref{fig:inductive_list}, defined in Idris-like syntax:

\begin{figure}
\begin{alltt}
data List : Type -> Type where
  Nil  : List a
  (::) : a  -> List a -> List a
\end{alltt}
\caption{An inductive definition of a list structure.}
\label{fig:inductive_list}
\end{figure}

An instance of \texttt{List} can be constructed using the two constructors, \texttt{Nil} and \texttt{(::)} (cons). Notably, the only way to construct a \texttt{List} in finite time is to apply the \texttt{Nil} constructor at some point. Hence, a \texttt{List} instance is clearly defined by construction, so \texttt{List} is an inductive definition. Could we define lists coinductively also? A coinductive definition requires that we define what can be observed about a list. So, what can we say about list? The definition of \texttt{List} provides some intuition. At any point in time, we can either observe no elements (\texttt{Nil}) or we can observe an element and the rest of the list (\texttt{(::)}). We cannot, however, straightforwardly implement a coinductive list with two such observations, since the observations in a coinductive definition must specify those observations which can be made at any \emph{one} point in time. Surely, we can never at the same time observe no elements and one element (and the rest of the list). What we can say is that if we blindly observe any position in the list, we will either find nothing, or we will find an element and a pointer to the rest of the list. Let us try to formalize this notion with the definition of \texttt{CoList} in Figure~\ref{fig:CoList}.

\begin{figure}
\begin{alltt}
codata CoList : Type -> Type where
  Elem : CoList a -> Either () (a, CoList a)
\end{alltt}
\caption{A coinductive definition of a list structure.}
\label{fig:CoList}
\end{figure}

% cons : a -> List a -> List a
% Elem (cons a l) = Just (a, l)

% append : List a -> List a -> List a
% Elem (append xs ys) = case Elem xs of
%                         Just (a, l) => Just (a, (append l ys))
%                         Nothing => Elem ys

Notice how the types (and names) have changed. Since we have to define the object of our observations, the \texttt{Elem} observation must take a \texttt{CoList a} as parameter. Also, because we are not \emph{constructing} a \texttt{CoList}, the result of \texttt{Elem} does not have to be \texttt{CoList~a}. Instead it is an \texttt{Either} type, which denotes that whenever we try to observe an instance of \texttt{CoList}, we can either get nothing if the list is empty, represented here by a unit value, or \texttt{(x, xs)}, where \texttt{x} is an element and \texttt{xs} is the rest of the list.

Understanding the duality between these two definitions requires a bit of desugaring. We can desugar the \texttt{Either} type from the second example into a sum type, \texttt{() + (a, CoList a)}. Furthermore, we can desugar the two constructors from the first example into one constructor. Since \texttt{Nil} has no parameters, its input can be described by a unit value. The \texttt{(::)} constructor has two parameters, an element and a list. The constructors of \texttt{List} can therefore be reduced to one constructor with a sum type \texttt{() + (a, List a)} as parameter, describing the input of both \texttt{Nil} and \texttt{(::)}. The desugared types of the two definitions are shown side by side in Figure~\ref{fig:List_CoList_duality}.

\begin{figure}
\begin{alltt}
List   : () + (a, List a)   ->   List a
CoList : CoList a           ->   () + (a, CoList a)
\end{alltt}
\caption{The desugared types of \texttt{List} and \texttt{CoList}.}
\label{fig:List_CoList_duality}
\end{figure}

When juxtaposing these types, it becomes apparent that the ways we can construct an inductively defined list is dual to what we can observe about a coinductively defined list. This duality is a general property which exists between inductive and coinductive data: Constructors tell us how data can be built, observations tell us what we can observe about our data.

% \subsubsection{Bisimulation}
% Since coinductive data has no inherent structure, it does not always make sense to talk about equality between two instances of a coinductive type. Instead, it may be the case that two instances of codata give rise to the same sequence of observations, such that they cannot be told apart by the results of our observations. When instances of codata are observationally indistinguishable in this way, we say they are \emph{bisimilar}, as one instance simulates the behaviour of the other. Further details on this phenomenon can be found in the tutorial by Jacobs and Rutten\,\citep{Jacobs97atutorial}.

\subsection{The Current Status of Codata in Idris}
\label{sec:stateinidris}
Coinductive data types already exist in Idris, although they are not defined by observations. Instead, they are defined by constructors. A coinductive definition by constructors as currently implemented in Idris is shown in Figure~\ref{fig:stream_current} for an infinite list, also called a \texttt{Stream}.

\begin{figure}
\begin{alltt}
codata Stream : Type -> Type where
  (::) : a -> Stream a -> Stream a
\end{alltt}
\caption{A stream definition as it currently looks in Idris.}
\label{fig:stream_current}
\end{figure}

At first glance, the type of the \texttt{(::)} constructor looks reasonable. Taking this type at face value, let us try to imagine how a \texttt{Stream} of all the natural numbers could be built:

\begin{alltt}
(0 :: (1 :: (2 :: (3 :: (4 :: (5 :: \ldots))))))
\end{alltt}

This seems to be impossible. Building a \texttt{Stream} requires a new \texttt{Stream}, which again requires a new \texttt{Stream}, leading to an infinite chain of \texttt{Stream}s. Is \texttt{Stream} inhabited at all? Fortunately, the answer is yes, the reason being that the syntax hides an important detail. Internally, the \texttt{(::)} constructor only requires a lazily evaluated \texttt{Stream} as its second argument. Instead of giving an actual stream, we can provide a promise that the rest of the \texttt{Stream} can be generated later. This is captured by the \texttt{Inf} type operator in Figure \ref{fig:stream_current_Inf_and_natsFrom}, which is applied automatically by elaborator. The corecursive call in \texttt{nats} will be lazily evaluated, and therefore not cause an infinite computation.

\begin{figure}
\begin{alltt}
codata Stream : Type -> Type where
  (::) : a -> Inf (Stream a) -> Stream a

natsFrom : Nat -> Stream Nat
natsFrom n = n :: Delay (natsFrom (S n))
\end{alltt}
\caption{A stream definition as it currently looks in Idris with the implicit \texttt{Inf} operator made explicit. This allows us to define an infinite sequence of natural numbers as shown with \texttt{natsFrom}. The \texttt{Delay} constructor for lazily evaluated defintions is applied on the recursive call to \texttt{natsFrom}.}
\label{fig:stream_current_Inf_and_natsFrom}
\end{figure}

This scheme of lazily evaluating coinductive arguments is applied automatically to any constructor in a \texttt{codata} declaration during elaboration, and \texttt{Inf} is therefore optional (for mixed inductive-coinductive definitions) in the concrete Idris syntax. As such, codata in Idris is currently modeled as lazily evaluated data where observations can be made by pattern matching.

To ensure the productivity of functions returning codata, Idris has a productivity checker which analyzes a program according to the \emph{guardedness} principle\,\citep{Coquand94,Gimenez95}: Any corecursive call must appear directly under a constructor. In the \texttt{natsFrom} example, the corecursive call appears directly under the \texttt{(::)} constructor. If we try to define the a stream of the natural numbers without a \texttt{Nat} argument (shown in Figure \ref{fig:nats}), however, the productivity checker rejects the program (as of Idris version \texttt{0.9.12-git:d9a96d1}, at least), complaining that \texttt{nats} is possibly not total. In this case the corecursive call does not appear directly under \texttt{(::)}, but is wrapped in a call to \texttt{map}. Therefore, even though \texttt{nats} is in fact productive, it is not productive according to the guardedness principle.

\begin{figure}
\begin{alltt}
nats : Stream Nat
nats = Z :: map S nats
\end{alltt}
\caption{A stream of all the natural numbers which is productive, but not according to the guardedness principle.}
\label{fig:nats}
\end{figure}

In its original formulation (which is also the one implemented for Idris), the guardedness principle is quite simple, but also rather conservative. The productivity checking algorithm we present in Section~\ref{sec:productivity} accepts more functions as being productive, but is arguably not as simple.

\subsection{Copatterns}
\label{sec:copatterns}
\emph{Destructor copatterns}, or simply \emph{copatterns}\,\citep{Abel13Copatterns}, provide a way of defining functions on coinductive data in terms of observations. Like pattern matching allows us to define functions on inductive data by analyzing the structure of the input, copatterns enable us to make experiments on functions with a result of coinductive type. Building on the intuition presented in Section~\ref{sec:codata}, we begin by defining an infinite list by observations, \texttt{Stream}, in the same vein as \texttt{CoList}:

\begin{figure}
\begin{alltt}
codata Stream : Type -> Type where
  head : Stream a -> a
  tail : Stream a -> Stream a
\end{alltt}
\caption{An infinite list defined by observations.}
\label{fig:stream}
\end{figure}

The syntax for \texttt{codata} definitions presented in Figure~\ref{fig:stream} is quite similar to the existing syntax shown in Figure~\ref{fig:stream_current}. The major difference is that we no longer define constructors, but observations. On a \texttt{Stream}, two observations can be made: \texttt{head} and \texttt{tail}. The former provides us with the first element of the stream, while the latter gives us with the rest of the infinite stream, upon which another element can be observed with \texttt{head}. With respect to the stream definition given in Section~\ref{sec:stateinidris}, the \texttt{head} observation from Figure~\ref{fig:stream} corresponds to the first argument of the \texttt{(::)} constructor, and \texttt{tail} corresponds to the second argument. The \texttt{Stream} defined by observations can be used to define the \texttt{nats} function from Figure~\ref{fig:nats} using copatterns, as shown in Figure~\ref{fig:nats_copatterns}.

\begin{figure}
\begin{alltt}
nats : Stream Nat
head nats = Z
tail nats = map S nats
\end{alltt}
\caption{A definition of \texttt{nats} using copatterns.}
\label{fig:nats_copatterns}
\end{figure}

Because the result type of \texttt{nats} is coinductive, we can use copatterns to define the outcomes of our observations. The intuition is that the first element of \texttt{nats} is zero (\texttt{Z}), and the rest of the natural numbers are all the natural numbers incremented by one (\texttt{map S nats}). Initially, the \texttt{head} observation will therefore return \texttt{Z}. Making a \texttt{tail} observation results in a new stream where all the elements of \texttt{nats} are incremented by one (using the \texttt{S} constructor for natural numbers). Consequently, the outcome of making a subsequent \texttt{head} observation is \texttt{S Z}. As we can increment a natural number infinitely many times, we can also make infinitely many \texttt{tail} observations, where the result of a \texttt{head} observation will be incremented for each \texttt{tail} observation.

Syntactically, projection happens on the outside of definitions when we use copatterns, as opposed to pattern matching, where projection on parameters happens inside of definitions. As an example, consider the definition of \texttt{map} in Figure~\ref{fig:map_copatterns}.

\begin{figure}
\begin{alltt}
map : (a -> b) -> Stream a -> Stream b
head (map f s) = f (head s)
tail (map f s) = map f (tail s)
\end{alltt}
\caption{The \texttt{map} function defined with copatterns.}
\label{fig:map_copatterns}
\end{figure}

For \texttt{map}, it is clear that the observations are applied on the entire definition \texttt{map f s}. Projections on the entire definition make sense because \texttt{map f s} has the coinductive type \texttt{Stream b}, and can therefore be the subject of observations. In this sense, copatterns can be said to be dual to pattern matching in the same way that coinductive data is dual to inductive data. With pattern matching, we can analyze how data has been constructed, and with copatterns we can define the outcome of observations. Where pattern matching is a way of processing input, copatterns provide the means for describing output. In continuation of this description, the behaviour of copatterns during evaluation becomes interesting, but we will defer this discussion to Section~\ref{sec:implementing-copatterns}.

In general, copatterns are used whenever we define a function that results in something coinductive. Nevertheless, there are some cases where definitions do not benefit from the use of copatterns, even though their result is coinductive. Especially, this is the case for definitions that are terminating rather than productive. An elaboration on this will be provided in Section~\ref{sec:copattern_in_idris_productivity_checker}.

% Dual to pattern matching

% Copatterns in Agda

% Inductively defined data can be analyzed by defining functions on that data by traditional pattern matching, where a \emph{pattern} is a (finite and valid) combination of constructor applications for the given data. In this respect,

% \begin{figure}
% \begin{alltt}
% pow2 : Stream Nat
% head pow2 = S Z
% head (tail pow2) = S (S Z)
% tail (tail pow2) = zipWith _+_ (tail pow2) (tail pow2)
% \end{alltt}
% \caption{A definition of an infinite stream of powers of 2 using copatterns.}
% \end{figure}

% by defining functions on that data using traditional pattern

% Inductively defined data can be analyzed by defining functions in terms of a set of \textit{patterns}, where a pattern constitutes a recognizable structure in the data we are analyzing.

% Because we know that the data has been constructed using a finite number of data constructors, the number of ways we can take that same data apart is also finite by definition.

% Consider a standard list data structure, defined in Haskell-like syntax:

% \begin{alltt}
% data List a = Nil
%             | Cons a (List a)
% \end{alltt}

% \texttt{List a} consists of two data constructors, \texttt{Nil} and \texttt{Cons}. Because these two constructors constitute the only that we can construct a \texttt{List a},

\subsection{Existing Implementations of Copatterns}
Copatterns already exist in other languages, for example in Agda\,\cite{Norell:thesis}. Here, definitions for coinductive types are quite interesting. A coinductive type is defined as a record type with a \texttt{coinductive} flag, an example of which can be seen in Figure~\ref{fig:agda_stream}. Observations are defined as fields of the record type.

%Notice the implicit sizes. These are not strictly necessary, but are needed if the user wants productivity checking using sized types rather than guardedness. These different techniques for are discussed in Section~\ref{sec:related_work}.

\begin{figure}
\begin{alltt}
record Stream (A : Set) : Set where
  coinductive
  field
    head : A
    tail : Stream A
open Stream
\end{alltt}
\caption{Sized \texttt{Stream} definition in Agda.}
\label{fig:agda_stream}
\end{figure}

Definitions with copatterns are almost identical to what has already been discussed. A simple example where sized types are not necessary for productivity checking is \texttt{repeat} in Figure~\ref{fig:agda_repeat}. This definition passes a simple guardedness check.

\begin{figure}
\begin{alltt}
repeat : \{A : Set\} -> A -> Stream A
head (repeat a) = a
tail (repeat a) = repeat a
\end{alltt}
\caption{A corecursive \texttt{repeat} function in Agda.}
\label{fig:agda_repeat}
\end{figure}

If we want to write more advanced corecursive functions in Agda, we have to use sized types to reason about productivity. Further discussion on these will be provided in Section~\ref{sec:sized_types}.

%Earlier we saw a definition of a stream of natural numbers. An Agda implementation of this is shown in Figure~\ref{fig:agda_nats}. Since \texttt{nats} does not pass the guardedness check, we have to help the productivity checker by using sized types.


\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage[cache=false]{minted}
\usepackage{makecell}
\usepackage{amsmath}

\title{Recursion in Python}
\author{Guillaume Macneil}

\begin{document}
\maketitle

\begin{abstract}
This is the fifth lesson on the 'Introduction to Python' course. This course is loosely based around the 'MIT Introduction to Computer Science - Fall 2016' course. Our course is more focused towards the Python programming side of things.
\end{abstract}

\section{Introduction to Recursion}
There are two main ways to define recursion:

\begin{itemize}
    \item \textbf{\textit{Semantically}}, recursion is a programming technique where a function calls itself. This is a confusing concept for many, "How can a piece of code tell the interpreter to run that very code, all while the code itself is running?" This is a good question, and can be explained in many ways - my favourite of which using acronyms.\medskip

    In the book 'G{\"o}del, Escher, Bach: An Eternal Golden Braid', Douglas R. Hofstadter describes recursion using the acronym '\textbf{GOD}' (not to be confused with the deity). Two of the characters in the book encounter a being called a Djinn and one of them asks what '\textbf{GOD}' stands for. The Djinn replies that '\textbf{GOD}' stands for '\textbf{GOD} \textbf{o}f \textbf{D}jinn', which in turn stands for '\textbf{GOD} \textbf{o}f \textbf{D}jinn \textbf{o}f \textbf{D}jinn', which in turn stands for '\textbf{GOD} \textbf{o}f \textbf{D}jinn \textbf{o}f \textbf{D}jinn \textbf{o}f \textbf{D}jinn' and so on. Though the book discusses recursion in much greater detail, I feel that this describes recursion quite well, with '\textbf{GOD}' being a function and '\textbf{G}' being the code that recursively calls the '\textbf{GOD}' function.\footnote{This section on the book 'GEB' has become a bit of a tangent, so I will finish it by saying that 'GEB' is a very good book to read for anyone interested in Computer Science, Mathematics or to some degree Psychology. I will warn you though it is a \textbf{substantial} book.}

    \item \textbf{\textit{Algorithmically}}, recursion is a way to design solutions to problems by the \textit{divide-and-conquer} technique - a way of reducing a problem into simpler versions of itself which can, in turn be solved either individually or by reducing the problem again.
\end{itemize}
It is important to note that the '\textbf{GOD}' acronym example isn't entirely representative of how recursion works in general programming. The acronym example is an example of what is called \textit{infinite recursion}, meaning that the function will continue to call itself forever, with no end in sight. In programming, the goal is to avoid this because otherwise the program would never end. So, in programming the recursive function must have one or more \textit{base cases} - reduced versions of the problem that are easily solvable.

\section{Recursion in Python}
Let's start by considering multiplication. Multiplication is the act of adding '\textit{a}' repeatedly to itself '\textit{b}' times. There is a way a multiplication function can be written without recursion:

\begin{minted}{python}
def multiply(a, b):
    output = 0
	while b > 0:
		output += a
		b -= 1
	return output

multiply(3, 5)
# Returns 15
\end{minted}
Now there's nothing inherently wrong with this function, it's actually quite a neat solution (in my opinion), but there is a simpler way of doing it using recursion. Let's visualise what we are doing conceptually:
\[a\times b=a_1+a_2+a_3+a_4+...+a_{b-3}+a_{b-2}+a_{b-1}+a_b \]
If we think about it closely we could vastly simplify this by using some multiplication. "But wait a minute! How can we use multiplication when we are defining the process of multiplication?" By using recursion. Look at what the equation becomes:
\[a\times b=a+a(b-1)\]
Now this seems much more manageable, so here is the multiplication function written recursively using Python:

\begin{minted}{python}
def multiply(a, b):
	if b == 1:
		return a
	else:
		return a + multiply(a, b-1)

multiply(3, 5)
# Returns 15
\end{minted}

Now this function is much less easy to understand than the last one. You can see that it takes \textit{a} and \textit{b} as arguments - the two numbers to multiply. You can also see that the first part of the if statement immediately returns the number \textit{a} if \textit{b} is equal to 1. This makes sense because any number multiplied by 1 is left unchanged. In the else block though, the function returns the number \textit{a} added to a new instance of the function which takes \textit{a} and \textit{b-1} as arguments. If you look carefully, you can see that we have actually written out the simplified equation here. By this recursive process, you can also see that the function will keep calling itself until \textit{b} is equal to 1. This is the \textit{base case}. Once \textit{b} is equal to 1, the function will just output the summation so far - which turns out to be the product of the two arguments. \medskip

Now after all that, you might be wondering: "Why would I bother doing that? The first, non-recursive function is so much easier." This is a valid question which is made even more valid when you consider that recursion isn't even always more efficient than just simple iteration. Recursion is, however, generally more intuitive than iteration - even if it may not seem so currently. It is important to remember that recursion is just a tool in your programming toolbox, just because you can use recursion for a problem doesn't always make it worthwhile. \medskip

Anyway, here is a \textit{factorial} implementation as a final example of recursion. \textit{Factorial} is a mathematical operation that multiplies an integer \textbf{n} by every integer before it, not including \textbf{0}. Here it is in mathematical notation:
\[n!=n\times(n-1)\times(n-2)\times(n-3)\times(n-4)\times...\times1 \]
As you can see, this is a very similar operation to the multiplication example, here is how it could be written in python:
\begin{minted}{python}
def fact(n):
    if n == 1:
        return 1
    else:
        return n*fact(n-1)
\end{minted}
\end{document}


\section{Numbers}\label{sec:numbers}

Numbers are perhaps the most ubiquitous concept in mathematics. Even among non-mathematicians, division by zero or \( 0.999\ldots = 1 \) seem to be a common topic of discourse, either as a joke or a sincere misunderstanding.

The aforementioned topics were studied extensively by mathematicians and have simple justifications from the point of view of abstract mathematics:
\begin{itemize}
  \item We may want to somehow define division by zero in the \hyperref[def:set_of_real_numbers]{set \( \BbbR \) of real numbers}, however that would make it a \hyperref[def:semiring/commutative_unital_ring]{commutative unital ring} rather than a \hyperref[def:field]{field}, which, by \fullref{thm:def:semiring/properties/cancellable_iff_not_zero_divisor}, would deprive us of the cancellative property of multiplication.

  Our familiar arithmetic of real numbers heavily relies on the cancellative property, therefore we simply disallow division by zero.

  \item The set \( \BbbR \) of real numbers is a uniform space and thus every \hyperref[def:fundamental_net]{fundamental sequence} is convergent by \fullref{thm:cauchys_net_convergence_criterion}. Furthermore, since \( \BbbR \) is also a \hyperref[def:separation_axioms/T2]{Hausdorff} space, by \fullref{thm:t2_iff_singleton_limits}, every fundamental sequence has a unique limit.

  Now consider the following two fundamental sequences:
  \begin{align*}
    &1, 1, 1, 1, \ldots, \\
    &0, 0.9, 0.99, \ldots.
  \end{align*}

  Their difference
  \begin{equation*}
    1, 0.1, 0.01, \ldots
  \end{equation*}
  converges to \( 0 \).

  Therefore, the two original sequences converge to the same real number, namely \( 1 \).
\end{itemize}

Unfortunately, a formal study of numbers also leads to artifacts such as the nonstandard natural numbers discussed in \fullref{rem:standard_models_of_arithmetic}.

We will describe some basic properties of the common number systems:
\begin{itemize}
  \item The \hyperref[def:set_of_natural_numbers]{set \( \BbbN \) of natural numbers} from the perspective of \fullref{sec:mathematical_logic}.
  \item The \hyperref[def:set_of_integers]{set \( \BbbZ \) of integers} from the perspective of \fullref{sec:commutative_algebra}.
  \item The \hyperref[def:set_of_rational_numbers]{set \( \BbbQ \) of rational numbers}, only briefly mentioned.
  \item The \hyperref[def:set_of_real_numbers]{set \( \BbbR \) of real numbers} from the perspective of \fullref{sec:real_analysis}.
  \item The \hyperref[def:set_of_real_numbers]{set \( \BbbC \) of complex numbers} from the perspective of \fullref{sec:complex_analysis} and \fullref{sec:commutative_algebra}.
\end{itemize}


\section{L'H\^{o}pital's Rule}
\subsection{Indeterminate Form 0/0}
If both $f(x)$ and $g(x)$ are 0 at $x=a$, then the limit
\begin{equation*}
	\lim_{x\to a}{\frac{f(x)}{g(x)}}.
\end{equation*}
is an indeterminate form of 0/0, meaning we can't substitute $x=a$ to evaluate the limit.
However, L'\^{o}pital's Rule allows us to modify this limit to get another limit, which might not have this indeterminate form but is guaranteed to have the same limit.

\begin{theorem}[L'H\^{o}pital's Rule, Weaker Form]
	If $f(a) = g(a) = 0$; $f^\prime(a)$ and $g^\prime(a) \neq 0$ exist, then
	\begin{equation*}
		\lim_{x\to a}{\frac{f(x)}{g(x)}} = \frac{f^\prime(a)}{g^\prime(a)}.
	\end{equation*}
\end{theorem}
\begin{proof}
	\begin{align*}
		\lim_{x\to a}{\frac{f(x)}{g(x)}} &= \lim_{x\to a}{\frac{f(x)-0}{g(x)-0}} \\
		&= \lim_{x\to a}{\frac{f(x)-f(a)}{g(x)-g(a)}} \\
		&= \lim_{x\to a}{\frac{\frac{f(x)-f(a)}{x-a}}{\frac{g(x)-g(a)}{x-a}}} \\
		&= \frac{\lim_{x\to a}{\frac{f(x)-f(a)}{x-a}}}{\lim_{x\to a}{\frac{g(x)-g(a)}{x-a}}} \\
		&= \frac{f^\prime(a)}{g^\prime(a)}.
	\end{align*}
\end{proof}

\begin{example}
	Find $\lim_{x\to 2}{\frac{x^2-4}{x-2}}$ using L'H\^{o}pital's Rule.
\end{example}
\begin{answer}
	\begin{equation*}
		\lim_{x\to 2}{\frac{x^2-4}{x-2}} = \frac{2(2)}{1} = 4.
	\end{equation*}

	Note that we get the same answer if we didn't use L'H\^{o}pital's Rule and instead factored.
	\begin{equation*}
		\lim_{x\to 2}{\frac{x^2-4}{x-2}} = \lim_{x\to 2}{\frac{(x+2)(x-2)}{x-2}} \lim_{x\to 2}{x+2} = 4.
	\end{equation*}
\end{answer}

It's possible that $f^\prime(a) = g^\prime(a) = 0$, meaning we're still left with the indeterminate form 0/0.
However, we can use a stringer form of L'H\^{o}pital's Rule that allows us to not have to immediate substitute $x=a$ and allows us to apply the rule multiple times if needed.
\begin{theorem}[L'H\^{o}pital's Rule, Stronger Form]
	If $f(a)=g(a)=0$; $f$ and $g$ are differentiable on an open interval $I$ that contains $a$; $g^\prime(x)\neq 0$ if $x\neq a$, then
	\begin{equation*}
		\lim_{x\to a}{\frac{f(x)}{g(x)}} = \lim_{x\to a}{\frac{f^\prime(x)}{g^\prime(x)}}
	\end{equation*}
	if the right-hand limit exists.
\end{theorem}

\begin{example}
	Find the following limit or show that it doesn't exist.
	\begin{equation*}
		\lim_{x\to 0}{\frac{\cos{x}-1}{e^x - x - 1}}.
	\end{equation*}
\end{example}
\begin{answer}
	$\cos{0}-1 = 0 = e^0 - 0 - 1$; $e^x - x - 1 \neq 0$ if $x\neq 0$ on all real numbers.
	\begin{equation*}
		\lim_{x\to 0}{\frac{\cos{x}-1}{e^x - x - 1}} = \lim_{x\to 0}{\frac{-\sin{x}}{e^x - 1}}.
	\end{equation*}

	$-\sin{0} = 0 = e^0 - 1$; $e^x - 1 \neq 0$ if $x\neq 0$ on all real numbers.
	\begin{equation*}
		\lim_{x\to 0}{\frac{-\sin{x}}{e^x - 1}} = \lim_{x\to 0}{\frac{-\cos{x}}{e^x}} = \frac{-1}{1} = -1.
	\end{equation*}
\end{answer}

\subsection{Indeterminate Forms $\infty/\infty$, $\infty\cdot 0$, \& $\infty - \infty$}
\subsubsection{$\infty/\infty$}
L'H\^{o}pital's still applies as written for the indeterminate form $\infty/\infty$.

\begin{example}
	Find the following limit or show that it doesn't exist.
	\begin{equation*}
		\lim_{x\to\pi/2}\frac{\tan{x}}{1+\tan{x}}.
	\end{equation*}
\end{example}
\begin{answer}
	Applying L'H\^{o}pital's Rule,
	\begin{equation*}
		\lim_{x\to\pi/2}{\frac{\tan{x}}{1+\tan{x}}} = \lim_{x\to\pi/2}\frac{\sec^2{x}}{\sec^2{x}} = 1.
	\end{equation*}
\end{answer}

\subsubsection{$\infty\cdot 0$}
We need to rearrange the limit into a 0/0 or $\infty/\infty$ indeterminate form.
\begin{example}
	Find the following limit or show that it doesn't exist.
	\begin{equation*}
		\lim_{x\to\infty}{x\sin{\frac{1}{x}}}.
	\end{equation*}
\end{example}
\begin{answer}
	Rearranging,
	\begin{equation*}
		\lim_{x\to\infty}{x\sin{\frac{1}{x}}} = \lim_{x\to\infty}\frac{\sin{\frac{1}{x}}}{\frac{1}{x}}.
	\end{equation*}

	Since the limit now has indeterminate form 0/0, we can apply L'H\^{o}pital's Rule.
	\begin{equation*}
		\lim_{x\to\infty}\frac{\sin{\frac{1}{x}}}{\frac{1}{x}} = \lim_{x\to\infty}\frac{\frac{-1}{x^2}\cos{\frac{1}{x}}}{\frac{-1}{x^2}} = cos(0) = 1.
	\end{equation*}
\end{answer}

\subsubsection{$\infty - \infty$}
We need to rearrange the limit into a 0/0 or $\infty/\infty$ indeterminate form.
\begin{example}
	Find the following limit or show that it doesn't exist.
	\begin{equation*}
		\lim_{x\to 1}{\frac{1}{\ln{x}} - \frac{1}{x-1}}.
	\end{equation*}
\end{example}
\begin{answer}
	Rearranging,
	\begin{equation*}
		\lim_{x\to 1}{\frac{1}{\ln{x}} - \frac{1}{x-1}} = \lim_{x\to 1}{\frac{x-1-\ln{x}}{(x-1)\ln{x}}}.
	\end{equation*}
	Since the limit now has indeterminate form 0/0, we can apply L'H\^{o}pital's Rule.
	\begin{equation*}
		\lim_{x\to 1}{\frac{x-1-\ln{x}}{(x-1)\ln{x}}} = \lim_{x\to 1}{\frac{1-\frac{1}{x}}{(x-1)\frac{1}{x} + \ln{x}}} = \lim_{x\to 1}{\frac{\frac{1}{x^2}}{\frac{1}{x} - (x-1)\frac{1}{x^2} + \frac{1}{x}}} = \frac{1}{1-0+1} = \frac{1}{2}.
	\end{equation*}
\end{answer}

\subsection{Indeterminate Forms $1^\infty$, $0^0$, \& $\infty^0$}
For indeterminate forms with exponents, we should take the natural log of the limit, solve that limit, and then exponentiate.

\subsubsection{$1^\infty$}
\begin{example}
	Find the following limit or show that it doesn't exist.
	\begin{equation*}
		\lim_{x\to \infty}{\left(1+\frac{1}{x}\right)^x}.
	\end{equation*}
\end{example}
\begin{answer}
	Let $L$ be the value of the limit.
	\begin{align*}
		L &= \lim_{x\to \infty}{\left(1+\frac{1}{x}\right)^x} \\
		\ln{L} &= \lim_{x\to\infty}{\ln{\left(\left(1+\frac{1}{x}\right)^x\right)}} \\
		&= \lim_{x\to\infty}{x\ln{\left(1+\frac{1}{x}\right)}} \text{ (indeterminate form $\infty\cdot 0$)} \\
		&= \lim_{x\to\infty}{\frac{\ln{\left(1+\frac{1}{x}\right)}}{\frac{1}{x}}} \text{ (indeterminate form $0/0$)} \\
		&= \lim_{x\to\infty}{\frac{\frac{1}{1+\frac{1}{x}}\frac{-1}{x^2}}{\frac{-1}{x^2}}} \\
		&= \lim_{x\to\infty}{\frac{1}{1+\frac{1}{x}}} \\
		&= 1 \\
		e^{\ln{L}} &= e^1 \\
		L &= e.
	\end{align*}
\end{answer}

\subsubsection{$0^0$}
\begin{example}
	Find the following limit or show that it doesn't exist.
	\begin{equation*}
		\lim_{x\to 0^+}{x^x}.
	\end{equation*}
\end{example}
\begin{answer}
	Let $L$ be the value of the limit.
	\begin{align*}
		L &= \lim_{x\to 0^+}{x^x} \\
		\ln{L} &= \lim_{x\to 0^+}{x\ln{x}} \text{ (indeterminate form $0\cdot-\infty$)} \\
		&= \lim_{x\to 0^+}{\frac{\ln{x}}{\frac{1}{x}}} \text{ (indeterminate form $-\infty/\infty$)} \\
		&= \lim_{x\to 0^+}{\frac{\frac{1}{x}}{\frac{-1}{x^2}}} \\
		&= \lim_{x\to 0^+}{\frac{1}{\frac{-1}{x}}} \\
		&= \lim_{x\to 0^+}{-x} \\
		&= 0 \\
		e^{\ln{L}} &= e^0 \\
		L &= 1.
	\end{align*}
\end{answer}

\subsubsection{$\infty^0$}
\begin{example}
	Find the following limit or show that it doesn't exist.
	\begin{equation*}
		\lim_{x\to\infty}{x^{\frac{1}{x}}}.
	\end{equation*}
\end{example}
\begin{answer}
	Let $L$ be the value of the limit.
	\begin{align*}
		L &= \lim_{x\to\infty}{x^{\frac{1}{x}}} \\
		\ln{L} &= \lim_{x\to\infty}{\frac{1}{x}\ln{x}} \text{ (indeterminate form $0\cdot\infty$)} \\
		&= \lim_{x\to\infty}{\frac{\ln{x}}{x}} \text{ (indeterminate form $\infty/\infty$)} \\
		&= \lim_{x\to\infty}{\frac{\frac{1}{x}}{1}} \\
		&= 0 \\
		e^{\ln{L}} &= e^0 \\
		L &= 1.
	\end{align*}
\end{answer}


\Lecture{Jayalal Sarma}{Oct 21, 2020}{19}{Computing Ramsey Numbers and Multidimensional Ramsey numbers}{Shivlal Gangesh}{$\alpha$}{JS}
\section{Generalizing Ramsey numbers}
\begin{definition}[3-dimensional Ramsey numbers]
$R_3(p,q,r)$ is the minimum number $n$, such that any 3-edge coloring $K_n$ must have either a red $K_p$ or a blue $K_q$ or a green $K_r$
\end{definition}
\begin{definition}[$k$-dimensional Ramsey numbers]
$R_k(s_1,s_2,\cdots ,s_k)$ is the minimum number of vertices $n$ such that for any $k$-edge coloring of $K_n$  there must exist an $i$ such that there is a $K_{s_i}$ of colour $i$
\end{definition}

\section{Some Observations}
\begin{property}
$R(2,p)=p$
\end{property}
\begin{proof}
$ $
 \begin{description}
    \item[Case1 : $R(2,p) \leq p$]
    $ $ \newline
    Any 2-coloring of $K_p$ must have either a red $K_2$ or blue $K_p$. This is true because either there can exist a red edge (red $K_2$) or no red edge (blue $K_p$) in $K_p$
    \item[Case 2 : $R(2,p) \geq p$]
    $ $ \newline
    There exist a 2-coloring of edges of $K_{p-1}$ such that no red $K_2$ exists and no blue $K_p$ exists. Coloring all the edges of $K_{p-1}$ with blue will result in no red $K_2$ and no blue $K_p$ in $K_{p-1}$
 \end{description}
\end{proof}
\begin{claim}
$$ R(p,q) \leq {p+q-2 \choose p-1} $$
\end{claim}
\begin{proof}
 \begin{align*}
     R(p,q) &\leq  R(p,q-1) + R(p-1,q) && \textrm{(Erdos-Szekeres recurrence relation)} \\
     &\leq {p+(q-1)-2 \choose p-1} + {p-1+q-2 \choose p-2} \\
     &\leq {p+q-3 \choose p-1} + {p+q-3 \choose p-2} \\
     &\leq {p+q-2 \choose p-1}  && ({n+1 \choose k+1} = {n \choose k+1} +{n \choose k})
 \end{align*}

\end{proof}
\section{Explicit Computation of R(3,4)}
We don't know the exact values of Ramsey numbers for higher values as their computation becomes very hard. There is this famous saying by Paul Erdos on the difficulty of computing Ramsey numbers that
\begin{description}
   \item[Paul Erdos on Ramsey numbers]
   $ $ \newline
\textit{   "Suppose aliens invade the earth and threaten to obliterate it in a year's time unless human beings can find the Ramsey number for red five and blue five. We could marshal the world's best minds and fastest computers, and within a year we could probably calculate the value. If the aliens demanded the Ramsey number for red six and blue six, however, we would have no choice but to launch a preemptive attack."}
\end{description}
 So let us now try to calculate the value of $R(3,4)$.
 \begin{claim}
 $$ R(3,4) = 9 $$
 \end{claim}
 \begin{proof}
 $ $
 Consider any 2-coloring of $K_9$ and call it as $G$. We need to prove that $G$ has either a red $K_3$ or a blue $K_4$. Any vertex in $G$ can have it's incident edges as one of the three cases below
  \begin{itemize}
  \item \textbf{Case 1 : }There are at least $4$ red edges going out of the vertex
  \item \textbf{Case 2 : }There are at least $6$ blue edges going out of the vertex
  \item \textbf{Case 3 : }There are exactly $3$ red edges and $5$ blue edges going out of the vertex
  \end{itemize}
 However note that not all vertices in $G$ come under \textbf{Case 3} because, if so then the total sum of degrees of all vertices becomes odd which is not possible. So let $v$ be a vertex in $G$ which does not fall under \textbf{Case 3}. Then
 \begin{description}
    \item[Case 1 : There are at least 4 red edges going out of $v$ ]
    $ $ \newline
    Let $H_1$ be the subgraph of $G$ formed from the four vertices which are sharing the red edge with $v$.  Since we know that $R(2,4)=4$, $H_1$ with 4 vertices must have a red $K_2$ or a blue $K4$, So along with vertex $v$, $G$ must have a red $K_3$ or a blue $K_4$.
    \item[Case 2 :There are at least 6 blue edges going out of $v$]
    $ $ \newline
    Let $H_2$ be the subgraph of $G$ formed from the six vertices which are sharing the blue edge with $v$. Since we know that $R(3,3)=6$, $H_2$ with 6 vertices must have a red $K_3$ or a blue $K3$, So along with vertex $v$, $G$ must have a red $K_3$ or a blue $K_4$.
    \item[Proof for tightness]
    $ $ \newline
    To prove that $9$ is tight, we need to show that there is a 2-coloring of $K_8$ such that it does not have red $K_3$ or blue $K_4$. Given below is one such  example
\begin{figure}[h!]
    \centering
    \includegraphics[width=0.5\linewidth]{images/R34counter_example.png}
    \caption{2-coloring of $K_8$ with no red $K_3$ and no blue $K_4$}
\end{figure}
 \end{description}

 \end{proof}
 As the values $p$, $q$ increases we can only calculate the range of the Ramsey number. The following is a table with value or range of Ramsey numbers for the first few natural numbers.
 \begin{figure}[h!]
    \centering
    \includegraphics[width=1\linewidth]{images/RamseyTable.png}
    \caption{Table for $R(p,q)$}
\end{figure}