\chapter{B\'{e}zier Intersection Problems}\label{chap:bezier-intersection}

\section{Intersecting B\'{e}zier Curves}

The problem of intersecting two B\'{e}zier curves is a core building
block for intersecting two B\'{e}zier triangles in \(\reals^2\)
Since a curve is an algebraic variety of dimension one,
the intersections will either be a curve segment common to both curves (if
they coincide) or a finite set of points (i.e. dimension zero).
Many algorithms have been described in the literature, both
geometric (\cite{Sederberg1986, Sederberg1990, Kim1998}) and
algebraic (\cite{Manocha:CSD-92-698}).

In the implementation for this work, the B\'{e}zier subdivision
algorithm is used.
In the case of a transversal intersection (i.e. one where the
tangents to each curve are not parallel and both are non-zero),
this algorithm performs very well. However, when curves are tangent,
a large number of (false) candidate intersections are detected and
convergence of Newton's method slows once in a neighborhood of an
actual intersection. Non-transversal intersections
have infinite condition number, but transversal intersections with
very high condition number can also cause convergence problems.

\begin{figure}
  \includegraphics{../images/bezier-intersection/bbox_check.pdf}
  \centering
  \captionsetup{width=.75\linewidth}
  \caption{Bounding box intersection predicate. This is a cheap way to
    conclude that two curves don't intersect, though it inherently is
    susceptible to false positives.}
  \label{fig:bounding-box-check}
\end{figure}

In the B\'{e}zier subdivision algorithm, we first check if the
bounding boxes for the curves are disjoint
(Figure~\ref{fig:bounding-box-check}).
We use the bounding boxes
rather than the convex hulls since they are easier to compute and
the intersections of boxes are easier to check.
If they are disjoint, the pair can be rejected. If not, each curve
\(\mathcal{C} = b\left(\left[0, 1\right]\right)\) is split into two halves
by splitting the unit interval: \(b\left(\left[0, \frac{1}{2}\right]\right)\)
and \(b\left(\left[\frac{1}{2}, 1\right]\right)\)
(Figure~\ref{fig:bezier-curve-subdivision}).

\begin{figure}
  \includegraphics{../images/bezier-intersection/subdivide_curve.pdf}
  \centering
  \captionsetup{width=.75\linewidth}
  \caption{B\'{e}zier curve subdivision.}
  \label{fig:bezier-curve-subdivision}
\end{figure}

\begin{figure}
  \includegraphics{../images/bezier-intersection/subdivision_process.pdf}
  \centering
  \captionsetup{width=.75\linewidth}
  \caption{B\'{e}zier subdivision algorithm.}
  \label{fig:bezier-subdivision-process}
\end{figure}

As the subdivision continues,
some pairs of curve segments may be kept around that won't lead to an
intersection (Figure~\ref{fig:bezier-subdivision-process}).
Once the curve segments are close to linear within a given tolerance
(Figure~\ref{fig:bezier-subdivision-linearized}), the process
terminates.

\begin{figure}
  \includegraphics{../images/bezier-intersection/subdivision_linearized.pdf}
  \centering
  \captionsetup{width=.75\linewidth}
  \caption{Subdividing until linear within tolerance.}
  \label{fig:bezier-subdivision-linearized}
\end{figure}

Once both curve segments are linear (to tolerance), the intersection is
approximated by intersecting the lines connecting the endpoints of each
curve segment. This approximation is used as a starting point for Newton's
method, to find a root of \(F(s, t) = b_0(s) - b_1(t)\). Since
\(b_0(s), b_1(t) \in \reals^2\) we have Jacobian \(J =
\left[ \begin{array}{c c} b_0'(s) & -b_1'(t) \end{array}\right]\).
With these, Newton's method is
\begin{equation}
\left[ \begin{array}{c c} s_{n + 1} & t_{n + 1} \end{array}\right]^T =
\left[ \begin{array}{c c} s_n & t_n \end{array}\right]^T -
J_n^{-1} F_n.
\end{equation}
This also gives an indication why convergence issues occur at non-transveral
intersections: they are exactly the intersections where the Jacobian is
singular.

\section{Intersecting B\'{e}zier Triangles}\label{sec:intersect-bez-tri}

The chief difficulty in intersecting two surfaces is intersecting their edges,
which are B\'{e}zier curves.
Though this is just a part of the overall algorithm, it proved to be the
\emph{most difficult} to implement (\cite{Hermes2017}). So the first part
of the algorithm is to find all points
where the edges intersect (Figure~\ref{fig:edge-intersections}).

\begin{figure}
  \includegraphics{../images/bezier-intersection/main_figure21.pdf}
  \centering
  \captionsetup{width=.75\linewidth}
  \caption{Edge intersections during B\'{e}zier triangle intersection.}
  \label{fig:edge-intersections}
\end{figure}

To determine the curve segments that bound the curved polygon region(s)
(see Section~\ref{subsec:curved-polygons} for more about curved polygons) of
intersection, we not only need to keep track
of the coordinates of intersection, we also need to keep note of
\emph{which} edges the intersection occurred on and the parameters along
each curve.
With this information, we can classify each point of intersection
according to which of the two curves forms the boundary of the
curved polygon (Figure~\ref{fig:intersection-classification}).
Using the right-hand rule we can compare the tangent
vectors on each curve to determine which one is on the interior.

\begin{figure}
  \includegraphics{../images/bezier-intersection/main_figure22.pdf}
  \centering
  \captionsetup{width=.75\linewidth}
  \caption{Classified intersections during B\'{e}zier triangle intersection.}
  \label{fig:intersection-classification}
\end{figure}

This classification becomes more difficult when the curves
are tangent at an intersection, when the intersection occurs at a corner
of one of the surfaces or when two intersecting edges are coincident
on the same algebraic curve (Figure~\ref{fig:intersection-difficulties}).

\begin{figure}
  \includegraphics{../images/bezier-intersection/main_figure23.pdf}
  \centering
  \captionsetup{width=.75\linewidth}
  \caption{B\'{e}zier triangle intersection difficulties.}
  \label{fig:intersection-difficulties}
\end{figure}

In the case of tangency, the intersection is non-transversal, hence has
infinite condition number. In the case of coincident curves, there are
infinitely many intersections (along the segment when the curves
coincide) so the subdivision process breaks down.

\subsection{Example}

Consider two B\'{e}zier surfaces
(Figure~\ref{fig:surface-surface-example})

\begin{equation}
b_0(s, t) =
\left[ \begin{array}{c}
    8 s \\ 8 t \end{array}\right] \qquad
b_1(s, t) =
\left[ \begin{array}{c}
    2 (6 s + t - 1) \\
    2 (8 s^2 + 8 s t - 8 s + 3 t + 2) \end{array}\right]
\end{equation}
\begin{figure}
  \includegraphics{../images/bezier-intersection/main_figure24.pdf}
  \centering
  \captionsetup{width=.75\linewidth}
  \caption{Surface Intersection Example}
  \label{fig:surface-surface-example}
\end{figure}

In the \emph{first step} we find all intersections of the
edge curves
\begin{multline}
E_0(r) = \left[ \begin{array}{c} 8 r \\ 0 \end{array}\right],
E_1(r) = \left[ \begin{array}{c} 8 (1 - r) \\ 8 r \end{array}\right],
E_2(r) = \left[ \begin{array}{c} 0 \\ 8 (1 - r) \end{array}\right], \\
E_3(r) = \left[ \begin{array}{c} 2 (6 r - 1) \\ 4 (2 r - 1)^2
  \end{array}\right],
E_4(r) = \left[ \begin{array}{c} 10 (1 - r) \\ 2 (3 r + 2) \end{array}\right],
E_5(r) = \left[ \begin{array}{c} - 2 r \\ 2 (5 - 3 r) \end{array}\right].
\end{multline}
We find three intersections
and we classify each of them by comparing the tangent vectors
\begin{gather}
  I_1:
  E_2\left(\frac{7}{9}\right) =
E_3\left(\frac{1}{6}\right) = \frac{16}{9}
\left[ \begin{array}{c} 0 \\ 1 \end{array}\right] \Longrightarrow
E_2'\left(\frac{7}{9}\right) \times
E_3'\left(\frac{1}{6}\right) = 96 \\
I_2:
E_0\left(\frac{1}{2}\right) =
E_3\left(\frac{1}{2}\right) =
\left[ \begin{array}{c} 4 \\ 0 \end{array}\right] \Longrightarrow
E_0'\left(\frac{1}{2}\right) \times
E_3'\left(\frac{1}{2}\right) = 0 \\
  I_3:
E_1\left(\frac{1}{8}\right) =
E_3\left(\frac{3}{4}\right) =
\left[ \begin{array}{c} 7 \\ 1 \end{array}\right] \Longrightarrow
E_1'\left(\frac{1}{8}\right) \times
E_3'\left(\frac{3}{4}\right) = -160.
\end{gather}
From here, we construct our curved polygon intersection by drawing
from our list of intersections until none remain.

\begin{itemize}
\itemsep 0em
\item First consider \(I_1\). Since
  \(E_2' \times
  E_3' > 0\)
  at this point, then we consider the curve
  \(E_3\) to be
  \emph{interior}.
\item After classification, we move along
  \(E_3\) until we
  encounter another intersection: \(I_2\)
\item \(I_2\) is a point of tangency since
  \(E_0'\left(\frac{1}{2}\right) \times
  E_3'\left(\frac{1}{2}\right) = 0\).
  Since a tangency has no impact on
  the underlying intersection geometry, we ignore it and
  keep moving.
\item Continuing to move along
  \(E_3\), we
  encounter another intersection: \(I_3\).
  Since
  \(E_1' \times
  E_3' < 0\)
  at this point, we consider the curve
  \(E_1\) to be
  \emph{interior} at the intersection. Thus we stop moving
  along \(E_3\)
  and we have our first curved segment:
  \(E_3\left(\left[
    \frac{1}{6}, \frac{3}{4}\right]\right)\)
\item Finding no other intersections on \(E_1\)
  we continue until the end of the edge.
  Now our (ordered) curved segments are:
  \begin{equation}
  E_3\left(\left[
    \frac{1}{6}, \frac{3}{4}\right]\right) \longrightarrow
  E_1\left(\left[
    \frac{1}{8}, 1\right]\right).
  \end{equation}
\item Next we stay at the corner and switch to the next curve
  \(E_2\), moving along that curve
  until we hit the next intersecton \(I_1\).
  Now our (ordered) curved segments are:
  \begin{equation}
  E_3\left(\left[
    \frac{1}{6}, \frac{3}{4}\right]\right) \longrightarrow
  E_1\left(\left[
    \frac{1}{8}, 1\right]\right) \longrightarrow
  E_2\left(\left[
    0, \frac{7}{9}\right]\right).
  \end{equation}
  Since we are now back where we started (at \(I_1\))
  the process stops
\end{itemize}
We represent the boundary of the curved polygon as B\'{e}zier curves, so
to complete the process we reparameterize (\cite[Ch.~5.4]{Farin2001}) each
curve onto the relevant interval. For example,
\(E_3\) has control points
\(p_0 = \left[ \begin{array}{c} -2 \\ 4 \end{array}\right]\),
\(p_1 = \left[ \begin{array}{c} 4 \\ -4 \end{array}\right]\),
\(p_2 = \left[ \begin{array}{c} 10 \\ 4 \end{array}\right]\)
and we reparameterize on \(\alpha = \frac{1}{6}, \beta = \frac{3}{4}\) to
control points
\begin{align}
  q_0 &= E_3\left(\frac{1}{6}\right) =
  \frac{16}{9} \left[ \begin{array}{c} 0 \\ 1 \end{array}\right] \\
  q_1 &= (1 - \alpha) \left[(1 - \beta) p_0 + \beta p_1\right] +
   \alpha \left[(1 - \beta) p_1 + \beta p_2\right] = \frac{1}{6} \left[
    \begin{array}{c} 21 \\ -8 \end{array}\right] \\
  q_2 &= E_3\left(\frac{3}{4}\right) = \left[
    \begin{array}{c} 7 \\ 1 \end{array}\right].
\end{align}

\section{B\'{e}zier Triangle Inverse}

The problem of determining the parameters \((s, t)\) given a point
\(\bm{p} = \left[\begin{array}{c c} x & y\end{array}\right]^T\)
in a B\'{e}zier triangle can also be solved by using
subdivision with a bounding box predicate and then Newton's method
at the end.

\begin{figure}
  \includegraphics{../images/bezier-intersection/locate_in_triangle.pdf}
  \centering
  \captionsetup{width=.75\linewidth}
  \caption{Checking for a point \(\bm{p}\) in each of four subregions
    when subdividing a B\'{e}zier triangle.}
  \label{fig:locate-in-triangle}
\end{figure}

For example, Figure~\ref{fig:locate-in-triangle} shows
how regions of \(\utri\) can be discarded recursively until the
suitable region for \((s, t)\) has a sufficiently small area. At
this point, we can apply Newton's method to the map \(F(s, t) =
b(s, t) - \bm{p}\). It's very helpful (for Newton's method) that
\(F: \reals^2 \longrightarrow \reals^2\) since the Jacobian will
always be invertible
when the B\'{e}zier triangle is valid. If \(\bm{p} \in \reals^3\)
then the system would be underdetermined. Similarly, if
\(\bm{p} \in \reals^2\) but \(b(s)\) is a B\'{e}zier curve then the
system would be overdetermined.


%!TEX root =  ../main.tex

\objective{Connect names of types of equations with graphs.}

We have said that a function is a relation of inputs to outputs, with no more than one output per input.
We have learned that functions can be defined graphically, algebraically, numerical, or verbally.
A function that is defined by an algebra equation usually has a descriptive name.
In this section, we will look at several groupings of various functions, some of which you should
be very familiar with, and some of which may be new.

You might be used to seeing a  \gls{graph} of certain equations, written algebraically with $y$ in terms
of $x$, like $y=x$.  These have then been graphed on the Cartesian plane, as a continuous curve,
with each point corresponding to an ordered pair, $(x,y)$.  Leonhard Euler created much of the notation
we use today, including \emph{function notation}: $y=f(x)$.

\marginfig[-0in]{\chapdir/pics/Linear_Function_Graph.png}{Linear functions.\label{fig:LinearFunction}}
\subsubsection{Linear}
One of the most obvious things to see is a straight line.
Humans create straight lines seemingly more often
than anything else.  Hence, lines can feel unnatural or reassuring.
What are some of the properties of lines?
How might two lines be the same?  How might they differ?

\marginfig[-0in]{\chapdir/pics/AndraGrad-4}{A quadratic function is a polynomial of degree two.}
Lines could have the same slope, and therefore never run into each other.
They would only be distinguished by their
heights.  For convenience, we measure the height of a \gls{linear} function
in Analytic Geometry by its starting value, its $y$ when $x$
equals zero.  Conversely, these starting locations might be the same and
slope might be different.  You have learned \index{linear!intercept form}
to distinguish these two different variables as $m$ and $b$, as in $y=mx+b$, and we shall see
that it is expedient to distinguish them \textbf{constant} functions, $y=k$.
\index{constant!function}

\subsubsection{Quadratic}
Many things in our world operate over two dimensions, such as gravity.
Hence, Newton found that the force
of two objects upon each other is proportional to the \emph{square} of their distance.
Squares graphed make a
\textbf{parabola}, a word that in Greek references the path of a falling or thrown object.
Algebraically, we can see all such shapes\index{quadratic!standard form}
have an equation of the form $y=ax^2+bx+c$, which is called \gls{quadratic}.
You should already know a great deal about quadratics from previous classes.

\paragraph{Power}
As more dimension interact, the exponent on $x$ can become very
complicated, and even fractional.  We can generalize\index{power function!standard form}
from $y=x$ to $y=x^2$ and $y=x^3$ to $y=a\cdot x^b$.  We shall study them in more depth
in chapter 5.

\paragraph{Polynomial}
A sum of power functions with whole number exponents is called a
\textbf{polynomial}.  Such equations are among the most well-studied
areas in mathematics.  A polynomial divided by a polynomial is called
a \textbf{rational function}.  Both are the subject of chapter 6.
\index{polynomial}\index{rational function}

\subsubsection{Exponential}
\marginfig[-0in]{\chapdir/pics/2^x_function_graph}{$2^x$ is an  exponential function}
Quantities that experience the same percentage growth or decay
year over year look similar in the algebra: $x$ is in
the exponent, and hence such an equation is called an \gls{exponential} function.  The general form
is $y=a\cdot b^x$.  \index{exponential function!standard form}
The ``opposite''\footnote{There are \emph{many} things
which could be called `opposite'
in mathematics, so this is not technical language.  We will define `inverses' of functions in 4.4.} of such a
function is a called a \gls{logarithm}, and we will follow the TI-8* for now and use the generic equation
$y=a+b\ln{x}$.  \index{logarithmic function}

\subsubsection{Periodic}
Many phenomena in nature reoccur the same way at regular intervals.
Such functions are said to be \textbf{periodic}.
We will  study `simple harmonic motion,' which comes from components of motion in circles, in section III,
Trigonometric Functions.  For now\footnote{Later, we
will factor the ``inside,'' but this first kind is the sort produced by your grapher.}, use the general equation $y=a\cdot\sin(bx+c)+d$.\index{sine function}

\inlinefig{\chapdir/pics/Periodic_function_illustration.png}{\label{fig:periodic}A periodic function is so called because it repeats at a given interval, called the period (P).}


\input{../../assignment-header}

%========================================================================
\title{Direct Collocation via Trapezoid Method}
\author{Matthew P. Kelly}
%========================================================================
\begin{document}
\maketitle

\begin{abstract*}
This document gives a few examples of how to perform transcription using the
trapezoid method for direct collocation.
\end{abstract*}

\section{Boundary Value Problem with Path Objective (simple)}

Here is a general formulation for a continuous-time trajectory optimization problem.
For now, let's assume that the duration $T$ is given.

\begin{align*}
  & \text{minimize: } \qquad J = \int_0^T \! g(t,\, \bm{x},\, \bm{u}) \, dt \\
  & \text{subject to: } \qquad \bm{0} = \bm{h}(\bm{x}(0), \, \bm{x}(T)) \\
  & \text{dynamics: } \qquad \dot{\bm{x}} = \bm{f}(t,\, \bm{x},\, \bm{u}) \\
\end{align*}

Perform direct transcription using the trapezoid method. In other words,
the system dynamics and path objective are both approximated
using the trapezoid rule for quadrature.
To start with, we will us a uniform time grid with $N$ segments:
\begin{equation*}
  h = \frac{T}{N}  \quad \quad \quad \quad t_k = k \cdot h
\end{equation*}

\textbf{Decision Variables: }  $\displaystyle
  \bm{x}_0, \bm{x}_1, \dots ,\bm{x}_N, \quad \bm{u}_0, \bm{u}_1, \dots, \bm{u}_N
$ \\ \vspace{1em} \\

\textbf{Objective Function: } $\displaystyle
  J = \frac{h}{2} \cdot \sum_{k=0}^{N-1} \Big(
  g(t_k,\,  \bm{x}_k,\,  \bm{u}_k)
  \, + \,
  g(t_{k+1},\,  \bm{x}_{k+1},\,  \bm{u}_{k+1}) \Big)
$ \\ \vspace{1em} \\

\textbf{Boundary Constraints: } $\displaystyle
  \bm{0} = \bm{h}(\bm{x}_0, \, \bm{x}_N)
$ \\ \vspace{1em} \\

\textbf{System Dynamics Constraints: } \\
\begin{equation*}
  \bm{x}_{k+1} = \bm{x}_k + \frac{h}{2} \cdot
  \Big(
  \bm{f}(t_k,\,  \bm{x}_k,\,  \bm{u}_k)
  \, + \,
  \bm{f}(t_{k+1},\,  \bm{x}_{k+1},\,  \bm{u}_{k+1})
  \Big)
  \quad \quad \quad \quad k \in 0 \dots (N-1)
\end{equation*}

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

\section{Boundary Value Problem with Path Objective (Arbitrary Grid)}

Here is a general formulation for a continuous-time trajectory optimization problem.
Now let's make the boundary times decision variables and use an arbitrary grid.

\begin{align*}
  & \text{minimize: } \qquad J = \int_{T_0}^{T_F} \! g(t,\, \bm{x},\, \bm{u}) \, dt \\[1em]
  & \text{subject to: } \qquad \bm{0} = \bm{h}(T_0, \, T_F,\, \bm{x}(T_0), \, \bm{x}(T_F)) \\[1em]
  & \text{dynamics: } \qquad \dot{\bm{x}} = \bm{f}(t,\, \bm{x},\, \bm{u}) \\
\end{align*}

We will use an arbitrary grid, which we
assume is provided either by the user or a mesh refinement algorithm.
We then apply a linear mapping to this initial grid such that the
initial and final points on the grid match up with
the initial and final times that the optimization is using. This allows us to
compute the time grid from the
boundary times ($t_0, t_N$) and the mesh fraction ($\gamma_0, \gamma_1, \dots, \gamma_N$).

\begin{equation*}
  h_k = t_{k+1} - t_k
  \quad \quad \quad \quad
  t_k = \frac{t_N - t_0}{\gamma_N - \gamma_0} \cdot (\gamma_k - \gamma_0) + t_0
\end{equation*}

\textbf{Decision Variables: }  $\displaystyle
  t_0, \, t_N,\,
  \quad
  \bm{x}_0,\, \bm{x}_1,\, \dots, \,\bm{x}_N,\,
  \quad
  \bm{u}_0,\, \bm{u}_1,\, \dots,\, \bm{u}_N\,
$ \\ \vspace{1em} \\

\textbf{Objective Function: } $\displaystyle
  J = \frac{1}{2} \cdot \sum_{k=0}^{N-1}
  h_k
  \Big( g(t_k,\,  \bm{x}_k,\,  \bm{u}_k)
  \, + \,
  g(t_{k+1},\,  \bm{x}_{k+1},\,  \bm{u}_{k+1}) \Big)
$ \\ \vspace{1em} \\

\textbf{Boundary Constraints: } $\displaystyle
  \bm{0} = \bm{h}(t_0, \, t_N,\, \bm{x}_0, \, \bm{x}_N)
$ \\ \vspace{1em} \\

\textbf{System Dynamics Constraints: } \\
\begin{equation*}
  \bm{x}_{k+1} = \bm{x}_k + \frac{h_k}{2} \cdot
  \Big(
  \bm{f}(t_k,\,  \bm{x}_k,\,  \bm{u}_k)
  \, + \,
  \bm{f}(t_{k+1},\,  \bm{x}_{k+1},\,  \bm{u}_{k+1})
  \Big)
  \quad \quad \quad \quad k \in 0 \dots (N-1)
\end{equation*}

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


\documentclass[11pt,oneside]{article}	%use"amsart"insteadof"article"forAMSLaTeXformat
\usepackage{geometry}		%Seegeometry.pdftolearnthelayoutoptions.Therearelots.
\geometry{letterpaper}		%...ora4paperora5paperor...
%\geometry{landscape}		%Activateforforrotatedpagegeometry
%\usepackage[parfill]{parskip}		%Activatetobeginparagraphswithanemptylineratherthananindent
\usepackage{graphicx}				%Usepdf,png,jpg,orepsßwithpdflatex;useepsinDVImode
								%TeXwillautomaticallyconverteps-->pdfinpdflatex
\usepackage{amssymb}
\usepackage{amsmath}
\usepackage{amsthm}
\newtheorem{definition}{Definition}
\newtheorem{theorem}{Theorem}

\usepackage[colorlinks]{hyperref}

\input{macros}

\title{The \texttt{smplxn} module
\footnote{This document is part of the framework~\cite{cclar-proj:2013:00}. \today}
}
\author{Alberto Paoluzzi}
%\date{}							%Activatetodisplayagivendateornodate

\begin{document}
\maketitle
\nonstopmode

\begin{abstract}
This module defines a minimal set of functions to generate a dimension-independent grid of simplices.
The name of the library was firstly used by our CAD Lab at University of Rome ``La Sapienza'' in years 1987/88 when we started working with dimension-independent simplicial complexes~\cite{Paoluzzi:1993:DMS:169728.169719}. This one in turn imports some functions from the \texttt{scipy} package and the geometric library \texttt{pyplasm}~\cite{}.
\end{abstract}

\tableofcontents\newpage

\section{Introduction}

The $Simple_X^n$ library, named \texttt{simplexn} within the Python version of the LARCC framework,
provides  combinatorial algorithms for some basic functions of geometric modelling with simplicial complexes. In particular, provides the efficient creation of simplicial complexes generated by simplicial complexes of lower dimension, the production of simplicial grids of any dimension, and the extraction of facets (i.e.~of $(d-1)$-faces) of complexes of $d$-simplices.

\section{Some simplicial algorithms}

The main aim of the simplicial functions given in this library is to provide optimal combinatorial algorithms, whose time complexity is linear in the size of the output.
Such a goal is achieved by calculating each cell in the output via closed combinatorial formulas, that do not require any searching nor data structure traversal to produce their results.

\subsection{Linear extrusion of a complex}

Here we discuss an implementation of the linear extrusion of simplicial complexes according to the method discussed in~\cite{Paoluzzi:1993:DMS:169728.169719} and~\cite{DBLP:journals/cad/FerruciP91}. In synthesis, for each $d$-simplex in the input complex, we generate combinatorially a $(d+1)$-simplicial \emph{tube}, i.e.~a chain of $d+1$ simplexes of dimension $d+1$. It can be shown that if the input simplices are a simplicial complex, then the output simplices are a complex too.

In other words, if the input is a complex, where all $d$-cells either intersect along a common face or are pairwise disjoints, then the output is also a simplicial complex of dimension $d+1$. This method is computationally optimal, since it does not require any search or traversal of data structures. The algorithm~\cite{DBLP:journals/cad/FerruciP91} just writes the output making a constant number $O(1)$ of operation for each one of its $n$ output $d$-cells, so that the time complexity is $\Omega(n)$, where $n = d\,m$, being $m$ the number and $d$ the dimension (and the storage size) of the input cells, represented as lists of indices of vertices.

\paragraph{Computation}

Let us concentrate on the generation of the simplex chain $\gamma^{d+1}$ of dimension $d+1$ produced by combinatorial extrusion of a single simplex
\[
\sigma^d = \langle v_0, v_1, \ldots, v_d,   \rangle .
\]
Then we have, with $|\gamma^{d+1}| = \sigma^d \times I$, and $I=[0,1]$:
\[
\gamma^{d+1} = \sum_{k=0}^{d} (-1)^{kd} \langle v_k, \ldots v_d, v^*_0, \ldots  v^*_k \rangle
\]
with $v_k\in \sigma^d \times \{0\}$ and  $v^*_k\in \sigma^d \times \{1\}$, and where the term $(-1)^{kd}$ is used to generate a chain of coherently-oriented extruded simplices.

\begin{figure}[htbp] %  figure placement: here, top, bottom, or page
   \centering
   \begin{minipage}[c]{0.49\linewidth}
		\caption{Extrusion of (a) a point; (b) a straight line segment; (c) a triangle.}
	\end{minipage}
   \begin{minipage}[c]{0.49\linewidth}
		\includegraphics[width=0.8\linewidth]{images/extrusion}
	\end{minipage}
   \label{fig:extrusion}
\end{figure}

In our implementation the combinatorial algorithm above is twofold generalised:
\begin{enumerate}
\item by applying it to all $d$-simplices of a LAR model of dimension $d$;
\item by using instead of the single interval $I=[0,1]$, the possibly unconnected set of 1D intervals generated by the list of integer numbers stored in the \texttt{pattern} variable
\end{enumerate}

\paragraph{Implementation}
In the macro below, \texttt{larExtrude1} is the function to generate the output model vertices in a multiple extrusion of a LAR model.

First we notice that the \texttt{model} variable contains a pair (\texttt{V}, \texttt{FV}), where \texttt{V} is the array of input vertices, and \texttt{FV} is the array of $d$-cells (given as lists of vertex indices) providing the  input representation of a LAR cellular complex.

The \texttt{pattern} variable is a list of integers, whose absolute values provide the sizes of the ordered set of 1D (in local coords) subintervals specified by the \texttt{pattern} itself. Such subintervals are assembled in global coordinates, and each one of them is considered either solid or void depending on the sign of the corresponding integer, which may be either positive (solid subinterval) or negative (void subinterval).

Therefore, a value \texttt{pattern = [1,1,-1,1]} must be interpreted as the 1D simplicial complex
\[
[0,1] \cup [1,2] \cup [3,4]
\]
with five vertices \texttt{W = [[0.0], [1.0], [2.0], [3.0], [4.0]]} and three $1$-cells \texttt{[[0,1], [1,2], [3,4]]}.

\texttt{V} is the list of input $d$-vertices (each given as a list of $d$ coordinates);
\texttt{coords} is a list of absolute translation parameters to be applied to \texttt{V} in order to generate the output vertices generated by the combinatorial extrusion algorithm.

The \texttt{cellGroups} variable is used to select the groups of $(d+1)$-simplices corresponding to solid intervals in the input \texttt{pattern}, and \texttt{CAT} provides to flatten their set, by removing a level of square brackets.

%-------------------------------------------------------------------------------
@d Simplicial model extrusion in accord with a 1D pattern
@{def larExtrude1(model,pattern):
    V, FV = model
    d, m = len(FV[0]), len(pattern)
    coords = list(cumsum([0]+(AA(ABS)(pattern))))
    offset, outcells, rangelimit = len(V), [], d*m
    for cell in FV:
        @< Append a chain of extruded cells to outcells @>
    outcells = AA(CAT)(TRANS(outcells))
    cellGroups = [group for k,group in enumerate(outcells) if pattern[k]>0 ]
    outVertices = [v+[z] for z in coords for v in V]
    outModel = outVertices, CAT(cellGroups)
    return outModel
@}
%-------------------------------------------------------------------------------

\paragraph{Extrusion of single cells}
For each cell in \texttt{FV} a chain of vertices is created, then they are separated into groups of $d+1$ consecutive elements, by shifting one position at a time.

%-------------------------------------------------------------------------------
@d Append a chain of extruded cells to outcells
@{@< Create the indices of vertices in the cell "tube" @>
@< Take groups of d+1 elements, by shifting one position @>
@}
%-------------------------------------------------------------------------------

\paragraph{Assembling vertex indices in a tube with their shifted images}
Here the ``long'' chain of vertices is created.
%-------------------------------------------------------------------------------
@d Create the indices of vertices in the cell "tube"
@{tube = [v + k*offset for k in range(m+1) for v in cell]	@}
%-------------------------------------------------------------------------------

\paragraph{Selecting and reshaping extruded cells in a tube}
Here the chain of vertices is spitted into subchains, and such subchains are reshaped into three-dimensional arrays of indices.
%-------------------------------------------------------------------------------
@d Take groups of d+1 elements, by shifting one position
@{cellTube = [tube[k:k+d+1] for k in range(rangelimit)]
outcells += [reshape(cellTube, newshape=(m,d,d+1)).tolist()]	@}
%-------------------------------------------------------------------------------

\begin{definition}[Big-Omega order]
We say that a function $f(n)$ is \emph{Big-Omega} order of a function $f(n)$, and write
$f(n) \in \Omega(g(n))$ when a constant $c$ exists, such that:
\[
\lim_{n\to\infty} \frac{f(n)}{g(n)}=c>0,\qquad \mbox{where\ } 0<c\leq\infty.
\]
\end{definition}

\begin{theorem}[Optimality]
The combinatorial algorithm for extrusion of simplicial complexes has time complexity $\Omega(n)$.
\end{theorem}
\proof{
Of course, if we denote as $g(n) = nd$ the time needed to write the input of the extrusion algorithm, proportional to the constant length $d$ of cells, and as $f(m) = m(d+1)$ the time needed to write the output, where $m=n(d+1)$, we have
\[
\lim_{n\to\infty} \frac{f(n)}{g(n)}= \lim_{n\to\infty} \frac{m(d+1)}{nd}
= \lim_{n\to\infty} \frac{[n(d+1)](d+1)}{nd} = \frac{(d+1)^2}{d} = c > 0
\]
\qed}

\subsubsection{Examples of simplicial complex extrusions}

\paragraph{Example 1}
It is interesting to notice that the 2D model extruded in example 1 below and shown in Figure~\ref{fig:assembly} is locally non-manifold, and that several instance of the pattern in the $z$ direction are obtained by just inserting a void subinterval (negative size) in the \texttt{pattern} value.

\begin{figure}[htbp] %  figure placement: here, top, bottom, or page
   \centering
   \includegraphics[width=0.7\linewidth]{images/assembly}
   \caption{A simplicial complex providing a quite complex 3D assembly of tetrahedra.}
   \label{fig:assembly}
\end{figure}

\paragraph{Examples 2 and 3}
The examples show that the implemented \texttt{larExtrude1} algorithm is fully multidimensional.
It may be worth noting the initial definition of the empty \texttt{model}, as a pair having the empty list as vertex set and the list \texttt{[[0]]} as the cell list. Such initial value is used
to define a predefinite constant \texttt{VOID}.

\begin{figure}[htbp] %  figure placement: here, top, bottom, or page
   \centering
   \includegraphics[height=0.25\linewidth,width=0.25\linewidth]{images/simplexn-1a}
   \includegraphics[height=0.25\linewidth,width=0.25\linewidth]{images/simplexn-1b}
   \includegraphics[height=0.25\linewidth,width=0.25\linewidth]{images/simplexn-1c}
   \caption{1-, 2-, and 3-dimensional simplicial complex generated by repeated extrusion with the same pattern.}
   \label{fig:example}
\end{figure}

%-------------------------------------------------------------------------------
@D Examples of simplicial complex extrusions
@{# example 1
V = [[0,0],[1,0],[2,0],[0,1],[1,1],[2,1],[0,2],[1,2],[2,2]]
FV = [[0,1,3],[1,2,4],[2,4,5],[3,4,6],[4,6,7],[5,7,8]]
model = larExtrude1((V,FV),4*[1,2,-3])
VIEW(EXPLODE(1,1,1.2)(MKPOLS(model)))

# example 2
model = larExtrude1( VOID, 10*[1] )
VIEW(EXPLODE(1.5,1.5,1.5)(MKPOLS(model)))
model = larExtrude1( model, 10*[1] )
VIEW(EXPLODE(1.5,1.5,1.5)(MKPOLS(model)))
model = larExtrude1( model, 10*[1] )
VIEW(EXPLODE(1.5,1.5,1.5)(MKPOLS(model)))

# example 3
model = larExtrude1( VOID, 10*[1,-1] )
VIEW(EXPLODE(1.5,1.5,1.5)(MKPOLS(model)))
model = larExtrude1( model, 10*[1] )
VIEW(EXPLODE(1.5,1.5,1.5)(MKPOLS(model)))
@}
%-------------------------------------------------------------------------------

\begin{figure}[htbp] %  figure placement: here, top, bottom, or page
   \centering
   \includegraphics[height=0.25\linewidth,width=0.25\linewidth]{images/simplexn-2a}
   \includegraphics[height=0.25\linewidth,width=0.25\linewidth]{images/simplexn-2b}
   \caption{1- and 2-dimensional simplicial complexes generated by different patterns.}
   \label{fig:example}
\end{figure}

\subsection{Generation of multidimensional simplicial grids}

The generation of simplicial grids of any dimension and shape using the \texttt{larSimplexGrid1}
is amazingly simple. The input parameter \texttt{shape} is either a tuple or a list of integers used to specify the \emph{shape} of the created array, i.e.~both the number of its dimensions (given by \texttt{len(shape)}) and the \texttt{size} of each dimension $k$ (given by the \texttt{shape[k]} element).
The implementation starts from the LAR model of the VOID simplicial complex (denoted as \texttt{VOID}, a predefined constant) and updates the \texttt{model} variable extruding it iteratively according to the specs given by \texttt{shape}.
Just notice that the returned grid \texttt{model} has vertices with integer coordinates, that can be subsequently scaled and/or translated and/or mapped in any other way, according to the user needs.

%-------------------------------------------------------------------------------
@d Generation of simplicial grids
@{def larSimplexGrid1(shape):
    model = VOID
    for item in shape:
        model = larExtrude1(model,item*[1])
    return model
@}
%-------------------------------------------------------------------------------

\paragraph{Examples of simplicial grids} The two examples of simplicial grids generated by the macro below with \texttt{shape} equal to \texttt{[3,3]} and \texttt{[2,3,4]}, respectively, are displayed in Figure~\ref{fig:simplexn-3}.

\begin{figure}[htbp] %  figure placement: here, top, bottom, or page
   \centering
   \includegraphics[height=0.25\linewidth,width=0.25\linewidth]{images/simplexn-3a}
   \includegraphics[height=0.25\linewidth,width=0.25\linewidth]{images/simplexn-3b}
   \caption{2- and 3-dimensional simplicial grids.}
   \label{fig:simplexn-3}
\end{figure}

%-------------------------------------------------------------------------------
@d Examples of simplicial grids
@{grid_2d = larSimplexGrid1([3,3])
VIEW(EXPLODE(1.5,1.5,1.5)(MKPOLS(grid_2d)))

grid_3d = larSimplexGrid1([2,3,4])
VIEW(EXPLODE(1.5,1.5,1.5)(MKPOLS(grid_3d)))
@}
%-------------------------------------------------------------------------------

\subsection{Facet extraction from simplices}

A $k$-face of a $d$-simplex is defined as the convex hull of any subset of $k$ vertices.
A $(d-1)$-face of a $d$-simplex
\[
\sigma^d = \langle v_0, v_1, \ldots, v_d \rangle
\]
 is also called a \emph{facet}. Each of the $d+1$ facets of $\sigma^d$, obtained by removing a vertex from $\sigma^d$, is a $(d-1)$-simplex. A simplex may be oriented in two different ways according to the permutation
class of its vertices. The simplex \emph{orientation} is so changed by either multiplying the simplex by -1, or by executing an odd number of exchanges of its vertices.

The chain of oriented boundary facets of $\sigma^d$, usually denoted as $\partial \sigma^d$, is generated combinatorially as follows:
\[
\partial\, \sigma^d = \sum_{k=0}^d (-1)^d \langle v_0, \ldots, v_{k-1}, v_{k+1}, \ldots, v_d \rangle
\]

\paragraph{Implementation}

The \texttt{larSimplexFacets} function, for estraction of non-oriented $(d-1)$-facets of $d$-dimensional simplices, returns a list of $d$-tuples of integers, i.e.~the input LAR representation of the topology of a cellular complex. The final steps are used to remove the duplicated facets, by transforming the sorted facets into a \emph{set of strings}, so removing the duplicated elements.

%-------------------------------------------------------------------------------
@d Facets extraction from a set of simplices
@{def larSimplexFacets(simplices):
    out = []
    d = len(simplices[0])
    for simplex in simplices:
        out += AA(sorted)([simplex[0:k]+simplex[k+1:d] for k in range(d)])
    out = set(AA(tuple)(out))
    return  sorted(out)
@}
%-------------------------------------------------------------------------------

\paragraph{Examples of facet extraction}
The simple generation of the LAR model of a simplicial decomposition of a 3D cube as a \texttt{larSimplexGrid1} with \texttt{shape = [1,1,1]} and of its 2D and 1D skeletons is shown here.

%-------------------------------------------------------------------------------
@d Examples of facet extraction from 3D simplicial cube
@{V,CV = larSimplexGrid1([1,1,1])
VIEW(EXPLODE(1.5,1.5,1.5)(MKPOLS((V,CV))))
SK2 = (V,larSimplexFacets(CV))
VIEW(EXPLODE(1.5,1.5,1.5)(MKPOLS(SK2)))
SK1 = (V,larSimplexFacets(SK2[1]))
VIEW(EXPLODE(1.5,1.5,1.5)(MKPOLS(SK1)))
@}
%-------------------------------------------------------------------------------

\subsection{Converting a LAR B-Rep into a set of triangles}

In this section we show how to convert a LAR boundary representation (B-Rep), i.e.~a LAR model $\texttt{V,FV}$ made of 2D faces, usually quads but also general polygons, into a LAR model \texttt{verts,triangles} made by triangles.

\paragraph{From LAR faces to LAR triangles by vertex sorting}
From every boundary face we generate a new vertex in \texttt{V}, computed as the centroid of face vertices, and transform each face in a set of triangles, each one given by the face's centroid and by one of the boundary edges.

Since each face is known as a spatially unordered set of vertices, we need to make some more work to extract its edges. First, the face is affinely transformed into the $z=0$ plane, then its (now 2D) vertices are circularly ordered around the origin, so that the original vertex indices are also circularly ordered. Such set of edges provides the indices of vertices to be attached to the centroid index to give the needed triangle indices.

%-------------------------------------------------------------------------------
@D From LAR faces to LAR triangles
@{""" Transformation to triangles by sorting circularly the vertices of faces """
def quads2tria(model):
	V,FV = model
	out = []
	nverts = len(V)-1
	for face in FV:
		centroid = CCOMB([V[v] for v in face])
		V += [centroid]
		nverts += 1

		v1, v2 = DIFF([V[face[0]],centroid]), DIFF([V[face[1]],centroid])
		v3 = VECTPROD([v1,v2])
		if ABS(VECTNORM(v3)) < 10**3:
			v1, v2 = DIFF([V[face[0]],centroid]), DIFF([V[face[2]],centroid])
			v3 = VECTPROD([v1,v2])
		transf = mat(INV([v1,v2,v3]))
		verts = [(V[v]*transf).tolist()[0][:-1]  for v in face]

		tcentroid = CCOMB(verts)
		tverts = [DIFF([v,tcentroid]) for v in verts]
		rverts = sorted([[ATAN2(vert),v] for vert,v in zip(tverts,face)])
		ord = [pair[1] for pair in rverts]
		ord = ord + [ord[0]]
		edges = [[n,ord[k+1]] for k,n in enumerate(ord[:-1])]
		triangles = [[nverts] + edge for edge in edges]
		out += triangles
	return V,out
@}
%-------------------------------------------------------------------------------

\subsection{Exporting the $Simple_x^n$ library}
The current version of the \texttt{simplexn} library is exported here. Next versions will take care of the OpenCL acceleration and data partitioning with very-large size simplicial grids and their sets of faces.

%-------------------------------------------------------------------------------
@O larlib/larlib/simplexn.py
@{# -*- coding: utf-8 -*-
"""Module for facet extraction, extrusion and simplicial grids"""
from larlib import *

VOID = V0,CV0 = [[]],[[0]]    # the empty simplicial model
@< Cumulative sum  @>
@< Simplicial model extrusion in accord with a 1D pattern @>
@< Generation of simplicial grids @>
@< Facets extraction from a set of simplices @>
@< From LAR faces to LAR triangles @>
if __name__ == "__main__":
	@< Examples of simplicial complex extrusions @>
	@< Examples of simplicial grids @>
	@< Examples of facet extraction from 3D simplicial cube @>
@}
%-------------------------------------------------------------------------------

\section{Signed (co)boundary matrices of a simplicial complex}
\label{simplicial}

\section{Test examples}

\subsection{Structured grid}

\subsubsection{2D example}

\paragraph{Generate a simplicial decomposition}
Then we generate and show a 2D decomposition of the unit square $[0,1]^2\subset\E^2$ into a $3\times 3$ grid of simplices (triangles, in this case), using the \texttt{larSimplexGrid1} function, that returns a pair \texttt{(V,FV)}, made by the array \texttt{V} of vertices, and by the array \texttt{FV} of ``faces by vertex'' indices, that constitute a \emph{reduced} simplicial LAR of the $[0,1]^2$ domain. The computed \texttt{FV} array is then dispayed ``exploded'', being $ex,ey,ez$ the explosion parameters in the $x,y,z$ coordinate directions, respectively. Notice that the \texttt{MKPOLS} pyplasm primitive requires a pair \texttt{(V,FV)}, that we call a ``model'', as input --- i.e. a pair made by the array \texttt{V} of vertices, and by a zero-based array of array of indices of vertices. Elsewhere in this document we identified such a data structure as CSR$(M_d)$, for some dimension $d$. Suc notation stands for the Compressed Sparse Row representation of a binary characteristic matrix.

@d Generate a simplicial decomposition ot the $[0,1]^2$ domain
@{V,FV = larSimplexGrid1([3,3])
VIEW(EXPLODE(1.5,1.5,1.5)(MKPOLS((V,FV))))
@}

\paragraph{Extract the $(d-1)$-faces}
Since the complex is simplicial, we can directly extract its facets (in this case the 1-faces, i.e. its edges) by invoking the \texttt{larSimplexFacets} function on the argument \texttt{FV}, so returning the array \texttt{EV} of ``edges by vertex'' indices.

%-------------------------------------------------------------------------------
@d Extract the edges of the 2D decomposition
@{EV = larSimplexFacets(FV)
ex,ey,ez = 1.5,1.5,1.5
VIEW(EXPLODE(ex,ey,ez)(MKPOLS((V,EV))))
@}
%-------------------------------------------------------------------------------

\paragraph{Export the executable file}
We are finally able to generate and output a complete test file, including the visualization expressions. This file can be executed by the \texttt{test} target of the \texttt{make} command.

%-------------------------------------------------------------------------------
@O test/py/simplexn/test01.py
@{""" 2D example """
from larlib import *

@<Generate a simplicial decomposition ot the $[0,1]^2$ domain@>
@<Extract the edges of the 2D decomposition@>
@}
%-------------------------------------------------------------------------------

\subsubsection{3D example}

In this case we produce a $2\times 2\times 2$ grid of tetrahedra. The dimension (3D) of the model to be generated is inferred by the presence of 3 parameters in the parameter list of the \texttt{larSimplexGrid1} function.

%-------------------------------------------------------------------------------
@d Generate a simplicial decomposition ot the $[0,1]^3$ domain
@{V,CV = larSimplexGrid1([2,2,2])
VIEW(EXPLODE(1.5,1.5,1.5)(MKPOLS((V,CV))))
@}
%-------------------------------------------------------------------------------

and repeat two times the facet extraction:

%-------------------------------------------------------------------------------
@d Extract the faces and edges of the 3D decomposition
@{
FV = larSimplexFacets(CV)
VIEW(EXPLODE(1.5,1.5,1.5)(MKPOLS((V,FV))))
EV = larSimplexFacets(FV)
VIEW(EXPLODE(1.5,1.5,1.5)(MKPOLS((V,EV))))
@}
%-------------------------------------------------------------------------------

and finally export a new test file:

%-------------------------------------------------------------------------------
@O test/py/simplexn/test02.py
@{""" 3D example """
from larlib import *

@<Generate a simplicial decomposition ot the $[0,1]^3$ domain@>
@<Extract the faces and edges of the 3D decomposition@>
@}
%-------------------------------------------------------------------------------

\subsection{Unstructured grid}

\subsubsection{2D example}

\subsubsection{3D example}

\appendix
\section{Utilities}

%-------------------------------------------------------------------------------
@d Cumulative sum
@{
def cumsum(iterable):
    # cumulative addition: list(cumsum(range(4))) => [0, 1, 3, 6]
    iterable = iter(iterable)
    s = iterable.next()
    yield s
    for c in iterable:
        s = s + c
        yield s
@}
%-------------------------------------------------------------------------------

\bibliographystyle{amsalpha}
\bibliography{simplexn}

\end{document}


\documentclass[../Notes/main.tex]{subfiles}

\begin{document}
\section{Mathematics}
\subsection{Useful Data}
\begin{tabular}{| l | c | c | c |}
    \hline
    \(n\)     & Primes less than \(n\) & Maximal Prime Gap & \(\max_{0<i<n}(d(i))\) \\
    \hline
    \num{1e2} & \num{25}               & \num{8}           & \num{12}               \\
    \num{1e3} & \num{168}              & \num{20}          & \num{32}               \\
    \num{1e4} & \num{1229}             & \num{36}          & \num{64}               \\
    \num{1e5} & \num{9592}             & \num{72}          & \num{128}              \\
    \num{1e6} & \num{78498}            & \num{114}         & \num{240}              \\
    \num{1e7} & \num{664579}           & \num{154}         & \num{448}              \\
    \num{1e8} & \num{5761455}          & \num{220}         & \num{768}              \\
    \num{1e9} & \num{50487534}         & \num{282}         & \num{1344}             \\
    \hline
\end{tabular}

\subsection{Modular Arithmetic}

\subsubsection{Chinese Remainder Theorem}
\lstinputlisting[firstline=2]{CRT/CRT.cpp}

\subsubsection{Binomial Coefficients mod m}
\lstinputlisting[firstline=2]{nCr/nCr.cpp}

\subsection{Primality Checks}
\subsubsection{Miller Rabin}
\lstinputlisting[firstline=2]{primalityChecks/millerRabin/millerRabin.cpp}

\subsubsection{Sieve of Eratosthenes}
\lstinputlisting[firstline=2]{primalityChecks/sieveEratosthenes/sieve.cpp}

\subsubsection{trialDivision}
\lstinputlisting[firstline=2]{primalityChecks/trialDivision/trialDivision.cpp}

\subsection{Others}
\subsubsection{Polynomials}
\lstinputlisting[firstline=2]{polynomials/polynomials.cpp}

\subsubsection{Factorial Factorization}
\lstinputlisting[firstline=2]{factorialFactorization/factorialFactorization.cpp}

\end{document}


\subsection{Overview}

\begin{figure*}[ht]
  \includegraphics[width=\textwidth]{img/classifier_comparison}
  \caption{Visualization of 1D classifier performance. Red points have observed EM counterparts, while blue do not. We trained the classifier only on the data with solid points, and obtained a decision boundary shown by the dashed line. The open points are the remaining half of the data, which, as you can see, were correctly classified by this decision boundary.}
  \label{fig:class}
\end{figure*}

\begin{figure*}[ht]
  \includegraphics[width=\textwidth]{img/mass-distribution}
  \caption{Decision boundary from 1D classifier trained on $\mathcal{M}_c$, overlayed on the 2D mass distribution. Red points have EM counterparts, while blue do not.}
  \label{fig:2D}
\end{figure*}

\begin{figure*}[ht]
  \includegraphics[width=\textwidth]{img/classifier-2D.pdf}
  \caption{Results of linear SVM classifier, trained on half of the data set, displayed here to perfectly classify the entire data set. Red points represent events with EM counterparts, and blue points represent the events without. The predictions of the classifier are shown as the yellow and blue shaded regions.}
  \label{fig:2dclass}
\end{figure*}

LIGO can provide very rapid mass estimates of candidate GW events. Since most of these detections are binary black holes, and EM followup is extremely expensive, very few events are expected to have confirmed EM counterparts.

We have trained a classifier to determine if an event will have a EM counterpart. In \S\ref{sec:classifier-method} we discuss the method used, and in \S\ref{sec:classifier-results} we discuss our results.

\subsection{Method}
\label{sec:classifier-method}
We trained this classifier on the first half of the data, simply taking the mid-way point in $\mathcal{M}_c$ between the population of events with EM counterparts and without. This is demonstrated in Figure \ref{fig:class}.

We took a slightly different approach for the 2D mass distribution, as part of the \textbf{500\% extra credit} problem. Here we trained a linear SVM, using \texttt{sklearn.svm.LinearSVC}, with \texttt{C=100}, and the masses transformed into log-space. Again, we performed the training on half of the data, and made correct predictions on the full data set. The results are shown in Figure \ref{fig:2dclass}.

\subsection{Results}
\label{sec:classifier-results}

The classifier correctly separated the two groups with $100\%$ completeness and zero contamination, even when the training was done using only half of the data set. Of course, this is potentially sensitive to precisely \emph{which} half of the data set was used, so one can imagine a likely scenario where this failed.

Looking at Figure \ref{fig:chirp}, you can see that the decision boundary occurs in one of the histogram bins with zero observations. In this sense, it does correlate with structure in the data.

In Figure \ref{fig:2D}, we have plotted that same decision boundary over the 2D mass distribution. To do this, we had to derive an expression for $m_2(m_1, \mathcal{M}_c)$, which we accomplished using \texttt{Mathematica}. The expression is
%
\begin{equation}
  m_2(m_1, \mathcal{M}_c) =
  \frac{(2/3)^{1/3} \mathcal{M}_c^5}{X} +
  \frac{X}{2^{1/3} \cdot 3^{2/3} \cdot m_1^3},
%
  \label{eq:m2-m1-Mc}
\end{equation}
%
where
%
\begin{equation}
  X \equiv
  \qty[
    9 m_1^7 \mathcal{M}_c^5 +
    \sqrt{3 m_1^9 \mathcal{M}_c^{10} \qty(27 m_1^5 - 4 \mathcal{M}_c^3)}
  ]^{1/3}.
\end{equation}
%
As you can see from Figure \ref{fig:2D}, this line corresponds to the division between the events with and without counterparts.

A similar result is obtained using the linear SVM on the 2D mass distribution directly. The result is shown in Figure \ref{fig:2dclass}.


\section{Paper 2}
\subsection{\emph{"Linear Spectral Clustering Superpixel"}}
\begin{frame}{INTRODUCTION}
    The introduced technique is called SUPERPIXEL. Widely used in image
    processing for particular tasks such as image segmentation, image analysis,
    image classification, target tracking, 3D reconstruction, surface retrieval and
    object proposal. The purpose of the elaborate story is to reduce the
    computational complexity through a superpixel system called LSC (Linear Spectral
    Clustering).
\end{frame}

\begin{frame}{LSC SUPERPIXEL pt1}
    Goal: optimization (max/min) of two objective functions to create clusters of pixels called superpixels:
    \begin{block}{Objective Function 1: Weighted K-Means}
        $$ F_{km} = \sum_{k=1}^K\sum_{p\in\pi_k}\omega(p)= || \phi(p)-m_k ||^2 $$
    \end{block}
    \begin{block}{Objective Function 2: Normalized cuts}
        $$ F_{N_{cuts}} = \frac{1}{K}\sum_{k=1}^K\frac{\sum_{p\in\pi_k}\sum_{q\in\pi_k}W(p,q)}{\sum_{p\in\pi_k}\sum_{q\in{V}}W(p,q)} $$
    \end{block}
    Problem: extremely high computational!
\end{frame}

\begin{frame}{LSC SUPERPIXEL pt2}
    If corollary 1 is satisfied, then  \emph{weghted K-means clustering} can be used
    for segmentation and for creation of superpixel regions, instead of the
    eigen-vector based method.
    \begin{block}{\bfseries{Corollary 1}}
        Optimizations of the objective functions of the weighted K-means
        and the normalized cuts are mathematically equivalent if (1) and (2)
        hold simultaneously. The symbol $ \cdot $ stands for inner product.
    \end{block}

    \begin{block}{Equation (1)}
           $$ \omega(p)\phi(p) \cdot \omega(q)\phi(q) = W(p,q), \forall p,q \in V $$
    \end{block}

    \begin{block}{Equation (2)}
        $$ \omega(p) = \sum_{q \in V} W(p,q), \forall p \in V $$
    \end{block}
\end{frame}

\begin{frame}{LSC Algorithm pt1}
    Problem? $ \rightarrow $ Find the correct positive similarity function $ W (p,q) $,
    between two data points \emph{p} and \emph{q} to solve equation 1.
    \begin{block}{Similarity Function}
        \begin{equation}\small
            \begin{split}
                W(p,q) = C_s^2(\cos \frac{\pi}{2}(x_p-x_q)+\cos\frac{\pi}{2}(y_p-y_q)) \\
                + C_c^2(\cos \frac{\pi}{2}(l_p-l_q)+\cos\frac{\pi}{2}(\alpha_p-\alpha_q) \\
                + \cos\frac{\pi}{2}(\beta_p-\beta_q)x2.55^2)
            \end{split}
        \end{equation}
    \end{block}

    \begin{block}{Mapping Function}
        \begin{equation}\small
            \begin{split}
                \phi(p) = \frac{1}{\omega(p)}[C_c\cos\frac{\pi}{2}l_p, C_c\sin\frac{\pi}{2}l_p, 2.55C_c\cos\frac{\pi}{2}\alpha_p \\
                x 2.55C_c\sin\frac{\pi}{2}\alpha_p, 2.55C_c\cos\frac{\pi}{2}\beta_p, 2.55C_c\sin\frac{\pi}{2}\alpha_p, \\
                x C_s\cos\frac{\pi}{2}x_p, C_s\sin\frac{\pi}{2}x_p, C_s\cos\frac{\pi}{2}y_p, C_s\sin\frac{\pi}{2}x_p]
            \end{split}
        \end{equation}
    \end{block}

\end{frame}

\begin{frame}{LSC Algorithm pt2}
    Assuming that equation 1 exists, LSC method takes two parameters as
    input; The image to be segmented and the preferred K number of
    superpixels that the algorithm will have to produce. The number K
    corresponds to the number of centroids and each of these will be useful
    for grouping the neighbors pixels, in a range of $ \tau v_x \ x \ \tau v_y $, with $ \tau>0.5 $,
    using a distance comparison.
    \begin{figure}[h!]
        \centering
        \includegraphics[width = 0.7 \linewidth]{paper2/slide1.png}
        \centering
        \caption{Sample images segmented with K = 1000/500/200 superpixels using LSC.}
        \label{fig: metrics}
    \end{figure}
\end{frame}

\begin{frame}{COMPARATIVE EXPERIMENTS}
    \begin{table}[htbp!]
        \centering
        \begin{adjustbox}{max width=\textwidth}
        \begin{tabular}{*{9}{|c}|}%%{|c|c|c|c|c|c|c|c|c|}
            \hline
            & EneOpt0 & SEEDS\footfullcite{0781426509} & ERS\footfullcite{0781426508} & Lattices & NCuts & SLIC\footfullcite{0781426514} & Turbo & LSC \\
            \hline
            \bfseries{ADERENCE TO BOUNDARY} & & & & & & & & \\
            \emph{Under segmentation error} & 0.230 & 0.197 & 0.198 & 0.303 & 0.220 & 0.213 & 0.277 & \bfseries{0.190}\\
            \emph{Boundary recall} & 0.765 & 0.918 & 0.920 & 0.811 & 0.789 & 0.837 & 0.739 & \bfseries{0.926}\\
            \emph{Achievable segmentation accuracy} & 0.950 & 0.960 & 0.959 & 0.933 & 0.956 & 0.956 & 0.943 & \bfseries{0.962}\\
            \hline
            \bfseries{SEGMENTATION SPEED} & & & & & & & & \\
            \emph{Computational complexity} & $ O(N^3/K^2) $ & $ O(N) $ & $ O(N^2 \lg{N}) $ & $ O(N^{\frac{3}{2}} \lg{N}) $ & $ O(N^{\frac{3}{2}}) $ & $ O(N) $ & $ O(N) $ & $ O(N) $\\
            \emph{Average time per image} & 3.35s & \bfseries{0.0935}s & 0.969s & 0.284s & 93.4s & 0.125s & 6.61s & 0.334s\\
            \hline
        \end{tabular}
        \end{adjustbox}
        \caption{Performance metrics superpixel segmentation algorithms at K=400}
        \label{table superpixels}
    \end{table}
    Best performance: low "Under segmentation Error" (\emph{UE}), high
    "Boundary Recall" (\emph{BR}) and high "Achievable segmentation accuracy
    (\emph{ASA}).
\end{frame}

\begin{frame}{APPLICATIONS: Class segmentation}
    \begin{figure}[htbp]
        \centering
        \includegraphics[width = 1 \linewidth]{images/paper2/superpixelAlgo.png}
        \centering
        \caption{Segmentation using different superpixels algorithms. (a) Original Image. (b) QS. (c) ERS. (d) SLIC. (e) LSC. (f)Ground Truth.}
        \label{fig: superpixelSegmentation}
    \end{figure}

    \begin{table}[h!]
        \centering
        \begin{adjustbox}{max width=4cm}
        \begin{tabular}{*{5}{|c}|}%%{|c|c|c|c|c|}
            \hline
            & QS & ERS & SLIC & LSC\\
            \hline
            bike & 72.2 & 74.2 & 76.3 & \bfseries{76.9}\\
            cars & 72.2 & 74.7 & 72.5 & \bfseries{76.8}\\
            person & 66.3 & 66.5 & 66.7 & \bfseries{67.0}\\
            \hline
        \end{tabular}
        \end{adjustbox}
        \caption{Accuracy using different superpixels algorithms.}
        \label{table accuracy}
    \end{table}
\end{frame}

\begin{frame}{APPLICATIONS: Weakly Supervised Semantic Segmentation}
    \begin{minipage}{\linewidth}
        \centering
        \begin{minipage}{0.45\linewidth}
            \begin{figure}[H]
                \includegraphics[width = 0.7 \linewidth]{images/paper2/semanticSegmentation.png}
                \caption{Weakly supervised semantic segmentation. (a) A training image with bounding boxes. (b) Output of soft-max layer of $ FCN_c $. (c) Coarse semantic segmentation result. (d) Superpixels with higher probability of foreground. (e) Fore-/Background segmentation result after iterative optimization. (f) Refined semantic segmentation result.}
            \end{figure}
        \end{minipage}
        \hspace{0.05\linewidth}
        \begin{minipage}{0.45\linewidth}
            \begin{figure}[htbp]
                \centering
                \includegraphics[width = 1 \linewidth]{images/paper2/segmentationAlgo.png}
                \centering
                \caption{Semantic segmentation. (a) Input image. (b) Strong. (c) Bbox-seg. (d) $ Joint_{sp} $ (LSC) }
            \end{figure}
            \begin{table}[H]
                \begin{adjustbox}{max width=4cm}
                    \begin{tabular}{*{3}{|c}|}%%{|c|c|c|}
                        \hline
                        Strong\footnotemark[1]& Bbox-seg\footnotemark[1] & $ Joint_{sp} $ \\
                        \hline
                        62.5 & 60.6 & \bfseries{64.0} \\
                        \hline
                    \end{tabular}
                \end{adjustbox}
                \caption{Semantic segmentation accuracy in terms of Mean IOU (\%)}
            \end{table}
        \end{minipage}
    \end{minipage}
    \footnotetext[1]{\tiny G. Papandreou, L. Chen, K. Murphy, and A. Yuille, “Weakly-and semi-
    supervised learning of a deep convolutional network for semantic image segmentation,” in Proc. ICCV, pp. 1742–1750, Dec. 2015}
\end{frame}

\begin{frame}{CONCLUSIONS}
    The LSC algorithm seems to be the best in terms of adherence to the
    boundary and in the creation of superpixels with increasingly regular
    shape, but there are still two problems to solve:
    \begin{enumerate}
        \item The number K of superpixels entered manually
        \item New similarity techniques to improve performance
    \end{enumerate}
\end{frame}


% !TeX root = constructions.tex

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\chapter{Doubling a Cube}\label{c.cube}

\section{Messer's doubling of a cube}\label{s.cube1}

To double a cube we need to construct  $\sqrt[3]{2}$. This construction is based on \cite{newton,hwa}.

\subsection{Dividing a length into thirds}

Lang \cite{lang} shows efficient constructs for rational fractions of the length of the side of a square (piece of paper). Here, we need to divide the side of the square into thirds.

First, fold the square in half to locate the point $J=(1,1/2)$. Next, draw the lines $\overline{AC}$ and $\overline{BJ}$.
\begin{center}
\begin{tikzpicture}[scale=.8]
% Draw square
\coordinate (A) at (0,12);
\coordinate (B) at (0,0);
\coordinate (C) at (12,0);
\coordinate (D) at (12,12);

\fill (A) circle (2pt) node[left]  {$A=(0,1)$};
\fill (B) circle (2pt) node[left]  {$B=(0,0)$};
\fill (C) circle (2pt) node[right] {$C=(1,0)$};
\fill (D) circle (2pt) node[right] {$D=(1,1)$};

\draw [thick] (A)  -- (B) -- (C) -- (D) -- cycle;

% Divide a side in half

\coordinate (M)  at (0,6);
\coordinate (N) at (12,6);
\fill (M) circle (2pt) node[left] {$I=(0,1/2)$};
\fill (N) circle (2pt) node[right] {$J=(1,1/2)$};
\draw [thick,dashed] (M) -- (N);

\draw [thick,dotted,name path=ac] (A) --
   node[near start,above,xshift=24pt] {$y=1-x$} (C);
\draw [thick,dotted,name path=be2] (B) --
   node[near start,above,xshift=-12pt,yshift=-2pt] {$y=\disfrac{1}{2}x$} (N);

\path [name intersections = {of = ac and be2, by = {I}}];
\fill (I) circle (2pt)
   node[below,xshift=-6pt,yshift=-8pt] {$K=$}
   node[below,xshift=-6pt,yshift=-20pt] {$(2/3,1/3)$};

\coordinate (E)  at (0,4);
\coordinate (F) at (12,4);
\fill (E) circle (2pt) node[left] {$E=(0,1/3)$};
\fill (F) circle (2pt) node[right] {$F=(1,1/3)$};
\draw [thick,dashed] (E) -- (F);

\coordinate (G)  at (0,8);
\coordinate (H) at (12,8);
\fill (G) circle (2pt) node[left] {$G=(0,2/3)$};
\fill (H) circle (2pt) node[right] {$H=(1,2/3)$};
\draw [very thick,dotted] (G) -- (H);
\end{tikzpicture}
\end{center}

The coordinates of their point of intersection $K$ are obtained by solving the two equations:
\vspace{-2ex}
\begin{form}{1.1}
y&=&1-x\\
y&=&\disfrac{1}{2}x\,.
\end{form}
The result is $x=2/3, y=1/3$.

Construct the line $\overline{EF}$ perpendicular to $\overline{AB}$ through $K$, and construct the reflection $\overline{GH}$ of $\overline{BC}$ around $\overline{EF}$. The side of the square has been divided into thirds.

\subsection{Building $\sqrt[3]{2}$}

\begin{center}
\begin{tikzpicture}[scale=.9]
% Draw and label square
\coordinate (A) at (0,12);
\coordinate (B) at (0,0);
\coordinate (C) at (12,0);
\coordinate (D) at (12,12);
\fill (A) circle (1.5pt) node[left]  {$A$};
\fill (B) circle (1.5pt) node[left]  {$B$};
\fill (C) circle (1.5pt) node[right] {$C$};
\fill (D) circle (1.5pt) node[right] {$D$};
\draw (B) rectangle +(12pt,12pt);
\draw[rotate=90] (C) rectangle +(12pt,12pt);
\draw [thick] (A)  -- (B) -- (C) -- (D) -- cycle;

% Draw line one-third from botton
\coordinate (E)  at (0,4);
\coordinate (F) at (12,4);
\fill (E) circle (1.5pt) node[left] {$E$};
\fill (F) circle (1.5pt) node[right] {$F$};
\draw [very thick,dotted,name path=ef] (E) -- (F);

% Draw line two-thirds from bottom
\coordinate (G)  at (0,8);
\coordinate (H) at (12,8);
\fill (G) circle (1.5pt) node[left] {$G$};
\fill (H) circle (1.5pt) node[right] {$H$};
\draw[rotate=-90] (G) rectangle +(12pt,12pt);
\draw [very thick,dotted] (G) -- (H);

% Draw reflections of C and F
\coordinate (CP) at (0,5.31);
\coordinate (FP) at (2.96,8);
\fill (CP) circle (1.5pt)
  node[left] {$C'$}
  node[above right,yshift=8pt] {$\alpha$}
  node[below right,xshift=-2pt,yshift=-12pt] {$\alpha'$};
\fill (FP) circle (1.5pt)
  node[above] {$F'$}
  node[below left,xshift=-8pt] {$\alpha'$};
\draw[rotate=-50] (CP) rectangle +(12pt,12pt);
\draw[very thick,dotted] (CP) -- (FP);

% Draw fold and fold arrows
% Tangent is y = 2.26x - 10.9
% Crosses x axis at (4.83,0)
\coordinate (J) at (4.83,0);
\fill (J) circle (1.5pt)
    node[below] {$J$}
    node[above left,xshift=-8pt] {$\alpha$};
\draw [very thick,dashed,name path=jd] (J) -- node[very near end,left] {$l$} (10,12);
\draw[thick,dotted,bend right=40,->] (C) to ($(CP)+(4pt,0)$);
\draw[thick,dotted,bend right=40,->] (F) to ($(FP)+(4pt,4pt)$);

% Draw hypotenuses of right triangles
\draw[very thick,dotted] (CP) -- (J);
\path (J)  -- (C);

% Labels on BC and hypotenuses
\path (CP) -- node[right] {$(a+1)-b$} (J);
\path (J)  -- node[below] {$(a+1)-b$} (C);
\path (B)  -- node[below] {$b$} (J);
\path (C)  -- node[right] {$\disfrac{a+1}{3}$} (F);
\path (CP) -- node[right,xshift=10pt] {$\disfrac{a+1}{3}$} (FP);

% Labels on AB
\draw[<->] ($(A)+(-1,0)$)    --
  node[fill=white] {$a$} ($(CP)+(-1,0)$);
\draw[<->] ($(CP)+(-1,0)$)   --
  node[fill=white] {$1$} ($(B)+(-1,0)$);
\draw[<->] ($(CP)+(-2.5,0)$) --
  node[fill=white] {$a-\disfrac{a+1}{3}$} ($(G)+(-2.5,0)$);
\draw[<->] ($(A)+(-2.5,0)$) --
  node[fill=white] {$\disfrac{a+1}{3}$} ($(G)+(-2.5,0)$);
\end{tikzpicture}
\end{center}

Label the side of the square by $a+1$. The construction will show that $a=\sqrt[3]{2}$.

Using Axiom~6 place $C$ at $C'$ on $\overline{AB}$ and $F$ at $F'$ on $\overline{GH}$.  Denote by $J$ the point intersection of the fold with $\overline{BC}$ and denote by $b$ the length of $\overline{BJ}$. The length of $\overline{JC}$ is $(a+1)-b$.

When the fold is performed, the line segment $\overline{JC}$ is reflected onto the line segment $\overline{JC'}$ of the same length, and $\overline{CF}$ is folded onto the line segment $\overline{C'F'}$ of the same length. A simple computation shows that the length of $\overline{GC'}$ is:
\begin{equation}
a-\disfrac{a+1}{3}=\disfrac{2a-1}{3}\,.\label{eq.one-third}
\end{equation}
Finally, since $\angle FCJ$ is a right angle, so is $\angle F'C'J$.

$\triangle C'BJ$ is a right triangle so by Pythagoras' theorem:
\vspace{-2ex}
\begin{form}{1.1}
1^2 + b^2 &=& ((a+1)-b)^2\\
%&=& a^2+2a+1 - 2(a+1)b + b^2\\
a^2+2a - 2(a+1)b&=&0\\
b&=&\disfrac{a^2+2a}{2(a+1)}\,.
\end{form}

$\angle GC'F' + \angle F'C'J + \angle JC'B = 180^\circ$ since they form the straight line $\overline{GB}$. Denote $\angle GC'F'$ by $\alpha$.
\[
\angle JC'B=180^\circ - \angle F'C'J - \angle GC'F'= 180^\circ - 90^\circ - \alpha=90^\circ -\alpha\,,
\]
which we denote by $\alpha'$. The triangles $\triangle C'BJ$, $\triangle F'GC'$ are right triangles, so $\angle C'JB=\alpha$ and $\angle C'F'G=\alpha'$. Therefore, the triangles are similar and using Equation~\ref{eq.one-third} we have:
\[
\disfrac{b}{(a+1)-b}=\disfrac{\disfrac{2a-1}{3}}{\disfrac{a+1}{3}}\,.
\]
Substituting for $b$:
\vspace{-2ex}
\begin{form}{1.8}
\disfrac{\disfrac{a^2+2a}{2(a+1)}}{(a+1)-\disfrac{a^2+2a}{2(a+1)}}&=&\disfrac{2a-1}{a+1}\\
%\disfrac{a^2+2a}{(a+1)\cdot 2(a+1)-(a^2+2a)}&=&\disfrac{2a-1}{a+1}\\
\disfrac{a^2+2a}{a^2+2a +2}&=&\disfrac{2a-1}{a+1}\,.
%a^3+3a^2+2a&=&(2a-1)(a^2+2a+2)\,.
%&=&2a^3+3a^2+2a-2\,.
\end{form}

Simplifying results in $a^3=2$ and $a=\sqrt[3]{2}$.

\newpage

\section{Beloch's doubling of a cube}\label{s.cube2}

Margharita P. Beloch formalized Axiom~6 (Section~\ref{s.ax6}) and showed that it could be used to solve cubic equations. Here we give her construction for doubling the cube. The solution of cubic equations is discussed in Chapters~\ref{c.lill}, \ref{c.beloch}.

\subsection{The construction}

Place point $A$ at $(-1,0)$ and point $B$ at $(0,-2)$. Let $p$ be the line with equation $x=1$ and let $q$ be the line with equation $y=2$. Using Axiom~6 construct a fold $l$ that places $A$ at $A'$ on $p$ and $B$ at $B'$ on $q$. Denote the intersection of the fold and the $y$-axis by $Y$ and the intersection of the fold and $x$-axis by $X$.

\begin{center}
\begin{tikzpicture}[scale=1]
% Draw and label square
\coordinate (O) at (0,0);
\coordinate (A) at (-2,0);
\coordinate (B) at (0,-4);
\fill (O) circle (1.5pt)
  node[below left,xshift=-7pt] {$O$}
  node[below left,yshift=-12pt] {$(0,0)$};
\fill (A) circle (1.5pt)
  node[above left,xshift=-7pt] {$A$}
  node[below left,xshift=2pt,yshift=0pt] {$(-1,0)$};
\fill (B) circle (1.5pt)
  node[left,xshift=-12pt] {$B$}
  node[left,yshift=-12pt] {$(0,-2)$};

%\draw[thick] (0,-4.5) -- node[near start, left,yshift=-20pt] {$p$} +(0,10);
%\draw[thick] (-5,0) -- node[very near start, below,xshift=-16pt] {$q$} +(12,0);
\draw[thick] (0,-4.5) --  node[very near end,above left,yshift=12pt] {$y$-\textsf{axis}} +(0,10);
\draw[thick] (-5,0)   -- node[very near start,above left] {$x$-\textsf{axis}} +(12,0);
\draw[very thick] (2,-4.5) -- node[very near start, right,yshift=-10pt] {$p\!:x=1$} +(0,10);
\draw[very thick] (-5,4) -- node[very near start, above,xshift=-16pt] {$q\!: y=2$} +(12,0);

\coordinate (AP) at (2,5);
\fill (AP) circle (1.5pt) node[above right] {$A'$};
\coordinate (BP) at (6.34,4);
\fill (BP) circle (1.5pt) node[above right] {$B'$};

% Tangent y = -0.8x + 1.26

% Exchanged X and Y
\coordinate (X) at (0,2.52);
\coordinate (Y) at (3.15,0);
\fill (X) circle (1.5pt) node[right,xshift=4pt,yshift=2pt] {$Y$};
\fill (Y) circle (1.5pt) node[above right,xshift=10pt] {$X$};
\draw [very thick,dashed] ($(X)!-1.1!(Y)$) -- node[very near end,right,xshift=8pt] {$l$} ($(X)!2!(Y)$);

\draw [very thick,dotted] (A) -- (AP);
\draw [very thick,dotted] (B) -- (BP);

\draw[thick,dotted,bend left=40,->] (A) to ($(AP)+(-4pt,0)$);
\draw[thick,dotted,bend left=40,->] (B) to ($(BP)+(-6pt,-3pt)$);

%\node[above left] at (0,4) {$(0,2)$};
%\node[below left] at (2,0) {$(1,0)$};

\end{tikzpicture}
\end{center}

\newpage

\subsection{Proof}

Let us extract a simplified diagram:

\begin{center}
\begin{tikzpicture}[scale=.9]
\coordinate (O) at (0,0);
\coordinate (A) at (-2,0);
\coordinate (B) at (0,-4);
\fill (O) circle (1.5pt)
  node[below left,xshift=-7pt] {$O$};
\fill (A) circle (1.5pt)
  node[above left,xshift=-7pt] {$A$}
  node[above right,xshift=10pt] {$\alpha$};
\fill (B) circle (1.5pt)
  node[left,xshift=-12pt] {$B$}
  node[above right,yshift=12pt] {$\alpha'$};

\draw[thick] (0,-4.5) -- +(0,10);
\draw[thick] (-3,0)   -- +(8,0);

\coordinate (AP) at (2,5);
\fill (AP) circle (1.5pt) node[above right] {$A'$};
\coordinate (BP) at (6.34,4);
\fill (BP) circle (1.5pt) node[above right] {$B'$};

% Tangent y = -0.8x + 1.26

% Exchanged X and Y
\coordinate (X) at (0,2.52);
\coordinate (Y) at (3.15,0);
\fill (X) circle (1.5pt)
  node[right,xshift=4pt,yshift=2pt] {$Y$}
  node[below right,yshift=-14pt] {$\alpha$}
  node[below left,xshift=2pt,yshift=-12pt] {$\alpha'$};
\fill (Y) circle (1.5pt)
  node[above right,xshift=10pt] {$X$}
  node[below left,xshift=-13pt,yshift=-2pt] {$\alpha$}
  node[above left,xshift=-15pt] {$\alpha'$};
\draw [very thick,dashed] ($(X)!-.4!(Y)$) -- ($(X)!1.2!(Y)$);

\draw [very thick,dotted] (A) -- (AP);
\draw [very thick,dotted] (B) -- (BP);

\draw (0,0) rectangle +(10pt,10pt);
\draw[rotate=-130] (X) rectangle +(10pt,10pt);
\draw[rotate=145] (Y) rectangle +(10pt,10pt);

\end{tikzpicture}
\end{center}

The fold is the perpendicular bisector of $\overline{AA'}$ and $\overline{BB'}$. Therefore, $\angle AYX$ and $\angle YXB$ are right angles and $\overline{AA'}$ is parallel to $\overline{BB'}$. By alternate interior angles $\angle YAO =\angle BXO=\alpha$. If an acute angle in a right triangle is $\alpha$, the other acute angle must be $90^\circ - \alpha$, which we denote $\alpha'$. The labeling of the angles in all the triangles in the diagram follows immediately.

We have three similar triangles $\triangle AOY\sim \triangle YOX \sim \triangle XOB$. $\overline{OA}=1$, $\overline{OB}=2$ are given, so:
\vspace{-2ex}
\begin{form}{1.4}
\disfrac{\overline{OY}}{\overline{OA}}=\disfrac{\overline{OX}}{\overline{OY}}=\disfrac{\overline{OB}}{\overline{OX}}\\
\disfrac{\overline{OY}}{1}=\disfrac{\overline{OX}}{\overline{OY}}\\
\overline{OY}^2=\overline{OX}\\
\disfrac{\overline{OY}}{1}=\disfrac{2}{\overline{OX}}\\
\overline{OY}^2=\overline{OX}=\disfrac{2}{\overline{OY}}\;,
\end{form}
resulting in $\overline{OY}^3=2$ and $\overline{OY}=\sqrt[3]{2}$.


\ProvidesFile{mpc.tex}

\documentclass[a4paper]{article}

\pagestyle{empty}

\usepackage{caption}
\usepackage{subcaption}

\usepackage{hyperref}

\usepackage{float}

\bibliographystyle{plain}
\usepackage[numbers]{natbib}

\usepackage{times}

\usepackage{graphicx}
\usepackage{url}

\usepackage{amsmath,amssymb}
\usepackage{cases}
\usepackage{color}
\usepackage{tikz}

\usepackage{mymath}
\usepackage{lipm_notation}

\usetikzlibrary{snakes}

\usepackage{a4wide}
\renewcommand{\baselinestretch}{1.5}

\begin{document}

\section*{Model of the system}

\noindent We assume the following discrete-time dynamic system:

\begin{equation}
\begin{split}
    \cstate_{k+1} =& \M{A}_k \cstate_k + \M{B}_k \cjerk_k\\
    \cop_{k+1} =& \M{D}_{k} \cstate_{k+1}
\end{split}
\end{equation}

\noindent State and control variables:

\begin{equation}
    \cstate =
    \begin{bmatrix}
        c^{x}\\
        \dot{c}^{x}\\
        \ddot{c}^{x}\\
        c^{y}\\
        \dot{c}^{y}\\
        \ddot{c}^{y}\\
        c^{\theta} \\
        \dot{c}^{\theta} \\
        \ddot{c}^{\theta} \\
    \end{bmatrix},
    \quad
    \V{u} = \dddot{\V{c}} =
    \begin{bmatrix}
        \dddot{c}^{x}\\
        \dddot{c}^{y}\\
        \dddot{c}^{\theta}\\
    \end{bmatrix}
\end{equation}

\noindent Where $c^{\theta}$ is the yaw angle of the torso. The state transition and control matrices of the discretized system
are:

\begin{equation}
\M{A}_k =
\begin{bmatrix}
    \M{M}_k       & \M{0}         & \M{0} \\
    \M{0}         & \M{M}_k       & \M{0} \\
    \M{0}         & \M{0}         & \M{M}_k \\
\end{bmatrix}
\end{equation}
\noindent where $\M{M}_k$ is:
\begin{equation}
\M{M}_k =
\begin{bmatrix}
    1       & T_k   & T_k^2/2\\
    0       & 1     & T_k    \\
    0       & 0     & 1      \\
\end{bmatrix}
\end{equation}
\noindent Control matrix:
\begin{equation}
\quad
\M{B}_k =
\begin{bmatrix}
    T_k^3/6 & 0       & 0       \\
    T_k^2/2 & 0       & 0       \\
    T       & 0       & 0       \\
    0       & T_k^3/6 & 0       \\
    0       & T_k^2/2 & 0       \\
    0       & T       & 0       \\
    0       & 0       & T_k^3/6 \\
    0       & 0       & T_k^2/2 \\
    0       & 0       & T
\end{bmatrix}
\end{equation}

\noindent Output matrix:
\begin{equation}
\quad
\M{D}_k =
\begin{bmatrix}
    1 & 0 & -\frac{c_{k}^{z}}{g} & 0 & 0 & 0 & 0 & 0 & 0\\
    0 & 0 & 0 & 1 & 0 & -\frac{c_{k}^{z}}{g} & 0 & 0 & 0\\
\end{bmatrix}
\end{equation}

\noindent The state vector does not contain the feet orientations and their derivatives. The reason therefor is that we are interested only in the feet positions and orientations when they are static on the ground.

\section*{Condensation of the system matrices}

\noindent We put the system matrices in the condensed form for the whole preview horizon ($N$ intervals):

\begin{equation}
\begin{split}
    \cState_{i+1} = \M{U}_{x} \cstate_{0} + \M{U}_{u} \cJerk_{i}\\
    \CoP_{i+1} = \M{O}_{x} \cstate_{0} + \M{O}_{u} \cJerk_{i}
\end{split}
\end{equation}

\noindent And corresponding matrices:

\begin{equation}
    \M{U}_{x} =
        \begin{bmatrix}
        \M{A}_0    \\
        \M{A}_1 \M{A}_0  \\
        \vdots           \\
        \M{A}_{N-1} \dots \M{A}_0 \\
        \end{bmatrix}
    \quad\quad
    \M{U}_{u} =
        \begin{bmatrix}
        \M{B}_0                             & \M{0}                                 & \dots & \M{0} \\
        \M{A}_1 \M{B}_0                     & \M{B}_1                               & \dots & \M{0} \\
        \vdots                              & \vdots                                & \ddots& \vdots \\
        \M{A}_{N-1} \dots \M{A}_1 \M{B}_0   & \M{A}_{N-1} \dots \M{A}_2 \M{B}_1     & \dots & \M{B}_{N-1} \\
        \end{bmatrix}
\end{equation}

\begin{equation}
    \M{O}_{x} =
        \begin{bmatrix}
        \M{D}_1 \M{A}_0    \\
        \M{D}_2 \M{A}_1 \M{A}_0  \\
        \vdots           \\
        \M{D}_{N-1} \M{A}_{N-2} \dots \M{A}_0 \\
        \end{bmatrix}
    \quad\quad
    \M{O}_{u} =
        \begin{bmatrix}
        \M{D}_1 \M{B}_0                     & \M{0}                                 & \dots & \M{0} \\
        \M{D}_2 \M{A}_1 \M{B}_0             & \M{D}_2 \M{B}_1                       & \dots & \M{0} \\
        \vdots                              & \vdots                                & \ddots& \vdots \\
        \M{D}_{N-1} \M{A}_{N-2} \dots \M{A}_1 \M{B}_0   & \M{D}_{N-1} \M{A}_{N-2} \dots \M{A}_2 \M{B}_1     & \dots & \M{D}_{N-1}\M{B}_{N-2} \\
        \end{bmatrix}
\end{equation}

\section*{Constraints}

Let $\SET{I}$ be the set containing indices of sampling intervals, $\SET{I}^l_f
\subset \SET{I}$ be the set of indices where orientations of the left foot are
fixed within $N$ timesteps of a preview, the set $\SET{I}^r_f$ is defined equivalently for the right foot. Content of the sets $\SET{I}^l_f$ and $\SET{I}^r_f$ are defined by the finite state machine at the beginning of
each preview and are used to build the constraints and selection matrices. For each step there is a defined velocity and duration.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\paragraph{Footstep positions}
Footstep positions are expressed in the global frame - in general to impose simple bounds as constraints on the variable footstep positions we need to translate and rotate from global to local foot frame.
In this case we assume that the constraints on the feet positions have the shape of rectangles. Furthermore, we do not consider the rotation of the constraints.\\

\noindent The footstep position and orientation corresponding to $k$-th ($k = 1,\dots,N$) sampling interval is denoted as $\V{f}_k = (f^x_k, f^y_k, f^{\theta}_k)$.
We can map the $M$ footsteps into $N$ sampling intervals of an MPC using the following formula:

\begin{equation}
\begin{split}
    \underbrace{
    \begin{bmatrix}
        \M{f}_1 \\
        \vdots \\
        \M{f}_N
    \end{bmatrix}
    }_{\M{F}_{i+1}}
    & =
    \begin{bmatrix}
        1   &  0   &   \dots   &   0 \\
        1   &  0   &   \dots   &   0 \\
        0   &  1   &   \dots   &   0 \\
        0   &  1   &   \dots   &   0 \\
        0   &  1   &   \dots   &   0 \\
        \vdots  &  \vdots  &   \ddots  &   \vdots \\
        0   &  0   &   \dots   &   1 \\
    \end{bmatrix}
    \begin{bmatrix}
        \overline{\M{f}}_0\\
        \vdots\\
        \overline{\M{f}}_M \\
    \end{bmatrix}
    =
    \underbrace{
    \begin{bmatrix}
        1   \\
        1   \\
        0   \\
        0   \\
        0   \\
        \vdots  \\
        0   \\
    \end{bmatrix}}_{\M{V}_{i+1}}
    \overline{\M{f}_0}
    +
    \underbrace{
    \begin{bmatrix}
        0   &   \dots   &   0 \\
        0   &   \dots   &   0 \\
        1   &   \dots   &   0 \\
        1   &   \dots   &   0 \\
        1   &   \dots   &   0 \\
        \vdots  &   \ddots  &   \vdots \\
        0   &   \dots   &   1 \\
    \end{bmatrix}}_{\overline{\M{V}}_{i+1}}
    \underbrace{
    \begin{bmatrix}
        \overline{\M{f}}_1 \\
        \vdots\\
        \overline{\M{f}}_M\\
    \end{bmatrix}}_{\overline{\M{F}}_{i+1}}
\end{split}
\end{equation}

\noindent $\overline{\M{V}}_{i+1}$ matrix has $N$ rows corresponding to $N$ time intervals and $M$ columns corresponding to $M$ footsteps in the preview horizon. Equation 11
will be used in the objective function in order to express footsteps in terms of decision variables $\overline{\M{F}}_{i+1}$. Matrices $\overline{\M{V}}_{i+1}$, $\M{V}_{i+1}$ are built before each preview based on the states previewed by the finite state machine.
States are previewed according to the time of the preview, sampling time of one interval of the preview and duration of each allowed state. \\

\noindent The difference between two consecutive steps (position of the next step with respect to the previous one) should lie within a rectangle. We therefore constrain the position
of the next footstep with respect to the previous footstep for all footsteps in the preview. Rotation of this constraint is not taken into account, for example, for three steps in the preview the second step's rotation is not considered when constraining the third step.
Potentially, it can lead to problems such as self-collisions, however in practice this seems to be of lesser importance especially when violent rotations are prohibited. \\

\noindent We have therefore:

\begin{equation}
\begin{bmatrix}
    \ubar{p}^{x}_{k} \\
    \ubar{p}^{y}_{k}
\end{bmatrix}
\le
\begin{bmatrix}
    \overline{{f}}^{x}_{k+1} - \overline{{f}}^{x}_{k} \\
    \overline{{f}}^{y}_{k+1} - \overline{{f}}^{y}_{k}
\end{bmatrix}
 \le
\begin{bmatrix}
    \bar{p}^{x}_{k} \\
    \bar{p}^{y}_{k}
\end{bmatrix}
, \quad k = 0 \dots M-1
\end{equation}

\noindent Where $M$ is the number of steps in the preview.

\noindent In short:

\begin{equation}
\ubarV{P} \le \M{A}_{p}\V{X} \le \barV{P}
\end{equation}

\noindent Where $\V{X}$ is the decision variables vector.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\paragraph{CoP position}
Bounds on the CoP are expressed in the global frame. Orientations $f^{\theta}_k$ of the footsteps are disregarded in this constraint. We disregard them because of the geometry of the constraint we assume to avoid
nonlinearity. Namely, we constrain the CoP to lie within much smaller bounds which do not change with the orientations of the feet. These smaller bounds are represented conceptually as a circle and approximated by a square inscribed therein.
Therefore, as circle is invariant to the rotation, we can drop the rotation matrix from the CoP constraints but keep the feet rotations among decision variables which will appear in the objective function.

\begin{equation}
\begin{bmatrix}
    \underline{z}^{x}_{k} \\
    \underline{z}^{y}_{k}
\end{bmatrix}
\leq
\begin{bmatrix}
    z^{x}_{k} - f^{x}_{k} \\
    z^{y}_{k} - f^{y}_{k}
\end{bmatrix}
\leq
\begin{bmatrix}
    \overline{z}^{x}_{k} \\
    \overline{z}^{y}_{k}
\end{bmatrix}
\quad k = 1 \dots N
\end{equation}

\noindent In short:

\begin{equation}
\ubarV{Z} \le \M{A}_{z}\V{X} \le \barV{Z}
\end{equation}

\section*{Other variables}

\paragraph{Decision variables}

\begin{equation}
    \quad
    \V{X} =
    \begin{bmatrix}
        \dddot{\M{C}} \\
        \overline{\M{F}}^{x} \\
        \overline{\M{F}}^{y} \\
        \overline{\M{F}}^{\theta}
    \end{bmatrix}
    \quad
\end{equation}

\section*{Objective function}

\begin{equation}
\begin{split}
    \MINIMIZE{\M{X}}  & \frac{\beta}{2} \NORM{\cVel^{x} - \cVel^{x}_{ref}}^2 + \frac{\beta}{2} \NORM{\cVel^{y} - \cVel^{y}_{ref}}^2 + \\
                        & \frac{\gamma}{2}  \NORM{\CoP^{x} - \M{F}^{x}}^2 + \frac{\gamma}{2}  \NORM{\CoP^{y} - \M{F}^{y}}^2 +\\
                        & \frac{\alpha}{2} \NORM{\cJerk^{x}}^2 + \frac{\alpha}{2} \NORM{\cJerk^{y}}^2 + \frac{\gamma}{2} \NORM{\M{F}^{\theta} - \cPos^{\theta}}^2 +\\
                        & \frac{\beta}{2} \NORM{\cVel^{\theta} - \cVel^{\theta}_{ref}}^2 +\\
                        & \frac{\alpha}{2} \NORM{\cJerk^{\theta}}^2 \\
    \SUBJECTTO          & \ubarV{P} \le \M{A}_{p}\V{X} \le \barV{P} \\
                        & \ubarV{Z} \le \M{A}_{z}\V{X} \le \barV{Z}
\end{split}
\end{equation}

\section*{Hierarchical least squares problem}
\begin{description}
    \item[Level 1:]
        \begin{equation}
        \begin{split}
            & \ubarV{Z} \le \M{A}_{z}\V{X} \le \barV{Z} \\
            & \ubarV{P} \le \M{A}_{p}\V{X} \le \barV{P}
        \end{split}
        \end{equation}

    \item[Level 2:]
        \begin{equation}
        \begin{split}
            & \sqrt{\frac{\alpha}{2}} \cJerk = 0 \\
            & \sqrt{\frac{\beta}{2}} \M{S}_{vx} \V{U}_{u} \cJerk = \sqrt{\frac{\beta}{2}} (\cVel^{x}_{ref} - \M{S}_{vx} \V{U}_{x} \cstate_{0})\\
            & \sqrt{\frac{\beta}{2}} \M{S}_{vy} \V{U}_{u} \cJerk = \sqrt{\frac{\beta}{2}} (\cVel^{y}_{ref} - \M{S}_{vy} \V{U}_{x} \cstate_{0})\\
            & \sqrt{\frac{\beta}{2}} \M{S}_{vt} \V{U}_{u} \cJerk = \sqrt{\frac{\beta}{2}} (\cVel^{\theta}_{ref} - \M{S}_{vt} \V{U}_{x} \cstate_{0})\\
            & \sqrt{\frac{\gamma}{2}} (\M{S}_{cx} \M{D} \V{U}_{u} \cJerk - \overline{\M{V}} \overline{\M{F}}^{x}) = \sqrt{\frac{\gamma}{2}} (\M{V}\overline{\M{f}}^{x}_{0} - \M{S}_{cx} \M{D} \V{U}_{x} \cstate_{0})\\
            & \sqrt{\frac{\gamma}{2}} (\M{S}_{cy} \M{D} \V{U}_{u} \cJerk - \overline{\M{V}} \overline{\M{F}}^{y}) = \sqrt{\frac{\gamma}{2}} (\M{V}\overline{\M{f}}^{y}_{0} - \M{S}_{cy} \M{D} \V{U}_{x} \cstate_{0})\\
            & \sqrt{\frac{\gamma}{2}} (\overline{\M{V}} \overline{\M{F}}^{\theta} - \M{S}_{t} \V{U}_{u} \cJerk) = \sqrt{\frac{\gamma}{2}} (\M{V}\overline{\M{f}}^{\theta}_{0} - \M{S}_{t} \V{U}_{x} \cstate_{0})\\
        \end{split}
        \end{equation}
\end{description}

\section*{Swing foot trajectory generation}

Trajectory is generated using cubic polynomial of the form
\begin{equation}
    at^3 + bt^2 + ct + d = y_{swing},
\end{equation}
where $t$ is time instance; $a,b,c,d$ are coefficients; and $y_{swing}$ is position of the swing
foot at time $t$.

\noindent Derivatives of the cubic polynomial are
\begin{equation}
\begin{split}
    & 3at^2 + 2bt + c = \dot{y}_{swing},\\
    & 6at + 2b = \ddot{y}_{swing},\\
    & 6a = \dddot{y}_{swing}.\\
\end{split}
\end{equation}

\noindent Second derivative (acceleration) will be tracked by the whole-body controller. Hence, the second derivative equation is used to generate
trajectory.

\noindent Knowing initial and final time and position of the motion, coefficients $a$ and $b$ can be expressed as follows
\begin{equation}
\begin{split}
    & a = -\frac{2}{t^{3}_f}(y_{swing,f} - y_{swing,i})\\
    & b = \frac{3}{t^{2}_f}(y_{swing,f} - y_{swing,i})\\
\end{split}
\end{equation}

\noindent Accelerations to be tracked can be found then, using
\begin{equation}
\begin{split}
    & -\frac{12}{t^{3}_f}(y_{swing,f} - y_{swing,i})t + \frac{6}{t^{2}_f}(y_{swing,f} - y_{swing,i}) = \ddot{y}_{swing}\\
\end{split}
\end{equation}

\noindent for every swing phase the above polynomial is evaluated at a desired frequency between $[0, T_{support}]$. With initial and final
positions ($y_{swing, i}$ and $y_{swing, f}$) taken from the planned footsteps.
During transitional double support all accelerations are set to zero. For the $z$ coordinate a fixed
step height $h_{step}$ is used to determine the trajectory as follows
\begin{equation}
    y_{swing,f}^z =
    \left\{
        \begin{array}{ll}
            h_{step}    & t \le \frac{1}{2}T_{support}, \\
            0           & t > \frac{1}{2}T_{support}\\
        \end{array}
    \right.
\end{equation}

\noindent Accelerations of the torso ($\ddot{c}^x$, $\ddot{c}^y$, $\ddot{c}^\theta$) are taken directly from the state vector
(they are not interpolated using polynomials).

\end{document}


\section{Gaussian Product Wavefunction}
\label{sec:ionwf}

The Gaussian Product wavefunction implements eq.~\ref{eq:gauss_prod_wf}
\begin{equation}
\Psi(\vec{R}) = \prod_{i=1}^N \exp\left[ -\frac{(\vec{R}_i-\vec{R}_i^o)^2}{2\sigma_i^2} \right]
\label{eq:gauss_prod_wf},
\end{equation}
where $\vec{R}_i$ is the position of the $i^{\text{th}}$ quantum particle and $\vec{R}_i^o$ is its center. $\sigma_i$ is the width of the Gaussian orbital around center $i$.

This variational wavefunction enhances single-particle density at chosen spatial locations with adjustable strengths. It is useful whenever such localization is physically relevant yet not captured by other parts of the trial wavefunction. For example, in an electron-ion simulation of a solid, the ions are localized around their crystal lattice sites. This single-particle localization is not captured by the ion-ion Jastrow. Therefore the addition of this localization term will improve the wavefunction. The simplest use case of this wavefunction is perhaps the quantum harmonic oscillator (please see the ``tests/models/sho'' folder for examples).

\subsubsection{Input Specification}

\begin{table}[h]
\begin{center}
\begin{tabular}{l c c c l }
\hline
\multicolumn{5}{l}{Gaussian Product Wavefunction (ionwf)} \\
\hline
\bfseries name & \bfseries datatype & \bfseries values & \bfseries defaults  & \bfseries description \\
\hline
name & text & ionwf & (required) & Unique name for this wavefunction \\
width & floats & 1.0 -1 & (required) & Widths of Gaussian orbitals.\\
source & text & ion0 & (required) & Name of classical particle set.\\
\hline
\end{tabular}
\end{center}
\end{table}

\FloatBarrier

Additional information:
\begin{itemize}
\item \texttt{width} There must be one width provided for each quantum particle. If a negative width is given, then its corresponding Gaussian orbital is removed. Negative width is useful if one wants to use Gaussian wavefunction for a subset of the quantum particles.
\item \texttt{source} The Gaussian centers must be specified in the form of a classical particle set. This classical particle set is likely the ion positions ``ion0'', hence the name ``ionwf''. However, one may define arbitrary centers using a different particle set. Please refer to examples in `tests/models/sho'.
\end{itemize}

\subsection{Example Use Case}
\begin{lstlisting}
  <qmcsystem>
    <simulationcell>
      <parameter name="bconds">
            n n n
      </parameter>
    </simulationcell>
    <particleset name="e">
      <group name="u" size="1">
        <parameter name="mass">5.0</parameter>
        <attrib name="position" datatype="posArray" condition="0">
          0.0001 -0.0001 0.0002
        </attrib>
      </group>
    </particleset>
    <particleset name="ion0" size="1">
      <group name="H">
        <attrib name="position" datatype="posArray" condition="0">
          0 0 0
        </attrib>
      </group>
    </particleset>
    <wavefunction target="e" id="psi0">
      <ionwf name="iwf" source="ion0" width="0.8165"/>
    </wavefunction>
    <hamiltonian name="h0" type="generic" target="e">
      <extpot type="HarmonicExt" mass="5.0" energy="0.3"/>
      <estimator type="latticedeviation" name="latdev"
        target="e"    tgroup="u"
        source="ion0" sgroup="H"/>
    </hamiltonian>
  </qmcsystem>
\end{lstlisting}