%-------------------------------------------------------------------
%
% Author    : Vadim Vinnik
% E-mail    : vadim.vinnik@gmail.com
% Status    : Draft
% License   : Creative commons
%
%-------------------------------------------------------------------

\documentclass{article}

\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{amsthm}
\usepackage{amsmath}
\usepackage{dirtree}
\usepackage{listings}
\usepackage{stackrel}

\lstloadlanguages{Haskell}
\lstset{%
  basicstyle={\small\ttfamily},%
  language=Haskell%
}

\DTsetlength{0.2em}{2em}{0.2em}{0.4pt}{1pt}

\theoremstyle{definition}
\newtheorem{Df}{Definition}
\newtheorem{St}{Statement}
\newtheorem{Ex}{Example}

\newcommand{\setcharmvcn}{M}
\newcommand{\setcharmt}{T}

\newcommand{\setsymbol}[3]{\mathcal{#1}_{#2,#3}}

\newcommand{\setmvcn}[2]{\setsymbol{\setcharmvcn}{#1}{#2}}
\newcommand{\setmt}[2]{\setsymbol{\setcharmt}{#1}{#2}}

\newcommand{\seta}{\mathcal{A}}
\newcommand{\setn}{\mathcal{N}}

\newcommand{\flatten}{\operatorname{Fl}}
\newcommand{\select}{\operatorname{Sel}}
\newcommand{\deref}{\operatorname{Get}}
\newcommand{\putval}{\operatorname{Put}}
\newcommand{\proj}[2]{\operatorname{pr}^{#1}_{#2}}
\newcommand{\fmap}{\operatorname{Map}}
\newcommand{\fpam}{\operatorname{Pam}}
\newcommand{\id}{\operatorname{id}}
\newcommand{\apply}{\operatorname{Apply}}
\newcommand{\ylppa}{\operatorname{Ylppa}}
\newcommand{\eval}{\operatorname{Eval}}

\newcommand{\inapply}{\mathbin{\nabla}}

\title{Compound names with multiple values: formalisation, properties and implementation}
\author{Vadim Vinnik}
\date{2016}

\begin{document}

\maketitle

\begin{abstract}
Naming is one of the most fundamental concepts in programming.  In most cases,
a name is considered to be atomic and to have a unique value.  This paper
describes a kind of naming with both these principles negated: names form a
monoid under concatenation, and each name can be associated with multiple
values.  Two different but equivalent formalisations are defined, their
isomorphism is shown.  Counterparts of set-theoretical union, intersection and
cartesian product operations are defined, their properties are described.  A
data type implementing this kind of naming is designed in Haskell, it fits into
functor, applicative functor and monad classes.

Keywords:
applicative functor,
atomicity,
cartesian product,
compoundness,
concatenation,
denotation,
dereferencing,
functor,
Haskell,
implementation,
intersection,
monad,
monoid,
multivaluedness,
name,
relation,
set,
trie,
union.
\end{abstract}

\tableofcontents

\section{Introduction}

A trilateral relation between a \emph{name}, its \emph{meaning} and
\emph{value} has been in the focus of philosophical and mathematical logic,
metamathematics, semiotics and epistemology for a long time.  For example,
important questions about naming were raised and deeply investigated in
fundamental works by G.\,Frege~\cite{bib:frege},
L.\,Wittgenstein~\cite{bib:wittgenstein}, W.\,Quine~\cite{bib:quine}.  With
arising of computer science, naming gained a special significance~-- for
example, \emph{a name that refers to a name that, finally, relates to an
entity} is not a purely philosophical excercise anymore but a working tool for
everyday~-- an \emph{indirect pointer}; a \emph{a name with a meaning but
without a value} turned into a \emph{null reference} with both its power and
danger; \emph{names changing their values depeding on the context} became
\emph{variables} in the sense of imperative programming. Since \emph{addresses}
of some entities in memory are obviously a special case of names, and since
addresses are, in their turn, computable values, relations and interactions
between names and values in programming are even more complicated than in
pre-computer semiotics.

Therefore, every comprehensive theory of programming must give a special
explication of naming and include a mathematical model that reflects its
properties and behaviour.  Approaches and formal techniques however could be
very different.

For example, \emph{A Practical Theory of Programming}~\cite{bib:ptop} as well
as \emph{Unifying Theories of Programming}~\cite{bib:utp} represent a variable
declaration by means of a quantifier in some first order logic.  In the
first-order logic, a variable refers to an unspecified object of a semantic
domain; the formula tells about the objects using names to represent them.
Objects belong to the semantic level, and names to the syntactical level that
do not intersect.  Therefore, the first order formalism works fine for programs
that have a predefined list of variables but hardly can describe programs that
dynamically allocate memory for objects whose number is not known \emph{a
priori}.

On the contrast to above, there are theories that explicitly describe memory
layout and allocation operations, for example in terms of memory block
references~\cite{bib:leroy}, and other formal memory models.
Such theories reflect semantics of programs on a
relatively low, implementation-aware level, and their primary application is
formal specification and verification of compilers and OS kernels.

There is yet another option between these two extremes.  Names can be regarded
as computable values without cumbersome specifics of \emph{being addresses}.  A
typical example arises from array processing: \lstinline{a[i]} is a computable
name because this expression, depending on the current value of~\lstinline{i},
can refer to any of the array's elements and, therefore, evaluates to one of
the elements' names~--- and it is exactly how array indexing operation is
treated in C~language: adding offset \lstinline{i * size} to the base
address~\lstinline{a} gives a pointer to the element.

An elegant and general formalism for naming that does not burden names
with any alien specifics, but allows any specifics to be added if needed,
is a notion of \emph{naming set} introduced by V.\,N.\,Redko in a
comprehensive conception of \emph{compositional programming}~\cite{bib:redko}.

\begin{Df}\label{df:naming-set}
Suppose there is a given set~$D$ whose elements are called \emph{values}, or
\emph{denotata}, and a set~$V$ of objects called \emph{names}.
A \emph{$(V,D)$-naming set} (the prefix will be omitted when possible) is a
partial mapping $s: V\to D$.
\end{Df}

In other words, a naming set is an object of the form
\[
  s = \{ (v_1, d_1), (v_2, d_2), \ldots, \} ,
\]
where $v_i\in V$, $d_i\in D$, and all~$v_i$ are pairwise distinct. The
latter requirement formalizes \emph{unambiguity}, or \emph{univaluedness}: a
name cannot have different values in a given context.

\begin{Ex}\label{ex:naming-set}
A naming set $s = \{ (a, 1), (t, 7), (w, 1) \}$ represents a context where
the name~$a$ has a value~1, the name~$b$ refers to a value~7 and the name~$w$
denotes~1, no other names have values.
\end{Ex}

A set-theoretical intersection  of naming sets is obviously a naming set
whe\-re\-as a union is not because it can violate univaluedness:
\[
  \{ (a, 0) \} \cup \{ (a, 1) \} = \{ (a, 0), (a, 1) \} .
\]

Mappings similar to the one defined above are widely used in theoretical
computer science for syntactical as well as semantical tasks, a good example
could be an approach to definition of programming
languages~\cite{bib:ollongren}.  \emph{Dictionaries}~\cite{bib:dictionary} and
\emph{associative arrays}~\cite{bib:mehlhorn-assoc} are abstract data types
implementing the same idea, included into standard libraries of various
programming languages and widely used in practice.

At the topmost abstraction level, a naming set represents a ``plain'' relation
where names and values are atomic in the sense that their internal structures
and any non-trivial properties are hidden as irrelevant.  In fact, the only
special property taken into account by the definition above is
\emph{equatability} of names: for any two names, it should be possible to
decide whether they are identical.

Although def.~\ref{df:naming-set} does not mention or use any special properties
of names and values, it does not require their absense.
Introducing various properties of names and/or denotata, one can obtain a
number of interesting and useful specialised formalisations of naming for
theoretical purposes as well as implementable data structures suitable for
practical tasks. This article describes a kind of naming with
two important differences from the definition~\ref{df:naming-set}.
\begin{itemize}
\item \emph{Multivaluedness}: any name can be related to zero or more values;
\item \emph{Compoundness of names}: compound names could be concatenated from
shorter ones, i.e. names form a monoid under concatenation.
\end{itemize}
The first difference may seem violating the general definition of the
naming set but multivaluedness could be easily modelled as a special case of
univaluedness: the value is unique and is a set (of `proper' values).

\subsection*{Conventions about notation}

For any set~$X$, let~$X^\ast$ denote a set of all sequences of its elements
(also known as \emph{chains}), and~$2^X$ be a set of all subsets of~$X$.
If~$a,b\in X^\ast$ are two chains, their concatenation will be denoted simply
as~$ab$. Let~$\varepsilon$ stand for the empty chain.
Let $\proj{n}{k}$ be a function that maps an $n$-tuple to its $k$-th component.

A set of Latin letters (the alphabet) is denoted as~$\seta$,
and~$\setn$ denotes a set of natural numbers~-- these two sets will be
used in examples.

Throughout this paper, a class of atomic names is denoted with~$V$. The
variable~$u$ (maybe, with indices or other decorations) always takes values
in~$V$, whereas $v$ and $w$ take values from~$V^\ast$.

Some more notations will be introduced later, immediately before they are used.

\section{Relation-based definition and basic properties}

Let~$V$ be a given set of objects called \emph{atomic names}. Elements
of~$V^\ast$ are called \emph{compound names}. Let us omit the words ``atomic''
and ``compound'' if it does not lead to confusion.

\begin{Df}\label{df:mvcn}
A \emph{$(V,D)$-multinaming set} is a binary relation
\[
  s \subseteq V^\ast \times D .
\]
Whenever $V$ and $D$ are obvious from the context, we'll omit ``$(V,D)$-''
prefix and write simply ``multinaming set''. A set of $(V,D)$-multinaming sets will be
denoted~$\setmvcn{V}{D}$.
\end{Df}

Note that there is an obvious mapping from the class of $(V,D)$-multinaming
sets to the class of $(V^\ast, 2^D)$-naming sets as well as an opposite
mapping. Therefore, a multivalued naming could be modelled as a special case of
a univalued naming with extra specifics applied to values (being sets) and
names (being chains). Such modelling is not investigated below~-- instead, two
formalisations are described that reflect the essence of the notion in a more
direct way.

\begin{Ex}\label{ex:mvcn}
The following object is an $(\seta, \setn)$-multinaming set:
\[
  s = \{
    (\varepsilon, 0),
    (\varepsilon, 1),
    (a,           2),
    (a,           3),
    (a,           4),
    (aa,          5),
    (ab,          6),
    (b,           7),
    (baaa,        8)
  \} .
\]
Here the empty name has two values (0 and~1), name~$a$ has three (2, 3 and~4),
comound names~$aa$ and~$ab$ have each a single value (5 and~6, respectively),
name~$b$ has a value~7 and, finally, a name~$baaa$ has one value~8. All other
names from~$\seta^\ast$ have no values.
\end{Ex}

Note that, in contrast with naming sets, no special conditions are imposed
on a multinaming set~--- it is just an arbitrary set of name-value pairs.
Therefore, $\setmvcn{V}{D}$ is closed against set-theore\-tical union
and intersection.
\begin{St}\label{st:mvcn-setop}
If~$s$ and~$t$ are $(V,D)$-multinaming sets, so are~$s\cup t$ and~$s\cap t$.
\end{St}

When it is important to emphasise that union and intersection are operations
on multinaming sets rather than on general case of sets, we will
write~$\cup_\setcharmvcn$ and~$\cap_\setcharmvcn$.

One of the fundamental operations on (univalued) naming sets is retrieving the
only (if any) value~$d$ associated with the name~$v$ in a naming set~$s$.
Depending on the goals and abstraction level of a particular context, it could
be regarded either as~$s(v)=d$, i.e. applying a function~$s$ to an
argument~$v$, or as an operation whose arguments are the naming set and the
name, i.e.~$\deref(s, v)=d$. Its counterpart in multinaming set world that
retrieves all values of a name, no matter how many, obviously cannot be denoted
using the first style.

\begin{Df}\label{df:mvcn-dereferencing}
\emph{Dereferencing} is an operation~$\deref_\setcharmvcn$ (or, whenever
possible, omiting the subscript, simply~$\deref$) of type
$\setmvcn{V}{D} \times V^\ast \to 2^D$,
such that
\[
  \deref_\setcharmvcn(s, v) = \{ d \mid (v, d) \in s \} .
\]
\end{Df}

Unlike the univalued case, here~$\deref$ is a total operation: even if a
name~$v$ does not have any associated value in a multinaming set~$s$, dereferencing
it just yields an empty set of values.

\begin{Ex}\label{ex:mvcn-dereferencing}
Consider a multinaming set~$s$ from ex.~\ref{ex:mvcn}. Then
\begin{eqnarray*}
  \deref(s, \varepsilon) & = & \{ 0, 1 \}, \\
  \deref(s, baaa)        & = & \{ 8 \}, \\
  \deref(s, cdcd)        & = & \varnothing .
\end{eqnarray*}

\end{Ex}

It follows immediately from the definition that dereferencing distributes
over set-theore\-tical operations.
\begin{St}\label{st:mvcn-deref-distributivity}
Let~$\odot$ stand for either~$\cup$ or~$\cap$, and let~$s$ and~$t$ be
$(V,D)$-multinaming sets. Then, for every~$v\in V^\ast$,
\[
  \deref(s\odot t, v) = \deref(s, v) \odot \deref(t, v) .
\]
\end{St}

The following important property means, in fact, that every multinaming set is completely
defined by the values of all its names.  In terms of programming, it means that
if two multinaming set objects' behaviours (observed through the $\deref$ selector) are
indiscernible, the objects are identical.
\begin{St}\label{st:mvcn-deref-equality}
Let $s, t \in \setmvcn{V}{D}$. Then
\[
  (\forall v\in V^\ast . \deref(s,v) = \deref(t,v)) \implies (s = t) .
\]
\end{St}

The following operation is, in a reasonable sense, an opposite to
dereferencing.  It replaces all values of some name with a new set of values.
Thus, it is similar to assignment in the sense of imperative programming.
\begin{Df}\label{df:mvcn-replace}
\emph{Replacement} is an operation
\begin{eqnarray*}
 & \putval_\setcharmvcn :
    \setmvcn{V}{D} \times V^\ast \times 2^D \to \setmvcn{V}{D}, \\
 & \putval_\setcharmvcn(s, v, x) =
      \{ (w, d) \mid (w, d) \in s, w \neq v \} \cup
      \{ (v, d) \mid d \in x \} .
\end{eqnarray*}
The subscript will be omitted further whenever possible.
\end{Df}
In other words, this operation deletes from~$s$ all values corresponding to
the name~$v$, leaves all other name-value pairs intact and assigns new values
to~$v$.

\begin{Ex}\label{ex:mvcn-replace}
Let~$s$ be a multinaming set from ex.~\ref{ex:mvcn}. Then
\[
  \putval(s, a, \{ 9, 10 \}) = \{
    (\varepsilon, 0),
    (\varepsilon, 1),
    (a,           9),
    (a,           10),
    (aa,          5),
    (ab,          6),
    (b,           7),
    (baaa,        8)
  \} .
\]
\end{Ex}

The main property of replacement is obvious and immediately follows from the
definition: it changes the values of one name and does not influence the other
names. Except this, two replacement operations commute if they
relate to different names, otherwise the outer operation absorbs the inner one.
\begin{St}\label{st:mvcn-replace-deref}
Let~$s \in \setmvcn{V}{D}$, $v, w \in V^\ast$, $x, y \in 2^D$. Then
\begin{eqnarray*}
  & \deref(\putval(s, v, x), v) = x , \\
  & v \neq w \implies \deref(\putval(s, v, x), w) = \deref(s, w) , \\
  & \putval(\putval(s, v, x), v, y) = \putval(s, v, y) , \\
  & v \neq w \implies \putval(\putval(s, v, x), w, y) = \putval(\putval(s, w, y), v, x) .
\end{eqnarray*}
\end{St}

Let us introduce special terms and symbols for the two extreme cases of
multinaming sets, namely:
\begin{Df}\label{df:mvcn-extreme}
Multinaming set $\bot_\setcharmvcn$ called \emph{empty} and $\top_\setcharmvcn$ called
\emph{full} are defined by
\begin{eqnarray*}
  \bot_\setcharmvcn &  = &  \varnothing ; \\
  \top_\setcharmvcn &  = &  V^\ast \times D .
\end{eqnarray*}
Further, we'll omit the subscript when it does not lead to confusion.
\end{Df}

In other words, each name in the empty multinaming set has no value whereas in the
full multinaming set every name has all possible values.
\begin{St}\label{st:mvcn-extreme-deref}
For any~$v\in V^\ast$,
\begin{eqnarray*}
  \deref(\bot, v) & = & \varnothing, \\
  \putval(\bot, v, \varnothing) & = & \bot , \\
  \deref(\top, v) & = & D , \\
  \putval(\top, v, D) & = & \top .
\end{eqnarray*}
\end{St}

The next property is also just a trivial consequence of the definition:~$\bot$
and~$\top$ objects are units of~$\cup$ and~$\cap$ operations respectively and
zeros vice versa.
\begin{St}\label{st:mvcn-neutrals}
For any multinaming set~$s$,
\begin{eqnarray*}
  \bot \cup s & = & s,    \\
  \top \cap s & = & s,    \\
  \bot \cap s & = & \bot, \\
  \top \cup s & = & \top.
\end{eqnarray*}
\end{St}

Note that a compound name~$v$ in a multinaming set~$s$ not only refers to its
values but also is a common prefix for a ``bunch'' of names starting with~$v$.
A name~$vw$ in a multinaming set~$s$ can be regarded as a name~$w$
\emph{relative} to a point referred to by~$v$ or, in other words, as a name~$w$
in a multinaming set subobject selected from~$s$. To select a subobject means:
throw away names that do not start with~$v$, and remove this comon prefix from
those that do. Formally, it leads to the definition.

\begin{Df}\label{df:mvcn-select}
Let~$s\in\setmvcn{V}{D}$, $v\in V^\ast$, then \emph{selection} from~$s$
under~$v$ is
\[
  \select_\setcharmvcn(s,v) = \{ (w, d) \mid (vw, d)\in s \} \in\setmvcn{V}{D}.
\]
As always, the subscript will be omited if possible.
\end{Df}

\begin{Ex}\label{ex:mvcn-select}
Let~$s$ be a multinaming set from ex.~\ref{ex:mvcn}, then
\begin{eqnarray*}
  \select(s, a) & = & \{
    (\varepsilon, 2),
    (\varepsilon, 3),
    (\varepsilon, 4),
    (a,           5),
    (b,           6)
  \} , \\
  \select(s, b) & = & \{
    (\varepsilon, 7),
    (aaa,         8)
  \} , \\
  \select(s, cdcd) & = & \bot .
\end{eqnarray*}
\end{Ex}

\begin{St}\label{st:mvcn-selection-properties}
For any~$s,t\in\setmvcn{V}{D}$, $v, w\in V^\ast$, $\odot\in\{\cup, \cap\}$,
\begin{eqnarray*}
  & \select(\bot,v) = \bot, \\
  & \select(\top,v) = \top, \\
  & \select(s,\varepsilon) = s, \\
  & \select(s,vw) = \select(\select(s,v), w), \\
  & \select(s\odot t, v) = \select(s,v)\odot \select(t,v).
\end{eqnarray*}
\end{St}
In other words,
\begin{itemize}
\item selection preserves empty and full multinaming set;
\item selection under an empty name is an identity over multinaming sets;
\item selection under a compound name can be performed by parts;
\item selection distributes over union and intersection.
\end{itemize}

It is interesting to note that there is another formalisation of the
multivalued naming that is, however, equivalent to the above definitions.  It
is described in the next section.

\section{Trie-based definition}

Take a closer look at the multinaming set~$s$ from ex.~\ref{ex:mvcn}.  Recall
the idea underlying selection operation: any name~$v$ is a common prefix for a
bunch of names of the form~$vw$~-- and, therefore, is a root of a sub-naming
relative to~$v$. Except this, take into account that the empty
name~$\varepsilon$ is a common prefix for all names.

The name~$\varepsilon$, the simplest name ever, refers in~$s$ to a set of
values~$\{0,1\}$. Name~$a=\varepsilon a$ is an extension of~$\varepsilon$ by
one atomic name and refers to values~$\{2,3,4\}$. In its turn, name~$a$ can be
extended by one atomic name to~$aa$, $ab$, \ldots, $az$, from which only the
former two have values.  Now return to the empty name and compose another its
continuation, namely~$b$.  This name has no values but it is a prefix for~$ba$
that, in its turn, can be extended to~$baa$ and then to~$baaa$ that has
non-empty set of values.

This gives a hierarchical view of~$V^\ast$ where
\begin{itemize}
\item the root of the hierarchy is the empty name;
\item appending an atomic component to a name moves one level deeper;
\item a common prefix is a common ancestor.
\end{itemize}
The corresponding tree-like representation of the multinaming set~$s$ is shown on
fig.~\ref{fig:trie}.

\begin{figure}[ht]
\begin{center}
\begin{minipage}{17em}
\dirtree{%
  .1 $\varepsilon$\DTcomment{$\{0, 1\}$} .
    .2 $a$\DTcomment{$\{2, 3, 4\}$} .
      .3 $a$\DTcomment{$\{5\}$} .
      .3 $b$\DTcomment{$\{6\}$} .
    .2 $b$\DTcomment{$\{7\}$} .
      .3 $a$\DTcomment{$\varnothing$} .
        .4 $a$\DTcomment{$\varnothing$} .
          .5 $a$\DTcomment{$\{8\}$} .
}
\end{minipage}
\end{center}
\caption{A multitrie corresponding to the multinaming set~$s$}\label{fig:trie}
\end{figure}

To grasp this informal consideration in a definition, it would be convenient to
assume that every node in the hierarchy has \emph{all} possible children~-- i.e.
that the hierarchy includes all names from~$V^\ast$ regardless of whether they
have values: otherwise we needed a special treatment for missing names in
every subsequent definition or statement. This leads to the following

\begin{Df}\label{df:mt}
A class of \emph{$(V,D)$-multitries} (or simply \emph{multitries} when~$V$
and~$D$ are known from the context or irrelevant):
\[
  \setmt{V}{D} = 2^D \times (V \to \setmt{V}{D}) .
\]
\end{Df}

In other words, a $(V,D)$-multitrie is a pair $s = (x, m)$ where~$x\subseteq D$
is a set of values and $m: V \to \setmt{V}{D}$ is a total mapping of
atomic names to some $(V,D)$-multitries called \emph{children}.
Note that this recursive definition does
not have any basic case: every multitrie contains child multitries
under all atomic names, hence there are no leaf nodes.
Depicting multitries graphically, as on fig.~\ref{fig:trie}, we will however
only draw nodes of interest assuning that all other nodes have empty sets of
values.  Note that a $(V,D)$-multitrie is a \emph{trie} also known as
a prefx tree~\cite{bib:knuth-trie}~-- that justifies the term.

Extreme multitries have the following recurrent definitions.
\begin{Df}\label{df:mt-extreme}
\emph{Empty} and \emph{full} $(V,D)$-multitries:
\begin{eqnarray*}
  \bot_\setcharmt & = &
      ( \varnothing, \{ u \mapsto \bot_\setcharmt \mid u\in V \} ) , \\
  \top_\setcharmt & = &
      ( D,           \{ u \mapsto \top_\setcharmt \mid u\in V \} ) .
\end{eqnarray*}
Subscripts will be further omited whenever possible.
\end{Df}
In other words, empty (full) multitrie is a multitrie that has an empty
(full) set of values and whose children under all atomic names are, in their
turn, empty (full) multitries.

\begin{Df}\label{df:mt-select}
\emph{Selection} operation. Let $s=(x,m) \in \setmt{V}{D}$, $u\in V$,
$v\in V^\ast$, then
\begin{eqnarray*}
  \select_\setcharmt(s, \varepsilon) & = & s , \\
  \select_\setcharmt(s, u v) & = & \select_\setcharmt(m(u), v) .
\end{eqnarray*}
Subscripts will be omited if possible.
\end{Df}

In other words, selection operation finds a node pointed to by the
compound name as a path in the trie, and takes a sub-trie starting
at this node.

\begin{Ex}\label{ex:mt-select}
Consider a multitrie~$s$ depicted on fig.~\ref{fig:trie}. Selection under a
name~$a$ results in a multitrie~$\select(s,a)$ shown on
fig.~\ref{fig:mt-select}.
\end{Ex}

\begin{figure}[ht]
\begin{center}
\begin{minipage}{17em}
\dirtree{%
  .1 $\varepsilon$\DTcomment{$\{2, 3, 4\}$} .
    .2 $a$\DTcomment{$\{5\}$} .
    .2 $b$\DTcomment{$\{6\}$} .
}
\end{minipage}
\end{center}
\caption{Selection of a multitrie}\label{fig:mt-select}
\end{figure}

\begin{Df}\label{df:mt-deref}
Given a $(V,D)$-multitrie~$s$ and a name~$v\in V^\ast$, \emph{dereferencing}
of~$v$ in~$s$ is
\[
  \deref_\setcharmt(s, v) = \proj{2}{1}(\select(s, v)) .
\]
As always, we'll not write the subscript if it is obvious from the context.
\end{Df}

In other words, if $\select(s,v) = (x,m)$, then $\deref(s, v) = x$. To
dereference a name in a multitrie, one needs to follow the compound name
as a path to a node in the trie and then take the value stored in that node.

\begin{Df}\label{df:mt-setop}
\emph{Union} and \emph{intersection}.
Let
$\odot \in \{ \cup, \cap \}$,
$s, t \in \setmt{V}{D}$,
$s = (x, m)$, $t = (y, n)$.
Then
\[
  s \odot_\setcharmt  t =
    (x \odot y, \{ u \mapsto m(u) \odot_\setcharmt n(u) \mid u \in V \}) .
\]
\end{Df}
Note that subscripts in this definition help to distinguish between
set-the\-o\-re\-ti\-cal operations on sets of values and corresponding operations
on multitries.

In other words, to build $r = s \cup t$, one needs to go through all compound
names and, for each name, build a union of the value sets contained in the
operands under that name.

Let us also define an operation that corresponds to replacement
defined for multinaming sets (see def.~\ref{df:mvcn-replace}). Like other multitrie
operations, the most natural way of defining it is recursive.

\begin{Df}\label{df:mt-replace}
\emph{Replacement} is an operation
\[
  \putval_\setcharmt : \setmt{V}{D} \times V^\ast \times 2^D \to \setmt{V}{D},
\]
such that, for any
$s = (x, m) \in \setmt{V}{D}$, $y \in 2^D$, $u \in V$, $v \in V^\ast$,
\begin{eqnarray*}
  \putval_\setcharmt(s, \varepsilon, y) & = & (y, m) , \\
  \putval_\setcharmt(s, u v, y) & = & (x, m') ,
\end{eqnarray*}
where $m' : V \to \setmt{V}{D}$ is such a function that $m'(u') = m(u')$ for any
$u'\neq u$, and
\[
  m'(u) = \putval_\setcharmt(m(u), v, y) .
\]
The subscript after the operation will be omited whenever it does not lead to
confusion.
\end{Df}

In other words, to perform a replacement in a multitrie, one has to distunguish
between two cases. If the name to be replaced is empty, just replase the set of
values in the root node of the trie. Otherwise, take the first atomic component
of the name, go to the child node associated with that atom, and perform a
replacement under a remainder of the name.

It is easy to see that properties identical to those of multinaming sets
hold for multitries, namely counterparts of
st.~\ref{st:mvcn-deref-distributivity},
\ref{st:mvcn-deref-equality},
\ref{st:mvcn-replace-deref},
\ref{st:mvcn-extreme-deref},
\ref{st:mvcn-neutrals}
and~\ref{st:mvcn-selection-properties}.
Moreover, all properties of multinaming sets and multitries are identical because
of the following property.

\begin{St}\label{st:isomorph}
Consider a mapping~$\varphi: \setmvcn{V}{D} \to \setmt{V}{D}$, such that,
for any~$s\in \setmvcn{V}{D}$,
\[
  \varphi(s) = (
    \deref_\setcharmvcn(s, \varepsilon) ,
    \{ u \mapsto \varphi(\select_\setcharmvcn(s, u) \mid u\in V \})
  ) .
\]
Then~$\varphi$ is a bijection that preserves
extreme elements, union, intersection, dereferencing, replacement and selection
operations:
\begin{eqnarray*}
  & \varphi(\bot_{\setcharmvcn}) = \bot_{\setcharmt}, \\
  & \varphi(\top_{\setcharmvcn}) = \top_{\setcharmt}, \\
  & \varphi(s \mathbin{\odot_{\setcharmvcn}} t) =
      \varphi(s) \mathbin{\odot_{\setcharmt}} \varphi(t) , \\
  & \deref_{\setcharmvcn}(s, v) =
      \deref_{\setcharmt}(\varphi(s), v) , \\
  & \varphi(\putval_{\setcharmvcn}(s, v, s)) =
      \putval_{\setcharmt}(\varphi(s), v, s) , \\
  & \varphi(\select_{\setcharmvcn}(s, v)) =
      \select_{\setcharmt}(\varphi(s), v) ,
\end{eqnarray*}
for all $s,t \in \setmvcn{V}{D}$, $v \in V^\ast$.
\end{St}

In other words, $\varphi$~is an isomorphism from many-sorted algebra of
multinaming sets to an algebra of multitries.
This allows us to switch flexibly between multinaming set and multitrie
languages when describing further notions, choosing the most
appropriate form in each particular case.

\section{Cartesian product and flattening}

Operations described in the previous sections (union, intersection, selection)
preserve the type and structure of their operands. This section describes two
more complicated operations.

Before giving a formal definition for a cartesian product of namings, let us
informally describe how should an operation look like to deserve this name.
Let~$s'$ and~$s''$ be two multinaming sets. The values in their cartesian
product should be pairs~$(d',d'')$ where $d'$~is a value from~$s'$ and $d''$~is
taken from~$s''$. But these values are attached to some names~-- say,
$v'$~and~$v''$, respectively.  Therefore, the product should contain the
combined value~$(d',d'')$ under a name combined from~$v'$ and $v''$, and the
only combining operation defined for names is concatenation.

\begin{Df}\label{df:mvcn-cartesian}
Let~$s'$ and~$s''$ be $(V,D')$- and $(V,D'')$-multinaming sets, respectively. Their
\emph{cartesian product} is a $(V,D'\times D'')$-multinaming set
\[
  s'\times s'' = \{ (v' v'', (d',d'')) \mid (v',d')\in s', (v'',d'')\in s'' \} .
\]
\end{Df}

\begin{Ex}\label{ex:cartesian}
Consider the following multinaming sets:
\begin{eqnarray*}
  s'  & = & \{ (\varepsilon, 0), (a, 1), (a, 2) \} , \\
  s'' & = & \{ (\varepsilon, 3), (\varepsilon, 4), (b, 5) \} .
\end{eqnarray*}
Then their cartesian product is
\begin{eqnarray*}
  s' \times s'' & = &  \{ (\varepsilon, (0, 3)), (\varepsilon, (0, 4)) \} \cup \\
    & \cup & \{ (b, (0, 5)) \} \cup \\
    & \cup & \{ (a, (1, 3)), (a, (1, 4)), (a, (2, 3)), (a, (2, 4)) \} \cup \\
    & \cup & \{ (ab, (1, 5)), (ab, (2, 5)) \} .
\end{eqnarray*}
\end{Ex}

\begin{St}\label{st:cartesian-distributivity}
Obviously,~$\times$ distributes over $\cap$ and $\cup$.
For any $s' \in \setmvcn{V}{D'}$ and $s''_1, s''_2 \in \setmvcn{V}{D''}$,
\[
  s'\times(s''_1\odot s''_2) = (s'\times s''_1) \odot (s'\times s''_2) .
\]
The same holds for the left operand.
\end{St}

\begin{St}\label{st:deref-cartesian}
For any $s' \in \setmvcn{V}{D'}$ and $s'' \in \setmvcn{V}{D''}$,
\[
  \deref(s' \times s'', w) =
      \bigcup_{v',v''\in V^\ast: v' v'' = w}
          \deref(s', v')
          \times
          \deref(s'', v'') .
\]
\end{St}

This is the main property of cartesian product. Since a multinaming set is
completely defined by values of all names (st.~\ref{st:mvcn-deref-equality}),
it is preserved by the mapping~$\varphi$ from st.~\ref{st:isomorph}. Also, this
property may be taken as a definition of cartesian product for multitries.

Consider a multinaming set~$s$ whose values are, in their turn, multinaming
sets.  Flattening operation formally defined below turns it into a ``plain''
multinaming set.  Supose a name~$v'$ in~$s$ has a value~$t$ (and, maybe, some
other values).  Take a name~$v''$ that has a value~$d$ in the multinaming set~$t$
(and maybe other values).  Then flattening should turn~$s$ into such a
multinaming set~$r$, where~$d$ is a value of the name~$v'v''$.

\begin{Df}\label{df:flatten}
\emph{Flattening} is a unary operation
$\flatten : \setmvcn{V}{\setmvcn{V}{D}} \to\setmvcn{V}{D}$,
such that, for any $(V,\setmvcn{V}{D})$-multinaming set~$s$,
\[
  \flatten(s) = \{ (v'v'', d) \mid (v', t) \in s, (v'', d) \in t \} .
\]
\end{Df}

\begin{Ex}\label{ex:flatten}
Let
\begin{eqnarray*}
  t_1 & = & \{ (\varepsilon, 0), (a, 1) \} ,\\
  t_2 & = & \{ (a, 2), (aa, 3) \} ,\\
  t_3 & = & \{ (\varepsilon, 4), (a, 5) \} ,\\
  s   & = & \{ (\varepsilon, t_1), (\varepsilon, t_2), (a, t_3) \} .
\end{eqnarray*}
Then
\[
  \flatten(s) = \{
      (\varepsilon, 0), (a, 1), (a, 2), (a, 4), (aa, 3), (aa, 5)
  \} .
\]
The empty name~$\varepsilon$ has two values in~$s$, namely~$t_1$ and~$t_2$.
In~$t_1$, in its turn, the only value of~$\varepsilon$ is~0, whereas in~$t_2$
it does not have any value. Therefore, 0~is the only value of $\varepsilon
\varepsilon = \varepsilon$ in~$\flatten(s)$.  The name~$a$ has one value in~$t_1$
and one value in~$t_2$, it is~1 and~2, respectively.  Then $a = \varepsilon a$
has values~1 and~2 in $\flatten(s)$.  The name~$a$ in~$s$ has a value~$t_3$
where the empty name's value is~4. Thus, 4~is also a value of $a \varepsilon =
a$ in~$\flatten(s)$.

Now look at the name~$aa$. Its value~3 is inherited from~$t_2$. Except this,
name~$a$ in~$s$ has a valaue~$t_3$ that, in its turn, contains a name~$a$ with
a value~5. Hence, the name~$aa$ has in $\flatten(s)$ the second value~5.
\end{Ex}

The following property can be used to define flattening for multitries~--
in terms of dereferencing operation.
\begin{St}\label{st:deref-flatten}
For any $(V,\setmvcn{V}{D})$-multinaming set~$s$,
\[
  \deref(\flatten(s), w) =
      \bigcup_{v',v''\in V^\ast: v' v'' = w}
        \deref(\deref(s, v'), v'') .
\]
\end{St}

\section{Elementwise mappings and applications}

The previous sections described operations on namings containing some
`ordinary' values. Now let us consider how do namings interact with
functions, including how can a naming populated with functions act itself
as a function.

\begin{Df}\label{df:mvcn-map}
Let $f : D \to D'$. Then $\fmap$ operation turns it into a \emph{mapping
function} $\fmap_{\setcharmvcn} f : \setmvcn{V}{D} \to \setmvcn{V}{D'}$, such
that
\[
  (\fmap_{\setcharmvcn} f)(s) = \{ (v, f(d)) \mid (v, d) \in s \}
\]
for any $s \in \setmvcn{V}{D}$.
\end{Df}

The definition of mapping for multitries is straightforward, it can be easily
obtained from isomorphism. There are following well-known properties:

\begin{St}\label{st:map-properties}
If $\circ$ is a composition of unary functions, i.e. $(g\circ f)(x) = g(f(x))$ for
all $f$, $g$, $x$ of matching types, and $\id_X : X \to X$ is an identity function,
$\id_X(x) = x$ for any $x\in X$, then
\begin{eqnarray*}
  & \fmap \id_D = \id_{\setmvcn{V}{D}} , \\
  & \fmap (g \circ f) = (\fmap g) \circ (\fmap f) .
\end{eqnarray*}
\end{St}

\begin{St}\label{st:map-distributivity}
Mapping function distributes over set-theoretical union (but not intersection, in general):
Let $f: D \to D'$, $s, t \in \setmvcn{V}{D}$. Then
\[
  (\fmap f) (s \cup t) = (\fmap f)(s) \cup (\fmap f)(t) .
\]
\end{St}

Thus, $\fmap$ operation can apply a single unary function to a multinaming set of
values. It is easy to define an operation $\fpam$ that does the opposite:
applies a multinaming set of unary functions to a single value. For this purpose,
let us define first an auxiliary function that turns a value~$x$ into a
high order function applying an argument function to~$x$:

\begin{Df}\label{df:ylppa}
\emph{Reverse application} is a function
\[
  \ylppa : X \to ((X \to Y) \to Y),
\]
such that, for every $x\in X$, $\xi = \ylppa x$ is a function satisfying the
equation
\[
  \xi(f) = f(x)
\]
for every $f: X\to Y$.
\end{Df}

Then the reverse mapping operation gets a concise definition.

\begin{Df}\label{df:mvcn-pam}
\emph{Reverse mapping} is an operation
\[
  \fpam_{\setcharmvcn} : \setmvcn{V}{D \to D'} \to (D \to \setmvcn{V}{D'}),
\]
such that
\[
  (\fpam s)(d) = (\fmap (\ylppa d))(s) .
\]
for any $s\in \setmvcn{V}{D \to D'}$, $d\in D$.
\end{Df}

It is easy to see from the definitions of $\fmap$ and $\ylppa$ that $\fpam$
really does what was intended:

\begin{St}\label{st:mvcn-pam}
If $s$ is a $(V, D\to D')$-multinaming set, $d\in D$,
\[
  (\fpam s)(d) = \{ (v, f(d)) \mid (v, f) \in s \} .
\]
\end{St}

Since reverse mapping is defined as a special case of mapping, it inherits
distributivity, see st.~\ref{st:map-distributivity}.

\begin{St}\label{st:pam-distributivity}
Let $d\in D$, $s, t \in \setmvcn{V}{D \to D'}$. Then
\[
  (\fpam (s \cup t))(d) = (\fpam s)(d) \cup (\fpam t)(d) .
\]
\end{St}

Having defined operations that apply a single function to a multinaming set of values
and a multinaming set of functions to a single value, let us define an
operation that applies a multinaming set of functions to a multinaming set of values. The
operation must preserve trie-like naming structures of both operands~-- the
considerations motivating the definition of cartesian product apply here
as well. To avoid rewriting essentially the same definition twice, let us
instead introduce an auxiliary operation and reuse a previously defined
operation.

\begin{Df}\label{df:eval}
Operation $\eval$ called \emph{(unary) evaluation} has type
$(X \to Y) \times X \to Y$ and is defined as follows.
\[
  \eval (f, x) = f(x) .
\]
\end{Df}

In other words, this operation takes a pair whose first element is a unary
function and the second is an argument, and applies the function to the
argument. Thus, the application operation over multinaming sets can be defined as
follows.

\begin{Df}\label{df:mvcn-apply-cartesian}
\emph{Cartesian application} is an operation of type
\[
\setmvcn{V}{D\to D'} \times \setmvcn{V}{D} \to \setmvcn{V}{D'} ,
\]
such that
\[
  \apply_{\setcharmvcn}^{\times} (s, t) = (\fmap \eval) (s \times t)
\]
for any~$s$ and~$t$ of matching types.
\end{Df}

Recalling the definitions of cartesian product and evaluation, one can
obtain the main property of cartesian application (that could be also taken
for a definition, in which case def.~\ref{df:mvcn-apply-cartesian} would turn
into a theorem).

\begin{St}\label{st:mvcn-apply-cartesian}
If $s\in \setmvcn{V}{D\to D'}$, $t\in \setmvcn{V}{D}$,
\[
  \apply_{\setcharmvcn}^{\times} (s, t) =
    \{ (vw, f(d)) \mid (v,f) \in s, (w,d) \in t \} .
\]
\end{St}

Therefore, for every function~$f$ contained in~$s$ under a compound name~$v$
and every object~$d$ contained in~$t$ under a name~$w$, the resulting
multitrie contains a value~$f(d)$ under a name~$vw$.

Let us introduce an infix alias for the cartesian application operation to make
formulation of its properties more elegant:
\[
  s \inapply t = \apply^{\times} (s, t) .
\]

\begin{St}\label{st:apply-distr}
Cartesian application distributes over set-theoretical union.
For any~$s, s_1, s_2, t, t_1, t_2$ of matching types,
\begin{eqnarray*}
  (s_1 \cup s_2) \inapply t = (s_1 \inapply t) \cup (s_2 \inapply t) , \\
  s \inapply (t_1 \cup t_2) = (s \inapply t_1) \cup (s \inapply t_2) .
\end{eqnarray*}
\end{St}

\section{Notes about implementation}

A container type implementing the multivalued naming with compound names has
been defined in Haskell programming language. Some trade-offs between the
mathematical purity and implementability could hardly be avoided. On the other
hand, the conceptual framework provided by Haskell gave a
direction towards some additional features that turn an abstract mathematical
notion into a potentially useful tool.

The mathematical construct described above formalizes manyvaluedness by means
of a \emph{set}: the value of $\deref$ function is a set of the name's values.
In Haskell programming, however, the most common representation of a many-valued
function is a function whose value is a \emph{list} of possible
values~\cite[p.~285]{bib:lipovaca}.  Using lists instead of sets gives some
benefits. For example, the many-valued function, as a value generator, does not
need to compare every newly produced value with all previous ones. Lists can be
generated by one function and consumed by another in a lazy manner. Elements'
type needs to be an instance of \lstinline{Ord} class for sets and does not for
lists.  Note that,  from the
mathematical perspective, lists are closer to multisets than to sets because of
possibly duplicate elements.  Keeping in mind that a list-based implementation
is not isomorphic to the set-based specification, let us justify it as an
acceptable approximation.

The previous sections presented two isomorphic though different formalisations:
multinaming sets and multitries. The former has higer abstraction level and suits well
for specification purposes whereas the latter involves a trie~-- a practical
data structure suitable for an efficient implementation. The only impractical
feature of multitries definition introduced for the sake of mathematical
simplicity is their infiniteness~-- every multitrie has a child node under
every atomic name; this helped to simplify formulae by omiting check whether a
name is present in the trie.  In the trie-based implementation, however, it would be
better to store finite maps and perform such checks for the sake of efficiency.
In particular, if the underlying trie does not contain any child node for a
particular name, the object's behaviour observed via functions is the same as if
it associated this name with an empty multitrie.

All this leads to the following basic definition (indeed, the module hides it
behind smart constructors).

\begin{lstlisting}
data MultiTrie v d = MultiTrie {
        values :: [d],
        children :: Data.Map.Map v (MultiTrie v d) }
\end{lstlisting}

The most important functions defined in the module are listed below.

\begin{lstlisting}
empty ::
  MultiTrie v d
leaf ::
    [d] -> MultiTrie v d
addValue ::
    d -> MultiTrie v d -> MultiTrie v d
values ::
    MultiTrie v d -> [d]
children ::
    MultiTrie v d -> MultiTrieMap v d
null ::
    MultiTrie v d -> Bool
size ::
    MultiTrie v d -> Int
isEqualStrict :: (Ord v, Eq d) =>
    MultiTrie v d -> MultiTrie v d -> Bool
subnode :: Ord v =>
    [v] -> MultiTrie v d -> MultiTrie v d
map :: Ord v =>
    (d -> w) -> MultiTrie v d -> MultiTrie v w
cartesian :: Ord v =>
    MultiTrie v d -> MultiTrie v w -> MultiTrie v (d, w)
union :: Ord v =>
    MultiTrie v d -> MultiTrie v d -> MultiTrie v d
flatten :: Ord v =>
    MultiTrie v (MultiTrie v d) -> MultiTrie v d
apply :: Ord v =>
    MultiTrie v (d -> w) -> MultiTrie v d -> MultiTrie v w
toMap :: Ord v =>
    MultiTrie v d -> Map [v] [d]
toList :: Ord v =>
    MultiTrie v d -> [([v], d)]
fromList :: Ord v =>
    [([v], d)] -> MultiTrie v d
\end{lstlisting}

Here is a short explanation of their semantics.
\begin{description}
\item [empty]
  A constant for the empty multitrie~$\bot$, see def.~\ref{df:mvcn-extreme}
  and~\ref{df:mt-extreme}.
\item [leaf] Given a list of values, constructs a multitrie that has this list
  in its root node and no other valies (i.e. all other names yield to an empty
  list of values).
\item [addValue]
  Given a value and a multitrie, prepend the value to the list stored in the
  root node.
\item [values]
  Get a list of values from the root node of a multitrie.
\item [children]
  From the root node of a multitrie, get a mapping of atomic names to the
  child nodes.
\item [null]
  Check whether the argument multitrie is empty.
\item [size]
  Get the total number of values in the multitrie.
\item [isEqualStrict]
  Compare two multitries: they are considered equal if equal are lists of
  values under all compound names. I.e. if the multitries have equal lists
  of values in their root nodes and, for every atomic name, the corresponding
  child multitries are equal in this sense, in their turn. There is another
  function for weak comparison~-- it ignores order of elements in the lists
  treating them as multisets.
\item [subnode]
  Get a node pointed to by a compound name. If the name is not present in the
  underlying data structure, the function anyway yields a correct value, the
  empty multitrie. This function implements selection operation from
  def.~\ref{df:mvcn-select} and~\ref{df:mt-select}.
\item [map]
  Apply a function to each value in a multitrie and combine results into
  a new multitrie preserving the names (and, therefore, the trie structure),
  see def.~\ref{df:mvcn-map}.
  This is a specific implementation of the \lstinline{fmap} method from the
  \lstinline{Functor} class.
\item [cartesian]
  Construct a cartesian product of two multitries in the sense of
  def.~\ref{df:mvcn-cartesian} and st.~\ref{st:deref-cartesian}.
\item [union]
  Construct a union of two multitries, see st.~\ref{st:mvcn-setop} and
  def.~\ref{df:mt-setop}. There is another function for intersection.
\item [flatten]
  Given a multitrie whose values are, in their turn, multitries, construct
  a flattened multitrie, see def.~\ref{df:flatten} and
  st.~\ref{st:deref-flatten}. This is a specific implementation of the
  \lstinline{join} function defined for all types of the \lstinline{Monad}
  class.
\item [apply]
  Cartesian
  application of a multitrie of functions to a multitrie of arguments, see
  def.~\ref{df:mvcn-apply-cartesian}.
\item [toMap]
  Convert a multitrie to a \lstinline{Data.Map} that maps compound names to
  lists of values. Corresponds to an inverse of the isomorphism~$\varphi$
  from st.~\ref{st:isomorph}.
\item [toList]
  Convert a multitrie to a list of name--value pairs.
\item [fromList]
  Convert a list of name--value pairs to a multitrie.
\end{description}

Finally, \lstinline{map} function that implements the $\fmap$ operation
(def.~\ref{df:mvcn-map} and st.~\ref{st:map-properties})
makes \lstinline{MultiTrie} type an instance of the \lstinline{Functor} class;
\lstinline{apply} function as an implementation of $\apply^{\times}$
operation makes it an instance of the \lstinline{Applicative} class;
\emph{bind} operation (not shown in this article; easy to define using mapping
and flattening operations) makes the type an instance of the
\lstinline{Monad} class.

\section{Conclusion}

The notion of naming and its most general formalisation, taken as a starting
point, has been transformed into a more concrete notion enriched with specifics of
\emph{structuredness} and \emph{many-valuedness}. Being structured
means that a name can not only refer to an atomic value but also
to a structured value, i.e. to a subobject that, in its turn, has named parts.
Being many-valued means that, instead of a unique atomic value, each leaf node
of a structured object can have zero, one or multiple, even infinitely many
values.

It is not surprising that structuredness and manyvaluedness appear together.
Although univalued structured objects seem more familiar (and, in fact, found
in practical programming everywhere), it is multivaluedness that makes
mathematical properties of structured namings elegant and harmonic: otherwise
set-theoretical union and intersection, cartesian product, flattening and
application would not make sense. Due to multivaluedness, these operations are
not just meaningful but also obey `good' properties, e.g.  associativity and/or
distributivity over other operations.

From the two formalisations of multivalued structured objects, the first
approach is \emph{extensional}~-- it concentrates on the properties of the
naming relation taken as a whole. The second approach is \emph{intensional}, it
reveals a decomposition of the whole naming into simpler sub-naming and thus
gives a hint about how it could be implemented programmatically.  The `good'
properties of operations fit the multitrie data type into rich typeclasses that
makes multitries a first-class member of Haskell container types, together with
lists, maps and trees.

As far as a list is a conventional model for a non-deterministic computation
that generates cases one by one in a lazy manner, a multitrie could be used to
represent a non-deterministic structure unfolding when the consumer needs more
detail.  On the other hand, in the same way as a list could be \emph{simply a
list}, a multitrie could represent a static entity for which a list is a normal
contents (i.e. not a set of possibilities). A typical example could be a
directory tree where an atomic name corresponds to a directory, a compound name
means a path, and values correspond to individual files.  A structure of an XML
document is another example of such objects.

\begin{thebibliography}{00}

\bibitem{bib:frege}
  Gottlob Frege,
  \"Uber Sinn und Bedeutung.
  In: Zeitschrift f\"ur Philosophie und philosophische Kritik,
  NF~100. 1892, S.~25--50.

\bibitem{bib:wittgenstein}
  Ludwig Wittgenstein,
  Tractatus logico-philosophicus, Logisch-phi\-lo\-so\-phi\-sche Abhandlung.
  Suhrkamp,
  Frankfurt am Main,
  2003.

\bibitem{bib:quine}
  Quine, Willard Van Orman,
  Word and Object [1960].
  New edition, with a foreword by Patricia Churchland,
  Cambridge,
  Mass.: MIT Press,
  2015.

\bibitem{bib:ptop}
  Eric C.R. Hehner,
  A Practical Theory of Programming,
  2016-4-14 edition,
  http://www.cs.utoronto.ca/~hehner/aPToP/aPToP.pdf.

\bibitem{bib:utp}
  C.\,A.\,R.\,Hoare, He Jifeng,
  Unifying Theories of Programming,
  Prentice-Hall,
  1998.

\bibitem{bib:leroy}
  Xavier Leroy, Sandrine Blazy.
  Formal verification of a C-like memory model and its uses for verifying program transformations.
  Journal of Automated Reasoning.
  41(1), pp.1-31, July 2008.

\bibitem{bib:redko}
  Basarab~I., Nikitchenko~N., Red’ko~V.
  Compositional Databases.
  Kiev: Lybed’, 1992.~-- 191~p. (In Russian).

\bibitem{bib:ollongren}
  Alexander Ollongren,
  Definition of programming languages by interpreting automata.
  London: Academic Press,
  1974.

\bibitem{bib:dictionary}
  Paul~E.~Black,
  ``Dictionary'', in Dictionary of Algorithms and Data Structures [online],
  Vreda Pieterse and Paul E. Black, eds.
  Available from: http://www.nist.gov/dads/HTML/dictionary.html

\bibitem{bib:mehlhorn-assoc}
  Kurt Mehlhorn, Peter Sanders
  ``4: Hash Tables and Associative Arrays'',
  Algorithms and Data Structures: The Basic Toolbox
  Springer, pp.~81--98.

\bibitem{bib:knuth-trie}
  Donald Knuth,
  ``6.3: Digital Searching''.
  The Art of Computer Programming,
  Volume 3: Sorting and Searching (2nd ed.).
  Addison-Wesley. p.~492.

\bibitem{bib:lipovaca}
  Miran Lipova\v{c}a.
  Learn You Haskell for Great Good!
  360 pages,
  No Starch Press,
  2011.

\end{thebibliography}

\end{document}


\subsection{Hebbian Learning}

What underlying principle or set of principles govern learning and the formation of memories? Inspired by recent discoveries in neuroscience and synaptic research, Donald Hebb proposed an iconic postulate in 1949, \textit{``When an axon of cell A is near enough to excite a cell B and repeatedly or persistently takes part in firing it, some growth process or metabolic change takes place in one or both cells such that A's efficiency, as one of the cells firing B, is increased.''} which is often summarized as \textit{``neurons which fire together, wire together''} \cite{hebbs_rule}. Ever since its formulation, Hebb's rule has been a cornerstone in understanding the inner workings of learning, memory formation and associative memory. Later research has extended Hebb's rule to include a notion of decay, where synaptic connections are weakened (and subsequently associations broken). Without this addition, all synapses would eventually converge to their maximum efficiency through synaptic potentiation, thus making them in-differentiable and thereby removing the selective property which is key for associative memory recall \cite{anti_hebbian}.


\section{Tides in HECRAS and \anuga{}}
This test compares idealised tidal channel flow in HECRAS and ANUGA. The tidal
amplitude (0.4m) is a significant fraction of the channel depth ($\simeq 1$m),
so nonlinear tidal deformation is significant.

A 20m wide, 1000m long straight channel with rectangular cross-section flows through a
floodplain (10m wide on either side of the channel). Upstream of 220m the bed
elevation is constant (1m below the floodplain), downstream of 100m it is 3m below
the floodplain, and it varies linearly in between. The floodplain has a constant
elevation (1m). Manning's n is 0.03. The upstream boundary is reflective, while
at the downstream boundary a stage timeseries $y(t)$ is imposed (where $t$ is
time in seconds):
$$y=0.6+0.4*\sin(2\pi t/(1800))$$

\subsection{Results}
Figure~\ref{result} show stage timeseries at various stations downstream in each model.
For visual clarity the gauges are offset vertically.  The ANUGA and HECRAS
results should be visually indistinguishable.  There is a clear deformation of
the tide as it travels upstream, with the incoming tide having a shorter
duration than the outgoing tide at upstream stations, which is typical for
tides in shallow channels when overbank effects are not dominant. In this
example there is minor overbank inundation in parts of both models, but it is
just a few cm deep.

\begin{figure}
\begin{center}
\includegraphics[width=1.0\textwidth]{CENTRAL_CHANNEL.png}
\end{center}
\caption{Tidal levels in HECRAS and \anuga{}}
\label{result}
\end{figure}

Note that this ANUGA model uses a coarse mesh with discontinuous elevation to
resolve the banks, so this example should not run with non-discontinuous
elevation flow algorithms.


\documentclass[12]{article}
\usepackage[margin=1in]{geometry}
\usepackage{graphicx, float,amsmath, physics, amssymb, mathtools, siunitx}
\usepackage{physics,hyperref,subcaption}
\hypersetup{
    colorlinks=true,
    linkcolor=black,
    filecolor=black,
    urlcolor=blue,
    citecolor=black,
}
\renewcommand{\baselinestretch}{1.2}

\graphicspath{{./Plots/}}

\begin{document}
\begin{flushright}
Tim Skaras

Advisor: Professor Mustafa Amin
\end{flushright}

\begin{center}
{\LARGE Faraday Wave Experiment}
\end{center}

\section{Introduction}

Bose-Einstein Condensation (BEC) is a state of matter in boson gases that results when atoms, cooled very close to absolute zero, abruptly accumulate in their ground state \cite{schroeder1999introduction}. This state of matter has been experimentally realized using various atomic vapors \cite{pethick2008bose}. In particular, a laboratory here at Rice led by Professor Randall Hulet has studied Bose-Einstein Condensation in lithium. Professor Hulet's lab is able to tune the interaction strength between atoms by exploiting a shallow zero-crossing of a Feshbach resonance, and, due to nonlinearity, this can result in rich dynamics such as the creation of matter-wave soliton trains \cite{nguyen2017formation}. Because it is difficult to study nonlinear systems analytically, computational tools have been important for understanding the behavior of these systems.

\subsection{Project Overview}

More recently, Professor Hulet's lab has performed experiments on the emergence of Faraday Waves in a Bose-Einstein Condensate by periodically modulating the scattering length for these atoms. In these experiments, they have modulated the scattering length periodically for a fixed period of time. Then after holding the scattering length constant, they observe that perturbations of particular wavenumbers will grow rapidly, resulting in the emergence of faraday waves.

Using a mean field theory, it can be shown that the dynamics of a Bose-Einstein condensate are governed by the time-dependent Gross-Pitaevskii Equation \cite{pethick2008bose}
\begin{equation}
i \hbar \frac{\partial \psi(\mathbf{r}, t)}{\partial t}=-\frac{\hbar^{2}}{2 m} \nabla^{2} \psi(\mathbf{r}, t)+V(\mathbf{r}) \psi(\mathbf{r}, t)+ g|\psi(\mathbf{r}, t)|^{2} \psi(\mathbf{r}, t), \quad \quad g \equiv 4 \pi \hbar^{2} a_{s} / m
\label{DimGPE3D}
\end{equation}
\nolinebreak
where $\psi$ is a field describing the number density of atoms in real space, hence the total particle number $N$ satisfies
\begin{equation}
\int_{\mathbb{R}^{3}} d \mathbf{r}|\psi(\mathbf{r})|^{2} = N
\end{equation}
The parameter $g$ corresponds to the interaction strength between atoms ($g>0$ corresponding to repulsive interactions and $g < 0$ corresponding to attractive interactions), and is defined in terms of the scattering length $a_s$ and the atomic mass $m$.

In this project, I numerically solve this nonlinear, partial differential equation assuming a cigar-shaped trapping potential in three spatial dimensions to computationally confirm recent experimental results from Professor Hulet's lab by showing that the BEC's perturbations in Fourier space grow in the expected way.

\section{Methods}

\subsection{Dimensionless GPE}
\label{sec:DimGPE}

Though the form given for the Gross-Pitaevskii equation in (\ref{DimGPE3D}) is physically correct, the units in which the equation has been expressed are not appropriate for the time and length scale of our problem. To remedy this, we will first scale the field
\begin{equation}
\frac{\psi}{\sqrt{N}} \rightarrow \psi
\end{equation}
which now gives the PDE
\begin{equation}
i \hbar \frac{\partial \psi(\mathbf{r}, t)}{\partial t}=-\frac{\hbar^{2}}{2 m} \nabla^{2} \psi(\mathbf{r}, t)+V(\mathbf{r}) \psi(\mathbf{r}, t)+ gN|\psi(\mathbf{r}, t)|^{2} \psi(\mathbf{r}, t), \quad \quad g \equiv 4 \pi \hbar^{2} a_{s} / m
\label{GPEUnity}
\end{equation}
with a normalization condition that is set to unity
\begin{equation}
\int_{\mathbb{R}^{3}} d \mathbf{r}|\psi(\mathbf{r})|^{2} = 1
\end{equation}
To make the GPE dimensionless, we stipulate that the potential is harmonic
\begin{equation}
V(\textbf{r}) = \frac{m}{2}\left(\omega_{x}^{2} x^{2}+\omega_{y}^{2} y^{2}+\omega_{z}^{2} z^{2}\right)
\end{equation}
and then choose a convenient characteristic length $a_0$ and scale our coordinates as follows
\begin{equation}
\omega_{x} t \rightarrow t, \quad \mathbf{r} / a_{0} \rightarrow \mathbf{r}, \quad a_{0}^{3 / 2} \psi \rightarrow \psi \quad \text { where } \quad a_{0} \equiv \sqrt{\frac{\hbar }{ m \omega_{x}}}
\label{scaling}
\end{equation}
Plugging (\ref{scaling}) into (\ref{GPEUnity}) and simplifying we find the GPE in dimensionless form can be written as
\begin{equation}
i \frac{\partial \psi(\mathbf{r}, t)}{\partial t}= -\frac{1}{2 } \nabla^{2} \psi(\mathbf{r}, t)+V(\mathbf{r}) \psi(\mathbf{r}, t)+ gN|\psi(\mathbf{r}, t)|^{2} \psi(\mathbf{r}, t), \quad \quad g \equiv 4 \pi a_{s}
\label{GPE3D}
\end{equation}
where the potential has been scaled so that one of the trapping frequencies is unity
\begin{equation*}
V(\textbf{r}) = \frac{1}{2}\left( x^{2}+\gamma_{y}^{2} y^{2}+\gamma_{z}^{2} z^{2}\right), \quad \gamma_y \equiv \frac{\omega_y}{\omega_x}, \quad \gamma_z \equiv \frac{\omega_z}{\omega_x}
\end{equation*}
For the Faraday Wave experiment that we will be considering, the trapping potential is cylindrically symmetric with $\omega_x = \omega_y$. We thus define $\omega_\rho$ as the trapping frequency along the x-axis and y-axis (henceforth called the radial direction), thus $\omega_\rho = \omega_x = \omega_y$. So the trapping potential is really
\begin{equation}
V(\textbf{r}) = \frac{1}{2}\left( \rho^{2}+\gamma_{z}^{2} z^{2}\right), \quad \rho^2 = x^2 + y^2, \quad \gamma_z \equiv \frac{\omega_z}{\omega_\rho}.
\end{equation}

\subsection{Numerical Methods}
To solve this nonlinear PDE, I use a time-splitting spectral (TSSP) method while assuming periodic boundary conditions. The general idea behind applying this method is that some operators on the RHS of (\ref{GPE3D}) are easy to apply in momentum space (e.g., the second order derivative) and some are easy to apply in position space (e.g., the potential term). To exploit this fact, this method involves shifting the wave function solution between its real space and momentum space representation via fourier transformation and applying each operator component in the space it is most easily applied.

Before I can start solving the nonlinear PDE, however, I must find the correct initial condition. These experiments in Hulet's lab are performed on BEC that is very close to its ground state. The ground state for the GPE is not known analytically in this trapping potential, so I will use finite difference methods to implement the imaginary-time propagation method \cite{chiofalo2000ground, muruganandam2009fortran}, which will allow me to numerically calculate the ground state.

The TSSP method is described in detail in \cite{bao2003numerical} for a one dimensional version of the GPE, and the method can be straightforwardly generalized to three spatial dimensions without affecting the method's validity. The advantages of this method are multifold: the TSSP method is unconditionally stable, time reversible, time-transverse invariant, conserves particle number, and is second order accurate in space and time \cite{bao2003numerical}. One noteworthy drawback is that this method is not symplectic, i.e., it does not conserve energy.

Time reversible means that if the solution $\psi_{n+1}$ at $t_{n+1}$ is obtained by applying the TSSP method to the solution $\psi_n$ at $t_n$, then the past state can be re-obtained from $\psi_{n+1}$ by using TSSP with time step $-\Delta t = -(t_{n+1} - t_n)$. Time-transverse invariance or gauge invariance refers to the property of the GPE that if $V \rightarrow V + \alpha$ where $\alpha \in \mathbb{R}$, then the solution $\psi \rightarrow \psi e^{i\alpha t}$, which implies that number density of atoms $|\psi|^2$ is unchanged under this transformation. This method respects this property by producing the corresponding changes in $\psi$ when $V$ is transformed in this way \cite{antoine2013computational}.

\subsection{Implementation and Validation}

I have implemented this spectral method in Python\footnote{My \href{https://github.com/TimSkaras/GPE-SpectralMethod}{github} repository}. I used the CuPy package\footnote{\href{https://cupy.chainer.org}{CuPy website}} to implement this method because this package provides a NumPy-like environment that performs computations on a GPU. This allowed my code to acheive considerable speedup (almost an order of magnitude for certain problems) over a serial implementation. I will now consider some of the test cases that I have used to ensure I have correctly implemented the time-splitting spectral method and the imaginary-time propagation method.

\subsubsection{Homogeneous Solution}

It can be trivially verified that
\begin{equation}
\psi(t) = A e^{-i g|A|^2 t}, \quad A \in \mathbb{C}
\end{equation}
is a solution to (\ref{GPE3D}). It should be noted that the method will accurately solve a constant intial condition ($\psi(\textbf{x},0) = A$) only when the time step is small compared to the period of oscillation which is determined by angular frequency $\omega = g |A|^2$. In the file \href{https://github.com/TimSkaras/GPE-SpectralMethod/blob/master/Tests/homogeneous_test.py}{homogeneous\_test.py}, I solve a homogeneous initial condition with $A = \frac{1}{2}$ and $g = 10$ thus giving $T = \frac{2\pi}{\omega} = 2.51$. Our time step is $\Delta t \approx 0.0179$. For more details on parameters, see the file linked in this document.

After solving the problem with these initial conditions until $t = 2.5$. When the code is run using a GPU, the maximum error at any one gridpoint is on the order of $10^{-14}$ and the normalization loss ratio (the change in the normalization divided by the norm at $t=0$) is also on the order of $10^{-14}$. Running the code in serial gives a max error and norm loss ratio of the same order of magnitude.

\subsubsection{Plane Wave}

It is also possible to show that the Gross-Pitaevskii Equation admits a plane wave solution with the form
\begin{equation}
\psi(\textbf{r},t) = Ae^{i(\textbf{k} \dotproduct \textbf{r} - \omega t)}, \quad A \in \mathbb{C}
\end{equation}
provided that $\omega$ and $\vec{k}$ satisfy the dispersion relation
\begin{equation}
\omega(\textbf{k}) = \frac{1}{2}|\textbf{k}|^2 + g \abs{A}^2
\end{equation}
In the file \href{https://github.com/TimSkaras/GPE-SpectralMethod/blob/master/Tests/homogeneous_test.py}{planewave\_test.py}, I use this analytic solution to again test the accuracy of my solver. I use the same value for $A$ and $g$ but with $\vec{k} = (\frac{2\pi}{L_x}, 2\frac{2\pi}{L_y},3\frac{2\pi}{L_z})$ the period is now $T = \frac{2\pi}{\omega} = 1.97$. Solving this plane wave initial condition until $t = 2.5$ gives a max error on the order of $10^{-13}$ and a norm loss ratio on the order of $10^{-14}$. Changing from GPU to serial has no significant effect on the error and loss of normalization.

Because this initial condition is spatially varying, it gives us a little more information on how well the solver is working. The spatial derivative in (\ref{GPE3D}) is handled entirely separately from the potential and nonlinear terms. The TSSP method splits (\ref{GPE3D}) into two equations that each be solved exactly and then combines the splitting steps together using Strang splitting to give a second-order accurate solution. The equation with the Laplacian is solved using fourier transforms, and in the code this is handled with FFT. This test and the previous one are useful for testing these different components and isolating which part of the solver has a problem if any.

\subsubsection{Thomas-Fermi Ground State}

The previous two test cases are meant to ensure that the code is correctly solving equation (\ref{GPE3D}), but it is also necessary to test that I have correctly implemented the imaginary-time propagation method. Though we have no exact ground state to which we can compare our numerical result, it is possible to write down an approximate ground state for certain limiting cases of the GPE \cite{bao2003numerical, bao2003ground}.

As explained in the references just cited, a stationary solution $\phi(\textbf{x})$ of the GPE can be written as
\begin{equation}
\psi(\textbf{r},t)  = e^{-i\mu t}\phi(\textbf{r})
\label{stationary}
\end{equation}
where $\mu$ is the chemical potential. Plugging (\ref{stationary}) into (\ref{GPE3D}) gives us the equation $\phi(\textbf{x})$ must satisfy to be a stationary solution
\begin{equation}
\mu \phi(\mathbf{r})=-\frac{1}{2} \nabla^{2} \phi(\mathbf{r})+V(\mathbf{r}) \phi(\mathbf{r})+ g|\phi(\mathbf{r})|^{2} \phi(\mathbf{r})
\label{StationaryGPE}
\end{equation}
with the normalization condition
\begin{equation}
\int_{\mathbb{R}^{3}}|\phi(\mathbf{r})|^{2} d \mathbf{r}=1.
\label{NormCondition}
\end{equation}
The ground state is the stationary solution satsifying (\ref{StationaryGPE}) and (\ref{NormCondition}) while also minimizing the energy functional
\begin{equation}
E[\phi] := \int_{\mathbb{R}^{3}} \left[ \frac1{2} |\nabla \phi|^{2}  + V(\textbf{r})|\phi|^{2} + \frac{g}{2}|\phi|^{4} \right] d \mathbf{r}
\label{Energy}
\end{equation}
This ground state solution is unique if we also require that $\phi$ be real. In the strongly-interacting regime where $g N \gg a_{0}$ and $g > 0$, the ground state can be approximated as
\begin{equation}
\mu_{g}=\frac{1}{2}\left(\frac{15 gN \gamma_y\gamma_{z}}{4 \pi}\right)^{2 / 5}, \phi_{g}(\mathbf{x})=\left\{\begin{array}{ll}{\sqrt{\frac{\mu_{g}-V(\mathbf{x}) }{gN}},} & {V(\mathbf{x})<\mu_{g}} \\ {0,} & {\text { otherwise }}\end{array}\right.
\label{StrongGS}
\end{equation}
This approximate ground state is known as the Thomas-Fermi ground state. It can be derived from the Thomas-Fermi approximtion where the kinetic term in (\ref{GPE3D}) is dropped from the equation.

In the file \href{https://github.com/TimSkaras/GPE-SpectralMethod/blob/master/Tests/TFgs_test.py}{TFgs\_test.py}, I have used my implementation of the imaginary-time propagation method to find the ground state in a trap with $\omega_x = \omega_y = \omega_z = 1$ and $gN = 2000$. On a grid of points $64 \times 64 \times 64$ points, I have compared my numerically calculated ground state with the analytic approximation given in (\ref{StrongGS}), and I have provided a plot of each in figure \ref{fig:TFgs}.

\begin{figure}[h]
    \begin{subfigure}[t]{0.5\textwidth}
        \includegraphics[scale=0.36]{Plots/TFgsNumerical}
        \caption{}
    \end{subfigure}\hfill
    \begin{subfigure}[t]{0.45\textwidth}
        \includegraphics[scale=0.35]{Plots/TFgsAnalytic}
        \caption{}
    \end{subfigure}
    \caption{These are plots of $|\psi|^2$ for the numerically calculated solution (a) and the analytic approximation (b). The x-dimension has been integrated out to make plotting possible. The two are very similar execpt at the boundary where the analytic aproximation becomes zero.}
    \label{fig:TFgs}
\end{figure}

To compare how close the numerical solution is the analytic approximation, I used equation (\ref{Energy}) to calculate the ground state energy for each. The numerical solution has an energy of 8.28 and the analytic approximation has an energy of 8.37. The max error between the wavefunction for each was 0.010.

These figures are not as promising as the tests for the GPE solver were, but there may be good reason for this. The energy of the Thomas-Fermi ground state is actually infinite, namely
\begin{equation}
E[\phi_g] = +\infty
\end{equation}
due to the low regularity of $\phi_g$ at the free boundary where $V(x) = \mu_g$. To remedy this issue, an interface layer has to be constructed at this boundary to improve the accuracy of the approximation \cite{bao2003ground}.

\section{Results}

\subsection{Experimental Setup}

In the experiment, the lithium BEC is confined in a cylindrically symmetric harmonic trap. Let $\omega_\rho$ be the trapping frequency in the radial direction and $\omega_z$ the trapping frequency in the axial direction (i.e., along the z-axis). The experimental parameters are
\begin{equation}
\left(\frac{\omega_{\rho}}{2 \pi}, \frac{\omega_{z}}{2 \pi}\right)=(476 \,\mathrm{Hz},7 \,\mathrm{Hz}) , \quad a_{0}=1.74 \mu \mathrm{m}, \quad N \approx 7 \times 10^{5}, \quad a_s \approx 4r_{\text{Bohr}}, \quad t_{mod} = 5~\textrm{ms}
\end{equation}
Because $\omega_\rho \gg \omega_z$, the BEC in its ground state is highly elongated along the axial direction. In the experiment, the scattering length is modulated periodically such that
\begin{equation}
  g(t) =
  \begin{cases}
		g_0(1 + \epsilon \sin(\omega t)) & \text{if $0\leq t \leq t_{mod}$} \\
		g_0 & \text{else}
  \end{cases}
\end{equation}
where $g_0$ is the value for $g = 4\pi a_s$ before the experiment begins, $t_{mod}$ is the length of time over which the scattering length is modulated, and $\epsilon = 0.2$. The modulation frequency of the scattering length $\omega$ varies depending on the epxeriment being performed.

When the scattering length is modulated in this way, the BEC expands and contracts within the trapping potential, and continues to do so after the scattering length is kept fixed. This expansion and contraction sets up a persistent modulation of the width which in turn drives the growth of periodic spatial perturbations along the axial direction of the BEC. The rate of growth for these spatial perturbations is dependent on the perturbation's wavenumber. There is one mode in particular that will grow faster than all other modes which we call $k_{max}$, and the timescale on which this dominant growing mode will emerge is dependent on the scattering length modulation frequency $\omega$ \cite{mustafa}.

In order to reconstruct the experiment in numerical simulation, these parameters must be converted to dimensionless form as described in section \ref{sec:DimGPE}. Doing so we obtain
\begin{equation}
\left(\omega_\rho, \omega_z\right)=(1 , \textstyle\frac{7}{476}), \quad g \approx 0.001528, \quad gN \approx 1070, \quad t_{mod} = 14.952 \approx 5\pi.
\end{equation}

We have computationally simulated a condensate with these conditions where $\omega = 2\omega_\rho$, and an animation of its time evolution can be downloaded \href{https://github.com/TimSkaras/GPE-SpectralMethod/blob/master/Animations/CodnensateAnimation.mp4}{here}. With this simulation, we have can test how well energy is conserved by the numercal method. Unfortunately, the time-splitting spectral method is not guaranteed to conserve energy, so checking that the energy is conserved can be a indicator that the time-step is not too large. Figure \ref{fig:energy} plots how the energy of the condensate changes with time. As we expect, the energy is increasing before $t_{mod}$ as a result of the changing scattering length. After $t_{mod}$ the scattering length is held constant and the energy remains relativly constant as well.

\begin{figure}
\centering
\includegraphics[width=\textwidth]{energyPlot}
\caption{Energy of condensate over time}
\label{fig:energy}
\end{figure}

\subsection{Computational Results}
\label{subsec:CompResults}

Now, we analyze computational results that can be directly compared with experiment. Due to limitations on instrument precision in the laboratory, certain properties of the BEC cannot be measured. The results that can be compared with experimental measurement include: (1) how the time it takes for the the dominant mode to reach its maximum amplitude varies with the scattering length modulation frequency $\omega$ and (2) how the wavenumber of the dominant mode varies with $\omega$.

First, we find the ground state for the trapping potential and experimental parameters described above and then evolve the system forward in time. After a long enough time has elapsed, the small spatial perturbations along the axial direction will grow until a dominant mode emerges. We will use a fourier transformation to analyze the growth and amplitude of each mode for the spatial perturbations. One of the modes grows in amplitude until reaching a maximum. Afterwards, this dominant mode will have a decaying amplitude until it grows in size again. We denote as $t_{max}$ the time it takes for this dominant mode to reach its maximum. In figure \ref{fig:tmaxNat}, I have plotted how $t_{max}$ varies with the modulation frequency. We see that $t_{max}$ increases as $\omega$ moves away from the resonant frequency, which is $2\omega_\rho$ or twice the radial trapping frequency \cite{mustafa}. See figure \ref{fig:tmaxExp} to view this plot with the units used in experiment rather than in dimensionless form.

\begin{figure}[H]
\centering
\includegraphics[scale=0.9]{tmaxNatUnits}
\caption{This plot compares $t_{max}$ with the modulation frequency $\omega$. The maximum emerges the soonest when the modulation frequency is at its resonant frequency, which is twice the radial trapping frequency.}
\label{fig:tmaxNat}
\end{figure}

\begin{figure}[b]
\centering
\includegraphics[scale=0.9]{tmaxExpUnits}
\caption{This plot compares $t_{max}$ with the modulation frequency $\omega$. The maximum emerges the soonest when the modulation frequency is at its resonant frequency, which is twice the radial trapping frequency.}
\label{fig:tmaxExp}
\end{figure}

Next, we look at how the wavenumber of the dominant mode varies with $\omega$. Theoretical analysis predicts that the wavenumber of the dominant mode should always be $k_{dom} = 1.1$ or $k_{dom} = 0.632$ \si{\micro\meter^{-1}} should be independent of $\omega$ \cite{mustafa}. Our computational results are close to this prediction, with the wavenumber of the dominant mode remaining close to this analytic prediction. In figure \ref{fig:kmaxNat}, we have plotted how the wavenumber of the dominant mode varies with the modulation frequency.

\begin{figure}[H]
\centering
\includegraphics[scale=0.9]{kmaxNatUnits}
\caption{This plot compares $k_{max}$ with the modulation frequency $\omega$.}
\label{fig:kmaxNat}
\end{figure}

\begin{figure}[b]
\centering
\includegraphics[scale=0.9]{kmaxExpUnits}
\caption{This plot compares $k_{max}$ with the modulation frequency $\omega$.}
\label{fig:kmaxExp}
\end{figure}

%There are two ways that we can define the ``dominant mode": the mode that reaches the maximum amplitude first and the mode that has the largest amplitude as the spatial perturbations leave the domain of validity. The analytic predictions for predicting what mode has the fastest growth rate \cite{mustafa} assume that the amplitude of each mode is small. This simplifies the analysis because it also means that the each of the spatial perturbation modes will grow independently of each other and not be coupled. When the amplitude of one or more mores has grown sufficiently large, this assumption no longer holds and the analytic predictions are cannot reliably predict behavior. The ``domain of validity" is the time frame in which this assumption of uncoupled modes still holds

\subsection{Island Formation}

One notable phenomenon in the animations that we have produced from these simulations is that modulating the scattering length produces an ``island" or isolated accumulation of atoms to the left and right of the central cloud. For simulations with the parameters given in subsection \ref{subsec:CompResults}, the islands tend to form around $t = 285$ as illustrated in figure \ref{fig:islands1}. The full 1D animation of these dynamics can be viewed \href{https://github.com/TimSkaras/GPE-SpectralMethod/blob/master/Animations/CodnensateAnimation.mp4}{here}. Additionally, we have created a 2D animation of the same simulation, though now displayed as a heat map, which can be viewed \href{https://github.com/TimSkaras/GPE-SpectralMethod/blob/master/Animations/heatMapIslands.mp4}{here}. I speculate the the island formation is the result of the periodic expansion and contraction of the atomic cloud and the growth of spatial patterns on the BEC surface that results from this expansion and contraction, rather than being directly caused by the periodic modulation of the scattering length \textit{per se}.

At the very least, it can be shown that this expansion and contraction can also be produced by modulating the potential for a fixed period of time, which also ultimately produces similar dynamics by causing the atomic cloud to expand and contract. In this 1D \href{}{animation} and in this 2D heat map \href{}{animation}

\begin{figure}[H]
\centering
\includegraphics[scale=0.6]{IslandFormation1D}
\caption{This plot shows the islands around the time when they first form after the scattering length has been modulated at the resonant frequency. This plot shows the number density of atoms along the z-axis when $t = 285$.}
\label{fig:islands1}
\end{figure}

\bibliographystyle{abbrv}
\bibliography{FaradayExperimentBib}

\end{document}


\subsection{Estimating other priors}


\documentclass{article}

\usepackage{mathtools}
\usepackage{tikz}
\usepackage{siunitx}

\newtheorem{theorem}{Example}

\begin{document}
\section*{Electronic Materials}
There are four classes:
\begin{itemize}
    \item Superconductors
          \begin{itemize}
              \item Type 1
              \item Type 2
              \item Ceramic (YBCO)
          \end{itemize}
    \item Conductors
          \begin{itemize}
              \item Linear
              \item Nonlinear
          \end{itemize}
    \item Semi-Conductors
          \begin{itemize}
              \item Elemental
              \item Compound
          \end{itemize}
    \item Dielectrics
          \begin{itemize}
              \item Linear
              \item Nonlinear
          \end{itemize}
\end{itemize}
\subsection*{Electrical Conductivity}

\subsection*{Ohm's Law}
$V = IR$\\
$V$ Voltage \si{\volt}\\
$I$ Current \si{\ampere}\\
$R$ Resistance \si{\ohm}

\subsection*{Power}
\begin{equation*}
    \begin{aligned}
        P           & = VI = I^2 R (\si{\watt}) \\
        V           & = IR                      \\
        R           & = \rho \frac{l}{A}        \\
        V           & = I\rho \frac{l}{A}       \\
        \frac{I}{A} & = \frac{V}{l}\sigma       \\
        \frac{V}{l} & = E \frac{V}{cm}          \\
        \frac{I}{A} & = J \frac{A}{m^2}         \\
        \sigma      & = n \cdot q \cdot \mu
    \end{aligned}
\end{equation*}

\begin{theorem}
    A current of 5A is passed through a 2mm-diameter wire, 500m long, made of
    \begin{itemize}
        \item Copper
        \item Germanium
    \end{itemize}
    Calculate the power loss for Cu and Ge wires
    \begin{equation*}
        \begin{aligned}
            \sigma(Cu) & = 5.98\cdot 10^5 \rho ^-1 cm^-1    \\
            \sigma(Ge) & = 2.10\cdot 10^-2 \rho ^-1 cm^-1   \\
            P=I^2R     & = I^2 \frac{1}{\sigma} \frac{l}{A}
        \end{aligned}
    \end{equation*}
\end{theorem}

\begin{theorem}
    If all the valence electrons in copper contribute to current flow, calculate:
    \begin{itemize}
        \item The mobility of an electronsthe average drift velocity for electrons in a 100cm copper wire when 10v are applied
    \end{itemize}
    \begin{equation*}
        \begin{aligned}
            \sigma & = n \cdot q \cdot \mu          \\
            \mu    & = \frac{\sigma}{nq}            \\
            \sigma & = \num{5.98E5}                 \\
            q      & = \num{1.6E-19}                \\
            a_0    & = \SI{3.6151E-8}{\centi\meter} \\
            \mu &= \SI{44.2}{\centi\meter\squared\per\volt\per\second}
        \end{aligned}
    \end{equation*}
\end{theorem}
\section*{Ionic Conductivity}
Conductivity increases with temperatue.
\end{document}


\subsection{Leaf-Zone Humidity Regulation}
\label{sec:humidityregulation}

\textbf{Purpose}: Regulates the relative humidity of the leaf zone.

\textbf{Function}:
\begin{itemize}
    \item \textbf{Inputs}: Humidification on/off control signal (\ref{sec:automation}), dehumidification on/off control signal (\ref{sec:automation})
    \item \textbf{Outputs}: Humidification or dehumidification on-demand
\end{itemize}

\textbf{Method}:
\begin{enumerate}
    \item \textit{Process}:
    \begin{enumerate}
        \item When humidity is too low (below dead-zone), humidification is activated;
        \item When humidity is too high (above dead-zone), dehumidification is activated;
        \item When humidity is at target (within dead-zone), both systems are deactivated;
    \end{enumerate}
\end{enumerate}

\textbf{Features}:
\begin{itemize}
    \item \textit{Humidification System}: See Section \ref{sec:humidification}.
    \item \textit{Dehumidification System}: See Section \ref{sec:dehumidification}.
    \item \textit{Humidity Sensors}: Multiple temperature and humidity sensors \cite{sht31} on small daughterboards frame-mounted throughout the growth environment to measure air relative humidity (\%RH). Informs the \textbf{bang-bang control loop}.
    \item \textit{Bang-Bang Control Loop}: A bang-bang (on/off) control loop with a hysteresis dead-zone (see equation \ref{eqn:bangbang}). Humidity sensors inform the loop, "error" is calculated (current vs desired humidity), and this informs whether or not to activate either the humidification or dehumidification systems (or neither). Requires tuning of dead-zone (automatic). Built into the automation system (see \ref{sec:automation});
\end{itemize}

\begin{gather}
    \label{eqn:bangbang}
    u(t)=\begin{dcases}
        -1  &   x < -d \\
        0   &   -d \leq x \leq d \\
        1   &   x > d \\
    \end{dcases}
\end{gather}

\clearpage

\subsubsection{Humidification}
\label{sec:humidification}

\textbf{Purpose}: Actively \textit{increases} growth environment air humidity.

\textbf{Function}:
\begin{itemize}
    \item \textbf{Inputs}: Power, humidification on/off control signal (\ref{sec:automation}), RO water\footnote{RO water contains no minerals/particulate, and as such prevents the common problem of mesh clog/calcification.}
    \item \textbf{Outputs}: Dry water vapour (\ref{sec:automation})
\end{itemize}

\textbf{Method}:
\begin{enumerate}
    \item \textit{Setup}:
    \begin{enumerate}
        \item Connect humidification control signal to control module.
        \item Connect RO water line to water tank.
    \end{enumerate}
    \item \textit{Testing}:
    \begin{itemize}
        \item Humidification unit responds to control signal as expected;
        \item Humidity sensor reads as expected;
        \item Tank does not leak;
    \end{itemize}
    \item \textit{Process}:
    \begin{enumerate}
        \item Water is delivered to a small tank (nebulizer is mounted);
        \item Power and control signal activate a nebulizer driver;
        \item Nebulizer vapourizes water;
    \end{enumerate}
    \item \textit{Shutdown}:
    \begin{enumerate}
        \item Disconnect RO water line and drain tank;
        \item Disconnect control signals from control module;
    \end{enumerate}
\end{enumerate}

\textbf{Features}:
\begin{itemize}
    \item \textit{Circulation Fans}: To circulate dry water vapour for even humidification. See Section \ref{sec:airthermoregulation}.
    \item \textit{Humidification Unit}: Easily controllable and produces a consistent vapour. Comprised of:
    \begin{itemize}
        \item \textit{Water Tank}: Holds a small amount of water behind the piezoelectric mesh.
        \item \textit{Mesh Nebulizer}: Piezoelectric ceramic disc with a microporous stainless steel mesh in the center. Oscillates in such a way that dry vapour is generated when water is passed over the mesh. Mounted to the water tank.
        \item \textit{Driver Circuit}: Fixed-frequency\footnote{113kHz for 20mm disc} 555 timer circuit driving an amplifier/LC circuit generates an sinusoidal signal. Powers the piezoelectric disc.
    \end{itemize}
\end{itemize}

\clearpage

\subsubsection{Dehumidification}
\label{sec:dehumidification}

\textbf{Purpose}: Actively \textit{decreases} growth environment air humidity.

\textbf{Function}:
\begin{itemize}
    \item \textbf{Inputs}: Humid air (high water vapour content), dehumidification on/off control signal, dry desiccant
    \item \textbf{Outputs}: Dry air (low water vapour content), saturated desiccant, desiccant saturation level signal
\end{itemize}

\textbf{Method}:
\begin{enumerate}
    \item \textit{Setup}:
    \begin{enumerate}
        \item Connect dehumidification control signal to control module;
        \item Insert dry desiccant cartridge;
    \end{enumerate}
    \item \textit{Testing}:
    \begin{itemize}
        \item Desiccant removes moisture from air.
        \item Desiccant indicates saturation as expected, which is sensed by computer.
        \item Shutters operate as intended, and no dehumidification occurs when closed.
        \item Maximum dehumidification rate exceeds total plant transpiration rate.
    \end{itemize}
    \item \textit{Process}:
    \begin{enumerate}
        \item Dehumidification control signal activates fans and opens shutters;
        \item Humid air passes over the desiccant, and dry air exits the unit;
        \item Desiccant becomes saturated, and indicates degree of saturation;
        \item Indication is sensed by computer (\ref{sec:automation}), which notifies the user when to replace and dehydrate/"recharge" desiccant;
    \end{enumerate}
    \item \textit{Shutdown}:
    \begin{enumerate}
        \item Disconnect control signals from control module;
        \item Recharge cartridge;
    \end{enumerate}
\end{enumerate}

\textbf{Calculations}:\\
Assuming an air temperature of 30$\degree$C, water vapour saturation $p_{30C}$ of $30.4g/m^{3}$, relative humidity target range $[\text{\%RH}_{min},\text{\%RH}_{max}]$ of 20\% to 90\%, and 6\% dessicant capacity (by mass):
\begin{gather}
    m_{vapour} = \text{\%RH} * p_{30C} * V\\
    V_{4U} = (0.5m)^3 * 4 = 0.5m^{3} \\
    m_{extracted} = m_{max} - m_{min} = (\text{\%RH}_{max}-\text{\%RH}_{min}) * p_{30C} * V = 10.64\text{g water}\\
    m_{desiccant}=\frac{10.64g}{0.06 \%} = 177.3\text{g desiccant}
\end{gather}

$\therefore$ 177.3g of 6\% capacity desiccant is needed to change the RH\% of a 4U Class 2 setup from 90\% to 20\%.

\clearpage

\textbf{Features}:
\begin{itemize}
    \item \textit{Dehumidification Unit}: One input port and one output port. Comprised of:
    \begin{itemize}
        \item \textit{Fans}: Humidity-rated fans force moist air through the desiccant cartridge input port and dry air out of the output port.
        \item \textit{Filter}: Polyethylene-polyropylene blend (non-toxic) MERV 13 (0.3 micron) air filters \cite{filter} located at input and output ports of dehumidification chamber eliminate risk of any airborne pathogens being transferred onto silica beads and out of the system during cartridge recharging.
        \item \textit{Shutters}: Servo-actuated shutters enable opening and closing of dehumidifier input and output on demand. Air-tight when closed to prevent unintended dehumidification.
        \item \textit{Desiccant Cartridge}: Oven-safe. Easily removable for swapping and "recharging". Contains the silica gel desiccant.
        \item \textit{Indicating Silica Gel Desiccant}: Cheap, efficient, food-safe, reusable chemical desiccant beads with a water mass capacity of 6\% \cite{desiccant}. Changes color from blue to pink when saturated.
    \end{itemize}
    \item \textit{Color Sensor}: Optical color sensor \cite{colorsensor} senses cartridge saturation. Informs when to recharge the desiccant cartridge (see \ref{sec:automation}).
    \item \textit{Evaporator Oven}: A ventilated oven that can maintain 125°C for 12 hours \cite{desiccant}. Heats cartridge to evaporate/"bake off" moisture collected by silica beads, thus "recharging" them. Vapour is vented to onboard dehumidifier for recapture.
\end{itemize}


\subsection{The Galilean group}