\section{dynTsET Design}
\label{sec:TechDes}

\tcr{My main criticism of the paper is the presentation. While I appreciate the use of diagrams in the first half of the paper, high-level explanations are missing later. The paper does not do a very good job providing an intuition for how the data structure works. For example, I was struggling understanding the role of the monoidal set. The paper also explains too little of the background regarding used existing data structures and their realisation in Haskell libraries. For example, the interface to the finger tree ADT and the Measured type class. In general, most of the explanations are closely tight to the code but don’t give a high-level picture of what individual operations do in terms of the Euler tour. Given that there is plenty of space left in the paper, this could be improved in the final version.}

\tcr{This reviewer can't help but think that there seems to be a lot of redundancy in the proposed data structure, as the Euler tour node pairs are present in both the sets and in the finger trees.}

In this section, we present the data types and the operations to manage dynamic trees through Euler-tour trees, that is \dyntset. Firstly, we describe how to convert any-degree tree into a Euler-tour tree. Secondly, assuming we are provided with Euler-tour trees, we define our initial data type which stores those trees within the leaves of a finger tree. Thirdly, we detail the functions for linking and cutting trees when performed in isolation. Finally, we incorporate the Euler-tour trees into the context of a forest. At this point, we describe the three operations regarded to dynamic trees: \conn (connectivity query), \link and \cut for trees within a forest. At any time, the number of nodes is fixed and every node is uniquely identified; nodes and edges are both represented as pairs. Full source code is located at \url{https://github.com/jcsaenzcarrasco/ETdynTs}.

\subsection{From $k$-degree tree to Euler-tour tree}

In Haskell, a $k-$degree tree (i.e. any-degree tree) is also known as multiway tree or rose tree. Actually, there is a library that defines such trees, \code{Data.Tree}, in the Haskell community's central package archive (Hackage).

\begin{lstlisting}
data Tree a = Node {
        rootLabel :: a,
        subForest :: Forest a
    }
\end{lstlisting}

So, a tree is a node of type \code{a} (i.e. its root) altogether with a list (possibly empty) of subtrees, seen as forest of type \code{Forest a}. Analogous to multiway trees, our trees (finger trees holding Euler-tours) can not be empty.

Firstly, we turn a tree into a list of nodes, by attaching (mapping) the prefix and suffix of current node to inner subtrees. We later feed this list into a finger tree. The following function snippet can be read as \textit{rose-tree-to-euler-tour-tree}.

\begin{lstlisting}[mathescape]
rt2et :: (Eq a) $\Rightarrow$ Tree a $\to$ [(a,a)]
rt2et (Node x ts) = case ts of
  [] $\to$ [(x,x)]
  _  $\to$ root ++ concat ( map ($\lambda$t $\to$ pref t ++ rt2et t ++ suff t) ts )
    where
     pref v = [(x,rootLabel v)]
     suff v = [(rootLabel v,x)]
     root   = [(x,x)]
\end{lstlisting}

Since \code{concat} and \texttt{++} take $O(n)$ where $n$ is the size of the input tree, \code{rt2et} takes $O(n)$. \tcr{Should we need to prove this ???}

The corresponding forest transformation to list of pairs is simply the application of \code{rt2et} to every element in the tree list. Because it requires a single traversal, \code{rf2et} (read as \textit{rose-forest-2-euler-tour-tree}) requires $O(n)$ time, where $n$ is the number of elements in the forest.

\begin{lstlisting}[mathescape]
rf2et :: (Eq a) $\Rightarrow$ Forest a $\to$ [[(a,a)]]
rf2et []          = []
rf2et [Node x []] = [[(x,x)]]
rf2et (t:ts)      = (rt2et t) : rf2et ts
\end{lstlisting}

Once a tree $t$ of any degree is turned into an Euler tour $et$, we are able to manage $et$ as a sequence.

\subsection{Euler-tour tree as finger tree of pairs with a set of pairs as monoidal annotation}

Since finger trees work efficiently on sequences, according to \cite{FTs} (see also Table~\ref{tab:FTfuncs}), we tailored the finger tree in order to support \link, \cut and \conn operations over unrooted trees following the procedures for modifying encodings (i.e. conversions between any-degree tree and Euler-tours) by Henzinger and King in \cite{Rand-DynGs-Algos}.

Recall from Figure~\ref{fig:FTdatatype}, the finger tree \code{data FingerTree v a}, has two polymorphic types, the first one (\code{v}) is the type of the monoidal annotation and the second (\code{a}) the type of the values stored at the leaves, which in our case is the sequence type. In Section~\ref{sec:ETt} we provided the need for nodes and edges to be treated as pairs (see also Figure~\ref{fig:Euler-tour}), therefore our values type is \code{(a,a)} for any type \code{a}, although in the following sections we will define such pairs as integers for practical purposes. In this manner, a pair $(u,v)$ (atomic element in the sequence) represents a node, when $u = v$, and an edge when $u \neq v$. From here, every element in the sequence can be located.

For the internal finger tree nodes (monoidal annotations), where searching take place, we define \code{Data.Set (a,a)} as our type. By doing so, we are able to take advantage from some set-like operations such as membership-test, insertion and union.

We define the set-insertion operation every time a pair (either edge or node) is added to an Euler-tour tree (i.e. finger tree). The set-union is already defined in \code{Data.Set} at its monoidal binary operation, therefore there is no need to define this in our proposal. Testing membership is performed through the finger tree \code{search} function \cite{FTsURL}. Our data type for holding a sequence (Euler-tour tree) whithin a finger tree is called \code{TreeEF} defined below followed by its corresponding instance for \textit{measuring} it, that is, returning a set when a value is provided.

\begin{lstlisting}[mathescape]
import qualified Data.FingerTree as FT
import qualified Data.Set        as S

type TreeEF   a = FingerTree (S.Set (a,a)) (a,a)

instance (Ord a) $\Rightarrow$ Measured (S.Set (a,a)) (a,a) where
   measure (x,y) = S.insert (x,y) S.empty
\end{lstlisting}

In the context of performance, we recall finger tree functions (see Table~\ref{tab:FTfuncs}). At that stage, every function assumes the monoidal annotation takes $O(1)$. Since our annotation is not a simple type, we calculate the corresponding finger tree operations into our \dyntset proposal as:
\begin{itemize}
\item \code{viewl}: remains the same as there is no further operations involved, that is, $O(1)$.
\item $\lhd$: since the insertion takes place through a set-insertion, then we have $O(\log n)$ replacing $O(1)$.
\item $\rhd$: same as $\lhd$
\item $\bowtie$: concatenation involves the set-union operation at the monoidal annotation nodes. Then, let $m$ and $n$ be the sizes of the sets every time there is a union operation performed. Following the performance and constraint from Table~\ref{tab:Setfuncs}, we have $O(m(\log\frac{n}{m} +1))$. If $m$ is 1, that is, inserting a single element in a set of size $n$ (as in $\lhd$ or $\rhd$) we have $O(1(\log\frac{n}{1} +1))$ which turns $O(\log n)$. If $m$ is at most $n$, then $O(n(\log\frac{n}{n} +1))$, resulting in $O(n)$. Although the latter case (the worst) might be presented at any time, it is not always the case when concatenating since sizes of the sets in a finger tree are not constant, either growing up to $n$ for both sets or shrinking down to 1 for one set. In any case, for $\bowtie$ we have $O(\log(min(m,n)))$ where $m$ and $n$ might get $n^2$, hence $O(\log n^2)$.
\item \code{search}: every search in the finger tree uses a test-membership in the monoidal annotations nodes which takes $O(\log n)$. Then, the $O(\log(min(i,n-i)))$ is substituted by $O(\log (\log n))$, resulting in $O(\log^2 n)$. Although this just the calculation of the performances of a set within a finger tree. Since a finger tree (non singular) has a monoidal annotation on its top (line 3 in Figure~\ref{fig:FTdatatype}) the look up for an element is actually a simple test-membership operation, that is, $O(\log n)$.
\end{itemize}

Summarising the above, the following are the types and bounds for \dyntset, provided type \code{v} is actually \code{Set b} and type \code{b} is actually the pair \code{(a,a)}

\small
\begin{table}[H]
\begin{center}
\begin{tabular}{||l | l | c||}
 \hline
 Function         & Type                                   &
      \begin{tabular}{c} Time complexity \\
                         (amortised bounds)
      \end{tabular} \\
 \hline\hline
 \texttt{viewl}   &
      \begin{tabular}{l} \texttt{FingerTree v b}   \\
                         \texttt{$\to$ ViewL (FingerTree v b)  }
      \end{tabular}
                  & $O(1)$ \\
 \hline
 \texttt{search}  &
      \begin{tabular}{l} \texttt{(v $\to$ v $\to$ Bool)}   \\
                         \texttt{$\to$ FingerTree v b  }   \\
                         \texttt{$\to$ SearchResult v b  }
      \end{tabular}
          & $O(\log n)$  \\
 \hline
 \texttt{$\lhd$}  &
      \begin{tabular}{l} \texttt{b $\to$ FingerTree v b} \\
                         \texttt{$\to$ FingerTree v b}
      \end{tabular}
          & $O(\log n)$                \\
 \hline
 \texttt{$\rhd$}  &
      \begin{tabular}{l} \texttt{FingerTree v b $\to$ b} \\
                         \texttt{$\to$ FingerTree v b}
      \end{tabular}
          & $O(\log n)$                \\
 \hline
 \texttt{$\bowtie$}  &
      \begin{tabular}{l} \texttt{FingerTree v b} \\
                         \texttt{$\to$ FingerTree v b} \\
                         \texttt{$\to$ FingerTree v b}
      \end{tabular}
          & $O(\log n^2)$         \\
 \hline
\end{tabular}
\caption{\dyntset types and performances}
\label{tab:dyntsetFTfuncs}
\end{center}
\end{table}
\normalsize

\subsection{rooting and rerooting a tree}
Functions \root and \reroot play a crucial importance in the definition of \link, \cut and \conn as we shall see shortly. We mentioned earlier that dynamic trees is about managing unrooted trees. By \root we refer to the entry point of any Euler-tour, which always starts in the form $(v,v)$ since it represents a node. By \emph{unrooted} tree we refer to the fact that any node in the tree can be its \root. This is actually performed in function \link.

We have showed that \code{viewl} returns the leftist element of a finger tree. Applying \code{viewl} a \code{TreeEF} we have its root as in the following snippet.
\begin{lstlisting}[mathescape]
root :: Ord a $\Rightarrow$ TreeEF a $\to$ Maybe a
root tree = case viewl tree of
  EmptyL   $\to$ Nothing
  x :< _   $\to$ Just ( fst x )
\end{lstlisting}

We return the first element in the pair $(v,v)$ since any $v$ represents the node-root. Time complexity of \root is $O(1)$ since \code{viewl} performs $O(1)$ in the finger tree and we simply pattern match over its results.

Then, for \textit{reroot}ing a tree we follow the second procedure by Henzinger and King in \cite{Rand-DynGs-Algos}, which states:
\begin{displayquote}
\emph{To change the root of \textit{T} from $r$ to $s$}: Let $o_s$ denote any occurrence of $s$. Splice out the first part of the sequence ending with the occurrence before $o_s$, remove its first occurrence ($o_r$), and tack the first part on to the end of the sequence, which now begins with $o_s$. Add a new occurrence $o_s$ to the end.
\end{displayquote}

So, instead of looking for $r$ (old root) occurrences, we focus only in the new root($s$). We splice out the first and second occurrences of node $s$ by simply searching for it as $(s,s)$ in the finger tree: \code{S.member (s,s) tree}. Then, simply glue all the parts in order, that is, the new root first (leftist) followed by the second and first occurrences of $s$: \code{(s,s)} $\lhd$ \code{(right } $\bowtie$ \code{ left)}. This is denoted in the following snippet.

\begin{lstlisting}[mathescape]
reroot :: Ord a $\Rightarrow$ TreeEF a $\to$ a $\to$ TreeEF a
reroot tree node = case (FT.search pred tree) of
   Position left _ right $\to$ rootTree $\lhd$ (right $\bowtie$ left)
   _                     $\to$ tree
 where rootTree      = (node,node)
       pred before _ = (S.member rootTree) before
\end{lstlisting}

\tcr{PERFORMANCE of REROOT }\tcb{Operators $\lhd$, \code{FT.search}, and $\bowtie$ take $O(1)$, $O(\log n)$ and $O(\log n^2)$ amortised respectively on finger trees. Since we are applying them only once, our \reroot function also takes $O(\log n^2)$}. In case \reroot is asked altogether with a node not in the tree, it simply returns the original \code{tree} (fourth line in above snippet).

\subsection{linking and cutting trees off the forest}

For cutting a tree or deleting an edge following Henzinger and King in their first procedure in \cite{Rand-DynGs-Algos} we have:
\begin{displayquote}
\emph{To delete edge \{$a$,$b$\} from $T$:} Let $T_1$ and $T_2$ be the two trees that result, where $a \in$ $T_1$ and $b \in$ $T_2$. Let $o_{a_1}$, $o_{b_1}$, $o_{b_2}$ represent the occurrences encountered in the two traversals of \{$a,b$\}. If $o_{a_1} < o_{b_1}$ and $o_{b_1} < o_{b_2}$, then $o_{a_1} < o_{b_1} < o_{b_2} < o_{a_2}$. Thus, ET($T_2$) is given by the interval of ET($T$) $o_{b_1}$, \ldots, $o_{b_2}$ and ET($T_1$) is given by splicing out of ET($T$) the sequence $o_{b_1}$, \ldots, $o_{a_2}$.
\end{displayquote}

The following snippet shows the \code{cutTree} operation analogous to the above procedure :
\begin{lstlisting}[mathescape]
cutTree :: Ord a $\Rightarrow$ a $\to$ a $\to$ TreeEF a $\to$ Maybe (TreeEF a,TreeEF a)
cutTree u v tree = case FT.search predUV tree of
 Position left _ right $\to$
   case (FT.search predVU left ) of
      Position leftL _ rightL $\to$
        Just (rightL, leftL $\bowtie$ right)
      _                $\to$
        case (FT.search predVU right) of
          Position leftR _ rightR $\to$
            Just (leftR, left $\bowtie$ rightR)
          _ $\to$ Nothing
 _  $\to$ Nothing
 where
   predUV before _ = (S.member (u,v)) before
   predVU before _ = (S.member (v,u)) before
\end{lstlisting}

The snippet quite follows the procedure. The pairs $(u,v)$ and $(v,u)$ are left out the resulting sequences in the wildcards in lines 3, 5 and 9. Since we search $(u,v)$ first, there are only two possibilities for $(v,u)$ to be part of. If it is on the left we build up $T_1$ from \code{rightL}, and $T_2$ from \code{leftL} and \code{right}. Otherwise $T_1$ is built from \code{leftR} and $T_2$ from \code{left} and \code{rightR}. $T_2$ is spliced out through the $\bowtie$ operator.

\tcr{PERFORMANCE of cutTree }\tcb{Operator $\bowtie$ and function \code{FT.search} take $O(\log n^2)$ and $O(\log n)$ amortised respectively on finger trees. Since we are applying $\bowtie$ once and \code{search} twice, then \code{cutTree} function also takes $O(\log n^2)$}. In case \code{cutTree} is called with nodes belonging different components (edge not in \code{tree}), then \code{cutTree} returns \code{Nothing} in $O(\log n)$, which will be captured as failure in \cut within a forest operation.

Now, for linking a tree (or joining two trees), we follow the third and final encoding in \cite{Rand-DynGs-Algos}:
\begin{displayquote}
\emph{To join two rooted trees $T$ and $T'$ by edge $e$:} Let $e = \{a,b\}$ with $a \in T$ and $b \in T'$. Given any  occurrence $o_a$ and $o_b$, reroot $T'$ at $b$, create a new occurrence $o_{a_n}$ and splice the sequence $ET(T')o_{a_n}$ into $ET(T)$ immediately after $o_a$.
\end{displayquote}

The following snippet translate the above procedure quite close.
\begin{lstlisting}[mathescape]
linkTree :: Ord a $\Rightarrow$ a $\to$ TreeEF a $\to$ a $\to$ TreeEF a $\to$ Maybe (TreeEF a)
linkTree u tu v tv = case (pairIn (u,u) tu, pairIn (v,v) tv) of
  (False, _    ) $\to$ Nothing
  (_    , False) $\to$ Nothing
  (True , True ) $\to$ Just $\$$
    let from = reroot tu u
        (Position left _ right) = FT.search pred tv
    in  ((left $\rhd$ (v,v)) $\rhd$ (v,u)) $\bowtie$ from $\bowtie$ ((u,v) $\lhd$ right)
 where
   pred before _ = (S.member (v,v)) before
\end{lstlisting}

We build $e = \{a,b\}$ where $a \in T$ and $b \in T'$ from the procedure in line 2 as \code{(u,u)} $\in$ \code{tu} and \code{(v,v)} $\in$ \code{tv}.  Then, in line 6, we reroot $T'$ at $b$ as \code{reroot tu u} calling its result as \code{from} and finally splicing it in line 8 immediately after \code{(v,u)}.

\tcr{PERFORMANCE of linkTree.} We have two times the performance of \code{search} within \code{pairIn} (line 2 above), that is, $O(\log n)$. Then we call \code{search} one more time at line 7. Finally we build up the resulting tree by applying $\lhd$ and $\rhd$ taking $O(1)$ and $\bowtie$ taking $O(\log n^2)$ time. Function \code{pairIn} is defined as
\begin{lstlisting} [mathescape]
pairIn :: (Measured (S.Set a) a, Ord a)
       $\Rightarrow$ a $\to$ FingerTree (S.Set a) a
       $\to$ Bool
pairIn p monFT = case (FT.search pred monFT) of
  Position _ _ _ $\to$ True
  _              $\to$ False
 where
   pred before _ = (S.member p) before
\end{lstlisting}

\subsection{\link, \cut and \conn within a forest}
Literature refers to link and cut operations (as in \cite{DS-DynTs}, \cite{WerneckR-PhD} and \cite{Rand-DynGs-Algos}) to the definitions and analysis we have done previously. In this part, we shall see that \link, \cut specialise the former ones in the context of a forest. Moreover, \conn answers the queries for \textit{connectivity} in the dynamic setting, that is, given an finite sequence of link and cut operations applied to a forest, \conn returns \code{True} if the two nodes provided belong to the same component (tree) within a forest, or \code{False} otherwise.

Firstly, we need to define a data type for a forest structure. In Section~\ref{sec:Prelim} we defined a tree as Euler-tour, which is now the leaf in the forest-finger-tree structure i.e. its \textit{element}. Likewise the internal nodes in a tree, a set is also the monoidal annotation in the forest type. The result, a finger tree comprised of finger trees.
\begin{lstlisting}[mathescape]
type ForestEF a = FingerTree (S.Set (a,a)) (TreeEF a)
\end{lstlisting}

The fastest and easiest operation is \conn. It simply tests membership for each node against the top set in the forest, that is, the monoidal annotation in the root of the finger tree: \code{nodeIn node forest}. Then, if both nodes are elements of the forest implies they belong to a tree, remaining the question for whether or not both roots are the same
\begin{lstlisting}[mathescape]
conn :: Ord a $\Rightarrow$ a $\to$ a $\to$ ForestEF a $\to$ Bool
conn x y f =
 case (nodeIn x f, nodeIn y f) of
  (Just (tx,rx) , Just (ty,ry)) $\to$ if rx == ry  then True else False
  _                             $\to$ False
\end{lstlisting}

Notice we have not searched pairs of nodes but the nodes themselves. This is evaluated internally in \code{nodeIn} function.
\begin{lstlisting}[mathescape]
nodeIn :: Ord a $\Rightarrow$ a $\to$ ForestEF a $\to$ Maybe (TreeEF a, a)
nodeIn node forest =
 case FT.search pred forest of
  Position _ tree _ $\to$
     case (root tree) of
       Nothing    $\to$ Nothing
       Just rootT $\to$ Just (tree, rootT)
  _                 $\to$ Nothing
 where
   pred before _ = (S.member (node,node)) before
\end{lstlisting}

Following the bounds from Table~\ref{tab:dyntsetFTfuncs} we have that \code{nodeIn}, called only twice, applies \code{root} which takes $O(1)$ and \code{FT.search} which takes $O(\log n)$, thus querying for connectivity in our structure through \conn takes $O(\log n)$.

Similar to \code{cutTree}, \cut requires two nodes as arguments, but alike \code{cutTree} requires:
\begin{itemize}
\item [req$_{c1}$]: a forest instead of a tree, although the tree is searched rather than provided;
\item [req$_{c2}$]: the tree where the nodes belong to is left out of the forest;
\item [req$_{c3}$]: the resulting trees from cutting are inserted into the \textit{new} forest (from the left)
\end{itemize}

By {\cut}ting trees the forest increases its number of trees, from two when the forest has a single tree up to the number of nodes when each tree does not have children.

\begin{lstlisting}[mathescape]
cut :: Ord a $\Rightarrow$ a $\to$ a $\to$ ForestEF a $\to$ ForestEF a
cut x y forest
 | x == y    = forest
 | otherwise =
    case connected x y forest of
      (True, Just (tx,_,_,_)) $\to$ case (cutTree x y tx) of
        Nothing     $\to$ forest
        Just result $\to$ buildForest result
      _                       $\to$ forest
 where
    buildForest (t2,t3) = t2 $\lhd$ (t3 $\lhd$ (lf $\bowtie$ rf))
    Position lf _ rf    = FT.search pred forest
    pred before _       = (S.member (x,x)) before
\end{lstlisting}

In \dyntset, \cut does not assume nodes belong to the tree. We verify this in lines 5 and 6. req$_{c1}$ is discharged in line 6 i.e. \code{tx}; req$_{c2}$ is fulfilled in line 12 through the wildcard \code{_}. req$_{c3}$ is met through \code{buildForest} function in line 11.

\tcr{PERFORMANCE of \cut }\tcb{We perform $O(\log n)$ in \code{connected} (line 5) as we shall see shortly. Later, \code{cutTree} in line 6 takes $O(\log m^2)$. Here, $n$ represents the number of nodes in the forest and $m$ the number of nodes in \code{tx} (i.e. local tree). In case the forest is comprised of a single tree i.e. $m = n$, then \code{cutTree} takes $O(\log n^2)$. Function \code{buildForest}, defined at line 11, takes $2T_1(\lhd)+T_2(\bowtie)$. The function $T_1$ is the time taken for gluing (inserting) the resulting trees from cutting, \code{t2} and \code{t3}, into the forest. Function $T_2$ is the time taken of gluing (concatenating) the subforest \code{lf} and subforest \code{rf}. This concatenation is the effect of leaving apart the cut tree, \code{tx}. Since both $T_1$ and $T_2$ operate over the forest, $n$ is the variable. Then, $T_1 = O(\log n)$ and $T_2 = O(\log n^2)$ following the performance from Table~\ref{tab:dyntsetFTfuncs}. Thus, \cut takes up to $O(\log n^2)$ amortised time. }

We take advantage from function \code{nodeIn} to define \code{connected} as auxiliary function for \cut and \link. Here is its definition.
\begin{lstlisting}[mathescape]
connected :: Ord a $\Rightarrow$ a $\to$ a $\to$ ForestEF a
          $\to$ (Bool, Maybe (TreeEF a, a, TreeEF a, a) )
connected x y f =
 case (nodeIn x f, nodeIn y f) of
  (Just (tx,rx)     , Just (ty,ry)) $\to$ if rx == ry
                                   then (True,  Just(tx,rx,tx,rx))
                                   else (False, Just(tx,rx,ty,ry))
  _                                 $\to$ (False, Nothing)
\end{lstlisting}
Function \code{connected} takes twice the time as \code{nodeIn} as this is called once per node. The remaining code is just pattern matching.

The \link operation follows the same pattern than \cut operation. The difference is the application of \code{linkTree} and the construction of the \textit{new} forest. Also, similar to \cut, \link requires:
\begin{itemize}
\item [req$_{l1}$]: a forest instead of a tree, although the tree is searched rather than provided, satisfied through \code{connected} as in \cut.
\item [req$_{l2}$]: the trees where the nodes belong to are left out of the forest, two steps rather than one as in \cut
\item [req$_{l3}$]: the resulting tree from linking is inserted into the \textit{new} forest (from the left)
\end{itemize}

\begin{lstlisting}[mathescape]
link :: Ord a $\Rightarrow$ a $\to$ a $\to$ ForestEF a $\to$ ForestEF a
link x y forest
  | x == y    = forest
  | otherwise =
     case connected x y forest of
      (False, Just (tx,rx,ty,ry)) $\to$ case (linkTree x tx y ty) of
         Nothing     $\to$ forest
         Just result $\to$ linkAll result
      _                           $\to$ forest
 where
    Position lf' _ rf' = FT.search predX forest
    Position lf  _ rf  = FT.search predY (lf' $\bowtie$ rf')
    linkAll tree    = tree $\lhd$ (lf $\bowtie$ rf)
    predX before _ = (S.member (x,x)) before
    predY before _ = (S.member (y,y)) before
\end{lstlisting}
\tcr{PERFORMANCE of \link }. Following the bottom-up approach from the above snippet and the performances from Table~\ref{tab:dyntsetFTfuncs}, we have in line 11, the subforests \code{lf'} and \code{rf'} which get rid of the original tree containing node \code{x}. Then, in line 12, \code{lf} and \code{rf} are the subforests after disposing the original tree containing node \code{y} (wildcards \code{_} respectively). These two steps satisfy req$_{l2}$ and take twice the time of \code{FT.search} which is $O(\log n)$ and once the time of $\bowtie$ at forest level which is $O(\log n^2)$. Then \code{linkAll}, defined at line 13, calls $\lhd$ for inserting the \textit{new} \code{tree}, as \code{result} of \code{linkTree}, into the \textit{new} forest, taking $O(\log n)$ altogether with the concatenation of \code{lf} and \code{rf} in $O(\log n^2)$. With this, we meet req$_{l3}$. In line 5, we ensure to look for the nodes \code{x} and \code{y} within the \code{forest} in $O(\log n)$. If both nodes are members of the \code{forest} but not connected, line 6, then \code{linkTree} is performed in $O(\log m^2)$ where $m$ is the size of the sum of the number of the nodes in trees \code{tx} and \code{ty}, unless $\vert$\code{tx}$\vert + \vert$\code{ty}$\vert = n$, where \code{linkTree} takes $O(\log n^2)$. Since no loop or recursion is involved and that of a constant number of operations were made in \link, this function takes up to $O(\log n^2)$ amortised.


\section{Instructions for running the shallow flow models}

Python 3 software is available for download from Zenodo \citep{shaw-kesserwani2019b} which includes
\begin{enumerate}
    \item a one-dimensional shallow flow model which can operate as a stochastic Galerkin model or a deterministic model
    \item code for running Monte Carlo iterations of the deterministic model
    \item preconfigured lake-at-rest, steady-state critical flow and steady-state flow over an irregular bed test cases
\end{enumerate}
First ensure that Python 3, NumPy and SciPy are installed.
Then, install the shallow flow model:
\begin{verbatim}
pip3 install --user --editable swepc.python
\end{verbatim}

\subsection{Running the Stochastic Galerkin Model}
To run the stochastic Galerkin model:
\begin{Verbatim}[commandchars=\\\{\}]
swepc --degree \textit{<P>} \textit{<testCase>} \textit{<discretisation>} --output-dir \textit{<directory>}
\end{Verbatim}
where \Verb[commandchars=\\\{\}]+\textit{<testCase>}+ is either \Verb+lakeAtRest+, \Verb+criticalSteadyState+ or \Verb+tsengSteadyState+,
\Verb[commandchars=\\\{\}]+\textit{<discretisation>}+ is either \Verb+wellBalancedH+ for the well-balanced surface gradient method, or \Verb+centredDifferenceH+ for the centred difference method given by equations~\eqref{eqn:flux-centred} and \eqref{eqn:source-centred}.
If \Verb[commandchars=\\\{\}]+--degree \textit{<P>}+ is omitted then the default basis order $P = 3$ is used.
If \Verb[commandchars=\\\{\}]+--degree 0+ is specified then the model operates as a deterministic model.
On running the model, the following text files are written to the specified output directory:
\begin{description}
\item[\Verb+coefficients.dat+]{Stochastic Galerkin expansion coefficients for topography $z$, water depth $h$ and discharge $q$}
\item[\Verb+statistics.dat+]{Mean, standard deviation, skew and kurtosis calculated using equations~\eqref{eqn:moment}, \eqref{eqn:mean} and \eqref{eqn:variance}}
\item[\Verb+derived-statistics.dat+]{Statistics for the depth-averaged velocity and the free-surface elevation, a derived quantity calculated from equation~\eqref{eqn:h-eta-z}}
\end{description}
Each file has one line per element with explanatory header rows prefixed by \Verb+#+.

\subsection{Calculating Probability Density Functions}
A probability density function for any variable can be calculated from the expansion coefficients for a given element:
\begin{Verbatim}[commandchars=\\\{\}]
sed -n \textit{<line>}p coefficients.dat
   | swepdf --min \textit{<value>} --max \textit{<value>} \textit{<variable>} > pdf.dat
\end{Verbatim}
where \Verb[commandchars=\\\{\}]+\textit{<line>}+ is the line number in \Verb+coefficients.dat+ corresponding to the chosen element, and \Verb[commandchars=\\\{\}]+\textit{<variable>}+ is \Verb+z+ (topography), \Verb+water+ (water depth), \Verb+q+ (discharge) or \Verb+derived-eta+ (free-surface elevation).
The probability density function is calculated between the \Verb+--min+ and \Verb+--max+ values and written to \Verb+pdf.dat+.

\subsection{Running Monte Carlo Simulations}
To run a Monte Carlo simulation:
\begin{Verbatim}[commandchars=\\\{\}]
swepc --monte-carlo --mc-iterations \textit{<value>}
  criticalSteadyState \textit{<discretisation>} --output-dir \textit{<directory>}
\end{Verbatim}
which writes the following text files:
\begin{description}
\item[\Verb+statistics.dat+]{Mean, standard deviation, skew and kurtosis for topography, water depth and discharge}
\item[\Verb+derived-statistics.dat+]{Mean and standard deviation for free-surface elevation and depth-averaged velocity}
\cprotect\item[\Verb[commandchars=\\\{\}]+sample\textit{<n>}.dat+]{Deterministic model data with one file per element (numbered $0, \ldots, M-1$), each having one line per Monte Carlo iteration}
\end{description}


\documentclass[twoside,9pt,twocolumn]{aiaa}
% can use letter, twoside, oneside, 9pt, 10pt, 11pt, 12pt, onecolumn, twocolumn, conference, submit, mtpro
% aiaa conference papers should use the options oneside,10pt,letter,onecolumn,conference
\usepackage{graphicx}
\usepackage{rotating}
\usepackage{bm}

\newcommand{\alb}{\vspace{0.1cm}\\} % array line break
\newcommand{\mfd}{\displaystyle}
\renewcommand{\vec}[1]{\bm{#1}}

\author{  Daesu Oh\thanks{Graduate Student, Dept.\ of Aerospace Engineering, ohdaesu@pnu.edu}
          ~and~
          B.\ Parent\thanks{Assistant Professor, Dept.\ of Aerospace Engineering, parent@pnu.edu}\\
          {\it Pusan National University, Busan 609-735, South Korea}\\
          ~and\\
          Mikhail Shneider\thanks{Research Staff Member, Dept.\ of Mechanical and Aerospace
                                  Engineering}
          ~and
          Sergey Macheret\thanks{Senior Research Scientist, Dept.\ of Mechanical and Aerospace
                                 Engineering, now at Lockheed Martin.}\\
          {\it Princeton University, Princeton, NJ 08544-5263, USA}\\}

\title{Example of a \LaTeX\ Article in AIAA Format}

\abstract{A new formulation of the generalized Ohm's law is here presented that is applicable to weakly-ionized plasmas with multiple types of ions. The novel formulation takes into consideration the separate ion slip currents associated with each type of ion and is recommended for computational studies of non-neutral and quasi-neutral weakly-ionized plasmas. Starting from the new form of the generalized Ohm's law, we derive an electric field potential equation that is applicable to a plasma with more than one type of ions. Despite some similarities between the potential equation and the Poisson equation, it is argued that the discretization of the potential equation cannot be accomplished in the same manner by using only central differences. It is here proven (and subsequently verified through a testcase) that when the plasma exhibits conjunctly a high Hall parameter and a high electrical conductivity gradient, the centered stencils introduce spurious oscillations which can lead to severe numerical error. Another contribution of this paper is to present a novel discretization of the potential equation which consists of a blend of central and upwind differences. The proposed scheme is consistently monotonic for any value of the Hall parameter and is second-order accurate except in the vicinity of discontinuities.
}

\acknowledgments{Numerous discussions with Park Chan-Wook helped improve the quality of this manuscript considerably. This work was sponsored by a Pusan National University Grant.}
% use =acknowledgment{} for a single acknowledgment

\setlength\nomenclaturelabelwidth{0.43 in}

\nomenclature{

  \begin{nomenclaturelist}{Roman Symbols}
   \item[$a_i^{\rm SS}$]     wave speed associated with the skew-symmetric terms of the tensor conductivity
   \item[$\vec{B}$]          magnetic field vector
   \item[$\bar{\vec{B}}$]      normalized magnetic field vector, $\vec{B}/|\vec{B}|$
   \item[$C_k$]       charge of $k$th species
   \item[$\vec{E}$]          electric field vector
   \item[$N_k$]       number density of $k$th species
   \item[$s_k$]       sign of the charge, $-1$ for electrons and negative ions and $+1$ for positive ions
   \item[$\vec{v}$]          velocity vector of the bulk of the gas
   \item[$X_i$]       grid index along $x_i$ coordinate
   \item[$x_i$]       spatial coordinate
   \item[$Y_k$]       matrix needed to determine the conductivity
  \end{nomenclaturelist}

  \begin{nomenclaturelist}{Greek Symbols}
   \item[$\sigma$]       scalar conductivity, $\sum |C_k| N_k \mu_k$
   \item[$\wtilde{\sigma}$]       tensorial conductivity
   \item[$\wtilde{\sigma}^{\rm S}$]       symmetric part of tensorial conductivity
   \item[$\wtilde{\sigma}^{\rm SS}$]       skew-symmetric part of tensorial conductivity
   \item[$\phi$]       electric field potential
   \item[$\beta_{\rm e}$]       Hall parameter for the electrons, $\mu_{\rm e} |\vec{B}|$
   \item[$\delta_{x_i}$]       discretization operator along  $x_i$ coordinate
   \item[$\Delta {x_i}$]       grid spacing along  $x_i$ coordinate
   \item[$\mu_k$]       mobility of $k$th species
  \end{nomenclaturelist}

}

\begin{document}
\maketitle
\makenomenclature

\section{Introduction}

\dropword Several applications of weakly-ionized plasma technologies for improving the performance of aircraft have recently been the subject of considerable interest.
One possible application is aerodynamic flow control through virtual bodies created by heat deposition using electron beams or another type of external ionizer \cite{jpp:2008:gaitonde,jpp:2008:shneider,jpp:2008:knight}.  Other applications are centered on the force exerted on the airflow due to magnetohydrodynamic interaction (MHD) or electrohydrodynamic interaction (EHD). The EHD interaction (or \emph{ion wind}) is suspected to be one of the mechanisms responsible for the high success of plasma actuators in preventing or delaying boundary layer separation \cite{aiaa:2009:roupassov}, in enhancing jet mixing \cite{aiaa:2008:benard}, in keeping the flow attached on turbine blades \cite{aiaa:2007:rizzetta}, or in controlling the vortices above a delta wing \cite{aiaa:2008:greenblatt}. On the other hand, the MHD interaction could be useful in controlling the inlet flowfield  \cite{aiaa:2002:shang,aiaaconf:2002:shneider}, in imparting momentum to a gas \cite{jpp:2005:parent,jpp:2007:parent}, or in generating electrical power aboard an aircraft through a MHD generator \cite{jpp:2009:fujino,aiaa:2009:wan}.

\subsection{EHD Interaction}
Despite some success using the weakly-ionized plasma technologies, there remain several key physical phenomena that are still not well understood. For instance, it is not clear whether plasma actuators achieve flow control through the EHD interaction or through heating, or how much of the Joule heating losses observed in a MHD generator occur within the plasma sheath. To obtain a better understanding of the physical phenomena, it is desirable to obtain more detailed computational results.
%
\begin{table}[ht]
\fontsizetable
\begin{center}
  \begin{threeparttable}
    \tablecaption{$\epsilon$ and $\sigma$ for some species \tnote{1}}
    \fontsizetable
    \begin{tabular}{lllll}
      \toprule
species$_k$     &  ${\rm He}$    &  ${\rm H}_2$   &  ${\rm O}_2$   &  ${\rm N}_2$  \\
\midrule
$\epsilon_k$ [K]&  $10.22$       &  $59.7$        &  $106.7$       &  $71.4$       \\
$\sigma_k$ [nm] &  $0.2576$      &  $0.2827$      &  $0.3467$      &  $0.3798$     \\
      \bottomrule
    \end{tabular}
    \label{table:species-epssig}
    \begin{tablenotes}
      \item [1] taken from Dixon-Lewis 103 $103$; $T^\star_k=T/ \epsilon_k$
    \end{tablenotes}
  \end{threeparttable}
\end{center}
\end{table}
%

A computational study of plasmas generally requires the coupled solution of the Navier-Stokes equations to obtain the bulk flow properties and of the Maxwell equations to obtain the electric and magnetic field distributions. However, when a plasma is weakly-ionized (that is, when the fraction of the gas molecules that are ionized are in the range $10^{-8}$ to $10^{-2}$) and when the applied magnetic field does not vary in time, it can be shown that the sole solution of the  electric field potential provides a reasonable approximation to the electromagnetic fields.

The discretization of the potential equation has so far been accomplished through second-order accurate centered stencils. This has proven to be a successful strategy. Indeed, the potential equation can be written as a diffusion equation, and the diffusion derivatives can generally be discretized successfully using centered stencils. But, as will be shown in this paper, this discretization approach fails when both the  Hall parameter is high and the gradient of the electrical conductivity is high. In the plasma regions with such characteristics, the centered stencils introduce  spurious oscillations which can lead to severe numerical error. As a remedy for this problem, a new discretization stencil for the potential equation is here proposed. The proposed scheme is consistently monotonic for any value of the Hall parameter and is second-order accurate except in the vicinity of discontinuities.

%
\begin{table*}
  \center\fontsizetable
  \begin{threeparttable}
    \tablecaption{8-species 28-reactions air chemical model. The species consist of $\rm e^-$, $\rm O_2$, $\rm N_2$, $\rm O$, $\rm N$, $\rm O_2^+$, $\rm N_2^+$, $\rm O_2^-$.}
    \label{tab:reactions}
    \fontsizetable
    \begin{tabular}{llll}
    \toprule
    No.&Reaction & Rate Coefficient [1/s or cm$^3$/s or cm$^6$/s] & Reference \\
    \midrule
    1a  & $\rm e^- + N_2   \rightarrow N_2^+ + e^- + e^-$
       &  $10^{-8.3 -36.5/\vartheta}$~cm$^3$/s
       & Ref.\ \cite{book:1991:raizer} \\
    1b  & $\rm e^- + O_2   \rightarrow O_2^+ + e^- + e^-$
       &  $10^{-8.8 -28.1/\vartheta}$~cm$^3$/s
       & Ref.\ \cite{book:1991:raizer} \\
    2a & $\rm e^-+O_2^+ \rightarrow O + O$
       & $2.0 \times 10^{-7} (300/T_{\rm e})^{0.7}  $ cm$^3$/s
       & Ref.\ \cite{misc:1997:aleksandrov}\\
    2b & $\rm e^-+N_2^+ \rightarrow N + N$
       & $2.8 \times 10^{-7} (300/T_{\rm e})^{0.5}  $ cm$^3$/s
       & Ref.\ \cite{misc:1992:kossyi}\\
    3a & $\rm O_2^{-}+N_2^{+} \rightarrow O_2 + N_2$
       & $2.0 \times 10^{-7} (300/T)^{0.5}$ cm$^3$/s
       & Ref.\ \cite{misc:1992:kossyi}\\
    3b & $\rm O_2^{-}+O_2^{+} \rightarrow O_2 + O_2$
       & $2.0 \times 10^{-7} (300/T)^{0.5}$ cm$^3$/s
       & Ref.\ \cite{misc:1992:kossyi}\\
    4a & $\rm O_2^{-}+N_2^{+} + N_2\rightarrow O_2 + N_2 +N_2$
       & $2.0 \times 10^{-25} (300/T)^{2.5}$ cm$^6$/s
       & Ref.\ \cite{misc:1992:kossyi}\\
    4b & $\rm O_2^{-}+O_2^{+} + N_2\rightarrow O_2 + O_2 +N_2$
       & $2.0 \times 10^{-25} (300/T)^{2.5}$ cm$^6$/s
       & Ref.\ \cite{misc:1992:kossyi}\\
    4c & $\rm O_2^{-}+N_2^{+} + O_2\rightarrow O_2 + N_2 +O_2$
       & $2.0 \times 10^{-25} (300/T)^{2.5}$ cm$^6$/s
       & Ref.\ \cite{misc:1992:kossyi}\\
    4d & $\rm O_2^{-}+O_2^{+} + O_2\rightarrow O_2 + O_2 +O_2$
       & $2.0 \times 10^{-25} (300/T)^{2.5}$ cm$^6$/s
       & Ref.\ \cite{misc:1992:kossyi}\\
    5a & $\rm e^- + O_2 +O_2 \rightarrow O_2^- + O_2$
       & $1.4 \times 10^{-29} \frac{300}{T_{\rm e}} \exp \left( \frac{-600}{T}\right)
         \exp \left( \frac{700(T_{\rm e}-T)}{T_{\rm e} T}  \right)$ cm$^6$/s
       & Ref.\ \cite{misc:1992:kossyi}\\
    5b & $\rm e^- + O_2 + N_2 \rightarrow O_2^- + N_2$
       & $1.07 \times 10^{-31} \left( \frac{300}{T_{\rm e}} \right)^2 \exp \left( \frac{-70}{T}\right)
         \exp \left( \frac{1500(T_{\rm e}-T)}{T_{\rm e} T}  \right)$ cm$^6$/s
       & Ref.\ \cite{misc:1992:kossyi}\\
    6  & $\rm O_2^- + O_2 \rightarrow e + O_2 + O_2$
       & $8.6 \times 10^{-10} \exp \left( \frac{-6030}{T}\right)
               \left[1-\exp \left( \frac{-1570}{T} \right)  \right]$ cm$^3$/s
       & Ref.\ \cite{book:1997:bazelyan}, Ch.\ 2\\
    7a  & $\rm O_2 \rightarrow e^- + O_2^+$
       & $2.0 \times 10^{17} ~Q_{\rm b}/N$ 1/s
       & Ref.\ \cite{book:1982:bychkov}\\
    7b  & $\rm N_2 \rightarrow e^- + N_2^+$
       & $1.8 \times 10^{17} ~Q_{\rm b}/N$ 1/s
       & Ref.\ \cite{book:1982:bychkov}\\
    8a  & $\rm O_2 + O_2 \rightarrow 2 O + O_2$
       & $3.7 \times 10^{-8} \exp(-59380/T) [1-\exp(-2240/T)]$ cm$^3$/s
       & Refs.\ \cite{misc:1997:aleksandrov}\\
    8b  & $\rm O_2 + N_2 \rightarrow 2 O + N_2$
       & $9.3 \times 10^{-9} \exp(-59380/T) [1-\exp(-2240/T)]$ cm$^3$/s
       & Refs.\ \cite{misc:1997:aleksandrov}\\
    8c  & $\rm O_2 + O \rightarrow 3 O$
       & $1.3 \times 10^{-7} \exp(-59380/T) [1-\exp(-2240/T)]$ cm$^3$/s
       & Refs.\ \cite{misc:1997:aleksandrov}\\
    8d  & $\rm N_2 + O_2 \rightarrow 2 N + O_2$
       & $5.0 \times 10^{-8} \exp(-113200/T) [1-\exp(-3354/T)]$ cm$^3$/s
       & Refs.\ \cite{misc:1997:aleksandrov}\\
    8e  & $\rm N_2 + N_2 \rightarrow 2 N + N_2$
       & $5.0 \times 10^{-8} \exp(-113200/T) [1-\exp(-3354/T)]$ cm$^3$/s
       & Refs.\ \cite{misc:1997:aleksandrov}\\
    8f  & $\rm N_2 + O \rightarrow 2 N + O$
       & $1.1 \times 10^{-7} \exp(-113200/T) [1-\exp(-3354/T)]$ cm$^3$/s
       & Refs.\ \cite{misc:1997:aleksandrov}\\
    9a  & $\rm O + O + O_2 \rightarrow 2 O_2$
       & $2.45 \times 10^{-31} T^{-0.63}$ cm$^6$/s
       & Refs.\ \cite{misc:1997:aleksandrov}\\
    9b  & $\rm O + O + N_2 \rightarrow O_2+N_2$
       & $2.76 \times 10^{-34} \exp(720/T)$ cm$^6$/s
       & Refs.\ \cite{misc:1997:aleksandrov}\\
    9c  & $\rm O + O + O \rightarrow O_2+O$
       & $8.8 \times 10^{-31} T^{-0.63}$ cm$^6$/s
       & Refs.\ \cite{misc:1997:aleksandrov}\\
    9d  & $\rm N + N + O_2 \rightarrow N_2 + O_2$
       & $8.27 \times 10^{-34} \exp(500/T)$ cm$^6$/s
       & Refs.\ \cite{misc:1997:aleksandrov}\\
    9e  & $\rm N + N + N_2 \rightarrow 2 N_2$
       & $8.27 \times 10^{-34} \exp(500/T)$ cm$^6$/s
       & Refs.\ \cite{misc:1997:aleksandrov}\\
    9f  & $\rm N + N + O \rightarrow N_2 + O$
       & $8.27 \times 10^{-34} \exp(500/T)$ cm$^6$/s
       & Refs.\ \cite{misc:1997:aleksandrov}\\
    9g  & $\rm N + N + N \rightarrow N_2 + N $
       & $8.27 \times 10^{-34} \exp(500/T)$ cm$^6$/s
       & Refs.\ \cite{misc:1997:aleksandrov}\\
    \bottomrule
    \end{tabular}
   \end{threeparttable}
\end{table*}
%

%
\begin{figure}[t]
   \fontsizefigure
   \begin{center}
   \includegraphics[width=0.9\columnwidth]{central.pdf}\\
   (a) Central\\[1.5em]
   \includegraphics[width=0.9\columnwidth]{tvd.pdf}\\
   (b) TVD
   \end{center}
\figurecaption{Comparison of the potential contours (in volts) between the standard 9-point central-difference stencil and the proposed 13-point upwinded stencil.}
\label{fig:potentialcontours}
\end{figure}
%

The electric field potential equation can be obtained from the charged species mass and momentum conservation equations by assuming that the plasma is quasi-neutral and that the terms involving changes in inertia, viscous diffusion, pressure gradients, and collisions between charged particules are negligible compared to the terms involving electromagnetic forces and collisions between a charged particule and a neutral. Such can shown to be valid assumptions as long as the plasma remains weakly-ionized. Then, the potential equation becomes:
%
\begin{equation}
  \sum_i \frac{\partial}{\partial x_i} \sum_j  \wtilde{\sigma}_{ij} \left(\frac{\partial \phi}{\partial x_j}  - \left(\vec{v} \times \vec{B}\right)_j\right) =0
\end{equation}
%
where the  potential is defined such that $\vec{E}_j=-\partial \phi / \partial x_j$ and where the tensorial conductivity corresponds to:
%
\begin{equation}
\wtilde{\sigma}_{ij}=\sum_k |C_k| N_k \mu_k \left[Y_k\right]_{ij}
\end{equation}
%
with the matrix $Y_k$ equal to:
%
\begin{equation}
  Y_k = \left[\begin{array}{ccc}
      1 & -s_k \mu_k \vec{B}_3  &  s_k \mu_k \vec{B}_2 \\
      s_k \mu_k \vec{B}_3 &  1 &  -s_k \mu_k \vec{B}_1 \\
      -s_k \mu_k \vec{B}_2 &  s_k \mu_k \vec{B}_1 & 1  \\
    \end{array} \right]^{-1}
\end{equation}
%
The existence of a potential for the electric field implies steady-state of the magnetic field. This is a reasonable assumption for weakly-ionized flowfields as long as the external magnetic field  does not vary in time. Indeed, the induced magnetic field can be considered negligible for weakly-ionized plasmas because the latter exhibit a low magnetic Reynolds number. For reasons that shall become apparent subsequently, the tensorial conductivity can also be written as a sum of a symmetric matrix and a skew-symmetric matrix:
%
\begin{equation}
  \wtilde{\sigma}=\wtilde{\sigma}^{\rm S} + \wtilde{\sigma}^{\rm SS}
\end{equation}
%
with the symmetric matrix equal to:
%
\begin{equation}
\wtilde{\sigma}^{\rm S}=\sum_k \frac{|C_k| N_k \mu_k}{1+\mu_k^2|\vec{B}|^2}
\left[\begin{array}{ccc}
1+\mu_k^2\vec{B}_1^2
  & \mu_k^2 \vec{B}_1 \vec{B}_2
  & \mu_k^2\vec{B}_1 \vec{B}_3  \alb
\mu_k^2 \vec{B}_1 \vec{B}_2
  & 1+\mu_k^2\vec{B}_2^2
  & \mu_k^2\vec{B}_2 \vec{B}_3  \alb
\mu_k^2\vec{B}_1 \vec{B}_3
  & \mu_k^2\vec{B}_2 \vec{B}_3
  & 1+\mu_k^2\vec{B}_3^2
\end{array}
\right]
\end{equation}
%
and the skew-symmetric matrix equal to:
%
\begin{equation}
\wtilde{\sigma}^{\rm SS}=\sum_k \frac{|C_k| N_k \mu_k}{1+\mu_k^2|\vec{B}|^2}
\left[\begin{array}{ccc}
0
 & s_k \mu_k  \vec{B}_3
 & -s_k \mu_k   \vec{B}_2 \alb
-s_k \mu_k  \vec{B}_3
 & 0
 &  s_k \mu_k \vec{B}_1 \alb
s_k \mu_k \vec{B}_2
 & -s_k \mu_k \vec{B}_1
 & 0
\end{array}
\right]
\end{equation}
%
Then, after substituting the latter in the electric field potential equation, the following is obtained:
%
\begin{equation}
  \sum_i \frac{\partial}{\partial x_i} \sum_j   \left((\wtilde{\sigma}_{ij}^{\rm S}+\wtilde{\sigma}_{ij}^{\rm SS})\frac{\partial \phi}{\partial x_j}  - \wtilde{\sigma}_{ij}\left(\vec{v} \times \vec{B}\right)_j\right) =0
\end{equation}
%
It can be easily shown that the term function of the skew-symmetric conductivity tensor can be rewritten to:
%
\begin{equation}
\begin{array}{l}
\mfd\sum_i \frac{\partial}{\partial x_i} \sum_j \wtilde{\sigma}_{ij}^{\rm SS} \frac{\partial \phi}{\partial x_j} =
 \sum_i \sum_j     \frac{\partial }{\partial x_j}\left(\frac{\partial \wtilde{\sigma}_{ij}^{\rm SS}}{\partial x_i} \phi\right) \alb\mfd
~~~~
- \phi \sum_i \sum_j \frac{\partial^2 \wtilde{\sigma}_{ij}^{\rm SS}}{\partial x_i \partial x_j}
+\sum_i \sum_j \wtilde{\sigma}_{ij}^{\rm SS}     \frac{\partial^2 \phi}{\partial x_j \partial x_i}
\end{array}
\end{equation}
%
The last two terms on the RHS will always be zero due to the commutativity of differentiation and due to the matrix $\wtilde{\sigma}^{\rm SS}$ being skew-symmetric and having diagonal elements equal to zero. Then, the electric field potential equation collapses to:
%
\begin{equation}
\sum_i \frac{\partial}{\partial x_i}   \sum_j   \left(\wtilde{\sigma}_{ij}^{\rm S}\frac{\partial \phi}{\partial x_j}  - \wtilde{\sigma}_{ij}\left(\vec{v} \times \vec{B}\right)_j\right)
+ \sum_i \sum_j     \frac{\partial }{\partial x_j}\left(\frac{\partial \wtilde{\sigma}_{ij}^{\rm SS}}{\partial x_i} \phi\right)
=0
\end{equation}
%
By substituting the $i$ and $j$ indices of the last term on the LHS and defining the wave speed associated with the skew-symmetric terms as
%
\begin{equation}
  a_i^{\rm SS} \equiv -\sum_j \frac{\partial \wtilde{\sigma}_{ji}^{\rm SS}}{\partial x_j}
\end{equation}
%
%
\begin{figure*}[t]
   \fontsizefigure
   \begin{center}
   \includegraphics[width=0.9\columnwidth]{central.pdf}
   ~~~~
   \includegraphics[width=0.9\columnwidth]{tvd.pdf}
   \end{center}
\figurecaption{Comparison of the potential contours (in volts) between the standard 9-point central-difference stencil and the proposed 13-point upwinded stencil.}
\label{fig:potentialcontours2}
\end{figure*}
%
the potential equation becomes:
%
\begin{equation}
\sum_i \frac{\partial}{\partial x_i}   \sum_j   \left(\wtilde{\sigma}_{ij}^{\rm S}\frac{\partial \phi}{\partial x_j}  - \wtilde{\sigma}_{ij}\left(\vec{v} \times \vec{B}\right)_j\right)
- \sum_i     \frac{\partial }{\partial x_i}\left(a_i^{\rm SS} \phi\right)
=0
\end{equation}
%
Interestingly, the skew-symmetric diffusion terms can be seen to collapse to a convection-like derivative, with the wave speed being proportional to the gradient of the conductivity.

\section{Discretization of the Potential Equation ($\phi$)}

The electric field potential equation can  be expressed in discrete form as:
%
\begin{equation}
\sum_i \delta_{x_i}   \sum_j   \left(\wtilde{\sigma}_{ij}^{\rm S} \delta_{x_j} \phi  - \wtilde{\sigma}_{ij}\left(\vec{v} \times \vec{B}\right)_j\right)
- \sum_i     \delta_{x_i}\left(a_i^{\rm SS} \phi\right)
=0
\end{equation}
%
Because central differences cannot be used to discretize a convection derivative without introducing even-odd discoupling of the properties, it is necessary to use an upwinded stencil to discretize the
last derivative to prevent spurrious oscillations from forming.
Therefore, in conservative form on a uniformly-spaced mesh, the discretization stencil of the skew-symmetric terms is set to:
%
%
\begin{equation}
\left[\delta_{x_i}\left( a_i^{\rm SS} \phi \right)\right]^{X_i} = \frac{\left( a_i^{\rm SS} \phi \right)^{X_i+\frac{1}{2}}-\left( a_i^{\rm SS} \phi \right)^{X_i-\frac{1}{2}}} {\Delta x_i}
\end{equation}
%
with the flux at the interface discretized using an upwinded stencil combined with a symmetric minmod TVD limiter \cite{jcp:1990:yee}:
%
\begin{equation}
\begin{array}{l}
\mfd
\left( a_i^{\rm SS} \phi \right)^{X_i+\frac{1}{2}}
=
\frac{1}{2}
\left(a_i^{\rm SS} \phi\right)^{X_i}
+
\frac{1}{2}
\left(a_i^{\rm SS} \phi\right)^{X_i+1}
\alb\mfd~~~~~~-\frac{1}{2}\left|a_i^{\rm SS}\right|^{X_i+\frac{1}{2}}\Delta\phi^{X_i+\frac{1}{2}}
\alb\mfd~~~~~~+\frac{1}{2}{\left|a_i^{\rm SS}\right|}^{X_i+\frac{1}{2}}~~{\rm minmod}\left(\Delta\phi^{X_i-\frac{1}{2}},~\Delta\phi^{X_i+\frac{1}{2}},~\Delta\phi^{X_i+\frac{3}{2}}
  \right)
\end{array}
\end{equation}
%
with $\Delta\phi^{X_i+\frac{1}{2}}\equiv\phi^{X_i+1}-\phi^{X_i}$ and where the minmod function returns the minimum of its arguments if the arguments are all positive, the maximum if the arguments are all negative, and zero if the arguments are of mixed signs. Such a stencil is monotonicity-preserving while being second-order accurate in regions where the properties vary smoothly.
The other diffusion terms can be discretized with centered stencils as they do not pose any problem:
%
\begin{equation}
\left[ \delta_{x_i}    \left(\wtilde{\sigma}_{ij}^{\rm S} \delta_{x_j} \phi\right)\right]^{X_i}
=\frac{\left(\wtilde{\sigma}_{ij}^{\rm S} \delta_{x_j} \phi \right)^{X_i+\frac{1}{2}}-\left( \wtilde{\sigma}_{ij}^{\rm S} \delta_{x_j} \phi \right)^{X_i-\frac{1}{2}}} {\Delta x_i}
\end{equation}
%
where the flux at the interface would correspond to, when $i=j$:
%
\begin{equation}
\left(\wtilde{\sigma}_{ij}^{\rm S} \delta_{x_j} \phi \right)^{X_i+\frac{1}{2}}
=
\left(\wtilde{\sigma}_{ii}^{\rm S}\right)^{X_i+\frac{1}{2}}
\frac{
\phi^{X_i+1}-\phi^{X_i}
}{
\Delta x_i
}
\end{equation}
%
and to, when $i\ne j$:
%
\begin{equation}
\begin{array}{l}
\mfd\left(\wtilde{\sigma}_{ij}^{\rm S} \delta_{x_j} \phi \right)^{X_i+\frac{1}{2}}
=
\left(\wtilde{\sigma}_{ij}^{\rm S}\right)^{X_i+\frac{1}{2},X_j}
\alb\mfd
~~~~~\times\frac{
\phi^{X_i,X_j+1}+\phi^{X_i+1,X_j+1}-\phi^{X_i,X_j-1}-\phi^{X_i+1,X_j-1}
}{
4 \Delta x_j
}
\end{array}
\end{equation}
%

\section{Test Cases}

While the numerical method outlined above is written in general form and is applicable to plasmas in which both electrons and ions can carry current, the test case here presented is limited for simplicity to a plasma in which the current is carried solely by the electrons. Then, the symmetric conductivity matrix simplifies to:
%
\begin{equation}
  \wtilde{\sigma}^{\rm S}\rightarrow \frac{\sigma}{1+\beta_{\rm e}^2}\left[
\begin{array}{ccc}
 1+\beta_{\rm e}^2 \bar{\vec{B}}_1^2
 &  \beta_{\rm e}^2\bar{\vec{B}}_1 \bar{\vec{B}}_2
 &  \beta_{\rm e}^2\bar{\vec{B}}_1 \bar{\vec{B}}_3 \alb
 \beta_{\rm e}^2\bar{\vec{B}}_1 \bar{\vec{B}}_2
 &  1+\beta_{\rm e}^2\bar{\vec{B}}_2^2
 &  \beta_{\rm e}^2\bar{\vec{B}}_2 \bar{\vec{B}}_3 \alb
 \beta_{\rm e}^2\bar{\vec{B}}_1 \bar{\vec{B}}_3
 &  \beta_{\rm e}^2\bar{\vec{B}}_2 \bar{\vec{B}}_3
 &  1+\beta_{\rm e}^2\bar{\vec{B}}_3^2
\end{array}
\right]
\end{equation}
%
and the skew-symmetric matrix becomes:
%
\begin{equation}
  \wtilde{\sigma}^{\rm SS}\rightarrow \frac{ \sigma }{1+\beta_{\rm e}^2}\left[
\begin{array}{ccc}
0
 & -\beta_{\rm e}\bar{\vec{B}}_3
 & \beta_{\rm e}\bar{\vec{B}}_2 \alb
   \beta_{\rm e}\bar{\vec{B}}_3
 & 0
 & -\beta_{\rm e}\bar{\vec{B}}_1 \alb
-\beta_{\rm e}\bar{\vec{B}}_2
 & \beta_{\rm e}\bar{\vec{B}}_1
 & 0
\end{array}
\right]
\end{equation}
%
From the latter, it is apparent that the skew symmetric terms are negligible when the Hall parameter is much less than unity. Additionally, as was  shown in the previous section, the skew symmetric terms collapse to zero when there is no gradient of the conductivity.
Therefore, in order to test adequately the proposed discretization scheme,  the Hall parameter and the conductivity gradient are here set sufficiently high that the skew-symmetric terms  predominate over the symmetric terms.

The  test case consists of a two-dimensional domain with Dirichlet boundary conditions:
%
\begin{equation}
 \phi_{x=0}=20~{\rm V},~~\phi_{x=1\,{\rm m}}=20~{\rm V}
,~~\phi_{y=0}=10~{\rm V},~~\phi_{y=1\,{\rm m}}=40~{\rm V}
\end{equation}
%
with the Hall parameter  fixed to 20, the bulk gas velocity to zero, and the conductivity such that it exhibits a strong gradient in some regions of the domain:
%
\begin{equation}
\sigma=
\left\{
\begin{array}{ll}
 1.0~{\rm S/m}&{\rm for~}0.25~{\rm m} \le x \le 0.75~{\rm m}\alb
 0.0001~{\rm S/m}&{\rm otherwise}
\end{array}
\right.
\end{equation}
%
Even thus the gradient of the conductivity is high and  the Hall parameter is high, spurious oscillations may still not occur. Indeed, the skew-symmetric terms may  become  negligible for certain orientations of the magnetic field vector. It can be easily shown that this would occur when the magnetic field vector lies within the plane made by the potential gradient vector and the conductivity gradient vector. For this reason and because it is desired to test the monotonicity-preserving capability of the proposed scheme under the most stringent conditions, the normalized magnetic field vector is here fixed perpendicular to the computational domain:
%
\begin{equation}
\bar{B}=(0,~0,~1)
\end{equation}
%
The mesh is made of 50 grid lines along each dimension and the solution is advanced iteratively using an implicit approximate factorization algorithm until convergence is attained. The solution is considered converged when the discrete residual on all nodes falls below a given threshold typically set to $10^{-3}$. This is verified to be sufficiently small to yield potential contours that are visually indistinguishable from those obtained using a residual convergence threshold set to machine tolerance (about $10^{-13}$).

A comparison between the potential contours obtained with the standard 9-point central-difference stencil and the proposed 13-point upwinded stencil is shown in Fig.\ \ref{fig:potentialcontours}. As expected, the use of the standard central-difference stencil is seen to introduce severe spurrious oscillations of the electric field potential in the regions where the gradient of the conductivity is high. Such aphysical oscillations of the potential are completely removed when the upwinded stencil is used.
 While not shown here for brevity, several other test cases confirm the monotonicity-preserving capability and second-order accuracy of the proposed method.

\section{Conclusions}

There are two significant results of the research described in this paper. First, only a small range of values for the cross-diffusion coefficient $\sigma_d$ exists that yields satisfactory spreading rates for free shear flows.
The discretization of the electric field potential equation is here demonstrated to require the use of upwinded stencils in order to yield a solution free of spurrious oscillations. The use of upwinded stencils is seen to be necessary when the skew-symmetric terms part of the tensor conductivity matrix predominate over the other terms. This is shown to be the case when three conditions are met: (i) the Hall parameter is high, (ii) the conductivity exhibits a significant spatial gradient, and (iii) the magnetic field vector has a component perpendicular to both the potential gradient vector and the conductivity gradient vector.

A new discretization stencil for the potential equation is here proposed, spanning 13 grid points in 2D and 33 grid point in 3D. The stencil consists of a minmod TVD upwinded scheme for the skew-symmetric terms and a central difference stencil for the other terms. The proposed method is monotonicity-preserving  and, in regions where the properties vary smoothly, reaches second-order accuracy. Several test cases were performed to evaluate the performance of the proposed method compared to the standard central-difference scheme. In all cases, including those with the most stringent conditions, the use of the proposed method results in a complete removal of the aphysical oscillations.

\appendix
\section{Appendix Test}

The proposed upwinded stencil  is recommended for all flow problems in which the electric field potential equation is solved in coupled form with the Navier Stokes equations, irrespectively of the value of the average Hall parameter. Indeed, even if the Hall parameter remains low on average, it can attain values well exceeding unity in some flow regions due to Joule heating or some other phenomenon decreasing locally the gas density (on which the Hall parameter inversely depends).
%
\begin{equation}
a=b+c
\end{equation}
%

\bibliography{all}
\bibliographystyle{aiaa}

    \end{document}


\documentclass[simplex.tex]{subfiles}
% NO NEED TO INPUT PREAMBLES HERE
% packages are inherited; you can compile this on its own

\onlyinsubfile{
\title{NeuroData SIMPLEX Report: Subfile}
}

\begin{document}
\onlyinsubfile{
\maketitle
\thispagestyle{empty}

The following report documents the progress made by the labs of Randal~Burns and Joshua~T.~Vogelstein at Johns Hopkins University towards goals set by the DARPA SIMPLEX grant.

%%%% Table of Contents
\tableofcontents

%%%% Publications
\bibliographystyle{IEEEtran}
\begin{spacing}{0.5}
\section*{Publications, Presentations, and Talks}
%\vspace{-20pt}
\nocite{*}
{\footnotesize	\bibliography{simplex}}
\end{spacing}
%%%% End Publications
}

\subsection{FlashY}

FlashY is created to encapsulate the R packages created for
multiple-graph processing and clustering.

When multiple graphs are involved, the dimensionality problem becomes
more challenging -- since each graph is a matrix, stacking multiple
graphs leads to a 3-dimensional array referred as tensor. There has been
little research in handling this type of data in the network data
domain. A dimension reduction toolbox, to be used in R, has been created
to convert each adjacency matrix into a small vector, while retaining
most of the variability across subjects. We tested, as shown in Figure
\ref{fig:flashy}, the classification performance using sex as outcome
labels and brain network as input, the low dimensional vector produced
indistinguishably good performance as the large network data.

\begin{figure}[h!]
\begin{cframed}
\centering
\includegraphics[width=0.75\textwidth]{./figs/flashY.png}
\caption{
View of the low-dimensional vectors from 46 subjects, dimension is
reduced from 4,900 to only 30 for each subject.
}
\label{fig:flashy}
\end{cframed}
\end{figure}

We consider improving the stability in clustering objects. When the
sample size is low but there is large variability due to the high
dimension, the inferences based on the existing clustering methods
(k-means, Gaussian mixture model, etc.) tend to produce large error.
This problem is critical and common in graph clustering, as the number
of graphs is typically low but the number of vertices is high. To solve
this, a new clustering method, namely ``jk-means'' is developed in R.
With a truncation, substantial error reduction can be obtained via the
bias-variance tradeoff. Shown in the figure, the new jk-means clustering
tool (red) produces significantly better result than the other models.

\begin{figure}[h!]
\begin{cframed}
\centering
\includegraphics[width=0.75\textwidth]{./figs/jkmeans.png}
\caption{
Illustration of the jk-means, compared with Gaussian Mixture Model (j=5). The j=1 jk-means model (red) has significantly lower error compared to the others, when the sample size is smaller than 500.
}
\label{fig:jkmeans}
\end{cframed}
\end{figure}

\end{document}


    \filetitle{nnznonlin}{Number of non-linearised data points}{plan/nnznonlin}

	\paragraph{Syntax}\label{syntax}

\begin{verbatim}
N = nnznonlin(P)
\end{verbatim}

\paragraph{Input arguments}\label{input-arguments}

\begin{itemize}
\itemsep1pt\parskip0pt\parsep0pt
\item
  \texttt{P} {[} plan {]} - Simulation plan.
\end{itemize}

\paragraph{Output arguments}\label{output-arguments}

\begin{itemize}
\itemsep1pt\parskip0pt\parsep0pt
\item
  \texttt{N} {[} numeric {]} - Number of non-linearised equations.
\end{itemize}

\paragraph{Description}\label{description}

\paragraph{Example}\label{example}


\chapter{Results}
\label{results}
%[inline]{tons of pictures. easy pictures, hard pictures, why they're hard}
%DONE{methodology section, like how neural networks were used, opencv section in methodology. cpu and clock speed and rate of processing}

\section{Methodology}

%Opencv/environment/language
\subsection{Environment}
This project was done entirely in OpenCV 3.0 using their C++ libraries. The computer used for this project was running Windows 8.1 on a Intel i5-2500K CPU with a maximum clock speed of 4.1 GHz. The OpenCV libraries are widely used and support a large amount of languages and platforms, including Apple iOS, Android, OpenCL, CUDA, as well as Mac, Linux and PC, which means that the code is easily ported to most any platform \cite{OpenCVPlatforms}. The input images were all read from saved video files on disk, and fed one by one into this project's algorithm.

%what data was used, where it came from, what was trained, etc.
\subsection{Dataset}
%JeneePlz
The data used for the results were a selection of videos from multiple white crosswalks and streets without crosswalks taken at and around street intersections. The videos were taken at multiple times of day ranging from early morning to early night. For each crosswalk, five videos were taken going the same direction across the crosswalk. The videos were a high angle, a low angle, walking on the left side, on the right side, and a walking in the center.  Videos were given categories: time of day, angle of video, type of crosswalk, color, crosswalk title, etc. Crosswalks were marked to be used only for training the neural network, and other crosswalks marked only to be used for evaluating results. The training set contained three hybrid crosswalks, six zebra crosswalks, and ten videos that did not include crosswalks. The result testing set contained three hybrid crosswalks, nine zebra crosswalks, and eighteen videos that did not include crosswalks. All data in the results section is generated from videos that were never used in the training process of the neural network. Over 14,000 stripelets were marked by hand as part of a crosswalk or not part of a crosswalk for use when training the neural network, and over 18,000 manually marked stripelets were used for the output. Each crosswalk video only used 20 frames, whereas videos without crosswalk may have used more. Hybrid crosswalks were included as well because they were working with the algorithm as well.

%How Neural Networks are used here (explain some of the experimentation around different layers, and how they didn't do much)
\section{Neural Network Configuration}
%Jeneeplz
For this project, neural networks are used for the prediction of stripelets as either being part of a crosswalk or not. Neural networks require a set number of hidden layers with a set number of neurons, so some experimentation was done to determine these numbers. As shown in figure \ref{fig:Neural1png}, for this project, the final result was one hidden layer of 14 neurons. A supervised feedforward network trained using backpropagation was used for this project. This neural network configuration is one of the simpler configurations, and remains very effective. An unsupervised neural network configuration would not be as optimal for this same exact data because the outputs are known, allowing a supervised method to train more efficiently. A larger training set would likely be required for an unsupervised network.

%D:\Users\SandyBridge\Dropbox\Thesis\My Paper Stuff\Results\Results of NN Training with diff neurons.xlsx
%    \begin{table}[t]
%%        \begin{longtable}{| r | r | r | r |}
 %       \hline
 %       Neurons in Hidden Layer & True Positive Rate & False Positive Rate & q-value \bigstrut\\
 %       \hline
 %       15 & 74.42\% & 2.36\% & 0.086 \bigstrut\\
 %       \hline
 %       \caption[Selected Neural Network Configuration Results]{Stripelet identification results from neural network training with selected hidden layer configuration}
 %       \label{tab:NN-HiddenLayersResults}
 %       \end{longtable}
 %   \end{table}

 %TODO

There is no real consensus on exactly how many hidden layers and neurons should be used in the perfect neural network configuration. The different rules of thumb have been that no more than one hidden layer is typically needed, and the number of neurons should be between the number of inputs and the number of outputs, and layers must have more than one neuron\cite{Heaton:2008:INN:1502373}. With those being the guidelines, one hidden layer with a number of neurons mostly ranging from the number of inputs to the number of outputs was chosen with a range from 2 to 22 neurons in the hidden layer. Subsets of these training parameters were tried as well, with none having better results than using all eleven parameters.

The neural network training of the crosswalk stripelets used many different input parameters to predict the output. The metric used for evaluating the parameters was finding the true positive and false negative rates, as well as the false discovery rate (also known as q-value). The true positive rate is calculated by dividing the number of crosswalk stripelets that were predicted correctly as stripelets over the total number of crosswalk stripelets. The false positive rate is calculated by dividing the number of non-crosswalk stripelets predicted as stripelets out of the total number of non-crosswalk stripelets. The q-value is found by dividing the number of false positives by the number of stripelets that were predicted to be part of a crosswalk. Table \ref{tab:nnresultsoverall} shows the neural network prediction rates over the entire result set. Only 16.6\% of the positively predicted stripelets were incorrect.

As shown in appendix table \ref{tab:NN-HiddenLayersResultsAPP}, some configurations were better than others, but none by much. The configuration with the 14 neuron hidden layer had the lowest false positive rate of 3.12\%, so it was chosen as the configuration to be used for the rest of this project. This fits with the original assumption that the number of neurons should be between the number of inputs and outputs as shown in figure \ref{fig:Neural1png}.

\begin{figure}[t]
\begin{center}
\includegraphics[width=10cm]{figures/ChosenNN3Small.png}
\captionfonts
\caption{Final neural network configuration showing input layers, hidden layers, and output layers}
\label{fig:Neural1png}
\end{center}
\end{figure}

    \begin{table}[t]
        \begin{longtable}{|r|r|r|r|}
        \caption{Neural Network results over stripelets in final dataset}
        \label{tab:nnresultsoverall}\\
        \hline
        Number of Stripelets & True Pos Rate & False Pos Rate & Q-Val \bigstrut\\
        \hline
        19461 & 77.61\% & 3.57\% & 0.1663 \bigstrut\\
        \hline
        \end{longtable}
    \end{table}

\clearpage

\section{Crosswalk Detection}
Once the neural network has finished culling stripelets, the remaining stripelets are then fed through the crosswalk detection algorithm. The results are again categorized by type of crosswalk, time of day, etc.

\clearpage

\subsection{Effect of Different Video Angles}

There were five different angles used for the videos of the crosswalks, with 340 frames of video at each angle across many crosswalks. Examples of each angle are shown in figure \ref{fig:AllFiveAngles}. The low angle had worse correct prediction rates than the others, as shown in table \ref{tab:downbad}. The reason for this is that the cell phone camera was angled too low to capture enough stripelets for a positive identification. A few examples are given in figure \ref{fig:downBadPic}. The poor results from the bad video angle show that in an actual use case, that angle must be disallowed. The user could be trained to hold the cell phone camera at the proper angle, and if they did not, the sensors would allow the application to notify the user to adjust the camera angle. Because of this, the videos taken at that downward angle will be removed from the overall dataset.

\begin{figure}[t]
\begin{center}
\includegraphics[width=15cm]{figures/DownBad.png}
\captionfonts
\caption{Examples of the low angle video that garnered poor results}
\label{fig:downBadPic}
\end{center}
\end{figure}

\begin{figure}[t]
\begin{center}
\includegraphics[width=15cm]{figures/AllFiveAngles.png}
\captionfonts
\caption{All five angles which videos were taken of the crosswalks. Left to right: (a) Low Angle (b) Left Side (c) Standard (d) Right Side (e) High Angle}
\label{fig:AllFiveAngles}
\end{center}
\end{figure}

\begin{table}[t]
    \begin{longtable}{|r|r|r|}
    \caption{Results of crosswalk detection categorized by video angle}
    \label{tab:downbad}\\

    \hline
    Camera Angle & True Positive Rate & False Positive Rate \bigstrut\\
    \hline
    Low Angle & 45.67\% & 0.00\% \bigstrut\\
    \hline
    Left Side & 77.00\% & 1.00\% \bigstrut\\
    \hline
    Standard & 77.00\% & 0.33\% \bigstrut\\
    \hline
    Right Side & 76.67\% & 1.33\% \bigstrut\\
    \hline
    High Angle & 73.33\% & 0.00\% \bigstrut\\
    \hline
    \end{longtable}
\end{table}

\clearpage

\subsection{Effect of Time of Day}
Each crosswalk was categorized by time of day, morning, midday and night, to see if that had any effect on the prediction rates. The results are shown in table \ref{tab:timeofday}. There were 300 crosswalk frames for each different time of day. The results for each time of day were rather close together, with a slight increase for morning. This might have to do with the lighting causing the image to be more easy to categorize during the morning hours. This data shows that different lighting caused by different time of day did not seem to be a strong factor in the results.

\begin{table}[t]
    \begin{longtable}{|r|r|r|}
    \caption{Results of crosswalk detection categorized by time of day}
    \label{tab:timeofday}\\
    \hline
    Time of Day & True Positive Rate & False Positive Rate \bigstrut\\
    \hline
    Morning & 79.09\% & 2.91\% \bigstrut\\
    \hline
    Midday & 75.00\% & 2.05\% \bigstrut\\
    \hline
    Night & 75.44\% & 1.90\% \bigstrut\\
    \hline
    \end{longtable}
\end{table}

\subsection{Zebra Crosswalk Versus Hybrid Crosswalk}

The true positive percent results of zebra stripe and hybrid crosswalks detection are shown in table \ref{tab:typeOfCwalk}. There were nine zebra stripe crosswalks in the dataset, and six hybrids. The least accurately predicted crosswalk was in the hybrid dataset, leading to a much higher standard deviation. The zebra crosswalks were predicted more consistently, leading to a lower standard deviation and higher true positive percents. The training data was biased towards zebra crosswalks, with three hybrids trained versus nine zebra crosswalks. As shown in the table \ref{tab:typeOfCwalk}, the zebra crosswalk median true positive rate only dropped about 3\%, with the introduction of the neural network, while the hybrid median dropped almost 24\% after neural network application. The hybrid crosswalks observed in the area these videos were taken appeared to more frequently have paint irregularities than the zebra crosswalks, as shown in Figure \ref{fig:poorlyPaintedHybrid}, potentially due to different maintenance practices by the municipality, which could also explain the discrepancy. One of the neural network parameters regarding the pixel intensity of the area surrounding the stripelet would also be different for hybrid versus zebra, because hybrids would have a higher value due to the white lines on the sides being part of their surroundings. It is likely that adding more hybrid crosswalks to the training dataset would improve their results.

\begin{figure}[t]
\begin{center}
\includegraphics[width=10cm]{figures/PoorlyPaintedHybrid.png}
\captionfonts
\caption{Poorly painted hybrid crosswalk}
\label{fig:poorlyPaintedHybrid}
\end{center}
\end{figure}

\clearpage

\begin{table}[t]
    \begin{longtable}{|r|r|r|r|r|r|r|}
    \caption{True positive percent results of crosswalk detection categorized by type of crosswalk}
    \label{tab:typeOfCwalk}\\
    \hline
    Type  & \multicolumn{1}{l|}{Neural Network Enabled} & Min   & Avg   & Median & Max   & STD \bigstrut\\
    \hline
    Hybrid & YES   & 0.00\% & 57.92\% & 62.50\% & 85.00\% & 30.68\% \bigstrut\\
    \hline
    Hybrid & NO    & 15.00\% & 76.46\% & 86.25\% & 98.75\% & 31.18\% \bigstrut\\
    \hline
    Zebra & YES   & 52.50\% & 88.06\% & 95.00\% & 98.75\% & 15.30\% \bigstrut\\
    \hline
    Zebra & NO    & 62.50\% & 92.22\% & 97.50\% & 100.00\% & 11.85\% \bigstrut\\
    \hline
    \end{longtable}
\end{table}

\subsection{Effects of Crosswalk Traversal on Accuracy}

As the user walks across the crosswalk, the view of the crosswalk changes and the algorithm needs to continue guiding them. For each crosswalk, 20 frames equidistant throughout the video were used. The expected result of this is that there would be a decrease in true positive rate as the user progresses because there will be fewer stripelets in the image to work with. The data shown in figure \ref{fig:graphOfFrameCount} shows exactly that. The neural network made the rate go down as one would expect, but the drop seemed to increase as the end of the crosswalk was reached. This may be because the training data may be more biased to earlier frames, since the early frames are guaranteed to have more stripelets. In figure \ref{fig:NumStripeletsvsRates}, we can also see that the number of stripelets in each image as the video went on became fewer as the user crossed the crosswalk, but the predictions of the stripelets stayed mostly consistent throughout.

\begin{figure}[t]
\begin{center}
\includegraphics[width=10cm]{figures/FrameResultsGraph.png}
\captionfonts
\caption{True positive results grouped by frame of video (frame 1 to frame 20) as crosswalk is traversed}
\label{fig:graphOfFrameCount}
\end{center}
\end{figure}

\begin{figure}[t]
\begin{center}
\includegraphics[width=12cm]{figures/NumStripeletsvsRates.png}
\captionfonts
\caption{True and false positive results grouped by frame of video and showing number of detected stripelets (frame 1 to frame 20)}
\label{fig:NumStripeletsvsRates}
\end{center}
\end{figure}

\clearpage

\subsection{Per Crosswalk Analysis of Results}

For this section, the crosswalk videos were grouped by their respective crosswalks, and the non-crosswalk videos were kept as separate groups. The results of this are shown in the appendix tables \ref{tab:appendixcrosswalkresults} and \ref{tab:appendixcrosswalkresultswithoutNeural}, and the summary results are shown in table \ref{tab:crosswalkResultsSummary}. Crosswalks have both true and false positive rates depending on whether they were predicted as being a crosswalk by correct reasoning or not. Videos not containing a crosswalk only have false positives because they cannot contain a crosswalk.  There were a couple outliers in each category (crosswalk vs not) that are included in the dataset, and will be investigated in a later section.

Overall, the average true positive rate of the crosswalk videos was 76\% $\pm$ 13.42\% with a standard deviation of 26.52\%. The average false positive rate of crosswalk images was 0.59\% $\pm$ .64\% with a standard deviation of 1.26\%. The average false positive rate of the non-crosswalk videos was 1.67\% $\pm$ 1.75\% with a standard deviation of 3.45\%.
The true positive predictions of crosswalks had a rather high standard deviation, which was heavily affected by the one outlier crosswalk, and the false positives were more tightly grouped with a lower standard deviation.

\begin{table}[t]
    \begin{longtable}{|r|r|r|r|r|r|r|}
    \caption[Results summary by video/crosswalk]{Results summary by video/crosswalk. Crosswalks have true and false positives, while non-crosswalk videos only have false positives}
    \label{tab:crosswalkResultsSummary}\\
    \hline
          & Cwalk & Minimum & Average & Median & Maximum & STD \bigstrut\\
    \hline
    True Pos Rates & YES   & 0.00\% & 76.00\% & 82.50\% & 98.75\% & 26.52\% \bigstrut\\
    \hline
    False Pos Rates & YES   & 0.00\% & 0.59\% & 0.00\% & 3.75\% & 1.26\% \bigstrut\\
    \hline
    False Pos Rates & NO    & 0.00\% & 1.67\% & 0.00\% & 12.00\% & 3.45\% \bigstrut\\
    \hline
    \end{longtable}
\end{table}

\subsection{Yellow Crosswalks}

In order to determine how well yellow crosswalks worked with white crosswalk training data, two yellow crosswalks were tested, one being a standard zebra and the other a hybrid. The hybrid scored 24\% true positive rate, and the zebra scored 66\%, both out of 80 frames. Those results are promising enough to conclude that yellow crosswalks will likely work well with this approach, and would probably improve with yellow crosswalks being included in the training data, due to the differing intensity values between the two colors affecting neural network parameters.

\subsection{Challenging Images and Analysis}

The video with the highest amount of false positives (12\%) was `NonC Output Night 13,' which was a street being crossed not at an intersection, and with bike lanes going across both sides. The bike lanes and sidewalk were incorrectly matched together, which ended up passing the neural network and the validation as a crosswalk. A couple examples are shown in figure \ref{fig:worstFalsePosPic}, one can see the identified stripelets. More neural network parameters may be able to help remove these from the stripelet set, perhaps something relating to the vertical pixel intensity.

\begin{figure}[t]
\begin{center}
\includegraphics[width=10cm]{figures/NonCWorstCwalk.png}
\captionfonts
\caption{Example frames from 'NonC Output Night 13,' the video with the highest amount of false positives}
\label{fig:worstFalsePosPic}
\end{center}
\end{figure}

Another video with a high amount of false positives (6.67\%) was `NonC Output Night 11,' which is a of a parking lot with many horizontal lines painted throughout.  A few pictures are shown in figure \ref{fig:2ndworstFalsePosPic}. These examples aren't typically what one would expect to see if they were trying to cross the street, but they are lines that look similar to a zebra crosswalk. They could potentially be filtered out by using some sort of expected width vs Y axis level in the image.

\begin{figure}[t]
\begin{center}
\includegraphics[width=14cm]{figures/NonC2ndWorstCwalk.png}
\captionfonts
\caption{Example frames from 'NonC Output Night 11,' the video with the second highest amount of false positives}
\label{fig:2ndworstFalsePosPic}
\end{center}
\end{figure}

One crosswalk specifically had the worst results by far, 'Night hybrid 3,' shown in figure \ref{fig:worstcwalk}. None of the eighty frames were correctly identified in this crosswalk, whereas the next lowest crosswalk had 53\% of frames correctly identified. The neural network failed to correctly identify enough stripelets in the majority of the images to pass the crosswalk validation. This crosswalk had very odd pavement coloring, which may have contributed to why it failed the neural network.  Potentially this issue could be solved by adding more training data and including more odd crosswalks such as this one.

\begin{figure}[t]
\begin{center}
\includegraphics[width=14cm]{figures/WorstCwalk.png}
\captionfonts
\caption{Example frames from 'Night hybrid 3,' the crosswalk with the worst true positive rate}
\label{fig:worstcwalk}
\end{center}
\end{figure}

\clearpage

\subsection{Overall Results}
%\todo[inline]{JASON - Add another evaluation metric here}
Over all of the videos, including 1200 crosswalk frames and 970 non-crosswalk frames, and using the neural network to cull stripelets before detection, a q-value of .021 is obtained for crosswalk predictions. When not using the neural network to cull the stripelets, the q-value is .200 (see table \ref{tab:overallresults}). Using the neural network garners an improvement of 933\% of this value. In simpler terms, using neural networks, out of 1000 positively predicted images, only 21 would be false positives versus 200 without using the neural predictions. Figure \ref{fig:CrosswalkTruePosWithAndWithout} shows that for every video, the neural network does drop the positive identifications, but figure \ref{fig:VideoFalsePosWithAndWithout} shows that false positive rates dropped drastically as well for every single case.

\begin{table}[t]
    \begin{longtable}{|r|r|r|r|}
    \caption{Results of crosswalk detection with/without neural networks. Improvement of 937\% in q-value}
    \label{tab:overallresults}\\
    \hline
    \multicolumn{1}{|c|}{Neural Network Enabled} & True Positive Rate & False Positive Rate & q-value \bigstrut\\
    \hline
    NO    & 91.00\% & 24.88\% & 0.200 \bigstrut\\
    \hline
    YES   & 76.51\% & 2.04\% & 0.021 \bigstrut\\
    \hline
    \end{longtable}
\end{table}

\begin{figure}[t]
\begin{center}
\includegraphics[width=14cm]{figures/CrosswalkTruePosWithAndWithout.png}
\captionfonts
\caption{Shows the true positive rates per crosswalk with and without the neural network enabled}
\label{fig:CrosswalkTruePosWithAndWithout}
\end{center}
\end{figure}

\begin{figure}[t]
\begin{center}
\includegraphics[width=14cm]{figures/VideoFalsePosWithAndWithout.png}
\captionfonts
\caption{Shows the false positive rates per video with and without the neural network enabled}
\label{fig:VideoFalsePosWithAndWithout}
\end{center}
\end{figure}

\subsection{Crosswalk Boundary Line Drawing Results}

A subset of 180 images were selected to test the crosswalk boundary drawing and had their boundary lines manually drawn. A metric was needed in order to compare the correct line with the estimated line. The metric used involved taking multiple points that were equidistant along the estimated line and finding the normal distance to the manually drawn line. These distances were then summed up to give a general gauge of how close lines were together. Exactly identical lines would have a difference value of zero, while more distinct lines would have greater values. Some example images with their evaluation result values are shown in figure \ref{fig:LinesUsingJustGoodStartAndEnds2}. Overall, the results were rather promising, with the vast majority of lines from images with a recognized crosswalk being close to correct with a median measure of 82 and only 16\% of the lines being over the threshold of 400. As shown in figure \ref{fig:400Metric}, 400 was a generous measure, because even at 400, the lines are still close enough.  If the stripelets are predicted properly, and a crosswalk is recognized, the edges of the stripelets are almost guaranteed to be good metrics of the crosswalk edges.

\begin{figure}[t]
\begin{center}
\includegraphics[width=15cm]{figures/LinesUsingJustGoodStartAndEnds2.png}
\captionfonts
%Jeneeplz what term for "left evaluation value"
\caption{Orange and red dots are the right and left points used. Green is the manually drawn boundary. Blue is the estimated boundary. Left to right: (a) Left evaluation metric of 38, right 34. (b) left: 178, right: 135. (c) left: 235, right: 90}
\label{fig:LinesUsingJustGoodStartAndEnds2}
\end{center}
\end{figure}

\begin{figure}[t]
\begin{center}
\includegraphics[width=12cm]{figures/400RightSide.png}
\captionfonts
%Jeneeplz what term for "left evaluation value"
\caption{Orange and red dots are the right and left points used. Green is the manually drawn boundary. Blue is the estimated boundary. The evaluation metric on the right side is 400, which is considered the high range of acceptable}
\label{fig:400Metric}
\end{center}
\end{figure}