\documentclass[12pt]{article}
\input{physics1}
\begin{document}

\section*{NYU Physics I---potential energy}

For a conservative force, the potential energy is the (negative of
the) line integral of the force and the force is the (negative of the)
derivative of the potential.  This is related to the fundamental
theorem of calculus but it is also very fundamental in physics.  Here
we do a non-trivial example.

\paragraph{\theproblem}\refstepcounter{problem}%
Consider a particle subject to a potential energy of the form
\begin{equation}
U = \frac{B}{x^2} - \frac{A}{x} \quad ,
\label{eq:hard}
\end{equation}
where $A$ and $B$ are positive constants.  If $x$ is measured in $\m$,
what are the units of $A$ and $B$?

Consider another particle subject to a potential energy of the form
\begin{equation}
U = \frac{1}{2}\,k\,(x-x_0)^2
\label{eq:easy}
\end{equation}
where $k$ is a constant.  If $x$ is measured in $\m$, what are
the units of $k$?

\paragraph{\theproblem}\refstepcounter{problem}%
Sketch both potentials $U$ vs $x$.

\paragraph{\theproblem}\refstepcounter{problem}%
Take derivatives for each potential, and use these to get the ``force
law'' for each potential. Plot the $x$ component of the force as a
function of position $x$. Be careful about the direction (sign) of the
force.

\paragraph{\theproblem}\refstepcounter{problem}%
Find the equilibrium position (or positions, if there are more than
one) $x_\mathrm{eq}$ for each of the potentials.  That is, compute the
$x$ positions where there is no force and the potential is at a
minimum.

\paragraph{\theproblem}\refstepcounter{problem}%
Take a second derivative for each potential at the (or an) equilibrium point.
What are the units of this second derivative?  Interpret it physically
in terms of force and distance. What does this have to do with the
Taylor series? Discuss.

\paragraph{\theproblem}\refstepcounter{problem}%
In the second potential (\ref{eq:easy}), you know what the dynamics
are: what happens to the system as a function of time if displaced
from equilibrium?  How does this relate to what happens in the first
potential (\ref{eq:hard})?  There is a limit in which these look
\emph{very similar}; what is it?

\paragraph{\theproblem}\refstepcounter{problem}%
Of what kind of system might potential (\ref{eq:hard}) be a model?

\end{document}


\subsection{Turing machines}

A Turing machine is a pushdown automaton where the stack is no longer LiFo.


\chapter{Sverdrup balance and basin-scale circulation}
\label{chap:sverdrup}

\includegraphics[width=6.5in]{figs/Geostrophic/HaidaEddy}

We saw above that the Ekman balance can drive convergences and divergences in the ocean, and that these cause the water to pile up preferentially creating pressure gradients.  The pressure gradients are then balanced by the Coriolis force, in the geostrophic balance, and water flows parallel to lines of constant pressure, clockwise around highs in the Northern hemisphere.

This \emph{all} happens on the large scale.  If we consider the subtropical gyre, between 15 and 45 degrees, there is an Ekman convergence towards the centre of the gyre, and that causes there to be a sea-surface high there.  The water will flow around that sea-surface high in a clockwise direction (northern hemisphere).  However that leaves two questions:
\begin{enumerate}
    \item How strong will the flow be?  Alternately, how high will the highs in the middle of the gyre be?
    \item Why is the gyre asymmetric east-west?
\end{enumerate}

The answer is, as we will see below, that the flow is driven by the conservation of angular momentum acting in the presence of basin-scale changes in the Coriolis frequency.  Water with a negative (clockwise) torque exerted on it can either spin with negative (clockwise) angular momentum, or it can move to a region with lower background ``planetary'' angular momentum.

\section{Circulation}

Idealizing the winds and seasurface in the subtropical gyre we have the idea that the winds blow from west to east in the westerlies (45 N) and east to west in the Trades (15 N; \fref{fig:GyreSketch}).  Based on the dynamics as we've understood them so far, this leads to an Ekman convergence everywhere in the gyre, and a raising of the seasurface height, and causing a downwelling.

\begin{figure}[hbt]
  \begin{center}
    \includegraphics{figs/Sverdrup/GyreSketch}
    \caption{Idealized sketch of the wind stress in the subtropical gyre (northern hemisphere).   Top panel is from above, with coasts on the west and east side.  Westerlies peak at 45 N, and the trades at 15 N.  This makes a high in the middle, but offset to the west.  Bottom panel is the same situation looking at the side from the east towards the west. The Ekman layer is shown with the blue arrows, noting that there is downwelling throughout this gyre.}
    \label{fig:GyreSketch}
  \end{center}
\end{figure}

However, the observed gyre is asymmetric, with the high concentrated near the western boundary. This implies that the velocity is largely equatorward everywhere in the gyre, except to the west of the high, along the \Wikiref{Western boundary}. The real situation is even more asymmetric than pictured in \fref{fig:GyreSketch}.  If we remember that the geostrophic interior velocity is proportional to the strength of the pressure gradient, then we would expect very slow flow towards the south in the interior, and very fast flow along this western boundary.  The western boundary current in the N. Pacific subtropical gyre is the \Wikiref{Kuroshio}; the \Wikiref{Gulf Stream} is the corresponding current in the Atlantic.

\section{Conservation of potential vorticity}

The way to understand the gyre circulation is to consider the conservation of angular momentum, or in fluid mechanics we call it \Wikiref{potential vorticity}.  Just like any angular momentum, the potential vorticity changes in response to torque, in this case from the wind and seafloor.  A simplified version, useful for our case is:
\begin{equation}
    \frac{d}{dt}\left(\frac{\zeta + f}{H} \right) = \frac{1}{H^2\rho_0} \left[\frac{d\tau_y^W}{dx} - \frac{d\tau_x^W}{dy} + \frac{d\tau_y^B}{dx} - \frac{d\tau_x^B}{dy}\right]
    \label{eq:conspotvort}
\end{equation}
Here the term on the left side of the equation is the potential vorticity, and the term on the right side the torque due to the wind stress ($\tau_x^W, \tau_y^W$) and bottom friction ($\tau^B$).  $H$ is the water depth, and $f$ is the Coriolis parameter, which we keep in mind varies with latitude, or $y$.  We call this the \emph{planetary vorticity} and is the vertical angular momentum due to the earth's rotation.
\begin{marginfigure}
    \includegraphics{figs/Sverdrup/relativevortsketch}
    \caption{Sketch of velocity gradients in a counter clockwise flow.  Note $\zeta>0$ in this flow.}
    \label{fig:relativevortsketch}
\end{marginfigure}
The term $\zeta$ is the \Wikiref{relative vorticity} of the flow and is defined as:
\begin{equation}
    \zeta = \frac{dv}{dx} - \frac{du}{dy}
\end{equation}
where $u$ and $v$ are the x- and y-components of velocity.  It is relatively straight forward to see how this relates to a spinning flow (\fref{fig:relativevortsketch}).  Consider a flow spinning in a counter-clockwise manner.  The velocity gradients in such a flow are such that $zeta > 0$.  This uses the \Wikiref{right-hand rule}, which says that if you curl your right hand fingers in the direction of rotation, your thumb will point up for positive vorticity and down for negative vorticity (this is just a convention, and could have just as easily been the other way, but it is useful to choose one convention and stick with it).  Of course a clockwise flow has a negative vorticity.

The same logic and sign convention applies to torque.  In the gyre sketched in \fref{fig:GyreSketch}, the gradients in $\tau^W$ are such that $\frac{d\tau_x^W}{dy} < 0$, so the wind is exerting a negative torque on the water.

\begin{derivbox}[label={box:potentialvort}]{Derivation of potential vorticity}
Potential vorticity for a barotropic fluid is relatively straight forward to derive.  We  need the momentum equations and the continuity equation:
\begin{eqnarray*}
    \frac{du}{dt} & = & -\frac{1}{\rho}\frac{dP}{dx} + fv + \frac{1}{\rho}\frac{d\tau_x}{dz}\\
    \frac{dv}{dt} & = & -\frac{1}{\rho}\frac{dP}{dy} - fu + \frac{1}{\rho}\frac{d\tau_y}{dz}
\end{eqnarray*}
If we take $-d/dy$ of the first equation and $d/dx$ of the second and add them, then the pressure term drops out:
\begin{equation}
    \frac{d}{dt} \left( \frac{dv}{dx} - \frac{du}{dy}\right) = -f \left(\frac{du}{dx} + \frac{dv}{dy} \right) + \frac{1}{\rho}\left(\frac{d^2\tau_y}{dz\,dx} - \frac{d^2\tau_x}{dz\,dy}\right)
\end{equation}
and we note that the first term is just the derivative of $\zeta$ with time.

We integrate this vertically from the sea-floor to sea surface, and assume that the water is $H$ deep, including any sea-surface displacements.
\begin{equation}
    H\frac{d\zeta}{dt}  = -f H \left(\frac{du}{dx} + \frac{dv}{dy} \right) + \frac{1}{\rho}\left(\frac{d\tau_y^W}{dx} - \frac{d\tau_x^W}{dy}\right) + \frac{1}{\rho}\left(\frac{d\tau_y^B}{dx} - \frac{d\tau_x^B}{dy}\right)
\end{equation}
So now we use the fact that $\frac{du}{dx} + \frac{dv}{dy} = -dW/dz = H^{-1}\frac{dH}{dt}$.

TODO: finish
\end{derivbox}

We saw in the classroom demo a consequence of the conservation of potential vorticity:  when water that is initially not moving in a rotating reference frame moves from shallow water to deep water, the water column deepens, so $H$ increases (\fref{fig:PVChangeEddy}).  There are no substantial bottom or surface friction, so no external torque on the water column.  However, it does have initial \emph{planetary vorticity}, $f$ from the rotation of the reference frame.  Since there is no torque we can write:
\begin{equation}
    \frac{\zeta_0 + f_0}{H_0} = \frac{\zeta_F + f_F}{H_F}
\end{equation}
Now initially the water is not moving, and $f$ is constant, so we can solve for $\zeta_F$ to find that the water is spinning with a vorticity that has the same sign as $f$:
\begin{equation}
    \zeta_F = f \left(\frac{H_F}{H_0} - 1 \right)
\end{equation}
\begin{marginfigure}
    \includegraphics{figs/Sverdrup/PVChangeEddy}
    \caption{Sketch of parcel of water moving from shallow to deep region.  As it moves to deep region its planetary vorticity is stretched and manifests as an eddy rotating in the same direction as the planetary vorticity.}
    \label{fig:PVChangeEddy}
\end{marginfigure}
and because $H_F>H_0$ this is a positive number.  This is all directly analogous to the spinning ice skater who draws in their arms, and makes themselves thinner, and hence spin faster, just here the effect is caused by the earth spinning rather than the skater.  \marginnote{It is actually the same math if the eddy starts spinning so it has \emph{relative vorticity} as well as having \emph{planetary vorticity}, there is just an extra term: $\zeta_F = \frac{H_F}{H_0}\left(\zeta_0 +f\right) - f$}

On the large scale, ie. our basin, it is important to bear in mind two facts.  First, $f$ varies with latitude - it is higher at the poles and zero at the equator. So that means when we think about $\frac{f+\zeta}{H}$ changing with time following a parcel of water, we need to remember that $f$ can change too.  Second, On large scales $\zeta \approx 0$, and in fact if $\zeta$ is large, like in an eddy or cyclone, it will tend to move poleward if it is a cyclone, and equatorward if an anti-cyclone.  To see why this is, consider $\zeta_0$ which is large at a latitude where $f=f_0$.  Supposing $H$ is constant, then for $\zeta_F$ to be driven to zero we have an expression for $f_F$:\marginnote{Of course a cyclone will also die out due to friction, and loss of warm water feeding the low pressure system in its centre, but the tendency to move North is because of the conservation of potential vorticity.}
\begin{equation}
    \zeta_0 + f_0 = f_F
\end{equation}
So for a hurricane $\zeta_0>0$, they always move poleward, and die out, partially because they are moving to a region with higher planetary vorticity.

\section{Sverdrup transport}

The Sverdrup transport is a straight-forward application of the conservation of potential vorticity \fref{eq:conspotvort}, if we realize a few things.  First, let us approximate the ocean depth as a constant.  Second, we assume bottom friction is generally quite small, so $\tau_x^B\approx\tau_y^B\approx 0$. Third, note that on the scale of the whole Pacific, the relative vorticity is substantially smaller than $f$, so we can write $f+\zeta \approx f$.  To see this, consider the scale of the fastest velocity in the ocean, which is about $U\sim 1 \mathrm{m\,s^{-1}}$.  This is spread over a distance of $L\sim 10,000\ \mathrm{km}$, so the scale of vorticity is $U/L \sim 10^{-7}\ \mathrm{s^{-1}}$.  Compare to $f\approx 10^{-4}\ \mathrm{s^{-1}}$, and it is clear that on large scales (say scales > 10 km), $f>>\zeta$.  Finally, lets only consider that the wind is in the x-direction as sketched in \fref{fig:GyreSketch}.
These assumptions simplify \fref{eq:conspotvort} significantly:
\begin{equation}
    H\frac{d f}{dt} = -\frac{1}{\rho_0}\left[\frac{d\tau_y^W}{dx}\right]
\end{equation}
So what this says is that the rate of change of $f$ is proportional to the wind torque.  In the sketch above (\fref{fig:GyreSketch}) the torque is clearly negative, so this equation says that $f$ must decrease with time following a parcel of fluid.  The way that $f$ decreases with time is by moving South because $f$ is a sinusoid centered at the equator.

Indeed the torque tells us how fast the water will move north or south under the Sverdrup balance.  If $v$ is the north-south velocity, then
\begin{equation}
    \frac{df}{dt} = v \frac{df}{dy}
\end{equation}
where $y$ is in m.  $df/dy$ is a function of latitude, but we often can make the \Wikiref{beta-plane} approximation and assume its a constant $\beta$.  At 30 degrees latitude (the middle of the subtropical gyre) $\beta \approx 2.3\times 10^{-11}\ \mathrm{[(ms)^{-1}]}$.    The gives us the Sverdrup relation:
\begin{equation}
    Hv  \approx -\frac{1}{\beta \rho_0}\left[\frac{d\tau_y^W}{dx}\right]
    \label{eq:Sverdrup}
\end{equation}
So, in the case where the torque is negative the velocity $v$ is negative, and thus to the south.

\begin{derivbox}[label={box:beta}]{Calculating Beta}
    The rate of change of $f$ with the y coordinate, $\beta = \frac{df}{dy}$ is readily calculated from $f$ and the radius of the Earth, $R$.  $f=2\Omega \sin \lambda$ and $y = R \lambda$, so
    \begin{eqnarray*}
        \beta & = & \frac{df}{dy} \\
              & = &  \frac{df}{d\lambda} \frac{d\lambda}{dy} \\
              & = &  \frac{2\Omega}{R} \cos \lambda\
    \end{eqnarray*}
    So with $R=6371\ \mathrm{km}$ and $2\Omega = 1.45\times10^{-4}\ \mathrm{s^{-1}}$, then at 30 N, $\beta \approx 2.3\times 10^{-11}\ \mathrm{[(ms)^{-1}]}$.
\end{derivbox}

So let us apply to our wind torque pictured in \fref{fig:GyreSketch}.  If we assume that the wind stress profile is given by $\tau_x^W(y) = \tau_0 \sin \left(2\pi \frac{y-y_{30}}{2L}\right)$, where $\tau_0 = 0.1 \mathrm{N\,m^{-2}}$, and $L = 3300\ \mathrm{km}$ is the north-south extent of the basin (see \fref{fig:GyreWindSketch}).  So the gradient is given by
\begin{equation}
    -\frac{d\tau_x^W}{dy} = -\tau_0 \frac{\pi}{L} \cos \pi  \left(\frac{y-y_{30}}{L}\right)
\end{equation}
So, the transport is given by
\begin{equation}
    Hv \approx \left(4.14 \ \mathrm{m^2\,s^{-1}}\right) \cos \pi  \left(\frac{y-y_{30}}{L}\right)
\end{equation}
So, at 30-degrees, the 2-D transport is $4.14\ \mathrm{m^2\,s^{-1}}$. Averaged over the 4000-m water depth we can arrive at an average velocity of $v\approx 1\ \mathrm{mm\, s^{-1}}$, though the actual wind-driven transport tends to be surface intensified.  Integrated across the Pacific, with a width of 10,000 km this yields a total 3-D transport of $4.14\times10^{7}\ \mathrm{m^3\,s^{-1}}$, or 40 Sv.  Note that as we get closer to the bottom ($\lambda=15 N$) and the top ($\lambda= 45N$) the transport drops to zero (\fref{fig:GyreSketch}).
\begin{figure}[hbt]
  \begin{center}
    \includegraphics{figs/Sverdrup/GyreWindSketch}
    \caption{Sketch of shape of wind stress (left), shape of Sverdrup transport (middle), and arrows indicating what that transport looks like when looking from above (right).}
    \label{fig:GyreWindSketch}
  \end{center}
\end{figure}

Note that this sense of transport agrees with observations of a sea-surface high displaced to the west of the gyre.  Of the flow is clockwise around the high, then all the water to the east of the high will be moving southwards.  This estimate also accords with our best estimates of the transport in the gyre from calculating geostrophic velocities (\fref{GrayRiserFig2}).

\begin{figure}[hbt]
  \begin{center}
    \includegraphics{figs/Sverdrup/GrayRiserFig2}
    \caption{Geostrophic streamfunction at 5 dbar in $m^2s^{-2}$, estimated from Argo floats. Red high, clockwise flow. \citep{grayriser14}}
    \label{fig:GrayRiserFig2}
  \end{center}
\end{figure}

\subsection{Alternative derivation: Ekman pumping}

An alternative way to think about the Sverdrup balance is to separate the upper-ocean Ekman layer from the interior of the ocean.  In this case, the interior of the ocean does not feel the wind friction, and hence has no mechanical torque acting on it.  However, there is a constant downwelling of water from the Ekman pumping.  This causes the water already in the interior to be squished, so $dH/dt < 0$, and the water will tend to move south.

In terms of the vorticity equation, we can write it with no torques and small relative vorticity as
\begin{equation}
    \frac{d}{dt}\frac{f}{H} = 0
\end{equation}
or using the the fact that $d(ab)/dt = adb/dt + b da/dt$:
\begin{equation}
    Hv\beta = f \frac{dH}{dt} = f w
\end{equation}
where the rate of squishing of the deeper water is $w$, the rate of Ekman pumping (\fref{fig:SverdrupEkman}).

\begin{figure}[hbt]
  \begin{center}
    \includegraphics{figs/Sverdrup/SverdrupEkman}
    \caption{Sketch of how Ekman pumping pushes down on the water in the interior, causing $H$ to decrease, and hence the water to tend to flow south to compensate.}
    \label{fig:SverdrupEkman}
  \end{center}
\end{figure}

We noted in \fref{ch:coriolis} that the rate of Ekman pumping is related the to curl of the wind stress:
\begin{equation}
    w = -\frac{1}{f\rho_0}\frac{d\tau_x^W}{dy}
\end{equation}
or,
\begin{equation}
    Hv\beta = f \frac{dH}{dt} = -\frac{1}{\rho_0}\frac{d\tau_x^W}{dy}
\end{equation}
just like in the derivation above.

\section{Return flow}

Remember that the Sverdrup balance applies from the top to the bottom of the water column, so if all the water between 15 and 45 N is flowing south under the Sverdrup balance, there has to be a return flow to the north somewhere.  The shape of the sea-surface height in \fref{fig:GrayRiserFig2} indicates that the northward flow is on the west side of the basin, and indeed we can easily argue that this is indeed true.

In order for flow to move north, it needs a positive torque.  The wind torque is negative, so the opposing torque must be from friction and tend to spin the water counter-clockwise.  If we assume the torque comes from the sides, we simply cheque the sign of the torque exerted by a parcel of water moving north on either sidewall (\fref{fig:TorquesReturn}).  If the return flow were in the east, then the friction force would be on the east side of a parcel of water, and there would be no friction force on the left side.  This would tend to spin the water in a clockwise sense, or with negative torque.  This is, of course, the wrong sense, because we need a positive torque.  If we consider a return flow on the west side, the friction is on the west side of a parcel moving north, and there is no friction on the east side, so the parcel will tend to be torqued in a counter-clockwise direction, and hence this is where the return flow must be.

\begin{figure}[hbt]
  \begin{center}
    \includegraphics{figs/Sverdrup/TorquesReturn}
    \caption{Sketch of sidewall torque on two alternate return flows in a subtropical gyre.}
    \label{fig:TorquesReturn}
  \end{center}
\end{figure}

The final missing piece is that water must move fro the interior to and from the western boundary current.  just using conservation of volume, we can readily infer that the water south of 30 N must be moving west, and the water north must be moving east.  Thus the flow follows the geostrophic contours as plotted in \fref{fig:GrayRiserFig2}, moving around the high sealevel in a clockwise fashion.  Where the sea level gradient is steepest, the flow is the fastest, in the Western Boundary current.

Looking at \fref{fig:GrayRiserFig2}, it is apparent that there is a western boundary current in both the northern and southern hemispheres, and in all the ocean basins.  In the subtropical gyres, these currents carry water from the equator towards the poles, and in the subpolar gyres, they do the opposite.  Its worth testing your knowledge by considering the wind patterns in the southern hemisphere, or the subpolar gyre, and see if the sign of the torque accords with \fref{fig:GrayRiserFig2}.


\documentclass{mrl}

\title{An efficient implementation of MKEcoin subaddresses}
\authors{Sarang Noether\footnote{\texttt{sarang.noether@protonmail.com}} and Brandon Goodell\footnote{\texttt{surae.noether@protonmail.com}}}
\affiliations{MKEcoin Research Lab}
\date{\today}

\type{RESEARCH BULLETIN}
\ident{MRL-XXXX}

\begin{document}

\begin{abstract}
Users of the MKEcoin cryptocurrency who wish to reuse wallet addresses in an unlinkable way must maintain separate wallets, which necessitates scanning incoming transactions for each one. We document a new address scheme that allows a user to maintain a single master wallet address and generate an arbitary number of unlinkable subaddresses. Each transaction needs to be scanned only once to determine if it is destinated for any of the user's subaddresses. The scheme additionally supports multiple outputs to other subaddresses, and is as efficient as traditional wallet transactions.
\end{abstract}

\section{Introduction}
Privacy within MKEcoin transactions is achieved by three primary constructions: ring signatures, one-time keys, and amount commitments. The use of ring signatures ensures that an attacker cannot determine the actual input public key used in the transaction, as it is obscured by the presence of randomly chosen input public keys \cite{cryptonote}. Amount commitments use homomorphic properties to guarantee that while a third party is not able to determine the amount of a transaction output, it can prove that the transaction inputs and outputs are balanced. When combined with a range proof to ensure that the output is within a defined and valid range, commitments mask transaction amounts while avoiding misuse by a malicious spender. One-time keys are generated using transaction parameters and the recipient's published wallet address, and are intended to make it impossible for anyone but the recipient to identify the destination of transactions or spend the resulting funds.

An issue not addressed (pun intended) by these privacy guards is that of recipient addresses. Bob may wish to receive MKEcoin into a wallet for personal donations, but also wish to receive MKEcoin for purchases from his business. If Bob is conscious of his privacy, he may not wish to use the same wallet address, since this links his personal and business online presence to the same individual. An obvious solution is for Bob to create two wallets and publish the addresses separately, one to his personal blog and the other to his business site. However, this means that Bob must scan each incoming transaction twice to determine if it was sent to one of his two wallets. This problem is compounded linearly when Bob creates additional addresses for separate uses.

What is needed is a method for allowing Bob to publish different and unlinkable addresses in a way that does not adversely affect computations applied to incoming transactions. In this whitepaper, we document an efficient solution to the problem: a \textit{subaddress} scheme \cite{pr}. The scheme allows Bob to produce as many addresses as he wishes and distribute them in any way he sees fit. These subaddresses cannot be linked to each other, nor to Bob's original wallet address. When scanning incoming transactions, the computations required scale in constant time with the number of subaddresses, meaning there is no additional computational complexity.

\section{Construction}
Suppose that Alice wishes to send some of her hard-earned MKEcoin to Bob. Bob's master wallet address, which he has not published anywhere, is $(A,B) = (aG, bG)$, where $a$ and $b$ are secret scalars and $G$ a common elliptic curve basepoint. Bob wishes to use his master address to generate a subaddress, which he can give to Alice or otherwise publish.

Bob is assumed to maintain a list on the computer tasked with managing his wallets; this list consists of scalars used in previous subaddresses. To create a new subaddress, Bob chooses a scalar $i$, not necessarily at random, that is not already in the list. He computes the following:
\begin{eqnarray*}
D_i &\equiv& B + H_s(a,i)G \\
C_i &\equiv& aD_i
\end{eqnarray*}
Here $H_s$ is a cryptographic scalar hash function. The subaddress is defined as the pair of points $(C_i,D_i)$. Bob is assumed to also have a hash table stored on his computer that maps $D_i \mapsto i$.

To send MKEcoin to Bob's subaddress $(C_i,D_i)$, Alice chooses a random transaction scalar $s$ and computes the transaction public key:
$$R \equiv sD_i$$
Alice then computes the output public key:
$$P \equiv H_s(sC_i)G + D_i$$
The use of separate transaction keys for each output allows Alice to include multiple outputs directed to subaddresses.

If Alice wants to send change to her own master wallet address $(X,Y) = (xG,yG)$, she can do so by constructing a change public key:
$$P_{\operatorname{change}} \equiv H_s(xR)G + Y$$
If instead Alice has a subaddress $(Z_j,W_j)$ of her own, she can direct her change output there:
$$P_{\operatorname{change}} \equiv H_s(xR)G + W_j$$

When Bob scans incoming transactions, he checks each output public key $P$ (with associated transaction public key $R$) by computing the following:
$$D' \equiv P - H_s(aR)G$$
If Bob sees that this value $D'$ maps to a scalar $i$ in his local hash table, he is assured that the output was sent to the subaddress $(C_i,D_i)$. This is because
\begin{eqnarray*}
P - H_s(aR)G &=& H_s(sC_i)G + D_i - H_s(a(sD_i))G \\
&=& H_s(sC_i)G + D_i - H_s(s(aD_i))G \\
&=& H_s(sC_i)G + D_i - H_s(sC_i)G \\
&=& D_i.
\end{eqnarray*}

In order to use his funds as the input to a later transaction, Bob needs to be able to determine the private key associated to $P$. He can do this easily using the index returned from the hash table lookup:
$$p \equiv H_s(aR) + b + H_s(a,i)$$
This succeeds since
\begin{eqnarray*}
pG &=& (H_s(aR) + b + H_s(a,i))G \\
&=& (H_s(sC_i) + b + H_s(a,i))G \\
&=& H_s(sC_i)G + D_i \\
&=& P.
\end{eqnarray*}

\section{Integration with transactions}
The present subaddress scheme introduces a necessary change in the handling of transactions, and cannot be considered a ``drop-in" replacement for standard wallets. When Alice wishes to spend to Bob's standard wallet, she constructs a transaction public key $R = rG$ using the common basepoint. One naive way that Alice could later prove she was the author of the transaction is to prove knowledge of $r$ (or, even more naively, reveal $r$ directly) to a third party; notably, she can do this without revealing that the funds go to Bob's wallet address.

Using subaddresses, Alice must instead construct the transaction public key as $R = sD$, using Bob's subaddress public key as the basepoint. Since the secret key $s$ is chosen uniformly at random, a subaddress transaction public key is still uniformly distributed; however, Alice can no longer naively prove she knows the common basepoint secret key without also revealing Bob's subaddress as the recipient of the funds, since it is tied in with Bob's subaddress in the Diffie-Hellman exchange. She would need to reveal $D$ in addition to $s$. While other methods exist to prove authorship of a transaction using commitments, it is worth noting this change.

With standard transactions, Bob can ask Charlie to watch incoming transactions for him, or otherwise wish for Charlie to audit his wallet. To do this, Bob would reveal to Charlie the secret view key $a$ and wallet address component $B$. In the subaddress scheme, Bob can similarly reveal $a$ to Charlie. Charlie must then construct the hash table using either a list of known indices from Bob or a set range that he precomputes.

\section{Subaddress accounts}
Since a change output can be directed to either the sender's master wallet or a subaddress, it is possible to logically group subaddresses in a natural way that parallels the function of separate wallet balances. One way to do this is to replace the subaddress index $i$ with an ordered pair $(i,j)$. For any fixed $i$, the wallet holder defines the set of subaddresses $\{i,j\}_j$ as an \textit{account}, where each subaddress has \textit{major index} $i$ and \textit{minor index} $j$.

When Bob receives funds at a subaddress $(i,j)$ within account $i$, his wallet software sums the funds held by all subaddresses in the account as a single balance. Change can then be redirected to the subaddress $(i,0)$ when spent. We stress that this is a protocol convenience only, and has no bearing on the cryptography of the subaddress scheme.

\section{Analysis}
\subsection{Linking and wallet determination}
Because the cryptographic scalar hash function $H_s$ has uniformly distributed output, the set of Bob's possible subaddress components $$\{D_i\}_i = \{B + H_s(a,i)G\}_i$$ is also uniformly distributed \cite{uniform}. This means an adversary in possession of an arbitrary collection of subaddresses $\{(C_i,D_i)\}_i = \{aD_i,D_i\}$ can neither determine the discrete logarithm $a = \log_{C_i} D_i$ nor invert the hash function (which would also require knowledge of $B$). This means Bob's master wallet address is protected, even if the adversary convinces him to generate new subaddresses with chosen indices.

\subsection{Reconstructed wallet}
If Bob loses access to his local wallet software and restores from the seed, he will not immediately be able to identify transactions destined for his subaddresses, as he would need access to the hash table. To reconstruct the table without missing any likely subaddresses, Bob chooses two lookahead values, $L_M$ and $L_m$. He generates the hash table using major indices $i \leq L_M$ and minor indices $j \leq L_m$ (for each major index). After scanning transactions using the initial table, Bob repeats this process, ensuring he has generated hash entries $L_M$ past the highest major index of any transaction, and $L_m$ past the highest minor index within each major index. Provided used subaddresses do not fall beyond these lookahead values in any transactions, Bob will recover the necessary hash entries.

\subsection{Mixed-type transactions}
Suppose that Alice's wallet software had one too many glasses of cryptocognac, and formats a transaction incorrectly. In particular, suppose Alice produces the transaction public key $R = sG$ (instead of $R = sD$) but continues to compute the output public key as $P = H_s(sC_i) + D_i$. That is, the transaction is now of ``mixed type" and is not a correct subaddress transaction.

In this case, the transaction public key no longer contains information about the subaddress destination, and Bob cannot use a single scan to detect this transaction. Indeed, his wallet software will fail to recognize that the mixed-type transaction is directed at him. However, if Bob suspects that this situation has arisen, he can iterate through his subaddress indices and compute
$$P - H_s(a[b+H_s(a,j)]R)$$
for each $j$ that he has used to generate a subaddress. For $j = i$, the result is guaranteed to be $D_i$. This means that Alice's error can be detected if Bob performs such a linear scan, and Bob can still recover the private key needed to spend his money. The tradeoff is that Bob loses the ability to perform single transaction scans, so he may choose to have his wallet software complete a linear scan every so often if he is concerned about mixed-type transactions.

\subsection{Secret view key}
It is not possible to provide view access to a third party selectively to only particular subaddresses under the assumption of uniformly distributed secret keys. If Charlie receives Bob's view key $a$ and one hash table entry $D_i \mapsto i$, he computes the master wallet address component $B = D_i - H_s(a,i)G$. If Bob does not choose his subaddress indices at random, Charlie can easily reconstruct other hash table entries using low indices that are likely also subaddresses Bob has used:
$$D_j = B + H_s(a,j)G$$
In order to keep other transactions private so Charlie cannot view them, Bob must create a new master wallet and ensure Charlie does not have access to its secret view key.

\subsection{Secret spend key}
Similarly, it is not possible to provide a third party with the ability to selectively spend funds from a particular subaddress if the secret keys are uniformly distributed. To spend funds from any subaddress, Bob needs both master wallet secret keys $a$ and $b$, as well as the subaddress index. Revealing this information to Charlie would allow him to spend funds sent to any subaddress to which he knows (or can otherwise determine) the index. Of course, the correct way to do this is for Bob to send funds to Charlie's wallet or subaddress, just as with a standard wallet setup.

\subsection{Efficiency}
Construction of a new subaddress requires a trivial number of elliptic curve operations and is negligible since this operation is performed only as needed.

Sending to a subaddress requires the same number of operations as an equivalent traditional transaction to a standard wallet address. However, instead of computing the transaction key $R = rG$ using the common basepoint in a traditional transaction, Alice instead computes the key as $R = sD$ using the subaddress basepoint; indeed, Alice does not even know the transaction secret key in this case! This means she cannot precompute the transaction key without knowing the desired recipient's subaddress. In practice, this is not an issue. Computation of the output public key is precisely analogous to the traditional case.

Using a standard wallet, Bob would check a transaction against his master wallet secret view key by applying one hash-to-scalar operation, two elliptic curve scalar multiplications, and one elliptic curve point addition (where the hash time is negligible). In the present scheme, Bob must apply the same number of equivalent operations, with the point addition replaced with point subtraction. There is an additional hash lookup for each transaction, but this scales in constant time with the number of generated subaddresses. This is in stark contrast to the use of multiple wallet addresses, where each transaction must be separately checked against each secret view key.

We therefore conclude that scanning incoming (correctly formatted) transactions for ownership by an arbitrary number of subaddresses is no greater than scanning for ownership by a single standard wallet address. This reduces the otherwise linear scaling of scanning for multiple standard wallet addresses to constant time in the subaddress case.

\section{Conclusions}
We have presented brief documentation of a subaddress scheme, an efficient alternative to maintenance of multiple wallet addresses. Under the standard CryptoNote wallet implementation in MKEcoin, Bob must publish separate wallet addresses if he wishes to keep them unlinkable from the perspective of a third party or adversary. However, this approach requires Bob (or another holder of his secret view key) to check every incoming transaction against each of his addresses.

The proposed scheme allows Bob to use a single master wallet address to efficiently generate as many subaddresses as he wishes. An adversary can neither determine if two subaddresses are generated from the same master wallet address, nor identify the parent address. Bob need only maintain a local private hash table that links subaddresses to the scalar index used to generate them.

Transactions to a subaddress require only a minor change to the existing transaction protocol. Multiple outputs are supported, and the change output of a transaction from Alice to Bob can be directed to either Alice's master wallet address or to a subaddress of her choice. When examining incoming transactions, Bob performs only a single verification for each transaction regardless of the number of subaddresses he maintains, using his local hash table to recover the corresponding transaction private key.

Unlinkable subaddresses represent an efficient and secure solution to the problem of multiple wallet addresses, allowing users to determine how their wallets are presented to others and the level of privacy they desire.

\bibliographystyle{plain}
\bibliography{main}

\end{document}


\chapter{Basic Data  Structures}

\section{Introduction}
Abstract Data Types (ADT):
\begin{enumerate}
\item Queue
\item Stack
\item HashMap
\end{enumerate}
Implementation (for both queue and stack):
\begin{enumerate}
\item Linked List
\item Resizing Array:
\begin{enumerate}
\item Doubling: when full (100\%).
\item Halfing: when one-quarter full (25\%).
\end{enumerate}}
\end{enumerate}}
Python Library:
\begin{enumerate}
\item \pythoninline{collections.deque} \footnote{The naming in Python collections is awkward: \href{http://stackoverflow.com/questions/18953681/naming-convention-in-collections-why-are-some-lowercase-and-others-capwords}{discussion}.}
\item \pythoninline{list}
\item \pythoninline{dict, OrderedDict, defaultdict}
\end{enumerate}}
Java Library:
\begin{enumerate}
\item \javainline{java.util.Stack<E>}
\item \javainline{java.util.LinkedList<E>}
\item \javainline{java.util.HashMap<K, V>; java.util.TreeMap<K, V>}
\end{enumerate}}

\section{Stack}
\subsection{Stack and Recursion}
How a compiler implements a function:
\begin{enumerate}
\item Function call: push local environment and return address
\item Return: pop return address and local environment.
\end{enumerate}

Recursive function: function calls itself. It can always be implemented by using an explicit stack to remove recursion.

Stack can convert recursive \textbf{dfs} to iterative.

\subsection{Usage}
The core philosophy of using stack is to maintain a relationship invariant among stack element.

The \textbf{relationship invariants} can be:
\begin{enumerate}
\item strictly asc/ strictly desc
\item non-desc/ non-asc
\end{enumerate}

\subsection{Applications}
\runinhead{Largest Rectangle.} Find the largest rectangle in the matrix (histogram). Given $n$ non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.

\begin{figure}[hbtp]
\centering
\subfloat{\includegraphics[scale=2.00]{histogram_area}}
\caption{Largest rectangle in histogram}
\label{fig:histogram_area}
\end{figure}

Keep a stack storing the bars in non-decreasing, then calculate the area by popping out the stack to get the currently lowest bar which determines the height of the rectangle.
\\
Core clues:
\begin{enumerate}
\item \textbf{Invariant}: Maintain the non-decreasing stack, using INDEX.
\item Popping triggers the calculation of area
\item Calculate the rectangle width by index diff
\item Post-processing in the end
\end{enumerate}
\newpage
Code:
\begin{python}
def largestRectangleArea(self, height):
    n = len(height)
    gmax = -sys.maxint-1
    stk = []  # store the idx, non-decreasing stack

    for i in xrange(n):
        while stk and height[stk[-1]] > height[i]:
            last = stk.pop()
            if stk:  # calculate area when popping
                area = height[last]*(i-(stk[-1]+1))
            else:
                area = height[last]*i
            gmax = max(gmax, area)

        stk.append(i)

    # after array scan, process the dangling stack
    i = n
    ...

    return gmax
\end{python}

\runinhead{Longest Valid Parentheses.}
Given a string containing just the characters `(' and `)', find the length of the longest valid (well-formed) parentheses substring. Core clues:
\begin{enumerate}
\item \textbf{Invariant}: Stack holds the INDEX of UNPAIRED brackets, either ( or ).
\item Thus, \pyinline{stk[-1]} stores the last unpaired bracket.
\item The length of the well-formed parentheses is: if currently \textbf{valid}, current scanning index \pyinline{idx} minus the last \textbf{invalid} index of bracket \pyinline{stk[-1]}
\end{enumerate}
\begin{python}
def longestValidParentheses(self, s):
  stk = []
  maxa = 0
  for idx, val in enumerate(s):
    if val == ")" and stk and s[stk[-1]] == "(":
      stk.pop()
      if not stk:
        maxa = max(maxa, idx+1)
      else:
        maxa = max(maxa, idx-stk[-1])
    else:
      stk.append(idx)

  return maxa

\end{python}
\subsection{All nearest smaller values}\label{allNearestSmaller}
\textbf{Nearest smaller}. Left neighbor of a value $v$ to be the value that occurs prior to $v$, is smaller than $v$, and is closer in position to $v$ than any other smaller value.

For each position in a sequence of numbers, search among the \textit{previous} positions for the last position that contains a smaller value.

Core clues:
\begin{enumerate}
\item Nearest $\equiv$ spactial locality.
\item \textbf{Invariant}: Maintain a \textit{strictly increasing} stack.
\item If all nearest \textit{larger} values, maintain a \textit{strictly decreasing} stack.
\end{enumerate}

\begin{python}
def allNearestSmaller(self, A):
    P = [-1 for _ in A]
    stk = []
    for i, v in enumerate(A):
        while stk and A[stk[-1]] >= v: stk.pop()

        if stk:
            P[i] = stk[-1]
        else:
            P[i] = -1  # no preceding smaller value

        stk.append(i)  # store the idx or val

    return P
\end{python}

\section{Map}
\subsection{Math relations}
\textbf{1-1 Map}. Mathematically, full projection. One map, dual entries.
\begin{python}
class OneToOneMap(object):
    def __init__(self):
        self.m = {}  # keep a single map

    def set(self, a, b):
        self.m[a] = b
        self.m[b] = a

    def get(self, a):
        return self.m.get(a)
\end{python}
\subsection{Operations}
\runinhead{Sorting by value.} Sort the map entries by values \pyinline{itemgetter}.
\begin{python}
from operators import itemgetter
sorted(hm.items(), key=itemgetter(1), reverse=True)
sorted(hm.items(), key=lambda x: x[1], reverse=True)
\end{python}


\documentclass{amsart}

\newcommand{\e}{{\mathbf e}}
\newcommand\tr{\mathop{\text{tr}}}

\title{Using the FEC Software}

\begin{document}

\maketitle

\noindent
The {\tt fec} software is invoked by the command
\begin{center}
{\tt fec -p parameter-file.txt}
\end{center}
where {\tt parameter-file.txt} is a text file that sets various parameters, described below.  The command can be invoked with two other command line options, for example:
\begin{center}
{\tt fec -p parameter-file.txt -o output-file -v10}
\end{center}
where {\tt output-file} is the output file, which will default to {\tt s.out} if not specified, and {\tt -v} denotes verbose output, and if followed by a number $n$, will write out to the console every $n$th time it writes data to the output file.

The program {\tt fec} uses the Fast Exact Closure (FEC) to solve Jeffery's equation \cite{jeffery} with diffusion for the second order moment tensor $A$:
$$ \frac {\partial A}{\partial t} = \tfrac12(\Omega\cdot A - A\cdot\Omega + \lambda(\Gamma\cdot A+A\cdot \Gamma) - 2 \lambda \mathbb A:\Gamma) + D_r (2I-6A) ,$$
where $\Gamma$ is the rate of strain tensor, $\Omega$ is the vorticity tensor, and $\mathbb A$ is the fourth order moment tensor computed from $A$ using the exact closure.

\section*{Basic Parameters}

\noindent
The parameter file consists of a number of lines, each of the form
\begin{center}
{\tt parameter=value}
\end{center}
The order in which they are written in the parameter file is unimportant.

\begin{itemize}
\item The start time and stop time are set by parameters {\tt tstart} and {\tt tend}.
\item The rate of strain tensor is set by parameters {\tt gamma11}, {\tt gamma12}, {\tt gamma13}, {\tt gamma22}, {\tt gamma23}, {\tt gamma33}.
\item The vorticity is set by parameters {\tt w1}, {\tt w2}, {\tt w3}.
\item The initial state is $\psi = 1/4\pi$.  Later versions of the software may allow this to be different.
\item By default the program will solve the differential equations using the order four-five Runge-Kutta-Fehlberg method.
\item The parameter set as {\tt ode\_rk\_4=1} will cause the program will use the order four Runge-Kutta method.
\item For the Runge-Kutta method, the step size of time is set by the parameter {\tt h}.  For adaptive methods, this parameter sets the initial step size of time.  This defaults to $10^{-3}$ if not set.
\item For the adaptive Runge-Kutta-Fehlberg method, the parameter {\tt tol} sets the desired error.  This defaults to $10^{-3}$ if it is not set.
\item Data will be printed to the output file every {\tt print\_every} time steps.  This defaults to $1$ if it is not set.
\item The parameter set as {\tt do\_reset=1} makes the program slightly slower, but slightly more accurate in the case that the eigenvalues of $A$ are sometimes not all distinct.
\end{itemize}

\section*{Output}

\noindent
The program, by default, will write to the output file a series of lines containing
\begin{center}$t$ $a_{11}$ $a_{12}$ $a_{13}$ $a_{22}$ $a_{23}$ $a_{33}$\end{center}
where $a_{ij}$ denotes the entries of $A$.  If the command line option {\tt -v} with a number is specified, the program will write this same information to the console.  Here $a_{ij}$ are the coefficients of the second moments tensor.

\section*{Folgar-Tucker model}

\noindent
The program will default to solving Jeffery's equation with the Folgar-Tucker diffusion term \cite{folgar}.  This sets the diffusion term to $ D_r = C_I \gamma $.
Here, and elsewhere, $\gamma = \left(\frac12\Gamma:\Gamma\right)^{1/2}$.
\begin{itemize}
\item The parameter {\tt lambda} is the Jeffery's parameter $\lambda$.
\item The parameter {\tt CI} sets the parameter $C_I$.
\end{itemize}

\section*{The ARD model of Phelps and Tucker}

\noindent
This ``Anisotropic Rotary Diffusion'' model is described in \cite{ard}.
\begin{align*}
\frac {\partial A}{\partial t} = &\tfrac12(\Omega\cdot A - A\cdot\Omega + \lambda(\Gamma\cdot A+A\cdot \Gamma) - 2 \lambda \mathbb A:\Gamma) \\
& + 2D_r -2(\tr D_r)A - 5(A\cdot D_r+D_r\cdot A) + 10 \mathbb A:D_r .
\end{align*}
Here
$$ D_r = b_1 \gamma I + b_2 \gamma A + b_3 \gamma A^2 + \tfrac12{b_4} \Gamma + \tfrac14{b_5}\gamma^{-1} \Gamma^2 .$$

\begin{itemize}
\item The parameter set as {\tt do\_ard=1} causes ARD to be used.
\item The parameters {\tt b1}, {\tt b2}, {\tt b3}, {\tt b4} and {\tt b5} set $b_1$, $b_2$, $b_3$, $b_4$ and $b_5$.
\end{itemize}

\section*{The RSC model of Wang, O'Gara and Tucker}

\noindent
This causes an artificial scaled reduction of the evolution of $\psi$, the ``Reduced-Strain Closure" model.  This can be used in conjunction with any of the other models.  It is described in \cite{rsc}.  It causes the P.D.E.\
$$ \frac{\partial A}{\partial t} = F(A),$$
to be replaced by
$$ \frac{\partial A}{\partial t} = F(A) - (1-\kappa)\mathbb M: F(A),$$
where $\mathbb M = \sum_{i=1}^3 \e_i\e_i\e_i\e_i$, with $\e_1$, $\e_2$, $\e_3$ being the orthonormal eigenvectors of $A$.

This method has intellectual property restrictions \cite{rsc-pat}.  If you use {\tt do\_rsc=1}, the program will interrogate you to see if you comply with this patent.  You may switch off the interrogation by setting the environment variable {\tt MAY\_USE\_PATENT\_7266469}.

\begin{itemize}
\item The parameter set as {\tt do\_rsc=1} causes RSC to take place.
\item The parameter {\tt kappa} sets the scale reduction factor $\kappa$.
\end{itemize}

\section*{Acknowledgments}

\noindent
This work was supported by the National Science Foundation, Division of Civil, Mechanical and Manufacturing Innovation, award number 0727399 (NSF CMMI 0727399).

\begin{thebibliography}{99}
\bibitem{jeffery}
G.B. Jeffery, The Motion of Ellipsoidal Particles Immersed in a Viscous Fluid, Proceedings of the Royal Society of London A {\bf 102}, 161-179, (1923).
\bibitem{folgar}
F.P. Folgar and C.L. Tucker, Orientation Behavior of Fibers in Concentrated Suspensions, Jn. of Reinforced Plastics and Composites {\bf 3}, 98-119 (1984).
\bibitem{rsc-pat}
C.L. Tucker III, J. Wang, and J.F. O'Gara, Method and article of manufacture for determining a rate of change of orientation of a plurality of fibers disposed in a fluid. U.S. Patent No. 7,266,469 (2007).
\bibitem{rsc}
Jin Wang, John F. O'Gara, and Charles L. Tucker, III, An objective model for slow orientation kinetics in concentrated fiber suspensions: Theory and rheological evidence, J. Rheology {\bf 52}, 1179-1200 (2008).
\bibitem{ard}
Jay H. Phelps and Charles L. Tucker III, An anisotropic rotary diffusion model for fiber orientation in short- and long-fiber thermoplastics, Journal of Non-Newtonian Fluid Mechanics, to appear (2008).
\end{thebibliography}

\end{document}


\documentclass{article}

\usepackage{Sweave}

\begin{document}
\subsection*{Introduction}

We generate 3D gaussian data,
We generate 3D Gaussian data,
\begin{Schunk}
\begin{Sinput}
R> set.seed(1)
R> n <- 100
R> x <- rnorm(n); y <- 2*x + rnorm(n)/2
R> U3 <- cbind(x, y, z = -3*x + y + rnorm(n)/4)
\end{Sinput}
\end{Schunk}
look at its structure
\begin{Schunk}
\begin{Sinput}
R> str(U3) # its structure ((comment kept))
\end{Sinput}
\begin{Soutput}
 num [1:100, 1:3] -0.626 0.184 -0.836 1.595 0.33 ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr [1:3] "x" "y" "z"
\end{Soutput}
\end{Schunk}
and load package \texttt{lattice}
\begin{Schunk}
\begin{Sinput}
R> if(!require("lattice")) q("no")
\end{Sinput}
\end{Schunk}
to visualize it by a simple scatter plot matrix
\begin{figure}[h!]
\centering
\begin{Schunk}
\begin{Sinput}
R> splom(U3, xlab ="", cex = 0.4)
\end{Sinput}
\end{Schunk}
\includegraphics{swv-keepSrc-1-splom}
\caption{100 vectors of random variates ... ...}
\label{fig:AC_Joe}
\end{figure}

\subsection*{Session Information}

\begin{Schunk}
\begin{Sinput}
R> toLatex(sessionInfo())
\end{Sinput}
\begin{itemize}\raggedright
  \item R version 4.0.3 (2020-10-10), \verb|x86_64-pc-linux-gnu|
  \item Locale: \verb|LC_CTYPE=en_US.UTF-8|, \verb|LC_NUMERIC=C|, \verb|LC_TIME=en_US.UTF-8|, \verb|LC_COLLATE=en_US.UTF-8|, \verb|LC_MONETARY=en_US.UTF-8|, \verb|LC_MESSAGES=C|, \verb|LC_PAPER=en_US.UTF-8|, \verb|LC_NAME=C|, \verb|LC_ADDRESS=C|, \verb|LC_TELEPHONE=C|, \verb|LC_MEASUREMENT=en_US.UTF-8|, \verb|LC_IDENTIFICATION=C|
  \item Running under: \verb|Ubuntu 20.04.1 LTS|
  \item Matrix products: default
  \item BLAS/LAPACK: \verb|/usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.8.so|
  \item Base packages: base, datasets, graphics, grDevices,
    methods, stats, utils
  \item Other packages: lattice~0.20-41
  \item Loaded via a namespace (and not attached):
    compiler~4.0.3, grid~4.0.3, tools~4.0.3
\end{itemize}\end{Schunk}

\end{document}


% !TeX spellcheck = en_US
% !TeX root = DynELA.tex
%
% LaTeX source file of DynELA FEM Code
%
% (c) by Olivier Pantalé 2020
%
\chapter{DynELA single element sample cases}

\startcontents[chapters]
\printmyminitoc[1]\LETTRINE{T}his chapter deals with some numerical applications of
the \DynELA~for dynamic applications in 2D, axi-symmetric and 3D
cases. In the subsequent tests, if not specified, a Johnson-Cook constitutive
law is used to model the behavior of the material. The Johnson-Cook
hardening flow law is probably the most widely used flow law for the
simulation of high strain rate deformation processes taking into account
plastic strain, plastic strain rate and temperature effects. Since
a lot of efforts have been made in the past to identify the constitutive
flow law parameters for many materials, it is implemented in numerous
Finite Element codes such as Abaqus \cite{abaqus20146}. The general
formulation of the Johnson-Cook law $\sigma^{y}(\overline{\varepsilon}^{p},\stackrel{\bullet}{\overline{\varepsilon}^{p}},T)$
is given by the following equation:

\begin{equation}
\sigma^{y}=\left(A+B\overline{\varepsilon}^{p^{n}}\right)\left[1+C\ln\left(\frac{\stackrel{\bullet}{\overline{\varepsilon}^{p}}}{\stackrel{\bullet}{\overline{\varepsilon}_{0}}}\right)\right]\left[1-\left(\frac{T-T_{0}}{T_{m}-T_{0}}\right)^{m}\right]\label{eq:Samples!Johnson-Cook}
\end{equation}
where $\stackrel{\bullet}{\overline{\varepsilon}_{0}}$ is the reference
strain rate, $T_{0}$ and $T_{m}$ are the reference temperature and
the melting temperature of the material respectively and $A$, $B$,
$C$, $n$ and $m$ are the five constitutive flow law parameters.
A 42CrMo4 steel following the Johnson-Cook behavior law has been selected
for all those tests, and material properties are reported in Table
\ref{tab:Samples!JohnsonCookParameters}.

\begin{table}[h]
\begin{center}\begin{tcolorbox}[width=.75\textwidth,myTab,tabularx={C|C|C|C|C|C|C}]
$E$ & $\nu$ & $A$ & $B$ & $C$ & $n$ & $m$ \\
\small{($Gpa$)} &  & \small{($MPa$)} & \small{($MPa$)} &  &  & \\ \hline
$206.9$ & $0.3$ & $806$ & $614$ & $0.0089$ & $0.168$ & $1.1$ \\ \hline\hline
$\rho$ & $\lambda$ & $C_{p}$ & $\eta$ & $\stackrel{\bullet}{\overline{\varepsilon}_{0}}$ & $T_{0}$ & $T_{m}$ \\
\small{$(kg/m^{3})$} & \small{$(W/m^{\circ}C)$} & \small{$(J/Kg^{\circ}C)$} & & \small{$(s^{-1})$} & \small{$(^{\circ}C)$} & \small{$(^{\circ}C)$} \\ \hline
$7830$ & $34.0$ & $460$ & $0.9$ & $1.0$ & $20$ & $1540$
\end{tcolorbox}\end{center}

\caption{Material parameters of the Johnson-Cook behavior for the numerical
tests\label{tab:Samples!JohnsonCookParameters}}
\end{table}

\section{Uniaxial tensile tests}

\subsection{Element plane tensile test}

The uniaxial one element tensile test is a numerical test where an
plane element (with a square prescribed shape) is subjected to pure
tensile as presented in figure \ref{fig:Samples!Single!Tensile}.
\begin{figure}[h]
\begin{centering}
\includegraphics[width=0.5\columnwidth]{Figures/SamplesSingleTensile}
\par\end{centering}
\caption{Numerical model for the one element tensile test\label{fig:Samples!Single!Tensile}}
\end{figure}
 The initial shape of the specimen is $10\,mm\times10\,mm$, the two
left nodes of the element are encastred and a prescribed horizontal
displacement $d=10\,mm$ is applied on the two right nodes of the
same element as illustrated in Figure \ref{fig:Samples!Single!Tensile}.
As we are using an explicit integration scheme, the total simulation
time is set to $t=0.01\,s$.

All the properties of the constitutive law reported in Table \ref{tab:Samples!JohnsonCookParameters}
are used and the material is assumed to follow the Johnson-Cook behavior
described by equation \ref{eq:Samples!Johnson-Cook}.

Figure \ref{fig:Samples!Single!Tensile-Comparison} shows the comparison
of the DynELA solver results (plotted in red) and the Abaqus numerical
results (plotted in blue) concerning the evolution of the stress components
$\sigma_{11}$, $\sigma_{22}$, $\sigma_{12}$, $\overline{\sigma}$,
$\overline{\varepsilon}^{p}$ and $T$ \versus  the horizontal displacement
of the right edge of the specimen along the horizontal axis. For the
Abaqus model, the exact same mesh has been used. Comparison of Abaqus
and DynELA results is made by averaging the DynELA results on the
$4$ integration points of the element. This has been done because
\DynELA~uses full integrated elements while Abaqus have reduced
integrated elements only but in fact, the DynELA results at the $4$
integration points are the same in this benchmark test.

\begin{figure}[h]
\begin{centering}
\begin{tabular}{cc}
\includegraphics[width=0.45\columnwidth]{Figures/Samples/Element/Tensile_stress_11} & \includegraphics[width=0.45\columnwidth]{Figures/Samples/Element/Tensile_stress_22}\tabularnewline
\includegraphics[width=0.45\columnwidth]{Figures/Samples/Element/Tensile_stress_12} & \includegraphics[width=0.45\columnwidth]{Figures/Samples/Element/Tensile_vonMises}\tabularnewline
\includegraphics[width=0.45\columnwidth]{Figures/Samples/Element/Tensile_plasticStrain} & \includegraphics[width=0.45\columnwidth]{Figures/Samples/Element/Tensile_temperature}\tabularnewline
\end{tabular}
\par\end{centering}
\caption{Comparison of numerical and analytical results for the one element
tensile test\label{fig:Samples!Single!Tensile-Comparison}}
\end{figure}
\clearpage

\subsection{Element 3D tensile test}

The uniaxial one element 3D tensile test is a numerical test where
a 3D brick element (with a cubic prescribed shape) is subjected to
radial tensile as presented in figure \ref{fig:Samples!Single!Tensile-3D}.
No boundary condition has been prescribed on the $\overrightarrow{z}$
direction, so that the reduction of the width during the test can
occur. The initial shape of the specimen is $10\,mm\times10\,mm\times10\,mm$
and the the two left nodes of the element are restrained for their
displacements along the $\overrightarrow{x}$ and $\overrightarrow{y}$
directions and a prescribed horizontal displacement $d=10\,mm$ is
applied on the two right nodes of the same element as illustrated
in Figure \ref{fig:Samples!Single!Tensile-3D}. As we are using an
explicit integration scheme, the total simulation time is set to $t=0.01\,s$.
\begin{figure}[h]
\begin{centering}
\includegraphics[width=0.5\columnwidth]{Figures/SamplesSingleTensile3D}
\par\end{centering}
\caption{Numerical model for the one element tensile test\label{fig:Samples!Single!Tensile-3D}}
\end{figure}

All the properties of the constitutive law reported in Table \ref{tab:Samples!JohnsonCookParameters}
are used and the material is assumed to follow the Johnson-Cook behavior
described by equation \ref{eq:Samples!Johnson-Cook}.

Figure \ref{fig:Samples!Single!Tensile-Comparison-3D} shows the comparison
of the DynELA solver results (plotted in red) and the Abaqus numerical
results (plotted in blue) concerning the evolution of the stress components
$\sigma_{11}$, $\sigma_{22}$, $\sigma_{12}$, $\overline{\sigma}$,
$\overline{\varepsilon}^{p}$ and $T$ \versus  the horizontal displacement
of the right edge of the specimen along the horizontal axis. For the
Abaqus model, the exact same mesh has been used. Comparison of Abaqus
and DynELA results is made by averaging the DynELA and the Abaqus
results on the $8$ integration points of the element.

\begin{figure}[h]
\begin{centering}
\begin{tabular}{cc}
\includegraphics[width=0.45\columnwidth]{Figures/Samples/Element/Tensile3D_stress_11} & \includegraphics[width=0.45\columnwidth]{Figures/Samples/Element/Tensile3D_stress_22}\tabularnewline
\includegraphics[width=0.45\columnwidth]{Figures/Samples/Element/Tensile3D_stress_12} & \includegraphics[width=0.45\columnwidth]{Figures/Samples/Element/Tensile3D_vonMises}\tabularnewline
\includegraphics[width=0.45\columnwidth]{Figures/Samples/Element/Tensile3D_plasticStrain} & \includegraphics[width=0.45\columnwidth]{Figures/Samples/Element/Tensile3D_temperature}\tabularnewline
\end{tabular}
\par\end{centering}
\caption{Comparison of numerical and analytical results for the 3D one element
tensile test\label{fig:Samples!Single!Tensile-Comparison-3D}}
\end{figure}

\subsection{Element radial tensile test}

The uniaxial one element radial tensile test is a numerical test where
an axisymmetric element (with a square prescribed shape) is subjected
to pure radial tensile as presented in figure \ref{fig:Samples!Single!Tensile}.
The initial shape of the specimen is $10\,mm\times10\,mm$ and the
the two left nodes of the element are encastred and a prescribed horizontal
displacement $d=10\,mm$ is applied on the two right nodes of the
same element as illustrated in Figure \ref{fig:Samples!Single!Tensile}.
As we are using an explicit integration scheme, the total simulation
time is set to $t=0.01\,s$.

All the properties of the constitutive law reported in Table \ref{tab:Samples!JohnsonCookParameters}
are used and the material is assumed to follow the Johnson-Cook behavior
described by equation \ref{eq:Samples!Johnson-Cook}.

Figure \ref{fig:Samples!Single!Radial-Comparison} shows the comparison
of the DynELA solver results (plotted in red) and the Abaqus numerical
results (plotted in blue) concerning the evolution of the stress components
$\sigma_{11}$, $\sigma_{22}$, $\sigma_{12}$, $\overline{\sigma}$,
$\overline{\varepsilon}^{p}$ and $T$ \versus  the horizontal displacement
of the right edge of the specimen along the horizontal axis. Again,
comparison of Abaqus and DynELA results is made by averaging the DynELA
results on the $4$ integration points of the element because \DynELA~uses
full integrated elements while Abaqus have reduced integrated elements
only but in fact, the DynELA results at the $4$ integration points
are the same in this benchmark test.

\begin{figure}[h]
\begin{centering}
\begin{tabular}{cc}
\includegraphics[width=0.45\columnwidth]{Figures/Samples/Element/Radial_stress_11} & \includegraphics[width=0.45\columnwidth]{Figures/Samples/Element/Radial_stress_22}\tabularnewline
\includegraphics[width=0.45\columnwidth]{Figures/Samples/Element/Radial_stress_12} & \includegraphics[width=0.45\columnwidth]{Figures/Samples/Element/Radial_vonMises}\tabularnewline
\includegraphics[width=0.45\columnwidth]{Figures/Samples/Element/Radial_plasticStrain} & \includegraphics[width=0.45\columnwidth]{Figures/Samples/Element/Radial_temperature}\tabularnewline
\end{tabular}
\par\end{centering}
\caption{Comparison of numerical and analytical results for the one element
radial tensile test\label{fig:Samples!Single!Radial-Comparison}}
\end{figure}
\clearpage

\subsection{Element radial torus test}

The uniaxial one element torus tensile test is a numerical test where
an axisymmetric element (with a square prescribed shape) is subjected
to radial tensile as presented in figure \ref{fig:Samples!Single!Torus}.
\begin{figure}[h]
\begin{centering}
\includegraphics[width=0.5\columnwidth]{Figures/SamplesSingleTorus}
\par\end{centering}
\caption{Numerical model for the one element torus test\label{fig:Samples!Single!Torus}}
\end{figure}
 The difference with the previous test is that the left edge of the
specimen in not aligned with the symmetry axis, the radial coordinate
of the left edge is $r=10\,mm$. The initial shape of the specimen
is $10\,mm\times10\,mm$ and a prescribed horizontal displacement
$d=10\,mm$ is applied on the two left nodes of the element as illustrated
in Figure \ref{fig:Samples!Single!Torus}. As we are using an explicit
integration scheme, the total simulation time is set to $t=0.01\,s$.
All the properties of the constitutive law reported in Table \ref{tab:Samples!JohnsonCookParameters}
are used and the material is assumed to follow the Johnson-Cook behavior
described by equation \ref{eq:Samples!Johnson-Cook}.

As a global comparison, Figure \ref{fig:Samples!Single!Torus-Comparison-ux}
show the comparison of the right edge displacement \versus the left
edge displacement for both the DynELA and the Abaqus simulations.
\begin{figure}[h]
\begin{centering}
\includegraphics[width=0.5\columnwidth]{Figures/Samples/Element/Torus_dispX}
\par\end{centering}
\caption{Comparison of the right edge displacement for the one element torus
test\label{fig:Samples!Single!Torus-Comparison-ux}}
\end{figure}

Figure \ref{fig:Samples!Single!Torus-Comparison} shows the comparison
of the DynELA solver results (plotted in red) and the Abaqus numerical
results (plotted in blue) concerning the evolution of the stress components
$\sigma_{11}$, $\sigma_{22}$, $\sigma_{12}$, $\overline{\sigma}$,
$\overline{\varepsilon}^{p}$ and $T$ \versus  the horizontal displacement
of the right edge of the specimen along the horizontal axis. As the
Abaqus software only provides under-integrated elements, we are using
a $2\times2$ elements mesh for the Abaqus model, as presented in
Figure \ref{fig:Samples!Single!Torus-Abaqus}, to compare the results.
On abaqus, the mean value of the results of the $4$ elements is computed
and compared to the mean value of the $4$ integration points of the
DynELA simulation.
\begin{figure}[h]
\begin{centering}
\includegraphics[width=0.5\columnwidth]{Figures/SamplesSingleTorusAbaqus}
\par\end{centering}
\caption{Numerical model for the one element torus test under Abaqus\label{fig:Samples!Single!Torus-Abaqus}}
\end{figure}

\begin{figure}[h]
\begin{centering}
\begin{tabular}{cc}
\includegraphics[width=0.45\columnwidth]{Figures/Samples/Element/Torus_stress_11} & \includegraphics[width=0.45\columnwidth]{Figures/Samples/Element/Torus_stress_22}\tabularnewline
\includegraphics[width=0.45\columnwidth]{Figures/Samples/Element/Torus_stress_12} & \includegraphics[width=0.45\columnwidth]{Figures/Samples/Element/Torus_vonMises}\tabularnewline
\includegraphics[width=0.45\columnwidth]{Figures/Samples/Element/Torus_plasticStrain} & \includegraphics[width=0.45\columnwidth]{Figures/Samples/Element/Torus_temperature}\tabularnewline
\end{tabular}
\par\end{centering}
\caption{Comparison of numerical results for the one element torus tensile
test\label{fig:Samples!Single!Torus-Comparison}}
\end{figure}
\clearpage

\section{Uniaxial one element shear test}

The uniaxial one element shear test is a numerical test where an element
(with a square prescribed shape) is subjected to pure shear test as
presented in figure \ref{fig:Samples!Single!Shear}.
\begin{figure}[h]
\begin{centering}
\includegraphics[width=0.5\columnwidth]{Figures/SamplesSingleShear}
\par\end{centering}
\caption{Numerical model for the one element shear test\label{fig:Samples!Single!Shear}}
\end{figure}
 The initial shape of the specimen is $10\,mm\times10\,mm$ and the
the two bottom nodes of the element are encastred and a prescribed
horizontal displacement $d=100\,mm$ is applied on the two upper nodes
of the same element as illustrated in Figure \ref{fig:Samples!Single!Shear}.
As we are using an explicit integration scheme, the total simulation
time is set to $t=0.01\,s$. Mechanical properties of the material
are reported in Table \ref{tab:Samples!JohnsonCookParameters}.

Comparison of Abaqus and DynELA results is made by averaging the DynELA
results on the $4$ integration points of the element. This has been
done because \DynELA~uses full integrated elements while Abaqus
have reduced integrated elements only but in fact, the DynELA results
at the $4$ integration points are the same in this benchmark test.

\subsection{Elastic case}

In this case, only the elastic properties of the constitutive law
reported in Table \ref{tab:Samples!JohnsonCookParameters} are used
and the material is assumed to be hyper-elastic. As we are using a
Jaumann objective rate within the \DynELA, one can obtain, using
an analytical development, the following results for the proposed
case:
\begin{equation}
\Sig=G\left[\begin{array}{ccc}
1-\cos e & \sin e & 0\\
 & \cos e-1 & 0\\
sym &  & 0
\end{array}\right],
\end{equation}
where $G=\mu=\frac{E}{2(1+\nu)}$ is the shear modulus of the material
and $e$ is the elongation along the horizontal axis with $e_{max}=10$
conforming to the prescribed boundaries conditions. Figure \ref{fig:Samples!Single!Shear-Elastic-Comparison}
shows the comparison of the DynELA solver results (plotted in red)
and both the analytical (plotted in blue) and the Abaqus numerical
results (plotted in green) concerning the evolution of the stress
components $\sigma_{11}$, $\sigma_{22}$, $\sigma_{12}$ and $\overline{\sigma}$
\versus  the horizontal displacement of the top edge of the specimen
along the horizontal axis. A perfect match between all those results
can be seen from this later.

\begin{figure}[h]
\begin{centering}
\begin{tabular}{cc}
\includegraphics[width=0.45\columnwidth]{Figures/Samples/Element/Shear-Elastic_stress_11} & \includegraphics[width=0.45\columnwidth]{Figures/Samples/Element/Shear-Elastic_stress_22}\tabularnewline
\includegraphics[width=0.45\columnwidth]{Figures/Samples/Element/Shear-Elastic_stress_12} & \includegraphics[width=0.45\columnwidth]{Figures/Samples/Element/Shear-Elastic_vonMises}\tabularnewline
\end{tabular}
\par\end{centering}
\caption{Comparison of numerical and analytical results for the one element
elastic shear test\label{fig:Samples!Single!Shear-Elastic-Comparison}}
\end{figure}
\clearpage

\subsection{Johnson-Cook plastic behaviour}

In this case, all the properties of the constitutive law reported
in Table \ref{tab:Samples!JohnsonCookParameters} are used and the
material is assumed to follow the Johnson-Cook behavior described
by equation \ref{eq:Samples!Johnson-Cook}. Figure \ref{fig:Samples!Single!Shear-Comparison}
shows the comparison of the DynELA solver results (plotted in red)
and the Abaqus numerical results (plotted in blue) concerning the
evolution of the stress components $\sigma_{11}$, $\sigma_{22}$,
$\sigma_{12}$, $\overline{\sigma}$, $\overline{\varepsilon}^{p}$
and $T$ \versus  the horizontal displacement of the top edge of
the specimen along the horizontal axis.

\begin{figure}[h]
\begin{centering}
\begin{tabular}{cc}
\includegraphics[width=0.45\columnwidth]{Figures/Samples/Element/Shear-Plastic_stress_11} & \includegraphics[width=0.45\columnwidth]{Figures/Samples/Element/Shear-Plastic_stress_22}\tabularnewline
\includegraphics[width=0.45\columnwidth]{Figures/Samples/Element/Shear-Plastic_stress_12} & \includegraphics[width=0.45\columnwidth]{Figures/Samples/Element/Shear-Plastic_vonMises}\tabularnewline
\includegraphics[width=0.45\columnwidth]{Figures/Samples/Element/Shear-Plastic_plasticStrain} & \includegraphics[width=0.45\columnwidth]{Figures/Samples/Element/Shear-Plastic_temperature}\tabularnewline
\end{tabular}
\par\end{centering}
\caption{Comparison of numerical and analytical results for the one element
shear test\label{fig:Samples!Single!Shear-Comparison}}
\end{figure}


\section{Introduction\label{sec:intro}}

Linear elliptic homogeneous partial differential equations (\pdes) play an important role in modeling many physical interactions, including
electrostatics, elastostatics, acoustic scattering, and viscous fluid flow.
Using ideas from potential theory allow us to reformulate the associated boundary value problem (\bvp) as an integral equation.
The solution to the \bvp can then be expressed as a layer potential, i.e., a surface convolution against the \pde's fundamental solution.
Discretizing the integral equation formulation offers several potential advantages over common used direct \pde discretization methods such as finite element or finite volume methods.

First, the system of equations uses asymptotically fewer variables because only the domain boundary requires discretization.
There is no need to discretize the volume, which is often the most time-consuming
and error-prone task in the full simulation pipeline, especially if complex boundary geometry is involved.
This aspect of integral formulations is particularly important for problems with changing geometries such as particulate flows, or flows with deforming boundaries, as well as moving boundaries.
Second, while the algebraic system resulting from discretization is dense, efficient $O(N)$ methods are available to solve it.
A suitable integral formulation can yield a well-conditioned system that can be solved using an iterative method like \gmres in relatively few iterations.
Third, high-order quadrature rules for smooth functions can be leveraged to dramatically improve the accuracy for a given discretization size over a standard method.
In other words, integral equation solvers can be both more efficient, usually if high accuracy is desired, and more robust, as they do not require volume meshing.

For elliptic problems with smooth (or mostly smooth) domain boundaries, high-order methods have a significant advantage over standard methods, drastically reducing the number of degrees of freedom needed to approximate a solution to a given accuracy.
However, realizing this potential presents a significant challenge: for integral equation methods to achieve high-order accuracy, they require a high-order quadrature and a high-order surface approximation to compute the integrals accurately.

One of the main difficulties in constructing high\-order boundary integral equation (\bie) solvers is the need for accurate quadrature rules for \emph{singular} integrals, as
the formulation requires the solution of an integral equation involving the singular fundamental solution of the \pde.
Moreover, if the solution needs to be evaluated arbitrarily close to the boundary, then one must numerically compute \emph{nearly singular} integrals with high-order accuracy.
In some sense, the near singular integrals are even more difficult to handle compared to singular integrals, since simple change of variable techniques that are often used to eliminate singularities on the boundary are harder to apply.
Precomputing high-order singular/near-singular quadrature weights also presents a considerable problem, as these necessarily depend on the local surface shape and different sets of weights are required for each sample point.
Furthermore, the sampling density required for accurate singular/near-singular integration is highly dependent on the boundary geometry.
For example, two nearly touching pieces of the boundary require a sampling density proportional to the distance between them; applying such a fine discretization globally will become prohibitively expensive.

%In this paper, we present a new, high-order, boundary integral solver with the following features:
%(1) a standard tensor-product polynomial-based representation is used for surfaces, which enables compatibility with common geometric modeling surface representations and significantly simplifying parallelization.
%(2) We rely on a scheme that reduces the computation of near-singular \emph{and} singular integrals to computation of non-singular integrals at a set of \emph{check points} sufficiently well separated from the surface.
%(3) We use a fully automatic adaptive refinement scheme to ensure necessary geometric criteria on the surface discretization for accurate integration.
%(4) We describe an accurate heuristic error estimate driving the second adaptive refinement stage.
%
%We next discuss the related work, and then summarize our contributions in greater detail in context.

\subsection{Contributions}
We introduce a new, high-order boundary integral solver for non-oscillatory elliptic \pdes.
A preliminary parallel version of this method is used in \cite{lu2019scalable} to simulate red blood cell flows through complex blood vessel with high numerical accuracy.
We describe the
%non-parallel
singular/near\-singular quadrature scheme for single- and double-layer potentials with the following features:
\begin{itemize}
\item {\bf Surface representation.} %Compared to \cite{YBZ}, which uses a specialized overlapping-patch surface representation from \cite{ying2004simple},
  We use standard B\'ezier patches to define the domain boundary, which simplifies the use of the solver on \abbrev{CAD} geometry, increases the efficiency of surface evaluation and simplifies parallelization.
        %(In comparison, previous work has used high-order global parametrization, such as tensor-product Fourier basis functions \cite{malhotra2019taylor}, high-order triangle surface elements \cite{wala20193d}, or high-order patch-based manifold constructions \cite{bruno2007accurate, ying2004simple}.) \note[DZ]{Seems out of place, why talk about previous work in the middle of contributions?}
        We use a \emph{quad-tree} of patches that allows us to approximate complex surfaces with nonuniform curvature distribution efficiently and to refine sampling as required by surface quadrature.
   Our method extends directly to other surface representation.

\item {\bf Singular and near-singular quadrature.}
We introduce an approximation-based singular/near\-singular quadrature scheme for single- and double-layer potentials in \threed: after computing the solution at a set of nearby \textit{check points}, placed along a line intersecting the target, we extrapolate the solution to the target point.
We have named this scheme \qbkix, for reasons that are apparent from \Cref{fig:qbkix-schematic}.
In order to ensure accuracy of the scheme for complex geometries, a key component of our scheme is a set of geometric criteria for surface sampling needed for accurate integration along with fast algorithms to refine the sampling adaptively so that these criteria are satisfied.

Our approach is originally motivated by the near-singular evaluation scheme of \cite{YBZ,QB}, which implements a similar scheme that includes an additional on-surface singular evaluation to allow for interpolation of the solution.
Removing this interpolation step and directly extrapolating solution values achieves optimal complexity without greatly affecting accuracy.

%Further improvements in our method are inspired by the recent algorithmic advances in the \qbx literature.
%As in \cite{RBZ}, our quadrature method relies solely on kernel evaluations and is therefore valid for any linear, constant-coefficient \pde, making it very simple algorithmically.
%However, rather than computing an approximate solution in a disk containing the target point, we construct an approximation along a line intersecting the target.
%This is similar to the work of \cite{ST}; a new set of check points is required for each target point, but each extrapolation has asymptotically optimal complexity.

\item{\bf Refinement for geometric admissibilty and quadrature accuracy.}
%Our geometric admissibility criteria are similar to \cite{wala20193d}. \note[DZ]{need to elaborate}
We present a set of criteria that allows for accurate integration via \qbkix called \textit{geometric admissibilty}.
This is similar in spirit to \cite{RKO} and \cite{wala20193d}, but adapted to the geometry of our particular quadrature scheme.
To guarantee quadrature accuracy of our method, we detail an adaptive $h$-refinement approach of the integral equation discretization based on a simple criteria to enable a fast refinement pipeline.
%To guarantee quadrature accuracy of our method, we opt for an adaptive $h$-refinement approach of the integral equation discretization rather than the $p$-refinement approach taken in \cite{wala20193d} and the adaptive global parameter selection approach of \cite{aT1}.
%This allows us to take boundary curvature and variation in the booundary data into account during upsampling.
%This allows for the quadrature resolution to vary across the boundary domain.
%\item {\bf Complexity analysis} We provide a detailed analysis of the geometry processing and query algorithms that \qbkix requires and demonstrate $O(N)$ complexity.
\item {\bf Error convergence and comparison} We apply \qbkix to a variety of problems on various geometries to demonstrate high-order convergence. We also compare our method with \cite{YBZ} to highlight the differences between global and local singular quadrature schemes.  We also solve Laplace and Stokes problems on challenging domain boundaries.
%\item{\bf Error estimate and heuristics.}
%    We demonstrate the error behavior of a simple \oned extrapolation of a singular function in finite arithmetic.
%    We have also derived an approximate, iteration-free error heuristic in \threed, similar to \cite{aT2}, that is used to determine the amount of upsampling required each patch.
%    Moreover, by only using point evaluation of the solution, we also avoid the \qbx-\fmm error coupling observed in \cite{RKO} and addressed in \cite{wala2018fast, wala20193d}.
\end{itemize}

\subsection{Related Work\label{sec:related_work}}
%In an effort to realize the benefits of boundary integral methods, the development of singular and near-singular integration methods has become a well-studied area of research.
We will restrict our discussion to elliptic \pde solvers in \threed using boundary integral formulations.
The common schemes to discretize boundary integral equations are the \textit{Galerkin} method, the \textit{collocation} method, and the \textit{\nystrom} method \cite{atkinson2009numerical}.
After choosing a set of basis functions to represent the solution, the Galerkin method forms a linear system for the coefficients of the solution by computing double integrals of the chosen basis functions multiplied by singular kernels.
The collocation method computes a set of unknown functions that match the solution at a prescribed set of points.
To form the required linear system, it assumes that an accurate quadrature rule is available for evaluating the layer potential at the discretization points.
For a particular choice of quadratures, collocation and \nystrom discretizations can lead to equivalent algebraic systems \cite[Chapter 13]{K}.
In this paper, we focus on the \emph{\nystrom} discretization, which is both simple (the integral in the equation is replaced by the quadrature approximation) and enables very efficient methods to solve the discretized integral equation.
The Galerkin and collocation approaches are commonly referred to as \textit{boundary element methods} (\bem) and have become very popular.
There have been many optimized \bem implementations for elliptic (Laplace, Helmholtz) and Maxwell problems.
One such implementation is \bem++, presented in \cite{smigaj2015solving}, with extensions for adaptivity added in \cite{bespalov2019adaptive,betcke2019adaptive}.
\cite{chaillat2017fast,chaillat2017theory} present iterative solvers for high-frequency scattering problems in elastodynamics, based on a \bem implementation coupled with fast summation methods to enable accurate solutions on complex triangle meshes.
For a more complete background of \bem, we refer the reader to \cite{steinbach2007numerical}.

A significant advancement in the field of finite element methods, called \textit{isogeometric analysis} (\iga)\cite{hughes2005isogeometric}, has been recently applied to boundary integral formulations.
\iga couples the basis functions defining the surface geometry with the analytic approaches for the finite element scheme.
Most relevant to this work, \iga has recently been applied to singular and hypersingular boundary integral equations with a collocation discretization \cite{taus2016isogeometric} with great success.
A \nystrom \iga method coupled with a regularized quadrature scheme is detailed in \cite{zechner2016isogeometric}.

%In the \bie literature, singular and near-singular integration schemes tend to fall into one of three categories: \textit{singularity cancellation} (remove the singularity via a change of variables), \textit{singularity subtraction} or \textit{asymptotic correction} methods.
In the \bie literature, singular and near-singular integration schemes fall into one of the several categories: \textit{singularity cancellation},  \textit{asymptotic correction}, \textit{singularity subtraction} or \textit{custom quadrature} schemes.
Singularity cancellation schemes apply a change of variables to remove the singularity in the layer potential, allowing for the application of standard smooth quadrature rules.
The first polar change of variables was detailed in the context of acoustic scattering \cite{bruno2001fast}, which leveraged a partition of unity and a polar quadrature rule to remove the singularity in the integrand of layer potential.
Fast summations were performed with \fft's and the periodic trapezoidal rule enables high-order convergence; the method was extended to open surfaces in \cite{bruno2013high}.
This methodology was applied to general elliptic \pdes in \cite{YBZ} and coupled with the kernel-independent fast multipole method \cite{ying2004kernel} and a $C^\infty$ surface representation for complex geometries \cite{ying2004simple}.
Recently, \cite{malhotra2019taylor} demonstrated that the choice of partition of unity function used for the change of variables has a dramatic effect on overall convergence order, although not in the context of elliptic \pdes.
The first singularity cancellation scheme in \threed on general surfaces composed of piecewise smooth triangles was presented in \cite{bremer2012nystrom,bremer2013numerical} by splitting a triangle into three subtriangles at the singularity and computing a polar integral on each new triangle.
\cite{ganesh2004high} introduced a change of variables method for acoustic scattering on \threed surfaces parametrized by spherical coordinates by integrating over a rotated coordinate system that cancels out the singularity.
\cite{abduljabbar2019extreme} outlines a fast exascale solver for soft body acoustic problems on triangle meshes \threed and using Duffy transforms as for singular/near-singular quadratures.

Asymptotic correction methods study the inaccuracies due to the singular \pde kernel with asymtotic analysis and apply a compensating correction. % which removes the singularity in the integrand but introduces errors in solution; corrections are applied to ensure high-order accuracy.
\cite{beale2004grid,beale2016simple,tlupova2019regularized} compute the integral with a regularized kernel and add corrections for regularization and discretization for the single and double layer Laplace kernel in \threed, along with the Stokeslet and stresslet in \threed.
\cite{carvalho2018asymptotic1} computes an asymptotic expansion of the kernel itself, which is used to remove the aliasing error incurred when applying smooth quadrature rules to near-singular layer potentials.
This method is extended to \threed in \cite{carvalho2018asymptotic} and a complete asymptotic analysis of the double-layer integral is performed in \cite{khatri2020close}.

Singularity subtraction methods \cite{jarvenpaa2003singularity, jarvenpaa2006singularity, nair2013singularity} explicitly subtract the singular component of the integrand, which produces a smooth bounded integral that can be integrated with standard quadrature rules.
Custom quadrature rules aim to integrate a particular family of functions to high-order accuracy.
This can allow for arbitrarily accurate and extremely fast singular integration methods, since the quadrature rules can be precomputed and stored \cite{alpert1999hybrid, xiao2010numerical}.

The most noteworthy singular quadrature scheme that does not fit into one of the above categories is that of \cite{HO}.
This method is similar to the second-kind barycentric interpolation \cite{BT}; it forms a rational function whose numerator and denominator compensates for the error as the target point approaches the boundary.
\cite{wu2020solution} has implemented an adaptive version of \cite{HO} for complex Stokes flows in \twod and
\cite{klinteberg2019accurate} have recently produced a remarkable extension to nearly-singular line integrals in \twod and \threed.
While this method performs exceptionally well in practice, it does not immediately generalize to \threed surfaces in an efficient manner.

The \textit{method of fundamental solutions}, which represents the solution as a sum of point charges on an equivalent surface outside of the \pde domain, removing the need for singular evaluation, has also seen a great deal of success in \twod \cite{barnett2008stability} and in axis-symmetric \threed problems \cite{liu2016efficient}. Recently, \cite{gopal2019solving} has introduced an \twod approach similar in spirit to the method of fundamental solutions for domains with corners, but formulated as a rational approximation problem in the complex plane rather than as a boundary integral equation.
The lack of singular integration makes these methods advantageous, but placing the point charges robustly can be challenging in practice.
General \threed geometries also remain a challenge.

There has been a great deal of recent work on special analyses of regions with corners \cite{SR,S,serkh2018solution,hoskins2019numerical,rachh2017solution,serkh2016solution}.
Rather than a dyadic refinement of the discretization toward corners to handle the artificial singularities, these works have shown that the solution can be appropriately captured with special quadratures for a certain class of functions.
Although not yet generalized to \threed, this work has the potential to vastly improve the performance of \threed \nystrom boundary integral methods on regions with corners and edges.

Our method falls into a final category: approximation-based quadrature schemes.
The first use of a local expansion to approximate a layer potential near the boundary of a \twod boundary was presented in \cite{barnett2014evaluation}.
By using an refined, or \textit{upsampled}, global quadrature rule to accurately compute coefficients of a Taylor series, the resulting expansion serves as a reasonable approximation to the solution near the boundary where quadrature rules for smooth functions are inaccurate.
This scheme was then adapted to evaluate the solution both near and on the boundary, called Quadrature by Expansion (\qbx) \cite{KBGN}.
The first rigorous error analysis of the truncation error of \qbx was carried out in \cite{EGK}.

Great progress has been made in this area since \cite{KBGN}.
A fast implementation of \qbx in \twod, along with a set of geometric constraints required for well-behaved convergence, was presented in \cite{RKO}.
However, the interaction of the expansions of \qbx and the expansions used in the translation operators of the \fmm resulted in a loss of accuracy, which required an artificially high multipole order to compensate.
\cite{wala2018fast} addresses this shortcoming by enforcing a confinement criteria on the location of expansion disks relative to \fmm tree boxes.
\cite{aT2} provided extremely tight error heuristics for various kernels and quadrature rules using contour integration and the asymptotic approach of \cite{elliott2008clenshaw}.
\cite{aT1} then leveraged these estimates in a \qbx algorithm for Laplace and Helmholtz problems in \twod that adaptively selects the amount of upsampled quadrature and the expansion order for each \qbx expansion.
In the spirit of \cite{ying2004kernel}, \cite{RBZ} generalizes \qbx to any elliptic \pde by using potential theory to form a local, least-squares solution approximation using only evaluations of the \pde's Green's function.

The first extension of \qbx to \threed  was \cite{ST}, where the authors present a \textit{local, target-specific } \qbx method on spheroidal geometries.
In a local \qbx scheme, an upsampled accurate quadrature is used as a local correction to the expansion coefficients computed from the coarse quadrature rule over the boundary.
This is in contrast with a \textit{global} scheme, where the expansion coefficients are computed from the upsampled quadrature with no need for correction.
The first local \qbx scheme appears in \cite{barnett2014evaluation} in \twod, but the notion of local \fmm corrections dates back to earlier work such as \cite{alpert1999hybrid, kapur1997high}.
The expansions in \cite{ST} computed in a target-specific \qbx scheme can only be used to evaluate a single target point, but each expansion can be computed at a lower cost than a regular expansion valid in a disk.
The net effect of both these algorithmic variations are greatly improved constants, which are required for complicated geometries in \threed.
In \cite{aT2}, very accurate error heuristics are derived for the tensor product Gauss-Legendre rule on a surface panel and a simple spheroidal geometry in \threed, which were then leveraged to estimate \qbx quadrature errors.
\cite{af2016fast} generalized \qbx to Stokes problems on spheroidal geometries in \threed.
\cite{wala20193d} extends the \qbx-\fmm coupling detailed in \cite{wala2018fast}, along with the geometric criteria and algorithms of \cite{RKO} that guarantees accurate quadrature, to \threed surfaces.
\cite{wala2019optimization} improves upon this by adding target-specific expansions to \cite{wala20193d}, achieving a 40\% speed-up and \cite{wala2020approximation} provides a thorough error analysis of the interaction between computing \qbx expansions and \fmm local expansions.

The rest of the paper is organized as follows:
In \cref{sec:formulation}, we briefly summarize the problem formulation, geometry representation and discretization.
In \cref{sec:algo}, we detail our singular evaluation scheme and with algorithms to enforce admissibility, adaptively upsample the boundary discretization, and query surface geometry to evaluate singular/near-singular integrals.
In \cref{sec:error}, we provide error estimates for \qbkix. %and a complexity analysis for our scheme.
%We also derive a quadrature error heuristic to use as a refinement criteria in adaptive upsampling
In \cref{sec:complexity}, we summarize the complexity of each of the algorithms described in \cref{sec:algo}.
In \cref{sec:results}, we detail convergence tests of our singular evaluation scheme and compare against other state-of-the-art methods.