\section{ODE solvers}

ODE solvers implement animation algorithms applied at each time step to integrate time and compute positions and velocities one time step forward in time.
% Each step of the algorithm is implemented using a visitor to traverse the scenegraph starting from the node the solver is attached to.
The solvers do not directly address the physical models.
They apply abstract mechanical operations to state vectors represented by IDs, as illustrated in the algorithm shown in Figure~\ref{fig:eulerexplicit}.
\begin{figure}
\begin{center}
\begin{algorithmic}
\STATE void  \textbf{ExplicitEulerSolver::solve(VecId x, VecId v, double dt)}
\STATE create auxiliary vectors a,f
\STATE resetForce(f)
\STATE accumulateForce(f,x,v)
\STATE computeAcceleration(a,f)
\STATE project(a,a)
\STATE v += a * dt
\STATE x += v * dt
\end{algorithmic}
\caption{Euler's explicit time integration.}
\label{fig:eulerexplicit}
\end{center}
\end{figure}
Each mechanical operation, such as allocating a state vector or accumulating the forces, is implemented using a specialized visitor parameterized on vector IDs or control values such as dt.
This allows to implement the solvers completely independenly of the physical model.
Each vector used by a solver ID is actually scattered over all the state vector containers in the different nodes in the scope of the solver.
Some vector operations such as the dot product apply only to the independent DOFs, stored in the state vectors not attached to a parent by a mapping.
Notice that this design avoids the assembly of global state vectors (i.e. copying Vec3 and quaternions to and from  vectors of scalars).
Moreover, the virtual function calls are resolved at the granularity of the state vectors (i.e. all the particles together, and all the moving frames together) rather than each primitive (i.e. each particle and each frame independently), and allow to optimize each implementation independently.
There is thus virtually no loss of efficiency when mixing arbitrary types in the same simulation.

% The ODE solver creates visitors and applies them to its parent node.
% The ComputeDf visitor presented in Figure~\ref{fig:DfVisitor} finds no mapping nor DOF at the root level (functions are called only if the corresponding component is present in the node), and continues the traversal in the two child branches.
% Each object computes its own force change df corresponding to its own displacement dx, as previously explained.
% The objects are independent because there is no mapping to a commom DOF component at the scene level.
% Each object manages its own state vectors.
% Thus, using visitors allows the solver to transparently handle an arbitrary number of objects of arbitrary types in the same scene.
% One can use visitors without knowing to which objects they apply.
% This is a key feature of the SOFA design, which allows us design the algorithms once and to apply them to all types of simulated objects.
% Notice that this design avoids the assembly of global state vectors (i.e. copying Vec3 and quaternions to and from  vectors of scalars).
% Moreover, the virtual function calls are resolved at the granularity of the state vectors (i.e. all the particles together, and all the moving frames together) rather than each primitive (i.e. each particle and each frame independently), and allow to optimize each implementation independently.
% There is thus virtually no loss of efficiency when mixing arbitrary types in the same simulation.
% Hence the ``versatile yet efficient'' motto of SOFA.

We have identified two families of ODE solvers.
The first contains the explicit solvers, which compute the derivative at the beginning of the time step. They are variants of the Euler explicit solver presented in Figure~\ref{fig:eulerexplicit}, and are easily implemented in Sofa using the same operators.
The second family contains the implicit solvers, which consider the derivative at the end or somewhere in the middle of the time step. They typically require the solution of equation systems such as:
\begin{equation}
\label{eq:linear-system}
\underbrace{\left(\alpha \M  + \beta \B  + \gamma \K \right)}_{\mathbf{A}}   \Vdv =  \vec b
%\underbrace{\P \left(\alpha \M  + \beta \B  + \gamma \K \right)}_{\mathbf{A}}   \Vdv =  \vec b
\end{equation}
where $\M$ is the mass matrix, $\K = \frac{\partial \Vf}{\partial \Vx}$ and $\B = \frac{\partial \Vf}{\partial \Vv}$ respectively are the \textit{stiffness} and \textit{damping} matrices (the method is explicit if $\beta$ and $\gamma$ are null). In order to apply simple displacement constraints,  a projection matrix $\P$ can be used, and the system becomes $\P^T \mathbf{A} \P \Vdv =\P^T \vec b $~\cite{baraff98large}.
Implicit integration has the advantage of being more stable for stiff forces or large time steps. However, solving these equation systems requires linear solvers, discussed in the next section.
Currently, eight ODE solvers have been implemented, including symplectic Euler and explicit Runge-Kutta4, implicit Euler and statics solution.

\section{Linear solvers}
\subsection{Conjugate Gradient} An interesting feature of visitor-based mechanical computations is their ability to efficiently and transparently compute matrix products.
Thus, we have proposed in SOFA an implementation of the Conjugate Gradient, based on the graph traversal.
The visitor shown in Figure~\ref{fig:DfVisitor} computes the force change \textit{df} based on a given displacement \textit{dx}, as repeatedly performed in Conjugate Gradient algorithm.
An arbitrary number of forces and projections may be present in all the nodes, resulting in a complicated stiffness matrix, as shown in the following equation:
\begin{equation}
 \label{eq:dfdx}
\vec{df} = \sum_i  \left( \prod_{j \in path(i)} \mat J_j  \right)^T \K_i \left( \prod_{j \in path(i)} \mat J_j  \right) \vec{dx}
\end{equation}
where $\K_i$ is the stiffness matrix of force $i$, matrix $\J$ encodes the first-order mapping relation of a node with respect to its parent, and $path(i)$ is the list of nodes from the solver to the node the force applies to.
\begin{figure}
\begin{center}
\begin{tabular}{c|c}
\begin{minipage}[t]{0.52\linewidth}
\begin{algorithmic}
\STATE bool \textbf{ComputeDfVisitor::topDown}():
\STATE dof.resetF(this.df)
\IF{mapping}
\STATE mapping.applyJ(this.dx)
\ENDIF
% \FORALL {projection P}
% \STATE P.project( this.dx,this.dx )
% \ENDFOR
\RETURN true
\end{algorithmic}
\end{minipage}
&
%  \hspace{0.01\linewidth}
% &
%  \hspace{0.01\linewidth}
% &
 \begin{minipage}[t]{0.46\linewidth}
\begin{algorithmic}
\STATE void \textbf{ComputeDfVisitor::bottomUp}():
\FORALL {forceField F}
\STATE F.addDF( this.df,this.dx )
\ENDFOR
% \FORALL {projection P}
% \STATE P.project( this.df,this.df )
% \ENDFOR
\STATE mapping.applyJT(this.df)
\end{algorithmic}
 \end{minipage}
\end{tabular}
\caption{Computing $df$ given $dx$ using a visitor.}
\label{fig:DfVisitor}
\end{center}
\end{figure}
This complex product is computed using only matrix-vector products and with optimal factoring thanks to the recursive implementation.
It allows us to efficiently apply implicit time integration to arbitrary scenes using the Conjugate Gradient.
This method allows us to trade-off accuracy for speed by limiting the number of steps of the iterative solution.

\subsection{Direct Solvers} Direct solvers are also available in SOFA. They can be used as preconditionners of the conjugate gradient algorithm~\cite{CADC10} or for directly solving equation \ref{eq:linear-system}.
Their implementation are based on external libraries such as Eigen, MKL and Taucs.
When dealing with Finite Element Models, the matrices are generally very sparse and
efficient implementations based on sparse factorizations allow for fast computations.
Moreover, when dealing with specific topologies, like wire-like structures, tri-diagonal band solvers can be used for extremely fast results in $\mathcal{O}(n)$
These different linear solvers address matrices which  can be stored in different formats, adapted to the numerical library.
%or even not explicitly stored when only matrix-vector products are applied.
The type of matrix is a parameter of the linear solver, and of the visitors the solver uses.
Ten linear solvers have been implemented in \sofa{}. They can be interchanged to compare their efficiency.

\subsection{From ODE solver to linear solver}

In SOFA, all states of a mechanical object is described by its degree of freedom. The main works for the simulation are filling and inverting a matrix system in order to find the states of mechanical objects by steps of time. This system matrix can be described as below :
 \[
\left[ \textbf{MBK} \right].a=f \text{    ,  or at time n+1 :   }\left[ \textbf{MBK} \right].a_{n+1}=f_{n+1}
\]
where,
\[
\left\{
\begin{array}{l}
\textbf{M} \text { : the mass matrix   }  \\
\textbf{B} \text { : the damping matrix   }  \\
\textbf{K} \text { : the stiffness matrix   }  \\
\left[ \textbf{MBK} \right] \text {  : is a linear combination of MBK (not multiplication)   }  \\
a_{n+1} \text { : accelerator field} \\
f_{n+1} \text { : force field}
\end{array}\right.
\]
 Usually, \textbf{M} is filled by \textbf{mass} components, \textbf{K} is filled by \textbf{forcefield} or \textbf{interactionforcefield} components, \textbf{B} (often $\alpha\textbf{M}+\beta\textbf{K}$ ) and $\left[ \textbf{MBK} \right]$ are computed by \textbf{odesolver} components. The works left to invert the matrix system are done by \textbf{linearsolver} components.
\begin{center}
\includegraphics[scale=0.3]{matrix_bloc.pdf}
\end{center}
On the case for example when there are two mechanical objects, we can see a global stiffness matrix describing the two mechanical states, composed diagonal blocs and non-diagonal blocs. The diagonal blocs are filled by \textbf{mass},\textbf{forcefield} components, and the non-diagonal ones are filled by \textbf{interactionforcefield} if existed.
\paragraph{Mapping matrix contribution : } When existe a mapping on the simulation scene, the states of two mechanical objects are relied by :
\[
\begin{array}{rl}
\textbf{x}_{2} & = \Im\left(\textbf{x}_{1}\right)           \text{      ,	mapping::apply}             \\
\textbf{v}_{2} & = \left[\textbf{J}\right] \textbf{v}_{1}   \text{      ,	mapping::applyJ}
\end{array}
\]
The $\left[\textbf{J}\right]$ matrix is derivative of $\Im$ operator and is defined by the \textbf{mapping} components. The dynamic and matrix system of the two objects are relied by :
\[
\begin{array}{rl}
\textbf{f}                  & += \textbf{f}_{1}  +   \left[\textbf{J}\right]^{t} \textbf{f}_{2}         \text{      ,	mapping::applyJT}             \\
\left[ \textbf{MBK} \right] & += \left[ \textbf{MBK} \right]_{1}  + \left[\textbf{J}\right]^{t}  \left[ \textbf{MBK} \right]_{2} \left[\textbf{J}\right]
\end{array}
\]
The resolution of the system with the mapping is done in general :
\[
\left\{
\begin{array}{rl}
\textbf{a}^{n+1}        & = \left[ \textbf{MBK} \right]^{-1}  \textbf{f}^{n+1}    \\
\textbf{v}^{n+1}_{1}    & = \textbf{v}^{n}_{1}     + dt.\textbf{a}^{n+1}         \\
\textbf{x}^{n+1}_{1}    & = \textbf{x}^{n}_{1}     + dt.\textbf{v}^{n+1}         \\
\textbf{x}^{n+1}_{2}    &  \text{ ,	mapping::apply }     \\
\textbf{v}^{n+1}_{2}    &  \text{ ,	mapping::applyJ }
\end{array}
\right.
\]

\subsection{Particular implementation in SOFA}
The direct solver demands to build explicitly the matrix, and invert this matrix after every step of time in order to solve the mechanical response after a solicitation. In SOFA, there are a little more complicated component called mapping, relying geometrical and mechanical properties by master-slave (DOF-mapped object) relation. All changes of geometry or solicitation to one object interfere to other and vice versa. If the mapped object have its own mechanical behavior, it must be counted on the mechanical propagation by the mapping.
\subsubsection{self-stiffness propagation }
\[
\begin{array}{cc}
\includegraphics[scale=0.3]{stiffness_propagation_matrix.pdf}
&
\includegraphics[scale=0.35]{stiffness_propagation.pdf}
\end{array}
\]
In the simple simulation scene, \textbf{MS2} is a mapped object to the \textbf{MS1} mechanical object by the mapping. The matrix to be inverted for all mechanical response is the filled colorized one ($K_{11}$), the matrix $K_{22}$ describing mechanical properties of the second objects must contribute to $K_{11}$ by the formula :
\[
\left\{
\begin{array}{ll}
K_{11}       & += J^t * K_{22} * J               \\
\text{or,}   &         \\
K_{tempo}    & =  J^t * K_{22}                   \\
K_{11}       & += K_{tempo} * J                  \\
\end{array}
\right.
\]
By doing this computation, we propagate the stiffness of the mapped mechanical object to its root mechanical object.
\subsubsection{interaction-stiffness propagation }
In the general case, the may have a simulation scene where there are many level of mapped mechanical states (mapped of mapped state ...) and many interaction forcefield interacting between them. Therefor the stiffness of interaction forcefield and the mapped mechanical state need to be propagated through the mappings. We can imagine for one propagation, there are two simple cases.
\paragraph{Interaction beweent Real Mechanical Object and Mapped Mechanical Object}
\[
\begin{array}{cc}
\includegraphics[scale=0.3]{interaction_Real_Mapped_Matrix}
&
\includegraphics[scale=0.35]{interaction_Real_Mapped}
\end{array}
\]
In the case where one of the two mechanical states in interaction is non-mapped, the propagation can be computed directly by the formula :
\[
\left\{
\begin{array}{ll}
K_{11}       & += J^t * K_{33} * J               \\
\text{or,}   &                                   \\
K_{tempo}    & =  J^t * K_{33}                   \\
K_{11}       & += K_{tempo} * J                  \\
\text{and,}&                 \\
I_{12}       & += J^t * I_{32}                   \\
I_{21}       & += I_{23} * J
\end{array}
\right.
\]
\paragraph{Interaction beweent Mapped Mechanical Object and Mapped Mechanical Object}
\begin{center}
  \includegraphics[scale=0.3]{interaction_Mapped_Mapped}
\end{center}
In the case where the two mechanical states in interaction are mapped, the propagation can be computed by two steps. The first consist to propagate the interaction $I_{34}$ to the interation $I_{14}$ :
\[
\left\{
\begin{array}{ll}
K_{11}       & += J^t * K_{33} * J               \\
\text{or,}   &                                   \\
K_{tempo}    & =  J^t * K_{33}                   \\
K_{11}       & += K_{tempo} * J                  \\
\text{and,}&                 \\
I_{14}       & += J^t_A * I_{34}                  \\
I_{41}       & += I_{43} * J_A
\end{array}
\right.
\]
The following step can compute as the one of above paragraph, propagating the interation $I_{14}$ to $I_{12}$.

%In summary, ODE solution is performed using a hierarchy of algorithms and data structures with each level implemented in a different component: the main ODE solution algorithm , the auxiliary linear solver  parameterized by the type of matrix, and an optional preconditioner when the Conjugate Gradient linear solver is used.
%Using a direct solver requires the explicit computation and storage of the system matrix \mat A of Equation~\ref{eq:linear-system}.
%The mass and stiffness matrices are written by the components and summed at each node level. They are then multiplied by the projection and mapping matrices during visitor traversals, and stored in the solver.

\section{Constraint solvers}
\label{lm}
To handle different kinds of interactions (contact, friction, joints between particles..) between the simulated objects, SOFA allows the use of Lagrange multipliers~\cite{DDKA06}.
%see \textit{e.g.}\cite{Duriez_eurographics2008}.
%The third family of solvers involves non-trivial constraints requiring additional equations, and additional unknowns called
They may be combined with explicit or implicit integration.
Each constraint depends on the relative position of the interacting objects, and on optional parameters
(such as a friction coefficient, etc.)\footnote{For simplicity, we present the equations for two interacting objects
(rigid or deformable) $1$ and $2$, but the solution applies to arbitrary number of interacting bodies.}:
\begin{equation}
\begin{array}{c}
\Phi(\Vx_1, \Vx_2, ...) = 0 \\
\Psi(\Vx_1, \Vx_2, ... ) \geq 0
\end{array}
\label{eq:constraints}
\end{equation} where $\Phi$ represents the bilateral interaction laws (attachments, sliding joints, etc.) whereas $\Psi$ represents unilateral interaction laws (contact, friction, etc.). These functions can be non-linear.
% The solution uses Lagrange multipliers and a single linearization by time step (see~\cite{DDKA06}).
The Lagrange multipliers are computed at each simulation step.
%However, for interaction including deformations, there is often a temporal coherency on the multipliers values.
%Thus, we can provide an estimate $\tilde{\lambda}$ at the beginning of each time step and compute a correction $\Delta \lambda$ so that $\lambda = \tilde{\lambda} +\Delta \lambda$.
They add force terms to Equation (\ref{eq:linear-system}):
\begin{equation}
\begin{array}{c}
\mathbf{A}_1  \Vdv_1 = \mathbf{b}_1 + \mathbf{H}_1^T \lambda\\
\mathbf{A}_2  \Vdv_2 = \mathbf{b}_2 + \mathbf{H}_2^T \lambda
\label{eq:constraint-systeme}
\end{array}
\end{equation}
where
\begin{equation}
\mathbf{H}_1 = [\frac{\delta \Phi}{\delta \Vx_1} \  ; \  \frac{\delta \Psi}{\delta \Vx_1}  ]\qquad  \mathbf{H}_2 = [\frac{\delta \Phi}{\delta \Vx_2} \  ; \  \frac{\delta \Psi}{\delta \Vx_2}  ].
\end{equation}
Matrices $\mathbf{H}_1$ and $\mathbf{H}_2$ are stored in the mechanical state component of each node. Thus, when the constraint applies to a model that is mapped (see section \ref{sec:mappings}), the constraints are recursively mapped upward like forces to be applied to the independent degrees of freedom~\cite{Duriez_eurographics2008}.
% An example that illustrates this concept can be found in \cite{Duriez_eurographics2008}.
Solving the constraints is done by following these steps:

\textbf{Step 1, Free Motion}: interacting objects are solved independently while setting $ \lambda  = 0$.
We obtain what we call a \textit{free motion} $\Vdv_1^{\mathrm{f}}$  and  $\Vdv_2^{\mathrm{f}}$ for each object. After integration, we obtain $\Vx_{1}^{\mathrm{f}}$ and $\Vx_{2}^{\mathrm{f}}$.
%For the prediction, use $\tilde{\lambda} = \lambda^{t}$.
During this step, each object solves equation~(\ref{eq:constraint-systeme}) with $ \lambda  = 0$ independently using a dedicated solver.

\vspace{2mm}

\textbf{Step 2, Constraint Solving}:
%the constraint laws are linearized as follows:
%\begin{equation}
%\label{eq:const-lin}
%\underbrace{
%\left[ \! \! \!
%\begin{array}{c}
%\Phi(\Vx_{1}^{t+h}, \Vx_{2}^{t+h})  \\
%\Psi(\Vx_{1}^{t+h}, \Vx_{2}^{t+h})
%\end{array} \! \! \!
%\right]}_{\boldsymbol{\delta}^{t+h}}  \!
%=  \!
%\underbrace{
%\left[ \! \! \!
%\begin{array}{c}
%\Phi(\Vx_{1}^{\mathrm{f}}, \Vx_{2}^{\mathrm{f}})  \\
%\Psi(\Vx_{1}^{\mathrm{f}}, \Vx_{2}^{\mathrm{f}})
%\end{array}\! \! \!
%\right]}_{\boldsymbol{\delta}^{\mathrm{f}}}
% + h\mathbf{H}_1\Vdv_1^{\mathrm{c}}  +  h\mathbf{H}_2\Vdv_2^{\mathrm{c}}
%\end{equation}
%With $\Vdv_1^{\mathrm{c}}$ and $\Vdv_2^{\mathrm{c}}$ being the unknown corrective motion ($\Vdv= \Vdv^{\mathrm{f}} + \Vdv^{\mathrm{c}}$) when solving equation \ref{eq:constraint-systeme} with $\mathbf{b}_1 = \mathbf{b}_2 = 0$. By gathering equations \ref{eq:constraint-systeme} and \ref{eq:const-lin}, we have:
The constrained equations can be linearized and linked to the dynamics (see \cite{CJADLC10} for details).
\begin{equation}
\left[
\begin{array}{c}
\Phi(\Vx_{1}, \Vx_{2})  \\
\Psi(\Vx_{1}, \Vx_{2})
\end{array} \! \! \!
\right]
 =
 % \underbrace{
\left[ \! \! \!
\begin{array}{c}
\Phi(\Vx_{1}^{\mathrm{f}}, \Vx_{2}^{\mathrm{f}})  \\
\Psi(\Vx_{1}^{\mathrm{f}}, \Vx_{2}^{\mathrm{f}})
\end{array}\! \! \!
\right]
%}_{ \delta^{\mathrm{f}}  }
 +
 \underbrace{
 h\mathbf{H}_1\Vdv_1^{\mathrm{c}}  +  h\mathbf{H}_2\Vdv_2^{\mathrm{c}}
 }_{h \left[  \mathbf{H}_1 \mathbf{A}_1^{-1}  \mathbf{H}_1^T + \mathbf{H}_2 \mathbf{A}_2^{-1}  \mathbf{H}_2^T \right]\lambda
 }
 %=
 %\delta^{\mathrm{f}} +
%\underbrace{h \left[  \mathbf{H}_1 \mathbf{A}_1^{-1}  \mathbf{H}_1^T + \mathbf{H}_2 \mathbf{A}_2^{-1}  \mathbf{H}_2^T \right]}_{\mathbf{W}} \lambda
\label{eq:addjminvjt}
\end{equation}
With $\Vdv^{\mathrm{c}} = \Vdv - \Vdv^{\mathrm{f}}$.
Together with equation (\ref{eq:constraints}), these equations compose a Mixed Complementarity Problem that can be solved by a variety of solvers.
We compute the value of $ \lambda$ using a projected Gauss-Seidel algorithm that iteratively checks and projects the various constraint laws contained in $\Phi$ and  $\Psi$ ~\cite{DGMCG09}.

\textbf{Step 3, Corrective Motion}: when the value of $\lambda$ is available, the corrective motion is computed as follows:
%
\begin{equation}
\label{eq:corrective-motion}
\begin{array}{c}
\Vx_{1}^{t+h} =  \Vx_{1}^{\mathrm{f}} + h \Vdv_1^{\mathrm{c}} \  \  \mathrm{ with } \  \  \Vdv_1^{\mathrm{c}} = \mathbf{A}_1^{-1}  \mathbf{H}_1^T \lambda \\
\Vx_{2}^{t+h} =  \Vx_{2}^{\mathrm{f}} + h \Vdv_2^{\mathrm{c}} \  \  \mathrm{ with } \  \  \Vdv_2^{\mathrm{c}} = \mathbf{A}_2^{-1}  \mathbf{H}_2^T \lambda
\end{array}
\end{equation}
%

A Master Solver, which is generally placed at the top of the graph of SOFA has the role of imposing this new scheduling to the rest of the graph.
%
\begin{figure}[!htb]
\centering
% FreeMotionScheme is missing from SVN
\includegraphics[width= 0.9\columnwidth]{ConstraintSolver.png}
\caption{Contact process using constraints: A unilateral constraint is placed at the level of the contact points. The constraint direction is mapped to the degrees of freedom of the objects to obtain matrix $ \mathbf{H}^T$. The \textit{ConstraintCorrections} components compute the compliance to obtain equation \ref{eq:addjminvjt}. The Constraint solver found a new value of $\lambda$ which is sent to the  \textit{ConstraintCorrections} to compute an adequate corrective motion. The Master Solver is placed at the root of the simulation graph to impose the steps of the simulation process.  }
\label{shema_ToH}
\end{figure}

\textbf{Compliance computation} : Equations~\ref{eq:addjminvjt} and~\ref{eq:corrective-motion} involve the inverse of matrix $\mathbf{A}$ (called compliance matrix), which changes at every time step namely in case of a non-linear model.
Depending on the simulation case, computing this inverse could be time consuming for real-time simulation.
When this is too time-consuming, we propose several strategies to improve the speed of the algorithm such as using the diagonal of $\mathbf{A}$ instead of the hole matrix, or a precomputed inverse~\cite{Saupin08}, or an asynchronous factorization on the GPU~\cite{CourtecuisseMICCAI11}.
These strategies are implemented in a category of components, called  \textit{ConstraintCorrections} that provide different ways of computing $\Vdv^{\mathrm{c}}$ given a value of $\lambda$. Given a simulation, it is very easy to make tests and chose the better solution.


%\chapter{Bose--Einstein condensate dynamics}
The purpose of this chapter is to introduce the reader to vortex states of BECs, and eventually discuss manipulations of these states. In the following sections we will examine both the static and the dynamical solutions of the Gross--Pitaevskii equation (GPE), using the methods previously discussed. We will first briefly discuss few vortex solutions, with an analysis of their properties via an examination of the velocity field.

We will follow this by providing the details of the model system of a vortex lattice in a rapidly rotating BEC, using the theoretical framework developed in Chapter~\ref{chp:background}. Next, we will discuss the application of two distinct ways for manipulating and controlling the condensate: (1) applying an external potential to the trapped condensate for a short timescale, and (2) direct manipulation of the wavefunction phase. Both of these are experimentally realistic, and though they can be experimentally implemented by similar means, they serve two very different purposes, and they will be treated as such.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Simulating Bose--Einstein condensate dynamics}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

In Sections~\ref{sub:gpederiv}~and~\ref{sec:fso} we have outlined both the analytical Thomas--Fermi (TF) and numerical solutions of the GPE. It is instructive to compare the results from these two methods. For a stationary condensate in the ground state of a harmonic trapping potential the profile and width should be comparable, with the TF solution deviating only in the low-density regions. Fig.~\ref{fig:gpe_tf_3} shows a comparison of the two-dimensional profile for both methods, for condensates of $^{87}$Rb with $N=10^{5}$ atoms, and trapping frequencies of $\omega_{\mathbf{r}}=2\pi\times (1, 1, 16 )$ Hz. Both solutions show good agreement, deviating only where expected, and hence showing a well developed numerical procedure.
\begin{figure}\centering
    \includegraphics[width=\textwidth,trim=0ex 0ex 0ex 0ex]{Images/ch4_vtx/gpe_tf_3.pdf}
    \caption{The numerical solution (left) and Thomas-Fermi (middle) solutions for a two-dimensional condensate of $^{87}$Rb with $N=1\times 10^5$ atoms. The lineplot (right) is a central cut through both profiles showing the close match.}\label{fig:gpe_tf_3}
\end{figure}

While the Thomas--Fermi solution closely agrees with the numerical solution of the Gross--Pitaevskii equation, this solution is only applicable for stationary states with negligible kinetic energy, i.e.\ when the nonlinear interaction dominates over the kinetic energy term. For more complex problems involving dynamics, full numerical integration of the Gross--Pitaevskii equation is required.

One example where the TF approach fails is when investigating superfluid vortex dynamics. To generate vortices in the condensate angular momentum must be added to the system. Seeding a single vortex in the condensate requires that the frequency of rotation, $\Omega$, must be higher than the critical rotation frequency $\Omega_c$, as discussed in Sec.~\ref{ss:vorticesinbec}, and numerically, this is most easily simulated in the co-rotating frame as given by Eq.~\eqref{eqn:gpe_rotation}. Experimentally, there are many ways to create vortices in a condensate, such as stirring with a blue-detuned laser beam \cite{Vtx:Raman_prl_2001}, carefully inverting the trap bias field potential \cite{VTX:Nakahara_physb_2000,VTX:Leanhardt_prl_2002,VTX:Kawaguchi_pra_2004_2, VTX:Kuwamoto_jpsj_2010,VTX:Masuda_pra_2016}, or through the use of artificial gauge fields \cite{AO:Dalibard_rmp_2011}, to name but a few. In the next sections we will concentrate on solutions where the vortices are already present in the condensate and have settled into the lowest energy configuration.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Few vortex condensates}\label{sec:fewvtx}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

As discussed in Section~\ref{sec:superfluid}, the study of quantum vortices remains an active area of research. As the condensate kinetic energy scales as $E_k \propto l^2$ (Sec.~\ref{ss:vorticesinbec}), increased angular momentum leads to the appearance of more singly charged vortices rather than one multiply charged vortex. For a single vortex in a rotating condensate the only stationary solution that exists is if the vortex resides at the exact centre of the trapping potential, making the system radially symmetric. For two vortices the radial symmetry of the system is broken, with the two vortices arranging themselves in the most favourable position to minimise the energy of the system, as with all higher vortex states. Placing vortices of the same sign into a condensate will allow them to behave as identically charged particles, and they will repel, and form ordered lattices with increasing vortex numbers (see Fig.~\ref{fig:few_rho}). Similarly, if instead we pair a vortex and an antivortex, they will attract, and remain in constant motion, or disappear altogether in the presence of dissipation.

This stability and dynamical behaviour can be understood by examining the velocity fields of the vortices, as shown in Fig.~\ref{fig:vel_field} for like-signed vortices, and Fig.~\ref{fig:vel_pm} for a vortex-antivortex pair. The velocity fields of the vortices are additive, which for like-signed windings creates regions of zero flow, and for opposite-windings creates large flows between them respectively. From Eq.~\ref{eqn:1_over_r} the velocity field of the irrotational quantum vortex scales as $v \propto {1/r}$, and hence becomes singular at the vortex centre, giving rise to the large velocities close to the singularity. Fig.~\ref{fig:vel_pm_contour} shows a clearer view of the velocity fields as depicted by Fig.~\ref{fig:vel_field}, where the presence of maxima is easily observed at the cores, with field minima also observed due to the vortex-vortex interactions.

\begin{figure}\centering
    \includegraphics[width=0.48\textwidth]{Images/ch4_vtx/fewvortex_rho.pdf}
    \includegraphics[width=0.48\textwidth]{Images/ch4_vtx/fewvortex_theta.pdf}
    \caption{Density (left) and phase (right) for condensates carrying 1,2,3,and 7 vortices respectively.}
    \label{fig:few_rho}
\end{figure}

\begin{figure}\centering
    \includegraphics[width=0.95\textwidth]{Images/ch4_vtx/velocity/velocity_fixedmag}
    \caption{Magnitude of the velocity field and the direction of rotation of the field for clockwise circulating vortices. As the velocity follows a $1/r$ profile the magnitude becomes singular at the centre of the vortices, which is capped here at $v=2.4\times 10^{-3}$ (ms$^{-1}$).}
    \label{fig:vel_field}
\end{figure}

\begin{figure}\centering
    \includegraphics[width=0.55\textwidth]{Images/ch4_vtx/vtx_anti_velfield}
    \caption{Velocity field direction and magnitude originating from vortex and antivortex present in a condensate. Colour scale is in units of ($ms^{-1}$).}
    \label{fig:vel_pm}
\end{figure}

\iffalse
\begin{figure}\centering
    \includegraphics[width=0.45\textwidth]{Images/ch4_vtx/vtx_anti_velfield}
    \includegraphics[width=0.45\textwidth]{Images/ch4_vtx/vtx_antivtx_traj}
    \caption{(Left) Velocity field originating from vortex and antivortex present in a condensate. (Right) Trajectories of vortex and antivortex in a condensate in the lab frame. Vortices travel on circulating paths which will always intersect through their starting position. Color is used to represent the same times for both vortex and antivortex, which is on the order of seconds.}
    \label{fig:vel_pm}
\end{figure}
\fi

\begin{figure}\centering
    %\includegraphics[width=0.95\textwidth]{Images/ch4_vtx/velocity/vel_axis_png}
    \includegraphics[width=0.95\textwidth]{Images/ch4_vtx/velocity/vel.png}
    \caption{Magnitude of the velocity field for small numbers of like-signed vortices in a condensate. The velocity field can be seen to become singular at the centre, which here has its magnitude capped at a lower value than Figs.~\ref{fig:vel_field} and~\ref{fig:vel_pm} to aid visibility. Regions of minimal velocity are seen, wherein the opposing field lines compensate one another.}
    \label{fig:vel_pm_contour}
\end{figure}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Rapidly rotating vortex lattice}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Model system}\label{sec:modelsystem}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%\todo[inline]{Fix velocity fields of all the plots and ensure they are all using the same units and similar ranges.}
%\todo[inline]{Explain away the antivortex wobble}
For the work to follow we assume a standard single component Bose--Einstein condensate in a radially symmetric trap of frequency $\omega_\perp = 2\pi \times 1$ Hz. By tightly confining the condensate along the $z$-dimension, with trapping frequency $\omega_z = 2\pi\times 16$ Hz, such that $\omega_z $ is greater than $ \omega_\perp$, the condensate enters the desired pancake-shaped geometry. The system is then modelled using the mean-field GPE Hamiltonian as
\begin{equation}\label{eqn:gpe_h0}
	H_{\mathrm{GP}} = -\frac{\hbar^2}{2m}\nabla^2 + \frac{1}{2}m\omega_{\perp}^2\mathbf{r}^2 + g_{\textrm{2D}}\vert\Psi(\mathbf{r},t)\vert^2.
\end{equation}

Here, we define the two-dimensional effective interaction strength $g_{\textrm{2D}}$ given by Eq.~\eqref{eqn:g2d_efint}, as
\begin{equation}
g_{\textrm{2D}} = g\sqrt{\frac{m\omega_z}{2\pi\hbar}} = 4g \sqrt{\frac{m}{\hbar}}.
\end{equation}

To describe the system we enter the co-rotating frame, which is done by including the angular momentum operator $L_z$ in the Hamiltonian. The time dependent dynamics of the system are then given by the GPE as
\begin{equation}\label{eqn:gpe2d_}
	\textrm{i}\hbar\partial_t\Psi(\mathbf{r},t) = \left[ H_{\text{GP}}  -  \Omega L_z \right] \Psi(\mathbf{r},t).
\end{equation}

If the angular rotation frequency approaches the condensate trapping frequency, $\Omega \approx \omega_\perp$, the condensate gains a large triangular lattice of vortices.  The effect of setting $\Omega=\omega_\perp$, can be partially understood in a mean-field setting by rewriting the GPE kinetic and rotation terms in the form
\begin{equation}
    \frac{\mathbf{p}^2}{2m} + \frac{m\Omega\mathbf{r}^2}{2} - \Omega L_z = \frac{\mathbf{\left(p -{\textit{ m}}\boldsymbol{\Omega}\times\mathbf{r}\right)^2}}{2m}.
\end{equation}

The resulting changes to the GPE are then given by
\begin{equation}\label{eqn:vector_potential_gpe}
    \textrm{i}\hbar\partial_t \Psi =
    \left(\frac{1}{2m}(-i\hbar\nabla - m\boldsymbol{\Omega}\times\mathbf{r})^2 + \frac{m}{2}(\omega_\perp^2 - \Omega^2){r}^2 + g_{\textrm{2D}}|\Psi|^2 \right)\Psi.
\end{equation}
The above Hamiltonian demonstrates the correspondence between a rotating condensate and that of a non-relativistic charged particle in a magnetic field~\cite{Vtx:Mueller_prl_2002}.
%\begin{equation}
%     H_L = \frac{1}{2m}\left(-i\hbar \nabla  - q\mathbf{A}\right)^2 + q\phi
%\end{equation}
%where $q$ is the particle charge, $\mathbf{A}$ is the respective gauge potential, and $\phi$ the respective scalar potential.
One can see that when the rotation and trapping frequencies are equal, the condensate no longer sees a confining potential, due to the centrifugal force experienced, given by the term $-m\Omega^2r^2/2$.

As stated earlier in Sec.~\ref{sec:sec2_vtxlatt} as $\Omega$ approaches $\omega_\perp$, the use of mean-field theory becomes less justified, and the system enters a strongly correlated regime. If the filling fraction $\nu$ is in the range of $10 \leq \nu \leq 1000$, the system enters the ``mean-field quantum Hall'' regime, where the Gross--Pitaevskii theory is still working well. The system examined here is well within this regime for a frequency of $\Omega = 0.995\omega_\perp$. This allows us to work with systems that have a very large vortex lattice, and are still described by mean-field theory \cite{BEC:Fetter_revmodphys_2009}.

In the following we will numerically solve Eq.~\eqref{eqn:gpe2d_}, using the pseudospectral Fourier split operator method and making use of GPU computing as described in Sec.~\ref{sec:GPUE}. For realistic experimental parameters we assume  $N\approx 10^6$ atoms of $^{87}$Rb, with an $s$-wave scattering length of $a_s=4.76\times10^{-9}$ m~\cite{AO:Roberts_prl_1998}. The numerically evaluated ground-state for the given set of parameters is shown previously in Fig.~\ref{fig:showingoff} and has a radius of approximately $3.5\times 10^{-4}$ m. For these parameters, the number of vortices within the visible density region is approximately 600, giving a filling factor of $\nu \approx 800 $. This places the system within the mean-field quantum Hall regime, and therefore a description using Gross--Pitaevskii theory is adequate~\cite{Vtx:Schweikhard_prl_2004}.

Following an imaginary time-evolution as outlined in Sec.~\ref{sec:timeev}, we first find the ground state of the condensate in a harmonic potential, starting with a condensate without vortices. We then linearly ramp the rotation frequency to avoid the lattice disordering issue discussed in Sec.~\ref{ss:ang_mom_fso}. This allows us to follow the ground state solution at all times while the rotation frequency is increased, which has the added advantage of returning a ground state solution for any required rotation frequency. Examples of several states obtained during a single simulation are given in Fig.~\ref{fig:inc_omega}. The previously discussed resolution considerations become apparent as the rotation rate is increased for both the position and momentum space representations of the wavefunction. A movie of the wavefunction density is available at the following URL~\cite{YT:BEC_gen}, in which the frequency is ramped from $\Omega/\omega_\perp = 0.39 \to 0.995$.

The rapidly rotating vortex lattice is known to exhibit solid-body-like rotation \cite{Vtx:AboShaeer_sci_2001}. This can be seen in Fig.~\ref{fig:solidbody}, where the coarse-grained flow of the velocity field increases as a function of the distance from the lattice centre. This rigid-body behaviour allows us to treat the lattice as a solid object. Recalling the Feynman relation for vortex density Eq.~\eqref{eqn:feynman}, $n_v = m\Omega/(\pi\hbar)$, we choose an area over which the lattice spacing is almost constant and the vortex density closely matches this relation. In this rapidly rotating regime the vortices close to the centre will have an almost uniform profile~\cite{VTX:Watanabe_pra_2006}; for the above system parameters this is fulfilled by a hard-walled radial boundary of $r=2\times 10^{-4}$ m, in which the number of vortices are calculated to being $N_v \approx 342$. Employing the vortex detection and tracking methods described in Sec.~\ref{sec:vortrack}, within the same region gives $N_v = 341$ vortices, with a lattice spacing of $a_v \approx 2.1\times 10^{-5}$ m, and with a standard deviation of $\sigma \approx 2.7 \times 10^{-7}$ m. These values indicate that within this region the lattice is well ordered. While the condensate has more vortices outside this boundary that are initially ordered, during time evolution many of these move more easily due to the large velocity fields closer to the edges. The above boundary gives a well ordered lattice that remains well ordered for several seconds of time evolution.

\begin{figure}\centering
    \includegraphics[width=0.85\textwidth]{Images/ch4_vtx/ramp_omega_2.pdf}
    \caption{Density distributions of the wavefunction in position (top) and momentum (bottom) space for increasing rotation frequencies (from left to right). The color axis differs for each plot for visibility, as with a constant axis it is difficult to view densities across all magnitudes. The growth rate of the condensate radius in both position and momentum space becomes large when $\Omega_z \approx \omega_\perp$.}
    \label{fig:inc_omega}
\end{figure}

\begin{figure}\centering
    \includegraphics[width=0.47\textwidth,clip,trim={0cm 0cm 0 0cm}]{Images/ch4_vtx/solidbody_v}
    \includegraphics[width=0.43\textwidth,clip,trim={0cm 0cm 0 0cm}]{Images/ch4_vtx/solidbody_vel_r}
    \caption{(Left) Magnitude and direction of flow of the velocity field for a rapidly rotating vortex lattice in the rapidly rotating frame. (Right) The angle-averaged velocity field from condensate centre. The solid-body rotation can be seen, where the coarse-grained condensate velocity scales as $v \propto r$ from the condensate centre. Close to the vortex cores the velocity field retains a $1/r_{\textrm{vtx}}$ profile, becoming singular at the core centres, with $r_{\textrm{vtx}}$ as the distance from the respective cores.}
    \label{fig:solidbody}
\end{figure}

If, however, the linear ramp is performed too quickly, or an initial state is chosen that already contains a large amount of angular momentum without being the eigenstate, the vortices tend to enter from the boundary all at once, and fail to converge to the well ordered ground state. A demonstration of this such issue is shown in Fig.~\ref{fig:malformed_lattice}, and indicates the need for a slow ramp of $\Omega$ that is essentially adiabatic in imaginary time. As higher rotation frequencies are reached, the rate at which vortices enter the condensate increases rapidly. While the rapid entry of vortices was a problem for reaching an ordered lattice without a ramp of rotation frequency, the presence of an existing lattice during ramping allows all newly entered vortices to order more easily. Therefore, a linear ramp is effective and does not require a more complex scaling.

\begin{figure}
    \centering
    \includegraphics[width=0.65\textwidth]{Images/ch4_vtx/toofast_099_1e7}
    \caption{Disordered lattice resulting from starting in imaginary time evolution at the required rotation rate (here $\Omega=0.99\omega_\perp$). If the rotation frequency is chosen too large without allowing the lattice to form and order, the resulting vortices all enter instantaneously and compete for their final positions. The system only converges one timescales that exceed reasonable computing times.}
    \label{fig:malformed_lattice}
\end{figure}

In the following section we will discuss perturbations of the condensate in the presence and absence of vortices. For the above system, we will investigate the effect of perturbations to both the global and local condensate order due to changes in the lattice structure.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 1
\section{Condensate perturbations}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% a
\subsection{Trapping potential control}\label{ss:pert_opt_latt}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
With the model system outlined in Sec.~\ref{sec:modelsystem}, we will now imagine an abrupt change to the Hamiltonian, such that, $H(t) = H_{\textrm{GP}} + f(t) V_{\textrm{ext}}$, where $V_{\textrm{ext}}$ is an external potential, and $f(t)$ is some function of time to control the application of $V_{\textrm{ext}}$. In this scenario the initial wavefunction, which is a stationary state of $H_{\textrm{GP}}$, will no longer remain so provided that $H_{\textrm{GP}}$ and $f(t) V_{\textrm{ext}}$ are non-commuting. Assuming the time of application of the additional term is much shorter than any other timescale of the condensate dynamics, any modification of the Hamiltonian in this way can be viewed as a method for changing the phase of the wavefunction.
%\begin{equation}
%    e^{i\phi} \mapsto \exp\left(-i\frac{Ht}{\hbar}\right),
%\end{equation}
The resulting effect on the wavefunction can be given as
\begin{subequations}
\begin{align}
    \Psi(t=0) &= |\Psi(t=0)|e^{\textrm{i}\theta_0} \\
    \Psi(t) &= \Psi(t=0) e^{ - \textrm{i} \frac{ V_{\textrm{ext}} \Delta t}{\hbar}} \\
            &= |\Psi(t=0)| e^{\textrm{i}\left(\theta_0 - \frac{V_{\textrm{ext}} \Delta t}{\hbar}\right)} \nonumber
\end{align}
\end{subequations}
where we have made use of Eq.~\eqref{eqn:madelung}. After application of $V_{\textrm{ext}}$ the wavefunction phase is given by
\begin{equation}
    \theta^{'} = \theta_0 - \frac{E_{\textrm{ext}} \Delta t}{\hbar},
\end{equation}
where $E_{\textrm{ext}}$ is the perturbance energy. One commonly used method to manipulate the condensate is through the use of optical potentials, which offer a large degree of control over the respective system's Hamiltonian \cite{BEC:Bloch_revmodphys_2008}. The electric field component of an arbitrary optical field, described by a wavevector $\mathbf{k}$, and frequency, $\omega$ is given by
\begin{equation}
    \mathbf{E}(\mathbf{r},t) = \varepsilon_0 e^{\textrm{i}\left(\mathbf{k}\cdot\mathbf{r} - \omega t\right)} + \ \varepsilon_0^{*} e^{-\textrm{i}\left(\mathbf{k}\cdot\mathbf{r} - \omega t\right)},
\end{equation}
where $\varepsilon_0$ is the field amplitude. Using the dipole approximation, the interaction of an atom with a laser field is given by~\cite{BK:Foot_2005}
\begin{equation}
\mathcal{V} = -{\mathbf{d}}\cdot {\mathbf{E}},
\end{equation}
where ${\mathbf{d}}$ is the electric dipole moment operator. For a two level atom with a ground state $| g \rangle$, and an excited state $| e \rangle$ with energy difference $\hbar \omega_0$, the dipole operator can be written as
\begin{align}\label{eqn:dipole_approx}
\mathbf{d} &= \langle g|\mathbf{d}|e \rangle | g \rangle \langle e | + \langle e|\mathbf{d}|g \rangle | e \rangle \langle g | \nonumber \\
&= \boldsymbol{\mu}_{eg} | g \rangle \langle e | + \boldsymbol{\mu}_{eg}^{*} | e \rangle \langle g |,
\end{align}
where we have made use of $\langle g|\mathbf{d}|g \rangle = \langle e|\mathbf{d}|e \rangle  = 0$, since the atoms have no permanent dipole moment. From Eq.~\eqref{eqn:dipole_approx} the Hamiltonian of the two-level system can then be written as
\begin{align}\label{eqn:dip_hamiltonian}
    H &= H_0  + \mathcal{V} \nonumber \\
      &=  \hbar\omega_0 |e\rangle\langle e | - (\boldsymbol{\mu}_{eg} | g \rangle \langle e | + \boldsymbol{\mu}_{eg}^{*} | e \rangle \langle g |)\cdot ( \varepsilon_0 e^{\textrm{i}\left(\mathbf{k}\cdot\mathbf{r} - \omega t\right)} +  \varepsilon_0^{*} e^{-\textrm{i}\left(\mathbf{k}\cdot\mathbf{r} - \omega t\right)}).
\end{align}
After expanding~\eqref{eqn:dip_hamiltonian} we can then rewrite $\boldsymbol{\mu}_{eg}\cdot \varepsilon_0 = \hbar\Omega_r$, where $\Omega_r$ is the Rabi-oscillation frequency between the states. Assuming that the detuning $\Delta = \omega - \omega_0$ between the laser field and transition frequency is small, $\Delta \ll \omega + \omega_0$, allows use of the rotating wave approximation. For this we first perform a unitary transformation of the system into the interaction picture rotating with $H_0$ using the operator $U = e^{-\textrm{i}\omega_0 t|e\rangle\langle e|}$ as
\begin{align}
    H_{\textrm{int}} & = U^{\dagger} \mathcal{V} U.
\end{align}
All resulting terms featuring $\omega + \omega_0$ can be considered to be rapidly oscillating, and average out to zero. Following this approximation, the Hamiltonian can be transformed back into the Schr\"odinger picture, giving
\begin{align}
 H^{'} = \hbar\omega_0 - \hbar\Omega\left(e^{\textrm{i}\omega t}|e\rangle\langle g|   + e^{-\textrm{i}\omega t}|g\rangle\langle e|  \right).
\end{align}
The final shift of the energies is then given as
\begin{equation}\label{eqn:acshift}
\mathcal{V} = -\frac{\alpha}{2}\langle \mathbf{E}^2\rangle_t ,
\end{equation}
where $\alpha$ is the real component of the atomic polarisability, and $\langle \cdot \rangle_t$ denotes the time average. If the electric field is spatially inhomogeneous, then this leads to a force of the form
\begin{equation}
\mathbf{F}_d = \frac{\alpha}{2}\nabla\langle \mathbf{E}^2 \rangle_t ,
\end{equation}
which is known as the dipole force. Assuming counter propagating plane waves, we can then model a standing wave solution of the resulting optical potential as
\begin{equation}
    V_{\textrm{ext}} \approx -\frac{\Omega_0^2(\mathbf{r})}{4\Delta}  = V_0 \cos^2 (\mathbf{k} \cdot \mathbf{r}),
\end{equation}
where $V_0 = -\Omega_0^2/4\Delta$ is the field intensity, and $\Omega_0 \propto |\varepsilon_0|^2$ is the Rabi-frequency of the standing wave. The optical potential forms a highly periodic system given an appropriately chosen $\mathbf{k}$, and is known as an \textit{optical lattice}. Optical lattices have become very common in BEC experiments as they allow for control of the kinetic energy term of the atoms to a very high degree~\cite{OL:Greiner_nat_2002,OL:Reijnders_prl_2004,OL:Sorensen_prl_2005,Vtx:Tung_prl_2006,Vtx:Vignolo_pra_2007,BEC:Watanabe_entropy_2016}.

%The optical lattice potential can be used to create one, two, or three-dimensional periodic trapping structures.
%\todo[inline]{Add full optical potential including polarisation terms}
Different geometric potentials can be formed with optical lattices by using laser fields with different $\mathbf{k}$ vectors. Assuming standing waves with different polarisation axes or slightly different wavelengths, the interference effects between two or more fields can be ignored, with the resulting optical field given by the summation of lattice potentials with wavevectors $\mathbf{k}_{1,..,n}$. Creating a 2D lattice with $n$-fold rotational symmetry requires $n/2$ $\mathbf{k}$-vectors separated by ${2\pi/n}$, and with $n/2 \in \mathbb{Z}^{+}$. Taking a square lattice as an example, which has a 4-fold rotational symmetry, it can be created by two $\mathbf{k}$-vectors, separated by $\pi/2$, as
\begin{equation}
    \mathbf{k}_0 = \left[ \begin{array}{cc}
    1 \\
    0
    \end{array} \right],~
    \mathbf{k}_1 =
    \left[ \begin{array}{cc}
     0 \\
     1
    \end{array} \right].\label{eqn:sqlatt}
\end{equation}
The resulting potential is shown in Fig.~\ref{fig:cos2xy}.
\begin{figure}\centering
    \includegraphics[width=0.55\textwidth]{./Images/ch4_vtx/VOPT/squarelatt}
    \caption{Square lattice generation using two orthogonal propagating laser fields with wavevectors $\mathbf{k}_1$ and $\mathbf{k}_2$, as defined by Eq.~\eqref{eqn:sqlatt}.}\label{fig:cos2xy}
\end{figure}
The time the optical lattice is applied to the condensate can be controlled by choosing the function $f(t)$. Applying a lattice for a finite, but short, time only will lead to a modification of the wavefunction phase, which then subsequently, and on a much longer time-scale, will have an effect on the density distribution. Of particular interest to us is the use of an optical potential that is pulsed one or several times, which can be described by $f(t)$ as a periodic delta function. The condensate phase profile is the only quantity immediately modified, and any change in the density distribution appears only in the following evolution.

\iffalse
For the purpose of my system, we intend to create a two-dimensional optical lattice, wherein the structure of the lattice matches that of the triangular Abrikosov vortex pattern. The triangular lattice has 6-fold rotational symmetry, and can be formed with wavevectors

\begin{subequations}
    \begin{align}
        \mathbf{k}_1 &= k_0\left\{\frac{\sqrt(3)}{2},\frac{1}{2}\right\} \\
        \mathbf{k}_2 &= k_0\{0,1\} \\
        \mathbf{k}_3 &= k_0\left\{\frac{\sqrt(3)}{2},-\frac{1}{2}\right\} \\
    \end{align}
\end{subequations}
where $k_0 = 4\pi/(\sqrt(3)a_\text{O})$, and $a_\text{O}$ is the lattice spacing.
\fi

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% b
\subsection{Direct phase manipulation}\label{sec:phase}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

While ground state condensates will have a flat phase across the system, there are two interesting examples where a spatially dependent phase exists: dark solitons~\cite{BEC:Denschlag_science_2000} and vortices~\cite{Vtx:Dobrek_pra_1999}. We have previously discussed the $2\pi$ phase profile of a vortex that leads to the singularities in the wavefunction. In contrast, dark solitons feature a $\pi$ phase jump profile. These excitations are unstable in dimensions higher than one, and will decay via the snake instability to paired vortices and antivortices~\cite{Tikhonenko:96, PhysRevLett.86.2926, BEC:Brand_pra_2002}. Where so far we have only considered the short-term evolution of the wavefunction after being kicked by an optical potential, we will in the following consider what structures can be created in the condensate by careful phase manipulation techniques, besides dark solitons and vortices.

For this we will assume that the BEC allows for a short enough application of potentials so that only the phase is affected, and discuss direct manipulation of the wavefunction, as opposed to modification of the Hamiltonian. Following \cite{BK:Pitaevskii_Stringari_2003} and taking Eq.~\eqref{eqn:madelung}, the phase of the condensate can then be written as
\begin{equation}
\theta = \theta_0 + \theta_i,
\end{equation}

where $\theta_0$ is the unperturbed condensate phase, and $\theta_i$ is the phase pattern to be imprinted. Upon solving for the initial condensate ground state with deterministic phase, an additional phase pattern can be imprinted at any time by simply multiplying the wavefunction by $e^{\text{i}\theta_i}$. However, without careful choice of the phase terms their addition can lead to unwanted dynamics, so care must be taken to choose a well defined initial and imprinted phase pattern.

The advantage of the phase imprinting model is that for topological defects, one can imprint the required winding instantaneously, allowing them to appear at predefined positions. The density also needs to only adjust itself locally to the phase singularity, with the remaining condensate seeing an almost constant shift in phase. The creation of vortices through application of localised $\pm 2\pi$ phase winding defects in the condensate therefore allows for direct control of the angular momentum and vorticity within the BEC. While discussed in the literature for the creation of vortices, it is worth noting that the phase imprinting method can also be used to annihilate a vortex from the condensate by applying a phase profile of opposite winding, removing the singularity. This will leave the condensate with a density depletion at the prior location of the phase singularity. Without the phase singularity this depletion will fill in and excite phonon modes in the condensate during time evolution. This process will form the basis for further discussions and analysis of vortex carrying condensates.

Experimental realisation of arbitrary potential patterns to achieve the required phase is accessible through the use of spatial light modulators (SLM)~\cite{VTX:Moulder_pra_2012}. These devices behave as digital displays, through which visual patterns can be expressed in a time dependent manner, allowing the application of a laser field in the required form. We will assume for all future discussions that the potentials we require are experimentally realisable with sufficient resolution, and focus on the resulting effect on the condensate. For the creation of a single vortex the $2\pi$ phase winding pattern can be created spatially using the two-argument four-quadrant form of $\arctan$ as given by
\begin{equation}
    \theta_i(\mathbf{x},\mathbf{y};x_0,y_0) = \arctan(\mathbf{y}-y_0,\mathbf{x}-x_0),
\end{equation}
which locates the singularity at the position $\left(x_0,y_0\right)$. The resulting phase is shown in Fig.~\ref{fig:atan2phase}(left), and including the additional phase singularity term $\theta_i$, the condensate wavefunction following an imprint is given as
\begin{equation}
    \Psi^{'}(\mathbf{r},t) = |\Psi(\mathbf{r},t)|e^{\text{i}(\theta_0(\mathbf{r},t) + \theta_i(\mathbf{r}))}.
\end{equation}

\begin{figure}\centering
    \includegraphics[width=0.45\textwidth]{Images/ch4_vtx/2pi.pdf}
    \includegraphics[width=0.435\textwidth]{Images/ch4_vtx/3_2pi.pdf}
    \caption{$2\pi$ phase winding shown for a single (left) and three separated (right) phase singularities. The application of separate phase singularities can be treated as summing each individual phase profile, $\left(\displaystyle\sum\limits_i \theta_i \right)\mod 2\pi$. Note that the resolution used in the numerical examples is much higher than can be obtained from currently available SLMs.}\label{fig:atan2phase}
\end{figure}

Following the imprint this process will create phonons in the condensate density that will radiate outwards from the singularity imprint. As imprinting is directly controlling the condensate phase, it can also be considered a direct manipulation of the kinetic energy since the superfluid velocity depends on the phase gradient (see Eq.~\eqref{eqn:velocity}). This, in reverse, means that by applying spatially inhomogeneous phase profiles the atomic velocity can be adjusted to different values in different regions of the condensate. To demonstrate this we consider a simple example of a Gaussian phase profile applied to the condensate. The imprinted profile has the form
\begin{equation}
    \theta_{i}(\mathbf{r}) = A\exp\left( -\frac{ |\mathbf{r}-\mathbf{r}_0|^2 }{2\sigma^2 } \right) \mod 2\pi,
\end{equation}
where $A$ is the phase profile amplitude, $\mathbf{r}_0$ is the centre of the Gaussian curve, and $\sigma$ is adjusted to match the condensate width. The modulo $2\pi$ ensures that the phase wraps around for amplitudes exceeding the $(0,2\pi)$ range. The Gaussian profile has large radial gradients in two-dimensions, so that an imprint on the condensate should lead to radial velocities and therefore an expansion or contraction of the cloud (see Fig.~\ref{fig:gaussian}). This can be expected to lead to interference fringes, as the faster moving atoms have the possibility to overtake the slower ones for sufficiently large amplitudes~\cite{BEC:Busch_pra_2002}. In Fig.~\ref{fig:gaussian_wfc}, where a slice through the condensate centre is given for both position and momentum space, this can be clearly seen.

\begin{figure}\centering
    \includegraphics[width=0.95\textwidth]{Images/ch4_vtx/velocity/gaussian_imprint}
    \caption{Velocity fields and magnitude (left) and phase (right) for a condensate directly following a Gaussian phase imprint. The lengths of the arrows give the magnitude of the respective velocity components, with the color map indicating this also for clarity. The sign of the imprint changes the direction of the respective kinetic components, with a positive imprint initially creating a density contraction (top), and negative creating an expansion (bottom), with the arrows indicating the direction of the flow.}\label{fig:gaussian}
\end{figure}

\begin{figure}\centering
    \includegraphics[width=0.95\textwidth]{Images/ch4_vtx/gaussian_imprint_B}
    %\includegraphics[width=0.95\textwidth]{Images/ch4_vtx/velocity/gaussian_imprint_wfck}
    \caption{A cut through the condensate wavefunction density following the phase imprinting of a Gaussian with amplitudes $A=\pm ( 2\pi, 6\pi, 10\pi)$. The positive imprints create an initial contraction of the cloud (top), while the negative imprints lead to expansion (bottom). For the larger kicking strengths interference fringes can be observed during expansion and contractions.}\label{fig:gaussian_wfc}
\end{figure}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Condensate analysis}\label{sec:con_analysis}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
To analyse the effects of the phase imprinting we will below introduce the decomposition of the kinetic energy to isolate the effect from phonons and vortices. Following this, for the vortex lattice we will introduce two closely linked methods to examine geometric structure --- Delaunay triangulation and Voronoi tessellation. These methods are dual to one another, and can be used to easily identify order, structure and local parameters within systems of many particles.

\subsection{Kinetic energy decomposition}\label{sec:kinspec}
Given that the phase engineering modifies the condensate kinetic energy profile, it is instructive to quantify this effect. One can apply a spectral decomposition of the kinetic energy of the condensate into contributions solely from the vortices (incompressible), and those from the phonons (compressible)~\cite{CT:Nore_prl_1997,CT:Nore_pof_1997,CT:Bradley_prx_2012}. For this, the wavefunction is again written in terms of amplitude $\sqrt{\rho(\mathbf{r},t)}$ and phase $S(\mathbf{r},t)$, which allows the kinetic part of the Gross--Pitaevskii energy functional Eq.~\eqref{eqn:functional_full} to be calculated as
\begin{equation}
    E_{\text{kqp}} = \int d\mathbf{r} \left( \frac{\hbar^2}{2m}| \nabla\sqrt{\rho(\mathbf{r},t)} |^2  + \frac{m}{2}|\sqrt{\rho(\mathbf{r},t)}\mathbf{v}(\mathbf{r},t) |^2\right).
\end{equation}
One can then decompose this into the quantum pressure (first) and kinetic energy (second) terms. The kinetic energy term can be seen as a density-weighted velocity field, $\mathbf{u}(\mathbf{r},t) = \sqrt{\rho(\mathbf{r},t)}\mathbf{v}(\mathbf{r},t)$, and it can be further decomposed into the sum of compressible and incompressible terms,
\begin{equation}\label{eqn:kin_en}
    \mathbf{u(r},t) = \mathbf{u}^c(\mathbf{r},t) + \mathbf{u}^i(\mathbf{r},t).
\end{equation}
The two terms can be calculated by performing a Helmholtz decomposition of the field $\mathbf{u}$, which separates terms that are longitudinal ($\mathbf{u}^c$) and transversal ($\mathbf{u}^i$) with
\begin{subequations}\label{eqn:kinterms}
\begin{align}
    \nabla \times \mathbf{u}^c(\mathbf{r},t) &= 0, \\
    \nabla \cdot \mathbf{u}^i(\mathbf{r},t) &= 0.
\end{align}
\end{subequations}
By introducing the vector potential, $\mathbf{A}$, and the scalar potential, $B$, such that
\begin{subequations}
\begin{align}
    \mathbf{u}^c = \nabla B, \\
    \mathbf{u}^i = \nabla \times \mathbf{A},
\end{align}
\end{subequations}
we can rewrite Eq.~\eqref{eqn:kin_en} as
\begin{align}
    \nabla \times \mathbf{u}(\mathbf{r},t) = -\nabla^2 \mathbf{A}, \\
    \nabla \cdot \mathbf{u}(\mathbf{r},t) = \nabla^2 {B}.
\end{align}

To solve the above equation we begin by seeking a solution for $B$ by performing a spectral decomposition of the full density-weighted velocity field as
\begin{equation}
    B = \displaystyle\sum\limits_{j} \frac{k_j}{|\mathbf{k}|^2}\mathscr{F}[\mathbf{u}],
\end{equation}
where $k_j$ is the $j$-th component in $\mathbf{k}$ space, and $\mathscr{F}$ is the Fourier transform. The resulting solution for $\mathbf{u}^c$ is then given by
\begin{equation}
    \mathscr{F}[\mathbf{u}_i^c] = \displaystyle\sum\limits_{j} \frac{k_i k_j}{|\mathbf{k}|^2} \mathscr{F}[\mathbf{u}],
\end{equation}
which after taking note of Eq.~\eqref{eqn:kin_en} gives
\begin{align}
    \mathscr{F}[\mathbf{u}_i^i] &= \mathscr{F}[\mathbf{u}_i] - \mathscr{F}[\mathbf{u}_i^c]. \\
    &= \displaystyle\sum\limits_{j}\left(\delta_{i,j} - \frac{k_ik_j}{|\mathbf{k}|^2}\right)\mathscr{F}[\mathbf{u}_i]. \nonumber
\end{align}

This decomposition separates the energy contribution from phonons and vortex cores, represented by compressible and incompressible terms respectively~\cite{CT:Horng_pra_2009}. By averaging over binned shells in $\mathbf{k}$-space, the kinetic energy spectra, $E^{c,i}(k)$, are calculated as~\cite{CT:Bradley_prx_2012}
\begin{equation}\label{eqn:kin_spec_ic}
	E^{c,i}(k) = \frac{mk}{2}\sum\limits_{j\in\mathbf{r}} \int\limits_{0}^{2\pi}d\phi_k \frac{ |\mathcal{U}_j^{c,i}(\mathbf{k},t) |^2}{s_k},
\end{equation}
where
\begin{equation}
	\mathcal{U}_j^{c,i}(\mathbf{k},t) = \int d^2 \mathbf{r} e^{-\textrm{i}(\mathbf{k}\cdot\mathbf{r})} u_j^{c,i}(\mathbf{r},t).
\end{equation}
The terms $u_j^{c,i}(\mathbf{r},t)$ represent the position-space density-weighted velocity components in the specified shell, where $\phi_k$ is the polar angle, and $s_k$ is the number of values in the chosen shell.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Delaunay triangulation and Voronoi tessellation}\label{sec:delaunay}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
A common method for examining the ordering and periodicity of large-scale crystalline structures is to generate a mesh with each vertex being the location of a particle. With this, one can easily observe ordered and disordered regions in a material; well defined straight lines indicate a perfect crystal, with any bends indicating the presence of imperfections. Some of the most widely used methods for this are the dual techniques from computational geometry of Delaunay triangulation and Voronoi tessellation.

The Delaunay triangulation of an arbitrary set of points in Euclidian space, $\mathbf{R}$, which we will denote as $D(\mathbf{R})$, is constructed in the following way:
\begin{enumerate}
    \item No point will fall within the interior of any circumcircle of 3 points where $\mathbf{r}_{1..3} \subset \mathbf{R}$
    \item The Delaunay triangulation will maximise the minimum angle between points.
    \item If four points are on the same circumcircle, then both possible configurations give a Delaunay triangulation.
\end{enumerate}

\begin{figure}\centering
    %\includegraphics[width=0.45\textwidth]{Images/ch6_phasegineer/imgs/delaun}
    \includegraphics[width=0.45\textwidth]{Images/ch4_vtx/deltri}
    \caption{Non-Delaunay $(a)$ and Delaunay $(b)$ triangulation of 4 Euclidian points.}\label{fig:delaun}
\end{figure}
This concept is more easily explained visually. Fig.~\ref{fig:delaun} shows two different triangulations of four points; situation $(a)$ is a non-Delaunay triangulation, as the points $\mathbf{r}_1$ and $\mathbf{r}_3$ each fall within the circumcircle of the other points. However, by simply flipping the central edge from $(\mathbf{r}_2, \mathbf{r}_4)$ to $(\mathbf{r}_1, \mathbf{r}_3)$ we can see in $(b)$ that we now have a valid Delaunay triangulation. No point falls within the circumcircle of the other points, and the minimum angle formed is maximised relative to configuration $(a)$. Following directly from this, one can see that Delaunay triangulation can be used to connect the closest vertices in a network. A nice side-effect of Delaunay triangulation is that one can examine when the number of edges from a vertex deviates from the expected value in the lattice, which is 6 for triangular lattices. This can be a useful means to locate defects in a crystal lattice, and we will make use of this during later discussions. This is performed using the built-in \textsc{MATLAB} function ``delaunayTriangulation'', and counting the number of attachments to each individual vertex. A triangulation of the vortex lattice from Fig.~\ref{fig:showingoff} within the previously discussed radial boundary of $r=2\times 10^{-4}$ m is shown in Fig.~\ref{fig:delaun_vtxlatt}.

\begin{figure}\centering
    \includegraphics[width=0.45\textwidth]{Images/ch4_vtx/Del_tr_VTXLATT}
    \caption{Delaunay triangulation of the vortex lattice ground state. The vertices away from the condensate boundary have the expected 6-edge structure.}\label{fig:delaun_vtxlatt}
\end{figure}

An alternative representation, using the dual of the Delaunay triangulation, is that of the Voronoi tessellation (diagram). The characteristic of these diagrams is that they are composed of cells each encompassing an individual vertex, within which all enclosed points are closer to that particular vertex than any other. This representation can be generated from the Delaunay triangulation and vice-versa. Taking the centres of the circumcircles describing the Delaunay triangulations, and connecting these forms the boundaries of the Voronoi cells. A simple generation method can be seen as creating and expanding the radius of circles (or $n$-spheres in $n$-dimensions) centred on each vertex. Where the circles intersect with one another defines the boundary of each individual cell. An example of a Voronoi diagram compared with a Delaunay triangulation is given by Fig.~\ref{fig:Voronoi}.
\begin{figure}\centering
    \includegraphics[width=0.55\textwidth]{Images/ch4_vtx/voronoi}
    \caption{Comparison of Delaunay triangulation $(a)$ with a Voronoi diagram $(b)$. These graphs are duals, which means that one can be used to generate the other.}\label{fig:Voronoi}
\end{figure}
The area of each cell can be used as a metric of the strength of the interaction between particles in a many-body system, but also we may represent quantities local to each region in a system by the colour-scale of each cell. For the vortex lattice as given by Fig.~\ref{fig:showingoff}, a sample Voronoi diagram is given in Fig.~\ref{fig:voron_vtxlatt} with the color representing the area spanned by each Voronoi cell of the lattice.

\begin{figure}\centering
    \includegraphics[width=0.55\textwidth]{Images/ch4_vtx/Voronoi_area_VTXLATT}
    \caption{Voronoi tesselation of the vortex lattice. The area of each cell is represented by the color mapping. To avoid the tessellation tending to infinity, a buffer region of vortices is created close to the boundary. }\label{fig:voron_vtxlatt}
\end{figure}


\chapter{Conclusions and future work}
\label{chp:chapter7}
\graphicspath{{figures/}{figures/chapter6/}}
\pgfplotsset{
  table/search path={{figures/chapter6/data},{data}},
}

In this dissertation, an isogeometric analysis based patch coupling framework for higher order PDEs is developed. Mathematical analysis and numerical examples veriefy the accuracy and robustness of this technology. The use of dual basis with compact support significantly increases the sparsity of the constrained linear system and reduces the computational cost. In addition, this technology provides a unified formulation when dealing with vertices with different valences, which makes it an ideal analysis technology for higher order problems over unstructured meshes. The main contributions can be summarized as:
\begin{itemize}
  \item Formulation of abstract dual mortar method for both homogeneous and non-homogeneous constraints.
  \item Development of \Bezier dual mortaring framework for higher order problems, including biharmonic problem, phase-field problem and Kirchhoff-Love shell problem.
  \item Development and implementation of different vertex treatments for multi-patch coupling problem.
  \item Development of the enriched \Bezier dual basis, which improves the approximation ability of the \Bezier dual basis.
  \item Development and implementation of two locking-free formulations for both Timoshenko beam and linear elasticity problem.
  \item Implementation of a C++ based multi-thread isogeometric analysis code which is utilized in:
  \begin{itemize}
    \item Simulations of Poisson and biharmonic problems
    \item Simulations of wave propagation problems
    \item Simulations of coupling problems based on the discontinuous Galerkin method
    \item Simulations of linear elasticity and Timoshenko beam problems
    \item Simulations of phase field problems
    \item Simulations of Kirchhoff-Love shell problems
  \end{itemize}
\end{itemize}

There exist many potential future work we can perspect from this work. From the modelling aspect, a potential extension of the present work is to incorperate the constrained NURBS patches directly into the CAD process. The dual mortar formulation provides a direct access to locally supported basis functions in the constrained space, however, these basis functions are not guaranteed to be positive over their supports and form a partition of unity, which are of crucial importance for the CAD community. Hence, in order to use the constrained basis functions as the design space, a better formulation is needed to accommodate these two properties. The support size of the constrained basis function is directly linked to the support size of dual basis functions. However, current enrichment procedure improves the polynomial reproduction at the expense of support size of enriched \Bezier dual basis functions. We believe there exists a better formulation that can achieve the same performance without any influences on the support size.\par

There are many potential research topics in the analysis aspect as well. Since the focus of this research is on the development of a coupling formulation, we assume all materials tested in this work to be linear elastic. Hence, the verification of the dual mortar formulation over non-linear material is needed. The vibration example proved that the weak-$C^1$ coupling scheme can significantly reduce the highest eigenvalue. Hence, it is interested to see the performance of this work in explicit dynamics. $C^2$ continuous functions are required for solving $6^\text{th}$ order PDEs, including the triharmonic equation~\cite{tagliabue2014isogeometric, bartezzaghi2015isogeometric}, the phase-field crystal equation~\cite{gomez2012unconditionally} and Kirchhoff-Love shell with strain gradient elasticity~\cite{balobanov2019kirchhoff}. Fortunately, it seems that most of the theory and formulation developed in this dissertation can be directly applied in the formulation of weak-$C^2$ continuity. For the coupling of Kirchhoff-Love shell, the dual mortar compatible constraint in this work is slightly stronger than what is required by the problem and may lead to sub-optimal convergence for patches connected at a kink. Hence, the development of a better constraint for Kirchhoff-Love shell is still needed. In addition, shell structures are often connected with solid components (e.g. stiffner), an extension to handle solid-shell coupling is of crucial importance. Furthermore, in the development of dual basis based locking-free element, our study is restricted to the small deformation scenario, however, an extension to the large deformation scenario is of crucial importance. In all of these directions, the use of isogeometric analysis should lead to improvements in both efficiency and accuracy. As a result, these direction may become potentially fruitful research areas in the future.


\section{Zipper}

% \question{Add a visual example?}

The Zipper is a technique of representing a data structure by keeping track of how the data structure is being traversed through. The Zipper was first described by \citeauthor{huet1997zipper}\cite{huet1997zipper} and is a solution for efficiently updating pure recursive data structures in a purely functional programming language (e.g., Haskell). This is accomplished by keeping track of the downward current subtree and the upward path, also known as the \textit{location}.

To keep track of the upward path, we need to store the path we traverse to the current subtree. The traversed path is stored in the \texttt{Cxt} datatype. The \texttt{Cxt} datatype represents three options the path could be at: the \texttt{Top}, the path has traversed to the left (\texttt{L}), or the path has traversed to the right (\texttt{R}).

\begin{minted}{haskell}
data Cxt a = Top
           | L (Cxt a) (Tree a) a
           | R (Cxt a) (Tree a) a

type Loc a = (Tree a, Cxt a)

enter :: Tree a -> Loc a
enter t = (t, Top)
\end{minted}

Using the \texttt{Loc}, we can define multiple functions on how to traverse through the \texttt{Tree}. Then, when we get to the desired location in the \texttt{Tree}, we can call the \texttt{modify} function to change the \texttt{Tree} at the current location.

Eventually, when every value in the \texttt{Tree} has been changed, the entire \texttt{Tree} can then be rebuilt using the \texttt{Cxt}. By recursively calling the \texttt{up} function until the top is reached, the current subtree gets rebuilt. And when the top is reached, the entire tree is then returned.

\begin{minted}{haskell}
left :: Loc a -> Loc a
left (Node l x r, c) = (l, L c r x)

right :: Loc a -> Loc a
right (Node l x r, c) = (r, R c l x)

up :: Loc a -> Loc a
up (t, L c r x) = (Node t x r, c)
up (t, R c l x) = (Node l x t, c)

modify :: (Tree a -> Tree a) -> Loc a -> Loc a
modify f (t, c) = (f t, c)

leave :: Loc a -> a
leave (t, Top) = t
leave l        = top (up l)

> leave $ modify (const (Leaf 4)) $ left $ enter (Node (Leaf 1) 2 (Leaf 3))
    (Node (Leaf 4) 2 (Leaf 3))
\end{minted}

\subsection{Zipper \texttt{TreeH}}
\label{subsec-zipper-treeh}

The implementation of the Zipper for the \texttt{TreeH} datatype is the same as for the \texttt{Tree} datatype. However, the \texttt{TreeH} also contains the hash of the current and underlying data structure. Therefore, when a value is modified in the \texttt{TreeH}, all the parent nodes of the modified value needs to be updated.

The \texttt{updateLoc} function modifies the value at the current location, then checks if the location has any parents. If the location has any parents, go up to that parent, update the hash of that parent and recursively update the parents hashes until we are at the top of the data structure. Otherwise, return the modified locations, because all the other hashes are not affected by the change.

\begin{minted}{haskell}
updateLoc :: (TreeH a -> TreeH a) -> Loc a -> Loc a
updateLoc f l = if top l' then l' else updateParents (up l')
  where
    l' = modify f l
    updateParents :: Loc a -> Loc a
    updateParents (Loc x Top) = Loc (updateHash x) Top
    updateParents (Loc x cs)  = updateParents $ up (Loc (updateHash x) cs)
\end{minted}

Then, the \texttt{update} function can be defined using the \texttt{updateLoc} function, by first traversing through the data structure with the given directions. Then modifying the location using the \texttt{updateLoc} function and then leave the location and the function results in the updated data structure.

\begin{minted}{haskell}
update :: (TreeH a -> TreeH a) -> [Loc a -> Loc a] -> TreeH a -> TreeH a
update f dirs t = leave $ updateLoc f l'
  where
    l' = applyDirs dirs (enter t)
\end{minted}


% Note that the text in the [] brackets is the one that will
% appear in the table of contents, whilst the text in the {}
% brackets will appear in the main thesis.

%% APPENDIX HEADER ////////////////////////////////////////////////////////////////////////////////////

\chapter{Interfaces coupling matrix}
\label{app:algorithm}

%% APPENDIX CONTENT ///////////////////////////////////////////////////////////////////////////////////
\begin{algorithm}[H]
	\SetAlgoLined
	\KwResult{coupling matrix \textbf{G}}
	\For{i = 1 \KwTo 2}{
		create \(n^{\Gamma}\times n^{s_i}\) null matrix
		\(\mathbf{G}_i\),\\
		\For{j = 1 \KwTo \(n^{\Gamma}\)} {
			find \(ownerElement^j_i\) in the structure \(s_i\)
			containing interface node \(j\) with global coordinates vector:
			\(X_p=(x^j_p,y^j_p)\)\;
			assign vector \(X_e=(x_e,y_e)\) of coordinates of all nodes in
			\(ownerElement^j_i\)\;
			assign initial coordinates
			\(X_{\kappa}=(x^j_{\kappa},y^j_{\kappa})\) to the nearest node in
			\(ownerElement^j_i\) to node \(j\)\;
			transform global coordinates \(X_{\kappa}\) to a local coordinate system \(\xi_{\kappa}=\xi(X_{\kappa});\quad
			\eta_{\kappa}=\eta(X_{\kappa})\)\;
			\While{\(\left|X_p-X_{\kappa}\right|>tol\)}{
				\(\xi_{\kappa+1}=\xi_{\kappa}+(J^{-1}_{\kappa})_{11}.*(x^j_p-x_{\kappa}^j)
				+(J^{-1}_{\kappa})_{12}.*(y^j_p-y_{\kappa}^j)\)\;
				\(\eta_{\kappa+1}=\eta_{\kappa}+(J^{-1}_{\kappa})_{21}.*(x^j_p-x_{\kappa}^j)
				+(J^{-1}_{\kappa})_{22}.*(y^j_p-y_{\kappa}^j)\)\;
				\(X_{\kappa}=N_{\kappa+1}X_e\)\;
				}
			\(\mathbf{G}_i(j,n^{X_e})=N_{\kappa+1}\)\;
		}
		\uIf{\(s_i\) is 3D} {
			\(\mathbf{G}_i=\left[\begin{array}{ccc}
			\mathbf{G}_i & \mathbf{0} & \mathbf{0}\\
			\mathbf{0} & \mathbf{G}_i & \mathbf{0}\\
			\mathbf{0} & \mathbf{0} & \mathbf{G}_i
			\end{array} \right]
			\)\;
		}
		\ElseIf{\(s_i\) is 2D} {
			\(\mathbf{G}_i=\left[\begin{array}{ccccc}
			\mathbf{G}_i & \mathbf{0} & \mathbf{0} &
			\frac{h_i}{2}\mathbf{G}_i & \mathbf{0}\\
			\mathbf{0} & \mathbf{G}_i & \mathbf{0} & \mathbf{0} &
			\frac{h_i}{2}\mathbf{G}_i\\
			\mathbf{0} & \mathbf{0} & \mathbf{G}_i & \mathbf{0} &
			\mathbf{0}
			\end{array} \right]\)\;
		}
	}
	\(\mathbf{G}=\left[\begin{array}{cc}
	\mathbf{G}_1 & \mathbf{G}_2
	\end{array} \right].\)
	\caption{Interface coupling matrix formulation}
	\label{alg:G_matrix}
\end{algorithm}
where \(s_i\) is the structure to, \(n^{\Gamma}\) and \(n^{s_i}\) are numbers of nodes of the interface, respectively; \(J_{\kappa}\) is the Jacobian evaluated at \((\xi_{\kappa},\eta_{\kappa})\) and \(N_{\kappa+1}\) is the shape function evaluated at \((\xi_{\kappa+1},\eta_{\kappa+1})\), \(n^{X_e}\) is the vector of global order numbers of all nodes in the \(ownerElements^j_i\), \(h_i\) is a thickness of the structure \(s_i\) and \(tol\) is a termination criterion for iterations.


\chapter{Introduction}
WEC-Sim (Wave Energy Converter SIMulator) is an open source wave energy converter (WEC) simulation tool. The code is developed in MATLAB and Simulink using the multibody dynamics solver SimMechanics. WEC-Sim has the ability to model devices that are comprised of rigid bodies, power-take-off (PTO) systems, and mooring systems. Hydrodynamic forces are modeled using a radiation and diffarction method, and the system dynamics is performed in the time domain by solving the governing WEC equations of motion in 6 degrees of freedom (DOF).

In this user manual, the theory of WEC-Sim is described in \hyperlink{chapter.2}{Chapter 2}. The installation of MATLAB and WEC-Sim and how to run WEC-Sim is described in \hyperlink{chapter.3}{Chapter 3}. The pre-developed WEC component library structure is presented in \hyperlink{chapter.4}{Chapter 4}. The code WEC-Sim structure and the input parameters for running WEC-Sim are described in \hyperlink{chapter.5}{Chapter 5}. Finally, the application of WEC-Sim to model a point absorber and a oscillating surge device is presented in \hyperlink{chapter.6}{Chapter 6}.